TripalEntityController.inc 10 KB

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