Projet

Général

Profil

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

root / drupal7 / sites / all / modules / entity / modules / callbacks.inc @ 082b75eb

1
<?php
2

    
3
/**
4
 * @file
5
 * Provides various callbacks for the whole core module integration.
6
 */
7

    
8
/**
9
 * Callback for getting properties of an entity.
10
 */
11
function entity_metadata_entity_get_properties($entity, array $options, $name, $entity_type) {
12
  if ($name == 'url') {
13
    $return = entity_uri($entity_type, $entity);
14
    return url($return['path'], $return['options'] + $options);
15
  }
16
}
17

    
18
/**
19
 * Callback for getting book node properties.
20
 * @see entity_metadata_book_entity_info_alter()
21
 */
22
function entity_metadata_book_get_properties($node, array $options, $name, $entity_type) {
23
  switch ($name) {
24
    case 'book':
25
      if (isset($node->book['bid'])) {
26
        return $node->book['bid'];
27
      }
28
      return NULL;
29

    
30
    case 'book_ancestors':
31
      $ancestors = array();
32
      while (!empty($node->book['plid']) && $node->book['plid'] != -1) {
33
        $link = book_link_load($node->book['plid']);
34
        array_unshift($ancestors, $link['nid']);
35
        $node = node_load($link['nid']);
36
      }
37
      return $ancestors;
38
  }
39
}
40

    
41
/**
42
 * Callback for getting comment properties.
43
 * @see entity_metadata_comment_entity_info_alter()
44
 */
45
function entity_metadata_comment_get_properties($comment, array $options, $name) {
46
  switch ($name) {
47
    case 'name':
48
      return $comment->name;
49

    
50
    case 'mail':
51
      if ($comment->uid != 0) {
52
        $account = user_load($comment->uid);
53
        return $account->mail;
54
      }
55
      return $comment->mail;
56

    
57
    case 'edit_url':
58
      return url('comment/edit/' . $comment->cid, $options);
59

    
60
    case 'parent':
61
      if (!empty($comment->pid)) {
62
        return $comment->pid;
63
      }
64
      // There is no parent comment.
65
      return NULL;
66
  }
67
}
68

    
69
/**
70
 * Callback for setting comment properties.
71
 * @see entity_metadata_comment_entity_info_alter()
72
 */
73
function entity_metadata_comment_setter($comment, $name, $value) {
74
  switch ($name) {
75
    case 'node':
76
      $comment->nid = $value;
77
      // Also set the bundle name.
78
      $node = node_load($value);
79
      $comment->node_type = 'comment_node_' . $node->type;
80
      break;
81
  }
82
}
83

    
84
/**
85
 * Callback for getting comment related node properties.
86
 * @see entity_metadata_comment_entity_info_alter()
87
 */
88
function entity_metadata_comment_get_node_properties($node, array $options, $name, $entity_type) {
89
  switch ($name) {
90
    case 'comment_count':
91
      return isset($node->comment_count) ? $node->comment_count : 0;
92

    
93
    case 'comment_count_new':
94
      return comment_num_new($node->nid);
95

    
96
    case 'comments':
97
      $select = db_select('comment', 'c')
98
        ->fields('c', array('cid'))
99
        ->condition('c.nid', $node->nid);
100
      return array_keys($select->execute()->fetchAllKeyed(0, 0));
101
  }
102
}
103

    
104
/**
105
 * Getter callback for getting global languages.
106
 */
107
function entity_metadata_locale_get_languages($data, array $options, $name) {
108
  return isset($GLOBALS[$name]) ? $GLOBALS[$name]->language : NULL;
109
}
110

    
111
/**
112
 * Getter callback for getting the preferred user language.
113
 */
114
function entity_metadata_locale_get_user_language($account, array $options, $name) {
115
  return user_preferred_language($account)->language;
116
}
117

    
118
/**
119
 * Return the options lists for the node and comment status property.
120
 */
121
function entity_metadata_status_options_list() {
122
  return array(
123
    NODE_PUBLISHED => t('Published'),
124
    NODE_NOT_PUBLISHED => t('Unpublished'),
125
  );
126
}
127

    
128
/**
129
 * Callback for getting node properties.
130
 *
131
 * @see entity_metadata_node_entity_info_alter()
132
 */
133
function entity_metadata_node_get_properties($node, array $options, $name, $entity_type) {
134
  switch ($name) {
135
    case 'is_new':
136
      return empty($node->nid) || !empty($node->is_new);
137

    
138
    case 'source':
139
      if (!empty($node->tnid) && $source = node_load($node->tnid)) {
140
        return $source;
141
      }
142
      return NULL;
143

    
144
    case 'edit_url':
145
      return url('node/' . $node->nid . '/edit', $options);
146

    
147
    case 'author':
148
      return !empty($node->uid) ? $node->uid : drupal_anonymous_user();
149
  }
150
}
151

    
152
/**
153
 * Callback for determing access for node revision related properties.
154
 */
155
function entity_metadata_node_revision_access($op, $name, $entity = NULL, $account = NULL) {
156
  return $op == 'view' ? user_access('view revisions', $account) : user_access('administer nodes', $account);
157
}
158

    
159
/**
160
 * Callback for getting poll properties.
161
 * @see entity_metadata_poll_entity_info_alter()
162
 */
163
function entity_metadata_poll_node_get_properties($node, array $options, $name) {
164
  $total_votes = $highest_votes = 0;
165
  foreach ($node->choice as $choice) {
166
    if ($choice['chvotes'] > $highest_votes) {
167
      $winner = $choice;
168
      $highest_votes = $choice['chvotes'];
169
    }
170
    $total_votes = $total_votes + $choice['chvotes'];
171
  }
172

    
173
  if ($name == 'poll_duration') {
174
    return $node->runtime;
175
  }
176
  elseif ($name == 'poll_votes') {
177
    return $total_votes;
178
  }
179
  elseif (!isset($winner)) {
180
    // There is no poll winner yet.
181
    return NULL;
182
  }
183
  switch ($name) {
184
    case 'poll_winner_votes':
185
        return $winner['chvotes'];
186

    
187
    case 'poll_winner':
188
        return $winner['chtext'];
189

    
190
    case 'poll_winner_percent':
191
        return ($winner['chvotes'] / $total_votes) * 100;
192
  }
193
}
194

    
195
/**
196
 * Callback for getting statistics properties.
197
 * @see entity_metadata_statistics_entity_info_alter()
198
 */
199
function entity_metadata_statistics_node_get_properties($node, array $options, $name) {
200
  $statistics = (array) statistics_get($node->nid);
201
  $statistics += array('totalcount' => 0, 'daycount' => 0, 'timestamp' => NULL);
202

    
203
  switch ($name) {
204
    case 'views':
205
      return $statistics['totalcount'];
206

    
207
    case 'day_views':
208
      return $statistics['daycount'];
209

    
210
    case 'last_view':
211
      return $statistics['timestamp'];
212
  }
213
}
214

    
215
/**
216
 * Access callback for restricted node statistics properties.
217
 */
218
function entity_metadata_statistics_properties_access($op, $property, $entity = NULL, $account = NULL) {
219
  if ($property == 'views' && user_access('view post access counter', $account)) {
220
    return TRUE;
221
  }
222
  return user_access('access statistics', $account);
223
}
224

    
225
/**
226
 * Callback for getting site-wide properties.
227
 * @see entity_metadata_system_entity_info_alter()
228
 */
229
function entity_metadata_system_get_properties($data = FALSE, array $options, $name) {
230
  switch ($name) {
231
    case 'name':
232
      return variable_get('site_name', 'Drupal');
233

    
234
    case 'url':
235
      return url('<front>', $options);
236

    
237
    case 'login_url':
238
      return url('user', $options);
239

    
240
    case 'current_user':
241
      return $GLOBALS['user']->uid ? $GLOBALS['user']->uid : drupal_anonymous_user();
242

    
243
    case 'current_date':
244
      return REQUEST_TIME;
245

    
246
    case 'current_page':
247
      // Subsequent getters of the struct retrieve the actual values.
248
      return array();
249

    
250
    default:
251
      return variable_get('site_' . $name, '');
252
  }
253
}
254

    
255
/**
256
 * Callback for getting properties for the current page request.
257
 * @see entity_metadata_system_entity_info_alter()
258
 */
259
function entity_metadata_system_get_page_properties($data = array(), array $options, $name) {
260
  switch ($name) {
261
    case 'url':
262
      return $GLOBALS['base_root'] . request_uri();
263
  }
264
}
265

    
266
/**
267
 * Callback for getting file properties.
268
 * @see entity_metadata_system_entity_info_alter()
269
 */
270
function entity_metadata_system_get_file_properties($file, array $options, $name) {
271
  switch ($name) {
272
    case 'name':
273
      return $file->filename;
274

    
275
    case 'mime':
276
      return $file->filemime;
277

    
278
    case 'size':
279
      return $file->filesize;
280

    
281
    case 'url':
282
      return url(file_create_url($file->uri), $options);
283

    
284
    case 'owner':
285
      return $file->uid;
286
  }
287
}
288

    
289
/**
290
 * Callback for getting term properties.
291
 *
292
 * @see entity_metadata_taxonomy_entity_info_alter()
293
 */
294
function entity_metadata_taxonomy_term_get_properties($term, array $options, $name) {
295
  switch ($name) {
296
    case 'node_count':
297
      return count(taxonomy_select_nodes($term->tid));
298

    
299
    case 'description':
300
      return check_markup($term->description, isset($term->format) ? $term->format : NULL, '', TRUE);
301

    
302
    case 'parent':
303
      if (isset($term->parent[0]) && !is_array(isset($term->parent[0]))) {
304
        return $term->parent;
305
      }
306
      return array_keys(taxonomy_get_parents($term->tid));
307

    
308
    case 'parents_all':
309
      // We have to return an array of ids.
310
      $tids = array();
311
      foreach (taxonomy_get_parents_all($term->tid) as $parent) {
312
        $tids[] = $parent->tid;
313
      }
314
      return $tids;
315
  }
316
}
317

    
318
/**
319
 * Callback for setting term properties.
320
 *
321
 * @see entity_metadata_taxonomy_entity_info_alter()
322
 */
323
function entity_metadata_taxonomy_term_setter($term, $name, $value) {
324
  switch ($name) {
325
    case 'vocabulary':
326
      // Make sure to update the taxonomy bundle key, so load the vocabulary.
327
      // Support both, loading by name or ID.
328
      $vocabulary = is_numeric($value) ? taxonomy_vocabulary_load($value) : taxonomy_vocabulary_machine_name_load($value);
329
      $term->vocabulary_machine_name = $vocabulary->machine_name;
330
      return $term->vid = $vocabulary->vid;
331
    case 'parent':
332
      return $term->parent = $value;
333
  }
334
}
335

    
336
/**
337
 * Callback for getting vocabulary properties.
338
 * @see entity_metadata_taxonomy_entity_info_alter()
339
 */
340
function entity_metadata_taxonomy_vocabulary_get_properties($vocabulary, array $options, $name) {
341
  switch ($name) {
342
    case 'term_count':
343
      $sql = "SELECT COUNT (1) FROM {taxonomy_term_data} td WHERE td.vid = :vid";
344
      return db_query($sql, array(':vid' => $vocabulary->vid))->fetchField();
345
  }
346
}
347

    
348
/**
349
 * Callback for getting user properties.
350
 * @see entity_metadata_user_entity_info_alter()
351
 */
352
function entity_metadata_user_get_properties($account, array $options, $name, $entity_type) {
353
  switch ($name) {
354
    case 'last_access':
355
      // In case there was no access the value is 0, but we have to return NULL.
356
      return empty($account->access) ? NULL : $account->access;
357

    
358
    case 'last_login':
359
      return empty($account->login) ? NULL : $account->login;
360

    
361
    case 'name':
362
      return empty($account->uid) ? variable_get('anonymous', t('Anonymous')) : $account->name;
363

    
364
    case 'url':
365
      if (empty($account->uid)) {
366
        return NULL;
367
      }
368
      $return = entity_uri('user', $account);
369
      return $return ? url($return['path'], $return['options'] + $options) : '';
370

    
371
    case 'edit_url':
372
      return empty($account->uid) ? NULL : url("user/$account->uid/edit", $options);
373

    
374
    case 'roles':
375
      return isset($account->roles) ? array_keys($account->roles) : array();
376

    
377
    case 'theme':
378
      return empty($account->theme) ? variable_get('theme_default', 'bartik') : $account->theme;
379
  }
380
}
381

    
382
/**
383
 * Callback for setting user properties.
384
 * @see entity_metadata_user_entity_info_alter()
385
 */
386
function entity_metadata_user_set_properties($account, $name, $value) {
387
  switch ($name) {
388
    case 'roles':
389
      $account->roles = array_intersect_key(user_roles(), array_flip($value));
390
      break;
391
  }
392
}
393

    
394
/**
395
 * Options list callback returning all user roles.
396
 */
397
function entity_metadata_user_roles($property_name = 'roles', $info = array(), $op = 'edit') {
398
  $roles = user_roles();
399
  if ($op == 'edit') {
400
    unset($roles[DRUPAL_AUTHENTICATED_RID], $roles[DRUPAL_ANONYMOUS_RID]);
401
  }
402
  return $roles;
403
}
404

    
405
/**
406
 * Return the options lists for user status property.
407
 */
408
function entity_metadata_user_status_options_list() {
409
  return array(
410
    0 => t('Blocked'),
411
    1 => t('Active'),
412
  );
413
}
414

    
415
/**
416
 * Callback defining an options list for language properties.
417
 */
418
function entity_metadata_language_list() {
419
  $list = array();
420
  $list[LANGUAGE_NONE] = t('Language neutral');
421
  foreach (language_list() as $language) {
422
    $list[$language->language] = t($language->name);
423
  }
424
  return $list;
425
}
426

    
427
/**
428
 * Callback for getting field property values.
429
 */
430
function entity_metadata_field_property_get($entity, array $options, $name, $entity_type, $info) {
431
  $field = field_info_field($name);
432
  $columns = array_keys($field['columns']);
433
  $langcode = isset($options['language']) ? $options['language']->language : LANGUAGE_NONE;
434
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $field, $langcode, TRUE);
435
  $values = array();
436
  if (isset($entity->{$name}[$langcode])) {
437
    foreach ($entity->{$name}[$langcode] as $delta => $data) {
438
      $values[$delta] = $data[$columns[0]];
439
      if ($info['type'] == 'boolean' || $info['type'] == 'list<boolean>') {
440
        // Ensure that we have a clean boolean data type.
441
        $values[$delta] = (boolean) $values[$delta];
442
      }
443
    }
444
  }
445
  // For an empty single-valued field, we have to return NULL.
446
  return $field['cardinality'] == 1 ? ($values ? reset($values) : NULL) : $values;
447
}
448

    
449
/**
450
 * Callback for setting field property values.
451
 */
452
function entity_metadata_field_property_set($entity, $name, $value, $langcode, $entity_type, $info) {
453
  $field = field_info_field($name);
454
  $columns = array_keys($field['columns']);
455
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $field, $langcode);
456
  $values = $field['cardinality'] == 1 ? array($value) : (array) $value;
457

    
458
  $items = array();
459
  foreach ($values as $delta => $value) {
460
    if (isset($value)) {
461
      $items[$delta][$columns[0]] = $value;
462
      if ($info['type'] == 'boolean' || $info['type'] == 'list<boolean>') {
463
        // Convert boolean values back to an integer for writing.
464
        $items[$delta][$columns[0]] = (integer) $items[$delta][$columns[0]] = $value;
465
      }
466
    }
467
  }
468
  $entity->{$name}[$langcode] = $items;
469
  // Empty the static field language cache, so the field system picks up any
470
  // possible new languages.
471
  drupal_static_reset('field_language');
472
}
473

    
474
/**
475
 * Callback returning the options list of a field.
476
 */
477
function entity_metadata_field_options_list($name, $info) {
478
  $field_property_info = $info;
479
  if (is_numeric($name) && isset($info['parent'])) {
480
    // The options list is to be returned for a single item of a multiple field.
481
    $field_property_info = $info['parent']->info();
482
    $name = $field_property_info['name'];
483
  }
484
  if (($field = field_info_field($name)) && isset($field_property_info['parent'])) {
485
    // Retrieve the wrapped entity holding the field.
486
    $wrapper = $field_property_info['parent'];
487
    try {
488
      $entity = $wrapper->value();
489
    }
490
    catch (EntityMetadataWrapperException $e) {
491
      // No data available.
492
      $entity = NULL;
493
    }
494

    
495
    // Support translating labels via i18n field.
496
    if (module_exists('i18n_field') && ($translate = i18n_field_type_info($field['type'], 'translate_options'))) {
497
      return $translate($field);
498
    }
499
    else {
500
      $instance = $wrapper->getBundle() ? field_info_instance($wrapper->type(), $name, $wrapper->getBundle()) : NULL;
501
      return (array) module_invoke($field['module'], 'options_list', $field, $instance, $wrapper->type(), $entity);
502
    }
503
  }
504
}
505

    
506
/**
507
 * Callback to verbatim get the data structure of a field. Useful for fields
508
 * that add metadata for their own data structure.
509
 */
510
function entity_metadata_field_verbatim_get($entity, array $options, $name, $entity_type, &$context) {
511
  // Set contextual info useful for getters of any child properties.
512
  $context['instance'] = field_info_instance($context['parent']->type(), $name, $context['parent']->getBundle());
513
  $context['field'] = field_info_field($name);
514
  $langcode = isset($options['language']) ? $options['language']->language : LANGUAGE_NONE;
515
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $context['field'], $langcode, TRUE);
516

    
517
  if ($context['field']['cardinality'] == 1) {
518
    return isset($entity->{$name}[$langcode][0]) ? $entity->{$name}[$langcode][0] : NULL;
519
  }
520
  return isset($entity->{$name}[$langcode]) ? $entity->{$name}[$langcode] : array();
521
}
522

    
523
/**
524
 * Writes the passed field items in the object. Useful as field level setter
525
 * to set the whole data structure at once.
526
 */
527
function entity_metadata_field_verbatim_set($entity, $name, $items, $langcode, $entity_type) {
528
  $field = field_info_field($name);
529
  $langcode = entity_metadata_field_get_language($entity_type, $entity, $field, $langcode);
530
  $value = $field['cardinality'] == 1 ? array($items) : (array) $items;
531
  // Filter out any items set to NULL.
532
  $entity->{$name}[$langcode] = array_filter($value);
533

    
534
  // Empty the static field language cache, so the field system picks up any
535
  // possible new languages.
536
  drupal_static_reset('field_language');
537
}
538

    
539
/**
540
 * Helper for determining the field language to be used.
541
 *
542
 * Note that we cannot use field_language() as we are not about to display
543
 * values, but generally read/write values.
544
 *
545
 * @param $fallback
546
 *   (optional) Whether to fall back to the entity default language, if no
547
 *   value is available for the given language code yet.
548
 *
549
 * @return
550
 *   The language code to use.
551
 */
552
function entity_metadata_field_get_language($entity_type, $entity, $field, $langcode = LANGUAGE_NONE, $fallback = FALSE) {
553
  // Try to figure out the default language used by the entity.
554
  // With Drupal >= 7.15 we can use entity_language().
555
  if (function_exists('entity_language')) {
556
    $default_langcode = entity_language($entity_type, $entity);
557
  }
558
  else {
559
    $default_langcode = !empty($entity->language) ? $entity->language : LANGUAGE_NONE;
560
  }
561

    
562
  // Determine the right language to use.
563
  if ($default_langcode != LANGUAGE_NONE && field_is_translatable($entity_type, $field)) {
564
    $langcode = ($langcode != LANGUAGE_NONE) ? field_valid_language($langcode, $default_langcode) : $default_langcode;
565
    if (!isset($entity->{$field['field_name']}[$langcode]) && $fallback) {
566
      $langcode = $default_langcode;
567
    }
568
    return $langcode;
569
  }
570
  else {
571
    return LANGUAGE_NONE;
572
  }
573
}
574

    
575
/**
576
 * Callback for getting the sanitized text of 'text_formatted' properties.
577
 * This callback is used for both the 'value' and the 'summary'.
578
 */
579
function entity_metadata_field_text_get($item, array $options, $name, $type, $context) {
580
  // $name is either 'value' or 'summary'.
581
  if (!isset($item['safe_' . $name])) {
582
    // Apply input formats.
583
    $langcode = isset($options['language']) ? $options['language']->language : '';
584
    $format = isset($item['format']) ? $item['format'] : filter_default_format();
585
    $item['safe_' . $name] = check_markup($item[$name], $format, $langcode);
586
    // To speed up subsequent calls, update $item with the 'safe_value'.
587
    $context['parent']->set($item);
588
  }
589
  return $item['safe_' . $name];
590
}
591

    
592
/**
593
 * Defines the list of all available text formats.
594
 */
595
function entity_metadata_field_text_formats() {
596
  foreach (filter_formats() as $key => $format) {
597
    $formats[$key] = $format->name;
598
  }
599
  return $formats;
600
}
601

    
602
/**
603
 * Callback for getting the file entity of file fields.
604
 */
605
function entity_metadata_field_file_get($item) {
606
  return $item['fid'];
607
}
608

    
609
/**
610
 * Callback for setting the file entity of file fields.
611
 */
612
function entity_metadata_field_file_set(&$item, $property_name, $value) {
613
  $item['fid'] = $value;
614
}
615

    
616
/**
617
 * Callback for auto-creating file field $items.
618
 */
619
function entity_metadata_field_file_create_item($property_name, $context) {
620
  // 'fid' is required, so 'file' has to be set as initial property.
621
  return array('display' => isset($context['field']['settings']['display_default']) ? $context['field']['settings']['display_default'] : 0);
622
}
623

    
624
/**
625
 * Callback for validating file field $items.
626
 */
627
function entity_metadata_field_file_validate_item($items, $context) {
628
  // Allow NULL values.
629
  if (!isset($items)) {
630
    return TRUE;
631
  }
632

    
633
  // Stream-line $items for multiple vs non-multiple fields.
634
  $items = !entity_property_list_extract_type($context['type']) ? array($items) : (array) $items;
635

    
636
  foreach ($items as $item) {
637
    // File-field items require a valid file.
638
    if (!isset($item['fid']) || !file_load($item['fid'])) {
639
      return FALSE;
640
    }
641
    if (isset($context['property info']['display']) && !isset($item['display'])) {
642
      return FALSE;
643
    }
644
  }
645
  return TRUE;
646
}
647

    
648
/**
649
 * Access callback for the node entity.
650
 *
651
 * This function does not implement hook_node_access(), thus it may not be
652
 * called entity_metadata_node_access().
653
 *
654
 * @see entity_access()
655
 *
656
 * @param $op
657
 *   The operation being performed. One of 'view', 'update', 'create' or
658
 *   'delete'.
659
 * @param $node
660
 *   A node to check access for. Must be a node object. Must have nid,
661
 *   except in the case of 'create' operations.
662
 * @param $account
663
 *   The user to check for. Leave it to NULL to check for the global user.
664
 *
665
 * @throws EntityMalformedException
666
 *
667
 * @return boolean
668
 *   TRUE if access is allowed, FALSE otherwise.
669
 */
670
function entity_metadata_no_hook_node_access($op, $node = NULL, $account = NULL) {
671
  // First deal with the case where a $node is provided.
672
  if (isset($node)) {
673
    if (empty($node->vid) && in_array($op, array('create', 'update'))) {
674
      // This is a new node or the original node.
675
      if (isset($node->type)) {
676
        $op = empty($node->nid) || !empty($node->is_new) ? 'create' : 'update';
677
        return node_access($op, $op == 'create' ? $node->type : $node, $account);
678
      }
679
      else {
680
        throw new EntityMalformedException('Permission to create a node was requested but no node type was given.');
681
      }
682
    }
683
    // If a non-default revision is given, incorporate revision access.
684
    $default_revision = node_load($node->nid);
685
    if ($node->vid !== $default_revision->vid) {
686
      return _node_revision_access($node, $op, $account);
687
    }
688
    else {
689
      return node_access($op, $node, $account);
690
    }
691
  }
692
  // No node is provided. Check for access to all nodes.
693
  if (user_access('bypass node access', $account)) {
694
    return TRUE;
695
  }
696
  if (!user_access('access content', $account)) {
697
    return FALSE;
698
  }
699
  if ($op == 'view' && node_access_view_all_nodes($account)) {
700
    return TRUE;
701
  }
702
  return FALSE;
703
}
704

    
705
/**
706
 * Access callback for the user entity.
707
 */
708
function entity_metadata_user_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
709
  $account = isset($account) ? $account : $GLOBALS['user'];
710
  // Grant access to the users own user account and to the anonymous one.
711
  if (isset($entity->uid) && $op != 'delete' && (($entity->uid == $account->uid && $entity->uid) || (!$entity->uid && $op == 'view'))) {
712
    return TRUE;
713
  }
714
  if (user_access('administer users', $account)
715
    || user_access('access user profiles', $account) && $op == 'view' && (empty($entity) || !empty($entity->status))) {
716
    return TRUE;
717
  }
718
  return FALSE;
719
}
720

    
721
/**
722
 * Access callback for restricted user properties.
723
 */
724
function entity_metadata_user_properties_access($op, $property, $entity = NULL, $account = NULL) {
725
  if (user_access('administer users', $account)) {
726
    return TRUE;
727
  }
728
  $account = isset($account) ? $account : $GLOBALS['user'];
729
  // Flag to indicate if this user entity is the own user account.
730
  $is_own_account = isset($entity->uid) && $account->uid == $entity->uid;
731
  switch ($property) {
732
    case 'name':
733
      // Allow view access to anyone with access to the entity.
734
      if ($op == 'view') {
735
        return TRUE;
736
      }
737
      // Allow edit access for own user name if the permission is satisfied.
738
      return $is_own_account && user_access('change own username', $account);
739
    case 'mail':
740
      // Allow access to own mail address.
741
      return $is_own_account;
742
    case 'roles':
743
      // Allow view access for own roles.
744
      return ($op == 'view' && $is_own_account);
745
  }
746
  return FALSE;
747
}
748

    
749
/**
750
 * Access callback for the comment entity.
751
 */
752
function entity_metadata_comment_access($op, $entity = NULL, $account = NULL) {
753
  // When determining access to a comment, 'comment_access' does not take any
754
  // access restrictions to the comment's associated node into account. If a
755
  // comment has an associated node, the user must be able to view it in order
756
  // to access the comment.
757
  if (isset($entity->nid)) {
758
    if (!entity_access('view', 'node', node_load($entity->nid), $account)) {
759
      return FALSE;
760
    }
761
  }
762

    
763
  // Comment administrators are allowed to perform all operations on all
764
  // comments.
765
  if (user_access('administer comments', $account)) {
766
    return TRUE;
767
  }
768

    
769
  // Unpublished comments can never be accessed by non-admins.
770
  if (isset($entity->status) && $entity->status == COMMENT_NOT_PUBLISHED) {
771
    return FALSE;
772
  }
773

    
774
  if (isset($entity) && $op == 'update') {
775
    // Because 'comment_access' only checks the current user, we need to do our
776
    // own access checking if an account was specified.
777
    if (!isset($account)) {
778
      return comment_access('edit', $entity);
779
    }
780
    else {
781
      return $account->uid && $account->uid == $entity->uid && user_access('edit own comments', $account);
782
    }
783
  }
784
  if (user_access('access comments', $account) && $op == 'view') {
785
    return TRUE;
786
  }
787
  return FALSE;
788
}
789

    
790
/**
791
 * Access callback for restricted comment properties.
792
 */
793
function entity_metadata_comment_properties_access($op, $property, $entity = NULL, $account = NULL) {
794
  return user_access('administer comments', $account);
795
}
796

    
797
/**
798
 * Access callback for the taxonomy entities.
799
 */
800
function entity_metadata_taxonomy_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
801
  // If user has administer taxonomy permission then no further checks.
802
  if (user_access('administer taxonomy', $account)) {
803
    return TRUE;
804
  }
805
  switch ($op) {
806
    case "view":
807
      if (user_access('access content', $account)) {
808
        return TRUE;
809
      }
810
      break;
811
    case "update":
812
      if ($entity_type == 'taxonomy_term') {
813
        return user_access("edit terms in $entity->vid", $account);
814
      }
815
      break;
816
    case "create":
817
      if ($entity_type == 'taxonomy_term') {
818
        // Check for taxonomy_access_fix contrib module which adds additional
819
        // permissions to create new terms in a given vocabulary.
820
        if (function_exists('taxonomy_access_fix_access')) {
821
          return taxonomy_access_fix_access('add terms', $entity->vocabulary_machine_name);
822
        }
823
      }
824
      break;
825
    case "delete":
826
      if ($entity_type == 'taxonomy_term') {
827
        return user_access("delete terms in $entity->vid", $account);
828
      }
829
      break;
830
  }
831
  return FALSE;
832
}
833

    
834
/**
835
 * Access callback for file entities.
836
 */
837
function entity_metadata_file_access($op, $file = NULL, $account = NULL, $entity_type) {
838
  // We can only check access for the current user, so return FALSE on other accounts.
839
  global $user;
840
  if ($op == 'view' && isset($file) && (!isset($account) || $user->uid == $account->uid)) {
841
    // Invoke hook_file_download() to obtain access information.
842
    foreach (module_implements('file_download') as $module) {
843
      $result = module_invoke($module, 'file_download', $file->uri);
844
      if ($result == -1) {
845
        return FALSE;
846
      }
847
    }
848
    return TRUE;
849
  }
850
  return FALSE;
851
}
852

    
853

    
854
/**
855
 * Callback to determine access for properties which are fields.
856
 */
857
function entity_metadata_field_access_callback($op, $name, $entity = NULL, $account = NULL, $entity_type) {
858
  $field = field_info_field($name);
859
  return field_access($op, $field, $entity_type, $entity, $account);
860
}
861

    
862
/**
863
 * Callback to create entity objects.
864
 */
865
function entity_metadata_create_object($values = array(), $entity_type) {
866
  $info = entity_get_info($entity_type);
867
  // Make sure at least the bundle and label properties are set.
868
  if (isset($info['entity keys']['bundle']) && $key = $info['entity keys']['bundle']) {
869
    $values += array($key => NULL);
870
  }
871
  if (isset($info['entity keys']['label']) && $key = $info['entity keys']['label']) {
872
    $values += array($key => NULL);
873
  }
874
  $entity = (object) $values;
875
  $entity->is_new = TRUE;
876
  return $entity;
877
}
878

    
879
/**
880
 * Callback to create a new comment.
881
 */
882
function entity_metadata_create_comment($values = array()) {
883
  $comment = (object) ($values + array(
884
    'status' => COMMENT_PUBLISHED,
885
    'pid' => 0,
886
    'subject' => '',
887
    'uid' => 0,
888
    'language' => LANGUAGE_NONE,
889
    'node_type' => NULL,
890
    'is_new' => TRUE,
891
  ));
892
  $comment->cid = FALSE;
893
  return $comment;
894
}
895

    
896
/**
897
 * Callback to create a new node.
898
 */
899
function entity_metadata_create_node($values = array()) {
900
  $node = (object) array(
901
    'type' => $values['type'],
902
    'language' => LANGUAGE_NONE,
903
    'is_new' => TRUE,
904
  );
905
  // Set some defaults.
906
  $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
907
  foreach (array('status', 'promote', 'sticky') as $key) {
908
    $node->$key = (int) in_array($key, $node_options);
909
  }
910
  if (module_exists('comment') && !isset($node->comment)) {
911
    $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
912
  }
913
  // Apply the given values.
914
  foreach ($values as $key => $value) {
915
    $node->$key = $value;
916
  }
917
  return $node;
918
}
919

    
920
/**
921
 * Callback to save a user account.
922
 */
923
function entity_metadata_user_save($account) {
924
  $edit = (array) $account;
925
  // Don't save the hashed password as password.
926
  unset($edit['pass']);
927
  user_save($account, $edit);
928
}
929

    
930
/**
931
 * Callback to delete a file.
932
 * Watch out to not accidentilly implement hook_file_delete().
933
 */
934
function entity_metadata_delete_file($fid) {
935
  file_delete(file_load($fid), TRUE);
936
}
937

    
938
/**
939
 * Callback to view nodes.
940
 */
941
function entity_metadata_view_node($entities, $view_mode = 'full', $langcode = NULL) {
942
  $result = node_view_multiple($entities, $view_mode, 0, $langcode);
943
  // Make sure to key the result with 'node' instead of 'nodes'.
944
  return array('node' => reset($result));
945
}
946

    
947
/**
948
 * Callback to view comments.
949
 */
950
function entity_metadata_view_comment($entities, $view_mode = 'full', $langcode = NULL) {
951
  $build = array();
952
  $nodes = array();
953
  // The comments, indexed by nid and then by cid.
954
  $nid_comments = array();
955
  foreach ($entities as $cid => $comment) {
956
    $nid = $comment->nid;
957
    $nodes[$nid] = $nid;
958
    $nid_comments[$nid][$cid] = $comment;
959
  }
960
  $nodes = node_load_multiple(array_keys($nodes));
961
  foreach ($nid_comments as $nid => $comments) {
962
    $node = isset($nodes[$nid]) ? $nodes[$nid] : NULL;
963
    $build += comment_view_multiple($comments, $node, $view_mode, 0, $langcode);
964
  }
965
  return array('comment' => $build);
966
}
967

    
968
/**
969
 * Callback to view an entity, for which just ENTITYTYPE_view() is available.
970
 */
971
function entity_metadata_view_single($entities, $view_mode = 'full', $langcode = NULL, $entity_type) {
972
  $function = $entity_type . '_view';
973
  $build = array();
974
  foreach ($entities as $key => $entity) {
975
    $build[$entity_type][$key] = $function($entity, $view_mode, $langcode);
976
  }
977
  return $build;
978
}
979

    
980
/**
981
 * Callback to get the form of a node.
982
 */
983
function entity_metadata_form_node($node) {
984
  // Pre-populate the form-state with the right form include.
985
  $form_state['build_info']['args'] = array($node);
986
  form_load_include($form_state, 'inc', 'node', 'node.pages');
987
  return drupal_build_form($node->type . '_node_form', $form_state);
988
}
989

    
990
/**
991
 * Callback to get the form of a comment.
992
 */
993
function entity_metadata_form_comment($comment) {
994
  if (!isset($comment->node_type)) {
995
    $node = node_load($comment->nid);
996
    $comment->node_type = 'comment_node_' . $node->type;
997
  }
998
  return drupal_get_form($comment->node_type . '_form', $comment);
999
}
1000

    
1001
/**
1002
 * Callback to get the form of a user account.
1003
 */
1004
function entity_metadata_form_user($account) {
1005
  // If $account->uid is set then we want a user edit form.
1006
  // Otherwise we want the user register form.
1007
  if (isset($account->uid)) {
1008
    $form_id = 'user_profile_form';
1009
    form_load_include($form_state, 'inc', 'user', 'user.pages');
1010
  }
1011
  else {
1012
    $form_id = 'user_register_form';
1013
  }
1014
  $form_state['build_info']['args'] = array($account);
1015
  return drupal_build_form($form_id, $form_state);
1016
}
1017

    
1018
/**
1019
 * Callback to get the form of a term.
1020
 */
1021
function entity_metadata_form_taxonomy_term($term) {
1022
  // Pre-populate the form-state with the right form include.
1023
  $form_state['build_info']['args'] = array($term);
1024
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');
1025
  return drupal_build_form('taxonomy_form_term', $form_state);
1026
}
1027

    
1028
/**
1029
 * Callback to get the form of a vocabulary.
1030
 */
1031
function entity_metadata_form_taxonomy_vocabulary($vocab) {
1032
  // Pre-populate the form-state with the right form include.
1033
  $form_state['build_info']['args'] = array($vocab);
1034
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');
1035
  return drupal_build_form('taxonomy_form_vocabulary', $form_state);
1036
}
1037

    
1038
/**
1039
 * Callback to get the form for entities using the entity API admin ui.
1040
 */
1041
function entity_metadata_form_entity_ui($entity, $entity_type) {
1042
  $info = entity_get_info($entity_type);
1043
  $form_state = form_state_defaults();
1044
  // Add in the include file as the form API does else with the include file
1045
  // specified for the active menu item.
1046
  if (!empty($info['admin ui']['file'])) {
1047
    $path = isset($info['admin ui']['file path']) ? $info['admin ui']['file path'] : drupal_get_path('module', $info['module']);
1048
    $form_state['build_info']['files']['entity_ui'] = $path . '/' . $info['admin ui']['file'];
1049
    // Also load the include file.
1050
    if (file_exists($form_state['build_info']['files']['entity_ui'])) {
1051
      require_once DRUPAL_ROOT . '/' . $form_state['build_info']['files']['entity_ui'];
1052
    }
1053
  }
1054
  return entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state);
1055
}
1056

    
1057
/**
1058
 * Callback for querying entity properties having their values stored in the
1059
 * entities main db table.
1060
 */
1061
function entity_metadata_table_query($entity_type, $property, $value, $limit) {
1062
  $properties = entity_get_all_property_info($entity_type);
1063
  $info = $properties[$property] + array('schema field' => $property);
1064

    
1065
  $query = new EntityFieldQuery();
1066
  $query->entityCondition('entity_type', $entity_type, '=')
1067
        ->propertyCondition($info['schema field'], $value, is_array($value) ? 'IN' : '=')
1068
        ->range(0, $limit);
1069

    
1070
  $result = $query->execute();
1071
  return !empty($result[$entity_type]) ? array_keys($result[$entity_type]) : array();
1072
}
1073

    
1074
/**
1075
 * Callback for querying entities by field values. This function just queries
1076
 * for the value of the first specified column. Also it is only suitable for
1077
 * fields that don't process the data, so it's stored the same way as returned.
1078
 */
1079
function entity_metadata_field_query($entity_type, $property, $value, $limit) {
1080
  $query = new EntityFieldQuery();
1081
  $field = field_info_field($property);
1082
  $columns = array_keys($field['columns']);
1083

    
1084
  $query->entityCondition('entity_type', $entity_type, '=')
1085
        ->fieldCondition($field, $columns[0], $value, is_array($value) ? 'IN' : '=')
1086
        ->range(0, $limit);
1087

    
1088
  $result = $query->execute();
1089
  return !empty($result[$entity_type]) ? array_keys($result[$entity_type]) : array();
1090
}
1091

    
1092
/**
1093
 * Implements entity_uri() callback for file entities.
1094
 */
1095
function entity_metadata_uri_file($file) {
1096
  return array(
1097
    'path' => file_create_url($file->uri),
1098
  );
1099
}