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

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

8
namespace Drupal\views_ui;
9

10
use Drupal\views\ViewExecutable;
11
use Drupal\Core\Database\Database;
12
use Drupal\Core\TypedData\ContextAwareInterface;
13
use Drupal\views\Plugin\views\query\Sql;
14 15
use Drupal\views\Plugin\Core\Entity\View;
use Drupal\views\ViewStorageInterface;
16

17 18 19
/**
 * Stores UI related temporary settings.
 */
20
class ViewUI implements ViewStorageInterface {
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

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

  /**
   * Stores an array of errors for any displays.
   *
   * @var array
   */
  public $display_errors;

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

  /**
   * How long the view takes to build.
   *
   * @var int
   */
  public $build_time;

  /**
   * How long the view takes to render.
   *
   * @var int
   */
  public $render_time;

  /**
   * How long the view takes to execute.
   *
   * @var int
   */
  public $execute_time;

  /**
   * If this view is locked for editing.
   *
   * @var bool
   */
  public $locked;

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

  /**
   * Is the view runned in a context of the preview in the admin interface.
   *
   * @var bool
   */
  public $live_preview;
98

99
  public $displayID;
100

101
  public $renderPreview = FALSE;
102 103

  /**
104
   * The View storage object.
105
   *
106
   * @var \Drupal\views\Plugin\Core\Entity\View
107
   */
108
  protected $storage;
109 110

  /**
111
   * The View executable object.
112
   *
113
   * @var \Drupal\views\ViewExecutable
114
   */
115
  protected $executable;
116

117 118 119 120 121 122 123 124 125
  /**
   * Stores a list of database queries run beside the main one from views.
   *
   * @var array
   *
   * @see \Drupal\Core\Database\Log
   */
  protected $additionalQueries;

126
  /**
127
   * Constructs a View UI object.
128
   *
129 130
   * @param \Drupal\views\ViewStorageInterface $storage
   *   The View storage object to wrap.
131
   */
132 133 134 135
  public function __construct(ViewStorageInterface $storage) {
    $this->entityType = 'view';
    $this->storage = $storage;
    $this->executable = $storage->get('executable');
136 137 138
  }

  /**
139
   * Overrides \Drupal\Core\Config\Entity\ConfigEntityBase::get().
140
   */
141 142 143
  public function get($property_name, $langcode = NULL) {
    if (property_exists($this->storage, $property_name)) {
      return $this->storage->get($property_name, $langcode);
144 145
    }

146
    return isset($this->{$property_name}) ? $this->{$property_name} : NULL;
147 148 149
  }

  /**
150
   * Overrides \Drupal\Core\Config\Entity\ConfigEntityBase::set().
151
   */
152 153 154
  public function set($property_name, $value) {
    if (property_exists($this->storage, $property_name)) {
      $this->storage->set($property_name, $value);
155 156
    }
    else {
157
      $this->{$property_name} = $value;
158 159 160
    }
  }

161 162
  public static function getDefaultAJAXMessage() {
    return '<div class="message">' . t("Click on an item to edit that item's details.") . '</div>';
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
  }

  /**
   * 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.
   */
  public function standardSubmit($form, &$form_state) {
    // 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.
    if ($revert) {
      // If it's revert just change the override and return.
182
      $display = &$this->executable->displayHandlers->get($form_state['display_id']);
183 184 185 186 187 188 189 190 191 192 193 194 195
      $display->optionsOverride($form, $form_state);

      // Don't execute the normal submit handling but still store the changed view into cache.
      views_ui_cache_set($this);
      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.
196
      $display = &$this->executable->displayHandlers->get($form_state['display_id']);
197 198 199 200 201 202 203 204 205
      // 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.
206
      $display = &$this->executable->displayHandlers->get($form_state['display_id']);
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
      // optionsOverride toggles the override of this section.
      $display->optionsOverride($form, $form_state);
      $display->submitOptionsForm($form, $form_state);
    }

    $submit_handler = $form['#form_id'] . '_submit';
    if (function_exists($submit_handler)) {
      $submit_handler($form, $form_state);
    }
  }

  /**
   * Submit handler for cancel button
   */
  public function standardCancel($form, &$form_state) {
    if (!empty($this->changed) && isset($this->form_cache)) {
      unset($this->form_cache);
      views_ui_cache_set($this);
    }

227
    $form_state['redirect'] = 'admin/structure/views/view/' . $this->id() . '/edit';
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263
  }

  /**
   * 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?
   */
  public function getStandardButtons(&$form, &$form_state, $form_id, $name = NULL, $third = NULL, $submit = NULL) {
    $form['buttons'] = array(
      '#prefix' => '<div class="clearfix"><div class="form-buttons">',
      '#suffix' => '</div></div>',
    );

    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.
    if (empty($form_state['ok_button'])) {
      $form['buttons']['submit'] = array(
        '#type' => 'submit',
        '#value' => $name,
        // 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')),
264
        '#button_type' => 'primary',
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 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
      );
      // Form API button click detection requires the button's #value to be the
      // 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 step. However,
      // views_ui_ajax_form() 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.
      if (isset($names)) {
        $form['buttons']['submit']['#values'] = $names;
        $form['buttons']['submit']['#process'] = array_merge(array('views_ui_form_button_was_clicked'), element_info_property($form['buttons']['submit']['#type'], '#process', array()));
      }
      // If a validation handler exists for the form, assign it to this button.
      if (function_exists($form_id . '_validate')) {
        $form['buttons']['submit']['#validate'][] = $form_id . '_validate';
      }
    }

    // Create a "Cancel" button. For purely informational forms, label it "OK".
    $cancel_submit = function_exists($form_id . '_cancel') ? $form_id . '_cancel' : array($this, 'standardCancel');
    $form['buttons']['cancel'] = array(
      '#type' => 'submit',
      '#value' => empty($form_state['ok_button']) ? t('Cancel') : t('Ok'),
      '#submit' => array($cancel_submit),
      '#validate' => array(),
    );

    // Some forms specify a third button, with a name and submit handler.
    if ($third) {
      if (empty($submit)) {
        $submit = 'third';
      }
      $third_submit = function_exists($form_id . '_' . $submit) ? $form_id . '_' . $submit : array($this, 'standardCancel');

      $form['buttons'][$submit] = array(
        '#type' => 'submit',
        '#value' => $third,
        '#validate' => array(),
        '#submit' => array($third_submit),
      );
    }

    // 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'])) {
      $form_state['title'] = $form['#title'];
    }
    if (isset($form['#url'])) {
      $form_state['url'] = $form['#url'];
    }
    if (isset($form['#section'])) {
      $form_state['#section'] = $form['#section'];
    }
    // Finally, we never want these cached -- our object cache does that for us.
    $form['#no_cache'] = TRUE;

    // If this isn't an ajaxy form, then we want to set the title.
    if (!empty($form['#title'])) {
      drupal_set_title($form['#title']);
    }
  }

  /**
   * Return the was_defaulted, is_defaulted and revert state of a form.
   */
  public function getOverrideValues($form, $form_state) {
    // Make sure the dropdown exists in the first place.
    if (isset($form_state['values']['override']['dropdown'])) {
      // #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');
      $is_defaulted = ($form_state['values']['override']['dropdown'] === 'default');
      $revert = ($form_state['values']['override']['dropdown'] === 'default_revert');

      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.
        $form['#section'] = str_replace('default-', $form_state['display_id'] . '-', $form['#section']);
      }
    }
    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);
  }

  /**
   * Submit handler to break_lock a view.
   */
  public function submitBreakLock(&$form, &$form_state) {
360 361
    drupal_container()->get('user.tempstore')->get('views')->delete($this->id());
    $form_state['redirect'] = 'admin/structure/views/view/' . $this->id() . '/edit';
362 363 364 365 366 367 368 369 370 371 372 373 374
    drupal_set_message(t('The lock has been broken and you may now edit this view.'));
  }

  /**
   * Form constructor callback to reorder displays on a view
   */
  public function buildDisplaysReorderForm($form, &$form_state) {
    $display_id = $form_state['display_id'];

    $form['view'] = array('#type' => 'value', '#value' => $this);

    $form['#tree'] = TRUE;

375
    $count = count($this->get('display'));
376

377
    $displays = $this->get('display');
378
    uasort($displays, array('static', 'sortPosition'));
379
    $this->set('display', $displays);
380
    foreach ($displays as $display) {
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 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
      $form[$display['id']] = array(
        'title'  => array('#markup' => $display['display_title']),
        'weight' => array(
          '#type' => 'weight',
          '#value' => $display['position'],
          '#delta' => $count,
          '#title' => t('Weight for @display', array('@display' => $display['display_title'])),
          '#title_display' => 'invisible',
        ),
        '#tree' => TRUE,
        '#display' => $display,
        'removed' => array(
          '#type' => 'checkbox',
          '#id' => 'display-removed-' . $display['id'],
          '#attributes' => array('class' => array('views-remove-checkbox')),
          '#default_value' => isset($display['deleted']),
        ),
      );

      if (isset($display['deleted']) && $display['deleted']) {
        $form[$display['id']]['deleted'] = array('#type' => 'value', '#value' => TRUE);
      }
      if ($display['id'] === 'default') {
        unset($form[$display['id']]['weight']);
        unset($form[$display['id']]['removed']);
      }

    }

    $form['#title'] = t('Displays Reorder');
    $form['#section'] = 'reorder';

    // Add javascript settings that will be added via $.extend for tabledragging
    $form['#js']['tableDrag']['reorder-displays']['weight'][0] = array(
      'target' => 'weight',
      'source' => NULL,
      'relationship' => 'sibling',
      'action' => 'order',
      'hidden' => TRUE,
      'limit' => 0,
    );

423
    $form['#action'] = url('admin/structure/views/nojs/reorder-displays/' . $this->id() . '/' . $display_id);
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453

    $this->getStandardButtons($form, $form_state, 'views_ui_reorder_displays_form');
    $form['buttons']['submit']['#submit'] = array(array($this, 'submitDisplaysReorderForm'));

    return $form;
  }

  /**
   * Submit handler for rearranging display form
   */
  public function submitDisplaysReorderForm($form, &$form_state) {
    foreach ($form_state['input'] as $display => $info) {
      // add each value that is a field with a weight to our list, but only if
      // it has had its 'removed' checkbox checked.
      if (is_array($info) && isset($info['weight']) && empty($info['removed'])) {
        $order[$display] = $info['weight'];
      }
    }

    // Sort the order array
    asort($order);

    // Fixing up positions
    $position = 1;

    foreach (array_keys($order) as $display) {
      $order[$display] = $position++;
    }

    // Setting up position and removing deleted displays
454
    $displays = $this->get('display');
455 456 457
    foreach ($displays as $display_id => $display) {
      // Don't touch the default !!!
      if ($display_id === 'default') {
458
        $displays[$display_id]['position'] = 0;
459 460 461
        continue;
      }
      if (isset($order[$display_id])) {
462
        $displays[$display_id]['position'] = $order[$display_id];
463 464
      }
      else {
465
        $displays[$display_id]['deleted'] = TRUE;
466 467 468 469
      }
    }

    // Sorting back the display array as the position is not enough
470
    uasort($displays, array('static', 'sortPosition'));
471
    $this->set('display', $displays);
472 473 474

    // Store in cache
    views_ui_cache_set($this);
475
    $form_state['redirect'] = array('admin/structure/views/view/' . $this->id() . '/edit', array('fragment' => 'views-tab-default'));
476 477 478 479 480 481 482
  }

  /**
   * Add another form to the stack; clicking 'apply' will go to this form
   * rather than closing the ajax popup.
   */
  public function addFormToStack($key, $display_id, $args, $top = FALSE, $rebuild_keys = FALSE) {
483 484 485 486 487 488
    // 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.
    $seen_ids_init = &drupal_static('drupal_html_id:init');
    $seen_ids_init = array();

489 490 491 492
    if (empty($this->stack)) {
      $this->stack = array();
    }

493
    $stack = array($this->buildIdentifier($key, $display_id, $args), $key, $display_id, $args);
494 495 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 521 522 523 524 525 526 527 528 529 530
    // 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.
   */
  public function submitItemAdd($form, &$form_state) {
    $type = $form_state['type'];
531
    $types = ViewExecutable::viewsHandlerTypes();
532 533 534 535 536 537 538
    $section = $types[$type]['plural'];

    // 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.
539
      $display = &$this->executable->displayHandlers->get($form_state['display_id']);
540 541 542 543 544 545 546 547
      // 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.
548
      $display = &$this->executable->displayHandlers->get($form_state['display_id']);
549 550 551 552 553 554 555 556 557 558 559 560
      // optionsOverride toggles the override of this section.
      $display->setOverride($section);
    }

    if (!empty($form_state['values']['name']) && is_array($form_state['values']['name'])) {
      // Loop through each of the items that were checked and add them to the view.
      foreach (array_keys(array_filter($form_state['values']['name'])) as $field) {
        list($table, $field) = explode('.', $field, 2);

        if ($cut = strpos($field, '$')) {
          $field = substr($field, 0, $cut);
        }
561
        $id = $this->executable->addItem($form_state['display_id'], $type, $table, $field);
562 563 564 565 566 567 568 569

        // 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'];
        }
        $handler = views_get_handler($table, $field, $key);
570
        if ($this->executable->displayHandlers->get('default')->useGroupBy() && $handler->usesGroupBy()) {
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590
          $this->addFormToStack('config-item-group', $form_state['display_id'], array($type, $id));
        }

        // check to see if this type has settings, if so add the settings form first
        if ($handler && $handler->hasExtraOptions()) {
          $this->addFormToStack('config-item-extra', $form_state['display_id'], array($type, $id));
        }
        // Then add the form to the stack
        $this->addFormToStack('config-item', $form_state['display_id'], array($type, $id));
      }
    }

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

    // Store in cache
    views_ui_cache_set($this);
  }

591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
  /**
   * 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;
  }

614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633
  public function renderPreview($display_id, $args = array()) {
    // Save the current path so it can be restored before returning from this function.
    $old_q = current_path();

    // Determine where the query and performance statistics should be output.
    $config = config('views.settings');
    $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());
    $output = '';

634
    $errors = $this->executable->validate();
635 636
    if ($errors === TRUE) {
      $this->ajax = TRUE;
637
      $this->executable->live_preview = TRUE;
638 639 640 641 642 643 644 645 646 647 648 649 650
      $this->views_ui_context = TRUE;

      // AJAX happens via $_POST but everything expects exposed data to
      // be in GET. Copy stuff but remove ajax-framework specific keys.
      // If we're clicking on links in a preview, though, we could actually
      // still have some in $_GET, so we use $_REQUEST to ensure we get it all.
      $exposed_input = drupal_container()->get('request')->request->all();
      foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids', 'ajax_page_state', 'form_id', 'form_build_id', 'form_token') as $key) {
        if (isset($exposed_input[$key])) {
          unset($exposed_input[$key]);
        }
      }

651
      $this->executable->setExposedInput($exposed_input);
652

653
      if (!$this->executable->setDisplay($display_id)) {
654 655 656
        return t('Invalid display id @display', array('@display' => $display_id));
      }

657
      $this->executable->setArguments($args);
658 659

      // Store the current view URL for later use:
660 661
      if ($this->executable->display_handler->getOption('path')) {
        $path = $this->executable->getUrl();
662 663 664
      }

      // Make view links come back to preview.
665
      $this->override_path = 'admin/structure/views/nojs/preview/' . $this->id() . '/' . $display_id;
666 667 668 669 670 671 672 673 674 675 676 677 678 679

      // Also override the current path so we get the pager.
      $original_path = current_path();
      $q = _current_path($this->override_path);
      if ($args) {
        $q .= '/' . implode('/', $args);
        _current_path($q);
      }

      // 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();
680 681 682 683 684 685 686 687 688 689

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

      timer_start('views_ui.preview');

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

      // Execute/get the view preview.
690
      $preview = $this->executable->preview($display_id, $args);
691 692 693 694 695 696 697

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

      $this->render_time = timer_stop('views_ui.preview');

698 699 700 701 702 703 704 705 706 707
      views_ui_contextual_links_suppress_pop();

      // Reset variables.
      unset($this->override_path);
      _current_path($original_path);

      // Prepare the query information and statistics to show either above or
      // below the view preview.
      if ($show_info || $show_query || $show_stats) {
        // Get information from the preview for display.
708
        if (!empty($this->executable->build_info['query'])) {
709
          if ($show_query) {
710
            $query_string = $this->executable->build_info['query'];
711 712 713
            // Only the sql default class has a method getArguments.
            $quoted = array();

714
            if ($this->executable->query instanceof Sql) {
715
              $quoted = $query_string->getArguments();
716 717 718 719 720 721 722 723 724 725
              $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);
                }
              }
            }
726 727
            $rows['query'][] = array('<strong>' . t('Query') . '</strong>', '<pre>' . check_plain(strtr($query_string, $quoted)) . '</pre>');
            if (!empty($this->additionalQueries)) {
728
              $queries = '<strong>' . t('These queries were run during view rendering:') . '</strong>';
729
              foreach ($this->additionalQueries as $query) {
730 731 732
                if ($queries) {
                  $queries .= "\n";
                }
733 734
                $query_string = strtr($query['query'], $query['args']);
                $queries .= t('[@time ms] @query', array('@time' => round($query['time'] * 100000, 1) / 100000.0, '@query' => $query_string));
735 736 737 738 739 740
              }

              $rows['query'][] = array('<strong>' . t('Other queries') . '</strong>', '<pre>' . $queries . '</pre>');
            }
          }
          if ($show_info) {
741
            $rows['query'][] = array('<strong>' . t('Title') . '</strong>', filter_xss_admin($this->executable->getTitle()));
742 743 744 745 746 747 748 749 750 751
            if (isset($path)) {
              $path = l($path, $path);
            }
            else {
              $path = t('This display has no path.');
            }
            $rows['query'][] = array('<strong>' . t('Path') . '</strong>', $path);
          }

          if ($show_stats) {
752 753 754
            $rows['statistics'][] = array('<strong>' . t('Query build time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->build_time * 100000) / 100)));
            $rows['statistics'][] = array('<strong>' . t('Query execute time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->execute_time * 100000) / 100)));
            $rows['statistics'][] = array('<strong>' . t('View render time') . '</strong>', t('@time ms', array('@time' => intval($this->executable->render_time * 100000) / 100)));
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847

          }
          drupal_alter('views_preview_info', $rows, $this);
        }
        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')) {
            $rows['query'] = array(array('<strong>' . t('Query') . '</strong>', t('No query was run')));
          }
          else {
            $rows['statistics'] = array(array('<strong>' . t('Query') . '</strong>', t('No query was run')));
          }
        }
      }
    }
    else {
      foreach ($errors as $error) {
        drupal_set_message($error, 'error');
      }
      $preview = t('Unable to preview due to validation errors.');
    }

    // Assemble the preview, the query info, and the query statistics in the
    // requested order.
    if ($show_location === 'above') {
      if ($combined) {
        $output .= '<div class="views-query-info">' . theme('table', array('rows' => array_merge($rows['query'], $rows['statistics']))) . '</div>';
      }
      else {
        $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['query'])) . '</div>';
      }
    }
    elseif ($show_stats === 'above') {
      $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['statistics'])) . '</div>';
    }

    $output .= $preview;

    if ($show_location === 'below') {
      if ($combined) {
        $output .= '<div class="views-query-info">' . theme('table', array('rows' => array_merge($rows['query'], $rows['statistics']))) . '</div>';
      }
      else {
        $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['query'])) . '</div>';
      }
    }
    elseif ($show_stats === 'below') {
      $output .= '<div class="views-query-info">' . theme('table', array('rows' => $rows['statistics'])) . '</div>';
    }

    _current_path($old_q);
    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)) {
      $stack = $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;
  }

  /**
   * Build a form identifier that we can use to see if one form
   * is the same as another. Since the arguments differ slightly
   * we do a lot of spiffy concatenation here.
   */
  public function buildIdentifier($key, $display_id, $args) {
    $form = views_ui_ajax_forms($key);
    // Automatically remove the single-form cache if it exists and
    // does not match the key.
848
    $identifier = implode('-', array($key, $this->id(), $display_id));
849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867

    foreach ($form['args'] as $id) {
      $arg = (!empty($args)) ? array_shift($args) : NULL;
      $identifier .= '-' . $arg;
    }
    return $identifier;
  }

  /**
   * Display position sorting function
   */
  public static function sortPosition($display1, $display2) {
    if ($display1['position'] != $display2['position']) {
      return $display1['position'] < $display2['position'] ? -1 : 1;
    }

    return 0;
  }

868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896
  /**
   * Build up a $form_state object suitable for use with drupal_build_form
   * based on known information about a form.
   */
  public function buildFormState($js, $key, $display_id, $args) {
    $form = views_ui_ajax_forms($key);
    // Build up form state
    $form_state = array(
      'form_key' => $key,
      'form_id' => $form['form_id'],
      'view' => &$this,
      'ajax' => $js,
      'display_id' => $display_id,
      'no_redirect' => TRUE,
    );
    // If an method was specified, use that for the callback.
    if (isset($form['callback'])) {
      $form_state['build_info']['args'] = array();
      $form_state['build_info']['callback'] = array($this, $form['callback']);
    }

    foreach ($form['args'] as $id) {
      $form_state[$id] = (!empty($args)) ? array_shift($args) : NULL;
    }

    return $form_state;
  }

  /**
897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021
   * Passes through all unknown calls onto the storage object.
   */
  public function __call($method, $args) {
    return call_user_func_array(array($this->storage, $method), $args);
  }

  /**
   * Implements \IteratorAggregate::getIterator().
   */
  public function getIterator() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::id().
   */
  public function id() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::uuid().
   */
  public function uuid() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::isNew().
   */
  public function isNew() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::entityType().
   */
  public function entityType() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::bundle().
   */
  public function bundle() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::isDefaultRevision().
   */
  public function isDefaultRevision($new_value = NULL) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::getRevisionId().
   */
  public function getRevisionId() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::entityInfo().
   */
  public function entityInfo() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::createDuplicate().
   */
  public function createDuplicate() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::delete().
   */
  public function delete() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::save().
   */
  public function save() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::uri().
   */
  public function uri() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::label().
   */
  public function label($langcode = NULL) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::isNewRevision().
   */
  public function isNewRevision() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::setNewRevision().
   */
  public function setNewRevision($value = TRUE) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Entity\EntityInterface::enforceIsNew().
   */
  public function enforceIsNew($value = TRUE) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

1022 1023 1024 1025 1026 1027 1028
  /**
   * Implements \Drupal\Core\Entity\EntityInterface::getExportProperties().
   */
  public function getExportProperties() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
  /**
   * Implements \Drupal\Core\TypedData\TranslatableInterface::getTranslation().
   */
  public function getTranslation($langcode, $strict = TRUE) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\TranslatableInterface::getTranslationLanguages().
   */
  public function getTranslationLanguages($include_default = TRUE) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\TranslatableInterface::language)().
   */
  public function language() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\AccessibleInterface::access().
   */
1053
  public function access($operation = 'view', \Drupal\user\Plugin\Core\Entity\User $account = NULL) {
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::isEmpty)().
   */
  public function isEmpty() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyValues().
   */
  public function getPropertyValues() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinitions().
   */
  public function getPropertyDefinitions() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::getPropertyDefinition().
   */
  public function getPropertyDefinition($name) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::setPropertyValues().
   */
  public function setPropertyValues($values) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ComplexDataInterface::getProperties().
   */
  public function getProperties($include_computed = FALSE) {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
1100
   * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::enable().
1101 1102 1103 1104 1105 1106
   */
  public function enable() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
1107
   * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::disable().
1108 1109 1110 1111 1112 1113
   */
  public function disable() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
1114
   * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::status().
1115
   */
1116
  public function status() {
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::getOriginalID().
   */
  public function getOriginalID() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\Config\Entity\ConfigEntityInterface::setOriginalID().
1129
   */
1130 1131
  public function setOriginalID($id) {
    return $this->__call(__FUNCTION__, func_get_args());
1132 1133
  }

1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181
  /**
   * Implements Drupal\Core\Entity\EntityInterface::getBCEntity().
   */
  public function getBCEntity() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements Drupal\Core\Entity\EntityInterface::getOriginalEntity().
   */
  public function getOriginalEntity() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ContextAwareInterface::getName().
   */
  public function getName() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ContextAwareInterface::getRoot().
   */
  public function getRoot() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ContextAwareInterface::getPropertyPath().
   */
  public function getPropertyPath() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ContextAwareInterface::getParent().
   */
  public function getParent() {
    return $this->__call(__FUNCTION__, func_get_args());
  }

  /**
   * Implements \Drupal\Core\TypedData\ContextAwareInterface::setContext().
   */
  public function setContext($name = NULL, ContextAwareInterface $parent = NULL) {
    return $this->__call(__FUNCTION__, func_get_args());
  }
1182
}