Projet

Général

Profil

Paste
Télécharger (74,3 ko) Statistiques
| Branche: | Révision:

root / htmltest / sites / all / modules / views / includes / view.inc @ a5572547

1 85ad3d82 Assos Assos
<?php
2
3
/**
4
 * @file
5
 * Provides the view object type and associated methods.
6
 */
7
8
/**
9
 * @defgroup views_objects Objects that represent a View or part of a view
10
 * @{
11
 * These objects are the core of Views do the bulk of the direction and
12
 * storing of data. All database activity is in these objects.
13
 */
14
15
/**
16
 * An object to contain all of the data to generate a view, plus the member
17
 * functions to build the view query, execute the query and render the output.
18
 */
19
class view extends views_db_object {
20
  var $db_table = 'views_view';
21
  var $base_table = 'node';
22
  var $base_field = 'nid';
23
24
  /**
25
   * The name of the view.
26
   *
27
   * @var string
28
   */
29
  var $name = "";
30
31
  /**
32
   * The id of the view, which is used only for views in the database.
33
   *
34
   * @var number
35
   */
36
  var $vid;
37
38
  /**
39
   * The description of the view, which is used only in the interface.
40
   *
41
   * @var string
42
   */
43
  var $description;
44
45
  /**
46
   * The "tags" of a view.
47
   * The tags are stored as a single string, though it is used as multiple tags
48
   * for example in the views overview.
49
   *
50
   * @var string
51
   */
52
  var $tag;
53
54
  /**
55
   * The human readable name of the view.
56
   *
57
   * @var string
58
   */
59
  var $human_name;
60
61
  /**
62
   * The core version the view was created for.
63
   * @var int
64
   */
65
  var $core;
66
67
  /**
68
   * The views-api version this view was created by.
69
   *
70
   * Some examples of the variable are 3.0 or 3.0-alpha1
71
   *
72
   * @var string
73
   */
74
  var $api_version;
75
76
  /**
77
   * Is the view disabled.
78
   *
79
   * This value is used for exported view, to provide some default views which aren't enabled.
80
   *
81
   * @var bool
82
   */
83
  var $disabled;
84
85
  // State variables
86
  var $built = FALSE;
87
  var $executed = FALSE;
88
  var $editing = FALSE;
89
90
  var $args = array();
91
  var $build_info = array();
92
93
  var $use_ajax = FALSE;
94
95
  /**
96
   * Where the results of a query will go.
97
   *
98
   * The array must use a numeric index starting at 0.
99
   *
100
   * @var array
101
   */
102
  var $result = array();
103
104
  // May be used to override the current pager info.
105
  var $current_page = NULL;
106
  var $items_per_page = NULL;
107
  var $offset = NULL;
108
  var $total_rows = NULL;
109
110
  // Places to put attached renderings:
111
  var $attachment_before = '';
112
  var $attachment_after = '';
113
114
  // Exposed widget input
115
  var $exposed_data = array();
116
  var $exposed_input = array();
117
  // Exposed widget input directly from the $form_state['values'].
118
  var $exposed_raw_input = array();
119
120
  // Used to store views that were previously running if we recurse.
121
  var $old_view = array();
122
123
  // To avoid recursion in views embedded into areas.
124
  var $parent_views = array();
125
126
  // Is the current stored view runned as an attachment to another view.
127
  var $is_attachment = NULL;
128
129
  // Stores the next steps of form items to handle.
130
  // It's an array of stack items, which contain the form id, the type of form,
131
  // the view, the display and some additional arguments.
132
  // @see views_ui_add_form_to_stack()
133
  // var $stack;
134
135
  /**
136
   * Identifier of the current display.
137
   *
138
   * @var string
139
   */
140
  var $current_display;
141
142
  /**
143
   * Where the $query object will reside:
144
   *
145
   * @var views_plugin_query
146
   */
147
  var $query = NULL;
148
149
   /**
150
   * The current used display plugin.
151
   *
152
   * @var views_plugin_display
153
   */
154
  var $display_handler;
155
156
  /**
157
   * Stores all display handlers of this view.
158
   *
159
   * @var array[views_display]
160
   */
161
  var $display;
162
163
  /**
164
   * The current used style plugin.
165
   *
166
   * @var views_plugin_style
167
   */
168
   var $style_plugin;
169
170
  /**
171
   * Stored the changed options of the style plugin.
172
   *
173
   * @deprecated Better use $view->style_plugin->options
174
   * @var array
175
   */
176
  var $style_options;
177
178
  /**
179
   * Stores the current active row while rendering.
180
   *
181
   * @var int
182
   */
183
  var $row_index;
184
185
   /**
186
   * Allow to override the url of the current view.
187
   *
188
   * @var string
189
   */
190
  var $override_url = NULL;
191
192
  /**
193
   * Allow to override the path used for generated urls.
194
   *
195
   * @var string
196
   */
197
  var $override_path = NULL;
198
199
  /**
200
   * Allow to override the used database which is used for this query.
201
   */
202
  var $base_database = NULL;
203
204
  /**
205
   * Here comes a list of the possible handler which are active on this view.
206
   */
207
208
  /**
209
   * Stores the field handlers which are initialized on this view.
210
   * @var array[views_handler_field]
211
   */
212
  var $field;
213
214
  /**
215
   * Stores the argument handlers which are initialized on this view.
216
   * @var array[views_handler_argument]
217
   */
218
  var $argument;
219
220
  /**
221
   * Stores the sort handlers which are initialized on this view.
222
   * @var array[views_handler_sort]
223
   */
224
  var $sort;
225
226
  /**
227
   * Stores the filter handlers which are initialized on this view.
228
   * @var array[views_handler_filter]
229
   */
230
  var $filter;
231
232
  /**
233
   * Stores the relationship handlers which are initialized on this view.
234
   * @var array[views_handler_relationship]
235
   */
236
  var $relationship;
237
238
  /**
239
   * Stores the area handlers for the header which are initialized on this view.
240
   * @var array[views_handler_area]
241
   */
242
  var $header;
243
244
  /**
245
   * Stores the area handlers for the footer which are initialized on this view.
246
   * @var array[views_handler_area]
247
   */
248
  var $footer;
249
250
  /**
251
   * Stores the area handlers for the empty text which are initialized on this view.
252
   * @var array[views_handler_area]
253
   */
254
  var $empty;
255
256
  /**
257
   * Constructor
258
   */
259
  function __construct() {
260
    parent::init();
261
    // Make sure all of our sub objects are arrays.
262
    foreach ($this->db_objects() as $object) {
263
      $this->$object = array();
264
    }
265
  }
266
267
  /**
268
   * Perform automatic updates when loading or importing a view.
269
   *
270
   * Over time, some things about Views or Drupal data has changed.
271
   * this attempts to do some automatic updates that must happen
272
   * to ensure older views will at least try to work.
273
   */
274
  function update() {
275
    // When views are converted automatically the base_table should be renamed
276
    // to have a working query.
277
    $this->base_table = views_move_table($this->base_table);
278
  }
279
280
281
  /**
282
   * Returns a list of the sub-object types used by this view. These types are
283
   * stored on the display, and are used in the build process.
284
   */
285
  function display_objects() {
286
    return array('argument', 'field', 'sort', 'filter', 'relationship', 'header', 'footer', 'empty');
287
  }
288
289
  /**
290
   * Returns the complete list of dependent objects in a view, for the purpose
291
   * of initialization and loading/saving to/from the database.
292
   */
293
  static function db_objects() {
294
    return array('display');
295
  }
296
297
  /**
298
   * Set the arguments that come to this view. Usually from the URL
299
   * but possibly from elsewhere.
300
   */
301
  function set_arguments($args) {
302
    $this->args = $args;
303
  }
304
305
  /**
306
   * Change/Set the current page for the pager.
307
   */
308
  function set_current_page($page) {
309
    $this->current_page = $page;
310
311
    // If the pager is already initialized, pass it through to the pager.
312
    if (!empty($this->query->pager)) {
313
      return $this->query->pager->set_current_page($page);
314
    }
315
316
  }
317
318
  /**
319
   * Get the current page from the pager.
320
   */
321
  function get_current_page() {
322
    // If the pager is already initialized, pass it through to the pager.
323
    if (!empty($this->query->pager)) {
324
      return $this->query->pager->get_current_page();
325
    }
326
327
    if (isset($this->current_page)) {
328
      return $this->current_page;
329
    }
330
  }
331
332
  /**
333
   * Get the items per page from the pager.
334
   */
335
  function get_items_per_page() {
336
    // If the pager is already initialized, pass it through to the pager.
337
    if (!empty($this->query->pager)) {
338
      return $this->query->pager->get_items_per_page();
339
    }
340
341
    if (isset($this->items_per_page)) {
342
      return $this->items_per_page;
343
    }
344
  }
345
346
  /**
347
   * Set the items per page on the pager.
348
   */
349
  function set_items_per_page($items_per_page) {
350
    $this->items_per_page = $items_per_page;
351
352
    // If the pager is already initialized, pass it through to the pager.
353
    if (!empty($this->query->pager)) {
354
      $this->query->pager->set_items_per_page($items_per_page);
355
    }
356
  }
357
358
  /**
359
   * Get the pager offset from the pager.
360
   */
361
  function get_offset() {
362
    // If the pager is already initialized, pass it through to the pager.
363
    if (!empty($this->query->pager)) {
364
      return $this->query->pager->get_offset();
365
    }
366
367
    if (isset($this->offset)) {
368
      return $this->offset;
369
    }
370
  }
371
372
  /**
373
   * Set the offset on the pager.
374
   */
375
  function set_offset($offset) {
376
    $this->offset = $offset;
377
378
    // If the pager is already initialized, pass it through to the pager.
379
    if (!empty($this->query->pager)) {
380
      $this->query->pager->set_offset($offset);
381
    }
382
  }
383
384
  /**
385
   * Determine if the pager actually uses a pager.
386
   */
387
  function use_pager() {
388
    if (!empty($this->query->pager)) {
389
      return $this->query->pager->use_pager();
390
    }
391
  }
392
393
  /**
394
   * Whether or not AJAX should be used. If AJAX is used, paging,
395
   * tablesorting and exposed filters will be fetched via an AJAX call
396
   * rather than a page refresh.
397
   */
398
  function set_use_ajax($use_ajax) {
399
    $this->use_ajax = $use_ajax;
400
  }
401
402
  /**
403
   * Set the exposed filters input to an array. If unset they will be taken
404
   * from $_GET when the time comes.
405
   */
406
  function set_exposed_input($filters) {
407
    $this->exposed_input = $filters;
408
  }
409
410
  /**
411
   * Figure out what the exposed input for this view is.
412
   */
413
  function get_exposed_input() {
414
    // Fill our input either from $_GET or from something previously set on the
415
    // view.
416
    if (empty($this->exposed_input)) {
417
      $this->exposed_input = $_GET;
418
      // unset items that are definitely not our input:
419
      foreach (array('page', 'q') as $key) {
420
        if (isset($this->exposed_input[$key])) {
421
          unset($this->exposed_input[$key]);
422
        }
423
      }
424
425
      // If we have no input at all, check for remembered input via session.
426
427
      // If filters are not overridden, store the 'remember' settings on the
428
      // default display. If they are, store them on this display. This way,
429
      // multiple displays in the same view can share the same filters and
430
      // remember settings.
431
      $display_id = ($this->display_handler->is_defaulted('filters')) ? 'default' : $this->current_display;
432
433
      if (empty($this->exposed_input) && !empty($_SESSION['views'][$this->name][$display_id])) {
434
        $this->exposed_input = $_SESSION['views'][$this->name][$display_id];
435
      }
436
    }
437
438
    return $this->exposed_input;
439
  }
440
441
  /**
442
   * Set the display for this view and initialize the display handler.
443
   */
444
  function init_display($reset = FALSE) {
445
    // The default display is always the first one in the list.
446
    if (isset($this->current_display)) {
447
      return TRUE;
448
    }
449
450
    // Instantiate all displays
451
    foreach (array_keys($this->display) as $id) {
452
      // Correct for shallow cloning
453
      // Often we'll have a cloned view so we don't mess up each other's
454
      // displays, but the clone is pretty shallow and doesn't necessarily
455
      // clone the displays. We can tell this by looking to see if a handler
456
      // has already been set; if it has, but $this->current_display is not
457
      // set, then something is dreadfully wrong.
458
      if (!empty($this->display[$id]->handler)) {
459
        $this->display[$id] = clone $this->display[$id];
460
        unset($this->display[$id]->handler);
461
      }
462
      $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
463
      if (!empty($this->display[$id]->handler)) {
464
        $this->display[$id]->handler->localization_keys = array($id);
465
        // Initialize the new display handler with data.
466
        $this->display[$id]->handler->init($this, $this->display[$id]);
467
        // If this is NOT the default display handler, let it know which is
468
        // since it may well utilize some data from the default.
469
        // This assumes that the 'default' handler is always first. It always
470
        // is. Make sure of it.
471
        if ($id != 'default') {
472
          $this->display[$id]->handler->default_display = &$this->display['default']->handler;
473
        }
474
      }
475
    }
476
477
    $this->current_display = 'default';
478
    $this->display_handler = &$this->display['default']->handler;
479
480
    return TRUE;
481
  }
482
483
  /**
484
   * Get the first display that is accessible to the user.
485
   *
486
   * @param $displays
487
   *   Either a single display id or an array of display ids.
488
   */
489
  function choose_display($displays) {
490
    if (!is_array($displays)) {
491
      return $displays;
492
    }
493
494
    $this->init_display();
495
496
    foreach ($displays as $display_id) {
497
      if ($this->display[$display_id]->handler->access()) {
498
        return $display_id;
499
      }
500
    }
501
502
    return 'default';
503
  }
504
505
  /**
506
   * Set the display as current.
507
   *
508
   * @param $display_id
509
   *   The id of the display to mark as current.
510
   */
511
  function set_display($display_id = NULL) {
512
    // If we have not already initialized the display, do so. But be careful.
513
    if (empty($this->current_display)) {
514
      $this->init_display();
515
516
      // If handlers were not initialized, and no argument was sent, set up
517
      // to the default display.
518
      if (empty($display_id)) {
519
        $display_id = 'default';
520
      }
521
    }
522
523
    $display_id = $this->choose_display($display_id);
524
525
    // If no display id sent in and one wasn't chosen above, we're finished.
526
    if (empty($display_id)) {
527
      return FALSE;
528
    }
529
530
    // Ensure the requested display exists.
531
    if (empty($this->display[$display_id])) {
532
      $display_id = 'default';
533
      if (empty($this->display[$display_id])) {
534
        vpr('set_display() called with invalid display id @display.', array('@display' => $display_id));
535
        return FALSE;
536
      }
537
    }
538
539
    // Set the current display.
540
    $this->current_display = $display_id;
541
542
    // Ensure requested display has a working handler.
543
    if (empty($this->display[$display_id]->handler)) {
544
      return FALSE;
545
    }
546
547
    // Set a shortcut
548
    $this->display_handler = &$this->display[$display_id]->handler;
549
550
    return TRUE;
551
  }
552
553
  /**
554
   * Find and initialize the style plugin.
555
   *
556
   * Note that arguments may have changed which style plugin we use, so
557
   * check the view object first, then ask the display handler.
558
   */
559
  function init_style() {
560
    if (isset($this->style_plugin)) {
561
      return is_object($this->style_plugin);
562
    }
563
564
    if (!isset($this->plugin_name)) {
565
      $this->plugin_name = $this->display_handler->get_option('style_plugin');
566
      $this->style_options = $this->display_handler->get_option('style_options');
567
    }
568
569
    $this->style_plugin = views_get_plugin('style', $this->plugin_name);
570
571
    if (empty($this->style_plugin)) {
572
      return FALSE;
573
    }
574
575
    // init the new style handler with data.
576
    $this->style_plugin->init($this, $this->display[$this->current_display], $this->style_options);
577
    return TRUE;
578
  }
579
580
  /**
581
   * Attempt to discover if the view has handlers missing relationships.
582
   *
583
   * This will try to add relationships automatically if it can, and will
584
   * remove the handlers if it cannot.
585
   */
586
  function fix_missing_relationships() {
587
    if (isset($this->relationships_fixed)) {
588
      return;
589
    }
590
591
    $this->relationships_fixed = TRUE;
592
593
    // Go through all of our handler types and test them to see if they
594
    // are missing relationships. Missing relationships can cause fatally
595
    // broken Views.
596
    $base_tables = array(
597
      $this->base_table => TRUE,
598
      '#global' => TRUE,
599
    );
600
601
    // For each relationship we have, make sure we mark the base it provides as
602
    // available.
603
    foreach ($this->display_handler->get_option('relationships') as $id => $options) {
604
      $options['table'] = views_move_table($options['table']);
605
      $data = views_fetch_data($options['table'], FALSE);
606
      if (isset($data[$options['field']]['relationship']['base'])) {
607
        $base_tables[$data[$options['field']]['relationship']['base']] = TRUE;
608
      }
609
    }
610
611
    $base_tables = array_keys($base_tables);
612
    $missing_base_tables = array();
613
614
    $types = views_object_types();
615
    foreach ($types as $key => $info) {
616
      foreach ($this->display_handler->get_option($info['plural']) as $id => $options) {
617
        $options['table'] = views_move_table($options['table']);
618
        $data = views_fetch_data($options['table'], FALSE);
619
620
        $valid_bases = array($options['table']);
621
        if (isset($data['table']['join'])) {
622
          $valid_bases = array_merge($valid_bases, array_keys($data['table']['join']));
623
        }
624
625
        // If the base table is missing, record it so we can try to fix it.
626
        if (!array_intersect($valid_bases, $base_tables)) {
627
          $missing_base_tables[$options['table']][] = array('type' => $key, 'id' => $id);
628
        }
629
      }
630
    }
631
632
    if (!empty($missing_base_tables)) {
633
      // This will change handlers, so make sure any existing handlers get
634
      // tossed.
635
      $this->display_handler->handlers = array();
636
      $this->relationships_changed = TRUE;
637
      $this->changed = TRUE;
638
639
      // Try to fix it.
640
      foreach ($missing_base_tables as $table => $handlers) {
641
        $data = views_fetch_data($table);
642
        $relationship = NULL;
643
644
        // Does the missing base table have a default relationship we can
645
        // throw in?
646
        if (isset($data['table']['default_relationship'][$this->base_table])) {
647
          // Create the relationship.
648
          $info = $data['table']['default_relationship'][$this->base_table];
649
650
          $relationship_options = isset($info['options']) ? $info['options'] : array();
651
          $relationship = $this->add_item($this->current_display, 'relationship', $info['table'], $info['field'], $relationship_options);
652
        }
653
        foreach ($handlers as $handler) {
654
          $options = $this->display_handler->get_option($types[$handler['type']]['plural']);
655
          if ($relationship) {
656
            $options[$handler['id']]['relationship'] = $relationship;
657
          }
658
          else {
659
            unset($options[$handler['id']]);
660
          }
661
          $this->display_handler->set_option($types[$handler['type']]['plural'], $options);
662
        }
663
      }
664
    }
665
  }
666
667
  /**
668
   * Acquire and attach all of the handlers.
669
   */
670
  function init_handlers() {
671
    if (empty($this->inited)) {
672
      $this->fix_missing_relationships();
673
      foreach (views_object_types() as $key => $info) {
674
        $this->_init_handler($key, $info);
675
      }
676
      $this->inited = TRUE;
677
    }
678
  }
679
680
  /**
681
   * Initialize the pager
682
   *
683
   * Like style initialization, pager initialization is held until late
684
   * to allow for overrides.
685
   */
686
  function init_pager() {
687
    if (empty($this->query->pager)) {
688
      $this->query->pager = $this->display_handler->get_plugin('pager');
689
690
      if ($this->query->pager->use_pager()) {
691
        $this->query->pager->set_current_page($this->current_page);
692
      }
693
694
      // These overrides may have been set earlier via $view->set_*
695
      // functions.
696
      if (isset($this->items_per_page)) {
697
        $this->query->pager->set_items_per_page($this->items_per_page);
698
      }
699
700
      if (isset($this->offset)) {
701
        $this->query->pager->set_offset($this->offset);
702
      }
703
    }
704
  }
705
706
  /**
707
   * Create a list of base tables eligible for this view. Used primarily
708
   * for the UI. Display must be already initialized.
709
   */
710
  function get_base_tables() {
711
    $base_tables = array(
712
      $this->base_table => TRUE,
713
      '#global' => TRUE,
714
    );
715
716
    foreach ($this->display_handler->get_handlers('relationship') as $handler) {
717
      $base_tables[$handler->definition['base']] = TRUE;
718
    }
719
    return $base_tables;
720
  }
721
722
  /**
723
   * Run the pre_query() on all active handlers.
724
   */
725
  function _pre_query() {
726
    foreach (views_object_types() as $key => $info) {
727
      $handlers = &$this->$key;
728
      $position = 0;
729
      foreach ($handlers as $id => $handler) {
730
        $handlers[$id]->position = $position;
731
        $handlers[$id]->pre_query();
732
        $position++;
733
      }
734
    }
735
  }
736
737
  /**
738
   * Run the post_execute() on all active handlers.
739
   */
740
  function _post_execute() {
741
    foreach (views_object_types() as $key => $info) {
742
      $handlers = &$this->$key;
743
      foreach ($handlers as $id => $handler) {
744
        $handlers[$id]->post_execute($this->result);
745
      }
746
    }
747
  }
748
749
  /**
750
   * Attach all of the handlers for each type.
751
   *
752
   * @param $key
753
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'
754
   * @param $info
755
   *   The $info from views_object_types for this object.
756
   */
757
  function _init_handler($key, $info) {
758
    // Load the requested items from the display onto the object.
759
    $this->$key = $this->display_handler->get_handlers($key);
760
761
    // This reference deals with difficult PHP indirection.
762
    $handlers = &$this->$key;
763
764
    // Run through and test for accessibility.
765
    foreach ($handlers as $id => $handler) {
766
      if (!$handler->access()) {
767
        unset($handlers[$id]);
768
      }
769
    }
770
  }
771
772
  /**
773
   * Build all the arguments.
774
   */
775
  function _build_arguments() {
776
    // Initially, we want to build sorts and fields. This can change, though,
777
    // if we get a summary view.
778
    if (empty($this->argument)) {
779
      return TRUE;
780
    }
781
782
    // build arguments.
783
    $position = -1;
784
785
    // Create a title for use in the breadcrumb trail.
786
    $title = $this->display_handler->get_option('title');
787
788
    $this->build_info['breadcrumb'] = array();
789
    $breadcrumb_args = array();
790
    $substitutions = array();
791
792
    $status = TRUE;
793
794
    // Iterate through each argument and process.
795
    foreach ($this->argument as $id => $arg) {
796
      $position++;
797
      $argument = &$this->argument[$id];
798
799
      if ($argument->broken()) {
800
        continue;
801
      }
802
803
      $argument->set_relationship();
804
805
      $arg = isset($this->args[$position]) ? $this->args[$position] : NULL;
806
      $argument->position = $position;
807
808
      if (isset($arg) || $argument->has_default_argument()) {
809
        if (!isset($arg)) {
810
          $arg = $argument->get_default_argument();
811
          // make sure default args get put back.
812
          if (isset($arg)) {
813
            $this->args[$position] = $arg;
814
          }
815
          // remember that this argument was computed, not passed on the URL.
816
          $argument->is_default = TRUE;
817
        }
818
819
        // Set the argument, which will also validate that the argument can be set.
820
        if (!$argument->set_argument($arg)) {
821
          $status = $argument->validate_fail($arg);
822
          break;
823
        }
824
825
        if ($argument->is_exception()) {
826
          $arg_title = $argument->exception_title();
827
        }
828
        else {
829
          $arg_title = $argument->get_title();
830
          $argument->query($this->display_handler->use_group_by());
831
        }
832
833
        // Add this argument's substitution
834
        $substitutions['%' . ($position + 1)] = $arg_title;
835
        $substitutions['!' . ($position + 1)] = strip_tags(decode_entities($arg));
836
837
        // Since we're really generating the breadcrumb for the item above us,
838
        // check the default action of this argument.
839
        if ($this->display_handler->uses_breadcrumb() && $argument->uses_breadcrumb()) {
840
          $path = $this->get_url($breadcrumb_args);
841
          if (strpos($path, '%') === FALSE) {
842
            if (!empty($argument->options['breadcrumb_enable']) && !empty($argument->options['breadcrumb'])) {
843
              $breadcrumb = $argument->options['breadcrumb'];
844
            }
845
            else {
846
              $breadcrumb = $title;
847
            }
848
            $this->build_info['breadcrumb'][$path] = str_replace(array_keys($substitutions), $substitutions, $breadcrumb);
849
          }
850
        }
851
852
        // Allow the argument to muck with this breadcrumb.
853
        $argument->set_breadcrumb($this->build_info['breadcrumb']);
854
855
        // Test to see if we should use this argument's title
856
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
857
          $title = $argument->options['title'];
858
        }
859
860
        $breadcrumb_args[] = $arg;
861
      }
862
      else {
863
        // determine default condition and handle.
864
        $status = $argument->default_action();
865
        break;
866
      }
867
868
      // Be safe with references and loops:
869
      unset($argument);
870
    }
871
872
    // set the title in the build info.
873
    if (!empty($title)) {
874
      $this->build_info['title'] = $title;
875
    }
876
877
    // Store the arguments for later use.
878
    $this->build_info['substitutions'] = $substitutions;
879
880
    return $status;
881
  }
882
883
  /**
884
   * Do some common building initialization.
885
   */
886
  function init_query() {
887
    if (!empty($this->query)) {
888
      $class = get_class($this->query);
889
      if ($class && $class != 'stdClass') {
890
        // return if query is already initialized.
891
        return TRUE;
892
      }
893
    }
894
895
    // Create and initialize the query object.
896
    $views_data = views_fetch_data($this->base_table);
897
    $this->base_field = !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '';
898
    if (!empty($views_data['table']['base']['database'])) {
899
      $this->base_database = $views_data['table']['base']['database'];
900
    }
901
902
    // Load the options.
903
    $query_options = $this->display_handler->get_option('query');
904
905
    // Create and initialize the query object.
906
    $plugin = !empty($views_data['table']['base']['query class']) ? $views_data['table']['base']['query class'] : 'views_query';
907
    $this->query = views_get_plugin('query', $plugin);
908
909
    if (empty($this->query)) {
910
      return FALSE;
911
    }
912
913
    $this->query->init($this->base_table, $this->base_field, $query_options['options']);
914
    return TRUE;
915
  }
916
917
  /**
918
   * Build the query for the view.
919
   */
920
  function build($display_id = NULL) {
921
    if (!empty($this->built)) {
922
      return;
923
    }
924
925
    if (empty($this->current_display) || $display_id) {
926
      if (!$this->set_display($display_id)) {
927
        return FALSE;
928
      }
929
    }
930
931
    // Let modules modify the view just prior to building it.
932
    foreach (module_implements('views_pre_build') as $module) {
933
      $function = $module . '_views_pre_build';
934
      $function($this);
935
    }
936
937
    // Attempt to load from cache.
938
    // @todo Load a build_info from cache.
939
940
    $start = microtime(TRUE);
941
    // If that fails, let's build!
942
    $this->build_info = array(
943
      'query' => '',
944
      'count_query' => '',
945
      'query_args' => array(),
946
    );
947
948
    $this->init_query();
949
950
    // Call a module hook and see if it wants to present us with a
951
    // pre-built query or instruct us not to build the query for
952
    // some reason.
953
    // @todo: Implement this. Use the same mechanism Panels uses.
954
955
    // Run through our handlers and ensure they have necessary information.
956
    $this->init_handlers();
957
958
    // Let the handlers interact with each other if they really want.
959
    $this->_pre_query();
960
961
    if ($this->display_handler->uses_exposed()) {
962
      $exposed_form = $this->display_handler->get_plugin('exposed_form');
963
      // (1) Record the errors before rendering the exposed form widgets.
964
      $errors_before = form_set_error();
965
      $this->exposed_widgets = $exposed_form->render_exposed_form();
966
      // (2) Record the errors after rendering the exposed form widgets.
967
      $errors_after = form_set_error();
968
      // Find out if the validation of any of the elements in the exposed form
969
      // has failed by comparing (1) and (2) above. Don't mess with the view
970
      // otherwise.
971
      $exposed_errors = count($errors_after) > count($errors_before);
972
      if ($exposed_errors || !empty($this->build_info['abort'])) {
973
        $this->built = TRUE;
974
        // Don't execute the query, but rendering will still be executed to display the empty text.
975
        $this->executed = TRUE;
976
        return empty($this->build_info['fail']);
977
      }
978
    }
979
980
    // Build all the relationships first thing.
981
    $this->_build('relationship');
982
983
    // Set the filtering groups.
984
    if (!empty($this->filter)) {
985
      $filter_groups = $this->display_handler->get_option('filter_groups');
986
      if ($filter_groups) {
987
        $this->query->set_group_operator($filter_groups['operator']);
988
        foreach($filter_groups['groups'] as $id => $operator) {
989
          $this->query->set_where_group($operator, $id);
990
        }
991
      }
992
    }
993
994
    // Build all the filters.
995
    $this->_build('filter');
996
997
    $this->build_sort = TRUE;
998
999
    // Arguments can, in fact, cause this whole thing to abort.
1000
    if (!$this->_build_arguments()) {
1001
      $this->build_time = microtime(TRUE) - $start;
1002
      $this->attach_displays();
1003
      return $this->built;
1004
    }
1005
1006
    // Initialize the style; arguments may have changed which style we use,
1007
    // so waiting as long as possible is important. But we need to know
1008
    // about the style when we go to build fields.
1009
    if (!$this->init_style()) {
1010
      $this->build_info['fail'] = TRUE;
1011
      return FALSE;
1012
    }
1013
1014
    if ($this->style_plugin->uses_fields()) {
1015
      $this->_build('field');
1016
    }
1017
1018
    // Build our sort criteria if we were instructed to do so.
1019
    if (!empty($this->build_sort)) {
1020
      // Allow the style handler to deal with sorting.
1021
      if ($this->style_plugin->build_sort()) {
1022
        $this->_build('sort');
1023
      }
1024
      // allow the plugin to build second sorts as well.
1025
      $this->style_plugin->build_sort_post();
1026
    }
1027
1028
    // Allow area handlers to affect the query.
1029
    $this->_build('header');
1030
    $this->_build('footer');
1031
    $this->_build('empty');
1032
1033
    // Allow display handler to affect the query:
1034
    $this->display_handler->query($this->display_handler->use_group_by());
1035
1036
    // Allow style handler to affect the query:
1037
    $this->style_plugin->query($this->display_handler->use_group_by());
1038
1039
    // Allow exposed form to affect the query:
1040
    if (isset($exposed_form)) {
1041
      $exposed_form->query();
1042
    }
1043
1044
    if (variable_get('views_sql_signature', FALSE)) {
1045
      $this->query->add_signature($this);
1046
    }
1047
1048
    // Let modules modify the query just prior to finalizing it.
1049
    $this->query->alter($this);
1050
1051
    // Only build the query if we weren't interrupted.
1052
    if (empty($this->built)) {
1053
      // Build the necessary info to execute the query.
1054
      $this->query->build($this);
1055
    }
1056
1057
    $this->built = TRUE;
1058
    $this->build_time = microtime(TRUE) - $start;
1059
1060
    // Attach displays
1061
    $this->attach_displays();
1062
1063
    // Let modules modify the view just after building it.
1064
    foreach (module_implements('views_post_build') as $module) {
1065
      $function = $module . '_views_post_build';
1066
      $function($this);
1067
    }
1068
1069
    return TRUE;
1070
  }
1071
1072
  /**
1073
   * Internal method to build an individual set of handlers.
1074
   *
1075
   * @param string $key
1076
   *    The type of handlers (filter etc.) which should be iterated over to
1077
   *    build the relationship and query information.
1078
   */
1079
  function _build($key) {
1080
    $handlers = &$this->$key;
1081
    foreach ($handlers as $id => $data) {
1082
1083
      if (!empty($handlers[$id]) && is_object($handlers[$id])) {
1084
        $multiple_exposed_input = array(0 => NULL);
1085
        if ($handlers[$id]->multiple_exposed_input()) {
1086
          $multiple_exposed_input = $handlers[$id]->group_multiple_exposed_input($this->exposed_data);
1087
        }
1088
        foreach ($multiple_exposed_input as $group_id) {
1089
          // Give this handler access to the exposed filter input.
1090
          if (!empty($this->exposed_data)) {
1091
            $converted = FALSE;
1092
            if ($handlers[$id]->is_a_group()) {
1093
              $converted = $handlers[$id]->convert_exposed_input($this->exposed_data, $group_id);
1094
              $handlers[$id]->store_group_input($this->exposed_data, $converted);
1095
              if (!$converted) {
1096
                continue;
1097
              }
1098
            }
1099
            $rc = $handlers[$id]->accept_exposed_input($this->exposed_data);
1100
            $handlers[$id]->store_exposed_input($this->exposed_data, $rc);
1101
            if (!$rc) {
1102
              continue;
1103
            }
1104
          }
1105
          $handlers[$id]->set_relationship();
1106
          $handlers[$id]->query($this->display_handler->use_group_by());
1107
        }
1108
      }
1109
    }
1110
  }
1111
1112
  /**
1113
   * Execute the view's query.
1114
   *
1115
   * @param string $display_id
1116
   *   The machine name of the display, which should be executed.
1117
   *
1118
   * @return bool
1119
   *   Return whether the executing was successful, for example an argument
1120
   *   could stop the process.
1121
   */
1122
  function execute($display_id = NULL) {
1123
    if (empty($this->built)) {
1124
      if (!$this->build($display_id)) {
1125
        return FALSE;
1126
      }
1127
    }
1128
1129
    if (!empty($this->executed)) {
1130
      return TRUE;
1131
    }
1132
1133
    // Don't allow to use deactivated displays, but display them on the live preview.
1134
    if (!$this->display[$this->current_display]->handler->get_option('enabled') && empty($this->live_preview)) {
1135
      $this->build_info['fail'] = TRUE;
1136
      return FALSE;
1137
    }
1138
1139
    // Let modules modify the view just prior to executing it.
1140
    foreach (module_implements('views_pre_execute') as $module) {
1141
      $function = $module . '_views_pre_execute';
1142
      $function($this);
1143
    }
1144
1145
    // Check for already-cached results.
1146
    if (!empty($this->live_preview)) {
1147
      $cache = FALSE;
1148
    }
1149
    else {
1150
      $cache = $this->display_handler->get_plugin('cache');
1151
    }
1152
    if ($cache && $cache->cache_get('results')) {
1153
      if($this->query->pager->use_pager()) {
1154
        $this->query->pager->total_items = $this->total_rows;
1155
        $this->query->pager->update_page_info();
1156
      }
1157
      vpr('Used cached results');
1158
    }
1159
    else {
1160
      $this->query->execute($this);
1161
      // Enforce the array key rule as documented in
1162
      // views_plugin_query::execute().
1163
      $this->result = array_values($this->result);
1164
      $this->_post_execute();
1165
      if ($cache) {
1166
        $cache->cache_set('results');
1167
      }
1168
    }
1169
1170
    // Let modules modify the view just after executing it.
1171
    foreach (module_implements('views_post_execute') as $module) {
1172
      $function = $module . '_views_post_execute';
1173
      $function($this);
1174
    }
1175
1176
    $this->executed = TRUE;
1177
  }
1178
1179
  /**
1180
   * Render this view for a certain display.
1181
   *
1182
   * Note: You should better use just the preview function if you want to
1183
   * render a view.
1184
   *
1185
   * @param string $display_id
1186
   *   The machine name of the display, which should be rendered.
1187
   *
1188
   * @return (string|NULL)
1189
   *   Return the output of the rendered view or NULL if something failed in the process.
1190
   */
1191
  function render($display_id = NULL) {
1192
    $this->execute($display_id);
1193
1194
    // Check to see if the build failed.
1195
    if (!empty($this->build_info['fail'])) {
1196
      return;
1197
    }
1198
    if (!empty($this->view->build_info['denied'])) {
1199
      return;
1200
    }
1201
1202
    drupal_theme_initialize();
1203
1204
    $start = microtime(TRUE);
1205
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1206
      $this->start_query_capture();
1207
    }
1208
1209
    $exposed_form = $this->display_handler->get_plugin('exposed_form');
1210
    $exposed_form->pre_render($this->result);
1211
1212
    // Check for already-cached output.
1213
    if (!empty($this->live_preview)) {
1214
      $cache = FALSE;
1215
    }
1216
    else {
1217
      $cache = $this->display_handler->get_plugin('cache');
1218
    }
1219
    if ($cache && $cache->cache_get('output')) {
1220
    }
1221
    else {
1222
      if ($cache) {
1223
        $cache->cache_start();
1224
      }
1225
1226
      // Run pre_render for the pager as it might change the result.
1227
      if (!empty($this->query->pager)) {
1228
        $this->query->pager->pre_render($this->result);
1229
      }
1230
1231
      // Initialize the style plugin.
1232
      $this->init_style();
1233
1234
      // Give field handlers the opportunity to perform additional queries
1235
      // using the entire resultset prior to rendering.
1236
      if ($this->style_plugin->uses_fields()) {
1237
        foreach ($this->field as $id => $handler) {
1238
          if (!empty($this->field[$id])) {
1239
            $this->field[$id]->pre_render($this->result);
1240
          }
1241
        }
1242
      }
1243
1244
      $this->style_plugin->pre_render($this->result);
1245
1246
      // Let modules modify the view just prior to rendering it.
1247
      foreach (module_implements('views_pre_render') as $module) {
1248
        $function = $module . '_views_pre_render';
1249
        $function($this);
1250
      }
1251
1252
      // Let the themes play too, because pre render is a very themey thing.
1253
      foreach ($GLOBALS['base_theme_info'] as $base) {
1254
        $function = $base->name . '_views_pre_render';
1255
        if (function_exists($function)) {
1256
          $function($this);
1257
        }
1258
      }
1259
      $function = $GLOBALS['theme'] . '_views_pre_render';
1260
      if (function_exists($function)) {
1261
        $function($this);
1262
      }
1263
1264
      $this->display_handler->output = $this->display_handler->render();
1265
      if ($cache) {
1266
        $cache->cache_set('output');
1267
      }
1268
    }
1269
    $this->render_time = microtime(TRUE) - $start;
1270
1271
    $exposed_form->post_render($this->display_handler->output);
1272
1273
    if ($cache) {
1274
      $cache->post_render($this->display_handler->output);
1275
    }
1276
1277
    // Let modules modify the view output after it is rendered.
1278
    foreach (module_implements('views_post_render') as $module) {
1279
      $function = $module . '_views_post_render';
1280
      $function($this, $this->display_handler->output, $cache);
1281
    }
1282
1283
    // Let the themes play too, because post render is a very themey thing.
1284
    foreach ($GLOBALS['base_theme_info'] as $base) {
1285
      $function = $base->name . '_views_post_render';
1286
      if (function_exists($function)) {
1287
        $function($this);
1288
      }
1289
    }
1290
    $function = $GLOBALS['theme'] . '_views_post_render';
1291
    if (function_exists($function)) {
1292
      $function($this, $this->display_handler->output, $cache);
1293
    }
1294
1295
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1296
      $this->end_query_capture();
1297
    }
1298
1299
    return $this->display_handler->output;
1300
  }
1301
1302
  /**
1303
   * Render a specific field via the field ID and the row #
1304
   *
1305
   * Note: You might want to use views_plugin_style::render_fields as it
1306
   * caches the output for you.
1307
   *
1308
   * @param string $field
1309
   *   The id of the field to be rendered.
1310
   *
1311
   * @param int $row
1312
   *   The row number in the $view->result which is used for the rendering.
1313
   *
1314
   * @return string
1315
   *   The rendered output of the field.
1316
   */
1317
  function render_field($field, $row) {
1318
    if (isset($this->field[$field]) && isset($this->result[$row])) {
1319
      return $this->field[$field]->advanced_render($this->result[$row]);
1320
    }
1321
  }
1322
1323
  /**
1324
   * Execute the given display, with the given arguments.
1325
   * To be called externally by whatever mechanism invokes the view,
1326
   * such as a page callback, hook_block, etc.
1327
   *
1328
   * This function should NOT be used by anything external as this
1329
   * returns data in the format specified by the display. It can also
1330
   * have other side effects that are only intended for the 'proper'
1331
   * use of the display, such as setting page titles and breadcrumbs.
1332
   *
1333
   * If you simply want to view the display, use view::preview() instead.
1334
   */
1335
  function execute_display($display_id = NULL, $args = array()) {
1336
    if (empty($this->current_display) || $this->current_display != $this->choose_display($display_id)) {
1337
      if (!$this->set_display($display_id)) {
1338
        return FALSE;
1339
      }
1340
    }
1341
1342
    $this->pre_execute($args);
1343
1344
    // Execute the view
1345
    $output = $this->display_handler->execute();
1346
1347
    $this->post_execute();
1348
    return $output;
1349
  }
1350
1351
  /**
1352
   * Preview the given display, with the given arguments.
1353
   *
1354
   * To be called externally, probably by an AJAX handler of some flavor.
1355
   * Can also be called when views are embedded, as this guarantees
1356
   * normalized output.
1357
   */
1358
  function preview($display_id = NULL, $args = array()) {
1359
    if (empty($this->current_display) || ((!empty($display_id)) && $this->current_display != $display_id)) {
1360
      if (!$this->set_display($display_id)) {
1361
        return FALSE;
1362
      }
1363
    }
1364
1365
    $this->preview = TRUE;
1366
    $this->pre_execute($args);
1367
    // Preview the view.
1368
    $output = $this->display_handler->preview();
1369
1370
    $this->post_execute();
1371
    return $output;
1372
  }
1373
1374
  /**
1375
   * Run attachments and let the display do what it needs to do prior
1376
   * to running.
1377
   */
1378
  function pre_execute($args = array()) {
1379
    $this->old_view[] = views_get_current_view();
1380
    views_set_current_view($this);
1381
    $display_id = $this->current_display;
1382
1383
    // Prepare the view with the information we have, but only if we were
1384
    // passed arguments, as they may have been set previously.
1385
    if ($args) {
1386
      $this->set_arguments($args);
1387
    }
1388
1389
    // Let modules modify the view just prior to executing it.
1390
    foreach (module_implements('views_pre_view') as $module) {
1391
      $function = $module . '_views_pre_view';
1392
      $function($this, $display_id, $this->args);
1393
    }
1394
1395
    // Allow hook_views_pre_view() to set the dom_id, then ensure it is set.
1396
    $this->dom_id = !empty($this->dom_id) ? $this->dom_id : md5($this->name . REQUEST_TIME . rand());
1397
1398
    // Allow the display handler to set up for execution
1399
    $this->display_handler->pre_execute();
1400
  }
1401
1402
  /**
1403
   * Unset the current view, mostly.
1404
   */
1405
  function post_execute() {
1406
    // unset current view so we can be properly destructed later on.
1407
    // Return the previous value in case we're an attachment.
1408
1409
    if ($this->old_view) {
1410
      $old_view = array_pop($this->old_view);
1411
    }
1412
1413
    views_set_current_view(isset($old_view) ? $old_view : FALSE);
1414
  }
1415
1416
  /**
1417
   * Run attachment displays for the view.
1418
   */
1419
  function attach_displays() {
1420
    if (!empty($this->is_attachment)) {
1421
      return;
1422
    }
1423
1424
    if (!$this->display_handler->accept_attachments()) {
1425
      return;
1426
    }
1427
1428
    $this->is_attachment = TRUE;
1429
    // Give other displays an opportunity to attach to the view.
1430
    foreach ($this->display as $id => $display) {
1431
      if (!empty($this->display[$id]->handler)) {
1432
        $this->display[$id]->handler->attach_to($this->current_display);
1433
      }
1434
    }
1435
    $this->is_attachment = FALSE;
1436
  }
1437
1438
  /**
1439
   * Called to get hook_menu() information from the view and the named display handler.
1440
   *
1441
   * @param $display_id
1442
   *   A display id.
1443
   * @param $callbacks
1444
   *   A menu callback array passed from views_menu_alter().
1445
   */
1446
  function execute_hook_menu($display_id = NULL, &$callbacks = array()) {
1447
    // Prepare the view with the information we have.
1448
1449
    // This was probably already called, but it's good to be safe.
1450
    if (!$this->set_display($display_id)) {
1451
      return FALSE;
1452
    }
1453
1454
    // Execute the view
1455
    if (isset($this->display_handler)) {
1456
      return $this->display_handler->execute_hook_menu($callbacks);
1457
    }
1458
  }
1459
1460
  /**
1461
   * Called to get hook_block information from the view and the
1462
   * named display handler.
1463
   */
1464
  function execute_hook_block_list($display_id = NULL) {
1465
    // Prepare the view with the information we have.
1466
1467
    // This was probably already called, but it's good to be safe.
1468
    if (!$this->set_display($display_id)) {
1469
      return FALSE;
1470
    }
1471
1472
    // Execute the view
1473
    if (isset($this->display_handler)) {
1474
      return $this->display_handler->execute_hook_block_list();
1475
    }
1476
  }
1477
1478
  /**
1479
   * Determine if the given user has access to the view. Note that
1480
   * this sets the display handler if it hasn't been.
1481
   */
1482
  function access($displays = NULL, $account = NULL) {
1483
    // Noone should have access to disabled views.
1484
    if (!empty($this->disabled)) {
1485
      return FALSE;
1486
    }
1487
1488
    if (!isset($this->current_display)) {
1489
      $this->init_display();
1490
    }
1491
1492
    if (!$account) {
1493
      $account = $GLOBALS['user'];
1494
    }
1495
1496
    // We can't use choose_display() here because that function
1497
    // calls this one.
1498
    $displays = (array)$displays;
1499
    foreach ($displays as $display_id) {
1500
      if (!empty($this->display[$display_id]->handler)) {
1501
        if ($this->display[$display_id]->handler->access($account)) {
1502
          return TRUE;
1503
        }
1504
      }
1505
    }
1506
1507
    return FALSE;
1508
  }
1509
1510
  /**
1511
   * Get the view's current title. This can change depending upon how it
1512
   * was built.
1513
   */
1514
  function get_title() {
1515
    if (empty($this->display_handler)) {
1516
      if (!$this->set_display('default')) {
1517
        return FALSE;
1518
      }
1519
    }
1520
1521
    // During building, we might find a title override. If so, use it.
1522
    if (!empty($this->build_info['title'])) {
1523
      $title = $this->build_info['title'];
1524
    }
1525
    else {
1526
      $title = $this->display_handler->get_option('title');
1527
    }
1528
1529
    // Allow substitutions from the first row.
1530
    if ($this->init_style()) {
1531
      $title = $this->style_plugin->tokenize_value($title, 0);
1532
    }
1533
    return $title;
1534
  }
1535
1536
  /**
1537
   * Override the view's current title.
1538
   *
1539
   * The tokens in the title get's replaced before rendering.
1540
   */
1541
  function set_title($title) {
1542
     $this->build_info['title'] = $title;
1543
     return TRUE;
1544
   }
1545
1546
  /**
1547
   * Return the human readable name for a view.
1548
   *
1549
   * When a certain view doesn't have a human readable name return the machine readable name.
1550
   */
1551
  function get_human_name() {
1552
    if (!empty($this->human_name)) {
1553
      $human_name = $this->human_name;
1554
    }
1555
    else {
1556
      $human_name = $this->name;
1557
    }
1558
    return $human_name;
1559
  }
1560
1561
  /**
1562
   * Force the view to build a title.
1563
   */
1564
  function build_title() {
1565
    $this->init_display();
1566
1567
    if (empty($this->built)) {
1568
      $this->init_query();
1569
    }
1570
1571
    $this->init_handlers();
1572
1573
    $this->_build_arguments();
1574
  }
1575
1576
  /**
1577
   * Get the URL for the current view.
1578
   *
1579
   * This URL will be adjusted for arguments.
1580
   */
1581
  function get_url($args = NULL, $path = NULL) {
1582
    if (!empty($this->override_url)) {
1583
      return $this->override_url;
1584
    }
1585
1586
    if (!isset($path)) {
1587
      $path = $this->get_path();
1588
    }
1589
    if (!isset($args)) {
1590
      $args = $this->args;
1591
1592
      // Exclude arguments that were computed, not passed on the URL.
1593
      $position = 0;
1594
      if (!empty($this->argument)) {
1595
        foreach ($this->argument as $argument_id => $argument) {
1596
          if (!empty($argument->is_default) && !empty($argument->options['default_argument_skip_url'])) {
1597
            unset($args[$position]);
1598
          }
1599
          $position++;
1600
        }
1601
      }
1602
    }
1603
    // Don't bother working if there's nothing to do:
1604
    if (empty($path) || (empty($args) && strpos($path, '%') === FALSE)) {
1605
      return $path;
1606
    }
1607
1608
    $pieces = array();
1609
    $argument_keys = isset($this->argument) ? array_keys($this->argument) : array();
1610
    $id = current($argument_keys);
1611
    foreach (explode('/', $path) as $piece) {
1612
      if ($piece != '%') {
1613
        $pieces[] = $piece;
1614
      }
1615
      else {
1616
        if (empty($args)) {
1617
          // Try to never put % in a url; use the wildcard instead.
1618
          if ($id && !empty($this->argument[$id]->options['exception']['value'])) {
1619
            $pieces[] = $this->argument[$id]->options['exception']['value'];
1620
          }
1621
          else {
1622
            $pieces[] = '*'; // gotta put something if there just isn't one.
1623
          }
1624
1625
        }
1626
        else {
1627
          $pieces[] = array_shift($args);
1628
        }
1629
1630
        if ($id) {
1631
          $id = next($argument_keys);
1632
        }
1633
      }
1634
    }
1635
1636
    if (!empty($args)) {
1637
      $pieces = array_merge($pieces, $args);
1638
    }
1639
    return implode('/', $pieces);
1640
  }
1641
1642
  /**
1643
   * Get the base path used for this view.
1644
   */
1645
  function get_path() {
1646
    if (!empty($this->override_path)) {
1647
      return $this->override_path;
1648
    }
1649
1650
    if (empty($this->display_handler)) {
1651
      if (!$this->set_display('default')) {
1652
        return FALSE;
1653
      }
1654
    }
1655
    return $this->display_handler->get_path();
1656
  }
1657
1658
  /**
1659
   * Get the breadcrumb used for this view.
1660
   *
1661
   * @param $set
1662
   *   If true, use drupal_set_breadcrumb() to install the breadcrumb.
1663
   */
1664
  function get_breadcrumb($set = FALSE) {
1665
    // Now that we've built the view, extract the breadcrumb.
1666
    $base = TRUE;
1667
    $breadcrumb = array();
1668
1669
    if (!empty($this->build_info['breadcrumb'])) {
1670
      foreach ($this->build_info['breadcrumb'] as $path => $title) {
1671
        // Check to see if the frontpage is in the breadcrumb trail; if it
1672
        // is, we'll remove that from the actual breadcrumb later.
1673
        if ($path == variable_get('site_frontpage', 'node')) {
1674
          $base = FALSE;
1675
          $title = t('Home');
1676
        }
1677
        if ($title) {
1678
          $breadcrumb[] = l($title, $path, array('html' => TRUE));
1679
        }
1680
      }
1681
1682
      if ($set) {
1683
        if ($base) {
1684
          $breadcrumb = array_merge(drupal_get_breadcrumb(), $breadcrumb);
1685
        }
1686
        drupal_set_breadcrumb($breadcrumb);
1687
      }
1688
    }
1689
    return $breadcrumb;
1690
  }
1691
1692
  /**
1693
   * Is this view cacheable?
1694
   */
1695
  function is_cacheable() {
1696
    return $this->is_cacheable;
1697
  }
1698
1699
  /**
1700
   * Set up query capturing.
1701
   *
1702
   * db_query() stores the queries that it runs in global $queries,
1703
   * bit only if dev_query is set to true. In this case, we want
1704
   * to temporarily override that setting if it's not and we
1705
   * can do that without forcing a db rewrite by just manipulating
1706
   * $conf. This is kind of evil but it works.
1707
   */
1708
  function start_query_capture() {
1709
    global $conf, $queries;
1710
    if (empty($conf['dev_query'])) {
1711
      $this->fix_dev_query = TRUE;
1712
      $conf['dev_query'] = TRUE;
1713
    }
1714
1715
    // Record the last query key used; anything already run isn't
1716
    // a query that we are interested in.
1717
    $this->last_query_key = NULL;
1718
1719
    if (!empty($queries)) {
1720
      $keys = array_keys($queries);
1721
      $this->last_query_key = array_pop($keys);
1722
    }
1723
  }
1724
1725
  /**
1726
   * Add the list of queries run during render to buildinfo.
1727
   *
1728
   * @see view::start_query_capture()
1729
   */
1730
  function end_query_capture() {
1731
    global $conf, $queries;
1732
    if (!empty($this->fix_dev_query)) {
1733
      $conf['dev_query'] = FALSE;
1734
    }
1735
1736
    // make a copy of the array so we can manipulate it with array_splice.
1737
    $temp = $queries;
1738
1739
    // Scroll through the queries until we get to our last query key.
1740
    // Unset anything in our temp array.
1741
    if (isset($this->last_query_key)) {
1742
      while (list($id, $query) = each($queries)) {
1743
        if ($id == $this->last_query_key) {
1744
          break;
1745
        }
1746
1747
        unset($temp[$id]);
1748
      }
1749
    }
1750
1751
    $this->additional_queries = $temp;
1752
  }
1753
1754
  /**
1755
   * Static factory method to load a list of views based upon a $where clause.
1756
   *
1757
   * Although this method could be implemented to simply iterate over views::load(),
1758
   * that would be very slow.  Buiding the views externally from unified queries is
1759
   * much faster.
1760
   */
1761
  static function load_views() {
1762
    $result = db_query("SELECT DISTINCT v.* FROM {views_view} v");
1763
    $views = array();
1764
1765
    // Load all the views.
1766
    foreach ($result as $data) {
1767
      $view = new view;
1768
      $view->load_row($data);
1769
      $view->loaded = TRUE;
1770
      $view->type = t('Normal');
1771
      $views[$view->name] = $view;
1772
      $names[$view->vid] = $view->name;
1773
    }
1774
1775
    // Stop if we didn't get any views.
1776
    if (!$views) {
1777
      return array();
1778
    }
1779
1780
    // Now load all the subtables:
1781
    foreach (view::db_objects() as $key) {
1782
      $object_name = "views_$key";
1783
      $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1784
        array(':vids' => array_keys($names)));
1785
1786
      foreach ($result as $data) {
1787
        $object = new $object_name(FALSE);
1788
        $object->load_row($data);
1789
1790
        // Because it can get complicated with this much indirection,
1791
        // make a shortcut reference.
1792
        $location = &$views[$names[$object->vid]]->$key;
1793
1794
        // If we have a basic id field, load the item onto the view based on
1795
        // this ID, otherwise push it on.
1796
        if (!empty($object->id)) {
1797
          $location[$object->id] = $object;
1798
        }
1799
        else {
1800
          $location[] = $object;
1801
        }
1802
      }
1803
    }
1804
    return $views;
1805
  }
1806
1807
  /**
1808
   * Save the view to the database. If the view does not already exist,
1809
   * A vid will be assigned to the view and also returned from this function.
1810
   */
1811
  function save() {
1812
    if ($this->vid == 'new') {
1813
      $this->vid = NULL;
1814
    }
1815
    // If there is no vid, check if a view with this machine name already exists.
1816
    elseif (empty($this->vid)) {
1817
      $vid = db_query("SELECT vid from {views_view} WHERE name = :name", array(':name' => $this->name))->fetchField();
1818
      $this->vid = $vid ? $vid : NULL;
1819
    }
1820
1821
    $transaction = db_transaction();
1822
1823
    try {
1824
      // If we have no vid or our vid is a string, this is a new view.
1825
      if (!empty($this->vid)) {
1826
        // remove existing table entries
1827
        foreach ($this->db_objects() as $key) {
1828
          db_delete('views_' . $key)
1829
            ->condition('vid', $this->vid)
1830
            ->execute();
1831
        }
1832
      }
1833
1834
      $this->save_row(!empty($this->vid) ? 'vid' : FALSE);
1835
1836
      // Save all of our subtables.
1837
      foreach ($this->db_objects() as $key) {
1838
        $this->_save_rows($key);
1839
      }
1840
    }
1841
    catch (Exception $e) {
1842
      $transaction->rollback();
1843
      watchdog_exception('views', $e);
1844
      throw $e;
1845
    }
1846
1847
    $this->save_locale_strings();
1848
1849
    // Clear caches.
1850
    views_invalidate_cache();
1851
  }
1852
1853
  /**
1854
   * Save a row to the database for the given key, which is one of the
1855
   * keys from view::db_objects()
1856
   */
1857
  function _save_rows($key) {
1858
    $count = 0;
1859
    foreach ($this->$key as $position => $object) {
1860
      $object->position = ++$count;
1861
      $object->vid = $this->vid;
1862
      $object->save_row();
1863
    }
1864
  }
1865
1866
  /**
1867
   * Delete the view from the database.
1868
   */
1869
  function delete($clear = TRUE) {
1870
    if (empty($this->vid)) {
1871
      return;
1872
    }
1873
1874
    db_delete('views_view')
1875
      ->condition('vid', $this->vid)
1876
      ->execute();
1877
    // Delete from all of our subtables as well.
1878
    foreach ($this->db_objects() as $key) {
1879
      db_delete('views_'. $key)
1880
        ->condition('vid', $this->vid)
1881
        ->execute();
1882
    }
1883
1884
    cache_clear_all('views_query:' . $this->name, 'cache_views');
1885
1886
    if ($clear) {
1887
      // Clear caches.
1888
      views_invalidate_cache();
1889
    }
1890
  }
1891
1892
  /**
1893
   * Export a view as PHP code.
1894
   */
1895
  function export($indent = '') {
1896
    $this->init_display();
1897
    $this->init_query();
1898
    $output = '';
1899
    $output .= $this->export_row('view', $indent);
1900
    // Set the API version
1901
    $output .= $indent . '$view->api_version = \'' . views_api_version() . "';\n";
1902
    $output .= $indent . '$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */' . "\n";
1903
1904
    foreach ($this->display as $id => $display) {
1905
      $output .= "\n" . $indent . "/* Display: $display->display_title */\n";
1906
      $output .= $indent . '$handler = $view->new_display(' . ctools_var_export($display->display_plugin, $indent) . ', ' . ctools_var_export($display->display_title, $indent) . ', \'' . $id . "');\n";
1907
      if (empty($display->handler)) {
1908
        // @todo -- probably need a method of exporting broken displays as
1909
        // they may simply be broken because a module is not installed. That
1910
        // does not invalidate the display.
1911
        continue;
1912
      }
1913
1914
      $output .= $display->handler->export_options($indent, '$handler->options');
1915
    }
1916
1917
    // Give the localization system a chance to export translatables to code.
1918
    if ($this->init_localization()) {
1919
      $this->export_locale_strings('export');
1920
      $translatables = $this->localization_plugin->export_render($indent);
1921
      if (!empty($translatables)) {
1922
        $output .= $translatables;
1923
      }
1924
    }
1925
1926
    return $output;
1927
  }
1928
1929
  /**
1930
   * Make a copy of this view that has been sanitized of all database IDs
1931
   * and handlers and other stuff.
1932
   *
1933
   * I'd call this clone() but it's reserved.
1934
   */
1935
  function copy() {
1936
    $code = $this->export();
1937
    eval($code);
1938
    return $view;
1939
  }
1940
1941
  /**
1942
   * Safely clone a view.
1943
   *
1944
   * Because views are complicated objects within objects, and PHP loves to
1945
   * do references to everything, if a View is not properly and safely
1946
   * cloned it will still have references to the original view, and can
1947
   * actually cause the original view to point to objects in the cloned
1948
   * view. This gets ugly fast.
1949
   *
1950
   * This will completely wipe a view clean so it can be considered fresh.
1951
   *
1952
   * @return view
1953
   *    The cloned view.
1954
   */
1955
  function clone_view() {
1956
    $clone = version_compare(phpversion(), '5.0') < 0 ? $this : clone($this);
1957
1958
    $keys = array('current_display', 'display_handler', 'build_info', 'built', 'executed', 'attachment_before', 'attachment_after', 'field', 'argument', 'filter', 'sort', 'relationship', 'header', 'footer', 'empty', 'query', 'inited', 'style_plugin', 'plugin_name', 'exposed_data', 'exposed_input', 'exposed_widgets', 'many_to_one_tables', 'feed_icon');
1959
    foreach ($keys as $key) {
1960
      if (isset($clone->$key)) {
1961
        unset($clone->$key);
1962
      }
1963
    }
1964
    $clone->built = $clone->executed = FALSE;
1965
    $clone->build_info = array();
1966
    $clone->attachment_before = '';
1967
    $clone->attachment_after = '';
1968
    $clone->result = array();
1969
1970
    // shallow cloning means that all the display objects
1971
    // *were not cloned*. We must clone them ourselves.
1972
    $displays = array();
1973
    foreach ($clone->display as $id => $display) {
1974
      $displays[$id] = clone $display;
1975
      if (isset($displays[$id]->handler)) {
1976
        unset($displays[$id]->handler);
1977
      }
1978
    }
1979
    $clone->display = $displays;
1980
1981
    return $clone;
1982
  }
1983
1984
  /**
1985
   * Unset references so that a $view object may be properly garbage
1986
   * collected.
1987
   */
1988
  function destroy() {
1989
    foreach (array_keys($this->display) as $display_id) {
1990
      if (isset($this->display[$display_id]->handler)) {
1991
        $this->display[$display_id]->handler->destroy();
1992
        unset($this->display[$display_id]->handler);
1993
      }
1994
    }
1995
1996
    foreach (views_object_types() as $type => $info) {
1997
      if (isset($this->$type)) {
1998
        $handlers = &$this->$type;
1999
        foreach ($handlers as $id => $item) {
2000
          $handlers[$id]->destroy();
2001
        }
2002
        unset($handlers);
2003
      }
2004
    }
2005
2006
    if (isset($this->style_plugin)) {
2007
      $this->style_plugin->destroy();
2008
      unset($this->style_plugin);
2009
    }
2010
2011
    // Clear these to make sure the view can be processed/used again.
2012
    if (isset($this->display_handler)) {
2013
      unset($this->display_handler);
2014
    }
2015
2016
    if (isset($this->current_display)) {
2017
      unset($this->current_display);
2018
    }
2019
2020
    if (isset($this->query)) {
2021
      unset($this->query);
2022
    }
2023
2024
    $keys = array('current_display', 'display_handler', 'build_info', 'built', 'executed', 'attachment_before', 'attachment_after', 'field', 'argument', 'filter', 'sort', 'relationship', 'header', 'footer', 'empty', 'query', 'result', 'inited', 'style_plugin', 'plugin_name', 'exposed_data', 'exposed_input', 'many_to_one_tables');
2025
    foreach ($keys as $key) {
2026
      if (isset($this->$key)) {
2027
        unset($this->$key);
2028
      }
2029
    }
2030
2031
    // These keys are checked by the next init, so instead of unsetting them,
2032
    // just set the default values.
2033
    $keys = array('items_per_page', 'offset', 'current_page');
2034
    foreach ($keys as $key) {
2035
      if (isset($this->$key)) {
2036
        $this->$key = NULL;
2037
      }
2038
    }
2039
2040
    $this->built = $this->executed = FALSE;
2041
    $this->build_info = array();
2042
    $this->attachment_before = '';
2043
    $this->attachment_after = '';
2044
  }
2045
2046
  /**
2047
   * Make sure the view is completely valid.
2048
   *
2049
   * @return
2050
   *   TRUE if the view is valid; an array of error strings if it is not.
2051
   */
2052
  function validate() {
2053
    $this->init_display();
2054
2055
    $errors = array();
2056
    $this->display_errors = NULL;
2057
2058
    $current_display = $this->current_display;
2059
    foreach ($this->display as $id => $display) {
2060
      if ($display->handler) {
2061
        if (!empty($display->deleted)) {
2062
          continue;
2063
        }
2064
2065
        $result = $this->display[$id]->handler->validate();
2066
        if (!empty($result) && is_array($result)) {
2067
          $errors = array_merge($errors, $result);
2068
          // Mark this display as having validation errors.
2069
          $this->display_errors[$id] = TRUE;
2070
        }
2071
      }
2072
    }
2073
2074
    $this->set_display($current_display);
2075
    return $errors ? $errors : TRUE;
2076
  }
2077
2078
  /**
2079
   * Find and initialize the localizer plugin.
2080
   */
2081
  function init_localization() {
2082
    if (isset($this->localization_plugin) && is_object($this->localization_plugin)) {
2083
      return TRUE;
2084
    }
2085
2086
    $this->localization_plugin = views_get_plugin('localization', views_get_localization_plugin());
2087
2088
    if (empty($this->localization_plugin)) {
2089
      $this->localization_plugin = views_get_plugin('localization', 'none');
2090
      return FALSE;
2091
    }
2092
2093
    /**
2094
    * Figure out whether there should be options.
2095
    */
2096
    $this->localization_plugin->init($this);
2097
2098
    return $this->localization_plugin->translate;
2099
  }
2100
2101
  /**
2102
   * Determine whether a view supports admin string translation.
2103
   */
2104
  function is_translatable() {
2105
    // If the view is normal or overridden, use admin string translation.
2106
    // A newly created view won't have a type. Accept this.
2107
    return (!isset($this->type) || in_array($this->type, array(t('Normal'), t('Overridden')))) ? TRUE : FALSE;
2108
  }
2109
2110
  /**
2111
   * Send strings for localization.
2112
   */
2113
  function save_locale_strings() {
2114
    $this->process_locale_strings('save');
2115
  }
2116
2117
  /**
2118
   * Delete localized strings.
2119
   */
2120
  function delete_locale_strings() {
2121
    $this->process_locale_strings('delete');
2122
  }
2123
2124
  /**
2125
   * Export localized strings.
2126
   */
2127
  function export_locale_strings() {
2128
    $this->process_locale_strings('export');
2129
  }
2130
2131
  /**
2132
   * Process strings for localization, deletion or export to code.
2133
   */
2134
  function process_locale_strings($op) {
2135
    // Ensure this view supports translation, we have a display, and we
2136
    // have a localization plugin.
2137
    // @fixme Export does not init every handler.
2138
    if (($this->is_translatable() || $op == 'export') && $this->init_display() && $this->init_localization()) {
2139
      $this->localization_plugin->process_locale_strings($op);
2140
    }
2141
  }
2142
2143
}
2144
2145
/**
2146
 * Base class for views' database objects.
2147
 */
2148
class views_db_object {
2149
  public $db_table;
2150
2151
  /**
2152
   * Initialize this object, setting values from schema defaults.
2153
   *
2154
   * @param $init
2155
   *   If an array, this is a set of values from db_fetch_object to
2156
   *   load. Otherwse, if TRUE values will be filled in from schema
2157
   *   defaults.
2158
   */
2159
  function init($init = TRUE) {
2160
    if (is_array($init)) {
2161
      return $this->load_row($init);
2162
    }
2163
2164
    if (!$init) {
2165
      return;
2166
    }
2167
2168
    $schema = drupal_get_schema($this->db_table);
2169
2170
    if (!$schema) {
2171
      return;
2172
    }
2173
2174
    // Go through our schema and build correlations.
2175
    foreach ($schema['fields'] as $field => $info) {
2176
      if ($info['type'] == 'serial') {
2177
        $this->$field = NULL;
2178
      }
2179
      if (!isset($this->$field)) {
2180
        if (!empty($info['serialize']) && isset($info['serialized default'])) {
2181
          $this->$field = unserialize($info['serialized default']);
2182
        }
2183
        elseif (isset($info['default'])) {
2184
          $this->$field = $info['default'];
2185
        }
2186
        else {
2187
          $this->$field = '';
2188
        }
2189
      }
2190
    }
2191
  }
2192
2193
  /**
2194
   * Write the row to the database.
2195
   *
2196
   * @param $update
2197
   *   If true this will be an UPDATE query. Otherwise it will be an INSERT.
2198
   */
2199
  function save_row($update = NULL) {
2200
    $fields = $defs = $values = $serials = array();
2201
    $schema = drupal_get_schema($this->db_table);
2202
2203
    // Go through our schema and build correlations.
2204
    foreach ($schema['fields'] as $field => $info) {
2205
      // special case -- skip serial types if we are updating.
2206
      if ($info['type'] == 'serial') {
2207
        $serials[] = $field;
2208
        continue;
2209
      }
2210
      elseif ($info['type'] == 'int') {
2211
        $this->$field = (int) $this->$field;
2212
      }
2213
      $fields[$field] = empty($info['serialize']) ? $this->$field : serialize($this->$field);
2214
    }
2215
    if (!$update) {
2216
      $query = db_insert($this->db_table);
2217
    }
2218
    else {
2219
      $query = db_update($this->db_table)
2220
        ->condition($update, $this->$update);
2221
    }
2222
    $return = $query
2223
      ->fields($fields)
2224
      ->execute();
2225
2226
    if ($serials && !$update) {
2227
      // get last insert ids and fill them in.
2228
      // Well, one ID.
2229
      foreach ($serials as $field) {
2230
        $this->$field = $return;
2231
      }
2232
    }
2233
  }
2234
2235
  /**
2236
   * Load the object with a row from the database.
2237
   *
2238
   * This method is separate from the constructor in order to give us
2239
   * more flexibility in terms of how the view object is built in different
2240
   * contexts.
2241
   *
2242
   * @param $data
2243
   *   An object from db_fetch_object. It should contain all of the fields
2244
   *   that are in the schema.
2245
   */
2246
  function load_row($data) {
2247
    $schema = drupal_get_schema($this->db_table);
2248
2249
    // Go through our schema and build correlations.
2250
    foreach ($schema['fields'] as $field => $info) {
2251
      $this->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
2252
    }
2253
  }
2254
2255
  /**
2256
   * Export a loaded row, such as an argument, field or the view itself to PHP code.
2257
   *
2258
   * @param $identifier
2259
   *   The variable to assign the PHP code for this object to.
2260
   * @param $indent
2261
   *   An optional indentation for prettifying nested code.
2262
   */
2263
  function export_row($identifier = NULL, $indent = '') {
2264
    ctools_include('export');
2265
2266
    if (!$identifier) {
2267
      $identifier = $this->db_table;
2268
    }
2269
    $schema = drupal_get_schema($this->db_table);
2270
2271
    $output = $indent . '$' . $identifier . ' = new ' . get_class($this) . "();\n";
2272
    // Go through our schema and build correlations.
2273
    foreach ($schema['fields'] as $field => $info) {
2274
      if (!empty($info['no export'])) {
2275
        continue;
2276
      }
2277
      if (!isset($this->$field)) {
2278
        if (isset($info['default'])) {
2279
          $this->$field = $info['default'];
2280
        }
2281
        else {
2282
          $this->$field = '';
2283
        }
2284
2285
        // serialized defaults must be set as serialized.
2286
        if (isset($info['serialize'])) {
2287
          $this->$field = unserialize($this->$field);
2288
        }
2289
      }
2290
      $value = $this->$field;
2291
      if ($info['type'] == 'int') {
2292
        if (isset($info['size']) && $info['size'] == 'tiny') {
2293
          $value = (bool) $value;
2294
        }
2295
        else {
2296
          $value = (int) $value;
2297
        }
2298
      }
2299
2300
      $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
2301
    }
2302
    return $output;
2303
  }
2304
2305
  /**
2306
   * Add a new display handler to the view, automatically creating an id.
2307
   *
2308
   * @param $type
2309
   *   The plugin type from the views plugin data. Defaults to 'page'.
2310
   * @param $title
2311
   *   The title of the display; optional, may be filled in from default.
2312
   * @param $id
2313
   *   The id to use.
2314
   * @return
2315
   *   The key to the display in $view->display, so that the new display
2316
   *   can be easily located.
2317
   */
2318
  function add_display($type = 'page', $title = NULL, $id = NULL) {
2319
    if (empty($type)) {
2320
      return FALSE;
2321
    }
2322
2323
    $plugin = views_fetch_plugin_data('display', $type);
2324
    if (empty($plugin)) {
2325
      $plugin['title'] = t('Broken');
2326
    }
2327
2328
2329
    if (empty($id)) {
2330
      $id = $this->generate_display_id($type);
2331
      if ($id !== 'default') {
2332
        preg_match("/[0-9]+/", $id, $count);
2333
        $count = $count[0];
2334
      }
2335
      else {
2336
        $count = '';
2337
      }
2338
2339
      if (empty($title)) {
2340
        if ($count > 1) {
2341
          $title = $plugin['title'] . ' ' . $count;
2342
        }
2343
        else {
2344
          $title = $plugin['title'];
2345
        }
2346
      }
2347
    }
2348
2349
    // Create the new display object
2350
    $display = new views_display;
2351
    $display->options($type, $id, $title);
2352
2353
    // Add the new display object to the view.
2354
    $this->display[$id] = $display;
2355
    return $id;
2356
  }
2357
2358
  /**
2359
   * Generate a display id of a certain plugin type.
2360
   *
2361
   * @param $type
2362
   *   Which plugin should be used for the new display id.
2363
   */
2364
  function generate_display_id($type) {
2365
    // 'default' is singular and is unique, so just go with 'default'
2366
    // for it. For all others, start counting.
2367
    if ($type == 'default') {
2368
      return 'default';
2369
    }
2370
    // Initial id.
2371
    $id = $type . '_1';
2372
    $count = 1;
2373
2374
    // Loop through IDs based upon our style plugin name until
2375
    // we find one that is unused.
2376
    while (!empty($this->display[$id])) {
2377
      $id = $type . '_' . ++$count;
2378
    }
2379
2380
    return $id;
2381
  }
2382
2383
  /**
2384
   * Generates a unique ID for an item.
2385
   *
2386
   * These items are typically fields, filters, sort criteria, or arguments.
2387
   *
2388
   * @param $requested_id
2389
   *   The requested ID for the item.
2390
   * @param $existing_items
2391
   *   An array of existing items, keyed by their IDs.
2392
   *
2393
   * @return
2394
   *   A unique ID. This will be equal to $requested_id if no item with that ID
2395
   *   already exists. Otherwise, it will be appended with an integer to make
2396
   *   it unique, e.g. "{$requested_id}_1", "{$requested_id}_2", etc.
2397
   */
2398
  public static function generate_item_id($requested_id, $existing_items) {
2399
    $count = 0;
2400
    $id = $requested_id;
2401
    while (!empty($existing_items[$id])) {
2402
      $id = $requested_id . '_' . ++$count;
2403
    }
2404
    return $id;
2405
  }
2406
2407
  /**
2408
   * Create a new display and a display handler for it.
2409
   * @param $type
2410
   *   The plugin type from the views plugin data. Defaults to 'page'.
2411
   * @param $title
2412
   *   The title of the display; optional, may be filled in from default.
2413
   * @param $id
2414
   *   The id to use.
2415
   * @return views_plugin_display
2416
   *   A reference to the new handler object.
2417
   */
2418
  function &new_display($type = 'page', $title = NULL, $id = NULL) {
2419
    $id = $this->add_display($type, $title, $id);
2420
2421
    // Create a handler
2422
    $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
2423
    if (empty($this->display[$id]->handler)) {
2424
      // provide a 'default' handler as an emergency. This won't work well but
2425
      // it will keep things from crashing.
2426
      $this->display[$id]->handler = views_get_plugin('display', 'default');
2427
    }
2428
2429
    if (!empty($this->display[$id]->handler)) {
2430
      // Initialize the new display handler with data.
2431
      $this->display[$id]->handler->init($this, $this->display[$id]);
2432
      // If this is NOT the default display handler, let it know which is
2433
      if ($id != 'default') {
2434
        $this->display[$id]->handler->default_display = &$this->display['default']->handler;
2435
      }
2436
    }
2437
2438
    return $this->display[$id]->handler;
2439
  }
2440
2441
  /**
2442
   * Add an item with a handler to the view.
2443
   *
2444
   * These items may be fields, filters, sort criteria, or arguments.
2445
   */
2446
  function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
2447
    $types = views_object_types();
2448
    $this->set_display($display_id);
2449
2450
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2451
2452
    if (empty($id)) {
2453
      $id = $this->generate_item_id($field, $fields);
2454
    }
2455
2456
    $new_item = array(
2457
      'id' => $id,
2458
      'table' => $table,
2459
      'field' => $field,
2460
    ) + $options;
2461
2462
    if (!empty($types[$type]['type'])) {
2463
      $handler_type = $types[$type]['type'];
2464
    }
2465
    else {
2466
      $handler_type = $type;
2467
    }
2468
2469
    $handler = views_get_handler($table, $field, $handler_type);
2470
2471
    $fields[$id] = $new_item;
2472
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2473
2474
    return $id;
2475
  }
2476
2477
  /**
2478
   * Get an array of items for the current display.
2479
   */
2480
  function get_items($type, $display_id = NULL) {
2481
    $this->set_display($display_id);
2482
2483
    if (!isset($display_id)) {
2484
      $display_id = $this->current_display;
2485
    }
2486
2487
    // Get info about the types so we can get the right data.
2488
    $types = views_object_types();
2489
    return $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2490
  }
2491
2492
  /**
2493
   * Get the configuration of an item (field/sort/filter/etc) on a given
2494
   * display.
2495
   */
2496
  function get_item($display_id, $type, $id) {
2497
    // Get info about the types so we can get the right data.
2498
    $types = views_object_types();
2499
    // Initialize the display
2500
    $this->set_display($display_id);
2501
2502
    // Get the existing configuration
2503
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2504
2505
    return isset($fields[$id]) ? $fields[$id] : NULL;
2506
  }
2507
2508
  /**
2509
   * Set the configuration of an item (field/sort/filter/etc) on a given
2510
   * display.
2511
   *
2512
   * Pass in NULL for the $item to remove an item.
2513
   */
2514
  function set_item($display_id, $type, $id, $item) {
2515
    // Get info about the types so we can get the right data.
2516
    $types = views_object_types();
2517
    // Initialize the display
2518
    $this->set_display($display_id);
2519
2520
    // Get the existing configuration
2521
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2522
    if (isset($item)) {
2523
      $fields[$id] = $item;
2524
    }
2525
    else {
2526
      unset($fields[$id]);
2527
    }
2528
2529
    // Store.
2530
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2531
  }
2532
2533
  /**
2534
   * Set an option on an item.
2535
   *
2536
   * Use this only if you have just 1 or 2 options to set; if you have
2537
   * many, consider getting the item, adding the options and doing
2538
   * set_item yourself.
2539
   */
2540
  function set_item_option($display_id, $type, $id, $option, $value) {
2541
    $item = $this->get_item($display_id, $type, $id);
2542
    $item[$option] = $value;
2543
    $this->set_item($display_id, $type, $id, $item);
2544
  }
2545
}
2546
2547
/**
2548
 * A display type in a view.
2549
 *
2550
 * This is just the database storage mechanism, and isn't terribly important
2551
 * to the behavior of the display at all.
2552
 */
2553
class views_display extends views_db_object {
2554
  /**
2555
   * The display handler itself, which has all the methods.
2556
   *
2557
   * @var views_plugin_display
2558
   */
2559
  var $handler;
2560
2561
  /**
2562
   * Stores all options of the display, like fields, filters etc.
2563
   *
2564
   * @var array
2565
   */
2566
  var $display_options;
2567
2568
  var $db_table = 'views_display';
2569
  function views_display($init = TRUE) {
2570
    parent::init($init);
2571
  }
2572
2573
  function options($type, $id, $title) {
2574
    $this->display_plugin = $type;
2575
    $this->id = $id;
2576
    $this->display_title = $title;
2577
  }
2578
}
2579
2580
/**
2581
 * Provide a list of views object types used in a view, with some information
2582
 * about them.
2583
 */
2584
function views_object_types() {
2585
  static $retval = NULL;
2586
2587
  // statically cache this so t() doesn't run a bajillion times.
2588
  if (!isset($retval)) {
2589
    $retval = array(
2590
      'field' => array(
2591
        'title' => t('Fields'), // title
2592
        'ltitle' => t('fields'), // lowercase title for mid-sentence
2593
        'stitle' => t('Field'), // singular title
2594
        'lstitle' => t('field'), // singular lowercase title for mid sentence
2595
        'plural' => 'fields',
2596
      ),
2597
      'argument' => array(
2598
        'title' => t('Contextual filters'),
2599
        'ltitle' => t('contextual filters'),
2600
        'stitle' => t('Contextual filter'),
2601
        'lstitle' => t('contextual filter'),
2602
        'plural' => 'arguments',
2603
      ),
2604
      'sort' => array(
2605
        'title' => t('Sort criteria'),
2606
        'ltitle' => t('sort criteria'),
2607
        'stitle' => t('Sort criterion'),
2608
        'lstitle' => t('sort criterion'),
2609
        'plural' => 'sorts',
2610
      ),
2611
      'filter' => array(
2612
        'title' => t('Filter criteria'),
2613
        'ltitle' => t('filter criteria'),
2614
        'stitle' => t('Filter criterion'),
2615
        'lstitle' => t('filter criterion'),
2616
        'plural' => 'filters',
2617
      ),
2618
      'relationship' => array(
2619
        'title' => t('Relationships'),
2620
        'ltitle' => t('relationships'),
2621
        'stitle' => t('Relationship'),
2622
        'lstitle' => t('Relationship'),
2623
        'plural' => 'relationships',
2624
      ),
2625
      'header' => array(
2626
        'title' => t('Header'),
2627
        'ltitle' => t('header'),
2628
        'stitle' => t('Header'),
2629
        'lstitle' => t('Header'),
2630
        'plural' => 'header',
2631
        'type' => 'area',
2632
      ),
2633
      'footer' => array(
2634
        'title' => t('Footer'),
2635
        'ltitle' => t('footer'),
2636
        'stitle' => t('Footer'),
2637
        'lstitle' => t('Footer'),
2638
        'plural' => 'footer',
2639
        'type' => 'area',
2640
      ),
2641
      'empty' => array(
2642
        'title' => t('No results behavior'),
2643
        'ltitle' => t('no results behavior'),
2644
        'stitle' => t('No results behavior'),
2645
        'lstitle' => t('No results behavior'),
2646
        'plural' => 'empty',
2647
        'type' => 'area',
2648
      ),
2649
    );
2650
  }
2651
2652
  return $retval;
2653
}
2654
2655
/**
2656
 * @}
2657
 */