TripalEntityController.inc 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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. // Call the parent constructor.
  35. $entity = parent::create($values);
  36. // Allow modules to make additions to the entity when it's created.
  37. $modules = module_implements('entity_create');
  38. foreach ($modules as $module) {
  39. $function = $module . '_entity_create';
  40. $function($entity, $values['type']);
  41. }
  42. return $entity;
  43. }
  44. /**
  45. * Overrides EntityAPIController::delete().
  46. *
  47. * @param array $ids
  48. * An array of the ids denoting which entities to delete.
  49. * @param DatabaseTransaction $transaction
  50. * Optionally a DatabaseTransaction object to use. Allows overrides to pass in
  51. * their transaction object.
  52. */
  53. public function delete($ids, $transaction = NULL) {
  54. if (!$transaction) {
  55. $transaction = db_transaction();
  56. }
  57. try {
  58. // First load the entity.
  59. $entities = entity_load('TripalEntity', $ids);
  60. // Then properly delete each one.
  61. foreach ($entities as $entity) {
  62. // Invoke hook_entity_delete().
  63. module_invoke_all('entity_delete', $entity, $entity->type);
  64. // Delete any field data for this entity.
  65. field_attach_delete('TripalEntity', $entity);
  66. // Delete the entity record from our base table.
  67. db_delete('tripal_entity')
  68. ->condition('id', $entity->id)
  69. ->execute();
  70. }
  71. }
  72. catch (Exception $e) {
  73. $transaction->rollback();
  74. watchdog_exception('tripal', $e);
  75. throw $e;
  76. return FALSE;
  77. }
  78. return TRUE;
  79. }
  80. /**
  81. * Sets the title for an entity.
  82. *
  83. * @param $entity
  84. * @param $title
  85. */
  86. public function setTitle($entity, $title = NULL) {
  87. // If no title was supplied then we should try to generate one using the
  88. // default format set by admins.
  89. if (!$title) {
  90. // Load the TripalBundle entity for this TripalEntity.
  91. // Get the format for the title based on the bundle of the entity.
  92. // And then replace all the tokens with values from the entity fields.
  93. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  94. $title = tripal_get_title_format($bundle_entity);
  95. $title = tripal_replace_entity_tokens($title, $entity, $bundle_entity);
  96. }
  97. // As long as we were able to determine a title, we should update it ;-).
  98. if ($title) {
  99. db_update('tripal_entity')
  100. ->fields(array(
  101. 'title' => $title
  102. ))
  103. ->condition('id', $entity->id)
  104. ->execute();
  105. }
  106. }
  107. /**
  108. * Sets the URL alias for an entity.
  109. */
  110. public function setAlias($entity, $alias = NULL) {
  111. $source_url = "bio_data/$entity->id";
  112. // If no alias was supplied then we should try to generate one using the
  113. // default format set by admins.
  114. if (!$alias) {
  115. // Load the TripalBundle entity for this TripalEntity.
  116. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  117. // First get the format for the url alias based on the bundle of the entity.
  118. $alias = tripal_get_bundle_variable('url_format', $bundle_entity->id);
  119. // And then replace all the tokens with values from the entity fields.
  120. $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  121. }
  122. // If there was no defaults supplied by the admins
  123. // then we should gneerate our own using the term name and entity id.
  124. if (!$alias) {
  125. // Load the term for this TripalEntity.
  126. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  127. $term = reset($term);
  128. // Set a default based on the term name and entity id.
  129. $alias = str_replace(' ', '', $term->name) . '/[TripalEntity__entity_id]';
  130. // And then replace all the tokens with values from the entity fields.
  131. $alias = tripal_replace_entity_tokens($alias, $entity, $bundle_entity);
  132. }
  133. // Make sure the alias doesn't contain spaces.
  134. $alias = preg_replace('/\s+/','-',$alias);
  135. // Or any non alpha numeric characters.
  136. $alias = preg_replace('/[^a-zA-Z0-9\-\/]/','',$alias);
  137. $alias = preg_replace('/_/','-',$alias);
  138. if ($alias) {
  139. // Determine if this alias has already been used.
  140. $sql ='
  141. SELECT count(*) as num_alias
  142. FROM {url_alias}
  143. WHERE alias=:alias
  144. ';
  145. $num_aliases = db_query($sql, array(':alias' => $alias))->fetchField();
  146. // Either there isn't an alias yet so we just create one.
  147. // OR an Alias already exists but we would like to add a new one.
  148. if ($num_aliases == 0) {
  149. // First delete any previous alias' for this entity.
  150. // Then save the new one.
  151. // TODO: publishing an entity can be very slow if there are lots of
  152. // entries in the url_alias table, due to this type of
  153. // SQL statement that gets called somewhere by Drupal:
  154. // SELECT DISTINCT SUBSTRING_INDEX(source, '/', 1) AS path FROM url_alias.
  155. // Perhaps we should write our own SQL to avoid this issue.
  156. $values = array(
  157. 'source' => $source_url,
  158. 'alias' => $alias,
  159. 'language' => 'und',
  160. );
  161. drupal_write_record('url_alias', $values);
  162. // path_delete(array('source' => $source_url));
  163. // $path = array('source' => $source_url, 'alias' => $alias);
  164. // path_save($path);
  165. }
  166. // If there is only one alias matching then it might just be that we already
  167. // assigned this alias to this entity in a previous save.
  168. elseif ($num_aliases == 1) {
  169. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  170. // Check to see if the single alias is for the same entity and if not
  171. // warn the admin that the alias is already used (ie: not unique?)
  172. $sql = "
  173. SELECT count(*) as num_alias
  174. FROM {url_alias}
  175. WHERE alias=:alias AND source=:source
  176. ";
  177. $replace = array(':alias' => $alias, ':source' => $source_url);
  178. $same_alias = db_query($sql, $replace)->fetchField();
  179. if (!$same_alias) {
  180. $msg = 'The URL alias, %alias, already exists for another page. ' .
  181. 'Please ensure the pattern supplied on the <a href="!link" ' .
  182. 'target="_blank">%type Edit Page</a> under URL Path options is ' .
  183. 'unique.';
  184. $msg_var = array(
  185. '%alias' => $alias,
  186. '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
  187. '%type' => $bundle_entity->label
  188. );
  189. tripal_report_error('trpentity', TRIPAL_WARNING, $msg, $msg_var);
  190. drupal_set_message(t($msg, $msg_var), 'warning');
  191. }
  192. }
  193. // If there are more then one alias' matching what we generated then there's
  194. // a real problem and we need to warn the administrator.
  195. else {
  196. $bundle_entity = tripal_load_bundle_entity(array('name' => $entity->bundle));
  197. $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias',
  198. array(':alias' => $alias))->fetchAll();
  199. $pages = array();
  200. foreach($aliases as $a) {
  201. $pages[] = $a->source;
  202. }
  203. $msg = 'The URL alias, %alias, already exists for multiple pages! '.
  204. 'Please ensure the pattern supplied on the <a href="!link" ' .
  205. 'target="_blank">%type Edit Page</a> under URL Path options is ' .
  206. 'unique.';
  207. $msg_var = array(
  208. '%alias' => $alias,
  209. '!link' => url("admin/structure/bio_data/manage/$entity->bundle"),
  210. '%type' => $bundle_entity->label
  211. );
  212. drupal_set_message(t($msg, $msg_var), 'error');
  213. $msg .= ' This url alias has already been used for the following pages: %pages.
  214. You can manually delete alias\' using a combination of path_load() and path_delete().';
  215. $msg_var['%pages'] = implode(', ', $pages);
  216. tripal_report_error('trpentity', TRIPAL_ERROR, $msg, $msg_var);
  217. }
  218. }
  219. }
  220. /**
  221. * Saves a new entity.
  222. *
  223. * @param $entity
  224. * A TripalEntity object to save.
  225. *
  226. * @return
  227. * The saved entity object with updated properties.
  228. */
  229. public function save($entity) {
  230. global $user;
  231. $pkeys = array();
  232. $transaction = db_transaction();
  233. try {
  234. // If our entity has no id, then we need to give it a
  235. // time of creation.
  236. if (empty($entity->id)) {
  237. $entity->created = time();
  238. $invocation = 'entity_insert';
  239. }
  240. else {
  241. $invocation = 'entity_update';
  242. $pkeys = array('id');
  243. }
  244. // Invoke hook_entity_presave().
  245. module_invoke_all('entity_presave', $entity, $entity->type);
  246. // Write out the entity record.
  247. $record = array(
  248. 'term_id' => $entity->term_id,
  249. 'type' => $entity->type,
  250. 'bundle' => $entity->bundle,
  251. 'title' => $entity->title,
  252. 'uid' => $user->uid,
  253. 'created' => $entity->created,
  254. 'changed' => time(),
  255. );
  256. if (property_exists($entity, 'nid') and $entity->nid) {
  257. $record['nid'] = $entity->nid;
  258. }
  259. if ($invocation == 'entity_update') {
  260. $record['id'] = $entity->id;
  261. }
  262. $success = drupal_write_record('tripal_entity', $record, $pkeys);
  263. if ($success == SAVED_NEW) {
  264. $entity->id = $record['id'];
  265. }
  266. // Now we need to either insert or update the fields which are
  267. // attached to this entity. We use the same primary_keys logic
  268. // to determine whether to update or insert, and which hook we
  269. // need to invoke.
  270. if ($invocation == 'entity_insert') {
  271. field_attach_insert('TripalEntity', $entity);
  272. }
  273. else {
  274. field_attach_update('TripalEntity', $entity);
  275. }
  276. // Set the title for this entity.
  277. $this->setTitle($entity);
  278. // Set the path/url alias for this entity.
  279. $this->setAlias($entity);
  280. // Invoke either hook_entity_update() or hook_entity_insert().
  281. module_invoke_all('entity_postsave', $entity, $entity->type);
  282. module_invoke_all($invocation, $entity, $entity->type);
  283. return $entity;
  284. }
  285. catch (Exception $e) {
  286. $transaction->rollback();
  287. watchdog_exception('tripal', $e);
  288. drupal_set_message("Could not save the entity: " . $e->getMessage(), "error");
  289. return FALSE;
  290. }
  291. }
  292. /**
  293. * Override the load function.
  294. *
  295. * A TripalEntity may have a large number of fields attached which may
  296. * slow down the loading of pages and web services. Therefore, we only
  297. * want to attach fields that are needed.
  298. *
  299. * @param $ids
  300. * The list of entity IDs to load.
  301. * @param $conditions
  302. * The list of key/value filters for querying the entity.
  303. * @param $field_ids
  304. * The list of numeric field IDs for fields that should be attached.
  305. */
  306. public function load($ids = array(), $conditions = array(), $field_ids = array()) {
  307. $entities = array();
  308. // Revisions are not statically cached, and require a different query to
  309. // other conditions, so separate the revision id into its own variable.
  310. if ($this->revisionKey && isset($conditions[$this->revisionKey])) {
  311. $revision_id = $conditions[$this->revisionKey];
  312. unset($conditions[$this->revisionKey]);
  313. }
  314. else {
  315. $revision_id = FALSE;
  316. }
  317. // Create a new variable which is either a prepared version of the $ids
  318. // array for later comparison with the entity cache, or FALSE if no $ids
  319. // were passed. The $ids array is reduced as items are loaded from cache,
  320. // and we need to know if it's empty for this reason to avoid querying the
  321. // database when all requested entities are loaded from cache.
  322. $passed_ids = !empty($ids) ? array_flip($ids) : FALSE;
  323. // Try to load entities from the static cache.
  324. if ($this->cache && !$revision_id) {
  325. $entities = $this->cacheGet($ids, $conditions);
  326. // If any entities were loaded, remove them from the ids still to load.
  327. if ($passed_ids) {
  328. $ids = array_keys(array_diff_key($passed_ids, $entities));
  329. }
  330. }
  331. // Support the entitycache module if activated.
  332. if (!empty($this->entityInfo['entity cache']) && !$revision_id && $ids && !$conditions) {
  333. $cached_entities = EntityCacheControllerHelper::entityCacheGet($this, $ids, $conditions);
  334. // If any entities were loaded, remove them from the ids still to load.
  335. $ids = array_diff($ids, array_keys($cached_entities));
  336. $entities += $cached_entities;
  337. // Add loaded entities to the static cache if we are not loading a
  338. // revision.
  339. if ($this->cache && !empty($cached_entities) && !$revision_id) {
  340. $this->cacheSet($cached_entities);
  341. }
  342. }
  343. // Load any remaining entities from the database. This is the case if $ids
  344. // is set to FALSE (so we load all entities), if there are any ids left to
  345. // load or if loading a revision.
  346. if (!($this->cacheComplete && $ids === FALSE && !$conditions) && ($ids === FALSE || $ids || $revision_id)) {
  347. $queried_entities = array();
  348. foreach ($this->query($ids, $conditions, $revision_id) as $record) {
  349. // Skip entities already retrieved from cache.
  350. if (isset($entities[$record->{$this->idKey}])) {
  351. continue;
  352. }
  353. // For DB-based entities take care of serialized columns.
  354. if (!empty($this->entityInfo['base table'])) {
  355. $schema = drupal_get_schema($this->entityInfo['base table']);
  356. foreach ($schema['fields'] as $field => $info) {
  357. if (!empty($info['serialize']) && isset($record->$field)) {
  358. $record->$field = unserialize($record->$field);
  359. // Support automatic merging of 'data' fields into the entity.
  360. if (!empty($info['merge']) && is_array($record->$field)) {
  361. foreach ($record->$field as $key => $value) {
  362. $record->$key = $value;
  363. }
  364. unset($record->$field);
  365. }
  366. }
  367. }
  368. }
  369. $queried_entities[$record->{$this->idKey}] = $record;
  370. }
  371. }
  372. // Pass all entities loaded from the database through $this->attachLoad(),
  373. // which attaches fields (if supported by the entity type) and calls the
  374. // entity type specific load callback, for example hook_node_load().
  375. if (!empty($queried_entities)) {
  376. $this->attachLoad($queried_entities, $revision_id, $field_ids);
  377. $entities += $queried_entities;
  378. }
  379. // Entity cache module support: Add entities to the entity cache if we are
  380. // not loading a revision.
  381. if (!empty($this->entityInfo['entity cache']) && !empty($queried_entities) && !$revision_id) {
  382. EntityCacheControllerHelper::entityCacheSet($this, $queried_entities);
  383. }
  384. if ($this->cache) {
  385. // Add entities to the cache if we are not loading a revision.
  386. if (!empty($queried_entities) && !$revision_id) {
  387. $this->cacheSet($queried_entities);
  388. // Remember if we have cached all entities now.
  389. if (!$conditions && $ids === FALSE) {
  390. $this->cacheComplete = TRUE;
  391. }
  392. }
  393. }
  394. // Ensure that the returned array is ordered the same as the original
  395. // $ids array if this was passed in and remove any invalid ids.
  396. if ($passed_ids && $passed_ids = array_intersect_key($passed_ids, $entities)) {
  397. foreach ($passed_ids as $id => $value) {
  398. $passed_ids[$id] = $entities[$id];
  399. }
  400. $entities = $passed_ids;
  401. }
  402. return $entities;
  403. }
  404. /**
  405. * Override the attachLoad function.
  406. *
  407. * A TripalEntity may have a large number of fields attached which may
  408. * slow down the loading of pages and web services. Therefore, we only
  409. * want to attach fields that are needed.
  410. *
  411. * @param $queried_entities
  412. * The list of queried
  413. * @param $revision_id
  414. * ID of the revision that was loaded, or FALSE if the most current
  415. * revision was loaded.
  416. * @param $field_ids
  417. */
  418. protected function attachLoad(&$queried_entities, $revision_id = FALSE,
  419. $field_ids = array()) {
  420. // Attach fields.
  421. if ($this->entityInfo['fieldable']) {
  422. if ($revision_id) {
  423. $function = 'field_attach_load_revision';
  424. }
  425. else {
  426. $function = 'field_attach_load';
  427. }
  428. foreach ($queried_entities as $id => $entity) {
  429. $info = entity_get_info($entity->type);
  430. $field_cache = array_key_exists('field cache', $info) ? $info['field cache'] : FALSE;
  431. $bundle_name = $entity->bundle;
  432. // Iterate through the field instances and find those that are set to
  433. // 'auto_attach' and which are attached to this bundle. Add all
  434. // fields that don't need auto attach to the field_ids array.
  435. $instances = field_info_instances('TripalEntity', $bundle_name);
  436. foreach ($instances as $instance) {
  437. $field_name = $instance['field_name'];
  438. $field = field_info_field($field_name);
  439. $field_id = $field['id'];
  440. // Add this field to the entity with default value.
  441. if (!isset($queried_entities[$id]->$field_name)) {
  442. $queried_entities[$id]->$field_name = array();
  443. }
  444. // Options used for the field_attach_load function.
  445. $options = array();
  446. $options['field_id'] = $field['id'];
  447. // The cache ID for the entity. We must manually set the cache
  448. // because the field_attach_load won't do it for us.
  449. $cfid = "field:TripalEntity:$id:$field_name";
  450. // Check if the field is cached. if so, then don't reload.
  451. if ($field_cache) {
  452. $cache_data = cache_get($cfid, 'cache_field');
  453. if (!empty($cache_data)) {
  454. $queried_entities[$id]->$field_name = $cache_data->data;
  455. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  456. continue;
  457. }
  458. }
  459. // If a list of field_ids is provided then we specifically want
  460. // to only load the fields specified.
  461. if (count($field_ids) > 0) {
  462. if (in_array($field_id, $field_ids)) {
  463. $function($this->entityType, array($entity->id => $queried_entities[$id]),
  464. FIELD_LOAD_CURRENT, $options);
  465. // Cache the field.
  466. if ($field_cache) {
  467. cache_set($cfid, $entity->$field_name, 'cache_field');
  468. }
  469. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  470. }
  471. }
  472. // If we don't have a list of fields then load them all, but only
  473. // if the instance is a TripalField and it is set to not auto
  474. // attach then we will ignore it. It can only be set by providing
  475. // the id in the $field_id array handled previously.
  476. else {
  477. // We only load via AJAX if empty fields are not hidden.
  478. $bundle = tripal_load_bundle_entity(array('name' => $bundle_name));
  479. $hide_variable = tripal_get_bundle_variable('hide_empty_field', $bundle->id, 'hide');
  480. if (array_key_exists('settings', $instance) and
  481. array_key_exists('auto_attach', $instance['settings']) and
  482. $instance['settings']['auto_attach'] == FALSE and
  483. $hide_variable == 'show') {
  484. // Add an empty value. This will allow the tripal_entity_view()
  485. // hook to add the necessary prefixes to the field for ajax
  486. // loading.
  487. $queried_entities[$id]->$field_name['und'][0]['value'] = '';
  488. $queried_entities[$id]->{$field_name}['#processed'] = FALSE;
  489. }
  490. else {
  491. $function($this->entityType, array($entity->id => $queried_entities[$id]),
  492. FIELD_LOAD_CURRENT, $options);
  493. // Cache the field.
  494. if ($field_cache) {
  495. cache_set($cfid, $entity->$field_name, 'cache_field');
  496. }
  497. $queried_entities[$id]->{$field_name}['#processed'] = TRUE;
  498. }
  499. }
  500. }
  501. }
  502. }
  503. // Call hook_entity_load().
  504. foreach (module_implements('entity_load') as $module) {
  505. $function = $module . '_entity_load';
  506. $function($queried_entities, $this->entityType);
  507. }
  508. // Call hook_TYPE_load(). The first argument for hook_TYPE_load() are
  509. // always the queried entities, followed by additional arguments set in
  510. // $this->hookLoadArguments.
  511. $args = array_merge(array($queried_entities), $this->hookLoadArguments);
  512. foreach (module_implements($this->entityInfo['load hook']) as $module) {
  513. call_user_func_array($module . '_' . $this->entityInfo['load hook'], $args);
  514. }
  515. }
  516. }