TripalEntityController.inc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744
  1. <?php
  2. /**
  3. * TripalEntityController extends DrupalDefaultEntityController.
  4. *
  5. * Our subclass of DrupalDefaultEntityController lets us add a few
  6. * important create, update, and delete methods.
  7. */
  8. class TripalEntityController extends EntityAPIController {
  9. public function __construct($entityType) {
  10. parent::__construct($entityType);
  11. }
  12. /**
  13. * Create a Tripal data entity
  14. *
  15. * We first set up the values that are specific
  16. * to our data schema but then also go through the EntityAPIController
  17. * function.
  18. *
  19. * @param $type
  20. * The machine-readable type of the entity.
  21. *
  22. * @return
  23. * An object with all default fields initialized.
  24. */
  25. public function create(array $values = []) {
  26. // Add some items to the values array passed to the constructor
  27. global $user;
  28. $values['uid'] = $user->uid;
  29. $values['created'] = time();
  30. $values['changed'] = time();
  31. $values['title'] = '';
  32. $values['type'] = 'TripalEntity';
  33. $values['nid'] = '';
  34. $values['status'] = 1;
  35. // Call the parent constructor.
  36. $entity = parent::create($values);
  37. // Allow modules to make additions to the entity when it's created.
  38. $modules = module_implements('entity_create');
  39. foreach ($modules as $module) {
  40. $function = $module . '_entity_create';
  41. if (isset($values['bundle_object'])) {
  42. $function($entity, $values['type'], $values['bundle_object']);
  43. }
  44. else {
  45. $function($entity, $values['type']);
  46. }
  47. }
  48. return $entity;
  49. }
  50. /**
  51. * Overrides EntityAPIController::delete().
  52. *
  53. * @param array $ids
  54. * An array of the ids denoting which entities to delete.
  55. * @param DatabaseTransaction $transaction
  56. * Optionally a DatabaseTransaction object to use. Allows overrides to
  57. * pass in their transaction object.
  58. */
  59. public function delete($ids, $transaction = NULL) {
  60. if (!$transaction) {
  61. $transaction = db_transaction();
  62. }
  63. try {
  64. // First load the entity.
  65. $entities = entity_load('TripalEntity', $ids);
  66. // Then properly delete each one.
  67. foreach ($entities as $entity) {
  68. // Invoke hook_entity_delete().
  69. module_invoke_all('entity_delete', $entity, $entity->type);
  70. // Delete any field data for this entity.
  71. field_attach_delete('TripalEntity', $entity);
  72. // Delete the entity record from our base table.
  73. db_delete('tripal_entity')
  74. ->condition('id', $entity->id)
  75. ->execute();
  76. }
  77. } catch (Exception $e) {
  78. if ($transaction) {
  79. $transaction->rollback();
  80. }
  81. watchdog_exception('tripal', $e);
  82. throw $e;
  83. return FALSE;
  84. }
  85. return TRUE;
  86. }
  87. /**
  88. * Sets the title for an entity.
  89. *
  90. * @param $entity
  91. * The entity whose title should be changed.
  92. * @param $title
  93. * The title to use. It can contain tokens the correspond to field values.
  94. * Token should be be compatible with those returned by
  95. * tripal_get_entity_tokens().
  96. * @param $cache
  97. * This array is used to store objects you want to cache for performance
  98. * reasons, as well as, cache related options. The following are supported:
  99. * - TripalBundle $bundle
  100. * The bundle for the current entity.
  101. */
  102. public function setTitle($entity, $title = NULL, $cache = []) {
  103. if (isset($cache['bundle'])) {
  104. $bundle = $cache['bundle'];
  105. }
  106. else {
  107. $bundle = tripal_load_bundle_entity(['name' => $entity->bundle]);
  108. }
  109. // If no title was supplied then we should try to generate one using the
  110. // default format set by admins.
  111. if (!$title) {
  112. $title = tripal_get_title_format($bundle);
  113. }
  114. $title = tripal_replace_entity_tokens($title, $entity, $bundle);
  115. if ($title) {
  116. db_update('tripal_entity')
  117. ->fields([
  118. 'title' => $title,
  119. ])
  120. ->condition('id', $entity->id)
  121. ->execute();
  122. }
  123. }
  124. /**
  125. * Sets the URL alias for an entity.
  126. *
  127. * @param $entity
  128. * The entity whose URL alias should be changed.
  129. * @param $alias
  130. * The alias to use. It can contain tokens the correspond to field values.
  131. * Token should be be compatible with those returned by
  132. * tripal_get_entity_tokens().
  133. * @param $cache
  134. * This array is used to store objects you want to cache for performance
  135. * reasons, as well as, cache related options. The following are supported:
  136. * - TripalBundle $bundle
  137. * The bundle for the current entity.
  138. * - TripalTerm $term
  139. * The term for the current entity.
  140. */
  141. public function setAlias($entity, $alias = NULL, $cache = []) {
  142. $source_url = "bio_data/$entity->id";
  143. // If no alias was supplied then we should try to generate one using the
  144. // default format set by admins.
  145. if (!$alias) {
  146. // Load the TripalBundle entity for this TripalEntity (if it's not cached).
  147. // First get the format for the url alias based on the bundle of the entity.
  148. // Then replace all the tokens with values from the entity fields.
  149. if (isset($cache['bundle'])) {
  150. $bundle_entity = $cache['bundle'];
  151. }
  152. else {
  153. $bundle_entity = tripal_load_bundle_entity(['name' => $entity->bundle]);
  154. }
  155. $alias = tripal_get_bundle_variable('url_format', $bundle_entity->id);
  156. $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  157. }
  158. // If there is still no alias supplied then we should generate one using
  159. // the term name and entity id.
  160. if (!$alias) {
  161. // Load the term for this TripalEntity. Set a default based on the term
  162. // name and entity id. Then replace all the tokens with values from
  163. // the entity fields.
  164. $term = (isset($cache['term'])) ? $cache['term'] : entity_load('TripalTerm', ['id' => $entity->term_id]);
  165. $term = reset($term);
  166. $alias = str_replace(' ', '', $term->name) . '/[TripalEntity__entity_id]';
  167. $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  168. }
  169. // Check if the passed alias has tokens. Load the TripalBundle entity for
  170. // this TripalEntity. Then replace all the tokens with values from the
  171. // entity fields.
  172. if ($alias && (preg_match_all("/\[[^\]]*\]/", $alias, $bundle_tokens))) {
  173. if (isset($cache['bundle'])) {
  174. $bundle_entity = $cache['bundle'];
  175. }
  176. else {
  177. $bundle_entity = tripal_load_bundle_entity(['name' => $entity->bundle]);
  178. }
  179. $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  180. }
  181. // Make sure the alias doesn't contain spaces.
  182. //$alias = preg_replace('/\s+/','-',$alias);
  183. // Or any non alpha numeric characters.
  184. //$alias = preg_replace('/[^a-zA-Z0-9\-\/]/','',$alias);
  185. //$alias = preg_replace('/_/','-',$alias);
  186. if ($alias) {
  187. // Determine if this alias has already been used.
  188. $sql = '
  189. SELECT count(*) as num_alias
  190. FROM {url_alias}
  191. WHERE alias=:alias
  192. ';
  193. $num_aliases = db_query($sql, [':alias' => $alias])->fetchField();
  194. // Either there isn't an alias yet so we just create one.
  195. // OR an Alias already exists but we would like to add a new one.
  196. if ($num_aliases == 0) {
  197. // First delete any previous alias' for this entity.
  198. // Then save the new one.
  199. // @performance: Look into this further.
  200. // @spficklin publishing an entity can be very slow if there are lots of
  201. // entries in the url_alias table, due to this type of
  202. // SQL statement that gets called in drupal_path_alias_whitelist_rebuild():
  203. // SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM url_alias.
  204. // Perhaps we should write our own SQL to avoid this issue.
  205. // @lacey: drupal_path_alias_whitelist_rebuild() isn't getting called for me during publish.
  206. $values = [
  207. 'source' => $source_url,
  208. 'alias' => $alias,
  209. 'language' => 'und',
  210. ];
  211. // Now check if an entry with the source url for this entity already
  212. // exists. This is an issue when updating existing url aliases. To avoid
  213. // creating 404s existing aliases need to be updated and a redirect
  214. // created to handle the old alias.
  215. $existing_aliases = db_select('url_alias', 'ua')
  216. ->fields('ua')
  217. ->condition('source', $source_url, '=')
  218. ->execute()->fetchAll();
  219. $num_aliases = count($existing_aliases);
  220. if ($num_aliases) {
  221. // For each existing entry create a redirect.
  222. foreach ($existing_aliases as $ea) {
  223. $path = [
  224. 'source' => $ea->source,
  225. 'alias' => $alias,
  226. 'pid' => $ea->pid,
  227. 'original' => [
  228. 'alias' => $ea->alias,
  229. 'pid' => $ea->pid,
  230. 'language' => $ea->language,
  231. ],
  232. ];
  233. module_load_include('module', 'redirect', 'redirect');
  234. redirect_path_update($path);
  235. //After redirects created now update the url_aliases table.
  236. db_update('url_alias')
  237. ->fields([
  238. 'alias' => $alias,
  239. ])
  240. ->condition('source', $source_url, '=')
  241. ->condition('pid', $ea->pid, '=')
  242. ->execute();
  243. }
  244. }
  245. else {
  246. drupal_write_record('url_alias', $values);
  247. }
  248. }
  249. // If there is only one alias matching then it might just be that we
  250. // already assigned this alias to this entity in a previous save.
  251. elseif ($num_aliases == 1) {
  252. if (isset($cache['bundle'])) {
  253. $bundle_entity = $cache['bundle'];
  254. }
  255. else {
  256. $bundle_entity = tripal_load_bundle_entity(['name' => $entity->bundle]);
  257. }
  258. // Check to see if the single alias is for the same entity and if not
  259. // warn the admin that the alias is already used (ie: not unique?)
  260. $sql = "
  261. SELECT count(*) as num_alias
  262. FROM {url_alias}
  263. WHERE alias=:alias AND source=:source
  264. ";
  265. $replace = [':alias' => $alias, ':source' => $source_url];
  266. $same_alias = db_query($sql, $replace)->fetchField();
  267. if (!$same_alias) {
  268. $msg = 'The URL alias, %alias, already exists for another page. ' .
  269. 'Please ensure the pattern supplied on the <a href="!link" ' .
  270. 'target="_blank">%type Edit Page</a> under URL Path options is ' .
  271. 'unique.';
  272. $msg_var = [
  273. '%alias' => $alias,
  274. '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
  275. '%type' => $bundle_entity->label,
  276. ];
  277. tripal_report_error('trpentity', TRIPAL_WARNING, $msg, $msg_var);
  278. drupal_set_message(t($msg, $msg_var), 'warning');
  279. }
  280. }
  281. // If there are more then one alias' matching what we generated then there's
  282. // a real problem and we need to warn the administrator.
  283. else {
  284. if (isset($cache['bundle'])) {
  285. $bundle_entity = $cache['bundle'];
  286. }
  287. else {
  288. $bundle_entity = tripal_load_bundle_entity(['name' => $entity->bundle]);
  289. }
  290. $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias',
  291. [':alias' => $alias])->fetchAll();
  292. $pages = [];
  293. foreach ($aliases as $a) {
  294. $pages[] = $a->source;
  295. }
  296. $msg = 'The URL alias, %alias, already exists for multiple pages! ' .
  297. 'Please ensure the pattern supplied on the <a href="!link" ' .
  298. 'target="_blank">%type Edit Page</a> under URL Path options is ' .
  299. 'unique.';
  300. $msg_var = [
  301. '%alias' => $alias,
  302. '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
  303. '%type' => $bundle_entity->label,
  304. ];
  305. drupal_set_message(t($msg, $msg_var), 'error');
  306. $msg .= ' This url alias has already been used for the following pages: %pages.
  307. You can manually delete alias\' using a combination of path_load() and path_delete().';
  308. $msg_var['%pages'] = implode(', ', $pages);
  309. tripal_report_error('trpentity', TRIPAL_ERROR, $msg, $msg_var);
  310. }
  311. }
  312. }
  313. /**
  314. * Saves a new entity.
  315. *
  316. * @param $entity
  317. * A TripalEntity object to save.
  318. * @param $cache
  319. * This array is used to store objects you want to cache for performance
  320. * reasons, as well as, cache related options. The following are supported:
  321. * - boolean $clear_cached_fields
  322. * Clearing cached fields is NECESSARY. IF you choose to set this to
  323. * false then YOU must clear the cache yourself using
  324. * cache_clear_all('field:TripalEntity:[entity_id]', 'cache_field', TRUE).
  325. * The only known reason to set this to FALSE is to clear the cache in bulk
  326. * for perfomance reasons.
  327. * - TripalBundle $bundle
  328. * The bundle for the current entity.
  329. * - TripalTerm $term
  330. * The term for the current entity.
  331. *
  332. * @return
  333. * The saved entity object with updated properties.
  334. */
  335. public function save($entity, $cache = []) {
  336. global $user;
  337. $pkeys = [];
  338. if (!isset($cache['clear_cached_fields'])) {
  339. $cache['clear_cached_fields'] = TRUE;
  340. }
  341. $changed_date = time();
  342. $create_date = $changed_date;
  343. if (property_exists($entity, 'created')) {
  344. if (!is_numeric($entity->created)) {
  345. $temp = new DateTime($entity->created);
  346. $create_date = $temp->getTimestamp();
  347. }
  348. }
  349. $status = 1;
  350. if (property_exists($entity, 'status')) {
  351. if ($entity->status === 0 or $entity->status === 1) {
  352. $status = $entity->status;
  353. }
  354. }
  355. $transaction = db_transaction();
  356. try {
  357. // If our entity has no id, then we need to give it a
  358. // time of creation.
  359. if (empty($entity->id)) {
  360. $entity->created = $create_date;
  361. $invocation = 'entity_insert';
  362. }
  363. else {
  364. $invocation = 'entity_update';
  365. $pkeys = ['id'];
  366. }
  367. if (property_exists($entity, 'publish') and $entity->publish == TRUE) {
  368. $invocation = 'entity_publish';
  369. }
  370. // Invoke hook_entity_presave().
  371. module_invoke_all('entity_presave', $entity, $entity->type);
  372. // Write out the entity record.
  373. $record = [
  374. 'term_id' => $entity->term_id,
  375. 'type' => $entity->type,
  376. 'bundle' => $entity->bundle,
  377. 'title' => $entity->title,
  378. 'uid' => $entity->uid,
  379. 'created' => $create_date,
  380. 'changed' => $changed_date,
  381. 'status' => $status,
  382. ];
  383. if (property_exists($entity, 'nid') and $entity->nid) {
  384. $record['nid'] = $entity->nid;
  385. }
  386. if ($invocation == 'entity_update') {
  387. $record['id'] = $entity->id;
  388. }
  389. $success = drupal_write_record('tripal_entity', $record, $pkeys);
  390. if ($success == SAVED_NEW) {
  391. $entity->id = $record['id'];
  392. }
  393. // Now we need to either insert or update the fields which are
  394. // attached to this entity. We use the same primary_keys logic
  395. // to determine whether to update or insert, and which hook we
  396. // need to invoke. We do not attach fields when publishing an entity.
  397. // This is because a field may have default values and if so, those fields
  398. // will be attached and the storage backend may then try to insert
  399. // fields which should not be inserted because they already exist.
  400. if ($invocation == 'entity_insert') {
  401. field_attach_insert('TripalEntity', $entity);
  402. }
  403. if ($invocation == 'entity_update') {
  404. field_attach_update('TripalEntity', $entity);
  405. }
  406. // Set the title for this entity.
  407. $this->setTitle($entity, NULL, $cache);
  408. // Set the path/url alias for this entity.
  409. $this->setAlias($entity, NULL, $cache);
  410. // Invoke either hook_entity_update() or hook_entity_insert().
  411. module_invoke_all('entity_postsave', $entity, $entity->type);
  412. module_invoke_all($invocation, $entity, $entity->type);
  413. // Clear any cache entries for this entity so it can be reloaded using
  414. // the values that were just saved.
  415. // Also, we don't need to clear cached fields when publishing because we
  416. // didn't attach any (see above).
  417. if ($cache['clear_cached_fields'] AND ($invocation != 'entity_publish')) {
  418. $cid = 'field:TripalEntity:' . $entity->id;
  419. cache_clear_all($cid, 'cache_field', TRUE);
  420. }
  421. return $entity;
  422. } catch (Exception $e) {
  423. $transaction->rollback();
  424. watchdog_exception('tripal', $e);
  425. drupal_set_message("Could not save the TripalEntity: " . $e->getMessage(), "error");
  426. return FALSE;
  427. }
  428. }
  429. /**
  430. * Override the load function.
  431. *
  432. * A TripalEntity may have a large number of fields attached which may
  433. * slow down the loading of pages and web services. Therefore, we only
  434. * want to attach fields that are needed.
  435. *
  436. * @param $ids
  437. * The list of entity IDs to load.
  438. * @param $conditions
  439. * The list of key/value filters for querying the entity.
  440. * @param $field_ids
  441. * The list of numeric field IDs for fields that should be attached.
  442. * @param $cache
  443. * When loading of entities they can be cached with Drupal for later
  444. * faster loading. However, this can cause memory issues when running
  445. * Tripal jobs that load lots of entities. Caching of entities can
  446. * be disabled to improve memory performance by setting this to FALSE.
  447. */
  448. public function load($ids = [], $conditions = [], $field_ids = [], $cache = TRUE) {
  449. $entities = [];
  450. // Revisions are not statically cached, and require a different query to
  451. // other conditions, so separate the revision id into its own variable.
  452. if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
  453. $revision_id = $conditions[$this->revisionKey];
  454. unset($conditions[$this->revisionKey]);
  455. }
  456. else {
  457. $revision_id = FALSE;
  458. }
  459. // Create a new variable which is either a prepared version of the $ids
  460. // array for later comparison with the entity cache, or FALSE if no $ids
  461. // were passed. The $ids array is reduced as items are loaded from cache,
  462. // and we need to know if it's empty for this reason to avoid querying the
  463. // database when all requested entities are loaded from cache.
  464. $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
  465. // Try to load entities from the static cache.
  466. if ($this->cache && !$revision_id) {
  467. $entities = $this->cacheGet($ids, $conditions);
  468. // If any entities were loaded, remove them from the ids still to load.
  469. if ($passed_ids) {
  470. $ids = array_keys(array_diff_key($passed_ids, $entities));
  471. }
  472. }
  473. // Support the entitycache module if activated.
  474. if (!empty($this->entityInfo['entity cache']) && !$revision_id && $ids && !$conditions) {
  475. $cached_entities = EntityCacheControllerHelper::entityCacheGet($this, $ids, $conditions);
  476. // If any entities were loaded, remove them from the ids still to load.
  477. $ids = array_diff($ids, array_keys($cached_entities));
  478. $entities += $cached_entities;
  479. // Add loaded entities to the static cache if we are not loading a
  480. // revision.
  481. if ($this->cache && !empty($cached_entities) && !$revision_id) {
  482. $this->cacheSet($cached_entities);
  483. }
  484. }
  485. // Load any remaining entities from the database. This is the case if $ids
  486. // is set to FALSE (so we load all entities), if there are any ids left to
  487. // load or if loading a revision.
  488. if (!($this->cacheComplete && $ids === FALSE && !$conditions) && ($ids === FALSE || $ids || $revision_id)) {
  489. $queried_entities = [];
  490. foreach ($this->query($ids, $conditions, $revision_id) as $record) {
  491. // Skip entities already retrieved from cache.
  492. if (isset($entities[$record->{$this->idKey}])) {
  493. continue;
  494. }
  495. // For DB-based entities take care of serialized columns.
  496. if (!empty($this->entityInfo['base table'])) {
  497. $schema = drupal_get_schema($this->entityInfo['base table']);
  498. foreach ($schema['fields'] as $field => $info) {
  499. if (!empty($info['serialize']) && isset($record->$field)) {
  500. $record->$field = unserialize($record->$field);
  501. // Support automatic merging of 'data' fields into the entity.
  502. if (!empty($info['merge']) && is_array($record->$field)) {
  503. foreach ($record->$field as $key => $value) {
  504. $record->$key = $value;
  505. }
  506. unset($record->$field);
  507. }
  508. }
  509. }
  510. }
  511. $queried_entities[$record->{$this->idKey}] = $record;
  512. }
  513. }
  514. // Pass all entities loaded from the database through $this->attachLoad(),
  515. // which attaches fields (if supported by the entity type) and calls the
  516. // entity type specific load callback, for example hook_node_load().
  517. if (!empty($queried_entities)) {
  518. $this->attachLoad($queried_entities, $revision_id, $field_ids);
  519. $entities += $queried_entities;
  520. }
  521. // Entity cache module support: Add entities to the entity cache if we are
  522. // not loading a revision.
  523. if (!empty($this->entityInfo['entity cache']) && !empty($queried_entities) && !$revision_id) {
  524. EntityCacheControllerHelper::entityCacheSet($this, $queried_entities);
  525. }
  526. if ($this->cache and $cache) {
  527. // Add entities to the cache if we are not loading a revision.
  528. if (!empty($queried_entities) && !$revision_id) {
  529. $this->cacheSet($queried_entities);
  530. // Remember if we have cached all entities now.
  531. if (!$conditions && $ids === FALSE) {
  532. $this->cacheComplete = TRUE;
  533. }
  534. }
  535. }
  536. // Ensure that the returned array is ordered the same as the original
  537. // $ids array if this was passed in and remove any invalid ids.
  538. if ($passed_ids && $passed_ids = array_intersect_key($passed_ids, $entities)) {
  539. foreach ($passed_ids as $id => $value) {
  540. $passed_ids[$id] = $entities[$id];
  541. }
  542. $entities = $passed_ids;
  543. }
  544. return $entities;
  545. }
  546. /**
  547. * Override the attachLoad function.
  548. *
  549. * A TripalEntity may have a large number of fields attached which may
  550. * slow down the loading of pages and web services. Therefore, we only
  551. * want to attach fields that are needed.
  552. *
  553. * @param $queried_entities
  554. * The list of queried
  555. * @param $revision_id
  556. * ID of the revision that was loaded, or FALSE if the most current
  557. * revision was loaded.
  558. * @param $field_ids
  559. */
  560. protected function attachLoad(&$queried_entities, $revision_id = FALSE,
  561. $field_ids = []) {
  562. // Attach fields.
  563. if ($this->entityInfo['fieldable']) {
  564. if ($revision_id) {
  565. $function = 'field_attach_load_revision';
  566. }
  567. else {
  568. $function = 'field_attach_load';
  569. }
  570. foreach ($queried_entities as $id => $entity) {
  571. $info = entity_get_info($queried_entities[$id]->type);
  572. $field_cache = array_key_exists('field cache', $info) ? $info['field cache'] : FALSE;
  573. $bundle_name = $queried_entities[$id]->bundle;
  574. $bundle = tripal_load_bundle_entity(['name' => $bundle_name]);
  575. // Iterate through the field instances and find those that are set to
  576. // 'auto_attach' and which are attached to this bundle. Add all
  577. // fields that don't need auto attach to the field_ids array.
  578. $instances = field_info_instances('TripalEntity', $bundle_name);
  579. foreach ($instances as $instance) {
  580. $field_name = $instance['field_name'];
  581. $field = field_info_field($field_name);
  582. $field_id = $field['id'];
  583. // Add this field to the entity with default value.
  584. if (!isset($queried_entities[$id]->{$field_name})) {
  585. $queried_entities[$id]->{$field_name} = [];
  586. }
  587. // Options used for the field_attach_load function.
  588. $options = [];
  589. $options['field_id'] = $field['id'];
  590. // The cache ID for the entity. We must manually set the cache
  591. // because the field_attach_load won't do it for us.
  592. $cfid = "field:TripalEntity:$id:$field_name";
  593. // Check if the field is cached. if so, then don't reload.
  594. if ($field_cache) {
  595. $cache_data = cache_get($cfid, 'cache_field');
  596. if (!empty($cache_data)) {
  597. $queried_entities[$id]->{$field_name} = $cache_data->data;
  598. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  599. continue;
  600. }
  601. }
  602. // If a list of field_ids is provided then we specifically want
  603. // to only load the fields specified.
  604. if (count($field_ids) > 0) {
  605. if (in_array($field_id, $field_ids)) {
  606. $function($this->entityType, [$id => $queried_entities[$id]],
  607. FIELD_LOAD_CURRENT, $options);
  608. // Cache the field.
  609. if ($field_cache) {
  610. cache_set($cfid, $queried_entities[$id]->{$field_name}, 'cache_field');
  611. }
  612. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  613. }
  614. }
  615. // If we don't have a list of fields then load them all, but only
  616. // if the instance is a TripalField and it is set to not auto
  617. // attach then we will ignore it. It can only be set by providing
  618. // the id in the $field_id array handled previously.
  619. else {
  620. // Does the field instance have an 'auto_attach' setting?
  621. $auto_attach = FALSE;
  622. if (array_key_exists('settings', $instance) and
  623. array_key_exists('auto_attach', $instance['settings']) and
  624. $instance['settings']['auto_attach'] == TRUE) {
  625. $auto_attach = TRUE;
  626. }
  627. // Do not load fields that are not auto attached. Instead set
  628. // their value to an empty string and set the #processed key to
  629. // FALSE.
  630. if (!$auto_attach) {
  631. // Add an empty value. This will allow the tripal_entity_view()
  632. // hook to add the necessary prefixes to the field for ajax
  633. // loading.
  634. $queried_entities[$id]->{$field_name}['und'][0]['value'] = '';
  635. $queried_entities[$id]->{$field_name}['#processed'] = FALSE;
  636. }
  637. else {
  638. $function($this->entityType, [$id => $queried_entities[$id]],
  639. FIELD_LOAD_CURRENT, $options);
  640. // Cache the field.
  641. if ($field_cache) {
  642. if (property_exists($queried_entities[$id], $field_name)) {
  643. cache_set($cfid, $queried_entities[$id]->{$field_name}, 'cache_field');
  644. }
  645. }
  646. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  647. }
  648. }
  649. }
  650. }
  651. }
  652. // Call hook_entity_load().
  653. foreach (module_implements('entity_load') as $module) {
  654. $function = $module . '_entity_load';
  655. $function($queried_entities, $this->entityType);
  656. }
  657. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  658. // always the queried entities, followed by additional arguments set in
  659. // $this->hookLoadArguments.
  660. $args = array_merge([$queried_entities], $this->hookLoadArguments);
  661. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  662. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  663. }
  664. }
  665. }