<?PHP
#
#   FILE:  F-UpdateCollectionStats.php
#
#   USAGE: Provides a function to perform collection stats update in the background.
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012 Internet Scout
#   http://scout.wisc.edu
#

/**
* Callback for updating the collection statistics, usually executed as a
* background task.
*/
function UpdateCollectionStats()
{
    $CollectionStats = array();

    $RFactory = new ResourceFactory();
    $ClassFactory = new ClassificationFactory();
    $MSchema = new MetadataSchema();
    $CNFactory = new ControlledNameFactory();
    $SearchEngine = new SPTSearchEngine();

    # query total number of resources from DB
    $CollectionStats["TotalNumberOfResources"] =
        $RFactory->GetItemCount();

    # query number of released resources from DB
    $CollectionStats["NumberOfReleasedResources"] =
        $RFactory->GetItemCount("ReleaseFlag = 1");

    # Count rated resources:
    $CollectionStats["NumberOfRatedResources"] =
        $RFactory->GetRatedResourceCount();

    # Count the classifications:
    $CollectionStats["TotalNumberOfClassifications"] =
        $ClassFactory->GetItemCount();

    # Count the controlled names:
    $CNCount = 0;
    $Fields = $MSchema->GetFields(MetadataSchema::MDFTYPE_CONTROLLEDNAME);
    foreach ($Fields as $Field)
    {
        $CNCount += $CNFactory->GetItemCount("FieldId = ".$Field->Id());
    }
    $CollectionStats["TotalNumberOfControlledNames"] = $CNCount ;

    # Count total search terms:
    $CollectionStats["TotalSearchTerms"] =
        $SearchEngine->SearchTermCount();

    # Get the local statistics:
    $LocalStats = array();

    if (file_exists("include/SPT--Local.php"))
        require_once("include/SPT--Local.php");

    if (function_exists("Local_CollectionStatistics"))
        $LocalStats = Local_CollectionStatistics();

    global $AF;
    $SignalResult = $AF->SignalEvent("EVENT_LOCAL_COLLECTION_STATS",
        array("LocalStats" => $LocalStats));

    $CollectionStats["LocalStats"] = $SignalResult["LocalStats"];

    $DB = new Database();
    $DB->Query("DELETE FROM CachedValues WHERE NAME='CollectionStats'");

    $DB->Query("INSERT INTO CachedValues (Name,Value,Updated) VALUES "
               ."('CollectionStats','".addslashes(serialize($CollectionStats))."',NOW())");
}

?>