<?PHP

#
#   FILE:  SPT--QuickSearch.php
#
#   FUNCTIONS PROVIDED:
#       PrintSearchResults()
#           - print search results (calling PrintSearchResult() for the
#                   actual output
#       PrintSearchString()
#           - print search string text
#       PrintTotalNumberOfResults()
#           - print total number of results returned by search
#       PrintStartingResultNumber()
#       PrintEndingResultNumber()
#           - print starting and ending number of currently displayed results
#       PreviousResultsAvailable()
#       NextResultsAvailable()
#           - return TRUE if this is not the first/last page of results
#       PrintPreviousResultsLink()
#       PrintNextResultsLink()
#           - print URL for previous or next page of results
#       PrintNumberOfPreviousResults()
#       PrintNumberOfNextResults()
#           - print number of results on previous/next results page
#       NoResultsFound()
#           - returns TRUE if no search results were found
#       PrintSearchTime()
#           - print time taken for search, in seconds
#
#   FUNCTIONS EXPECTED:
#       PrintSearchResult($Title, $Description, $FullRecordLink, $Url, 
#                   $DateOfRecordCreation, $DateRecordAdded, $Contributor, 
#                   $EditOkay, $EditUrl, $DateLastVerified, $DateLastModified)
#           - called by PrintSearchResults() to output each result
#
#   FORM FIELDS EXPECTED:
#       F_SearchString
#           - text to search for
#
#   Part of the Scout Portal Toolkit
#   Copyright 2002 Internet Scout Project
#   http://scout.cs.wisc.edu
#

ParseArguments();
PageTitle("Search Results (${SearchString})");

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

function PrintSearchResults()
{
    global $SearchString;
    global $SearchResults;

    # make sure search has been done
    PerformSearch();

    # for each search result entry up to the limit to be displayed
    foreach ($SearchResults as $ResourceId => $Score)
    {
        # print entry
        $Resource = new Resource($ResourceId);
        global $G_User;
        PrintSearchResult($Resource,
                    "index.php?P=FullRecord&amp;ResourceId=".$ResourceId,
                    $Resource->UserCanEdit($G_User),
                    "index.php?P=EditResource&amp;ID=".$ResourceId,
                    $Resource->ScaledCumulativeRating());
    }
}

function PrintSearchString()
{
    global $SearchString;

    print(str_replace("\"", "&quot;", stripslashes($SearchString)));  # "
}

function PrintTotalNumberOfResults()
{
    global $Engine;

    # make sure search has been done
    PerformSearch();

    print($Engine->NumberOfResults());
}

function PrintStartingResultNumber()
{
    global $StartingResult;
    global $Engine;

    # make sure search has been done
    PerformSearch();

    if ($Engine->NumberOfResults() == 0)
    {
        print("0");
    }
    else
    {
        print($StartingResult + 1);
    }
}

function PrintEndingResultNumber()
{
    global $StartingResult;
    global $ResultsPerPage;
    global $Engine;

    # make sure search has been done
    PerformSearch();

    print(min(($StartingResult + $ResultsPerPage), $Engine->NumberOfResults()));
}

function PreviousResultsAvailable()
{
    global $StartingResult;

    return ($StartingResult > 0) ? TRUE : FALSE;
}

function NextResultsAvailable()
{
    global $StartingResult;
    global $ResultsPerPage;
    global $Engine;

    # make sure search has been done
    PerformSearch();

    return (($StartingResult + $ResultsPerPage) < $Engine->NumberOfResults()) ? TRUE : FALSE;
}

function PrintPreviousResultsLink()
{
    global $StartingResult;
    global $ResultsPerPage;
    global $SearchString;

    $NewStartingResult = max(($StartingResult - $ResultsPerPage), 0);
    print("index.php?P=QuickSearch&amp;ss=".urlencode($SearchString)
          ."&amp;sr=".$NewStartingResult);
}

function PrintNextResultsLink()
{
    global $StartingResult;
    global $ResultsPerPage;
    global $SearchString;

    $NewStartingResult = $StartingResult + $ResultsPerPage;
    print("index.php?P=QuickSearch&amp;?ss=".urlencode($SearchString)
          ."&amp;sr=".$NewStartingResult);
}

function NoResultsFound()
{
    global $Engine;

    # make sure search has been done
    PerformSearch();

    return ($Engine->NumberOfResults() == 0) ? TRUE : FALSE;
}

function PrintSearchTime()
{
    global $Engine;

    # make sure search has been done
    PerformSearch();

    printf("%.3f", $Engine->SearchTime());
}

function PrintNumberOfPreviousResults()
{
    global $ResultsPerPage;

    print($ResultsPerPage);
}

function PrintNumberOfNextResults()
{
    global $ResultsPerPage;
    global $StartingResult;
    global $Engine;

    # make sure search has been done
    PerformSearch();

    print(min($ResultsPerPage, ($Engine->NumberOfResults() - ($StartingResult + $ResultsPerPage))));
}


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

function ParseArguments()
{
    global $DB;

    global $ss;
    global $sr;
    global $F_SearchString;
    global $SearchString;
    global $SearchStrings;
    global $StartingResult;
    global $ResultsPerPage;

    # init SearchStrings
    $SearchStrings = NULL;

    # grab keyword search string
    if (isset($ss)) 
    {  
        $SearchString = stripslashes($ss);
    }
    else
    {
        if (isset($F_SearchString))
        {
            $SearchString = stripslashes($F_SearchString);
        }
    }

    # grab starting result number if passed in
    if (isset($sr))
    {       
        $StartingResult = $sr;
    }
    else
    {
        $StartingResult = 0;
    }

    # set results per page to a default for now
    $ResultsPerPage = 10;
}

function PerformSearch()
{
    global $SysConfig;
    global $Engine;
    global $SearchString;
    global $SearchStrings;
    global $SearchResults;
    global $StartingResult;
    global $ResultsPerPage;

    # bail out if we've already done search
    static $AlreadyPerformedSearch;
    if ($AlreadyPerformedSearch) {  return;  }
    $AlreadyPerformedSearch = TRUE;

    # create search engine
    $Engine = new SPTSearchEngine;

    # set OR/AND terms status
    $Engine->SearchTermsRequiredByDefault(
            $SysConfig->SearchTermsRequired());

    # add filter function if defined in HTML file
    if (function_exists("FilterSearchResults"))
    {
        $Engine->AddResultFilterFunction("FilterSearchResults");
    }

    # add filter function to return only released records
    $Engine->AddResultFilterFunction("FilterSearchResultsForReleasedRecords");

    # if advanced search
    if (isset($SearchStrings))
    {
        # add in search keywords if set
        if (isset($SearchString)) {  $SearchStrings["Keyword"] = $SearchString;  }
	
	# perform fielded search
        $SearchResults = $Engine->FieldedSearch(
                $SearchStrings, $StartingResult, $ResultsPerPage);
    }
    else
    {
        # perform keyword search
        $SearchResults = $Engine->Search(
                stripslashes($SearchString), $StartingResult, $ResultsPerPage);
    }
}

# filter the search results for only released records
function FilterSearchResultsForReleasedRecords($ResourceId)
{
    global $DB;

    $FilterQuery = " Select ResourceId FROM Resources WHERE ResourceId = ".
        intval($ResourceId)." AND ReleaseFlag = 1";

    $DB->Query($FilterQuery);
    return ($DB->NumRowsSelected()) ? FALSE : TRUE;
}

# (automatically called in StandardPageStart if defined)
function AddJavascript()
{
    global $ss;
    global $SearchString;

    # if our URL doesn't already contain search string
    #         and search string is set and advanced search not requested
    if (!isset($ss) && isset($SearchString) && !isset($SearchStrings))
    {
        # add JavaScript to reset our URL to include search string
        ?>
        <script><!--
            document.location.href = document.location + '?ss=<?PHP  print(htmlentities(urlencode($SearchString)));  ?>';
        --></script>
        <?PHP
    }
}

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

# non-standard global variables
global $Engine;
global $F_SearchString;
global $ResultsPerPage;
global $SearchResults;
global $SearchString;
global $SearchStrings;
global $StartingResult;
global $sr;
global $ss;

$F_SearchString = isset($_POST["F_SearchString"]) ? $_POST["F_SearchString"] : NULL;

$ss = isset($_GET["ss"]) ? $_GET["ss"] : NULL;
$sr = isset($_GET["sr"]) ? $_GET["sr"] : NULL;

?>
