tripal_views_query.inc

File

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