Projet

Général

Profil

Paste
Télécharger (51,6 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / entity / entity.module @ 74f6bef0

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_installed().
953
 */
954
function entity_modules_installed($modules) {
955
  module_load_install('entity');
956
  entity_entitycache_installed_modules($modules);
957
}
958

    
959
/**
960
 * Implements hook_modules_uninstalled().
961
 */
962
function entity_modules_uninstalled($modules) {
963
  module_load_install('entity');
964
  entity_entitycache_uninstalled_modules($modules);
965
}
966

    
967
/**
968
 * Implements hook_modules_enabled().
969
 */
970
function entity_modules_enabled($modules) {
971
  foreach (_entity_modules_get_default_types($modules) as $type) {
972
    _entity_defaults_rebuild($type);
973
  }
974
}
975

    
976
/**
977
 * Implements hook_modules_disabled().
978
 */
979
function entity_modules_disabled($modules) {
980
  foreach (_entity_modules_get_default_types($modules) as $entity_type) {
981
    $info = entity_get_info($entity_type);
982

    
983
    // Do nothing if the module providing the entity type has been disabled too.
984
    if (isset($info['module']) && in_array($info['module'], $modules)) {
985
      return;
986
    }
987

    
988
    $keys = $info['entity keys'] + array('module' => 'module', 'status' => 'status', 'name' => $info['entity keys']['id']);
989
    // Remove entities provided in code by one of the disabled modules.
990
    $query = new EntityFieldQuery();
991
    $query->entityCondition('entity_type', $entity_type, '=')
992
          ->propertyCondition($keys['module'], $modules, 'IN')
993
          ->propertyCondition($keys['status'], array(ENTITY_IN_CODE, ENTITY_FIXED), 'IN');
994
    $result = $query->execute();
995
    if (isset($result[$entity_type])) {
996
      $entities = entity_load($entity_type, array_keys($result[$entity_type]));
997
      entity_delete_multiple($entity_type, array_keys($entities));
998
    }
999

    
1000
    // Update overridden entities to be now custom.
1001
    $query = new EntityFieldQuery();
1002
    $query->entityCondition('entity_type', $entity_type, '=')
1003
          ->propertyCondition($keys['module'], $modules, 'IN')
1004
          ->propertyCondition($keys['status'], ENTITY_OVERRIDDEN, '=');
1005
    $result = $query->execute();
1006
    if (isset($result[$entity_type])) {
1007
      foreach (entity_load($entity_type, array_keys($result[$entity_type])) as $name => $entity) {
1008
        $entity->{$keys['status']} = ENTITY_CUSTOM;
1009
        $entity->{$keys['module']} = NULL;
1010
        entity_save($entity_type, $entity);
1011
      }
1012
    }
1013

    
1014
    // Rebuild the remaining defaults so any alterations of the disabled modules
1015
    // are gone.
1016
    _entity_defaults_rebuild($entity_type);
1017
  }
1018
}
1019

    
1020
/**
1021
 * Gets all entity types for which defaults are provided by the $modules.
1022
 */
1023
function _entity_modules_get_default_types($modules) {
1024
  $types = array();
1025
  foreach (entity_crud_get_info() as $entity_type => $info) {
1026
    if (!empty($info['exportable'])) {
1027
      $hook = isset($info['export']['default hook']) ? $info['export']['default hook'] : 'default_' . $entity_type;
1028
      foreach ($modules as $module) {
1029
        if (module_hook($module, $hook) || module_hook($module, $hook . '_alter')) {
1030
          $types[] = $entity_type;
1031
        }
1032
      }
1033
    }
1034
  }
1035
  return $types;
1036
}
1037

    
1038
/**
1039
 * Defines schema fields required for exportable entities.
1040
 *
1041
 * Warning: Do not call this function in your module's hook_schema()
1042
 * implementation or update functions. It is not safe to call functions of
1043
 * dependencies at this point. Instead of calling the function, just copy over
1044
 * the content.
1045
 * For more details see the issue http://drupal.org/node/1122812.
1046
 */
1047
function entity_exportable_schema_fields($module_col = 'module', $status_col = 'status') {
1048
  return array(
1049
    $status_col => array(
1050
      'type' => 'int',
1051
      'not null' => TRUE,
1052
      // Set the default to ENTITY_CUSTOM without using the constant as it is
1053
      // not safe to use it at this point.
1054
      'default' => 0x01,
1055
      'size' => 'tiny',
1056
      'description' => 'The exportable status of the entity.',
1057
    ),
1058
    $module_col => array(
1059
      'description' => 'The name of the providing module if the entity has been defined in code.',
1060
      'type' => 'varchar',
1061
      'length' => 255,
1062
      'not null' => FALSE,
1063
    ),
1064
  );
1065
}
1066

    
1067
/**
1068
 * Implements hook_flush_caches().
1069
 */
1070
function entity_flush_caches() {
1071
  entity_property_info_cache_clear();
1072
  // Re-build defaults in code, however skip it on the admin modules page. In
1073
  // case of enabling or disabling modules we already rebuild defaults in
1074
  // entity_modules_enabled() and entity_modules_disabled(), so we do not need
1075
  // to do it again.
1076
  if (current_path() != 'admin/modules/list/confirm') {
1077
    entity_defaults_rebuild();
1078
  }
1079

    
1080
  // Care about entitycache tables.
1081
  if (module_exists('entitycache')) {
1082
    $tables = array();
1083
    foreach (entity_crud_get_info() as $entity_type => $entity_info) {
1084
      if (isset($entity_info['module']) && !empty($entity_info['entity cache'])) {
1085
        $tables[] = 'cache_entity_' . $entity_type;
1086
      }
1087
    }
1088
    return $tables;
1089
  }
1090
}
1091

    
1092
/**
1093
 * Implements hook_theme().
1094
 */
1095
function entity_theme() {
1096
  // Build a pattern in the form of "(type1|type2|...)(\.|__)" such that all
1097
  // templates starting with an entity type or named like the entity type
1098
  // are found.
1099
  // This has to match the template suggestions provided in
1100
  // template_preprocess_entity().
1101
  $types = array_keys(entity_crud_get_info());
1102
  $pattern = '(' . implode('|', $types) . ')(\.|__)';
1103

    
1104
  return array(
1105
    'entity_status' => array(
1106
      'variables' => array('status' => NULL, 'html' => TRUE),
1107
      'file' => 'theme/entity.theme.inc',
1108
    ),
1109
    'entity' => array(
1110
      'render element' => 'elements',
1111
      'template' => 'entity',
1112
      'pattern' => $pattern,
1113
      'path' => drupal_get_path('module', 'entity') . '/theme',
1114
      'file' => 'entity.theme.inc',
1115
    ),
1116
    'entity_property' => array(
1117
      'render element' => 'elements',
1118
      'file' => 'theme/entity.theme.inc',
1119
    ),
1120
    'entity_ui_overview_item' => array(
1121
      'variables' => array('label' => NULL, 'entity_type' => NULL, 'url' => FALSE, 'name' => FALSE),
1122
      'file' => 'includes/entity.ui.inc'
1123
    ),
1124
  );
1125
}
1126

    
1127
/**
1128
 * Label callback that refers to the entity classes label method.
1129
 */
1130
function entity_class_label($entity) {
1131
  return $entity->label();
1132
}
1133

    
1134
/**
1135
 * URI callback that refers to the entity classes uri method.
1136
 */
1137
function entity_class_uri($entity) {
1138
  return $entity->uri();
1139
}
1140

    
1141
/**
1142
 * Implements hook_file_download_access() for entity types provided by the CRUD API.
1143
 */
1144
function entity_file_download_access($field, $entity_type, $entity) {
1145
  $info = entity_get_info($entity_type);
1146
  if (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
1147
    return entity_access('view', $entity_type, $entity);
1148
  }
1149
}
1150

    
1151
/**
1152
 * Determines the UI controller class for a given entity type.
1153
 *
1154
 * @return EntityDefaultUIController
1155
 *   If a type is given, the controller for the given entity type. Else an array
1156
 *   of all enabled UI controllers keyed by entity type is returned.
1157
 */
1158
function entity_ui_controller($type = NULL) {
1159
  $static = &drupal_static(__FUNCTION__);
1160

    
1161
  if (!isset($type)) {
1162
    // Invoke the function for each type to ensure we have fully populated the
1163
    // static variable.
1164
    foreach (entity_get_info() as $entity_type => $info) {
1165
      entity_ui_controller($entity_type);
1166
    }
1167
    return array_filter($static);
1168
  }
1169

    
1170
  if (!isset($static[$type])) {
1171
    $info = entity_get_info($type);
1172
    $class = isset($info['admin ui']['controller class']) ? $info['admin ui']['controller class'] : 'EntityDefaultUIController';
1173
    $static[$type] = (isset($info['admin ui']['path']) && $class) ? new $class($type, $info) : FALSE;
1174
  }
1175

    
1176
  return $static[$type];
1177
}
1178

    
1179
/**
1180
 * Implements hook_menu().
1181
 *
1182
 * @see EntityDefaultUIController::hook_menu()
1183
 */
1184
function entity_menu() {
1185
  $items = array();
1186
  foreach (entity_ui_controller() as $controller) {
1187
    $items += $controller->hook_menu();
1188
  }
1189
  return $items;
1190
}
1191

    
1192
/**
1193
 * Implements hook_forms().
1194
 *
1195
 * @see EntityDefaultUIController::hook_forms()
1196
 * @see entity_ui_get_form()
1197
 */
1198
function entity_forms($form_id, $args) {
1199
  // For efficiency only invoke an entity types controller, if a form of it is
1200
  // requested. Thus if the first (overview and operation form) or the third
1201
  // argument (edit form) is an entity type name, add in the types forms.
1202
  if (isset($args[0]) && is_string($args[0]) && entity_get_info($args[0])) {
1203
    $type = $args[0];
1204
  }
1205
  elseif (isset($args[2]) && is_string($args[2]) && entity_get_info($args[2])) {
1206
    $type = $args[2];
1207
  }
1208
  if (isset($type) && $controller = entity_ui_controller($type)) {
1209
    return $controller->hook_forms();
1210
  }
1211
}
1212

    
1213
/**
1214
 * A wrapper around drupal_get_form() that helps building entity forms.
1215
 *
1216
 * This function may be used by entities to build their entity form. It has to
1217
 * be used instead of calling drupal_get_form().
1218
 * Entity forms built with this helper receive useful defaults suiting for
1219
 * editing a single entity, whereas the special cases of adding and cloning
1220
 * of entities are supported too.
1221
 *
1222
 * While this function is intended to be used to get entity forms for entities
1223
 * using the entity ui controller, it may be used for entity types not using
1224
 * the ui controller too.
1225
 *
1226
 * @param $entity_type
1227
 *   The entity type for which to get the form.
1228
 * @param $entity
1229
 *   The entity for which to return the form.
1230
 *   If $op is 'add' the entity has to be either initialized before calling this
1231
 *   function, or NULL may be passed. If NULL is passed, an entity will be
1232
 *   initialized with empty values using entity_create(). Thus entities, for
1233
 *   which this is problematic have to care to pass in an initialized entity.
1234
 * @param $op
1235
 *   (optional) One of 'edit', 'add' or 'clone'. Defaults to edit.
1236
 * @param $form_state
1237
 *   (optional) A pre-populated form state, e.g. to add in form include files.
1238
 *   See entity_metadata_form_entity_ui().
1239
 *
1240
 * @return
1241
 *   The fully built and processed form, ready to be rendered.
1242
 *
1243
 * @see EntityDefaultUIController::hook_forms()
1244
 * @see entity_ui_form_submit_build_entity()
1245
 */
1246
function entity_ui_get_form($entity_type, $entity, $op = 'edit', $form_state = array()) {
1247
  if (isset($entity)) {
1248
    list(, , $bundle) = entity_extract_ids($entity_type, $entity);
1249
  }
1250
  $form_id = (!isset($bundle) || $bundle == $entity_type) ? $entity_type . '_form' : $entity_type . '_edit_' . $bundle . '_form';
1251

    
1252
  if (!isset($entity) && $op == 'add') {
1253
    $entity = entity_create($entity_type, array());
1254
  }
1255

    
1256
  // Do not use drupal_get_form(), but invoke drupal_build_form() ourself so
1257
  // we can prepulate the form state.
1258
  $form_state['wrapper_callback'] = 'entity_ui_main_form_defaults';
1259
  $form_state['entity_type'] = $entity_type;
1260
  form_load_include($form_state, 'inc', 'entity', 'includes/entity.ui');
1261

    
1262
  // Handle cloning. We cannot do that in the wrapper callback as it is too late
1263
  // for changing arguments.
1264
  if ($op == 'clone') {
1265
    $entity = entity_ui_clone_entity($entity_type, $entity);
1266
  }
1267

    
1268
  // We don't pass the entity type as first parameter, as the implementing
1269
  // module knows the type anyway. However, in order to allow for efficient
1270
  // hook_forms() implementiations we append the entity type as last argument,
1271
  // which the module implementing the form constructor may safely ignore.
1272
  // @see entity_forms()
1273
  $form_state['build_info']['args'] = array($entity, $op, $entity_type);
1274
  return drupal_build_form($form_id, $form_state);
1275
}
1276

    
1277
/**
1278
 * Helper for using i18n_string().
1279
 *
1280
 * @param $name
1281
 *   Textgroup and context glued with ':'.
1282
 * @param $default
1283
 *   String in default language. Default language may or may not be English.
1284
 * @param $langcode
1285
 *   (optional) The code of a certain language to translate the string into.
1286
 *   Defaults to the i18n_string() default, i.e. the current language.
1287
 *
1288
 * @see i18n_string()
1289
 */
1290
function entity_i18n_string($name, $default, $langcode = NULL) {
1291
  return function_exists('i18n_string') ? i18n_string($name, $default, array('langcode' => $langcode)) : $default;
1292
}
1293

    
1294
/**
1295
 * Implements hook_views_api().
1296
 */
1297
function entity_views_api() {
1298
  return array(
1299
    'api' => '3.0-alpha1',
1300
    'path' => drupal_get_path('module', 'entity') . '/views',
1301
  );
1302
}
1303

    
1304
/**
1305
 * Implements hook_field_extra_fields().
1306
 */
1307
function entity_field_extra_fields() {
1308
  // Invoke specified controllers for entity types provided by the CRUD API.
1309
  $items = array();
1310
  foreach (entity_crud_get_info() as $type => $info) {
1311
    if (!empty($info['extra fields controller class'])) {
1312
      $items = array_merge_recursive($items, entity_get_extra_fields_controller($type)->fieldExtraFields());
1313
    }
1314
  }
1315
  return $items;
1316
}
1317

    
1318
/**
1319
 * Gets the extra field controller class for a given entity type.
1320
 *
1321
 * @return EntityExtraFieldsControllerInterface|false
1322
 *   The controller for the given entity type or FALSE if none is specified.
1323
 */
1324
function entity_get_extra_fields_controller($type = NULL) {
1325
  $static = &drupal_static(__FUNCTION__);
1326

    
1327
  if (!isset($static[$type])) {
1328
    $static[$type] = FALSE;
1329
    $info = entity_get_info($type);
1330
    if (!empty($info['extra fields controller class'])) {
1331
      $static[$type] = new $info['extra fields controller class']($type);
1332
    }
1333
  }
1334
  return $static[$type];
1335
}
1336

    
1337
/**
1338
 * Returns a property wrapper for the given data.
1339
 *
1340
 * If an entity is wrapped, the wrapper can be used to retrieve further wrappers
1341
 * for the entitity properties. For that the wrapper support chaining, e.g. you
1342
 * can use a node wrapper to get the node authors mail address:
1343
 *
1344
 * @code
1345
 *   echo $wrappedNode->author->mail->value();
1346
 * @endcode
1347
 *
1348
 * @param $type
1349
 *   The type of the passed data.
1350
 * @param $data
1351
 *   The data to wrap. It may be set to NULL, so the wrapper can be used
1352
 *   without any data for getting information about properties.
1353
 * @param $info
1354
 *   (optional) Specify additional information for the passed data:
1355
 *    - langcode: (optional) If the data is language specific, its langauge
1356
 *      code. Defaults to NULL, what means language neutral.
1357
 *    - bundle: (optional) If an entity is wrapped but not passed, use this key
1358
 *      to specify the bundle to return a wrapper for.
1359
 *    - property info: (optional) May be used to use a wrapper with an arbitrary
1360
 *      data structure (type 'struct'). Use this key for specifying info about
1361
 *      properties in the same structure as used by hook_entity_property_info().
1362
 *    - property info alter: (optional) A callback for altering the property
1363
 *      info before it is utilized by the wrapper.
1364
 *    - property defaults: (optional) An array of defaults for the info of
1365
 *      each property of the wrapped data item.
1366
 * @return EntityMetadataWrapper
1367
 *   Dependend on the passed data the right wrapper is returned.
1368
 */
1369
function entity_metadata_wrapper($type, $data = NULL, array $info = array()) {
1370
  if ($type == 'entity' || (($entity_info = entity_get_info()) && isset($entity_info[$type]))) {
1371
    // If the passed entity is the global $user, we load the user object by only
1372
    // passing on the user id. The global user is not a fully loaded entity.
1373
    if ($type == 'user' && is_object($data) && $data == $GLOBALS['user']) {
1374
      $data = $data->uid;
1375
    }
1376
    return new EntityDrupalWrapper($type, $data, $info);
1377
  }
1378
  elseif ($type == 'list' || entity_property_list_extract_type($type)) {
1379
    return new EntityListWrapper($type, $data, $info);
1380
  }
1381
  elseif (isset($info['property info'])) {
1382
    return new EntityStructureWrapper($type, $data, $info);
1383
  }
1384
  else {
1385
    return new EntityValueWrapper($type, $data, $info);
1386
  }
1387
}
1388

    
1389
/**
1390
 * Returns a metadata wrapper for accessing site-wide properties.
1391
 *
1392
 * Although there is no 'site' entity or such, modules may provide info about
1393
 * site-wide properties using hook_entity_property_info(). This function returns
1394
 * a wrapper for making use of this properties.
1395
 *
1396
 * @return EntityMetadataWrapper
1397
 *   A wrapper for accessing site-wide properties.
1398
 *
1399
 * @see entity_metadata_system_entity_property_info()
1400
 */
1401
function entity_metadata_site_wrapper() {
1402
  $site_info = entity_get_property_info('site');
1403
  $info['property info'] = $site_info['properties'];
1404
  return entity_metadata_wrapper('site', FALSE, $info);
1405
}
1406

    
1407
/**
1408
 * Implements hook_module_implements_alter().
1409
 *
1410
 * Moves the hook_entity_info_alter() implementation to the bottom so it is
1411
 * invoked after all modules relying on the entity API.
1412
 * That way we ensure to run last and clear the field-info cache after the
1413
 * others added in their bundle information.
1414
 *
1415
 * @see entity_entity_info_alter()
1416
 */
1417
function entity_module_implements_alter(&$implementations, $hook) {
1418
  if ($hook == 'entity_info_alter') {
1419
    // Move our hook implementation to the bottom.
1420
    $group = $implementations['entity'];
1421
    unset($implementations['entity']);
1422
    $implementations['entity'] = $group;
1423
  }
1424
}
1425

    
1426
/**
1427
 * Implements hook_entity_info_alter().
1428
 *
1429
 * @see entity_module_implements_alter()
1430
 */
1431
function entity_entity_info_alter(&$entity_info) {
1432
  _entity_info_add_metadata($entity_info);
1433

    
1434
  // Populate a default value for the 'configuration' key of all entity types.
1435
  foreach ($entity_info as $type => $info) {
1436
    if (!isset($info['configuration'])) {
1437
      $entity_info[$type]['configuration'] = !empty($info['exportable']);
1438
    }
1439

    
1440
    if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
1441
      // Automatically disable field cache when entity cache is used.
1442
      if (!empty($info['entity cache']) && module_exists('entitycache')) {
1443
        $entity_info[$type]['field cache'] = FALSE;
1444
      }
1445
    }
1446
  }
1447
}
1448

    
1449
/**
1450
 * Adds metadata and callbacks for core entities to the entity info.
1451
 */
1452
function _entity_info_add_metadata(&$entity_info) {
1453
  // Set plural labels.
1454
  $entity_info['node']['plural label'] = t('Nodes');
1455
  $entity_info['user']['plural label'] = t('Users');
1456
  $entity_info['file']['plural label'] = t('Files');
1457

    
1458
  // Set descriptions.
1459
  $entity_info['node']['description'] = t('Nodes represent the main site content items.');
1460
  $entity_info['user']['description'] = t('Users who have created accounts on your site.');
1461
  $entity_info['file']['description'] = t('Uploaded file.');
1462

    
1463
  // Set access callbacks.
1464
  $entity_info['node']['access callback'] = 'entity_metadata_no_hook_node_access';
1465
  $entity_info['user']['access callback'] = 'entity_metadata_user_access';
1466
  // File entity has it's own entity_access function.
1467
  if (!module_exists('file_entity')) {
1468
    $entity_info['file']['access callback'] = 'entity_metadata_file_access';
1469
  }
1470

    
1471
  // CRUD function callbacks.
1472
  $entity_info['node']['creation callback'] = 'entity_metadata_create_node';
1473
  $entity_info['node']['save callback'] = 'node_save';
1474
  $entity_info['node']['deletion callback'] = 'node_delete';
1475
  $entity_info['node']['revision deletion callback'] = 'node_revision_delete';
1476
  $entity_info['user']['creation callback'] = 'entity_metadata_create_object';
1477
  $entity_info['user']['save callback'] = 'entity_metadata_user_save';
1478
  $entity_info['user']['deletion callback'] = 'user_delete';
1479
  $entity_info['file']['save callback'] = 'file_save';
1480
  $entity_info['file']['deletion callback'] = 'entity_metadata_delete_file';
1481

    
1482
  // Form callbacks.
1483
  $entity_info['node']['form callback'] = 'entity_metadata_form_node';
1484
  $entity_info['user']['form callback'] = 'entity_metadata_form_user';
1485

    
1486
  // URI callbacks.
1487
  if (!isset($entity_info['file']['uri callback'])) {
1488
    $entity_info['file']['uri callback'] = 'entity_metadata_uri_file';
1489
  }
1490

    
1491
  // View callbacks.
1492
  $entity_info['node']['view callback'] = 'entity_metadata_view_node';
1493
  $entity_info['user']['view callback'] = 'entity_metadata_view_single';
1494

    
1495
  if (module_exists('comment')) {
1496
    $entity_info['comment']['plural label'] = t('Comments');
1497
    $entity_info['comment']['description'] = t('Remark or note that refers to a node.');
1498
    $entity_info['comment']['access callback'] = 'entity_metadata_comment_access';
1499
    $entity_info['comment']['creation callback'] = 'entity_metadata_create_comment';
1500
    $entity_info['comment']['save callback'] = 'comment_save';
1501
    $entity_info['comment']['deletion callback'] = 'comment_delete';
1502
    $entity_info['comment']['view callback'] = 'entity_metadata_view_comment';
1503
    $entity_info['comment']['form callback'] = 'entity_metadata_form_comment';
1504
  }
1505
  if (module_exists('taxonomy')) {
1506
    $entity_info['taxonomy_term']['plural label'] = t('Taxonomy terms');
1507
    $entity_info['taxonomy_term']['description'] = t('Taxonomy terms are used for classifying content.');
1508
    $entity_info['taxonomy_term']['access callback'] = 'entity_metadata_taxonomy_access';
1509
    $entity_info['taxonomy_term']['creation callback'] = 'entity_metadata_create_object';
1510
    $entity_info['taxonomy_term']['save callback'] = 'taxonomy_term_save';
1511
    $entity_info['taxonomy_term']['deletion callback'] = 'taxonomy_term_delete';
1512
    $entity_info['taxonomy_term']['view callback'] = 'entity_metadata_view_single';
1513
    $entity_info['taxonomy_term']['form callback'] = 'entity_metadata_form_taxonomy_term';
1514

    
1515
    $entity_info['taxonomy_vocabulary']['plural label'] = t('Taxonomy vocabularies');
1516
    $entity_info['taxonomy_vocabulary']['description'] = t('Vocabularies contain related taxonomy terms, which are used for classifying content.');
1517
    $entity_info['taxonomy_vocabulary']['access callback'] = 'entity_metadata_taxonomy_access';
1518
    $entity_info['taxonomy_vocabulary']['creation callback'] = 'entity_metadata_create_object';
1519
    $entity_info['taxonomy_vocabulary']['save callback'] = 'taxonomy_vocabulary_save';
1520
    $entity_info['taxonomy_vocabulary']['deletion callback'] = 'taxonomy_vocabulary_delete';
1521
    $entity_info['taxonomy_vocabulary']['form callback'] = 'entity_metadata_form_taxonomy_vocabulary';
1522
    // Token type mapping.
1523
    $entity_info['taxonomy_term']['token type'] = 'term';
1524
    $entity_info['taxonomy_vocabulary']['token type'] = 'vocabulary';
1525
  }
1526
}
1527

    
1528
/**
1529
 * Implements hook_ctools_plugin_directory().
1530
 */
1531
function entity_ctools_plugin_directory($module, $plugin) {
1532
  if ($module == 'ctools' && $plugin == 'content_types') {
1533
    return 'ctools/content_types';
1534
  }
1535
}