ViewExecutable.php 57.2 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\Core\DependencyInjection\DependencySerializationTrait;
11
use Drupal\Core\Form\FormState;
12
use Drupal\Core\Session\AccountInterface;
13
use Drupal\views\Plugin\views\query\QueryPluginBase;
14
use Drupal\views\ViewStorageInterface;
15
use Drupal\Component\Utility\Tags;
16
use Symfony\Component\HttpFoundation\Request;
17
use Symfony\Component\HttpFoundation\Response;
18

merlinofchaos's avatar
merlinofchaos committed
19
/**
20 21
 * Represents a view as a whole.
 *
merlinofchaos's avatar
merlinofchaos committed
22 23 24
 * 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.
 */
25 26
class ViewExecutable {
  use DependencySerializationTrait;
27

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

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

  /**
   * Whether the view has been executed/query has been run.
   *
47 48
   * @todo Group with other static properties.
   *
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
   * @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
   */
72
  protected $ajaxEnabled = FALSE;
merlinofchaos's avatar
merlinofchaos committed
73

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

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

85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
  /**
   * The current page. If the view uses pagination.
   *
   * @var int
   */
  public $current_page = NULL;

  /**
   * The number of items per page.
   *
   * @var int
   */
  public $items_per_page = NULL;

  /**
   * The pager offset.
   *
   * @var int
   */
  public $offset = NULL;

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

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

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

  // Exposed widget input

129
  /**
130
   * All the form data from $form_state->getValues().
131 132 133 134
   *
   * @var array
   */
  public $exposed_data = array();
merlinofchaos's avatar
merlinofchaos committed
135

136 137 138 139 140 141
  /**
   * An array of input values from exposed forms.
   *
   * @var array
   */
  public $exposed_input = array();
merlinofchaos's avatar
merlinofchaos committed
142

143
  /**
144
   * Exposed widget input directly from the $form_state->getValues().
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
   *
   * @var array
   */
  public $exposed_raw_input = array();

  /**
   * Used to store views that were previously running if we recurse.
   *
   * @var array
   */
  public $old_view = array();

  /**
   * To avoid recursion in views embedded into areas.
   *
   * @var array
   */
  public $parent_views = array();

  /**
   * Whether this view is an attachment to another view.
   *
   * @var bool
   */
  public $is_attachment = NULL;
merlinofchaos's avatar
merlinofchaos committed
170 171 172 173 174 175

  /**
   * Identifier of the current display.
   *
   * @var string
   */
176
  public $current_display;
merlinofchaos's avatar
merlinofchaos committed
177 178

  /**
179
   * Where the $query object will reside.
merlinofchaos's avatar
merlinofchaos committed
180
   *
181
   * @var \Drupal\views\Plugin\views\query\QueryPluginBase
merlinofchaos's avatar
merlinofchaos committed
182
   */
183
  public $query = NULL;
merlinofchaos's avatar
merlinofchaos committed
184

185 186 187
  /**
   * The used pager plugin used by the current executed view.
   *
188
   * @var \Drupal\views\Plugin\views\pager\PagerPluginBase
189 190 191 192
   */
  public $pager = NULL;

  /**
merlinofchaos's avatar
merlinofchaos committed
193 194
   * The current used display plugin.
   *
195
   * @var \Drupal\views\Plugin\views\display\DisplayPluginBase
merlinofchaos's avatar
merlinofchaos committed
196
   */
197
  public $display_handler;
merlinofchaos's avatar
merlinofchaos committed
198

199 200 201 202 203 204
  /**
   * The list of used displays of the view.
   *
   * An array containing Drupal\views\Plugin\views\display\DisplayPluginBase
   * objects.
   *
205
   * @var \Drupal\views\DisplayBag
206 207 208
   */
  public $displayHandlers;

merlinofchaos's avatar
merlinofchaos committed
209 210 211
  /**
   * The current used style plugin.
   *
212
   * @var \Drupal\views\Plugin\views\style\StylePluginBase
merlinofchaos's avatar
merlinofchaos committed
213
   */
214
  public $style_plugin;
merlinofchaos's avatar
merlinofchaos committed
215

216 217 218 219 220 221 222
  /**
   * 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
223 224 225 226 227
  /**
   * Stores the current active row while rendering.
   *
   * @var int
   */
228
  public $row_index;
merlinofchaos's avatar
merlinofchaos committed
229

230
  /**
merlinofchaos's avatar
merlinofchaos committed
231 232 233 234
   * Allow to override the url of the current view.
   *
   * @var string
   */
235
  public $override_url = NULL;
merlinofchaos's avatar
merlinofchaos committed
236 237 238 239 240 241

  /**
   * Allow to override the path used for generated urls.
   *
   * @var string
   */
242
  public $override_path = NULL;
merlinofchaos's avatar
merlinofchaos committed
243 244 245

  /**
   * Allow to override the used database which is used for this query.
246 247
   *
   * @var bool
merlinofchaos's avatar
merlinofchaos committed
248
   */
249
  public $base_database = NULL;
merlinofchaos's avatar
merlinofchaos committed
250

251
  // Handlers which are active on this view.
merlinofchaos's avatar
merlinofchaos committed
252 253 254

  /**
   * Stores the field handlers which are initialized on this view.
255 256 257 258 259
   *
   * An array containing Drupal\views\Plugin\views\field\FieldPluginBase
   * objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
260
   */
261
  public $field;
merlinofchaos's avatar
merlinofchaos committed
262 263 264

  /**
   * Stores the argument handlers which are initialized on this view.
265 266 267 268 269
   *
   * An array containing Drupal\views\Plugin\views\argument\ArgumentPluginBase
   * objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
270
   */
271
  public $argument;
merlinofchaos's avatar
merlinofchaos committed
272 273 274

  /**
   * Stores the sort handlers which are initialized on this view.
275 276 277 278
   *
   * An array containing Drupal\views\Plugin\views\sort\SortPluginBase objects.
   *
   * @var array
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 286 287 288
   *
   * An array containing Drupal\views\Plugin\views\filter\FilterPluginBase
   * objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
289
   */
290
  public $filter;
merlinofchaos's avatar
merlinofchaos committed
291 292 293

  /**
   * Stores the relationship handlers which are initialized on this view.
294 295 296 297 298
   *
   * An array containing Drupal\views\Plugin\views\relationship\RelationshipPluginBase
   * objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
299
   */
300
  public $relationship;
merlinofchaos's avatar
merlinofchaos committed
301 302 303

  /**
   * Stores the area handlers for the header which are initialized on this view.
304 305 306 307
   *
   * An array containing Drupal\views\Plugin\views\area\AreaPluginBase objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
308
   */
309
  public $header;
merlinofchaos's avatar
merlinofchaos committed
310 311 312

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

  /**
   * Stores the area handlers for the empty text which are initialized on this view.
322 323 324 325
   *
   * An array containing Drupal\views\Plugin\views\area\AreaPluginBase objects.
   *
   * @var array
merlinofchaos's avatar
merlinofchaos committed
326
   */
327
  public $empty;
merlinofchaos's avatar
merlinofchaos committed
328

329 330 331
  /**
   * Stores the current response object.
   *
332
   * @var \Symfony\Component\HttpFoundation\Response
333 334 335
   */
  protected $response = NULL;

336 337 338 339 340 341 342
  /**
   * Stores the current request object.
   *
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

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 388 389 390 391 392 393 394 395 396 397
  /**
   * 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;

398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
  /**
   * A render array container to store render related information.
   *
   * For example you can alter the array and attach some css/js via the
   * #attached key. This is the required way to add custom css/js.
   *
   * @var array
   *
   * @see drupal_process_attached
   */
  public $element = array(
    '#attached' => array(
      'css' => array(),
      'js' => array(),
      'library' => array(),
    ),
  );

416 417 418 419 420 421 422
  /**
   * The current user.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $user;

423 424 425 426 427 428 429
  /**
   * Should the admin links be shown on the rendered view.
   *
   * @var bool
   */
  protected $showAdminLinks;

430 431 432
  /**
   * Constructs a new ViewExecutable object.
   *
433
   * @param \Drupal\views\ViewStorageInterface $storage
434
   *   The view config entity the actual information is stored on.
435 436
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
437
   */
438
  public function __construct(ViewStorageInterface $storage, AccountInterface $user) {
439 440
    // Reference the storage and the executable to each other.
    $this->storage = $storage;
441
    $this->storage->set('executable', $this);
442
    $this->user = $user;
443 444

    // Add the default css for a view.
445
    $this->element['#attached']['library'][] = 'views/views.module';
446 447 448
  }

  /**
449
   * @todo.
450
   */
451 452
  public function save() {
    $this->storage->save();
merlinofchaos's avatar
merlinofchaos committed
453 454 455 456 457 458
  }

  /**
   * Set the arguments that come to this view. Usually from the URL
   * but possibly from elsewhere.
   */
459
  public function setArguments($args) {
merlinofchaos's avatar
merlinofchaos committed
460 461 462 463 464 465
    $this->args = $args;
  }

  /**
   * Change/Set the current page for the pager.
   */
466
  public function setCurrentPage($page) {
merlinofchaos's avatar
merlinofchaos committed
467
    $this->current_page = $page;
468 469

    // If the pager is already initialized, pass it through to the pager.
470
    if (!empty($this->pager)) {
471
      return $this->pager->setCurrentPage($page);
472
    }
merlinofchaos's avatar
merlinofchaos committed
473 474 475 476 477
  }

  /**
   * Get the current page from the pager.
   */
478
  public function getCurrentPage() {
479
    // If the pager is already initialized, pass it through to the pager.
480
    if (!empty($this->pager)) {
481
      return $this->pager->getCurrentPage();
merlinofchaos's avatar
merlinofchaos committed
482
    }
483 484 485 486

    if (isset($this->current_page)) {
      return $this->current_page;
    }
merlinofchaos's avatar
merlinofchaos committed
487 488 489 490 491
  }

  /**
   * Get the items per page from the pager.
   */
492
  public function getItemsPerPage() {
493
    // If the pager is already initialized, pass it through to the pager.
494
    if (!empty($this->pager)) {
495
      return $this->pager->getItemsPerPage();
merlinofchaos's avatar
merlinofchaos committed
496
    }
497 498 499 500

    if (isset($this->items_per_page)) {
      return $this->items_per_page;
    }
merlinofchaos's avatar
merlinofchaos committed
501 502 503 504 505
  }

  /**
   * Set the items per page on the pager.
   */
506
  public function setItemsPerPage($items_per_page) {
merlinofchaos's avatar
merlinofchaos committed
507 508 509
    $this->items_per_page = $items_per_page;

    // If the pager is already initialized, pass it through to the pager.
510
    if (!empty($this->pager)) {
511
      $this->pager->setItemsPerPage($items_per_page);
merlinofchaos's avatar
merlinofchaos committed
512 513 514 515 516 517
    }
  }

  /**
   * Get the pager offset from the pager.
   */
518
  public function getOffset() {
519
    // If the pager is already initialized, pass it through to the pager.
520
    if (!empty($this->pager)) {
521
      return $this->pager->getOffset();
merlinofchaos's avatar
merlinofchaos committed
522
    }
523 524 525 526

    if (isset($this->offset)) {
      return $this->offset;
    }
merlinofchaos's avatar
merlinofchaos committed
527 528 529 530 531
  }

  /**
   * Set the offset on the pager.
   */
532
  public function setOffset($offset) {
merlinofchaos's avatar
merlinofchaos committed
533 534 535
    $this->offset = $offset;

    // If the pager is already initialized, pass it through to the pager.
536
    if (!empty($this->pager)) {
537
      $this->pager->setOffset($offset);
merlinofchaos's avatar
merlinofchaos committed
538 539 540 541 542 543
    }
  }

  /**
   * Determine if the pager actually uses a pager.
   */
544
  public function usePager() {
545
    if (!empty($this->pager)) {
546
      return $this->pager->usePager();
merlinofchaos's avatar
merlinofchaos committed
547 548 549 550
    }
  }

  /**
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568
   * 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
569
   */
570 571
  public function ajaxEnabled() {
    return $this->ajaxEnabled;
merlinofchaos's avatar
merlinofchaos committed
572 573 574 575
  }

  /**
   * Set the exposed filters input to an array. If unset they will be taken
576
   * from \Drupal::request()->query when the time comes.
merlinofchaos's avatar
merlinofchaos committed
577
   */
578
  public function setExposedInput($filters) {
merlinofchaos's avatar
merlinofchaos committed
579 580 581 582 583 584
    $this->exposed_input = $filters;
  }

  /**
   * Figure out what the exposed input for this view is.
   */
585
  public function getExposedInput() {
586 587
    // Fill our input either from \Drupal::request()->query or from something
    // previously set on the view.
merlinofchaos's avatar
merlinofchaos committed
588
    if (empty($this->exposed_input)) {
589
      $this->exposed_input = \Drupal::request()->query->all();
merlinofchaos's avatar
merlinofchaos committed
590 591 592 593 594 595 596 597 598 599 600 601 602
      // 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.
603
      $display_id = ($this->display_handler->isDefaulted('filters')) ? 'default' : $this->current_display;
merlinofchaos's avatar
merlinofchaos committed
604

605 606
      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
607 608 609 610 611 612 613 614 615
      }
    }

    return $this->exposed_input;
  }

  /**
   * Set the display for this view and initialize the display handler.
   */
616
  public function initDisplay() {
merlinofchaos's avatar
merlinofchaos committed
617 618 619 620
    if (isset($this->current_display)) {
      return TRUE;
    }

621
    // Initialize the display cache array.
622
    $this->displayHandlers = new DisplayBag($this, Views::pluginManager('display'));
merlinofchaos's avatar
merlinofchaos committed
623 624

    $this->current_display = 'default';
625
    $this->display_handler = $this->displayHandlers->get('default');
merlinofchaos's avatar
merlinofchaos committed
626 627 628 629 630 631 632

    return TRUE;
  }

  /**
   * Get the first display that is accessible to the user.
   *
633
   * @param array|string $displays
merlinofchaos's avatar
merlinofchaos committed
634
   *   Either a single display id or an array of display ids.
635 636 637
   *
   * @return string
   *   The first accessible display id, at least default.
merlinofchaos's avatar
merlinofchaos committed
638
   */
639
  public function chooseDisplay($displays) {
merlinofchaos's avatar
merlinofchaos committed
640 641 642 643
    if (!is_array($displays)) {
      return $displays;
    }

644
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
645 646

    foreach ($displays as $display_id) {
647
      if ($this->displayHandlers->get($display_id)->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
648 649 650 651 652 653 654
        return $display_id;
      }
    }

    return 'default';
  }

655 656 657 658 659 660 661 662 663 664 665 666 667
  /**
   * 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
668
  /**
669
   * Sets the current display.
merlinofchaos's avatar
merlinofchaos committed
670
   *
671 672 673 674 675
   * @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
676
   */
677
  public function setDisplay($display_id = NULL) {
678 679 680 681
    // 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.
682
      $this->initDisplay();
683
    }
merlinofchaos's avatar
merlinofchaos committed
684

685 686 687 688
    // 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
689 690
    }

691
    $display_id = $this->chooseDisplay($display_id);
merlinofchaos's avatar
merlinofchaos committed
692 693

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

699 700 701 702 703 704 705 706 707 708 709 710
    // 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;
    }

711 712 713 714 715
    if ($display = $this->displayHandlers->get($display_id)) {
      // Set a shortcut.
      $this->display_handler = $display;
      return TRUE;
    }
merlinofchaos's avatar
merlinofchaos committed
716

717
    return FALSE;
merlinofchaos's avatar
merlinofchaos committed
718 719
  }

720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
  /**
   * 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);
740
    $this->displayHandlers->addInstanceId($id);
741

742 743 744
    $display = $this->displayHandlers->get($id);
    $display->newDisplay();
    return $display;
745 746
  }

747 748 749 750 751 752 753 754 755 756 757 758 759
  /**
   * 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
760 761 762 763 764 765
  /**
   * 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.
   */
766
  public function initStyle() {
merlinofchaos's avatar
merlinofchaos committed
767
    if (isset($this->style_plugin)) {
768
      return TRUE;
merlinofchaos's avatar
merlinofchaos committed
769 770
    }

771
    $this->style_plugin = $this->display_handler->getPlugin('style');
merlinofchaos's avatar
merlinofchaos committed
772 773 774 775 776 777 778 779 780 781 782

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

    return TRUE;
  }

  /**
   * Acquire and attach all of the handlers.
   */
783
  public function initHandlers() {
784
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
785
    if (empty($this->inited)) {
786
      foreach ($this::getHandlerTypes() as $key => $info) {
787
        $this->_initHandler($key, $info);
merlinofchaos's avatar
merlinofchaos committed
788 789 790 791 792
      }
      $this->inited = TRUE;
    }
  }

793 794 795 796 797 798 799 800 801 802 803 804 805
  /**
   * 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
806 807 808 809 810 811
  /**
   * Initialize the pager
   *
   * Like style initialization, pager initialization is held until late
   * to allow for overrides.
   */
812
  public function initPager() {
813
    if (!isset($this->pager)) {
814
      $this->pager = $this->display_handler->getPlugin('pager');
merlinofchaos's avatar
merlinofchaos committed
815

816
      if ($this->pager->usePager()) {
817
        $this->pager->setCurrentPage($this->current_page);
merlinofchaos's avatar
merlinofchaos committed
818 819 820 821 822
      }

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

      if (isset($this->offset)) {
827
        $this->pager->setOffset($this->offset);
merlinofchaos's avatar
merlinofchaos committed
828 829 830 831
      }
    }
  }

832 833 834
  /**
   * Render the pager, if necessary.
   */
835
  public function renderPager($exposed_input) {
836
    if (!empty($this->pager) && $this->pager->usePager()) {
837 838 839 840 841 842
      return $this->pager->render($exposed_input);
    }

    return '';
  }

merlinofchaos's avatar
merlinofchaos committed
843 844 845 846
  /**
   * Create a list of base tables eligible for this view. Used primarily
   * for the UI. Display must be already initialized.
   */
847
  public function getBaseTables() {
merlinofchaos's avatar
merlinofchaos committed
848
    $base_tables = array(
849
      $this->storage->get('base_table') => TRUE,
merlinofchaos's avatar
merlinofchaos committed
850 851 852
      '#global' => TRUE,
    );

853
    foreach ($this->display_handler->getHandlers('relationship') as $handler) {
merlinofchaos's avatar
merlinofchaos committed
854 855 856 857 858 859
      $base_tables[$handler->definition['base']] = TRUE;
    }
    return $base_tables;
  }

  /**
860
   * Run the preQuery() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
861
   */
862
  protected function _preQuery() {
863
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
864 865 866 867
      $handlers = &$this->$key;
      $position = 0;
      foreach ($handlers as $id => $handler) {
        $handlers[$id]->position = $position;
868
        $handlers[$id]->preQuery();
merlinofchaos's avatar
merlinofchaos committed
869 870 871 872 873 874
        $position++;
      }
    }
  }

  /**
875
   * Run the postExecute() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
876
   */
877
  protected function _postExecute() {
878
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
879 880
      $handlers = &$this->$key;
      foreach ($handlers as $id => $handler) {
881
        $handlers[$id]->postExecute($this->result);
merlinofchaos's avatar
merlinofchaos committed
882 883 884 885 886 887 888 889 890 891
      }
    }
  }

  /**
   * Attach all of the handlers for each type.
   *
   * @param $key
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'
   * @param $info
892
   *   The $info from getHandlerTypes for this object.
merlinofchaos's avatar
merlinofchaos committed
893
   */
894
  protected function _initHandler($key, $info) {
merlinofchaos's avatar
merlinofchaos committed
895
    // Load the requested items from the display onto the object.
896
    $this->$key = $this->display_handler->getHandlers($key);
merlinofchaos's avatar
merlinofchaos committed
897 898 899 900 901 902

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

    // Run through and test for accessibility.
    foreach ($handlers as $id => $handler) {
903
      if (!$handler->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
904 905 906 907 908 909 910 911
        unset($handlers[$id]);
      }
    }
  }

  /**
   * Build all the arguments.
   */
912
  protected function _buildArguments() {
merlinofchaos's avatar
merlinofchaos committed
913 914 915 916 917 918 919 920 921 922 923
    // 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;

924 925 926
    // Get the title.
    $title = $this->display_handler->getOption('title');

merlinofchaos's avatar
merlinofchaos committed
927 928 929
    // Iterate through each argument and process.
    foreach ($this->argument as $id => $arg) {
      $position++;
930
      $argument = $this->argument[$id];
merlinofchaos's avatar
merlinofchaos committed
931 932 933 934 935

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

936
      $argument->setRelationship();
merlinofchaos's avatar
merlinofchaos committed
937 938 939 940

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

941
      if (isset($arg) || $argument->hasDefaultArgument()) {
merlinofchaos's avatar
merlinofchaos committed
942
        if (!isset($arg)) {
943
          $arg = $argument->getDefaultArgument();
merlinofchaos's avatar
merlinofchaos committed
944 945 946 947 948 949 950 951 952
          // 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.
953
        if (!$argument->setArgument($arg)) {
954
          $status = $argument->validateFail($arg);
merlinofchaos's avatar
merlinofchaos committed
955 956 957
          break;
        }

958
        if ($argument->isException()) {
959
          $arg_title = $argument->exceptionTitle();
merlinofchaos's avatar
merlinofchaos committed
960 961
        }
        else {
962
          $arg_title = $argument->getTitle();
963
          $argument->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
964 965 966 967 968 969 970 971 972 973 974 975 976
        }

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

        // 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.
977
        $status = $argument->defaultAction();
merlinofchaos's avatar
merlinofchaos committed
978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995
        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;
  }

996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008
  /**
   * 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
1009 1010 1011
  /**
   * Do some common building initialization.
   */
1012
  public function initQuery() {
merlinofchaos's avatar
merlinofchaos committed
1013 1014 1015 1016 1017 1018 1019 1020 1021
    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.
1022
    $views_data = Views::viewsData()->get($this->storage->get('base_table'));
1023
    $this->storage->set('base_field', !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '');
merlinofchaos's avatar
merlinofchaos committed
1024 1025 1026 1027
    if (!empty($views_data['table']['base']['database'])) {
      $this->base_database = $views_data['table']['base']['database'];
    }

1028
    $this->query = $this->display_handler->getPlugin('query');
merlinofchaos's avatar
merlinofchaos committed
1029 1030 1031 1032 1033 1034
    return TRUE;
  }

  /**
   * Build the query for the view.
   */
1035
  public function build($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1036 1037 1038 1039 1040
    if (!empty($this->built)) {
      return;
    }

    if (empty($this->current_display) || $display_id) {
1041
      if (!$this->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
1042 1043 1044 1045 1046
        return FALSE;
      }
    }

    // Let modules modify the view just prior to building it.
1047 1048
    $module_handler = \Drupal::moduleHandler();
    $module_handler->invokeAll('views_pre_build', array($this));
merlinofchaos's avatar
merlinofchaos committed
1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

    // 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(),
    );

1061
    $this->initQuery();
merlinofchaos's avatar
merlinofchaos committed
1062 1063 1064 1065 1066 1067 1068

    // 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.
1069
    $this->initHandlers();
merlinofchaos's avatar
merlinofchaos committed
1070 1071

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

1074 1075
    if ($this->display_handler->usesExposed()) {
      $exposed_form = $this->display_handler->getPlugin('exposed_form');
1076
      $this->exposed_widgets = $exposed_form->renderExposedForm();
1077
      if (FormState::hasAnyErrors() || !empty($this->build_info['abort'])) {
merlinofchaos's avatar
merlinofchaos committed
1078
        $this->built = TRUE;
1079
        // Don't execute the query, $form_state, but rendering will still be executed to display the empty text.
merlinofchaos's avatar
merlinofchaos committed
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
        $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)) {
1090
      $filter_groups = $this->display_handler->getOption('filter_groups');
merlinofchaos's avatar
merlinofchaos committed
1091
      if ($filter_groups) {
1092
        $this->query->setGroupOperator($filter_groups['operator']);
1093
        foreach ($filter_groups['groups'] as $id => $operator) {
1094
          $this->query->setWhereGroup($operator, $id);
merlinofchaos's avatar
merlinofchaos committed
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
        }
      }
    }

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

    $this->build_sort = TRUE;

    // Arguments can, in fact, cause this whole thing to abort.
1105
    if (!$this->_buildArguments()) {
merlinofchaos's avatar
merlinofchaos committed
1106
      $this->build_time = microtime(TRUE) - $start;
1107
      $this->attachDisplays();
merlinofchaos's avatar
merlinofchaos committed
1108 1109 1110 1111 1112 1113
      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.
1114
    if (!$this->initStyle()) {
merlinofchaos's avatar
merlinofchaos committed
1115 1116 1117 1118
      $this->build_info['fail'] = TRUE;
      return FALSE;
    }

1119
    if ($this->style_plugin->usesFields()) {
merlinofchaos's avatar
merlinofchaos committed
1120 1121 1122 1123 1124 1125
      $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.
1126
      if ($this->style_plugin->buildSort()) {
merlinofchaos's avatar
merlinofchaos committed
1127 1128 1129
        $this->_build('sort');
      }
      // allow the plugin to build second sorts as well.
1130
      $this->style_plugin->buildSortPost();
merlinofchaos's avatar
merlinofchaos committed
1131 1132 1133 1134 1135 1136 1137 1138
    }

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

    // Allow display handler to affect the query:
1139
    $this->display_handler->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1140 1141

    // Allow style handler to affect the query:
1142
    $this->style_plugin->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1143 1144 1145 1146 1147 1148

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

1149
    if (\Drupal::config('views.settings')->get('sql_signature')) {
1150
      $this->query->addSignature($this);
merlinofchaos's avatar
merlinofchaos committed
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165
    }

    // 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
1166
    $this->attachDisplays();
merlinofchaos's avatar
merlinofchaos committed
1167 1168

    // Let modules modify the view just after building it.
1169
    $module_handler->invokeAll('views_post_build', array($this));
merlinofchaos's avatar
merlinofchaos committed
1170 1171 1172 1173 1174 1175

    return TRUE;
  }

  /**
   * Internal method to build an individual set of handlers.
1176
   *
1177 1178
   * @todo Some filter needs this function, even it is internal.
   *
1179 1180 1181
   * @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
1182
   */
1183
  public function _build($key) {
merlinofchaos's avatar
merlinofchaos committed
1184 1185
    $handlers = &$this->$key;
    foreach ($handlers as $id => $data) {
1186

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

  /**
   * Execute the view's query.
1217 1218 1219 1220 1221 1222 1223
   *
   * @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
1224
   */
1225
  public function execute($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236
    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.
1237
    if (!$this->display_handler->isEnabled() && empty($this->live_preview)) {
merlinofchaos's avatar
merlinofchaos committed
1238 1239 1240 1241 1242
      $this->build_info['fail'] = TRUE;
      return FALSE;
    }

    // Let modules modify the view just prior to executing it.
1243 1244
    $module_handler = \Drupal::moduleHandler();
    $module_handler->invokeAll('views_pre_execute', array($this));
merlinofchaos's avatar
merlinofchaos committed
1245 1246 1247

    // Check for already-cached results.
    if (!empty($this->live_preview)) {
1248
      $cache = $this->display_handler->getPlugin('cache', 'none');
merlinofchaos's avatar
merlinofchaos committed
1249 1250
    }
    else {
1251
      $cache = $this->display_handler->getPlugin('cache');
merlinofchaos's avatar
merlinofchaos committed
1252
    }
1253 1254

    if ($cache->cacheGet('results')) {
1255
      if ($this->pager->usePager()) {
1256
        $this->pager->total_items = $this->total_rows;
1257
        $this->pager->updatePageInfo();
merlinofchaos's avatar
merlinofchaos committed
1258 1259 1260 1261
      }
    }
    else {
      $this->query->execute($this);
1262 1263 1264
      // Enforce the array key rule as documented in
      // views_plugin_query::execute().
      $this->result = array_values($this->result);
1265
      $this->_postExecute();
1266
      $cache->cacheSet('results');
merlinofchaos's avatar
merlinofchaos committed
1267 1268 1269
    }

    // Let modules modify the view just after executing it.
1270
    $module_handler->invokeAll('views_post_execute', array($this));
merlinofchaos's avatar
merlinofchaos committed
1271 1272 1273 1274 1275

    $this->executed = TRUE;
  }

  /**
1276 1277 1278 1279 1280 1281 1282 1283
   * 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.
   *
1284
   * @return string|null
1285
   *   Return the output of the rendered view or NULL if something failed in the process.
merlinofchaos's avatar
merlinofchaos committed
1286
   */
1287
  public function render($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1288 1289 1290 1291 1292 1293
    $this->execute($display_id);

    // Check to see if the build failed.
    if (!empty($this->build_info['fail'])) {
      return;
    }
1294
    if (!empty($this->build_info['denied'])) {
merlinofchaos's avatar
merlinofchaos committed
1295 1296 1297
      return;
    }

1298
    $exposed_form = $this->display_handler->getPlugin('exposed_form');
1299
    $exposed_form->preRender($this->result);
merlinofchaos's avatar
merlinofchaos committed
1300

1301 1302
    $module_handler = \Drupal::moduleHandler();

1303 1304 1305 1306 1307 1308
    // @TODO on the longrun it would be great to execute a view without
    //   the theme system at all, see https://drupal.org/node/2322623.
    $active_theme = \Drupal::theme()->getActiveTheme();
    $themes = array_keys($active_theme->getBaseThemes());
    $themes[] = $active_theme->getName();

merlinofchaos's avatar
merlinofchaos committed
1309 1310 1311 1312 1313
    // Check for already-cached output.
    if (!empty($this->live_preview)) {
      $cache = FALSE;
    }
    else {
1314
      $cache = $this->display_handler->getPlugin('cache');
merlinofchaos's avatar
merlinofchaos committed
1315
    }
1316

1317
    /** @var \Drupal\views\Plugin\views\cache\CachePluginBase $cache */
1318
    if ($cache && $cache->cacheGet('output')) {
merlinofchaos's avatar
merlinofchaos committed
1319 1320 1321
    }
    else {
      if ($cache) {
1322
        $cache->cacheStart();
merlinofchaos's avatar
merlinofchaos committed
1323 1324
      }

1325
      // Run preRender for the pager as it might change the result.
1326
      if (!empty($this->pager)) {
1327
        $this->pager->preRender($this->result);
merlinofchaos's avatar
merlinofchaos committed
1328 1329 1330
      }

      // Initialize the style plugin.
1331
      $this->initStyle();
merlinofchaos's avatar
merlinofchaos committed
1332

1333 1334 1335 1336 1337
      if (!isset($this->response)) {
        // Se