rdf.module 23.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Enables semantically enriched output for Drupal sites in the form of RDFa.
6 7
 */

8
use Drupal\Core\Routing\RouteMatchInterface;
9
use Drupal\Core\Template\Attribute;
10
use Drupal\rdf\Entity\RdfMapping;
11

12
/**
13
 * Implements hook_help().
14
 */
15
function rdf_help($route_name, RouteMatchInterface $route_match) {
16 17
  switch ($route_name) {
    case 'help.page.rdf':
18 19
      $output = '';
      $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>.', array(':rdfa' => 'http://www.w3.org/TR/xhtml-rdfa-primer/', ':rdf' => 'https://www.drupal.org/documentation/modules/rdf')) . '</p>';
21 22 23 24
      return $output;
  }
}

25
/**
26
 * @defgroup rdf RDF Mapping API
27
 * @{
28
 * Functions to describe entities and bundles in RDF.
29
 *
30 31 32 33
 * 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/
34 35
 * @see http://www.w3.org/TR/xhtml-rdfa-primer/
 *
36 37 38 39
 * 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.
40 41
 */
/**
42
 * Returns the RDF mapping object associated with a bundle.
43
 *
44 45 46 47 48 49 50 51
 * 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'.
52
 * @code
53 54 55 56 57 58 59 60
 * rdf_get_mapping('node', 'article')
 *   ->setBundleMapping(array(
 *     'types' => array('sioc:Post'),
 *   ))
 *   ->setFieldMapping('title', array(
 *     'properties' => array('dc:title')
 *   ))
 *   ->save();
61 62
 * @endcode
 *
63 64 65 66 67
 * @param string $entity_type
 *   The entity type.
 * @param string $bundle
 *   The bundle.
 *
68
 * @return \Drupal\rdf\Entity\RdfMapping
69
 *   The RdfMapping object.
70
 */
71 72
function rdf_get_mapping($entity_type, $bundle) {
  // Try loading the mapping from configuration.
73
  $mapping = RdfMapping::load($entity_type . '.' . $bundle);
74 75 76

  // If not found, create a fresh mapping object.
  if (!$mapping) {
77
    $mapping = RdfMapping::create(array(
78 79 80 81 82 83 84
      'targetEntityType' => $entity_type,
      'bundle' => $bundle,
    ));
  }

  return $mapping;
}
85

86 87 88 89 90 91 92 93
/**
 * 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/',
94
    'og'       => 'http://ogp.me/ns#',
95
    'rdfs'     => 'http://www.w3.org/2000/01/rdf-schema#',
96
    'schema'   => 'http://schema.org/',
97 98 99 100 101 102 103
    '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#',
  );
}

104
/**
105 106 107 108
 * Retrieves RDF namespaces.
 *
 * Invokes hook_rdf_namespaces() and collects RDF namespaces from modules that
 * implement it.
109 110
 */
function rdf_get_namespaces() {
111 112
  $namespaces = array();
  // 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 118 119 120 121 122
      if (array_key_exists($prefix, $namespaces) && $namespace !== $namespaces[$prefix]) {
        throw new Exception(t('Tried to map @prefix to @namespace, but @prefix is already mapped to @orig_namespace.', array('@prefix' => $prefix, '@namespace' => $namespace, '@orig_namespace' => $namespaces[$prefix])));
      }
      else {
        $namespaces[$prefix] = $namespace;
      }
123 124
    }
  }
125
  return $namespaces;
126 127
}

128 129 130 131 132 133 134 135 136
/**
 * @} End of "defgroup rdf".
 */

/**
 * @addtogroup rdf
 * @{
 */

137
/**
138 139
 * Builds an array of RDFa attributes for a given mapping.
 *
140 141 142 143
 * 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.
144
 *
145 146 147
 * @param array $mapping
 *   An array containing a mandatory 'properties' key and optional 'datatype',
 *   'datatype_callback' and 'type' keys. For example:
148 149
 *   @code
 *     array(
150 151 152 153 154 155 156
 *       'properties' => array('schema:interactionCount'),
 *       'datatype' => 'xsd:integer',
 *       'datatype_callback' => array(
 *         'callable' => 'Drupal\rdf\SchemaOrgDataConverter::interactionCount',
 *         'arguments' => array(
 *           'interaction_type' => 'UserComments'
 *         ),
157 158 159
 *       ),
 *     );
 *   @endcode
160
 * @param mixed $data
161 162
 *   (optional) A value that needs to be converted by the provided callback
 *   function.
163
 *
164
 * @return array
165
 *   RDFa attributes suitable for Drupal\Core\Template\Attribute.
166 167
 */
function rdf_rdfa_attributes($mapping, $data = NULL) {
168 169
  $attributes = array();

170
  // The type of mapping defaults to 'property'.
171
  $type = isset($mapping['mapping_type']) ? $mapping['mapping_type'] : 'property';
172 173 174 175 176

  switch ($type) {
    // The mapping expresses the relationship between two resources.
    case 'rel':
    case 'rev':
177
      $attributes[$type] = $mapping['properties'];
178 179 180 181 182
      break;

    // The mapping expresses the relationship between a resource and some
    // literal text.
    case 'property':
183 184 185 186
      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'])) {
187 188 189
          $callback = $mapping['datatype_callback']['callable'];
          $arguments = isset($mapping['datatype_callback']['arguments']) ? $mapping['datatype_callback']['arguments'] : NULL;
          $attributes['content'] = call_user_func($callback, $data, $arguments);
190 191 192 193 194
        }
        if (isset($mapping['datatype'])) {
          $attributes['datatype'] = $mapping['datatype'];
        }
        break;
195 196 197 198 199 200 201
      }
  }

  return $attributes;
}

/**
202
 * @} End of "addtogroup rdf".
203 204
 */

205 206 207 208 209 210 211 212 213 214 215 216
/**
 * 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);
217
      if ($field_mapping) {
218
        foreach ($entity->get($name) as $item) {
219
          $item->_attributes += rdf_rdfa_attributes($field_mapping, $item->toArray());
220 221 222 223 224 225
        }
      }
    }
  }
}

226
/**
227
 * Implements hook_ENTITY_TYPE_storage_load() for comment entities.
228
 */
229
function rdf_comment_storage_load($comments) {
230
  foreach ($comments as $comment) {
231 232 233
    // 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.
234 235
    $created_mapping = rdf_get_mapping('comment', $comment->bundle())
      ->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 240 241
    // 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();
242 243
    if ($comment->hasParentComment()) {
      $comment->rdf_data['pid_uri'] = $comment->getParentComment()->url();
244 245 246 247
    }
  }
}

248 249 250 251 252
/**
 * Implements hook_theme().
 */
function rdf_theme() {
  return array(
253 254 255
    'rdf_wrapper' => array(
      'variables' => array('attributes' => array(), 'content' => NULL),
    ),
256
    'rdf_metadata' => array(
257
      'variables' => array('metadata' => array()),
258 259 260 261
    ),
  );
}

262
/**
263
 * Implements hook_preprocess_HOOK() for HTML document templates.
264 265 266 267
 */
function rdf_preprocess_html(&$variables) {
  // Adds RDF namespace prefix bindings in the form of an RDFa 1.1 prefix
  // attribute inside the html element.
268 269 270
  if (!isset($variables['html_attributes']['prefix'])) {
    $variables['html_attributes']['prefix'] = array();
  }
271
  foreach (rdf_get_namespaces() as $prefix => $uri) {
272
    $variables['html_attributes']['prefix'][] = $prefix . ': ' . $uri . " ";
273 274 275
  }
}

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
/**
 * 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']);
  }
}


297
/**
298
 * Implements hook_preprocess_HOOK() for node templates.
299 300
 */
function rdf_preprocess_node(&$variables) {
301
  // Adds RDFa markup to the node container. The about attribute specifies the
302 303 304
  // 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.)
305 306 307
  $bundle = $variables['node']->bundle();
  $mapping = rdf_get_mapping('node', $bundle);
  $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'];
310

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 316
  if ($title_mapping) {
    $title_attributes['property'] = empty($title_mapping['properties']) ? NULL : $title_mapping['properties'];
317
    $title_attributes['content'] = $variables['node']->label();
318 319 320
    $variables['title_suffix']['rdf_meta_title'] = array(
      '#theme' => 'rdf_metadata',
      '#metadata' => array($title_attributes),
321
    );
322 323
  }

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());
328 329 330 331
    $rdf_metadata = array(
      '#theme' => 'rdf_metadata',
      '#metadata' => array($date_attributes),
    );
332
    $variables['metadata'] = \Drupal::service('renderer')->render($rdf_metadata);
333
  }
334 335

  // Adds RDFa markup annotating the number of comments a node has.
336 337
  if (\Drupal::moduleHandler()->moduleExists('comment') && \Drupal::currentUser()->hasPermission('access comments')) {
    $comment_count_mapping = $mapping->getPreparedFieldMapping('comment_count');
338 339
    if (!empty($comment_count_mapping['properties'])) {
      $fields = array_keys(\Drupal::service('comment.manager')->getFields('node'));
340
      $definitions = array_keys($variables['node']->getFieldDefinitions());
341 342 343 344
      $valid_fields = array_intersect($fields, $definitions);
      $count = 0;
      foreach ($valid_fields as $field_name) {
        $count += $variables['node']->get($field_name)->comment_count;
345 346
        // Adds RDFa markup for the comment count near the node title as
        // metadata.
347 348 349 350
        $comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']->get($field_name)->comment_count);
        $variables['title_suffix']['rdf_meta_comment_count'] = array(
          '#theme' => 'rdf_metadata',
          '#metadata' => array($comment_count_attributes),
351 352
        );
      }
353 354
    }
  }
355 356 357
}

/**
358
 * Implements hook_preprocess_HOOK() for user templates.
359
 */
360
function rdf_preprocess_user(&$variables) {
361
  /** @var $account \Drupal\user\UserInterface */
362
  $account = $variables['elements']['#user'];
363
  $uri = $account->urlInfo();
364 365
  $mapping = rdf_get_mapping('user', 'user');
  $bundle_mapping = $mapping->getPreparedBundleMapping();
366 367

  // Adds RDFa markup to the user profile page. Fields displayed in this page
368
  // will automatically describe the user.
369 370
  if (!empty($bundle_mapping['types'])) {
    $variables['attributes']['typeof'] = $bundle_mapping['types'];
371
    $variables['attributes']['about'] = $account->url();
372
  }
373 374
  // If we are on the user account page, add the relationship between the
  // sioc:UserAccount and the foaf:Person who holds the account.
375
  if (\Drupal::routeMatch()->getRouteName() == $uri->getRouteName()) {
376 377
    // Adds the markup for username as language neutral literal, see
    // rdf_preprocess_username().
378 379 380 381 382
    $name_mapping = $mapping->getPreparedFieldMapping('name');
    if (!empty($name_mapping['properties'])) {
      $username_meta = array(
        '#tag' => 'meta',
        '#attributes' => array(
383
          'about' => $account->url(),
384
          'property' => $name_mapping['properties'],
385
          'content' => $account->getDisplayName(),
386 387 388
          'lang' => '',
        ),
      );
389
      $variables['#attached']['html_head'][] = [$username_meta, 'rdf_user_username'];
390
    }
391
  }
392 393 394
}

/**
395
 * Implements hook_preprocess_HOOK() for username.html.twig.
396 397
 */
function rdf_preprocess_username(&$variables) {
398
  // Because lang is set on the HTML element that wraps the page, the
399 400 401 402
  // 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.
403
  if (empty($variables['attributes']['lang'])) {
404
    $variables['attributes']['lang'] = '';
405 406
  }

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 410 411 412
  // 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
413
  // profile in RDF.)
414
  if ($variables['uid'] > 0) {
415
    $variables['attributes']['about'] = \Drupal::url('entity.user.canonical', ['user' => $variables['uid']]);
416
  }
417

418 419 420 421
  // Add RDF type of user.
  $mapping = rdf_get_mapping('user', 'user');
  $bundle_mapping = $mapping->getPreparedBundleMapping();
  if (!empty($bundle_mapping['types'])) {
422
    $variables['attributes']['typeof'] = $bundle_mapping['types'];
423
  }
424 425 426
  // 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.
427 428
  $name_mapping = $mapping->getPreparedFieldMapping('name');
  if (!empty($name_mapping)) {
429 430
    $variables['attributes']['property'] = $name_mapping['properties'];
    $variables['attributes']['datatype'] = '';
431 432
  }
  // Add the homepage RDFa markup if present.
433 434
  $homepage_mapping = $mapping->getPreparedFieldMapping('homepage');
  if (!empty($variables['homepage']) && !empty($homepage_mapping)) {
435
    $variables['attributes']['rel'] = $homepage_mapping['properties'];
436
  }
437 438 439
  // 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']) {
440
    $variables['attributes']['content'] = $variables['name_raw'];
441
  }
442 443 444
}

/**
445
 * Implements hook_preprocess_HOOK() for comment templates.
446 447 448
 */
function rdf_preprocess_comment(&$variables) {
  $comment = $variables['comment'];
449 450 451
  $mapping = rdf_get_mapping('comment', $comment->bundle());
  $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 456
    // typeof attribute indicates its RDF type (e.g., sioc:Post, foaf:Document,
    // and so on.)
457
    $variables['attributes']['about'] = $comment->url();
458
    $variables['attributes']['typeof'] = $bundle_mapping['types'];
459 460
  }

461 462 463
  // Adds RDFa markup for the relation between the comment and its author.
  $author_mapping = $mapping->getPreparedFieldMapping('uid');
  if (!empty($author_mapping)) {
464 465 466 467 468 469 470 471 472 473 474 475 476
    $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,
    ];
477
  }
478
  // Adds RDFa markup for the date of the comment.
479 480
  $created_mapping = $mapping->getPreparedFieldMapping('created');
  if (!empty($created_mapping)) {
481 482
    // The comment date is precomputed as part of the rdf_data so that it can be
    // cached as part of the entity.
483
    $date_attributes = $comment->rdf_data['date'];
484 485 486 487 488

    $rdf_metadata = array(
      '#theme' => 'rdf_metadata',
      '#metadata' => array($date_attributes),
    );
489 490 491 492 493 494
    // 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];
495
  }
496
  $title_mapping = $mapping->getPreparedFieldMapping('subject');
497
  if (!empty($title_mapping)) {
498 499 500 501
    // 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.
502
    $variables['title_attributes']['property'] = $title_mapping['properties'];
503
    $variables['title_attributes']['datatype'] = '';
504 505 506 507
  }

  // Annotates the parent relationship between the current comment and the node
  // it belongs to. If available, the parent comment is also annotated.
508 509
  // @todo When comments are turned into fields, this should be changed.
  // Currently there is no mapping relating a comment to its node.
510 511
  $pid_mapping = $mapping->getPreparedFieldMapping('pid');
  if (!empty($pid_mapping)) {
512 513 514 515 516 517
    // 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;
518

519
    // Adds the relation to parent comment, if it exists.
520
    if ($comment->hasParentComment()) {
521
      $parent_comment_attributes['rel'] = $pid_mapping['properties'];
522 523
      // The parent comment URI is precomputed as part of the rdf_data so that
      // 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;
526 527
    }
  }
528 529
  // Adds RDF metadata markup above comment body if any.
  if (!empty($variables['rdf_metadata_attributes']) && isset($variables['content']['comment_body'])) {
530 531 532 533
    $rdf_metadata = array(
      '#theme' => 'rdf_metadata',
      '#metadata' => $variables['rdf_metadata_attributes'],
    );
534 535 536
    if (!empty($variables['content']['comment_body']['#prefix'])) {
      $rdf_metadata['#suffix'] = $variables['content']['comment_body']['#prefix'];
    }
537
    $variables['content']['comment_body']['#prefix'] = \Drupal::service('renderer')->render($rdf_metadata);
538
  }
539 540
}

541
/**
542
 * Implements hook_preprocess_HOOK() for taxonomy term templates.
543 544
 */
function rdf_preprocess_taxonomy_term(&$variables) {
545 546 547 548
  // 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).
549
  $term = $variables['term'];
550 551
  $mapping = rdf_get_mapping('taxonomy_term', $term->bundle());
  $bundle_mapping = $mapping->getPreparedBundleMapping();
552 553 554 555
  $variables['attributes']['about'] = $term->url();
  $variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];

  // Add RDFa markup for the taxonomy term name as metadata, if present.
556
  $name_field_mapping = $mapping->getPreparedFieldMapping('name');
557 558 559 560 561 562 563 564
  if (!empty($name_field_mapping) && !empty($name_field_mapping['properties'])) {
    $name_attributes = array(
      'property' => $name_field_mapping['properties'],
      'content' => $term->getName(),
    );
    $variables['title_suffix']['taxonomy_term_rdfa'] = array(
      '#theme' => 'rdf_metadata',
      '#metadata' => array($name_attributes),
565 566
    );
  }
567 568
}

569
/**
570
 * Implements hook_preprocess_HOOK() for image.html.twig.
571 572
 */
function rdf_preprocess_image(&$variables) {
573 574 575
  // 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.
576 577 578
  $variables['attributes']['typeof'] = array('foaf:Image');
}

579
/**
580 581 582
 * Prepares variables for RDF metadata templates.
 *
 * Default template: rdf-metadata.html.twig.
583
 *
584 585
 * 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
586
 * but not for machines because this hierarchy is not present in the DOM tree.
587 588
 * 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.
589
 *
590
 * @param array $variables
591 592 593 594
 *   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.
595
 */
596 597
function template_preprocess_rdf_metadata(&$variables) {
  foreach ($variables['metadata'] as $key => $attributes) {
598 599 600 601 602 603
    if (!is_null($attributes)) {
      $variables['metadata'][$key] = new Attribute($attributes);
    }
    else {
      $variables['metadata'][$key] = new Attribute();
    }
604
  }
605
}