Projet

Général

Profil

Paste
Télécharger (15,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / views / handlers / views_handler_relationship_groupwise_max.inc @ 7547bb19

1
<?php
2

    
3
/**
4
 * @file
5
 * Relationship for groupwise maximum handler.
6
 */
7

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

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

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

    
71
    return $options;
72
  }
73

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

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

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

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

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

    
113

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

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

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

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

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

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

    
197
      // Add the sort from the options to the default display.
198
      // This is broken, in that the sort order field also gets added as a
199
      // select field. See http://drupal.org/node/844910.
200
      // We work around this further down.
201
      $sort = $options['subquery_sort'];
202
      list($sort_table, $sort_field) = explode('.', $sort);
203
      $sort_options = array('order' => $options['subquery_order']);
204
      $temp_view->add_item('default', 'sort', $sort_table, $sort_field, $sort_options);
205
    }
206

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

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

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

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

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

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

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

    
248
    // Make every alias in the subquery safe within the outer query by
249
    // appending a namespace to it, '_inner' by default.
250
    $tables =& $subquery->getTables();
251
    foreach (array_keys($tables) as $table_name) {
252
      $tables[$table_name]['alias'] .= $this->subquery_namespace;
253
      // Namespace the join on every table.
254
      if (isset($tables[$table_name]['condition'])) {
255
        $tables[$table_name]['condition'] = $this->condition_namespace($tables[$table_name]['condition']);
256
      }
257
    }
258
    // Namespace fields.
259
    foreach (array_keys($fields) as $field_name) {
260
      $fields[$field_name]['table'] .= $this->subquery_namespace;
261
      $fields[$field_name]['alias'] .= $this->subquery_namespace;
262
    }
263
    // Namespace conditions.
264
    $where =& $subquery->conditions();
265
    $this->alter_subquery_condition($subquery, $where);
266
    // Not sure why, but our sort order clause doesn't have a table.
267
    // TODO: the call to add_item() above to add the sort handler is probably
268
    // wrong -- needs attention from someone who understands it.
269
    // In the meantime, this works, but with a leap of faith...
270
    $orders =& $subquery->getOrderBy();
271
    foreach ($orders as $order_key => $order) {
272
      // But if we're using a whole view, we don't know what we have!
273
      if ($options['subquery_view']) {
274
        list($sort_table, $sort_field) = explode('.', $order_key);
275
      }
276
      $orders[$sort_table . $this->subquery_namespace . '.' . $sort_field] = $order;
277
      unset($orders[$order_key]);
278
    }
279

    
280
    // The query we get doesn't include the LIMIT, so add it here.
281
    $subquery->range(0, 1);
282

    
283
    // Extract the SQL the temporary view built.
284
    $subquery_sql = $subquery->__toString();
285

    
286
    // Replace the placeholder with the outer, correlated field.
287
    // Eg, change the placeholder ':users_uid' into the outer field 'users.uid'.
288
    // We have to work directly with the SQL, because putting a name of a field
289
    // into a SelectQuery that it does not recognize (because it's outer) just
290
    // makes it treat it as a string.
291
    $outer_placeholder = ':' . str_replace('.', '_', $this->definition['outer field']);
292
    $subquery_sql = str_replace($outer_placeholder, $this->definition['outer field'], $subquery_sql);
293

    
294
    return $subquery_sql;
295
  }
296

    
297
  /**
298
   * Recursive helper to add a namespace to conditions.
299
   *
300
   * Similar to _views_query_tag_alter_condition().
301
   *
302
   * (Though why is the condition we get in a simple query 3 levels deep???)
303
   */
304
  function alter_subquery_condition(QueryAlterableInterface $query, &$conditions) {
305
    foreach ($conditions as $condition_id => &$condition) {
306
      // Skip the #conjunction element.
307
      if (is_numeric($condition_id)) {
308
        if (is_string($condition['field'])) {
309
          $condition['field'] = $this->condition_namespace($condition['field']);
310
        }
311
        elseif (is_object($condition['field'])) {
312
          $sub_conditions =& $condition['field']->conditions();
313
          $this->alter_subquery_condition($query, $sub_conditions);
314
        }
315
      }
316
    }
317
  }
318

    
319
  /**
320
   * Helper function to namespace query pieces.
321
   *
322
   * Turns 'foo.bar' into 'foo_NAMESPACE.bar'.
323
   */
324
  function condition_namespace($string) {
325
    return str_replace('.', $this->subquery_namespace . '.', $string);
326
  }
327

    
328
  /**
329
   * Called to implement a relationship in a query.
330
   * This is mostly a copy of our parent's query() except for this bit with
331
   * the join class.
332
   */
333
  function query() {
334
    // Figure out what base table this relationship brings to the party.
335
    $table_data = views_fetch_data($this->definition['base']);
336
    $base_field = empty($this->definition['base field']) ? $table_data['table']['base']['field'] : $this->definition['base field'];
337

    
338
    $this->ensure_my_table();
339

    
340
    $def = $this->definition;
341
    $def['table'] = $this->definition['base'];
342
    $def['field'] = $base_field;
343
    $def['left_table'] = $this->table_alias;
344
    $def['left_field'] = $this->field;
345
    if (!empty($this->options['required'])) {
346
      $def['type'] = 'INNER';
347
    }
348

    
349
    if ($this->options['subquery_regenerate']) {
350
      // For testing only, regenerate the subquery each time.
351
      $def['left_query'] = $this->left_query($this->options);
352
    }
353
    else {
354
      // Get the stored subquery SQL string.
355
      $cid = 'views_relationship_groupwise_max:' . $this->view->name . ':' . $this->view->current_display . ':' . $this->options['id'];
356
      $cache = cache_get($cid, 'cache_views_data');
357
      if (isset($cache->data)) {
358
        $def['left_query'] = $cache->data;
359
      }
360
      else {
361
        $def['left_query'] = $this->left_query($this->options);
362
        cache_set($cid, $def['left_query'], 'cache_views_data');
363
      }
364
    }
365

    
366
    if (!empty($def['join_handler']) && class_exists($def['join_handler'])) {
367
      $join = new $def['join_handler'];
368
    }
369
    else {
370
      $join = new views_join_subquery();
371
    }
372

    
373
    $join->definition = $def;
374
    $join->construct();
375
    $join->adjusted = TRUE;
376

    
377
    // use a short alias for this:
378
    $alias = $def['table'] . '_' . $this->table;
379

    
380
    $this->alias = $this->query->add_relationship($alias, $join, $this->definition['base'], $this->relationship);
381
  }
382
}