ViewExecutable.php 58 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2 3 4
<?php

/**
 * @file
5
 * Definition of Drupal\views\ViewExecutable.
merlinofchaos's avatar
merlinofchaos committed
6 7
 */

8 9
namespace Drupal\views;

10
use Drupal\Component\Utility\String;
11
use Drupal\Core\DependencyInjection\DependencySerializationTrait;
12
use Drupal\Core\Form\FormState;
13
use Drupal\Core\Session\AccountInterface;
14
use Drupal\views\Plugin\views\query\QueryPluginBase;
15
use Drupal\views\ViewStorageInterface;
16
use Drupal\Component\Utility\Tags;
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Response;
19

merlinofchaos's avatar
merlinofchaos committed
20
/**
21 22
 * Represents a view as a whole.
 *
merlinofchaos's avatar
merlinofchaos committed
23 24 25
 * An object to contain all of the data to generate a view, plus the member
 * functions to build the view query, execute the query and render the output.
 */
26 27
class ViewExecutable {
  use DependencySerializationTrait;
28

merlinofchaos's avatar
merlinofchaos committed
29
  /**
30
   * The config entity in which the view is stored.
merlinofchaos's avatar
merlinofchaos committed
31
   *
32
   * @var \Drupal\views\Entity\View
merlinofchaos's avatar
merlinofchaos committed
33
   */
34
  public $storage;
merlinofchaos's avatar
merlinofchaos committed
35

36 37 38
  /**
   * Whether or not the view has been built.
   *
39 40
   * @todo Group with other static properties.
   *
41 42 43 44 45 46 47
   * @var bool
   */
  public $built = FALSE;

  /**
   * Whether the view has been executed/query has been run.
   *
48 49
   * @todo Group with other static properties.
   *
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
   * @var bool
   */
  public $executed = FALSE;

  /**
   * Any arguments that have been passed into the view.
   *
   * @var array
   */
  public $args = array();

  /**
   * An array of build info.
   *
   * @var array
   */
  public $build_info = array();

  /**
   * Whether this view uses AJAX.
   *
   * @var bool
   */
73
  protected $ajaxEnabled = FALSE;
merlinofchaos's avatar
merlinofchaos committed
74

75 76 77 78 79
  /**
   * Where the results of a query will go.
   *
   * The array must use a numeric index starting at 0.
   *
80
   * @var \Drupal\views\ResultRow[]
81
   */
82
  public $result = array();
merlinofchaos's avatar
merlinofchaos committed
83 84 85

  // May be used to override the current pager info.

86 87 88 89 90
  /**
   * The current page. If the view uses pagination.
   *
   * @var int
   */
91
  protected $current_page = NULL;
92 93 94 95 96 97

  /**
   * The number of items per page.
   *
   * @var int
   */
98
  protected $items_per_page = NULL;
99 100 101 102 103 104

  /**
   * The pager offset.
   *
   * @var int
   */
105
  protected $offset = NULL;
106 107 108 109

  /**
   * The total number of rows returned from the query.
   *
110
   * @var int
111 112 113 114
   */
  public $total_rows = NULL;

  /**
115
   * Attachments to place before the view.
116
   *
117
   * @var array()
118
   */
119
  public $attachment_before = array();
120 121

  /**
122
   * Attachments to place after the view.
123
   *
124
   * @var array
125
   */
126
  public $attachment_after = array();
merlinofchaos's avatar
merlinofchaos committed
127

128 129 130 131 132 133 134
  /**
   * Feed icons attached to the view.
   *
   * @var array
   */
  public $feedIcons = array();

merlinofchaos's avatar
merlinofchaos committed
135 136
  // Exposed widget input

137
  /**
138
   * All the form data from $form_state->getValues().
139 140 141 142
   *
   * @var array
   */
  public $exposed_data = array();
merlinofchaos's avatar
merlinofchaos committed
143

144 145 146 147 148
  /**
   * An array of input values from exposed forms.
   *
   * @var array
   */
149
  protected $exposed_input = array();
merlinofchaos's avatar
merlinofchaos committed
150

151
  /**
152
   * Exposed widget input directly from the $form_state->getValues().
153 154 155 156 157 158 159 160
   *
   * @var array
   */
  public $exposed_raw_input = array();

  /**
   * Used to store views that were previously running if we recurse.
   *
161
   * @var \Drupal\views\ViewExecutable[]
162 163 164 165 166 167
   */
  public $old_view = array();

  /**
   * To avoid recursion in views embedded into areas.
   *
168
   * @var \Drupal\views\ViewExecutable[]
169 170 171 172 173 174 175 176 177
   */
  public $parent_views = array();

  /**
   * Whether this view is an attachment to another view.
   *
   * @var bool
   */
  public $is_attachment = NULL;
merlinofchaos's avatar
merlinofchaos committed
178 179 180 181 182 183

  /**
   * Identifier of the current display.
   *
   * @var string
   */
184
  public $current_display;
merlinofchaos's avatar
merlinofchaos committed
185 186

  /**
187
   * Where the $query object will reside.
merlinofchaos's avatar
merlinofchaos committed
188
   *
189
   * @var \Drupal\views\Plugin\views\query\QueryPluginBase
merlinofchaos's avatar
merlinofchaos committed
190
   */
191
  public $query = NULL;
merlinofchaos's avatar
merlinofchaos committed
192

193 194 195
  /**
   * The used pager plugin used by the current executed view.
   *
196
   * @var \Drupal\views\Plugin\views\pager\PagerPluginBase
197 198 199 200
   */
  public $pager = NULL;

  /**
merlinofchaos's avatar
merlinofchaos committed
201 202
   * The current used display plugin.
   *
203
   * @var \Drupal\views\Plugin\views\display\DisplayPluginBase
merlinofchaos's avatar
merlinofchaos committed
204
   */
205
  public $display_handler;
merlinofchaos's avatar
merlinofchaos committed
206

207 208 209 210 211 212
  /**
   * The list of used displays of the view.
   *
   * An array containing Drupal\views\Plugin\views\display\DisplayPluginBase
   * objects.
   *
213
   * @var \Drupal\views\DisplayPluginCollection
214 215 216
   */
  public $displayHandlers;

merlinofchaos's avatar
merlinofchaos committed
217 218 219
  /**
   * The current used style plugin.
   *
220
   * @var \Drupal\views\Plugin\views\style\StylePluginBase
merlinofchaos's avatar
merlinofchaos committed
221
   */
222
  public $style_plugin;
merlinofchaos's avatar
merlinofchaos committed
223

224 225 226 227 228 229 230
  /**
   * The current used row plugin, if the style plugin supports row plugins.
   *
   * @var \Drupal\views\Plugin\views\row\RowPluginBase
   */
  public $rowPlugin;

merlinofchaos's avatar
merlinofchaos committed
231 232 233 234 235
  /**
   * Stores the current active row while rendering.
   *
   * @var int
   */
236
  public $row_index;
merlinofchaos's avatar
merlinofchaos committed
237

238
  /**
merlinofchaos's avatar
merlinofchaos committed
239 240 241 242
   * Allow to override the url of the current view.
   *
   * @var string
   */
243
  public $override_url = NULL;
merlinofchaos's avatar
merlinofchaos committed
244 245 246 247 248 249

  /**
   * Allow to override the path used for generated urls.
   *
   * @var string
   */
250
  public $override_path = NULL;
merlinofchaos's avatar
merlinofchaos committed
251 252 253

  /**
   * Allow to override the used database which is used for this query.
254 255
   *
   * @var bool
merlinofchaos's avatar
merlinofchaos committed
256
   */
257
  public $base_database = NULL;
merlinofchaos's avatar
merlinofchaos committed
258

259
  // Handlers which are active on this view.
merlinofchaos's avatar
merlinofchaos committed
260 261 262

  /**
   * Stores the field handlers which are initialized on this view.
263
   *
264
   * @var \Drupal\views\Plugin\views\field\FieldPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
265
   */
266
  public $field;
merlinofchaos's avatar
merlinofchaos committed
267 268 269

  /**
   * Stores the argument handlers which are initialized on this view.
270
   *
271
   * @var \Drupal\views\Plugin\views\argument\ArgumentPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
272
   */
273
  public $argument;
merlinofchaos's avatar
merlinofchaos committed
274 275 276

  /**
   * Stores the sort handlers which are initialized on this view.
277
   *
278
   * @var \Drupal\views\Plugin\views\sort\SortPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
279
   */
280
  public $sort;
merlinofchaos's avatar
merlinofchaos committed
281 282 283

  /**
   * Stores the filter handlers which are initialized on this view.
284
   *
285
   * @var \Drupal\views\Plugin\views\filter\FilterPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
286
   */
287
  public $filter;
merlinofchaos's avatar
merlinofchaos committed
288 289 290

  /**
   * Stores the relationship handlers which are initialized on this view.
291
   *
292
   * @var \Drupal\views\Plugin\views\relationship\RelationshipPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
293
   */
294
  public $relationship;
merlinofchaos's avatar
merlinofchaos committed
295 296 297

  /**
   * Stores the area handlers for the header which are initialized on this view.
298
   *
299
   * @var \Drupal\views\Plugin\views\area\AreaPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
300
   */
301
  public $header;
merlinofchaos's avatar
merlinofchaos committed
302 303 304

  /**
   * Stores the area handlers for the footer which are initialized on this view.
305
   *
306
   * @var \Drupal\views\Plugin\views\area\AreaPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
307
   */
308
  public $footer;
merlinofchaos's avatar
merlinofchaos committed
309 310 311

  /**
   * Stores the area handlers for the empty text which are initialized on this view.
312 313 314
   *
   * An array containing Drupal\views\Plugin\views\area\AreaPluginBase objects.
   *
315
   * @var \Drupal\views\Plugin\views\area\AreaPluginBase[]
merlinofchaos's avatar
merlinofchaos committed
316
   */
317
  public $empty;
merlinofchaos's avatar
merlinofchaos committed
318

319 320 321
  /**
   * Stores the current response object.
   *
322
   * @var \Symfony\Component\HttpFoundation\Response
323 324 325
   */
  protected $response = NULL;

326 327 328 329 330 331 332
  /**
   * Stores the current request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
  /**
   * Does this view already have loaded it's handlers.
   *
   * @todo Group with other static properties.
   *
   * @var bool
   */
  public $inited;

  /**
   * The rendered output of the exposed form.
   *
   * @var string
   */
  public $exposed_widgets;

  /**
   * If this view has been previewed.
   *
   * @var bool
   */
  public $preview;

  /**
   * Force the query to calculate the total number of results.
   *
   * @todo Move to the query.
   *
   * @var bool
   */
  public $get_total_rows;

  /**
   * Indicates if the sorts have been built.
   *
   * @todo Group with other static properties.
   *
   * @var bool
   */
  public $build_sort;

  /**
   * Stores the many-to-one tables for performance.
   *
   * @var array
   */
  public $many_to_one_tables;

  /**
   * A unique identifier which allows to update multiple views output via js.
   *
   * @var string
   */
  public $dom_id;

388 389 390
  /**
   * A render array container to store render related information.
   *
391 392 393
   * For example you can alter the array and attach some asset library or JS
   * settings via the #attached key. This is the required way to add custom
   * CSS or JS.
394 395 396 397 398
   *
   * @var array
   *
   * @see drupal_process_attached
   */
399 400 401 402 403 404
  public $element = [
    '#attached' => [
      'library' => [],
      'drupalSettings' => [],
    ]
  ];
405

406 407 408 409 410 411 412
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $user;

413 414 415 416 417 418 419
  /**
   * Should the admin links be shown on the rendered view.
   *
   * @var bool
   */
  protected $showAdminLinks;

420 421 422
  /**
   * Constructs a new ViewExecutable object.
   *
423
   * @param \Drupal\views\ViewStorageInterface $storage
424
   *   The view config entity the actual information is stored on.
425 426
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
427
   */
428
  public function __construct(ViewStorageInterface $storage, AccountInterface $user) {
429 430
    // Reference the storage and the executable to each other.
    $this->storage = $storage;
431
    $this->storage->set('executable', $this);
432
    $this->user = $user;
433 434

    // Add the default css for a view.
435
    $this->element['#attached']['library'][] = 'views/views.module';
436 437 438
  }

  /**
439
   * @todo.
440
   */
441 442
  public function save() {
    $this->storage->save();
merlinofchaos's avatar
merlinofchaos committed
443 444 445 446 447 448
  }

  /**
   * Set the arguments that come to this view. Usually from the URL
   * but possibly from elsewhere.
   */
449
  public function setArguments($args) {
450
    $this->args = $args;
merlinofchaos's avatar
merlinofchaos committed
451 452 453 454 455
  }

  /**
   * Change/Set the current page for the pager.
   */
456
  public function setCurrentPage($page) {
merlinofchaos's avatar
merlinofchaos committed
457
    $this->current_page = $page;
458 459

    // If the pager is already initialized, pass it through to the pager.
460
    if (!empty($this->pager)) {
461
      return $this->pager->setCurrentPage($page);
462
    }
merlinofchaos's avatar
merlinofchaos committed
463 464 465 466 467
  }

  /**
   * Get the current page from the pager.
   */
468
  public function getCurrentPage() {
469
    // If the pager is already initialized, pass it through to the pager.
470
    if (!empty($this->pager)) {
471
      return $this->pager->getCurrentPage();
merlinofchaos's avatar
merlinofchaos committed
472
    }
473 474 475 476

    if (isset($this->current_page)) {
      return $this->current_page;
    }
merlinofchaos's avatar
merlinofchaos committed
477 478 479 480 481
  }

  /**
   * Get the items per page from the pager.
   */
482
  public function getItemsPerPage() {
483
    // If the pager is already initialized, pass it through to the pager.
484
    if (!empty($this->pager)) {
485
      return $this->pager->getItemsPerPage();
merlinofchaos's avatar
merlinofchaos committed
486
    }
487 488 489 490

    if (isset($this->items_per_page)) {
      return $this->items_per_page;
    }
merlinofchaos's avatar
merlinofchaos committed
491 492 493 494 495
  }

  /**
   * Set the items per page on the pager.
   */
496
  public function setItemsPerPage($items_per_page) {
merlinofchaos's avatar
merlinofchaos committed
497 498 499
    $this->items_per_page = $items_per_page;

    // If the pager is already initialized, pass it through to the pager.
500
    if (!empty($this->pager)) {
501
      $this->pager->setItemsPerPage($items_per_page);
merlinofchaos's avatar
merlinofchaos committed
502 503 504 505 506 507
    }
  }

  /**
   * Get the pager offset from the pager.
   */
508
  public function getOffset() {
509
    // If the pager is already initialized, pass it through to the pager.
510
    if (!empty($this->pager)) {
511
      return $this->pager->getOffset();
merlinofchaos's avatar
merlinofchaos committed
512
    }
513 514 515 516

    if (isset($this->offset)) {
      return $this->offset;
    }
merlinofchaos's avatar
merlinofchaos committed
517 518 519 520 521
  }

  /**
   * Set the offset on the pager.
   */
522
  public function setOffset($offset) {
merlinofchaos's avatar
merlinofchaos committed
523 524 525
    $this->offset = $offset;

    // If the pager is already initialized, pass it through to the pager.
526
    if (!empty($this->pager)) {
527
      $this->pager->setOffset($offset);
merlinofchaos's avatar
merlinofchaos committed
528 529 530 531 532 533
    }
  }

  /**
   * Determine if the pager actually uses a pager.
   */
534
  public function usePager() {
535
    if (!empty($this->pager)) {
536
      return $this->pager->usePager();
merlinofchaos's avatar
merlinofchaos committed
537 538 539 540
    }
  }

  /**
541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
   * Sets whether or not AJAX should be used.
   *
   * If AJAX is used, paging, tablesorting and exposed filters will be fetched
   * via an AJAX call rather than a page refresh.
   *
   * @param bool $use_ajax
   *   TRUE if AJAX should be used, FALSE otherwise.
   */
  public function setAjaxEnabled($ajax_enabled) {
    $this->ajaxEnabled = (bool) $ajax_enabled;
  }

  /**
   * Whether or not AJAX should be used.
   *
   * @see \Drupal\views\ViewExecutable::setAjaxEnabled().
   *
   * @return bool
merlinofchaos's avatar
merlinofchaos committed
559
   */
560 561
  public function ajaxEnabled() {
    return $this->ajaxEnabled;
merlinofchaos's avatar
merlinofchaos committed
562 563 564 565
  }

  /**
   * Set the exposed filters input to an array. If unset they will be taken
566
   * from \Drupal::request()->query when the time comes.
merlinofchaos's avatar
merlinofchaos committed
567
   */
568
  public function setExposedInput($filters) {
merlinofchaos's avatar
merlinofchaos committed
569 570 571 572 573 574
    $this->exposed_input = $filters;
  }

  /**
   * Figure out what the exposed input for this view is.
   */
575
  public function getExposedInput() {
576 577
    // Fill our input either from \Drupal::request()->query or from something
    // previously set on the view.
merlinofchaos's avatar
merlinofchaos committed
578
    if (empty($this->exposed_input)) {
579 580 581
      // Ensure that we can call the method at any point in time.
      $this->initDisplay();

582
      $this->exposed_input = \Drupal::request()->query->all();
merlinofchaos's avatar
merlinofchaos committed
583 584 585 586 587 588 589 590 591 592 593 594 595
      // unset items that are definitely not our input:
      foreach (array('page', 'q') as $key) {
        if (isset($this->exposed_input[$key])) {
          unset($this->exposed_input[$key]);
        }
      }

      // If we have no input at all, check for remembered input via session.

      // If filters are not overridden, store the 'remember' settings on the
      // default display. If they are, store them on this display. This way,
      // multiple displays in the same view can share the same filters and
      // remember settings.
596
      $display_id = ($this->display_handler->isDefaulted('filters')) ? 'default' : $this->current_display;
merlinofchaos's avatar
merlinofchaos committed
597

598 599
      if (empty($this->exposed_input) && !empty($_SESSION['views'][$this->storage->id()][$display_id])) {
        $this->exposed_input = $_SESSION['views'][$this->storage->id()][$display_id];
merlinofchaos's avatar
merlinofchaos committed
600 601 602 603 604 605 606 607 608
      }
    }

    return $this->exposed_input;
  }

  /**
   * Set the display for this view and initialize the display handler.
   */
609
  public function initDisplay() {
merlinofchaos's avatar
merlinofchaos committed
610 611 612 613
    if (isset($this->current_display)) {
      return TRUE;
    }

614
    // Initialize the display cache array.
615
    $this->displayHandlers = new DisplayPluginCollection($this, Views::pluginManager('display'));
merlinofchaos's avatar
merlinofchaos committed
616 617

    $this->current_display = 'default';
618
    $this->display_handler = $this->displayHandlers->get('default');
merlinofchaos's avatar
merlinofchaos committed
619 620 621 622 623 624 625

    return TRUE;
  }

  /**
   * Get the first display that is accessible to the user.
   *
626
   * @param array|string $displays
merlinofchaos's avatar
merlinofchaos committed
627
   *   Either a single display id or an array of display ids.
628 629 630
   *
   * @return string
   *   The first accessible display id, at least default.
merlinofchaos's avatar
merlinofchaos committed
631
   */
632
  public function chooseDisplay($displays) {
merlinofchaos's avatar
merlinofchaos committed
633 634 635 636
    if (!is_array($displays)) {
      return $displays;
    }

637
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
638 639

    foreach ($displays as $display_id) {
640
      if ($this->displayHandlers->get($display_id)->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
641 642 643 644 645 646 647
        return $display_id;
      }
    }

    return 'default';
  }

648 649 650 651 652 653 654 655 656 657 658 659 660
  /**
   * Gets the current display plugin.
   *
   * @return \Drupal\views\Plugin\views\display\DisplayPluginBase
   */
  public function getDisplay() {
    if (!isset($this->display_handler)) {
      $this->initDisplay();
    }

    return $this->display_handler;
  }

merlinofchaos's avatar
merlinofchaos committed
661
  /**
662
   * Sets the current display.
merlinofchaos's avatar
merlinofchaos committed
663
   *
664 665 666 667 668
   * @param string $display_id
   *   The ID of the display to mark as current.
   *
   * @return bool
   *   TRUE if the display was correctly set, FALSE otherwise.
merlinofchaos's avatar
merlinofchaos committed
669
   */
670
  public function setDisplay($display_id = NULL) {
671 672 673 674
    // If we have not already initialized the display, do so.
    if (!isset($this->current_display)) {
      // This will set the default display and instantiate the default display
      // plugin.
675
      $this->initDisplay();
676
    }
merlinofchaos's avatar
merlinofchaos committed
677

678 679 680 681
    // If no display ID is passed, we either have initialized the default or
    // already have a display set.
    if (!isset($display_id)) {
      return TRUE;
merlinofchaos's avatar
merlinofchaos committed
682 683
    }

684
    $display_id = $this->chooseDisplay($display_id);
merlinofchaos's avatar
merlinofchaos committed
685 686

    // Ensure the requested display exists.
687
    if (!$this->displayHandlers->has($display_id)) {
688 689
      debug(format_string('setDisplay() called with invalid display ID "@display".', array('@display' => $display_id)));
      return FALSE;
merlinofchaos's avatar
merlinofchaos committed
690 691
    }

692 693 694 695 696 697 698 699 700 701 702 703
    // Reset if the display has changed. It could be called multiple times for
    // the same display, especially in the UI.
    if ($this->current_display != $display_id) {
      // Set the current display.
      $this->current_display = $display_id;

      // Reset the style and row plugins.
      $this->style_plugin = NULL;
      $this->plugin_name = NULL;
      $this->rowPlugin = NULL;
    }

704 705 706 707 708
    if ($display = $this->displayHandlers->get($display_id)) {
      // Set a shortcut.
      $this->display_handler = $display;
      return TRUE;
    }
merlinofchaos's avatar
merlinofchaos committed
709

710
    return FALSE;
merlinofchaos's avatar
merlinofchaos committed
711 712
  }

713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732
  /**
   * Creates a new display and a display handler instance for it.
   *
   * @param string $plugin_id
   *   (optional) The plugin type from the Views plugin annotation. Defaults to
   *   'page'.
   * @param string $title
   *   (optional) The title of the display. Defaults to NULL.
   * @param string $id
   *   (optional) The ID to use, e.g., 'default', 'page_1', 'block_2'. Defaults
   *   to NULL.
   *
   * @return \Drupal\views\Plugin\views\display\DisplayPluginBase
   *   A new display plugin instance if executable is set, the new display ID
   *   otherwise.
   */
  public function newDisplay($plugin_id = 'page', $title = NULL, $id = NULL) {
    $this->initDisplay();

    $id = $this->storage->addDisplay($plugin_id, $title, $id);
733
    $this->displayHandlers->addInstanceId($id);
734

735 736 737
    $display = $this->displayHandlers->get($id);
    $display->newDisplay();
    return $display;
738 739
  }

740 741 742 743 744 745 746 747 748 749 750 751 752
  /**
   * Gets the current style plugin.
   *
   * @return \Drupal\views\Plugin\views\style\StylePluginBase
   */
  public function getStyle() {
    if (!isset($this->style_plugin)) {
      $this->initStyle();
    }

    return $this->style_plugin;
  }

merlinofchaos's avatar
merlinofchaos committed
753 754 755 756 757 758
  /**
   * Find and initialize the style plugin.
   *
   * Note that arguments may have changed which style plugin we use, so
   * check the view object first, then ask the display handler.
   */
759
  public function initStyle() {
merlinofchaos's avatar
merlinofchaos committed
760
    if (isset($this->style_plugin)) {
761
      return TRUE;
merlinofchaos's avatar
merlinofchaos committed
762 763
    }

764
    $this->style_plugin = $this->display_handler->getPlugin('style');
merlinofchaos's avatar
merlinofchaos committed
765 766 767 768 769 770 771 772 773 774 775

    if (empty($this->style_plugin)) {
      return FALSE;
    }

    return TRUE;
  }

  /**
   * Acquire and attach all of the handlers.
   */
776
  public function initHandlers() {
777
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
778
    if (empty($this->inited)) {
779
      foreach ($this::getHandlerTypes() as $key => $info) {
780
        $this->_initHandler($key, $info);
merlinofchaos's avatar
merlinofchaos committed
781 782 783 784 785
      }
      $this->inited = TRUE;
    }
  }

786 787 788 789 790 791 792 793 794 795 796 797 798
  /**
   * Get the current pager plugin.
   *
   * @return \Drupal\views\Plugin\views\pager\PagerPluginBase
   */
  public function getPager() {
    if (!isset($this->pager)) {
      $this->initPager();
    }

    return $this->pager;
  }

merlinofchaos's avatar
merlinofchaos committed
799 800 801 802 803 804
  /**
   * Initialize the pager
   *
   * Like style initialization, pager initialization is held until late
   * to allow for overrides.
   */
805
  public function initPager() {
806
    if (!isset($this->pager)) {
807
      $this->pager = $this->display_handler->getPlugin('pager');
merlinofchaos's avatar
merlinofchaos committed
808

809
      if ($this->pager->usePager()) {
810
        $this->pager->setCurrentPage($this->current_page);
merlinofchaos's avatar
merlinofchaos committed
811 812 813 814 815
      }

      // These overrides may have been set earlier via $view->set_*
      // functions.
      if (isset($this->items_per_page)) {
816
        $this->pager->setItemsPerPage($this->items_per_page);
merlinofchaos's avatar
merlinofchaos committed
817 818 819
      }

      if (isset($this->offset)) {
820
        $this->pager->setOffset($this->offset);
merlinofchaos's avatar
merlinofchaos committed
821 822 823 824
      }
    }
  }

825 826 827
  /**
   * Render the pager, if necessary.
   */
828
  public function renderPager($exposed_input) {
829
    if (!empty($this->pager) && $this->pager->usePager()) {
830 831 832 833 834 835
      return $this->pager->render($exposed_input);
    }

    return '';
  }

merlinofchaos's avatar
merlinofchaos committed
836 837 838 839
  /**
   * Create a list of base tables eligible for this view. Used primarily
   * for the UI. Display must be already initialized.
   */
840
  public function getBaseTables() {
merlinofchaos's avatar
merlinofchaos committed
841
    $base_tables = array(
842
      $this->storage->get('base_table') => TRUE,
merlinofchaos's avatar
merlinofchaos committed
843 844 845
      '#global' => TRUE,
    );

846
    foreach ($this->display_handler->getHandlers('relationship') as $handler) {
merlinofchaos's avatar
merlinofchaos committed
847 848 849 850 851 852
      $base_tables[$handler->definition['base']] = TRUE;
    }
    return $base_tables;
  }

  /**
853
   * Run the preQuery() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
854
   */
855
  protected function _preQuery() {
856
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
857 858 859 860
      $handlers = &$this->$key;
      $position = 0;
      foreach ($handlers as $id => $handler) {
        $handlers[$id]->position = $position;
861
        $handlers[$id]->preQuery();
merlinofchaos's avatar
merlinofchaos committed
862 863 864 865 866 867
        $position++;
      }
    }
  }

  /**
868
   * Run the postExecute() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
869
   */
870
  protected function _postExecute() {
871
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
872 873
      $handlers = &$this->$key;
      foreach ($handlers as $id => $handler) {
874
        $handlers[$id]->postExecute($this->result);
merlinofchaos's avatar
merlinofchaos committed
875 876 877 878 879 880 881 882 883 884
      }
    }
  }

  /**
   * Attach all of the handlers for each type.
   *
   * @param $key
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'
   * @param $info
885
   *   The $info from getHandlerTypes for this object.
merlinofchaos's avatar
merlinofchaos committed
886
   */
887
  protected function _initHandler($key, $info) {
merlinofchaos's avatar
merlinofchaos committed
888
    // Load the requested items from the display onto the object.
889
    $this->$key = &$this->display_handler->getHandlers($key);
merlinofchaos's avatar
merlinofchaos committed
890 891 892 893 894 895

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

    // Run through and test for accessibility.
    foreach ($handlers as $id => $handler) {
896
      if (!$handler->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
897 898 899 900 901 902 903 904
        unset($handlers[$id]);
      }
    }
  }

  /**
   * Build all the arguments.
   */
905
  protected function _buildArguments() {
merlinofchaos's avatar
merlinofchaos committed
906 907 908 909 910 911 912 913 914 915 916
    // Initially, we want to build sorts and fields. This can change, though,
    // if we get a summary view.
    if (empty($this->argument)) {
      return TRUE;
    }

    // build arguments.
    $position = -1;
    $substitutions = array();
    $status = TRUE;

917 918 919
    // Get the title.
    $title = $this->display_handler->getOption('title');

merlinofchaos's avatar
merlinofchaos committed
920 921 922
    // Iterate through each argument and process.
    foreach ($this->argument as $id => $arg) {
      $position++;
923
      $argument = $this->argument[$id];
merlinofchaos's avatar
merlinofchaos committed
924 925 926 927 928

      if ($argument->broken()) {
        continue;
      }

929
      $argument->setRelationship();
merlinofchaos's avatar
merlinofchaos committed
930 931 932 933

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

934
      if (isset($arg) || $argument->hasDefaultArgument()) {
merlinofchaos's avatar
merlinofchaos committed
935
        if (!isset($arg)) {
936
          $arg = $argument->getDefaultArgument();
merlinofchaos's avatar
merlinofchaos committed
937 938 939 940 941 942 943 944 945
          // make sure default args get put back.
          if (isset($arg)) {
            $this->args[$position] = $arg;
          }
          // remember that this argument was computed, not passed on the URL.
          $argument->is_default = TRUE;
        }

        // Set the argument, which will also validate that the argument can be set.
946
        if (!$argument->setArgument($arg)) {
947
          $status = $argument->validateFail($arg);
merlinofchaos's avatar
merlinofchaos committed
948 949 950
          break;
        }

951
        if ($argument->isException()) {
952
          $arg_title = $argument->exceptionTitle();
merlinofchaos's avatar
merlinofchaos committed
953 954
        }
        else {
955
          $arg_title = $argument->getTitle();
956
          $argument->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
957 958 959 960
        }

        // Add this argument's substitution
        $substitutions['%' . ($position + 1)] = $arg_title;
961
        $substitutions['!' . ($position + 1)] = strip_tags(String::decodeEntities($arg));
merlinofchaos's avatar
merlinofchaos committed
962 963 964 965 966 967 968 969

        // Test to see if we should use this argument's title
        if (!empty($argument->options['title_enable']) && !empty($argument->options['title'])) {
          $title = $argument->options['title'];
        }
      }
      else {
        // determine default condition and handle.
970
        $status = $argument->defaultAction();
merlinofchaos's avatar
merlinofchaos committed
971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988
        break;
      }

      // Be safe with references and loops:
      unset($argument);
    }

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

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

    return $status;
  }

989 990 991 992 993 994 995 996 997 998 999 1000 1001
  /**
   * Gets the current query plugin.
   *
   * @return \Drupal\views\Plugin\views\query\QueryPluginBase
   */
  public function getQuery() {
    if (!isset($this->query)) {
      $this->initQuery();
    }

    return $this->query;
  }

merlinofchaos's avatar
merlinofchaos committed
1002 1003 1004
  /**
   * Do some common building initialization.
   */
1005
  public function initQuery() {
merlinofchaos's avatar
merlinofchaos committed
1006 1007 1008 1009 1010 1011 1012 1013 1014
    if (!empty($this->query)) {
      $class = get_class($this->query);
      if ($class && $class != 'stdClass') {
        // return if query is already initialized.
        return TRUE;
      }
    }

    // Create and initialize the query object.
1015
    $views_data = Views::viewsData()->get($this->storage->get('base_table'));
1016
    $this->storage->set('base_field', !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '');
merlinofchaos's avatar
merlinofchaos committed
1017 1018 1019 1020
    if (!empty($views_data['table']['base']['database'])) {
      $this->base_database = $views_data['table']['base']['database'];
    }

1021
    $this->query = $this->display_handler->getPlugin('query');
merlinofchaos's avatar
merlinofchaos committed
1022 1023 1024 1025 1026 1027
    return TRUE;
  }

  /**
   * Build the query for the view.
   */
1028
  public function build($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1029 1030 1031 1032 1033
    if (!empty($this->built)) {
      return;
    }

    if (empty($this->current_display) || $display_id) {
1034
      if (!$this->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
1035 1036 1037 1038 1039
        return FALSE;
      }
    }

    // Let modules modify the view just prior to building it.
1040 1041
    $module_handler = \Drupal::moduleHandler();
    $module_handler->invokeAll('views_pre_build', array($this));
merlinofchaos's avatar
merlinofchaos committed
1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053

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

    $start = microtime(TRUE);
    // If that fails, let's build!
    $this->build_info = array(
      'query' => '',
      'count_query' => '',
      'query_args' => array(),
    );

1054
    $this->initQuery();
merlinofchaos's avatar
merlinofchaos committed
1055 1056 1057 1058 1059 1060 1061

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

    // Run through our handlers and ensure they have necessary information.
1062
    $this->initHandlers();
merlinofchaos's avatar
merlinofchaos committed
1063 1064

    // Let the handlers interact with each other if they really want.
1065
    $this->_preQuery();
merlinofchaos's avatar
merlinofchaos committed
1066

1067 1068
    if ($this->display_handler->usesExposed()) {
      $exposed_form = $this->display_handler->getPlugin('exposed_form');
1069
      $this->exposed_widgets = $exposed_form->renderExposedForm();
1070
      if (FormState::hasAnyErrors() || !empty($this->build_info['abort'])) {
merlinofchaos's avatar
merlinofchaos committed
1071
        $this->built = TRUE;
1072
        // Don't execute the query, $form_state, but rendering will still be executed to display the empty text.
merlinofchaos's avatar
merlinofchaos committed
1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
        $this->executed = TRUE;
        return empty($this->build_info['fail']);
      }
    }

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

    // Set the filtering groups.
    if (!empty($this->filter)) {
1083
      $filter_groups = $this->display_handler->getOption('filter_groups');
merlinofchaos's avatar
merlinofchaos committed
1084
      if ($filter_groups) {
1085
        $this->query->setGroupOperator($filter_groups['operator']);
1086
        foreach ($filter_groups['groups'] as $id => $operator) {
1087
          $this->query->setWhereGroup($operator, $id);
merlinofchaos's avatar
merlinofchaos committed
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
        }
      }
    }

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

    $this->build_sort = TRUE;

    // Arguments can, in fact, cause this whole thing to abort.
1098
    if (!$this->_buildArguments()) {
merlinofchaos's avatar
merlinofchaos committed
1099
      $this->build_time = microtime(TRUE) - $start;
1100
      $this->attachDisplays();
merlinofchaos's avatar
merlinofchaos committed
1101 1102 1103 1104 1105 1106
      return $this->built;
    }

    // Initialize the style; arguments may have changed which style we use,
    // so waiting as long as possible is important. But we need to know
    // about the style when we go to build fields.
1107
    if (!$this->initStyle()) {
merlinofchaos's avatar
merlinofchaos committed
1108 1109 1110 1111
      $this->build_info['fail'] = TRUE;
      return FALSE;
    }

1112
    if ($this->style_plugin->usesFields()) {
merlinofchaos's avatar
merlinofchaos committed
1113 1114 1115 1116 1117 1118
      $this->_build('field');
    }

    // Build our sort criteria if we were instructed to do so.
    if (!empty($this->build_sort)) {
      // Allow the style handler to deal with sorting.
1119
      if ($this->style_plugin->buildSort()) {
merlinofchaos's avatar
merlinofchaos committed
1120 1121 1122
        $this->_build('sort');
      }
      // allow the plugin to build second sorts as well.
1123
      $this->style_plugin->buildSortPost();
merlinofchaos's avatar
merlinofchaos committed
1124 1125 1126 1127 1128 1129 1130 1131
    }

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

    // Allow display handler to affect the query:
1132
    $this->display_handler->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1133 1134

    // Allow style handler to affect the query:
1135
    $this->style_plugin->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1136 1137 1138 1139 1140 1141

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

1142
    if (\Drupal::config('views.settings')->get('sql_signature')) {
1143
      $this->query->addSignature($this);
merlinofchaos's avatar
merlinofchaos committed
1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158
    }

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

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

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

    // Attach displays
1159
    $this->attachDisplays();
merlinofchaos's avatar
merlinofchaos committed
1160 1161

    // Let modules modify the view just after building it.
1162
    $module_handler->invokeAll('views_post_build', array($this));
merlinofchaos's avatar
merlinofchaos committed
1163 1164 1165 1166 1167 1168

    return TRUE;
  }

  /**
   * Internal method to build an individual set of handlers.
1169
   *
1170 1171
   * @todo Some filter needs this function, even it is internal.
   *
1172 1173 1174
   * @param string $key
   *    The type of handlers (filter etc.) which should be iterated over to
   *    build the relationship and query information.
merlinofchaos's avatar
merlinofchaos committed
1175
   */
1176
  public function _build($key) {
merlinofchaos's avatar
merlinofchaos committed
1177 1178
    $handlers = &$this->$key;
    foreach ($handlers as $id => $data) {
1179

merlinofchaos's avatar
merlinofchaos committed
1180
      if (!empty($handlers[$id]) && is_object($handlers[$id])) {
1181
        $multiple_exposed_input = array(0 => NULL);
1182
        if ($handlers[$id]->multipleExposedInput()) {
1183
          $multiple_exposed_input = $handlers[$id]->groupMultipleExposedInput($this->exposed_data);
1184 1185 1186 1187
        }
        foreach ($multiple_exposed_input as $group_id) {
          // Give this handler access to the exposed filter input.
          if (!empty($this->exposed_data)) {
1188
            if ($handlers[$id]->isAGroup()) {
1189
              $converted = $handlers[$id]->convertExposedInput($this->exposed_data, $group_id);
1190
              $handlers[$id]->storeGroupInput($this->exposed_data, $converted);
1191 1192 1193 1194
              if (!$converted) {
                continue;
              }
            }
1195 1196
            $rc = $handlers[$id]->acceptExposedInput($this->exposed_data);
            $handlers[$id]->storeExposedInput($this->exposed_data, $rc);
1197 1198 1199
            if (!$rc) {
              continue;
            }
merlinofchaos's avatar
merlinofchaos committed
1200
          }
1201
          $handlers[$id]->setRelationship();
1202
          $handlers[$id]->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1203 1204 1205 1206 1207 1208 1209
        }
      }
    }
  }

  /**
   * Execute the view's query.
1210 1211 1212 1213 1214 1215 1216
   *
   * @param string $display_id
   *   The machine name of the display, which should be executed.
   *
   * @return bool
   *   Return whether the executing was successful, for example an argument
   *   could stop the process.
merlinofchaos's avatar
merlinofchaos committed
1217
   */
1218
  public function execute($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
    if (empty($this->built)) {
      if (!$this->build($display_id)) {
        return FALSE;
      }
    }

    if (!empty($this->executed)) {
      return TRUE;
    }

    // Don't allow to use deactivated displays, but display them on the live preview.
1230
    if (!$this->display_handler->isEnabled() && empty($this->live_preview)) {
merlinofchaos's avatar
merlinofchaos committed
1231 1232 1233 1234 1235
      $this->build_info['fail'] = TRUE;
      return FALSE;
    }

    // Let modules modify the view just prior to executing it.
1236 1237
    $module_handler = \Drupal::moduleHandler();
    $module_handler->invokeAll('views_pre_execute', array($this));
merlinofchaos's avatar
merlinofchaos committed
1238 1239 1240

    // Check for already-cached results.
    if (!empty($this->live_preview)) {
1241
      $cache = $this->display_handler->getPlugin('cache', 'none');
merlinofchaos's avatar
merlinofchaos committed
1242 1243
    }
    else {
1244
      $cache = $this->display_handler->getPlugin('cache');
merlinofchaos's avatar
merlinofchaos committed
1245
    }
1246 1247

    if ($cache->cacheGet('results')) {
1248
      if ($this->pager->usePager()) {
1249
        $this->pager->total_items = $this->total_rows;
1250
        $this->pager->updatePageInfo();
merlinofchaos's avatar
merlinofchaos committed
1251 1252 1253 1254
      }
    }
    else {
      $this->query->execute($this);
1255 1256 1257
      // Enforce the array key rule as documented in
      // views_plugin_query::execute().
      $this->result = array_values($this->result);
1258
      $this->_postExecute();
1259
      $cache->cacheSet('results');
merlinofchaos's avatar
merlinofchaos committed
1260 1261 1262
    }

    // Let modules modify the view just after executing it.
1263
    $module_handler->invokeAll('views_post_execute', array($this));
merlinofchaos's avatar
merlinofchaos committed
1264 1265 1266 1267 1268

    $this->executed = TRUE;
  }

  /**
1269 1270 1271 1272 1273 1274 1275 1276
   * Render this view for a certain display.
   *
   * Note: You should better use just the preview function if you want to
   * render a view.
   *
   * @param string $display_id
   *   The machine name of the display, which should be rendered.
   *
1277
   * @return string|null
1278
   *   Return the output of the rendered view or NULL if something failed in the process.
merlinofchaos's avatar
merlinofchaos committed
1279
   */