Projet

Général

Profil

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

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

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 = isset($this->args[$position]) ? $this->args[$position] : NULL;
847
      $argument->position = $position;
848

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

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

    
865
        if ($argument->is_exception()) {
866
          $arg_title = $argument->exception_title();
867
        }
868
        else {
869
          $arg_title = $argument->get_title();
870
          $argument->query($this->display_handler->use_group_by());
871
        }
872

    
873
        // Add this argument's substitution.
874
        $substitutions['%' . ($position + 1)] = $arg_title;
875
        $substitutions['!' . ($position + 1)] = strip_tags(decode_entities($arg));
876

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

    
892
        // Allow the argument to muck with this breadcrumb.
893
        $argument->set_breadcrumb($this->build_info['breadcrumb']);
894

    
895
        // Test to see if we should use this argument's title.
896
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
897
          $title = $argument->options['title'];
898
        }
899

    
900
        $breadcrumb_args[] = $arg;
901
      }
902
      else {
903
        // determine default condition and handle.
904
        $status = $argument->default_action();
905
        break;
906
      }
907

    
908
      // Be safe with references and loops.
909
      unset($argument);
910
    }
911

    
912
    // set the title in the build info.
913
    if (!empty($title)) {
914
      $this->build_info['title'] = $title;
915
    }
916

    
917
    // Store the arguments for later use.
918
    $this->build_info['substitutions'] = $substitutions;
919

    
920
    return $status;
921
  }
922

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

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

    
942
    // Load the options.
943
    $query_options = $this->display_handler->get_option('query');
944

    
945
    // Create and initialize the query object.
946
    $plugin = !empty($views_data['table']['base']['query class']) ? $views_data['table']['base']['query class'] : 'views_query';
947
    $this->query = views_get_plugin('query', $plugin);
948

    
949
    if (empty($this->query)) {
950
      return FALSE;
951
    }
952

    
953
    $this->query->init($this->base_table, $this->base_field, $query_options['options']);
954
    return TRUE;
955
  }
956

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

    
965
    if (empty($this->current_display) || $display_id) {
966
      if (!$this->set_display($display_id)) {
967
        return FALSE;
968
      }
969
    }
970

    
971
    // Let modules modify the view just prior to building it.
972
    foreach (module_implements('views_pre_build') as $module) {
973
      $function = $module . '_views_pre_build';
974
      $function($this);
975
    }
976

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

    
987
    $this->init_query();
988

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

    
996
    // Let the handlers interact with each other if they really want.
997
    $this->_pre_query();
998

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

    
1019
    // Build all the relationships first thing.
1020
    $this->_build('relationship');
1021

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

    
1033
    // Build all the filters.
1034
    $this->_build('filter');
1035

    
1036
    $this->build_sort = TRUE;
1037

    
1038
    // Arguments can, in fact, cause this whole thing to abort.
1039
    if (!$this->_build_arguments()) {
1040
      $this->build_time = microtime(TRUE) - $start;
1041
      $this->attach_displays();
1042
      return $this->built;
1043
    }
1044

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

    
1053
    if ($this->style_plugin->uses_fields()) {
1054
      $this->_build('field');
1055
    }
1056

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

    
1067
    // Allow area handlers to affect the query.
1068
    $this->_build('header');
1069
    $this->_build('footer');
1070
    $this->_build('empty');
1071

    
1072
    // Allow display handler to affect the query.
1073
    $this->display_handler->query($this->display_handler->use_group_by());
1074

    
1075
    // Allow style handler to affect the query.
1076
    $this->style_plugin->query($this->display_handler->use_group_by());
1077

    
1078
    // Allow exposed form to affect the query.
1079
    if (isset($exposed_form)) {
1080
      $exposed_form->query();
1081
    }
1082

    
1083
    if (variable_get('views_sql_signature', FALSE)) {
1084
      $this->query->add_signature($this);
1085
    }
1086

    
1087
    // Let modules modify the query just prior to finalizing it.
1088
    $this->query->alter($this);
1089

    
1090
    // Only build the query if we weren't interrupted.
1091
    if (empty($this->built)) {
1092
      // Build the necessary info to execute the query.
1093
      $this->query->build($this);
1094
    }
1095

    
1096
    $this->built = TRUE;
1097
    $this->build_time = microtime(TRUE) - $start;
1098

    
1099
    // Attach displays.
1100
    $this->attach_displays();
1101

    
1102
    // Let modules modify the view just after building it.
1103
    foreach (module_implements('views_post_build') as $module) {
1104
      $function = $module . '_views_post_build';
1105
      $function($this);
1106
    }
1107

    
1108
    return TRUE;
1109
  }
1110

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

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

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

    
1168
    if (!empty($this->executed)) {
1169
      return TRUE;
1170
    }
1171

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

    
1179
    // Let modules modify the view just prior to executing it.
1180
    foreach (module_implements('views_pre_execute') as $module) {
1181
      $function = $module . '_views_pre_execute';
1182
      $function($this);
1183
    }
1184

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

    
1210
    // Let modules modify the view just after executing it.
1211
    foreach (module_implements('views_post_execute') as $module) {
1212
      $function = $module . '_views_post_execute';
1213
      $function($this);
1214
    }
1215

    
1216
    $this->executed = TRUE;
1217
  }
1218

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

    
1235
    // Check to see if the build failed.
1236
    if (!empty($this->build_info['fail'])) {
1237
      return;
1238
    }
1239
    if (!empty($this->view->build_info['denied'])) {
1240
      return;
1241
    }
1242

    
1243
    drupal_theme_initialize();
1244

    
1245
    $start = microtime(TRUE);
1246
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1247
      $this->start_query_capture();
1248
    }
1249

    
1250
    $exposed_form = $this->display_handler->get_plugin('exposed_form');
1251
    $exposed_form->pre_render($this->result);
1252

    
1253
    // Check for already-cached output.
1254
    if (!empty($this->live_preview)) {
1255
      $cache = FALSE;
1256
    }
1257
    else {
1258
      $cache = $this->display_handler->get_plugin('cache');
1259
    }
1260
    if ($cache && $cache->cache_get('output')) {
1261
    }
1262
    else {
1263
      if ($cache) {
1264
        $cache->cache_start();
1265
      }
1266

    
1267
      // Run pre_render for the pager as it might change the result.
1268
      if (!empty($this->query->pager)) {
1269
        $this->query->pager->pre_render($this->result);
1270
      }
1271

    
1272
      // Initialize the style plugin.
1273
      $this->init_style();
1274

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

    
1285
      $this->style_plugin->pre_render($this->result);
1286

    
1287
      // Let modules modify the view just prior to rendering it.
1288
      foreach (module_implements('views_pre_render') as $module) {
1289
        $function = $module . '_views_pre_render';
1290
        $function($this);
1291
      }
1292

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

    
1305
      $this->display_handler->output = $this->display_handler->render();
1306
      if ($cache) {
1307
        $cache->cache_set('output');
1308
      }
1309
    }
1310
    $this->render_time = microtime(TRUE) - $start;
1311

    
1312
    $exposed_form->post_render($this->display_handler->output);
1313

    
1314
    if ($cache) {
1315
      $cache->post_render($this->display_handler->output);
1316
    }
1317

    
1318
    // Let modules modify the view output after it is rendered.
1319
    foreach (module_implements('views_post_render') as $module) {
1320
      $function = $module . '_views_post_render';
1321
      $function($this, $this->display_handler->output, $cache);
1322
    }
1323

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

    
1336
    if (!empty($this->live_preview) && variable_get('views_show_additional_queries', FALSE)) {
1337
      $this->end_query_capture();
1338
    }
1339

    
1340
    return $this->display_handler->output;
1341
  }
1342

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

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

    
1382
    $this->pre_execute($args);
1383

    
1384
    // Execute the view.
1385
    $output = $this->display_handler->execute();
1386

    
1387
    $this->post_execute();
1388
    return $output;
1389
  }
1390

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

    
1405
    $this->preview = TRUE;
1406
    $this->pre_execute($args);
1407
    // Preview the view.
1408
    $output = $this->display_handler->preview();
1409

    
1410
    $this->post_execute();
1411
    return $output;
1412
  }
1413

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

    
1423
    // Prepare the view with the information we have, but only if we were
1424
    // passed arguments, as they may have been set previously.
1425
    if ($args) {
1426
      $this->set_arguments($args);
1427
    }
1428

    
1429
    // Trigger hook_views_pre_view(). Allow other modules to modify the view
1430
    // just prior to executing the preview.
1431
    foreach (module_implements('views_pre_view') as $module) {
1432
      $function = $module . '_views_pre_view';
1433
      $function($this, $display_id, $this->args);
1434
    }
1435

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

    
1439
    // Allow the display handler to set up for execution.
1440
    $this->display_handler->pre_execute();
1441
  }
1442

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

    
1453
    views_set_current_view(isset($old_view) ? $old_view : FALSE);
1454
  }
1455

    
1456
  /**
1457
   * Run attachment displays for the view.
1458
   */
1459
  public function attach_displays() {
1460
    if (!empty($this->is_attachment)) {
1461
      return;
1462
    }
1463

    
1464
    if (!$this->display_handler->accept_attachments()) {
1465
      return;
1466
    }
1467

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

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

    
1493
    // Execute the view.
1494
    if (isset($this->display_handler)) {
1495
      return $this->display_handler->execute_hook_menu($callbacks);
1496
    }
1497
  }
1498

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

    
1510
    // Execute the view.
1511
    if (isset($this->display_handler)) {
1512
      return $this->display_handler->execute_hook_block_list();
1513
    }
1514
  }
1515

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

    
1527
    if (!isset($this->current_display)) {
1528
      $this->init_display();
1529
    }
1530

    
1531
    if (!$account) {
1532
      $account = $GLOBALS['user'];
1533
    }
1534

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

    
1545
    return FALSE;
1546
  }
1547

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

    
1560
    // During building, we might find a title override. If so, use it.
1561
    if (!empty($this->build_info['title'])) {
1562
      $title = $this->build_info['title'];
1563
    }
1564
    else {
1565
      $title = $this->display_handler->get_option('title');
1566
    }
1567

    
1568
    // Allow substitutions from the first row.
1569
    if ($this->init_style()) {
1570
      $title = $this->style_plugin->tokenize_value($title, 0);
1571
    }
1572
    return $title;
1573
  }
1574

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

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

    
1601
  /**
1602
   * Force the view to build a title.
1603
   */
1604
  public function build_title() {
1605
    $this->init_display();
1606

    
1607
    if (empty($this->built)) {
1608
      $this->init_query();
1609
    }
1610

    
1611
    $this->init_handlers();
1612

    
1613
    $this->_build_arguments();
1614
  }
1615

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

    
1626
    if (!isset($path)) {
1627
      $path = $this->get_path();
1628
    }
1629
    if (!isset($args)) {
1630
      $args = $this->args;
1631

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

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

    
1666
        }
1667
        else {
1668
          $pieces[] = array_shift($args);
1669
        }
1670

    
1671
        if ($id) {
1672
          $id = next($argument_keys);
1673
        }
1674
      }
1675
    }
1676

    
1677
    if (!empty($args)) {
1678
      $pieces = array_merge($pieces, $args);
1679
    }
1680
    return implode('/', $pieces);
1681
  }
1682

    
1683
  /**
1684
   * Get the base path used for this view.
1685
   */
1686
  public function get_path() {
1687
    if (!empty($this->override_path)) {
1688
      return $this->override_path;
1689
    }
1690

    
1691
    if (empty($this->display_handler)) {
1692
      if (!$this->set_display('default')) {
1693
        return FALSE;
1694
      }
1695
    }
1696
    return $this->display_handler->get_path();
1697
  }
1698

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

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

    
1723
      if ($set) {
1724
        if ($base) {
1725
          $breadcrumb = array_merge(drupal_get_breadcrumb(), $breadcrumb);
1726
        }
1727
        drupal_set_breadcrumb($breadcrumb);
1728
      }
1729
    }
1730
    return $breadcrumb;
1731
  }
1732

    
1733
  /**
1734
   * Is this view cacheable?.
1735
   */
1736
  public function is_cacheable() {
1737
    return $this->is_cacheable;
1738
  }
1739

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

    
1755
    // Record the last query key used; anything already run isn't a query that
1756
    // we are interested in.
1757
    $this->last_query_key = NULL;
1758

    
1759
    if (!empty($queries)) {
1760
      $keys = array_keys($queries);
1761
      $this->last_query_key = array_pop($keys);
1762
    }
1763
  }
1764

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

    
1776
    // Make a copy of the array so we can manipulate it with array_splice.
1777
    $temp = $queries;
1778

    
1779
    // Scroll through the queries until we get to our last query key.
1780
    // Unset anything in our temp array.
1781
    if (isset($this->last_query_key)) {
1782
      foreach ($queries as $id => $query) {
1783
        if ($id == $this->last_query_key) {
1784
          break;
1785
        }
1786

    
1787
        unset($temp[$id]);
1788
      }
1789
    }
1790

    
1791
    $this->additional_queries = $temp;
1792
  }
1793

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

    
1805
    // Load all the views.
1806
    foreach ($result as $data) {
1807
      $view = new view();
1808
      $view->load_row($data);
1809
      $view->loaded = TRUE;
1810
      $view->type = t('Normal');
1811
      $views[$view->name] = $view;
1812
      $names[$view->vid] = $view->name;
1813
    }
1814

    
1815
    // Stop if we didn't get any views.
1816
    if (!$views) {
1817
      return array();
1818
    }
1819

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

    
1826
      foreach ($result as $data) {
1827
        $object = new $object_name(FALSE);
1828
        $object->load_row($data);
1829

    
1830
        // Because it can get complicated with this much indirection, make a
1831
        // shortcut reference.
1832
        $location = &$views[$names[$object->vid]]->$key;
1833

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

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

    
1864
    // Let modules modify the view just prior to saving it.
1865
    module_invoke_all('views_view_presave', $this);
1866

    
1867
    $transaction = db_transaction();
1868

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

    
1880
      $this->save_row(!empty($this->vid) ? 'vid' : FALSE);
1881

    
1882
      // Save all of our subtables.
1883
      foreach ($this->db_objects() as $key) {
1884
        $this->_save_rows($key);
1885
      }
1886
    }
1887
    catch (Exception $e) {
1888
      $transaction->rollback();
1889
      watchdog_exception('views', $e);
1890
      throw $e;
1891
    }
1892

    
1893
    $this->save_locale_strings();
1894

    
1895
    // Clear the relevant caches.
1896
    cache_clear_all('views_block_items:', 'cache_views', TRUE);
1897
    views_invalidate_cache('ctools_export:views_view:' . $this->name);
1898

    
1899
    // Notify modules that this view has been saved.
1900
    module_invoke_all('views_view_save', $this);
1901
  }
1902

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

    
1917
  /**
1918
   * Delete the view from the database.
1919
   */
1920
  public function delete($clear = TRUE) {
1921
    if (empty($this->vid)) {
1922
      return;
1923
    }
1924

    
1925
    db_delete('views_view')
1926
      ->condition('vid', $this->vid)
1927
      ->execute();
1928
    // Delete from all of our subtables as well.
1929
    foreach ($this->db_objects() as $key) {
1930
      db_delete('views_' . $key)
1931
        ->condition('vid', $this->vid)
1932
        ->execute();
1933
    }
1934

    
1935
    cache_clear_all('views_query:' . $this->name, 'cache_views');
1936

    
1937
    if ($clear) {
1938
      // Clear caches.
1939
      cache_clear_all('views_block_items:', 'cache_views', TRUE);
1940
      views_invalidate_cache('ctools_export:views_view:' . $this->name);
1941
    }
1942

    
1943
    // Notify modules that this view has been deleted.
1944
    module_invoke_all('views_view_delete', $this);
1945
  }
1946

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

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

    
1969
      $output .= $display->handler->export_options($indent, '$handler->options');
1970
    }
1971

    
1972
    // Give the localization system a chance to export translatables to code.
1973
    if ($this->init_localization()) {
1974
      $this->export_locale_strings('export');
1975
      $translatables = $this->localization_plugin->export_render($indent);
1976
      if (!empty($translatables)) {
1977
        $output .= $translatables;
1978
      }
1979
    }
1980

    
1981
    return $output;
1982
  }
1983

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

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

    
2011
    $keys = array('current_display', 'display_handler', 'build_info', 'built', 'executed', 'attachment_before', 'attachment_after', 'field', 'argument', 'filter', 'sort', 'relationship', 'header', 'footer', 'empty', 'query', 'inited', 'style_plugin', 'plugin_name', 'exposed_data', 'exposed_input', 'exposed_widgets', 'many_to_one_tables', 'feed_icon');
2012
    foreach ($keys as $key) {
2013
      if (isset($clone->{$key})) {
2014
        unset($clone->{$key});
2015
      }
2016
    }
2017
    $clone->built = $clone->executed = FALSE;
2018
    $clone->build_info = array();
2019
    $clone->attachment_before = '';
2020
    $clone->attachment_after = '';
2021
    $clone->result = array();
2022

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

    
2034
    return $clone;
2035
  }
2036

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

    
2048
    foreach (views_object_types() as $type => $info) {
2049
      if (isset($this->$type)) {
2050
        $handlers = &$this->$type;
2051
        foreach ($handlers as $id => $item) {
2052
          $handlers[$id]->destroy();
2053
        }
2054
        unset($handlers);
2055
      }
2056
    }
2057

    
2058
    if (isset($this->style_plugin)) {
2059
      $this->style_plugin->destroy();
2060
      unset($this->style_plugin);
2061
    }
2062

    
2063
    // Clear these to make sure the view can be processed/used again.
2064
    if (isset($this->display_handler)) {
2065
      unset($this->display_handler);
2066
    }
2067

    
2068
    if (isset($this->current_display)) {
2069
      unset($this->current_display);
2070
    }
2071

    
2072
    if (isset($this->query)) {
2073
      unset($this->query);
2074
    }
2075

    
2076
    $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');
2077
    foreach ($keys as $key) {
2078
      if (isset($this->$key)) {
2079
        unset($this->$key);
2080
      }
2081
    }
2082

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

    
2092
    $this->built = $this->executed = FALSE;
2093
    $this->build_info = array();
2094
    $this->attachment_before = '';
2095
    $this->attachment_after = '';
2096
  }
2097

    
2098
  /**
2099
   * Make sure the view is completely valid.
2100
   *
2101
   * @return bool
2102
   *   TRUE if the view is valid; an array of error strings if it is not.
2103
   */
2104
  public function validate() {
2105
    $this->init_display();
2106

    
2107
    $errors = array();
2108
    $this->display_errors = NULL;
2109

    
2110
    $current_display = $this->current_display;
2111
    foreach ($this->display as $id => $display) {
2112
      if ($display->handler) {
2113
        if (!empty($display->deleted)) {
2114
          continue;
2115
        }
2116

    
2117
        $result = $this->display[$id]->handler->validate();
2118
        if (!empty($result) && is_array($result)) {
2119
          $errors = array_merge($errors, $result);
2120
          // Mark this display as having validation errors.
2121
          $this->display_errors[$id] = TRUE;
2122
        }
2123
      }
2124
    }
2125

    
2126
    $this->set_display($current_display);
2127
    return $errors ? $errors : TRUE;
2128
  }
2129

    
2130
  /**
2131
   * Find and initialize the localization plugin.
2132
   */
2133
  public function init_localization() {
2134
    // If the translate attribute isn't set, init the localization plugin.
2135
    if (!isset($this->localization_plugin->translate)) {
2136
      $this->localization_plugin = views_get_plugin('localization', views_get_localization_plugin());
2137

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

    
2145
      // Init the plugin.
2146
      $this->localization_plugin->init($this);
2147
    }
2148

    
2149
    // Return the value of the translate property. This is set to FALSE if
2150
    // localization is off.
2151
    return $this->localization_plugin->translate;
2152
  }
2153

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

    
2167
  /**
2168
   * Send strings for localization.
2169
   */
2170
  public function save_locale_strings() {
2171
    $this->process_locale_strings('save');
2172
  }
2173

    
2174
  /**
2175
   * Delete localized strings.
2176
   */
2177
  public function delete_locale_strings() {
2178
    $this->process_locale_strings('delete');
2179
  }
2180

    
2181
  /**
2182
   * Export localized strings.
2183
   */
2184
  public function export_locale_strings() {
2185
    $this->process_locale_strings('export');
2186
  }
2187

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

    
2200
}
2201

    
2202
/**
2203
 * Base class for views' database objects.
2204
 */
2205
class views_db_object {
2206

    
2207
  public $db_table;
2208

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

    
2222
    if (!$init) {
2223
      return;
2224
    }
2225

    
2226
    $schema = drupal_get_schema($this->db_table);
2227

    
2228
    if (!$schema) {
2229
      return;
2230
    }
2231

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

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

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

    
2284
    if ($serials && !$update) {
2285
      // Get last insert ids and fill them in. Well, one ID.
2286
      foreach ($serials as $field) {
2287
        $this->$field = $return;
2288
      }
2289
    }
2290
  }
2291

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

    
2305
    // Go through our schema and build correlations.
2306
    foreach ($schema['fields'] as $field => $info) {
2307
      $this->$field = empty($info['serialize']) ? $data->$field : unserialize($data->$field);
2308
    }
2309
  }
2310

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

    
2324
    if (!$identifier) {
2325
      $identifier = $this->db_table;
2326
    }
2327
    $schema = drupal_get_schema($this->db_table);
2328

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

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

    
2358
      $output .= $indent . '$' . $identifier . '->' . $field . ' = ' . ctools_var_export($value, $indent) . ";\n";
2359
    }
2360
    return $output;
2361
  }
2362

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

    
2382
    $plugin = views_fetch_plugin_data('display', $type);
2383
    if (empty($plugin)) {
2384
      $plugin['title'] = t('Broken');
2385
    }
2386

    
2387
    if (empty($id)) {
2388
      $id = $this->generate_display_id($type);
2389
      if ($id !== 'default') {
2390
        preg_match("/[0-9]+/", $id, $count);
2391
        $count = $count[0];
2392
      }
2393
      else {
2394
        $count = '';
2395
      }
2396

    
2397
      if (empty($title)) {
2398
        if ($count > 1) {
2399
          $title = $plugin['title'] . ' ' . $count;
2400
        }
2401
        else {
2402
          $title = $plugin['title'];
2403
        }
2404
      }
2405
    }
2406

    
2407
    // Create the new display object.
2408
    $display = new views_display();
2409
    $display->options($type, $id, $title);
2410

    
2411
    // Add the new display object to the view.
2412
    $this->display[$id] = $display;
2413
    return $id;
2414
  }
2415

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

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

    
2438
    return $id;
2439
  }
2440

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

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

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

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

    
2498
    return $this->display[$id]->handler;
2499
  }
2500

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

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

    
2512
    if (empty($id)) {
2513
      $id = $this->generate_item_id($field, $fields);
2514
    }
2515

    
2516
    $new_item = array(
2517
      'id' => $id,
2518
      'table' => $table,
2519
      'field' => $field,
2520
    ) + $options;
2521

    
2522
    if (!empty($types[$type]['type'])) {
2523
      $handler_type = $types[$type]['type'];
2524
    }
2525
    else {
2526
      $handler_type = $type;
2527
    }
2528

    
2529
    $handler = views_get_handler($table, $field, $handler_type);
2530

    
2531
    $fields[$id] = $new_item;
2532
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2533

    
2534
    return $id;
2535
  }
2536

    
2537
  /**
2538
   * Get an array of items for the current display.
2539
   */
2540
  public function get_items($type, $display_id = NULL) {
2541
    $this->set_display($display_id);
2542

    
2543
    if (!isset($display_id)) {
2544
      $display_id = $this->current_display;
2545
    }
2546

    
2547
    // Get info about the types so we can get the right data.
2548
    $types = views_object_types();
2549
    return $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2550
  }
2551

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

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

    
2564
    return isset($fields[$id]) ? $fields[$id] : NULL;
2565
  }
2566

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

    
2578
    // Get the existing configuration.
2579
    $fields = $this->display[$display_id]->handler->get_option($types[$type]['plural']);
2580
    if (isset($item)) {
2581
      $fields[$id] = $item;
2582
    }
2583
    else {
2584
      unset($fields[$id]);
2585
    }
2586

    
2587
    // Store.
2588
    $this->display[$display_id]->handler->set_option($types[$type]['plural'], $fields);
2589
  }
2590

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

    
2603
}
2604

    
2605
/**
2606
 * A display type in a view.
2607
 *
2608
 * This is just the database storage mechanism, and isn't terribly important
2609
 * to the behavior of the display at all.
2610
 */
2611
class views_display extends views_db_object {
2612

    
2613
  /**
2614
   * The display handler itself, which has all the methods.
2615
   *
2616
   * @var views_plugin_display
2617
   */
2618
  public $handler;
2619

    
2620
  /**
2621
   * Stores all options of the display, like fields, filters etc.
2622
   *
2623
   * @var array
2624
   */
2625
  public $display_options;
2626

    
2627
  public $db_table = 'views_display';
2628
  public function __construct($init = TRUE) {
2629
    parent::init($init);
2630
  }
2631

    
2632
  /**
2633
   * {@inheritdoc}
2634
   */
2635
  public function options($type, $id, $title) {
2636
    $this->display_plugin = $type;
2637
    $this->id = $id;
2638
    $this->display_title = $title;
2639
  }
2640

    
2641
}
2642

    
2643
/**
2644
 * Provide a list of object types used in a view, with some info about them.
2645
 */
2646
function views_object_types() {
2647
  static $retval = NULL;
2648

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

    
2718
  return $retval;
2719
}
2720

    
2721
/**
2722
 * @}
2723
 */