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 @ 27945136

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

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

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

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

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

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

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

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

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

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

    
203
  entity_make_entity_universal($entity_type, $entities);
204

    
205
  return $entities;
206
}
207

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

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

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

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

    
258
  entity_make_entity_local($entity_type, $entity);
259

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

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

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

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

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

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

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

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

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

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

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

    
389
/**
390
 * Helper function that retrieves entity IDs by their UUIDs.
391
 *
392
 * @todo
393
 *   Limit the query.
394
 *
395
 * @param $entity_type
396
 *   The entity type we should be dealing with.
397
 * @param $uuids
398
 *   An array of UUIDs for which we should find their entity IDs. If $revision
399
 *   is TRUE this should be revision UUIDs instead.
400
 * @param $revision
401
 *   If TRUE the revision IDs is returned instead.
402
 * @return
403
 *   Array 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
    $result = $result->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 $entity_type
466
 *   The entity type we should be dealing with.
467
 * @param $ids
468
 *   An array of entity IDs for which we should find their UUIDs. If $revision
469
 *   is TRUE this should be revision IDs instead.
470
 * @param $revision
471
 *   If TRUE the revision UUIDs is returned instead.
472
 * @return
473
 *   Array of entity UUIDs keyed by their IDs. If $revision is TRUE revision
474
 *   IDs and UUIDs are returned instead.
475
 */
476
function entity_get_uuid_by_id($entity_type, $ids, $revision = FALSE) {
477
  if (empty($ids)) {
478
    return array();
479
  }
480
  $cached_ids = array_flip(entity_uuid_id_cache($entity_type, $ids, $revision));
481
  if (count($cached_ids) == count($ids)) {
482
    return $cached_ids;
483
  }
484
  $ids = array_diff($ids, $cached_ids);
485

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

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

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

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

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