Projet

Général

Profil

Paste
Télécharger (75 ko) Statistiques
| Branche: | Révision:

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

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
    if (empty($this->exposed_input)) {
415
      $this->exposed_input = array();
416

    
417
      // If filters are not overridden, store the 'remember' settings on the
418
      // default display. If they are, store them on this display. This way,
419
      // multiple displays in the same view can share the same filters and
420
      // remember settings.
421
      $display_id = ($this->display_handler->is_defaulted('filters')) ? 'default' : $this->current_display;
422

    
423
      // Start with remembered input via session.
424
      if (!empty($_SESSION['views'][$this->name][$display_id])) {
425
        $this->exposed_input = $_SESSION['views'][$this->name][$display_id];
426
      }
427

    
428
      // Fetch exposed input values from $_GET. Overwrite if clashing.
429
      foreach ($_GET as $key => $value) {
430
        if (!in_array($key, array('page', 'q'))) {
431
          $this->exposed_input[$key] = $value;
432
        }
433
      }
434
    }
435

    
436
    return $this->exposed_input;
437
  }
438

    
439
  /**
440
   * Set the display for this view and initialize the display handler.
441
   */
442
  function init_display($reset = FALSE) {
443
    // The default display is always the first one in the list.
444
    if (isset($this->current_display)) {
445
      return TRUE;
446
    }
447

    
448
    // Instantiate all displays
449
    foreach (array_keys($this->display) as $id) {
450
      // Correct for shallow cloning
451
      // Often we'll have a cloned view so we don't mess up each other's
452
      // displays, but the clone is pretty shallow and doesn't necessarily
453
      // clone the displays. We can tell this by looking to see if a handler
454
      // has already been set; if it has, but $this->current_display is not
455
      // set, then something is dreadfully wrong.
456
      if (!empty($this->display[$id]->handler)) {
457
        $this->display[$id] = clone $this->display[$id];
458
        unset($this->display[$id]->handler);
459
      }
460
      $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
461
      if (!empty($this->display[$id]->handler)) {
462
        $this->display[$id]->handler->localization_keys = array($id);
463
        // Initialize the new display handler with data.
464
        $this->display[$id]->handler->init($this, $this->display[$id]);
465
        // If this is NOT the default display handler, let it know which is
466
        // since it may well utilize some data from the default.
467
        // This assumes that the 'default' handler is always first. It always
468
        // is. Make sure of it.
469
        if ($id != 'default') {
470
          $this->display[$id]->handler->default_display = &$this->display['default']->handler;
471
        }
472
      }
473
    }
474

    
475
    $this->current_display = 'default';
476
    $this->display_handler = &$this->display['default']->handler;
477

    
478
    return TRUE;
479
  }
480

    
481
  /**
482
   * Get the first display that is accessible to the user.
483
   *
484
   * @param $displays
485
   *   Either a single display id or an array of display ids.
486
   */
487
  function choose_display($displays) {
488
    if (!is_array($displays)) {
489
      return $displays;
490
    }
491

    
492
    $this->init_display();
493

    
494
    foreach ($displays as $display_id) {
495
      if ($this->display[$display_id]->handler->access()) {
496
        return $display_id;
497
      }
498
    }
499

    
500
    return 'default';
501
  }
502

    
503
  /**
504
   * Set the display as current.
505
   *
506
   * @param $display_id
507
   *   The id of the display to mark as current.
508
   */
509
  function set_display($display_id = NULL) {
510
    // If we have not already initialized the display, do so. But be careful.
511
    if (empty($this->current_display)) {
512
      $this->init_display();
513

    
514
      // If handlers were not initialized, and no argument was sent, set up
515
      // to the default display.
516
      if (empty($display_id)) {
517
        $display_id = 'default';
518
      }
519
    }
520

    
521
    $display_id = $this->choose_display($display_id);
522

    
523
    // If no display id sent in and one wasn't chosen above, we're finished.
524
    if (empty($display_id)) {
525
      return FALSE;
526
    }
527

    
528
    // Ensure the requested display exists.
529
    if (empty($this->display[$display_id])) {
530
      $display_id = 'default';
531
      if (empty($this->display[$display_id])) {
532
        vpr('set_display() called with invalid display id @display.', array('@display' => $display_id));
533
        return FALSE;
534
      }
535
    }
536

    
537
    // Set the current display.
538
    $this->current_display = $display_id;
539

    
540
    // Ensure requested display has a working handler.
541
    if (empty($this->display[$display_id]->handler)) {
542
      return FALSE;
543
    }
544

    
545
    // Set a shortcut
546
    $this->display_handler = &$this->display[$display_id]->handler;
547

    
548
    return TRUE;
549
  }
550

    
551
  /**
552
   * Find and initialize the style plugin.
553
   *
554
   * Note that arguments may have changed which style plugin we use, so
555
   * check the view object first, then ask the display handler.
556
   */
557
  function init_style() {
558
    if (isset($this->style_plugin)) {
559
      return is_object($this->style_plugin);
560
    }
561

    
562
    if (!isset($this->plugin_name)) {
563
      $this->plugin_name = $this->display_handler->get_option('style_plugin');
564
      $this->style_options = $this->display_handler->get_option('style_options');
565
    }
566

    
567
    $this->style_plugin = views_get_plugin('style', $this->plugin_name);
568

    
569
    if (empty($this->style_plugin)) {
570
      return FALSE;
571
    }
572

    
573
    // init the new style handler with data.
574
    $this->style_plugin->init($this, $this->display[$this->current_display], $this->style_options);
575
    return TRUE;
576
  }
577

    
578
  /**
579
   * Attempt to discover if the view has handlers missing relationships.
580
   *
581
   * This will try to add relationships automatically if it can, and will
582
   * remove the handlers if it cannot.
583
   */
584
  function fix_missing_relationships() {
585
    if (isset($this->relationships_fixed)) {
586
      return;
587
    }
588

    
589
    $this->relationships_fixed = TRUE;
590

    
591
    // Go through all of our handler types and test them to see if they
592
    // are missing relationships. Missing relationships can cause fatally
593
    // broken Views.
594
    $base_tables = array(
595
      $this->base_table => TRUE,
596
      '#global' => TRUE,
597
    );
598

    
599
    // For each relationship we have, make sure we mark the base it provides as
600
    // available.
601
    foreach ($this->display_handler->get_option('relationships') as $id => $options) {
602
      $options['table'] = views_move_table($options['table']);
603
      $data = views_fetch_data($options['table'], FALSE);
604
      if (isset($data[$options['field']]['relationship']['base'])) {
605
        $base_tables[$data[$options['field']]['relationship']['base']] = TRUE;
606
      }
607
    }
608

    
609
    $base_tables = array_keys($base_tables);
610
    $missing_base_tables = array();
611

    
612
    $types = views_object_types();
613
    foreach ($types as $key => $info) {
614
      foreach ($this->display_handler->get_option($info['plural']) as $id => $options) {
615
        $options['table'] = views_move_table($options['table']);
616
        $data = views_fetch_data($options['table'], FALSE);
617

    
618
        $valid_bases = array($options['table']);
619
        if (isset($data['table']['join'])) {
620
          $valid_bases = array_merge($valid_bases, array_keys($data['table']['join']));
621
        }
622

    
623
        // If the base table is missing, record it so we can try to fix it.
624
        if (!array_intersect($valid_bases, $base_tables)) {
625
          $missing_base_tables[$options['table']][] = array('type' => $key, 'id' => $id);
626
        }
627
      }
628
    }
629

    
630
    if (!empty($missing_base_tables)) {
631
      // This will change handlers, so make sure any existing handlers get
632
      // tossed.
633
      $this->display_handler->handlers = array();
634
      $this->relationships_changed = TRUE;
635
      $this->changed = TRUE;
636

    
637
      // Try to fix it.
638
      foreach ($missing_base_tables as $table => $handlers) {
639
        $data = views_fetch_data($table);
640
        $relationship = NULL;
641

    
642
        // Does the missing base table have a default relationship we can
643
        // throw in?
644
        if (isset($data['table']['default_relationship'][$this->base_table])) {
645
          // Create the relationship.
646
          $info = $data['table']['default_relationship'][$this->base_table];
647

    
648
          $relationship_options = isset($info['options']) ? $info['options'] : array();
649
          $relationship = $this->add_item($this->current_display, 'relationship', $info['table'], $info['field'], $relationship_options);
650
        }
651
        foreach ($handlers as $handler) {
652
          $options = $this->display_handler->get_option($types[$handler['type']]['plural']);
653
          if ($relationship) {
654
            $options[$handler['id']]['relationship'] = $relationship;
655
          }
656
          else {
657
            unset($options[$handler['id']]);
658
          }
659
          $this->display_handler->set_option($types[$handler['type']]['plural'], $options);
660
        }
661
      }
662
    }
663
  }
664

    
665
  /**
666
   * Acquire and attach all of the handlers.
667
   */
668
  function init_handlers() {
669
    if (empty($this->inited)) {
670
      $this->fix_missing_relationships();
671
      foreach (views_object_types() as $key => $info) {
672
        $this->_init_handler($key, $info);
673
      }
674
      $this->inited = TRUE;
675
    }
676
  }
677

    
678
  /**
679
   * Initialize the pager
680
   *
681
   * Like style initialization, pager initialization is held until late
682
   * to allow for overrides.
683
   */
684
  function init_pager() {
685
    if (empty($this->query->pager)) {
686
      // If the query doesn't exist, initialize it.
687
      if (empty($this->query)) {
688
        $this->init_query();
689
      }
690
      $this->query->pager = $this->display_handler->get_plugin('pager');
691

    
692
      if ($this->query->pager->use_pager()) {
693
        $this->query->pager->set_current_page($this->current_page);
694
      }
695

    
696
      // These overrides may have been set earlier via $view->set_*
697
      // functions.
698
      if (isset($this->items_per_page)) {
699
        $this->query->pager->set_items_per_page($this->items_per_page);
700
      }
701

    
702
      if (isset($this->offset)) {
703
        $this->query->pager->set_offset($this->offset);
704
      }
705
    }
706
  }
707

    
708
  /**
709
   * Create a list of base tables eligible for this view. Used primarily
710
   * for the UI. Display must be already initialized.
711
   */
712
  function get_base_tables() {
713
    $base_tables = array(
714
      $this->base_table => TRUE,
715
      '#global' => TRUE,
716
    );
717

    
718
    foreach ($this->display_handler->get_handlers('relationship') as $handler) {
719
      $base_tables[$handler->definition['base']] = TRUE;
720
    }
721
    return $base_tables;
722
  }
723

    
724
  /**
725
   * Run the pre_query() on all active handlers.
726
   */
727
  function _pre_query() {
728
    foreach (views_object_types() as $key => $info) {
729
      $handlers = &$this->$key;
730
      $position = 0;
731
      foreach ($handlers as $id => $handler) {
732
        $handlers[$id]->position = $position;
733
        $handlers[$id]->pre_query();
734
        $position++;
735
      }
736
    }
737
  }
738

    
739
  /**
740
   * Run the post_execute() on all active handlers.
741
   */
742
  function _post_execute() {
743
    foreach (views_object_types() as $key => $info) {
744
      $handlers = &$this->$key;
745
      foreach ($handlers as $id => $handler) {
746
        $handlers[$id]->post_execute($this->result);
747
      }
748
    }
749
  }
750

    
751
  /**
752
   * Attach all of the handlers for each type.
753
   *
754
   * @param $key
755
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'
756
   * @param $info
757
   *   The $info from views_object_types for this object.
758
   */
759
  function _init_handler($key, $info) {
760
    // Load the requested items from the display onto the object.
761
    $this->$key = &$this->display_handler->get_handlers($key);
762

    
763
    // This reference deals with difficult PHP indirection.
764
    $handlers = &$this->$key;
765

    
766
    // Run through and test for accessibility.
767
    foreach ($handlers as $id => $handler) {
768
      if (!$handler->access()) {
769
        unset($handlers[$id]);
770
      }
771
    }
772
  }
773

    
774
  /**
775
   * Build all the arguments.
776
   */
777
  function _build_arguments() {
778
    // Initially, we want to build sorts and fields. This can change, though,
779
    // if we get a summary view.
780
    if (empty($this->argument)) {
781
      return TRUE;
782
    }
783

    
784
    // build arguments.
785
    $position = -1;
786

    
787
    // Create a title for use in the breadcrumb trail.
788
    $title = $this->display_handler->get_option('title');
789

    
790
    $this->build_info['breadcrumb'] = array();
791
    $breadcrumb_args = array();
792
    $substitutions = array();
793

    
794
    $status = TRUE;
795

    
796
    // Iterate through each argument and process.
797
    foreach ($this->argument as $id => $arg) {
798
      $position++;
799
      $argument = &$this->argument[$id];
800

    
801
      if ($argument->broken()) {
802
        continue;
803
      }
804

    
805
      $argument->set_relationship();
806

    
807
      $arg = isset($this->args[$position]) ? $this->args[$position] : NULL;
808
      $argument->position = $position;
809

    
810
      if (isset($arg) || $argument->has_default_argument()) {
811
        if (!isset($arg)) {
812
          $arg = $argument->get_default_argument();
813
          // make sure default args get put back.
814
          if (isset($arg)) {
815
            $this->args[$position] = $arg;
816
          }
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() || !empty($this->get_total_rows)) {
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, $this->display_handler->output, $cache);
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
    // No one 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->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
    // Let modules modify the view just prior to saving it.
1822
    module_invoke_all('views_view_presave', $this);
1823

    
1824
    $transaction = db_transaction();
1825

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

    
1837
      $this->save_row(!empty($this->vid) ? 'vid' : FALSE);
1838

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

    
1850
    $this->save_locale_strings();
1851

    
1852
    // Clear caches.
1853
    views_invalidate_cache();
1854

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

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

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

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

    
1890
    cache_clear_all('views_query:' . $this->name, 'cache_views');
1891

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

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

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

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

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

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

    
1935
    return $output;
1936
  }
1937

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

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

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

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

    
1990
    return $clone;
1991
  }
1992

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

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

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

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

    
2025
    if (isset($this->current_display)) {
2026
      unset($this->current_display);
2027
    }
2028

    
2029
    if (isset($this->query)) {
2030
      unset($this->query);
2031
    }
2032

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

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

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

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

    
2064
    $errors = array();
2065
    $this->display_errors = NULL;
2066

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

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

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

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

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

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

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

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

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

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

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

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

    
2157
}
2158

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

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

    
2178
    if (!$init) {
2179
      return;
2180
    }
2181

    
2182
    $schema = drupal_get_schema($this->db_table);
2183

    
2184
    if (!$schema) {
2185
      return;
2186
    }
2187

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2342

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

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

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

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

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

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

    
2394
    return $id;
2395
  }
2396

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

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

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

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

    
2452
    return $this->display[$id]->handler;
2453
  }
2454

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

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

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

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

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

    
2483
    $handler = views_get_handler($table, $field, $handler_type);
2484

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

    
2488
    return $id;
2489
  }
2490

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

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

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

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

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

    
2519
    return isset($fields[$id]) ? $fields[$id] : NULL;
2520
  }
2521

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

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

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

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

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

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

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

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

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

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

    
2666
  return $retval;
2667
}
2668

    
2669
/**
2670
 * @}
2671
 */