rdf.module in Drupal 10
Same filename and directory in other branches
Enables semantically enriched output for Drupal sites in the form of RDFa.
File
core/modules/rdf/rdf.moduleView source
<?php
/**
* @file
* Enables semantically enriched output for Drupal sites in the form of RDFa.
*/
use Drupal\Core\Url;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Template\Attribute;
use Drupal\rdf\Entity\RdfMapping;
/**
* Implements hook_help().
*/
function rdf_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.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 your website 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 modules define RDF mappings for their data model, and the core themes output this RDF metadata information along with the human-readable visual information. For more information, see the <a href=":rdf">online documentation for the RDF module</a>.', [
':rdfa' => 'http://www.w3.org/TR/xhtml-rdfa-primer/',
':rdf' => 'https://www.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 with 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\Entity\RdfMapping
* The RdfMapping object.
*/
function rdf_get_mapping($entity_type, $bundle) {
// Try loading the mapping from configuration.
$mapping = RdfMapping::load($entity_type . '.' . $bundle);
// If not found, create a fresh mapping object.
if (!$mapping) {
$mapping = RdfMapping::create([
'targetEntityType' => $entity_type,
'bundle' => $bundle,
]);
}
return $mapping;
}
/**
* Implements hook_rdf_namespaces().
*/
function rdf_rdf_namespaces() {
return [
'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 = [];
// In order to resolve duplicate namespaces by using the earliest defined
// namespace, do not use \Drupal::moduleHandler()->invokeAll().
\Drupal::moduleHandler()
->invokeAllWith('rdf_namespaces', function (callable $hook, string $module) use (&$namespaces) {
$namespacesFromHook = $hook();
foreach ($namespacesFromHook as $prefix => $namespace) {
if (array_key_exists($prefix, $namespaces) && $namespace !== $namespaces[$prefix]) {
throw new Exception("Tried to map '{$prefix}' to '{$namespace}', but '{$prefix}' is already mapped to '{$namespaces[$prefix]}'.");
}
else {
$namespaces[$prefix] = $namespace;
}
}
});
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('schema:interactionCount'),
* 'datatype' => 'xsd:integer',
* 'datatype_callback' => array(
* 'callable' => 'Drupal\rdf\SchemaOrgDataConverter::interactionCount',
* 'arguments' => array(
* 'interaction_type' => 'UserComments'
* ),
* ),
* );
* @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 = [];
// The type of mapping defaults to 'property'.
$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']['callable'];
$arguments = $mapping['datatype_callback']['arguments'] ?? NULL;
$attributes['content'] = call_user_func($callback, $data, $arguments);
}
if (isset($mapping['datatype'])) {
$attributes['datatype'] = $mapping['datatype'];
}
break;
}
}
return $attributes;
}
/**
* @} End of "addtogroup rdf".
*/
/**
* Implements hook_entity_prepare_view().
*/
function rdf_entity_prepare_view($entity_type, array $entities, array $displays) {
// Iterate over the RDF mappings for each entity and prepare the RDFa
// attributes to be added inside field formatters.
foreach ($entities as $entity) {
$mapping = rdf_get_mapping($entity_type, $entity
->bundle());
// Only prepare the RDFa attributes for the fields which are configured to
// be displayed.
foreach ($displays[$entity
->bundle()]
->getComponents() as $name => $options) {
$field_mapping = $mapping
->getPreparedFieldMapping($name);
if ($field_mapping) {
foreach ($entity
->get($name) as $item) {
$item->_attributes += rdf_rdfa_attributes($field_mapping, $item
->toArray());
}
}
}
}
}
/**
* Implements hook_ENTITY_TYPE_storage_load() for comment entities.
*/
function rdf_comment_storage_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');
/** @var \Drupal\comment\CommentInterface $comment*/
$comment->rdf_data['date'] = rdf_rdfa_attributes($created_mapping, $comment
->get('created')
->first()
->toArray());
if ($entity = $comment
->getCommentedEntity()) {
// The current function is a storage level hook, so avoid to bubble
// bubbleable metadata, because it can be outside of a render context.
$comment->rdf_data['entity_uri'] = $entity
->toUrl()
->toString(TRUE)
->getGeneratedUrl();
}
if ($parent = $comment
->getParentComment()) {
$comment->rdf_data['pid_uri'] = $parent
->toUrl()
->toString(TRUE)
->getGeneratedUrl();
}
}
}
/**
* Implements hook_theme().
*/
function rdf_theme() {
return [
'rdf_wrapper' => [
'variables' => [
'attributes' => [],
'content' => NULL,
],
],
'rdf_metadata' => [
'variables' => [
'metadata' => [],
],
],
];
}
/**
* Implements hook_preprocess_HOOK() for HTML document templates.
*/
function rdf_preprocess_html(&$variables) {
// Adds RDF namespace prefix bindings in the form of an RDFa 1.1 prefix
// attribute inside the html element.
if (!isset($variables['html_attributes']['prefix'])) {
$variables['html_attributes']['prefix'] = [];
}
foreach (rdf_get_namespaces() as $prefix => $uri) {
$variables['html_attributes']['prefix'][] = $prefix . ': ' . $uri . " ";
}
}
/**
* Implements hook_preprocess_HOOK() for UID field templates.
*/
function rdf_preprocess_field__node__uid(&$variables) {
_rdf_set_field_rel_attribute($variables);
}
/**
* Transforms the field property attribute into a rel attribute.
*/
function _rdf_set_field_rel_attribute(&$variables) {
// Swap the regular field property attribute and use the rel attribute
// instead so that it plays well with the RDFa markup when only a link is
// present in the field output, for example in the case of the uid field.
if (!empty($variables['attributes']['property'])) {
$variables['attributes']['rel'] = $variables['attributes']['property'];
unset($variables['attributes']['property']);
}
}
/**
* Implements hook_preprocess_HOOK() for node templates.
*/
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['url']) ? NULL : $variables['url'];
$variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
// Adds RDFa markup for the node title as metadata because wrapping the title
// with markup is not reliable and the title output is different depending on
// the view mode (e.g. full vs. teaser).
$title_mapping = $mapping
->getPreparedFieldMapping('title');
if ($title_mapping) {
$title_attributes['property'] = empty($title_mapping['properties']) ? NULL : $title_mapping['properties'];
$title_attributes['content'] = $variables['node']
->label();
$variables['title_suffix']['rdf_meta_title'] = [
'#theme' => 'rdf_metadata',
'#metadata' => [
$title_attributes,
],
];
}
// Adds RDFa markup for the date.
$created_mapping = $mapping
->getPreparedFieldMapping('created');
if (!empty($created_mapping)) {
$date_attributes = rdf_rdfa_attributes($created_mapping, $variables['node']
->get('created')
->first()
->toArray());
$rdf_metadata = [
'#theme' => 'rdf_metadata',
'#metadata' => [
$date_attributes,
],
];
// Depending on whether custom preprocessing is enabled, the 'created'
// field may appear in either of two different places, so check both of
// those places here.
// @see template_preprocess_node.
if (!empty($variables['display_submitted'])) {
// If custom preprocessing is enabled, then detect if the 'created'
// field is displayed by checking the 'display_submitted' variable. In
// this case, for back-compatibility, put the metadata into a special
// variable.
$variables['metadata'] = \Drupal::service('renderer')
->render($rdf_metadata);
}
elseif (isset($variables['elements']['created'])) {
// Otherwise, detect if the 'created' field is displayed by checking if
// it is present in the 'elements variable. Put the metadata into
// title_suffix, along with other metadata added by this module.
$variables['title_suffix']['rdf_meta_created'] = $rdf_metadata;
}
}
// Adds RDFa markup annotating the number of comments a node has.
if (\Drupal::moduleHandler()
->moduleExists('comment') && \Drupal::currentUser()
->hasPermission('access comments')) {
$comment_count_mapping = $mapping
->getPreparedFieldMapping('comment_count');
if (!empty($comment_count_mapping['properties'])) {
$fields = array_keys(\Drupal::service('comment.manager')
->getFields('node'));
$definitions = array_keys($variables['node']
->getFieldDefinitions());
$valid_fields = array_intersect($fields, $definitions);
foreach ($valid_fields as $field_name) {
// Adds RDFa markup for the comment count near the node title as
// metadata.
$comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']
->get($field_name)->comment_count);
$variables['title_suffix']['rdf_meta_comment_count'] = [
'#theme' => 'rdf_metadata',
'#metadata' => [
$comment_count_attributes,
],
];
}
}
}
}
/**
* Implements hook_preprocess_HOOK() for user templates.
*/
function rdf_preprocess_user(&$variables) {
/** @var \Drupal\user\UserInterface $account */
$account = $variables['elements']['#user'];
$uri = $account
->toUrl();
$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'] = $account
->toUrl()
->toString();
}
// If we are on the user account page, add the relationship between the
// sioc:UserAccount and the foaf:Person who holds the account.
if (\Drupal::routeMatch()
->getRouteName() == $uri
->getRouteName()) {
// 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 = [
'#tag' => 'meta',
'#attributes' => [
'about' => $account
->toUrl()
->toString(),
'property' => $name_mapping['properties'],
'content' => $account
->getDisplayName(),
'lang' => '',
],
];
$variables['#attached']['html_head'][] = [
$username_meta,
'rdf_user_username',
];
}
}
}
/**
* Implements hook_preprocess_HOOK() for username.html.twig.
*/
function rdf_preprocess_username(&$variables) {
// 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'])) {
$variables['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) {
$variables['attributes']['about'] = Url::fromRoute('entity.user.canonical', [
'user' => $variables['uid'],
])
->toString();
}
// Add RDF type of user.
$mapping = rdf_get_mapping('user', 'user');
$bundle_mapping = $mapping
->getPreparedBundleMapping();
if (!empty($bundle_mapping['types'])) {
$variables['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)) {
$variables['attributes']['property'] = $name_mapping['properties'];
$variables['attributes']['datatype'] = '';
}
// Add the homepage RDFa markup if present.
$homepage_mapping = $mapping
->getPreparedFieldMapping('homepage');
if (!empty($variables['homepage']) && !empty($homepage_mapping)) {
$variables['attributes']['rel'] = $homepage_mapping['properties'];
}
// Long usernames are truncated by template_preprocess_username(). Store the
// full name in the content attribute so it can be extracted in RDFa.
if ($variables['truncated']) {
$variables['attributes']['content'] = $variables['name_raw'];
}
}
/**
* Implements hook_preprocess_HOOK() for comment templates.
*/
function rdf_preprocess_comment(&$variables) {
$comment = $variables['comment'];
$mapping = rdf_get_mapping('comment', $comment
->bundle());
$bundle_mapping = $mapping
->getPreparedBundleMapping();
if (!empty($bundle_mapping['types']) && !isset($comment->in_preview)) {
// 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.)
$variables['attributes']['about'] = $comment
->toUrl()
->toString();
$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 = [
'rel' => $author_mapping['properties'],
];
// Wraps the 'author' and 'submitted' variables which are both available in
// comment.html.twig.
$variables['author'] = [
'#theme' => 'rdf_wrapper',
'#content' => $variables['author'],
'#attributes' => $author_attributes,
];
$variables['submitted'] = [
'#theme' => 'rdf_wrapper',
'#content' => $variables['submitted'],
'#attributes' => $author_attributes,
];
}
// Adds RDFa markup for the date of the comment.
$created_mapping = $mapping
->getPreparedFieldMapping('created');
if (!empty($created_mapping) && isset($comment->rdf_data)) {
// 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 = [
'#theme' => 'rdf_metadata',
'#metadata' => [
$date_attributes,
],
];
// Ensure the original variable is represented as a render array.
$created = !is_array($variables['created']) ? [
'#markup' => $variables['created'],
] : $variables['created'];
$submitted = !is_array($variables['submitted']) ? [
'#markup' => $variables['submitted'],
] : $variables['submitted'];
// Make render array and RDF metadata available in comment.html.twig.
$variables['created'] = [
$created,
$rdf_metadata,
];
$variables['submitted'] = [
$submitted,
$rdf_metadata,
];
}
$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 entity.
$parent_entity_attributes['rel'] = $pid_mapping['properties'];
// The parent entity URI is precomputed as part of the rdf_data so that it
// can be cached as part of the entity.
$parent_entity_attributes['resource'] = $comment->rdf_data['entity_uri'];
$variables['rdf_metadata_attributes'][] = $parent_entity_attributes;
// Adds the relation to parent comment, if it exists.
if ($comment
->hasParentComment()) {
$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 any.
if (!empty($variables['rdf_metadata_attributes']) && isset($variables['content']['comment_body'])) {
$rdf_metadata = [
'#theme' => 'rdf_metadata',
'#metadata' => $variables['rdf_metadata_attributes'],
];
if (!empty($variables['content']['comment_body']['#prefix'])) {
$rdf_metadata['#suffix'] = $variables['content']['comment_body']['#prefix'];
}
$variables['content']['comment_body']['#prefix'] = \Drupal::service('renderer')
->render($rdf_metadata);
}
}
/**
* Implements hook_preprocess_HOOK() for taxonomy term templates.
*/
function rdf_preprocess_taxonomy_term(&$variables) {
// Adds RDFa markup to the taxonomy term 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., schema:Thing, skos:Concept, and so on).
$term = $variables['term'];
$mapping = rdf_get_mapping('taxonomy_term', $term
->bundle());
$bundle_mapping = $mapping
->getPreparedBundleMapping();
$variables['attributes']['about'] = $variables['url'];
$variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
// Add RDFa markup for the taxonomy term name as metadata, if present.
$name_field_mapping = $mapping
->getPreparedFieldMapping('name');
if (!empty($name_field_mapping) && !empty($name_field_mapping['properties'])) {
$name_attributes = [
'property' => $name_field_mapping['properties'],
'content' => $term
->getName(),
];
$variables['title_suffix']['taxonomy_term_rdfa'] = [
'#theme' => 'rdf_metadata',
'#metadata' => [
$name_attributes,
],
];
}
}
/**
* Implements hook_preprocess_HOOK() for image.html.twig.
*/
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'] = [
'foaf:Image',
];
}
/**
* Prepares variables for RDF metadata templates.
*
* Default template: rdf-metadata.html.twig.
*
* 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 hierarchy 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 array $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.
*/
function template_preprocess_rdf_metadata(&$variables) {
foreach ($variables['metadata'] as $key => $attributes) {
if (!is_null($attributes)) {
$variables['metadata'][$key] = new Attribute($attributes);
}
else {
$variables['metadata'][$key] = new Attribute();
}
}
}