Projet

Général

Profil

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

root / drupal7 / sites / all / modules / views / includes / view.inc @ 7547bb19

1
<?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
        }
816

    
817
        // Set the argument, which will also validate that the argument can be set.
818
        if (!$argument->set_argument($arg)) {
819
          $status = $argument->validate_fail($arg);
820
          break;
821
        }
822

    
823
        if ($argument->is_exception()) {
824
          $arg_title = $argument->exception_title();
825
        }
826
        else {
827
          $arg_title = $argument->get_title();
828
          $argument->query($this->display_handler->use_group_by());
829
        }
830

    
831
        // Add this argument's substitution
832
        $substitutions['%' . ($position + 1)] = $arg_title;
833
        $substitutions['!' . ($position + 1)] = strip_tags(decode_entities($arg));
834

    
835
        // Since we're really generating the breadcrumb for the item above us,
836
        // check the default action of this argument.
837
        if ($this->display_handler->uses_breadcrumb() && $argument->uses_breadcrumb()) {
838
          $path = $this->get_url($breadcrumb_args);
839
          if (strpos($path, '%') === FALSE) {
840
            if (!empty($argument->options['breadcrumb_enable']) && !empty($argument->options['breadcrumb'])) {
841
              $breadcrumb = $argument->options['breadcrumb'];
842
            }
843
            else {
844
              $breadcrumb = $title;
845
            }
846
            $this->build_info['breadcrumb'][$path] = str_replace(array_keys($substitutions), $substitutions, $breadcrumb);
847
          }
848
        }
849

    
850
        // Allow the argument to muck with this breadcrumb.
851
        $argument->set_breadcrumb($this->build_info['breadcrumb']);
852

    
853
        // Test to see if we should use this argument's title
854
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
855
          $title = $argument->options['title'];
856
        }
857

    
858
        $breadcrumb_args[] = $arg;
859
      }
860
      else {
861
        // determine default condition and handle.
862
        $status = $argument->default_action();
863
        break;
864
      }
865

    
866
      // Be safe with references and loops:
867
      unset($argument);
868
    }
869

    
870
    // set the title in the build info.
871
    if (!empty($title)) {
872
      $this->build_info['title'] = $title;
873
    }
874

    
875
    // Store the arguments for later use.
876
    $this->build_info['substitutions'] = $substitutions;
877

    
878
    return $status;
879
  }
880

    
881
  /**
882
   * Do some common building initialization.
883
   */
884
  function init_query() {
885
    if (!empty($this->query)) {
886
      $class = get_class($this->query);
887
      if ($class && $class != 'stdClass') {
888
        // return if query is already initialized.
889
        return TRUE;
890
      }
891
    }
892

    
893
    // Create and initialize the query object.
894
    $views_data = views_fetch_data($this->base_table);
895
    $this->base_field = !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '';
896
    if (!empty($views_data['table']['base']['database'])) {
897
      $this->base_database = $views_data['table']['base']['database'];
898
    }
899

    
900
    // Load the options.
901
    $query_options = $this->display_handler->get_option('query');
902

    
903
    // Create and initialize the query object.
904
    $plugin = !empty($views_data['table']['base']['query class']) ? $views_data['table']['base']['query class'] : 'views_query';
905
    $this->query = views_get_plugin('query', $plugin);
906

    
907
    if (empty($this->query)) {
908
      return FALSE;
909
    }
910

    
911
    $this->query->init($this->base_table, $this->base_field, $query_options['options']);
912
    return TRUE;
913
  }
914

    
915
  /**
916
   * Build the query for the view.
917
   */
918
  function build($display_id = NULL) {
919
    if (!empty($this->built)) {
920
      return;
921
    }
922

    
923
    if (empty($this->current_display) || $display_id) {
924
      if (!$this->set_display($display_id)) {
925
        return FALSE;
926
      }
927
    }
928

    
929
    // Let modules modify the view just prior to building it.
930
    foreach (module_implements('views_pre_build') as $module) {
931
      $function = $module . '_views_pre_build';
932
      $function($this);
933
    }
934

    
935
    // Attempt to load from cache.
936
    // @todo Load a build_info from cache.
937

    
938
    $start = microtime(TRUE);
939
    // If that fails, let's build!
940
    $this->build_info = array(
941
      'query' => '',
942
      'count_query' => '',
943
      'query_args' => array(),
944
    );
945

    
946
    $this->init_query();
947

    
948
    // Call a module hook and see if it wants to present us with a
949
    // pre-built query or instruct us not to build the query for
950
    // some reason.
951
    // @todo: Implement this. Use the same mechanism Panels uses.
952

    
953
    // Run through our handlers and ensure they have necessary information.
954
    $this->init_handlers();
955

    
956
    // Let the handlers interact with each other if they really want.
957
    $this->_pre_query();
958

    
959
    if ($this->display_handler->uses_exposed()) {
960
      $exposed_form = $this->display_handler->get_plugin('exposed_form');
961
      // (1) Record the errors before rendering the exposed form widgets.
962
      $errors_before = form_set_error();
963
      $this->exposed_widgets = $exposed_form->render_exposed_form();
964
      // (2) Record the errors after rendering the exposed form widgets.
965
      $errors_after = form_set_error();
966
      // Find out if the validation of any of the elements in the exposed form
967
      // has failed by comparing (1) and (2) above. Don't mess with the view
968
      // otherwise.
969
      $exposed_errors = count($errors_after) > count($errors_before);
970
      if ($exposed_errors || !empty($this->build_info['abort'])) {
971
        $this->built = TRUE;
972
        // Don't execute the query, but rendering will still be executed to display the empty text.
973
        $this->executed = TRUE;
974
        return empty($this->build_info['fail']);
975
      }
976
    }
977

    
978
    // Build all the relationships first thing.
979
    $this->_build('relationship');
980

    
981
    // Set the filtering groups.
982
    if (!empty($this->filter)) {
983
      $filter_groups = $this->display_handler->get_option('filter_groups');
984
      if ($filter_groups) {
985
        $this->query->set_group_operator($filter_groups['operator']);
986
        foreach($filter_groups['groups'] as $id => $operator) {
987
          $this->query->set_where_group($operator, $id);
988
        }
989
      }
990
    }
991

    
992
    // Build all the filters.
993
    $this->_build('filter');
994

    
995
    $this->build_sort = TRUE;
996

    
997
    // Arguments can, in fact, cause this whole thing to abort.
998
    if (!$this->_build_arguments()) {
999
      $this->build_time = microtime(TRUE) - $start;
1000
      $this->attach_displays();
1001
      return $this->built;
1002
    }
1003

    
1004
    // Initialize the style; arguments may have changed which style we use,
1005
    // so waiting as long as possible is important. But we need to know
1006
    // about the style when we go to build fields.
1007
    if (!$this->init_style()) {
1008
      $this->build_info['fail'] = TRUE;
1009
      return FALSE;
1010
    }
1011

    
1012
    if ($this->style_plugin->uses_fields()) {
1013
      $this->_build('field');
1014
    }
1015

    
1016
    // Build our sort criteria if we were instructed to do so.
1017
    if (!empty($this->build_sort)) {
1018
      // Allow the style handler to deal with sorting.
1019
      if ($this->style_plugin->build_sort()) {
1020
        $this->_build('sort');
1021
      }
1022
      // allow the plugin to build second sorts as well.
1023
      $this->style_plugin->build_sort_post();
1024
    }
1025

    
1026
    // Allow area handlers to affect the query.
1027
    $this->_build('header');
1028
    $this->_build('footer');
1029
    $this->_build('empty');
1030

    
1031
    // Allow display handler to affect the query:
1032
    $this->display_handler->query($this->display_handler->use_group_by());
1033

    
1034
    // Allow style handler to affect the query:
1035
    $this->style_plugin->query($this->display_handler->use_group_by());
1036

    
1037
    // Allow exposed form to affect the query:
1038
    if (isset($exposed_form)) {
1039
      $exposed_form->query();
1040
    }
1041

    
1042
    if (variable_get('views_sql_signature', FALSE)) {
1043
      $this->query->add_signature($this);
1044
    }
1045

    
1046
    // Let modules modify the query just prior to finalizing it.
1047
    $this->query->alter($this);
1048

    
1049
    // Only build the query if we weren't interrupted.
1050
    if (empty($this->built)) {
1051
      // Build the necessary info to execute the query.
1052
      $this->query->build($this);
1053
    }
1054

    
1055
    $this->built = TRUE;
1056
    $this->build_time = microtime(TRUE) - $start;
1057

    
1058
    // Attach displays
1059
    $this->attach_displays();
1060

    
1061
    // Let modules modify the view just after building it.
1062
    foreach (module_implements('views_post_build') as $module) {
1063
      $function = $module . '_views_post_build';
1064
      $function($this);
1065
    }
1066

    
1067
    return TRUE;
1068
  }
1069

    
1070
  /**
1071
   * Internal method to build an individual set of handlers.
1072
   *
1073
   * @param string $key
1074
   *    The type of handlers (filter etc.) which should be iterated over to
1075
   *    build the relationship and query information.
1076
   */
1077
  function _build($key) {
1078
    $handlers = &$this->$key;
1079
    foreach ($handlers as $id => $data) {
1080

    
1081
      if (!empty($handlers[$id]) && is_object($handlers[$id])) {
1082
        $multiple_exposed_input = array(0 => NULL);
1083
        if ($handlers[$id]->multiple_exposed_input()) {
1084
          $multiple_exposed_input = $handlers[$id]->group_multiple_exposed_input($this->exposed_data);
1085
        }
1086
        foreach ($multiple_exposed_input as $group_id) {
1087
          // Give this handler access to the exposed filter input.
1088
          if (!empty($this->exposed_data)) {
1089
            $converted = FALSE;
1090
            if ($handlers[$id]->is_a_group()) {
1091
              $converted = $handlers[$id]->convert_exposed_input($this->exposed_data, $group_id);
1092
              $handlers[$id]->store_group_input($this->exposed_data, $converted);
1093
              if (!$converted) {
1094
                continue;
1095
              }
1096
            }
1097
            $rc = $handlers[$id]->accept_exposed_input($this->exposed_data);
1098
            $handlers[$id]->store_exposed_input($this->exposed_data, $rc);
1099
            if (!$rc) {
1100
              continue;
1101
            }
1102
          }
1103
          $handlers[$id]->set_relationship();
1104
          $handlers[$id]->query($this->display_handler->use_group_by());
1105
        }
1106
      }
1107
    }
1108
  }
1109

    
1110
  /**
1111
   * Execute the view's query.
1112
   *
1113
   * @param string $display_id
1114
   *   The machine name of the display, which should be executed.
1115
   *
1116
   * @return bool
1117
   *   Return whether the executing was successful, for example an argument
1118
   *   could stop the process.
1119
   */
1120
  function execute($display_id = NULL) {
1121
    if (empty($this->built)) {
1122
      if (!$this->build($display_id)) {
1123
        return FALSE;
1124
      }
1125
    }
1126

    
1127
    if (!empty($this->executed)) {
1128
      return TRUE;
1129
    }
1130

    
1131
    // Don't allow to use deactivated displays, but display them on the live preview.
1132
    if (!$this->display[$this->current_display]->handler->get_option('enabled') && empty($this->live_preview)) {
1133
      $this->build_info['fail'] = TRUE;
1134
      return FALSE;
1135
    }
1136

    
1137
    // Let modules modify the view just prior to executing it.
1138
    foreach (module_implements('views_pre_execute') as $module) {
1139
      $function = $module . '_views_pre_execute';
1140
      $function($this);
1141
    }
1142

    
1143
    // Check for already-cached results.
1144
    if (!empty($this->live_preview)) {
1145
      $cache = FALSE;
1146
    }
1147
    else {
1148
      $cache = $this->display_handler->get_plugin('cache');
1149
    }
1150
    if ($cache && $cache->cache_get('results')) {
1151
      if($this->query->pager->use_pager() || !empty($this->get_total_rows)) {
1152
        $this->query->pager->total_items = $this->total_rows;
1153
        $this->query->pager->update_page_info();
1154
      }
1155
      vpr('Used cached results');
1156
    }
1157
    else {
1158
      $this->query->execute($this);
1159
      // Enforce the array key rule as documented in
1160
      // views_plugin_query::execute().
1161
      $this->result = array_values($this->result);
1162
      $this->_post_execute();
1163
      if ($cache) {
1164
        $cache->cache_set('results');
1165
      }
1166
    }
1167

    
1168
    // Let modules modify the view just after executing it.
1169
    foreach (module_implements('views_post_execute') as $module) {
1170
      $function = $module . '_views_post_execute';
1171
      $function($this);
1172
    }
1173

    
1174
    $this->executed = TRUE;
1175
  }
1176

    
1177
  /**
1178
   * Render this view for a certain display.
1179
   *
1180
   * Note: You should better use just the preview function if you want to
1181
   * render a view.
1182
   *
1183
   * @param string $display_id
1184
   *   The machine name of the display, which should be rendered.
1185
   *
1186
   * @return (string|NULL)
1187
   *   Return the output of the rendered view or NULL if something failed in the process.
1188
   */
1189
  function render($display_id = NULL) {
1190
    $this->execute($display_id);
1191

    
1192
    // Check to see if the build failed.
1193
    if (!empty($this->build_info['fail'])) {
1194
      return;
1195
    }
1196
    if (!empty($this->view->build_info['denied'])) {
1197
      return;
1198
    }
1199

    
1200
    drupal_theme_initialize();
1201

    
1202
    $start = microtime(TRUE);
1203
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1204
      $this->start_query_capture();
1205
    }
1206

    
1207
    $exposed_form = $this->display_handler->get_plugin('exposed_form');
1208
    $exposed_form->pre_render($this->result);
1209

    
1210
    // Check for already-cached output.
1211
    if (!empty($this->live_preview)) {
1212
      $cache = FALSE;
1213
    }
1214
    else {
1215
      $cache = $this->display_handler->get_plugin('cache');
1216
    }
1217
    if ($cache && $cache->cache_get('output')) {
1218
    }
1219
    else {
1220
      if ($cache) {
1221
        $cache->cache_start();
1222
      }
1223

    
1224
      // Run pre_render for the pager as it might change the result.
1225
      if (!empty($this->query->pager)) {
1226
        $this->query->pager->pre_render($this->result);
1227
      }
1228

    
1229
      // Initialize the style plugin.
1230
      $this->init_style();
1231

    
1232
      // Give field handlers the opportunity to perform additional queries
1233
      // using the entire resultset prior to rendering.
1234
      if ($this->style_plugin->uses_fields()) {
1235
        foreach ($this->field as $id => $handler) {
1236
          if (!empty($this->field[$id])) {
1237
            $this->field[$id]->pre_render($this->result);
1238
          }
1239
        }
1240
      }
1241

    
1242
      $this->style_plugin->pre_render($this->result);
1243

    
1244
      // Let modules modify the view just prior to rendering it.
1245
      foreach (module_implements('views_pre_render') as $module) {
1246
        $function = $module . '_views_pre_render';
1247
        $function($this);
1248
      }
1249

    
1250
      // Let the themes play too, because pre render is a very themey thing.
1251
      foreach ($GLOBALS['base_theme_info'] as $base) {
1252
        $function = $base->name . '_views_pre_render';
1253
        if (function_exists($function)) {
1254
          $function($this);
1255
        }
1256
      }
1257
      $function = $GLOBALS['theme'] . '_views_pre_render';
1258
      if (function_exists($function)) {
1259
        $function($this);
1260
      }
1261

    
1262
      $this->display_handler->output = $this->display_handler->render();
1263
      if ($cache) {
1264
        $cache->cache_set('output');
1265
      }
1266
    }
1267
    $this->render_time = microtime(TRUE) - $start;
1268

    
1269
    $exposed_form->post_render($this->display_handler->output);
1270

    
1271
    if ($cache) {
1272
      $cache->post_render($this->display_handler->output);
1273
    }
1274

    
1275
    // Let modules modify the view output after it is rendered.
1276
    foreach (module_implements('views_post_render') as $module) {
1277
      $function = $module . '_views_post_render';
1278
      $function($this, $this->display_handler->output, $cache);
1279
    }
1280

    
1281
    // Let the themes play too, because post render is a very themey thing.
1282
    foreach ($GLOBALS['base_theme_info'] as $base) {
1283
      $function = $base->name . '_views_post_render';
1284
      if (function_exists($function)) {
1285
        $function($this);
1286
      }
1287
    }
1288
    $function = $GLOBALS['theme'] . '_views_post_render';
1289
    if (function_exists($function)) {
1290
      $function($this, $this->display_handler->output, $cache);
1291
    }
1292

    
1293
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1294
      $this->end_query_capture();
1295
    }
1296

    
1297
    return $this->display_handler->output;
1298
  }
1299

    
1300
  /**
1301
   * Render a specific field via the field ID and the row #
1302
   *
1303
   * Note: You might want to use views_plugin_style::render_fields as it
1304
   * caches the output for you.
1305
   *
1306
   * @param string $field
1307
   *   The id of the field to be rendered.
1308
   *
1309
   * @param int $row
1310
   *   The row number in the $view->result which is used for the rendering.
1311
   *
1312
   * @return string
1313
   *   The rendered output of the field.
1314
   */
1315
  function render_field($field, $row) {
1316
    if (isset($this->field[$field]) && isset($this->result[$row])) {
1317
      return $this->field[$field]->advanced_render($this->result[$row]);
1318
    }
1319
  }
1320

    
1321
  /**
1322
   * Execute the given display, with the given arguments.
1323
   * To be called externally by whatever mechanism invokes the view,
1324
   * such as a page callback, hook_block, etc.
1325
   *
1326
   * This function should NOT be used by anything external as this
1327
   * returns data in the format specified by the display. It can also
1328
   * have other side effects that are only intended for the 'proper'
1329
   * use of the display, such as setting page titles and breadcrumbs.
1330
   *
1331
   * If you simply want to view the display, use view::preview() instead.
1332
   */
1333
  function execute_display($display_id = NULL, $args = array()) {
1334
    if (empty($this->current_display) || $this->current_display != $this->choose_display($display_id)) {
1335
      if (!$this->set_display($display_id)) {
1336
        return FALSE;
1337
      }
1338
    }
1339

    
1340
    $this->pre_execute($args);
1341

    
1342
    // Execute the view
1343
    $output = $this->display_handler->execute();
1344

    
1345
    $this->post_execute();
1346
    return $output;
1347
  }
1348

    
1349
  /**
1350
   * Preview the given display, with the given arguments.
1351
   *
1352
   * To be called externally, probably by an AJAX handler of some flavor.
1353
   * Can also be called when views are embedded, as this guarantees
1354
   * normalized output.
1355
   */
1356
  function preview($display_id = NULL, $args = array()) {
1357
    if (empty($this->current_display) || ((!empty($display_id)) && $this->current_display != $display_id)) {
1358
      if (!$this->set_display($display_id)) {
1359
        return FALSE;
1360
      }
1361
    }
1362

    
1363
    $this->preview = TRUE;
1364
    $this->pre_execute($args);
1365
    // Preview the view.
1366
    $output = $this->display_handler->preview();
1367

    
1368
    $this->post_execute();
1369
    return $output;
1370
  }
1371

    
1372
  /**
1373
   * Run attachments and let the display do what it needs to do prior
1374
   * to running.
1375
   */
1376
  function pre_execute($args = array()) {
1377
    $this->old_view[] = views_get_current_view();
1378
    views_set_current_view($this);
1379
    $display_id = $this->current_display;
1380

    
1381
    // Prepare the view with the information we have, but only if we were
1382
    // passed arguments, as they may have been set previously.
1383
    if ($args) {
1384
      $this->set_arguments($args);
1385
    }
1386

    
1387
    // Let modules modify the view just prior to executing it.
1388
    foreach (module_implements('views_pre_view') as $module) {
1389
      $function = $module . '_views_pre_view';
1390
      $function($this, $display_id, $this->args);
1391
    }
1392

    
1393
    // Allow hook_views_pre_view() to set the dom_id, then ensure it is set.
1394
    $this->dom_id = !empty($this->dom_id) ? $this->dom_id : md5($this->name . REQUEST_TIME . rand());
1395

    
1396
    // Allow the display handler to set up for execution
1397
    $this->display_handler->pre_execute();
1398
  }
1399

    
1400
  /**
1401
   * Unset the current view, mostly.
1402
   */
1403
  function post_execute() {
1404
    // unset current view so we can be properly destructed later on.
1405
    // Return the previous value in case we're an attachment.
1406

    
1407
    if ($this->old_view) {
1408
      $old_view = array_pop($this->old_view);
1409
    }
1410

    
1411
    views_set_current_view(isset($old_view) ? $old_view : FALSE);
1412
  }
1413

    
1414
  /**
1415
   * Run attachment displays for the view.
1416
   */
1417
  function attach_displays() {
1418
    if (!empty($this->is_attachment)) {
1419
      return;
1420
    }
1421

    
1422
    if (!$this->display_handler->accept_attachments()) {
1423
      return;
1424
    }
1425

    
1426
    $this->is_attachment = TRUE;
1427
    // Give other displays an opportunity to attach to the view.
1428
    foreach ($this->display as $id => $display) {
1429
      if (!empty($this->display[$id]->handler)) {
1430
        $this->display[$id]->handler->attach_to($this->current_display);
1431
      }
1432
    }
1433
    $this->is_attachment = FALSE;
1434
  }
1435

    
1436
  /**
1437
   * Called to get hook_menu() information from the view and the named display handler.
1438
   *
1439
   * @param $display_id
1440
   *   A display id.
1441
   * @param $callbacks
1442
   *   A menu callback array passed from views_menu_alter().
1443
   */
1444
  function execute_hook_menu($display_id = NULL, &$callbacks = array()) {
1445
    // Prepare the view with the information we have.
1446

    
1447
    // This was probably already called, but it's good to be safe.
1448
    if (!$this->set_display($display_id)) {
1449
      return FALSE;
1450
    }
1451

    
1452
    // Execute the view
1453
    if (isset($this->display_handler)) {
1454
      return $this->display_handler->execute_hook_menu($callbacks);
1455
    }
1456
  }
1457

    
1458
  /**
1459
   * Called to get hook_block information from the view and the
1460
   * named display handler.
1461
   */
1462
  function execute_hook_block_list($display_id = NULL) {
1463
    // Prepare the view with the information we have.
1464

    
1465
    // This was probably already called, but it's good to be safe.
1466
    if (!$this->set_display($display_id)) {
1467
      return FALSE;
1468
    }
1469

    
1470
    // Execute the view
1471
    if (isset($this->display_handler)) {
1472
      return $this->display_handler->execute_hook_block_list();
1473
    }
1474
  }
1475

    
1476
  /**
1477
   * Determine if the given user has access to the view. Note that
1478
   * this sets the display handler if it hasn't been.
1479
   */
1480
  function access($displays = NULL, $account = NULL) {
1481
    // Noone should have access to disabled views.
1482
    if (!empty($this->disabled)) {
1483
      return FALSE;
1484
    }
1485

    
1486
    if (!isset($this->current_display)) {
1487
      $this->init_display();
1488
    }
1489

    
1490
    if (!$account) {
1491
      $account = $GLOBALS['user'];
1492
    }
1493

    
1494
    // We can't use choose_display() here because that function
1495
    // calls this one.
1496
    $displays = (array)$displays;
1497
    foreach ($displays as $display_id) {
1498
      if (!empty($this->display[$display_id]->handler)) {
1499
        if ($this->display[$display_id]->handler->access($account)) {
1500
          return TRUE;
1501
        }
1502
      }
1503
    }
1504

    
1505
    return FALSE;
1506
  }
1507

    
1508
  /**
1509
   * Get the view's current title. This can change depending upon how it
1510
   * was built.
1511
   */
1512
  function get_title() {
1513
    if (empty($this->display_handler)) {
1514
      if (!$this->set_display('default')) {
1515
        return FALSE;
1516
      }
1517
    }
1518

    
1519
    // During building, we might find a title override. If so, use it.
1520
    if (!empty($this->build_info['title'])) {
1521
      $title = $this->build_info['title'];
1522
    }
1523
    else {
1524
      $title = $this->display_handler->get_option('title');
1525
    }
1526

    
1527
    // Allow substitutions from the first row.
1528
    if ($this->init_style()) {
1529
      $title = $this->style_plugin->tokenize_value($title, 0);
1530
    }
1531
    return $title;
1532
  }
1533

    
1534
  /**
1535
   * Override the view's current title.
1536
   *
1537
   * The tokens in the title get's replaced before rendering.
1538
   */
1539
  function set_title($title) {
1540
     $this->build_info['title'] = $title;
1541
     return TRUE;
1542
   }
1543

    
1544
  /**
1545
   * Return the human readable name for a view.
1546
   *
1547
   * When a certain view doesn't have a human readable name return the machine readable name.
1548
   */
1549
  function get_human_name() {
1550
    if (!empty($this->human_name)) {
1551
      $human_name = $this->human_name;
1552
    }
1553
    else {
1554
      $human_name = $this->name;
1555
    }
1556
    return $human_name;
1557
  }
1558

    
1559
  /**
1560
   * Force the view to build a title.
1561
   */
1562
  function build_title() {
1563
    $this->init_display();
1564

    
1565
    if (empty($this->built)) {
1566
      $this->init_query();
1567
    }
1568

    
1569
    $this->init_handlers();
1570

    
1571
    $this->_build_arguments();
1572
  }
1573

    
1574
  /**
1575
   * Get the URL for the current view.
1576
   *
1577
   * This URL will be adjusted for arguments.
1578
   */
1579
  function get_url($args = NULL, $path = NULL) {
1580
    if (!empty($this->override_url)) {
1581
      return $this->override_url;
1582
    }
1583

    
1584
    if (!isset($path)) {
1585
      $path = $this->get_path();
1586
    }
1587
    if (!isset($args)) {
1588
      $args = $this->args;
1589

    
1590
      // Exclude arguments that were computed, not passed on the URL.
1591
      $position = 0;
1592
      if (!empty($this->argument)) {
1593
        foreach ($this->argument as $argument_id => $argument) {
1594
          if (!empty($argument->options['default_argument_skip_url'])) {
1595
            unset($args[$position]);
1596
          }
1597
          $position++;
1598
        }
1599
      }
1600
    }
1601
    // Don't bother working if there's nothing to do:
1602
    if (empty($path) || (empty($args) && strpos($path, '%') === FALSE)) {
1603
      return $path;
1604
    }
1605

    
1606
    $pieces = array();
1607
    $argument_keys = isset($this->argument) ? array_keys($this->argument) : array();
1608
    $id = current($argument_keys);
1609
    foreach (explode('/', $path) as $piece) {
1610
      if ($piece != '%') {
1611
        $pieces[] = $piece;
1612
      }
1613
      else {
1614
        if (empty($args)) {
1615
          // Try to never put % in a url; use the wildcard instead.
1616
          if ($id && !empty($this->argument[$id]->options['exception']['value'])) {
1617
            $pieces[] = $this->argument[$id]->options['exception']['value'];
1618
          }
1619
          else {
1620
            $pieces[] = '*'; // gotta put something if there just isn't one.
1621
          }
1622

    
1623
        }
1624
        else {
1625
          $pieces[] = array_shift($args);
1626
        }
1627

    
1628
        if ($id) {
1629
          $id = next($argument_keys);
1630
        }
1631
      }
1632
    }
1633

    
1634
    if (!empty($args)) {
1635
      $pieces = array_merge($pieces, $args);
1636
    }
1637
    return implode('/', $pieces);
1638
  }
1639

    
1640
  /**
1641
   * Get the base path used for this view.
1642
   */
1643
  function get_path() {
1644
    if (!empty($this->override_path)) {
1645
      return $this->override_path;
1646
    }
1647

    
1648
    if (empty($this->display_handler)) {
1649
      if (!$this->set_display('default')) {
1650
        return FALSE;
1651
      }
1652
    }
1653
    return $this->display_handler->get_path();
1654
  }
1655

    
1656
  /**
1657
   * Get the breadcrumb used for this view.
1658
   *
1659
   * @param $set
1660
   *   If true, use drupal_set_breadcrumb() to install the breadcrumb.
1661
   */
1662
  function get_breadcrumb($set = FALSE) {
1663
    // Now that we've built the view, extract the breadcrumb.
1664
    $base = TRUE;
1665
    $breadcrumb = array();
1666

    
1667
    if (!empty($this->build_info['breadcrumb'])) {
1668
      foreach ($this->build_info['breadcrumb'] as $path => $title) {
1669
        // Check to see if the frontpage is in the breadcrumb trail; if it
1670
        // is, we'll remove that from the actual breadcrumb later.
1671
        if ($path == variable_get('site_frontpage', 'node')) {
1672
          $base = FALSE;
1673
          $title = t('Home');
1674
        }
1675
        if ($title) {
1676
          $breadcrumb[] = l($title, $path, array('html' => TRUE));
1677
        }
1678
      }
1679

    
1680
      if ($set) {
1681
        if ($base) {
1682
          $breadcrumb = array_merge(drupal_get_breadcrumb(), $breadcrumb);
1683
        }
1684
        drupal_set_breadcrumb($breadcrumb);
1685
      }
1686
    }
1687
    return $breadcrumb;
1688
  }
1689

    
1690
  /**
1691
   * Is this view cacheable?
1692
   */
1693
  function is_cacheable() {
1694
    return $this->is_cacheable;
1695
  }
1696

    
1697
  /**
1698
   * Set up query capturing.
1699
   *
1700
   * db_query() stores the queries that it runs in global $queries,
1701
   * bit only if dev_query is set to true. In this case, we want
1702
   * to temporarily override that setting if it's not and we
1703
   * can do that without forcing a db rewrite by just manipulating
1704
   * $conf. This is kind of evil but it works.
1705
   */
1706
  function start_query_capture() {
1707
    global $conf, $queries;
1708
    if (empty($conf['dev_query'])) {
1709
      $this->fix_dev_query = TRUE;
1710
      $conf['dev_query'] = TRUE;
1711
    }
1712

    
1713
    // Record the last query key used; anything already run isn't
1714
    // a query that we are interested in.
1715
    $this->last_query_key = NULL;
1716

    
1717
    if (!empty($queries)) {
1718
      $keys = array_keys($queries);
1719
      $this->last_query_key = array_pop($keys);
1720
    }
1721
  }
1722

    
1723
  /**
1724
   * Add the list of queries run during render to buildinfo.
1725
   *
1726
   * @see view::start_query_capture()
1727
   */
1728
  function end_query_capture() {
1729
    global $conf, $queries;
1730
    if (!empty($this->fix_dev_query)) {
1731
      $conf['dev_query'] = FALSE;
1732
    }
1733

    
1734
    // make a copy of the array so we can manipulate it with array_splice.
1735
    $temp = $queries;
1736

    
1737
    // Scroll through the queries until we get to our last query key.
1738
    // Unset anything in our temp array.
1739
    if (isset($this->last_query_key)) {
1740
      while (list($id, $query) = each($queries)) {
1741
        if ($id == $this->last_query_key) {
1742
          break;
1743
        }
1744

    
1745
        unset($temp[$id]);
1746
      }
1747
    }
1748

    
1749
    $this->additional_queries = $temp;
1750
  }
1751

    
1752
  /**
1753
   * Static factory method to load a list of views based upon a $where clause.
1754
   *
1755
   * Although this method could be implemented to simply iterate over views::load(),
1756
   * that would be very slow.  Buiding the views externally from unified queries is
1757
   * much faster.
1758
   */
1759
  static function load_views() {
1760
    $result = db_query("SELECT DISTINCT v.* FROM {views_view} v");
1761
    $views = array();
1762

    
1763
    // Load all the views.
1764
    foreach ($result as $data) {
1765
      $view = new view;
1766
      $view->load_row($data);
1767
      $view->loaded = TRUE;
1768
      $view->type = t('Normal');
1769
      $views[$view->name] = $view;
1770
      $names[$view->vid] = $view->name;
1771
    }
1772

    
1773
    // Stop if we didn't get any views.
1774
    if (!$views) {
1775
      return array();
1776
    }
1777

    
1778
    // Now load all the subtables:
1779
    foreach (view::db_objects() as $key) {
1780
      $object_name = "views_$key";
1781
      $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1782
        array(':vids' => array_keys($names)));
1783

    
1784
      foreach ($result as $data) {
1785
        $object = new $object_name(FALSE);
1786
        $object->load_row($data);
1787

    
1788
        // Because it can get complicated with this much indirection,
1789
        // make a shortcut reference.
1790
        $location = &$views[$names[$object->vid]]->$key;
1791

    
1792
        // If we have a basic id field, load the item onto the view based on
1793
        // this ID, otherwise push it on.
1794
        if (!empty($object->id)) {
1795
          $location[$object->id] = $object;
1796
        }
1797
        else {
1798
          $location[] = $object;
1799
        }
1800
      }
1801
    }
1802
    return $views;
1803
  }
1804

    
1805
  /**
1806
   * Save the view to the database. If the view does not already exist,
1807
   * A vid will be assigned to the view and also returned from this function.
1808
   */
1809
  function save() {
1810
    if ($this->vid == 'new') {
1811
      $this->vid = NULL;
1812
    }
1813
    // If there is no vid, check if a view with this machine name already exists.
1814
    elseif (empty($this->vid)) {
1815
      $vid = db_query("SELECT vid from {views_view} WHERE name = :name", array(':name' => $this->name))->fetchField();
1816
      $this->vid = $vid ? $vid : NULL;
1817
    }
1818

    
1819
    // Let modules modify the view just prior to saving it.
1820
    module_invoke_all('views_view_presave', $this);
1821

    
1822
    $transaction = db_transaction();
1823

    
1824
    try {
1825
      // If we have no vid or our vid is a string, this is a new view.
1826
      if (!empty($this->vid)) {
1827
        // remove existing table entries
1828
        foreach ($this->db_objects() as $key) {
1829
          db_delete('views_' . $key)
1830
            ->condition('vid', $this->vid)
1831
            ->execute();
1832
        }
1833
      }
1834

    
1835
      $this->save_row(!empty($this->vid) ? 'vid' : FALSE);
1836

    
1837
      // Save all of our subtables.
1838
      foreach ($this->db_objects() as $key) {
1839
        $this->_save_rows($key);
1840
      }
1841
    }
1842
    catch (Exception $e) {
1843
      $transaction->rollback();
1844
      watchdog_exception('views', $e);
1845
      throw $e;
1846
    }
1847

    
1848
    $this->save_locale_strings();
1849

    
1850
    // Clear caches.
1851
    views_invalidate_cache();
1852

    
1853
    // Notify modules that this view has been saved.
1854
    module_invoke_all('views_view_save', $this);
1855
  }
1856

    
1857
  /**
1858
   * Save a row to the database for the given key, which is one of the
1859
   * keys from view::db_objects()
1860
   */
1861
  function _save_rows($key) {
1862
    $count = 0;
1863
    foreach ($this->$key as $position => $object) {
1864
      $object->position = ++$count;
1865
      $object->vid = $this->vid;
1866
      $object->save_row();
1867
    }
1868
  }
1869

    
1870
  /**
1871
   * Delete the view from the database.
1872
   */
1873
  function delete($clear = TRUE) {
1874
    if (empty($this->vid)) {
1875
      return;
1876
    }
1877

    
1878
    db_delete('views_view')
1879
      ->condition('vid', $this->vid)
1880
      ->execute();
1881
    // Delete from all of our subtables as well.
1882
    foreach ($this->db_objects() as $key) {
1883
      db_delete('views_'. $key)
1884
        ->condition('vid', $this->vid)
1885
        ->execute();
1886
    }
1887

    
1888
    cache_clear_all('views_query:' . $this->name, 'cache_views');
1889

    
1890
    if ($clear) {
1891
      // Clear caches.
1892
      views_invalidate_cache();
1893
    }
1894

    
1895
    // Notify modules that this view has been deleted.
1896
    module_invoke_all('views_view_delete', $this);
1897
  }
1898

    
1899
  /**
1900
   * Export a view as PHP code.
1901
   */
1902
  function export($indent = '') {
1903
    $this->init_display();
1904
    $this->init_query();
1905
    $output = '';
1906
    $output .= $this->export_row('view', $indent);
1907
    // Set the API version
1908
    $output .= $indent . '$view->api_version = \'' . views_api_version() . "';\n";
1909
    $output .= $indent . '$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */' . "\n";
1910

    
1911
    foreach ($this->display as $id => $display) {
1912
      $output .= "\n" . $indent . "/* Display: $display->display_title */\n";
1913
      $output .= $indent . '$handler = $view->new_display(' . ctools_var_export($display->display_plugin, $indent) . ', ' . ctools_var_export($display->display_title, $indent) . ', \'' . $id . "');\n";
1914
      if (empty($display->handler)) {
1915
        // @todo -- probably need a method of exporting broken displays as
1916
        // they may simply be broken because a module is not installed. That
1917
        // does not invalidate the display.
1918
        continue;
1919
      }
1920

    
1921
      $output .= $display->handler->export_options($indent, '$handler->options');
1922
    }
1923

    
1924
    // Give the localization system a chance to export translatables to code.
1925
    if ($this->init_localization()) {
1926
      $this->export_locale_strings('export');
1927
      $translatables = $this->localization_plugin->export_render($indent);
1928
      if (!empty($translatables)) {
1929
        $output .= $translatables;
1930
      }
1931
    }
1932

    
1933
    return $output;
1934
  }
1935

    
1936
  /**
1937
   * Make a copy of this view that has been sanitized of all database IDs
1938
   * and handlers and other stuff.
1939
   *
1940
   * I'd call this clone() but it's reserved.
1941
   */
1942
  function copy() {
1943
    $code = $this->export();
1944
    eval($code);
1945
    return $view;
1946
  }
1947

    
1948
  /**
1949
   * Safely clone a view.
1950
   *
1951
   * Because views are complicated objects within objects, and PHP loves to
1952
   * do references to everything, if a View is not properly and safely
1953
   * cloned it will still have references to the original view, and can
1954
   * actually cause the original view to point to objects in the cloned
1955
   * view. This gets ugly fast.
1956
   *
1957
   * This will completely wipe a view clean so it can be considered fresh.
1958
   *
1959
   * @return view
1960
   *    The cloned view.
1961
   */
1962
  function clone_view() {
1963
    $clone = version_compare(phpversion(), '5.0') < 0 ? $this : clone($this);
1964

    
1965
    $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');
1966
    foreach ($keys as $key) {
1967
      if (isset($clone->$key)) {
1968
        unset($clone->$key);
1969
      }
1970
    }
1971
    $clone->built = $clone->executed = FALSE;
1972
    $clone->build_info = array();
1973
    $clone->attachment_before = '';
1974
    $clone->attachment_after = '';
1975
    $clone->result = array();
1976

    
1977
    // shallow cloning means that all the display objects
1978
    // *were not cloned*. We must clone them ourselves.
1979
    $displays = array();
1980
    foreach ($clone->display as $id => $display) {
1981
      $displays[$id] = clone $display;
1982
      if (isset($displays[$id]->handler)) {
1983
        unset($displays[$id]->handler);
1984
      }
1985
    }
1986
    $clone->display = $displays;
1987

    
1988
    return $clone;
1989
  }
1990

    
1991
  /**
1992
   * Unset references so that a $view object may be properly garbage
1993
   * collected.
1994
   */
1995
  function destroy() {
1996
    foreach (array_keys($this->display) as $display_id) {
1997
      if (isset($this->display[$display_id]->handler)) {
1998
        $this->display[$display_id]->handler->destroy();
1999
        unset($this->display[$display_id]->handler);
2000
      }
2001
    }
2002

    
2003
    foreach (views_object_types() as $type => $info) {
2004
      if (isset($this->$type)) {
2005
        $handlers = &$this->$type;
2006
        foreach ($handlers as $id => $item) {
2007
          $handlers[$id]->destroy();
2008
        }
2009
        unset($handlers);
2010
      }
2011
    }
2012

    
2013
    if (isset($this->style_plugin)) {
2014
      $this->style_plugin->destroy();
2015
      unset($this->style_plugin);
2016
    }
2017

    
2018
    // Clear these to make sure the view can be processed/used again.
2019
    if (isset($this->display_handler)) {
2020
      unset($this->display_handler);
2021
    }
2022

    
2023
    if (isset($this->current_display)) {
2024
      unset($this->current_display);
2025
    }
2026

    
2027
    if (isset($this->query)) {
2028
      unset($this->query);
2029
    }
2030

    
2031
    $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');
2032
    foreach ($keys as $key) {
2033
      if (isset($this->$key)) {
2034
        unset($this->$key);
2035
      }
2036
    }
2037

    
2038
    // These keys are checked by the next init, so instead of unsetting them,
2039
    // just set the default values.
2040
    $keys = array('items_per_page', 'offset', 'current_page');
2041
    foreach ($keys as $key) {
2042
      if (isset($this->$key)) {
2043
        $this->$key = NULL;
2044
      }
2045
    }
2046

    
2047
    $this->built = $this->executed = FALSE;
2048
    $this->build_info = array();
2049
    $this->attachment_before = '';
2050
    $this->attachment_after = '';
2051
  }
2052

    
2053
  /**
2054
   * Make sure the view is completely valid.
2055
   *
2056
   * @return
2057
   *   TRUE if the view is valid; an array of error strings if it is not.
2058
   */
2059
  function validate() {
2060
    $this->init_display();
2061

    
2062
    $errors = array();
2063
    $this->display_errors = NULL;
2064

    
2065
    $current_display = $this->current_display;
2066
    foreach ($this->display as $id => $display) {
2067
      if ($display->handler) {
2068
        if (!empty($display->deleted)) {
2069
          continue;
2070
        }
2071

    
2072
        $result = $this->display[$id]->handler->validate();
2073
        if (!empty($result) && is_array($result)) {
2074
          $errors = array_merge($errors, $result);
2075
          // Mark this display as having validation errors.
2076
          $this->display_errors[$id] = TRUE;
2077
        }
2078
      }
2079
    }
2080

    
2081
    $this->set_display($current_display);
2082
    return $errors ? $errors : TRUE;
2083
  }
2084

    
2085
  /**
2086
   * Find and initialize the localization plugin.
2087
   */
2088
  function init_localization() {
2089
    // If the translate attribute isn't set, init the localization plugin.
2090
    if (!isset($this->localization_plugin->translate)) {
2091
      $this->localization_plugin = views_get_plugin('localization', views_get_localization_plugin());
2092

    
2093
      // If the plugin is still not set, turn off all localization by using the
2094
      // views_plugin_localization_none plugin. This plugin has the translate
2095
      // property set to FALSE, signifying localization should not occur.
2096
      if (empty($this->localization_plugin)) {
2097
        $this->localization_plugin = views_get_plugin('localization', 'none');
2098
      }
2099

    
2100
      // Init the plugin.
2101
      $this->localization_plugin->init($this);
2102
    }
2103

    
2104
    // Return the value of the translate property. This is set to FALSE if
2105
    // localization is off.
2106
    return $this->localization_plugin->translate;
2107
  }
2108

    
2109
  /**
2110
   * Determine whether a view supports admin string translation.
2111
   */
2112
  function is_translatable() {
2113
    // Use translation no matter what type of view.
2114
    if (variable_get('views_localize_all', FALSE)) {
2115
      return TRUE;
2116
    }
2117
    // If the view is normal or overridden, use admin string translation.
2118
    // A newly created view won't have a type. Accept this.
2119
    return (!isset($this->type) || in_array($this->type, array(t('Normal'), t('Overridden')))) ? TRUE : FALSE;
2120
  }
2121

    
2122
  /**
2123
   * Send strings for localization.
2124
   */
2125
  function save_locale_strings() {
2126
    $this->process_locale_strings('save');
2127
  }
2128

    
2129
  /**
2130
   * Delete localized strings.
2131
   */
2132
  function delete_locale_strings() {
2133
    $this->process_locale_strings('delete');
2134
  }
2135

    
2136
  /**
2137
   * Export localized strings.
2138
   */
2139
  function export_locale_strings() {
2140
    $this->process_locale_strings('export');
2141
  }
2142

    
2143
  /**
2144
   * Process strings for localization, deletion or export to code.
2145
   */
2146
  function process_locale_strings($op) {
2147
    // Ensure this view supports translation, we have a display, and we
2148
    // have a localization plugin.
2149
    // @fixme Export does not init every handler.
2150
    if (($this->is_translatable() || $op == 'export') && $this->init_display() && $this->init_localization()) {
2151
      $this->localization_plugin->process_locale_strings($op);
2152
    }
2153
  }
2154

    
2155
}
2156

    
2157
/**
2158
 * Base class for views' database objects.
2159
 */
2160
class views_db_object {
2161
  public $db_table;
2162

    
2163
  /**
2164
   * Initialize this object, setting values from schema defaults.
2165
   *
2166
   * @param $init
2167
   *   If an array, this is a set of values from db_fetch_object to
2168
   *   load. Otherwse, if TRUE values will be filled in from schema
2169
   *   defaults.
2170
   */
2171
  function init($init = TRUE) {
2172
    if (is_array($init)) {
2173
      return $this->load_row($init);
2174
    }
2175

    
2176
    if (!$init) {
2177
      return;
2178
    }
2179

    
2180
    $schema = drupal_get_schema($this->db_table);
2181

    
2182
    if (!$schema) {
2183
      return;
2184
    }
2185

    
2186
    // Go through our schema and build correlations.
2187
    foreach ($schema['fields'] as $field => $info) {
2188
      if ($info['type'] == 'serial') {
2189
        $this->$field = NULL;
2190
      }
2191
      if (!isset($this->$field)) {
2192
        if (!empty($info['serialize']) && isset($info['serialized default'])) {
2193
          $this->$field = unserialize($info['serialized default']);
2194
        }
2195
        elseif (isset($info['default'])) {
2196
          $this->$field = $info['default'];
2197
        }
2198
        else {
2199
          $this->$field = '';
2200
        }
2201
      }
2202
    }
2203
  }
2204

    
2205
  /**
2206
   * Write the row to the database.
2207
   *
2208
   * @param $update
2209
   *   If true this will be an UPDATE query. Otherwise it will be an INSERT.
2210
   */
2211
  function save_row($update = NULL) {
2212
    $fields = $defs = $values = $serials = array();
2213
    $schema = drupal_get_schema($this->db_table);
2214

    
2215
    // Go through our schema and build correlations.
2216
    foreach ($schema['fields'] as $field => $info) {
2217
      // special case -- skip serial types if we are updating.
2218
      if ($info['type'] == 'serial') {
2219
        $serials[] = $field;
2220
        continue;
2221
      }
2222
      elseif ($info['type'] == 'int') {
2223
        $this->$field = (int) $this->$field;
2224
      }
2225
      $fields[$field] = empty($info['serialize']) ? $this->$field : serialize($this->$field);
2226
    }
2227
    if (!$update) {
2228
      $query = db_insert($this->db_table);
2229
    }
2230
    else {
2231
      $query = db_update($this->db_table)
2232
        ->condition($update, $this->$update);
2233
    }
2234
    $return = $query
2235
      ->fields($fields)
2236
      ->execute();
2237

    
2238
    if ($serials && !$update) {
2239
      // get last insert ids and fill them in.
2240
      // Well, one ID.
2241
      foreach ($serials as $field) {
2242
        $this->$field = $return;
2243
      }
2244
    }
2245
  }
2246

    
2247
  /**
2248
   * Load the object with a row from the database.
2249
   *
2250
   * This method is separate from the constructor in order to give us
2251
   * more flexibility in terms of how the view object is built in different
2252
   * contexts.
2253
   *
2254
   * @param $data
2255
   *   An object from db_fetch_object. It should contain all of the fields
2256
   *   that are in the schema.
2257
   */
2258
  function load_row($data) {
2259
    $schema = drupal_get_schema($this->db_table);
2260

    
2261
    // Go through our schema and build correlations.
2262
    foreach ($schema['fields'] as $field => $info) {
2263
      $this->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
2264
    }
2265
  }
2266

    
2267
  /**
2268
   * Export a loaded row, such as an argument, field or the view itself to PHP code.
2269
   *
2270
   * @param $identifier
2271
   *   The variable to assign the PHP code for this object to.
2272
   * @param $indent
2273
   *   An optional indentation for prettifying nested code.
2274
   */
2275
  function export_row($identifier = NULL, $indent = '') {
2276
    ctools_include('export');
2277

    
2278
    if (!$identifier) {
2279
      $identifier = $this->db_table;
2280
    }
2281
    $schema = drupal_get_schema($this->db_table);
2282

    
2283
    $output = $indent . '$' . $identifier . ' = new ' . get_class($this) . "();\n";
2284
    // Go through our schema and build correlations.
2285
    foreach ($schema['fields'] as $field => $info) {
2286
      if (!empty($info['no export'])) {
2287
        continue;
2288
      }
2289
      if (!isset($this->$field)) {
2290
        if (isset($info['default'])) {
2291
          $this->$field = $info['default'];
2292
        }
2293
        else {
2294
          $this->$field = '';
2295
        }
2296

    
2297
        // serialized defaults must be set as serialized.
2298
        if (isset($info['serialize'])) {
2299
          $this->$field = unserialize($this->$field);
2300
        }
2301
      }
2302
      $value = $this->$field;
2303
      if ($info['type'] == 'int') {
2304
        if (isset($info['size']) && $info['size'] == 'tiny') {
2305
          $value = (bool) $value;
2306
        }
2307
        else {
2308
          $value = (int) $value;
2309
        }
2310
      }
2311

    
2312
      $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
2313
    }
2314
    return $output;
2315
  }
2316

    
2317
  /**
2318
   * Add a new display handler to the view, automatically creating an id.
2319
   *
2320
   * @param $type
2321
   *   The plugin type from the views plugin data. Defaults to 'page'.
2322
   * @param $title
2323
   *   The title of the display; optional, may be filled in from default.
2324
   * @param $id
2325
   *   The id to use.
2326
   * @return
2327
   *   The key to the display in $view->display, so that the new display
2328
   *   can be easily located.
2329
   */
2330
  function add_display($type = 'page', $title = NULL, $id = NULL) {
2331
    if (empty($type)) {
2332
      return FALSE;
2333
    }
2334

    
2335
    $plugin = views_fetch_plugin_data('display', $type);
2336
    if (empty($plugin)) {
2337
      $plugin['title'] = t('Broken');
2338
    }
2339

    
2340

    
2341
    if (empty($id)) {
2342
      $id = $this->generate_display_id($type);
2343
      if ($id !== 'default') {
2344
        preg_match("/[0-9]+/", $id, $count);
2345
        $count = $count[0];
2346
      }
2347
      else {
2348
        $count = '';
2349
      }
2350

    
2351
      if (empty($title)) {
2352
        if ($count > 1) {
2353
          $title = $plugin['title'] . ' ' . $count;
2354
        }
2355
        else {
2356
          $title = $plugin['title'];
2357
        }
2358
      }
2359
    }
2360

    
2361
    // Create the new display object
2362
    $display = new views_display;
2363
    $display->options($type, $id, $title);
2364

    
2365
    // Add the new display object to the view.
2366
    $this->display[$id] = $display;
2367
    return $id;
2368
  }
2369

    
2370
  /**
2371
   * Generate a display id of a certain plugin type.
2372
   *
2373
   * @param $type
2374
   *   Which plugin should be used for the new display id.
2375
   */
2376
  function generate_display_id($type) {
2377
    // 'default' is singular and is unique, so just go with 'default'
2378
    // for it. For all others, start counting.
2379
    if ($type == 'default') {
2380
      return 'default';
2381
    }
2382
    // Initial id.
2383
    $id = $type . '_1';
2384
    $count = 1;
2385

    
2386
    // Loop through IDs based upon our style plugin name until
2387
    // we find one that is unused.
2388
    while (!empty($this->display[$id])) {
2389
      $id = $type . '_' . ++$count;
2390
    }
2391

    
2392
    return $id;
2393
  }
2394

    
2395
  /**
2396
   * Generates a unique ID for an item.
2397
   *
2398
   * These items are typically fields, filters, sort criteria, or arguments.
2399
   *
2400
   * @param $requested_id
2401
   *   The requested ID for the item.
2402
   * @param $existing_items
2403
   *   An array of existing items, keyed by their IDs.
2404
   *
2405
   * @return
2406
   *   A unique ID. This will be equal to $requested_id if no item with that ID
2407
   *   already exists. Otherwise, it will be appended with an integer to make
2408
   *   it unique, e.g. "{$requested_id}_1", "{$requested_id}_2", etc.
2409
   */
2410
  public static function generate_item_id($requested_id, $existing_items) {
2411
    $count = 0;
2412
    $id = $requested_id;
2413
    while (!empty($existing_items[$id])) {
2414
      $id = $requested_id . '_' . ++$count;
2415
    }
2416
    return $id;
2417
  }
2418

    
2419
  /**
2420
   * Create a new display and a display handler for it.
2421
   * @param $type
2422
   *   The plugin type from the views plugin data. Defaults to 'page'.
2423
   * @param $title
2424
   *   The title of the display; optional, may be filled in from default.
2425
   * @param $id
2426
   *   The id to use.
2427
   * @return views_plugin_display
2428
   *   A reference to the new handler object.
2429
   */
2430
  function &new_display($type = 'page', $title = NULL, $id = NULL) {
2431
    $id = $this->add_display($type, $title, $id);
2432

    
2433
    // Create a handler
2434
    $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
2435
    if (empty($this->display[$id]->handler)) {
2436
      // provide a 'default' handler as an emergency. This won't work well but
2437
      // it will keep things from crashing.
2438
      $this->display[$id]->handler = views_get_plugin('display', 'default');
2439
    }
2440

    
2441
    if (!empty($this->display[$id]->handler)) {
2442
      // Initialize the new display handler with data.
2443
      $this->display[$id]->handler->init($this, $this->display[$id]);
2444
      // If this is NOT the default display handler, let it know which is
2445
      if ($id != 'default') {
2446
        $this->display[$id]->handler->default_display = &$this->display['default']->handler;
2447
      }
2448
    }
2449

    
2450
    return $this->display[$id]->handler;
2451
  }
2452

    
2453
  /**
2454
   * Add an item with a handler to the view.
2455
   *
2456
   * These items may be fields, filters, sort criteria, or arguments.
2457
   */
2458
  function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
2459
    $types = views_object_types();
2460
    $this->set_display($display_id);
2461

    
2462
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2463

    
2464
    if (empty($id)) {
2465
      $id = $this->generate_item_id($field, $fields);
2466
    }
2467

    
2468
    $new_item = array(
2469
      'id' => $id,
2470
      'table' => $table,
2471
      'field' => $field,
2472
    ) + $options;
2473

    
2474
    if (!empty($types[$type]['type'])) {
2475
      $handler_type = $types[$type]['type'];
2476
    }
2477
    else {
2478
      $handler_type = $type;
2479
    }
2480

    
2481
    $handler = views_get_handler($table, $field, $handler_type);
2482

    
2483
    $fields[$id] = $new_item;
2484
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2485

    
2486
    return $id;
2487
  }
2488

    
2489
  /**
2490
   * Get an array of items for the current display.
2491
   */
2492
  function get_items($type, $display_id = NULL) {
2493
    $this->set_display($display_id);
2494

    
2495
    if (!isset($display_id)) {
2496
      $display_id = $this->current_display;
2497
    }
2498

    
2499
    // Get info about the types so we can get the right data.
2500
    $types = views_object_types();
2501
    return $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2502
  }
2503

    
2504
  /**
2505
   * Get the configuration of an item (field/sort/filter/etc) on a given
2506
   * display.
2507
   */
2508
  function get_item($display_id, $type, $id) {
2509
    // Get info about the types so we can get the right data.
2510
    $types = views_object_types();
2511
    // Initialize the display
2512
    $this->set_display($display_id);
2513

    
2514
    // Get the existing configuration
2515
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2516

    
2517
    return isset($fields[$id]) ? $fields[$id] : NULL;
2518
  }
2519

    
2520
  /**
2521
   * Set the configuration of an item (field/sort/filter/etc) on a given
2522
   * display.
2523
   *
2524
   * Pass in NULL for the $item to remove an item.
2525
   */
2526
  function set_item($display_id, $type, $id, $item) {
2527
    // Get info about the types so we can get the right data.
2528
    $types = views_object_types();
2529
    // Initialize the display
2530
    $this->set_display($display_id);
2531

    
2532
    // Get the existing configuration
2533
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2534
    if (isset($item)) {
2535
      $fields[$id] = $item;
2536
    }
2537
    else {
2538
      unset($fields[$id]);
2539
    }
2540

    
2541
    // Store.
2542
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2543
  }
2544

    
2545
  /**
2546
   * Set an option on an item.
2547
   *
2548
   * Use this only if you have just 1 or 2 options to set; if you have
2549
   * many, consider getting the item, adding the options and doing
2550
   * set_item yourself.
2551
   */
2552
  function set_item_option($display_id, $type, $id, $option, $value) {
2553
    $item = $this->get_item($display_id, $type, $id);
2554
    $item[$option] = $value;
2555
    $this->set_item($display_id, $type, $id, $item);
2556
  }
2557
}
2558

    
2559
/**
2560
 * A display type in a view.
2561
 *
2562
 * This is just the database storage mechanism, and isn't terribly important
2563
 * to the behavior of the display at all.
2564
 */
2565
class views_display extends views_db_object {
2566
  /**
2567
   * The display handler itself, which has all the methods.
2568
   *
2569
   * @var views_plugin_display
2570
   */
2571
  var $handler;
2572

    
2573
  /**
2574
   * Stores all options of the display, like fields, filters etc.
2575
   *
2576
   * @var array
2577
   */
2578
  var $display_options;
2579

    
2580
  var $db_table = 'views_display';
2581
  function __construct($init = TRUE) {
2582
    parent::init($init);
2583
  }
2584

    
2585
  function options($type, $id, $title) {
2586
    $this->display_plugin = $type;
2587
    $this->id = $id;
2588
    $this->display_title = $title;
2589
  }
2590
}
2591

    
2592
/**
2593
 * Provide a list of views object types used in a view, with some information
2594
 * about them.
2595
 */
2596
function views_object_types() {
2597
  static $retval = NULL;
2598

    
2599
  // statically cache this so t() doesn't run a bajillion times.
2600
  if (!isset($retval)) {
2601
    $retval = array(
2602
      'field' => array(
2603
        'title' => t('Fields'), // title
2604
        'ltitle' => t('fields'), // lowercase title for mid-sentence
2605
        'stitle' => t('Field'), // singular title
2606
        'lstitle' => t('field'), // singular lowercase title for mid sentence
2607
        'plural' => 'fields',
2608
      ),
2609
      'argument' => array(
2610
        'title' => t('Contextual filters'),
2611
        'ltitle' => t('contextual filters'),
2612
        'stitle' => t('Contextual filter'),
2613
        'lstitle' => t('contextual filter'),
2614
        'plural' => 'arguments',
2615
      ),
2616
      'sort' => array(
2617
        'title' => t('Sort criteria'),
2618
        'ltitle' => t('sort criteria'),
2619
        'stitle' => t('Sort criterion'),
2620
        'lstitle' => t('sort criterion'),
2621
        'plural' => 'sorts',
2622
      ),
2623
      'filter' => array(
2624
        'title' => t('Filter criteria'),
2625
        'ltitle' => t('filter criteria'),
2626
        'stitle' => t('Filter criterion'),
2627
        'lstitle' => t('filter criterion'),
2628
        'plural' => 'filters',
2629
      ),
2630
      'relationship' => array(
2631
        'title' => t('Relationships'),
2632
        'ltitle' => t('relationships'),
2633
        'stitle' => t('Relationship'),
2634
        'lstitle' => t('Relationship'),
2635
        'plural' => 'relationships',
2636
      ),
2637
      'header' => array(
2638
        'title' => t('Header'),
2639
        'ltitle' => t('header'),
2640
        'stitle' => t('Header'),
2641
        'lstitle' => t('Header'),
2642
        'plural' => 'header',
2643
        'type' => 'area',
2644
      ),
2645
      'footer' => array(
2646
        'title' => t('Footer'),
2647
        'ltitle' => t('footer'),
2648
        'stitle' => t('Footer'),
2649
        'lstitle' => t('Footer'),
2650
        'plural' => 'footer',
2651
        'type' => 'area',
2652
      ),
2653
      'empty' => array(
2654
        'title' => t('No results behavior'),
2655
        'ltitle' => t('no results behavior'),
2656
        'stitle' => t('No results behavior'),
2657
        'lstitle' => t('No results behavior'),
2658
        'plural' => 'empty',
2659
        'type' => 'area',
2660
      ),
2661
    );
2662
  }
2663

    
2664
  return $retval;
2665
}
2666

    
2667
/**
2668
 * @}
2669
 */