Project

General

Profile

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

root / drupal7 / sites / all / modules / views / plugins / views_plugin_query_default.inc @ d719f12f

1
<?php
2

    
3
/**
4
 * @file
5
 * Defines the default query object.
6
 */
7

    
8
/**
9
 * Object used to create a SELECT query.
10
 *
11
 * @ingroup views_query_plugins
12
 */
13
class views_plugin_query_default extends views_plugin_query {
14

    
15
  /**
16
   * A list of tables in the order they should be added, keyed by alias.
17
   */
18
  var $table_queue = array();
19

    
20
  /**
21
   * Holds an array of tables and counts added so that we can create aliases
22
   */
23
  var $tables = array();
24

    
25
  /**
26
   * Holds an array of relationships, which are aliases of the primary
27
   * table that represent different ways to join the same table in.
28
   */
29
  var $relationships = array();
30

    
31
  /**
32
   * An array of sections of the WHERE query. Each section is in itself
33
   * an array of pieces and a flag as to whether or not it should be AND
34
   * or OR.
35
   */
36
  var $where = array();
37
  /**
38
   * An array of sections of the HAVING query. Each section is in itself
39
   * an array of pieces and a flag as to whether or not it should be AND
40
   * or OR.
41
   */
42
  var $having = array();
43
  /**
44
   * The default operator to use when connecting the WHERE groups. May be
45
   * AND or OR.
46
   */
47
  var $group_operator = 'AND';
48

    
49
  /**
50
   * A simple array of order by clauses.
51
   */
52
  var $orderby = array();
53

    
54
  /**
55
   * A simple array of group by clauses.
56
   */
57
  var $groupby = array();
58

    
59

    
60
  /**
61
   * An array of fields.
62
   */
63
  var $fields = array();
64

    
65

    
66
  /**
67
   * The table header to use for tablesort. This matters because tablesort
68
   * needs to modify the query and needs the header.
69
   */
70
  var $header = array();
71

    
72
  /**
73
   * A flag as to whether or not to make the primary field distinct.
74
   */
75
  var $distinct = FALSE;
76

    
77
  var $has_aggregate = FALSE;
78

    
79
  /**
80
   * Should this query be optimized for counts, for example no sorts.
81
   */
82
  var $get_count_optimized = NULL;
83

    
84
  /**
85
   * The current used pager plugin.
86
   *
87
   * @var views_plugin_pager
88
   */
89
   var $pager = NULL;
90

    
91
   /**
92
    * An array mapping table aliases and field names to field aliases.
93
    */
94
   var $field_aliases = array();
95

    
96
   /**
97
    * Query tags which will be passed over to the dbtng query object.
98
    */
99
   var $tags = array();
100

    
101
  /**
102
   * Is the view marked as not distinct.
103
   *
104
   * @var bool
105
   */
106
  var $no_distinct;
107

    
108
  /**
109
   * Defines the distinct type.
110
   * - FALSE if it's distinct by base field.
111
   * - TRUE if it just adds the sql distinct keyword.
112
   *
113
   * @var bool
114
   */
115
  public $pure_distinct = FALSE;
116

    
117
  /**
118
   * Constructor; Create the basic query object and fill with default values.
119
   */
120
  function init($base_table = 'node', $base_field = 'nid', $options) {
121
    parent::init($base_table, $base_field, $options);
122
    $this->base_table = $base_table;  // Predefine these above, for clarity.
123
    $this->base_field = $base_field;
124
    $this->relationships[$base_table] = array(
125
      'link' => NULL,
126
      'table' => $base_table,
127
      'alias' => $base_table,
128
      'base' => $base_table
129
    );
130

    
131
    // init the table queue with our primary table.
132
    $this->table_queue[$base_table] = array(
133
      'alias' => $base_table,
134
      'table' => $base_table,
135
      'relationship' => $base_table,
136
      'join' => NULL,
137
    );
138

    
139
    // init the tables with our primary table
140
    $this->tables[$base_table][$base_table] = array(
141
      'count' => 1,
142
      'alias' => $base_table,
143
    );
144

    
145
/**
146
 * -- we no longer want the base field to appear automatically.
147
    if ($base_field) {
148
      $this->fields[$base_field] = array(
149
        'table' => $base_table,
150
        'field' => $base_field,
151
        'alias' => $base_field,
152
      );
153
    }
154
 */
155

    
156
    $this->count_field = array(
157
      'table' => $base_table,
158
      'field' => $base_field,
159
      'alias' => $base_field,
160
      'count' => TRUE,
161
    );
162
  }
163

    
164
  // ----------------------------------------------------------------
165
  // Utility methods to set flags and data.
166

    
167
  /**
168
   * Set the view to be distinct.
169
   *
170
   * There are either distinct per base field or distinct in the pure sql way,
171
   * based on $pure_distinct.
172
   *
173
   * @param bool $value
174
   *   Should the view by distincted.
175
   * @param bool $pure_distinct
176
   *   Should only the sql keyword be added.
177
   */
178
  function set_distinct($value = TRUE, $pure_distinct = FALSE) {
179
    if (!(isset($this->no_distinct) && $value)) {
180
      $this->distinct = $value;
181
      $this->pure_distinct = $pure_distinct;
182
    }
183
  }
184

    
185
  /**
186
   * Set what field the query will count() on for paging.
187
   */
188
  function set_count_field($table, $field, $alias = NULL) {
189
    if (empty($alias)) {
190
      $alias = $table . '_' . $field;
191
    }
192
    $this->count_field = array(
193
      'table' => $table,
194
      'field' => $field,
195
      'alias' => $alias,
196
      'count' => TRUE,
197
    );
198
  }
199

    
200
  /**
201
   * Set the table header; used for click-sorting because it's needed
202
   * info to modify the ORDER BY clause.
203
   */
204
  function set_header($header) {
205
    $this->header = $header;
206
  }
207

    
208
  function option_definition() {
209
    $options = parent::option_definition();
210
    $options['disable_sql_rewrite'] = array(
211
      'default' => FALSE,
212
      'translatable' => FALSE,
213
      'bool' => TRUE,
214
    );
215
    $options['distinct'] = array(
216
      'default' => FALSE,
217
      'bool' => TRUE,
218
    );
219
    $options['pure_distinct'] = array(
220
      'default' => FALSE,
221
      'bool' => TRUE,
222
    );
223
    $options['slave'] = array(
224
      'default' => FALSE,
225
      'bool' => TRUE,
226
    );
227
    $options['query_comment'] = array(
228
      'default' => '',
229
    );
230
    $options['query_tags'] = array(
231
      'default' => array(),
232
    );
233

    
234
    return $options;
235
  }
236

    
237
  /**
238
   * Add settings for the ui.
239
   */
240
  function options_form(&$form, &$form_state) {
241
    parent::options_form($form, $form_state);
242

    
243
    $form['disable_sql_rewrite'] = array(
244
      '#title' => t('Disable SQL rewriting'),
245
      '#description' => t('Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_query_alter().'),
246
      '#type' => 'checkbox',
247
      '#default_value' => !empty($this->options['disable_sql_rewrite']),
248
      '#suffix' => '<div class="messages warning sql-rewrite-warning js-hide">' . t('WARNING: Disabling SQL rewriting means that node access security is disabled. This may allow users to see data they should not be able to see if your view is misconfigured. Please use this option only if you understand and accept this security risk.') . '</div>',
249
    );
250
    $form['distinct'] = array(
251
      '#type' => 'checkbox',
252
      '#title' => t('Distinct'),
253
      '#description' => t('This will make the view display only distinct items. If there are multiple identical items, each will be displayed only once. You can use this to try and remove duplicates from a view, though it does not always work. Note that this can slow queries down, so use it with caution.'),
254
      '#default_value' => !empty($this->options['distinct']),
255
    );
256
    $form['pure_distinct'] = array(
257
      '#type' => 'checkbox',
258
      '#title' => t('Pure Distinct'),
259
      '#description' => t('This will prevent views from adding the base column to the distinct field. If this is not selected and the base column is a primary key, then a non-pure distinct will not function properly because the primary key is always unique.'),
260
      '#default_value' => !empty($this->options['pure_distinct']),
261
      '#dependency' => array('edit-query-options-distinct' => '1'),
262
    );
263
    $form['slave'] = array(
264
      '#type' => 'checkbox',
265
      '#title' => t('Use Slave Server'),
266
      '#description' => t('This will make the query attempt to connect to a slave server if available.  If no slave server is defined or available, it will fall back to the default server.'),
267
      '#default_value' => !empty($this->options['slave']),
268
    );
269
    $form['query_comment'] = array(
270
      '#type' => 'textfield',
271
      '#title' => t('Query Comment'),
272
      '#description' => t('If set, this comment will be embedded in the query and passed to the SQL server. This can be helpful for logging or debugging.'),
273
      '#default_value' => $this->options['query_comment'],
274
    );
275
    $form['query_tags'] = array(
276
      '#type' => 'textfield',
277
      '#title' => t('Query Tags'),
278
      '#description' => t('If set, these tags will be appended to the query and can be used to identify the query in a module. This can be helpful for altering queries.'),
279
      '#default_value' => implode(', ', $this->options['query_tags']),
280
      '#element_validate' => array('views_element_validate_tags'),
281
    );
282
  }
283

    
284
  /**
285
   * Special submit handling.
286
   */
287
  function options_submit(&$form, &$form_state) {
288
    $element = array('#parents' => array('query', 'options', 'query_tags'));
289
    $value = explode(',', drupal_array_get_nested_value($form_state['values'], $element['#parents']));
290
    $value = array_filter(array_map('trim', $value));
291
    form_set_value($element, $value, $form_state);
292
  }
293

    
294
  // ----------------------------------------------------------------
295
  // Table/join adding
296

    
297
  /**
298
   * A relationship is an alternative endpoint to a series of table
299
   * joins. Relationships must be aliases of the primary table and
300
   * they must join either to the primary table or to a pre-existing
301
   * relationship.
302
   *
303
   * An example of a relationship would be a nodereference table.
304
   * If you have a nodereference named 'book_parent' which links to a
305
   * parent node, you could set up a relationship 'node_book_parent'
306
   * to 'node'. Then, anything that links to 'node' can link to
307
   * 'node_book_parent' instead, thus allowing all properties of
308
   * both nodes to be available in the query.
309
   *
310
   * @param $alias
311
   *   What this relationship will be called, and is also the alias
312
   *   for the table.
313
   * @param views_join $join
314
   *   A views_join object (or derived object) to join the alias in.
315
   * @param $base
316
   *   The name of the 'base' table this relationship represents; this
317
   *   tells the join search which path to attempt to use when finding
318
   *   the path to this relationship.
319
   * @param $link_point
320
   *   If this relationship links to something other than the primary
321
   *   table, specify that table here. For example, a 'track' node
322
   *   might have a relationship to an 'album' node, which might
323
   *   have a relationship to an 'artist' node.
324
   */
325
  function add_relationship($alias, $join, $base, $link_point = NULL) {
326
    if (empty($link_point)) {
327
      $link_point = $this->base_table;
328
    }
329
    elseif (!array_key_exists($link_point, $this->relationships)) {
330
      return FALSE;
331
    }
332

    
333
    // Make sure $alias isn't already used; if it, start adding stuff.
334
    $alias_base = $alias;
335
    $count = 1;
336
    while (!empty($this->relationships[$alias])) {
337
      $alias = $alias_base . '_' . $count++;
338
    }
339

    
340
    // Make sure this join is adjusted for our relationship.
341
    if ($link_point && isset($this->relationships[$link_point])) {
342
      $join = $this->adjust_join($join, $link_point);
343
    }
344

    
345
    // Add the table directly to the queue to avoid accidentally marking
346
    // it.
347
    $this->table_queue[$alias] = array(
348
      'table' => $join->table,
349
      'num' => 1,
350
      'alias' => $alias,
351
      'join' => $join,
352
      'relationship' => $link_point,
353
    );
354

    
355
    $this->relationships[$alias] = array(
356
      'link' => $link_point,
357
      'table' => $join->table,
358
      'base' => $base,
359
    );
360

    
361
    $this->tables[$this->base_table][$alias] = array(
362
      'count' => 1,
363
      'alias' => $alias,
364
    );
365

    
366
    return $alias;
367
  }
368

    
369
  /**
370
   * Add a table to the query, ensuring the path exists.
371
   *
372
   * This function will test to ensure that the path back to the primary
373
   * table is valid and exists; if you do not wish for this testing to
374
   * occur, use $query->queue_table() instead.
375
   *
376
   * @param $table
377
   *   The name of the table to add. It needs to exist in the global table
378
   *   array.
379
   * @param $relationship
380
   *   An alias of a table; if this is set, the path back to this table will
381
   *   be tested prior to adding the table, making sure that all intermediary
382
   *   tables exist and are properly aliased. If set to NULL the path to
383
   *   the primary table will be ensured. If the path cannot be made, the
384
   *   table will NOT be added.
385
   * @param views_join $join
386
   *   In some join configurations this table may actually join back through
387
   *   a different method; this is most likely to be used when tracing
388
   *   a hierarchy path. (node->parent->parent2->parent3). This parameter
389
   *   will specify how this table joins if it is not the default.
390
   * @param $alias
391
   *   A specific alias to use, rather than the default alias.
392
   *
393
   * @return $alias
394
   *   The alias of the table; this alias can be used to access information
395
   *   about the table and should always be used to refer to the table when
396
   *   adding parts to the query. Or FALSE if the table was not able to be
397
   *   added.
398
   */
399
  function add_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
400
    if (!$this->ensure_path($table, $relationship, $join)) {
401
      return FALSE;
402
    }
403

    
404
    if ($join && $relationship) {
405
      $join = $this->adjust_join($join, $relationship);
406
    }
407

    
408
    return $this->queue_table($table, $relationship, $join, $alias);
409
  }
410

    
411
  /**
412
   * Add a table to the query without ensuring the path.
413
   *
414
   * This is a pretty internal function to Views and add_table() or
415
   * ensure_table() should be used instead of this one, unless you are
416
   * absolutely sure this is what you want.
417
   *
418
   * @param $table
419
   *   The name of the table to add. It needs to exist in the global table
420
   *   array.
421
   * @param $relationship
422
   *   The primary table alias this table is related to. If not set, the
423
   *   primary table will be used.
424
   * @param views_join $join
425
   *   In some join configurations this table may actually join back through
426
   *   a different method; this is most likely to be used when tracing
427
   *   a hierarchy path. (node->parent->parent2->parent3). This parameter
428
   *   will specify how this table joins if it is not the default.
429
   * @param $alias
430
   *   A specific alias to use, rather than the default alias.
431
   *
432
   * @return $alias
433
   *   The alias of the table; this alias can be used to access information
434
   *   about the table and should always be used to refer to the table when
435
   *   adding parts to the query. Or FALSE if the table was not able to be
436
   *   added.
437
   */
438
  function queue_table($table, $relationship = NULL, $join = NULL, $alias = NULL) {
439
    // If the alias is set, make sure it doesn't already exist.
440
    if (isset($this->table_queue[$alias])) {
441
      return $alias;
442
    }
443

    
444
    if (empty($relationship)) {
445
      $relationship = $this->base_table;
446
    }
447

    
448
    if (!array_key_exists($relationship, $this->relationships)) {
449
      return FALSE;
450
    }
451

    
452
    if (!$alias && $join && $relationship && !empty($join->adjusted) && $table != $join->table) {
453
      if ($relationship == $this->base_table) {
454
        $alias = $table;
455
      }
456
      else {
457
        $alias = $relationship . '_' . $table;
458
      }
459
    }
460

    
461
    // Check this again to make sure we don't blow up existing aliases for already
462
    // adjusted joins.
463
    if (isset($this->table_queue[$alias])) {
464
      return $alias;
465
    }
466

    
467
    $alias = $this->mark_table($table, $relationship, $alias);
468

    
469
    // If no alias is specified, give it the default.
470
    if (!isset($alias)) {
471
      $alias = $this->tables[$relationship][$table]['alias'] . $this->tables[$relationship][$table]['count'];
472
    }
473

    
474
    // If this is a relationship based table, add a marker with
475
    // the relationship as a primary table for the alias.
476
    if ($table != $alias) {
477
      $this->mark_table($alias, $this->base_table, $alias);
478
    }
479

    
480
    // If no join is specified, pull it from the table data.
481
    if (!isset($join)) {
482
      $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
483
      if (empty($join)) {
484
        return FALSE;
485
      }
486

    
487
      $join = $this->adjust_join($join, $relationship);
488
    }
489

    
490
    $this->table_queue[$alias] = array(
491
      'table' => $table,
492
      'num' => $this->tables[$relationship][$table]['count'],
493
      'alias' => $alias,
494
      'join' => $join,
495
      'relationship' => $relationship,
496
    );
497

    
498
    return $alias;
499
  }
500

    
501
  function mark_table($table, $relationship, $alias) {
502
    // Mark that this table has been added.
503
    if (empty($this->tables[$relationship][$table])) {
504
      if (!isset($alias)) {
505
        $alias = '';
506
        if ($relationship != $this->base_table) {
507
          // double underscore will help prevent accidental name
508
          // space collisions.
509
          $alias = $relationship . '__';
510
        }
511
        $alias .= $table;
512
      }
513
      $this->tables[$relationship][$table] = array(
514
        'count' => 1,
515
        'alias' => $alias,
516
      );
517
    }
518
    else {
519
      $this->tables[$relationship][$table]['count']++;
520
    }
521

    
522
    return $alias;
523
  }
524

    
525
  /**
526
   * Ensure a table exists in the queue; if it already exists it won't
527
   * do anything, but if it doesn't it will add the table queue. It will ensure
528
   * a path leads back to the relationship table.
529
   *
530
   * @param $table
531
   *   The unaliased name of the table to ensure.
532
   * @param $relationship
533
   *   The relationship to ensure the table links to. Each relationship will
534
   *   get a unique instance of the table being added. If not specified,
535
   *   will be the primary table.
536
   * @param views_join $join
537
   *   A views_join object (or derived object) to join the alias in.
538
   *
539
   * @return
540
   *   The alias used to refer to this specific table, or NULL if the table
541
   *   cannot be ensured.
542
   */
543
  function ensure_table($table, $relationship = NULL, $join = NULL) {
544
    // ensure a relationship
545
    if (empty($relationship)) {
546
      $relationship = $this->base_table;
547
    }
548

    
549
    // If the relationship is the primary table, this actually be a relationship
550
    // link back from an alias. We store all aliases along with the primary table
551
    // to detect this state, because eventually it'll hit a table we already
552
    // have and that's when we want to stop.
553
    if ($relationship == $this->base_table && !empty($this->tables[$relationship][$table])) {
554
      return $this->tables[$relationship][$table]['alias'];
555
    }
556

    
557
    if (!array_key_exists($relationship, $this->relationships)) {
558
      return FALSE;
559
    }
560

    
561
    if ($table == $this->relationships[$relationship]['base']) {
562
      return $relationship;
563
    }
564

    
565
    // If we do not have join info, fetch it.
566
    if (!isset($join)) {
567
      $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
568
    }
569

    
570
    // If it can't be fetched, this won't work.
571
    if (empty($join)) {
572
      return;
573
    }
574

    
575
    // Adjust this join for the relationship, which will ensure that the 'base'
576
    // table it links to is correct. Tables adjoined to a relationship
577
    // join to a link point, not the base table.
578
    $join = $this->adjust_join($join, $relationship);
579

    
580
    if ($this->ensure_path($table, $relationship, $join)) {
581
      // Attempt to eliminate redundant joins.  If this table's
582
      // relationship and join exactly matches an existing table's
583
      // relationship and join, we do not have to join to it again;
584
      // just return the existing table's alias.  See
585
      // http://groups.drupal.org/node/11288 for details.
586
      //
587
      // This can be done safely here but not lower down in
588
      // queue_table(), because queue_table() is also used by
589
      // add_table() which requires the ability to intentionally add
590
      // the same table with the same join multiple times.  For
591
      // example, a view that filters on 3 taxonomy terms using AND
592
      // needs to join taxonomy_term_data 3 times with the same join.
593

    
594
      // scan through the table queue to see if a matching join and
595
      // relationship exists.  If so, use it instead of this join.
596

    
597
      // TODO: Scanning through $this->table_queue results in an
598
      // O(N^2) algorithm, and this code runs every time the view is
599
      // instantiated (Views 2 does not currently cache queries).
600
      // There are a couple possible "improvements" but we should do
601
      // some performance testing before picking one.
602
      foreach ($this->table_queue as $queued_table) {
603
        // In PHP 4 and 5, the == operation returns TRUE for two objects
604
        // if they are instances of the same class and have the same
605
        // attributes and values.
606
        if ($queued_table['relationship'] == $relationship && $queued_table['join'] == $join) {
607
          return $queued_table['alias'];
608
        }
609
      }
610

    
611
      return $this->queue_table($table, $relationship, $join);
612
    }
613
  }
614

    
615
  /**
616
   * Make sure that the specified table can be properly linked to the primary
617
   * table in the JOINs. This function uses recursion. If the tables
618
   * needed to complete the path back to the primary table are not in the
619
   * query they will be added, but additional copies will NOT be added
620
   * if the table is already there.
621
   */
622
  function ensure_path($table, $relationship = NULL, $join = NULL, $traced = array(), $add = array()) {
623
    if (!isset($relationship)) {
624
      $relationship = $this->base_table;
625
    }
626

    
627
    if (!array_key_exists($relationship, $this->relationships)) {
628
      return FALSE;
629
    }
630

    
631
    // If we do not have join info, fetch it.
632
    if (!isset($join)) {
633
      $join = $this->get_join_data($table, $this->relationships[$relationship]['base']);
634
    }
635

    
636
    // If it can't be fetched, this won't work.
637
    if (empty($join)) {
638
      return FALSE;
639
    }
640

    
641
    // Does a table along this path exist?
642
    if (isset($this->tables[$relationship][$table]) ||
643
      ($join && $join->left_table == $relationship) ||
644
      ($join && $join->left_table == $this->relationships[$relationship]['table'])) {
645

    
646
      // Make sure that we're linking to the correct table for our relationship.
647
      foreach (array_reverse($add) as $table => $path_join) {
648
        $this->queue_table($table, $relationship, $this->adjust_join($path_join, $relationship));
649
      }
650
      return TRUE;
651
    }
652

    
653
    // Have we been this way?
654
    if (isset($traced[$join->left_table])) {
655
      // we looped. Broked.
656
      return FALSE;
657
    }
658

    
659
    // Do we have to add this table?
660
    $left_join = $this->get_join_data($join->left_table, $this->relationships[$relationship]['base']);
661
    if (!isset($this->tables[$relationship][$join->left_table])) {
662
      $add[$join->left_table] = $left_join;
663
    }
664

    
665
    // Keep looking.
666
    $traced[$join->left_table] = TRUE;
667
    return $this->ensure_path($join->left_table, $relationship, $left_join, $traced, $add);
668
  }
669

    
670
  /**
671
   * Fix a join to adhere to the proper relationship; the left table can vary
672
   * based upon what relationship items are joined in on.
673
   */
674
  function adjust_join($join, $relationship) {
675
    if (!empty($join->adjusted)) {
676
      return $join;
677
    }
678

    
679
    if (empty($relationship) || empty($this->relationships[$relationship])) {
680
      return $join;
681
    }
682

    
683
    // Adjusts the left table for our relationship.
684
    if ($relationship != $this->base_table) {
685
      // If we're linking to the primary table, the relationship to use will
686
      // be the prior relationship. Unless it's a direct link.
687

    
688
      // Safety! Don't modify an original here.
689
      $join = clone $join;
690

    
691
      // Do we need to try to ensure a path?
692
      if ($join->left_table != $this->relationships[$relationship]['table'] &&
693
          $join->left_table != $this->relationships[$relationship]['base'] &&
694
          !isset($this->tables[$relationship][$join->left_table]['alias'])) {
695
        $this->ensure_table($join->left_table, $relationship);
696
      }
697

    
698
      // First, if this is our link point/anchor table, just use the relationship
699
      if ($join->left_table == $this->relationships[$relationship]['table']) {
700
        $join->left_table = $relationship;
701
      }
702
      // then, try the base alias.
703
      elseif (isset($this->tables[$relationship][$join->left_table]['alias'])) {
704
        $join->left_table = $this->tables[$relationship][$join->left_table]['alias'];
705
      }
706
      // But if we're already looking at an alias, use that instead.
707
      elseif (isset($this->table_queue[$relationship]['alias'])) {
708
        $join->left_table = $this->table_queue[$relationship]['alias'];
709
      }
710
    }
711

    
712
    $join->adjusted = TRUE;
713
    return $join;
714
  }
715

    
716
  /**
717
   * Retrieve join data from the larger join data cache.
718
   *
719
   * @param $table
720
   *   The table to get the join information for.
721
   * @param $base_table
722
   *   The path we're following to get this join.
723
   *
724
   * @return views_join
725
   *   A views_join object or child object, if one exists.
726
   */
727
  function get_join_data($table, $base_table) {
728
    // Check to see if we're linking to a known alias. If so, get the real
729
    // table's data instead.
730
    if (!empty($this->table_queue[$table])) {
731
      $table = $this->table_queue[$table]['table'];
732
    }
733
    return views_get_table_join($table, $base_table);
734
  }
735

    
736
  /**
737
   * Get the information associated with a table.
738
   *
739
   * If you need the alias of a table with a particular relationship, use
740
   * ensure_table().
741
   */
742
  function get_table_info($table) {
743
    if (!empty($this->table_queue[$table])) {
744
      return $this->table_queue[$table];
745
    }
746

    
747
    // In rare cases we might *only* have aliased versions of the table.
748
    if (!empty($this->tables[$this->base_table][$table])) {
749
      $alias = $this->tables[$this->base_table][$table]['alias'];
750
      if (!empty($this->table_queue[$alias])) {
751
        return $this->table_queue[$alias];
752
      }
753
    }
754
  }
755

    
756
  /**
757
   * Add a field to the query table, possibly with an alias. This will
758
   * automatically call ensure_table to make sure the required table
759
   * exists, *unless* $table is unset.
760
   *
761
   * @param $table
762
   *   The table this field is attached to. If NULL, it is assumed this will
763
   *   be a formula; otherwise, ensure_table is used to make sure the
764
   *   table exists.
765
   * @param $field
766
   *   The name of the field to add. This may be a real field or a formula.
767
   * @param $alias
768
   *   The alias to create. If not specified, the alias will be $table_$field
769
   *   unless $table is NULL. When adding formulae, it is recommended that an
770
   *   alias be used.
771
   * @param $params
772
   *   An array of parameters additional to the field that will control items
773
   *   such as aggregation functions and DISTINCT.
774
   *
775
   * @return $name
776
   *   The name that this field can be referred to as. Usually this is the alias.
777
   */
778
  function add_field($table, $field, $alias = '', $params = array()) {
779
    // We check for this specifically because it gets a special alias.
780
    if ($table == $this->base_table && $field == $this->base_field && empty($alias)) {
781
      $alias = $this->base_field;
782
    }
783

    
784
    if ($table && empty($this->table_queue[$table])) {
785
      $this->ensure_table($table);
786
    }
787

    
788
    if (!$alias && $table) {
789
      $alias = $table . '_' . $field;
790
    }
791

    
792
    // Make sure an alias is assigned
793
    $alias = $alias ? $alias : $field;
794

    
795
    // PostgreSQL truncates aliases to 63 characters: http://drupal.org/node/571548
796

    
797
    // We limit the length of the original alias up to 60 characters
798
    // to get a unique alias later if its have duplicates
799
    $alias = strtolower(substr($alias, 0, 60));
800

    
801
    // Create a field info array.
802
    $field_info = array(
803
      'field' => $field,
804
      'table' => $table,
805
      'alias' => $alias,
806
    ) + $params;
807

    
808
    // Test to see if the field is actually the same or not. Due to
809
    // differing parameters changing the aggregation function, we need
810
    // to do some automatic alias collision detection:
811
    $base = $alias;
812
    $counter = 0;
813
    while (!empty($this->fields[$alias]) && $this->fields[$alias] != $field_info) {
814
      $field_info['alias'] = $alias = $base . '_' . ++$counter;
815
    }
816

    
817
    if (empty($this->fields[$alias])) {
818
      $this->fields[$alias] = $field_info;
819
    }
820

    
821
    // Keep track of all aliases used.
822
    $this->field_aliases[$table][$field] = $alias;
823

    
824
    return $alias;
825
  }
826

    
827
  /**
828
   * Remove all fields that may've been added; primarily used for summary
829
   * mode where we're changing the query because we didn't get data we needed.
830
   */
831
  function clear_fields() {
832
    $this->fields = array();
833
  }
834

    
835
  /**
836
   * Add a simple WHERE clause to the query. The caller is responsible for
837
   * ensuring that all fields are fully qualified (TABLE.FIELD) and that
838
   * the table already exists in the query.
839
   *
840
   * @param $group
841
   *   The WHERE group to add these to; groups are used to create AND/OR
842
   *   sections. Groups cannot be nested. Use 0 as the default group.
843
   *   If the group does not yet exist it will be created as an AND group.
844
   * @param $field
845
   *   The name of the field to check.
846
   * @param $value
847
   *   The value to test the field against. In most cases, this is a scalar. For more
848
   *   complex options, it is an array. The meaning of each element in the array is
849
   *   dependent on the $operator.
850
   * @param $operator
851
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
852
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
853
   *   = otherwise. If $field is a string you have to use 'formula' here.
854
   *
855
   * The $field, $value and $operator arguments can also be passed in with a
856
   * single DatabaseCondition object, like this:
857
   * @code
858
   *   $this->query->add_where(
859
   *     $this->options['group'],
860
   *     db_or()
861
   *       ->condition($field, $value, 'NOT IN')
862
   *       ->condition($field, $value, 'IS NULL')
863
   *   );
864
   * @endcode
865
   *
866
   * @see QueryConditionInterface::condition()
867
   * @see DatabaseCondition
868
   */
869
  function add_where($group, $field, $value = NULL, $operator = NULL) {
870
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
871
    // the default group.
872
    if (empty($group)) {
873
      $group = 0;
874
    }
875

    
876
    // Check for a group.
877
    if (!isset($this->where[$group])) {
878
      $this->set_where_group('AND', $group);
879
    }
880

    
881
    $this->where[$group]['conditions'][] = array(
882
      'field' => $field,
883
      'value' => $value,
884
      'operator' => $operator,
885
    );
886
  }
887

    
888
  /**
889
   * Add a complex WHERE clause to the query.
890
   *
891
   * The caller is responsible for ensuring that all fields are fully qualified
892
   * (TABLE.FIELD) and that the table already exists in the query.
893
   * Internally the dbtng method "where" is used.
894
   *
895
   * @param $group
896
   *   The WHERE group to add these to; groups are used to create AND/OR
897
   *   sections. Groups cannot be nested. Use 0 as the default group.
898
   *   If the group does not yet exist it will be created as an AND group.
899
   * @param $snippet
900
   *   The snippet to check. This can be either a column or
901
   *   a complex expression like "UPPER(table.field) = 'value'"
902
   * @param $args
903
   *   An associative array of arguments.
904
   *
905
   * @see QueryConditionInterface::where()
906
   */
907
  function add_where_expression($group, $snippet, $args = array()) {
908
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
909
    // the default group.
910
    if (empty($group)) {
911
      $group = 0;
912
    }
913

    
914
    // Check for a group.
915
    if (!isset($this->where[$group])) {
916
      $this->set_where_group('AND', $group);
917
    }
918

    
919
    $this->where[$group]['conditions'][] = array(
920
      'field' => $snippet,
921
      'value' => $args,
922
      'operator' => 'formula',
923
    );
924
  }
925

    
926
  /**
927
   * Add a simple HAVING clause to the query.
928
   *
929
   * The caller is responsible for ensuring that all fields are fully qualified
930
   * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist in the query.
931
   * Internally the dbtng method "havingCondition" is used.
932
   *
933
   * @param $group
934
   *   The HAVING group to add these to; groups are used to create AND/OR
935
   *   sections. Groups cannot be nested. Use 0 as the default group.
936
   *   If the group does not yet exist it will be created as an AND group.
937
   * @param $field
938
   *   The name of the field to check.
939
   * @param $value
940
   *   The value to test the field against. In most cases, this is a scalar. For more
941
   *   complex options, it is an array. The meaning of each element in the array is
942
   *   dependent on the $operator.
943
   * @param $operator
944
   *   The comparison operator, such as =, <, or >=. It also accepts more complex
945
   *   options such as IN, LIKE, or BETWEEN. Defaults to IN if $value is an array
946
   *   = otherwise.  If $field is a string you have to use 'formula' here.
947
   *
948
   * @see SelectQueryInterface::havingCondition()
949
   */
950
  function add_having($group, $field, $value = NULL, $operator = NULL) {
951
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
952
    // the default group.
953
    if (empty($group)) {
954
      $group = 0;
955
    }
956

    
957
    // Check for a group.
958
    if (!isset($this->having[$group])) {
959
      $this->set_where_group('AND', $group, 'having');
960
    }
961

    
962
    // Add the clause and the args.
963
    $this->having[$group]['conditions'][] = array(
964
      'field' => $field,
965
      'value' => $value,
966
      'operator' => $operator,
967
    );
968
  }
969

    
970
  /**
971
   * Add a complex HAVING clause to the query.
972
   * The caller is responsible for ensuring that all fields are fully qualified
973
   * (TABLE.FIELD) and that the table and an appropriate GROUP BY already exist in the query.
974
   * Internally the dbtng method "having" is used.
975
   *
976
   * @param $group
977
   *   The HAVING group to add these to; groups are used to create AND/OR
978
   *   sections. Groups cannot be nested. Use 0 as the default group.
979
   *   If the group does not yet exist it will be created as an AND group.
980
   * @param $snippet
981
   *   The snippet to check. This can be either a column or
982
   *   a complex expression like "COUNT(table.field) > 3"
983
   * @param $args
984
   *   An associative array of arguments.
985
   *
986
   * @see QueryConditionInterface::having()
987
   */
988
  function add_having_expression($group, $snippet, $args = array()) {
989
    // Ensure all variants of 0 are actually 0. Thus '', 0 and NULL are all
990
    // the default group.
991
    if (empty($group)) {
992
      $group = 0;
993
    }
994

    
995
    // Check for a group.
996
    if (!isset($this->having[$group])) {
997
      $this->set_where_group('AND', $group, 'having');
998
    }
999

    
1000
    // Add the clause and the args.
1001
    $this->having[$group]['conditions'][] = array(
1002
      'field' => $snippet,
1003
      'value' => $args,
1004
      'operator' => 'formula',
1005
    );
1006
  }
1007

    
1008
  /**
1009
   * Add an ORDER BY clause to the query.
1010
   *
1011
   * @param $table
1012
   *   The table this field is part of. If a formula, enter NULL.
1013
   *   If you want to orderby random use "rand" as table and nothing else.
1014
   * @param $field
1015
   *   The field or formula to sort on. If already a field, enter NULL
1016
   *   and put in the alias.
1017
   * @param $order
1018
   *   Either ASC or DESC.
1019
   * @param $alias
1020
   *   The alias to add the field as. In SQL, all fields in the order by
1021
   *   must also be in the SELECT portion. If an $alias isn't specified
1022
   *   one will be generated for from the $field; however, if the
1023
   *   $field is a formula, this alias will likely fail.
1024
   * @param $params
1025
   *   Any params that should be passed through to the add_field.
1026
   */
1027
  function add_orderby($table, $field = NULL, $order = 'ASC', $alias = '', $params = array()) {
1028
    // Only ensure the table if it's not the special random key.
1029
    // @todo: Maybe it would make sense to just add a add_orderby_rand or something similar.
1030
    if ($table && $table != 'rand') {
1031
      $this->ensure_table($table);
1032
    }
1033

    
1034
    // Only fill out this aliasing if there is a table;
1035
    // otherwise we assume it is a formula.
1036
    if (!$alias && $table) {
1037
      $as = $table . '_' . $field;
1038
    }
1039
    else {
1040
      $as = $alias;
1041
    }
1042

    
1043
    if ($field) {
1044
      $as = $this->add_field($table, $field, $as, $params);
1045
    }
1046

    
1047
    $this->orderby[] = array(
1048
      'field' => $as,
1049
      'direction' => strtoupper($order)
1050
    );
1051

    
1052
	/**
1053
 	 * -- removing, this should be taken care of by field adding now.
1054
     * -- leaving commented because I am unsure.
1055
      // If grouping, all items in the order by must also be in the
1056
      // group by clause. Check $table to ensure that this is not a
1057
      // formula.
1058
      if ($this->groupby && $table) {
1059
        $this->add_groupby($as);
1060
      }
1061
    */
1062
  }
1063

    
1064
  /**
1065
   * Add a simple GROUP BY clause to the query. The caller is responsible
1066
   * for ensuring that the fields are fully qualified and the table is properly
1067
   * added.
1068
   */
1069
  function add_groupby($clause) {
1070
    // Only add it if it's not already in there.
1071
    if (!in_array($clause, $this->groupby)) {
1072
      $this->groupby[] = $clause;
1073
    }
1074
  }
1075

    
1076
  /**
1077
   * Returns the alias for the given field added to $table.
1078
   *
1079
   * @see views_plugin_query_default::add_field()
1080
   */
1081
  function get_field_alias($table_alias, $field) {
1082
    return isset($this->field_aliases[$table_alias][$field]) ? $this->field_aliases[$table_alias][$field] : FALSE;
1083
  }
1084

    
1085
  /**
1086
   * Adds a query tag to the sql object.
1087
   *
1088
   * @see SelectQuery::addTag()
1089
   */
1090
  function add_tag($tag) {
1091
    $this->tags[] = $tag;
1092
  }
1093

    
1094
  /**
1095
   * Generates a unique placeholder used in the db query.
1096
   */
1097
  function placeholder($base = 'views') {
1098
    static $placeholders = array();
1099
    if (!isset($placeholders[$base])) {
1100
      $placeholders[$base] = 0;
1101
      return ':' . $base;
1102
    }
1103
    else {
1104
      return ':' . $base . ++$placeholders[$base];
1105
    }
1106
  }
1107

    
1108
  /**
1109
   * Construct the "WHERE" or "HAVING" part of the query.
1110
   *
1111
   * As views has to wrap the conditions from arguments with AND, a special
1112
   * group is wrapped around all conditions. This special group has the ID 0.
1113
   * There is other code in filters which makes sure that the group IDs are
1114
   * higher than zero.
1115
   *
1116
   * @param $where
1117
   *   'where' or 'having'.
1118
   */
1119
  function build_condition($where = 'where') {
1120
    $has_condition = FALSE;
1121
    $has_arguments = FALSE;
1122
    $has_filter = FALSE;
1123

    
1124
    $main_group = db_and();
1125
    $filter_group = $this->group_operator == 'OR' ? db_or() : db_and();
1126

    
1127
    foreach ($this->$where as $group => $info) {
1128

    
1129
      if (!empty($info['conditions'])) {
1130
        $sub_group = $info['type'] == 'OR' ? db_or() : db_and();
1131
        foreach ($info['conditions'] as $key => $clause) {
1132
          // DBTNG doesn't support to add the same subquery twice to the main
1133
          // query and the count query, so clone the subquery to have two instances
1134
          // of the same object. - http://drupal.org/node/1112854
1135
          if (is_object($clause['value']) && $clause['value'] instanceof SelectQuery) {
1136
            $clause['value'] = clone $clause['value'];
1137
          }
1138
          if ($clause['operator'] == 'formula') {
1139
            $has_condition = TRUE;
1140
            $sub_group->where($clause['field'], $clause['value']);
1141
          }
1142
          else {
1143
            $has_condition = TRUE;
1144
            $sub_group->condition($clause['field'], $clause['value'], $clause['operator']);
1145
          }
1146
        }
1147

    
1148
        // Add the item to the filter group.
1149
        if ($group != 0) {
1150
          $has_filter = TRUE;
1151
          $filter_group->condition($sub_group);
1152
        }
1153
        else {
1154
          $has_arguments = TRUE;
1155
          $main_group->condition($sub_group);
1156
        }
1157
      }
1158
    }
1159

    
1160
    if ($has_filter) {
1161
      $main_group->condition($filter_group);
1162
    }
1163

    
1164
    if (!$has_arguments && $has_condition) {
1165
      return $filter_group;
1166
    }
1167
    if ($has_arguments && $has_condition) {
1168
      return $main_group;
1169
    }
1170
  }
1171

    
1172
  /**
1173
   * Build fields array.
1174
   */
1175
  function compile_fields($fields_array, $query) {
1176
    $non_aggregates = array();
1177
    foreach ($fields_array as $field) {
1178
      $string = '';
1179
      if (!empty($field['table'])) {
1180
        $string .= $field['table'] . '.';
1181
      }
1182
      $string .= $field['field'];
1183
      $fieldname = (!empty($field['alias']) ? $field['alias'] : $string);
1184

    
1185
      if (!empty($field['distinct'])) {
1186
        throw new Exception("Column-level distinct is not supported anymore.");
1187
      }
1188

    
1189
      if (!empty($field['count'])) {
1190
        // Retained for compatibility
1191
        $field['function'] = 'count';
1192
        // It seems there's no way to abstract the table+column reference
1193
        // without adding a field, aliasing, and then using the alias.
1194
      }
1195

    
1196
      if (!empty($field['function'])) {
1197
        $info = $this->get_aggregation_info();
1198
        if (!empty($info[$field['function']]['method']) && function_exists($info[$field['function']]['method'])) {
1199
          $string = $info[$field['function']]['method']($field['function'], $string);
1200
          $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
1201
          $query->addExpression($string, $fieldname, $placeholders);
1202
        }
1203

    
1204
        $this->has_aggregate = TRUE;
1205
      }
1206
      // This is a formula, using no tables.
1207
      elseif (empty($field['table'])) {
1208
        $non_aggregates[] = $fieldname;
1209
        $placeholders = !empty($field['placeholders']) ? $field['placeholders'] : array();
1210
        $query->addExpression($string, $fieldname, $placeholders);
1211
      }
1212

    
1213
      elseif ($this->distinct && !in_array($fieldname, $this->groupby)) {
1214
        // d7cx: This code was there, apparently needed for PostgreSQL
1215
        // $string = db_driver() == 'pgsql' ? "FIRST($string)" : $string;
1216
        $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
1217
      }
1218
      elseif (empty($field['aggregate'])) {
1219
        $non_aggregates[] = $fieldname;
1220
        $query->addField(!empty($field['table']) ? $field['table'] : $this->base_table, $field['field'], $fieldname);
1221
      }
1222

    
1223
      // @TODO Remove this old code.
1224
      if (!empty($field['distinct']) && empty($field['function'])) {
1225
        $distinct[] = $string;
1226
      }
1227
      else {
1228
        $fields[] = $string;
1229
      }
1230

    
1231
      if ($this->get_count_optimized) {
1232
        // We only want the first field in this case.
1233
        break;
1234
      }
1235
    }
1236
    return array(
1237
      $non_aggregates,
1238
    );
1239
  }
1240

    
1241
  /**
1242
   * Generate a query and a countquery from all of the information supplied
1243
   * to the object.
1244
   *
1245
   * @param $get_count
1246
   *   Provide a countquery if this is true, otherwise provide a normal query.
1247
   */
1248
  function query($get_count = FALSE) {
1249
    // Check query distinct value.
1250
    if (empty($this->no_distinct) && $this->distinct && !empty($this->fields)) {
1251
      if ($this->pure_distinct === FALSE){
1252
        $base_field_alias = $this->add_field($this->base_table, $this->base_field);
1253
        $this->add_groupby($base_field_alias);
1254
      }
1255
      $distinct = TRUE;
1256
    }
1257

    
1258
    /**
1259
     * An optimized count query includes just the base field instead of all the fields.
1260
     * Determine of this query qualifies by checking for a groupby or distinct.
1261
     */
1262
    $fields_array = $this->fields;
1263
    if ($get_count && !$this->groupby) {
1264
      foreach ($fields_array as $field) {
1265
        if (!empty($field['distinct']) || !empty($field['function'])) {
1266
          $this->get_count_optimized = FALSE;
1267
          break;
1268
        }
1269
      }
1270
    }
1271
    else {
1272
      $this->get_count_optimized = FALSE;
1273
    }
1274
    if (!isset($this->get_count_optimized)) {
1275
      $this->get_count_optimized = TRUE;
1276
    }
1277

    
1278
    $options = array();
1279
    $target = 'default';
1280
    $key = 'default';
1281
    // Detect an external database and set the
1282
    if (isset($this->view->base_database)) {
1283
      $key = $this->view->base_database;
1284
    }
1285

    
1286
    // Set the slave target if the slave option is set
1287
    if (!empty($this->options['slave'])) {
1288
      $target = 'slave';
1289
    }
1290

    
1291
    // Go ahead and build the query.
1292
    // db_select doesn't support to specify the key, so use getConnection directly.
1293
    $query = Database::getConnection($target, $key)
1294
      ->select($this->base_table, $this->base_table, $options)
1295
      ->addTag('views')
1296
      ->addTag('views_' . $this->view->name);
1297

    
1298
    // Add the tags added to the view itself.
1299
    foreach ($this->tags as $tag) {
1300
      $query->addTag($tag);
1301
    }
1302

    
1303
    if (!empty($distinct)) {
1304
      $query->distinct();
1305
    }
1306

    
1307
    $joins = $where = $having = $orderby = $groupby = '';
1308
    $fields = $distinct = array();
1309

    
1310
    // Add all the tables to the query via joins. We assume all LEFT joins.
1311
    foreach ($this->table_queue as $table) {
1312
      if (is_object($table['join'])) {
1313
        $table['join']->build_join($query, $table, $this);
1314
      }
1315
    }
1316

    
1317
    $this->has_aggregate = FALSE;
1318
    $non_aggregates = array();
1319

    
1320
    list($non_aggregates) = $this->compile_fields($fields_array, $query);
1321

    
1322
    if (count($this->having)) {
1323
      $this->has_aggregate = TRUE;
1324
    }
1325
    elseif (!$this->has_aggregate) {
1326
      // Allow 'GROUP BY' even no aggregation function has been set.
1327
      $this->has_aggregate = $this->view->display_handler->get_option('group_by');
1328
    }
1329
    if ($this->has_aggregate && (!empty($this->groupby) || !empty($non_aggregates))) {
1330
      $groupby = array_unique(array_merge($this->groupby, $non_aggregates));
1331
      foreach ($groupby as $field) {
1332
        $query->groupBy($field);
1333
      }
1334
      if (!empty($this->having) && $condition = $this->build_condition('having')) {
1335
        $query->havingCondition($condition);
1336
      }
1337
    }
1338

    
1339
    if (!$this->get_count_optimized) {
1340
      // we only add the orderby if we're not counting.
1341
      if ($this->orderby) {
1342
        foreach ($this->orderby as $order) {
1343
          if ($order['field'] == 'rand_') {
1344
            $query->orderRandom();
1345
          }
1346
          else {
1347
            $query->orderBy($order['field'], $order['direction']);
1348
          }
1349
        }
1350
      }
1351
    }
1352

    
1353
    if (!empty($this->where) && $condition = $this->build_condition('where')) {
1354
      $query->condition($condition);
1355
    }
1356

    
1357
    // Add a query comment.
1358
    if (!empty($this->options['query_comment'])) {
1359
      $query->comment($this->options['query_comment']);
1360
    }
1361

    
1362
    // Add the query tags.
1363
    if (!empty($this->options['query_tags'])) {
1364
      foreach ($this->options['query_tags'] as $tag) {
1365
        $query->addTag($tag);
1366
      }
1367
    }
1368

    
1369
    // Add all query substitutions as metadata.
1370
    $query->addMetaData('views_substitutions', module_invoke_all('views_query_substitutions', $this));
1371

    
1372
    if (!$get_count) {
1373
      if (!empty($this->limit) || !empty($this->offset)) {
1374
        // We can't have an offset without a limit, so provide a very large limit
1375
        // instead.
1376
        $limit  = intval(!empty($this->limit) ? $this->limit : 999999);
1377
        $offset = intval(!empty($this->offset) ? $this->offset : 0);
1378
        $query->range($offset, $limit);
1379
      }
1380
    }
1381

    
1382
    return $query;
1383
  }
1384

    
1385
  /**
1386
   * Get the arguments attached to the WHERE and HAVING clauses of this query.
1387
   */
1388
  function get_where_args() {
1389
    $args = array();
1390
    foreach ($this->where as $group => $where) {
1391
      $args = array_merge($args, $where['args']);
1392
    }
1393
    foreach ($this->having as $group => $having) {
1394
      $args = array_merge($args, $having['args']);
1395
    }
1396
    return $args;
1397
  }
1398

    
1399
  /**
1400
   * Let modules modify the query just prior to finalizing it.
1401
   */
1402
  function alter(&$view) {
1403
    foreach (module_implements('views_query_alter') as $module) {
1404
      $function = $module . '_views_query_alter';
1405
      $function($view, $this);
1406
    }
1407
  }
1408

    
1409
  /**
1410
   * Builds the necessary info to execute the query.
1411
   */
1412
  function build(&$view) {
1413
    // Make the query distinct if the option was set.
1414
    if (!empty($this->options['distinct'])) {
1415
      $this->set_distinct(TRUE, !empty($this->options['pure_distinct']));
1416
    }
1417

    
1418
    // Store the view in the object to be able to use it later.
1419
    $this->view = $view;
1420

    
1421
    $view->init_pager();
1422

    
1423
    // Let the pager modify the query to add limits.
1424
    $this->pager->query();
1425

    
1426
    $view->build_info['query'] = $this->query();
1427
    $view->build_info['count_query'] = $this->query(TRUE);
1428
  }
1429

    
1430
  /**
1431
   * Executes the query and fills the associated view object with according
1432
   * values.
1433
   *
1434
   * Values to set: $view->result, $view->total_rows, $view->execute_time,
1435
   * $view->current_page.
1436
   */
1437
  function execute(&$view) {
1438
    $external = FALSE; // Whether this query will run against an external database.
1439
    $query = $view->build_info['query'];
1440
    $count_query = $view->build_info['count_query'];
1441

    
1442
    $query->addMetaData('view', $view);
1443
    $count_query->addMetaData('view', $view);
1444

    
1445
    if (empty($this->options['disable_sql_rewrite'])) {
1446
      $base_table_data = views_fetch_data($this->base_table);
1447
      if (isset($base_table_data['table']['base']['access query tag'])) {
1448
        $access_tag = $base_table_data['table']['base']['access query tag'];
1449
        $query->addTag($access_tag);
1450
        $count_query->addTag($access_tag);
1451
      }
1452
    }
1453

    
1454
    $items = array();
1455
    if ($query) {
1456
      $additional_arguments = module_invoke_all('views_query_substitutions', $view);
1457

    
1458
      // Count queries must be run through the preExecute() method.
1459
      // If not, then hook_query_node_access_alter() may munge the count by
1460
      // adding a distinct against an empty query string
1461
      // (e.g. COUNT DISTINCT(1) ...) and no pager will return.
1462
      // See pager.inc > PagerDefault::execute()
1463
      // http://api.drupal.org/api/drupal/includes--pager.inc/function/PagerDefault::execute/7
1464
      // See http://drupal.org/node/1046170.
1465
      $count_query->preExecute();
1466

    
1467
      // Build the count query.
1468
      $count_query = $count_query->countQuery();
1469

    
1470
      // Add additional arguments as a fake condition.
1471
      // XXX: this doesn't work... because PDO mandates that all bound arguments
1472
      // are used on the query. TODO: Find a better way to do this.
1473
      if (!empty($additional_arguments)) {
1474
        // $query->where('1 = 1', $additional_arguments);
1475
        // $count_query->where('1 = 1', $additional_arguments);
1476
      }
1477

    
1478
      $start = microtime(TRUE);
1479

    
1480

    
1481
      try {
1482
        if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
1483
          $this->pager->execute_count_query($count_query);
1484
        }
1485

    
1486
        $this->pager->pre_execute($query);
1487

    
1488
        $result = $query->execute();
1489

    
1490
        $view->result = array();
1491
        foreach ($result as $item) {
1492
          $view->result[] = $item;
1493
        }
1494

    
1495
        $this->pager->post_execute($view->result);
1496

    
1497
        if ($this->pager->use_count_query() || !empty($view->get_total_rows)) {
1498
          $view->total_rows = $this->pager->get_total_items();
1499
        }
1500
      }
1501
      catch (Exception $e) {
1502
        $view->result = array();
1503
        if (!empty($view->live_preview)) {
1504
          drupal_set_message($e->getMessage(), 'error');
1505
        }
1506
        else {
1507
          vpr('Exception in @human_name[@view_name]: @message', array('@human_name' => $view->human_name, '@view_name' => $view->name, '@message' => $e->getMessage()));
1508
        }
1509
      }
1510

    
1511
    }
1512
    else {
1513
      $start = microtime(TRUE);
1514
    }
1515
    $view->execute_time = microtime(TRUE) - $start;
1516
  }
1517

    
1518
  function add_signature(&$view) {
1519
    $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
1520
  }
1521

    
1522
  function get_aggregation_info() {
1523
    // @todo -- need a way to get database specific and customized aggregation
1524
    // functions into here.
1525
    return array(
1526
      'group' => array(
1527
        'title' => t('Group results together'),
1528
        'is aggregate' => FALSE,
1529
      ),
1530
      'count' => array(
1531
        'title' => t('Count'),
1532
        'method' => 'views_query_default_aggregation_method_simple',
1533
        'handler' => array(
1534
          'argument' => 'views_handler_argument_group_by_numeric',
1535
          'field' => 'views_handler_field_numeric',
1536
          'filter' => 'views_handler_filter_group_by_numeric',
1537
          'sort' => 'views_handler_sort_group_by_numeric',
1538
        ),
1539
      ),
1540
      'count_distinct' => array(
1541
        'title' => t('Count DISTINCT'),
1542
        'method' => 'views_query_default_aggregation_method_distinct',
1543
        'handler' => array(
1544
          'argument' => 'views_handler_argument_group_by_numeric',
1545
          'field' => 'views_handler_field_numeric',
1546
          'filter' => 'views_handler_filter_group_by_numeric',
1547
          'sort' => 'views_handler_sort_group_by_numeric',
1548
        ),
1549
      ),
1550
      'sum' => array(
1551
        'title' => t('Sum'),
1552
        'method' => 'views_query_default_aggregation_method_simple',
1553
        'handler' => array(
1554
          'argument' => 'views_handler_argument_group_by_numeric',
1555
          'filter' => 'views_handler_filter_group_by_numeric',
1556
          'sort' => 'views_handler_sort_group_by_numeric',
1557
        ),
1558
      ),
1559
      'avg' => array(
1560
        'title' => t('Average'),
1561
        'method' => 'views_query_default_aggregation_method_simple',
1562
        'handler' => array(
1563
          'argument' => 'views_handler_argument_group_by_numeric',
1564
          'filter' => 'views_handler_filter_group_by_numeric',
1565
          'sort' => 'views_handler_sort_group_by_numeric',
1566
        ),
1567
      ),
1568
      'min' => array(
1569
        'title' => t('Minimum'),
1570
        'method' => 'views_query_default_aggregation_method_simple',
1571
        'handler' => array(
1572
          'argument' => 'views_handler_argument_group_by_numeric',
1573
          'filter' => 'views_handler_filter_group_by_numeric',
1574
          'sort' => 'views_handler_sort_group_by_numeric',
1575
        ),
1576
      ),
1577
      'max' => array(
1578
        'title' => t('Maximum'),
1579
        'method' => 'views_query_default_aggregation_method_simple',
1580
        'handler' => array(
1581
          'argument' => 'views_handler_argument_group_by_numeric',
1582
          'filter' => 'views_handler_filter_group_by_numeric',
1583
          'sort' => 'views_handler_sort_group_by_numeric',
1584
        ),
1585
      ),
1586
      'stddev_pop' => array(
1587
        'title' => t('Standard deviation'),
1588
        'method' => 'views_query_default_aggregation_method_simple',
1589
        'handler' => array(
1590
          'argument' => 'views_handler_argument_group_by_numeric',
1591
          'filter' => 'views_handler_filter_group_by_numeric',
1592
          'sort' => 'views_handler_sort_group_by_numeric',
1593
        ),
1594
      )
1595
    );
1596
  }
1597

    
1598
  /**
1599
   * Returns the according entity objects for the given query results.
1600
   *
1601
   */
1602
  function get_result_entities($results, $relationship = NULL) {
1603
    $base_table = $this->base_table;
1604
    $base_table_alias = $base_table;
1605

    
1606
    if (!empty($relationship)) {
1607
      foreach ($this->view->relationship as $current) {
1608
        if ($current->alias == $relationship) {
1609
          $base_table = $current->definition['base'];
1610
          $base_table_alias = $relationship;
1611
          break;
1612
        }
1613
      }
1614
    }
1615
    $table_data = views_fetch_data($base_table);
1616

    
1617
    // Bail out if the table has not specified the according entity-type.
1618
    if (!isset($table_data['table']['entity type'])) {
1619
      return FALSE;
1620
    }
1621
    $entity_type = $table_data['table']['entity type'];
1622
    $info = entity_get_info($entity_type);
1623
    $is_revision = !empty($table_data['table']['revision']);
1624
    $id_alias = $this->get_field_alias($base_table_alias, $info['entity keys'][$is_revision ? 'revision' : 'id']);
1625

    
1626
    // Assemble the ids of the entities to load.
1627
    $ids = array();
1628
    foreach ($results as $key => $result) {
1629
      if (isset($result->$id_alias)) {
1630
        $ids[$key] = $result->$id_alias;
1631
      }
1632
    }
1633

    
1634
    if (!$is_revision) {
1635
      $entities = entity_load($entity_type, $ids);
1636

    
1637
      // Re-key the array by row-index.
1638
      $result = array();
1639
      foreach ($ids as $key => $id) {
1640
        $result[$key] = isset($entities[$id]) ? $entities[$id] : FALSE;
1641
      }
1642
    }
1643
    else {
1644
      // There's no way in core to load revisions in bulk.
1645
      $result = array();
1646
      foreach ($ids as $key => $id) {
1647
        // Nodes can be dealt with in core.
1648
        if ($entity_type == 'node') {
1649
          $result[$key] = node_load(NULL, $id);
1650
        }
1651
        // Otherwise see if entity is enabled.
1652
        elseif (module_exists('entity')) {
1653
          $result[$key] = entity_revision_load($entity_type, $id);
1654
        }
1655
        else {
1656
          // Otherwise this isn't supported.
1657
          watchdog('views', 'Attempt to load a revision on an unsupported entity type @entity_type.', array('@entity_type' => $entity_type), WATCHDOG_WARNING);
1658
        }
1659
      }
1660
    }
1661

    
1662
    return array($entity_type, $result);
1663
  }
1664
}
1665

    
1666
function views_query_default_aggregation_method_simple($group_type, $field) {
1667
  return strtoupper($group_type) . '(' . $field . ')';
1668
}
1669

    
1670
function views_query_default_aggregation_method_distinct($group_type, $field) {
1671
  $group_type = str_replace('_distinct', '', $group_type);
1672
  return strtoupper($group_type) . '(DISTINCT ' . $field . ')';
1673
}
1674

    
1675
/**
1676
 * Validation callback for query tags.
1677
 */
1678
function views_element_validate_tags($element, &$form_state) {
1679
  $values = array_map('trim', explode(',', $element['#value']));
1680
  foreach ($values as $value) {
1681
    if (preg_match("/[^a-z_]/", $value)) {
1682
      form_error($element, t('The query tags may only contain lower-case alphabetical characters and underscores.'));
1683
      return;
1684
    }
1685
  }
1686
}