<?PHP

/**
* Display a resource field value.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
*/
function PrintResourceFieldValue(Resource $Resource, MetadataField $Field)
{
    # the value unmodified by any plugins
    $RawValue = $Resource->Get($Field, TRUE);

    # allow plugins to modify the value
    $SignalResult = $GLOBALS["AF"]->SignalEvent(
        "EVENT_FIELD_DISPLAY_FILTER", array(
            "Field" => $Field,
            "Resource" => $Resource,
            "Value" => $RawValue));
    $Value = $SignalResult["Value"];

    # get extra HTML to display if any
    $SignalResult = $GLOBALS["AF"]->SignalEvent(
        "EVENT_APPEND_HTML_TO_FIELD_DISPLAY",
        array(
            "Field" => $Field, "Resource" => $Resource,
            "Context" => "DISPLAY", "Html" => NULL));
    $ExtraHtml = $SignalResult["Html"];

    # just print the value in its own div if the field value can no longer be
    # reliably handled by the rest of the function. also print out any extra
    # HTML
    if (gettype($Value) != gettype($RawValue))
    {
        DisplayModifiedFieldValue($Resource, $Field, $Value);
        print $ExtraHtml;
        return;
    }

    # display each field type differently
    switch ($Field->Type())
    {
        case MetadataSchema::MDFTYPE_TEXT:
            # strip any threats from the field and use a div because the field
            # may contain HTML
            if ($Field->AllowHtml())
            {
                DisplayResourceFieldValueWithDiv(
                    $Resource,
                    $Field,
                    StripXSSThreats($Value));
            }

            # just escape the value and use a span otherwise
            else
            {
                DisplayResourceFieldValueWithSpan(
                    $Resource,
                    $Field,
                    defaulthtmlentities($Value));
            }
            break;

        case MetadataSchema::MDFTYPE_PARAGRAPH:
            # strip potential XSS threats from values that allow HTML and just
            # escape values from fields that don't
            $Html = $Field->AllowHtml()
                ? StripXSSThreats($Value) : defaulthtmlentities($Value);

            # convert newlines to line break elements if the WYSIWYG editor was
            # not used because the WYSIWYG editor is for full-blown HTML while
            # the field is just for casual HTML use when converting newlines to
            # breaks is expected
            if (!$Field->AllowHTML() || !$Field->UseWysiwygEditor())
            {
                $Html = nl2br($Html);
            }

            # display using a div tag if HTML is allowed
            if ($Field->AllowHtml())
            {
                DisplayResourceFieldValueWithDiv(
                    $Resource,
                    $Field,
                    $Html);
            }

            # otherwise, use a more semantic p element
            else
            {
                DisplayResourceFieldValueWithParagraph(
                    $Resource,
                    $Field,
                    $Html);
            }
            break;

        case MetadataSchema::MDFTYPE_NUMBER:
            DisplayResourceFieldValueWithSpan(
                $Resource,
                $Field,
                defaulthtmlentities($Value));
            break;

        case MetadataSchema::MDFTYPE_DATE:
            DisplayResourceFieldValueWithTime(
                $Resource,
                $Field,
                defaulthtmlentities($Value->Formatted()),
                $Value->PFormatted("Y-m-d H:i:s"));
            break;

        case MetadataSchema::MDFTYPE_TIMESTAMP:
            DisplayResourceFieldValueWithTime(
                $Resource,
                $Field,
                defaulthtmlentities($Value),
                date("Y-m-d H:i:s", strtotime($Value)));
            break;

        case MetadataSchema::MDFTYPE_FLAG:
            # convert the value to its corresponding label if it appears to not
            # have been modified
            if (is_numeric($Value) || is_bool($Value))
            {
                $Value = $Value ? $Field->FlagOnLabel() : $Field->FlagOffLabel();
            }

            DisplayResourceFieldValueWithSpan(
                $Resource,
                $Field,
                defaulthtmlentities($Value));
            break;

        case MetadataSchema::MDFTYPE_TREE:
            DisplayResourceFieldValueWithList(
                $Resource,
                $Field,
                $Value,
                "DisplayClassificationResourceFieldValue");
            break;

        case MetadataSchema::MDFTYPE_CONTROLLEDNAME:
        case MetadataSchema::MDFTYPE_OPTION:
            DisplayResourceFieldValueWithList(
                $Resource,
                $Field,
                $Value,
                "DisplayControlledNameResourceFieldValue");
            break;

        case MetadataSchema::MDFTYPE_USER:
            # convert the value to a user name
            $Value = is_null($Value->Get("UserId"))
                ? "--" : $Value->Get("UserName");

            DisplayResourceFieldValueWithSpan(
                $Resource,
                $Field,
                defaulthtmlentities($Value));
            break;

        case MetadataSchema::MDFTYPE_IMAGE:
            # the image is valid so display it as an image because an "empty"
            # img element is invalid HTML
            if ($Value instanceof SPTImage
                && $Value->PreviewUrl()
                && is_readable($Value->PreviewUrl()))
            {
                DisplayImageResourceFieldValue($Resource, $Field, $Value);
            }

            # the image is not valid, so print an empty span
            else
            {
                DisplayResourceFieldValueWithSpan($Resource, $Field, NULL);
            }
            break;

        case MetadataSchema::MDFTYPE_FILE:
            DisplayResourceFieldValueWithList(
                $Resource,
                $Field,
                $Value,
                "DisplayFileResourceFieldValue");
            break;

        case MetadataSchema::MDFTYPE_URL:
            DisplayUrlResourceFieldValue($Resource, $Field, $Value);
            break;

        case MetadataSchema::MDFTYPE_POINT:
            # convert the value to a string representation
            $Value = !is_null($Value["X"])
                ? $Value["X"].", ".$Value["Y"] : "";

            DisplayResourceFieldValueWithSpan(
                $Resource,
                $Field,
                defaulthtmlentities($Value));
            break;

        case MetadataSchema::MDFTYPE_REFERENCE:
            DisplayResourceFieldValueWithList(
                $Resource,
                $Field,
                $Value,
                "DisplayReferenceResourceFieldValue");
            break;
    }

    # print out any extra HTML
    print $ExtraHtml;
}

/**
* Display an inline field value using a span element. This function should only
* be used if a more appropriate element (semantically) isn't available.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Html HTML representation of the value.
*/
function DisplayResourceFieldValueWithSpan(
    Resource $Resource,
    MetadataField $Field,
    $Html)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Html);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
?>
  <span class="cw-field cw-field-value cw-field-inline cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
        data-schema_id="<?PHP print $SafeSchemaId; ?>"
        data-resource_id="<?PHP print $SafeResourceId; ?>"
        data-field_id="<?PHP print $SafeFieldId; ?>"
        ><?PHP print $Html; ?></span>
<?PHP
}

/**
* Display a block-level field value using a div element. This function should
* only be used if a more appropriate element (semantically) isn't available.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Html HTML representation of the value.
*/
function DisplayResourceFieldValueWithDiv(
    Resource $Resource,
    MetadataField $Field,
    $Html)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Html);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
?>
  <div class="cw-field cw-field-value cw-field-block cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
       data-schema_id="<?PHP print $SafeSchemaId; ?>"
       data-resource_id="<?PHP print $SafeResourceId; ?>"
       data-field_id="<?PHP print $SafeFieldId; ?>"
       ><?PHP print $Html; ?></div>
<?PHP
}

/**
* Display a block-level field value using a p element.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Html HTML representation of the value.
*/
function DisplayResourceFieldValueWithParagraph(
    Resource $Resource,
    MetadataField $Field,
    $Html)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Html);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
?>
  <p class="cw-field cw-field-value cw-field-paragraph cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     ><?PHP print $Html; ?></p>
<?PHP
}

/**
* Display an inline field value using a time element.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Html HTML representation of the value.
* @param string $Datetime Value for the datetime attribute.
*/
function DisplayResourceFieldValueWithTime(
    Resource $Resource,
    MetadataField $Field,
    $Html,
    $Datetime)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Html);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeDatetime = defaulthtmlentities($Datetime);
?>
  <time class="cw-field cw-field-value cw-field-datetime cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
        data-schema_id="<?PHP print $SafeSchemaId; ?>"
        data-resource_id="<?PHP print $SafeResourceId; ?>"
        data-field_id="<?PHP print $SafeFieldId; ?>"
        datetime="<?PHP print $SafeDatetime; ?>"
        ><?PHP print $Html; ?></time>
<?PHP
}

/**
* Display a resource field value inline with an a element.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Href The href attribute of the a element.
* @param mixed $Value The value for the inner HTML of the a element.
* @param callback $ValueCallack Optional callback executed using with the value
*      to get the value instead of using the value directly.
*/
function DisplayResourceFieldValueWithAnchor(
    Resource $Resource,
    MetadataField $Field,
    $Href,
    $ValueOrCallbackArgs,
    $ValueCallback=NULL)
{
    $UsesCallback = is_callable($ValueCallback);

    # get the value using the callback if given
    if ($UsesCallback)
    {
        ob_start();
        call_user_func_array($ValueCallback, $ValueOrCallbackArgs);
        $Value = ob_get_clean();
    }

    # just use the value directly otherwise
    else
    {
        $Value = $ValueOrCallbackArgs;
    }

    # determine if the value is empty
    $IsEmpty = !strlen($Value);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeFieldName = defaulthtmlentities($Field->Name());
    $SafeHref = defaulthtmlentities($Href);
    $SafeValueType = defaulthtmlentities(
        $UsesCallback ? "cw-field-container" : "cw-field-value");
?>
  <a class="cw-field <?PHP print $SafeValueType; ?> cw-field-anchor cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
     href="<?PHP print $SafeHref; ?>"
     ><?PHP print $Value; ?></a>
<?PHP
}

/**
* Display a field value that may have multiple values.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param array $Values The values to print.
* @param callback $ValueCallback The callback to execute for each item.
*/
function DisplayResourceFieldValueWithList(
    Resource $Resource,
    MetadataField $Field,
    array $Values,
    $ValueCallback)
{
    # determine if the list is empty
    $IsEmpty = !count($Values);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
?>
  <ul class="cw-field cw-field-container cw-field-list cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
      data-schema_id="<?PHP print $SafeSchemaId; ?>"
      data-resource_id="<?PHP print $SafeResourceId; ?>"
      data-field_id="<?PHP print $SafeFieldId; ?>">
    <?PHP foreach ($Values as $Value) { ?>
      <li><?PHP call_user_func($ValueCallback, $Resource, $Field, $Value); ?></li>
    <?PHP } ?>
  </ul>
<?PHP
}

/**
* Display a classification field value.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param Classification $Value The classification value to print.
*/
function DisplayClassificationResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    Classification $Value)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Value->Name());

    # try to get the qualifier for the field and classification
    $Qualifier = GetResourceFieldValueQualifier(
        $Resource,
        $Field,
        $Value->Id());

    $HasQualifier = FALSE;

    if (!is_null($Qualifier) && $Field->ShowQualifiers())
    {
        $HasQualifier = TRUE;
        $SafeQualifierUrl = defaulthtmlentities($Qualifier->Url());
        $SafeQualifierName = defaulthtmlentities($Qualifier->Name());
    }

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeFieldIdForUrl = defaulthtmlentities(urlencode($Field->Id()));
    $SafeIdForUrl = defaulthtmlentities(urlencode($Value->Id()));
    $SafeName = defaulthtmlentities($Value->Name());
?>
  <a class="cw-field cw-field-value cw-field-link cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     href="index.php?P=AdvancedSearch&amp;Q=Y&amp;G<?PHP print $SafeFieldIdForUrl; ?>=<?PHP print $SafeIdForUrl; ?>"
     title="Search for all resources also classified as &quot;<?PHP print $SafeName; ?>&quot;"
     ><?PHP print $SafeName; ?></a>
  <?PHP if ($HasQualifier) { ?>
    <a class="cw-field cw-field-qualifier cw-field-link cw-field-type-<?PHP print $SafeTypeForClass; ?>"
       href="<?PHP print $SafeQualifierUrl; ?>"
       ><small>(<?PHP print $SafeQualifierName; ?>)</small></a>
  <?PHP } ?>
<?PHP
}

/**
* Display a controlled name field value.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param ControlledName $Value The controlled name value to print.
*/
function DisplayControlledNameResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    ControlledName $Value)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Value->Name());

    # try to get the qualifier for the field and classification
    $Qualifier = GetResourceFieldValueQualifier(
        $Resource,
        $Field,
        $Value->Id());

    $HasQualifier = FALSE;

    if (!is_null($Qualifier) && $Field->ShowQualifiers())
    {
        $HasQualifier = TRUE;
        $SafeQualifierUrl = defaulthtmlentities($Qualifier->Url());
        $SafeQualifierName = defaulthtmlentities($Qualifier->Name());
    }

    # escape values that will be printed
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeFieldIdForUrl = defaulthtmlentities(urlencode($Field->Id()));
    $SafeIdForUrl = defaulthtmlentities(urlencode($Value->Id()));
    $SafeName = defaulthtmlentities($Value->Name());
?>
  <a class="cw-field cw-field-value cw-field-link cw-field-type-controlledname <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
     href="index.php?P=AdvancedSearch&amp;Q=Y&amp;G<?PHP print $SafeFieldIdForUrl; ?>=<?PHP print $SafeIdForUrl; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     title="Search for all resources also classified as &quot;<?PHP print $SafeName; ?>&quot;"
     ><?PHP print $SafeName; ?></a>
  <?PHP if ($HasQualifier) { ?>
    <a class="cw-field cw-field-qualifier cw-field-link cw-field-type-controlledname"
       href="<?PHP print $SafeQualifierUrl; ?>"
       ><small>(<?PHP print $SafeQualifierName; ?>)</small></a>
  <?PHP } ?>
<?PHP
}

/**
* Display the field value for an image field.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param SPTImage $Value The image value to print.
*/
function DisplayImageResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    SPTImage $Value)
{
    # escape values that will be printed
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeSrc = defaulthtmlentities($Value->PreviewUrl());
    $SafeAlt = defaulthtmlentities($Value->AltText());
    $SafeTitle = defaulthtmlentities($Value->AltText());
    $SafeResourceIdForHref = defaulthtmlentities(urlencode($Resource->Id()));
    $SafeFieldNameForHref = defaulthtmlentities(urlencode($Field->Name()));
?>
  <a class="cw-field cw-field-container cw-field-anchor cw-field-type-stillimage"
     href="index.php?P=FullImage&amp;ResourceId=<?PHP print $SafeResourceIdForHref; ?>&amp;FI=<?PHP print $Field->Id(); ?>&amp;ID=<?PHP  print $Value->Id();  ?>"
     ><img class="cw-field cw-field-value cw-field-image cw-field-type-stillimage"
           data-schema_id="<?PHP print $SafeSchemaId; ?>"
           data-resource_id="<?PHP print $SafeResourceId; ?>"
           data-field_id="<?PHP print $SafeFieldId; ?>"
           alt="<?PHP print $SafeAlt; ?>"
           title="<?PHP print $SafeTitle; ?>"
           src="<?PHP print $SafeSrc; ?>" /></a>
<?PHP
}

/**
* Display the field value for a file field.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param File $Value The file value to print.
*/
function DisplayFileResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    File $Value)
{
    # escape values that will be printed
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeHref = defaulthtmlentities($Value->GetLink());
    $SafeName = defaulthtmlentities($Value->Name());
?>
  <a class="cw-field cw-field-value cw-field-anchor cw-field-type-file"
     href="<?PHP print $SafeHref; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     title="Download &quot;<?PHP print $SafeName; ?>&quot;"
     ><?PHP print $SafeName; ?></a>
<?PHP
}

/**
* Display the field value for a file field.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Value The URL value to print.
*/
function DisplayUrlResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    $Value)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Value);

    # escape values that will be printed
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeResourceIdForUrl = defaulthtmlentities(urlencode($Resource->Id()));
    $SafeFieldIdForUrl = defaulthtmlentities(urlencode($Field->Id()));
    $SafeValue = defaulthtmlentities(NeatlyTruncateString($Value, 70, TRUE));
    $SafeTruncValue = defaulthtmlentities(NeatlyTruncateString($Value, 70, TRUE));
    $UseNewWindow = $GLOBALS["G_SysConfig"]->ResourceLaunchesNewWindowEnabled();
?>
  <a class="cw-field cw-field-value cw-field-anchor cw-field-type-url <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
     href="index.php?P=GoTo&amp;ID=<?PHP print $SafeResourceIdForUrl; ?>&amp;MF=<?PHP print $SafeFieldIdForUrl; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     title="Visit &quot;<?PHP print $SafeValue; ?>&quot;"
     <?PHP if ($UseNewWindow) print 'target="_blank"'; ?>
     ><?PHP print $SafeTruncValue; ?></a>
<?PHP
}

/**
* Display the field value for a reference field.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param Resource $Value The reference value to print.
*/
function DisplayReferenceResourceFieldValue(
    Resource $Resource,
    MetadataField $Field,
    Resource $Value)
{
    # escape values that will be printed
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
    $SafeValueIdForUrl = defaulthtmlentities(urlencode($Value->Id()));

    $Schema = new MetadataSchema($Value->SchemaId());
    $TitleField = NULL;

    # use the standard title field for default resources
    if ($Schema->Id() == MetadataSchema::SCHEMAID_DEFAULT)
    {
        $TitleField = $Schema->GetFieldByMappedName("Title");
    }

    # otherwise, try for a field named "Title"
    else if ($Schema->FieldExists("Title"))
    {
        $TitleField = $Schema->GetFieldByName("Title");
    }

    # finally, try for a field named "Name"
    else if ($Schema->FieldExists("Name"))
    {
        $TitleField = $Schema->GetFieldByName("Name");
    }

    # get the title and escape it as necessary based off of the field
    if (isset($TitleField))
    {
        $Title = $Value->Get($TitleField);
        $SafeTitle = $TitleField->AllowHTML()
            ? StripXSSThreats($Title) : defaulthtmlentities($Title);
    }

    # just use a generic title
    else
    {
        $Title = "Resource #".$Value->Id();
        $SafeTitle = defaulthtmlentities($Title);
    }
?>
  <a class="cw-field cw-field-value cw-field-anchor cw-field-type-reference"
     href="index.php?P=FullRecord&amp;ID=<?PHP print $SafeValueIdForUrl; ?>"
     data-schema_id="<?PHP print $SafeSchemaId; ?>"
     data-resource_id="<?PHP print $SafeResourceId; ?>"
     data-field_id="<?PHP print $SafeFieldId; ?>"
     title="View more information for &quot;<?PHP print $SafeTitle; ?>&quot;"
     ><?PHP print $SafeTitle; ?></a>
<?PHP
}

/**
* Display a field value modified by a plugin.
* @param Resource $Resource Resource for which to print a field value.
* @param MetadataField $Field Metadata field for which to print the value.
* @param string $Html HTML representation of the value.
*/
function DisplayModifiedFieldValue(Resource $Resource, MetadataField $Field, $Html)
{
    # determine if the value is empty
    $IsEmpty = !strlen($Html);

    # escape values that will be printed
    $SafeTypeForClass = defaulthtmlentities(strtolower($Field->TypeAsName()));
    $SafeSchemaId = defaulthtmlentities($Resource->SchemaId());
    $SafeResourceId = defaulthtmlentities($Resource->Id());
    $SafeFieldId = defaulthtmlentities($Field->Id());
?>
  <div class="cw-field cw-field-value cw-field-modified cw-field-type-<?PHP print $SafeTypeForClass; ?> <?PHP if ($IsEmpty) print "cw-field-empty"; ?>"
       data-schema_id="<?PHP print $SafeSchemaId; ?>"
       data-resource_id="<?PHP print $SafeResourceId; ?>"
       data-field_id="<?PHP print $SafeFieldId; ?>"
       ><?PHP print $Html; ?></div>
<?PHP
}

/**
* Get the qualifier of a metadata field for a resource.
* @param Resource $Resource Resource object.
* @param MetadataField $Field MetadataField object.
* @param int $Id ID used for a specific value if the field value has multiple.
* @return Returns a Qualifier object or NULL if a qualifier is not set.
*/
function GetResourceFieldValueQualifier(Resource $Resource, MetadataField $Field, $Id=NULL)
{
    if (!$Field->UsesQualifiers())
    {
        return NULL;
    }

    $Qualifier = $Resource->GetQualifierByField($Field, TRUE);

    # if the field allows multiple values, get the one for a specific value of
    # the group if it's set and not null
    if (!is_null($Id) && is_array($Qualifier) && isset($Id, $Qualifier))
    {
        $Qualifier = $Qualifier[$Id];
    }

    # an invalid qualifier
    if (!($Qualifier instanceof Qualifier)
        || $Qualifier->Status() !== Qualifier::STATUS_OK)
    {
        return NULL;
    }

    return $Qualifier;
}
