TripalEntityController.inc 27 KB

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