rdf.module 25 KB

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