TripalEntityController.inc 10 KB

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