Projet

Général

Profil

Paste
Télécharger (52,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / entity / entity.module @ a45e4bc1

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
  else {
207
    $bundle = NULL;
208
  }
209
  return entity_ui_get_action_title($op, $entity_type, $bundle);
210
}
211

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
778
  if ($prefix) {
779
    $output = str_replace("\n", "\n$prefix", $output);
780
  }
781
  return $output;
782
}
783

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

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

    
818
  if ($prefix) {
819
    $output = str_replace("\n", "\n$prefix", $output);
820
  }
821
  return $output;
822
}
823

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

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

    
866
    // Check for the existence of the module and status columns.
867
    if (!in_array($keys['status'], $info['schema_fields_sql']['base table']) || !in_array($keys['module'], $info['schema_fields_sql']['base table'])) {
868
      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);
869
      return;
870
    }
871

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

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

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

    
900
    // Load all existing entities.
901
    $existing_entities = entity_load_multiple_by_name($entity_type, array_keys($entities));
902

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

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

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

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

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

    
950
    lock_release('entity_rebuild_' . $entity_type);
951
  }
952
}
953

    
954
/**
955
 * Implements hook_modules_installed().
956
 */
957
function entity_modules_installed($modules) {
958
  module_load_install('entity');
959
  entity_entitycache_installed_modules($modules);
960
}
961

    
962
/**
963
 * Implements hook_modules_uninstalled().
964
 */
965
function entity_modules_uninstalled($modules) {
966
  module_load_install('entity');
967
  entity_entitycache_uninstalled_modules($modules);
968
}
969

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1179
  return $static[$type];
1180
}
1181

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

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

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

    
1255
  if (!isset($entity) && $op == 'add') {
1256
    $entity = entity_create($entity_type, array());
1257
  }
1258

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

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

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

    
1280

    
1281
/**
1282
 * Gets the page/menu title for local action operations.
1283
 *
1284
 * @param $op
1285
 *  The current operation. One of 'add' or 'import'.
1286
 * @param $entity_type
1287
 *  The entity type.
1288
 * @param $bundle_name
1289
 *  (Optional) The name of the bundle. May be NULL if the bundle name is not
1290
 *  relevant to the current page. If the entity type has only one bundle, or no
1291
 *  bundles, this will be the same as the entity type.
1292
 */
1293
function entity_ui_get_action_title($op, $entity_type, $bundle_name = NULL) {
1294
  $info = entity_get_info($entity_type);
1295
  switch ($op) {
1296
    case 'add':
1297
      if (isset($bundle_name) && $bundle_name != $entity_type) {
1298
        return t('Add @bundle_name @entity_type', array(
1299
          '@bundle_name' => drupal_strtolower($info['bundles'][$bundle_name]['label']),
1300
          '@entity_type' => drupal_strtolower($info['label']),
1301
        ));
1302
      }
1303
      else {
1304
        return t('Add @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
1305
      }
1306
    case 'import':
1307
      return t('Import @entity_type', array('@entity_type' => drupal_strtolower($info['label'])));
1308
  }
1309
}
1310

    
1311
/**
1312
 * Helper for using i18n_string().
1313
 *
1314
 * @param $name
1315
 *   Textgroup and context glued with ':'.
1316
 * @param $default
1317
 *   String in default language. Default language may or may not be English.
1318
 * @param $langcode
1319
 *   (optional) The code of a certain language to translate the string into.
1320
 *   Defaults to the i18n_string() default, i.e. the current language.
1321
 *
1322
 * @see i18n_string()
1323
 */
1324
function entity_i18n_string($name, $default, $langcode = NULL) {
1325
  return function_exists('i18n_string') ? i18n_string($name, $default, array('langcode' => $langcode)) : $default;
1326
}
1327

    
1328
/**
1329
 * Implements hook_views_api().
1330
 */
1331
function entity_views_api() {
1332
  return array(
1333
    'api' => '3.0-alpha1',
1334
    'path' => drupal_get_path('module', 'entity') . '/views',
1335
  );
1336
}
1337

    
1338
/**
1339
 * Implements hook_field_extra_fields().
1340
 */
1341
function entity_field_extra_fields() {
1342
  // Invoke specified controllers for entity types provided by the CRUD API.
1343
  $items = array();
1344
  foreach (entity_crud_get_info() as $type => $info) {
1345
    if (!empty($info['extra fields controller class'])) {
1346
      $items = array_merge_recursive($items, entity_get_extra_fields_controller($type)->fieldExtraFields());
1347
    }
1348
  }
1349
  return $items;
1350
}
1351

    
1352
/**
1353
 * Gets the extra field controller class for a given entity type.
1354
 *
1355
 * @return EntityExtraFieldsControllerInterface|false
1356
 *   The controller for the given entity type or FALSE if none is specified.
1357
 */
1358
function entity_get_extra_fields_controller($type = NULL) {
1359
  $static = &drupal_static(__FUNCTION__);
1360

    
1361
  if (!isset($static[$type])) {
1362
    $static[$type] = FALSE;
1363
    $info = entity_get_info($type);
1364
    if (!empty($info['extra fields controller class'])) {
1365
      $static[$type] = new $info['extra fields controller class']($type);
1366
    }
1367
  }
1368
  return $static[$type];
1369
}
1370

    
1371
/**
1372
 * Returns a property wrapper for the given data.
1373
 *
1374
 * If an entity is wrapped, the wrapper can be used to retrieve further wrappers
1375
 * for the entitity properties. For that the wrapper support chaining, e.g. you
1376
 * can use a node wrapper to get the node authors mail address:
1377
 *
1378
 * @code
1379
 *   echo $wrappedNode->author->mail->value();
1380
 * @endcode
1381
 *
1382
 * @param $type
1383
 *   The type of the passed data.
1384
 * @param $data
1385
 *   The data to wrap. It may be set to NULL, so the wrapper can be used
1386
 *   without any data for getting information about properties.
1387
 * @param $info
1388
 *   (optional) Specify additional information for the passed data:
1389
 *    - langcode: (optional) If the data is language specific, its langauge
1390
 *      code. Defaults to NULL, what means language neutral.
1391
 *    - bundle: (optional) If an entity is wrapped but not passed, use this key
1392
 *      to specify the bundle to return a wrapper for.
1393
 *    - property info: (optional) May be used to use a wrapper with an arbitrary
1394
 *      data structure (type 'struct'). Use this key for specifying info about
1395
 *      properties in the same structure as used by hook_entity_property_info().
1396
 *    - property info alter: (optional) A callback for altering the property
1397
 *      info before it is utilized by the wrapper.
1398
 *    - property defaults: (optional) An array of defaults for the info of
1399
 *      each property of the wrapped data item.
1400
 * @return EntityMetadataWrapper
1401
 *   Dependend on the passed data the right wrapper is returned.
1402
 */
1403
function entity_metadata_wrapper($type, $data = NULL, array $info = array()) {
1404
  if ($type == 'entity' || (($entity_info = entity_get_info()) && isset($entity_info[$type]))) {
1405
    // If the passed entity is the global $user, we load the user object by only
1406
    // passing on the user id. The global user is not a fully loaded entity.
1407
    if ($type == 'user' && is_object($data) && $data == $GLOBALS['user']) {
1408
      $data = $data->uid;
1409
    }
1410
    return new EntityDrupalWrapper($type, $data, $info);
1411
  }
1412
  elseif ($type == 'list' || entity_property_list_extract_type($type)) {
1413
    return new EntityListWrapper($type, $data, $info);
1414
  }
1415
  elseif (isset($info['property info'])) {
1416
    return new EntityStructureWrapper($type, $data, $info);
1417
  }
1418
  else {
1419
    return new EntityValueWrapper($type, $data, $info);
1420
  }
1421
}
1422

    
1423
/**
1424
 * Returns a metadata wrapper for accessing site-wide properties.
1425
 *
1426
 * Although there is no 'site' entity or such, modules may provide info about
1427
 * site-wide properties using hook_entity_property_info(). This function returns
1428
 * a wrapper for making use of this properties.
1429
 *
1430
 * @return EntityMetadataWrapper
1431
 *   A wrapper for accessing site-wide properties.
1432
 *
1433
 * @see entity_metadata_system_entity_property_info()
1434
 */
1435
function entity_metadata_site_wrapper() {
1436
  $site_info = entity_get_property_info('site');
1437
  $info['property info'] = $site_info['properties'];
1438
  return entity_metadata_wrapper('site', FALSE, $info);
1439
}
1440

    
1441
/**
1442
 * Implements hook_module_implements_alter().
1443
 *
1444
 * Moves the hook_entity_info_alter() implementation to the bottom so it is
1445
 * invoked after all modules relying on the entity API.
1446
 * That way we ensure to run last and clear the field-info cache after the
1447
 * others added in their bundle information.
1448
 *
1449
 * @see entity_entity_info_alter()
1450
 */
1451
function entity_module_implements_alter(&$implementations, $hook) {
1452
  if ($hook == 'entity_info_alter') {
1453
    // Move our hook implementation to the bottom.
1454
    $group = $implementations['entity'];
1455
    unset($implementations['entity']);
1456
    $implementations['entity'] = $group;
1457
  }
1458
}
1459

    
1460
/**
1461
 * Implements hook_entity_info_alter().
1462
 *
1463
 * @see entity_module_implements_alter()
1464
 */
1465
function entity_entity_info_alter(&$entity_info) {
1466
  _entity_info_add_metadata($entity_info);
1467

    
1468
  // Populate a default value for the 'configuration' key of all entity types.
1469
  foreach ($entity_info as $type => $info) {
1470
    if (!isset($info['configuration'])) {
1471
      $entity_info[$type]['configuration'] = !empty($info['exportable']);
1472
    }
1473

    
1474
    if (isset($info['controller class']) && in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
1475
      // Automatically disable field cache when entity cache is used.
1476
      if (!empty($info['entity cache']) && module_exists('entitycache')) {
1477
        $entity_info[$type]['field cache'] = FALSE;
1478
      }
1479
    }
1480
  }
1481
}
1482

    
1483
/**
1484
 * Adds metadata and callbacks for core entities to the entity info.
1485
 */
1486
function _entity_info_add_metadata(&$entity_info) {
1487
  // Set plural labels.
1488
  $entity_info['node']['plural label'] = t('Nodes');
1489
  $entity_info['user']['plural label'] = t('Users');
1490
  $entity_info['file']['plural label'] = t('Files');
1491

    
1492
  // Set descriptions.
1493
  $entity_info['node']['description'] = t('Nodes represent the main site content items.');
1494
  $entity_info['user']['description'] = t('Users who have created accounts on your site.');
1495
  $entity_info['file']['description'] = t('Uploaded file.');
1496

    
1497
  // Set access callbacks.
1498
  $entity_info['node']['access callback'] = 'entity_metadata_no_hook_node_access';
1499
  $entity_info['user']['access callback'] = 'entity_metadata_user_access';
1500
  // File entity has it's own entity_access function.
1501
  if (!module_exists('file_entity')) {
1502
    $entity_info['file']['access callback'] = 'entity_metadata_file_access';
1503
  }
1504

    
1505
  // CRUD function callbacks.
1506
  $entity_info['node']['creation callback'] = 'entity_metadata_create_node';
1507
  $entity_info['node']['save callback'] = 'node_save';
1508
  $entity_info['node']['deletion callback'] = 'node_delete';
1509
  $entity_info['node']['revision deletion callback'] = 'node_revision_delete';
1510
  $entity_info['user']['creation callback'] = 'entity_metadata_create_object';
1511
  $entity_info['user']['save callback'] = 'entity_metadata_user_save';
1512
  $entity_info['user']['deletion callback'] = 'user_delete';
1513
  $entity_info['file']['save callback'] = 'file_save';
1514
  $entity_info['file']['deletion callback'] = 'entity_metadata_delete_file';
1515

    
1516
  // Form callbacks.
1517
  $entity_info['node']['form callback'] = 'entity_metadata_form_node';
1518
  $entity_info['user']['form callback'] = 'entity_metadata_form_user';
1519

    
1520
  // URI callbacks.
1521
  if (!isset($entity_info['file']['uri callback'])) {
1522
    $entity_info['file']['uri callback'] = 'entity_metadata_uri_file';
1523
  }
1524

    
1525
  // View callbacks.
1526
  $entity_info['node']['view callback'] = 'entity_metadata_view_node';
1527
  $entity_info['user']['view callback'] = 'entity_metadata_view_single';
1528

    
1529
  if (module_exists('comment')) {
1530
    $entity_info['comment']['plural label'] = t('Comments');
1531
    $entity_info['comment']['description'] = t('Remark or note that refers to a node.');
1532
    $entity_info['comment']['access callback'] = 'entity_metadata_comment_access';
1533
    $entity_info['comment']['creation callback'] = 'entity_metadata_create_comment';
1534
    $entity_info['comment']['save callback'] = 'comment_save';
1535
    $entity_info['comment']['deletion callback'] = 'comment_delete';
1536
    $entity_info['comment']['view callback'] = 'entity_metadata_view_comment';
1537
    $entity_info['comment']['form callback'] = 'entity_metadata_form_comment';
1538
  }
1539
  if (module_exists('taxonomy')) {
1540
    $entity_info['taxonomy_term']['plural label'] = t('Taxonomy terms');
1541
    $entity_info['taxonomy_term']['description'] = t('Taxonomy terms are used for classifying content.');
1542
    $entity_info['taxonomy_term']['access callback'] = 'entity_metadata_taxonomy_access';
1543
    $entity_info['taxonomy_term']['creation callback'] = 'entity_metadata_create_object';
1544
    $entity_info['taxonomy_term']['save callback'] = 'taxonomy_term_save';
1545
    $entity_info['taxonomy_term']['deletion callback'] = 'taxonomy_term_delete';
1546
    $entity_info['taxonomy_term']['view callback'] = 'entity_metadata_view_single';
1547
    $entity_info['taxonomy_term']['form callback'] = 'entity_metadata_form_taxonomy_term';
1548

    
1549
    $entity_info['taxonomy_vocabulary']['plural label'] = t('Taxonomy vocabularies');
1550
    $entity_info['taxonomy_vocabulary']['description'] = t('Vocabularies contain related taxonomy terms, which are used for classifying content.');
1551
    $entity_info['taxonomy_vocabulary']['access callback'] = 'entity_metadata_taxonomy_access';
1552
    $entity_info['taxonomy_vocabulary']['creation callback'] = 'entity_metadata_create_object';
1553
    $entity_info['taxonomy_vocabulary']['save callback'] = 'taxonomy_vocabulary_save';
1554
    $entity_info['taxonomy_vocabulary']['deletion callback'] = 'taxonomy_vocabulary_delete';
1555
    $entity_info['taxonomy_vocabulary']['form callback'] = 'entity_metadata_form_taxonomy_vocabulary';
1556
    // Token type mapping.
1557
    $entity_info['taxonomy_term']['token type'] = 'term';
1558
    $entity_info['taxonomy_vocabulary']['token type'] = 'vocabulary';
1559
  }
1560
}
1561

    
1562
/**
1563
 * Implements hook_ctools_plugin_directory().
1564
 */
1565
function entity_ctools_plugin_directory($module, $plugin) {
1566
  if ($module == 'ctools' && $plugin == 'content_types') {
1567
    return 'ctools/content_types';
1568
  }
1569
}