<?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 = StripXSSThreats($Resource->Get($TitleField));
    }

    # 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 More Info\""
            ." alt=\"View More Info 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 ($ScreenshotField
        && $ScreenshotField->Status() == MetadataSchema::MDFSTAT_OK
        && $Resource->UserCanViewField($G_User, $ScreenshotField))
    {
        $ScreenshotFieldName = $ScreenshotField->Name();
        $Screenshot = $Resource->Get($ScreenshotField, TRUE);

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

    # retrieve and format resource rating
    $RatingField = $Schema->GetFieldByName("Cumulative Rating");
    $RatingsEnabled = $G_SysConfig->ResourceRatingsEnabled();
    if ($RatingsEnabled && $Resource->UserCanViewField($G_User, $RatingField))
    {
        $ScaledRating = $Resource->ScaledCumulativeRating();
        if (!is_null($ScaledRating) && $ScaledRating > 0)
        {
            $StarCount = max(1, ($ScaledRating / 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 class="cw-table cw-table-fullsize cw-content-resourcesummary">
    <tbody>
        <tr>
            <td rowspan="2">
                <?PHP if (isset($ResourceLinkTag)) { print($ResourceLinkTag); } ?>
                <img src="<?PHP $AF->PUIFile("go.gif"); ?>" alt="View Resource" />
                <?PHP if (isset($ResourceLinkTag)) { print("</a>"); } ?>
            </td>

            <td>
                <?PHP if ($DisplayExportCheckbox) { ?>
                <input type="checkbox" name="F_OkayForExport_<?PHP print($Resource->Id());  ?>" />
                <?PHP } ?>
            </td>

            <td>
              <?PHP if (isset($Title) || isset($Description)) { ?>
                    <?PHP if (isset($Title)) { ?>
                        <?PHP  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                                    ? $FullRecordLinkTag : (isset($ResourceLinkTag)
                                    ? $ResourceLinkTag : ""));  ?>
                        <b><?PHP print($Title); ?></b>
                        <?PHP  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                                    ? "</a>" : (isset($ResourceLinkTag)
                                    ? "</a>" : ""));  ?>
                    <?PHP } ?>

                    <?PHP if (isset($Description)) { ?>
                    <p><?PHP print $Description; ?></p>
                    <?PHP } ?>
                <?PHP } ?>
            </td>

            <td>
                <?PHP  if (isset($Screenshot)) {  ?>
                <a href="index.php?P=FullImage&amp;ResourceId=<?PHP print $Resource->Id(); ?>&amp;FieldName=<?PHP print $ScreenshotFieldName; ?>">
                    <img height="<?PHP print $Screenshot->ThumbnailHeight(); ?>" width="<?PHP print $Screenshot->ThumbnailWidth(); ?>" src="<?PHP print $Screenshot->ThumbnailUrl(); ?>" title="<?PHP print $Screenshot->AltText(); ?>" alt="<?PHP print $Screenshot->AltText(); ?>" />
                </a>
                <?PHP } ?>
            </td>

            <td>
                <ul class="cw-list cw-list-unmarked cw-list-dematte">
                    <?PHP if (isset($RatingGraphic) && $RatingsEnabled) { ?>
                    <li><img src="<?PHP $AF->PUIFile($RatingGraphic); ?>" title="<?PHP print($RatingAltText); ?>" alt="<?PHP print($RatingAltText); ?>" style="height: 12px; width: 64px;" /></li>
                    <?PHP } ?>
                    <?PHP if (strlen($AccessibilityMatch)) { ?>
                    <li><img src="<?PHP $AF->PUIFile("AccessMatch.gif"); ?>" title="<?PHP print $AccessibilityMatch; ?>" alt="<?PHP print $AccessibilityMatch; ?>" style="border: none;" /></li>
                    <?PHP } ?>
                    <li><?PHP print($FullRecordLinkTag."More Info</a>"); ?></li>
                    <?PHP if ($EditOkay) { ?>
                    <li><a class="cw-button cw-button-constrained cw-button-elegant" href="index.php?P=EditResource&amp;ID=<?PHP print $Resource->Id(); ?>">Edit</a></li>
                    <?PHP } ?>
                </ul>
            </td>
        </tr>

        <tr>
            <td></td>
            <td colspan="4">
            <?PHP if (isset($UserRating) || isset($DisplayableResourceLink)) { ?>
                <?PHP if (isset($UserRating) && $RatingsEnabled) { 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 } ?>
            <?PHP } ?>
            </td>
        </tr>

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

    </tbody>
</table>

<?PHP } ?>
