ViewUI.php 38.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\views_ui\ViewUI.
6 7
 */

8
namespace Drupal\views_ui;
9

10
use Drupal\Component\Utility\Html;
11
use Drupal\Component\Utility\Timer;
12
use Drupal\Component\Utility\Xss;
13
use Drupal\Core\EventSubscriber\AjaxResponseSubscriber;
14
use Drupal\Core\Form\FormStateInterface;
15
use Drupal\Core\Url;
16
use Drupal\views\Views;
17
use Drupal\Core\Entity\EntityStorageInterface;
18
use Drupal\views\ViewExecutable;
19
use Drupal\Core\Database\Database;
20
use Drupal\Core\Session\AccountInterface;
21
use Drupal\views\Plugin\views\query\Sql;
22
use Drupal\views\Entity\View;
23
use Drupal\views\ViewEntityInterface;
24 25 26
use Symfony\Cmf\Component\Routing\RouteObjectInterface;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
27

28 29 30
/**
 * Stores UI related temporary settings.
 */
31
class ViewUI implements ViewEntityInterface {
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

  /**
   * Indicates if a view is currently being edited.
   *
   * @var bool
   */
  public $editing = FALSE;

  /**
   * Stores an array of displays that have been changed.
   *
   * @var array
   */
  public $changed_display;

  /**
48
   * How long the view takes to render in microseconds.
49
   *
50
   * @var float
51 52 53 54 55 56
   */
  public $render_time;

  /**
   * If this view is locked for editing.
   *
57
   * If this view is locked it will contain the result of
58 59
   * \Drupal\user\SharedTempStore::getMetadata(). Which can be a stdClass or
   * NULL.
60 61
   *
   * @var stdClass
62
   */
63
  public $lock;
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86

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

  /**
   * Stores options temporarily while editing.
   *
   * @var array
   */
  public $temporary_options;

  /**
   * Stores a stack of UI forms to display.
   *
   * @var array
   */
  public $stack;

  /**
87
   * Is the view run in a context of the preview in the admin interface.
88 89 90 91
   *
   * @var bool
   */
  public $live_preview;
92

93
  public $renderPreview = FALSE;
94 95

  /**
96
   * The View storage object.
97
   *
98
   * @var \Drupal\views\ViewEntityInterface
99
   */
100
  protected $storage;
101

102 103 104 105 106 107 108 109 110
  /**
   * Stores a list of database queries run beside the main one from views.
   *
   * @var array
   *
   * @see \Drupal\Core\Database\Log
   */
  protected $additionalQueries;

111 112 113 114 115
  /**
   * Contains an array of form keys and their respective classes.
   *
   * @var array
   */
116
  public static $forms = array(
117
    'add-handler' => '\Drupal\views_ui\Form\Ajax\AddItem',
118
    'analyze' => '\Drupal\views_ui\Form\Ajax\Analyze',
119 120 121
    'handler' => '\Drupal\views_ui\Form\Ajax\ConfigHandler',
    'handler-extra' => '\Drupal\views_ui\Form\Ajax\ConfigHandlerExtra',
    'handler-group' => '\Drupal\views_ui\Form\Ajax\ConfigHandlerGroup',
122 123 124 125 126
    'display' => '\Drupal\views_ui\Form\Ajax\Display',
    'edit-details' => '\Drupal\views_ui\Form\Ajax\EditDetails',
    'rearrange' => '\Drupal\views_ui\Form\Ajax\Rearrange',
    'rearrange-filter' => '\Drupal\views_ui\Form\Ajax\RearrangeFilter',
    'reorder-displays' => '\Drupal\views_ui\Form\Ajax\ReorderDisplays',
127 128
  );

129 130 131 132 133 134 135 136
  /**
   * Whether the config is being created, updated or deleted through the
   * import process.
   *
   * @var bool
   */
  private $isSyncing = FALSE;

137 138 139 140 141 142 143
  /**
   * Whether the config is being deleted through the uninstall process.
   *
   * @var bool
   */
  private $isUninstalling = FALSE;

144
  /**
145
   * Constructs a View UI object.
146
   *
147
   * @param \Drupal\views\ViewEntityInterface $storage
148
   *   The View storage object to wrap.
149
   */
150
  public function __construct(ViewEntityInterface $storage) {
151 152
    $this->entityType = 'view';
    $this->storage = $storage;
153 154 155
  }

  /**
156
   * {@inheritdoc}
157
   */
158 159 160
  public function get($property_name, $langcode = NULL) {
    if (property_exists($this->storage, $property_name)) {
      return $this->storage->get($property_name, $langcode);
161 162
    }

163
    return isset($this->{$property_name}) ? $this->{$property_name} : NULL;
164 165
  }

166
  /**
167
   * {@inheritdoc}
168 169 170 171 172
   */
  public function setStatus($status) {
    return $this->storage->setStatus($status);
  }

173
  /**
174
   * {@inheritdoc}
175
   */
176
  public function set($property_name, $value, $notify = TRUE) {
177 178
    if (property_exists($this->storage, $property_name)) {
      $this->storage->set($property_name, $value);
179 180
    }
    else {
181
      $this->{$property_name} = $value;
182 183 184
    }
  }

185 186 187 188 189 190 191
  /**
   * {@inheritdoc}
   */
  public function setSyncing($syncing) {
    $this->isSyncing = $syncing;
  }

192 193 194 195 196 197 198
  /**
   * {@inheritdoc}
   */
  public function setUninstalling($isUninstalling) {
    $this->isUninstalling = $isUninstalling;
  }

199 200 201 202 203 204 205
  /**
   * {@inheritdoc}
   */
  public function isSyncing() {
    return $this->isSyncing;
  }

206 207 208 209 210 211 212
  /**
   * {@inheritdoc}
   */
  public function isUninstalling() {
    return $this->isUninstalling;
  }

213 214 215 216 217 218 219
  /**
   * Basic submit handler applicable to all 'standard' forms.
   *
   * This submit handler determines whether the user wants the submitted changes
   * to apply to the default display or to the current display, and dispatches
   * control appropriately.
   */
220
  public function standardSubmit($form, FormStateInterface $form_state) {
221 222 223 224 225 226 227
    // Determine whether the values the user entered are intended to apply to
    // the current display or the default display.

    list($was_defaulted, $is_defaulted, $revert) = $this->getOverrideValues($form, $form_state);

    // Based on the user's choice in the display dropdown, determine which display
    // these changes apply to.
228
    $display_id = $form_state->get('display_id');
229 230
    if ($revert) {
      // If it's revert just change the override and return.
231
      $display = &$this->getExecutable()->displayHandlers->get($display_id);
232 233 234
      $display->optionsOverride($form, $form_state);

      // Don't execute the normal submit handling but still store the changed view into cache.
235
      $this->cacheSet();
236 237 238 239 240 241 242 243 244
      return;
    }
    elseif ($was_defaulted === $is_defaulted) {
      // We're not changing which display these form values apply to.
      // Run the regular submit handler for this form.
    }
    elseif ($was_defaulted && !$is_defaulted) {
      // We were using the default display's values, but we're now overriding
      // the default display and saving values specific to this display.
245
      $display = &$this->getExecutable()->displayHandlers->get($display_id);
246 247 248 249 250 251 252 253 254
      // optionsOverride toggles the override of this section.
      $display->optionsOverride($form, $form_state);
      $display->submitOptionsForm($form, $form_state);
    }
    elseif (!$was_defaulted && $is_defaulted) {
      // We used to have an override for this display, but the user now wants
      // to go back to the default display.
      // Overwrite the default display with the current form values, and make
      // the current display use the new default values.
255
      $display = &$this->getExecutable()->displayHandlers->get($display_id);
256 257 258 259 260
      // optionsOverride toggles the override of this section.
      $display->optionsOverride($form, $form_state);
      $display->submitOptionsForm($form, $form_state);
    }

261 262
    $submit_handler = [$form_state->getFormObject(), 'submitForm'];
    call_user_func_array($submit_handler, [&$form, $form_state]);
263 264 265 266 267
  }

  /**
   * Submit handler for cancel button
   */
268
  public function standardCancel($form, FormStateInterface $form_state) {
269 270
    if (!empty($this->changed) && isset($this->form_cache)) {
      unset($this->form_cache);
271
      $this->cacheSet();
272 273
    }

274
    $form_state->setRedirectUrl($this->urlInfo('edit-form'));
275 276 277 278 279 280 281 282 283 284
  }

  /**
   * Provide a standard set of Apply/Cancel/OK buttons for the forms. Also provide
   * a hidden op operator because the forms plugin doesn't seem to properly
   * provide which button was clicked.
   *
   * TODO: Is the hidden op operator still here somewhere, or is that part of the
   * docblock outdated?
   */
285
  public function getStandardButtons(&$form, FormStateInterface $form_state, $form_id, $name = NULL) {
286 287
    $form['actions'] = array(
      '#type' => 'actions',
288 289 290 291 292 293 294 295 296 297 298 299
    );

    if (empty($name)) {
      $name = t('Apply');
      if (!empty($this->stack) && count($this->stack) > 1) {
        $name = t('Apply and continue');
      }
      $names = array(t('Apply'), t('Apply and continue'));
    }

    // Forms that are purely informational set an ok_button flag, so we know not
    // to create an "Apply" button for them.
300
    if (!$form_state->get('ok_button')) {
301
      $form['actions']['submit'] = array(
302 303
        '#type' => 'submit',
        '#value' => $name,
304
        '#id' => 'edit-submit-' . Html::getUniqueId($form_id),
305 306 307 308 309 310
        // The regular submit handler ($form_id . '_submit') does not apply if
        // we're updating the default display. It does apply if we're updating
        // the current display. Since we have no way of knowing at this point
        // which display the user wants to update, views_ui_standard_submit will
        // take care of running the regular submit handler as appropriate.
        '#submit' => array(array($this, 'standardSubmit')),
311
        '#button_type' => 'primary',
312 313
      );
      // Form API button click detection requires the button's #value to be the
314 315 316
      // same between the form build of the initial page request, and the
      // initial form build of the request processing the form submission.
      // Ideally, the button's #value shouldn't change until the form rebuild
317
      // step. However, \Drupal\views_ui\Form\Ajax\ViewsFormBase::getForm()
318 319 320 321
      // implements a different multistep form workflow than the Form API does,
      // and adjusts $view->stack prior to form processing, so we compensate by
      // extending button click detection code to support any of the possible
      // button labels.
322
      if (isset($names)) {
323
        $form['actions']['submit']['#values'] = $names;
324
        $form['actions']['submit']['#process'] = array_merge(array('views_ui_form_button_was_clicked'), \Drupal::service('element_info')->getInfoProperty($form['actions']['submit']['#type'], '#process', array()));
325 326
      }
      // If a validation handler exists for the form, assign it to this button.
327
      $form['actions']['submit']['#validate'][] = [$form_state->getFormObject(), 'validateForm'];
328 329 330 331
    }

    // Create a "Cancel" button. For purely informational forms, label it "OK".
    $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : array($this, 'standardCancel');
332
    $form['actions']['cancel'] = array(
333
      '#type' => 'submit',
334
      '#value' => !$form_state->get('ok_button') ? t('Cancel') : t('Ok'),
335 336
      '#submit' => array($cancel_submit),
      '#validate' => array(),
337
      '#limit_validation_errors' => array(),
338 339 340 341 342
    );

    // Compatibility, to be removed later: // TODO: When is "later"?
    // We used to set these items on the form, but now we want them on the $form_state:
    if (isset($form['#title'])) {
343
      $form_state->set('title', $form['#title']);
344 345
    }
    if (isset($form['#section'])) {
346
      $form_state->set('#section', $form['#section']);
347 348 349 350 351 352 353 354
    }
    // Finally, we never want these cached -- our object cache does that for us.
    $form['#no_cache'] = TRUE;
  }

  /**
   * Return the was_defaulted, is_defaulted and revert state of a form.
   */
355
  public function getOverrideValues($form, FormStateInterface $form_state) {
356
    // Make sure the dropdown exists in the first place.
357
    if ($form_state->hasValue(array('override', 'dropdown'))) {
358 359 360
      // #default_value is used to determine whether it was the default value or not.
      // So the available options are: $display, 'default' and 'default_revert', not 'defaults'.
      $was_defaulted = ($form['override']['dropdown']['#default_value'] === 'defaults');
361 362 363
      $dropdown = $form_state->getValue(array('override', 'dropdown'));
      $is_defaulted = ($dropdown === 'default');
      $revert = ($dropdown === 'default_revert');
364 365 366 367

      if ($was_defaulted !== $is_defaulted && isset($form['#section'])) {
        // We're changing which display these values apply to.
        // Update the #section so it knows what to mark changed.
368
        $form['#section'] = str_replace('default-', $form_state->get('display_id') . '-', $form['#section']);
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
      }
    }
    else {
      // The user didn't get the dropdown for overriding the default display.
      $was_defaulted = FALSE;
      $is_defaulted = FALSE;
      $revert = FALSE;
    }

    return array($was_defaulted, $is_defaulted, $revert);
  }

  /**
   * Add another form to the stack; clicking 'apply' will go to this form
   * rather than closing the ajax popup.
   */
385
  public function addFormToStack($key, $display_id, $type, $id = NULL, $top = FALSE, $rebuild_keys = FALSE) {
386 387 388
    // Reset the cache of IDs. Drupal rather aggressively prevents ID
    // duplication but this causes it to remember IDs that are no longer even
    // being used.
389
    Html::resetSeenIds();
390

391 392 393 394
    if (empty($this->stack)) {
      $this->stack = array();
    }

395
    $stack = array(implode('-', array_filter(array($key, $this->id(), $display_id, $type, $id))), $key, $display_id, $type, $id);
396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
    // If we're being asked to add this form to the bottom of the stack, no
    // special logic is required. Our work is equally easy if we were asked to add
    // to the top of the stack, but there's nothing in it yet.
    if (!$top || empty($this->stack)) {
      $this->stack[] = $stack;
    }
    // If we're adding to the top of an existing stack, we have to maintain the
    // existing integer keys, so they can be used for the "2 of 3" progress
    // indicator (which will now read "2 of 4").
    else {
      $keys = array_keys($this->stack);
      $first = current($keys);
      $last = end($keys);
      for ($i = $last; $i >= $first; $i--) {
        if (!isset($this->stack[$i])) {
          continue;
        }
        // Move form number $i to the next position in the stack.
        $this->stack[$i + 1] = $this->stack[$i];
        unset($this->stack[$i]);
      }
      // Now that the previously $first slot is free, move the new form into it.
      $this->stack[$first] = $stack;
      ksort($this->stack);

      // Start the keys from 0 again, if requested.
      if ($rebuild_keys) {
        $this->stack = array_values($this->stack);
      }
    }
  }

  /**
   * Submit handler for adding new item(s) to a view.
   */
431
  public function submitItemAdd($form, FormStateInterface $form_state) {
432
    $type = $form_state->get('type');
433
    $types = ViewExecutable::getHandlerTypes();
434
    $section = $types[$type]['plural'];
435
    $display_id = $form_state->get('display_id');
436 437 438 439 440 441

    // Handle the override select.
    list($was_defaulted, $is_defaulted) = $this->getOverrideValues($form, $form_state);
    if ($was_defaulted && !$is_defaulted) {
      // We were using the default display's values, but we're now overriding
      // the default display and saving values specific to this display.
442
      $display = &$this->getExecutable()->displayHandlers->get($display_id);
443 444 445 446 447 448 449 450
      // setOverride toggles the override of this section.
      $display->setOverride($section);
    }
    elseif (!$was_defaulted && $is_defaulted) {
      // We used to have an override for this display, but the user now wants
      // to go back to the default display.
      // Overwrite the default display with the current form values, and make
      // the current display use the new default values.
451
      $display = &$this->getExecutable()->displayHandlers->get($display_id);
452 453 454 455
      // optionsOverride toggles the override of this section.
      $display->setOverride($section);
    }

456
    if (!$form_state->isValueEmpty('name') && is_array($form_state->getValue('name'))) {
457
      // Loop through each of the items that were checked and add them to the view.
458
      foreach (array_keys(array_filter($form_state->getValue('name'))) as $field) {
459 460 461 462 463
        list($table, $field) = explode('.', $field, 2);

        if ($cut = strpos($field, '$')) {
          $field = substr($field, 0, $cut);
        }
464
        $id = $this->getExecutable()->addHandler($display_id, $type, $table, $field);
465 466 467 468 469 470 471

        // check to see if we have group by settings
        $key = $type;
        // Footer,header and empty text have a different internal handler type(area).
        if (isset($types[$type]['type'])) {
          $key = $types[$type]['type'];
        }
472 473 474 475
        $item = array(
          'table' => $table,
          'field' => $field,
        );
476
        $handler = Views::handlerManager($key)->getHandler($item);
477
        if ($this->getExecutable()->displayHandlers->get('default')->useGroupBy() && $handler->usesGroupBy()) {
478
          $this->addFormToStack('handler-group', $display_id, $type, $id);
479 480 481 482
        }

        // check to see if this type has settings, if so add the settings form first
        if ($handler && $handler->hasExtraOptions()) {
483
          $this->addFormToStack('handler-extra', $display_id, $type, $id);
484 485
        }
        // Then add the form to the stack
486
        $this->addFormToStack('handler', $display_id, $type, $id);
487 488 489 490 491 492 493 494
      }
    }

    if (isset($this->form_cache)) {
      unset($this->form_cache);
    }

    // Store in cache
495
    $this->cacheSet();
496 497
  }

498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
  /**
   * Set up query capturing.
   *
   * \Drupal\Core\Database\Database stores the queries that it runs, if logging
   * is enabled.
   *
   * @see ViewUI::endQueryCapture()
   */
  public function startQueryCapture() {
    Database::startLog('views');
  }

  /**
   * Add the list of queries run during render to buildinfo.
   *
   * @see ViewUI::startQueryCapture()
   */
  public function endQueryCapture() {
    $queries = Database::getLog('views');

    $this->additionalQueries = $queries;
  }

521 522
  public function renderPreview($display_id, $args = array()) {
    // Save the current path so it can be restored before returning from this function.
523 524
    $request_stack = \Drupal::requestStack();
    $current_request = $request_stack->getCurrentRequest();
525
    $executable = $this->getExecutable();
526 527

    // Determine where the query and performance statistics should be output.
528
    $config = \Drupal::config('views.settings');
529 530 531 532 533 534 535 536 537 538 539 540 541
    $show_query = $config->get('ui.show.sql_query.enabled');
    $show_info = $config->get('ui.show.preview_information');
    $show_location = $config->get('ui.show.sql_query.where');

    $show_stats = $config->get('ui.show.performance_statistics');
    if ($show_stats) {
      $show_stats = $config->get('ui.show.sql_query.where');
    }

    $combined = $show_query && $show_stats;

    $rows = array('query' => array(), 'statistics' => array());

542
    $errors = $executable->validate();
543
    $executable->destroy();
544
    if (empty($errors)) {
545
      $this->ajax = TRUE;
546
      $executable->live_preview = TRUE;
547

548
      // AJAX happens via HTTP POST but everything expects exposed data to
549 550
      // be in GET. Copy stuff but remove ajax-framework specific keys.
      // If we're clicking on links in a preview, though, we could actually
551 552 553
      // have some input in the query parameters, so we merge request() and
      // query() to ensure we get it all.
      $exposed_input = array_merge(\Drupal::request()->request->all(), \Drupal::request()->query->all());
554
      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER, 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) {
555 556 557 558
        if (isset($exposed_input[$key])) {
          unset($exposed_input[$key]);
        }
      }
559
      $executable->setExposedInput($exposed_input);
560

561
      if (!$executable->setDisplay($display_id)) {
562 563 564
        return [
          '#markup' => t('Invalid display id @display', array('@display' => $display_id)),
        ];
565 566
      }

567
      $executable->setArguments($args);
568 569

      // Store the current view URL for later use:
570
      if ($executable->hasUrl() && $executable->display_handler->getOption('path')) {
571
        $path = $executable->getUrl();
572 573 574 575
      }

      // Make view links come back to preview.

576 577 578
      // Also override the current path so we get the pager, and make sure the
      // Request object gets all of the proper values from $_SERVER.
      $request = Request::createFromGlobals();
579 580 581 582 583 584 585 586 587 588 589
      $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'entity.view.preview_form');
      $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, \Drupal::service('router.route_provider')->getRouteByName('entity.view.preview_form'));
      $request->attributes->set('view', $this->storage);
      $request->attributes->set('display_id', $display_id);
      $raw_parameters = new ParameterBag();
      $raw_parameters->set('view', $this->id());
      $raw_parameters->set('display_id', $display_id);
      $request->attributes->set('_raw_variables', $raw_parameters);

      foreach ($args as $key => $arg) {
        $request->attributes->set('arg_' . $key, $arg);
590
      }
591
      $request_stack->push($request);
592 593 594 595 596 597

      // Suppress contextual links of entities within the result set during a
      // Preview.
      // @todo We'll want to add contextual links specific to editing the View, so
      //   the suppression may need to be moved deeper into the Preview pipeline.
      views_ui_contextual_links_suppress_push();
598 599 600

      $show_additional_queries = $config->get('ui.show.additional_queries');

601
      Timer::start('entity.view.preview_form');
602 603 604 605 606 607

      if ($show_additional_queries) {
        $this->startQueryCapture();
      }

      // Execute/get the view preview.
608
      $preview = $executable->preview($display_id, $args);
609 610 611 612 613

      if ($show_additional_queries) {
        $this->endQueryCapture();
      }

614
      $this->render_time = Timer::stop('entity.view.preview_form')['time'];
615

616 617 618 619
      views_ui_contextual_links_suppress_pop();

      // Prepare the query information and statistics to show either above or
      // below the view preview.
620 621 622
      // Initialise the empty rows arrays so we can safely merge them later.
      $rows['query'] = [];
      $rows['statistics'] = [];
623 624
      if ($show_info || $show_query || $show_stats) {
        // Get information from the preview for display.
625
        if (!empty($executable->build_info['query'])) {
626
          if ($show_query) {
627
            $query_string = $executable->build_info['query'];
628 629 630
            // Only the sql default class has a method getArguments.
            $quoted = array();

631
            if ($executable->query instanceof Sql) {
632
              $quoted = $query_string->getArguments();
633 634 635 636 637 638 639 640 641 642
              $connection = Database::getConnection();
              foreach ($quoted as $key => $val) {
                if (is_array($val)) {
                  $quoted[$key] = implode(', ', array_map(array($connection, 'quote'), $val));
                }
                else {
                  $quoted[$key] = $connection->quote($val);
                }
              }
            }
643
            $rows['query'][] = array(
644 645 646 647 648 649 650 651 652 653 654 655 656
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => "<strong>{% trans 'Query' %}</strong>",
                ),
              ),
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => '<pre>{{ query }}</pre>',
                  '#context' => array('query' => strtr($query_string, $quoted)),
                ),
              ),
657
            );
658
            if (!empty($this->additionalQueries)) {
659 660 661 662 663
              $queries[] = array(
                '#prefix' => '<strong>',
                '#markup' => t('These queries were run during view rendering:'),
                '#suffix' => '</strong>',
              );
664 665
              foreach ($this->additionalQueries as $query) {
                $query_string = strtr($query['query'], $query['args']);
666 667 668 669
                $queries[] = array(
                  '#prefix' => "\n",
                  '#markup' => t('[@time ms] @query', array('@time' => round($query['time'] * 100000, 1) / 100000.0, '@query' => $query_string)),
                );
670 671
              }

672
              $rows['query'][] = array(
673 674 675 676 677 678
                array(
                  'data' => array(
                    '#type' => 'inline_template',
                    '#template' => "<strong>{% trans 'Other queries' %}</strong>",
                  ),
                ),
679 680 681 682 683 684 685
                array(
                  'data' => array(
                    '#prefix' => '<pre>',
                     'queries' => $queries,
                     '#suffix' => '</pre>',
                    ),
                ),
686
              );
687 688 689
            }
          }
          if ($show_info) {
690
            $rows['query'][] = array(
691 692 693 694 695 696
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => "<strong>{% trans 'Title' %}</strong>",
                ),
              ),
697
              Xss::filterAdmin($executable->getTitle()),
698
            );
699
            if (isset($path)) {
700 701
              // @todo Views should expect and store a leading /. See:
              //   https://www.drupal.org/node/2423913
702
              $path = \Drupal::l($path->toString(), $path);
703 704 705 706
            }
            else {
              $path = t('This display has no path.');
            }
707 708 709 710 711 712 713 714 715 716 717 718 719 720
            $rows['query'][] = array(
              array(
                'data' => array(
                  '#prefix' => '<strong>',
                  '#markup' => t('Path'),
                  '#suffix' => '</strong>',
                ),
              ),
              array(
                'data' => array(
                  '#markup' => $path,
                ),
              )
            );
721 722
          }
          if ($show_stats) {
723
            $rows['statistics'][] = array(
724 725 726 727 728 729
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => "<strong>{% trans 'Query build time' %}</strong>",
                ),
              ),
730
              t('@time ms', array('@time' => intval($executable->build_time * 100000) / 100)),
731 732 733
            );

            $rows['statistics'][] = array(
734 735 736 737 738 739
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => "<strong>{% trans 'Query execute time' %}</strong>",
                ),
              ),
740
              t('@time ms', array('@time' => intval($executable->execute_time * 100000) / 100)),
741
            );
742

743
            $rows['statistics'][] = array(
744 745 746 747 748 749
              array(
                'data' => array(
                  '#type' => 'inline_template',
                  '#template' => "<strong>{% trans 'View render time' %}</strong>",
                ),
              ),
750
              t('@time ms', array('@time' => intval($this->render_time * 100) / 100)),
751
            );
752
          }
753
          \Drupal::moduleHandler()->alter('views_preview_info', $rows, $executable);
754 755 756 757 758
        }
        else {
          // No query was run. Display that information in place of either the
          // query or the performance statistics, whichever comes first.
          if ($combined || ($show_location === 'above')) {
759 760 761 762 763 764 765 766 767 768 769 770 771 772
            $rows['query'][] = array(
              array(
                'data' => array(
                  '#prefix' => '<strong>',
                  '#markup' => t('Query'),
                  '#suffix' => '</strong>',
                ),
              ),
              array(
                'data' => array(
                  '#markup' => t('No query was run'),
                ),
              ),
            );
773 774
          }
          else {
775 776 777 778 779 780 781 782 783 784 785 786 787 788
            $rows['statistics'][] = array(
              array(
                'data' => array(
                  '#prefix' => '<strong>',
                  '#markup' => t('Query'),
                  '#suffix' => '</strong>',
                ),
              ),
              array(
                'data' => array(
                  '#markup' => t('No query was run'),
                ),
              ),
            );
789 790 791 792 793
          }
        }
      }
    }
    else {
794 795 796 797
      foreach ($errors as $display_errors) {
        foreach ($display_errors as $error) {
          drupal_set_message($error, 'error');
        }
798
      }
799
      $preview = ['#markup' => t('Unable to preview due to validation errors.')];
800 801 802 803
    }

    // Assemble the preview, the query info, and the query statistics in the
    // requested order.
804
    $table = array(
805
      '#type' => 'table',
806 807
      '#prefix' => '<div class="views-query-info">',
      '#suffix' => '</div>',
808
      '#rows' => array_merge($rows['query'], $rows['statistics']),
809
    );
810

811
    if ($show_location == 'above') {
812 813 814 815
      $output = [
        'table' => $table,
        'preview' => $preview,
      ];
816
    }
817
    else {
818 819 820 821
      $output = [
        'preview' => $preview,
        'table' => $table,
      ];
822 823
    }

824 825 826 827 828
    // Ensure that we just remove an additional request we pushed earlier.
    // This could happen if $errors was not empty.
    if ($request_stack->getCurrentRequest() != $current_request) {
      $request_stack->pop();
    }
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
    return $output;
  }

  /**
   * Get the user's current progress through the form stack.
   *
   * @return
   *   FALSE if the user is not currently in a multiple-form stack. Otherwise,
   *   an associative array with the following keys:
   *   - current: The number of the current form on the stack.
   *   - total: The total number of forms originally on the stack.
   */
  public function getFormProgress() {
    $progress = FALSE;
    if (!empty($this->stack)) {
      // The forms on the stack have integer keys that don't change as the forms
      // are completed, so we can see which ones are still left.
      $keys = array_keys($this->stack);
      // Add 1 to the array keys for the benefit of humans, who start counting
      // from 1 and not 0.
      $current = reset($keys) + 1;
      $total = end($keys) + 1;
      if ($total > 1) {
        $progress = array();
        $progress['current'] = $current;
        $progress['total'] = $total;
      }
    }
    return $progress;
  }

860 861 862 863 864 865 866 867 868 869 870 871
  /**
   * Sets a cached view object in the user tempstore.
   */
  public function cacheSet() {
    if ($this->isLocked()) {
      drupal_set_message(t('Changes cannot be made to a locked view.'), 'error');
      return;
    }

    // Let any future object know that this view has changed.
    $this->changed = TRUE;

872
    $executable = $this->getExecutable();
873 874 875
    if (isset($executable->current_display)) {
      // Add the knowledge of the changed display, too.
      $this->changed_display[$executable->current_display] = TRUE;
876
      $executable->current_display = NULL;
877 878
    }

879 880 881
    // Unset handlers. We don't want to write these into the cache.
    $executable->display_handler = NULL;
    $executable->default_display = NULL;
882
    $executable->query = NULL;
883
    $executable->displayHandlers = NULL;
884
    \Drupal::service('user.shared_tempstore')->get('views')->set($this->id(), $this);
885 886 887 888 889 890 891 892 893
  }

  /**
   * Returns whether the current view is locked.
   *
   * @return bool
   *   TRUE if the view is locked, FALSE otherwise.
   */
  public function isLocked() {
894
    return is_object($this->lock) && ($this->lock->owner != \Drupal::currentUser()->id());
895 896
  }

897
  /**
898 899 900 901 902 903
   * Passes through all unknown calls onto the storage object.
   */
  public function __call($method, $args) {
    return call_user_func_array(array($this->storage, $method), $args);
  }

904 905 906 907 908 909 910
  /**
   * {@inheritdoc}
   */
  public function &getDisplay($display_id) {
    return $this->storage->getDisplay($display_id);
  }

911
  /**
912
   * {@inheritdoc}
913 914
   */
  public function id() {
915
    return $this->storage->id();
916 917 918
  }

  /**
919
   * {@inheritdoc}
920 921
   */
  public function uuid() {
922
    return $this->storage->uuid();
923 924 925
  }

  /**
926
   * {@inheritdoc}
927 928
   */
  public function isNew() {
929
    return $this->storage->isNew();
930 931 932
  }

  /**
933
   * {@inheritdoc}
934
   */
935 936
  public function getEntityTypeId() {
    return $this->storage->getEntityTypeId();
937 938 939
  }

  /**
940
   * {@inheritdoc}
941 942
   */
  public function bundle() {
943
    return $this->storage->bundle();
944 945 946
  }

  /**
947
   * {@inheritdoc}
948
   */
949 950
  public function getEntityType() {
    return $this->storage->getEntityType();
951 952 953
  }

  /**
954
   * {@inheritdoc}
955 956
   */
  public function createDuplicate() {
957
    return $this->storage->createDuplicate();
958 959
  }

960 961 962 963 964 965 966 967 968 969 970 971 972 973
  /**
   * {@inheritdoc}
   */
  public static function load($id) {
    return View::load($id);
  }

  /**
   * {@inheritdoc}
   */
  public static function loadMultiple(array $ids = NULL) {
    return View::loadMultiple($ids);
  }

974 975 976 977 978 979 980
  /**
   * {@inheritdoc}
   */
  public static function create(array $values = array()) {
    return View::create($values);
  }

981
  /**
982
   * {@inheritdoc}
983 984
   */
  public function delete() {
985
    return $this->storage->delete();
986 987 988
  }

  /**
989
   * {@inheritdoc}
990 991
   */
  public function save() {
992
    return $this->storage->save();
993 994 995
  }

  /**
996
   * {@inheritdoc}
997
   */
998 999
  public function urlInfo($rel = 'edit-form', array $options = []) {
    return $this->storage->urlInfo($rel, $options);
1000 1001
  }

1002 1003 1004 1005 1006 1007 1008
  /**
   * {@inheritdoc}
   */
  public function toUrl($rel = 'edit-form', array $options = []) {
    return $this->storage->toUrl($rel, $options);
  }

1009 1010 1011 1012 1013 1014 1015
  /**
   * {@inheritdoc}
   */
  public function link($text = NULL, $rel = 'edit-form', array $options = []) {
    return $this->storage->link($text, $rel, $options);
  }

1016 1017 1018 1019 1020 1021 1022
  /**
   * {@inheritdoc}
   */
  public function toLink($text = NULL, $rel = 'edit-form', array $options = []) {
    return $this->storage->toLink($text, $rel, $options);
  }

1023
  /**
1024
   * {@inheritdoc}
1025
   */
1026 1027
  public function label() {
    return $this->storage->label();
1028 1029 1030
  }

  /**
1031
   * {@inheritdoc}
1032 1033
   */
  public function enforceIsNew($value = TRUE) {
1034
    return $this->storage->enforceIsNew($value);
1035 1036
  }

1037
  /**
1038
   * {@inheritdoc}
1039
   */
1040 1041
  public function toArray() {
    return $this->storage->toArray();
1042 1043
  }

1044
  /**
1045
   * {@inheritdoc}
1046 1047
   */
  public function language() {
1048
    return $this->storage->language();
1049 1050 1051
  }

  /**
1052
   * {@inheritdoc}
1053
   */
1054 1055
  public function access($operation = 'view', AccountInterface $account = NULL, $return_as_object = FALSE) {
    return $this->storage->access($operation, $account, $return_as_object);
1056 1057 1058
  }

  /**
1059
   * {@inheritdoc}
1060 1061
   */
  public function enable() {
1062
    return $this->storage->enable();
1063 1064 1065
  }

  /**
1066
   * {@inheritdoc}
1067 1068
   */
  public function disable() {
1069
    return $this->storage->disable();
1070 1071 1072
  }

  /**
1073
   * {@inheritdoc}
1074
   */
1075
  public function status() {
1076
    return $this->storage->status();
1077 1078 1079
  }

  /**
1080
   * {@inheritdoc}
1081
   */
1082 1083
  public function getOriginalId() {
    return $this->storage->getOriginalId();
1084 1085 1086
  }

  /**
1087
   * {@inheritdoc}
1088
   */
1089 1090
  public function setOriginalId($id) {
    return $this->storage->setOriginalId($id);
1091 1092
  }

1093 1094 1095
  /**
   * {@inheritdoc}
   */
1096 1097
  public function preSave(EntityStorageInterface $storage) {
    $this->storage->presave($storage);
1098 1099 1100 1101 1102
  }

  /**
   * {@inheritdoc}
   */
1103 1104
  public function postSave(EntityStorageInterface $storage, $update = TRUE) {
    $this->storage->postSave($storage, $update);
1105 1106 1107 1108 1109
  }

  /**
   * {@inheritdoc}
   */
1110
  public static function preCreate(EntityStorageInterface $storage, array &$values) {
1111 1112
  }

1113 1114 1115
  /**
   * {@inheritdoc}
   */
1116 1117
  public function postCreate(EntityStorageInterface $storage) {
    $this->storage->postCreate($storage);
1118 1119 1120 1121 1122
  }

  /**
   * {@inheritdoc}
   */
1123
  public static function preDelete(EntityStorageInterface $storage, array $entities) {
1124
  }
1125

1126 1127 1128
  /**
   * {@inheritdoc}
   */
1129
  public static function postDelete(EntityStorageInterface $storage, array $entities) {
1130 1131 1132 1133 1134
  }

  /**
   * {@inheritdoc}
   */
1135
  public static function postLoad(EntityStorageInterface $storage, array &$entities) {
1136 1137
  }

1138 1139 1140 1141