views_handler_relationship_groupwise_max.inc 16 KB

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