<?PHP
#
#   FILE:  ViewFolder.php
#
#   Part of the Collection Workflow Integration System (CWIS)
#   Copyright 2012 Internet Scout Project
#   http://scout.wisc.edu/
#

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

/**
 * Print each folder item. This function also passes the previous and subsequent
 * items to the folder item printing function to facilitate item bubbling.
 * @param Folder $Folder Folder the items belong to
 * @param array $Items Folder items to print
 * @return void
 */
function PrintFolderItems(Folder $Folder, array $Items)
{
    # we want to be able to get next and previous values, so use numeric indices
    $Items = array_values($Items);
    $NumberItems = count($Items);

    for ($i = 0; $i < $NumberItems; $i++) {
        $Previous = isset($Items[$i-1]) ? $Items[$i-1] : NULL;
        $Next = isset($Items[$i+1]) ? $Items[$i+1] : NULL;

        PrintFolderItem($Folder, $Items[$i], $Previous, $Next);
    }
}

/**
 * Given a list of resource IDs, filter out the resources that are non-viewable
 * to the current user. The resources IDs can from multiple schema
 * @param array $ItemIds List of resource IDs to filter
 * @return array the list of filtered resources IDs
 */
function FilterNonviewableResources(array $ItemIds)
{
    $FilteringIds = array();
    $ResourceFactories = array();

    # divide $ItemIds by schema and construct ResourceFactory accordingly
    # to filter out resources
    foreach ($ItemIds as $ItemId)
    {
        $CurrentResource = new Resource($ItemId);
        $CurrentSchemaId = $CurrentResource->SchemaId();
        if (!array_key_exists($CurrentSchemaId, $FilteringIds))
        {
            $FilteringIds[$CurrentSchemaId] = array();
            $ResourceFactories[$CurrentSchemaId] = new ResourceFactory($CurrentSchemaId);
        }
        $FilteringIds[$CurrentSchemaId][] = $ItemId;
    }
    $ItemIds = array();
    # filter out the resources that the current user doesn't have permission to see
    foreach ($FilteringIds as $SchemaId => $FilteringId)
    {
        $ResourceFactory = $ResourceFactories[$SchemaId];
        $FilterResult = $ResourceFactory->
                FilterNonViewableResources($FilteringId, $GLOBALS["G_User"]);
        $ItemIds = array_merge($ItemIds, $FilterResult);
    }

    return $ItemIds;
}

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

global $Folder;
global $Id;
global $Name;
global $NormalizedName;
global $TruncatedName;
global $IsShared;
global $IsSelected;
global $OwnerId;
global $Note;
global $ItemIds;
global $Items;
global $ItemCount;
global $HasItems;
global $ShareUrl;

# redirect if no folder ID is given
if (!isset($_GET["FolderId"]))
{
    $AF->SetJumpToPage("P_Folders_ManageFolders");
    return;
}

$Offset = intval(GetArrayValue($_GET, "Offset", 0));
$Length = intval(GetArrayValue($_GET, "Length", 25));

# set the length to a sensible value if it is not already one
if (!$Length)
{
    $Length = 25;
}

try
{
    $FolderFactory = new Folders_FolderFactory($User->Id());
    $Folder = new Folders_Folder(GetArrayValue($_GET, "FolderId"));

    $Id = $Folder->Id();
    $Name = $Folder->Name();
    $NormalizedName = $Folder->NormalizedName();
    $TruncatedName = NeatlyTruncateString($Name, 18);
    $IsShared = $Folder->IsShared();
    $OwnerId = $Folder->OwnerId();
    $Note = $Folder->Note();
    $ItemIds = $Folder->GetItemIds($Offset, $Length);
    # filter out the resources that the current user cannot view
    $ItemIds = FilterNonviewableResources($ItemIds);

    $Items = array();
    $TotalItemCount = $Folder->GetItemCount();
    $ItemCount = count($ItemIds);
    $HasItems = $ItemCount > 0;
    $HasPreviousItems = $Offset > 0;
    $HasNextItems = $Offset + $Length < $TotalItemCount;
    $PreviousOffset = max(0, $Offset - $Length);
    $NextOffset = min($TotalItemCount, $Offset + $Length);
    $IsOwner = $User->Id() == $OwnerId;
    $IsSelected = FALSE;
    $ShareUrl = Folders_Common::GetShareUrl($Folder);

    # move back a page if items exist but there are none to display given the
    # offset and length
    if (!$HasItems && $TotalItemCount > 0)
    {
        # compute the new offset
        $Offset = max(0, $TotalItemCount - $Length - ($TotalItemCount % $Length));

        # construct the page to redirect to
        $Redirect = "P_Folders_ViewFolder";
        $Redirect .= "&FolderId=" . urlencode($Id);
        $Redirect .= "&Offset=" . urlencode($Offset);
        $Redirect .= "&Length=" . urlencode($Length);

        $AF->SetJumpToPage($Redirect);
    }

    # this will only work if the user is logged in, but since the page might be
    # shared, only fetch it conditionally
    if ($IsOwner)
    {
        $IsSelected = $FolderFactory->GetSelectedFolder()->Id() == $Folder->Id();
    }

    # transform item IDs into item objects
    foreach ($ItemIds as $ItemId)
    {
        $Resource = new Resource($ItemId);

        # make sure the user can view the resource
        if ($Resource->UserCanView($User))
        {
            $Items[$ItemId] = $Resource;
        }
    }

    # show login box if not shared and user is not logged in
    if (!$IsShared && !CheckAuthorization())
    {
        return;
    }

    # redirect if the user should not see the folder
    if (!$IsShared && !$IsOwner)
    {
        $AF->SetJumpToPage("P_Folders_ManageFolders");
        return;
    }

    PageTitle(strip_tags($Name));
}

# redirect if given a bad folder ID
catch (Exception $Exception)
{
    $AF->SetJumpToPage("P_Folders_ManageFolders");
    return;
}
