ViewExecutable.php 69.7 KB
Newer Older
merlinofchaos's avatar
merlinofchaos committed
1 2
<?php

3 4
namespace Drupal\views;

5
use Drupal\Component\Utility\Html;
6
use Drupal\Component\Utility\Tags;
7
use Drupal\Core\Routing\RouteProviderInterface;
8
use Drupal\Core\Session\AccountInterface;
9
use Drupal\views\Plugin\views\display\DisplayRouterInterface;
10
use Symfony\Component\HttpFoundation\Request;
11
use Symfony\Component\HttpFoundation\Response;
12
use Symfony\Component\Routing\Exception\RouteNotFoundException;
13

merlinofchaos's avatar
merlinofchaos committed
14
/**
15 16
 * Represents a view as a whole.
 *
merlinofchaos's avatar
merlinofchaos committed
17 18
 * 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.
19 20 21 22 23 24
 *
 * This class does not implement the Serializable interface since problems
 * occurred when using the serialize method.
 *
 * @see https://www.drupal.org/node/2849674
 * @see https://bugs.php.net/bug.php?id=66052
merlinofchaos's avatar
merlinofchaos committed
25
 */
26
class ViewExecutable {
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
   * @var bool
   */
  public $executed = FALSE;

  /**
   * Any arguments that have been passed into the view.
   *
   * @var array
   */
58
  public $args = [];
59 60 61 62 63 64

  /**
   * An array of build info.
   *
   * @var array
   */
65
  public $build_info = [];
66 67 68 69 70 71

  /**
   * 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 = [];
merlinofchaos's avatar
merlinofchaos committed
82 83 84

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

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

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

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

  /**
   * 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 = [];
119 120

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

127 128 129 130 131
  /**
   * Feed icons attached to the view.
   *
   * @var array
   */
132
  public $feedIcons = [];
133

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

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

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

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

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

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

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

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

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

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

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

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

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

223 224 225 226 227 228 229
  /**
   * 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
230 231 232 233 234
  /**
   * Stores the current active row while rendering.
   *
   * @var int
   */
235
  public $row_index;
merlinofchaos's avatar
merlinofchaos committed
236

237
  /**
merlinofchaos's avatar
merlinofchaos committed
238 239
   * Allow to override the url of the current view.
   *
240
   * @var \Drupal\Core\Url
merlinofchaos's avatar
merlinofchaos committed
241
   */
242
  public $override_url;
merlinofchaos's avatar
merlinofchaos committed
243 244 245 246 247 248

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

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

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

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

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

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

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

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

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

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

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

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

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

332 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
  /**
   * 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;

387 388 389
  /**
   * A render array container to store render related information.
   *
390 391 392
   * 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.
393 394 395
   *
   * @var array
   *
396
   * @see \Drupal\Core\Render\AttachmentsResponseProcessorInterface::processAttachments()
397
   */
398 399
  public $element = [
    '#attached' => [
400
      'library' => ['views/views.module'],
401
      'drupalSettings' => [],
402 403
    ],
    '#cache' => [],
404
  ];
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 423 424 425 426
  /**
   * The views data.
   *
   * @var \Drupal\views\ViewsData
   */
  protected $viewsData;

427 428 429 430 431 432 433
  /**
   * The route provider.
   *
   * @var \Drupal\Core\Routing\RouteProviderInterface
   */
  protected $routeProvider;

434 435 436 437 438 439 440
  /**
   * The entity type of the base table, if available.
   *
   * @var \Drupal\Core\Entity\EntityTypeInterface|false
   */
  protected $baseEntityType;

441 442 443 444 445 446 447
  /**
   * Holds all necessary data for proper unserialization.
   *
   * @var array
   */
  protected $serializationData;

448 449 450
  /**
   * Constructs a new ViewExecutable object.
   *
451
   * @param \Drupal\views\ViewEntityInterface $storage
452
   *   The view config entity the actual information is stored on.
453 454
   * @param \Drupal\Core\Session\AccountInterface $user
   *   The current user.
455 456
   * @param \Drupal\views\ViewsData $views_data
   *   The views data.
457 458
   * @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
   *   The route provider.
459
   */
460
  public function __construct(ViewEntityInterface $storage, AccountInterface $user, ViewsData $views_data, RouteProviderInterface $route_provider) {
461 462
    // Reference the storage and the executable to each other.
    $this->storage = $storage;
463
    $this->storage->set('executable', $this);
464
    $this->user = $user;
465
    $this->viewsData = $views_data;
466
    $this->routeProvider = $route_provider;
467 468 469
  }

  /**
470 471 472 473 474 475 476 477 478 479 480 481
   * Returns the identifier.
   *
   * @return string|null
   *   The entity identifier, or NULL if the object does not yet have an
   *   identifier.
   */
  public function id() {
    return $this->storage->id();
  }

  /**
   * Saves the view.
482
   */
483 484
  public function save() {
    $this->storage->save();
merlinofchaos's avatar
merlinofchaos committed
485 486 487
  }

  /**
488 489 490 491
   * Sets the arguments for the view.
   *
   * @param array $args
   *   The arguments passed to the view.
merlinofchaos's avatar
merlinofchaos committed
492
   */
493 494 495 496
  public function setArguments(array $args) {
    // The array keys of the arguments will be incorrect if set by
    // views_embed_view() or \Drupal\views\ViewExecutable:preview().
    $this->args = array_values($args);
merlinofchaos's avatar
merlinofchaos committed
497 498
  }

499 500 501 502 503 504 505 506 507 508 509 510 511 512
  /**
   * Expands the list of used cache contexts for the view.
   *
   * @param string $cache_context
   *   The additional cache context.
   *
   * @return $this
   */
  public function addCacheContext($cache_context) {
    $this->element['#cache']['contexts'][] = $cache_context;

    return $this;
  }

merlinofchaos's avatar
merlinofchaos committed
513
  /**
514
   * Sets the current page for the pager.
515 516 517
   *
   * @param int $page
   *   The current page.
merlinofchaos's avatar
merlinofchaos committed
518
   */
519
  public function setCurrentPage($page) {
merlinofchaos's avatar
merlinofchaos committed
520
    $this->current_page = $page;
521

522 523 524 525 526
    // Calls like ::unserialize() might call this method without a proper $page.
    // Also check whether the element is pre rendered. At that point, the cache
    // keys cannot longer be manipulated.
    if ($page !== NULL && empty($this->element['#pre_rendered'])) {
      $this->element['#cache']['keys'][] = 'page:' . $page;
527 528
    }

529
    // If the pager is already initialized, pass it through to the pager.
530
    if (!empty($this->pager)) {
531
      return $this->pager->setCurrentPage($page);
532
    }
merlinofchaos's avatar
merlinofchaos committed
533 534 535
  }

  /**
536 537 538 539
   * Gets the current page from the pager.
   *
   * @return int
   *   The current page.
merlinofchaos's avatar
merlinofchaos committed
540
   */
541
  public function getCurrentPage() {
542
    // If the pager is already initialized, pass it through to the pager.
543
    if (!empty($this->pager)) {
544
      return $this->pager->getCurrentPage();
merlinofchaos's avatar
merlinofchaos committed
545
    }
546 547 548 549

    if (isset($this->current_page)) {
      return $this->current_page;
    }
merlinofchaos's avatar
merlinofchaos committed
550 551 552
  }

  /**
553 554 555 556
   * Gets the items per page from the pager.
   *
   * @return int
   *   The items per page.
merlinofchaos's avatar
merlinofchaos committed
557
   */
558
  public function getItemsPerPage() {
559
    // If the pager is already initialized, pass it through to the pager.
560
    if (!empty($this->pager)) {
561
      return $this->pager->getItemsPerPage();
merlinofchaos's avatar
merlinofchaos committed
562
    }
563 564 565 566

    if (isset($this->items_per_page)) {
      return $this->items_per_page;
    }
merlinofchaos's avatar
merlinofchaos committed
567 568 569
  }

  /**
570
   * Sets the items per page on the pager.
571 572 573
   *
   * @param int $items_per_page
   *   The items per page.
merlinofchaos's avatar
merlinofchaos committed
574
   */
575
  public function setItemsPerPage($items_per_page) {
576 577 578 579 580
    // Check whether the element is pre rendered. At that point, the cache keys
    // cannot longer be manipulated.
    if (empty($this->element['#pre_rendered'])) {
      $this->element['#cache']['keys'][] = 'items_per_page:' . $items_per_page;
    }
merlinofchaos's avatar
merlinofchaos committed
581 582 583
    $this->items_per_page = $items_per_page;

    // If the pager is already initialized, pass it through to the pager.
584
    if (!empty($this->pager)) {
585
      $this->pager->setItemsPerPage($items_per_page);
merlinofchaos's avatar
merlinofchaos committed
586 587 588 589
    }
  }

  /**
590 591 592 593
   * Gets the pager offset from the pager.
   *
   * @return int
   *   The pager offset.
merlinofchaos's avatar
merlinofchaos committed
594
   */
595
  public function getOffset() {
596
    // If the pager is already initialized, pass it through to the pager.
597
    if (!empty($this->pager)) {
598
      return $this->pager->getOffset();
merlinofchaos's avatar
merlinofchaos committed
599
    }
600 601 602 603

    if (isset($this->offset)) {
      return $this->offset;
    }
merlinofchaos's avatar
merlinofchaos committed
604 605 606
  }

  /**
607
   * Sets the offset on the pager.
608 609 610
   *
   * @param int $offset
   *   The pager offset.
merlinofchaos's avatar
merlinofchaos committed
611
   */
612
  public function setOffset($offset) {
613 614 615 616 617 618
    // Check whether the element is pre rendered. At that point, the cache keys
    // cannot longer be manipulated.
    if (empty($this->element['#pre_rendered'])) {
      $this->element['#cache']['keys'][] = 'offset:' . $offset;
    }

merlinofchaos's avatar
merlinofchaos committed
619 620
    $this->offset = $offset;

621

merlinofchaos's avatar
merlinofchaos committed
622
    // If the pager is already initialized, pass it through to the pager.
623
    if (!empty($this->pager)) {
624
      $this->pager->setOffset($offset);
merlinofchaos's avatar
merlinofchaos committed
625 626 627 628
    }
  }

  /**
629 630 631 632
   * Determines if the view uses a pager.
   *
   * @return bool
   *   TRUE if the view uses a pager, FALSE otherwise.
merlinofchaos's avatar
merlinofchaos committed
633
   */
634
  public function usePager() {
635
    if (!empty($this->pager)) {
636
      return $this->pager->usePager();
merlinofchaos's avatar
merlinofchaos committed
637 638 639 640
    }
  }

  /**
641 642
   * Sets whether or not AJAX should be used.
   *
643
   * If AJAX is used, paging, table sorting, and exposed filters will be fetched
644 645
   * via an AJAX call rather than a page refresh.
   *
646
   * @param bool $ajax_enabled
647 648 649 650 651 652 653
   *   TRUE if AJAX should be used, FALSE otherwise.
   */
  public function setAjaxEnabled($ajax_enabled) {
    $this->ajaxEnabled = (bool) $ajax_enabled;
  }

  /**
654
   * Determines whether or not AJAX should be used.
655 656
   *
   * @return bool
657
   *   TRUE if AJAX is enabled, FALSE otherwise.
merlinofchaos's avatar
merlinofchaos committed
658
   */
659 660
  public function ajaxEnabled() {
    return $this->ajaxEnabled;
merlinofchaos's avatar
merlinofchaos committed
661 662 663
  }

  /**
664 665 666 667
   * Sets the exposed filters input to an array.
   *
   * @param string[] $filters
   *   The values taken from the view's exposed filters and sorts.
merlinofchaos's avatar
merlinofchaos committed
668
   */
669
  public function setExposedInput($filters) {
merlinofchaos's avatar
merlinofchaos committed
670 671 672 673
    $this->exposed_input = $filters;
  }

  /**
674 675 676 677 678 679 680 681 682 683
   * Figures out what the exposed input for this view is.
   *
   * They will be taken from \Drupal::request()->query or from
   * something previously set on the view.
   *
   * @return string[]
   *   An array containing the exposed input values keyed by the filter and sort
   *   name.
   *
   * @see self::setExposedInput()
merlinofchaos's avatar
merlinofchaos committed
684
   */
685
  public function getExposedInput() {
686 687
    // Fill our input either from \Drupal::request()->query or from something
    // previously set on the view.
merlinofchaos's avatar
merlinofchaos committed
688
    if (empty($this->exposed_input)) {
689 690 691
      // Ensure that we can call the method at any point in time.
      $this->initDisplay();

692
      $this->exposed_input = \Drupal::request()->query->all();
merlinofchaos's avatar
merlinofchaos committed
693
      // unset items that are definitely not our input:
694
      foreach (['page', 'q'] as $key) {
merlinofchaos's avatar
merlinofchaos committed
695 696 697 698 699 700 701 702 703 704 705
        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.
706
      $display_id = ($this->display_handler->isDefaulted('filters')) ? 'default' : $this->current_display;
merlinofchaos's avatar
merlinofchaos committed
707

708 709
      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
710 711 712 713 714 715 716
      }
    }

    return $this->exposed_input;
  }

  /**
717 718 719 720
   * Sets the display for this view and initializes the display handler.
   *
   * @return true
   *   Always returns TRUE.
merlinofchaos's avatar
merlinofchaos committed
721
   */
722
  public function initDisplay() {
merlinofchaos's avatar
merlinofchaos committed
723 724 725 726
    if (isset($this->current_display)) {
      return TRUE;
    }

727
    // Initialize the display cache array.
728
    $this->displayHandlers = new DisplayPluginCollection($this, Views::pluginManager('display'));
merlinofchaos's avatar
merlinofchaos committed
729 730

    $this->current_display = 'default';
731
    $this->display_handler = $this->displayHandlers->get('default');
merlinofchaos's avatar
merlinofchaos committed
732 733 734 735 736

    return TRUE;
  }

  /**
737
   * Gets the first display that is accessible to the user.
merlinofchaos's avatar
merlinofchaos committed
738
   *
739
   * @param array|string $displays
merlinofchaos's avatar
merlinofchaos committed
740
   *   Either a single display id or an array of display ids.
741 742 743
   *
   * @return string
   *   The first accessible display id, at least default.
merlinofchaos's avatar
merlinofchaos committed
744
   */
745
  public function chooseDisplay($displays) {
merlinofchaos's avatar
merlinofchaos committed
746 747 748 749
    if (!is_array($displays)) {
      return $displays;
    }

750
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
751 752

    foreach ($displays as $display_id) {
753
      if ($this->displayHandlers->get($display_id)->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
754 755 756 757 758 759 760
        return $display_id;
      }
    }

    return 'default';
  }

761 762 763 764
  /**
   * Gets the current display plugin.
   *
   * @return \Drupal\views\Plugin\views\display\DisplayPluginBase
765
   *   The current display plugin.
766 767 768 769 770 771 772 773 774
   */
  public function getDisplay() {
    if (!isset($this->display_handler)) {
      $this->initDisplay();
    }

    return $this->display_handler;
  }

merlinofchaos's avatar
merlinofchaos committed
775
  /**
776
   * Sets the current display.
merlinofchaos's avatar
merlinofchaos committed
777
   *
778 779 780 781 782
   * @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
783
   */
784
  public function setDisplay($display_id = NULL) {
785 786 787 788
    // 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.
789
      $this->initDisplay();
790
    }
merlinofchaos's avatar
merlinofchaos committed
791

792 793 794 795
    // 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
796 797
    }

798
    $display_id = $this->chooseDisplay($display_id);
merlinofchaos's avatar
merlinofchaos committed
799 800

    // Ensure the requested display exists.
801
    if (!$this->displayHandlers->has($display_id)) {
802
      debug(format_string('setDisplay() called with invalid display ID "@display".', ['@display' => $display_id]));
803
      return FALSE;
merlinofchaos's avatar
merlinofchaos committed
804 805
    }

806 807 808 809 810 811 812 813 814 815 816 817
    // 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;
    }

818 819 820 821 822
    if ($display = $this->displayHandlers->get($display_id)) {
      // Set a shortcut.
      $this->display_handler = $display;
      return TRUE;
    }
merlinofchaos's avatar
merlinofchaos committed
823

824
    return FALSE;
merlinofchaos's avatar
merlinofchaos committed
825 826
  }

827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846
  /**
   * 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);
847
    $this->displayHandlers->addInstanceId($id);
848

849 850 851
    $display = $this->displayHandlers->get($id);
    $display->newDisplay();
    return $display;
852 853
  }

854 855 856 857
  /**
   * Gets the current style plugin.
   *
   * @return \Drupal\views\Plugin\views\style\StylePluginBase
858
   *   The current style plugin.
859 860 861 862 863 864 865 866 867
   */
  public function getStyle() {
    if (!isset($this->style_plugin)) {
      $this->initStyle();
    }

    return $this->style_plugin;
  }

merlinofchaos's avatar
merlinofchaos committed
868
  /**
869
   * Finds and initializes the style plugin.
merlinofchaos's avatar
merlinofchaos committed
870 871 872
   *
   * Note that arguments may have changed which style plugin we use, so
   * check the view object first, then ask the display handler.
873 874 875
   *
   * @return bool
   *   TRUE if the style plugin was or could be initialized, FALSE otherwise.
merlinofchaos's avatar
merlinofchaos committed
876
   */
877
  public function initStyle() {
merlinofchaos's avatar
merlinofchaos committed
878
    if (isset($this->style_plugin)) {
879
      return TRUE;
merlinofchaos's avatar
merlinofchaos committed
880 881
    }

882
    $this->style_plugin = $this->display_handler->getPlugin('style');
merlinofchaos's avatar
merlinofchaos committed
883 884 885 886 887 888 889 890 891

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

    return TRUE;
  }

  /**
892
   * Acquires and attaches all of the handlers.
merlinofchaos's avatar
merlinofchaos committed
893
   */
894
  public function initHandlers() {
895
    $this->initDisplay();
merlinofchaos's avatar
merlinofchaos committed
896
    if (empty($this->inited)) {
897
      foreach ($this::getHandlerTypes() as $key => $info) {
898
        $this->_initHandler($key, $info);
merlinofchaos's avatar
merlinofchaos committed
899 900 901 902 903
      }
      $this->inited = TRUE;
    }
  }

904
  /**
905
   * Gets the current pager plugin.
906 907
   *
   * @return \Drupal\views\Plugin\views\pager\PagerPluginBase
908
   *   The current pager plugin.
909 910 911 912 913 914 915 916 917
   */
  public function getPager() {
    if (!isset($this->pager)) {
      $this->initPager();
    }

    return $this->pager;
  }

merlinofchaos's avatar
merlinofchaos committed
918
  /**
919
   * Initializes the pager.
merlinofchaos's avatar
merlinofchaos committed
920
   *
921 922
   * Like style initialization, pager initialization is held until late to allow
   * for overrides.
merlinofchaos's avatar
merlinofchaos committed
923
   */
924
  public function initPager() {
925
    if (!isset($this->pager)) {
926
      $this->pager = $this->display_handler->getPlugin('pager');
merlinofchaos's avatar
merlinofchaos committed
927

928
      if ($this->pager->usePager()) {
929
        $this->pager->setCurrentPage($this->current_page);
merlinofchaos's avatar
merlinofchaos committed
930 931 932 933 934
      }

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

      if (isset($this->offset)) {
939
        $this->pager->setOffset($this->offset);
merlinofchaos's avatar
merlinofchaos committed
940 941 942 943
      }
    }
  }

944
  /**
945 946 947 948 949 950 951
   * Renders the pager, if necessary.
   *
   * @param string[] $exposed_input
   *   The input values from the exposed forms and sorts of the view.
   *
   * @return array|string
   *   The render array of the pager if it's set, blank string otherwise.
952
   */
953
  public function renderPager($exposed_input) {
954
    if (!empty($this->pager) && $this->pager->usePager()) {
955 956 957 958 959 960
      return $this->pager->render($exposed_input);
    }

    return '';
  }

merlinofchaos's avatar
merlinofchaos committed
961
  /**
962 963 964 965 966 967
   * Creates a list of base tables to be used by the view.
   *
   * This is used primarily for the UI. The display must be already initialized.
   *
   * @return array
   *   An array of base tables to be used by the view.
merlinofchaos's avatar
merlinofchaos committed
968
   */
969
  public function getBaseTables() {
970
    $base_tables = [
971
      $this->storage->get('base_table') => TRUE,
merlinofchaos's avatar
merlinofchaos committed
972
      '#global' => TRUE,
973
    ];
merlinofchaos's avatar
merlinofchaos committed
974

975
    foreach ($this->display_handler->getHandlers('relationship') as $handler) {
merlinofchaos's avatar
merlinofchaos committed
976 977 978 979 980
      $base_tables[$handler->definition['base']] = TRUE;
    }
    return $base_tables;
  }

981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001
  /**
   * Returns the entity type of the base table, if available.
   *
   * @return \Drupal\Core\Entity\EntityType|false
   *   The entity type of the base table, or FALSE if none exists.
   */
  public function getBaseEntityType() {
    if (!isset($this->baseEntityType)) {
      $view_base_table = $this->storage->get('base_table');
      $views_data = $this->viewsData->get($view_base_table);
      if (!empty($views_data['table']['entity type'])) {
        $entity_type_id = $views_data['table']['entity type'];
        $this->baseEntityType = \Drupal::entityTypeManager()->getDefinition($entity_type_id);
      }
      else {
        $this->baseEntityType = FALSE;
      }
    }
    return $this->baseEntityType;
  }

merlinofchaos's avatar
merlinofchaos committed
1002
  /**
1003
   * Runs the preQuery() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
1004
   */
1005
  protected function _preQuery() {
1006
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
1007 1008 1009 1010
      $handlers = &$this->$key;
      $position = 0;
      foreach ($handlers as $id => $handler) {
        $handlers[$id]->position = $position;
1011
        $handlers[$id]->preQuery();
merlinofchaos's avatar
merlinofchaos committed
1012 1013 1014 1015 1016 1017
        $position++;
      }
    }
  }

  /**
1018
   * Runs the postExecute() on all active handlers.
merlinofchaos's avatar
merlinofchaos committed
1019
   */
1020
  protected function _postExecute() {
1021
    foreach ($this::getHandlerTypes() as $key => $info) {
merlinofchaos's avatar
merlinofchaos committed
1022 1023
      $handlers = &$this->$key;
      foreach ($handlers as $id => $handler) {
1024
        $handlers[$id]->postExecute($this->result);
merlinofchaos's avatar
merlinofchaos committed
1025 1026 1027 1028 1029
      }
    }
  }

  /**
1030
   * Attaches the views handler for the specific type.
merlinofchaos's avatar
merlinofchaos committed
1031
   *
1032 1033 1034 1035 1036
   * @param string $key
   *   One of 'argument', 'field', 'sort', 'filter', 'relationship'.
   * @param array $info
   *   An array of views handler types use in the view with additional
   *   information about them.
merlinofchaos's avatar
merlinofchaos committed
1037
   */
1038
  protected function _initHandler($key, $info) {
merlinofchaos's avatar
merlinofchaos committed
1039
    // Load the requested items from the display onto the object.
1040
    $this->$key = &$this->display_handler->getHandlers($key);
merlinofchaos's avatar
merlinofchaos committed
1041 1042 1043 1044 1045 1046

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

    // Run through and test for accessibility.
    foreach ($handlers as $id => $handler) {
1047
      if (!$handler->access($this->user)) {
merlinofchaos's avatar
merlinofchaos committed
1048 1049 1050 1051 1052 1053
        unset($handlers[$id]);
      }
    }
  }

  /**
1054
   * Builds all the arguments.
1055 1056 1057
   *
   * @return bool
   *   TRUE if the arguments were built successfully, FALSE otherwise.
merlinofchaos's avatar
merlinofchaos committed
1058
   */
1059
  protected function _buildArguments() {
merlinofchaos's avatar
merlinofchaos committed
1060 1061 1062 1063 1064 1065 1066 1067
    // 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;
1068
    $substitutions = [];
merlinofchaos's avatar
merlinofchaos committed
1069 1070
    $status = TRUE;

1071 1072 1073
    // Get the title.
    $title = $this->display_handler->getOption('title');

merlinofchaos's avatar
merlinofchaos committed
1074 1075 1076
    // Iterate through each argument and process.
    foreach ($this->argument as $id => $arg) {
      $position++;
1077
      $argument = $this->argument[$id];
merlinofchaos's avatar
merlinofchaos committed
1078 1079 1080 1081 1082

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

1083
      $argument->setRelationship();
merlinofchaos's avatar
merlinofchaos committed
1084 1085 1086 1087

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

1088
      if (isset($arg) || $argument->hasDefaultArgument()) {
merlinofchaos's avatar
merlinofchaos committed
1089
        if (!isset($arg)) {
1090
          $arg = $argument->getDefaultArgument();
merlinofchaos's avatar
merlinofchaos committed
1091 1092 1093 1094 1095 1096 1097 1098 1099
          // 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.
1100
        if (!$argument->setArgument($arg)) {
1101
          $status = $argument->validateFail($arg);
merlinofchaos's avatar
merlinofchaos committed
1102 1103 1104
          break;
        }

1105
        if ($argument->isException()) {
1106
          $arg_title = $argument->exceptionTitle();
merlinofchaos's avatar
merlinofchaos committed
1107 1108
        }
        else {
1109
          $arg_title = $argument->getTitle();
1110
          $argument->query($this->display_handler->useGroupBy());
merlinofchaos's avatar
merlinofchaos committed
1111 1112 1113
        }

        // Add this argument's substitution
1114 1115
        $substitutions["{{ arguments.$id }}"] = $arg_title;
        $substitutions["{{ raw_arguments.$id }}"] = strip_tags(Html::decodeEntities($arg));
merlinofchaos's avatar
merlinofchaos committed
1116 1117 1118 1119 1120 1121 1122 1123

        // 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.
1124
        $status = $argument->defaultAction();
merlinofchaos's avatar
merlinofchaos committed
1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
        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;
  }

1143 1144 1145 1146
  /**
   * Gets the current query plugin.
   *
   * @return \Drupal\views\Plugin\views\query\QueryPluginBase
1147
   *   The current query plugin.
1148 1149 1150 1151 1152 1153 1154 1155 1156
   */
  public function getQuery() {
    if (!isset($this->query)) {
      $this->initQuery();
    }

    return $this->query;
  }

merlinofchaos's avatar
merlinofchaos committed
1157
  /**
1158 1159 1160 1161
   * Initializes the query object for the view.
   *
   * @return true
   *   Always returns TRUE.
merlinofchaos's avatar
merlinofchaos committed
1162
   */
1163
  public function initQuery() {
merlinofchaos's avatar
merlinofchaos committed
1164 1165 1166 1167 1168 1169 1170 1171 1172
    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.
1173
    $views_data = Views::viewsData()->get($this->storage->get('base_table'));
1174
    $this->storage->set('base_field', !empty($views_data['table']['base']['field']) ? $views_data['table']['base']['field'] : '');
merlinofchaos's avatar
merlinofchaos committed
1175 1176 1177 1178
    if (!empty($views_data['table']['base']['database'])) {
      $this->base_database = $views_data['table']['base']['database'];
    }

1179
    $this->query = $this->display_handler->getPlugin('query');
merlinofchaos's avatar
merlinofchaos committed
1180 1181 1182 1183
    return TRUE;
  }

  /**
1184 1185 1186 1187 1188 1189 1190 1191
   * Builds the query for the view.
   *
   * @param string $display_id
   *   The display ID of the view.
   *
   * @return bool|null
   *   TRUE if the view build process was successful, FALSE if setting the
   *   display fails or NULL if the view has been built already.
merlinofchaos's avatar
merlinofchaos committed
1192
   */
1193
  public function build($display_id = NULL) {
merlinofchaos's avatar
merlinofchaos committed
1194 1195 1196 1197 1198
    if (!empty($this->built)) {
      return;
    }

    if (empty($this->current_display) || $display_id) {
1199
      if (!$this->setDisplay($display_id)) {
merlinofchaos's avatar
merlinofchaos committed
1200 1201 1202 1203 1204
        return FALSE;
      }
    }

    // Let modules modify the view just prior to building it.
1205
    $module_handler = \Drupal::moduleHandler();
1206
    $module_handler->invokeAll('views_pre_build', [$this]);
merlinofchaos's avatar
merlinofchaos committed
1207 1208 1209 1210 1211 1212

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

    $start = microtime(TRUE);
    // If that fails, let's build!
1213
    $this->build_info = [
merlinofchaos's avatar
merlinofchaos committed
1214 1215
      'query' => '',
      'count_query' => '',