<?PHP
#
#   FILE:  MyResourceViews.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2002-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

/**
* Plugin that adds the recently viewed resources for the current user to the
* sidebar.
*/
class MyResourceViews extends Plugin
{

    /**
    * Register information about this plugin.
    */
    public function Register()
    {
        $this->Name = "My Resource Views";
        $this->Version = "1.0.1";
        $this->Description = "Displays list of resources that user"
                ." has most recently viewed in a box in the sidebar.";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array(
                "CWISCore" => "2.2.0",
                "MetricsRecorder" => "1.1.1",
                );
        $this->EnabledByDefault = TRUE;

        $this->CfgSetup["BoxHeader"] = array(
                "Type" => "Text",
                "Label" => "Box Header",
                "Help" => "Title for <i>My Resource Views</i> box in sidebar.",
                "Size" => 40,
                "MaxLength" => 60,
                );
        $this->CfgSetup["ListLength"] = array(
                "Type" => "Number",
                "Label" => "Number of Resources to Display",
                "Help" => "Number of recent-viewed resources to display in box.",
                "MaxVal" => 20,
                );

        # get the list of schemas
        $Schemas = MetadataSchema::GetAllSchemas();
        # filter out user schema
        unset($Schemas[MetadataSchema::SCHEMAID_USER]);
        $Options = array();
        foreach ($Schemas as $TypeSchemaId => $TypeSchema)
        {
            $TypeSchemaName = $TypeSchema->Name();
            $Options[$TypeSchemaId] = $TypeSchemaName;
        }

        $this->CfgSetup["ResourceTypeToInclude"] = array(
                "Type" => "Option",
                "Label" => "Resource Types to Display",
                "Help" => "Types of resources to be included in " .
                        "<i>My Resource Views</i> box.",
                "AllowMultiple" => TRUE,
                # here the option array is indexed by the respected schema id
                "Options" => $Options,
                "Default" => array_keys($Schemas),
                );
    }

    /**
    * Initialize default settings.
    */
    public function Install()
    {
        $this->ConfigSetting("BoxHeader", "Recently Viewed");
        $this->ConfigSetting("ListLength", 5);
    }

    /**
    * Hook the events into the application framework.
    * @return Returns an array of events to be hooked into the application
    *      framework.
    */
    public function HookEvents()
    {
        return array(
                "EVENT_REQUEST_SIDEBAR_CONTENT" => "GenerateRecentlyViewedBox",
                );
    }

    /**
    * Generate and return the sidebar content for the recently viewed resources
    * of the current user.
    * @return Returns the sidebar content as a string for the recently viewed
    *      resources of the current user.
    */
    public function GenerateRecentlyViewedBox()
    {
        # if the user is logged in
        $Box = "";
        if ($GLOBALS["G_User"]->IsLoggedIn())
        {
            # get the list length + 5 in case some resources cannot be displayed
            $NumToFetch = $this->ConfigSetting("ListLength") + 5;

            # retrieve list of resources recently viewed by user
            $MRecorder = $GLOBALS["G_PluginManager"]->GetPlugin("MetricsRecorder");
            $Views = $MRecorder->GetFullRecordViews($GLOBALS["G_User"], $NumToFetch);

            # get the resources from the views
            foreach ($Views as $View)
            {
                # if resource still exists
                if (Resource::ItemExists($View["ResourceId"]))
                {
                    # load resource
                    $Resource = new Resource($View["ResourceId"]);

                    # if resource type should be displayed
                    #       and user can view the resource
                    if (in_array($Resource->SchemaId(),
                            $this->ConfigSetting("ResourceTypeToInclude"))
                            && $Resource->UserCanView($GLOBALS["G_User"]))
                    {
                        # add resource to display list
                        $SchemaCSSName = "cw-sidebar-resource-tag-" .
                                str_replace(array(" ", "/"), '',
                                        strtolower($Resource->Schema()->Name()));
                        $Resources[] = array(
                                "Resource" => $Resource,
                                "SchemaCSSName" => $SchemaCSSName,
                                "SchemaName" =>
                                        $Resource->Schema()->AbbreviatedName(),
                                );

                        # stop if enough resources have been found
                        if (count($Resources) >= $this->ConfigSetting("ListLength"))
                        {
                            break;
                        }
                    }
                }
            }

            # if there were resources found
            if (isset($Resources))
            {
                ob_start();
                ?><div class="cw-section cw-section-simple cw-html5-section">
                    <div class="cw-section-header cw-html5-header">
                        <b><?PHP  print($this->ConfigSetting("BoxHeader"));  ?></b>
                    </div>
                    <div class="cw-section-body">
                        <ul class="cw-list cw-list-noindent cw-list-dotlist">
                            <?PHP
                            # for each resource
                            foreach ($Resources as $Rsrc)
                            {
                                # format link to full record page
                                $Link = $Rsrc["Resource"]->GetViewPageUrl();

                                # format view label
                                $Title = $Rsrc["Resource"]->GetMapped("Title");
                                $Label = strip_tags($Title);

                                # add resource view to list in box
                                ?><li>
                                    <span class="cw-sidebar-resource-tag
                                            <?PHP print($Rsrc["SchemaCSSName"]); ?>">
                                        <?PHP print($Rsrc["SchemaName"]); ?></span>
                                    <a href="<?PHP  print($Link); ?>">
                                        <?PHP  print($Label);  ?>
                                    </a>
                                </li><?PHP
                            }
                        ?></ul>
                    </div>
                </div><?PHP
                $Box = ob_get_contents();
                ob_end_clean();
            }
        }

        # return generated box to caller
        return $Box;
    }
}
