TripalEntityController.inc 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. // Call the parent constructor.
  34. $entity = parent::create($values);
  35. // Allow modules to make additions to the entity when it's created.
  36. $modules = module_implements('entity_create');
  37. foreach ($modules as $module) {
  38. $function = $module . '_entity_create';
  39. $function($entity, $values['type']);
  40. }
  41. return $entity;
  42. }
  43. /**
  44. * Delete a single entity.
  45. *
  46. * Really a convenience function for deleteMultiple().
  47. */
  48. public function delete($entity) {
  49. $transaction = db_transaction();
  50. try {
  51. // Invoke hook_entity_delete().
  52. module_invoke_all('entity_delete', $entity, $entity->type);
  53. field_attach_delete('TripalEntity', $entity);
  54. db_delete('tripal_entity')
  55. ->condition('id', $entity->id)
  56. ->execute();
  57. }
  58. catch (Exception $e) {
  59. $transaction->rollback();
  60. watchdog_exception('tripal_entities', $e);
  61. throw $e;
  62. return FALSE;
  63. }
  64. return TRUE;
  65. }
  66. /**
  67. * Sets the title for an entity.
  68. *
  69. * @param $entity
  70. * @param $title
  71. */
  72. public function setTitle($entity, $title = NULL) {
  73. // If no title was supplied then we should try to generate one using the
  74. // default format set by admins.
  75. if (!$title) {
  76. // Load the TripalBundle entity for this TripalEntity.
  77. $bundle_entity = tripal_load_bundle_entity($entity->bundle);
  78. // First get the format for the title based on the bundle of the entity.
  79. $title = tripal_get_title_format($bundle_entity);
  80. // And then replace all the tokens with values from the entity fields.
  81. $title = tripal_replace_tokens($title, $entity, $bundle_entity);
  82. }
  83. // As long as we were able to determine a title, we should update it ;-).
  84. if ($title) {
  85. db_update('tripal_entity')
  86. ->fields(array(
  87. 'title' => $title
  88. ))
  89. ->condition('id', $entity->id)
  90. ->execute();
  91. }
  92. }
  93. /**
  94. * Sets the URL alias for an entity.
  95. */
  96. public function setAlias($entity, $alias = NULL) {
  97. $source_url = "bio-data/$entity->id";
  98. // If no alias was supplied then we should try to generate one using the
  99. // default format set by admins.
  100. if (!$alias) {
  101. // Load the TripalBundle entity for this TripalEntity.
  102. $bundle_entity = tripal_bundle_load($entity->bundle);
  103. // First get the format for the url alias based on the bundle of the entity.
  104. $alias = tripal_get_bundle_variable('url_format', $bundle_entity->id);
  105. // And then replace all the tokens with values from the entity fields.
  106. $alias = tripal_replace_tokens($alias, $entity, $bundle_entity);
  107. }
  108. // If there was no defaults supplied by the admins
  109. // then we should gneerate our own using the term name and entity id.
  110. if (!$alias) {
  111. // Load the term for this TripalEntity.
  112. $term = entity_load('TripalTerm', array('id' => $entity->term_id));
  113. $term = reset($term);
  114. // Set a default based on the term name and entity id.
  115. $alias = str_replace(' ', '', $term->name) . '/[TripalEntity__entity_id]';
  116. // And then replace all the tokens with values from the entity fields.
  117. $alias = tripal_replace_tokens($alias, $entity, $bundle_entity);
  118. }
  119. // Make sure the alias doesn't contain spaces.
  120. $alias = preg_replace('/\s+/','-',$alias);
  121. // Or any non alpha numeric characters.
  122. $alias = preg_replace('/[^a-zA-Z0-9\-\/]/','',$alias);
  123. $alias = preg_replace('/_/','-',$alias);
  124. if ($alias) {
  125. // Determine if this alias has already been used.
  126. $num_aliases = db_query('SELECT count(*) as num_alias FROM {url_alias} WHERE alias=:alias',
  127. array(':alias' => $alias))->fetchField();
  128. // Either there isn't an alias yet so we just create one.
  129. // OR an Alias already exists but we would like to add a new one.
  130. if ($num_aliases == 0) {
  131. // First delete any previous alias' for this entity.
  132. path_delete(array('source' => $source_url));
  133. // Then save the new one.
  134. $path = array('source' => $source_url, 'alias' => $alias);
  135. path_save($path);
  136. }
  137. // If there is only one alias matching then it might just be that we already
  138. // assigned this alias to this entity in a previous save.
  139. elseif ($num_aliases == 1) {
  140. $bundle_entity = tripal_bundle_load($entity->bundle);
  141. // Checking to see if the single alias is for the same entity and if not
  142. // warning the admin that the alias is already used (ie: not unique?)
  143. $same_alias = db_query('SELECT count(*) as num_alias FROM {url_alias} WHERE alias=:alias AND source=:source',
  144. array(':alias' => $alias, ':source' => $source_url))->fetchField();
  145. if (!$same_alias) {
  146. $msg = 'The URL alias, %alias, already exists for another page. Please ensure the pattern
  147. supplied on the <a href="!link" target="_blank">%type Edit Page</a> under URL Path options is unique.';
  148. $msg_var = array(
  149. '%alias' => $alias,
  150. '!link' => url("admin/structure/bio-data/manage/$entity->bundle"),
  151. '%type' => $bundle_entity->label
  152. );
  153. tripal_report_error(
  154. 'trpentity',
  155. TRIPAL_WARNING,
  156. $msg,
  157. $msg_var
  158. );
  159. drupal_set_message(t($msg, $msg_var), 'warning');
  160. }
  161. }
  162. // If there are more then one alias' matching what we generated then there's
  163. // a real problem and we need to warn the administrator.
  164. else {
  165. $bundle_entity = tripal_bundle_load($entity->bundle);
  166. $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias',
  167. array(':alias' => $alias))->fetchAll();
  168. $pages = array();
  169. foreach($aliases as $a) {
  170. $pages[] = $a->source;
  171. }
  172. $msg = 'The URL alias, %alias, already exists for multiple pages! Please ensure the pattern
  173. supplied on the <a href="!link" target="_blank">%type Edit Page</a> under URL Path options is unique.';
  174. $msg_var = array(
  175. '%alias' => $alias,
  176. '!link' => url("admin/structure/bio-data/manage/$entity->bundle"),
  177. '%type' => $bundle_entity->label
  178. );
  179. drupal_set_message(t($msg, $msg_var), 'error');
  180. $msg .= ' This url alias has already been used for the following pages: %pages.
  181. You can manually delete alias\' using a combination of path_load() and path_delete().';
  182. $msg_var['%pages'] = implode(', ', $pages);
  183. tripal_report_error(
  184. 'trpentity',
  185. TRIPAL_ERROR,
  186. $msg,
  187. $msg_var
  188. );
  189. }
  190. }
  191. }
  192. /**
  193. * Saves the custom fields using drupal_write_record().
  194. */
  195. public function save($entity) {
  196. global $user;
  197. $pkeys = array();
  198. $transaction = db_transaction();
  199. try {
  200. // If our entity has no id, then we need to give it a
  201. // time of creation.
  202. if (empty($entity->id)) {
  203. $entity->created = time();
  204. $invocation = 'entity_insert';
  205. }
  206. else {
  207. $invocation = 'entity_update';
  208. $pkeys = array('id');
  209. }
  210. // Invoke hook_entity_presave().
  211. module_invoke_all('entity_presave', $entity, $entity->type);
  212. // Write out the entity record.
  213. $record = array(
  214. 'term_id' => $entity->term_id,
  215. 'type' => $entity->type,
  216. 'bundle' => $entity->bundle,
  217. 'title' => $entity->title,
  218. 'uid' => $user->uid,
  219. 'created' => $entity->created,
  220. 'changed' => time(),
  221. );
  222. if ($invocation == 'entity_update') {
  223. $record['id'] = $entity->id;
  224. }
  225. $success = drupal_write_record('tripal_entity', $record, $pkeys);
  226. if ($success == SAVED_NEW) {
  227. $entity->id = $record['id'];
  228. }
  229. // Now we need to either insert or update the fields which are
  230. // attached to this entity. We use the same primary_keys logic
  231. // to determine whether to update or insert, and which hook we
  232. // need to invoke.
  233. if ($invocation == 'entity_insert') {
  234. field_attach_insert('TripalEntity', $entity);
  235. }
  236. else {
  237. field_attach_update('TripalEntity', $entity);
  238. }
  239. // Set the title for this entity.
  240. $this->setTitle($entity);
  241. // Set the path/url alias for this entity.
  242. $this->setAlias($entity);
  243. // Invoke either hook_entity_update() or hook_entity_insert().
  244. module_invoke_all('entity_postsave', $entity, $entity->type);
  245. module_invoke_all($invocation, $entity, $entity->type);
  246. return $entity;
  247. }
  248. catch (Exception $e) {
  249. $transaction->rollback();
  250. watchdog_exception('tripal_core', $e);
  251. drupal_set_message("Could not save the entity: " . $e->getMessage(), "error");
  252. return FALSE;
  253. }
  254. }
  255. }