Projet

Général

Profil

Paste
Télécharger (34,7 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / rdf / rdf.module @ 85ad3d82

1
<?php
2

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

    
8
/**
9
 * Implements hook_help().
10
 */
11
function rdf_help($path, $arg) {
12
  switch ($path) {
13
    case 'admin/help#rdf':
14
      $output = '';
15
      $output .= '<h3>' . t('About') . '</h3>';
16
      $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 Drupal sites 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 Drupal modules define RDF mappings for their data model, and the core Drupal themes output this RDF metadata information along with the human-readable visual information. For more information, see the online handbook entry for <a href="@rdf">RDF module</a>.', array('@rdfa' => 'http://www.w3.org/TR/xhtml-rdfa-primer/', '@rdf' => 'http://drupal.org/documentation/modules/rdf')) . '</p>';
17
      return $output;
18
  }
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
 * Example mapping from node.module:
38
 * @code
39
 *   array(
40
 *     'type' => 'node',
41
 *     'bundle' => RDF_DEFAULT_BUNDLE,
42
 *     'mapping' => array(
43
 *       'rdftype' => array('sioc:Item', 'foaf:Document'),
44
 *       'title' => array(
45
 *         'predicates' => array('dc:title'),
46
 *       ),
47
 *       'created' => array(
48
 *         'predicates' => array('dc:date', 'dc:created'),
49
 *         'datatype' => 'xsd:dateTime',
50
 *         'callback' => 'date_iso8601',
51
 *       ),
52
 *      'body' => array(
53
 *         'predicates' => array('content:encoded'),
54
 *       ),
55
 *       'uid' => array(
56
 *         'predicates' => array('sioc:has_creator'),
57
 *       ),
58
 *       'name' => array(
59
 *         'predicates' => array('foaf:name'),
60
 *       ),
61
 *     ),
62
 *   );
63
 * @endcode
64
 */
65

    
66
/**
67
 * RDF bundle flag: Default bundle.
68
 *
69
 * Implementations of hook_rdf_mapping() should use this constant for the
70
 * 'bundle' key when defining a default set of RDF mappings for an entity type.
71
 * Each bundle will inherit the default mappings defined for the entity type
72
 * unless the bundle defines its own specific mappings.
73
 */
74
define('RDF_DEFAULT_BUNDLE', '');
75

    
76
/**
77
 * Implements hook_rdf_namespaces().
78
 */
79
function rdf_rdf_namespaces() {
80
  return array(
81
    'content'  => 'http://purl.org/rss/1.0/modules/content/',
82
    'dc'       => 'http://purl.org/dc/terms/',
83
    'foaf'     => 'http://xmlns.com/foaf/0.1/',
84
    'og'       => 'http://ogp.me/ns#',
85
    'rdfs'     => 'http://www.w3.org/2000/01/rdf-schema#',
86
    'sioc'     => 'http://rdfs.org/sioc/ns#',
87
    'sioct'    => 'http://rdfs.org/sioc/types#',
88
    'skos'     => 'http://www.w3.org/2004/02/skos/core#',
89
    'xsd'      => 'http://www.w3.org/2001/XMLSchema#',
90
  );
91
}
92

    
93
/**
94
 * Returns an array of RDF namespaces defined in modules that implement
95
 * hook_rdf_namespaces().
96
 */
97
function rdf_get_namespaces() {
98
  $rdf_namespaces = module_invoke_all('rdf_namespaces');
99
  // module_invoke_all() uses array_merge_recursive() which might return nested
100
  // arrays if several modules redefine the same prefix multiple times. We need
101
  // to ensure the array of namespaces is flat and only contains strings as
102
  // URIs.
103
  foreach ($rdf_namespaces as $prefix => $uri) {
104
    if (is_array($uri)) {
105
      if (count(array_unique($uri)) == 1) {
106
        // All namespaces declared for this prefix are the same, merge them all
107
        // into a single namespace.
108
        $rdf_namespaces[$prefix] = $uri[0];
109
      }
110
      else {
111
        // There are conflicting namespaces for this prefix, do not include
112
        // duplicates in order to avoid asserting any inaccurate RDF
113
        // statements.
114
        unset($rdf_namespaces[$prefix]);
115
      }
116
    }
117
  }
118
  return $rdf_namespaces;
119
}
120

    
121
/**
122
 * Returns the mapping for attributes of a given entity type/bundle pair.
123
 *
124
 * @param $type
125
 *   An entity type.
126
 * @param $bundle
127
 *   (optional) A bundle name.
128
 *
129
 * @return
130
 *   The mapping corresponding to the requested entity type/bundle pair or an
131
 *   empty array.
132
 */
133
function rdf_mapping_load($type, $bundle = RDF_DEFAULT_BUNDLE) {
134
  // Retrieves the bundle-specific mapping from the entity info.
135
  $entity_info = entity_get_info($type);
136
  if (!empty($entity_info['bundles'][$bundle]['rdf_mapping'])) {
137
    return $entity_info['bundles'][$bundle]['rdf_mapping'];
138
  }
139
  // If there is no mapping defined for this bundle, we return the default
140
  // mapping that is defined for this entity type.
141
  else {
142
    return _rdf_get_default_mapping($type);
143
  }
144
}
145

    
146
/**
147
 * @} End of "defgroup rdf".
148
 */
149

    
150
/**
151
 * Helper function to get the default RDF mapping for a given entity type.
152
 *
153
 * @param $type
154
 *   An entity type, e.g. 'node' or 'comment'.
155
 *
156
 * @return
157
 *   The RDF mapping or an empty array if no mapping is defined for this entity
158
 *   type.
159
 */
160
function _rdf_get_default_mapping($type) {
161
  $default_mappings = &drupal_static(__FUNCTION__);
162

    
163
  if (!isset($default_mappings)) {
164
    // Get all of the modules that implement hook_rdf_mapping().
165
    $modules = module_implements('rdf_mapping');
166

    
167
    // Only consider the default entity mapping definitions.
168
    foreach ($modules as $module) {
169
      $mappings = module_invoke($module, 'rdf_mapping');
170
      foreach ($mappings as $mapping) {
171
        if ($mapping['bundle'] === RDF_DEFAULT_BUNDLE) {
172
          $default_mappings[$mapping['type']] = $mapping['mapping'];
173
        }
174
      }
175
    }
176
  }
177

    
178
  return isset($default_mappings[$type]) ? $default_mappings[$type] : array();
179
}
180

    
181
/**
182
 * Helper function to retrieve an RDF mapping from the database.
183
 *
184
 * @param $type
185
 *   The entity type the mapping refers to.
186
 * @param $bundle
187
 *   The bundle the mapping refers to.
188
 *
189
 * @return
190
 *   An RDF mapping structure or an empty array if no record was found.
191
 */
192
function _rdf_mapping_load($type, $bundle) {
193
  $mapping = db_select('rdf_mapping')
194
    ->fields(NULL, array('mapping'))
195
    ->condition('type', $type)
196
    ->condition('bundle', $bundle)
197
    ->execute()
198
    ->fetchField();
199

    
200
  if (!$mapping) {
201
    return array();
202
  }
203
  return unserialize($mapping);
204
}
205

    
206
/**
207
 * @addtogroup rdf
208
 * @{
209
 */
210

    
211
/**
212
 * Saves an RDF mapping to the database.
213
 *
214
 * Takes a mapping structure returned by hook_rdf_mapping() implementations
215
 * and creates or updates a record mapping for each encountered entity
216
 * type/bundle pair. If available, adds default values for non-existent mapping
217
 * keys.
218
 *
219
 * @param $mapping
220
 *   The RDF mapping to save, as an array.
221
 *
222
 * @return
223
 *   Status flag indicating the outcome of the operation.
224
 */
225
function rdf_mapping_save($mapping) {
226
  // In the case where a field has a mapping defined in the default entity
227
  // mapping, but a mapping is not specified in the bundle-specific mapping,
228
  // then use the default mapping for that field.
229
  $mapping['mapping'] += _rdf_get_default_mapping($mapping['type']);
230

    
231
  $status = db_merge('rdf_mapping')
232
    ->key(array(
233
      'type' => $mapping['type'],
234
      'bundle' => $mapping['bundle'],
235
    ))
236
    ->fields(array(
237
      'mapping' => serialize($mapping['mapping']),
238
    ))
239
    ->execute();
240

    
241
  entity_info_cache_clear();
242

    
243
  return $status;
244
}
245

    
246
/**
247
 * Deletes the mapping for the given bundle from the database.
248
 *
249
 * @param $type
250
 *   The entity type the mapping refers to.
251
 * @param $bundle
252
 *   The bundle the mapping refers to.
253
 *
254
 * @return
255
 *   Return boolean TRUE if mapping deleted, FALSE if not.
256
 */
257
function rdf_mapping_delete($type, $bundle) {
258
  $num_rows = db_delete('rdf_mapping')
259
    ->condition('type', $type)
260
    ->condition('bundle', $bundle)
261
    ->execute();
262

    
263
  return (bool) ($num_rows > 0);
264
}
265

    
266
/**
267
 * Builds an array of RDFa attributes for a given mapping. This array will
268
 * typically be passed through drupal_attributes() to create the attributes
269
 * variables that are available to template files. These include $attributes,
270
 * $title_attributes, $content_attributes and the field-specific
271
 * $item_attributes variables. For more information, see
272
 * theme_rdf_template_variable_wrapper().
273
 *
274
 * @param $mapping
275
 *   An array containing a mandatory 'predicates' key and optional 'datatype',
276
 *   'callback' and 'type' keys. For example:
277
 *   @code
278
 *     array(
279
 *       'predicates' => array('dc:created'),
280
 *       'datatype' => 'xsd:dateTime',
281
 *       'callback' => 'date_iso8601',
282
 *       ),
283
 *     );
284
 *   @endcode
285
 * @param $data
286
 *   A value that needs to be converted by the provided callback function.
287
 *
288
 * @return
289
 *   An array containing RDFa attributes suitable for drupal_attributes().
290
 */
291
function rdf_rdfa_attributes($mapping, $data = NULL) {
292
  // The type of mapping defaults to 'property'.
293
  $type = isset($mapping['type']) ? $mapping['type'] : 'property';
294

    
295
  switch ($type) {
296
    // The mapping expresses the relationship between two resources.
297
    case 'rel':
298
    case 'rev':
299
      $attributes[$type] = $mapping['predicates'];
300
      break;
301

    
302
    // The mapping expresses the relationship between a resource and some
303
    // literal text.
304
    case 'property':
305
      $attributes['property'] = $mapping['predicates'];
306
      // Convert $data to a specific format as per the callback function.
307
      if (isset($data) && isset($mapping['callback']) && function_exists($mapping['callback'])) {
308
        $callback = $mapping['callback'];
309
        $attributes['content'] = $callback($data);
310
      }
311
      if (isset($mapping['datatype'])) {
312
        $attributes['datatype'] = $mapping['datatype'];
313
      }
314
      break;
315
  }
316

    
317
  return $attributes;
318
}
319

    
320
/**
321
 * @} End of "addtogroup rdf".
322
 */
323

    
324
/**
325
 * Implements hook_modules_installed().
326
 *
327
 * Checks if the installed modules have any RDF mapping definitions to declare
328
 * and stores them in the rdf_mapping table.
329
 *
330
 * While both default entity mappings and specific bundle mappings can be
331
 * defined in hook_rdf_mapping(), default entity mappings are not stored in the
332
 * database. Only overridden mappings are stored in the database. The default
333
 * entity mappings can be overriden by specific bundle mappings which are
334
 * stored in the database and can be altered via the RDF CRUD mapping API.
335
 */
336
function rdf_modules_installed($modules) {
337
  foreach ($modules as $module) {
338
    $function = $module . '_rdf_mapping';
339
    if (function_exists($function)) {
340
      foreach ($function() as $mapping) {
341
        // Only the bundle mappings are saved in the database.
342
        if ($mapping['bundle'] !== RDF_DEFAULT_BUNDLE) {
343
          rdf_mapping_save($mapping);
344
        }
345
      }
346
    }
347
  }
348
}
349

    
350
/**
351
 * Implements hook_modules_uninstalled().
352
 */
353
function rdf_modules_uninstalled($modules) {
354
  // @todo Remove RDF mappings of uninstalled modules.
355
}
356

    
357
/**
358
 * Implements hook_entity_info_alter().
359
 *
360
 * Adds the proper RDF mapping to each entity type/bundle pair.
361
 *
362
 * @todo May need to move the comment below to another place.
363
 * This hook should not be used by modules to alter the bundle mappings.
364
 * The UI should always be authoritative. UI mappings are stored in the
365
 * database and if hook_entity_info_alter was used to override module defined
366
 * mappings, it would override the user defined mapping as well.
367
 */
368
function rdf_entity_info_alter(&$entity_info) {
369
  // Loop through each entity type and its bundles.
370
  foreach ($entity_info as $entity_type => $entity_type_info) {
371
    if (isset($entity_type_info['bundles'])) {
372
      foreach ($entity_type_info['bundles'] as $bundle => $bundle_info) {
373
        if ($mapping = _rdf_mapping_load($entity_type, $bundle)) {
374
          $entity_info[$entity_type]['bundles'][$bundle]['rdf_mapping'] = $mapping;
375
        }
376
        else {
377
          // If no mapping was found in the database, assign the default RDF
378
          // mapping for this entity type.
379
          $entity_info[$entity_type]['bundles'][$bundle]['rdf_mapping'] = _rdf_get_default_mapping($entity_type);
380
        }
381
      }
382
    }
383
  }
384
}
385

    
386
/**
387
 * Implements hook_entity_load().
388
 */
389
function rdf_entity_load($entities, $type) {
390
  foreach ($entities as $entity) {
391
    // Extracts the bundle of the entity being loaded.
392
    list($id, $vid, $bundle) = entity_extract_ids($type, $entity);
393
    $entity->rdf_mapping = rdf_mapping_load($type, $bundle);
394
  }
395
}
396

    
397
/**
398
 * Implements hook_comment_load().
399
 */
400
function rdf_comment_load($comments) {
401
  foreach ($comments as $comment) {
402
    // Pages with many comments can show poor performance. This information
403
    // isn't needed until rdf_preprocess_comment() is called, but set it here
404
    // to optimize performance for websites that implement an entity cache.
405
    $comment->rdf_data['date'] = rdf_rdfa_attributes($comment->rdf_mapping['created'], $comment->created);
406
    $comment->rdf_data['nid_uri'] = url('node/' . $comment->nid);
407
    if ($comment->pid) {
408
      $comment->rdf_data['pid_uri'] = url('comment/' . $comment->pid, array('fragment' => 'comment-' . $comment->pid));
409
    }
410
  }
411
}
412

    
413
/**
414
 * Implements hook_theme().
415
 */
416
function rdf_theme() {
417
  return array(
418
    'rdf_template_variable_wrapper' => array(
419
      'variables' => array('content' => NULL, 'attributes' => array(), 'context' => array(), 'inline' => TRUE),
420
    ),
421
    'rdf_metadata' => array(
422
      'variables' => array('metadata' => array()),
423
    ),
424
  );
425
}
426

    
427
/**
428
 * Template process function for adding extra tags to hold RDFa attributes.
429
 *
430
 * Since template files already have built-in support for $attributes,
431
 * $title_attributes, and $content_attributes, and field templates have support
432
 * for $item_attributes, we try to leverage those as much as possible. However,
433
 * in some cases additional attributes are needed not covered by these. We deal
434
 * with those here.
435
 */
436
function rdf_process(&$variables, $hook) {
437
  // Handles attributes needed for content not covered by title, content,
438
  // and field items. It does this by adjusting the variable sent to the
439
  // template so that the template doesn't have to worry about it. See
440
  // theme_rdf_template_variable_wrapper().
441
  if (!empty($variables['rdf_template_variable_attributes_array'])) {
442
    foreach ($variables['rdf_template_variable_attributes_array'] as $variable_name => $attributes) {
443
      $context = array(
444
        'hook' => $hook,
445
        'variable_name' => $variable_name,
446
        'variables' => $variables,
447
      );
448
      $variables[$variable_name] = theme('rdf_template_variable_wrapper', array('content' => $variables[$variable_name], 'attributes' => $attributes, 'context' => $context));
449
    }
450
  }
451
  // Handles additional attributes about a template entity that for RDF parsing
452
  // reasons, can't be placed into that template's $attributes variable. This
453
  // is "meta" information that is related to particular content, so render it
454
  // close to that content.
455
  if (!empty($variables['rdf_metadata_attributes_array'])) {
456
    if (!isset($variables['content']['#prefix'])) {
457
      $variables['content']['#prefix'] = '';
458
    }
459
    $variables['content']['#prefix'] = theme('rdf_metadata', array('metadata' => $variables['rdf_metadata_attributes_array'])) . $variables['content']['#prefix'];
460
  }
461
}
462

    
463
/**
464
 * Implements MODULE_preprocess_HOOK().
465
 */
466
function rdf_preprocess_node(&$variables) {
467
  // Adds RDFa markup to the node container. The about attribute specifies the
468
  // URI of the resource described within the HTML element, while the @typeof
469
  // attribute indicates its RDF type (e.g., foaf:Document, sioc:Person, and so
470
  // on.)
471
  $variables['attributes_array']['about'] = empty($variables['node_url']) ? NULL: $variables['node_url'];
472
  $variables['attributes_array']['typeof'] = empty($variables['node']->rdf_mapping['rdftype']) ? NULL : $variables['node']->rdf_mapping['rdftype'];
473

    
474
  // Adds RDFa markup to the title of the node. Because the RDFa markup is
475
  // added to the <h2> tag which might contain HTML code, we specify an empty
476
  // datatype to ensure the value of the title read by the RDFa parsers is a
477
  // literal.
478
  $variables['title_attributes_array']['property'] = empty($variables['node']->rdf_mapping['title']['predicates']) ? NULL : $variables['node']->rdf_mapping['title']['predicates'];
479
  $variables['title_attributes_array']['datatype'] = '';
480

    
481
  // In full node mode, the title is not displayed by node.tpl.php so it is
482
  // added in the <head> tag of the HTML page.
483
  if ($variables['page']) {
484
    $element = array(
485
      '#tag' => 'meta',
486
      '#attributes' => array(
487
        'content' => $variables['node']->title,
488
        'about' => $variables['node_url'],
489
      ),
490
    );
491
    if (!empty($variables['node']->rdf_mapping['title']['predicates'])) {
492
      $element['#attributes']['property'] = $variables['node']->rdf_mapping['title']['predicates'];
493
    }
494
    drupal_add_html_head($element, 'rdf_node_title');
495
  }
496

    
497
  // Adds RDFa markup for the date.
498
  if (!empty($variables['rdf_mapping']['created'])) {
499
    $date_attributes_array = rdf_rdfa_attributes($variables['rdf_mapping']['created'], $variables['created']);
500
    $variables['rdf_template_variable_attributes_array']['date'] = $date_attributes_array;
501
    if ($variables['submitted']) {
502
      $variables['rdf_template_variable_attributes_array']['submitted'] = $date_attributes_array;
503
    }
504
  }
505
  // Adds RDFa markup for the relation between the node and its author.
506
  if (!empty($variables['rdf_mapping']['uid'])) {
507
    $variables['rdf_template_variable_attributes_array']['name']['rel'] = $variables['rdf_mapping']['uid']['predicates'];
508
    if ($variables['submitted']) {
509
      $variables['rdf_template_variable_attributes_array']['submitted']['rel'] = $variables['rdf_mapping']['uid']['predicates'];
510
    }
511
  }
512

    
513
  // Adds RDFa markup annotating the number of comments a node has.
514
  if (isset($variables['node']->comment_count) && !empty($variables['node']->rdf_mapping['comment_count']['predicates'])) {
515
    // Annotates the 'x comments' link in teaser view.
516
    if (isset($variables['content']['links']['comment']['#links']['comment-comments'])) {
517
      $comment_count_attributes['property'] = $variables['node']->rdf_mapping['comment_count']['predicates'];
518
      $comment_count_attributes['content'] = $variables['node']->comment_count;
519
      $comment_count_attributes['datatype'] = $variables['node']->rdf_mapping['comment_count']['datatype'];
520
      // According to RDFa parsing rule number 4, a new subject URI is created
521
      // from the href attribute if no rel/rev attribute is present. To get the
522
      // original node URL from the about attribute of the parent container we
523
      // set an empty rel attribute which triggers rule number 5. See
524
      // http://www.w3.org/TR/rdfa-syntax/#sec_5.5.
525
      $comment_count_attributes['rel'] = '';
526
      $variables['content']['links']['comment']['#links']['comment-comments']['attributes'] += $comment_count_attributes;
527
    }
528
    // In full node view, the number of comments is not displayed by
529
    // node.tpl.php so it is expressed in RDFa in the <head> tag of the HTML
530
    // page.
531
    if ($variables['page'] && user_access('access comments')) {
532
      $element = array(
533
        '#tag' => 'meta',
534
        '#attributes' => array(
535
          'about' => $variables['node_url'],
536
          'property' => $variables['node']->rdf_mapping['comment_count']['predicates'],
537
          'content' => $variables['node']->comment_count,
538
          'datatype' => $variables['node']->rdf_mapping['comment_count']['datatype'],
539
        ),
540
      );
541
      drupal_add_html_head($element, 'rdf_node_comment_count');
542
    }
543
  }
544
}
545

    
546
/**
547
 * Implements MODULE_preprocess_HOOK().
548
 */
549
function rdf_preprocess_field(&$variables) {
550
  $element = $variables['element'];
551
  $mapping = rdf_mapping_load($element['#entity_type'], $element['#bundle']);
552
  $field_name = $element['#field_name'];
553

    
554
  if (!empty($mapping) && !empty($mapping[$field_name])) {
555
    foreach ($element['#items'] as $delta => $item) {
556
      $variables['item_attributes_array'][$delta] = rdf_rdfa_attributes($mapping[$field_name], $item);
557
      // If this field is an image, RDFa will not output correctly when the
558
      // image is in a containing <a> tag. If the field is a file, RDFa will
559
      // not output correctly if the filetype icon comes before the link to the
560
      // file. We correct this by adding a resource attribute to the div if
561
      // this field has a URI.
562
      if (isset($item['uri'])) {
563
        if (!empty($element[$delta]['#image_style'])) {
564
          $variables['item_attributes_array'][$delta]['resource'] = image_style_url($element[$delta]['#image_style'], $item['uri']);
565
        }
566
        else {
567
          $variables['item_attributes_array'][$delta]['resource'] = file_create_url($item['uri']);
568
        }
569
      }
570
    }
571
  }
572
}
573

    
574
/**
575
 * Implements MODULE_preprocess_HOOK().
576
 */
577
function rdf_preprocess_user_profile(&$variables) {
578
  $account = $variables['elements']['#account'];
579
  $uri = entity_uri('user', $account);
580

    
581
  // Adds RDFa markup to the user profile page. Fields displayed in this page
582
  // will automatically describe the user.
583
  if (!empty($account->rdf_mapping['rdftype'])) {
584
    $variables['attributes_array']['typeof'] = $account->rdf_mapping['rdftype'];
585
    $variables['attributes_array']['about'] = url($uri['path'], $uri['options']);
586
  }
587
  // Adds the relationship between the sioc:UserAccount and the foaf:Person who
588
  // holds the account.
589
  $account_holder_meta = array(
590
    '#tag' => 'meta',
591
    '#attributes' => array(
592
      'about' => url($uri['path'], array_merge($uri['options'], array('fragment' => 'me'))),
593
      'typeof' => array('foaf:Person'),
594
      'rel' => array('foaf:account'),
595
      'resource' => url($uri['path'], $uri['options']),
596
    ),
597
  );
598
  // Adds the markup for username.
599
  $username_meta = array(
600
    '#tag' => 'meta',
601
    '#attributes' => array(
602
      'about' => url($uri['path'], $uri['options']),
603
      'property' => $account->rdf_mapping['name']['predicates'],
604
      'content' => $account->name,
605
    )
606
  );
607
  drupal_add_html_head($account_holder_meta, 'rdf_user_account_holder');
608
  drupal_add_html_head($username_meta, 'rdf_user_username');
609
}
610

    
611
/**
612
 * Implements MODULE_preprocess_HOOK().
613
 */
614
function rdf_preprocess_username(&$variables) {
615
  // Because xml:lang is set on the HTML element that wraps the page, the
616
  // username inherits this language attribute. However, since the username
617
  // might not be transliterated to the same language that the content is in,
618
  // we do not want it to inherit the language attribute, so we set the
619
  // attribute to an empty string.
620
  if (empty($variables['attributes_array']['xml:lang'])) {
621
    $variables['attributes_array']['xml:lang'] = '';
622
  }
623

    
624
  // $variables['account'] is a pseudo account object, and as such, does not
625
  // contain the RDF mappings for the user. In the case of nodes and comments,
626
  // it contains the mappings for the node or comment object instead. However,
627
  // while the RDF mappings are available from a full user_load(), this should
628
  // be avoided for performance reasons. Since the type and bundle for users is
629
  // already known, call rdf_mapping_load() directly.
630
  $rdf_mapping = rdf_mapping_load('user', 'user');
631

    
632
  // The profile URI is used to identify the user account. The about attribute
633
  // is used to set the URI as the default subject of the predicates embedded
634
  // as RDFa in the child elements. Even if the user profile is not accessible
635
  // to the current user, we use its URI in order to identify the user in RDF.
636
  // We do not use this attribute for the anonymous user because we do not have
637
  // a user profile URI for it (only a homepage which cannot be used as user
638
  // profile in RDF.)
639
  if ($variables['uid'] > 0) {
640
    $variables['attributes_array']['about'] = url('user/' . $variables['uid']);
641
  }
642

    
643
  $attributes = array();
644
  // The typeof attribute specifies the RDF type(s) of this resource. They
645
  // are defined in the 'rdftype' property of the user RDF mapping.
646
  if (!empty($rdf_mapping['rdftype'])) {
647
    $attributes['typeof'] = $rdf_mapping['rdftype'];
648
  }
649
  // Annotate the username in RDFa. A property attribute is used with an empty
650
  // datatype attribute to ensure the username is parsed as a plain literal
651
  // in RDFa 1.0 and 1.1.
652
  if (!empty($rdf_mapping['name'])) {
653
    $attributes['property'] = $rdf_mapping['name']['predicates'];
654
    $attributes['datatype'] = '';
655
  }
656
  // Add the homepage RDFa markup if present.
657
  if (!empty($variables['homepage']) && !empty($rdf_mapping['homepage'])) {
658
    $attributes['rel'] = $rdf_mapping['homepage']['predicates'];
659
  }
660
  // The remaining attributes can have multiple values listed, with whitespace
661
  // separating the values in the RDFa attributes
662
  // (see http://www.w3.org/TR/rdfa-syntax/#rdfa-attributes).
663
  // Therefore, merge rather than override so as not to clobber values set by
664
  // earlier preprocess functions.
665
  $variables['attributes_array'] = array_merge_recursive($variables['attributes_array'], $attributes);
666
}
667

    
668
/**
669
 * Implements MODULE_preprocess_HOOK().
670
 */
671
function rdf_preprocess_comment(&$variables) {
672
  $comment = $variables['comment'];
673
  if (!empty($comment->rdf_mapping['rdftype'])) {
674
    // Adds RDFa markup to the comment container. The about attribute specifies
675
    // the URI of the resource described within the HTML element, while the
676
    // typeof attribute indicates its RDF type (e.g., sioc:Post, foaf:Document,
677
    // and so on.)
678
    $uri = entity_uri('comment', $comment);
679
    $variables['attributes_array']['about'] = url($uri['path'], $uri['options']);
680
    $variables['attributes_array']['typeof'] = $comment->rdf_mapping['rdftype'];
681
  }
682

    
683
  // Adds RDFa markup for the date of the comment.
684
  if (!empty($comment->rdf_mapping['created'])) {
685
    // The comment date is precomputed as part of the rdf_data so that it can be
686
    // cached as part of the entity.
687
    $date_attributes_array = $comment->rdf_data['date'];
688
    $variables['rdf_template_variable_attributes_array']['created'] = $date_attributes_array;
689
    $variables['rdf_template_variable_attributes_array']['submitted'] = $date_attributes_array;
690
  }
691
  // Adds RDFa markup for the relation between the comment and its author.
692
  if (!empty($comment->rdf_mapping['uid'])) {
693
    $variables['rdf_template_variable_attributes_array']['author']['rel'] = $comment->rdf_mapping['uid']['predicates'];
694
    $variables['rdf_template_variable_attributes_array']['submitted']['rel'] = $comment->rdf_mapping['uid']['predicates'];
695
  }
696
  if (!empty($comment->rdf_mapping['title'])) {
697
    // Adds RDFa markup to the subject of the comment. Because the RDFa markup
698
    // is added to an <h3> tag which might contain HTML code, we specify an
699
    // empty datatype to ensure the value of the title read by the RDFa parsers
700
    // is a literal.
701
    $variables['title_attributes_array']['property'] = $comment->rdf_mapping['title']['predicates'];
702
    $variables['title_attributes_array']['datatype'] = '';
703
  }
704

    
705
  // Annotates the parent relationship between the current comment and the node
706
  // it belongs to. If available, the parent comment is also annotated.
707
  if (!empty($comment->rdf_mapping['pid'])) {
708
    // Adds the relation to the parent node.
709
    $parent_node_attributes['rel'] = $comment->rdf_mapping['pid']['predicates'];
710
    // The parent node URI is precomputed as part of the rdf_data so that it can
711
    // be cached as part of the entity.
712
    $parent_node_attributes['resource'] = $comment->rdf_data['nid_uri'];
713
    $variables['rdf_metadata_attributes_array'][] = $parent_node_attributes;
714

    
715
    // Adds the relation to parent comment, if it exists.
716
    if ($comment->pid != 0) {
717
      $parent_comment_attributes['rel'] = $comment->rdf_mapping['pid']['predicates'];
718
      // The parent comment URI is precomputed as part of the rdf_data so that
719
      // it can be cached as part of the entity.
720
      $parent_comment_attributes['resource'] = $comment->rdf_data['pid_uri'];
721
      $variables['rdf_metadata_attributes_array'][] = $parent_comment_attributes;
722
    }
723
  }
724
}
725

    
726
/**
727
 * Implements MODULE_preprocess_HOOK().
728
 */
729
function rdf_preprocess_taxonomy_term(&$variables) {
730
  // Adds the RDF type of the term and the term name in a <meta> tag.
731
  $term = $variables['term'];
732
  $term_label_meta = array(
733
      '#tag' => 'meta',
734
      '#attributes' => array(
735
        'about' => url('taxonomy/term/' . $term->tid),
736
        'typeof' => $term->rdf_mapping['rdftype'],
737
        'property' => $term->rdf_mapping['name']['predicates'],
738
        'content' => $term->name,
739
      ),
740
    );
741
  drupal_add_html_head($term_label_meta, 'rdf_term_label');
742
}
743

    
744
/**
745
 * Implements hook_field_attach_view_alter().
746
 */
747
function rdf_field_attach_view_alter(&$output, $context) {
748
  // Append term mappings on displayed taxonomy links.
749
  foreach (element_children($output) as $field_name) {
750
    $element = &$output[$field_name];
751
    if ($element['#field_type'] == 'taxonomy_term_reference' && $element['#formatter'] == 'taxonomy_term_reference_link') {
752
      foreach ($element['#items'] as $delta => $item) {
753
        // This function is invoked during entity preview when taxonomy term
754
        // reference items might contain free-tagging terms that do not exist
755
        // yet and thus have no $item['taxonomy_term'].
756
        if (isset($item['taxonomy_term'])) {
757
          $term = $item['taxonomy_term'];
758
          if (!empty($term->rdf_mapping['rdftype'])) {
759
            $element[$delta]['#options']['attributes']['typeof'] = $term->rdf_mapping['rdftype'];
760
          }
761
          if (!empty($term->rdf_mapping['name']['predicates'])) {
762
            // A property attribute is used with an empty datatype attribute so
763
            // the term name is parsed as a plain literal in RDFa 1.0 and 1.1.
764
            $element[$delta]['#options']['attributes']['property'] = $term->rdf_mapping['name']['predicates'];
765
            $element[$delta]['#options']['attributes']['datatype'] = '';
766
          }
767
        }
768
      }
769
    }
770
  }
771
}
772

    
773
/**
774
 * Implements MODULE_preprocess_HOOK().
775
 */
776
function rdf_preprocess_image(&$variables) {
777
  // Adds the RDF type for image. We cannot use the usual entity-based mapping
778
  // to get 'foaf:Image' because image does not have its own entity type or
779
  // bundle.
780
  $variables['attributes']['typeof'] = array('foaf:Image');
781
}
782

    
783
/**
784
 * Returns HTML for a template variable wrapped in an HTML element with the
785
 * RDF attributes.
786
 *
787
 * This is called by rdf_process() shortly before the theme system renders
788
 * a template file. It is called once for each template variable for which
789
 * additional attributes are needed. While template files are responsible for
790
 * rendering the attributes for the template's primary object (via the
791
 * $attributes variable), title (via the $title_attributes variable), and
792
 * content (via the $content_attributes variable), additional template
793
 * variables that need containing attributes are routed through this function,
794
 * allowing the template file to receive properly wrapped variables.
795
 *
796
 * Tip for themers: if you're already outputting a wrapper element around a
797
 * particular template variable in your template file, and if you don't want
798
 * an extra wrapper element, you can override this function to not wrap that
799
 * variable and instead print the following inside your template file:
800
 * @code
801
 *   drupal_attributes($rdf_template_variable_attributes_array[$variable_name])
802
 * @endcode
803
 *
804
 * @param $variables
805
 *   An associative array containing:
806
 *   - content: A string of content to be wrapped with attributes.
807
 *   - attributes: An array of attributes to be placed on the wrapping element.
808
 *   - context: An array of context information about the content to be wrapped:
809
 *     - hook: The theme hook that will use the wrapped content. This
810
 *       corresponds to the key within the theme registry for this template.
811
 *       For example, if this content is about to be used in node.tpl.php or
812
 *       node-[type].tpl.php, then the 'hook' is 'node'.
813
 *     - variable_name: The name of the variable by which the template will
814
 *       refer to this content. Each template file has documentation about
815
 *       the variables it uses. For example, if this function is called in
816
 *       preparing the $author variable for comment.tpl.php, then the
817
 *       'variable_name' is 'author'.
818
 *     - variables: The full array of variables about to be passed to the
819
 *       template.
820
 *   - inline: TRUE if the content contains only inline HTML elements and
821
 *     therefore can be validly wrapped by a <span> tag. FALSE if the content
822
 *     might contain block level HTML elements and therefore cannot be validly
823
 *     wrapped by a <span> tag. Modules implementing preprocess functions that
824
 *     set 'rdf_template_variable_attributes_array' for a particular template
825
 *     variable that might contain block level HTML must also implement
826
 *     hook_preprocess_rdf_template_variable_wrapper() and set 'inline' to FALSE
827
 *     for that context. Themes that render normally inline content with block
828
 *     level HTML must similarly implement
829
 *     hook_preprocess_rdf_template_variable_wrapper() and set 'inline'
830
 *     accordingly.
831
 *
832
 * @see rdf_process()
833
 * @ingroup themeable
834
 * @ingroup rdf
835
 */
836
function theme_rdf_template_variable_wrapper($variables) {
837
  $output = $variables['content'];
838
  if (!empty($output) && !empty($variables['attributes'])) {
839
    $attributes = drupal_attributes($variables['attributes']);
840
    $output = $variables['inline'] ? "<span$attributes>$output</span>" : "<div$attributes>$output</div>";
841
  }
842
  return $output;
843
}
844

    
845
/**
846
 * Returns HTML for a series of empty spans for exporting RDF metadata in RDFa.
847
 *
848
 * Sometimes it is useful to export data which is not semantically present in
849
 * the HTML output. For example, a hierarchy of comments is visible for a human
850
 * but not for machines because this hiearchy is not present in the DOM tree.
851
 * We can express it in RDFa via empty <span> tags. These aren't visible and
852
 * give machines extra information about the content and its structure.
853
 *
854
 * @param $variables
855
 *   An associative array containing:
856
 *   - metadata: An array of attribute arrays. Each item in the array
857
 *     corresponds to its own set of attributes, and therefore, needs its own
858
 *     element.
859
 *
860
 * @see rdf_process()
861
 * @ingroup themeable
862
 * @ingroup rdf
863
 */
864
function theme_rdf_metadata($variables) {
865
  $output = '';
866
  foreach ($variables['metadata'] as $attributes) {
867
    // Add a class so that developers viewing the HTML source can see why there
868
    // are empty <span> tags in the document. The class can also be used to set
869
    // a CSS display:none rule in a theme where empty spans affect display.
870
    $attributes['class'][] = 'rdf-meta';
871
    // The XHTML+RDFa doctype allows either <span></span> or <span /> syntax to
872
    // be used, but for maximum browser compatibility, W3C recommends the
873
    // former when serving pages using the text/html media type, see
874
    // http://www.w3.org/TR/xhtml1/#C_3.
875
    $output .= '<span' . drupal_attributes($attributes) . '></span>';
876
  }
877
  return $output;
878
}