views_handler_relationship_groupwise_max.inc 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. /**
  3. * @file
  4. * Definition of views_handler_relationship_groupwise_max.
  5. */
  6. /**
  7. * Relationship handler that allows a groupwise maximum of the linked in table.
  8. *
  9. * For a definition, see:
  10. * http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
  11. * In lay terms, instead of joining to get all matching records in the linked
  12. * table, we get only one record, a 'representative record' picked according
  13. * to a given criteria.
  14. *
  15. * Example:
  16. * Suppose we have a term view that gives us the terms: Horse, Cat, Aardvark.
  17. * We wish to show for each term the most recent node of that term.
  18. * What we want is some kind of relationship from term to node.
  19. * But a regular relationship will give us all the nodes for each term,
  20. * giving the view multiple rows per term. What we want is just one
  21. * representative node per term, the node that is the 'best' in some way:
  22. * eg, the most recent, the most commented on, the first in alphabetical order.
  23. *
  24. * This handler gives us that kind of relationship from term to node.
  25. * The method of choosing the 'best' implemented with a sort
  26. * that the user selects in the relationship settings.
  27. *
  28. * So if we want our term view to show the most commented node for each term,
  29. * add the relationship and in its options, pick the 'Comment count' sort.
  30. *
  31. * Relationship definition
  32. * - 'outer field': The outer field to substitute into the correlated subquery.
  33. * This must be the full field name, not the alias.
  34. * Eg: 'term_data.tid'.
  35. * - 'argument table',
  36. * 'argument field': These options define a views argument that the subquery
  37. * must add to itself to filter by the main view.
  38. * Example: the main view shows terms, this handler is being used to get to
  39. * the nodes base table. Your argument must be 'term_node', 'tid', as this
  40. * is the argument that should be added to a node view to filter on terms.
  41. *
  42. * A note on performance:
  43. * This relationship uses a correlated subquery, which is expensive.
  44. * Subsequent versions of this handler could also implement the alternative way
  45. * of doing this, with a join -- though this looks like it could be pretty messy
  46. * to implement. This is also an expensive method, so providing both methods and
  47. * allowing the user to choose which one works fastest for their data might be
  48. * the best way.
  49. * If your use of this relationship handler is likely to result in large
  50. * data sets, you might want to consider storing statistics in a separate table,
  51. * in the same way as node_comment_statistics.
  52. *
  53. * @ingroup views_relationship_handlers
  54. */
  55. class views_handler_relationship_groupwise_max extends views_handler_relationship {
  56. /**
  57. * Defines default values for options.
  58. */
  59. public function option_definition() {
  60. $options = parent::option_definition();
  61. $options['subquery_sort'] = array('default' => NULL);
  62. // Descending more useful.
  63. $options['subquery_order'] = array('default' => 'DESC');
  64. $options['subquery_regenerate'] = array('default' => FALSE, 'bool' => TRUE);
  65. $options['subquery_view'] = array('default' => FALSE);
  66. $options['subquery_namespace'] = array('default' => FALSE);
  67. return $options;
  68. }
  69. /**
  70. * Extends the relationship's basic options.
  71. *
  72. * Allows the user to pick a sort and an order for it.
  73. */
  74. public function options_form(&$form, &$form_state) {
  75. parent::options_form($form, $form_state);
  76. // Get the sorts that apply to our base.
  77. $sorts = views_fetch_fields($this->definition['base'], 'sort');
  78. foreach ($sorts as $sort_id => $sort) {
  79. $sort_options[$sort_id] = "$sort[group]: $sort[title]";
  80. }
  81. $base_table_data = views_fetch_data($this->definition['base']);
  82. $form['subquery_sort'] = array(
  83. '#type' => 'select',
  84. '#title' => t('Representative sort criteria'),
  85. // Provide the base field as sane default sort option.
  86. '#default_value' => !empty($this->options['subquery_sort']) ? $this->options['subquery_sort'] : $this->definition['base'] . '.' . $base_table_data['table']['base']['field'],
  87. '#options' => $sort_options,
  88. '#description' => theme('advanced_help_topic', array('module' => 'views', 'topic' => 'relationship-representative')) .
  89. t("The sort criteria is applied to the data brought in by the relationship to determine how a representative item is obtained for each row. For example, to show the most recent node for each user, pick 'Content: Updated date'."),
  90. );
  91. $form['subquery_order'] = array(
  92. '#type' => 'radios',
  93. '#title' => t('Representative sort order'),
  94. '#description' => t("The ordering to use for the sort criteria selected above."),
  95. '#options' => array('ASC' => t('Ascending'), 'DESC' => t('Descending')),
  96. '#default_value' => $this->options['subquery_order'],
  97. );
  98. $form['subquery_namespace'] = array(
  99. '#type' => 'textfield',
  100. '#title' => t('Subquery namespace'),
  101. '#description' => t('Advanced. Enter a namespace for the subquery used by this relationship.'),
  102. '#default_value' => $this->options['subquery_namespace'],
  103. );
  104. // WIP: This stuff doesn't work yet: namespacing issues.
  105. // A list of suitable views to pick one as the subview.
  106. $views = array('' => '<none>');
  107. $all_views = views_get_all_views();
  108. foreach ($all_views as $view) {
  109. // Only get views that are suitable:
  110. // - base must the base that our relationship joins towards
  111. // - must have fields.
  112. if ($view->base_table == $this->definition['base'] && !empty($view->display['default']->display_options['fields'])) {
  113. // @todo check the field is the correct sort?
  114. // or let users hang themselves at this stage and check later?
  115. if ($view->type == 'Default') {
  116. $views[t('Default Views')][$view->name] = $view->name;
  117. }
  118. else {
  119. $views[t('Existing Views')][$view->name] = $view->name;
  120. }
  121. }
  122. }
  123. $form['subquery_view'] = array(
  124. '#type' => 'select',
  125. '#title' => t('Representative view'),
  126. '#default_value' => $this->options['subquery_view'],
  127. '#options' => $views,
  128. '#description' => t('Advanced. Use another view to generate the relationship subquery. This allows you to use filtering and more than one sort. If you pick a view here, the sort options above are ignored. Your view must have the ID of its base as its only field, and should have some kind of sorting.'),
  129. );
  130. $form['subquery_regenerate'] = array(
  131. '#type' => 'checkbox',
  132. '#title' => t('Generate subquery each time view is run.'),
  133. '#default_value' => $this->options['subquery_regenerate'],
  134. '#description' => t('Will re-generate the subquery for this relationship every time the view is run, instead of only when these options are saved. Use for testing if you are making changes elsewhere. WARNING: seriously impairs performance.'),
  135. );
  136. }
  137. /**
  138. * Helper function to create a pseudo view.
  139. *
  140. * We use this to obtain our subquery SQL.
  141. */
  142. public function get_temporary_view() {
  143. views_include('view');
  144. $view = new view();
  145. // @todo What's this?
  146. $view->vid = 'new';
  147. $view->base_table = $this->definition['base'];
  148. $view->add_display('default');
  149. return $view;
  150. }
  151. /**
  152. * When the form is submitted, take sure to clear the subquery string cache.
  153. */
  154. public function options_form_submit(&$form, &$form_state) {
  155. $cid = 'views_relationship_groupwise_max:' . $this->view->name . ':' . $this->view->current_display . ':' . $this->options['id'];
  156. cache_clear_all($cid, 'cache_views_data');
  157. }
  158. /**
  159. * Generate a subquery given the user options, as set in the options.
  160. * These are passed in rather than picked up from the object because we
  161. * generate the subquery when the options are saved, rather than when the view
  162. * is run. This saves considerable time.
  163. *
  164. * @param array $options
  165. * An array of options that contains the following items:
  166. * - subquery_sort: the id of a views sort.
  167. * - subquery_order: either ASC or DESC.
  168. *
  169. * @return string
  170. * The subquery SQL string, ready for use in the main query.
  171. */
  172. public function left_query($options) {
  173. // Either load another view, or create one on the fly.
  174. if ($options['subquery_view']) {
  175. $temp_view = views_get_view($options['subquery_view']);
  176. // Remove all fields from default display.
  177. unset($temp_view->display['default']->display_options['fields']);
  178. }
  179. else {
  180. // Create a new view object on the fly, which we use to generate a query
  181. // object and then get the SQL we need for the subquery.
  182. $temp_view = $this->get_temporary_view();
  183. // Add the sort from the options to the default display.
  184. list($sort_table, $sort_field) = explode('.', $options['subquery_sort']);
  185. $sort_options = array('order' => $options['subquery_order']);
  186. $temp_view->add_item('default', 'sort', $sort_table, $sort_field, $sort_options);
  187. }
  188. // Get the namespace string.
  189. $temp_view->namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : '_INNER';
  190. $this->subquery_namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : 'INNER';
  191. // The value we add here does nothing, but doing this adds the right tables
  192. // and puts in a WHERE clause with a placeholder we can grab later.
  193. $temp_view->args[] = '**CORRELATED**';
  194. // Add the base table ID field.
  195. $views_data = views_fetch_data($this->definition['base']);
  196. $base_field = $views_data['table']['base']['field'];
  197. $temp_view->add_item('default', 'field', $this->definition['base'], $this->definition['field']);
  198. // Add the correct argument for our relationship's base ie the "how to get
  199. // back to base" argument; the relationship definition defines which one to
  200. // use.
  201. $temp_view->add_item(
  202. 'default',
  203. 'argument',
  204. // For example, 'term_node',
  205. $this->definition['argument table'],
  206. // For example, 'tid'.
  207. $this->definition['argument field']
  208. );
  209. // Build the view. The creates the query object and produces the query
  210. // string but does not run any queries.
  211. $temp_view->build();
  212. // Now take the SelectQuery object the View has built and massage it
  213. // somewhat so we can get the SQL query from it.
  214. $subquery = $temp_view->build_info['query'];
  215. // Workaround until http://drupal.org/node/844910 is fixed.
  216. // Remove all fields from the SELECT except the base id.
  217. $fields =& $subquery->getFields();
  218. foreach (array_keys($fields) as $field_name) {
  219. // The base id for this subquery is stored in our definition.
  220. if ($field_name != $this->definition['field']) {
  221. unset($fields[$field_name]);
  222. }
  223. }
  224. // Make every alias in the subquery safe within the outer query by appending
  225. // a namespace to it, '_inner' by default.
  226. $tables =& $subquery->getTables();
  227. foreach (array_keys($tables) as $table_name) {
  228. $tables[$table_name]['alias'] .= $this->subquery_namespace;
  229. // Namespace the join on every table.
  230. if (isset($tables[$table_name]['condition'])) {
  231. $tables[$table_name]['condition'] = $this->condition_namespace($tables[$table_name]['condition']);
  232. }
  233. }
  234. // Namespace fields.
  235. foreach (array_keys($fields) as $field_name) {
  236. $fields[$field_name]['table'] .= $this->subquery_namespace;
  237. $fields[$field_name]['alias'] .= $this->subquery_namespace;
  238. }
  239. // Namespace conditions.
  240. $where =& $subquery->conditions();
  241. $this->alter_subquery_condition($subquery, $where);
  242. // Not sure why, but our sort order clause doesn't have a table.
  243. // @todo The call to add_item() above to add the sort handler is probably
  244. // wrong -- needs attention from someone who understands it.
  245. // In the meantime, this works, but with a leap of faith.
  246. $orders =& $subquery->getOrderBy();
  247. $orders_tmp = array();
  248. foreach ($orders as $order_key => $order) {
  249. // Until http://drupal.org/node/844910 is fixed, $order_key is a field
  250. // alias from SELECT. De-alias it using the View object.
  251. $sort_table = $temp_view->query->fields[$order_key]['table'];
  252. $sort_field = $temp_view->query->fields[$order_key]['field'];
  253. $orders_tmp[$sort_table . $this->subquery_namespace . '.' . $sort_field] = $order;
  254. }
  255. $orders = $orders_tmp;
  256. // The query we get doesn't include the LIMIT, so add it here.
  257. $subquery->range(0, 1);
  258. // Clone the query object to force recompilation of the underlying where and
  259. // having objects on the next step.
  260. $subquery = clone $subquery;
  261. // Add in Views Query Substitutions such as ***CURRENT_TIME***.
  262. views_query_views_alter($subquery);
  263. // Extract the SQL the temporary view built.
  264. $subquery_sql = $subquery->__toString();
  265. // Replace subquery argument placeholders.
  266. $quoted = $subquery->getArguments();
  267. $connection = Database::getConnection();
  268. foreach ($quoted as $key => $val) {
  269. if (is_array($val)) {
  270. $quoted[$key] = implode(', ', array_map(array($connection, 'quote'), $val));
  271. }
  272. // If the correlated placeholder has been located, replace it with the
  273. // outer field name.
  274. elseif ($val === '**CORRELATED**') {
  275. $quoted[$key] = $this->definition['outer field'];
  276. }
  277. else {
  278. $quoted[$key] = $connection->quote($val);
  279. }
  280. }
  281. $subquery_sql = strtr($subquery_sql, $quoted);
  282. return $subquery_sql;
  283. }
  284. /**
  285. * Recursive helper to add a namespace to conditions.
  286. *
  287. * Similar to _views_query_tag_alter_condition().
  288. *
  289. * (Though why is the condition we get in a simple query 3 levels deep???)
  290. */
  291. public function alter_subquery_condition(QueryAlterableInterface $query, &$conditions) {
  292. foreach ($conditions as $condition_id => &$condition) {
  293. // Skip the #conjunction element.
  294. if (is_numeric($condition_id)) {
  295. if (is_string($condition['field'])) {
  296. $condition['field'] = $this->condition_namespace($condition['field']);
  297. }
  298. elseif (is_object($condition['field'])) {
  299. $sub_conditions =& $condition['field']->conditions();
  300. $this->alter_subquery_condition($query, $sub_conditions);
  301. }
  302. }
  303. }
  304. }
  305. /**
  306. * Helper function to namespace query pieces.
  307. *
  308. * Turns 'foo.bar' into 'foo_NAMESPACE.bar'.
  309. */
  310. public function condition_namespace($string) {
  311. return str_replace('.', $this->subquery_namespace . '.', $string);
  312. }
  313. /**
  314. * Called to implement a relationship in a query.
  315. * This is mostly a copy of our parent's query() except for this bit with
  316. * the join class.
  317. */
  318. public function query() {
  319. // Figure out what base table this relationship brings to the party.
  320. $table_data = views_fetch_data($this->definition['base']);
  321. $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];
  322. $this->ensure_my_table();
  323. $def = $this->definition;
  324. $def['table'] = $this->definition['base'];
  325. $def['field'] = $base_field;
  326. $def['left_table'] = $this->table_alias;
  327. $def['left_field'] = $this->field;
  328. if (!empty($this->options['required'])) {
  329. $def['type'] = 'INNER';
  330. }
  331. if ($this->options['subquery_regenerate']) {
  332. // For testing only, regenerate the subquery each time.
  333. $def['left_query'] = $this->left_query($this->options);
  334. }
  335. else {
  336. // Get the stored subquery SQL string.
  337. $cid = 'views_relationship_groupwise_max:' . $this->view->name . ':' . $this->view->current_display . ':' . $this->options['id'];
  338. $cache = cache_get($cid, 'cache_views_data');
  339. if (isset($cache->data)) {
  340. $def['left_query'] = $cache->data;
  341. }
  342. else {
  343. $def['left_query'] = $this->left_query($this->options);
  344. cache_set($cid, $def['left_query'], 'cache_views_data');
  345. }
  346. }
  347. if (!empty($def['join_handler']) && class_exists($def['join_handler'])) {
  348. $join = new $def['join_handler'];
  349. }
  350. else {
  351. $join = new views_join_subquery();
  352. }
  353. $join->definition = $def;
  354. $join->construct();
  355. $join->adjusted = TRUE;
  356. // Use a short alias for this.
  357. $alias = $def['table'] . '_' . $this->table;
  358. $this->alias = $this->query->add_relationship($alias, $join, $this->definition['base'], $this->relationship);
  359. }
  360. }