Project

General

Profile

Paste
Download (33.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / entity / modules / callbacks.inc @ 7d7b5830

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'])) {
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 ($op == 'create') {
674
      if (isset($node->type)) {
675
        return node_access($op, $node->type, $account);
676
      }
677
      else {
678
        throw new EntityMalformedException('Permission to create a node was requested but no node type was given.');
679
      }
680
    }
681
    // If a non-default revision is given, incorporate revision access.
682
    $default_revision = node_load($node->nid);
683
    if ($node->vid !== $default_revision->vid) {
684
      return _node_revision_access($node, $op, $account);
685
    }
686
    else {
687
      return node_access($op, $node, $account);
688
    }
689
  }
690
  // No node is provided. Check for access to all nodes.
691
  if (user_access('bypass node access', $account)) {
692
    return TRUE;
693
  }
694
  if (!user_access('access content', $account)) {
695
    return FALSE;
696
  }
697
  if ($op == 'view' && node_access_view_all_nodes($account)) {
698
    return TRUE;
699
  }
700
  return FALSE;
701
}
702

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

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

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

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

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

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

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

    
795
/**
796
 * Access callback for the taxonomy entities.
797
 */
798
function entity_metadata_taxonomy_access($op, $entity = NULL, $account = NULL, $entity_type = NULL) {
799
  if ($entity_type == 'taxonomy_vocabulary') {
800
    return user_access('administer taxonomy', $account);
801
  }
802
  if (isset($entity) && $op == 'update' && !isset($account) && taxonomy_term_edit_access($entity)) {
803
    return TRUE;
804
  }
805
  if (user_access('administer taxonomy', $account) || user_access('access content', $account) && $op == 'view') {
806
    return TRUE;
807
  }
808
  return FALSE;
809
}
810

    
811
/**
812
 * Access callback for file entities.
813
 */
814
function entity_metadata_file_access($op, $file = NULL, $account = NULL, $entity_type) {
815
  // We can only check access for the current user, so return FALSE on other accounts.
816
  global $user;
817
  if ($op == 'view' && isset($file) && (!isset($account) || $user->uid == $account->uid)) {
818
    // Invoke hook_file_download() to obtain access information.
819
    foreach (module_implements('file_download') as $module) {
820
      $result = module_invoke($module, 'file_download', $file->uri);
821
      if ($result == -1) {
822
        return FALSE;
823
      }
824
    }
825
    return TRUE;
826
  }
827
  return FALSE;
828
}
829

    
830

    
831
/**
832
 * Callback to determine access for properties which are fields.
833
 */
834
function entity_metadata_field_access_callback($op, $name, $entity = NULL, $account = NULL, $entity_type) {
835
  $field = field_info_field($name);
836
  return field_access($op, $field, $entity_type, $entity, $account);
837
}
838

    
839
/**
840
 * Callback to create entity objects.
841
 */
842
function entity_metadata_create_object($values = array(), $entity_type) {
843
  $info = entity_get_info($entity_type);
844
  // Make sure at least the bundle and label properties are set.
845
  if (isset($info['entity keys']['bundle']) && $key = $info['entity keys']['bundle']) {
846
    $values += array($key => NULL);
847
  }
848
  if (isset($info['entity keys']['label']) && $key = $info['entity keys']['label']) {
849
    $values += array($key => NULL);
850
  }
851
  $entity = (object) $values;
852
  $entity->is_new = TRUE;
853
  return $entity;
854
}
855

    
856
/**
857
 * Callback to create a new comment.
858
 */
859
function entity_metadata_create_comment($values = array()) {
860
  $comment = (object) ($values + array(
861
    'status' => COMMENT_PUBLISHED,
862
    'pid' => 0,
863
    'subject' => '',
864
    'uid' => 0,
865
    'language' => LANGUAGE_NONE,
866
    'node_type' => NULL,
867
    'is_new' => TRUE,
868
  ));
869
  $comment->cid = FALSE;
870
  return $comment;
871
}
872

    
873
/**
874
 * Callback to create a new node.
875
 */
876
function entity_metadata_create_node($values = array()) {
877
  $node = (object) array(
878
    'type' => $values['type'],
879
    'language' => LANGUAGE_NONE,
880
    'is_new' => TRUE,
881
  );
882
  // Set some defaults.
883
  $node_options = variable_get('node_options_' . $node->type, array('status', 'promote'));
884
  foreach (array('status', 'promote', 'sticky') as $key) {
885
    $node->$key = (int) in_array($key, $node_options);
886
  }
887
  if (module_exists('comment') && !isset($node->comment)) {
888
    $node->comment = variable_get("comment_$node->type", COMMENT_NODE_OPEN);
889
  }
890
  // Apply the given values.
891
  foreach ($values as $key => $value) {
892
    $node->$key = $value;
893
  }
894
  return $node;
895
}
896

    
897
/**
898
 * Callback to save a user account.
899
 */
900
function entity_metadata_user_save($account) {
901
  $edit = (array) $account;
902
  // Don't save the hashed password as password.
903
  unset($edit['pass']);
904
  user_save($account, $edit);
905
}
906

    
907
/**
908
 * Callback to delete a file.
909
 * Watch out to not accidentilly implement hook_file_delete().
910
 */
911
function entity_metadata_delete_file($fid) {
912
  file_delete(file_load($fid), TRUE);
913
}
914

    
915
/**
916
 * Callback to view nodes.
917
 */
918
function entity_metadata_view_node($entities, $view_mode = 'full', $langcode = NULL) {
919
  $result = node_view_multiple($entities, $view_mode, 0, $langcode);
920
  // Make sure to key the result with 'node' instead of 'nodes'.
921
  return array('node' => reset($result));
922
}
923

    
924
/**
925
 * Callback to view comments.
926
 */
927
function entity_metadata_view_comment($entities, $view_mode = 'full', $langcode = NULL) {
928
  $build = array();
929
  $nodes = array();
930
  // The comments, indexed by nid and then by cid.
931
  $nid_comments = array();
932
  foreach ($entities as $cid => $comment) {
933
    $nid = $comment->nid;
934
    $nodes[$nid] = $nid;
935
    $nid_comments[$nid][$cid] = $comment;
936
  }
937
  $nodes = node_load_multiple(array_keys($nodes));
938
  foreach ($nid_comments as $nid => $comments) {
939
    $node = isset($nodes[$nid]) ? $nodes[$nid] : NULL;
940
    $build += comment_view_multiple($comments, $node, $view_mode, 0, $langcode);
941
  }
942
  return array('comment' => $build);
943
}
944

    
945
/**
946
 * Callback to view an entity, for which just ENTITYTYPE_view() is available.
947
 */
948
function entity_metadata_view_single($entities, $view_mode = 'full', $langcode = NULL, $entity_type) {
949
  $function = $entity_type . '_view';
950
  $build = array();
951
  foreach ($entities as $key => $entity) {
952
    $build[$entity_type][$key] = $function($entity, $view_mode, $langcode);
953
  }
954
  return $build;
955
}
956

    
957
/**
958
 * Callback to get the form of a node.
959
 */
960
function entity_metadata_form_node($node) {
961
  // Pre-populate the form-state with the right form include.
962
  $form_state['build_info']['args'] = array($node);
963
  form_load_include($form_state, 'inc', 'node', 'node.pages');
964
  return drupal_build_form($node->type . '_node_form', $form_state);
965
}
966

    
967
/**
968
 * Callback to get the form of a comment.
969
 */
970
function entity_metadata_form_comment($comment) {
971
  if (!isset($comment->node_type)) {
972
    $node = node_load($comment->nid);
973
    $comment->node_type = 'comment_node_' . $node->type;
974
  }
975
  return drupal_get_form($comment->node_type . '_form', $comment);
976
}
977

    
978
/**
979
 * Callback to get the form of a user account.
980
 */
981
function entity_metadata_form_user($account) {
982
  // If $account->uid is set then we want a user edit form.
983
  // Otherwise we want the user register form.
984
  if (isset($account->uid)) {
985
    $form_id = 'user_profile_form';
986
    form_load_include($form_state, 'inc', 'user', 'user.pages');
987
  }
988
  else {
989
    $form_id = 'user_register_form';
990
  }
991
  $form_state['build_info']['args'] = array($account);
992
  return drupal_build_form($form_id, $form_state);
993
}
994

    
995
/**
996
 * Callback to get the form of a term.
997
 */
998
function entity_metadata_form_taxonomy_term($term) {
999
  // Pre-populate the form-state with the right form include.
1000
  $form_state['build_info']['args'] = array($term);
1001
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');
1002
  return drupal_build_form('taxonomy_form_term', $form_state);
1003
}
1004

    
1005
/**
1006
 * Callback to get the form of a vocabulary.
1007
 */
1008
function entity_metadata_form_taxonomy_vocabulary($vocab) {
1009
  // Pre-populate the form-state with the right form include.
1010
  $form_state['build_info']['args'] = array($vocab);
1011
  form_load_include($form_state, 'inc', 'taxonomy', 'taxonomy.admin');
1012
  return drupal_build_form('taxonomy_form_vocabulary', $form_state);
1013
}
1014

    
1015
/**
1016
 * Callback to get the form for entities using the entity API admin ui.
1017
 */
1018
function entity_metadata_form_entity_ui($entity, $entity_type) {
1019
  $info = entity_get_info($entity_type);
1020
  $form_state = form_state_defaults();
1021
  // Add in the include file as the form API does else with the include file
1022
  // specified for the active menu item.
1023
  if (!empty($info['admin ui']['file'])) {
1024
    $path = isset($info['admin ui']['file path']) ? $info['admin ui']['file path'] : drupal_get_path('module', $info['module']);
1025
    $form_state['build_info']['files']['entity_ui'] = $path . '/' . $info['admin ui']['file'];
1026
    // Also load the include file.
1027
    if (file_exists($form_state['build_info']['files']['entity_ui'])) {
1028
      require_once DRUPAL_ROOT . '/' . $form_state['build_info']['files']['entity_ui'];
1029
    }
1030
  }
1031
  return entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state);
1032
}
1033

    
1034
/**
1035
 * Callback for querying entity properties having their values stored in the
1036
 * entities main db table.
1037
 */
1038
function entity_metadata_table_query($entity_type, $property, $value, $limit) {
1039
  $properties = entity_get_all_property_info($entity_type);
1040
  $info = $properties[$property] + array('schema field' => $property);
1041

    
1042
  $query = new EntityFieldQuery();
1043
  $query->entityCondition('entity_type', $entity_type, '=')
1044
        ->propertyCondition($info['schema field'], $value, is_array($value) ? 'IN' : '=')
1045
        ->range(0, $limit);
1046

    
1047
  $result = $query->execute();
1048
  return !empty($result[$entity_type]) ? array_keys($result[$entity_type]) : array();
1049
}
1050

    
1051
/**
1052
 * Callback for querying entities by field values. This function just queries
1053
 * for the value of the first specified column. Also it is only suitable for
1054
 * fields that don't process the data, so it's stored the same way as returned.
1055
 */
1056
function entity_metadata_field_query($entity_type, $property, $value, $limit) {
1057
  $query = new EntityFieldQuery();
1058
  $field = field_info_field($property);
1059
  $columns = array_keys($field['columns']);
1060

    
1061
  $query->entityCondition('entity_type', $entity_type, '=')
1062
        ->fieldCondition($field, $columns[0], $value, is_array($value) ? 'IN' : '=')
1063
        ->range(0, $limit);
1064

    
1065
  $result = $query->execute();
1066
  return !empty($result[$entity_type]) ? array_keys($result[$entity_type]) : array();
1067
}
1068

    
1069
/**
1070
 * Implements entity_uri() callback for file entities.
1071
 */
1072
function entity_metadata_uri_file($file) {
1073
  return array(
1074
    'path' => file_create_url($file->uri),
1075
  );
1076
}