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

/**
* Displays data for the UI about a user's saved searches and recent searches.
*/
class MySearches extends Plugin
{

    # ---- STANDARD PLUGIN INTERFACE -----------------------------------------

    /**
    * Register information about this plugin.
    */
    public function Register()
    {
        $this->Name = "My Searches";
        $this->Version = "1.0.1";
        $this->Description = "Provides data for the UI via events"
                ." about a user's saved searches and recent searches.";
        $this->Author = "Internet Scout";
        $this->Url = "http://scout.wisc.edu/cwis/";
        $this->Email = "scout@scout.wisc.edu";
        $this->Requires = array(
                "CWISCore" => "3.9.0",
                "MetricsRecorder" => "1.2.6",
            );
        $this->EnabledByDefault = TRUE;

        $this->CfgSetup["RecentSearches"] = array(
                "Type" => "Flag",
                "Label" => "Show Recent Searches",
                "Default" => "Yes",
                "Help" => "Display recent searches information.",
                "OnLabel" => "Yes",
                "OffLabel" => "No",
                );

        $this->CfgSetup["MySearches"] = array(
                "Type" => "Flag",
                "Label" => "Show My Searches",
                "Default" => "Yes",
                "Help" => "Display users' searches information.",
                "OnLabel" => "Yes",
                "OffLabel" => "No",
                );
    }

    /**
    * Initialize default settings.
    */
    public function Initialize()
    {
        # add extra function dirs that we need
        # these are listed in reverse order because each will be added to the
        # beginning of the search list
        $GLOBALS["AF"]->AddFunctionDirectories(array(
            "plugins/".__CLASS__."/interface/default/include/",
            "plugins/".__CLASS__."/interface/%ACTIVEUI%/include/",
            "local/plugins/".__CLASS__."/interface/default/include/",
            "local/plugins/".__CLASS__."/interface/%ACTIVEUI%/include/"));
    }

    /**
    * 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_HTML_INSERTION_POINT" =>
                array("PrintMySearches","PrintRecentSearches"),
            );
    }


    # ---- HOOKED METHODS ----------------------------------------------------

    /**
    * Print the My Searches UI content.
    * @param string $PageName Name of the current page
    * @param string $Location Location within the current page
    * @param mixed $Context Caller-defined context information
    */
    public function PrintMySearches($PageName, $Location, $Context=NULL)
    {
        if ($this->ConfigSetting("MySearches") == "Yes" &&
            $Location=="Sidebar Content" )
        {
            global $G_User;

            $Searches = GetSavedSearchesForUser($G_User->Id());
            $SearchesForDisplay = array();

            if (count($Searches))
            {
                $GLOBALS["AF"]->LoadFunction("PrintMySearchesSidebarBlock");
                foreach ($Searches as $Search)
                {
                    $SearchParams = $Search->SearchParameters();
                    $DisplayParams = SPTSearchEngine::ConvertToDisplayParameters(
                        $SearchParams);

                    $SearchesForDisplay[]= array(
                        "SearchURL" => "index.php?P=SearchResults&amp;Q=Y&amp;"
                        .$SearchParams->UrlParameterString(),
                        "SearchTitle" => $DisplayParams->TextDescription(
                             TRUE, FALSE, 30),
                        "SearchName" => $Search->SearchName(),
                        );
                }
                PrintMySearchesSidebarBlock($SearchesForDisplay);
            }
        }
    }

    /**
    * Print the Recent Searches UI content.
    * @param string $PageName Name of the current page
    * @param string $Location Location within the current page
    * @param mixed $Context Caller-defined context information
    */
    public function PrintRecentSearches($PageName, $Location, $Context=NULL)
    {
        # bail if we are not in the right location
        if (!($this->ConfigSetting("RecentSearches") == "Yes" &&
              $Location=="Sidebar Content" ))
        {
            return;
        }

        # bail if there is no current user
        if (!$GLOBALS["G_User"]->IsLoggedIn())
        {
            return;
        }

        # grab the recent searches for this user
        $MetricsRecorder = $GLOBALS["G_PluginManager"]->GetPlugin("MetricsRecorder");
        $SearchEventTypes = array(
                MetricsRecorder::ET_SEARCH,
                MetricsRecorder::ET_ADVANCEDSEARCH);
        $SearchEvents = $MetricsRecorder->GetEventData(
            "MetricsRecorder", $SearchEventTypes,
            NULL, NULL, $GLOBALS["G_User"]->Id() );

        # bail if no searches were found for this user
        if (!count($SearchEvents))
        {
            return;
        }

        # flip them to be in reverse-date order
        $SearchEvents = array_reverse($SearchEvents);

        # generate a list of searches we should show
        $SearchesForDisplay = array();
        $DisplayedSearches = array();

        # iterate over our events
        foreach ($SearchEvents as $Search)
        {
            # extract the search data, generate a key for it
            $SearchData = $Search["DataOne"];
            $SearchKey = md5($SearchData);

            # if we haven't already displayed this search
            if (!isset($DisplayedSearches[$SearchKey]) )
            {
                # attempt to get the search parameters out
                try
                {
                    $SearchParams = new SearchParameterSet($SearchData);
                    $DisplayParams = SPTSearchEngine::ConvertToDisplayParameters(
                        $SearchParams);

                    # mark this search as displayed, add it to our list
                    $DisplayedSearches[$SearchKey] = TRUE;
                    $SearchesForDisplay[]= array(
                            "SearchURL" => "index.php?P=SearchResults&amp;"
                                    .$SearchParams->UrlParameterString(),
                            "SearchName" =>
                                    "\n".$DisplayParams->TextDescription(TRUE, FALSE, 30),
                                );
                }
                catch (Exception $e)
                {
                    ; # continue on if search data was invalid
                }
            }

            # exit the loop if we've already got enough searches
            if (count($SearchesForDisplay) > 5)
            {
                break;
            }
        }

        # get the search display function, call it
        $GLOBALS["AF"]->LoadFunction("PrintRecentSearchesSidebarBlock");
        PrintRecentSearchesSidebarBlock($SearchesForDisplay);
    }
}
