<?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 = NULL, $AppendedRows = NULL,
    $DisplayDescription = TRUE, $DisplayExportCheckbox = FALSE,
    $TermsToHighlight = NULL, $FullRecordLink = NULL,
    $PrintResourceTypeTag = FALSE, $Context = array())
{
    #----- CONFIGURATION ----------------------------------------------

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


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

    global $AF, $G_SysConfig, $G_User, $G_PluginManager;

    # determine if the resource is editble by the current user
    if ($EditOkay === NULL)
    {
        $EditOkay = $Resource->UserCanEdit($G_User);
    }

    # retrieve and format title
    $Schema = new MetadataSchema($Resource->SchemaId());
    $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 ($FileField !== NULL)
    {
        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")."\""
                .($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
    if ($FullRecordLink === NULL)
    {
        $FullRecordLink = htmlspecialchars(
                preg_replace('%\$ID%', $Resource->Id(), $Schema->ViewPage()));
    }
    $FullRecordLinkTag = "<a href=\"".$FullRecordLink."\""
            ." title=\"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) || !count($Screenshot))
        {
            unset($Screenshot);
        }
        else
        {
            $Screenshot = array_shift($Screenshot);
            if (!($Screenshot instanceof SPTImage))
            {
                unset($Screenshot);
            }
            else
            {
                $ScreenshotThumbnailUrl = $Screenshot->ThumbnailUrl();
            }
        }
    }

    # retrieve and format resource rating
    $RatingsEnabled = FALSE;
    if ($Schema->FieldExists("Cumulative Rating"))
    {
        $RatingField = $Schema->GetFieldByName("Cumulative Rating");
        $RatingsEnabled = $G_SysConfig->ResourceRatingsEnabled();
        $RatingsEnabled = $RatingsEnabled
                && $Resource->UserCanViewField($G_User, $RatingField);
        if ($RatingsEnabled)
        {
            $SignalResult = $GLOBALS["AF"]->SignalEvent(
                "EVENT_RESOURCE_SHOW_RATING",
                array(
                    "Resource" => $Resource,
                    "Rating" => $Resource->Get($RatingField),
                    "ShowRating" => TRUE));
            $RatingsEnabled = $SignalResult["ShowRating"];

            $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;  }
    }

    # the URL of the current page with GET parameters
    $ReturnToString = urlencode($GLOBALS["AF"]->GetCleanUrl());
    $SafeReturnToString = defaulthtmlentities($ReturnToString);

    # get the schema name associated with this resource
    $SchemaCSSName = "cw-resourcesummary-resourcetype-tag-" .
            str_replace(array(" ", "/"), '', strtolower($Schema->Name()));
    $SchemaItemName = $Schema->ResourceName();

    # insert current resource id and resource to the context
    $Context["ResourceId"] = $Resource->Id();
    $Context["Resource"] = $Resource;

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

    /*
    * At this point these values should be available:
    *   $FullRecordLink - link to full record page
    *   $FullRecordLinkTag - complete <a> tag for full record page (includes alt
    *           attribute text)
    *   $Resource - Resource object
    *   $SchemaItemName - name of the type of item described by the current schema
    *   $SchemaCSSName - CSS class associated with type of item described by the
    *           current schema
    *
    * 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>
            </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 if ($PrintResourceTypeTag) { ?>
                            <span class="<?PHP print($SchemaCSSName); ?> cw-resourcesummary-resourcetype-tag"><?PHP print($SchemaItemName); ?></span>
                        <?PHP } ?>
                    <?PHP } ?>

                    <?PHP if (isset($Description)) { ?>
                    <p><?PHP print $Description; ?></p>
                    <?PHP } ?>
                    <?PHP
                        $GLOBALS["AF"]->SignalEvent("EVENT_HTML_INSERTION_POINT",
                            array($GLOBALS["AF"]->GetPageName(), "After Resource Description", $Context));
                    ?>
                <?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;FI=<?PHP print $ScreenshotField->Id(); ?>&amp;ID=<?PHP print $Screenshot->Id() ?>">
                            <img height="<?PHP print $Screenshot->ThumbnailHeight(); ?>" width="<?PHP print $Screenshot->ThumbnailWidth(); ?>" src="<?PHP print $ScreenshotThumbnailUrl; ?>" 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); ?>" class="cw-rating-graphic" /></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
                        $GLOBALS["AF"]->SignalEvent("EVENT_HTML_INSERTION_POINT",
                            array($GLOBALS["AF"]->GetPageName(), "Resource Summary Buttons", $Context));
                    ?>
                </ul>
            </td>
        </tr>

        <tr>
            <td></td>
            <td colspan="3" class="cw-rating-container">
            <?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 } ?>
