Projet

Général

Profil

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

root / drupal7 / sites / all / modules / uuid / uuid.entity.inc @ f8e16685

1
<?php
2

    
3
/**
4
 * @file
5
 * Entity related functions for UUID module.
6
 */
7

    
8
/**
9
 * Entity UUID exception class.
10
 */
11
class UuidEntityException extends Exception {}
12

    
13
/**
14
 * Returns entity info for all supported core entities.
15
 *
16
 * @see uuid_entity_info()
17
 * @see uuid_schema_alter()
18
 * @see uuid_install()
19
 * @see uuid_uninstall()
20
 */
21
function uuid_get_core_entity_info() {
22
  $info = array();
23
  $info['user'] = array(
24
    'base table' => 'users',
25
    'entity keys' => array(
26
      'uuid' => 'uuid',
27
    ),
28
  );
29
  $info['node'] = array(
30
    'base table' => 'node',
31
    'revision table' => 'node_revision',
32
    'entity keys' => array(
33
      'uuid' => 'uuid',
34
      'revision uuid' => 'vuuid',
35
    ),
36
  );
37
  if (module_exists('comment')) {
38
    $info['comment'] = array(
39
      'base table' => 'comment',
40
      'entity keys' => array(
41
        'uuid' => 'uuid',
42
      ),
43
    );
44
  }
45
  if (module_exists('file')) {
46
    $info['file'] = array(
47
      'base table' => 'file_managed',
48
      'entity keys' => array(
49
        'uuid' => 'uuid',
50
      ),
51
    );
52
  }
53
  if (module_exists('taxonomy')) {
54
    $info['taxonomy_term'] = array(
55
      'base table' => 'taxonomy_term_data',
56
      'entity keys' => array(
57
        'uuid' => 'uuid',
58
      ),
59
    );
60
  }
61
  if (module_exists('field_collection')) {
62
    $info['field_collection_item'] = array(
63
      'base table' => 'field_collection_item',
64
      'entity keys' => array(
65
        'uuid' => 'uuid',
66
      ),
67
    );
68
  }
69
  return $info;
70
}
71

    
72
/**
73
 * @defgroup uuid_entity_hooks UUID implementation of Entity API
74
 * @{
75
 */
76

    
77
/**
78
 * Implements hook_entity_info_alter().
79
 *
80
 * @see uuid_core_entity_info()
81
 */
82
function uuid_entity_info_alter(&$info) {
83
  foreach (uuid_get_core_entity_info() as $entity_type => $core_info) {
84
    $info[$entity_type]['uuid'] = TRUE;
85
    $info[$entity_type]['entity keys']['uuid'] = $core_info['entity keys']['uuid'];
86
    if (!empty($core_info['entity keys']['revision uuid'])) {
87
      $info[$entity_type]['entity keys']['revision uuid'] = $core_info['entity keys']['revision uuid'];
88
    }
89
  }
90
}
91

    
92
/**
93
 * Implements hook_entity_property_info_alter().
94
 *
95
 * This adds the UUID as an entity property for all UUID-enabled entities
96
 * which automatically gives us token and Rules integration.
97
 */
98
function uuid_entity_property_info_alter(&$info) {
99
  foreach (entity_get_info() as $entity_type => $entity_info) {
100
    if (isset($entity_info['uuid']) && $entity_info['uuid'] == TRUE
101
      && !empty($entity_info['entity keys']['uuid'])
102
      && empty($info[$entity_type]['properties'][$entity_info['entity keys']['uuid']])) {
103
      $info[$entity_type]['properties'][$entity_info['entity keys']['uuid']] = array(
104
        'label' => t('UUID'),
105
        'type' => 'text',
106
        'description' => t('The universally unique ID.'),
107
        'schema field' => $entity_info['entity keys']['uuid'],
108
      );
109
      if (!empty($entity_info['entity keys']['revision uuid'])
110
        && empty($info[$entity_type]['properties'][$entity_info['entity keys']['revision uuid']])) {
111
        $info[$entity_type]['properties'][$entity_info['entity keys']['revision uuid']] = array(
112
          'label' => t('Revision UUID'),
113
          'type' => 'text',
114
          'description' => t("The revision's universally unique ID."),
115
          'schema field' => $entity_info['entity keys']['revision uuid'],
116
        );
117
      }
118
    }
119
  }
120
}
121

    
122
/**
123
 * Implements hook_entity_presave().
124
 *
125
 * This is where all UUID-enabled entities get their UUIDs.
126
 */
127
function uuid_entity_presave($entity, $entity_type) {
128
  $info = entity_get_info($entity_type);
129
  if (isset($info['uuid']) && $info['uuid'] == TRUE && !empty($info['entity keys']['uuid'])) {
130
    $uuid_key = $info['entity keys']['uuid'];
131
    if (empty($entity->{$uuid_key})) {
132
      $entity->{$uuid_key} = uuid_generate();
133
    }
134
    if (!empty($info['entity keys']['revision uuid'])) {
135
      $vuuid_key = $info['entity keys']['revision uuid'];
136
      // If this entity comes from a remote environment and have a revision UUID
137
      // that exists locally we should not create a new revision. Because
138
      // otherwise revisions won't be tracked universally.
139
      // TODO: Move code dependent on the uuid_services module into it's own
140
      // implementation of hook_entity_presave().
141
      if (!empty($entity->uuid_services) && isset($entity->{$vuuid_key})) {
142
        $vuuid_exists = (bool) entity_get_id_by_uuid($entity_type, array($entity->{$vuuid_key}), TRUE);
143
        if ($vuuid_exists) {
144
          $entity->revision = FALSE;
145
        }
146
      }
147

    
148
      if ((isset($entity->revision) && $entity->revision == TRUE && empty($entity->uuid_services)) || empty($entity->{$vuuid_key})) {
149
        $entity->{$vuuid_key} = uuid_generate();
150
      }
151
    }
152
  }
153
}
154

    
155
/**
156
 * @} End of "UUID implementation of Entity API"
157
 */
158

    
159
/**
160
 * @defgroup uuid_entity_support UUID support for Entity API
161
 * @{
162
 * Functions that extends the Entity API with UUID support.
163
 */
164

    
165
/**
166
 * Load entities by their UUID, that only should containing UUID references.
167
 *
168
 * Optionally load revisions by their VUUID by passing it into $conditions.
169
 * Ex. $conditions['vuuid'][$vuuid]
170
 *
171
 * This function is mostly useful if you want to load an entity from the local
172
 * database that only should contain UUID references.
173
 *
174
 * @see entity_load()
175
 */
176
function entity_uuid_load($entity_type, $uuids = array(), $conditions = array(), $reset = FALSE) {
177
  // Allow Revision UUID to be passed in $conditions and translate.
178
  $entity_info[$entity_type] = entity_get_info($entity_type);
179
  $revision_key = $entity_info[$entity_type]['entity keys']['revision'];
180
  if (isset($entity_info[$entity_type]['entity keys']['revision uuid'])) {
181
    $revision_uuid_key = $entity_info[$entity_type]['entity keys']['revision uuid'];
182
  }
183
  if (isset($revision_uuid_key) && isset($conditions[$revision_uuid_key])) {
184
    $revision_id = entity_get_id_by_uuid($entity_type, array($conditions[$revision_uuid_key]), TRUE);
185
    $conditions[$revision_key] = $revision_id[$conditions[$revision_uuid_key]];
186
    unset($conditions[$revision_uuid_key]);
187
  }
188
  $ids = entity_get_id_by_uuid($entity_type, $uuids);
189
  $results = entity_load($entity_type, $ids, $conditions, $reset);
190
  $entities = array();
191

    
192
  // We need to do this little magic here, because objects are passed by
193
  // reference. And because hook_entity_uuid_load() has the intention changing
194
  // primary properties and fields from local IDs to UUIDs it will also change
195
  // DrupalDefaultEntityController::entityCache by reference which is a static
196
  // cache of entities. And that is not something we want.
197
  foreach ($results as $key => $entity) {
198
    // This will avoid passing our loaded entities by reference.
199
    $entities[$key] = clone $entity;
200
  }
201

    
202
  entity_make_entity_universal($entity_type, $entities);
203

    
204
  return $entities;
205
}
206

    
207
/**
208
 * Helper function to make an entity universal (i.e. only global references).
209
 */
210
function entity_make_entity_universal($entity_type, $entities) {
211
  // Let other modules transform local ID references to UUID references.
212
  if (!empty($entities)) {
213
    $hook = 'entity_uuid_load';
214
    foreach (module_implements($hook) as $module) {
215
      $function = $module . '_' . $hook;
216
      if (function_exists($function)) {
217
        $function($entities, $entity_type);
218
      }
219
    }
220
  }
221
}
222

    
223
/**
224
 * Permanently saves an entity by its UUID.
225
 *
226
 * This function depends on the Entity API module to provide the
227
 * 'entity_save()' function.
228
 *
229
 * This function is mostly useful if you want to save an entity into the local
230
 * database that only contains UUID references.
231
 *
232
 * @see entity_save()
233
 */
234
function entity_uuid_save($entity_type, $entity) {
235
  // This function, and this function only, depends on the entity module.
236
  if (!module_exists('entity')) {
237
    throw new UuidEntityException(t('Calling %function requires the Entity API module (!link).', array('%function' => __FUNCTION__, '!link' => 'http://drupal.org/project/entity')));
238
  }
239

    
240
  $info = entity_get_info($entity_type);
241
  $uuid_key = $info['entity keys']['uuid'];
242
  if (empty($entity->{$uuid_key}) || !uuid_is_valid($entity->{$uuid_key})) {
243
    watchdog('Entity UUID', 'Attempted to save an entity with an invalid UUID', array(), WATCHDOG_ERROR);
244
    return FALSE;
245
  }
246

    
247
  // Falling back on the variable node_options_[type] is not something an API
248
  // function should take care of. With normal (non UUID) nodes this is dealt
249
  // with in the form submit handler, i.e. not in node_save().
250
  // But since using entity_uuid_save() usually means you're trying to manage
251
  // entities remotely we do respect this variable here to make it work as the
252
  // node form, but only if we explicitly haven't set $node->revision already.
253
  if ($entity_type == 'node' && !isset($entity->revision) && in_array('revision', variable_get('node_options_' . $entity->type, array()))) {
254
    $entity->revision = 1;
255
  }
256

    
257
  entity_make_entity_local($entity_type, $entity);
258

    
259
  // Save the entity.
260
  $result = entity_save($entity_type, $entity);
261

    
262
  $hook = 'entity_uuid_save';
263
  foreach (module_implements($hook) as $module) {
264
    $function = $module . '_' . $hook;
265
    if (function_exists($function)) {
266
      $function($entity, $entity_type);
267
    }
268
  }
269
  return $result;
270
}
271

    
272
/**
273
 * Helper function to make an entity local (i.e. only local references).
274
 */
275
function entity_make_entity_local($entity_type, $entity) {
276
  $info = entity_get_info($entity_type);
277
  if (isset($info['uuid']) && $info['uuid'] == TRUE && !empty($info['entity keys']['uuid'])) {
278
    // Get the keys for local ID and UUID.
279
    $id_key = $info['entity keys']['id'];
280
    $uuid_key = $info['entity keys']['uuid'];
281

    
282
    // UUID entites must always provide a valid UUID when saving in order to do
283
    // the correct mapping between local and global IDs.
284
    if (empty($entity->{$uuid_key}) || !uuid_is_valid($entity->{$uuid_key})) {
285
      throw new UuidEntityException(t('Trying to save a @type entity with empty or invalid UUID.', array('@type' => $info['label'])));
286
    }
287

    
288
    // Fetch the local ID by its UUID.
289
    $ids = entity_get_id_by_uuid($entity_type, array($entity->{$uuid_key}));
290
    $id = reset($ids);
291
    // Set the correct local ID.
292
    if (empty($id)) {
293
      unset($entity->{$id_key});
294
      $entity->is_new = TRUE;
295
    }
296
    else {
297
      $entity->{$id_key} = $id;
298
      $entity->is_new = FALSE;
299
    }
300

    
301
    if (!empty($info['entity keys']['revision uuid'])) {
302
      // Get the keys for local revison ID and revision UUID.
303
      $vid_key = $info['entity keys']['revision'];
304
      $vuuid_key = $info['entity keys']['revision uuid'];
305
      $vid = NULL;
306
      // Fetch the local revision ID by its UUID.
307
      if (isset($entity->{$vuuid_key})) {
308
        // It's important to note that the revision UUID might be set here but
309
        // there might not exist a correspondant local revision ID in which case
310
        // we should unset the assigned revision ID to not confuse anyone with
311
        // revision IDs that might come from other environments.
312
        $vids = entity_get_id_by_uuid($entity_type, array($entity->{$vuuid_key}), TRUE);
313
        $vid = reset($vids);
314
      }
315
      if (empty($vid) && isset($entity->{$vid_key})) {
316
        unset($entity->{$vid_key});
317
      }
318
      elseif (!empty($vid)) {
319
        $entity->{$vid_key} = $vid;
320
      }
321
      // If the revision ID was unset before this (or just missing for some
322
      // reason) we fetch the current revision ID to build a better
323
      // representation of the node object we're working with.
324
      if ($entity_type == 'node' && !isset($entity->vid) && !$entity->is_new) {
325
        $entity->vid = db_select('node', 'n')
326
          ->condition('n.nid', $entity->nid)
327
          ->fields('n', array('vid'))
328
          ->execute()
329
          ->fetchField();
330
      }
331
    }
332

    
333
    // Let other modules transform UUID references to local ID references.
334
    $hook = 'entity_uuid_presave';
335
    foreach (module_implements($hook) as $module) {
336
      $function = $module . '_' . $hook;
337
      if (function_exists($function)) {
338
        $function($entity, $entity_type);
339
      }
340
    }
341
  }
342
  else {
343
    throw new UuidEntityException(t("Trying to operate on a @type entity, which doesn\'t support UUIDs.", array('@type' => $info['label'])));
344
  }
345
}
346

    
347
/**
348
 * Permanently delete the given entity by its UUID.
349
 *
350
 * This function depends on the Entity API module to provide the
351
 * 'entity_delete()' function.
352
 *
353
 * @see entity_delete()
354
 */
355
function entity_uuid_delete($entity_type, $uuid) {
356
  // This function, and this function only, depends on the entity module.
357
  if (!module_exists('entity')) {
358
    throw new UuidEntityException(t('Calling %function requires the Entity API module (!link).', array('%function' => __FUNCTION__, '!link' => 'http://drupal.org/project/entity')));
359
  }
360

    
361
  $info = entity_get_info($entity_type);
362
  if (isset($info['uuid']) && $info['uuid'] == TRUE) {
363
    // Fetch the local ID by its UUID.
364
    $ids = entity_get_id_by_uuid($entity_type, array($uuid));
365
    $id = reset($ids);
366
    $entity = entity_load($entity_type, array($id));
367

    
368
    // Let other modules transform UUID references to local ID references.
369
    $hook = 'entity_uuid_delete';
370
    foreach (module_implements($hook) as $module) {
371
      $function = $module . '_' . $hook;
372
      if (function_exists($function)) {
373
        $function($entity, $entity_type);
374
      }
375
    }
376

    
377
    if (empty($entity)) {
378
      return FALSE;
379
    }
380
    // Delete the entity.
381
    return entity_delete($entity_type, $id);
382
  }
383
  else {
384
    throw new UuidEntityException(t("Trying to delete a @type entity, which doesn\'t support UUIDs.", array('@type' => $info['label'])));
385
  }
386
}
387

    
388
/**
389
 * Helper function that retrieves entity IDs by their UUIDs.
390
 *
391
 * @todo
392
 *   Limit the query.
393
 *
394
 * @param string $entity_type
395
 *   The entity type we should be dealing with.
396
 * @param array $uuids
397
 *   List of UUIDs for which we should find their entity IDs. If $revision
398
 *   is TRUE this should be revision UUIDs instead.
399
 * @param bool $revision
400
 *   If TRUE the revision IDs is returned instead.
401
 *
402
 * @return array
403
 *   List of entity IDs keyed by their UUIDs. If $revision is TRUE revision
404
 *   IDs and UUIDs are returned instead.
405
 */
406
function entity_get_id_by_uuid($entity_type, $uuids, $revision = FALSE) {
407
  if (empty($uuids)) {
408
    return array();
409
  }
410
  $cached_ids = entity_uuid_id_cache($entity_type, $uuids, $revision);
411
  if (count($cached_ids) == count($uuids)) {
412
    return $cached_ids;
413
  }
414
  $uuids = array_diff($uuids, $cached_ids);
415
  $info = entity_get_info($entity_type);
416
  // Some contrib entities has no support for UUID, let's skip them.
417
  if (empty($info['uuid'])) {
418
    return array();
419
  }
420
  // Find out what entity keys to use.
421
  if (!$revision) {
422
    $table = $info['base table'];
423
    $id_key = $info['entity keys']['id'];
424
    $uuid_key = $info['entity keys']['uuid'];
425
  }
426
  elseif (isset($info['revision table'])) {
427
    $table = $info['revision table'];
428
    $id_key = $info['entity keys']['revision'];
429
    $uuid_key = $info['entity keys']['revision uuid'];
430
  }
431
  // If we want revision IDs, but the entity doesn't support it. Return empty.
432
  else {
433
    return array();
434
  }
435

    
436
  // Get all UUIDs in one query.
437
  $result = db_select($table, 't')
438
    ->fields('t', array($uuid_key, $id_key))
439
    ->condition($uuid_key, array_values($uuids), 'IN')
440
    ->execute()
441
    ->fetchAllKeyed();
442
  $cache = &drupal_static('entity_uuid_id_cache', array());
443
  $cache[$entity_type][(int) $revision] += $result;
444
  return $result + $cached_ids;
445
}
446

    
447
/**
448
 * Helper caching function.
449
 */
450
function entity_uuid_id_cache($entity_type, $ids, $revision) {
451
  $cache = &drupal_static(__FUNCTION__, array());
452
  if (empty($cache[$entity_type][(int) $revision])) {
453
    $cache[$entity_type][(int) $revision] = array();
454
  }
455
  $cached_ids = $cache[$entity_type][(int) $revision];
456
  return array_intersect_key($cached_ids, array_flip($ids));
457
}
458

    
459
/**
460
 * Helper function that retrieves UUIDs by their entity IDs.
461
 *
462
 * @todo
463
 *   Limit the query.
464
 *
465
 * @param string $entity_type
466
 *   The entity type we should be dealing with.
467
 * @param array $ids
468
 *   List of entity IDs for which we should find their UUIDs. If $revision
469
 *   is TRUE this should be revision IDs instead.
470
 * @param bool $revision
471
 *   If TRUE the revision UUIDs is returned instead.
472
 *
473
 * @return array
474
 *   List of entity UUIDs keyed by their IDs. If $revision is TRUE revision
475
 *   IDs and UUIDs are returned instead.
476
 */
477
function entity_get_uuid_by_id($entity_type, $ids, $revision = FALSE) {
478
  if (empty($ids)) {
479
    return array();
480
  }
481
  $cached_ids = array_flip(entity_uuid_id_cache($entity_type, $ids, $revision));
482
  if (count($cached_ids) == count($ids)) {
483
    return $cached_ids;
484
  }
485
  $ids = array_diff($ids, $cached_ids);
486

    
487
  $info = entity_get_info($entity_type);
488
  // Some contrib entities has no support for UUID, let's skip them.
489
  if (empty($info['uuid'])) {
490
    return array();
491
  }
492
  // Find out what entity keys to use.
493
  if (!$revision) {
494
    $table = $info['base table'];
495
    $id_key = $info['entity keys']['id'];
496
    $uuid_key = $info['entity keys']['uuid'];
497
  }
498
  elseif (isset($info['revision table'])) {
499
    $table = $info['revision table'];
500
    $id_key = $info['entity keys']['revision'];
501
    $uuid_key = $info['entity keys']['revision uuid'];
502
  }
503
  // If we want revision UUIDs, but the entity doesn't support it. Return empty.
504
  else {
505
    return array();
506
  }
507

    
508
  // Get all UUIDs in one query.
509
  $result = db_select($table, 't')
510
    ->fields('t', array($id_key, $uuid_key))
511
    ->condition($id_key, array_values($ids), 'IN')
512
    ->execute()
513
    ->fetchAllKeyed();
514
  $cache = &drupal_static('entity_uuid_id_cache', array());
515
  $cache[$entity_type][(int) $revision] += array_flip($result);
516
  return $result + $cached_ids;
517
}
518

    
519
/**
520
 * Helper function to change entity properties from ID to UUID.
521
 *
522
 * We never change user UID 0 or 1 to UUIDs. Those are low level user accounts
523
 * ("anonymous" and "root") that needs to be identified consistently across
524
 * any system.
525
 *
526
 * @todo
527
 *   Add tests for this function.
528
 *
529
 * @param array $objects
530
 *   List of objects that should get $properties changed. Can be either an
531
 *   entity object or a field items array.
532
 * @param string $entity_type
533
 *   The type of entity that all $properties refers to.
534
 * @param array $properties
535
 *   An array of properties that should be changed. All properties must refer to
536
 *   the same type of entity (the one referenced in $entity_type).
537
 */
538
function entity_property_id_to_uuid(&$objects, $entity_type, $properties) {
539
  if (!is_array($objects)) {
540
    $things = array(&$objects);
541
  }
542
  else {
543
    $things = &$objects;
544
  }
545
  if (!is_array($properties)) {
546
    $properties = array($properties);
547
  }
548
  $ids = array();
549
  $values = array();
550
  $i = 0;
551
  foreach ($things as &$object) {
552
    foreach ($properties as $property) {
553
      // This is probably an entity object.
554
      if (is_object($object) && isset($object->{$property})) {
555
        $values[$i] = &$object->{$property};
556
      }
557
      // This is probably a field items array.
558
      elseif (is_array($object) && isset($object[$property])) {
559
        $values[$i] = &$object[$property];
560
      }
561
      else {
562
        $i++;
563
        continue;
564
      }
565
      if (!($entity_type == 'user' && ($values[$i] == 0 || $values[$i] == 1))) {
566
        $ids[] = $values[$i];
567
      }
568
      $i++;
569
    }
570
  }
571
  $uuids = entity_get_uuid_by_id($entity_type, $ids);
572
  foreach ($values as $i => $value) {
573
    if (isset($uuids[$value])) {
574
      $values[$i] = $uuids[$value];
575
    }
576
  }
577
}
578

    
579
/**
580
 * Helper function to change entity properties from UUID to ID.
581
 *
582
 * @todo
583
 *   Add tests for this function.
584
 *
585
 * @param array $objects
586
 *   List of objects that should get $properties changed. Can be either an
587
 *   entity object or a field items array.
588
 * @param string $entity_type
589
 *   The type of entity that all $properties refers to.
590
 * @param array $properties
591
 *   An array of properties that should be changed. All properties must refer to
592
 *   the same type of entity (the one referenced in $entity_type).
593
 */
594
function entity_property_uuid_to_id(&$objects, $entity_type, $properties) {
595
  if (!is_array($objects)) {
596
    $things = array(&$objects);
597
  }
598
  else {
599
    $things = &$objects;
600
  }
601
  if (!is_array($properties)) {
602
    $properties = array($properties);
603
  }
604
  $uuids = array();
605
  $values = array();
606
  $i = 0;
607
  foreach ($things as &$object) {
608
    foreach ($properties as $property) {
609
      // This is probably an entity object.
610
      if (is_object($object) && isset($object->{$property})) {
611
        $values[$i] = &$object->{$property};
612
      }
613
      // This is probably a field items array.
614
      elseif (is_array($object) && isset($object[$property])) {
615
        $values[$i] = &$object[$property];
616
      }
617
      else {
618
        $i++;
619
        continue;
620
      }
621
      if (uuid_is_valid($values[$i])) {
622
        $uuids[] = $values[$i];
623
      }
624
      $i++;
625
    }
626
  }
627
  $ids = entity_get_id_by_uuid($entity_type, $uuids);
628
  foreach ($values as $i => $value) {
629
    if (isset($ids[$value])) {
630
      $values[$i] = $ids[$value];
631
    }
632
  }
633
}
634

    
635
/**
636
 * @} End of "UUID support for Entity API"
637
 */