<?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, $FullRecordLink = 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(GetResourceFieldValue($Resource, $TitleField));
    }

    $UrlLooksValid = TRUE;

    # get URL link (if any)
    $UrlField = $Schema->GetFieldByMappedName("Url");
    if ($Resource->UserCanViewField($G_User, $UrlField))
    {
        $Url = GetResourceFieldValue($Resource, $UrlField);

        if (strlen($Url))
        {
            $UrlLink = "index.php?P=GoTo&amp;ID=".$Resource->Id()
                    ."&amp;MF=".$UrlField->Id();
            $RealUrlLink = GetResourceFieldValue($Resource, $UrlField);

            if (!preg_match('/^\s*[a-zA-Z]+:\/\//', $RealUrlLink))
            {
                $UrlLooksValid = FALSE;
            }
        }
    }

    # get file link (if any)
    $FileField = $Schema->GetFieldByMappedName("File");
    if ($Resource->UserCanViewField($G_User, $FileField))
    {
        $FileList = GetResourceFieldValue($Resource, $FileField, TRUE);
        if (is_array($FileList) && count($FileList))
        {
            $File = array_shift($FileList);
            $FileLink = OurBaseUrl().$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;
    }

    $UrlLooksValid = isset($ResourceLink) && $UrlLooksValid;

    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))
    {
        if (strlen($RealUrlLink) > $MaxLengthResourceLink &&
            strlen(strip_tags($RealUrlLink))==strlen($RealUrlLink))
        {
            $DisplayableResourceLink = substr($RealUrlLink, 0, $MaxLengthResourceLink)."...";
        }
        else
        {
            $DisplayableResourceLink = $RealUrlLink;
        }
    }

    # get link to full record page
    $FullRecordLink = $FullRecordLink
        ? $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(GetResourceFieldValue($Resource, $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>";
                    $Patterns[] = "/^(".$Term.")$/i";
                    $Replacements[] = "<b>\\1</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 = GetResourceFieldValue($Resource, $ScreenshotField, TRUE);

        if (is_null($Screenshot)
            || ($Screenshot instanceof SPTImage
                && !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  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                                    ? $FullRecordLinkTag : (isset($ResourceLinkTag) && $UrlLooksValid
                                    ? $ResourceLinkTag : ""));  ?>
                <img src="<?PHP $AF->PUIFile("go.gif"); ?>" alt="View Resource" />
                <?PHP if (isset($ResourceLinkTag) && $UrlLooksValid) { 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) && $UrlLooksValid
                                    ? $ResourceLinkTag : ""));  ?>
                        <b><?PHP print($Title); ?></b>
                        <?PHP  print(($G_SysConfig->Value("TitlesLinkTo") == "RECORD")
                                    ? "</a>" : (isset($ResourceLinkTag) && $UrlLooksValid
                                    ? "</a>" : ""));  ?>
                    <?PHP } ?>

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

            <td>
                <?PHP  if (isset($Screenshot)) {  ?>
                    <?PHP if ($Screenshot instanceof SPTImage) { ?>
                        <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 } else { print $Screenshot; } ?>
                <?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" style="line-height: 27px">
            <?PHP if (isset($UserRating) || isset($DisplayableResourceLink)) { ?>
                <?PHP if (isset($UserRating) && $RatingsEnabled) { PrintFastRating($Resource->Id(), $UserRating); } ?>
                <?PHP if (isset($DisplayableResourceLink)) { ?>
                    <?PHP if ($UrlLooksValid) { ?>
                        <a href="<?PHP  print($ResourceLink);  ?>"<?PHP if($G_SysConfig->ResourceLaunchesNewWindowEnabled()) { print " target=\"_blank\""; } ?>>
                    <?PHP } ?>
                    <?PHP print $DisplayableResourceLink; ?>
                    <?PHP if ($UrlLooksValid) { ?>
                        </a>
                    <?PHP } ?>
                <?PHP } ?>
            <?PHP } ?>
            </td>
        </tr>

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

    </tbody>
</table>

<?PHP } ?>
