Project

General

Profile

Paste
Download (16.1 KB) Statistics
| Branch: | Revision:

root / drupal7 / sites / all / modules / views / handlers / views_handler_relationship_groupwise_max.inc @ 4003efde

1
<?php
2

    
3
/**
4
 * @file
5
 * Definition of views_handler_relationship_groupwise_max.
6
 */
7

    
8
/**
9
 * Relationship handler that allows a groupwise maximum of the linked in table.
10
 *
11
 * For a definition, see:
12
 * http://dev.mysql.com/doc/refman/5.0/en/example-maximum-column-group-row.html
13
 * In lay terms, instead of joining to get all matching records in the linked
14
 * table, we get only one record, a 'representative record' picked according
15
 * to a given criteria.
16
 *
17
 * Example:
18
 * Suppose we have a term view that gives us the terms: Horse, Cat, Aardvark.
19
 * We wish to show for each term the most recent node of that term.
20
 * What we want is some kind of relationship from term to node.
21
 * But a regular relationship will give us all the nodes for each term,
22
 * giving the view multiple rows per term. What we want is just one
23
 * representative node per term, the node that is the 'best' in some way:
24
 * eg, the most recent, the most commented on, the first in alphabetical order.
25
 *
26
 * This handler gives us that kind of relationship from term to node.
27
 * The method of choosing the 'best' implemented with a sort
28
 * that the user selects in the relationship settings.
29
 *
30
 * So if we want our term view to show the most commented node for each term,
31
 * add the relationship and in its options, pick the 'Comment count' sort.
32
 *
33
 * Relationship definition
34
 *  - 'outer field': The outer field to substitute into the correlated subquery.
35
 *       This must be the full field name, not the alias.
36
 *       Eg: 'term_data.tid'.
37
 *  - 'argument table',
38
 *    'argument field': These options define a views argument that the subquery
39
 *     must add to itself to filter by the main view.
40
 *     Example: the main view shows terms, this handler is being used to get to
41
 *     the nodes base table. Your argument must be 'term_node', 'tid', as this
42
 *     is the argument that should be added to a node view to filter on terms.
43
 *
44
 * A note on performance:
45
 * This relationship uses a correlated subquery, which is expensive.
46
 * Subsequent versions of this handler could also implement the alternative way
47
 * of doing this, with a join -- though this looks like it could be pretty messy
48
 * to implement. This is also an expensive method, so providing both methods and
49
 * allowing the user to choose which one works fastest for their data might be
50
 * the best way.
51
 * If your use of this relationship handler is likely to result in large
52
 * data sets, you might want to consider storing statistics in a separate table,
53
 * in the same way as node_comment_statistics.
54
 *
55
 * @ingroup views_relationship_handlers
56
 */
57
class views_handler_relationship_groupwise_max extends views_handler_relationship {
58

    
59
  /**
60
   * Defines default values for options.
61
   */
62
  public function option_definition() {
63
    $options = parent::option_definition();
64

    
65
    $options['subquery_sort'] = array('default' => NULL);
66
    // Descending more useful.
67
    $options['subquery_order'] = array('default' => 'DESC');
68
    $options['subquery_regenerate'] = array('default' => FALSE, 'bool' => TRUE);
69
    $options['subquery_view'] = array('default' => FALSE);
70
    $options['subquery_namespace'] = array('default' => FALSE);
71

    
72
    return $options;
73
  }
74

    
75
  /**
76
   * Extends the relationship's basic options.
77
   *
78
   * Allows the user to pick a sort and an order for it.
79
   */
80
  public function options_form(&$form, &$form_state) {
81
    parent::options_form($form, $form_state);
82

    
83
    // Get the sorts that apply to our base.
84
    $sorts = views_fetch_fields($this->definition['base'], 'sort');
85
    foreach ($sorts as $sort_id => $sort) {
86
      $sort_options[$sort_id] = "$sort[group]: $sort[title]";
87
    }
88
    $base_table_data = views_fetch_data($this->definition['base']);
89

    
90
    $form['subquery_sort'] = array(
91
      '#type' => 'select',
92
      '#title' => t('Representative sort criteria'),
93
      // Provide the base field as sane default sort option.
94
      '#default_value' => !empty($this->options['subquery_sort']) ? $this->options['subquery_sort'] : $this->definition['base'] . '.' . $base_table_data['table']['base']['field'],
95
      '#options' => $sort_options,
96
      '#description' => theme('advanced_help_topic', array('module' => 'views', 'topic' => 'relationship-representative')) .
97
      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'."),
98
    );
99

    
100
    $form['subquery_order'] = array(
101
      '#type' => 'radios',
102
      '#title' => t('Representative sort order'),
103
      '#description' => t("The ordering to use for the sort criteria selected above."),
104
      '#options' => array('ASC' => t('Ascending'), 'DESC' => t('Descending')),
105
      '#default_value' => $this->options['subquery_order'],
106
    );
107

    
108
    $form['subquery_namespace'] = array(
109
      '#type' => 'textfield',
110
      '#title' => t('Subquery namespace'),
111
      '#description' => t('Advanced. Enter a namespace for the subquery used by this relationship.'),
112
      '#default_value' => $this->options['subquery_namespace'],
113
    );
114

    
115
    // WIP: This stuff doesn't work yet: namespacing issues.
116
    // A list of suitable views to pick one as the subview.
117
    $views = array('' => '<none>');
118
    $all_views = views_get_all_views();
119
    foreach ($all_views as $view) {
120
      // Only get views that are suitable:
121
      // - base must the base that our relationship joins towards
122
      // - must have fields.
123
      if ($view->base_table == $this->definition['base'] && !empty($view->display['default']->display_options['fields'])) {
124
        // @todo check the field is the correct sort?
125
        // or let users hang themselves at this stage and check later?
126
        if ($view->type == 'Default') {
127
          $views[t('Default Views')][$view->name] = $view->name;
128
        }
129
        else {
130
          $views[t('Existing Views')][$view->name] = $view->name;
131
        }
132
      }
133
    }
134

    
135
    $form['subquery_view'] = array(
136
      '#type' => 'select',
137
      '#title' => t('Representative view'),
138
      '#default_value' => $this->options['subquery_view'],
139
      '#options' => $views,
140
      '#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.'),
141
    );
142

    
143
    $form['subquery_regenerate'] = array(
144
      '#type' => 'checkbox',
145
      '#title' => t('Generate subquery each time view is run.'),
146
      '#default_value' => $this->options['subquery_regenerate'],
147
      '#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.'),
148
    );
149
  }
150

    
151
  /**
152
   * Helper function to create a pseudo view.
153
   *
154
   * We use this to obtain our subquery SQL.
155
   */
156
  public function get_temporary_view() {
157
    views_include('view');
158
    $view = new view();
159
    // @todo What's this?
160
    $view->vid = 'new';
161
    $view->base_table = $this->definition['base'];
162
    $view->add_display('default');
163
    return $view;
164
  }
165

    
166
  /**
167
   * When the form is submitted, take sure to clear the subquery string cache.
168
   */
169
  public function options_form_submit(&$form, &$form_state) {
170
    $cid = 'views_relationship_groupwise_max:' . $this->view->name . ':' . $this->view->current_display . ':' . $this->options['id'];
171
    cache_clear_all($cid, 'cache_views_data');
172
  }
173

    
174
  /**
175
   * Generate a subquery given the user options, as set in the options.
176
   * These are passed in rather than picked up from the object because we
177
   * generate the subquery when the options are saved, rather than when the view
178
   * is run. This saves considerable time.
179
   *
180
   * @param array $options
181
   *   An array of options that contains the following items:
182
   *   - subquery_sort: the id of a views sort.
183
   *   - subquery_order: either ASC or DESC.
184
   *
185
   * @return string
186
   *    The subquery SQL string, ready for use in the main query.
187
   */
188
  public function left_query($options) {
189
    // Either load another view, or create one on the fly.
190
    if ($options['subquery_view']) {
191
      $temp_view = views_get_view($options['subquery_view']);
192
      // Remove all fields from default display.
193
      unset($temp_view->display['default']->display_options['fields']);
194
    }
195
    else {
196
      // Create a new view object on the fly, which we use to generate a query
197
      // object and then get the SQL we need for the subquery.
198
      $temp_view = $this->get_temporary_view();
199

    
200
      // Add the sort from the options to the default display.
201
      list($sort_table, $sort_field) = explode('.', $options['subquery_sort']);
202
      $sort_options = array('order' => $options['subquery_order']);
203
      $temp_view->add_item('default', 'sort', $sort_table, $sort_field, $sort_options);
204
    }
205

    
206
    // Get the namespace string.
207
    $temp_view->namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : '_INNER';
208
    $this->subquery_namespace = (!empty($options['subquery_namespace'])) ? '_' . $options['subquery_namespace'] : 'INNER';
209

    
210
    // The value we add here does nothing, but doing this adds the right tables
211
    // and puts in a WHERE clause with a placeholder we can grab later.
212
    $temp_view->args[] = '**CORRELATED**';
213

    
214
    // Add the base table ID field.
215
    $views_data = views_fetch_data($this->definition['base']);
216
    $base_field = $views_data['table']['base']['field'];
217
    $temp_view->add_item('default', 'field', $this->definition['base'], $this->definition['field']);
218

    
219
    // Add the correct argument for our relationship's base ie the "how to get
220
    // back to base" argument; the relationship definition defines which one to
221
    // use.
222
    $temp_view->add_item(
223
      'default',
224
      'argument',
225
      // For example, 'term_node',
226
      $this->definition['argument table'],
227
      // For example, 'tid'.
228
      $this->definition['argument field']
229
    );
230

    
231
    // Build the view. The creates the query object and produces the query
232
    // string but does not run any queries.
233
    $temp_view->build();
234

    
235
    // Now take the SelectQuery object the View has built and massage it
236
    // somewhat so we can get the SQL query from it.
237
    $subquery = $temp_view->build_info['query'];
238

    
239
    // Workaround until http://drupal.org/node/844910 is fixed.
240
    // Remove all fields from the SELECT except the base id.
241
    $fields =& $subquery->getFields();
242
    foreach (array_keys($fields) as $field_name) {
243
      // The base id for this subquery is stored in our definition.
244
      if ($field_name != $this->definition['field']) {
245
        unset($fields[$field_name]);
246
      }
247
    }
248

    
249
    // Make every alias in the subquery safe within the outer query by appending
250
    // a namespace to it, '_inner' by default.
251
    $tables =& $subquery->getTables();
252
    foreach (array_keys($tables) as $table_name) {
253
      $tables[$table_name]['alias'] .= $this->subquery_namespace;
254
      // Namespace the join on every table.
255
      if (isset($tables[$table_name]['condition'])) {
256
        $tables[$table_name]['condition'] = $this->condition_namespace($tables[$table_name]['condition']);
257
      }
258
    }
259
    // Namespace fields.
260
    foreach (array_keys($fields) as $field_name) {
261
      $fields[$field_name]['table'] .= $this->subquery_namespace;
262
      $fields[$field_name]['alias'] .= $this->subquery_namespace;
263
    }
264
    // Namespace conditions.
265
    $where =& $subquery->conditions();
266
    $this->alter_subquery_condition($subquery, $where);
267
    // Not sure why, but our sort order clause doesn't have a table.
268
    // @todo The call to add_item() above to add the sort handler is probably
269
    // wrong -- needs attention from someone who understands it.
270
    // In the meantime, this works, but with a leap of faith.
271
    $orders =& $subquery->getOrderBy();
272
    $orders_tmp = array();
273
    foreach ($orders as $order_key => $order) {
274
      // Until http://drupal.org/node/844910 is fixed, $order_key is a field
275
      // alias from SELECT. De-alias it using the View object.
276
      $sort_table = $temp_view->query->fields[$order_key]['table'];
277
      $sort_field = $temp_view->query->fields[$order_key]['field'];
278
      $orders_tmp[$sort_table . $this->subquery_namespace . '.' . $sort_field] = $order;
279
    }
280
    $orders = $orders_tmp;
281

    
282
    // The query we get doesn't include the LIMIT, so add it here.
283
    $subquery->range(0, 1);
284
    // Clone the query object to force recompilation of the underlying where and
285
    // having objects on the next step.
286
    $subquery = clone $subquery;
287

    
288
    // Add in Views Query Substitutions such as ***CURRENT_TIME***.
289
    views_query_views_alter($subquery);
290

    
291
    // Extract the SQL the temporary view built.
292
    $subquery_sql = $subquery->__toString();
293

    
294
    // Replace subquery argument placeholders.
295
    $quoted = $subquery->getArguments();
296
    $connection = Database::getConnection();
297
    foreach ($quoted as $key => $val) {
298
      if (is_array($val)) {
299
        $quoted[$key] = implode(', ', array_map(array($connection, 'quote'), $val));
300
      }
301
      // If the correlated placeholder has been located, replace it with the
302
      // outer field name.
303
      elseif ($val === '**CORRELATED**') {
304
        $quoted[$key] = $this->definition['outer field'];
305
      }
306
      else {
307
        $quoted[$key] = $connection->quote($val);
308
      }
309
    }
310
    $subquery_sql = strtr($subquery_sql, $quoted);
311

    
312
    return $subquery_sql;
313
  }
314

    
315
  /**
316
   * Recursive helper to add a namespace to conditions.
317
   *
318
   * Similar to _views_query_tag_alter_condition().
319
   *
320
   * (Though why is the condition we get in a simple query 3 levels deep???)
321
   */
322
  public function alter_subquery_condition(QueryAlterableInterface $query, &$conditions) {
323
    foreach ($conditions as $condition_id => &$condition) {
324
      // Skip the #conjunction element.
325
      if (is_numeric($condition_id)) {
326
        if (is_string($condition['field'])) {
327
          $condition['field'] = $this->condition_namespace($condition['field']);
328
        }
329
        elseif (is_object($condition['field'])) {
330
          $sub_conditions =& $condition['field']->conditions();
331
          $this->alter_subquery_condition($query, $sub_conditions);
332
        }
333
      }
334
    }
335
  }
336

    
337
  /**
338
   * Helper function to namespace query pieces.
339
   *
340
   * Turns 'foo.bar' into 'foo_NAMESPACE.bar'.
341
   */
342
  public function condition_namespace($string) {
343
    return str_replace('.', $this->subquery_namespace . '.', $string);
344
  }
345

    
346
  /**
347
   * Called to implement a relationship in a query.
348
   * This is mostly a copy of our parent's query() except for this bit with
349
   * the join class.
350
   */
351
  public function query() {
352
    // Figure out what base table this relationship brings to the party.
353
    $table_data = views_fetch_data($this->definition['base']);
354
    $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];
355

    
356
    $this->ensure_my_table();
357

    
358
    $def = $this->definition;
359
    $def['table'] = $this->definition['base'];
360
    $def['field'] = $base_field;
361
    $def['left_table'] = $this->table_alias;
362
    $def['left_field'] = $this->field;
363
    if (!empty($this->options['required'])) {
364
      $def['type'] = 'INNER';
365
    }
366

    
367
    if ($this->options['subquery_regenerate']) {
368
      // For testing only, regenerate the subquery each time.
369
      $def['left_query'] = $this->left_query($this->options);
370
    }
371
    else {
372
      // Get the stored subquery SQL string.
373
      $cid = 'views_relationship_groupwise_max:' . $this->view->name . ':' . $this->view->current_display . ':' . $this->options['id'];
374
      $cache = cache_get($cid, 'cache_views_data');
375
      if (isset($cache->data)) {
376
        $def['left_query'] = $cache->data;
377
      }
378
      else {
379
        $def['left_query'] = $this->left_query($this->options);
380
        cache_set($cid, $def['left_query'], 'cache_views_data');
381
      }
382
    }
383

    
384
    if (!empty($def['join_handler']) && class_exists($def['join_handler'])) {
385
      $join = new $def['join_handler'];
386
    }
387
    else {
388
      $join = new views_join_subquery();
389
    }
390

    
391
    $join->definition = $def;
392
    $join->construct();
393
    $join->adjusted = TRUE;
394

    
395
    // Use a short alias for this.
396
    $alias = $def['table'] . '_' . $this->table;
397

    
398
    $this->alias = $this->query->add_relationship($alias, $join, $this->definition['base'], $this->relationship);
399
  }
400

    
401
}