tripal_views_query.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 fields compatible with the Tripal storage API, the
  97. // incoming $field_name is a combination of the entity term ID,
  98. // followed by the field name and the the sub element string, with
  99. // sub elements children separated by a comma. For non Tripal
  100. // storage API the $field_name is a combination of the table name
  101. // followed by the table column. We have to handle both because
  102. // a TripalEntity can have both types attached.
  103. $elements = explode('.', $field_name);
  104. $field = NULL;
  105. if (count($elements) > 2) {
  106. $bundle_term = array_shift($elements);
  107. $field_name = array_shift($elements);
  108. // put the sub elements back together into a string with a
  109. // comma delimeter.
  110. $element_name = implode(',', $elements);
  111. }
  112. if (count($elements) == 2) {
  113. $field_name = array_shift($elements);
  114. $element_name = array_shift($elements);
  115. // At this point we're still not 100% sure if we have a
  116. // Tripal Storage API field or not. One quick way to
  117. // tell is to see if we get a field using the $field_name. if so the
  118. // field name comes in as the second element.
  119. $field = field_info_field($element_name);
  120. if ($field) {
  121. $field_name = $element_name;
  122. $element_name = '';
  123. }
  124. }
  125. if ($field) {
  126. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  127. // Construct the field term.
  128. $field_term = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  129. // Let's add add on the $field_term to the element_name and add the
  130. // query condition.
  131. if ($element_name) {
  132. $element_name = $field_term . ',' . $element_name;
  133. }
  134. else {
  135. $element_name = $field_term;
  136. }
  137. $this->query->fieldCondition($field_name, $element_name, $value, $operator);
  138. $this->cquery->fieldCondition($field_name, $element_name, $value, $operator);
  139. }
  140. else {
  141. // If we have a table name then this table is in the Drupal schema and
  142. // we need to add a relationship with the tripal_entity table.
  143. $table = $field_name;
  144. $field = $element_name;
  145. $this->query->relationshipCondition($table, $field, $value, $operator);
  146. $this->cquery->relationshipCondition($table, $field, $value, $operator);
  147. }
  148. }
  149. }
  150. /**
  151. * Add's a where exression clause to a query.
  152. *
  153. * @param $group
  154. * The WHERE group to add these to; groups are used to create AND/OR
  155. * sections. Groups cannot be nested. Use 0 as the default group. If the
  156. * group does not yet exist it will be created as an AND group.
  157. * @param $snippet
  158. * The snippet to check. This can be either a column or a complex
  159. * expression like "UPPER(table.field) = 'value'".
  160. * @param $args
  161. * An associative array of arguments.
  162. */
  163. public function add_where_expression($group, $snippet, $args = array()) {
  164. // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
  165. // the default group.
  166. if (empty($group)) {
  167. $group = 0;
  168. }
  169. // TODO: this function needs to be adjusted to pull out the element from
  170. // snippet (see the code for the add_where function above for an example.
  171. // for now this function will not properly work.
  172. // Check for a group.
  173. if (!isset($this->where[$group])) {
  174. $this->set_where_group('AND', $group);
  175. }
  176. $this->where[$group]['conditions'][] = array(
  177. 'field' => $snippet,
  178. 'value' => $args,
  179. 'operator' => 'formula',
  180. );
  181. }
  182. /**
  183. * Overrides add_orderby().
  184. */
  185. public function add_orderby($table, $field_name = NULL, $order = 'ASC', $alias = '', $params = array()) {
  186. if ($field_name) {
  187. // If we already have an orderBy for this field then remove it so
  188. // we can reset it.
  189. foreach ($this->order as $index => $order_details) {
  190. if ($order_details['field'] == $field_name) {
  191. $this->order[$index]['direction'] = $order;
  192. unset($this->order[$index]);
  193. }
  194. }
  195. $this->order[] = array(
  196. 'field' => $field_name,
  197. 'direction' => strtoupper($order)
  198. );
  199. // If the field_name comes to us with a period in it then it means that
  200. // we need to separate the field name from sub-element names.
  201. $matches = array();
  202. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  203. $field_name = $matches[1];
  204. $element_name = $matches[2];
  205. $field = field_info_field($field_name);
  206. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  207. $element_name = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'] . ',' . $element_name;
  208. $this->query->fieldOrderBy($field_name, $element_name, $order);
  209. }
  210. else {
  211. $instance = field_info_instance('TripalEntity', $field_name, $this->query->entityConditions['bundle']['value']);
  212. $field_term = $instance['settings']['term_vocabulary'] . ':' . $instance['settings']['term_accession'];
  213. $this->query->fieldOrderBy($field_name, $field_term, $order);
  214. }
  215. }
  216. }
  217. /**
  218. * Overrides build().
  219. */
  220. function build(&$view) {
  221. // Make the query distinct if the option was set.
  222. if (!empty($this->options['distinct'])) {
  223. $this->set_distinct(TRUE, !empty($this->options['pure_distinct']));
  224. }
  225. // Store the view in the object to be able to use it later.
  226. $this->view = $view;
  227. $view->init_pager();
  228. // Let the pager modify the query to add limits.
  229. $this->pager->query();
  230. $view->build_info['query'] = $this->query;
  231. $view->build_info['count_query'] = $this->cquery;
  232. }
  233. /**
  234. *
  235. * @param $view
  236. */
  237. function execute(&$view) {
  238. $query = $view->build_info['query'];
  239. $cquery = $view->build_info['count_query'];
  240. if ($query) {
  241. $start = microtime(TRUE);
  242. try {
  243. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  244. // TODO: The code below was taken from the
  245. // views_plugin_pager::execute_count_query($count_query) which would
  246. // be called here, but that function expects the query is a
  247. // database query rather than a TripalEntityField query. We
  248. // really should create a new tripal_views_plugin_pager class
  249. // and call the corresponding function here, but due to time
  250. // constraints this is the shortcut.
  251. $total_items = $this->cquery->execute();
  252. $this->pager->total_items = $total_items;
  253. if (!empty($this->pager->options['offset'])) {
  254. $this->pager->total_items -= $this->pager->options['offset'];
  255. };
  256. $this->pager->update_page_info();
  257. }
  258. // TODO: we need to implement a new views_plugin_pager class to
  259. // override the pre_execute to set the range, instead we'll just do
  260. // it manully here until we have the class.
  261. $this->pager->pre_execute($query);
  262. $num_items_per_page = $this->pager->get_items_per_page();
  263. $offset = $this->pager->get_current_page() * $num_items_per_page;
  264. // I'm not sure why an offset would come back as -1 but it has happened
  265. // with Drupal Views. This is a quick band-aid fix.
  266. $offset = ($offset < 0) ? 0 : $offset;
  267. $query->range($offset, $num_items_per_page);
  268. // Get the IDs
  269. $results = $query->execute();
  270. $entity_ids = (isset($results['TripalEntity']) AND is_array($results['TripalEntity'])) ? array_keys($results['TripalEntity']) : array();
  271. $this->pager->post_execute($view->result);
  272. if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
  273. $view->total_rows = $this->pager->get_total_items();
  274. }
  275. // Get the fields to attach to the entity
  276. $fields = array();
  277. $field_ids = array();
  278. foreach ($this->fields as $details) {
  279. $field_name = $details['field_name'];
  280. // If the field_name comes to us with a period in it then it means that
  281. // we need to separate the field name from sub-element names.
  282. $matches = array();
  283. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  284. $field_name = $matches[1];
  285. $element_name = $matches[2];
  286. }
  287. $field = field_info_field($field_name);
  288. if ($field) {
  289. $fields[$field_name] = $field;
  290. $field_ids[] = $field['id'];
  291. }
  292. }
  293. // Get the entity IDs from the query.
  294. $entities = tripal_load_entity('TripalEntity', $entity_ids, FALSE, $field_ids);
  295. $i = 0;
  296. foreach ($entities as $entity_id => $entity) {
  297. $view->result[$i] = new stdClass();
  298. foreach ($this->fields as $details) {
  299. $field_name = $details['field_name'];
  300. // The entity_id and link fields are not true fields. They are
  301. // added by the tripal_views_data_tripal_entity() function to provide
  302. // useful fields to reference entities. If we see these
  303. // we need to support them here by giving them values.
  304. if ($field_name == 'entity_id') {
  305. $view->result[$i]->$field_name = $entity;
  306. continue;
  307. }
  308. if ($field_name == 'link') {
  309. $view->result[$i]->$field_name = $entity;
  310. continue;
  311. }
  312. if ($field_name == 'edit_link') {
  313. $view->result[$i]->$field_name = $entity;
  314. continue;
  315. }
  316. if ($field_name == 'delete_link') {
  317. $view->result[$i]->$field_name = $entity;
  318. continue;
  319. }
  320. if ($field_name == 'status') {
  321. $view->result[$i]->$field_name = $entity->status;
  322. continue;
  323. }
  324. // If the field_name comes to us with a period in it then it means that
  325. // we need to separate the field name from sub-element names.
  326. $matches = array();
  327. if (preg_match('/^(.+?)\.(.*)$/', $field_name, $matches)) {
  328. $field_name = $matches[1];
  329. $element_name = $matches[2];
  330. }
  331. if (array_key_exists($field_name, $fields)) {
  332. $items = field_get_items('TripalEntity', $entity, $field_name);
  333. $view->result[$i]->$field_name = $items;
  334. }
  335. }
  336. // Always add the entity to the results so that handlers
  337. // can take advantage of it.
  338. $view->result[$i]->entity = $entity;
  339. $i++;
  340. }
  341. }
  342. catch (Exception $e) {
  343. $view->result = array();
  344. if (!empty($view->live_preview)) {
  345. drupal_set_message($e->getMessage(), 'error');
  346. }
  347. else {
  348. vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
  349. }
  350. }
  351. }
  352. else {
  353. $start = microtime(TRUE);
  354. }
  355. $view->execute_time = microtime(TRUE) - $start;
  356. }
  357. /**
  358. * Provides a unique placeholders for handlers.
  359. */
  360. public function placeholder() {
  361. // TODO: this function doesn't currently work. It is used by the
  362. // words, all words, shorter than, longer than filters, but those
  363. // are currently commented out.
  364. //return $this->query->placeholder($this->options['table'] . '_' . $this->options['field']);
  365. }
  366. /**
  367. * This function copied from views_plugin_query_default::add_relationship
  368. */
  369. public function add_relationship($alias, $join, $base, $link_point = NULL) {
  370. // Make sure $alias isn't already used; if it, start adding stuff.
  371. $alias_base = $alias;
  372. $count = 1;
  373. while (!empty($this->relationships[$alias])) {
  374. $alias = $alias_base . '_' . $count++;
  375. }
  376. $this->query->addRelationship($join->table, $alias, $join->field);
  377. $this->cquery->addRelationship($join->table, $alias, $join->field);
  378. return $alias;
  379. }
  380. }