TripalEntityController.inc 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  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. // The incoming values should have at a minimum the bundle_id;
  33. $bundle = $values['bundle'];
  34. $matches = array();
  35. if (preg_match('/bio-data_(.*)/', $bundle, $matches)) {
  36. $term_id = $matches[1];
  37. $values['type'] = 'TripalEntity';
  38. $values['term_id'] = $term_id;
  39. }
  40. return parent::create($values);
  41. }
  42. /**
  43. * Delete a single entity.
  44. *
  45. * Really a convenience function for deleteMultiple().
  46. */
  47. public function delete($entity) {
  48. $transaction = db_transaction();
  49. try {
  50. // Invoke hook_entity_delete().
  51. module_invoke_all('entity_delete', $entity, $entity->type);
  52. field_attach_delete('TripalEntity', $entity);
  53. db_delete('tripal_entity')
  54. ->condition('id', $entity->id)
  55. ->execute();
  56. }
  57. catch (Exception $e) {
  58. $transaction->rollback();
  59. watchdog_exception('tripal_entities', $e);
  60. throw $e;
  61. return FALSE;
  62. }
  63. return TRUE;
  64. }
  65. /**
  66. * Sets the title for an entity.
  67. *
  68. * @param $entity
  69. * @param $title
  70. */
  71. public function setTitle($entity, $title = NULL) {
  72. // If no title was supplied then we should try to generate one using the
  73. // default format set by admins.
  74. if (!$title) {
  75. // First get the format for the title based on the bundle of the entity.
  76. $bundle_entity = tripal_bundle_load($entity->bundle);
  77. $title = tripal_get_title_format($bundle_entity);
  78. // Determine which tokens were used in the format string
  79. if (preg_match_all('/\[\w+\]/', $title, $matches)) {
  80. $used_tokens = $matches[0];
  81. foreach($used_tokens as $token) {
  82. $field = str_replace(array('.','[',']'),array('__','',''),$token);
  83. $value = '';
  84. if (isset($entity->{$field})) {
  85. // Render the value from the field.
  86. // @TODO: Handle the case where thefield is empty... currently returns error.
  87. $field_value = field_get_items('TripalEntity', $entity, $field);
  88. $field_render_arr = field_view_value('TripalEntity', $entity, $field, $field_value[0]);
  89. $value = render($field_render_arr);
  90. }
  91. $title = str_replace($token, $value, $title);
  92. }
  93. }
  94. }
  95. // As long as we were able to determine a title, we should update it ;-).
  96. if ($title) {
  97. db_update('tripal_entity')
  98. ->fields(array(
  99. 'title' => $title
  100. ))
  101. ->condition('id', $entity->id)
  102. ->execute();
  103. }
  104. }
  105. /**
  106. * Sets the URL alias for an entity.
  107. */
  108. public function setAlias($entity, $alias = NULL) {
  109. $source_url = "bio-data/$entity->id";
  110. // If no alias was supplied then we should try to generate one using the
  111. // default format set by admins.
  112. if (!$alias) {
  113. // First get the format for the url alias based on the bundle of the entity.
  114. $bundle_entity = tripal_bundle_load($entity->bundle);
  115. $alias = tripal_get_bundle_variable('url_format', $bundle_entity->id);
  116. // Determine which tokens were used in the format string
  117. if (preg_match_all('/\[\w+\]/', $alias, $matches)) {
  118. $used_tokens = $matches[0];
  119. foreach($used_tokens as $token) {
  120. $field = str_replace(array('.','[',']'),array('__','',''),$token);
  121. $value = '';
  122. if (isset($entity->{$field})) {
  123. // Render the value from the field.
  124. // @TODO: Handle the case where thefield is empty... currently returns error.
  125. $field_value = field_get_items('TripalEntity', $entity, $field);
  126. $field_render_arr = field_view_value('TripalEntity', $entity, $field, $field_value[0]);
  127. $value = render($field_render_arr);
  128. }
  129. $alias = str_replace($token, trim($value), $alias);
  130. }
  131. }
  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. $num_aliases = db_query('SELECT count(*) as num_alias FROM {url_alias} WHERE alias=:alias',
  141. array(':alias' => $alias))->fetchField();
  142. // Either there isn't an alias yet so we just create one.
  143. // OR an Alias already exists but we would like to add a new one.
  144. if ($num_aliases == 0) {
  145. // First delete any previous alias' for this entity.
  146. path_delete(array('source' => $source_url));
  147. // Then save the new one.
  148. $path = array('source' => $source_url, 'alias' => $alias);
  149. path_save($path);
  150. }
  151. // If there is only one alias matching then it might just be that we already
  152. // assigned this alias to this entity in a previous save.
  153. elseif ($num_aliases == 1) {
  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' => $entity->bundle
  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. $aliases = db_query('SELECT source FROM {url_alias} WHERE alias=:alias',
  179. array(':alias' => $alias))->fetchAll();
  180. $pages = array();
  181. foreach($aliases as $a) {
  182. $pages[] = $a->source;
  183. }
  184. $msg = 'The URL alias, %alias, already exists for multiple pages! Please ensure the pattern
  185. supplied on the <a href="!link" target="_blank">%type Edit Page</a> under URL Path options is unique.';
  186. $msg_var = array(
  187. '%alias' => $alias,
  188. '!link' => url("admin/structure/bio-data/manage/$entity->bundle"),
  189. '%type' => $entity->bundle
  190. );
  191. drupal_set_message(t($msg, $msg_var), 'error');
  192. $msg .= ' This url alias has already been used for the following pages: %pages.
  193. You can manually delete alias\' using a combination of path_load() and path_delete().';
  194. $msg_var['%pages'] = implode(', ', $pages);
  195. tripal_report_error(
  196. 'trpentity',
  197. TRIPAL_ERROR,
  198. $msg,
  199. $msg_var
  200. );
  201. }
  202. }
  203. }
  204. /**
  205. * Saves the custom fields using drupal_write_record().
  206. */
  207. public function save($entity) {
  208. global $user;
  209. $pkeys = array();
  210. $transaction = db_transaction();
  211. try {
  212. // If our entity has no id, then we need to give it a
  213. // time of creation.
  214. if (empty($entity->id)) {
  215. $entity->created = time();
  216. $invocation = 'entity_insert';
  217. }
  218. else {
  219. $invocation = 'entity_update';
  220. $pkeys = array('id');
  221. }
  222. // Invoke hook_entity_presave().
  223. module_invoke_all('entity_presave', $entity, $entity->type);
  224. // Write out the entity record.
  225. $record = array(
  226. 'term_id' => $entity->term_id,
  227. 'type' => $entity->type,
  228. 'bundle' => $entity->bundle,
  229. 'title' => $entity->title,
  230. 'uid' => $user->uid,
  231. 'created' => $entity->created,
  232. 'changed' => time(),
  233. );
  234. if ($invocation == 'entity_update') {
  235. $record['id'] = $entity->id;
  236. }
  237. $success = drupal_write_record('tripal_entity', $record, $pkeys);
  238. if ($success == SAVED_NEW) {
  239. $entity->id = $record['id'];
  240. }
  241. // Now we need to either insert or update the fields which are
  242. // attached to this entity. We use the same primary_keys logic
  243. // to determine whether to update or insert, and which hook we
  244. // need to invoke.
  245. if ($invocation == 'entity_insert') {
  246. field_attach_insert('TripalEntity', $entity);
  247. }
  248. else {
  249. field_attach_update('TripalEntity', $entity);
  250. }
  251. // Set the title for this entity.
  252. $this->setTitle($entity);
  253. // Set the path/url alias for this entity.
  254. $this->setAlias($entity);
  255. // Invoke either hook_entity_update() or hook_entity_insert().
  256. module_invoke_all('entity_postsave', $entity, $entity->type);
  257. module_invoke_all($invocation, $entity, $entity->type);
  258. return $entity;
  259. }
  260. catch (Exception $e) {
  261. $transaction->rollback();
  262. watchdog_exception('tripal_core', $e);
  263. drupal_set_message("Could not save the entity:" . $e->getMessage(), "error");
  264. return FALSE;
  265. }
  266. }
  267. }