Projet

Général

Profil

Paste
Télécharger (33,5 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / rdf / rdf.module @ 4da4932d

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
  $mappings = _rdf_mapping_load_multiple($type, array($bundle));
194
  return $mappings ? reset($mappings) : array();
195
}
196

    
197
/**
198
 * Helper function to retrieve a set of RDF mappings from the database.
199
 *
200
 * @param $type
201
 *   The entity type of the mappings.
202
 * @param $bundles
203
 *   The bundles the mappings refer to.
204
 *
205
 * @return
206
 *   An array of RDF mapping structures, or an empty array.
207
 */
208
function _rdf_mapping_load_multiple($type, array $bundles) {
209
  $mappings = db_select('rdf_mapping')
210
    ->fields(NULL, array('bundle', 'mapping'))
211
    ->condition('type', $type)
212
    ->condition('bundle', $bundles)
213
    ->execute()
214
    ->fetchAllKeyed();
215

    
216
  foreach ($mappings as $bundle => $mapping) {
217
    $mappings[$bundle] = unserialize($mapping);
218
  }
219
  return $mappings;
220
}
221

    
222
/**
223
 * @addtogroup rdf
224
 * @{
225
 */
226

    
227
/**
228
 * Saves an RDF mapping to the database.
229
 *
230
 * Takes a mapping structure returned by hook_rdf_mapping() implementations
231
 * and creates or updates a record mapping for each encountered entity
232
 * type/bundle pair. If available, adds default values for non-existent mapping
233
 * keys.
234
 *
235
 * @param $mapping
236
 *   The RDF mapping to save, as an array.
237
 *
238
 * @return
239
 *   Status flag indicating the outcome of the operation.
240
 */
241
function rdf_mapping_save($mapping) {
242
  // In the case where a field has a mapping defined in the default entity
243
  // mapping, but a mapping is not specified in the bundle-specific mapping,
244
  // then use the default mapping for that field.
245
  $mapping['mapping'] += _rdf_get_default_mapping($mapping['type']);
246

    
247
  $status = db_merge('rdf_mapping')
248
    ->key(array(
249
      'type' => $mapping['type'],
250
      'bundle' => $mapping['bundle'],
251
    ))
252
    ->fields(array(
253
      'mapping' => serialize($mapping['mapping']),
254
    ))
255
    ->execute();
256

    
257
  entity_info_cache_clear();
258

    
259
  return $status;
260
}
261

    
262
/**
263
 * Deletes the mapping for the given bundle from the database.
264
 *
265
 * @param $type
266
 *   The entity type the mapping refers to.
267
 * @param $bundle
268
 *   The bundle the mapping refers to.
269
 *
270
 * @return
271
 *   Return boolean TRUE if mapping deleted, FALSE if not.
272
 */
273
function rdf_mapping_delete($type, $bundle) {
274
  $num_rows = db_delete('rdf_mapping')
275
    ->condition('type', $type)
276
    ->condition('bundle', $bundle)
277
    ->execute();
278

    
279
  return (bool) ($num_rows > 0);
280
}
281

    
282
/**
283
 * Builds an array of RDFa attributes for a given mapping. This array will
284
 * typically be passed through drupal_attributes() to create the attributes
285
 * variables that are available to template files. These include $attributes,
286
 * $title_attributes, $content_attributes and the field-specific
287
 * $item_attributes variables. For more information, see
288
 * theme_rdf_template_variable_wrapper().
289
 *
290
 * @param $mapping
291
 *   An array containing a mandatory 'predicates' key and optional 'datatype',
292
 *   'callback' and 'type' keys. For example:
293
 *   @code
294
 *     array(
295
 *       'predicates' => array('dc:created'),
296
 *       'datatype' => 'xsd:dateTime',
297
 *       'callback' => 'date_iso8601',
298
 *       ),
299
 *     );
300
 *   @endcode
301
 * @param $data
302
 *   A value that needs to be converted by the provided callback function.
303
 *
304
 * @return
305
 *   An array containing RDFa attributes suitable for drupal_attributes().
306
 */
307
function rdf_rdfa_attributes($mapping, $data = NULL) {
308
  // The type of mapping defaults to 'property'.
309
  $type = isset($mapping['type']) ? $mapping['type'] : 'property';
310

    
311
  switch ($type) {
312
    // The mapping expresses the relationship between two resources.
313
    case 'rel':
314
    case 'rev':
315
      $attributes[$type] = $mapping['predicates'];
316
      break;
317

    
318
    // The mapping expresses the relationship between a resource and some
319
    // literal text.
320
    case 'property':
321
      $attributes['property'] = $mapping['predicates'];
322
      // Convert $data to a specific format as per the callback function.
323
      if (isset($data) && isset($mapping['callback']) && function_exists($mapping['callback'])) {
324
        $callback = $mapping['callback'];
325
        $attributes['content'] = $callback($data);
326
      }
327
      if (isset($mapping['datatype'])) {
328
        $attributes['datatype'] = $mapping['datatype'];
329
      }
330
      break;
331
  }
332

    
333
  return $attributes;
334
}
335

    
336
/**
337
 * @} End of "addtogroup rdf".
338
 */
339

    
340
/**
341
 * Implements hook_modules_installed().
342
 *
343
 * Checks if the installed modules have any RDF mapping definitions to declare
344
 * and stores them in the rdf_mapping table.
345
 *
346
 * While both default entity mappings and specific bundle mappings can be
347
 * defined in hook_rdf_mapping(), default entity mappings are not stored in the
348
 * database. Only overridden mappings are stored in the database. The default
349
 * entity mappings can be overriden by specific bundle mappings which are
350
 * stored in the database and can be altered via the RDF CRUD mapping API.
351
 */
352
function rdf_modules_installed($modules) {
353
  foreach ($modules as $module) {
354
    $function = $module . '_rdf_mapping';
355
    if (function_exists($function)) {
356
      foreach ($function() as $mapping) {
357
        // Only the bundle mappings are saved in the database.
358
        if ($mapping['bundle'] !== RDF_DEFAULT_BUNDLE) {
359
          rdf_mapping_save($mapping);
360
        }
361
      }
362
    }
363
  }
364
}
365

    
366
/**
367
 * Implements hook_modules_uninstalled().
368
 */
369
function rdf_modules_uninstalled($modules) {
370
  // @todo Remove RDF mappings of uninstalled modules.
371
}
372

    
373
/**
374
 * Implements hook_entity_info_alter().
375
 *
376
 * Adds the proper RDF mapping to each entity type/bundle pair.
377
 *
378
 * @todo May need to move the comment below to another place.
379
 * This hook should not be used by modules to alter the bundle mappings.
380
 * The UI should always be authoritative. UI mappings are stored in the
381
 * database and if hook_entity_info_alter was used to override module defined
382
 * mappings, it would override the user defined mapping as well.
383
 */
384
function rdf_entity_info_alter(&$entity_info) {
385
  // Loop through each entity type and its bundles.
386
  foreach ($entity_info as $entity_type => $entity_type_info) {
387
    if (!empty($entity_type_info['bundles'])) {
388
      $bundles = array_keys($entity_type_info['bundles']);
389
      $mappings = _rdf_mapping_load_multiple($entity_type, $bundles);
390

    
391
      foreach ($bundles as $bundle) {
392
        if (isset($mappings[$bundle])) {
393
          $entity_info[$entity_type]['bundles'][$bundle]['rdf_mapping'] = $mappings[$bundle];
394
        }
395
        else {
396
          // If no mapping was found in the database, assign the default RDF
397
          // mapping for this entity type.
398
          $entity_info[$entity_type]['bundles'][$bundle]['rdf_mapping'] = _rdf_get_default_mapping($entity_type);
399
        }
400
      }
401
    }
402
  }
403
}
404

    
405
/**
406
 * Implements hook_entity_load().
407
 */
408
function rdf_entity_load($entities, $type) {
409
  foreach ($entities as $entity) {
410
    // Extracts the bundle of the entity being loaded.
411
    list($id, $vid, $bundle) = entity_extract_ids($type, $entity);
412
    $entity->rdf_mapping = rdf_mapping_load($type, $bundle);
413
  }
414
}
415

    
416
/**
417
 * Implements hook_comment_load().
418
 */
419
function rdf_comment_load($comments) {
420
  foreach ($comments as $comment) {
421
    // Pages with many comments can show poor performance. This information
422
    // isn't needed until rdf_preprocess_comment() is called, but set it here
423
    // to optimize performance for websites that implement an entity cache.
424
    $comment->rdf_data['date'] = rdf_rdfa_attributes($comment->rdf_mapping['created'], $comment->created);
425
    $comment->rdf_data['nid_uri'] = url('node/' . $comment->nid);
426
    if ($comment->pid) {
427
      $comment->rdf_data['pid_uri'] = url('comment/' . $comment->pid, array('fragment' => 'comment-' . $comment->pid));
428
    }
429
  }
430
}
431

    
432
/**
433
 * Implements hook_theme().
434
 */
435
function rdf_theme() {
436
  return array(
437
    'rdf_template_variable_wrapper' => array(
438
      'variables' => array('content' => NULL, 'attributes' => array(), 'context' => array(), 'inline' => TRUE),
439
    ),
440
    'rdf_metadata' => array(
441
      'variables' => array('metadata' => array()),
442
    ),
443
  );
444
}
445

    
446
/**
447
 * Template process function for adding extra tags to hold RDFa attributes.
448
 *
449
 * Since template files already have built-in support for $attributes,
450
 * $title_attributes, and $content_attributes, and field templates have support
451
 * for $item_attributes, we try to leverage those as much as possible. However,
452
 * in some cases additional attributes are needed not covered by these. We deal
453
 * with those here.
454
 */
455
function rdf_process(&$variables, $hook) {
456
  // Handles attributes needed for content not covered by title, content,
457
  // and field items. It does this by adjusting the variable sent to the
458
  // template so that the template doesn't have to worry about it. See
459
  // theme_rdf_template_variable_wrapper().
460
  if (!empty($variables['rdf_template_variable_attributes_array'])) {
461
    foreach ($variables['rdf_template_variable_attributes_array'] as $variable_name => $attributes) {
462
      $context = array(
463
        'hook' => $hook,
464
        'variable_name' => $variable_name,
465
        'variables' => $variables,
466
      );
467
      $variables[$variable_name] = theme('rdf_template_variable_wrapper', array('content' => $variables[$variable_name], 'attributes' => $attributes, 'context' => $context));
468
    }
469
  }
470
  // Handles additional attributes about a template entity that for RDF parsing
471
  // reasons, can't be placed into that template's $attributes variable. This
472
  // is "meta" information that is related to particular content, so render it
473
  // close to that content.
474
  if (!empty($variables['rdf_metadata_attributes_array'])) {
475
    if (!isset($variables['content']['#prefix'])) {
476
      $variables['content']['#prefix'] = '';
477
    }
478
    $variables['content']['#prefix'] = theme('rdf_metadata', array('metadata' => $variables['rdf_metadata_attributes_array'])) . $variables['content']['#prefix'];
479
  }
480
}
481

    
482
/**
483
 * Implements MODULE_preprocess_HOOK().
484
 */
485
function rdf_preprocess_node(&$variables) {
486
  // Adds RDFa markup to the node container. The about attribute specifies the
487
  // URI of the resource described within the HTML element, while the @typeof
488
  // attribute indicates its RDF type (e.g., foaf:Document, sioc:Person, and so
489
  // on.)
490
  $variables['attributes_array']['about'] = empty($variables['node_url']) ? NULL: $variables['node_url'];
491
  $variables['attributes_array']['typeof'] = empty($variables['node']->rdf_mapping['rdftype']) ? NULL : $variables['node']->rdf_mapping['rdftype'];
492

    
493
  // Adds RDFa markup about the title of the node to the title_suffix.
494
  if (!empty($variables['node']->rdf_mapping['title']['predicates'])) {
495
    $variables['title_suffix']['rdf_meta_title'] = array(
496
      '#theme' => 'rdf_metadata',
497
      '#metadata' => array(
498
        array(
499
          'property' => $variables['node']->rdf_mapping['title']['predicates'],
500
          'content' => $variables['node']->title,
501
        ),
502
      ),
503
    );
504
  }
505

    
506
  // Adds RDFa markup for the date.
507
  if (!empty($variables['rdf_mapping']['created'])) {
508
    $date_attributes_array = rdf_rdfa_attributes($variables['rdf_mapping']['created'], $variables['created']);
509
    $variables['rdf_template_variable_attributes_array']['date'] = $date_attributes_array;
510
    if ($variables['submitted']) {
511
      $variables['rdf_template_variable_attributes_array']['submitted'] = $date_attributes_array;
512
    }
513
  }
514
  // Adds RDFa markup for the relation between the node and its author.
515
  if (!empty($variables['rdf_mapping']['uid'])) {
516
    $variables['rdf_template_variable_attributes_array']['name']['rel'] = $variables['rdf_mapping']['uid']['predicates'];
517
    if ($variables['submitted']) {
518
      $variables['rdf_template_variable_attributes_array']['submitted']['rel'] = $variables['rdf_mapping']['uid']['predicates'];
519
    }
520
  }
521

    
522
  // Adds RDFa markup annotating the number of comments a node has.
523
  if (isset($variables['node']->comment_count) &&
524
      !empty($variables['node']->rdf_mapping['comment_count']['predicates']) &&
525
      user_access('access comments')) {
526
    // Adds RDFa markup for the comment count near the node title as metadata.
527
    $variables['title_suffix']['rdf_meta_comment_count'] = array(
528
      '#theme' => 'rdf_metadata',
529
      '#metadata' => array(
530
        array(
531
          'property' => $variables['node']->rdf_mapping['comment_count']['predicates'],
532
          'content' => $variables['node']->comment_count,
533
          'datatype' => $variables['node']->rdf_mapping['comment_count']['datatype'],
534
        ),
535
      ),
536
    );
537
  }
538
}
539

    
540
/**
541
 * Implements MODULE_preprocess_HOOK().
542
 */
543
function rdf_preprocess_field(&$variables) {
544
  $element = $variables['element'];
545
  $mapping = rdf_mapping_load($element['#entity_type'], $element['#bundle']);
546
  $field_name = $element['#field_name'];
547

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

    
568
/**
569
 * Implements MODULE_preprocess_HOOK().
570
 */
571
function rdf_preprocess_user_profile(&$variables) {
572
  $account = $variables['elements']['#account'];
573
  $uri = entity_uri('user', $account);
574

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

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

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

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

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

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

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

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

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

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

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

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

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

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