drupal/core/modules/rdf/rdf.module

637 lines
25 KiB
Plaintext

<?php
/**
* @file
* Enables semantically enriched output for Drupal sites in the form of RDFa.
*/
use Drupal\Component\Utility\NestedArray;
use Drupal\Core\Template\Attribute;
/**
* Implements hook_help().
*/
function rdf_help($path, $arg) {
switch ($path) {
case 'admin/help#rdf':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('The RDF module enriches your content with metadata to let other applications (e.g., search engines, aggregators, and so on) better understand its relationships and attributes. This semantically enriched, machine-readable output for Drupal sites uses the <a href="@rdfa">RDFa specification</a> which allows RDF data to be embedded in HTML markup. Other modules can define mappings of their data to RDF terms, and the RDF module makes this RDF data available to the theme. The core Drupal modules define RDF mappings for their data model, and the core Drupal themes output this RDF metadata information along with the human-readable visual information. For more information, see the online handbook entry for <a href="@rdf">RDF module</a>.', array('@rdfa' => 'http://www.w3.org/TR/xhtml-rdfa-primer/', '@rdf' => 'http://drupal.org/documentation/modules/rdf')) . '</p>';
return $output;
}
}
/**
* @defgroup rdf RDF Mapping API
* @{
* Functions to describe entities and bundles in RDF.
*
* The RDF module introduces RDF and RDFa to Drupal. RDF is a W3C standard to
* describe structured data. RDF can be serialized as RDFa in XHTML attributes
* to augment visual data with machine-readable hints.
* @see http://www.w3.org/RDF/
* @see http://www.w3.org/TR/xhtml-rdfa-primer/
*
* Modules can provide mappings of their bundles' data and metadata to RDF
* classes and properties. This module takes care of injecting these mappings
* into variables available to theme functions and templates. All Drupal core
* themes are coded to be RDFa compatible.
*/
/**
* Returns the RDF mapping object associated to a bundle.
*
* The function reads the rdf_mapping object from the current configuration,
* or returns a ready-to-use empty one if no configuration entry exists yet for
* this bundle. This streamlines the manipulation of mapping objects by always
* returning a consistent object that reflects the current state of the
* configuration.
*
* Example usage:
* -Map the 'article' bundle to 'sioc:Post' and the 'title' field to 'dc:title'.
* @code
* rdf_get_mapping('node', 'article')
* ->setBundleMapping(array(
* 'types' => array('sioc:Post'),
* ))
* ->setFieldMapping('title', array(
* 'properties' => array('dc:title')
* ))
* ->save();
* @endcode
*
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle.
*
* @return \Drupal\rdf\Plugin\Core\Entity\RdfMapping
* The RdfMapping object.
*/
function rdf_get_mapping($entity_type, $bundle) {
// Try loading the mapping from configuration.
$mapping = entity_load('rdf_mapping', $entity_type . '.' . $bundle);
// If not found, create a fresh mapping object.
if (!$mapping) {
$mapping = entity_create('rdf_mapping', array(
'targetEntityType' => $entity_type,
'bundle' => $bundle,
));
}
return $mapping;
}
/**
* Implements hook_rdf_namespaces().
*/
function rdf_rdf_namespaces() {
return array(
'content' => 'http://purl.org/rss/1.0/modules/content/',
'dc' => 'http://purl.org/dc/terms/',
'foaf' => 'http://xmlns.com/foaf/0.1/',
'og' => 'http://ogp.me/ns#',
'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
'schema' => 'http://schema.org/',
'sioc' => 'http://rdfs.org/sioc/ns#',
'sioct' => 'http://rdfs.org/sioc/types#',
'skos' => 'http://www.w3.org/2004/02/skos/core#',
'xsd' => 'http://www.w3.org/2001/XMLSchema#',
);
}
/**
* Retrieves RDF namespaces.
*
* Invokes hook_rdf_namespaces() and collects RDF namespaces from modules that
* implement it.
*/
function rdf_get_namespaces() {
$namespaces = array();
// In order to resolve duplicate namespaces by using the earliest defined
// namespace, do not use module_invoke_all().
foreach (module_implements('rdf_namespaces') as $module) {
$function = $module . '_rdf_namespaces';
if (function_exists($function)) {
$namespaces = NestedArray::mergeDeep($function(), $namespaces);
}
}
return $namespaces;
}
/**
* @} End of "defgroup rdf".
*/
/**
* @addtogroup rdf
* @{
*/
/**
* Builds an array of RDFa attributes for a given mapping.
*
* This array will typically be passed through Drupal\Core\Template\Attribute
* to create the attributes variables that are available to template files.
* These include $attributes, $title_attributes, $content_attributes and the
* field-specific $item_attributes variables.
*
* @param array $mapping
* An array containing a mandatory 'properties' key and optional 'datatype',
* 'datatype_callback' and 'type' keys. For example:
* @code
* array(
* 'properties' => array('dc:created'),
* 'datatype' => 'xsd:dateTime',
* 'datatype_callback' => 'date_iso8601',
* ),
* );
* @endcode
* @param mixed $data
* (optional) A value that needs to be converted by the provided callback
* function.
*
* @return array
* RDFa attributes suitable for Drupal\Core\Template\Attribute.
*/
function rdf_rdfa_attributes($mapping, $data = NULL) {
$attributes = array();
// The type of mapping defaults to 'property'.
$type = isset($mapping['mapping_type']) ? $mapping['mapping_type'] : 'property';
switch ($type) {
// The mapping expresses the relationship between two resources.
case 'rel':
case 'rev':
$attributes[$type] = $mapping['properties'];
break;
// The mapping expresses the relationship between a resource and some
// literal text.
case 'property':
if (!empty($mapping['properties'])) {
$attributes['property'] = $mapping['properties'];
// Convert $data to a specific format as per the callback function.
if (isset($data) && !empty($mapping['datatype_callback'])) {
$callback = $mapping['datatype_callback'];
$attributes['content'] = call_user_func($callback, $data);
}
if (isset($mapping['datatype'])) {
$attributes['datatype'] = $mapping['datatype'];
}
break;
}
}
return $attributes;
}
/**
* @} End of "addtogroup rdf".
*/
/**
* Implements hook_comment_load().
*/
function rdf_comment_load($comments) {
foreach ($comments as $comment) {
// Pages with many comments can show poor performance. This information
// isn't needed until rdf_preprocess_comment() is called, but set it here
// to optimize performance for websites that implement an entity cache.
$created_mapping = rdf_get_mapping('comment', $comment->bundle())
->getPreparedFieldMapping('created');
$comment->rdf_data['date'] = rdf_rdfa_attributes($created_mapping, $comment->created->value);
$comment->rdf_data['nid_uri'] = url('node/' . $comment->nid->target_id);
if ($comment->pid->target_id) {
$comment->rdf_data['pid_uri'] = url('comment/' . $comment->pid->target_id);
}
}
}
/**
* Implements hook_theme().
*/
function rdf_theme() {
return array(
'rdf_metadata' => array(
'variables' => array('metadata' => array()),
),
);
}
/**
* Implements hook_preprocess_HOOK() for html.tpl.php.
*/
function rdf_preprocess_html(&$variables) {
// Adds RDF namespace prefix bindings in the form of an RDFa 1.1 prefix
// attribute inside the html element.
$prefixes = array();
if (!isset($variables['html_attributes']['prefix'])) {
$variables['html_attributes']['prefix'] = array();
}
foreach(rdf_get_namespaces() as $prefix => $uri) {
$variables['html_attributes']['prefix'][] = $prefix . ': ' . $uri . "\n";
}
}
/**
* Implements hook_preprocess_HOOK() for node.html.twig.
*/
function rdf_preprocess_node(&$variables) {
// Adds RDFa markup to the node container. The about attribute specifies the
// URI of the resource described within the HTML element, while the @typeof
// attribute indicates its RDF type (e.g., foaf:Document, sioc:Person, and so
// on.)
$bundle = $variables['node']->bundle();
$mapping = rdf_get_mapping('node', $bundle);
$bundle_mapping = $mapping->getPreparedBundleMapping('node', $bundle);
$variables['attributes']['about'] = empty($variables['node_url']) ? NULL: $variables['node_url'];
$variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
// Adds RDFa markup to the title of the node. Because the RDFa markup is
// added to the <h2> tag which might contain HTML code, we specify an empty
// datatype to ensure the value of the title read by the RDFa parsers is a
// literal.
$title_mapping = $mapping->getPreparedFieldMapping('title');
$variables['title_attributes']['property'] = empty($title_mapping['properties']) ? NULL : $title_mapping['properties'];
$variables['title_attributes']['datatype'] = '';
// In full node mode, the title is not displayed by node.html.twig so it is
// added in the <head> tag of the HTML page.
if ($variables['page']) {
$element = array(
'#tag' => 'meta',
'#attributes' => array(
'content' => $variables['label'],
'about' => $variables['node_url'],
),
);
if (!empty($title_mapping['properties'])) {
$element['#attributes']['property'] = $title_mapping['properties'];
}
drupal_add_html_head($element, 'rdf_node_title');
}
// Adds RDFa markup for the relation between the node and its author.
$author_mapping = $mapping->getPreparedFieldMapping('uid');
if (!empty($author_mapping['properties']) && $variables['submitted']) {
$author_attributes = array('rel' => $author_mapping['properties']);
$variables['submitted'] = '<span ' . new Attribute($author_attributes) . '>' . $variables['submitted'] . '</span>';
}
// Adds RDFa markup for the date.
$created_mapping = $mapping->getPreparedFieldMapping('created');
if (!empty($created_mapping) && $variables['submitted']) {
$date_attributes = rdf_rdfa_attributes($created_mapping, $variables['node']->created);
$rdf_metadata = array(
'#theme' => 'rdf_metadata',
'#metadata' => array($date_attributes),
);
$variables['submitted'] .= drupal_render($rdf_metadata);
}
// Adds RDFa markup annotating the number of comments a node has.
$comment_count_mapping = $mapping->getPreparedFieldMapping('comment_count');
if (isset($variables['node']->comment_count) && !empty($comment_count_mapping['properties'])) {
// Annotates the 'x comments' link in teaser view.
if (isset($variables['content']['links']['comment']['#links']['comment-comments'])) {
$comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']->comment_count);
// According to RDFa parsing rule number 4, a new subject URI is created
// from the href attribute if no rel/rev attribute is present. To get the
// original node URL from the about attribute of the parent container we
// set an empty rel attribute which triggers rule number 5. See
// http://www.w3.org/TR/rdfa-syntax/#sec_5.5.
$comment_count_attributes['rel'] = '';
$variables['content']['links']['comment']['#links']['comment-comments']['attributes'] += $comment_count_attributes;
}
// In full node view, the number of comments is not displayed by
// node.html.twig so it is expressed in RDFa in the <head> tag of the HTML
// page.
if ($variables['page'] && user_access('access comments')) {
$element = array(
'#tag' => 'meta',
'#attributes' => array(
'about' => $variables['node_url'],
'property' => $comment_count_mapping['properties'],
'content' => $variables['node']->comment_count,
'datatype' => $comment_count_mapping['datatype'],
),
);
drupal_add_html_head($element, 'rdf_node_comment_count');
}
}
}
/**
* Implements hook_preprocess_HOOK() for field.tpl.php.
*/
function rdf_preprocess_field(&$variables) {
$element = $variables['element'];
$entity_type = $element['#entity_type'];
$bundle = $element['#bundle'];
$field_name = $element['#field_name'];
$field_mapping = rdf_get_mapping($entity_type, $bundle)
->getPreparedFieldMapping($field_name);
if (!empty($field_mapping)) {
foreach ($element['#items'] as $delta => $item) {
$variables['item_attributes'][$delta] = rdf_rdfa_attributes($field_mapping, $item);
// If this field is an image, RDFa will not output correctly when the
// image is in a containing <a> tag. If the field is a file, RDFa will
// not output correctly if the filetype icon comes before the link to the
// file. We correct this by adding a resource attribute to the div if
// this field has a URI.
if (isset($item['entity']->uri)) {
if (!empty($element[$delta]['#image_style'])) {
$variables['item_attributes'][$delta]['resource'] = image_style_url($element[$delta]['#image_style'], $item['entity']->getFileUri());
}
else {
$variables['item_attributes'][$delta]['resource'] = file_create_url($item['entity']->getFileUri());
}
}
}
}
}
/**
* Implements hook_preprocess_HOOK() for user.tpl.php.
*/
function rdf_preprocess_user(&$variables) {
$account = $variables['elements']['#user'];
$uri = $account->uri();
$mapping = rdf_get_mapping('user', 'user');
$bundle_mapping = $mapping->getPreparedBundleMapping();
// Adds RDFa markup to the user profile page. Fields displayed in this page
// will automatically describe the user.
if (!empty($bundle_mapping['types'])) {
$variables['attributes']['typeof'] = $bundle_mapping['types'];
$variables['attributes']['about'] = url($uri['path'], $uri['options']);
}
// If we are on the user account page, add the relationship between the
// sioc:UserAccount and the foaf:Person who holds the account.
if (current_path() == $uri['path']) {
// Adds the markup for username as language neutral literal, see
// rdf_preprocess_username().
$name_mapping = $mapping->getPreparedFieldMapping('name');
if (!empty($name_mapping['properties'])) {
$username_meta = array(
'#tag' => 'meta',
'#attributes' => array(
'about' => url($uri['path'], $uri['options']),
'property' => $name_mapping['properties'],
'content' => $account->name,
'lang' => '',
),
);
drupal_add_html_head($username_meta, 'rdf_user_username');
}
}
}
/**
* Implements hook_preprocess_HOOK() for theme_username().
*/
function rdf_preprocess_username(&$variables) {
$attributes = array();
// Because lang is set on the HTML element that wraps the page, the
// username inherits this language attribute. However, since the username
// might not be transliterated to the same language that the content is in,
// we do not want it to inherit the language attribute, so we set the
// attribute to an empty string.
if (empty($variables['attributes']['lang'])) {
$attributes['lang'] = '';
}
// The profile URI is used to identify the user account. The about attribute
// is used to set the URI as the default subject of the properties embedded
// as RDFa in the child elements. Even if the user profile is not accessible
// to the current user, we use its URI in order to identify the user in RDF.
// We do not use this attribute for the anonymous user because we do not have
// a user profile URI for it (only a homepage which cannot be used as user
// profile in RDF.)
if ($variables['uid'] > 0) {
$attributes['about'] = url('user/' . $variables['uid']);
}
// Add RDF type of user.
$mapping = rdf_get_mapping('user', 'user');
$bundle_mapping = $mapping->getPreparedBundleMapping();
if (!empty($bundle_mapping['types'])) {
$attributes['typeof'] = $bundle_mapping['types'];
}
// Annotate the username in RDFa. A property attribute is used with an empty
// datatype attribute to ensure the username is parsed as a plain literal
// in RDFa 1.0 and 1.1.
$name_mapping = $mapping->getPreparedFieldMapping('name');
if (!empty($name_mapping)) {
$attributes['property'] = $name_mapping['properties'];
$attributes['datatype'] = '';
}
// Add the homepage RDFa markup if present.
$homepage_mapping = $mapping->getPreparedFieldMapping('homepage');
if (!empty($variables['homepage']) && !empty($homepage_mapping)) {
$attributes['rel'] = $homepage_mapping['properties'];
}
// The remaining attributes can have multiple values listed, with whitespace
// separating the values in the RDFa attributes
// (see http://www.w3.org/TR/rdfa-syntax/#rdfa-attributes).
// Therefore, merge rather than override so as not to clobber values set by
// earlier preprocess functions. These attributes will be placed in the a
// element if a link is rendered, or on a span element otherwise.
if (isset($variables['link_path'])) {
$variables['link_options']['attributes'] = array_merge_recursive($variables['link_options']['attributes'], $attributes);
}
else {
$variables['attributes'] = array_merge_recursive($variables['attributes'], $attributes);
}
}
/**
* Implements hook_preprocess_HOOK() for comment.html.twig.
*/
function rdf_preprocess_comment(&$variables) {
$comment = $variables['comment'];
$mapping = rdf_get_mapping('comment', $comment->bundle());
$bundle_mapping = $mapping->getPreparedBundleMapping();
if (!empty($bundle_mapping['types'])) {
// Adds RDFa markup to the comment container. The about attribute specifies
// the URI of the resource described within the HTML element, while the
// typeof attribute indicates its RDF type (e.g., sioc:Post, foaf:Document,
// and so on.)
$uri = $comment->uri();
$variables['attributes']['about'] = url($uri['path'], $uri['options']);
$variables['attributes']['typeof'] = $bundle_mapping['types'];
}
// Adds RDFa markup for the relation between the comment and its author.
$author_mapping = $mapping->getPreparedFieldMapping('uid');
if (!empty($author_mapping)) {
$author_attributes = array('rel' => $author_mapping['properties']);
// Wraps the author variable and the submitted variable which are both
// available in comment.html.twig.
$variables['author'] = '<span ' . new Attribute($author_attributes) . '>' . $variables['author'] . '</span>';
$variables['submitted'] = '<span ' . new Attribute($author_attributes) . '>' . $variables['submitted'] . '</span>';
}
// Adds RDFa markup for the date of the comment.
$created_mapping = $mapping->getPreparedFieldMapping('created');
if (!empty($created_mapping)) {
// The comment date is precomputed as part of the rdf_data so that it can be
// cached as part of the entity.
$date_attributes = $comment->rdf_data['date'];
$rdf_metadata = array(
'#theme' => 'rdf_metadata',
'#metadata' => array($date_attributes),
);
$created_metadata_markup = drupal_render($rdf_metadata);
// Appends the markup to the created variable and the submitted variable
// which are both available in comment.html.twig.
$variables['created'] .= $created_metadata_markup;
$variables['submitted'] .= $created_metadata_markup;
}
$title_mapping = $mapping->getPreparedFieldMapping('subject');
if (!empty($title_mapping)) {
// Adds RDFa markup to the subject of the comment. Because the RDFa markup
// is added to an <h3> tag which might contain HTML code, we specify an
// empty datatype to ensure the value of the title read by the RDFa parsers
// is a literal.
$variables['title_attributes']['property'] = $title_mapping['properties'];
$variables['title_attributes']['datatype'] = '';
}
// Annotates the parent relationship between the current comment and the node
// it belongs to. If available, the parent comment is also annotated.
// @todo When comments are turned into fields, this should be changed.
// Currently there is no mapping relating a comment to its node.
$pid_mapping = $mapping->getPreparedFieldMapping('pid');
if (!empty($pid_mapping)) {
// Adds the relation to the parent node.
$parent_node_attributes['rel'] = $pid_mapping['properties'];
// The parent node URI is precomputed as part of the rdf_data so that it can
// be cached as part of the entity.
$parent_node_attributes['resource'] = $comment->rdf_data['nid_uri'];
$variables['rdf_metadata_attributes'][] = $parent_node_attributes;
// Adds the relation to parent comment, if it exists.
if ($comment->pid->target_id != 0) {
$parent_comment_attributes['rel'] = $pid_mapping['properties'];
// The parent comment URI is precomputed as part of the rdf_data so that
// it can be cached as part of the entity.
$parent_comment_attributes['resource'] = $comment->rdf_data['pid_uri'];
$variables['rdf_metadata_attributes'][] = $parent_comment_attributes;
}
}
// Adds RDF metadata markup above comment body.
if (!empty($variables['rdf_metadata_attributes'])) {
if (!isset($variables['content']['comment_body']['#prefix'])) {
$variables['content']['comment_body']['#prefix'] = '';
}
$rdf_metadata = array(
'#theme' => 'rdf_metadata',
'#metadata' => $variables['rdf_metadata_attributes'],
);
$variables['content']['comment_body']['#prefix'] = drupal_render($rdf_metadata) . $variables['content']['comment_body']['#prefix'];
}
}
/**
* Implements hook_preprocess_HOOK() for taxonomy-term.tpl.php.
*/
function rdf_preprocess_taxonomy_term(&$variables) {
$term = $variables['term'];
$mapping = rdf_get_mapping('taxonomy_term', $term->bundle());
$bundle_mapping = $mapping->getPreparedBundleMapping();
$name_field_mapping = $mapping->getPreparedFieldMapping('name');
// Adds the RDF type of the term and the term name in a <meta> tag.
$term_label_meta = array(
'#tag' => 'meta',
'#attributes' => array(
'about' => url('taxonomy/term/' . $term->id()),
'typeof' => $bundle_mapping['types'],
'property' => $name_field_mapping['properties'],
'content' => $term->label(),
),
);
drupal_add_html_head($term_label_meta, 'rdf_term_label');
}
/**
* Implements hook_field_attach_view_alter().
*/
function rdf_field_attach_view_alter(&$output, $context) {
// Append term mappings on displayed taxonomy links.
foreach (element_children($output) as $field_name) {
$element = &$output[$field_name];
if ($element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'taxonomy_term_reference_link') {
foreach ($element['#items'] as $delta => $item) {
// This function is invoked during entity preview when taxonomy term
// reference items might contain free-tagging terms that do not exist
// yet and thus have no $item['entity'].
if (isset($item['entity'])) {
$term = $item['entity'];
$mapping = rdf_get_mapping('taxonomy_term', $term->bundle());
$bundle_mapping = $mapping->getPreparedBundleMapping();
if (!empty($bundle_mapping['types'])) {
$element[$delta]['#options']['attributes']['typeof'] = $bundle_mapping['types'];
}
$name_field_mapping = $mapping->getPreparedFieldMapping('name');
if (!empty($name_field_mapping['properties'])) {
// A property attribute is used with an empty datatype attribute so
// the term name is parsed as a plain literal in RDFa 1.0 and 1.1.
$element[$delta]['#options']['attributes']['property'] = $name_field_mapping['properties'];
$element[$delta]['#options']['attributes']['datatype'] = '';
}
}
}
}
}
}
/**
* Implements hook_preprocess_HOOK() for theme_image().
*/
function rdf_preprocess_image(&$variables) {
// Adds the RDF type for image. We cannot use the usual entity-based mapping
// to get 'foaf:Image' because image does not have its own entity type or
// bundle.
$variables['attributes']['typeof'] = array('foaf:Image');
}
/**
* Returns HTML for a series of empty spans for exporting RDF metadata in RDFa.
*
* Sometimes it is useful to export data which is not semantically present in
* the HTML output. For example, a hierarchy of comments is visible for a human
* but not for machines because this hiearchy is not present in the DOM tree.
* We can express it in RDFa via empty <span> tags. These aren't visible and
* give machines extra information about the content and its structure.
*
* @param $variables
* An associative array containing:
* - metadata: An array of attribute arrays. Each item in the array
* corresponds to its own set of attributes, and therefore, needs its own
* element.
*
* @see rdf_process()
* @ingroup themeable
* @ingroup rdf
*/
function theme_rdf_metadata($variables) {
$output = '';
foreach ($variables['metadata'] as $attributes) {
// Add a class so that developers viewing the HTML source can see why there
// are empty <span> tags in the document. The class can also be used to set
// a CSS display:none rule in a theme where empty spans affect display.
$attributes['class'][] = 'rdf-meta';
// The XHTML+RDFa doctype allows either <span></span> or <span /> syntax to
// be used, but for maximum browser compatibility, W3C recommends the
// former when serving pages using the text/html media type, see
// http://www.w3.org/TR/xhtml1/#C_3.
$output .= '<span' . new Attribute($attributes) . '></span>';
}
return $output;
}