tripal_views_query.inc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. <?php
  2. class tripal_views_query extends views_plugin_query {
  3. /**
  4. * The EntityFieldQuery object used to perform the query
  5. */
  6. var $query;
  7. /**
  8. * The EntityFieldQuery object used to perform the count query.
  9. * It will not include the order by and only fields that are used in
  10. * filters.
  11. */
  12. var $cquery;
  13. /**
  14. * The fields that are to be included in the query.
  15. */
  16. var $fields;
  17. /**
  18. * The filters that are to be included in the query.
  19. */
  20. var $filters;
  21. /**
  22. * The sort item that are to be included in the query.
  23. */
  24. var $order;
  25. /**
  26. * Ensure a table exists in the queue.
  27. *
  28. * This function overrides the views_plugin_query version of the function
  29. * but does nothing other than return the "table" (or bundle) name as
  30. * we won't be using aliases for bundles.
  31. *
  32. * @param $table
  33. * The unaliased name of the table to ensure.
  34. * @param $relationship
  35. * The relationship to ensure the table links to. Each relationship will
  36. * get a unique instance of the table being added. If not specified, will
  37. * be the primary table.
  38. * @param $join
  39. * A views_join object (or derived object) to join the alias in.
  40. *
  41. * @return
  42. * The alias used to refer to this specific table, or NULL if the table
  43. * cannot be ensured.
  44. */
  45. public function ensure_table($table, $relationship = NULL, $join = NULL) {
  46. // Because we are not querying a table, we're querying a TripalFieldQuery
  47. // object we don't need to ensure the table.
  48. return $table;
  49. }
  50. /**
  51. *
  52. */
  53. public function init($base_table = 'tripal_entity', $base_field = 'id', $options) {;
  54. parent::init($base_table, $base_field, $options);
  55. $this->fields = array();
  56. $this->where = array();
  57. $this->order = array();
  58. // Creqte the TripalFieldQuery object.
  59. $this->query = new TripalFieldQuery();
  60. $this->cquery = new TripalFieldQuery();
  61. $this->cquery->count();
  62. // Convert the $base_table into the bundle table. Because every
  63. // tripal site will have different bundle tables we have to do the
  64. // conversion for cross-site compatibility.
  65. list($vocabulary, $accession) = explode('__', $base_table);
  66. $term = tripal_load_term_entity(array('vocabulary' => $vocabulary, 'accession' => $accession));
  67. $bundle = tripal_load_bundle_entity(array('term_id' => $term->id));
  68. // Make sure we only query on the entities for this bundle type.
  69. $this->query->entityCondition('entity_type', 'TripalEntity');
  70. $this->query->entityCondition('bundle', $bundle->name);
  71. $this->cquery->entityCondition('entity_type', 'TripalEntity');
  72. $this->cquery->entityCondition('bundle', $bundle->name);
  73. }
  74. /**
  75. *
  76. */
  77. public function add_field($table_alias, $field_name, $alias = '', $params = array()) {
  78. $this->fields[] = array(
  79. 'table_alias' => $table_alias,
  80. 'field_name' => $field_name,
  81. 'alias' => $alias,
  82. 'params' => $params
  83. );
  84. }
  85. /**
  86. * Add a simple WHERE clause to the query.
  87. *
  88. * @param $group
  89. * The WHERE group to add these to; groups are used to create AND/OR
  90. * sections. Groups cannot be nested. Use 0 as the default group. If the
  91. * group does not yet exist it will be created as an AND group.
  92. * @param $field
  93. * The name of the field to check.
  94. * @param $value
  95. * The value to test the field against. In most cases, this is a scalar.
  96. * For more complex options, it is an array. The meaning of each element
  97. * in the array is dependent on the $operator.
  98. * @param $operator
  99. * The comparison operator, such as =, <, or >=. It also accepts more
  100. * complex options such as IN, LIKE, or BETWEEN. Defaults to IN if $value
  101. * is an array = otherwise. If $field is a string you have to use 'formula'
  102. * here.
  103. */
  104. public function add_where($group, $field_name, $value = NULL, $operator = NULL) {
  105. $this->filters[] = array(
  106. 'group' => $group,
  107. 'field_name' => $field_name,
  108. 'value' => $value,
  109. 'op' => $operator
  110. );
  111. if ($value) {
  112. // Handle the bundle properties separate from real fields.
  113. if ($field_name == 'entity_id' or $field_name == 'status') {
  114. $this->query->propertyCondition($field_name, $value, $operator);
  115. $this->cquery->propertyCondition($field_name, $value, $operator);
  116. return;
  117. }
  118. // If the field_name comes to us with a period in it then it means that
  119. // we need to separate the field name from sub-element names.
  120. $matches = array();
  121. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  122. $field_name = $matches[1];
  123. $element_name = $matches[2];
  124. $field = field_info_field($field_name);
  125. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  126. $field_class = $field['type'];
  127. if (tripal_load_include_field_class($field_class)) {
  128. $field_obj = new $field_class($field, $instance);
  129. $element_name = $field_obj->getFieldTermID() . ',' . $element_name;
  130. // Replace periods with commas.
  131. $element_name = preg_replace('/\./', ',', $element_name);
  132. $this->query->fieldCondition($field_name, $element_name, $value, $operator);
  133. $this->cquery->fieldCondition($field_name, $element_name, $value, $operator);
  134. }
  135. else {
  136. throw new Exception("Unkown element id: '$element_name'.");
  137. }
  138. }
  139. else {
  140. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  141. $field_term = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  142. $this->query->fieldCondition($field_name, $field_term, $value, $operator);
  143. $this->cquery->fieldCondition($field_name, $field_term, $value, $operator);
  144. }
  145. }
  146. }
  147. /**
  148. * Overrides add_orderby().
  149. */
  150. public function add_orderby($table, $field_name = NULL, $order = 'ASC', $alias = '', $params = array()) {
  151. if ($field_name) {
  152. // Make sure we don't put the orderby in more than once.
  153. foreach ($this->order as $index => $order_details) {
  154. if ($order_details['field'] == $field_name) {
  155. return;
  156. }
  157. }
  158. $this->order[] = array(
  159. 'field' => $field_name,
  160. 'direction' => strtoupper($order)
  161. );
  162. // If the field_name comes to us with a period in it then it means that
  163. // we need to separate the field name from sub-element names.
  164. $matches = array();
  165. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  166. $field_name = $matches[1];
  167. $element_name = $matches[2];
  168. $field = field_info_field($field_name);
  169. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  170. $element_name = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'] . ',' . $element_name;
  171. $this->query->fieldOrderBy($field_name, $element_name, $order);
  172. }
  173. else {
  174. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  175. $field_term = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  176. $this->query->fieldOrderBy($field_name, $field_term, $order);
  177. }
  178. }
  179. }
  180. /**
  181. * Overrides build().
  182. */
  183. function build(&$view) {
  184. // Make the query distinct if the option was set.
  185. if (!empty($this->options['distinct'])) {
  186. $this->set_distinct(TRUE, !empty($this->options['pure_distinct']));
  187. }
  188. // Store the view in the object to be able to use it later.
  189. $this->view = $view;
  190. $view->init_pager();
  191. // Let the pager modify the query to add limits.
  192. $this->pager->query();
  193. $view->build_info['query'] = $this->query;
  194. $view->build_info['count_query'] = $this->cquery;
  195. }
  196. /**
  197. *
  198. * @param $view
  199. */
  200. function execute(&$view) {
  201. $query = $view->build_info['query'];
  202. $cquery = $view->build_info['count_query'];
  203. if ($query) {
  204. $start = microtime(TRUE);
  205. try {
  206. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  207. // TODO: The code below was taken from the
  208. // views_plugin_pager::execute_count_query($count_query) which would
  209. // be called here, but that function expects the query is a
  210. // database query rather than a TripalEntityField query. We
  211. // really should create a new tripal_views_plugin_pager class
  212. // and call the corresponding function here, but due to time
  213. // constraints this is the shortcut.
  214. $total_items = $cquery->execute();
  215. $this->pager->total_items = $total_items;
  216. if (!empty($this->pager->options['offset'])) {
  217. $this->pager->total_items -= $this->pager->options['offset'];
  218. };
  219. $this->pager->update_page_info();
  220. }
  221. // TODO: we need to implement a new views_plugin_pager class to
  222. // override the pre_execute to set the range, instead we'll just do
  223. // it manully here until we have the class.
  224. $this->pager->pre_execute($query);
  225. $num_items_per_page = $this->pager->get_items_per_page();
  226. $offset = $this->pager->get_current_page() * $num_items_per_page;
  227. // I'm not sure why an offset would come back as -1 but it has happened
  228. // with Drupal Views. This is a quick band-aid fix.
  229. $offset = ($offset < 0) ? 0 : $offset;
  230. $query->range($offset, $num_items_per_page);
  231. // Get the IDs
  232. $results = $query->execute();
  233. $entity_ids = array_keys($results['TripalEntity']);
  234. $this->pager->post_execute($view->result);
  235. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  236. $view->total_rows = $this->pager->get_total_items();
  237. }
  238. // Get the fields to attach to the entity
  239. $fields = array();
  240. $field_ids = array();
  241. foreach ($this->fields as $details) {
  242. $field_name = $details['field_name'];
  243. // If the field_name comes to us with a period in it then it means that
  244. // we need to separate the field name from sub-element names.
  245. $matches = array();
  246. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  247. $field_name = $matches[1];
  248. $element_name = $matches[2];
  249. }
  250. $field = field_info_field($field_name);
  251. if ($field) {
  252. $fields[$field_name] = $field;
  253. $field_ids[] = $field['id'];
  254. }
  255. }
  256. // Get the entity IDs from the query.
  257. $entities = tripal_load_entity('TripalEntity', $entity_ids, FALSE, $field_ids);
  258. $i = 0;
  259. foreach ($entities as $entity_id => $entity) {
  260. $view->result[$i] = new stdClass();
  261. foreach ($this->fields as $details) {
  262. $field_name = $details['field_name'];
  263. // The entity_id and link fields are not true fields. They are
  264. // added by the tripal_views_data_tripal_entity() function to provide
  265. // useful fields to reference entities. If we see these
  266. // we need to support them here by giving them values.
  267. if ($field_name == 'entity_id') {
  268. $view->result[$i]->$field_name = $entity;
  269. continue;
  270. }
  271. if ($field_name == 'link') {
  272. $view->result[$i]->$field_name = $entity;
  273. continue;
  274. }
  275. if ($field_name == 'edit_link') {
  276. $view->result[$i]->$field_name = $entity;
  277. continue;
  278. }
  279. if ($field_name == 'delete_link') {
  280. $view->result[$i]->$field_name = $entity;
  281. continue;
  282. }
  283. if ($field_name == 'status') {
  284. $view->result[$i]->$field_name = $entity->status;
  285. continue;
  286. }
  287. // If the field_name comes to us with a period in it then it means that
  288. // we need to separate the field name from sub-element names.
  289. $matches = array();
  290. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  291. $field_name = $matches[1];
  292. $element_name = $matches[2];
  293. }
  294. if (array_key_exists($field_name, $fields)) {
  295. $items = field_get_items('TripalEntity', $entity, $field_name);
  296. $view->result[$i]->$field_name = $items;
  297. }
  298. }
  299. // Always add the entity to the results so that handlers
  300. // can take advantage of it.
  301. $view->result[$i]->entity = $entity;
  302. $i++;
  303. }
  304. }
  305. catch (Exception $e) {
  306. $view->result = array();
  307. if (!empty($view->live_preview)) {
  308. drupal_set_message($e->getMessage(), 'error');
  309. }
  310. else {
  311. vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
  312. }
  313. }
  314. }
  315. else {
  316. $start = microtime(TRUE);
  317. }
  318. $view->execute_time = microtime(TRUE) - $start;
  319. }
  320. }