rdf.module 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. <?php
  2. /**
  3. * @file
  4. * Enables semantically enriched output for Drupal sites in the form of RDFa.
  5. */
  6. use Drupal\Core\Routing\RouteMatchInterface;
  7. use Drupal\Core\Template\Attribute;
  8. use Drupal\rdf\Entity\RdfMapping;
  9. /**
  10. * Implements hook_help().
  11. */
  12. function rdf_help($route_name, RouteMatchInterface $route_match) {
  13. switch ($route_name) {
  14. case 'help.page.rdf':
  15. $output = '';
  16. $output .= '<h3>' . t('About') . '</h3>';
  17. $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>';
  18. return $output;
  19. }
  20. }
  21. /**
  22. * @defgroup rdf RDF Mapping API
  23. * @{
  24. * Functions to describe entities and bundles in RDF.
  25. *
  26. * The RDF module introduces RDF and RDFa to Drupal. RDF is a W3C standard to
  27. * describe structured data. RDF can be serialized as RDFa in XHTML attributes
  28. * to augment visual data with machine-readable hints.
  29. * @see http://www.w3.org/RDF/
  30. * @see http://www.w3.org/TR/xhtml-rdfa-primer/
  31. *
  32. * Modules can provide mappings of their bundles' data and metadata to RDF
  33. * classes and properties. This module takes care of injecting these mappings
  34. * into variables available to theme functions and templates. All Drupal core
  35. * themes are coded to be RDFa compatible.
  36. */
  37. /**
  38. * Returns the RDF mapping object associated with a bundle.
  39. *
  40. * The function reads the rdf_mapping object from the current configuration,
  41. * or returns a ready-to-use empty one if no configuration entry exists yet for
  42. * this bundle. This streamlines the manipulation of mapping objects by always
  43. * returning a consistent object that reflects the current state of the
  44. * configuration.
  45. *
  46. * Example usage:
  47. * -Map the 'article' bundle to 'sioc:Post' and the 'title' field to 'dc:title'.
  48. * @code
  49. * rdf_get_mapping('node', 'article')
  50. * ->setBundleMapping(array(
  51. * 'types' => array('sioc:Post'),
  52. * ))
  53. * ->setFieldMapping('title', array(
  54. * 'properties' => array('dc:title')
  55. * ))
  56. * ->save();
  57. * @endcode
  58. *
  59. * @param string $entity_type
  60. * The entity type.
  61. * @param string $bundle
  62. * The bundle.
  63. *
  64. * @return \Drupal\rdf\Entity\RdfMapping
  65. * The RdfMapping object.
  66. */
  67. function rdf_get_mapping($entity_type, $bundle) {
  68. // Try loading the mapping from configuration.
  69. $mapping = RdfMapping::load($entity_type . '.' . $bundle);
  70. // If not found, create a fresh mapping object.
  71. if (!$mapping) {
  72. $mapping = RdfMapping::create([
  73. 'targetEntityType' => $entity_type,
  74. 'bundle' => $bundle,
  75. ]);
  76. }
  77. return $mapping;
  78. }
  79. /**
  80. * Implements hook_rdf_namespaces().
  81. */
  82. function rdf_rdf_namespaces() {
  83. return [
  84. 'content' => 'http://purl.org/rss/1.0/modules/content/',
  85. 'dc' => 'http://purl.org/dc/terms/',
  86. 'foaf' => 'http://xmlns.com/foaf/0.1/',
  87. 'og' => 'http://ogp.me/ns#',
  88. 'rdfs' => 'http://www.w3.org/2000/01/rdf-schema#',
  89. 'schema' => 'http://schema.org/',
  90. 'sioc' => 'http://rdfs.org/sioc/ns#',
  91. 'sioct' => 'http://rdfs.org/sioc/types#',
  92. 'skos' => 'http://www.w3.org/2004/02/skos/core#',
  93. 'xsd' => 'http://www.w3.org/2001/XMLSchema#',
  94. ];
  95. }
  96. /**
  97. * Retrieves RDF namespaces.
  98. *
  99. * Invokes hook_rdf_namespaces() and collects RDF namespaces from modules that
  100. * implement it.
  101. */
  102. function rdf_get_namespaces() {
  103. $namespaces = [];
  104. // In order to resolve duplicate namespaces by using the earliest defined
  105. // namespace, do not use \Drupal::moduleHandler()->invokeAll().
  106. foreach (\Drupal::moduleHandler()->getImplementations('rdf_namespaces') as $module) {
  107. $function = $module . '_rdf_namespaces';
  108. foreach ($function() as $prefix => $namespace) {
  109. if (array_key_exists($prefix, $namespaces) && $namespace !== $namespaces[$prefix]) {
  110. 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]]));
  111. }
  112. else {
  113. $namespaces[$prefix] = $namespace;
  114. }
  115. }
  116. }
  117. return $namespaces;
  118. }
  119. /**
  120. * @} End of "defgroup rdf".
  121. */
  122. /**
  123. * @addtogroup rdf
  124. * @{
  125. */
  126. /**
  127. * Builds an array of RDFa attributes for a given mapping.
  128. *
  129. * This array will typically be passed through Drupal\Core\Template\Attribute
  130. * to create the attributes variables that are available to template files.
  131. * These include $attributes, $title_attributes, $content_attributes and the
  132. * field-specific $item_attributes variables.
  133. *
  134. * @param array $mapping
  135. * An array containing a mandatory 'properties' key and optional 'datatype',
  136. * 'datatype_callback' and 'type' keys. For example:
  137. * @code
  138. * array(
  139. * 'properties' => array('schema:interactionCount'),
  140. * 'datatype' => 'xsd:integer',
  141. * 'datatype_callback' => array(
  142. * 'callable' => 'Drupal\rdf\SchemaOrgDataConverter::interactionCount',
  143. * 'arguments' => array(
  144. * 'interaction_type' => 'UserComments'
  145. * ),
  146. * ),
  147. * );
  148. * @endcode
  149. * @param mixed $data
  150. * (optional) A value that needs to be converted by the provided callback
  151. * function.
  152. *
  153. * @return array
  154. * RDFa attributes suitable for Drupal\Core\Template\Attribute.
  155. */
  156. function rdf_rdfa_attributes($mapping, $data = NULL) {
  157. $attributes = [];
  158. // The type of mapping defaults to 'property'.
  159. $type = isset($mapping['mapping_type']) ? $mapping['mapping_type'] : 'property';
  160. switch ($type) {
  161. // The mapping expresses the relationship between two resources.
  162. case 'rel':
  163. case 'rev':
  164. $attributes[$type] = $mapping['properties'];
  165. break;
  166. // The mapping expresses the relationship between a resource and some
  167. // literal text.
  168. case 'property':
  169. if (!empty($mapping['properties'])) {
  170. $attributes['property'] = $mapping['properties'];
  171. // Convert $data to a specific format as per the callback function.
  172. if (isset($data) && !empty($mapping['datatype_callback'])) {
  173. $callback = $mapping['datatype_callback']['callable'];
  174. $arguments = isset($mapping['datatype_callback']['arguments']) ? $mapping['datatype_callback']['arguments'] : NULL;
  175. $attributes['content'] = call_user_func($callback, $data, $arguments);
  176. }
  177. if (isset($mapping['datatype'])) {
  178. $attributes['datatype'] = $mapping['datatype'];
  179. }
  180. break;
  181. }
  182. }
  183. return $attributes;
  184. }
  185. /**
  186. * @} End of "addtogroup rdf".
  187. */
  188. /**
  189. * Implements hook_entity_prepare_view().
  190. */
  191. function rdf_entity_prepare_view($entity_type, array $entities, array $displays) {
  192. // Iterate over the RDF mappings for each entity and prepare the RDFa
  193. // attributes to be added inside field formatters.
  194. foreach ($entities as $entity) {
  195. $mapping = rdf_get_mapping($entity_type, $entity->bundle());
  196. // Only prepare the RDFa attributes for the fields which are configured to
  197. // be displayed.
  198. foreach ($displays[$entity->bundle()]->getComponents() as $name => $options) {
  199. $field_mapping = $mapping->getPreparedFieldMapping($name);
  200. if ($field_mapping) {
  201. foreach ($entity->get($name) as $item) {
  202. $item->_attributes += rdf_rdfa_attributes($field_mapping, $item->toArray());
  203. }
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * Implements hook_ENTITY_TYPE_storage_load() for comment entities.
  210. */
  211. function rdf_comment_storage_load($comments) {
  212. foreach ($comments as $comment) {
  213. // Pages with many comments can show poor performance. This information
  214. // isn't needed until rdf_preprocess_comment() is called, but set it here
  215. // to optimize performance for websites that implement an entity cache.
  216. $created_mapping = rdf_get_mapping('comment', $comment->bundle())
  217. ->getPreparedFieldMapping('created');
  218. /** @var \Drupal\comment\CommentInterface $comment*/
  219. $comment->rdf_data['date'] = rdf_rdfa_attributes($created_mapping, $comment->get('created')->first()->toArray());
  220. $entity = $comment->getCommentedEntity();
  221. // The current function is a storage level hook, so avoid to bubble
  222. // bubbleable metadata, because it can be outside of a render context.
  223. $comment->rdf_data['entity_uri'] = $entity->toUrl()->toString(TRUE)->getGeneratedUrl();
  224. if ($comment->hasParentComment()) {
  225. $comment->rdf_data['pid_uri'] = $comment->getParentComment()->url();
  226. }
  227. }
  228. }
  229. /**
  230. * Implements hook_theme().
  231. */
  232. function rdf_theme() {
  233. return [
  234. 'rdf_wrapper' => [
  235. 'variables' => ['attributes' => [], 'content' => NULL],
  236. ],
  237. 'rdf_metadata' => [
  238. 'variables' => ['metadata' => []],
  239. ],
  240. ];
  241. }
  242. /**
  243. * Implements hook_preprocess_HOOK() for HTML document templates.
  244. */
  245. function rdf_preprocess_html(&$variables) {
  246. // Adds RDF namespace prefix bindings in the form of an RDFa 1.1 prefix
  247. // attribute inside the html element.
  248. if (!isset($variables['html_attributes']['prefix'])) {
  249. $variables['html_attributes']['prefix'] = [];
  250. }
  251. foreach (rdf_get_namespaces() as $prefix => $uri) {
  252. $variables['html_attributes']['prefix'][] = $prefix . ': ' . $uri . " ";
  253. }
  254. }
  255. /**
  256. * Implements hook_preprocess_HOOK() for UID field templates.
  257. */
  258. function rdf_preprocess_field__node__uid(&$variables) {
  259. _rdf_set_field_rel_attribute($variables);
  260. }
  261. /**
  262. * Transforms the field property attribute into a rel attribute.
  263. */
  264. function _rdf_set_field_rel_attribute(&$variables) {
  265. // Swap the regular field property attribute and use the rel attribute
  266. // instead so that it plays well with the RDFa markup when only a link is
  267. // present in the field output, for example in the case of the uid field.
  268. if (!empty($variables['attributes']['property'])) {
  269. $variables['attributes']['rel'] = $variables['attributes']['property'];
  270. unset($variables['attributes']['property']);
  271. }
  272. }
  273. /**
  274. * Implements hook_preprocess_HOOK() for node templates.
  275. */
  276. function rdf_preprocess_node(&$variables) {
  277. // Adds RDFa markup to the node container. The about attribute specifies the
  278. // URI of the resource described within the HTML element, while the @typeof
  279. // attribute indicates its RDF type (e.g., foaf:Document, sioc:Person, and so
  280. // on.)
  281. $bundle = $variables['node']->bundle();
  282. $mapping = rdf_get_mapping('node', $bundle);
  283. $bundle_mapping = $mapping->getPreparedBundleMapping('node', $bundle);
  284. $variables['attributes']['about'] = empty($variables['url']) ? NULL : $variables['url'];
  285. $variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
  286. // Adds RDFa markup for the node title as metadata because wrapping the title
  287. // with markup is not reliable and the title output is different depending on
  288. // the view mode (e.g. full vs. teaser).
  289. $title_mapping = $mapping->getPreparedFieldMapping('title');
  290. if ($title_mapping) {
  291. $title_attributes['property'] = empty($title_mapping['properties']) ? NULL : $title_mapping['properties'];
  292. $title_attributes['content'] = $variables['node']->label();
  293. $variables['title_suffix']['rdf_meta_title'] = [
  294. '#theme' => 'rdf_metadata',
  295. '#metadata' => [$title_attributes],
  296. ];
  297. }
  298. // Adds RDFa markup for the date.
  299. $created_mapping = $mapping->getPreparedFieldMapping('created');
  300. if (!empty($created_mapping) && $variables['display_submitted']) {
  301. $date_attributes = rdf_rdfa_attributes($created_mapping, $variables['node']->get('created')->first()->toArray());
  302. $rdf_metadata = [
  303. '#theme' => 'rdf_metadata',
  304. '#metadata' => [$date_attributes],
  305. ];
  306. $variables['metadata'] = \Drupal::service('renderer')->render($rdf_metadata);
  307. }
  308. // Adds RDFa markup annotating the number of comments a node has.
  309. if (\Drupal::moduleHandler()->moduleExists('comment') && \Drupal::currentUser()->hasPermission('access comments')) {
  310. $comment_count_mapping = $mapping->getPreparedFieldMapping('comment_count');
  311. if (!empty($comment_count_mapping['properties'])) {
  312. $fields = array_keys(\Drupal::service('comment.manager')->getFields('node'));
  313. $definitions = array_keys($variables['node']->getFieldDefinitions());
  314. $valid_fields = array_intersect($fields, $definitions);
  315. $count = 0;
  316. foreach ($valid_fields as $field_name) {
  317. $count += $variables['node']->get($field_name)->comment_count;
  318. // Adds RDFa markup for the comment count near the node title as
  319. // metadata.
  320. $comment_count_attributes = rdf_rdfa_attributes($comment_count_mapping, $variables['node']->get($field_name)->comment_count);
  321. $variables['title_suffix']['rdf_meta_comment_count'] = [
  322. '#theme' => 'rdf_metadata',
  323. '#metadata' => [$comment_count_attributes],
  324. ];
  325. }
  326. }
  327. }
  328. }
  329. /**
  330. * Implements hook_preprocess_HOOK() for user templates.
  331. */
  332. function rdf_preprocess_user(&$variables) {
  333. /** @var $account \Drupal\user\UserInterface */
  334. $account = $variables['elements']['#user'];
  335. $uri = $account->urlInfo();
  336. $mapping = rdf_get_mapping('user', 'user');
  337. $bundle_mapping = $mapping->getPreparedBundleMapping();
  338. // Adds RDFa markup to the user profile page. Fields displayed in this page
  339. // will automatically describe the user.
  340. if (!empty($bundle_mapping['types'])) {
  341. $variables['attributes']['typeof'] = $bundle_mapping['types'];
  342. $variables['attributes']['about'] = $account->url();
  343. }
  344. // If we are on the user account page, add the relationship between the
  345. // sioc:UserAccount and the foaf:Person who holds the account.
  346. if (\Drupal::routeMatch()->getRouteName() == $uri->getRouteName()) {
  347. // Adds the markup for username as language neutral literal, see
  348. // rdf_preprocess_username().
  349. $name_mapping = $mapping->getPreparedFieldMapping('name');
  350. if (!empty($name_mapping['properties'])) {
  351. $username_meta = [
  352. '#tag' => 'meta',
  353. '#attributes' => [
  354. 'about' => $account->url(),
  355. 'property' => $name_mapping['properties'],
  356. 'content' => $account->getDisplayName(),
  357. 'lang' => '',
  358. ],
  359. ];
  360. $variables['#attached']['html_head'][] = [$username_meta, 'rdf_user_username'];
  361. }
  362. }
  363. }
  364. /**
  365. * Implements hook_preprocess_HOOK() for username.html.twig.
  366. */
  367. function rdf_preprocess_username(&$variables) {
  368. // Because lang is set on the HTML element that wraps the page, the
  369. // username inherits this language attribute. However, since the username
  370. // might not be transliterated to the same language that the content is in,
  371. // we do not want it to inherit the language attribute, so we set the
  372. // attribute to an empty string.
  373. if (empty($variables['attributes']['lang'])) {
  374. $variables['attributes']['lang'] = '';
  375. }
  376. // The profile URI is used to identify the user account. The about attribute
  377. // is used to set the URI as the default subject of the properties embedded
  378. // as RDFa in the child elements. Even if the user profile is not accessible
  379. // to the current user, we use its URI in order to identify the user in RDF.
  380. // We do not use this attribute for the anonymous user because we do not have
  381. // a user profile URI for it (only a homepage which cannot be used as user
  382. // profile in RDF.)
  383. if ($variables['uid'] > 0) {
  384. $variables['attributes']['about'] = \Drupal::url('entity.user.canonical', ['user' => $variables['uid']]);
  385. }
  386. // Add RDF type of user.
  387. $mapping = rdf_get_mapping('user', 'user');
  388. $bundle_mapping = $mapping->getPreparedBundleMapping();
  389. if (!empty($bundle_mapping['types'])) {
  390. $variables['attributes']['typeof'] = $bundle_mapping['types'];
  391. }
  392. // Annotate the username in RDFa. A property attribute is used with an empty
  393. // datatype attribute to ensure the username is parsed as a plain literal
  394. // in RDFa 1.0 and 1.1.
  395. $name_mapping = $mapping->getPreparedFieldMapping('name');
  396. if (!empty($name_mapping)) {
  397. $variables['attributes']['property'] = $name_mapping['properties'];
  398. $variables['attributes']['datatype'] = '';
  399. }
  400. // Add the homepage RDFa markup if present.
  401. $homepage_mapping = $mapping->getPreparedFieldMapping('homepage');
  402. if (!empty($variables['homepage']) && !empty($homepage_mapping)) {
  403. $variables['attributes']['rel'] = $homepage_mapping['properties'];
  404. }
  405. // Long usernames are truncated by template_preprocess_username(). Store the
  406. // full name in the content attribute so it can be extracted in RDFa.
  407. if ($variables['truncated']) {
  408. $variables['attributes']['content'] = $variables['name_raw'];
  409. }
  410. }
  411. /**
  412. * Implements hook_preprocess_HOOK() for comment templates.
  413. */
  414. function rdf_preprocess_comment(&$variables) {
  415. $comment = $variables['comment'];
  416. $mapping = rdf_get_mapping('comment', $comment->bundle());
  417. $bundle_mapping = $mapping->getPreparedBundleMapping();
  418. if (!empty($bundle_mapping['types']) && !isset($comment->in_preview)) {
  419. // Adds RDFa markup to the comment container. The about attribute specifies
  420. // the URI of the resource described within the HTML element, while the
  421. // typeof attribute indicates its RDF type (e.g., sioc:Post, foaf:Document,
  422. // and so on.)
  423. $variables['attributes']['about'] = $comment->url();
  424. $variables['attributes']['typeof'] = $bundle_mapping['types'];
  425. }
  426. // Adds RDFa markup for the relation between the comment and its author.
  427. $author_mapping = $mapping->getPreparedFieldMapping('uid');
  428. if (!empty($author_mapping)) {
  429. $author_attributes = ['rel' => $author_mapping['properties']];
  430. // Wraps the 'author' and 'submitted' variables which are both available in
  431. // comment.html.twig.
  432. $variables['author'] = [
  433. '#theme' => 'rdf_wrapper',
  434. '#content' => $variables['author'],
  435. '#attributes' => $author_attributes,
  436. ];
  437. $variables['submitted'] = [
  438. '#theme' => 'rdf_wrapper',
  439. '#content' => $variables['submitted'],
  440. '#attributes' => $author_attributes,
  441. ];
  442. }
  443. // Adds RDFa markup for the date of the comment.
  444. $created_mapping = $mapping->getPreparedFieldMapping('created');
  445. if (!empty($created_mapping)) {
  446. // The comment date is precomputed as part of the rdf_data so that it can be
  447. // cached as part of the entity.
  448. $date_attributes = $comment->rdf_data['date'];
  449. $rdf_metadata = [
  450. '#theme' => 'rdf_metadata',
  451. '#metadata' => [$date_attributes],
  452. ];
  453. // Ensure the original variable is represented as a render array.
  454. $created = !is_array($variables['created']) ? ['#markup' => $variables['created']] : $variables['created'];
  455. $submitted = !is_array($variables['submitted']) ? ['#markup' => $variables['submitted']] : $variables['submitted'];
  456. // Make render array and RDF metadata available in comment.html.twig.
  457. $variables['created'] = [$created, $rdf_metadata];
  458. $variables['submitted'] = [$submitted, $rdf_metadata];
  459. }
  460. $title_mapping = $mapping->getPreparedFieldMapping('subject');
  461. if (!empty($title_mapping)) {
  462. // Adds RDFa markup to the subject of the comment. Because the RDFa markup
  463. // is added to an <h3> tag which might contain HTML code, we specify an
  464. // empty datatype to ensure the value of the title read by the RDFa parsers
  465. // is a literal.
  466. $variables['title_attributes']['property'] = $title_mapping['properties'];
  467. $variables['title_attributes']['datatype'] = '';
  468. }
  469. // Annotates the parent relationship between the current comment and the node
  470. // it belongs to. If available, the parent comment is also annotated.
  471. // @todo When comments are turned into fields, this should be changed.
  472. // Currently there is no mapping relating a comment to its node.
  473. $pid_mapping = $mapping->getPreparedFieldMapping('pid');
  474. if (!empty($pid_mapping)) {
  475. // Adds the relation to the parent entity.
  476. $parent_entity_attributes['rel'] = $pid_mapping['properties'];
  477. // The parent entity URI is precomputed as part of the rdf_data so that it
  478. // can be cached as part of the entity.
  479. $parent_entity_attributes['resource'] = $comment->rdf_data['entity_uri'];
  480. $variables['rdf_metadata_attributes'][] = $parent_entity_attributes;
  481. // Adds the relation to parent comment, if it exists.
  482. if ($comment->hasParentComment()) {
  483. $parent_comment_attributes['rel'] = $pid_mapping['properties'];
  484. // The parent comment URI is precomputed as part of the rdf_data so that
  485. // it can be cached as part of the entity.
  486. $parent_comment_attributes['resource'] = $comment->rdf_data['pid_uri'];
  487. $variables['rdf_metadata_attributes'][] = $parent_comment_attributes;
  488. }
  489. }
  490. // Adds RDF metadata markup above comment body if any.
  491. if (!empty($variables['rdf_metadata_attributes']) && isset($variables['content']['comment_body'])) {
  492. $rdf_metadata = [
  493. '#theme' => 'rdf_metadata',
  494. '#metadata' => $variables['rdf_metadata_attributes'],
  495. ];
  496. if (!empty($variables['content']['comment_body']['#prefix'])) {
  497. $rdf_metadata['#suffix'] = $variables['content']['comment_body']['#prefix'];
  498. }
  499. $variables['content']['comment_body']['#prefix'] = \Drupal::service('renderer')->render($rdf_metadata);
  500. }
  501. }
  502. /**
  503. * Implements hook_preprocess_HOOK() for taxonomy term templates.
  504. */
  505. function rdf_preprocess_taxonomy_term(&$variables) {
  506. // Adds RDFa markup to the taxonomy term container.
  507. // The @about attribute specifies the URI of the resource described within
  508. // the HTML element, while the @typeof attribute indicates its RDF type
  509. // (e.g., schema:Thing, skos:Concept, and so on).
  510. $term = $variables['term'];
  511. $mapping = rdf_get_mapping('taxonomy_term', $term->bundle());
  512. $bundle_mapping = $mapping->getPreparedBundleMapping();
  513. $variables['attributes']['about'] = $term->url();
  514. $variables['attributes']['typeof'] = empty($bundle_mapping['types']) ? NULL : $bundle_mapping['types'];
  515. // Add RDFa markup for the taxonomy term name as metadata, if present.
  516. $name_field_mapping = $mapping->getPreparedFieldMapping('name');
  517. if (!empty($name_field_mapping) && !empty($name_field_mapping['properties'])) {
  518. $name_attributes = [
  519. 'property' => $name_field_mapping['properties'],
  520. 'content' => $term->getName(),
  521. ];
  522. $variables['title_suffix']['taxonomy_term_rdfa'] = [
  523. '#theme' => 'rdf_metadata',
  524. '#metadata' => [$name_attributes],
  525. ];
  526. }
  527. }
  528. /**
  529. * Implements hook_preprocess_HOOK() for image.html.twig.
  530. */
  531. function rdf_preprocess_image(&$variables) {
  532. // Adds the RDF type for image. We cannot use the usual entity-based mapping
  533. // to get 'foaf:Image' because image does not have its own entity type or
  534. // bundle.
  535. $variables['attributes']['typeof'] = ['foaf:Image'];
  536. }
  537. /**
  538. * Prepares variables for RDF metadata templates.
  539. *
  540. * Default template: rdf-metadata.html.twig.
  541. *
  542. * Sometimes it is useful to export data which is not semantically present in
  543. * the HTML output. For example, a hierarchy of comments is visible for a human
  544. * but not for machines because this hierarchy is not present in the DOM tree.
  545. * We can express it in RDFa via empty <span> tags. These aren't visible and
  546. * give machines extra information about the content and its structure.
  547. *
  548. * @param array $variables
  549. * An associative array containing:
  550. * - metadata: An array of attribute arrays. Each item in the array
  551. * corresponds to its own set of attributes, and therefore, needs its own
  552. * element.
  553. */
  554. function template_preprocess_rdf_metadata(&$variables) {
  555. foreach ($variables['metadata'] as $key => $attributes) {
  556. if (!is_null($attributes)) {
  557. $variables['metadata'][$key] = new Attribute($attributes);
  558. }
  559. else {
  560. $variables['metadata'][$key] = new Attribute();
  561. }
  562. }
  563. }