<?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, $G_PluginManager;

    # 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 ($DescriptionField instanceof MetadataField
            && $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)
                {
                    $SafeTerm = preg_quote($Term, "/");
                    $Patterns[] = "/([^a-z]{1})(".$SafeTerm.")([^a-z]{1})/i";
                    $Replacements[] = "\\1<b>\\2</b>\\3";
                    $Patterns[] = "/^(".$SafeTerm.")([^a-z]{1})/i";
                    $Replacements[] = "<b>\\1</b>\\2";
                    $Patterns[] = "/([^a-z]{1})(".$SafeTerm.")$/i";
                    $Replacements[] = "\\1<b>\\2</b>";
                    $Patterns[] = "/^(".$SafeTerm.")$/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);

    # the URL of the current page with GET parameters
    $ReturnToString = urlencode("index.php?".http_build_query($_GET));
    $SafeReturnToString = defaulthtmlentities($ReturnToString);

    # whether or not the Folders plugin is enabled and if the user is on a page
    # belonging to the Folders plugin
    $FoldersEnabled = $G_PluginManager->PluginEnabled("Folders");
    $IsLoggedIn = $G_User->IsLoggedIn();
    $InFoldersPlugin = FALSE !== strpos(GetArrayValue($_GET, "P"), "P_Folders_");
    $DisplayFolderContent = $FoldersEnabled && $IsLoggedIn;

    if ($InFoldersPlugin)
    {
        global $Folders_Folder, $Folders_Previous, $Folders_Next;

        # these are retrieved from Folders/ViewFolder.html
        $Folder = $Folders_Folder;
        $Previous = $Folders_Previous;
        $Next = $Folders_Next;

        $SafeFolderId = defaulthtmlentities(urlencode($Folder->Id()));
        $SafeItemId = defaulthtmlentities(urlencode($Resource->Id()));
        $SafeResourceNote = defaulthtmlentities($Folder->NoteForItem($Resource->Id()));

        $HasPrevious = !is_null($Previous);
        $SafePreviousId = ($HasPrevious) ? defaulthtmlentities(urlencode($Previous->Id())) : NULL;

        $HasNext = !is_null($Next);
        $SafeNextId = ($HasNext) ? defaulthtmlentities(urlencode($Next->Id())) : NULL;
    }

    else if ($DisplayFolderContent)
    {
        $InFolder = $AF->SignalEvent(
            "FOLDERS_RESOURCE_IN_SELECTED_FOLDER",
            array($Resource, $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 if ($InFoldersPlugin) { ?>
                      <p class="folders-item-note" data-folderid="<?PHP print $SafeFolderId; ?>" data-itemid="<?PHP print $SafeItemId; ?>">
                        <span class="folders-item-notetext"><?PHP print nl2br($SafeResourceNote); ?></span>
                        <?PHP if ($SafeResourceNote) { ?><br /><?PHP } ?>
                        <a class="cw-button cw-button-constrained cw-button-iconed cw-button-elegant folders-editnote" href="index.php?P=P_Folders_ChangeResourceNote&amp;FolderId=<?PHP print $SafeFolderId; ?>&amp;ItemId=<?PHP print $SafeItemId; ?>&amp;ReturnTo=<?PHP print $SafeReturnToString; ?>">
                          <img class="cw-button-icon" src="<?PHP $AF->PUIFile("note_edit.png"); ?>" alt="" />
                          <?PHP if (!$SafeResourceNote) { ?>
                            Add
                          <?PHP } else { ?>
                            Edit
                          <?PHP } ?>
                          Note
                        </a>
                      </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-iconed cw-button-elegant" href="index.php?P=EditResource&amp;ID=<?PHP print $Resource->Id(); ?>">
                        <img class="cw-button-icon" src="<?PHP $AF->PUIFile("pencil.png"); ?>" alt="" />
                        Edit
                      </a>
                    </li>
                    <?PHP } ?>
                    <?PHP if ($DisplayFolderContent) { ?>
                      <?PHP if ($InFoldersPlugin) { ?>
                        <li>
                          <a class="cw-button cw-button-constrained cw-button-iconed cw-button-elegant folders-removeresource" href="index.php?P=P_Folders_RemoveItem&amp;FolderId=<?PHP print $SafeFolderId; ?>&amp;ItemId=<?PHP print $SafeItemId; ?>&amp;ReturnTo=<?PHP print $SafeReturnToString; ?>" title="Remove this resource from the list" data-parentfolderid="<?PHP print $SafeFolderId; ?>" data-itemid="<?PHP print $SafeItemId; ?>">
                            <img class="cw-button-icon" src="<?PHP $AF->PUIFile("cross.png"); ?>" alt="" />
                            Remove
                          </a>
                        </li>
                        <noscript>
                          <li>
                            <?PHP if ($HasPrevious) { ?>
                              <a class="cw-button cw-button-constrained cw-button-elegant" href="index.php?P=P_Folders_MoveItem&amp;FolderId=<?PHP print $SafeFolderId; ?>&amp;TargetItemId=<?PHP print $SafeItemId; ?>&amp;ItemId=<?PHP print $SafePreviousId; ?>&amp;ReturnTo=<?PHP print $SafeReturnToString; ?>" title="Move this resource up">
                                &uarr;
                              </a>
                            <?PHP } else { ?>
                              <span class="cw-button cw-button-constrained cw-button-active cw-button-elegant" title="This resource cannot be moved up because it is at the top of the list">&uarr;</span>
                            <?PHP } ?>
                            <?PHP if ($HasNext) { ?>
                              <a class="cw-button cw-button-constrained cw-button-elegant" href="index.php?P=P_Folders_MoveItem&amp;FolderId=<?PHP print $SafeFolderId; ?>&amp;TargetItemId=<?PHP print $SafeNextId; ?>&amp;ItemId=<?PHP print $SafeItemId; ?>&amp;ReturnTo=<?PHP print $SafeReturnToString; ?>" title="Move this resource down">
                                &darr;
                              </a>
                            <?PHP } else { ?>
                              <span class="cw-button cw-button-constrained cw-button-active cw-button-elegant" title="This resource cannot be moved down because it is at the bottom of the list">&darr;</span>
                            <?PHP } ?>
                          </li>
                        </noscript>
                      <?PHP } else { ?>
                        <?PHP if (!$InFolder) { ?>
                          <a class="cw-button cw-button-constrained cw-button-iconed cw-button-elegant" data-itemid="<?PHP print $Resource->Id(); ?>" href="index.php?P=P_Folders_AddItem&amp;ItemId=<?PHP print $Resource->Id(); ?>&amp;ReturnTo=<?PHP print $SafeReturnToString; ?>" title="Add this resource to the currently selected folder">
                            <img class="cw-button-icon" src="<?PHP $AF->PUIFile("folder_add.png"); ?>" alt="" />
                            Folder
                          </a>
                        <?PHP } ?>
                      <?PHP } ?>
                    <?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 class="cw-content-fullurl" 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 } ?>
