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

# ----- HELPER FUNCTIONS -----------------------------------------------------

/**
* Get sorting information from GET parameters.
* @return Returns an array containing the sort field name and sort descending
*      value
*/
function GetSortInfo()
{
    global $SysConfig;

    $Schema = new MetadataSchema();
    $SortField = NULL;
    $SortFieldId = GetArrayValue($_GET, "SF");
    $SortDescending = GetArrayValue($_GET, "SD");

    # use specified sort field
    if ($SortFieldId)
    {
        $Field = $Schema->GetField(intval($SortFieldId));

        if ($Field instanceof MetadataField
            && $Field->Status() == MetadataSchema::MDFSTAT_OK)
        {
            $SortField = $Field;
        }
    }

    # use the default sort field
    if (is_null($SortField))
    {
        try
        {
            $Field = $Schema->GetField($SysConfig->DefaultSortField());

            if ($Field instanceof MetadataField
                && $Field->Status() == MetadataSchema::MDFSTAT_OK)
            {
                $SortField = $Field;
            }
        }
        catch (Exception $e)
        {
            ; # continue on when there is no default sort field
        }
    }

    # use the sort order specified
    if (!is_null($SortDescending))
    {
        $SortDescending = (bool)$SortDescending;
    }

    # use the sort order defaults for the given sort field
    else if (!is_null($SortField))
    {
        switch ($SortField->Type())
        {
            case MetadataSchema::MDFTYPE_NUMBER:
            case MetadataSchema::MDFTYPE_DATE:
            case MetadataSchema::MDFTYPE_TIMESTAMP:
                $SortDescending = TRUE;
                break;
            default:
                $SortDescending = FALSE;
                break;
        }
    }

    # otherwise sort descending by default
    else
    {
        $SortDescending = TRUE;
    }

    $SortFieldName = $SortField instanceof MetadataField
        ? $SortField->Name() : $SortField;

    return array($SortFieldName, $SortDescending);
}

/**
* Perform a search using the given search groups and sorting info.
* @param SearchParameterSet $SearchParams Search group parameters for the search engine.
* @param string $SortFieldName Name of the field to sort by.
* @param bool $SortDescending TRUE to sort the results in descending order.
* @return Returns an array of search results.
*/
function PerformSearch(SearchParameterSet $SearchParams, $SortFieldName, $SortDescending)
{
    $SearchEngine = new SPTSearchEngine();

    # signal event to allow modification of search parameters
    $SignalResult = $GLOBALS["AF"]->SignalEvent(
        "EVENT_FIELDED_SEARCH", array(
            "SearchParameters" => $SearchParams,
            "User" => $GLOBALS["G_User"],
            "SavedSearch" => NULL));
    $SearchParams = $SignalResult["SearchParameters"];

    # perform search
    $SearchResults = $SearchEngine->Search($SearchParams, 0, PHP_INT_MAX,
            $SortFieldName, $SortDescending);

    # filter resources the user cannot see
    foreach ($SearchResults as $SchemaId => $Results)
    {
        $RFactory = new ResourceFactory($SchemaId);
        $ViewableIds = $RFactory->FilterNonViewableResources(
                array_keys($Results), $GLOBALS["G_User"]);
        $SearchResults[$SchemaId] = array_intersect_key(
                $Results, array_flip($ViewableIds) );
    }

    return $SearchResults;
}

/**
* Callback function used with search engine objects to filter out temporary
* resources.
* @param int $Id Resource ID to check.
* @return Returns TRUE if the resource ID is less than zero.
*/
function Folders_FilterOutTempResources($Id)
{
    return $Id < 0;
}

# ----- SETUP ----------------------------------------------------------------
# check authorization
if (!Folders_Common::ApiPageCompletion("P_Folders_ManageFolders"))
{
    return;
}

# get the folders plugin
$FoldersPlugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();

# set up variables
$Errors = array();
$FolderFactory = new Folders_FolderFactory($User->Id());
$FolderId = GetArrayValue($_GET, "FolderId");

# get the currently selected folder if no folder ID is given
if ($FolderId === NULL)
{
    $FolderId = $FolderFactory->GetSelectedFolder()->Id();
}

$ResourceFolder = $FolderFactory->GetResourceFolder();
$Folder = new Folders_Folder($FolderId);

$FolderId = GetArrayValue($_GET, "FolderId");

$ItemType = GetArrayValue($_GET, "ItemType");

PageTitle("Folders - Add Items to Folder");

# ----- MAIN -----------------------------------------------------------------
# add items only if the resource folder contains this folder, which implies
# that the user owns the folder and it's a valid folder of resources
if ($ResourceFolder->ContainsItem($Folder->Id()))
{
    $SearchParams = new SearchParameterSet();
    $SearchParams->UrlParameters($_GET);

    list($SortFieldName, $SortDescending) = GetSortInfo();

    $SearchResults = PerformSearch(
        $SearchParams,
        $SortFieldName,
        $SortDescending);

    foreach ($SearchResults as $SchemaId => $Results)
    {
        # filter out the resources that do not belong to the target $ItemType
        if (($ItemType !== NULL) && ($SchemaId != $ItemType))
        {
            continue;
        }
        $Folder->AppendItems(array_keys($Results));
    }
}
else
{
    # user doesn't own the folder
    array_push($Errors, 'E_FOLDERS_NOTFOLDEROWNER');
}
# ----- PAGE ROUTING  -----------------------------------------------------------------
# handle page routing based on the success/failure above.

# This page does not output any HTML
$GLOBALS["AF"]->SuppressHTMLOutput();

$FoldersPlugin::ProcessPageResponse($Errors, ReachedWithAjax());
