TripalEntityController.inc 27 KB

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