<?php

#
#   FILE:  SPT--FullRecord.php
#
#   FUNCTIONS PROVIDED:
#       PrintControlledNames()
#           - print list of controlled names associated with the record
#       PrintClassificationNames()
#           - print list of classification names associated with the record
#       UserAlreadyRatedResource()
#           - indicate whether logged in user has already rated resource
#       PrintUserRatingNumber()
#       PrintCumulativeRatingNumber()
#           - print raw rating number
#       PrintUserRatingGraphic()
#       PrintCumulativeRatingGraphic()
#           - call user-supplied routine to display appropriate rating graphic
#       PrintNumberOfRatings()
#           - print number of ratings used to calculate cumulative rating
#       PrintNumberOfRatings()
#           - print an "s" if there was more than one rating
#       ResourceHasBeenRated()
#           - returns TRUE if someone has rated this resource
#       PrintRateResourceLink()
#           - print URL (to go in form tag action field) for rating processing
#       ResourceCommentsAreAvailable()
#           - returns TRUE is this resource has comments
#       PrintResourceComments()
#           - calls PrintResourceComment() for each comment for this resource
#
#   FUNCTIONS EXPECTED:
#       PrintForumMessage($Subject, $Body, $DatePosted, $PosterName,
#               $PosterEmail, $EditOkay, $EditLink, $DeleteLink)
#           - called by PrintResourceComments() for each comment
#       PrintControlledName()
#           - called by PrintControlledNames() for each controlled name
#       PrintCNStart()
#       PrintCNEnd()
#       PrintNewLine()
#       PrintNameType()
#       PrintClassStart()
#       PrintClassEnd()
#       PrintClassificationInfo()
#           - ???
#       PrintRatingGraphicNoRating()
#           - print graphic (or text) to indicate resource with no rating
#       PrintRatingGraphic0()
#       PrintRatingGraphic1()
#       PrintRatingGraphic2()
#       PrintRatingGraphic3()
#       PrintRatingGraphic4()
#       PrintRatingGraphic5()
#       PrintRatingGraphic6()
#       PrintRatingGraphic7()
#       PrintRatingGraphic8()
#       PrintRatingGraphic9()
#       PrintRatingGraphic10()
#           - print graphic (or text) to indicate specified rating
#        PrintTextField()
#
#   Part of the Scout Portal Toolkit
#   Copyright 2003 Internet Scout Project
#   http://scout.cs.wisc.edu
#

PageTitle("Full Resource Record Display");

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

function PrintResourceId()
{
    global $Resource;

    print $Resource->Id();
}

function PrintTitle()
{
    global $Resource;

    print GetHtmlEscapedString($Resource->Get("Title"));
}

function PrintFieldName()
{
    global $Field;

    print $Field->Name();
}

function PrintValue()
{
    global $Field, $Value, $TruncateValue;

    global $Resource;
    global $AF;
    $SignalResult = $AF->SignalEvent(
            "EVENT_FIELD_DISPLAY_FILTER", array(
            "Field" => $Field,
            "Resource" => $Resource,
            "Value" => $Value));
    $OurValue = $SignalResult["Value"];

    if ($Field->Type() == MetadataSchema::MDFTYPE_POINT)
    {
        print(htmlentities($OurValue["X"]).", ".htmlentities($OurValue["Y"]));
    }
    else
    {
        if ($TruncateValue)
        {
            print NeatlyTruncateString(stripslashes($OurValue),70,TRUE);
        }
        else
        {
            print stripslashes($OurValue);
        }
    }
}

function PrintQualifier()
{
    global $Field;
    global $Entry;
    global $Value;
    global $GenericId;

    if ($Field->UsesQualifiers())
    {
        $Qualifier = $Entry[$Field->Name()." Qualifier"];
        # normal field
        if (is_object($Qualifier))
        {
            $Name = $Qualifier->Name();
            if (!empty($Name))
                print "<small> (<a href=\"".$Qualifier->Url()."\">".
                    $Qualifier->Name()."</a>)</small>";
        }
        # controlled name, options, or classifications, use global Qualifier
        else if (is_array($Qualifier))
        {
            # look up this qualifier
            foreach ($Qualifier as $ArrayId => $QualifierObj)
            {
                if ($ArrayId == $GenericId)
                    break;
            }
            if (is_object($QualifierObj))
            {
                $Name = $QualifierObj->Name();
                if (!empty($Name))
                    print "<small> (<a href=\"".$QualifierObj->Url()."\">".
                        $QualifierObj->Name()."</a>)</small>";
            }
        }
    }
}

function GetLink()
{
    global $Link;

    print $Link;
}

function PrintControlledNameLink()
{
    global $ControlledNameLink;

    print $ControlledNameLink;
}

function CumulativeRatingFieldEnabled()
{
    global $Schema;

    $Field = $Schema->GetFieldByName("Cumulative Rating");
    return $Field->Viewable();
}

function PrintAllFields()
{
    global $Entry, $Schema, $Field, $Value, $Link, $SysConfig, $DB, $Resource;
    global $G_User, $TruncateValue;

    # for each metadata field
    $Fields = $Schema->GetFields(NULL, MetadataSchema::MDFORDER_DISPLAY);
    foreach ($Fields as $Field)
    {
        $FieldName = $Field->Name();
        $Value = $Entry[$FieldName];
        $TruncateValue = FALSE;
        if ($Resource->UserCanViewField($G_User, $Field) && !empty($Value))
        {
            switch($Field->Type())
            {
                case MetadataSchema::MDFTYPE_TEXT:
                case MetadataSchema::MDFTYPE_URL:
                    # special case to make Title hyperlink to URL
                    if ($FieldName == "Title" && strlen($Entry["Url"]) > 0)
                    {
                        $Link = $Entry["Url"]."\" class=\"ResourceTitle\"";
                        if ($SysConfig->ResourceLaunchesNewWindowEnabled())
                            $Link .= " target=\"_blank\"";
                        PrintLink();
                    }
                    else if ( $FieldName == "Url" )
                    {
                        $TruncateValue = TRUE;
                        $Link = $Value;
                        PrintLink();
                    }
                    else
                        PrintRow();
                    break;

                case MetadataSchema::MDFTYPE_PARAGRAPH:
                    # translate newlines into <br> prior to printing
                    $Value = str_replace("\n", "<br>", $Value);
                    PrintParagraphField();
                    break;

                case MetadataSchema::MDFTYPE_NUMBER:
                    if ($FieldName != "Cumulative Rating")
                        PrintRow();
                    break;

                case MetadataSchema::MDFTYPE_POINT:
                    PrintRow();
                    break;

                case MetadataSchema::MDFTYPE_DATE:
                	$Date = $Value;
			        $Value = $Date->Formatted();
                    if (!empty($Value))
                        PrintRow();
                    break;

                case MetadataSchema::MDFTYPE_TIMESTAMP:
                    PrintRow();
                    break;

                case MetadataSchema::MDFTYPE_FLAG:
			        if ($Value > 0)
				        $Value = $Field->FlagOnLabel();
			        else
				        $Value = $Field->FlagOffLabel();
				    PrintRow();
				    break;

                case MetadataSchema::MDFTYPE_TREE:
                    PrintClassificationNames();
                    break;

                case MetadataSchema::MDFTYPE_CONTROLLEDNAME:
                case MetadataSchema::MDFTYPE_OPTION:
                    PrintCNStart();
                    PrintControlledNames();
                    PrintCNEnd();
                    break;

                case MetadataSchema::MDFTYPE_USER:
                    if ($G_User->HasPriv(PRIV_RESOURCEADMIN))
                    {
                        $NewUser = $Entry[$FieldName];
                        # make sure UserId is valid
                        if (is_null($NewUser->Get("UserId")))
                            $Value = "Unknown";
                        else
                            $Value = $NewUser->Get("UserName");
                        PrintRow();
                    }
                    break;

                case MetadataSchema::MDFTYPE_IMAGE:
                    $SPTImage = $Resource->GetByField($Field, TRUE);
                    $ResourceId = $Resource->Id();
                    if ($SPTImage && (is_readable($SPTImage->PreviewUrl())))
                    {
                        PrintImageField($FieldName,
                                        "index.php?P=FullImage"
                                        ."&amp;ResourceId=".$ResourceId
                                        ."&amp;&FieldName=".$FieldName
                                        ."&amp;edit=0",
                                        $SPTImage->Height(),
                                        $SPTImage->Width(),
                                        $SPTImage->PreviewUrl(),
                                        $SPTImage->PreviewHeight(),
                                        $SPTImage->PreviewWidth(),
                                        $SPTImage->AltText());
                    }
                    break;

                case MetadataSchema::MDFTYPE_FILE:
                    if ($Resource->UserCanViewField($G_User, $Field))
                    {
                        PrintFileField($Field, $Resource);
                    }
                    break;
            }
        }
    }
}

# display controlled names for this record
function PrintControlledNames()
{
    global $Schema;
    global $Field;
    global $Link;
    global $Value;
    global $Resource;
    global $GenericId;

    # retrieve list of entries for field
    $Names = $Resource->GetByField($Field);

    # print field name
    PrintNameType($Field->Name());

    # for each entry
    foreach ($Names as $GenericId => $Value)
    {
        # build link to controlled name search
        if ($Field->Type() == MetadataSchema::MDFTYPE_OPTION)
        {
            $Link = "index.php?P=AdvancedSearch&amp;Q=Y&amp;"
                ."G".$Field->Id()."=".$GenericId;
        }
        else
        {
            $Link = "index.php?P=AdvancedSearch&amp;Q=Y&amp;"
                ."F".$Field->Id()."=".urlencode("=".$Value);
        }

         # print entry
         PrintLinkedValue();
    }
}

 # display classifications for this record
function PrintClassificationNames()
{
    global $Schema;
    global $Link;
    global $Field;
    global $Resource;
    global $Value;
    global $GenericId;

    if (isset($Field) && $Field->Enabled() && $Field->Viewable())
    {
        $Names = $Resource->Classifications();

        $NeedToPrintStart = TRUE;
        foreach ($Names as $ClassificationType => $ClassificationTypes)
        {
            if ($ClassificationType == $Field->Name())
            {
                foreach ($ClassificationTypes as $GenericId => $Classification)
                {
                    $Value = stripslashes($Classification);

                    if (!empty($Classification))
                    {
                        if ($NeedToPrintStart)
                        {
                            PrintClassStart();
                            $NeedToPrintStart = FALSE;
                        }
                        $Link = "index.php?P=AdvancedSearch&amp;Q=Y&amp;"
                            ."G".$Field->Id()."=".$GenericId;
                        PrintLinkedValue();
                    }
                }
                if (count($Names) > 0)
                    PrintClassEnd();
            }
        }
    }
}

function UserAlreadyRatedResource()
{
    global $Resource;
    return ($Resource->Rating() == NULL) ? FALSE : TRUE;
}

function PrintUserRatingNumber()
{
    global $Resource;
    print($Resource->Rating());
}

function PrintCumulativeRatingNumber()
{
    global $Resource;
    print($Resource->CumulativeRating());
}

function PrintUserRatingGraphic()
{
    global $Resource;
    PrintRatingGraphic($Resource->Rating());
}

function PrintCumulativeRatingGraphic()
{
    global $Resource;
    PrintRatingGraphic($Resource->CumulativeRating());
}

function PrintNumberOfRatings()
{
    global $Resource;
    print($Resource->NumberOfRatings());
}

function PrintNumberOfRatingsPlural()
{
    global $Resource;
    if ($Resource->NumberOfRatings() > 1) {  print("s");  }
}

function ResourceHasBeenRated()
{
    global $Resource;
    return ($Resource->NumberOfRatings() > 0) ? TRUE : FALSE;
}

function PrintRateResourceLink()
{
    global $ResourceId;
    print("index.php?P=RateResource&amp;F_ResourceId=".$ResourceId);
}

function ResourceCommentsAreAvailable()
{
    global $Resource;
    return ($Resource->NumberOfComments() > 0) ? TRUE : FALSE;
}

function CheckForEdit($PosterId)
{
    global $User;

    if (($User->Get("UserId") == $PosterId &&
        $User->HasPriv(PRIV_POSTCOMMENTS)) ||
        $User->HasPriv(PRIV_FORUMADMIN))
        return true;
    else
        return false;
}

function PrintResourceComments()
{
    global $User;
    global $Resource;
    global $ResourceId;

    # retrieve comments
    $Comments = $Resource->Comments();

    # for each comment
    foreach ($Comments as $Comment)
    {
        $EditOkay = CheckForEdit($Comment->PosterId());
        $MessageId = $Comment->MessageId();
        $EditLink = "index.php?P=AddResourceComment"
            ."&amp;ResourceId=".$ResourceId
            ."&amp;MessageId=".$MessageId;
        $DeleteLink = "index.php?P=AddResourceComment"
            ."&amp;ResourceId=".$ResourceId
            ."&amp;MessageId=".$MessageId;
        $SpamLink = $User->HasPriv(PRIV_FORUMADMIN, PRIV_USERADMIN) ?
            "index.php?P=CleanSpam"
            ."&amp;PosterId=".$Comment->PosterId()
            ."&amp;ResourceId=".$ResourceId :
            "";
# print comment
        PrintForumMessage(
                $Comment->Subject(),
                $Comment->Body(),
                $Comment->DatePosted(),
                $Comment->PosterName(),
                $Comment->PosterEmail(),
                $EditOkay,
                $EditLink,
                $DeleteLink,
                NULL,
                TRUE,
                $SpamLink);
    }
}

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

function PrintRatingGraphic($Rating)
{
    global $Resource;
    if (($Rating === NULL) || ($Resource->NumberOfRatings() < 1))
    {
        PrintRatingGraphicNoRating();
    }
    else
    {
        switch (intval(($Rating + 5) / 10))
        {
            case 0:  PrintRatingGraphic0();  break;
            case 1:  PrintRatingGraphic1();  break;
            case 2:  PrintRatingGraphic2();  break;
            case 3:  PrintRatingGraphic3();  break;
            case 4:  PrintRatingGraphic4();  break;
            case 5:  PrintRatingGraphic5();  break;
            case 6:  PrintRatingGraphic6();  break;
            case 7:  PrintRatingGraphic7();  break;
            case 8:  PrintRatingGraphic8();  break;
            case 9:  PrintRatingGraphic9();  break;
            case 10:  PrintRatingGraphic10();  break;
        }
    }
}



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

# non-standard global variables
global $ControlledNameLink;
global $Entry;
global $Field;
global $GenericId;
global $Link;
global $Resource;
global $ResourceId;
global $Schema;
global $Value;

global $Fields;
global $G_Resource;

# Get the schema
$Schema = new MetadataSchema();

# Get the fields for the schema
$Fields = $Schema->GetFields();

# if resource ID was supplied
$ResourceId = isset($_GET["ID"])
        ? intval($_GET["ID"]) : (isset($_GET["ResourceId"])
        ? intval($_GET["ResourceId"]) : $Session->Get("ResourceId"));
if ($ResourceId !== NULL)
{
    # load resource
    $Resource = new Resource($ResourceId);
    $G_Resource = $Resource;

    # check authorization if the resource has not been released
    if (!$Resource->Get("Release Flag"))
    {
        if (!CheckAuthorization(PRIV_RESOURCEADMIN, PRIV_MYRESOURCEADMIN, PRIV_RELEASEADMIN)) {  return;  }
    }

    # load resource values
    $Entry = $Resource->GetAsArray();
}
else
{
    # display error page
    if (!CheckAuthorization(-1)) {  return;  }
}

# cache various values
if (isset($Entry["DateLastVerified"]))
    $DateLastVerified = $Entry["DateLastVerified"];

?>
