5 * Enables semantically enriched output for Drupal sites in the form of RDFa.
8 use Drupal\Core\Routing\RouteMatchInterface;
9 use Drupal\Core\Template\Attribute;
10 use Drupal\rdf\Entity\RdfMapping;
13 * Implements hook_help().
15 function rdf_help($route_name, RouteMatchInterface $route_match) {
16 switch ($route_name) {
19 $output .= '<h3>' . t('About') . '</h3>';
20 $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>';
26 * @defgroup rdf RDF Mapping API
28 * Functions to describe entities and bundles in RDF.
30 * The RDF module introduces RDF and RDFa to Drupal. RDF is a W3C standard to
31 * describe structured data. RDF can be serialized as RDFa in XHTML attributes
32 * to augment visual data with machine-readable hints.
33 * @see http://www.w3.org/RDF/
34 * @see http://www.w3.org/TR/xhtml-rdfa-primer/
36 * Modules can provide mappings of their bundles' data and metadata to RDF
37 * classes and properties. This module takes care of injecting these mappings
38 * into variables available to theme functions and templates. All Drupal core
39 * themes are coded to be RDFa compatible.
42 * Returns the RDF mapping object associated with a bundle.
44 * The function reads the rdf_mapping object from the current configuration,
45 * or returns a ready-to-use empty one if no configuration entry exists yet for
46 * this bundle. This streamlines the manipulation of mapping objects by always
47 * returning a consistent object that reflects the current state of the
51 * -Map the 'article' bundle to 'sioc:Post' and the 'title' field to 'dc:title'.
53 * rdf_get_mapping('node', 'article')
54 * ->setBundleMapping(array(
55 * 'types' => array('sioc:Post'),
57 * ->setFieldMapping('title', array(
58 * 'properties' => array('dc:title')
63 * @param string $entity_type
65 * @param string $bundle
68 * @return \Drupal\rdf\Entity\RdfMapping
69 * The RdfMapping object.
71 function rdf_get_mapping($entity_type, $bundle) {
72 // Try loading the mapping from configuration.
73 $mapping = RdfMapping::load($entity_type . '.' . $bundle);
75 // If not found, create a fresh mapping object.
77 $mapping = RdfMapping::create([
78 'targetEntityType' => $entity_type,
87 * Implements hook_rdf_namespaces().
89 function rdf_rdf_namespaces() {
91 'content' => 'http://purl.org/rss/1.0/modules/content/',
92 'dc' => 'http://purl.org/dc/terms/',
93 'foaf' => 'http://xmlns.com/foaf/0.1/',
94 'og' => 'http://ogp.me/ns#',
95 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
96 'schema' => 'http://schema.org/',
97 'sioc' => 'http://rdfs.org/sioc/ns#',
98 'sioct' => 'http://rdfs.org/sioc/types#',
99 'skos' => 'http://www.w3.org/2004/02/skos/core#',
100 'xsd' => 'http://www.w3.org/2001/XMLSchema#',
105 * Retrieves RDF namespaces.
107 * Invokes hook_rdf_namespaces() and collects RDF namespaces from modules that
110 function rdf_get_namespaces() {
112 // In order to resolve duplicate namespaces by using the earliest defined
113 // namespace, do not use \Drupal::moduleHandler()->invokeAll().
114 foreach (\Drupal::moduleHandler()->getImplementations('rdf_namespaces') as $module) {
115 $function = $module . '_rdf_namespaces';
116 foreach ($function() as $prefix => $namespace) {
117 if (array_key_exists($prefix, $namespaces) && $namespace !== $namespaces[$prefix]) {
118 throw new Exception(t('Tried to map @prefix to @namespace, but @prefix is already mapped to @orig_namespace.', ['@prefix' => $prefix, '@namespace' => $namespace, '@orig_namespace' => $namespaces[$prefix]]));
121 $namespaces[$prefix] = $namespace;
129 * @} End of "defgroup rdf".
138 * Builds an array of RDFa attributes for a given mapping.
140 * This array will typically be passed through Drupal\Core\Template\Attribute
141 * to create the attributes variables that are available to template files.
142 * These include $attributes, $title_attributes, $content_attributes and the
143 * field-specific $item_attributes variables.
145 * @param array $mapping
146 * An array containing a mandatory 'properties' key and optional 'datatype',
147 * 'datatype_callback' and 'type' keys. For example:
150 * 'properties' => array('schema:interactionCount'),
151 * 'datatype' => 'xsd:integer',
152 * 'datatype_callback' => array(
153 * 'callable' => 'Drupal\rdf\SchemaOrgDataConverter::interactionCount',
154 * 'arguments' => array(
155 * 'interaction_type' => 'UserComments'
161 * (optional) A value that needs to be converted by the provided callback
165 * RDFa attributes suitable for Drupal\Core\Template\Attribute.
167 function rdf_rdfa_attributes($mapping, $data = NULL) {
170 // The type of mapping defaults to 'property'.
171 $type = isset($mapping['mapping_type']) ? $mapping['mapping_type'] : 'property';
174 // The mapping expresses the relationship between two resources.
177 $attributes[$type] = $mapping['properties'];
180 // The mapping expresses the relationship between a resource and some
183 if (!empty($mapping['properties'])) {
184 $attributes['property'] = $mapping['properties'];
185 // Convert $data to a specific format as per the callback function.
186 if (isset($data) && !empty($mapping['datatype_callback'])) {
187 $callback = $mapping['datatype_callback']['callable'];
188 $arguments = isset($mapping['datatype_callback']['arguments']) ? $mapping['datatype_callback']['arguments'] : NULL;
189 $attributes['content'] = call_user_func($callback, $data, $arguments);
191 if (isset($mapping['datatype'])) {
192 $attributes['datatype'] = $mapping['datatype'];
202 * @} End of "addtogroup rdf".
206 * Implements hook_entity_prepare_view().
208 function rdf_entity_prepare_view($entity_type, array $entities, array $displays) {
209 // Iterate over the RDF mappings for each entity and prepare the RDFa
210 // attributes to be added inside field formatters.
211 foreach ($entities as $entity) {
212 $mapping = rdf_get_mapping($entity_type, $entity->bundle());
213 // Only prepare the RDFa attributes for the fields which are configured to
215 foreach ($displays[$entity->bundle()]->getComponents() as $name => $options) {
216 $field_mapping = $mapping->getPreparedFieldMapping($name);
217 if ($field_mapping) {
218 foreach ($entity->get($name) as $item) {
219 $item->_attributes += rdf_rdfa_attributes($field_mapping, $item->toArray());
227 * Implements hook_ENTITY_TYPE_storage_load() for comment entities.
229 function rdf_comment_storage_load($comments) {
230 foreach ($comments as $comment) {
231 // Pages with many comments can show poor performance. This information
232 // isn't needed until rdf_preprocess_comment() is called, but set it here
233 // to optimize performance for websites that implement an entity cache.
234 $created_mapping = rdf_get_mapping('comment', $comment->bundle())
235 ->getPreparedFieldMapping('created');
236 /** @var \Drupal\comment\CommentInterface $comment*/
237 $comment->rdf_data['date'] = rdf_rdfa_attributes($created_mapping, $comment->get('created')->first()->toArray());
238 $entity = $comment->getCommentedEntity();
239 // The current function is a storage level hook, so avoid to bubble
240 // bubbleable metadata, because it can be outside of a render context.
241 $comment->rdf_data['entity_uri'] = $entity->toUrl()->toString(TRUE)->getGeneratedUrl();
242 if ($comment->hasParentComment()) {
243 $comment->rdf_data['pid_uri'] = $comment->getParentComment()->url();
249 * Implements hook_theme().
251 function rdf_theme() {
254 'variables' => ['attributes' => [], 'content' => NULL],
257 'variables' => ['metadata' => []],
263 * Implements hook_preprocess_HOOK() for HTML document templates.
265 function rdf_preprocess_html(&$variables) {
266 // Adds RDF namespace prefix bindings in the form of an RDFa 1.1 prefix
267 // attribute inside the html element.
268 if (!isset($variables['html_attributes']['prefix'])) {
269 $variables['html_attributes']['prefix'] = [];
271 foreach (rdf_get_namespaces() as $prefix => $uri) {
272 $variables['html_attributes']['prefix'][] = $prefix . ': ' . $uri . " ";
277 * Implements hook_preprocess_HOOK() for UID field templates.
279 function rdf_preprocess_field__node__uid(&$variables) {
280 _rdf_set_field_rel_attribute($variables);
284 * Transforms the field property attribute into a rel attribute.
286 function _rdf_set_field_rel_attribute(&$variables) {
287 // Swap the regular field property attribute and use the rel attribute
288 // instead so that it plays well with the RDFa markup when only a link is
289 // present in the field output, for example in the case of the uid field.
290 if (!empty($variables['attributes']['property'])) {
291 $variables['attributes']['rel'] = $variables['attributes']['property'];
292 unset($variables['attributes']['property']);
298 * Implements hook_preprocess_HOOK() for node templates.
300 function rdf_preprocess_node(&$variables) {
301 // Adds RDFa markup to the node container. The about attribute specifies the
302 // URI of the resource described within the HTML element, while the @typeof
303 // attribute indicates its RDF type (e.g., foaf:Document, sioc:Person, and so
305 $bundle = $variables['node']->bundle();
306 $mapping = rdf_get_mapping('node', $bundle);
307 $bundle_mapping = $mapping->getPreparedBundleMapping('node', $bundle);
308 $variables['attributes']['about'] = empty($variables['url']) ? NULL : $variables['url'];
309 $variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
311 // Adds RDFa markup for the node title as metadata because wrapping the title
312 // with markup is not reliable and the title output is different depending on
313 // the view mode (e.g. full vs. teaser).
314 $title_mapping = $mapping->getPreparedFieldMapping('title');
315 if ($title_mapping) {
316 $title_attributes['property'] = empty($title_mapping['properties']) ? NULL : $title_mapping['properties'];
317 $title_attributes['content'] = $variables['node']->label();
318 $variables['title_suffix']['rdf_meta_title'] = [
319 '#theme' => 'rdf_metadata',
320 '#metadata' => [$title_attributes],
324 // Adds RDFa markup for the date.
325 $created_mapping = $mapping->getPreparedFieldMapping('created');
326 if (!empty($created_mapping) && $variables['display_submitted']) {
327 $date_attributes = rdf_rdfa_attributes($created_mapping, $variables['node']->get('created')->first()->toArray());
329 '#theme' => 'rdf_metadata',
330 '#metadata' => [$date_attributes],
332 $variables['metadata'] = drupal_render($rdf_metadata);
335 // Adds RDFa markup annotating the number of comments a node has.
336 if (\Drupal::moduleHandler()->moduleExists('comment') && \Drupal::currentUser()->hasPermission('access comments')) {
337 $comment_count_mapping = $mapping->getPreparedFieldMapping('comment_count');
338 if (!empty($comment_count_mapping['properties'])) {
339 $fields = array_keys(\Drupal::service('comment.manager')->getFields('node'));
340 $definitions = array_keys($variables['node']->getFieldDefinitions());
341 $valid_fields = array_intersect($fields, $definitions);
343 foreach ($valid_fields as $field_name) {
344 $count += $variables['node']->get($field_name)->comment_count;
345 // Adds RDFa markup for the comment count near the node title as
347 $comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']->get($field_name)->comment_count);
348 $variables['title_suffix']['rdf_meta_comment_count'] = [
349 '#theme' => 'rdf_metadata',
350 '#metadata' => [$comment_count_attributes],
358 * Implements hook_preprocess_HOOK() for user templates.
360 function rdf_preprocess_user(&$variables) {
361 /** @var $account \Drupal\user\UserInterface */
362 $account = $variables['elements']['#user'];
363 $uri = $account->urlInfo();
364 $mapping = rdf_get_mapping('user', 'user');
365 $bundle_mapping = $mapping->getPreparedBundleMapping();
367 // Adds RDFa markup to the user profile page. Fields displayed in this page
368 // will automatically describe the user.
369 if (!empty($bundle_mapping['types'])) {
370 $variables['attributes']['typeof'] = $bundle_mapping['types'];
371 $variables['attributes']['about'] = $account->url();
373 // If we are on the user account page, add the relationship between the
374 // sioc:UserAccount and the foaf:Person who holds the account.
375 if (\Drupal::routeMatch()->getRouteName() == $uri->getRouteName()) {
376 // Adds the markup for username as language neutral literal, see
377 // rdf_preprocess_username().
378 $name_mapping = $mapping->getPreparedFieldMapping('name');
379 if (!empty($name_mapping['properties'])) {
383 'about' => $account->url(),
384 'property' => $name_mapping['properties'],
385 'content' => $account->getDisplayName(),
389 $variables['#attached']['html_head'][] = [$username_meta, 'rdf_user_username'];
395 * Implements hook_preprocess_HOOK() for username.html.twig.
397 function rdf_preprocess_username(&$variables) {
398 // Because lang is set on the HTML element that wraps the page, the
399 // username inherits this language attribute. However, since the username
400 // might not be transliterated to the same language that the content is in,
401 // we do not want it to inherit the language attribute, so we set the
402 // attribute to an empty string.
403 if (empty($variables['attributes']['lang'])) {
404 $variables['attributes']['lang'] = '';
407 // The profile URI is used to identify the user account. The about attribute
408 // is used to set the URI as the default subject of the properties embedded
409 // as RDFa in the child elements. Even if the user profile is not accessible
410 // to the current user, we use its URI in order to identify the user in RDF.
411 // We do not use this attribute for the anonymous user because we do not have
412 // a user profile URI for it (only a homepage which cannot be used as user
414 if ($variables['uid'] > 0) {
415 $variables['attributes']['about'] = \Drupal::url('entity.user.canonical', ['user' => $variables['uid']]);
418 // Add RDF type of user.
419 $mapping = rdf_get_mapping('user', 'user');
420 $bundle_mapping = $mapping->getPreparedBundleMapping();
421 if (!empty($bundle_mapping['types'])) {
422 $variables['attributes']['typeof'] = $bundle_mapping['types'];
424 // Annotate the username in RDFa. A property attribute is used with an empty
425 // datatype attribute to ensure the username is parsed as a plain literal
426 // in RDFa 1.0 and 1.1.
427 $name_mapping = $mapping->getPreparedFieldMapping('name');
428 if (!empty($name_mapping)) {
429 $variables['attributes']['property'] = $name_mapping['properties'];
430 $variables['attributes']['datatype'] = '';
432 // Add the homepage RDFa markup if present.
433 $homepage_mapping = $mapping->getPreparedFieldMapping('homepage');
434 if (!empty($variables['homepage']) && !empty($homepage_mapping)) {
435 $variables['attributes']['rel'] = $homepage_mapping['properties'];
437 // Long usernames are truncated by template_preprocess_username(). Store the
438 // full name in the content attribute so it can be extracted in RDFa.
439 if ($variables['truncated']) {
440 $variables['attributes']['content'] = $variables['name_raw'];
445 * Implements hook_preprocess_HOOK() for comment templates.
447 function rdf_preprocess_comment(&$variables) {
448 $comment = $variables['comment'];
449 $mapping = rdf_get_mapping('comment', $comment->bundle());
450 $bundle_mapping = $mapping->getPreparedBundleMapping();
452 if (!empty($bundle_mapping['types']) && !isset($comment->in_preview)) {
453 // Adds RDFa markup to the comment container. The about attribute specifies
454 // the URI of the resource described within the HTML element, while the
455 // typeof attribute indicates its RDF type (e.g., sioc:Post, foaf:Document,
457 $variables['attributes']['about'] = $comment->url();
458 $variables['attributes']['typeof'] = $bundle_mapping['types'];
461 // Adds RDFa markup for the relation between the comment and its author.
462 $author_mapping = $mapping->getPreparedFieldMapping('uid');
463 if (!empty($author_mapping)) {
464 $author_attributes = ['rel' => $author_mapping['properties']];
465 // Wraps the 'author' and 'submitted' variables which are both available in
466 // comment.html.twig.
467 $variables['author'] = [
468 '#theme' => 'rdf_wrapper',
469 '#content' => $variables['author'],
470 '#attributes' => $author_attributes,
472 $variables['submitted'] = [
473 '#theme' => 'rdf_wrapper',
474 '#content' => $variables['submitted'],
475 '#attributes' => $author_attributes,
478 // Adds RDFa markup for the date of the comment.
479 $created_mapping = $mapping->getPreparedFieldMapping('created');
480 if (!empty($created_mapping)) {
481 // The comment date is precomputed as part of the rdf_data so that it can be
482 // cached as part of the entity.
483 $date_attributes = $comment->rdf_data['date'];
486 '#theme' => 'rdf_metadata',
487 '#metadata' => [$date_attributes],
489 // Ensure the original variable is represented as a render array.
490 $created = !is_array($variables['created']) ? ['#markup' => $variables['created']] : $variables['created'];
491 $submitted = !is_array($variables['submitted']) ? ['#markup' => $variables['submitted']] : $variables['submitted'];
492 // Make render array and RDF metadata available in comment.html.twig.
493 $variables['created'] = [$created, $rdf_metadata];
494 $variables['submitted'] = [$submitted, $rdf_metadata];
496 $title_mapping = $mapping->getPreparedFieldMapping('subject');
497 if (!empty($title_mapping)) {
498 // Adds RDFa markup to the subject of the comment. Because the RDFa markup
499 // is added to an <h3> tag which might contain HTML code, we specify an
500 // empty datatype to ensure the value of the title read by the RDFa parsers
502 $variables['title_attributes']['property'] = $title_mapping['properties'];
503 $variables['title_attributes']['datatype'] = '';
506 // Annotates the parent relationship between the current comment and the node
507 // it belongs to. If available, the parent comment is also annotated.
508 // @todo When comments are turned into fields, this should be changed.
509 // Currently there is no mapping relating a comment to its node.
510 $pid_mapping = $mapping->getPreparedFieldMapping('pid');
511 if (!empty($pid_mapping)) {
512 // Adds the relation to the parent entity.
513 $parent_entity_attributes['rel'] = $pid_mapping['properties'];
514 // The parent entity URI is precomputed as part of the rdf_data so that it
515 // can be cached as part of the entity.
516 $parent_entity_attributes['resource'] = $comment->rdf_data['entity_uri'];
517 $variables['rdf_metadata_attributes'][] = $parent_entity_attributes;
519 // Adds the relation to parent comment, if it exists.
520 if ($comment->hasParentComment()) {
521 $parent_comment_attributes['rel'] = $pid_mapping['properties'];
522 // The parent comment URI is precomputed as part of the rdf_data so that
523 // it can be cached as part of the entity.
524 $parent_comment_attributes['resource'] = $comment->rdf_data['pid_uri'];
525 $variables['rdf_metadata_attributes'][] = $parent_comment_attributes;
528 // Adds RDF metadata markup above comment body if any.
529 if (!empty($variables['rdf_metadata_attributes']) && isset($variables['content']['comment_body'])) {
531 '#theme' => 'rdf_metadata',
532 '#metadata' => $variables['rdf_metadata_attributes'],
534 if (!empty($variables['content']['comment_body']['#prefix'])) {
535 $rdf_metadata['#suffix'] = $variables['content']['comment_body']['#prefix'];
537 $variables['content']['comment_body']['#prefix'] = drupal_render($rdf_metadata);
542 * Implements hook_preprocess_HOOK() for taxonomy term templates.
544 function rdf_preprocess_taxonomy_term(&$variables) {
545 // Adds RDFa markup to the taxonomy term container.
546 // The @about attribute specifies the URI of the resource described within
547 // the HTML element, while the @typeof attribute indicates its RDF type
548 // (e.g., schema:Thing, skos:Concept, and so on).
549 $term = $variables['term'];
550 $mapping = rdf_get_mapping('taxonomy_term', $term->bundle());
551 $bundle_mapping = $mapping->getPreparedBundleMapping();
552 $variables['attributes']['about'] = $term->url();
553 $variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
555 // Add RDFa markup for the taxonomy term name as metadata, if present.
556 $name_field_mapping = $mapping->getPreparedFieldMapping('name');
557 if (!empty($name_field_mapping) && !empty($name_field_mapping['properties'])) {
559 'property' => $name_field_mapping['properties'],
560 'content' => $term->getName(),
562 $variables['title_suffix']['taxonomy_term_rdfa'] = [
563 '#theme' => 'rdf_metadata',
564 '#metadata' => [$name_attributes],
570 * Implements hook_preprocess_HOOK() for image.html.twig.
572 function rdf_preprocess_image(&$variables) {
573 // Adds the RDF type for image. We cannot use the usual entity-based mapping
574 // to get 'foaf:Image' because image does not have its own entity type or
576 $variables['attributes']['typeof'] = ['foaf:Image'];
580 * Prepares variables for RDF metadata templates.
582 * Default template: rdf-metadata.html.twig.
584 * Sometimes it is useful to export data which is not semantically present in
585 * the HTML output. For example, a hierarchy of comments is visible for a human
586 * but not for machines because this hierarchy is not present in the DOM tree.
587 * We can express it in RDFa via empty <span> tags. These aren't visible and
588 * give machines extra information about the content and its structure.
590 * @param array $variables
591 * An associative array containing:
592 * - metadata: An array of attribute arrays. Each item in the array
593 * corresponds to its own set of attributes, and therefore, needs its own
596 function template_preprocess_rdf_metadata(&$variables) {
597 foreach ($variables['metadata'] as $key => $attributes) {
598 if (!is_null($attributes)) {
599 $variables['metadata'][$key] = new Attribute($attributes);
602 $variables['metadata'][$key] = new Attribute();