Projet

Général

Profil

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

root / htmltest / sites / all / modules / entity / entity.module @ dd54aff9

1
<?php
2

    
3
/**
4
 * @file
5
 * Module file for the entity API.
6
 */
7

    
8
module_load_include('inc', 'entity', 'modules/callbacks');
9
module_load_include('inc', 'entity', 'includes/entity.property');
10

    
11

    
12
/**
13
 * Defines status codes used for exportable entities.
14
 */
15

    
16
/**
17
 * A bit flag used to let us know if an entity is in the database.
18
 */
19

    
20

    
21
/**
22
 * A bit flag used to let us know if an entity has been customly defined.
23
 */
24
define('ENTITY_CUSTOM', 0x01);
25

    
26
/**
27
 * Deprecated, but still here for backward compatibility.
28
 */
29
define('ENTITY_IN_DB', 0x01);
30

    
31
/**
32
 * A bit flag used to let us know if an entity is a 'default' in code.
33
 */
34
define('ENTITY_IN_CODE', 0x02);
35

    
36
/**
37
 * A bit flag used to mark entities as overridden, e.g. they were originally
38
 * definded in code and are saved now in the database. Same as
39
 * (ENTITY_CUSTOM | ENTITY_IN_CODE).
40
 */
41
define('ENTITY_OVERRIDDEN', 0x03);
42

    
43
/**
44
 * A bit flag used to mark entities as fixed, thus not changeable for any
45
 * user.
46
 */
47
define('ENTITY_FIXED', 0x04 | 0x02);
48

    
49

    
50

    
51
/**
52
 * Determines whether for the given entity type a given operation is available.
53
 *
54
 * @param $entity_type
55
 *   The type of the entity.
56
 * @param $op
57
 *   One of 'create', 'view', 'save', 'delete', 'revision delete', 'access' or
58
 *   'form'.
59
 *
60
 * @return boolean
61
 *   Whether the entity type supports the given operation.
62
 */
63
function entity_type_supports($entity_type, $op) {
64
  $info = entity_get_info($entity_type);
65
  $keys = array(
66
    'view' => 'view callback',
67
    'create' => 'creation callback',
68
    'delete' => 'deletion callback',
69
    'revision delete' => 'revision deletion callback',
70
    'save' => 'save callback',
71
    'access' => 'access callback',
72
    'form' => 'form callback'
73
  );
74
  if (isset($info[$keys[$op]])) {
75
    return TRUE;
76
  }
77
  if ($op == 'revision delete') {
78
    return in_array('EntityAPIControllerInterface', class_implements($info['controller class']));
79
  }
80
  if ($op == 'form') {
81
    return (bool) entity_ui_controller($entity_type);
82
  }
83
  if ($op != 'access') {
84
    return in_array('EntityAPIControllerInterface', class_implements($info['controller class']));
85
  }
86
  return FALSE;
87
}
88

    
89
/**
90
 * Menu loader function: load an entity from its path.
91
 *
92
 * This can be used to load entities of all types in menu paths:
93
 *
94
 * @code
95
 * $items['myentity/%entity_object'] = array(
96
 *   'load arguments' => array('myentity'),
97
 *   'title' => ...,
98
 *   'page callback' => ...,
99
 *   'page arguments' => array(...),
100
 *   'access arguments' => array(...),
101
 * );
102
 * @endcode
103
 *
104
 * @param $entity_id
105
 *   The ID of the entity to load, passed by the menu URL.
106
 * @param $entity_type
107
 *   The type of the entity to load.
108
 * @return
109
 *   A fully loaded entity object, or FALSE in case of error.
110
 */
111
function entity_object_load($entity_id, $entity_type) {
112
  $entities = entity_load($entity_type, array($entity_id));
113
  return reset($entities);
114
}
115

    
116
/**
117
 * Page callback to show links to add an entity of a specific bundle.
118
 *
119
 * Entity modules that provide a further description to their bundles may wish
120
 * to implement their own version of this to show these.
121
 *
122
 * @param $entity_type
123
 *   The type of the entity.
124
 */
125
function entity_ui_bundle_add_page($entity_type) {
126
  // Set the title, as we're a MENU_LOCAL_ACTION and hence just get tab titles.
127
  module_load_include('inc', 'entity', 'includes/entity.ui');
128
  drupal_set_title(entity_ui_get_action_title('add', $entity_type));
129

    
130
  // Get entity info for our bundles.
131
  $info = entity_get_info($entity_type);
132
  $items = array();
133
  foreach ($info['bundles'] as $bundle_name => $bundle_info) {
134
    // Create an empty entity with just the bundle set to check for access.
135
    $dummy_entity = entity_create($entity_type, array(
136
      $info['entity keys']['bundle'] => $bundle_name,
137
    ));
138
    // If modules use a uid, they can default to the current-user
139
    // in their create() method on the storage controller.
140
    if (entity_access('create', $entity_type, $dummy_entity, $account = NULL)) {
141
      $add_path = $info['admin ui']['path'] . '/add/' . $bundle_name;
142
      $items[] = l(t('Add @label', array('@label' => $bundle_info['label'])), $add_path);
143
    }
144
  }
145
  return theme('item_list', array('items' => $items));
146
}
147

    
148
/**
149
 * Page callback to add an entity of a specific bundle.
150
 *
151
 * @param $entity_type
152
 *   The type of the entity.
153
 * @param $bundle_name
154
 *   The bundle machine name.
155
 */
156
function entity_ui_get_bundle_add_form($entity_type, $bundle_name) {
157
  $info = entity_get_info($entity_type);
158
  $bundle_key = $info['entity keys']['bundle'];
159

    
160
  // Make a stub entity of the right bundle to pass to the entity_ui_get_form().
161
  $values = array(
162
    $bundle_key => $bundle_name,
163
  );
164
  $entity = entity_create($entity_type, $values);
165

    
166
  return entity_ui_get_form($entity_type, $entity, 'add');
167
}
168

    
169
/**
170
 * Page callback for viewing an entity.
171
 *
172
 * @param Entity $entity
173
 *   The entity to be rendered.
174
 *
175
 * @return array
176
 *   A renderable array of the entity in full view mode.
177
 */
178
function entity_ui_entity_page_view($entity) {
179
  module_load_include('inc', 'entity', 'includes/entity.ui');
180
  return $entity->view('full', NULL, TRUE);
181
}
182

    
183
/**
184
 * Gets the page title for the passed operation.
185
 */
186
function entity_ui_get_page_title($op, $entity_type, $entity = NULL) {
187
  module_load_include('inc', 'entity', 'includes/entity.ui');
188
  $label = entity_label($entity_type, $entity);
189
  switch ($op) {
190
    case 'view':
191
      return $label;
192
    case 'edit':
193
      return t('Edit @label', array('@label' => $label));
194
    case 'clone':
195
      return t('Clone @label', array('@label' => $label));
196
    case 'revert':
197
      return t('Revert @label', array('@label' => $label));
198
    case 'delete':
199
      return t('Delete @label', array('@label' => $label));
200
    case 'export':
201
      return t('Export @label', array('@label' => $label));
202
  }
203
  if (isset($entity)) {
204
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
205
  }
206
  return entity_ui_get_action_title($op, $entity_type, $bundle);
207
}
208

    
209
/**
210
 * A wrapper around entity_load() to load a single entity by name or numeric id.
211
 *
212
 * @todo: Re-name entity_load() to entity_load_multiple() in d8 core and this
213
 * to entity_load().
214
 *
215
 * @param $entity_type
216
 *   The entity type to load, e.g. node or user.
217
 * @param $id
218
 *   The entity id, either the numeric id or the entity name. In case the entity
219
 *   type has specified a name key, both the numeric id and the name may be
220
 *   passed.
221
 *
222
 * @return
223
 *   The entity object, or FALSE.
224
 *
225
 * @see entity_load()
226
 */
227
function entity_load_single($entity_type, $id) {
228
  $entities = entity_load($entity_type, array($id));
229
  return reset($entities);
230
}
231

    
232
/**
233
 * A wrapper around entity_load() to return entities keyed by name key if existing.
234
 *
235
 * @param $entity_type
236
 *   The entity type to load, e.g. node or user.
237
 * @param $names
238
 *   An array of entity names or ids, or FALSE to load all entities.
239
 * @param $conditions
240
 *   (deprecated) An associative array of conditions on the base table, where
241
 *   the keys are the database fields and the values are the values those
242
 *   fields must have. Instead, it is preferable to use EntityFieldQuery to
243
 *   retrieve a list of entity IDs loadable by this function.
244
 *
245
 * @return
246
 *   An array of entity objects indexed by their names (or ids if the entity
247
 *   type has no name key).
248
 *
249
 * @see entity_load()
250
 */
251
function entity_load_multiple_by_name($entity_type, $names = FALSE, $conditions = array()) {
252
  $entities = entity_load($entity_type, $names, $conditions);
253
  $info = entity_get_info($entity_type);
254
  if (!isset($info['entity keys']['name'])) {
255
    return $entities;
256
  }
257
  return entity_key_array_by_property($entities, $info['entity keys']['name']);
258
}
259

    
260
/**
261
 * Permanently save an entity.
262
 *
263
 * In case of failures, an exception is thrown.
264
 *
265
 * @param $entity_type
266
 *   The type of the entity.
267
 * @param $entity
268
 *   The entity to save.
269
 *
270
 * @return
271
 *   For entity types provided by the CRUD API, SAVED_NEW or SAVED_UPDATED is
272
 *   returned depending on the operation performed. If there is no information
273
 *   how to save the entity, FALSE is returned.
274
 *
275
 * @see entity_type_supports()
276
 */
277
function entity_save($entity_type, $entity) {
278
  $info = entity_get_info($entity_type);
279
  if (method_exists($entity, 'save')) {
280
    return $entity->save();
281
  }
282
  elseif (isset($info['save callback'])) {
283
    $info['save callback']($entity);
284
  }
285
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
286
    return entity_get_controller($entity_type)->save($entity);
287
  }
288
  else {
289
    return FALSE;
290
  }
291
}
292

    
293
/**
294
 * Permanently delete the given entity.
295
 *
296
 * In case of failures, an exception is thrown.
297
 *
298
 * @param $entity_type
299
 *   The type of the entity.
300
 * @param $id
301
 *   The uniform identifier of the entity to delete.
302
 *
303
 * @return
304
 *   FALSE, if there were no information how to delete the entity.
305
 *
306
 * @see entity_type_supports()
307
 */
308
function entity_delete($entity_type, $id) {
309
  return entity_delete_multiple($entity_type, array($id));
310
}
311

    
312
/**
313
 * Permanently delete multiple entities.
314
 *
315
 * @param $entity_type
316
 *   The type of the entity.
317
 * @param $ids
318
 *   An array of entity ids of the entities to delete. In case the entity makes
319
 *   use of a name key, both the names or numeric ids may be passed.
320
 * @return
321
 *   FALSE if the given entity type isn't compatible to the CRUD API.
322
 */
323
function entity_delete_multiple($entity_type, $ids) {
324
  $info = entity_get_info($entity_type);
325
  if (isset($info['deletion callback'])) {
326
    foreach ($ids as $id) {
327
      $info['deletion callback']($id);
328
    }
329
  }
330
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
331
    entity_get_controller($entity_type)->delete($ids);
332
  }
333
  else {
334
    return FALSE;
335
  }
336
}
337

    
338
/**
339
 * Loads an entity revision.
340
 *
341
 * @param $entity_type
342
 *   The type of the entity.
343
 * @param $revision_id
344
 *   The id of the revision to load.
345
 *
346
 * @return
347
 *   The entity object, or FALSE if there is no entity with the given revision
348
 *   id.
349
 */
350
function entity_revision_load($entity_type, $revision_id) {
351
  $info = entity_get_info($entity_type);
352
  if (!empty($info['entity keys']['revision'])) {
353
    $entity_revisions = entity_load($entity_type, FALSE, array($info['entity keys']['revision'] => $revision_id));
354
    return reset($entity_revisions);
355
  }
356
  return FALSE;
357
}
358

    
359
/**
360
 * Deletes an entity revision.
361
 *
362
 * @param $entity_type
363
 *   The type of the entity.
364
 * @param $revision_id
365
 *   The revision ID to delete.
366
 *
367
 * @return
368
 *   TRUE if the entity revision could be deleted, FALSE otherwise.
369
 */
370
function entity_revision_delete($entity_type, $revision_id) {
371
  $info = entity_get_info($entity_type);
372
  if (isset($info['revision deletion callback'])) {
373
    return $info['revision deletion callback']($revision_id, $entity_type);
374
  }
375
  elseif (in_array('EntityAPIControllerRevisionableInterface', class_implements($info['controller class']))) {
376
    return entity_get_controller($entity_type)->deleteRevision($revision_id);
377
  }
378
  return FALSE;
379
}
380

    
381
/**
382
 * Checks whether the given entity is the default revision.
383
 *
384
 * Note that newly created entities will always be created in default revision,
385
 * thus TRUE is returned for not yet saved entities.
386
 *
387
 * @param $entity_type
388
 *   The type of the entity.
389
 * @param $entity
390
 *   The entity object to check.
391
 *
392
 * @return boolean
393
 *   A boolean indicating whether the entity is in default revision is returned.
394
 *   If the entity is not revisionable or is new, TRUE is returned.
395
 *
396
 * @see entity_revision_set_default()
397
 */
398
function entity_revision_is_default($entity_type, $entity) {
399
  $info = entity_get_info($entity_type);
400
  if (empty($info['entity keys']['revision'])) {
401
    return TRUE;
402
  }
403
  // Newly created entities will always be created in default revision.
404
  if (!empty($entity->is_new) || empty($entity->{$info['entity keys']['id']})) {
405
    return TRUE;
406
  }
407
  if (in_array('EntityAPIControllerRevisionableInterface', class_implements($info['controller class']))) {
408
    $key = !empty($info['entity keys']['default revision']) ? $info['entity keys']['default revision'] : 'default_revision';
409
    return !empty($entity->$key);
410
  }
411
  else {
412
    // Else, just load the default entity and compare the ID. Usually, the
413
    // entity should be already statically cached anyway.
414
    $default = entity_load_single($entity_type, $entity->{$info['entity keys']['id']});
415
    return $default->{$info['entity keys']['revision']} == $entity->{$info['entity keys']['revision']};
416
  }
417
}
418

    
419
/**
420
 * Sets a given entity revision as default revision.
421
 *
422
 * Note that the default revision flag will only be supported by entity types
423
 * based upon the EntityAPIController, i.e. implementing the
424
 * EntityAPIControllerRevisionableInterface.
425
 *
426
 * @param $entity_type
427
 *   The type of the entity.
428
 * @param $entity
429
 *   The entity revision to update.
430
 *
431
 * @see entity_revision_is_default()
432
 */
433
function entity_revision_set_default($entity_type, $entity) {
434
  $info = entity_get_info($entity_type);
435
  if (!empty($info['entity keys']['revision'])) {
436
    $key = !empty($info['entity keys']['default revision']) ? $info['entity keys']['default revision'] : 'default_revision';
437
    $entity->$key = TRUE;
438
  }
439
}
440

    
441
/**
442
 * Create a new entity object.
443
 *
444
 * @param $entity_type
445
 *   The type of the entity.
446
 * @param $values
447
 *   An array of values to set, keyed by property name. If the entity type has
448
 *   bundles the bundle key has to be specified.
449
 * @return
450
 *   A new instance of the entity type or FALSE if there is no information for
451
 *   the given entity type.
452
 *
453
 * @see entity_type_supports()
454
 */
455
function entity_create($entity_type, array $values) {
456
  $info = entity_get_info($entity_type);
457
  if (isset($info['creation callback'])) {
458
    return $info['creation callback']($values, $entity_type);
459
  }
460
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
461
    return entity_get_controller($entity_type)->create($values);
462
  }
463
  return FALSE;
464
}
465

    
466
/**
467
 * Exports an entity.
468
 *
469
 * Note: Currently, this only works for entity types provided with the entity
470
 * CRUD API.
471
 *
472
 * @param $entity_type
473
 *   The type of the entity.
474
 * @param $entity
475
 *   The entity to export.
476
 * @param $prefix
477
 *   An optional prefix for each line.
478
 * @return
479
 *   The exported entity as serialized string. The format is determined by the
480
 *   respective entity controller, e.g. it is JSON for the EntityAPIController.
481
 *   The output is suitable for entity_import().
482
 */
483
function entity_export($entity_type, $entity, $prefix = '') {
484
  if (method_exists($entity, 'export')) {
485
    return $entity->export($prefix);
486
  }
487
  $info = entity_get_info($entity_type);
488
  if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
489
    return entity_get_controller($entity_type)->export($entity, $prefix);
490
  }
491
}
492

    
493
/**
494
 * Imports an entity.
495
 *
496
 * Note: Currently, this only works for entity types provided with the entity
497
 * CRUD API.
498
 *
499
 * @param $entity_type
500
 *   The type of the entity.
501
 * @param string $export
502
 *   The string containing the serialized entity as produced by
503
 *   entity_export().
504
 * @return
505
 *   The imported entity object not yet saved.
506
 */
507
function entity_import($entity_type, $export) {
508
  $info = entity_get_info($entity_type);
509
  if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
510
    return entity_get_controller($entity_type)->import($export);
511
  }
512
}
513

    
514
/**
515
 * Checks whether an entity type is fieldable.
516
 *
517
 * @param $entity_type
518
 *   The type of the entity.
519
 *
520
 * @return
521
 *   TRUE if the entity type is fieldable, FALSE otherwise.
522
 */
523
function entity_type_is_fieldable($entity_type) {
524
  $info = entity_get_info($entity_type);
525
  return !empty($info['fieldable']);
526
}
527

    
528
/**
529
 * Builds a structured array representing the entity's content.
530
 *
531
 * The content built for the entity will vary depending on the $view_mode
532
 * parameter.
533
 *
534
 * Note: Currently, this only works for entity types provided with the entity
535
 * CRUD API.
536
 *
537
 * @param $entity_type
538
 *   The type of the entity.
539
 * @param $entity
540
 *   An entity object.
541
 * @param $view_mode
542
 *   A view mode as used by this entity type, e.g. 'full', 'teaser'...
543
 * @param $langcode
544
 *   (optional) A language code to use for rendering. Defaults to the global
545
 *   content language of the current request.
546
 * @return
547
 *   The renderable array.
548
 */
549
function entity_build_content($entity_type, $entity, $view_mode = 'full', $langcode = NULL) {
550
  $info = entity_get_info($entity_type);
551
  if (method_exists($entity, 'buildContent')) {
552
    return $entity->buildContent($view_mode, $langcode);
553
  }
554
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
555
    return entity_get_controller($entity_type)->buildContent($entity, $view_mode, $langcode);
556
  }
557
}
558

    
559
/**
560
 * Returns the entity identifier, i.e. the entities name or numeric id.
561
 *
562
 * Unlike entity_extract_ids() this function returns the name of the entity
563
 * instead of the numeric id, in case the entity type has specified a name key.
564
 *
565
 * @param $entity_type
566
 *   The type of the entity.
567
 * @param $entity
568
 *   An entity object.
569
 *
570
 * @see entity_extract_ids()
571
 */
572
function entity_id($entity_type, $entity) {
573
  if (method_exists($entity, 'identifier')) {
574
    return $entity->identifier();
575
  }
576
  $info = entity_get_info($entity_type);
577
  $key = isset($info['entity keys']['name']) ? $info['entity keys']['name'] : $info['entity keys']['id'];
578
  return isset($entity->$key) ? $entity->$key : NULL;
579
}
580

    
581
/**
582
 * Generate an array for rendering the given entities.
583
 *
584
 * Entities being viewed, are generally expected to be fully-loaded entity
585
 * objects, thus have their name or id key set. However, it is possible to
586
 * view a single entity without any id, e.g. for generating a preview during
587
 * creation.
588
 *
589
 * @param $entity_type
590
 *   The type of the entity.
591
 * @param $entities
592
 *   An array of entities to render.
593
 * @param $view_mode
594
 *   A view mode as used by this entity type, e.g. 'full', 'teaser'...
595
 * @param $langcode
596
 *   (optional) A language code to use for rendering. Defaults to the global
597
 *   content language of the current request.
598
 * @param $page
599
 *   (optional) If set will control if the entity is rendered: if TRUE
600
 *   the entity will be rendered without its title, so that it can be embeded
601
 *   in another context. If FALSE the entity will be displayed with its title
602
 *   in a mode suitable for lists.
603
 *   If unset, the page mode will be enabled if the current path is the URI
604
 *   of the entity, as returned by entity_uri().
605
 *   This parameter is only supported for entities which controller is a
606
 *   EntityAPIControllerInterface.
607
 * @return
608
 *   The renderable array, keyed by the entity type and by entity identifiers,
609
 *   for which the entity name is used if existing - see entity_id(). If there
610
 *   is no information on how to view an entity, FALSE is returned.
611
 */
612
function entity_view($entity_type, $entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
613
  $info = entity_get_info($entity_type);
614
  if (isset($info['view callback'])) {
615
    $entities = entity_key_array_by_property($entities, $info['entity keys']['id']);
616
    return $info['view callback']($entities, $view_mode, $langcode, $entity_type);
617
  }
618
  elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
619
    return entity_get_controller($entity_type)->view($entities, $view_mode, $langcode, $page);
620
  }
621
  return FALSE;
622
}
623

    
624
/**
625
 * Determines whether the given user can perform actions on an entity.
626
 *
627
 * For create operations, the pattern is to create an entity and then
628
 * check if the user has create access.
629
 *
630
 * @code
631
 * $node = entity_create('node', array('type' => 'page'));
632
 * $access = entity_access('create', 'node', $node, $account);
633
 * @endcode
634
 *
635
 * @param $op
636
 *   The operation being performed. One of 'view', 'update', 'create' or
637
 *   'delete'.
638
 * @param $entity_type
639
 *   The entity type of the entity to check for.
640
 * @param $entity
641
 *   Optionally an entity to check access for. If no entity is given, it will be
642
 *   determined whether access is allowed for all entities of the given type.
643
 * @param $account
644
 *   The user to check for. Leave it to NULL to check for the global user.
645
 *
646
 * @return boolean
647
 *   Whether access is allowed or not. If the entity type does not specify any
648
 *   access information, NULL is returned.
649
 *
650
 * @see entity_type_supports()
651
 */
652
function entity_access($op, $entity_type, $entity = NULL, $account = NULL) {
653
  if (($info = entity_get_info()) && isset($info[$entity_type]['access callback'])) {
654
    return $info[$entity_type]['access callback']($op, $entity, $account, $entity_type);
655
  }
656
}
657

    
658
/**
659
 * Gets the edit form for any entity.
660
 *
661
 * This helper makes use of drupal_get_form() and the regular form builder
662
 * function of the entity type to retrieve and process the form as usual.
663
 *
664
 * In order to use this helper to show an entity add form, the new entity object
665
 * can be created via entity_create() or entity_property_values_create_entity().
666
 *
667
 * @param $entity_type
668
 *   The type of the entity.
669
 * @param $entity
670
 *   The entity to show the edit form for.
671
 * @return
672
 *   The renderable array of the form. If there is no entity form or missing
673
 *   metadata, FALSE is returned.
674
 *
675
 * @see entity_type_supports()
676
 */
677
function entity_form($entity_type, $entity) {
678
  $info = entity_get_info($entity_type);
679
  if (isset($info['form callback'])) {
680
    return $info['form callback']($entity, $entity_type);
681
  }
682
  // If there is an UI controller, the providing module has to implement the
683
  // entity form using entity_ui_get_form().
684
  elseif (entity_ui_controller($entity_type)) {
685
    return entity_metadata_form_entity_ui($entity, $entity_type);
686
  }
687
  return FALSE;
688
}
689

    
690
/**
691
 * Converts an array of entities to be keyed by the values of a given property.
692
 *
693
 * @param array $entities
694
 *   The array of entities to convert.
695
 * @param $property
696
 *   The name of entity property, by which the array should be keyed. To get
697
 *   reasonable results, the property has to have unique values.
698
 *
699
 * @return array
700
 *   The same entities in the same order, but keyed by their $property values.
701
 */
702
function entity_key_array_by_property(array $entities, $property) {
703
  $ret = array();
704
  foreach ($entities as $entity) {
705
    $key = isset($entity->$property) ? $entity->$property : NULL;
706
    $ret[$key] = $entity;
707
  }
708
  return $ret;
709
}
710

    
711
/**
712
 * Get the entity info for the entity types provided via the entity CRUD API.
713
 *
714
 * @return
715
 *  An array in the same format as entity_get_info(), containing the entities
716
 *  whose controller class implements the EntityAPIControllerInterface.
717
 */
718
function entity_crud_get_info() {
719
  $types = array();
720
  foreach (entity_get_info() as $type => $info) {
721
    if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
722
      $types[$type] = $info;
723
    }
724
  }
725
  return $types;
726
}
727

    
728
/**
729
 * Checks if a given entity has a certain exportable status.
730
 *
731
 * @param $entity_type
732
 *   The type of the entity.
733
 * @param $entity
734
 *   The entity to check the status on.
735
 * @param $status
736
 *   The constant status like ENTITY_CUSTOM, ENTITY_IN_CODE, ENTITY_OVERRIDDEN
737
 *   or ENTITY_FIXED.
738
 *
739
 * @return
740
 *   TRUE if the entity has the status, FALSE otherwise.
741
 */
742
function entity_has_status($entity_type, $entity, $status) {
743
  $info = entity_get_info($entity_type);
744
  $status_key = empty($info['entity keys']['status']) ? 'status' : $info['entity keys']['status'];
745
  return isset($entity->{$status_key}) && ($entity->{$status_key} & $status) == $status;
746
}
747

    
748
/**
749
 * Export a variable. Copied from ctools.
750
 *
751
 * This is a replacement for var_export(), allowing us to more nicely
752
 * format exports. It will recurse down into arrays and will try to
753
 * properly export bools when it can.
754
 */
755
function entity_var_export($var, $prefix = '') {
756
  if (is_array($var)) {
757
    if (empty($var)) {
758
      $output = 'array()';
759
    }
760
    else {
761
      $output = "array(\n";
762
      foreach ($var as $key => $value) {
763
        $output .= "  '$key' => " . entity_var_export($value, '  ') . ",\n";
764
      }
765
      $output .= ')';
766
    }
767
  }
768
  elseif (is_bool($var)) {
769
    $output = $var ? 'TRUE' : 'FALSE';
770
  }
771
  else {
772
    $output = var_export($var, TRUE);
773
  }
774

    
775
  if ($prefix) {
776
    $output = str_replace("\n", "\n$prefix", $output);
777
  }
778
  return $output;
779
}
780

    
781
/**
782
 * Export a variable in pretty formatted JSON.
783
 */
784
function entity_var_json_export($var, $prefix = '') {
785
  if (is_array($var) && $var) {
786
    // Defines whether we use a JSON array or object.
787
    $use_array = ($var == array_values($var));
788
    $output = $use_array ? "[" : "{";
789

    
790
    foreach ($var as $key => $value) {
791
      if ($use_array) {
792
        $values[] = entity_var_json_export($value, '  ');
793
      }
794
      else {
795
        $values[] = entity_var_json_export((string) $key, '  ') . ' : ' . entity_var_json_export($value, '  ');
796
      }
797
    }
798
    // Use several lines for long content. However for objects with a single
799
    // entry keep the key in the first line.
800
    if (strlen($content = implode(', ', $values)) > 70 && ($use_array || count($values) > 1)) {
801
      $output .= "\n  " . implode(",\n  ", $values) . "\n";
802
    }
803
    elseif (strpos($content, "\n") !== FALSE) {
804
      $output .= " " . $content . "\n";
805
    }
806
    else {
807
      $output .= " " . $content . ' ';
808
    }
809
    $output .= $use_array ? ']' : '}';
810
  }
811
  else {
812
    $output = drupal_json_encode($var);
813
  }
814

    
815
  if ($prefix) {
816
    $output = str_replace("\n", "\n$prefix", $output);
817
  }
818
  return $output;
819
}
820

    
821
/**
822
 * Rebuild the default entities provided in code.
823
 *
824
 * Exportable entities provided in code get saved to the database once a module
825
 * providing defaults in code is activated. This allows module and entity_load()
826
 * to easily deal with exportable entities just by relying on the database.
827
 *
828
 * The defaults get rebuilt if the cache is cleared or new modules providing
829
 * defaults are enabled, such that the defaults in the database are up to date.
830
 * A default entity gets updated with the latest defaults in code during rebuild
831
 * as long as the default has not been overridden. Once a module providing
832
 * defaults is disabled, its default entities get removed from the database
833
 * unless they have been overridden. In that case the overridden entity is left
834
 * in the database, but its status gets updated to 'custom'.
835
 *
836
 * @param $entity_types
837
 *   (optional) If specified, only the defaults of the given entity types are
838
 *   rebuilt.
839
 */
840
function entity_defaults_rebuild($entity_types = NULL) {
841
  if (!isset($entity_types)) {
842
    $entity_types = array();
843
    foreach (entity_crud_get_info() as $type => $info) {
844
      if (!empty($info['exportable'])) {
845
        $entity_types[] = $type;
846
      }
847
    };
848
  }
849
  foreach ($entity_types as $type) {
850
    _entity_defaults_rebuild($type);
851
  }
852
}
853

    
854
/**
855
 * Actually rebuild the defaults of a given entity type.
856
 */
857
function _entity_defaults_rebuild($entity_type) {
858
  if (lock_acquire('entity_rebuild_' . $entity_type)) {
859
    $info = entity_get_info($entity_type);
860
    $hook = isset($info['export']['default hook']) ? $info['export']['default hook'] : 'default_' . $entity_type;
861
    $keys = $info['entity keys'] + array('module' => 'module', 'status' => 'status', 'name' => $info['entity keys']['id']);
862

    
863
    // Check for the existence of the module and status columns.
864
    if (!in_array($keys['status'], $info['schema_fields_sql']['base table']) || !in_array($keys['module'], $info['schema_fields_sql']['base table'])) {
865
      trigger_error("Missing database columns for the exportable entity $entity_type as defined by entity_exportable_schema_fields(). Update the according module and run update.php!", E_USER_WARNING);
866
      return;
867
    }
868

    
869
    // Invoke the hook and collect default entities.
870
    $entities = array();
871
    foreach (module_implements($hook) as $module) {
872
      foreach ((array) module_invoke($module, $hook) as $name => $entity) {
873
        $entity->{$keys['name']} = $name;
874
        $entity->{$keys['module']} = $module;
875
        $entities[$name] = $entity;
876
      }
877
    }
878
    drupal_alter($hook, $entities);
879

    
880
    // Check for defaults that disappeared.
881
    $existing_defaults = entity_load_multiple_by_name($entity_type, FALSE, array($keys['status'] => array(ENTITY_OVERRIDDEN, ENTITY_IN_CODE, ENTITY_FIXED)));
882

    
883
    foreach ($existing_defaults as $name => $entity) {
884
      if (empty($entities[$name])) {
885
        $entity->is_rebuild = TRUE;
886
        if (entity_has_status($entity_type, $entity, ENTITY_OVERRIDDEN)) {
887
          $entity->{$keys['status']} = ENTITY_CUSTOM;
888
          entity_save($entity_type, $entity);
889
        }
890
        else {
891
          entity_delete($entity_type, $name);
892
        }
893
        unset($entity->is_rebuild);
894
      }
895
    }
896

    
897
    // Load all existing entities.
898
    $existing_entities = entity_load_multiple_by_name($entity_type, array_keys($entities));
899

    
900
    foreach ($existing_entities as $name => $entity) {
901
      if (entity_has_status($entity_type, $entity, ENTITY_CUSTOM)) {
902
        // If the entity already exists but is not yet marked as overridden, we
903
        // have to update the status.
904
        if (!entity_has_status($entity_type, $entity, ENTITY_OVERRIDDEN)) {
905
          $entity->{$keys['status']} |= ENTITY_OVERRIDDEN;
906
          $entity->{$keys['module']} = $entities[$name]->{$keys['module']};
907
          $entity->is_rebuild = TRUE;
908
          entity_save($entity_type, $entity);
909
          unset($entity->is_rebuild);
910
        }
911

    
912
        // The entity is overridden, so we do not need to save the default.
913
        unset($entities[$name]);
914
      }
915
    }
916

    
917
    // Save defaults.
918
    $originals = array();
919
    foreach ($entities as $name => $entity) {
920
      if (!empty($existing_entities[$name])) {
921
        // Make sure we are updating the existing default.
922
        $entity->{$keys['id']} = $existing_entities[$name]->{$keys['id']};
923
        unset($entity->is_new);
924
      }
925
      // Pre-populate $entity->original as we already have it. So we avoid
926
      // loading it again.
927
      $entity->original = !empty($existing_entities[$name]) ? $existing_entities[$name] : FALSE;
928
      // Keep original entities for hook_{entity_type}_defaults_rebuild()
929
      // implementations.
930
      $originals[$name] = $entity->original;
931

    
932
      if (!isset($entity->{$keys['status']})) {
933
        $entity->{$keys['status']} = ENTITY_IN_CODE;
934
      }
935
      else {
936
        $entity->{$keys['status']} |= ENTITY_IN_CODE;
937
      }
938
      $entity->is_rebuild = TRUE;
939
      entity_save($entity_type, $entity);
940
      unset($entity->is_rebuild);
941
    }
942

    
943
    // Invoke an entity type-specific hook so modules may apply changes, e.g.
944
    // efficiently rebuild caches.
945
    module_invoke_all($entity_type . '_defaults_rebuild', $entities, $originals);
946

    
947
    lock_release('entity_rebuild_' . $entity_type);
948
  }
949
}
950

    
951
/**
952
 * Implements hook_modules_enabled().
953
 */
954
function entity_modules_enabled($modules) {
955
  foreach (_entity_modules_get_default_types($modules) as $type) {
956
    _entity_defaults_rebuild($type);
957
  }
958
}
959

    
960
/**
961
 * Implements hook_modules_disabled().
962
 */
963
function entity_modules_disabled($modules) {
964
  foreach (_entity_modules_get_default_types($modules) as $entity_type) {
965
    $info = entity_get_info($entity_type);
966

    
967
    // Do nothing if the module providing the entity type has been disabled too.
968
    if (isset($info['module']) && in_array($info['module'], $modules)) {
969
      return;
970
    }
971

    
972
    $keys = $info['entity keys'] + array('module' => 'module', 'status' => 'status', 'name' => $info['entity keys']['id']);
973
    // Remove entities provided in code by one of the disabled modules.
974
    $query = new EntityFieldQuery();
975
    $query->entityCondition('entity_type', $entity_type, '=')
976
          ->propertyCondition($keys['module'], $modules, 'IN')
977
          ->propertyCondition($keys['status'], array(ENTITY_IN_CODE, ENTITY_FIXED), 'IN');
978
    $result = $query->execute();
979
    if (isset($result[$entity_type])) {
980
      $entities = entity_load($entity_type, array_keys($result[$entity_type]));
981
      entity_delete_multiple($entity_type, array_keys($entities));
982
    }
983

    
984
    // Update overridden entities to be now custom.
985
    $query = new EntityFieldQuery();
986
    $query->entityCondition('entity_type', $entity_type, '=')
987
          ->propertyCondition($keys['module'], $modules, 'IN')
988
          ->propertyCondition($keys['status'], ENTITY_OVERRIDDEN, '=');
989
    $result = $query->execute();
990
    if (isset($result[$entity_type])) {
991
      foreach (entity_load($entity_type, array_keys($result[$entity_type])) as $name => $entity) {
992
        $entity->{$keys['status']} = ENTITY_CUSTOM;
993
        $entity->{$keys['module']} = NULL;
994
        entity_save($entity_type, $entity);
995
      }
996
    }
997

    
998
    // Rebuild the remaining defaults so any alterations of the disabled modules
999
    // are gone.
1000
    _entity_defaults_rebuild($entity_type);
1001
  }
1002
}
1003

    
1004
/**
1005
 * Gets all entity types for which defaults are provided by the $modules.
1006
 */
1007
function _entity_modules_get_default_types($modules) {
1008
  $types = array();
1009
  foreach (entity_crud_get_info() as $entity_type => $info) {
1010
    if (!empty($info['exportable'])) {
1011
      $hook = isset($info['export']['default hook']) ? $info['export']['default hook'] : 'default_' . $entity_type;
1012
      foreach ($modules as $module) {
1013
        if (module_hook($module, $hook) || module_hook($module, $hook . '_alter')) {
1014
          $types[] = $entity_type;
1015
        }
1016
      }
1017
    }
1018
  }
1019
  return $types;
1020
}
1021

    
1022
/**
1023
 * Defines schema fields required for exportable entities.
1024
 *
1025
 * Warning: Do not call this function in your module's hook_schema()
1026
 * implementation or update functions. It is not safe to call functions of
1027
 * dependencies at this point. Instead of calling the function, just copy over
1028
 * the content.
1029
 * For more details see the issue http://drupal.org/node/1122812.
1030
 */
1031
function entity_exportable_schema_fields($module_col = 'module', $status_col = 'status') {
1032
  return array(
1033
    $status_col => array(
1034
      'type' => 'int',
1035
      'not null' => TRUE,
1036
      // Set the default to ENTITY_CUSTOM without using the constant as it is
1037
      // not safe to use it at this point.
1038
      'default' => 0x01,
1039
      'size' => 'tiny',
1040
      'description' => 'The exportable status of the entity.',
1041
    ),
1042
    $module_col => array(
1043
      'description' => 'The name of the providing module if the entity has been defined in code.',
1044
      'type' => 'varchar',
1045
      'length' => 255,
1046
      'not null' => FALSE,
1047
    ),
1048
  );
1049
}
1050

    
1051
/**
1052
 * Implements hook_flush_caches().
1053
 */
1054
function entity_flush_caches() {
1055
  entity_property_info_cache_clear();
1056
  // Re-build defaults in code, however skip it on the admin modules page. In
1057
  // case of enabling or disabling modules we already rebuild defaults in
1058
  // entity_modules_enabled() and entity_modules_disabled(), so we do not need
1059
  // to do it again.
1060
  if (current_path() != 'admin/modules/list/confirm') {
1061
    entity_defaults_rebuild();
1062
  }
1063
}
1064

    
1065
/**
1066
 * Implements hook_theme().
1067
 */
1068
function entity_theme() {
1069
  // Build a pattern in the form of "(type1|type2|...)(\.|__)" such that all
1070
  // templates starting with an entity type or named like the entity type
1071
  // are found.
1072
  // This has to match the template suggestions provided in
1073
  // template_preprocess_entity().
1074
  $types = array_keys(entity_crud_get_info());
1075
  $pattern = '(' . implode('|', $types) . ')(\.|__)';
1076

    
1077
  return array(
1078
    'entity_status' => array(
1079
      'variables' => array('status' => NULL, 'html' => TRUE),
1080
      'file' => 'theme/entity.theme.inc',
1081
    ),
1082
    'entity' => array(
1083
      'render element' => 'elements',
1084
      'template' => 'entity',
1085
      'pattern' => $pattern,
1086
      'path' => drupal_get_path('module', 'entity') . '/theme',
1087
      'file' => 'entity.theme.inc',
1088
    ),
1089
    'entity_property' => array(
1090
      'render element' => 'elements',
1091
      'file' => 'theme/entity.theme.inc',
1092
    ),
1093
    'entity_ui_overview_item' => array(
1094
      'variables' => array('label' => NULL, 'entity_type' => NULL, 'url' => FALSE, 'name' => FALSE),
1095
      'file' => 'includes/entity.ui.inc'
1096
    ),
1097
  );
1098
}
1099

    
1100
/**
1101
 * Label callback that refers to the entity classes label method.
1102
 */
1103
function entity_class_label($entity) {
1104
  return $entity->label();
1105
}
1106

    
1107
/**
1108
 * URI callback that refers to the entity classes uri method.
1109
 */
1110
function entity_class_uri($entity) {
1111
  return $entity->uri();
1112
}
1113

    
1114
/**
1115
 * Implements hook_file_download_access() for entity types provided by the CRUD API.
1116
 */
1117
function entity_file_download_access($field, $entity_type, $entity) {
1118
  $info = entity_get_info($entity_type);
1119
  if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
1120
    return entity_access('view', $entity_type, $entity);
1121
  }
1122
}
1123

    
1124
/**
1125
 * Determines the UI controller class for a given entity type.
1126
 *
1127
 * @return EntityDefaultUIController
1128
 *   If a type is given, the controller for the given entity type. Else an array
1129
 *   of all enabled UI controllers keyed by entity type is returned.
1130
 */
1131
function entity_ui_controller($type = NULL) {
1132
  $static = &drupal_static(__FUNCTION__);
1133

    
1134
  if (!isset($type)) {
1135
    // Invoke the function for each type to ensure we have fully populated the
1136
    // static variable.
1137
    foreach (entity_get_info() as $entity_type => $info) {
1138
      entity_ui_controller($entity_type);
1139
    }
1140
    return array_filter($static);
1141
  }
1142

    
1143
  if (!isset($static[$type])) {
1144
    $info = entity_get_info($type);
1145
    $class = isset($info['admin ui']['controller class']) ? $info['admin ui']['controller class'] : 'EntityDefaultUIController';
1146
    $static[$type] = (isset($info['admin ui']['path']) && $class) ? new $class($type, $info) : FALSE;
1147
  }
1148

    
1149
  return $static[$type];
1150
}
1151

    
1152
/**
1153
 * Implements hook_menu().
1154
 *
1155
 * @see EntityDefaultUIController::hook_menu()
1156
 */
1157
function entity_menu() {
1158
  $items = array();
1159
  foreach (entity_ui_controller() as $controller) {
1160
    $items += $controller->hook_menu();
1161
  }
1162
  return $items;
1163
}
1164

    
1165
/**
1166
 * Implements hook_forms().
1167
 *
1168
 * @see EntityDefaultUIController::hook_forms()
1169
 * @see entity_ui_get_form()
1170
 */
1171
function entity_forms($form_id, $args) {
1172
  // For efficiency only invoke an entity types controller, if a form of it is
1173
  // requested. Thus if the first (overview and operation form) or the third
1174
  // argument (edit form) is an entity type name, add in the types forms.
1175
  if (isset($args[0]) && is_string($args[0]) && entity_get_info($args[0])) {
1176
    $type = $args[0];
1177
  }
1178
  elseif (isset($args[2]) && is_string($args[2]) && entity_get_info($args[2])) {
1179
    $type = $args[2];
1180
  }
1181
  if (isset($type) && $controller = entity_ui_controller($type)) {
1182
    return $controller->hook_forms();
1183
  }
1184
}
1185

    
1186
/**
1187
 * A wrapper around drupal_get_form() that helps building entity forms.
1188
 *
1189
 * This function may be used by entities to build their entity form. It has to
1190
 * be used instead of calling drupal_get_form().
1191
 * Entity forms built with this helper receive useful defaults suiting for
1192
 * editing a single entity, whereas the special cases of adding and cloning
1193
 * of entities are supported too.
1194
 *
1195
 * While this function is intended to be used to get entity forms for entities
1196
 * using the entity ui controller, it may be used for entity types not using
1197
 * the ui controller too.
1198
 *
1199
 * @param $entity_type
1200
 *   The entity type for which to get the form.
1201
 * @param $entity
1202
 *   The entity for which to return the form.
1203
 *   If $op is 'add' the entity has to be either initialized before calling this
1204
 *   function, or NULL may be passed. If NULL is passed, an entity will be
1205
 *   initialized with empty values using entity_create(). Thus entities, for
1206
 *   which this is problematic have to care to pass in an initialized entity.
1207
 * @param $op
1208
 *   (optional) One of 'edit', 'add' or 'clone'. Defaults to edit.
1209
 * @param $form_state
1210
 *   (optional) A pre-populated form state, e.g. to add in form include files.
1211
 *   See entity_metadata_form_entity_ui().
1212
 *
1213
 * @return
1214
 *   The fully built and processed form, ready to be rendered.
1215
 *
1216
 * @see EntityDefaultUIController::hook_forms()
1217
 * @see entity_ui_form_submit_build_entity()
1218
 */
1219
function entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state = array()) {
1220
  if (isset($entity)) {
1221
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
1222
  }
1223
  $form_id = (!isset($bundle) || $bundle == $entity_type) ? $entity_type . '_form' : $entity_type . '_edit_' . $bundle . '_form';
1224

    
1225
  if (!isset($entity) && $op == 'add') {
1226
    $entity = entity_create($entity_type, array());
1227
  }
1228

    
1229
  // Do not use drupal_get_form(), but invoke drupal_build_form() ourself so
1230
  // we can prepulate the form state.
1231
  $form_state['wrapper_callback'] = 'entity_ui_main_form_defaults';
1232
  $form_state['entity_type'] = $entity_type;
1233
  form_load_include($form_state, 'inc', 'entity', 'includes/entity.ui');
1234

    
1235
  // Handle cloning. We cannot do that in the wrapper callback as it is too late
1236
  // for changing arguments.
1237
  if ($op == 'clone') {
1238
    $entity = entity_ui_clone_entity($entity_type, $entity);
1239
  }
1240

    
1241
  // We don't pass the entity type as first parameter, as the implementing
1242
  // module knows the type anyway. However, in order to allow for efficient
1243
  // hook_forms() implementiations we append the entity type as last argument,
1244
  // which the module implementing the form constructor may safely ignore.
1245
  // @see entity_forms()
1246
  $form_state['build_info']['args'] = array($entity, $op, $entity_type);
1247
  return drupal_build_form($form_id, $form_state);
1248
}
1249

    
1250
/**
1251
 * Helper for using i18n_string().
1252
 *
1253
 * @param $name
1254
 *   Textgroup and context glued with ':'.
1255
 * @param $default
1256
 *   String in default language. Default language may or may not be English.
1257
 * @param $langcode
1258
 *   (optional) The code of a certain language to translate the string into.
1259
 *   Defaults to the i18n_string() default, i.e. the current language.
1260
 *
1261
 * @see i18n_string()
1262
 */
1263
function entity_i18n_string($name, $default, $langcode = NULL) {
1264
  return function_exists('i18n_string') ? i18n_string($name, $default, array('langcode' => $langcode)) : $default;
1265
}
1266

    
1267
/**
1268
 * Implements hook_views_api().
1269
 */
1270
function entity_views_api() {
1271
  return array(
1272
    'api' => '3.0-alpha1',
1273
    'path' => drupal_get_path('module', 'entity') . '/views',
1274
  );
1275
}
1276

    
1277
/**
1278
 * Implements hook_field_extra_fields().
1279
 */
1280
function entity_field_extra_fields() {
1281
  // Invoke specified controllers for entity types provided by the CRUD API.
1282
  $items = array();
1283
  foreach (entity_crud_get_info() as $type => $info) {
1284
    if (!empty($info['extra fields controller class'])) {
1285
      $items = array_merge_recursive($items, entity_get_extra_fields_controller($type)->fieldExtraFields());
1286
    }
1287
  }
1288
  return $items;
1289
}
1290

    
1291
/**
1292
 * Gets the extra field controller class for a given entity type.
1293
 *
1294
 * @return EntityExtraFieldsControllerInterface|false
1295
 *   The controller for the given entity type or FALSE if none is specified.
1296
 */
1297
function entity_get_extra_fields_controller($type = NULL) {
1298
  $static = &drupal_static(__FUNCTION__);
1299

    
1300
  if (!isset($static[$type])) {
1301
    $static[$type] = FALSE;
1302
    $info = entity_get_info($type);
1303
    if (!empty($info['extra fields controller class'])) {
1304
      $static[$type] = new $info['extra fields controller class']($type);
1305
    }
1306
  }
1307
  return $static[$type];
1308
}
1309

    
1310
/**
1311
 * Returns a property wrapper for the given data.
1312
 *
1313
 * If an entity is wrapped, the wrapper can be used to retrieve further wrappers
1314
 * for the entitity properties. For that the wrapper support chaining, e.g. you
1315
 * can use a node wrapper to get the node authors mail address:
1316
 *
1317
 * @code
1318
 *   echo $wrappedNode->author->mail->value();
1319
 * @endcode
1320
 *
1321
 * @param $type
1322
 *   The type of the passed data.
1323
 * @param $data
1324
 *   The data to wrap. It may be set to NULL, so the wrapper can be used
1325
 *   without any data for getting information about properties.
1326
 * @param $info
1327
 *   (optional) Specify additional information for the passed data:
1328
 *    - langcode: (optional) If the data is language specific, its langauge
1329
 *      code. Defaults to NULL, what means language neutral.
1330
 *    - bundle: (optional) If an entity is wrapped but not passed, use this key
1331
 *      to specify the bundle to return a wrapper for.
1332
 *    - property info: (optional) May be used to use a wrapper with an arbitrary
1333
 *      data structure (type 'struct'). Use this key for specifying info about
1334
 *      properties in the same structure as used by hook_entity_property_info().
1335
 *    - property info alter: (optional) A callback for altering the property
1336
 *      info before it is utilized by the wrapper.
1337
 *    - property defaults: (optional) An array of defaults for the info of
1338
 *      each property of the wrapped data item.
1339
 * @return EntityMetadataWrapper
1340
 *   Dependend on the passed data the right wrapper is returned.
1341
 */
1342
function entity_metadata_wrapper($type, $data = NULL, array $info = array()) {
1343
  if ($type == 'entity' || (($entity_info = entity_get_info()) && isset($entity_info[$type]))) {
1344
    // If the passed entity is the global $user, we load the user object by only
1345
    // passing on the user id. The global user is not a fully loaded entity.
1346
    if ($type == 'user' && is_object($data) && $data == $GLOBALS['user']) {
1347
      $data = $data->uid;
1348
    }
1349
    return new EntityDrupalWrapper($type, $data, $info);
1350
  }
1351
  elseif ($type == 'list' || entity_property_list_extract_type($type)) {
1352
    return new EntityListWrapper($type, $data, $info);
1353
  }
1354
  elseif (isset($info['property info'])) {
1355
    return new EntityStructureWrapper($type, $data, $info);
1356
  }
1357
  else {
1358
    return new EntityValueWrapper($type, $data, $info);
1359
  }
1360
}
1361

    
1362
/**
1363
 * Returns a metadata wrapper for accessing site-wide properties.
1364
 *
1365
 * Although there is no 'site' entity or such, modules may provide info about
1366
 * site-wide properties using hook_entity_property_info(). This function returns
1367
 * a wrapper for making use of this properties.
1368
 *
1369
 * @return EntityMetadataWrapper
1370
 *   A wrapper for accessing site-wide properties.
1371
 *
1372
 * @see entity_metadata_system_entity_property_info()
1373
 */
1374
function entity_metadata_site_wrapper() {
1375
  $site_info = entity_get_property_info('site');
1376
  $info['property info'] = $site_info['properties'];
1377
  return entity_metadata_wrapper('site', FALSE, $info);
1378
}
1379

    
1380
/**
1381
 * Implements hook_module_implements_alter().
1382
 *
1383
 * Moves the hook_entity_info_alter() implementation to the bottom so it is
1384
 * invoked after all modules relying on the entity API.
1385
 * That way we ensure to run last and clear the field-info cache after the
1386
 * others added in their bundle information.
1387
 *
1388
 * @see entity_entity_info_alter()
1389
 */
1390
function entity_module_implements_alter(&$implementations, $hook) {
1391
  if ($hook == 'entity_info_alter') {
1392
    // Move our hook implementation to the bottom.
1393
    $group = $implementations['entity'];
1394
    unset($implementations['entity']);
1395
    $implementations['entity'] = $group;
1396
  }
1397
}
1398

    
1399
/**
1400
 * Implements hook_entity_info_alter().
1401
 *
1402
 * @see entity_module_implements_alter()
1403
 */
1404
function entity_entity_info_alter(&$entity_info) {
1405
  _entity_info_add_metadata($entity_info);
1406

    
1407
  // Populate a default value for the 'configuration' key of all entity types.
1408
  foreach ($entity_info as $type => $info) {
1409
    if (!isset($info['configuration'])) {
1410
      $entity_info[$type]['configuration'] = !empty($info['exportable']);
1411
    }
1412
  }
1413
}
1414

    
1415
/**
1416
 * Adds metadata and callbacks for core entities to the entity info.
1417
 */
1418
function _entity_info_add_metadata(&$entity_info) {
1419
  // Set plural labels.
1420
  $entity_info['node']['plural label'] = t('Nodes');
1421
  $entity_info['user']['plural label'] = t('Users');
1422
  $entity_info['file']['plural label'] = t('Files');
1423

    
1424
  // Set descriptions.
1425
  $entity_info['node']['description'] = t('Nodes represent the main site content items.');
1426
  $entity_info['user']['description'] = t('Users who have created accounts on your site.');
1427
  $entity_info['file']['description'] = t('Uploaded file.');
1428

    
1429
  // Set access callbacks.
1430
  $entity_info['node']['access callback'] = 'entity_metadata_no_hook_node_access';
1431
  $entity_info['user']['access callback'] = 'entity_metadata_user_access';
1432
  // File entity has it's own entity_access function.
1433
  if (!module_exists('file_entity')) {
1434
    $entity_info['file']['access callback'] = 'entity_metadata_file_access';
1435
  }
1436

    
1437
  // CRUD function callbacks.
1438
  $entity_info['node']['creation callback'] = 'entity_metadata_create_node';
1439
  $entity_info['node']['save callback'] = 'node_save';
1440
  $entity_info['node']['deletion callback'] = 'node_delete';
1441
  $entity_info['node']['revision deletion callback'] = 'node_revision_delete';
1442
  $entity_info['user']['creation callback'] = 'entity_metadata_create_object';
1443
  $entity_info['user']['save callback'] = 'entity_metadata_user_save';
1444
  $entity_info['user']['deletion callback'] = 'user_delete';
1445
  $entity_info['file']['save callback'] = 'file_save';
1446
  $entity_info['file']['deletion callback'] = 'entity_metadata_delete_file';
1447

    
1448
  // Form callbacks.
1449
  $entity_info['node']['form callback'] = 'entity_metadata_form_node';
1450
  $entity_info['user']['form callback'] = 'entity_metadata_form_user';
1451

    
1452
  // URI callbacks.
1453
  if (!isset($entity_info['file']['uri callback'])) {
1454
    $entity_info['file']['uri callback'] = 'entity_metadata_uri_file';
1455
  }
1456

    
1457
  // View callbacks.
1458
  $entity_info['node']['view callback'] = 'entity_metadata_view_node';
1459
  $entity_info['user']['view callback'] = 'entity_metadata_view_single';
1460

    
1461
  if (module_exists('comment')) {
1462
    $entity_info['comment']['plural label'] = t('Comments');
1463
    $entity_info['comment']['description'] = t('Remark or note that refers to a node.');
1464
    $entity_info['comment']['access callback'] = 'entity_metadata_comment_access';
1465
    $entity_info['comment']['creation callback'] = 'entity_metadata_create_comment';
1466
    $entity_info['comment']['save callback'] = 'comment_save';
1467
    $entity_info['comment']['deletion callback'] = 'comment_delete';
1468
    $entity_info['comment']['view callback'] = 'entity_metadata_view_comment';
1469
    $entity_info['comment']['form callback'] = 'entity_metadata_form_comment';
1470
  }
1471
  if (module_exists('taxonomy')) {
1472
    $entity_info['taxonomy_term']['plural label'] = t('Taxonomy terms');
1473
    $entity_info['taxonomy_term']['description'] = t('Taxonomy terms are used for classifying content.');
1474
    $entity_info['taxonomy_term']['access callback'] = 'entity_metadata_taxonomy_access';
1475
    $entity_info['taxonomy_term']['creation callback'] = 'entity_metadata_create_object';
1476
    $entity_info['taxonomy_term']['save callback'] = 'taxonomy_term_save';
1477
    $entity_info['taxonomy_term']['deletion callback'] = 'taxonomy_term_delete';
1478
    $entity_info['taxonomy_term']['view callback'] = 'entity_metadata_view_single';
1479
    $entity_info['taxonomy_term']['form callback'] = 'entity_metadata_form_taxonomy_term';
1480

    
1481
    $entity_info['taxonomy_vocabulary']['plural label'] = t('Taxonomy vocabularies');
1482
    $entity_info['taxonomy_vocabulary']['description'] = t('Vocabularies contain related taxonomy terms, which are used for classifying content.');
1483
    $entity_info['taxonomy_vocabulary']['access callback'] = 'entity_metadata_taxonomy_access';
1484
    $entity_info['taxonomy_vocabulary']['creation callback'] = 'entity_metadata_create_object';
1485
    $entity_info['taxonomy_vocabulary']['save callback'] = 'taxonomy_vocabulary_save';
1486
    $entity_info['taxonomy_vocabulary']['deletion callback'] = 'taxonomy_vocabulary_delete';
1487
    $entity_info['taxonomy_vocabulary']['form callback'] = 'entity_metadata_form_taxonomy_vocabulary';
1488
    // Token type mapping.
1489
    $entity_info['taxonomy_term']['token type'] = 'term';
1490
    $entity_info['taxonomy_vocabulary']['token type'] = 'vocabulary';
1491
  }
1492
}
1493

    
1494
/**
1495
 * Implements hook_ctools_plugin_directory().
1496
 */
1497
function entity_ctools_plugin_directory($module, $plugin) {
1498
  if ($module == 'ctools' && $plugin == 'content_types') {
1499
    return 'ctools/content_types';
1500
  }
1501
}