Projet

Général

Profil

Paste
Télécharger (19,3 ko) Statistiques
| Branche: | Révision:

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

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
  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
}
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
 *   Statically cache as many IDs as possible and limit the query.
393
 *
394
 * @param $entity_type
395
 *   The entity type we should be dealing with.
396
 * @param $uuids
397
 *   An array of UUIDs for which we should find their entity IDs. If $revision
398
 *   is TRUE this should be revision UUIDs instead.
399
 * @param $revision
400
 *   If TRUE the revision IDs is returned instead.
401
 * @return
402
 *   Array of entity IDs keyed by their UUIDs. If $revision is TRUE revision
403
 *   IDs and UUIDs are returned instead.
404
 */
405
function entity_get_id_by_uuid($entity_type, $uuids, $revision = FALSE) {
406
  if (empty($uuids)) {
407
    return array();
408
  }
409
  $info = entity_get_info($entity_type);
410
  // Find out what entity keys to use.
411
  if (!$revision) {
412
    $table = $info['base table'];
413
    $id_key = $info['entity keys']['id'];
414
    $uuid_key = $info['entity keys']['uuid'];
415
  }
416
  elseif (isset($info['revision table'])) {
417
    $table = $info['revision table'];
418
    $id_key = $info['entity keys']['revision'];
419
    $uuid_key = $info['entity keys']['revision uuid'];
420
  }
421
  // If we want revision IDs, but the entity doesn't support it. Return empty.
422
  else {
423
    return array();
424
  }
425

    
426
  // Get all UUIDs in one query.
427
  return db_select($table, 't')
428
    ->fields('t', array($uuid_key, $id_key))
429
    ->condition($uuid_key, array_values($uuids), 'IN')
430
    ->execute()
431
    ->fetchAllKeyed();
432
}
433

    
434
/**
435
 * Helper function that retrieves UUIDs by their entity IDs.
436
 *
437
 * @todo
438
 *   Statically cache as many IDs as possible and limit the query.
439
 *
440
 * @param $entity_type
441
 *   The entity type we should be dealing with.
442
 * @param $ids
443
 *   An array of entity IDs for which we should find their UUIDs. If $revision
444
 *   is TRUE this should be revision IDs instead.
445
 * @param $revision
446
 *   If TRUE the revision UUIDs is returned instead.
447
 * @return
448
 *   Array of entity UUIDs keyed by their IDs. If $revision is TRUE revision
449
 *   IDs and UUIDs are returned instead.
450
 */
451
function entity_get_uuid_by_id($entity_type, $ids, $revision = FALSE) {
452
  if (empty($ids)) {
453
    return array();
454
  }
455
  $info = entity_get_info($entity_type);
456
  // Find out what entity keys to use.
457
  if (!$revision) {
458
    $table = $info['base table'];
459
    $id_key = $info['entity keys']['id'];
460
    $uuid_key = $info['entity keys']['uuid'];
461
  }
462
  elseif (isset($info['revision table'])) {
463
    $table = $info['revision table'];
464
    $id_key = $info['entity keys']['revision'];
465
    $uuid_key = $info['entity keys']['revision uuid'];
466
  }
467
  // If we want revision UUIDs, but the entity doesn't support it. Return empty.
468
  else {
469
    return array();
470
  }
471

    
472
  // Get all UUIDs in one query.
473
  return db_select($table, 't')
474
    ->fields('t', array($id_key, $uuid_key))
475
    ->condition($id_key, array_values($ids), 'IN')
476
    ->execute()
477
    ->fetchAllKeyed();
478
}
479

    
480
/**
481
 * Helper function to change entity properties from ID to UUID.
482
 *
483
 * We never change user UID 0 or 1 to UUIDs. Those are low level user accounts
484
 * ("anonymous" and "root") that needs to be identified consistently across
485
 * any system.
486
 *
487
 * @todo
488
 *   Add tests for this function.
489
 *
490
 * @param $objects
491
 *   An array of objects that should get $properties changed. Can be either an
492
 *   entity object or a field items array.
493
 * @param $entity_type
494
 *   The type of entity that all $properties refers to.
495
 * @param $properties
496
 *   An array of properties that should be changed. All properties must refer to
497
 *   the same type of entity (the one referenced in $entity_type).
498
 */
499
function entity_property_id_to_uuid(&$objects, $entity_type, $properties) {
500
  if (!is_array($objects)) {
501
    $things = array(&$objects);
502
  }
503
  else {
504
    $things = &$objects;
505
  }
506
  if (!is_array($properties)) {
507
    $properties = array($properties);
508
  }
509
  $ids = array();
510
  $values = array();
511
  $i = 0;
512
  foreach ($things as &$object) {
513
    foreach ($properties as $property) {
514
      // This is probably an entity object.
515
      if (is_object($object) && isset($object->{$property})) {
516
        $values[$i] = &$object->{$property};
517
      }
518
      // This is probably a field items array.
519
      elseif (is_array($object) && isset($object[$property])) {
520
        $values[$i] = &$object[$property];
521
      }
522
      else {
523
        $i++;
524
        continue;
525
      }
526
      if (!($entity_type == 'user' && ($values[$i] == 0 || $values[$i] == 1))) {
527
        $ids[] = $values[$i];
528
      }
529
      $i++;
530
    }
531
  }
532
  $uuids = entity_get_uuid_by_id($entity_type, $ids);
533
  foreach ($values as $i => $value) {
534
    if (isset($uuids[$value])) {
535
      $values[$i] = $uuids[$value];
536
    }
537
  }
538
}
539

    
540
/**
541
 * Helper function to change entity properties from UUID to ID.
542
 *
543
 * @todo
544
 *   Add tests for this function.
545
 *
546
 * @param $objects
547
 *   An array of objects that should get $properties changed. Can be either an
548
 *   entity object or a field items array.
549
 * @param $entity_type
550
 *   The type of entity that all $properties refers to.
551
 * @param $properties
552
 *   An array of properties that should be changed. All properties must refer to
553
 *   the same type of entity (the one referenced in $entity_type).
554
 */
555
function entity_property_uuid_to_id(&$objects, $entity_type, $properties) {
556
  if (!is_array($objects)) {
557
    $things = array(&$objects);
558
  }
559
  else {
560
    $things = &$objects;
561
  }
562
  if (!is_array($properties)) {
563
    $properties = array($properties);
564
  }
565
  $uuids = array();
566
  $values = array();
567
  $i = 0;
568
  foreach ($things as &$object) {
569
    foreach ($properties as $property) {
570
      // This is probably an entity object.
571
      if (is_object($object) && isset($object->{$property})) {
572
        $values[$i] = &$object->{$property};
573
      }
574
      // This is probably a field items array.
575
      elseif (is_array($object) && isset($object[$property])) {
576
        $values[$i] = &$object[$property];
577
      }
578
      else {
579
        $i++;
580
        continue;
581
      }
582
      if (uuid_is_valid($values[$i])) {
583
        $uuids[] = $values[$i];
584
      }
585
      $i++;
586
    }
587
  }
588
  $ids = entity_get_id_by_uuid($entity_type, $uuids);
589
  foreach ($values as $i => $value) {
590
    if (isset($ids[$value])) {
591
      $values[$i] = $ids[$value];
592
    }
593
  }
594
}
595

    
596
/**
597
 * @} End of "UUID support for Entity API"
598
 */