<?PHP

#
#   FILE:  SPT--RebuildRecommenderDB.php
#
#   FUNCTIONS PROVIDED:
#       RebuildIsComplete()
#           - returns TRUE if rebuild is complete
#       PercentRebuildComplete()
#           - returns percentage of rebuild completed so far
#
#   FUNCTIONS EXPECTED:
#       (none)
#
#   FORM FIELDS EXPECTED:
#       (none)
#
#   Part of the Scout Portal Toolkit
#   Copyright 2003 Internet Scout Project
#   http://scout.cs.wisc.edu
#

PageTitle("Rebuilding Recommender Database");

if (!CheckAuthorization(PRIV_SYSADMIN, PRIV_COLLECTIONADMIN)) {  return;  }

function ProcessResourceChunk($StartingResourceId)
{
    global $DB;

    # number of resources to update in each pass
    $RebuildChunkSize = 2;

    # if starting resource ID is set
    if (isset($StartingResourceId))
    {
        # process (update search data for) current chunk of resources
        $Recommender = new SPTRecommender;
        $EndResourceId = $Recommender->UpdateForItems(
                $StartingResourceId, $RebuildChunkSize);
    }
    else
    {
        # initialize starting resource ID
        $NewStartingResourceId = 0;
        $EndResourceId = -1;
    }

    # if we have processed all resources
    $RFactory = new ResourceFactory();
    $LastResourceId = $RFactory->GetHighestItemId();
    if ( !isset($LastResourceId) || $EndResourceId >= $LastResourceId )
    {       
        # set flag to indicate we're done
        $NewStartingResourceId = -1;

        # do end maintenance to DB
        if (!isset($Recommender)) {  $Recommender = new SPTRecommender;  }
        $Recommender->PruneCorrelations();
    }
    else
    {
        # set new starting resource ID
        $NewStartingResourceId = $EndResourceId + 1;
    }

    # return new starting resource ID to caller
    return $NewStartingResourceId;
}

function SetAutoRefreshStatus($NewStartingResourceId)
{
    global $AutoRefreshToPage;

    if ($NewStartingResourceId != -1)
    {
        if (isset($_GET["RSDElapsed"]))
            $ElapsedTime = intval($_GET["RSDElapsed"] 
                    + $GLOBALS["AF"]->GetElapsedExecutionTime());
        else
            $ElapsedTime = 0;

        $AutoRefreshToPage =
            "index.php?P=RebuildRecommenderDB"
            ."&RSDStartingResourceId=".$NewStartingResourceId
            ."&RSDElapsed=".$ElapsedTime;
    }
}

function RebuildIsComplete()
{
    global $StartingResourceId;

    if ($StartingResourceId == -1) {  return TRUE;  } else {  return FALSE;  }
}

function PercentRebuildComplete()
{
    global $DB;
    global $StartingResourceId;

    # get total number of resources
    $RFactory = new ResourceFactory();
    $TotalResources = $RFactory->GetItemCount(); 

    # get number of resources left to process
    $ResourcesProcessed = $RFactory->GetItemCount(
                            "ResourceId<${StartingResourceId}");

    # calculate percentage complete and return to caller
    return sprintf("%.1f", ($ResourcesProcessed * 100) / max(1,$TotalResources));
}

function EstimatedTimeRemainingInSeconds()
{
    global $_GET;

    # calculate initial estimate
    if (isset($_GET["RSDElapsed"]))
        $ElapsedTime = $_GET["RSDElapsed"];
    else
        $ElapsedTime = 0;
    $EstimatedTotalTime = ($ElapsedTime * 100) / PercentRebuildComplete();

    # adjust for rebuild speeding up toward end
    $EstimatedTotalTime = $EstimatedTotalTime * (1 - ((100 - PercentRebuildComplete()) / 325));

    # return result to caller
    return $EstimatedTotalTime - $ElapsedTime;
}

function EstimatedTimeRemaining()
{
    if (PercentRebuildComplete() < 2)
    {
        return "-:--";
    }
    else
    {
        return sprintf("%d:%02d:%02d", 
                intval(EstimatedTimeRemainingInSeconds() / 3600),
                intval((EstimatedTimeRemainingInSeconds() / 60) % 60),
                (EstimatedTimeRemainingInSeconds() % 60));
    }
}

function EstimatedTimeOfCompletion()
{
    if (PercentRebuildComplete() < 2)
    {
        return "-:--";
    }
    else
    {
        if (EstimatedTimeRemainingInSeconds() > (12 * 60 * 60))
        {
            return date("D g:ia", microtime(TRUE) + EstimatedTimeRemainingInSeconds());
        }
        else
        {
            return date("g:ia", microtime(TRUE) + EstimatedTimeRemainingInSeconds());
        }
    }
}

# non-standard global variables
global $AutoRefreshToPage;
global $StartingResourceId;
global $_GET;

# save page generation timestamp
if (isset($_GET["RSDStartingResourceId"]))
    $StartingResourceId = ProcessResourceChunk(
                                $_GET["RSDStartingResourceId"]);
else
    $StartingResourceId = 1;

SetAutoRefreshStatus($StartingResourceId);

?>
