<?PHP
#
#   FILE:  AJAXDropdown.php
#
#   FUNCTIONS PROVIDED:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function supplied for use in HTML file
#
#   FUNCTIONS EXPECTED:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function that HTML file must supply
#
#   OPTIONAL FUNCTIONS:
#       FunctionName($Parameter, $Parameter)
#           - brief description of function that HTML file may supply
#
#   FORM FIELDS EXPECTED:
#       F_FormFieldName
#           - brief description of form field purpose and/or content
#
#

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

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

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

$AF->SuppressHTMLOutput();

# if a version is specified
if (isset($_GET["Version"]))
{
    # VERSION 2
    $JsonHelper = new JsonHelper();

    # make sure user is logged in with sufficient privileges
    if (!$G_User->HasPriv(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN))
    {
        $JsonHelper->Error("Insufficient privileges");
        return;
    }

    # maximum number of results to display
    $MaxResultsToDisplay = 50;

    if (!isset($_GET["input"]))
    {
        $JsonHelper->Error("The \"input\" parameter is necessary");
        return;
    }

    if (!isset($_GET["fieldid"]))
    {
        $JsonHelper->Error("The \"fieldid\" parameter is necessary");
        return;
    }

    $SearchString = trim($_GET["input"]);
    $FieldId = trim($_GET["fieldid"]);

    if (($SearchString != "") && ($FieldId != ""))
    {
        # if field ID is valid
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($FieldId);
        if ($Field !== NULL)
        {
            $Search = "";
            $Words = preg_split("/\s+/", $SearchString, -1, PREG_SPLIT_NO_EMPTY);

            foreach ($Words as $Word)
            {
                # just add the word if it's quoted or has an asterisk already
                if (preg_match("/\"$/", $Word)
                    || preg_match("/\*$/", $Word))
                {
                    $Search .= $Word." ";
                }

                # add wildcard operator for stemming
                else
                {
                    $Search .= $Word."* ";
                }
            }

            # perform search
            $SearchResults = $Field->GetFactory()->SearchForItemNames(
                trim($Search), $MaxResultsToDisplay+1);
        }
    }

    else
    {
        $JsonHelper->Error("No search criteria were entered. Please enter them.");
        return;
    }

    # if there are no results
    $NumberOfResults = count($SearchResults);
    if ($NumberOfResults < 1)
    {
        $JsonHelper->AddDatum("error", TRUE);
        $JsonHelper->AddDatum("errorMessage", "No results found. Please broaden your search.");
        $JsonHelper->Success();
        return;
    }

    # if there are too many results
    else if ($NumberOfResults > $MaxResultsToDisplay)
    {
        $JsonHelper->AddDatum("error", TRUE);
        $JsonHelper->AddDatum("errorMessage", "More than $MaxResultsToDisplay results were found. Please narrow your search.");
        $JsonHelper->Success();
        return;
    }

    else
    {
        $JsonHelper->AddDatum("error", FALSE);
        $JsonHelper->AddDatum("results", $SearchResults);
        $JsonHelper->Success();
        return;
    }

    # return
    $JsonHelper->Error("An error occurred.");
    return;
}

# backwards compatibility, no version specified
else
{
    # make sure user is logged in with sufficient privileges
    if (!$G_User->HasPriv(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN))
    {
        return;
    }

    # maximum number of results to display
    $MaxResultsToDisplay = 50;

    # if a search string was entered and field ID is available
    $SearchString = trim($_GET["Argument"]);
    $FieldId = trim($_GET["FieldId"]);
    if (($SearchString != "") && ($FieldId != ""))
    {
        # if field ID is valid
        $Schema = new MetadataSchema();
        $Field = $Schema->GetField($FieldId);
        if ($Field !== NULL)
        {
            $Search = "";
            $Words = preg_split("/\s+/", $SearchString, -1, PREG_SPLIT_NO_EMPTY);

            foreach ($Words as $Word)
            {
                # just add the word if it's quoted or has an asterisk already
                if (preg_match("/\"$/", $Word)
                    || preg_match("/\*$/", $Word))
                {
                    $Search .= $Word." ";
                }

                # add wildcard operator for stemming
                else
                {
                    $Search .= $Word."* ";
                }
            }

            # perform search
            $SearchResults = $Field->GetFactory()->SearchForItemNames(
                trim($Search), $MaxResultsToDisplay+1);
        }
    }
    else
    {
        print "{ 'type' : 'error', 'message' : 'No search term was entered. Please enter one.',"
             ." 'resources' : [], 'numresources' : 0 }";
        return;
    }

    # if there are no results
    $NumberOfResults = count($SearchResults);
    if ($NumberOfResults < 1)
    {
        print "{ 'type' : 'error', 'message' : 'No results were found. Please enter a different"
             ." search term or broaden the search.', 'resources' : [], 'numresources' : 0 }";
    }
    # else if there are too many results
    else if ($NumberOfResults > $MaxResultsToDisplay)
    {
        print "{ 'type' : 'warning', 'message' : 'More than $MaxResultsToDisplay results were found."
             ." please narrow the search.', 'resources' : [], 'numresources' : 0 }";
    }
    else
    {
        $Return = "{ 'type' : 'ok', 'message' : '', 'resources' : [";
        foreach($SearchResults as $TempResult)
        {
            # Create and add JSON objects
            $Return .= "{ 'value' : '$TempResult' },";
        }
        print $Return . "], 'numresources' : $NumberOfResults }";
    }

    return;
}

?>
