<?PHP
#
#   FILE:  RSS.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2011-2013 Edward Almasy and Internet Scout Research Group
#   http://scout.wisc.edu/cwis/
#

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

/**
 * Determine if a MetadataField value can be displayed, depending on whether
 * it's enabled and the user has the necessary privileges.
 * @param $Field MetadataField object
 * return TRUE if the field can be displayed, FALSE otherwise
 */
function CanDisplayField(MetadataField $Field=NULL)
{
    global $User;

    # field not set or not enabled
    if (is_null($Field) || !$Field->Enabled())
    {
        return FALSE;
    }

    $ViewingPrivilege = $Field->ViewingPrivilege();

    # insufficient privileges
    if ($ViewingPrivilege === 0 || $User->HasPriv($ViewingPrivilege))
    {
        return FALSE;
    }

    return TRUE;
}

/**
 * Get the value of a metadata field for a resource. The value might be modified
 * by one or more plugins.
 * @param $Resource Resource object
 * @param $Field MetadataField object
 * @return the value of a metadata field for a resource
 */
function GetFieldValue(Resource $Resource, MetadataField $Field)
{
    global $AF;

    $Value = $Resource->Get($Field, TRUE);

    # allow plugins to modify the value
    $SignalResult = $AF->SignalEvent(
        "EVENT_FIELD_DISPLAY_FILTER", array(
            "Field" => $Field,
            "Resource" => $Resource,
            "Value" => $Value));
    $Value = $SignalResult["Value"];

    return $Value;
}

/**
 * Get the value of the resource field if it the user can view it and the
 * field is enabled.
 * @param $Resource Resource object
 * @param $Field MetadataField object
 * @return the value of the resource field or "Unavailable" if not available
 */
function GetValueForRss(Resource $Resource, MetadataField $Field=NULL)
{
    if ($Field instanceof MetadataField && CanDisplayField($Field))
    {
        $Value = strip_tags(GetFieldValue($Resource, $Field));
    }

    else
    {
        $Value = "Unavailable";
    }

    return $Value;
}

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

$RSS = new RSS();
$DB = new Database();

$DB->Query("SELECT * FROM RSSConfiguration");
$Entry = $DB->FetchRow();

$SiteLink = OurBaseUrl()."index.php?P=Home";
$RssLink = OurBaseUrl()."index.php?P=RSS";
$NumberOfEntriesToPublish = intval($Entry["EntriesToPublish"]);

$RSS->SetEncoding($SysConfig->DefaultCharacterSet());
$RSS->AddChannel(
    $Entry["ChannelTitle"], $SiteLink, $Entry["ChannelDescription"], $RssLink);
$RSS->SetImage(
    $Entry["ImageUrl"], $Entry["ImageHeight"],
    $Entry["ImageWidth"], $Entry["ImageDescription"]);
$RSS->SetLanguage(GetArrayValue($Entry, "Language", NULL));
$RSS->SetCopyright(GetArrayValue($Entry, "CopyRight", NULL));
$RSS->SetManagingEditor(GetArrayValue($Entry, "ManagingEditor", NULL));
$RSS->SetWebmaster(GetArrayValue($Entry, "Webmaster", NULL));
$RSS->SetPicsRating(GetArrayValue($Entry, "PicsRating", NULL));
$RSS->SetPublicationDate(date("Y-n-j"));

# set date of most recent update to resources
$ResourceFact = new ResourceFactory();
$LastChangeTimestamp = $ResourceFact->GetTimestampOfLastResourceModification();
$RSS->SetLastChangeDate(date("Y-m-d", $LastChangeTimestamp));

# if search criteria specified
if (isset($_GET["Q"]) && ($_GET["Q"] == "Y"))
{
    # if saved search is specified
    if (isset($_GET["SI"]) && isset($_GET["UI"]))
    {
        # retrieve search parameters from saved search
        $SFactory = new SavedSearchFactory();
        if ($SFactory->ItemExists($_GET["SI"]))
        {
            $Search = $SFactory->GetItem($_GET["SI"]);
            if ($_GET["UI"] == $Search->UserId())
            {
                $SearchGroups = $Search->SearchGroups();
            }
        }
    }

    # if search parameters not yet set
    if (!isset($SearchGroups))
    {
        # retrieve search parameters from URL
        $SearchGroups = SavedSearch::TranslateUrlParametersToSearchGroups($_GET);
    }

    # set up search engine
    $Engine = new SPTSearchEngine();
    $Engine->SearchTermsRequiredByDefault($SysConfig->SearchTermsRequired());

    # add condition to filter out any temporary resource records
    function FilterOutTempResources($Id) {  return ($Id < 0);  }
    $Engine->AddResultFilterFunction("FilterOutTempResources");

    # add condition to show only released resources
    $Schema = new MetadataSchema();
    $ReleaseField = $Schema->GetFieldByName("Release Flag");
    if ($ReleaseField)
    {
        $SearchGroups[$ReleaseField->Id()]["SearchStrings"]
                ["Release Flag"] = "=1";
        $SearchGroups[$ReleaseField->Id()]["Logic"] = SearchEngine::LOGIC_AND;
    }

    # perform search
    $SearchResults = $Engine->GroupedSearch(
            $SearchGroups, 0, $NumberOfEntriesToPublish,
            "Date Of Record Release", 1);

    # load resources
    $Resources = array();
    foreach ($SearchResults as $Id => $Score)
    {
        $Resources[$Id] = new Resource($Id);
    }
}

else
{
    # get resource info to publish
    $Resources = $ResourceFact->GetRecentlyReleasedResources(
            $NumberOfEntriesToPublish, 0, 7300);
}

$Schema = new MetadataSchema();
$TitleField = $Schema->GetFieldByMappedName("Title");
$DescriptionField = $Schema->GetFieldByMappedName("Description");
$DateField = $Schema->GetFieldByName("Date Of Record Release");

# add resources to feed
foreach ($Resources as $Resource)
{
    $Title = GetValueForRss($Resource, $TitleField);
    $Description = GetValueForRss($Resource, $DescriptionField);
    $Date = GetValueForRss($Resource, $DateField);
    $Url = OurBaseUrl()."index.php?P=FullRecord&ResourceId=".$Resource->Id();

    $RSS->AddItem($Title, $Url, $Description, $Date);
}

# suppress HTML output and publish RSS page
$AF->SuppressHTMLOutput();
$RSS->PrintRSS();
