uuid.entity.inc 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  1. <?php
  2. /**
  3. * @file
  4. * Entity related functions for UUID module.
  5. */
  6. /**
  7. * Entity UUID exception class.
  8. */
  9. class UuidEntityException extends Exception {}
  10. /**
  11. * Helper function that returns entity info for all supported core modules,
  12. * relevant for UUID functionality.
  13. *
  14. * @see uuid_entity_info()
  15. * @see uuid_schema_alter()
  16. * @see uuid_install()
  17. * @see uuid_uninstall()
  18. */
  19. function uuid_get_core_entity_info() {
  20. $info = array();
  21. $info['user'] = array(
  22. 'base table' => 'users',
  23. 'entity keys' => array(
  24. 'uuid' => 'uuid',
  25. ),
  26. );
  27. $info['node'] = array(
  28. 'base table' => 'node',
  29. 'revision table' => 'node_revision',
  30. 'entity keys' => array(
  31. 'uuid' => 'uuid',
  32. 'revision uuid' => 'vuuid',
  33. ),
  34. );
  35. if (module_exists('comment')) {
  36. $info['comment'] = array(
  37. 'base table' => 'comment',
  38. 'entity keys' => array(
  39. 'uuid' => 'uuid',
  40. ),
  41. );
  42. }
  43. if (module_exists('file')) {
  44. $info['file'] = array(
  45. 'base table' => 'file_managed',
  46. 'entity keys' => array(
  47. 'uuid' => 'uuid',
  48. ),
  49. );
  50. }
  51. if (module_exists('taxonomy')) {
  52. $info['taxonomy_term'] = array(
  53. 'base table' => 'taxonomy_term_data',
  54. 'entity keys' => array(
  55. 'uuid' => 'uuid',
  56. ),
  57. );
  58. }
  59. if (module_exists('field_collection')) {
  60. $info['field_collection_item'] = array(
  61. 'base table' => 'field_collection_item',
  62. 'entity keys' => array(
  63. 'uuid' => 'uuid',
  64. ),
  65. );
  66. }
  67. return $info;
  68. }
  69. /**
  70. * @defgroup uuid_entity_hooks UUID implementation of Entity API
  71. * @{
  72. */
  73. /**
  74. * Implements hook_entity_info_alter().
  75. *
  76. * @see uuid_core_entity_info()
  77. */
  78. function uuid_entity_info_alter(&$info) {
  79. foreach (uuid_get_core_entity_info() as $entity_type => $core_info) {
  80. $info[$entity_type]['uuid'] = TRUE;
  81. $info[$entity_type]['entity keys']['uuid'] = $core_info['entity keys']['uuid'];
  82. if (!empty($core_info['entity keys']['revision uuid'])) {
  83. $info[$entity_type]['entity keys']['revision uuid'] = $core_info['entity keys']['revision uuid'];
  84. }
  85. }
  86. }
  87. /**
  88. * Implements hook_entity_property_info_alter().
  89. *
  90. * This adds the UUID as an entity property for all UUID-enabled entities
  91. * which automatically gives us token and Rules integration.
  92. */
  93. function uuid_entity_property_info_alter(&$info) {
  94. foreach (entity_get_info() as $entity_type => $entity_info) {
  95. if (isset($entity_info['uuid']) && $entity_info['uuid'] == TRUE
  96. && !empty($entity_info['entity keys']['uuid'])
  97. && empty($info[$entity_type]['properties'][$entity_info['entity keys']['uuid']])) {
  98. $info[$entity_type]['properties'][$entity_info['entity keys']['uuid']] = array(
  99. 'label' => t('UUID'),
  100. 'type' => 'text',
  101. 'description' => t('The universally unique ID.'),
  102. 'schema field' => $entity_info['entity keys']['uuid'],
  103. );
  104. if (!empty($entity_info['entity keys']['revision uuid'])
  105. && empty($info[$entity_type]['properties'][$entity_info['entity keys']['revision uuid']])) {
  106. $info[$entity_type]['properties'][$entity_info['entity keys']['revision uuid']] = array(
  107. 'label' => t('Revision UUID'),
  108. 'type' => 'text',
  109. 'description' => t("The revision's universally unique ID."),
  110. 'schema field' => $entity_info['entity keys']['revision uuid'],
  111. );
  112. }
  113. }
  114. }
  115. }
  116. /**
  117. * Implements hook_entity_presave().
  118. *
  119. * This is where all UUID-enabled entities get their UUIDs.
  120. */
  121. function uuid_entity_presave($entity, $entity_type) {
  122. $info = entity_get_info($entity_type);
  123. if (isset($info['uuid']) && $info['uuid'] == TRUE && !empty($info['entity keys']['uuid'])) {
  124. $uuid_key = $info['entity keys']['uuid'];
  125. if (empty($entity->{$uuid_key})) {
  126. $entity->{$uuid_key} = uuid_generate();
  127. }
  128. if (!empty($info['entity keys']['revision uuid'])) {
  129. $vuuid_key = $info['entity keys']['revision uuid'];
  130. // If this entity comes from a remote environment and have a revision UUID
  131. // that exists locally we should not create a new revision. Because
  132. // otherwise revisions won't be tracked universally.
  133. // TODO: Move code dependent on the uuid_services module into it's own
  134. // implementation of hook_entity_presave().
  135. if (!empty($entity->uuid_services) && isset($entity->{$vuuid_key})) {
  136. $vuuid_exists = (bool) entity_get_id_by_uuid($entity_type, array($entity->{$vuuid_key}), TRUE);
  137. if ($vuuid_exists) {
  138. $entity->revision = FALSE;
  139. }
  140. }
  141. if ((isset($entity->revision) && $entity->revision == TRUE && empty($entity->uuid_services)) || empty($entity->{$vuuid_key})) {
  142. $entity->{$vuuid_key} = uuid_generate();
  143. }
  144. }
  145. }
  146. }
  147. /**
  148. * @} End of "UUID implementation of Entity API"
  149. */
  150. /**
  151. * @defgroup uuid_entity_support UUID support for Entity API
  152. * @{
  153. * Functions that extends the Entity API with UUID support.
  154. */
  155. /**
  156. * Load entities by their UUID, that only should containing UUID references.
  157. *
  158. * Optionally load revisions by their VUUID by passing it into $conditions.
  159. * Ex. $conditions['vuuid'][$vuuid]
  160. *
  161. * This function is mostly useful if you want to load an entity from the local
  162. * database that only should contain UUID references.
  163. *
  164. * @see entity_load()
  165. */
  166. function entity_uuid_load($entity_type, $uuids = array(), $conditions = array(), $reset = FALSE) {
  167. // Allow Revision UUID to be passed in $conditions and translate.
  168. $entity_info[$entity_type] = entity_get_info($entity_type);
  169. $revision_key = $entity_info[$entity_type]['entity keys']['revision'];
  170. if (isset($entity_info[$entity_type]['entity keys']['revision uuid'])) {
  171. $revision_uuid_key = $entity_info[$entity_type]['entity keys']['revision uuid'];
  172. }
  173. if (isset($revision_uuid_key) && isset($conditions[$revision_uuid_key])) {
  174. $revision_id = entity_get_id_by_uuid($entity_type, array($conditions[$revision_uuid_key]), TRUE);
  175. $conditions[$revision_key] = $revision_id[$conditions[$revision_uuid_key]];
  176. unset($conditions[$revision_uuid_key]);
  177. }
  178. $ids = entity_get_id_by_uuid($entity_type, $uuids);
  179. $results = entity_load($entity_type, $ids, $conditions, $reset);
  180. $entities = array();
  181. // We need to do this little magic here, because objects are passed by
  182. // reference. And because hook_entity_uuid_load() has the intention changing
  183. // primary properties and fields from local IDs to UUIDs it will also change
  184. // DrupalDefaultEntityController::entityCache by reference which is a static
  185. // cache of entities. And that is not something we want.
  186. foreach ($results as $key => $entity) {
  187. // This will avoid passing our loaded entities by reference.
  188. $entities[$key] = clone $entity;
  189. }
  190. entity_make_entity_universal($entity_type, $entities);
  191. return $entities;
  192. }
  193. /**
  194. * Helper function to make an entity universal (i.e. only global references).
  195. */
  196. function entity_make_entity_universal($entity_type, $entities) {
  197. // Let other modules transform local ID references to UUID references.
  198. if (!empty($entities)) {
  199. $hook = 'entity_uuid_load';
  200. foreach (module_implements($hook) as $module) {
  201. $function = $module . '_' . $hook;
  202. if (function_exists($function)) {
  203. $function($entities, $entity_type);
  204. }
  205. }
  206. }
  207. }
  208. /**
  209. * Permanently saves an entity by its UUID.
  210. *
  211. * This function depends on the Entity API module to provide the
  212. * 'entity_save()' function.
  213. *
  214. * This function is mostly useful if you want to save an entity into the local
  215. * database that only contains UUID references.
  216. *
  217. * @see entity_save()
  218. */
  219. function entity_uuid_save($entity_type, $entity) {
  220. // This function, and this function only, depends on the entity module.
  221. if (!module_exists('entity')) {
  222. throw new UuidEntityException(t('Calling %function requires the Entity API module (!link).', array('%function' => __FUNCTION__, '!link' => 'http://drupal.org/project/entity')));
  223. }
  224. $info = entity_get_info($entity_type);
  225. $uuid_key = $info['entity keys']['uuid'];
  226. if (empty($entity->{$uuid_key}) || !uuid_is_valid($entity->{$uuid_key})) {
  227. watchdog('Entity UUID', 'Attempted to save an entity with an invalid UUID', array(), WATCHDOG_ERROR);
  228. return FALSE;
  229. }
  230. // Falling back on the variable node_options_[type] is not something an API
  231. // function should take care of. With normal (non UUID) nodes this is dealt
  232. // with in the form submit handler, i.e. not in node_save().
  233. // But since using entity_uuid_save() usually means you're trying to manage
  234. // entities remotely we do respect this variable here to make it work as the
  235. // node form, but only if we explicitly haven't set $node->revision already.
  236. if ($entity_type == 'node' && !isset($entity->revision) && in_array('revision', variable_get('node_options_' . $entity->type, array()))) {
  237. $entity->revision = 1;
  238. }
  239. entity_make_entity_local($entity_type, $entity);
  240. // Save the entity.
  241. entity_save($entity_type, $entity);
  242. $hook = 'entity_uuid_save';
  243. foreach (module_implements($hook) as $module) {
  244. $function = $module . '_' . $hook;
  245. if (function_exists($function)) {
  246. $function($entity, $entity_type);
  247. }
  248. }
  249. }
  250. /**
  251. * Helper function to make an entity local (i.e. only local references).
  252. */
  253. function entity_make_entity_local($entity_type, $entity) {
  254. $info = entity_get_info($entity_type);
  255. if (isset($info['uuid']) && $info['uuid'] == TRUE && !empty($info['entity keys']['uuid'])) {
  256. // Get the keys for local ID and UUID.
  257. $id_key = $info['entity keys']['id'];
  258. $uuid_key = $info['entity keys']['uuid'];
  259. // UUID entites must always provide a valid UUID when saving in order to do
  260. // the correct mapping between local and global IDs.
  261. if (empty($entity->{$uuid_key}) || !uuid_is_valid($entity->{$uuid_key})) {
  262. throw new UuidEntityException(t('Trying to save a @type entity with empty or invalid UUID.', array('@type' => $info['label'])));
  263. }
  264. // Fetch the local ID by its UUID.
  265. $ids = entity_get_id_by_uuid($entity_type, array($entity->{$uuid_key}));
  266. $id = reset($ids);
  267. // Set the correct local ID.
  268. if (empty($id)) {
  269. unset($entity->{$id_key});
  270. $entity->is_new = TRUE;
  271. }
  272. else {
  273. $entity->{$id_key} = $id;
  274. $entity->is_new = FALSE;
  275. }
  276. if (!empty($info['entity keys']['revision uuid'])) {
  277. // Get the keys for local revison ID and revision UUID.
  278. $vid_key = $info['entity keys']['revision'];
  279. $vuuid_key = $info['entity keys']['revision uuid'];
  280. $vid = NULL;
  281. // Fetch the local revision ID by its UUID.
  282. if (isset($entity->{$vuuid_key})) {
  283. // It's important to note that the revision UUID might be set here but
  284. // there might not exist a correspondant local revision ID in which case
  285. // we should unset the assigned revision ID to not confuse anyone with
  286. // revision IDs that might come from other environments.
  287. $vids = entity_get_id_by_uuid($entity_type, array($entity->{$vuuid_key}), TRUE);
  288. $vid = reset($vids);
  289. }
  290. if (empty($vid) && isset($entity->{$vid_key})) {
  291. unset($entity->{$vid_key});
  292. }
  293. elseif (!empty($vid)) {
  294. $entity->{$vid_key} = $vid;
  295. }
  296. // If the revision ID was unset before this (or just missing for some
  297. // reason) we fetch the current revision ID to build a better
  298. // representation of the node object we're working with.
  299. if ($entity_type == 'node' && !isset($entity->vid) && !$entity->is_new) {
  300. $entity->vid = db_select('node', 'n')
  301. ->condition('n.nid', $entity->nid)
  302. ->fields('n', array('vid'))
  303. ->execute()
  304. ->fetchField();
  305. }
  306. }
  307. // Let other modules transform UUID references to local ID references.
  308. $hook = 'entity_uuid_presave';
  309. foreach (module_implements($hook) as $module) {
  310. $function = $module . '_' . $hook;
  311. if (function_exists($function)) {
  312. $function($entity, $entity_type);
  313. }
  314. }
  315. }
  316. else {
  317. throw new UuidEntityException(t('Trying to operate on a @type entity, which doesn\'t support UUIDs.', array('@type' => $info['label'])));
  318. }
  319. }
  320. /**
  321. * Permanently delete the given entity by its UUID.
  322. *
  323. * This function depends on the Entity API module to provide the
  324. * 'entity_delete()' function.
  325. *
  326. * @see entity_delete()
  327. */
  328. function entity_uuid_delete($entity_type, $uuid) {
  329. // This function, and this function only, depends on the entity module.
  330. if (!module_exists('entity')) {
  331. throw new UuidEntityException(t('Calling %function requires the Entity API module (!link).', array('%function' => __FUNCTION__, '!link' => 'http://drupal.org/project/entity')));
  332. }
  333. $info = entity_get_info($entity_type);
  334. if (isset($info['uuid']) && $info['uuid'] == TRUE) {
  335. // Fetch the local ID by its UUID.
  336. $ids = entity_get_id_by_uuid($entity_type, array($uuid));
  337. $id = reset($ids);
  338. $entity = entity_load($entity_type, array($id));
  339. // Let other modules transform UUID references to local ID references.
  340. $hook = 'entity_uuid_delete';
  341. foreach (module_implements($hook) as $module) {
  342. $function = $module . '_' . $hook;
  343. if (function_exists($function)) {
  344. $function($entity, $entity_type);
  345. }
  346. }
  347. if (empty($entity)) {
  348. return FALSE;
  349. }
  350. // Delete the entity.
  351. return entity_delete($entity_type, $id);
  352. }
  353. else {
  354. throw new UuidEntityException(t('Trying to delete a @type entity, which doesn\'t support UUIDs.', array('@type' => $info['label'])));
  355. }
  356. }
  357. /**
  358. * Helper function that retrieves entity IDs by their UUIDs.
  359. *
  360. * @todo
  361. * Statically cache as many IDs as possible and limit the query.
  362. *
  363. * @param $entity_type
  364. * The entity type we should be dealing with.
  365. * @param $uuids
  366. * An array of UUIDs for which we should find their entity IDs. If $revision
  367. * is TRUE this should be revision UUIDs instead.
  368. * @param $revision
  369. * If TRUE the revision IDs is returned instead.
  370. * @return
  371. * Array of entity IDs keyed by their UUIDs. If $revision is TRUE revision
  372. * IDs and UUIDs are returned instead.
  373. */
  374. function entity_get_id_by_uuid($entity_type, $uuids, $revision = FALSE) {
  375. if (empty($uuids)) {
  376. return array();
  377. }
  378. $info = entity_get_info($entity_type);
  379. // Find out what entity keys to use.
  380. if (!$revision) {
  381. $table = $info['base table'];
  382. $id_key = $info['entity keys']['id'];
  383. $uuid_key = $info['entity keys']['uuid'];
  384. }
  385. elseif (isset($info['revision table'])) {
  386. $table = $info['revision table'];
  387. $id_key = $info['entity keys']['revision'];
  388. $uuid_key = $info['entity keys']['revision uuid'];
  389. }
  390. // If we want revision IDs, but the entity doesn't support it. Return empty.
  391. else {
  392. return array();
  393. }
  394. // Get all UUIDs in one query.
  395. return db_select($table, 't')
  396. ->fields('t', array($uuid_key, $id_key))
  397. ->condition($uuid_key, array_values($uuids), 'IN')
  398. ->execute()
  399. ->fetchAllKeyed();
  400. }
  401. /**
  402. * Helper function that retrieves UUIDs by their entity IDs.
  403. *
  404. * @todo
  405. * Statically cache as many IDs as possible and limit the query.
  406. *
  407. * @param $entity_type
  408. * The entity type we should be dealing with.
  409. * @param $ids
  410. * An array of entity IDs for which we should find their UUIDs. If $revision
  411. * is TRUE this should be revision IDs instead.
  412. * @param $revision
  413. * If TRUE the revision UUIDs is returned instead.
  414. * @return
  415. * Array of entity UUIDs keyed by their IDs. If $revision is TRUE revision
  416. * IDs and UUIDs are returned instead.
  417. */
  418. function entity_get_uuid_by_id($entity_type, $ids, $revision = FALSE) {
  419. if (empty($ids)) {
  420. return array();
  421. }
  422. $info = entity_get_info($entity_type);
  423. // Find out what entity keys to use.
  424. if (!$revision) {
  425. $table = $info['base table'];
  426. $id_key = $info['entity keys']['id'];
  427. $uuid_key = $info['entity keys']['uuid'];
  428. }
  429. elseif (isset($info['revision table'])) {
  430. $table = $info['revision table'];
  431. $id_key = $info['entity keys']['revision'];
  432. $uuid_key = $info['entity keys']['revision uuid'];
  433. }
  434. // If we want revision UUIDs, but the entity doesn't support it. Return empty.
  435. else {
  436. return array();
  437. }
  438. // Get all UUIDs in one query.
  439. return db_select($table, 't')
  440. ->fields('t', array($id_key, $uuid_key))
  441. ->condition($id_key, array_values($ids), 'IN')
  442. ->execute()
  443. ->fetchAllKeyed();
  444. }
  445. /**
  446. * Helper function to change entity properties from ID to UUID.
  447. *
  448. * We never change user UID 0 or 1 to UUIDs. Those are low level user accounts
  449. * ("anonymous" and "root") that needs to be identified consistently across
  450. * any system.
  451. *
  452. * @todo
  453. * Add tests for this function.
  454. *
  455. * @param $objects
  456. * An array of objects that should get $properties changed. Can be either an
  457. * entity object or a field items array.
  458. * @param $entity_type
  459. * The type of entity that all $properties refers to.
  460. * @param $properties
  461. * An array of properties that should be changed. All properties must refer to
  462. * the same type of entity (the one referenced in $entity_type).
  463. */
  464. function entity_property_id_to_uuid(&$objects, $entity_type, $properties) {
  465. if (!is_array($objects)) {
  466. $things = array(&$objects);
  467. }
  468. else {
  469. $things = &$objects;
  470. }
  471. if (!is_array($properties)) {
  472. $properties = array($properties);
  473. }
  474. $ids = array();
  475. $values = array();
  476. $i = 0;
  477. foreach ($things as &$object) {
  478. foreach ($properties as $property) {
  479. // This is probably an entity object.
  480. if (is_object($object) && isset($object->{$property})) {
  481. $values[$i] = &$object->{$property};
  482. }
  483. // This is probably a field items array.
  484. elseif (is_array($object) && isset($object[$property])) {
  485. $values[$i] = &$object[$property];
  486. }
  487. else {
  488. $i++;
  489. continue;
  490. }
  491. if (!($entity_type == 'user' && ($values[$i] == 0 || $values[$i] == 1))) {
  492. $ids[] = $values[$i];
  493. }
  494. $i++;
  495. }
  496. }
  497. $uuids = entity_get_uuid_by_id($entity_type, $ids);
  498. foreach ($values as $i => $value) {
  499. if (isset($uuids[$value])) {
  500. $values[$i] = $uuids[$value];
  501. }
  502. }
  503. }
  504. /**
  505. * Helper function to change entity properties from UUID to ID.
  506. *
  507. * @todo
  508. * Add tests for this function.
  509. *
  510. * @param $objects
  511. * An array of objects that should get $properties changed. Can be either an
  512. * entity object or a field items array.
  513. * @param $entity_type
  514. * The type of entity that all $properties refers to.
  515. * @param $properties
  516. * An array of properties that should be changed. All properties must refer to
  517. * the same type of entity (the one referenced in $entity_type).
  518. */
  519. function entity_property_uuid_to_id(&$objects, $entity_type, $properties) {
  520. if (!is_array($objects)) {
  521. $things = array(&$objects);
  522. }
  523. else {
  524. $things = &$objects;
  525. }
  526. if (!is_array($properties)) {
  527. $properties = array($properties);
  528. }
  529. $uuids = array();
  530. $values = array();
  531. $i = 0;
  532. foreach ($things as &$object) {
  533. foreach ($properties as $property) {
  534. // This is probably an entity object.
  535. if (is_object($object) && isset($object->{$property})) {
  536. $values[$i] = &$object->{$property};
  537. }
  538. // This is probably a field items array.
  539. elseif (is_array($object) && isset($object[$property])) {
  540. $values[$i] = &$object[$property];
  541. }
  542. else {
  543. $i++;
  544. continue;
  545. }
  546. if (uuid_is_valid($values[$i])) {
  547. $uuids[] = $values[$i];
  548. }
  549. $i++;
  550. }
  551. }
  552. $ids = entity_get_id_by_uuid($entity_type, $uuids);
  553. foreach ($values as $i => $value) {
  554. if (isset($ids[$value])) {
  555. $values[$i] = $ids[$value];
  556. }
  557. }
  558. }
  559. /**
  560. * @} End of "UUID support for Entity API"
  561. */