<?PHP
#
#   FILE:  SPT--Advanced.php
#
#   FUNCTIONS PROVIDED:
#       None
#
#   FUNCTIONS EXPECTED:
#       None
#
#   Part of the Scout Portal Toolkit
#   Copyright 2001 Internet Scout Project
#   http://scout.cs.wisc.edu
#

require_once("lib/AxisPHP/Axis--StandardLibrary.php");


# ----- EXPORTED FUNCTIONS ---------------------------------------------------

function PrintSearchTextFormEntries($NumberOfEntries)
{
    global $G_SearchGroups;

    # retrieve current search parameters (if any)
    if (isset($G_SearchGroups) && isset($G_SearchGroups["MAIN"]["SearchStrings"]))
    {
        $SavedSearchValues = array_values($G_SearchGroups["MAIN"]["SearchStrings"]);
    }

    # for each field
    for ($Index = 0;  $Index < $NumberOfEntries;  $Index++)
    {
        # retrieve current search parameter for this field (if available)
        $DefaultValue = isset($SavedSearchValues[$Index])
                ? $SavedSearchValues[$Index] : "";

        # print option list and field
        PrintSearchTextFormEntry("F_SearchText".$Index, $DefaultValue, $Index);
    }
}

function PrintSearchTextFieldOptionList($CurrentIndex, $DefaultValue = NULL)
{
    # get list of available metadata fields (if not already retrieved)
    static $FieldList;
    if (!isset($FieldList))
    {
        global $G_User;
        $Schema = new MetadataSchema();
        $Fields = $Schema->GetFields(
            MetadataSchema::MDFTYPE_TEXT |
            MetadataSchema::MDFTYPE_PARAGRAPH |
            MetadataSchema::MDFTYPE_CONTROLLEDNAME |
            MetadataSchema::MDFTYPE_NUMBER |
            MetadataSchema::MDFTYPE_FILE |
            MetadataSchema::MDFTYPE_TREE |
            MetadataSchema::MDFTYPE_IMAGE |
            MetadataSchema::MDFTYPE_DATE |
            MetadataSchema::MDFTYPE_TIMESTAMP |
            MetadataSchema::MDFTYPE_URL );
        foreach ($Fields as $FieldId => $Field)
        {
            if ($Field->Enabled() && $Field->IncludeInAdvancedSearch()
                    && ($G_User->HasPriv($Field->ViewingPrivilege())
                        || $G_User->HasPriv($Field->EditingPrivilege())
                        || ($Field->ViewingPrivilege() == 0)))
            {
                $FieldList[$FieldId] = $Field->Name();
            }
        }
    }

    # add in keyword search
    $FieldList["Keyword"] = "Keyword";

    # put field in alphabetical order
    asort($FieldList);

    # if valid default value supplied by caller
    if ($DefaultValue && in_array($DefaultValue, $FieldList))
    {
        # convert default value to value index
        $DefaultValueIndex = array_search($DefaultValue, $FieldList);
    }
    else
    {
        # use keyword as default
        $DefaultValueIndex = "Keyword";
    }

    # print option list
    PrintOptionList("F_SearchCat".$CurrentIndex, $FieldList, $DefaultValueIndex);
}

function PrintSearchLimitFormEntries($FieldTypesOrFieldName = NULL)
{
    global $CurrentField;
    global $G_User;

    # for each limit of type specified
    $Schema = new MetadataSchema();
    if (is_string($FieldTypesOrFieldName))
    {
        $Fields = array($Schema->GetFieldByName($FieldTypesOrFieldName));
    }
    else
    {
        $Fields = $Schema->GetFields($FieldTypesOrFieldName);
    }
    foreach ($Fields as $CurrentField)
    {
        # if limit field is marked to be used in Advanced Search
        if ($CurrentField->Enabled()
                && $CurrentField->IncludeInAdvancedSearch()
                && ($G_User->HasPriv($CurrentField->ViewingPrivilege())
                    || $G_User->HasPriv($CurrentField->EditingPrivilege())
                    || ($CurrentField->ViewingPrivilege() == 0)))
        {
            # print entry
            PrintSearchLimitFormEntry($CurrentField->Name(), $CurrentField->Type());
        }
    }
}

# called in HTML file to display each option list in Limit Search section
function PrintSearchLimitOptionList($DisplayedListLength)
{
    global $G_SearchGroups;
    global $CurrentField;
    global $DB;

    # retrieve values for option list
    if ($CurrentField->Type() == MetadataSchema::MDFTYPE_USER)
    {
        $UserFactory = new UserFactory($DB);
        $PossibleValues = $UserFactory->GetUsersWithPrivileges(
                PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN);
    }
    else
    {
        if ($CurrentField->Name() == "Cumulative Rating")
        {
            $PossibleValues = array(
                    20 => "*",
                    40 => "**",
                    60 => "***",
                    80 => "****",
                    100 => "*****",
                    );
        }
        else
        {
            $PossibleValues = $CurrentField->GetPossibleValues();
            asort($PossibleValues);
        }
    }

    # assume no default values
    $DefaultValues = NULL;

    # if saved search available
    $FieldId = $CurrentField->Id();
    if (isset($G_SearchGroups))
    {
        # if default values available
        if (isset($G_SearchGroups[$FieldId]["SearchStrings"][$CurrentField->Name()]))
        {
            # if field is a flag or number
            if ($CurrentField->Type() & (MetadataSchema::MDFTYPE_FLAG|MetadataSchema::MDFTYPE_NUMBER))
            {
                # use value from SearchGroups directly
                $DefaultValues = preg_replace("/^[=><!]+/", "",
                        $G_SearchGroups[$FieldId]["SearchStrings"][$CurrentField->Name()]);
            }
            else
            {
                # convert values to indices to match option list values
                $Values = is_array($G_SearchGroups[$FieldId]["SearchStrings"][$CurrentField->Name()])
                        ? $G_SearchGroups[$FieldId]["SearchStrings"][$CurrentField->Name()]
                        : array($G_SearchGroups[$FieldId]["SearchStrings"][$CurrentField->Name()]);
                $DefaultValues = array();
                foreach ($Values as $Value)
                {
                    $Value = preg_replace("/^[=><!]+/", "", $Value);
                    $DefaultValues[] = array_search($Value, $PossibleValues);
                }
            }
        }
    }

    # add null entry if list is only one element long (so user has a way of selecting "no limit")
    if ($DisplayedListLength == 1)
    {
        $PossibleValues = array("-1" => "--") + $PossibleValues;
        if ($DefaultValues == NULL) {  $DefaultValues = "-1";  }
    }

    # if the field name is longer than any of the possible options, then extend
    # the width of the select box to match it to avoid display funkiness
    $Width = "100%";
    foreach ($PossibleValues as $Value)
    {
        if (strlen($Value) >= strlen($CurrentField->Name()))
        {
            $Width = NULL;
            break;
        }
    }

    # print option list
    PrintOptionList("F_SearchLimit".$FieldId."[]", $PossibleValues,
            $DefaultValues, NULL, $DisplayedListLength,
            TRUE, ($DisplayedListLength > 1), NULL, $Width);
}

# function to return action string for form tag
function GetAdvancedSearchAction()
{
    return("index.php?P=AdvancedSearch");
}

# function to return action string for Saved Search string
function GetSavedSearchAction()
{
    return("index.php?P=SavedSearch");
}

# function to print any error messages at top of the page
function PrintErrorMessages()
{
    global $ErrorMessages;

    # if error messages were passed from PreferencesComplete
    if (isset($ErrorMessages) && is_array($ErrorMessages) &&
        count($ErrorMessages) > 0)
    {
        # print error messages
        print("<ul><b>\n");
        foreach ($ErrorMessages as $Message)
        {
            printf("<li>%s</li>\n", $Message);
        }
        print("</ul></b>\n");
    }
}

# print option list with specified choices for records per page
function PrintRecordsPerPageOptionList()
{
    global $User;

    # for each specified choice
    $Args = func_get_args();
    $Default = -1;
    foreach ($Args as $Arg)
    {
        # add choice to list
        $Choices[$Arg] = $Arg;

        # if default is not yet set and choice is at or above default users last choice
        if (($Default == -1) && ($Arg >= $User->Get("RecordsPerPage")))
        {
            # set default
            $Default = $Arg;
        }
    }

    # print option list
    PrintOptionList("F_RecordsPerPage", $Choices, $Default);
}

# display available saved searches
function DisplayUserSearchList()
{
    global $User;

    # retrieve list of saved searches for current user
    $Searches = GetSavedSearchesForUser($User->Id());

    # if saved searches found
    if (count($Searches))
    {
        # begin search list
        print("<ul class=\"SPTSavedSearches\">\n");

        # for each saved search
        foreach ($Searches as $SearchId => $Search)
        {
            # add entry for search
            $Descrip = addslashes(strip_tags($Search->GetSearchGroupsAsTextDescription()));
            print("<li><a href=\"index.php?P=Advanced"
                  ."&amp;SI=".$Search->GetSearchId()."\" "
                  ."title=\"Search Parameters:\n".$Descrip."\">"
                  .htmlspecialchars($Search->SearchName())."</a></li>\n");
        }

        # end search list
        print("</ul>\n");
    }
    else
    {
        # print messages indicating no searches saved
        print("There are no searches currently saved.");
    }
}

# get number of searches user has saved
function GetSavedSearchCount()
{
    global $User;
    $Searches = GetSavedSearchesForUser($User->Id());
    return count($Searches);
}

function EditingSavedSearch()
{
    global $G_SavedSearch;

    return isset($G_SavedSearch) ? TRUE : FALSE;
}

function PrintSavedSearchName()
{
    global $G_SavedSearch;

    if (isset($G_SavedSearch)) {  print($G_SavedSearch->SearchName());  }
}

function PrintHiddenFormFields()
{
    global $G_SavedSearch;
    if (isset($G_SavedSearch))
    {
        print("<input type=\"hidden\" name=\"F_SearchId\" value=\"".$G_SavedSearch->GetSearchId()."\">\n");
    }
}


# ----- LOCAL FUNCTIONS ------------------------------------------------------

# ----- MAIN -----------------------------------------------------------------

# non-standard global variables
global $CurrentField;
global $ErrorMessages;
global $G_SavedSearch;
global $G_SearchGroups;

if ($User->IsLoggedIn() && isset($_GET["SI"]))
{
    $G_SavedSearch = new SavedSearch($_GET["SI"]);
    $G_SearchGroups = $G_SavedSearch->SearchGroups();
}
elseif (isset($_GET["RF"]))
{
    $G_SearchGroups = SavedSearch::TranslateUrlParametersToSearchGroups($_GET);
}
# PrintForDebug("G_SearchGroups", $G_SearchGroups);

PageTitle("Advanced Search");

?>
