TripalEntityController.inc 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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. // Make sure the alias doesn't contain spaces.
  109. $alias = preg_replace('/\s+/','-',$alias);
  110. // Or any non alpha numeric characters.
  111. $alias = preg_replace('/[^a-zA-Z0-9\-\/]/','',$alias);
  112. $alias = preg_replace('/_/','-',$alias);
  113. if ($alias) {
  114. // Determine if this alias has already been used.
  115. $num_aliases = db_query('SELECT count(*) as num_alias FROM {url_alias} WHERE alias=:alias',
  116. array(':alias' => $alias))->fetchField();
  117. // Either there isn't an alias yet so we just create one.
  118. // OR an Alias already exists but we would like to add a new one.
  119. if ($num_aliases == 0) {
  120. // First delete any previous alias' for this entity.
  121. path_delete(array('source' => $source_url));
  122. // Then save the new one.
  123. $path = array('source' => $source_url, 'alias' => $alias);
  124. path_save($path);
  125. }
  126. // If there is only one alias matching then it might just be that we already
  127. // assigned this alias to this entity in a previous save.
  128. elseif ($num_aliases == 1) {
  129. $bundle_entity = tripal_bundle_load($entity->bundle);
  130. // Checking to see if the single alias is for the same entity and if not
  131. // warning the admin that the alias is already used (ie: not unique?)
  132. $same_alias = db_query('SELECT count(*) as num_alias FROM {url_alias} WHERE alias=:alias AND source=:source',
  133. array(':alias' => $alias, ':source' => $source_url))->fetchField();
  134. if (!$same_alias) {
  135. $msg = 'The URL alias, %alias, already exists for another page. Please ensure the pattern
  136. supplied on the <a href="!link" target="_blank">%type Edit Page</a> under URL Path options is unique.';
  137. $msg_var = array(
  138. '%alias' => $alias,
  139. '!link' => url("admin/structure/bio-data/manage/$entity->bundle"),
  140. '%type' => $bundle_entity->label
  141. );
  142. tripal_report_error(
  143. 'trpentity',
  144. TRIPAL_WARNING,
  145. $msg,
  146. $msg_var
  147. );
  148. drupal_set_message(t($msg, $msg_var), 'warning');
  149. }
  150. }
  151. // If there are more then one alias' matching what we generated then there's
  152. // a real problem and we need to warn the administrator.
  153. else {
  154. $bundle_entity = tripal_bundle_load($entity->bundle);
  155. $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias',
  156. array(':alias' => $alias))->fetchAll();
  157. $pages = array();
  158. foreach($aliases as $a) {
  159. $pages[] = $a->source;
  160. }
  161. $msg = 'The URL alias, %alias, already exists for multiple pages! Please ensure the pattern
  162. supplied on the <a href="!link" target="_blank">%type Edit Page</a> under URL Path options is unique.';
  163. $msg_var = array(
  164. '%alias' => $alias,
  165. '!link' => url("admin/structure/bio-data/manage/$entity->bundle"),
  166. '%type' => $bundle_entity->label
  167. );
  168. drupal_set_message(t($msg, $msg_var), 'error');
  169. $msg .= ' This url alias has already been used for the following pages: %pages.
  170. You can manually delete alias\' using a combination of path_load() and path_delete().';
  171. $msg_var['%pages'] = implode(', ', $pages);
  172. tripal_report_error(
  173. 'trpentity',
  174. TRIPAL_ERROR,
  175. $msg,
  176. $msg_var
  177. );
  178. }
  179. }
  180. }
  181. /**
  182. * Saves the custom fields using drupal_write_record().
  183. */
  184. public function save($entity) {
  185. global $user;
  186. $pkeys = array();
  187. $transaction = db_transaction();
  188. try {
  189. // If our entity has no id, then we need to give it a
  190. // time of creation.
  191. if (empty($entity->id)) {
  192. $entity->created = time();
  193. $invocation = 'entity_insert';
  194. }
  195. else {
  196. $invocation = 'entity_update';
  197. $pkeys = array('id');
  198. }
  199. // Invoke hook_entity_presave().
  200. module_invoke_all('entity_presave', $entity, $entity->type);
  201. // Write out the entity record.
  202. $record = array(
  203. 'term_id' => $entity->term_id,
  204. 'type' => $entity->type,
  205. 'bundle' => $entity->bundle,
  206. 'title' => $entity->title,
  207. 'uid' => $user->uid,
  208. 'created' => $entity->created,
  209. 'changed' => time(),
  210. );
  211. if ($invocation == 'entity_update') {
  212. $record['id'] = $entity->id;
  213. }
  214. $success = drupal_write_record('tripal_entity', $record, $pkeys);
  215. if ($success == SAVED_NEW) {
  216. $entity->id = $record['id'];
  217. }
  218. // Now we need to either insert or update the fields which are
  219. // attached to this entity. We use the same primary_keys logic
  220. // to determine whether to update or insert, and which hook we
  221. // need to invoke.
  222. if ($invocation == 'entity_insert') {
  223. field_attach_insert('TripalEntity', $entity);
  224. }
  225. else {
  226. field_attach_update('TripalEntity', $entity);
  227. }
  228. // Set the title for this entity.
  229. $this->setTitle($entity);
  230. // Set the path/url alias for this entity.
  231. $this->setAlias($entity);
  232. // Invoke either hook_entity_update() or hook_entity_insert().
  233. module_invoke_all('entity_postsave', $entity, $entity->type);
  234. module_invoke_all($invocation, $entity, $entity->type);
  235. return $entity;
  236. }
  237. catch (Exception $e) {
  238. $transaction->rollback();
  239. watchdog_exception('tripal_core', $e);
  240. drupal_set_message("Could not save the entity: " . $e->getMessage(), "error");
  241. return FALSE;
  242. }
  243. }
  244. }