<?PHP

/**
 * Print summary containing standard info (title, description, URL, screenshot,
 *      rating) about the given Resource.
 * @param $Resource Resource object.
 * @param $EditOkay TRUE to show the editing link.  (OPTIONAL -- defaults to FALSE)
 * @param $AppendRows Additional rows (including <tr> tags) to append to
 *      the formatting table.  (OPTIONAL)
 * @param $DisplayDescription TRUE to display the resource description.
 *      (OPTIONAL -- defaults to TRUE)
 * @param $DisplayExportCheckbox TRUE to display the export checkbox.  
 *      (OPTIONAL -- defaults to FALSE)
 * @param $TermsToHightlight Terms to highlight in the description.  (OPTIONAL)
 */
function PrintResourceSummary($Resource, $EditOkay = FALSE, $AppendedRows = NULL, 
    $DisplayDescription = TRUE, $DisplayExportCheckbox = FALSE, $TermsToHighlight = NULL)
{
    #----- CONFIGURATION ----------------------------------------------

    # maximum length of displayed values (in characters)
    $MaxUrlLength = 60;
    $MaxLengthResourceLink = 60;
    $MaxDescriptionLength = 200;


    #----- SETUP ------------------------------------------------------

    global $AF, $G_SysConfig, $G_User;

    # retrieve and format title
    $Schema = new MetadataSchema();
    $TitleField = $Schema->GetFieldByMappedName("Title");
    if ($Resource->UserCanViewField($G_User, $TitleField))
    {
        $Title = strip_tags($Resource->Get($TitleField),
            "<"."b><"."i><"."u><"."sub><"."sup><"."strike><"."a>");
    }

    # get URL link (if any)
    $UrlField = $Schema->GetFieldByMappedName("Url");
    if ($Resource->UserCanViewField($G_User, $UrlField))
    {
        if (strlen($Resource->Get($UrlField))) 
        {
            $UrlLink = "index.php?P=GoTo&amp;ID=".$Resource->Id()
                    ."&amp;MF=".$UrlField->Id();
            $RealUrlLink = $Resource->Get($UrlField);
        }
    }

    # get file link (if any)
    $FileField = $Schema->GetFieldByMappedName("File");
    if ($Resource->UserCanViewField($G_User, $FileField))
    {
        $FileList = $Resource->Get($FileField, TRUE);
        if (count($FileList))
        {
            $File = array_shift($FileList);
            $FileLink = $File->GetLink();
        }
    }

    # get link to resource and displayable link to resource
    if (isset($UrlLink) && isset($FileLink))
    {
        $ResourceLink = ($G_SysConfig->Value("PreferredLinkValue") == "FILE")
                ? $FileLink : $UrlLink;
    }
    elseif (isset($UrlLink))
    {
        $ResourceLink = $UrlLink;
    }
    elseif (isset($FileLink))
    {
        $ResourceLink = $FileLink;
    }
    if (isset($ResourceLink))
    {
        $ResourceLinkTag = "<a href=\"".$ResourceLink."\" title=\"Go to "
                .(isset($Title) ? htmlspecialchars(strip_tags($Title)) : "Resource")."\""
                ." alt=\"Go to ".(isset($Title) 
                        ? htmlspecialchars(strip_tags($Title)) : "Resource")."\""
                .($G_SysConfig->Value("ResourceLaunchesNewWindowEnabled")
                        ? " target=\"_blank\"" : "").">";
    }
    if (isset($UrlLink) && ($ResourceLink == $UrlLink))
    {
        $DisplayableResourceLink = (strlen($RealUrlLink) <= $MaxLengthResourceLink)
                ? $RealUrlLink : substr($RealUrlLink, 0, $MaxLengthResourceLink)."...";
    }

    # get link to full record page
    $FullRecordLink = "index.php?P=FullRecord&amp;ID=".$Resource->Id();
    $FullRecordLinkTag = "<a href=\"".$FullRecordLink."\" title=\"View Full Record\""
            ." alt=\"View Full Record for ".(isset($Title) 
                    ? htmlspecialchars(strip_tags($Title)) : "Resource")."\">";

    # retrieve and format description
    if ($DisplayDescription)
    {
        $DescriptionField = $Schema->GetFieldByMappedName("Description");
        if ($Resource->UserCanViewField($G_User, $DescriptionField))
        {
            # get stripped and length-limited version of description
            $Description = strip_tags($Resource->Get($DescriptionField),
                "<"."b><"."i><"."u><"."sub><"."sup><"."strike><"."a>");
            $Description = NeatlyTruncateString($Description, $MaxDescriptionLength);
    
            # if list of search terms was supplied
            if (is_array($TermsToHighlight) && count($TermsToHighlight))
            {
                # highlight terms in description
                foreach ($TermsToHighlight as $Term)
                {
                    $Patterns[] = "/([^a-z]{1})(".$Term.")([^a-z]{1})/i";
                    $Replacements[] = "\\1<b>\\2</b>\\3";
                    $Patterns[] = "/^(".$Term.")([^a-z]{1})/i";
                    $Replacements[] = "<b>\\1</b>\\2";
                    $Patterns[] = "/([^a-z]{1})(".$Term.")$/i";
                    $Replacements[] = "\\1<b>\\2</b>";
                }
    
                $Description = preg_replace(
                        $Patterns, $Replacements, $Description);
            }
        }
    }

    # retrieve and format screenshot thumbnail
    $ScreenshotField = $Schema->GetFieldByMappedName("Screenshot");
    if ($Resource->UserCanViewField($G_User, $ScreenshotField))
    {
        $Screenshot = $Resource->Get("Screenshot", TRUE);

        if (is_null($Screenshot) || !is_readable($Screenshot->ThumbnailUrl()))
        {
            unset($Screenshot);
        }
    }

    # retrieve and format resource rating
    $RatingField = $Schema->GetFieldByName("Cumulative Rating");
    if ($G_SysConfig->ResourceRatingsEnabled()
        && $Resource->UserCanViewField($G_User, $RatingField))
    {
        if (!is_null($Resource->ScaledCumulativeRating()))
        {
            $StarCount = max(1, ($Resource->ScaledCumulativeRating() / 2));
            $RatingGraphic = sprintf("StarRating--%d_%d.gif", 
                    $StarCount, (($StarCount % 1) * 10));;
            $RatingAltText = sprintf("This resource has a %.1f-star rating.", 
                    $StarCount);;
        }
    }
    if ($G_User->IsLoggedIn())
    {
        $UserRating = $Resource->Rating();
        if ($UserRating == NULL) {  $UserRating = 0;  }
    }

    # retrieve alt text for accessibility match icon (if needed)
    $AccessibilityMatch = GetAccessMatchText($Resource, $Schema, $G_User);


    #----- DISPLAY ----------------------------------------------------

    /*
    * At this point these values should be available:
    *   $DisplayExportCheckbox - whether to display export checkbox
    *   $FullRecordLink - link to full record page
    *   $FullRecordLinkTag - complete <a> tag for full record page (includes alt
    *         attribute text)
    *   $Resource - Resource object
    *
    * And these values may (or may not) be available:
    *   $Description - possibly-truncated text for standard description field
    *         (terms highlighted and inappropriate HTML tags already stripped)
    *   $DisplayableResourceLink - displayable URL for resource itself or file
    *   $ResourceLink - URL to go to resource or to download file
    *   $ResourceLinkTag - complete <a> tag for resource link (includes title for
    *         alt attribute text and target=blank if resource should launch new window)
    *   $RatingGraphic - star rating graphic file name (no leading path)
    *   $RatingAltText - star rating graphic alt text
    *   $Screenshot - Image object for standard screenshot field
    *   $Title - text for standard title field (inappropriate HTML tags already stripped)
    *   $UserRating - value to be passed to PrintFastRating()
    */
?>
<table width="100%" border="0" cellpadding="0" cellspacing="0" 
        style="border-bottom: 1px solid #DDDDDD;">
<tr>
    <td align="center" valign="top" rowspan="2">
        <div style="width: 40px; margin-top: 5px;">
            <?PHP  if (isset($ResourceLinkTag)) {  print($ResourceLinkTag);  }  ?>
            <img src="<?PHP $AF->PUIFile("go.gif"); ?>" 
                    border="0" width="21" height="22"> 
            <?PHP  if (isset($ResourceLinkTag)) {  print("</a>");  }  ?>
        </div>
    </td>
    <?PHP if ($DisplayExportCheckbox) {  ?>
    <td align="left" valign="top">
        <input type="checkbox" name="F_OkayForExport_<?PHP 
                print($Resource->Id());  ?>" style="margin-top: 7px;" />
    </td>
    <?PHP }  ?>
    <?PHP  if (isset($Title) || isset($Description)) {  ?>
    <td width="100%" align="left" valign="top" style="padding: 5px; height: 0px;">
        <div style="margin-right: 20px;">
            <?PHP  if (isset($Title)) {  ?>
                <?PHP  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                            ? $FullRecordLinkTag : (isset($ResourceLinkTag)
                            ? $ResourceLinkTag : ""));  ?>
                <span class="ResourceHeader"><b><?PHP print($Title); ?></b></span>
                <?PHP  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                            ? "</a>" : (isset($ResourceLinkTag)
                            ? "</a>" : ""));  ?>
                <br />
            <?PHP } ?>
            <?PHP if (isset($Description)) {  print($Description); } ?>
        </div>
    </td>
    <?PHP } ?>
    <?PHP  if (isset($Screenshot)) {  ?>
    <td align="center" valign="top">
        <a href="index.php?P=FullImage&amp;ResourceId=<?PHP print $Resource->Id(); ?>&amp;FieldName=Screenshot"><img class="ThumbnailImage" src="<?PHP print $Screenshot->ThumbnailUrl(); ?>" title="<?PHP print $Screenshot->AltText(); ?>" alt="<?PHP print $Screenshot->AltText(); ?>" style="height: <?PHP print $Screenshot->ThumbnailHeight(); ?>; width: <?PHP print $Screenshot->ThumbnailWidth(); ?>; margin: 7px 0px <?PHP print (isset($UserRating) || isset($DisplayableResourceLink)) ? 0 : 7; ?>px 10px; padding: 10px; border: 1px solid #DDD; background: #F0F0F0;" /></a>
    </td>
    <?PHP  }  ?>
    <td valign="top" align="right">
        <div style="margin: 5px 0px 0px 15px;">
            <?PHP  if (isset($RatingGraphic)) {  ?>
            <img src="<?PHP $AF->PUIFile($RatingGraphic); ?>" title="<?PHP print($RatingAltText); ?>" alt="<?PHP print($RatingAltText); ?>" style="height: 12px; width: 64px;" /><br />
            <?PHP  }  ?>
            <?PHP  if (strlen($AccessibilityMatch)) {  ?>
            <img src="<?PHP $AF->PUIFile("AccessMatch.gif"); ?>" title="<?PHP print $AccessibilityMatch; ?>" alt="<?PHP print $AccessibilityMatch; ?>" style="border: none;" /><br />
            <?PHP  }  ?>
            <?PHP  print($FullRecordLinkTag."Full&nbsp;Record</a>");  ?>
            <?PHP if ($EditOkay) { ?>
            <br /><div class="editbutton"><a class="link" href="index.php?P=EditResource&amp;ID=<?PHP print $Resource->Id(); ?>">Edit</a></div>
            <?PHP } ?>
        </div>
    </td>
</tr>

<?PHP if (isset($UserRating) || isset($DisplayableResourceLink)) { ?>
<tr>
    <?PHP if ($DisplayExportCheckbox) { print "<td></td>"; } ?>
    <td align="left" valign="baseline" colspan="<?PHP (isset($Screenshot)) ? print "3" : print "2"; ?>" style="padding: 5px 0 5px 5px;">
        <?PHP if (isset($UserRating)) { PrintFastRating($Resource->Id(), $UserRating); } ?>
        <?PHP if (isset($DisplayableResourceLink)) { ?>
        <a href="<?PHP  print($ResourceLink);  ?>" style="line-height: 27px"<?PHP if($G_SysConfig->ResourceLaunchesNewWindowEnabled()) { print " target=\"_blank\""; } ?>>
        <?PHP print $DisplayableResourceLink; ?></a><?PHP } ?>
    </td>
</tr>
<?PHP } ?>

<?PHP if (!is_null($AppendedRows)) { print $AppendedRows; } ?>

</table>

<?PHP } ?>
