<?PHP
#
#   FILE:  Home.php
#
#   FUNCTIONS PROVIDED:
#       PrintAnnouncementsTableRows()
#           - outputs HTML for News & Announcements table
#       PrintNewResourceTableRows()
#           - outputs HTML for New Resources table
#       NumAnnouncementRows()
#           - returns the number or Announcements to be displayed
#
#   FUNCTIONS EXPECTED:
#       PrintAnnouncementRow($Headline, $DatePosted, $PosterName, $Text,
#                   $EditOkay, $EditLink)
#           - called to print line in News & Announcements table
#       PrintNoAnnouncementsMessage()
#           - called to print message that there were no announcements
#       PrintNewResourceRow($Title, $Description, $FullRecordLink, $Url,
#                   $DateOfRecordCreation, $DateRecordAdded, $Contributor,
#                   $EditOkay, $EditUrl, $DateLastVerified, $DateLastModified)
#           - called to print line in New Resources table
#       PrintNoResourcesMessage()
#           - called to print message that there were no resources to display
#
#   Part of the Scout Portal Toolkit
#   Copyright 2003 Internet Scout Project
#   http://scout.cs.wisc.edu
#

PageTitle("Home");

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

function AnnouncementsEnabled()
{
    global $SysConfig;

    return $SysConfig->AnnouncementsEnabled();
}

function PrintPrevAnnouncementLink()
{
    global $SysConfig;
    global $AnnouncementOffset;

    $NumAnnouncements = $SysConfig->NumAnnounceOnHomePage();
    $Offset = $AnnouncementOffset + $NumAnnouncements;

    print "index.php?P=Home&amp;AnnouncementOffset=$Offset";
}

function PrintNextAnnouncementLink()
{
    global $SysConfig;
    global $AnnouncementOffset;

    $NumAnnouncements = $SysConfig->NumAnnounceOnHomePage();
    $Offset = $AnnouncementOffset - $NumAnnouncements;

    print "index.php?P=Home&amp;AnnouncementOffset=$Offset";
}

function NextAnnouncementsAvailable()
{
    global $SysConfig;
    global $AnnouncementOffset;

    $NumAnnouncements = $SysConfig->NumAnnounceOnHomePage();
    return ($AnnouncementOffset >= $NumAnnouncements) ? TRUE : FALSE;
}

function PreviousAnnouncementsAvailable()
{
    global $MoreAnnouncements;
    return $MoreAnnouncements;
}

function PrintNumberOfAnnouncements()
{
    global $SysConfig;
    print $SysConfig->NumAnnounceOnHomePage();
}

function PrintAnnouncementsTableRows()
{
    global $User;
    global $DB;
    global $SysConfig;
    global $MoreAnnouncements;
    global $AnnouncementOffset;

    # an announcement is considered long if its text is more than this many
    # characters
    $LongTextLength = 275;

    # default values
    $MaxNumberOfDaysToGoBackForAnnouncements = 30;

    # if function to supply announcement DB query is available
    if (function_exists("SupplyAnnouncementDisplayQuery"))
    {
        # obtain query from function
        $DisplayQuery = SupplyAnnouncementDisplayQuery(
                $MaxNumberOfDaysToGoBackForAnnouncements,
                $SysConfig->NumAnnounceOnHomePage());
    }
    else
    {
        # use default query
        $DisplayQuery = "SELECT * FROM Announcements "
                ."ORDER BY DatePosted DESC "
                ."LIMIT ${AnnouncementOffset}, "
                ."999999999";
    }

    # query database for appropriate announcements
    $AnnouncementDB = new Database();
    $AnnouncementDB->Query($DisplayQuery);

    # determine number of announcements to display
    $MaxNumberOfAnnouncementsToDisplay=min($SysConfig->NumAnnounceOnHomePage(),
        $AnnouncementDB->NumRowsSelected());

    # determine if previous link should be displayed or not
    $MoreAnnouncements = ($AnnouncementDB->NumRowsSelected() <=
            $MaxNumberOfAnnouncementsToDisplay) ? false : true;

    $LongAnnouncements = array();

    # if announcements found
    if ($AnnouncementDB->NumRowsSelected() > 0)
    {
        $Index = 0;
        $Count = 0;

        # for each announcement
        while ($Index++ < $MaxNumberOfAnnouncementsToDisplay)
        {
            $Count++;
            $Announcement = $AnnouncementDB->FetchRow();

            # format date for display
            $DatePosted = date("M j", strtotime($Announcement["DatePosted"]));

            # get name of person who posted announcement
            $Poster = new User($DB, (int)$Announcement["PosterId"]);
            $PosterName = $Poster->Get("UserName");
            if (strlen($PosterName) < 1) {  $PosterName = "(unknown)";  }

            # add to the list of long announcements
            if (strlen($Announcement["AnnouncementText"]) > $LongTextLength)
            {
                $LongAnnouncements[] = array(
                    $Announcement["AnnouncementHeading"],
                    $DatePosted,
                    $PosterName,
                    $Announcement["AnnouncementText"],
                    $User->HasPriv(PRIV_NEWSADMIN),
                    "index.php?P=EditAnnouncement".
                    "&amp;F_Editing=1&amp;F_Id=".
                    $Announcement["AnnouncementId"]);
            }

            # otherwise print the announcement immediately
            else
            {
                PrintAnnouncementRow(
                    $Announcement["AnnouncementHeading"],
                    $DatePosted,
                    $PosterName,
                    $Announcement["AnnouncementText"],
                    $User->HasPriv(PRIV_NEWSADMIN),
                    "index.php?P=EditAnnouncement".
                    "&amp;F_Editing=1&amp;F_Id=".
                    $Announcement["AnnouncementId"]);
            }
        }

        # backwards compatibility
        $PrintLongFn = function_exists("PrintLongAnnouncementRow") ?
            "PrintLongAnnouncementRow" : "PrintAnnouncementRow";

        # if there is only one long announcement, don't make it clear the float
        if ($Count == 1 && count($LongAnnouncements) == 1)
        {
            $Parameters = array_shift($LongAnnouncements);
            $Parameters[] = FALSE;

            call_user_func_array($PrintLongFn, $Parameters);
        }

        # otherwise each long announcement should clear
        else
        {
            foreach ($LongAnnouncements as $Parameters)
            {
                call_user_func_array($PrintLongFn, $Parameters);
            }
        }
    }
    else
    {
        # print row with "no announcements" notice
        PrintNoAnnouncementsMessage();
    }
}

function NumAnnouncementRows()
{
    global $DB;
    global $SysConfig;
    global $_GET;

    # default values
    $MaxNumberOfDaysToGoBackForAnnouncements = 30;

    # if function to supply announcement DB query is available
    if (function_exists("SupplyAnnouncementDisplayQuery"))
    {
        # obtain query from function
        $DisplayQuery = SupplyAnnouncementDisplayQuery(
                $MaxNumberOfDaysToGoBackForAnnouncements,
                $SysConfig->NumAnnounceOnHomePage());
    }
    else
    {
        # use default query
        $DisplayQuery = "SELECT * FROM Announcements "
                ."ORDER BY DatePosted DESC "
                ."LIMIT 0, "
                ."999999999";
    }

    # query database for appropriate announcements
    $AnnouncementDB = new Database();
    $AnnouncementDB->Query($DisplayQuery);
    return $AnnouncementDB->NumRowsSelected();

}


function PrintPrevResourceLink()
{
    global $SysConfig;
    global $ResourceOffset;

    $NumResources = $SysConfig->NumResourcesOnHomePage();
    $Offset = $ResourceOffset + $NumResources;

    print "index.php?P=Home&amp;ResourceOffset=".$Offset;
}

function PrintNextResourceLink()
{
    global $SysConfig;
    global $ResourceOffset;

    $NumResources = $SysConfig->NumResourcesOnHomePage();
    $Offset = $ResourceOffset - $NumResources;

    print "index.php?P=Home&amp;ResourceOffset=".$Offset;
}

function NextResourcesAvailable()
{
    global $SysConfig;
    global $ResourceOffset;

    $NumResources = $SysConfig->NumResourcesOnHomePage();
    return ($ResourceOffset >= $NumResources) ? TRUE : FALSE;
}

function PreviousResourcesAvailable()
{
    global $MoreResources;
    return $MoreResources;
}

function PrintNumberOfResources()
{
    global $SysConfig;
    print $SysConfig->NumResourcesOnHomePage();
}

function PrintNewResourceTableRows()
{
    global $User;
    global $DB;
    global $MoreResources;
    global $SysConfig;
    global $ResourceOffset;

    $MaxDescriptionLength = 250;
    $MaxUrlLength = 60;

    if (is_null($ResourceOffset))
        $ResourceOffset = 0;

    # default values
    $MaxNumberOfResourcesToDisplay = $SysConfig->NumResourcesOnHomePage();
    $MaxNumberOfDaysToGoBackForResources = 7300;

    # if function to supply new resources is available
    if (function_exists("Local_GetNewResources"))
    {
        # call function to supply new resources
        $Resources = Local_GetNewResources(
                ($MaxNumberOfResourcesToDisplay + 1),
                $ResourceOffset,
                $MaxNumberOfDaysToGoBackForResources);
    }
    # backward compatibility to look for query string in UI file
    else if (function_exists("SupplyResourceDisplayQuery"))
    {
                # obtain query from function
        $DisplayQuery = SupplyResourceDisplayQuery(
                $MaxNumberOfDaysToGoBackForResources,
                $MaxNumberOfResourcesToDisplay+1,
                $ResourceOffset);

        # query database for appropriate resources
        $ResourceDB = new Database();
        $ResourceDB->Query($DisplayQuery);
        # set resource count
        $ResourceCount = $ResourceDB->NumRowsSelected();
        # get resources
        $Resources = array();
        while ($Resource = $ResourceDB->FetchRow())
        {
            array_push($Resources, new Resource($Resource["ResourceId"]));
        }
    }
    else
    {
        # retrieve resources using factory
        # NOTE:  Retrieves one more resource than is needed because we need
        #       to know if there are more resources.)
        $ResourceFact = new ResourceFactory();
        $Resources = $ResourceFact->GetRecentlyReleasedResources(
                ($MaxNumberOfResourcesToDisplay + 1),
                $ResourceOffset, $MaxNumberOfDaysToGoBackForResources);
    }

    # determine whether "Previous" link should be displayed
    $ResourceCount = count($Resources);
    $MoreResources = ($ResourceCount <= $MaxNumberOfResourcesToDisplay) ? FALSE : TRUE;

    # if resources found
    if ($ResourceCount)
    {
        # drop last resource if we have one more than is needed
        if ($ResourceCount > $MaxNumberOfResourcesToDisplay) {  array_pop($Resources);  }

        # for each resource
        foreach ($Resources as $Resource)
        {
            # display resource
            PrintNewResourceRow($Resource,
                    "index.php?P=FullRecord&amp;ID=".$Resource->Id(),
                    $Resource->UserCanEdit($User),
                    "index.php?P=EditResource&amp;ID=".$Resource->Id(),
                    $Resource->ScaledCumulativeRating());
        }
    }
    else
    {
        # print row with "no resources" notice
        PrintNoResourcesMessage();
    }
}

# (automatically called while outputing <head> section if defined)
function AddJavascript()
{
    global $DB;
    $DB->Query("SELECT * FROM RSSConfiguration");
    $RssInfo = $DB->FetchRow();
    if ($RssInfo["NotifyBrowser"])
    {
        $FeedLink = OurBaseUrl()."index.php?P=RSS";
        ?>
        <link rel="alternate" title="<?PHP  print($RssInfo["ChannelTitle"]);  ?>"
                href="<?PHP  print($FeedLink);  ?>" type="application/rss+xml" />
        <?PHP
    }
}


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

# non-standard global variables
global $AnnouncementOffset;
global $MoreAnnouncements;
global $MoreResources;
global $ResourceOffset;
global $ReleaseResourceTotal;

# get the total number of released resources
$ResourceFactory = new ResourceFactory();
$ReleaseResourceTotal = $ResourceFactory->GetReleasedResourceTotal();

if (isset($_GET["ResourceOffset"]))
    $ResourceOffset = intval($_GET["ResourceOffset"]);
else
    $ResourceOffset = 0;

if (isset($_GET["AnnouncementOffset"]))
    $AnnouncementOffset = intval($_GET["AnnouncementOffset"]);
else
    $AnnouncementOffset = 0;
