Projet

Général

Profil

Paste
Télécharger (76,4 ko) Statistiques
| Branche: | Révision:

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

1
<?php
2

    
3
/**
4
 * @file
5
 * @defgroup views_objects Objects that represent a View or part of a view
6
 * @{
7
 * These objects are the core of Views do the bulk of the direction and
8
 * storing of data. All database activity is in these objects.
9
 */
10

    
11
/**
12
 * An object to contain all of the data to generate a view.
13
 *
14
 * Also includes the member functions to build the view query, execute the
15
 * query and render the output.
16
 */
17
class view extends views_db_object {
18

    
19
  /**
20
   *
21
   */
22
  public $db_table = 'views_view';
23

    
24
  /**
25
   *
26
   */
27
  public $base_table = 'node';
28

    
29
  /**
30
   *
31
   */
32
  public $base_field = 'nid';
33

    
34
  /**
35
   * The name of the view.
36
   *
37
   * @var string
38
   */
39
  public $name = "";
40

    
41
  /**
42
   * The id of the view, which is used only for views in the database.
43
   *
44
   * @var number
45
   */
46
  public $vid;
47

    
48
  /**
49
   * The description of the view, which is used only in the interface.
50
   *
51
   * @var string
52
   */
53
  public $description;
54

    
55
  /**
56
   * The "tags" of a view.
57
   * The tags are stored as a single string, though it is used as multiple tags
58
   * for example in the views overview.
59
   *
60
   * @var string
61
   */
62
  public $tag;
63

    
64
  /**
65
   * The human readable name of the view.
66
   *
67
   * @var string
68
   */
69
  public $human_name;
70

    
71
  /**
72
   * The core version the view was created for.
73
   *
74
   * @var int
75
   */
76
  public $core;
77

    
78
  /**
79
   * The views-api version this view was created by.
80
   *
81
   * Some examples of the variable are 3.0 or 3.0-alpha1
82
   *
83
   * @var string
84
   */
85
  public $api_version;
86

    
87
  /**
88
   * Is the view disabled.
89
   *
90
   * This value is used for exported view, to provide some default views which
91
   * aren't enabled.
92
   *
93
   * @var bool
94
   */
95
  public $disabled;
96

    
97
  /**
98
   * State variable.
99
   */
100
  public $built = FALSE;
101

    
102
  /**
103
   * State variable.
104
   */
105
  public $executed = FALSE;
106

    
107
  /**
108
   * State variable.
109
   */
110
  public $editing = FALSE;
111

    
112
  /**
113
   *
114
   */
115
  public $args = array();
116

    
117
  /**
118
   *
119
   */
120
  public $build_info = array();
121

    
122
  /**
123
   *
124
   */
125
  public $use_ajax = FALSE;
126

    
127
  /**
128
   * Where the results of a query will go.
129
   *
130
   * The array must use a numeric index starting at 0.
131
   *
132
   * @var array
133
   */
134
  public $result = array();
135

    
136
  // May be used to override the current pager info.
137
  public $current_page = NULL;
138
  public $items_per_page = NULL;
139
  public $offset = NULL;
140
  public $total_rows = NULL;
141

    
142
  // Places to put attached renderings.
143
  public $attachment_before = '';
144
  public $attachment_after = '';
145

    
146
  // Exposed widget input.
147
  public $exposed_data = array();
148
  public $exposed_input = array();
149
  // Exposed widget input directly from the $form_state['values'].
150
  public $exposed_raw_input = array();
151

    
152
  // Used to store views that were previously running if we recurse.
153
  public $old_view = array();
154

    
155
  // To avoid recursion in views embedded into areas.
156
  public $parent_views = array();
157

    
158
  // Is the current stored view runned as an attachment to another view.
159
  public $is_attachment = NULL;
160

    
161
  // Stores the next steps of form items to handle.
162
  // It's an array of stack items, which contain the form id, the type of form,
163
  // the view, the display and some additional arguments.
164
  // @see views_ui_add_form_to_stack()
165
  // var $stack;
166
  /**
167
   * Identifier of the current display.
168
   *
169
   * @var string
170
   */
171
  public $current_display;
172

    
173
  /**
174
   * Where the $query object will reside:.
175
   *
176
   * @var views_plugin_query
177
   */
178
  public $query = NULL;
179

    
180
  /**
181
   * The current used display plugin.
182
   *
183
   * @var views_plugin_display
184
   */
185
  public $display_handler;
186

    
187
  /**
188
   * Stores all display handlers of this view.
189
   *
190
   * @var array[views_display]
191
   */
192
  public $display;
193

    
194
  /**
195
   * The current used style plugin.
196
   *
197
   * @var views_plugin_style
198
   */
199
  public $style_plugin;
200

    
201
  /**
202
   * Stored the changed options of the style plugin.
203
   *
204
   * @deprecated Better use $view->style_plugin->options
205
   *
206
   * @var array
207
   */
208
  public $style_options;
209

    
210
  /**
211
   * Stores the current active row while rendering.
212
   *
213
   * @var int
214
   */
215
  public $row_index;
216

    
217
  /**
218
   * Allow to override the url of the current view.
219
   *
220
   * @var string
221
   */
222
  public $override_url = NULL;
223

    
224
  /**
225
   * Allow to override the path used for generated urls.
226
   *
227
   * @var string
228
   */
229
  public $override_path = NULL;
230

    
231
  /**
232
   * Allow to override the used database which is used for this query.
233
   */
234
  public $base_database = NULL;
235

    
236
  /**
237
   * Here comes a list of the possible handler which are active on this view.
238
   */
239

    
240
  /**
241
   * Stores the field handlers which are initialized on this view.
242
   *
243
   * @var array[views_handler_field]
244
   */
245
  public $field;
246

    
247
  /**
248
   * Stores the argument handlers which are initialized on this view.
249
   *
250
   * @var array[views_handler_argument]
251
   */
252
  public $argument;
253

    
254
  /**
255
   * Stores the sort handlers which are initialized on this view.
256
   *
257
   * @var array[views_handler_sort]
258
   */
259
  public $sort;
260

    
261
  /**
262
   * Stores the filter handlers which are initialized on this view.
263
   *
264
   * @var array[views_handler_filter]
265
   */
266
  public $filter;
267

    
268
  /**
269
   * Stores the relationship handlers which are initialized on this view.
270
   *
271
   * @var array[views_handler_relationship]
272
   */
273
  public $relationship;
274

    
275
  /**
276
   * Stores the area handlers for the header which are initialized on this view.
277
   *
278
   * @var array[views_handler_area]
279
   */
280
  public $header;
281

    
282
  /**
283
   * Stores the area handlers for the footer which are initialized on this view.
284
   *
285
   * @var array[views_handler_area]
286
   */
287
  public $footer;
288

    
289
  /**
290
   * The area handlers for the empty text which are initialized on this view.
291
   *
292
   * @var array[views_handler_area]
293
   */
294
  public $empty;
295

    
296
  /**
297
   * Standard PHP constructor.
298
   */
299
  public function __construct() {
300
    parent::init();
301

    
302
    // Make sure all of the sub objects are arrays.
303
    foreach ($this->db_objects() as $object) {
304
      $this->$object = array();
305
    }
306
  }
307

    
308
  /**
309
   * Perform automatic updates when loading or importing a view.
310
   *
311
   * Over time, some things about Views or Drupal data has changed. this
312
   * attempts to do some automatic updates that must happen to ensure older
313
   * views will at least try to work.
314
   */
315
  public function update() {
316
    // When views are converted automatically the base_table should be renamed
317
    // to have a working query.
318
    $this->base_table = views_move_table($this->base_table);
319
  }
320

    
321
  /**
322
   * Returns a list of the sub-object types used by this view. These types are
323
   * stored on the display, and are used in the build process.
324
   */
325
  public function display_objects() {
326
    return array('argument', 'field', 'sort', 'filter', 'relationship', 'header', 'footer', 'empty');
327
  }
328

    
329
  /**
330
   * Returns the complete list of dependent objects in a view, for the purpose
331
   * of initialization and loading/saving to/from the database.
332
   */
333
  static function db_objects() {
334
    return array('display');
335
  }
336

    
337
  /**
338
   * Set the arguments that come to this view. Usually from the URL
339
   * but possibly from elsewhere.
340
   */
341
  public function set_arguments($args) {
342
    $this->args = $args;
343
  }
344

    
345
  /**
346
   * Change/Set the current page for the pager.
347
   */
348
  public function set_current_page($page) {
349
    $this->current_page = $page;
350

    
351
    // If the pager is already initialized, pass it through to the pager.
352
    if (!empty($this->query->pager)) {
353
      return $this->query->pager->set_current_page($page);
354
    }
355
  }
356

    
357
  /**
358
   * Get the current page from the pager.
359
   */
360
  public function get_current_page() {
361
    // If the pager is already initialized, pass it through to the pager.
362
    if (!empty($this->query->pager)) {
363
      return $this->query->pager->get_current_page();
364
    }
365

    
366
    if (isset($this->current_page)) {
367
      return $this->current_page;
368
    }
369
  }
370

    
371
  /**
372
   * Get the items per page from the pager.
373
   */
374
  public function get_items_per_page() {
375
    // If the pager is already initialized, pass it through to the pager.
376
    if (!empty($this->query->pager)) {
377
      return $this->query->pager->get_items_per_page();
378
    }
379

    
380
    if (isset($this->items_per_page)) {
381
      return $this->items_per_page;
382
    }
383
  }
384

    
385
  /**
386
   * Set the items per page on the pager.
387
   */
388
  public function set_items_per_page($items_per_page) {
389
    $this->items_per_page = $items_per_page;
390

    
391
    // If the pager is already initialized, pass it through to the pager.
392
    if (!empty($this->query->pager)) {
393
      $this->query->pager->set_items_per_page($items_per_page);
394
    }
395
  }
396

    
397
  /**
398
   * Get the pager offset from the pager.
399
   */
400
  public function get_offset() {
401
    // If the pager is already initialized, pass it through to the pager.
402
    if (!empty($this->query->pager)) {
403
      return $this->query->pager->get_offset();
404
    }
405

    
406
    if (isset($this->offset)) {
407
      return $this->offset;
408
    }
409
  }
410

    
411
  /**
412
   * Set the offset on the pager.
413
   */
414
  public function set_offset($offset) {
415
    $this->offset = $offset;
416

    
417
    // If the pager is already initialized, pass it through to the pager.
418
    if (!empty($this->query->pager)) {
419
      $this->query->pager->set_offset($offset);
420
    }
421
  }
422

    
423
  /**
424
   * Determine if the pager actually uses a pager.
425
   */
426
  public function use_pager() {
427
    if (!empty($this->query->pager)) {
428
      return $this->query->pager->use_pager();
429
    }
430
  }
431

    
432
  /**
433
   * Whether or not AJAX should be used. If AJAX is used, paging,
434
   * tablesorting and exposed filters will be fetched via an AJAX call
435
   * rather than a page refresh.
436
   */
437
  public function set_use_ajax($use_ajax) {
438
    $this->use_ajax = $use_ajax;
439
  }
440

    
441
  /**
442
   * Set the exposed filters input to an array. If unset they will be taken
443
   * from $_GET when the time comes.
444
   */
445
  public function set_exposed_input($filters) {
446
    $this->exposed_input = $filters;
447
  }
448

    
449
  /**
450
   * Figure out what the exposed input for this view is.
451
   */
452
  public function get_exposed_input() {
453
    if (empty($this->exposed_input)) {
454
      $this->exposed_input = array();
455

    
456
      // If filters are not overridden, store the 'remember' settings on the
457
      // default display. If they are, store them on this display. This way,
458
      // multiple displays in the same view can share the same filters and
459
      // remember settings.
460
      $display_id = ($this->display_handler->is_defaulted('filters')) ? 'default' : $this->current_display;
461

    
462
      // Start with remembered input via session.
463
      if (!empty($_SESSION['views'][$this->name][$display_id])) {
464
        $this->exposed_input = $_SESSION['views'][$this->name][$display_id];
465
      }
466

    
467
      // Fetch exposed input values from $_GET. Overwrite if clashing.
468
      foreach ($_GET as $key => $value) {
469
        if (!in_array($key, array('page', 'q'))) {
470
          $this->exposed_input[$key] = $value;
471
        }
472
      }
473
    }
474

    
475
    return $this->exposed_input;
476
  }
477

    
478
  /**
479
   * Set the display for this view and initialize the display handler.
480
   */
481
  public function init_display($reset = FALSE) {
482
    // The default display is always the first one in the list.
483
    if (isset($this->current_display)) {
484
      return TRUE;
485
    }
486

    
487
    // Instantiate all displays.
488
    foreach (array_keys($this->display) as $id) {
489
      // Correct for shallow cloning
490
      // Often we'll have a cloned view so we don't mess up each other's
491
      // displays, but the clone is pretty shallow and doesn't necessarily
492
      // clone the displays. We can tell this by looking to see if a handler
493
      // has already been set; if it has, but $this->current_display is not
494
      // set, then something is dreadfully wrong.
495
      if (!empty($this->display[$id]->handler)) {
496
        $this->display[$id] = clone $this->display[$id];
497
        unset($this->display[$id]->handler);
498
      }
499
      $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
500
      if (!empty($this->display[$id]->handler)) {
501
        $this->display[$id]->handler->localization_keys = array($id);
502
        // Initialize the new display handler with data.
503
        $this->display[$id]->handler->init($this, $this->display[$id]);
504
        // If this is NOT the default display handler, let it know which is
505
        // since it may well utilize some data from the default.
506
        // This assumes that the 'default' handler is always first. It always
507
        // is. Make sure of it.
508
        if ($id != 'default') {
509
          $this->display[$id]->handler->default_display = &$this->display['default']->handler;
510
        }
511
      }
512
    }
513

    
514
    $this->current_display = 'default';
515
    $this->display_handler = &$this->display['default']->handler;
516

    
517
    return TRUE;
518
  }
519

    
520
  /**
521
   * Get the first display that is accessible to the user.
522
   *
523
   * @param string|array $displays
524
   *   Either a single display id or an array of display ids.
525
   */
526
  public function choose_display($displays) {
527
    if (!is_array($displays)) {
528
      return $displays;
529
    }
530

    
531
    $this->init_display();
532

    
533
    foreach ($displays as $display_id) {
534
      if ($this->display[$display_id]->handler->access()) {
535
        return $display_id;
536
      }
537
    }
538

    
539
    return 'default';
540
  }
541

    
542
  /**
543
   * Set the display as current.
544
   *
545
   * @param string $display_id
546
   *   The id of the display to mark as current.
547
   */
548
  public function set_display($display_id = NULL) {
549
    // If we have not already initialized the display, do so. But be careful.
550
    if (empty($this->current_display)) {
551
      $this->init_display();
552

    
553
      // If handlers were not initialized, and no argument was sent, set up
554
      // to the default display.
555
      if (empty($display_id)) {
556
        $display_id = 'default';
557
      }
558
    }
559

    
560
    $display_id = $this->choose_display($display_id);
561

    
562
    // If no display id sent in and one wasn't chosen above, we're finished.
563
    if (empty($display_id)) {
564
      return FALSE;
565
    }
566

    
567
    // Ensure the requested display exists.
568
    if (empty($this->display[$display_id])) {
569
      $display_id = 'default';
570
      if (empty($this->display[$display_id])) {
571
        vpr('set_display() called with invalid display id @display.', array('@display' => $display_id));
572
        return FALSE;
573
      }
574
    }
575

    
576
    // Set the current display.
577
    $this->current_display = $display_id;
578

    
579
    // Ensure requested display has a working handler.
580
    if (empty($this->display[$display_id]->handler)) {
581
      return FALSE;
582
    }
583

    
584
    // Set a shortcut.
585
    $this->display_handler = &$this->display[$display_id]->handler;
586

    
587
    return TRUE;
588
  }
589

    
590
  /**
591
   * Find and initialize the style plugin.
592
   *
593
   * Note that arguments may have changed which style plugin we use, so
594
   * check the view object first, then ask the display handler.
595
   */
596
  public function init_style() {
597
    if (isset($this->style_plugin)) {
598
      return is_object($this->style_plugin);
599
    }
600

    
601
    if (!isset($this->plugin_name)) {
602
      $this->plugin_name = $this->display_handler->get_option('style_plugin');
603
      $this->style_options = $this->display_handler->get_option('style_options');
604
    }
605

    
606
    $this->style_plugin = views_get_plugin('style', $this->plugin_name);
607

    
608
    if (empty($this->style_plugin)) {
609
      return FALSE;
610
    }
611

    
612
    // Init the new style handler with data..
613
    $this->style_plugin->init($this, $this->display[$this->current_display], $this->style_options);
614
    return TRUE;
615
  }
616

    
617
  /**
618
   * Attempt to discover if the view has handlers missing relationships.
619
   *
620
   * This will try to add relationships automatically if it can, and will
621
   * remove the handlers if it cannot.
622
   */
623
  public function fix_missing_relationships() {
624
    if (isset($this->relationships_fixed)) {
625
      return;
626
    }
627

    
628
    $this->relationships_fixed = TRUE;
629

    
630
    // Go through all of our handler types and test them to see if they
631
    // are missing relationships. Missing relationships can cause fatally
632
    // broken Views.
633
    $base_tables = array(
634
      $this->base_table => TRUE,
635
      '#global' => TRUE,
636
    );
637

    
638
    // For each relationship we have, make sure we mark the base it provides as
639
    // available.
640
    foreach ($this->display_handler->get_option('relationships') as $id => $options) {
641
      $options['table'] = views_move_table($options['table']);
642
      $data = views_fetch_data($options['table'], FALSE);
643
      if (isset($data[$options['field']]['relationship']['base'])) {
644
        $base_tables[$data[$options['field']]['relationship']['base']] = TRUE;
645
      }
646
    }
647

    
648
    $base_tables = array_keys($base_tables);
649
    $missing_base_tables = array();
650

    
651
    $types = views_object_types();
652
    foreach ($types as $key => $info) {
653
      foreach ($this->display_handler->get_option($info['plural']) as $id => $options) {
654
        $options['table'] = views_move_table($options['table']);
655
        $data = views_fetch_data($options['table'], FALSE);
656

    
657
        $valid_bases = array($options['table']);
658
        if (isset($data['table']['join'])) {
659
          $valid_bases = array_merge($valid_bases, array_keys($data['table']['join']));
660
        }
661

    
662
        // If the base table is missing, record it so we can try to fix it.
663
        if (!array_intersect($valid_bases, $base_tables)) {
664
          $missing_base_tables[$options['table']][] = array('type' => $key, 'id' => $id);
665
        }
666
      }
667
    }
668

    
669
    if (!empty($missing_base_tables)) {
670
      // This will change handlers, so make sure any existing handlers get
671
      // tossed.
672
      $this->display_handler->handlers = array();
673
      $this->relationships_changed = TRUE;
674
      $this->changed = TRUE;
675

    
676
      // Try to fix it.
677
      foreach ($missing_base_tables as $table => $handlers) {
678
        $data = views_fetch_data($table);
679
        $relationship = NULL;
680

    
681
        // Does the missing base table have a default relationship we can
682
        // throw in?
683
        if (isset($data['table']['default_relationship'][$this->base_table])) {
684
          // Create the relationship.
685
          $info = $data['table']['default_relationship'][$this->base_table];
686

    
687
          $relationship_options = isset($info['options']) ? $info['options'] : array();
688
          $relationship = $this->add_item($this->current_display, 'relationship', $info['table'], $info['field'], $relationship_options);
689
        }
690
        foreach ($handlers as $handler) {
691
          $options = $this->display_handler->get_option($types[$handler['type']]['plural']);
692
          if ($relationship) {
693
            $options[$handler['id']]['relationship'] = $relationship;
694
          }
695
          else {
696
            unset($options[$handler['id']]);
697
          }
698
          $this->display_handler->set_option($types[$handler['type']]['plural'], $options);
699
        }
700
      }
701
    }
702
  }
703

    
704
  /**
705
   * Acquire and attach all of the handlers.
706
   */
707
  public function init_handlers() {
708
    if (empty($this->inited)) {
709
      $this->fix_missing_relationships();
710
      foreach (views_object_types() as $key => $info) {
711
        $this->_init_handler($key, $info);
712
      }
713
      $this->inited = TRUE;
714
    }
715
  }
716

    
717
  /**
718
   * Initialize the pager.
719
   *
720
   * Like style initialization, pager initialization is held until late
721
   * to allow for overrides.
722
   */
723
  public function init_pager() {
724
    if (empty($this->query->pager)) {
725
      // If the query doesn't exist, initialize it.
726
      if (empty($this->query)) {
727
        $this->init_query();
728
      }
729
      $this->query->pager = $this->display_handler->get_plugin('pager');
730

    
731
      if ($this->query->pager->use_pager()) {
732
        $this->query->pager->set_current_page($this->current_page);
733
      }
734

    
735
      // These overrides may have been set earlier via $view->set_*
736
      // functions.
737
      if (isset($this->items_per_page)) {
738
        $this->query->pager->set_items_per_page($this->items_per_page);
739
      }
740

    
741
      if (isset($this->offset)) {
742
        $this->query->pager->set_offset($this->offset);
743
      }
744
    }
745
  }
746

    
747
  /**
748
   * Create a list of base tables eligible for this view. Used primarily
749
   * for the UI. Display must be already initialized.
750
   */
751
  public function get_base_tables() {
752
    $base_tables = array(
753
      $this->base_table => TRUE,
754
      '#global' => TRUE,
755
    );
756

    
757
    foreach ($this->display_handler->get_handlers('relationship') as $handler) {
758
      $base_tables[$handler->definition['base']] = TRUE;
759
    }
760
    return $base_tables;
761
  }
762

    
763
  /**
764
   * Run the pre_query() on all active handlers.
765
   */
766
  public function _pre_query() {
767
    foreach (views_object_types() as $key => $info) {
768
      $handlers = &$this->$key;
769
      $position = 0;
770
      foreach ($handlers as $id => $handler) {
771
        $handlers[$id]->position = $position;
772
        $handlers[$id]->pre_query();
773
        $position++;
774
      }
775
    }
776
  }
777

    
778
  /**
779
   * Run the post_execute() on all active handlers.
780
   */
781
  public function _post_execute() {
782
    foreach (views_object_types() as $key => $info) {
783
      $handlers = &$this->$key;
784
      foreach ($handlers as $id => $handler) {
785
        $handlers[$id]->post_execute($this->result);
786
      }
787
    }
788
  }
789

    
790
  /**
791
   * Attach all of the handlers for each type.
792
   *
793
   * @param string $key
794
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'.
795
   * @param array $info
796
   *   The $info from views_object_types for this object.
797
   */
798
  public function _init_handler($key, $info) {
799
    // Load the requested items from the display onto the object.
800
    $this->$key = &$this->display_handler->get_handlers($key);
801

    
802
    // This reference deals with difficult PHP indirection.
803
    $handlers = &$this->$key;
804

    
805
    // Run through and test for accessibility.
806
    foreach ($handlers as $id => $handler) {
807
      if (!$handler->access()) {
808
        unset($handlers[$id]);
809
      }
810
    }
811
  }
812

    
813
  /**
814
   * Build all the arguments.
815
   */
816
  public function _build_arguments() {
817
    // Initially, we want to build sorts and fields. This can change, though,
818
    // if we get a summary view.
819
    if (empty($this->argument)) {
820
      return TRUE;
821
    }
822

    
823
    // build arguments.
824
    $position = -1;
825

    
826
    // Create a title for use in the breadcrumb trail.
827
    $title = $this->display_handler->get_option('title');
828

    
829
    $this->build_info['breadcrumb'] = array();
830
    $breadcrumb_args = array();
831
    $substitutions = array();
832

    
833
    $status = TRUE;
834

    
835
    // Iterate through each argument and process.
836
    foreach ($this->argument as $id => $arg) {
837
      $position++;
838
      $argument = &$this->argument[$id];
839

    
840
      if ($argument->broken()) {
841
        continue;
842
      }
843

    
844
      $argument->set_relationship();
845

    
846
      $arg = NULL;
847
      if (isset($this->args[$position]) && $this->args[$position] !== '') {
848
        $arg = $this->args[$position];
849
      }
850

    
851
      $argument->position = $position;
852

    
853
      if (isset($arg) || $argument->has_default_argument()) {
854
        if (!isset($arg)) {
855
          $arg = $argument->get_default_argument();
856
          // make sure default args get put back.
857
          if (isset($arg)) {
858
            $this->args[$position] = $arg;
859
          }
860
        }
861

    
862
        // Set the argument, which will also validate that the argument can be
863
        // set.
864
        if (!$argument->set_argument($arg)) {
865
          $status = $argument->validate_fail($arg);
866
          break;
867
        }
868

    
869
        if ($argument->is_exception()) {
870
          $arg_title = $argument->exception_title();
871
        }
872
        else {
873
          $arg_title = $argument->get_title();
874
          $argument->query($this->display_handler->use_group_by());
875
        }
876

    
877
        // Add this argument's substitution.
878
        $substitutions['%' . ($position + 1)] = $arg_title;
879
        $substitutions['!' . ($position + 1)] = strip_tags(decode_entities($arg));
880

    
881
        // Since we're really generating the breadcrumb for the item above us,
882
        // check the default action of this argument.
883
        if ($this->display_handler->uses_breadcrumb() && $argument->uses_breadcrumb()) {
884
          $path = $this->get_url($breadcrumb_args);
885
          if (strpos($path, '%') === FALSE) {
886
            if (!empty($argument->options['breadcrumb_enable']) && !empty($argument->options['breadcrumb'])) {
887
              $breadcrumb = $argument->options['breadcrumb'];
888
            }
889
            else {
890
              $breadcrumb = $title;
891
            }
892
            $this->build_info['breadcrumb'][$path] = str_replace(array_keys($substitutions), $substitutions, $breadcrumb);
893
          }
894
        }
895

    
896
        // Allow the argument to muck with this breadcrumb.
897
        $argument->set_breadcrumb($this->build_info['breadcrumb']);
898

    
899
        // Test to see if we should use this argument's title.
900
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
901
          $title = $argument->options['title'];
902
        }
903

    
904
        $breadcrumb_args[] = $arg;
905
      }
906
      else {
907
        // determine default condition and handle.
908
        $status = $argument->default_action();
909
        break;
910
      }
911

    
912
      // Be safe with references and loops.
913
      unset($argument);
914
    }
915

    
916
    // set the title in the build info.
917
    if (!empty($title)) {
918
      $this->build_info['title'] = $title;
919
    }
920

    
921
    // Store the arguments for later use.
922
    $this->build_info['substitutions'] = $substitutions;
923

    
924
    return $status;
925
  }
926

    
927
  /**
928
   * Do some common building initialization.
929
   */
930
  public function init_query() {
931
    if (!empty($this->query)) {
932
      $class = get_class($this->query);
933
      if ($class && $class != 'stdClass') {
934
        // return if query is already initialized.
935
        return TRUE;
936
      }
937
    }
938

    
939
    // Create and initialize the query object.
940
    $views_data = views_fetch_data($this->base_table);
941
    $this->base_field = !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '';
942
    if (!empty($views_data['table']['base']['database'])) {
943
      $this->base_database = $views_data['table']['base']['database'];
944
    }
945

    
946
    // Load the options.
947
    $query_options = $this->display_handler->get_option('query');
948

    
949
    // Create and initialize the query object.
950
    $plugin = !empty($views_data['table']['base']['query class']) ? $views_data['table']['base']['query class'] : 'views_query';
951
    $this->query = views_get_plugin('query', $plugin);
952

    
953
    if (empty($this->query)) {
954
      return FALSE;
955
    }
956

    
957
    $this->query->init($this->base_table, $this->base_field, $query_options['options']);
958
    return TRUE;
959
  }
960

    
961
  /**
962
   * Build the query for the view.
963
   */
964
  public function build($display_id = NULL) {
965
    if (!empty($this->built)) {
966
      return;
967
    }
968

    
969
    if (empty($this->current_display) || $display_id) {
970
      if (!$this->set_display($display_id)) {
971
        return FALSE;
972
      }
973
    }
974

    
975
    // Let modules modify the view just prior to building it.
976
    foreach (module_implements('views_pre_build') as $module) {
977
      $function = $module . '_views_pre_build';
978
      $function($this);
979
    }
980

    
981
    // Attempt to load from cache.
982
    // @todo Load a build_info from cache.
983
    $start = microtime(TRUE);
984
    // If that fails, let's build!
985
    $this->build_info = array(
986
      'query' => '',
987
      'count_query' => '',
988
      'query_args' => array(),
989
    );
990

    
991
    $this->init_query();
992

    
993
    // Call a module hook and see if it wants to present us with a
994
    // pre-built query or instruct us not to build the query for
995
    // some reason.
996
    // @todo Implement this. Use the same mechanism Panels uses.
997
    // Run through our handlers and ensure they have necessary information.
998
    $this->init_handlers();
999

    
1000
    // Let the handlers interact with each other if they really want.
1001
    $this->_pre_query();
1002

    
1003
    $exposed_form = FALSE;
1004
    if ($this->display_handler->uses_exposed()) {
1005
      $exposed_form = $this->display_handler->get_plugin('exposed_form');
1006
      // (1) Record the errors before rendering the exposed form widgets.
1007
      $errors_before = form_set_error();
1008
      $this->exposed_widgets = $exposed_form->render_exposed_form();
1009
      // (2) Record the errors after rendering the exposed form widgets.
1010
      $errors_after = form_set_error();
1011
      // Find out if the validation of any of the elements in the exposed form
1012
      // has failed by comparing (1) and (2) above. Don't mess with the view
1013
      // otherwise.
1014
      $exposed_errors = count($errors_after) > count($errors_before);
1015
      if ($exposed_errors || !empty($this->build_info['abort'])) {
1016
        $this->built = TRUE;
1017
        // Don't execute the query, but rendering will still be executed to
1018
        // display the empty text.
1019
        $this->executed = TRUE;
1020
        return empty($this->build_info['fail']);
1021
      }
1022
    }
1023

    
1024
    // Build all the relationships first thing.
1025
    $this->_build('relationship');
1026

    
1027
    // Set the filtering groups.
1028
    if (!empty($this->filter)) {
1029
      $filter_groups = $this->display_handler->get_option('filter_groups');
1030
      if ($filter_groups) {
1031
        $this->query->set_group_operator($filter_groups['operator']);
1032
        foreach ($filter_groups['groups'] as $id => $operator) {
1033
          $this->query->set_where_group($operator, $id);
1034
        }
1035
      }
1036
    }
1037

    
1038
    // Build all the filters.
1039
    $this->_build('filter');
1040

    
1041
    $this->build_sort = TRUE;
1042

    
1043
    // Arguments can, in fact, cause this whole thing to abort.
1044
    if (!$this->_build_arguments()) {
1045
      $this->build_time = microtime(TRUE) - $start;
1046
      $this->attach_displays();
1047
      return $this->built;
1048
    }
1049

    
1050
    // Initialize the style; arguments may have changed which style we use,
1051
    // so waiting as long as possible is important. But we need to know
1052
    // about the style when we go to build fields.
1053
    if (!$this->init_style()) {
1054
      $this->build_info['fail'] = TRUE;
1055
      return FALSE;
1056
    }
1057

    
1058
    if ($this->style_plugin->uses_fields()) {
1059
      $this->_build('field');
1060
    }
1061

    
1062
    // Build our sort criteria if we were instructed to do so.
1063
    if (!empty($this->build_sort)) {
1064
      // Allow the style handler to deal with sorting.
1065
      if ($this->style_plugin->build_sort()) {
1066
        $this->_build('sort');
1067
      }
1068
      // allow the plugin to build second sorts as well.
1069
      $this->style_plugin->build_sort_post();
1070
    }
1071

    
1072
    // Allow area handlers to affect the query.
1073
    $this->_build('header');
1074
    $this->_build('footer');
1075
    $this->_build('empty');
1076

    
1077
    // Allow display handler to affect the query.
1078
    $this->display_handler->query($this->display_handler->use_group_by());
1079

    
1080
    // Allow style handler to affect the query.
1081
    $this->style_plugin->query($this->display_handler->use_group_by());
1082

    
1083
    // Allow exposed form to affect the query.
1084
    if ($exposed_form) {
1085
      $exposed_form->query();
1086
    }
1087

    
1088
    if (variable_get('views_sql_signature', FALSE)) {
1089
      $this->query->add_signature($this);
1090
    }
1091

    
1092
    // Let modules modify the query just prior to finalizing it.
1093
    $this->query->alter($this);
1094

    
1095
    // Only build the query if we weren't interrupted.
1096
    if (empty($this->built)) {
1097
      // Build the necessary info to execute the query.
1098
      $this->query->build($this);
1099
    }
1100

    
1101
    $this->built = TRUE;
1102
    $this->build_time = microtime(TRUE) - $start;
1103

    
1104
    // Attach displays.
1105
    $this->attach_displays();
1106

    
1107
    // Let modules modify the view just after building it.
1108
    foreach (module_implements('views_post_build') as $module) {
1109
      $function = $module . '_views_post_build';
1110
      $function($this);
1111
    }
1112

    
1113
    return TRUE;
1114
  }
1115

    
1116
  /**
1117
   * Internal method to build an individual set of handlers.
1118
   *
1119
   * @param string $key
1120
   *    The type of handlers (filter etc.) which should be iterated over to
1121
   *    build the relationship and query information.
1122
   */
1123
  public function _build($key) {
1124
    $handlers = &$this->$key;
1125
    foreach ($handlers as $id => $data) {
1126

    
1127
      if (!empty($handlers[$id]) && is_object($handlers[$id])) {
1128
        $multiple_exposed_input = array(0 => NULL);
1129
        if ($handlers[$id]->multiple_exposed_input()) {
1130
          $multiple_exposed_input = $handlers[$id]->group_multiple_exposed_input($this->exposed_data);
1131
        }
1132
        foreach ($multiple_exposed_input as $group_id) {
1133
          // Give this handler access to the exposed filter input.
1134
          if (!empty($this->exposed_data)) {
1135
            $converted = FALSE;
1136
            if ($handlers[$id]->is_a_group()) {
1137
              $converted = $handlers[$id]->convert_exposed_input($this->exposed_data, $group_id);
1138
              $handlers[$id]->store_group_input($this->exposed_data, $converted);
1139
              if (!$converted) {
1140
                continue;
1141
              }
1142
            }
1143
            $rc = $handlers[$id]->accept_exposed_input($this->exposed_data);
1144
            $handlers[$id]->store_exposed_input($this->exposed_input, $rc);
1145
            if (!$rc) {
1146
              continue;
1147
            }
1148
          }
1149
          $handlers[$id]->set_relationship();
1150
          $handlers[$id]->query($this->display_handler->use_group_by());
1151
        }
1152
      }
1153
    }
1154
  }
1155

    
1156
  /**
1157
   * Execute the view's query.
1158
   *
1159
   * @param string $display_id
1160
   *   The machine name of the display, which should be executed.
1161
   *
1162
   * @return bool
1163
   *   Return whether the executing was successful, for example an argument
1164
   *   could stop the process.
1165
   */
1166
  public function execute($display_id = NULL) {
1167
    if (empty($this->built)) {
1168
      if (!$this->build($display_id)) {
1169
        return FALSE;
1170
      }
1171
    }
1172

    
1173
    if (!empty($this->executed)) {
1174
      return TRUE;
1175
    }
1176

    
1177
    // Don't allow to use deactivated displays, but display them on the live
1178
    // preview.
1179
    if (!$this->display[$this->current_display]->handler->get_option('enabled') && empty($this->live_preview)) {
1180
      $this->build_info['fail'] = TRUE;
1181
      return FALSE;
1182
    }
1183

    
1184
    // Let modules modify the view just prior to executing it.
1185
    foreach (module_implements('views_pre_execute') as $module) {
1186
      $function = $module . '_views_pre_execute';
1187
      $function($this);
1188
    }
1189

    
1190
    // Check for already-cached results.
1191
    if (!empty($this->live_preview)) {
1192
      $cache = FALSE;
1193
    }
1194
    else {
1195
      $cache = $this->display_handler->get_plugin('cache');
1196
    }
1197
    if ($cache && $cache->cache_get('results')) {
1198
      if ($this->query->pager->use_pager() || !empty($this->get_total_rows)) {
1199
        $this->query->pager->total_items = $this->total_rows;
1200
        $this->query->pager->update_page_info();
1201
      }
1202
      vpr('Used cached results');
1203
    }
1204
    else {
1205
      $this->query->execute($this);
1206
      // Enforce the array key rule as documented in
1207
      // views_plugin_query::execute().
1208
      $this->result = array_values($this->result);
1209
      $this->_post_execute();
1210
      if ($cache) {
1211
        $cache->cache_set('results');
1212
      }
1213
    }
1214

    
1215
    // Let modules modify the view just after executing it.
1216
    foreach (module_implements('views_post_execute') as $module) {
1217
      $function = $module . '_views_post_execute';
1218
      $function($this);
1219
    }
1220

    
1221
    $this->executed = TRUE;
1222
  }
1223

    
1224
  /**
1225
   * Render this view for a certain display.
1226
   *
1227
   * Note: You should better use just the preview function if you want to
1228
   * render a view.
1229
   *
1230
   * @param string $display_id
1231
   *   The machine name of the display, which should be rendered.
1232
   *
1233
   * @return string|NULL
1234
   *   Return the output of the rendered view or NULL if something failed in the
1235
   *   process.
1236
   */
1237
  public function render($display_id = NULL) {
1238
    $this->execute($display_id);
1239

    
1240
    // Check to see if the build failed.
1241
    if (!empty($this->build_info['fail'])) {
1242
      return;
1243
    }
1244
    if (!empty($this->build_info['denied'])) {
1245
      return;
1246
    }
1247

    
1248
    drupal_theme_initialize();
1249

    
1250
    $start = microtime(TRUE);
1251
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1252
      $this->start_query_capture();
1253
    }
1254

    
1255
    $exposed_form = $this->display_handler->get_plugin('exposed_form');
1256
    $exposed_form->pre_render($this->result);
1257

    
1258
    // Check for already-cached output.
1259
    if (!empty($this->live_preview)) {
1260
      $cache = FALSE;
1261
    }
1262
    else {
1263
      $cache = $this->display_handler->get_plugin('cache');
1264
    }
1265
    if ($cache && $cache->cache_get('output')) {
1266
    }
1267
    else {
1268
      if ($cache) {
1269
        $cache->cache_start();
1270
      }
1271

    
1272
      // Run pre_render for the pager as it might change the result.
1273
      if (!empty($this->query->pager)) {
1274
        $this->query->pager->pre_render($this->result);
1275
      }
1276

    
1277
      // Initialize the style plugin.
1278
      $this->init_style();
1279

    
1280
      // Give field handlers the opportunity to perform additional queries
1281
      // using the entire resultset prior to rendering.
1282
      if ($this->style_plugin->uses_fields()) {
1283
        foreach ($this->field as $id => $handler) {
1284
          if (!empty($this->field[$id])) {
1285
            $this->field[$id]->pre_render($this->result);
1286
          }
1287
        }
1288
      }
1289

    
1290
      $this->style_plugin->pre_render($this->result);
1291

    
1292
      // Let modules modify the view just prior to rendering it.
1293
      foreach (module_implements('views_pre_render') as $module) {
1294
        $function = $module . '_views_pre_render';
1295
        $function($this);
1296
      }
1297

    
1298
      // Let the themes play too, because pre render is a very themey thing.
1299
      foreach ($GLOBALS['base_theme_info'] as $base) {
1300
        $function = $base->name . '_views_pre_render';
1301
        if (function_exists($function)) {
1302
          $function($this);
1303
        }
1304
      }
1305
      $function = $GLOBALS['theme'] . '_views_pre_render';
1306
      if (function_exists($function)) {
1307
        $function($this);
1308
      }
1309

    
1310
      $this->display_handler->output = $this->display_handler->render();
1311
      if ($cache) {
1312
        $cache->cache_set('output');
1313
      }
1314
    }
1315
    $this->render_time = microtime(TRUE) - $start;
1316

    
1317
    $exposed_form->post_render($this->display_handler->output);
1318

    
1319
    if ($cache) {
1320
      $cache->post_render($this->display_handler->output);
1321
    }
1322

    
1323
    // Let modules modify the view output after it is rendered.
1324
    foreach (module_implements('views_post_render') as $module) {
1325
      $function = $module . '_views_post_render';
1326
      $function($this, $this->display_handler->output, $cache);
1327
    }
1328

    
1329
    // Let the themes play too, because post render is a very themey thing.
1330
    foreach ($GLOBALS['base_theme_info'] as $base) {
1331
      $function = $base->name . '_views_post_render';
1332
      if (function_exists($function)) {
1333
        $function($this, $this->display_handler->output, $cache);
1334
      }
1335
    }
1336
    $function = $GLOBALS['theme'] . '_views_post_render';
1337
    if (function_exists($function)) {
1338
      $function($this, $this->display_handler->output, $cache);
1339
    }
1340

    
1341
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1342
      $this->end_query_capture();
1343
    }
1344

    
1345
    return $this->display_handler->output;
1346
  }
1347

    
1348
  /**
1349
   * Render a specific field via the field ID and the row #.
1350
   *
1351
   * Note: You might want to use views_plugin_style::render_fields as it
1352
   * caches the output for you.
1353
   *
1354
   * @param string $field
1355
   *   The id of the field to be rendered.
1356
   * @param int $row
1357
   *   The row number in the $view->result which is used for the rendering.
1358
   *
1359
   * @return string
1360
   *   The rendered output of the field.
1361
   */
1362
  public function render_field($field, $row) {
1363
    if (isset($this->field[$field]) && isset($this->result[$row])) {
1364
      return $this->field[$field]->advanced_render($this->result[$row]);
1365
    }
1366
  }
1367

    
1368
  /**
1369
   * Execute the given display, with the given arguments.
1370
   * To be called externally by whatever mechanism invokes the view,
1371
   * such as a page callback, hook_block, etc.
1372
   *
1373
   * This function should NOT be used by anything external as this
1374
   * returns data in the format specified by the display. It can also
1375
   * have other side effects that are only intended for the 'proper'
1376
   * use of the display, such as setting page titles and breadcrumbs.
1377
   *
1378
   * If you simply want to view the display, use view::preview() instead.
1379
   */
1380
  public function execute_display($display_id = NULL, $args = array()) {
1381
    if (empty($this->current_display) || $this->current_display != $this->choose_display($display_id)) {
1382
      if (!$this->set_display($display_id)) {
1383
        return FALSE;
1384
      }
1385
    }
1386

    
1387
    $this->pre_execute($args);
1388

    
1389
    // Execute the view.
1390
    $output = $this->display_handler->execute();
1391

    
1392
    $this->post_execute();
1393
    return $output;
1394
  }
1395

    
1396
  /**
1397
   * Preview the given display, with the given arguments.
1398
   *
1399
   * To be called externally, probably by an AJAX handler of some flavor.
1400
   * Can also be called when views are embedded, as this guarantees
1401
   * normalized output.
1402
   */
1403
  public function preview($display_id = NULL, $args = array()) {
1404
    if (empty($this->current_display) || ((!empty($display_id)) && $this->current_display != $display_id)) {
1405
      if (!$this->set_display($display_id)) {
1406
        return FALSE;
1407
      }
1408
    }
1409

    
1410
    $this->preview = TRUE;
1411
    $this->pre_execute($args);
1412
    // Preview the view.
1413
    $output = $this->display_handler->preview();
1414

    
1415
    $this->post_execute();
1416
    return $output;
1417
  }
1418

    
1419
  /**
1420
   * Run attachments and let the display do what it needs to do prior
1421
   * to running.
1422
   */
1423
  public function pre_execute($args = array()) {
1424
    $this->old_view[] = views_get_current_view();
1425
    views_set_current_view($this);
1426
    $display_id = $this->current_display;
1427

    
1428
    // Prepare the view with the information we have, but only if we were
1429
    // passed arguments, as they may have been set previously.
1430
    if ($args) {
1431
      $this->set_arguments($args);
1432
    }
1433

    
1434
    // Trigger hook_views_pre_view(). Allow other modules to modify the view
1435
    // just prior to executing the preview.
1436
    foreach (module_implements('views_pre_view') as $module) {
1437
      $function = $module . '_views_pre_view';
1438
      $function($this, $display_id, $this->args);
1439
    }
1440

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

    
1444
    // Allow the display handler to set up for execution.
1445
    $this->display_handler->pre_execute();
1446
  }
1447

    
1448
  /**
1449
   * Unset the current view, mostly.
1450
   */
1451
  public function post_execute() {
1452
    // unset current view so we can be properly destructed later on.
1453
    // Return the previous value in case we're an attachment.
1454
    if ($this->old_view) {
1455
      $old_view = array_pop($this->old_view);
1456
    }
1457

    
1458
    views_set_current_view(isset($old_view) ? $old_view : FALSE);
1459
  }
1460

    
1461
  /**
1462
   * Run attachment displays for the view.
1463
   */
1464
  public function attach_displays() {
1465
    if (!empty($this->is_attachment)) {
1466
      return;
1467
    }
1468

    
1469
    if (!$this->display_handler->accept_attachments()) {
1470
      return;
1471
    }
1472

    
1473
    $this->is_attachment = TRUE;
1474
    // Give other displays an opportunity to attach to the view.
1475
    foreach ($this->display as $id => $display) {
1476
      if (!empty($this->display[$id]->handler)) {
1477
        $this->display[$id]->handler->attach_to($this->current_display);
1478
      }
1479
    }
1480
    $this->is_attachment = FALSE;
1481
  }
1482

    
1483
  /**
1484
   * Called to get hook_menu() info from the view and the named display handler.
1485
   *
1486
   * @param string $display_id
1487
   *   A display id.
1488
   * @param array $callbacks
1489
   *   A menu callback array passed from views_menu_alter().
1490
   */
1491
  public function execute_hook_menu($display_id = NULL, &$callbacks = array()) {
1492
    // Prepare the view with the information we have.
1493
    // This was probably already called, but it's good to be safe.
1494
    if (!$this->set_display($display_id)) {
1495
      return FALSE;
1496
    }
1497

    
1498
    // Execute the view.
1499
    if (isset($this->display_handler)) {
1500
      return $this->display_handler->execute_hook_menu($callbacks);
1501
    }
1502
  }
1503

    
1504
  /**
1505
   * Called to get hook_block information from the view and the
1506
   * named display handler.
1507
   */
1508
  public function execute_hook_block_list($display_id = NULL) {
1509
    // Prepare the view with the information we have.
1510
    // This was probably already called, but it's good to be safe.
1511
    if (!$this->set_display($display_id)) {
1512
      return FALSE;
1513
    }
1514

    
1515
    // Execute the view.
1516
    if (isset($this->display_handler)) {
1517
      return $this->display_handler->execute_hook_block_list();
1518
    }
1519
  }
1520

    
1521
  /**
1522
   * Determine if the given user has access to the view.
1523
   *
1524
   * Note that this sets the display handler if it hasn't been.
1525
   */
1526
  public function access($displays = NULL, $account = NULL) {
1527
    // No one should have access to disabled views.
1528
    if (!empty($this->disabled)) {
1529
      return FALSE;
1530
    }
1531

    
1532
    if (!isset($this->current_display)) {
1533
      $this->init_display();
1534
    }
1535

    
1536
    if (!$account) {
1537
      $account = $GLOBALS['user'];
1538
    }
1539

    
1540
    // We can't use choose_display() here because that function calls this one.
1541
    $displays = (array) $displays;
1542
    foreach ($displays as $display_id) {
1543
      if (!empty($this->display[$display_id]->handler)) {
1544
        if ($this->display[$display_id]->handler->access($account)) {
1545
          return TRUE;
1546
        }
1547
      }
1548
    }
1549

    
1550
    return FALSE;
1551
  }
1552

    
1553
  /**
1554
   * Get the view's current title.
1555
   *
1556
   * This can change depending upon how it was built.
1557
   */
1558
  public function get_title() {
1559
    if (empty($this->display_handler)) {
1560
      if (!$this->set_display('default')) {
1561
        return FALSE;
1562
      }
1563
    }
1564

    
1565
    // During building, we might find a title override. If so, use it.
1566
    if (!empty($this->build_info['title'])) {
1567
      $title = $this->build_info['title'];
1568
    }
1569
    else {
1570
      $title = $this->display_handler->get_option('title');
1571
    }
1572

    
1573
    // Allow substitutions from the first row.
1574
    if ($this->init_style()) {
1575
      $title = $this->style_plugin->tokenize_value($title, 0);
1576
    }
1577
    return $title;
1578
  }
1579

    
1580
  /**
1581
   * Override the view's current title.
1582
   *
1583
   * The tokens in the title get replaced before rendering.
1584
   */
1585
  public function set_title($title) {
1586
    $this->build_info['title'] = $title;
1587
    return TRUE;
1588
  }
1589

    
1590
  /**
1591
   * Return the human readable name for a view.
1592
   *
1593
   * When a certain view doesn't have a human readable name return the machine
1594
   * readable name.
1595
   */
1596
  public function get_human_name() {
1597
    if (!empty($this->human_name)) {
1598
      $human_name = $this->human_name;
1599
    }
1600
    else {
1601
      $human_name = $this->name;
1602
    }
1603
    return $human_name;
1604
  }
1605

    
1606
  /**
1607
   * Force the view to build a title.
1608
   */
1609
  public function build_title() {
1610
    $this->init_display();
1611

    
1612
    if (empty($this->built)) {
1613
      $this->init_query();
1614
    }
1615

    
1616
    $this->init_handlers();
1617

    
1618
    $this->_build_arguments();
1619
  }
1620

    
1621
  /**
1622
   * Get the URL for the current view.
1623
   *
1624
   * This URL will be adjusted for arguments.
1625
   */
1626
  public function get_url($args = NULL, $path = NULL) {
1627
    if (!empty($this->override_url)) {
1628
      return $this->override_url;
1629
    }
1630

    
1631
    if (!isset($path)) {
1632
      $path = $this->get_path();
1633
    }
1634
    if (!isset($args)) {
1635
      $args = $this->args;
1636

    
1637
      // Exclude arguments that were computed, not passed on the URL.
1638
      $position = 0;
1639
      if (!empty($this->argument)) {
1640
        foreach ($this->argument as $argument_id => $argument) {
1641
          if (!empty($argument->options['default_argument_skip_url'])) {
1642
            unset($args[$position]);
1643
          }
1644
          $position++;
1645
        }
1646
      }
1647
    }
1648
    // Don't bother working if there's nothing to do.
1649
    if (empty($path) || (empty($args) && strpos($path, '%') === FALSE)) {
1650
      return $path;
1651
    }
1652

    
1653
    $pieces = array();
1654
    $argument_keys = isset($this->argument) ? array_keys($this->argument) : array();
1655
    $id = current($argument_keys);
1656
    foreach (explode('/', $path) as $piece) {
1657
      if ($piece != '%') {
1658
        $pieces[] = $piece;
1659
      }
1660
      else {
1661
        if (empty($args)) {
1662
          // Try to never put % in a url; use the wildcard instead.
1663
          if ($id && !empty($this->argument[$id]->options['exception']['value'])) {
1664
            $pieces[] = $this->argument[$id]->options['exception']['value'];
1665
          }
1666
          else {
1667
            $pieces[] = '*';
1668
            // @todo Gotta put something if there just isn't one.
1669
          }
1670

    
1671
        }
1672
        else {
1673
          $pieces[] = array_shift($args);
1674
        }
1675

    
1676
        if ($id) {
1677
          $id = next($argument_keys);
1678
        }
1679
      }
1680
    }
1681

    
1682
    if (!empty($args)) {
1683
      $pieces = array_merge($pieces, $args);
1684
    }
1685
    return implode('/', $pieces);
1686
  }
1687

    
1688
  /**
1689
   * Get the base path used for this view.
1690
   */
1691
  public function get_path() {
1692
    if (!empty($this->override_path)) {
1693
      return $this->override_path;
1694
    }
1695

    
1696
    if (empty($this->display_handler)) {
1697
      if (!$this->set_display('default')) {
1698
        return FALSE;
1699
      }
1700
    }
1701
    return $this->display_handler->get_path();
1702
  }
1703

    
1704
  /**
1705
   * Get the breadcrumb used for this view.
1706
   *
1707
   * @param bool $set
1708
   *   If true, use drupal_set_breadcrumb() to install the breadcrumb.
1709
   */
1710
  public function get_breadcrumb($set = FALSE) {
1711
    // Now that we've built the view, extract the breadcrumb.
1712
    $base = TRUE;
1713
    $breadcrumb = array();
1714

    
1715
    if (!empty($this->build_info['breadcrumb'])) {
1716
      foreach ($this->build_info['breadcrumb'] as $path => $title) {
1717
        // Check to see if the frontpage is in the breadcrumb trail; if it
1718
        // is, we'll remove that from the actual breadcrumb later.
1719
        if ($path == variable_get('site_frontpage', 'node')) {
1720
          $base = FALSE;
1721
          $title = t('Home');
1722
        }
1723
        if ($title) {
1724
          $breadcrumb[] = l($title, $path, array('html' => TRUE));
1725
        }
1726
      }
1727

    
1728
      if ($set) {
1729
        if ($base) {
1730
          $breadcrumb = array_merge(drupal_get_breadcrumb(), $breadcrumb);
1731
        }
1732
        drupal_set_breadcrumb($breadcrumb);
1733
      }
1734
    }
1735
    return $breadcrumb;
1736
  }
1737

    
1738
  /**
1739
   * Is this view cacheable?.
1740
   */
1741
  public function is_cacheable() {
1742
    return $this->is_cacheable;
1743
  }
1744

    
1745
  /**
1746
   * Set up query capturing.
1747
   *
1748
   * Db_query() stores the queries that it runs in global $queries, bit only if
1749
   * dev_query is set to true. In this case, we want to temporarily override
1750
   * that setting if it's not and we can do that without forcing a db rewrite by
1751
   * just manipulating $conf. This is kind of evil but it works.
1752
   */
1753
  public function start_query_capture() {
1754
    global $conf, $queries;
1755
    if (empty($conf['dev_query'])) {
1756
      $this->fix_dev_query = TRUE;
1757
      $conf['dev_query'] = TRUE;
1758
    }
1759

    
1760
    // Record the last query key used; anything already run isn't a query that
1761
    // we are interested in.
1762
    $this->last_query_key = NULL;
1763

    
1764
    if (!empty($queries)) {
1765
      $keys = array_keys($queries);
1766
      $this->last_query_key = array_pop($keys);
1767
    }
1768
  }
1769

    
1770
  /**
1771
   * Add the list of queries run during render to buildinfo.
1772
   *
1773
   * @see view::start_query_capture()
1774
   */
1775
  public function end_query_capture() {
1776
    global $conf, $queries;
1777
    if (!empty($this->fix_dev_query)) {
1778
      $conf['dev_query'] = FALSE;
1779
    }
1780

    
1781
    // Make a copy of the array so we can manipulate it with array_splice.
1782
    $temp = $queries;
1783

    
1784
    // Scroll through the queries until we get to our last query key.
1785
    // Unset anything in our temp array.
1786
    if (isset($this->last_query_key)) {
1787
      foreach ($queries as $id => $query) {
1788
        if ($id == $this->last_query_key) {
1789
          break;
1790
        }
1791

    
1792
        unset($temp[$id]);
1793
      }
1794
    }
1795

    
1796
    $this->additional_queries = $temp;
1797
  }
1798

    
1799
  /**
1800
   * Static factory method to load a list of views based upon a $where clause.
1801
   *
1802
   * Although this method could be implemented to simply iterate over
1803
   * views::load(), that would be very slow.  Buiding the views externally from
1804
   * unified queries is much faster.
1805
   */
1806
  static function load_views() {
1807
    $result = db_query("SELECT DISTINCT v.* FROM {views_view} v");
1808
    $views = array();
1809

    
1810
    // Load all the views.
1811
    foreach ($result as $data) {
1812
      $view = new view();
1813
      $view->load_row($data);
1814
      $view->loaded = TRUE;
1815
      $view->type = t('Normal');
1816
      $views[$view->name] = $view;
1817
      $names[$view->vid] = $view->name;
1818
    }
1819

    
1820
    // Stop if we didn't get any views.
1821
    if (!$views) {
1822
      return array();
1823
    }
1824

    
1825
    // Now load all the subtables.
1826
    foreach (view::db_objects() as $key) {
1827
      $object_name = "views_$key";
1828
      $result = db_query("SELECT * FROM {{$object_name}} WHERE vid IN (:vids) ORDER BY vid, position",
1829
        array(':vids' => array_keys($names)));
1830

    
1831
      foreach ($result as $data) {
1832
        $object = new $object_name(FALSE);
1833
        $object->load_row($data);
1834

    
1835
        // Because it can get complicated with this much indirection, make a
1836
        // shortcut reference.
1837
        $location = &$views[$names[$object->vid]]->$key;
1838

    
1839
        // If we have a basic id field, load the item onto the view based on
1840
        // this ID, otherwise push it on.
1841
        if (!empty($object->id)) {
1842
          $location[$object->id] = $object;
1843
        }
1844
        else {
1845
          $location[] = $object;
1846
        }
1847
      }
1848
    }
1849
    return $views;
1850
  }
1851

    
1852
  /**
1853
   * Save the view to the database.
1854
   *
1855
   * If the view does not already exist a vid will be assigned to the view and
1856
   * also returned from this function.
1857
   */
1858
  public function save() {
1859
    if ($this->vid == 'new') {
1860
      $this->vid = NULL;
1861
    }
1862
    // If there is no vid, check if a view with this machine name already
1863
    // exists.
1864
    elseif (empty($this->vid)) {
1865
      $vid = db_query("SELECT vid from {views_view} WHERE name = :name", array(':name' => $this->name))->fetchField();
1866
      $this->vid = $vid ? $vid : NULL;
1867
    }
1868

    
1869
    // Let modules modify the view just prior to saving it.
1870
    module_invoke_all('views_view_presave', $this);
1871

    
1872
    $transaction = db_transaction();
1873

    
1874
    try {
1875
      // If we have no vid or our vid is a string, this is a new view.
1876
      if (!empty($this->vid)) {
1877
        // remove existing table entries.
1878
        foreach ($this->db_objects() as $key) {
1879
          db_delete('views_' . $key)
1880
            ->condition('vid', $this->vid)
1881
            ->execute();
1882
        }
1883
      }
1884

    
1885
      $this->save_row(!empty($this->vid) ? 'vid' : FALSE);
1886

    
1887
      // Save all of our subtables.
1888
      foreach ($this->db_objects() as $key) {
1889
        $this->_save_rows($key);
1890
      }
1891
    }
1892
    catch (Exception $e) {
1893
      $transaction->rollback();
1894
      watchdog_exception('views', $e);
1895
      throw $e;
1896
    }
1897

    
1898
    $this->save_locale_strings();
1899

    
1900
    // Clear the relevant caches.
1901
    cache_clear_all('views_block_items:', 'cache_views', TRUE);
1902
    views_invalidate_cache('ctools_export:views_view:' . $this->name);
1903

    
1904
    // Notify modules that this view has been saved.
1905
    module_invoke_all('views_view_save', $this);
1906
  }
1907

    
1908
  /**
1909
   * Save a row to the database for the given key.
1910
   *
1911
   * i.e. one of the keys from view::db_objects().
1912
   */
1913
  public function _save_rows($key) {
1914
    $count = 0;
1915
    foreach ($this->$key as $position => $object) {
1916
      $object->position = ++$count;
1917
      $object->vid = $this->vid;
1918
      $object->save_row();
1919
    }
1920
  }
1921

    
1922
  /**
1923
   * Delete the view from the database.
1924
   */
1925
  public function delete($clear = TRUE) {
1926
    if (empty($this->vid)) {
1927
      return;
1928
    }
1929

    
1930
    db_delete('views_view')
1931
      ->condition('vid', $this->vid)
1932
      ->execute();
1933
    // Delete from all of our subtables as well.
1934
    foreach ($this->db_objects() as $key) {
1935
      db_delete('views_' . $key)
1936
        ->condition('vid', $this->vid)
1937
        ->execute();
1938
    }
1939

    
1940
    cache_clear_all('views_query:' . $this->name, 'cache_views');
1941

    
1942
    if ($clear) {
1943
      // Clear caches.
1944
      cache_clear_all('views_block_items:', 'cache_views', TRUE);
1945
      views_invalidate_cache('ctools_export:views_view:' . $this->name);
1946
    }
1947

    
1948
    // Notify modules that this view has been deleted.
1949
    module_invoke_all('views_view_delete', $this);
1950
  }
1951

    
1952
  /**
1953
   * Export a view as PHP code.
1954
   */
1955
  public function export($indent = '') {
1956
    $this->init_display();
1957
    $this->init_query();
1958
    $output = '';
1959
    $output .= $this->export_row('view', $indent);
1960
    // Set the API version.
1961
    $output .= $indent . '$view->api_version = \'' . views_api_version() . "';\n";
1962
    $output .= $indent . '$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */' . "\n";
1963

    
1964
    foreach ($this->display as $id => $display) {
1965
      $output .= "\n" . $indent . "/* Display: $display->display_title */\n";
1966
      $output .= $indent . '$handler = $view->new_display(' . ctools_var_export($display->display_plugin, $indent) . ', ' . ctools_var_export($display->display_title, $indent) . ', \'' . $id . "');\n";
1967
      if (empty($display->handler)) {
1968
        // @todo Probably need a method of exporting broken displays as they
1969
        // may simply be broken because a module is not installed. That does
1970
        // not invalidate the display.
1971
        continue;
1972
      }
1973

    
1974
      $output .= $display->handler->export_options($indent, '$handler->options');
1975
    }
1976

    
1977
    // Give the localization system a chance to export translatables to code.
1978
    if ($this->init_localization()) {
1979
      $this->export_locale_strings('export');
1980
      $translatables = $this->localization_plugin->export_render($indent);
1981
      if (!empty($translatables)) {
1982
        $output .= $translatables;
1983
      }
1984
    }
1985

    
1986
    return $output;
1987
  }
1988

    
1989
  /**
1990
   * Make a copy of this view with IDs, handlers sanitized
1991
   *
1992
   * I'd call this clone() but it's reserved.
1993
   */
1994
  public function copy() {
1995
    $code = $this->export();
1996
    eval($code);
1997
    return $view;
1998
  }
1999

    
2000
  /**
2001
   * Safely clone a view.
2002
   *
2003
   * Because views are complicated objects within objects, and PHP loves to do
2004
   * references to everything, if a View is not properly and safely cloned it
2005
   * will still have references to the original view, and can actually cause the
2006
   * original view to point to objects in the cloned view. This gets ugly fast.
2007
   *
2008
   * This will completely wipe a view clean so it can be considered fresh.
2009
   *
2010
   * @return view
2011
   *    The cloned view.
2012
   */
2013
  public function clone_view() {
2014
    $clone = clone $this;
2015

    
2016
    $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_aliases', 'many_to_one_tables', 'feed_icon');
2017
    foreach ($keys as $key) {
2018
      if (isset($clone->{$key})) {
2019
        unset($clone->{$key});
2020
      }
2021
    }
2022
    $clone->built = $clone->executed = FALSE;
2023
    $clone->build_info = array();
2024
    $clone->attachment_before = '';
2025
    $clone->attachment_after = '';
2026
    $clone->result = array();
2027

    
2028
    // Shallow cloning means that all the display objects *were not cloned*. We
2029
    // must clone them ourselves.
2030
    $displays = array();
2031
    foreach ($clone->display as $id => $display) {
2032
      $displays[$id] = clone $display;
2033
      if (isset($displays[$id]->handler)) {
2034
        unset($displays[$id]->handler);
2035
      }
2036
    }
2037
    $clone->display = $displays;
2038

    
2039
    return $clone;
2040
  }
2041

    
2042
  /**
2043
   * Unset references so that a $view object may be properly garbage collected.
2044
   */
2045
  public function destroy() {
2046
    foreach (array_keys($this->display) as $display_id) {
2047
      if (isset($this->display[$display_id]->handler) && is_object($this->display[$display_id]->handler)) {
2048
        $this->display[$display_id]->handler->destroy();
2049
        unset($this->display[$display_id]->handler);
2050
      }
2051
    }
2052

    
2053
    foreach (views_object_types() as $type => $info) {
2054
      if (isset($this->$type)) {
2055
        $handlers = &$this->$type;
2056
        foreach ($handlers as $id => $item) {
2057
          $handlers[$id]->destroy();
2058
        }
2059
        unset($handlers);
2060
      }
2061
    }
2062

    
2063
    if (isset($this->style_plugin)) {
2064
      $this->style_plugin->destroy();
2065
      unset($this->style_plugin);
2066
    }
2067

    
2068
    // Clear these to make sure the view can be processed/used again.
2069
    if (isset($this->display_handler)) {
2070
      unset($this->display_handler);
2071
    }
2072

    
2073
    if (isset($this->current_display)) {
2074
      unset($this->current_display);
2075
    }
2076

    
2077
    if (isset($this->query)) {
2078
      unset($this->query);
2079
    }
2080

    
2081
    $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');
2082
    foreach ($keys as $key) {
2083
      if (isset($this->$key)) {
2084
        unset($this->$key);
2085
      }
2086
    }
2087

    
2088
    // These keys are checked by the next init, so instead of unsetting them,
2089
    // just set the default values.
2090
    $keys = array('items_per_page', 'offset', 'current_page');
2091
    foreach ($keys as $key) {
2092
      if (isset($this->$key)) {
2093
        $this->$key = NULL;
2094
      }
2095
    }
2096

    
2097
    $this->built = $this->executed = FALSE;
2098
    $this->build_info = array();
2099
    $this->attachment_before = '';
2100
    $this->attachment_after = '';
2101
  }
2102

    
2103
  /**
2104
   * Make sure the view is completely valid.
2105
   *
2106
   * @return bool
2107
   *   TRUE if the view is valid; an array of error strings if it is not.
2108
   */
2109
  public function validate() {
2110
    $this->init_display();
2111

    
2112
    $errors = array();
2113
    $this->display_errors = NULL;
2114

    
2115
    $current_display = $this->current_display;
2116
    foreach ($this->display as $id => $display) {
2117
      if ($display->handler) {
2118
        if (!empty($display->deleted)) {
2119
          continue;
2120
        }
2121

    
2122
        $result = $this->display[$id]->handler->validate();
2123
        if (!empty($result) && is_array($result)) {
2124
          $errors = array_merge($errors, $result);
2125
          // Mark this display as having validation errors.
2126
          $this->display_errors[$id] = TRUE;
2127
        }
2128
      }
2129
    }
2130

    
2131
    $this->set_display($current_display);
2132
    return $errors ? $errors : TRUE;
2133
  }
2134

    
2135
  /**
2136
   * Find and initialize the localization plugin.
2137
   */
2138
  public function init_localization() {
2139
    // If the translate attribute isn't set, init the localization plugin.
2140
    if (!isset($this->localization_plugin->translate)) {
2141
      $this->localization_plugin = views_get_plugin('localization', views_get_localization_plugin());
2142

    
2143
      // If the plugin is still not set, turn off all localization by using the
2144
      // views_plugin_localization_none plugin. This plugin has the translate
2145
      // property set to FALSE, signifying localization should not occur.
2146
      if (empty($this->localization_plugin)) {
2147
        $this->localization_plugin = views_get_plugin('localization', 'none');
2148
      }
2149

    
2150
      // Init the plugin.
2151
      $this->localization_plugin->init($this);
2152
    }
2153

    
2154
    // Return the value of the translate property. This is set to FALSE if
2155
    // localization is off.
2156
    return $this->localization_plugin->translate;
2157
  }
2158

    
2159
  /**
2160
   * Determine whether a view supports admin string translation.
2161
   */
2162
  public function is_translatable() {
2163
    // Use translation no matter what type of view.
2164
    if (variable_get('views_localize_all', FALSE)) {
2165
      return TRUE;
2166
    }
2167
    // If the view is normal or overridden, use admin string translation.
2168
    // A newly created view won't have a type. Accept this.
2169
    return (!isset($this->type) || in_array($this->type, array(t('Normal'), t('Overridden')))) ? TRUE : FALSE;
2170
  }
2171

    
2172
  /**
2173
   * Send strings for localization.
2174
   */
2175
  public function save_locale_strings() {
2176
    $this->process_locale_strings('save');
2177
  }
2178

    
2179
  /**
2180
   * Delete localized strings.
2181
   */
2182
  public function delete_locale_strings() {
2183
    $this->process_locale_strings('delete');
2184
  }
2185

    
2186
  /**
2187
   * Export localized strings.
2188
   */
2189
  public function export_locale_strings() {
2190
    $this->process_locale_strings('export');
2191
  }
2192

    
2193
  /**
2194
   * Process strings for localization, deletion or export to code.
2195
   */
2196
  public function process_locale_strings($op) {
2197
    // Ensure this view supports translation, we have a display, and we
2198
    // have a localization plugin.
2199
    // @todo Export does not init every handler.
2200
    if (($this->is_translatable() || $op == 'export') && $this->init_display() && $this->init_localization()) {
2201
      $this->localization_plugin->process_locale_strings($op);
2202
    }
2203
  }
2204

    
2205
}
2206

    
2207
/**
2208
 * Base class for views' database objects.
2209
 */
2210
class views_db_object {
2211

    
2212
  public $db_table;
2213

    
2214
  /**
2215
   * Initialize this object, setting values from schema defaults.
2216
   *
2217
   * @param array|bool $init
2218
   *   If an array, this is a set of values from db_fetch_object to
2219
   *   load. Otherwse, if TRUE values will be filled in from schema
2220
   *   defaults.
2221
   */
2222
  public function init($init = TRUE) {
2223
    if (is_array($init)) {
2224
      return $this->load_row($init);
2225
    }
2226

    
2227
    if (!$init) {
2228
      return;
2229
    }
2230

    
2231
    $schema = drupal_get_schema($this->db_table);
2232

    
2233
    if (!$schema) {
2234
      return;
2235
    }
2236

    
2237
    // Go through our schema and build correlations.
2238
    foreach ($schema['fields'] as $field => $info) {
2239
      if ($info['type'] == 'serial') {
2240
        $this->$field = NULL;
2241
      }
2242
      if (!isset($this->$field)) {
2243
        if (!empty($info['serialize']) && isset($info['serialized default'])) {
2244
          $this->$field = unserialize($info['serialized default']);
2245
        }
2246
        elseif (isset($info['default'])) {
2247
          $this->$field = $info['default'];
2248
        }
2249
        else {
2250
          $this->$field = '';
2251
        }
2252
      }
2253
    }
2254
  }
2255

    
2256
  /**
2257
   * Write the row to the database.
2258
   *
2259
   * @param bool $update
2260
   *   If true this will be an UPDATE query. Otherwise it will be an INSERT.
2261
   */
2262
  public function save_row($update = NULL) {
2263
    $fields = $defs = $values = $serials = array();
2264
    $schema = drupal_get_schema($this->db_table);
2265

    
2266
    // Go through our schema and build correlations.
2267
    foreach ($schema['fields'] as $field => $info) {
2268
      // Special case - skip serial types if we are updating.
2269
      if ($info['type'] == 'serial') {
2270
        $serials[] = $field;
2271
        continue;
2272
      }
2273
      elseif ($info['type'] == 'int') {
2274
        $this->$field = (int) $this->$field;
2275
      }
2276
      $fields[$field] = empty($info['serialize']) ? $this->$field : serialize($this->$field);
2277
    }
2278
    if (!$update) {
2279
      $query = db_insert($this->db_table);
2280
    }
2281
    else {
2282
      $query = db_update($this->db_table)
2283
        ->condition($update, $this->$update);
2284
    }
2285
    $return = $query
2286
      ->fields($fields)
2287
      ->execute();
2288

    
2289
    if ($serials && !$update) {
2290
      // Get last insert ids and fill them in. Well, one ID.
2291
      foreach ($serials as $field) {
2292
        $this->$field = $return;
2293
      }
2294
    }
2295
  }
2296

    
2297
  /**
2298
   * Load the object with a row from the database.
2299
   *
2300
   * This method is separate from the constructor in order to give us more
2301
   * flexibility in terms of how the view object is built in different contexts.
2302
   *
2303
   * @param object $data
2304
   *   An object from db_fetch_object. It should contain all of the fields
2305
   *   that are in the schema.
2306
   */
2307
  public function load_row($data) {
2308
    $schema = drupal_get_schema($this->db_table);
2309

    
2310
    // Go through our schema and build correlations.
2311
    foreach ($schema['fields'] as $field => $info) {
2312
      $this->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
2313
    }
2314
  }
2315

    
2316
  /**
2317
   * Export a loaded row.
2318
   *
2319
   * Might be an argument, field or the view itself to PHP code.
2320
   *
2321
   * @param string $identifier
2322
   *   The variable to assign the PHP code for this object to.
2323
   * @param int $indent
2324
   *   An optional indentation for prettifying nested code.
2325
   */
2326
  public function export_row($identifier = NULL, $indent = '') {
2327
    ctools_include('export');
2328

    
2329
    if (!$identifier) {
2330
      $identifier = $this->db_table;
2331
    }
2332
    $schema = drupal_get_schema($this->db_table);
2333

    
2334
    $output = $indent . '$' . $identifier . ' = new ' . get_class($this) . "();\n";
2335
    // Go through our schema and build correlations.
2336
    foreach ($schema['fields'] as $field => $info) {
2337
      if (!empty($info['no export'])) {
2338
        continue;
2339
      }
2340
      if (!isset($this->$field)) {
2341
        if (isset($info['default'])) {
2342
          $this->$field = $info['default'];
2343
        }
2344
        else {
2345
          $this->$field = '';
2346
        }
2347

    
2348
        // Serialized defaults must be set as serialized.
2349
        if (isset($info['serialize'])) {
2350
          $this->$field = unserialize($this->$field);
2351
        }
2352
      }
2353
      $value = $this->$field;
2354
      if ($info['type'] == 'int') {
2355
        if (isset($info['size']) && $info['size'] == 'tiny') {
2356
          $value = (bool) $value;
2357
        }
2358
        else {
2359
          $value = (int) $value;
2360
        }
2361
      }
2362

    
2363
      $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
2364
    }
2365
    return $output;
2366
  }
2367

    
2368
  /**
2369
   * Add a new display handler to the view, automatically creating an id.
2370
   *
2371
   * @param string $type
2372
   *   The plugin type from the views plugin data. Defaults to 'page'.
2373
   * @param string $title
2374
   *   The title of the display; optional, may be filled in from default.
2375
   * @param int $id
2376
   *   The id to use.
2377
   *
2378
   * @return string
2379
   *   The key to the display in $view->display, so that the new display can be
2380
   *   easily located.
2381
   */
2382
  public function add_display($type = 'page', $title = NULL, $id = NULL) {
2383
    if (empty($type)) {
2384
      return FALSE;
2385
    }
2386

    
2387
    $plugin = views_fetch_plugin_data('display', $type);
2388
    if (empty($plugin)) {
2389
      $plugin['title'] = t('Broken');
2390
    }
2391

    
2392
    if (empty($id)) {
2393
      $id = $this->generate_display_id($type);
2394
      if ($id !== 'default') {
2395
        preg_match("/[0-9]+/", $id, $count);
2396
        $count = $count[0];
2397
      }
2398
      else {
2399
        $count = '';
2400
      }
2401

    
2402
      if (empty($title)) {
2403
        if ($count > 1) {
2404
          $title = $plugin['title'] . ' ' . $count;
2405
        }
2406
        else {
2407
          $title = $plugin['title'];
2408
        }
2409
      }
2410
    }
2411

    
2412
    // Create the new display object.
2413
    $display = new views_display();
2414
    $display->options($type, $id, $title);
2415

    
2416
    // Add the new display object to the view.
2417
    $this->display[$id] = $display;
2418
    return $id;
2419
  }
2420

    
2421
  /**
2422
   * Generate a display id of a certain plugin type.
2423
   *
2424
   * @param string $type
2425
   *   Which plugin should be used for the new display id.
2426
   */
2427
  public function generate_display_id($type) {
2428
    // 'default' is singular and is unique, so just go with 'default'
2429
    // for it. For all others, start counting.
2430
    if ($type == 'default') {
2431
      return 'default';
2432
    }
2433
    // Initial id.
2434
    $id = $type . '_1';
2435
    $count = 1;
2436

    
2437
    // Loop through IDs based upon our style plugin name until we find one that
2438
    // is unused.
2439
    while (!empty($this->display[$id])) {
2440
      $id = $type . '_' . ++$count;
2441
    }
2442

    
2443
    return $id;
2444
  }
2445

    
2446
  /**
2447
   * Generates a unique ID for an item.
2448
   *
2449
   * These items are typically fields, filters, sort criteria, or arguments.
2450
   *
2451
   * @param int $requested_id
2452
   *   The requested ID for the item.
2453
   * @param array $existing_items
2454
   *   An array of existing items, keyed by their IDs.
2455
   *
2456
   * @return string
2457
   *   A unique ID. This will be equal to $requested_id if no item with that ID
2458
   *   already exists. Otherwise, it will be appended with an integer to make
2459
   *   it unique, e.g. "{$requested_id}_1", "{$requested_id}_2", etc.
2460
   */
2461
  public static function generate_item_id($requested_id, $existing_items) {
2462
    $count = 0;
2463
    $id = $requested_id;
2464
    while (!empty($existing_items[$id])) {
2465
      $id = $requested_id . '_' . ++$count;
2466
    }
2467
    return $id;
2468
  }
2469

    
2470
  /**
2471
   * Create a new display and a display handler for it.
2472
   *
2473
   * @param string $type
2474
   *   The plugin type from the views plugin data. Defaults to 'page'.
2475
   * @param string $title
2476
   *   The title of the display; optional, may be filled in from default.
2477
   * @param int $id
2478
   *   The id to use.
2479
   *
2480
   * @return views_plugin_display
2481
   *   A reference to the new handler object.
2482
   */
2483
  public function &new_display($type = 'page', $title = NULL, $id = NULL) {
2484
    $id = $this->add_display($type, $title, $id);
2485

    
2486
    // Create a handler.
2487
    $this->display[$id]->handler = views_get_plugin('display', $this->display[$id]->display_plugin);
2488
    if (empty($this->display[$id]->handler)) {
2489
      // Provide a 'default' handler as an emergency. This won't work well but
2490
      // it will keep things from crashing.
2491
      $this->display[$id]->handler = views_get_plugin('display', 'default');
2492
    }
2493

    
2494
    if (!empty($this->display[$id]->handler)) {
2495
      // Initialize the new display handler with data.
2496
      $this->display[$id]->handler->init($this, $this->display[$id]);
2497
      // If this is NOT the default display handler, let it know which is.
2498
      if ($id != 'default') {
2499
        $this->display[$id]->handler->default_display = &$this->display['default']->handler;
2500
      }
2501
    }
2502

    
2503
    return $this->display[$id]->handler;
2504
  }
2505

    
2506
  /**
2507
   * Add an item with a handler to the view.
2508
   *
2509
   * These items may be fields, filters, sort criteria, or arguments.
2510
   */
2511
  public function add_item($display_id, $type, $table, $field, $options = array(), $id = NULL) {
2512
    $types = views_object_types();
2513
    $this->set_display($display_id);
2514

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

    
2517
    if (empty($id)) {
2518
      $id = $this->generate_item_id($field, $fields);
2519
    }
2520

    
2521
    $new_item = array(
2522
      'id' => $id,
2523
      'table' => $table,
2524
      'field' => $field,
2525
    ) + $options;
2526

    
2527
    if (!empty($types[$type]['type'])) {
2528
      $handler_type = $types[$type]['type'];
2529
    }
2530
    else {
2531
      $handler_type = $type;
2532
    }
2533

    
2534
    $handler = views_get_handler($table, $field, $handler_type);
2535

    
2536
    $fields[$id] = $new_item;
2537
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2538

    
2539
    return $id;
2540
  }
2541

    
2542
  /**
2543
   * Get an array of items for the current display.
2544
   */
2545
  public function get_items($type, $display_id = NULL) {
2546
    $this->set_display($display_id);
2547

    
2548
    if (!isset($display_id)) {
2549
      $display_id = $this->current_display;
2550
    }
2551

    
2552
    // Get info about the types so we can get the right data.
2553
    $types = views_object_types();
2554
    return $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2555
  }
2556

    
2557
  /**
2558
   * Get the config of an item (field/sort/filter/etc) on a given display.
2559
   */
2560
  public function get_item($display_id, $type, $id) {
2561
    // Get info about the types so we can get the right data.
2562
    $types = views_object_types();
2563
    // Initialize the display.
2564
    $this->set_display($display_id);
2565

    
2566
    // Get the existing configuration.
2567
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2568

    
2569
    return isset($fields[$id]) ? $fields[$id] : NULL;
2570
  }
2571

    
2572
  /**
2573
   * Set the config of an item (field/sort/filter/etc) on a given display.
2574
   *
2575
   * Pass in NULL for the $item to remove an item.
2576
   */
2577
  public function set_item($display_id, $type, $id, $item) {
2578
    // Get info about the types so we can get the right data.
2579
    $types = views_object_types();
2580
    // Initialize the display.
2581
    $this->set_display($display_id);
2582

    
2583
    // Get the existing configuration.
2584
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2585
    if (isset($item)) {
2586
      $fields[$id] = $item;
2587
    }
2588
    else {
2589
      unset($fields[$id]);
2590
    }
2591

    
2592
    // Store.
2593
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2594
  }
2595

    
2596
  /**
2597
   * Set an option on an item.
2598
   *
2599
   * Use this only if you have just 1 or 2 options to set; if you have many,
2600
   * consider getting the item, adding the options and doing set_item yourself.
2601
   */
2602
  public function set_item_option($display_id, $type, $id, $option, $value) {
2603
    $item = $this->get_item($display_id, $type, $id);
2604
    $item[$option] = $value;
2605
    $this->set_item($display_id, $type, $id, $item);
2606
  }
2607

    
2608
}
2609

    
2610
/**
2611
 * A display type in a view.
2612
 *
2613
 * This is just the database storage mechanism, and isn't terribly important
2614
 * to the behavior of the display at all.
2615
 */
2616
class views_display extends views_db_object {
2617

    
2618
  /**
2619
   * The display handler itself, which has all the methods.
2620
   *
2621
   * @var views_plugin_display
2622
   */
2623
  public $handler;
2624

    
2625
  /**
2626
   * Stores all options of the display, like fields, filters etc.
2627
   *
2628
   * @var array
2629
   */
2630
  public $display_options;
2631

    
2632
  public $db_table = 'views_display';
2633
  public function __construct($init = TRUE) {
2634
    parent::init($init);
2635
  }
2636

    
2637
  /**
2638
   * {@inheritdoc}
2639
   */
2640
  public function options($type, $id, $title) {
2641
    $this->display_plugin = $type;
2642
    $this->id = $id;
2643
    $this->display_title = $title;
2644
  }
2645

    
2646
}
2647

    
2648
/**
2649
 * Provide a list of object types used in a view, with some info about them.
2650
 */
2651
function views_object_types() {
2652
  static $retval = NULL;
2653

    
2654
  // Statically cache this so t() doesn't run a bajillion times.
2655
  if (!isset($retval)) {
2656
    $retval = array(
2657
      'field' => array(
2658
        // Title.
2659
        'title' => t('Fields'),
2660
        // Lowercase title for mid-sentence.
2661
        'ltitle' => t('fields'),
2662
        // Singular title.
2663
        'stitle' => t('Field'),
2664
        // Lingular lowercase title for mid sentence.
2665
        'lstitle' => t('field'),
2666
        'plural' => 'fields',
2667
      ),
2668
      'argument' => array(
2669
        'title' => t('Contextual filters'),
2670
        'ltitle' => t('contextual filters'),
2671
        'stitle' => t('Contextual filter'),
2672
        'lstitle' => t('contextual filter'),
2673
        'plural' => 'arguments',
2674
      ),
2675
      'sort' => array(
2676
        'title' => t('Sort criteria'),
2677
        'ltitle' => t('sort criteria'),
2678
        'stitle' => t('Sort criterion'),
2679
        'lstitle' => t('sort criterion'),
2680
        'plural' => 'sorts',
2681
      ),
2682
      'filter' => array(
2683
        'title' => t('Filter criteria'),
2684
        'ltitle' => t('filter criteria'),
2685
        'stitle' => t('Filter criterion'),
2686
        'lstitle' => t('filter criterion'),
2687
        'plural' => 'filters',
2688
      ),
2689
      'relationship' => array(
2690
        'title' => t('Relationships'),
2691
        'ltitle' => t('relationships'),
2692
        'stitle' => t('Relationship'),
2693
        'lstitle' => t('Relationship'),
2694
        'plural' => 'relationships',
2695
      ),
2696
      'header' => array(
2697
        'title' => t('Header'),
2698
        'ltitle' => t('header'),
2699
        'stitle' => t('Header'),
2700
        'lstitle' => t('Header'),
2701
        'plural' => 'header',
2702
        'type' => 'area',
2703
      ),
2704
      'footer' => array(
2705
        'title' => t('Footer'),
2706
        'ltitle' => t('footer'),
2707
        'stitle' => t('Footer'),
2708
        'lstitle' => t('Footer'),
2709
        'plural' => 'footer',
2710
        'type' => 'area',
2711
      ),
2712
      'empty' => array(
2713
        'title' => t('No results behavior'),
2714
        'ltitle' => t('no results behavior'),
2715
        'stitle' => t('No results behavior'),
2716
        'lstitle' => t('No results behavior'),
2717
        'plural' => 'empty',
2718
        'type' => 'area',
2719
      ),
2720
    );
2721
  }
2722

    
2723
  return $retval;
2724
}
2725

    
2726
/**
2727
 * @}
2728
 */