PluginBase.php 20.7 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\views\Plugin\views\PluginBase.
6 7
 */

8
namespace Drupal\views\Plugin\views;
9

10
use Drupal\Component\Plugin\DependentPluginInterface;
11
use Drupal\Component\Utility\Xss;
12
use Drupal\Core\Form\FormStateInterface;
13
use Drupal\Core\Language\LanguageInterface;
14
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
15
use Drupal\Core\Plugin\PluginBase as ComponentPluginBase;
16
use Drupal\Core\Render\Element;
17
use Drupal\Core\StringTranslation\TranslatableMarkup;
18 19
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\ViewExecutable;
20
use Symfony\Component\DependencyInjection\ContainerInterface;
21

22 23 24 25 26 27 28 29 30 31 32
/**
 * Base class for any views plugin types.
 *
 * Via the @Plugin definition the plugin may specify a theme function or
 * template to be used for the plugin. It also can auto-register the theme
 * implementation for that file or function.
 * - theme: the theme implementation to use in the plugin. This may be the name
 *   of the function (without theme_ prefix) or the template file (without
 *   template engine extension).
 *   If a template file should be used, the file has to be placed in the
 *   module's templates folder.
33 34
 *   Example: theme = "mymodule_row" of module "mymodule" will implement
 *   mymodule-row.html.twig in the [..]/modules/mymodule/templates folder.
35 36 37 38 39 40 41 42
 * - register_theme: (optional) When set to TRUE (default) the theme is
 *   registered automatically. When set to FALSE the plugin reuses an existing
 *   theme implementation, defined by another module or views plugin.
 * - theme_file: (optional) the location of an include file that may hold the
 *   theme or preprocess function. The location has to be relative to module's
 *   root directory.
 * - module: machine name of the module. It must be present for any plugin that
 *   wants to register a theme.
43 44
 *
 * @ingroup views_plugins
45
 */
46
abstract class PluginBase extends ComponentPluginBase implements ContainerFactoryPluginInterface, ViewsPluginInterface, DependentPluginInterface {
47

48 49 50 51 52 53 54
  /**
   * Include negotiated languages when listing languages.
   *
   * @see \Drupal\views\Plugin\views\PluginBase::listLanguages()
   */
  const INCLUDE_NEGOTIATED = 16;

55 56 57 58 59 60 61
  /**
   * Include entity row languages when listing languages.
   *
   * @see \Drupal\views\Plugin\views\PluginBase::listLanguages()
   */
  const INCLUDE_ENTITY = 32;

62 63 64 65 66 67 68
  /**
   * Query string to indicate the site default language.
   *
   * @see \Drupal\Core\Language\LanguageInterface::LANGCODE_DEFAULT
   */
  const VIEWS_QUERY_LANGUAGE_SITE_DEFAULT = '***LANGUAGE_site_default***';

69
  /**
70
   * Options for this plugin will be held here.
71 72
   *
   * @var array
73
   */
74
  public $options = array();
75 76 77 78

  /**
   * The top object of a view.
   *
79
   * @var \Drupal\views\ViewExecutable
80
   */
81
  public $view = NULL;
82

83 84 85 86 87 88 89
  /**
   * The display object this plugin is for.
   *
   * For display plugins this is empty.
   *
   * @todo find a better description
   *
90
   * @var \Drupal\views\Plugin\views\display\DisplayPluginBase
91 92 93
   */
  public $displayHandler;

94
  /**
95
   * Plugins's definition
96 97 98
   *
   * @var array
   */
99
  public $definition;
100

101
  /**
102 103 104 105
   * Denotes whether the plugin has an additional options form.
   *
   * @var bool
   */
106
  protected $usesOptions = FALSE;
107

108 109 110 111 112 113
  /**
   * Stores the render API renderer.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;
114

aspilicious's avatar
aspilicious committed
115
  /**
116 117 118 119 120 121 122 123
   * Constructs a PluginBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
aspilicious's avatar
aspilicious committed
124
   */
125
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
126
    parent::__construct($configuration, $plugin_id, $plugin_definition);
127

128
    $this->definition = $plugin_definition + $configuration;
aspilicious's avatar
aspilicious committed
129 130
  }

131 132 133
  /**
   * {@inheritdoc}
   */
134
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
135 136 137
    return new static($configuration, $plugin_id, $plugin_definition);
  }

138
  /**
139
   * {@inheritdoc}
140 141 142
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    $this->view = $view;
143
    $this->setOptionDefaults($this->options, $this->defineOptions());
144 145 146 147 148
    $this->displayHandler = $display;

    $this->unpackOptions($this->options, $options);
  }

149 150 151 152 153 154 155 156 157
  /**
   * Information about options for all kinds of purposes will be held here.
   * @code
   * 'option_name' => array(
   *  - 'default' => default value,
   *  - 'contains' => (optional) array of items this contains, with its own
   *      defaults, etc. If contains is set, the default will be ignored and
   *      assumed to be array().
   *  ),
158
   * @endcode
159 160 161 162
   *
   * @return array
   *   Returns the options of this handler/plugin.
   */
163
  protected function defineOptions() { return array(); }
164

165 166 167 168 169 170 171 172
  /**
   * Fills up the options of the plugin with defaults.
   *
   * @param array $storage
   *   An array which stores the actual option values of the plugin.
   * @param array $options
   *   An array which describes the options of a plugin. Each element is an
   *   associative array containing:
173
   *   - default: The default value of one option. Should be translated to the
174
   *     interface text language selected for page if translatable.
175 176 177 178 179 180
   *   - (optional) contains: An array which describes the available options
   *     under the key. If contains is set, the default will be ignored and
   *     assumed to be an empty array.
   *   - (optional) 'bool': TRUE if the value is boolean, else FALSE.
   */
  protected function setOptionDefaults(array &$storage, array $options) {
181
    foreach ($options as $option => $definition) {
182
      if (isset($definition['contains'])) {
183
        $storage[$option] = array();
184
        $this->setOptionDefaults($storage[$option], $definition['contains']);
185 186
      }
      else {
187
        $storage[$option] = $definition['default'];
188 189
      }
    }
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
  }

  /**
   * {@inheritdoc}
   */
  public function filterByDefinedOptions(array &$storage) {
    $this->doFilterByDefinedOptions($storage, $this->defineOptions());
  }

  /**
   * Do the work to filter out stored options depending on the defined options.
   *
   * @param array $storage
   *   The stored options.
   *
   * @param array $options
   *   The defined options.
   */
  protected function doFilterByDefinedOptions(array &$storage, array $options) {
    foreach ($storage as $key => $sub_storage) {
      if (!isset($options[$key])) {
        unset($storage[$key]);
      }

      if (isset($options[$key]['contains'])) {
        $this->doFilterByDefinedOptions($storage[$key], $options[$key]['contains']);
      }
    }
218 219 220
  }

  /**
221
   * {@inheritdoc}
222
   */
223
  public function unpackOptions(&$storage, $options, $definition = NULL, $all = TRUE, $check = TRUE) {
224 225 226 227 228
    if ($check && !is_array($options)) {
      return;
    }

    if (!isset($definition)) {
229
      $definition = $this->defineOptions();
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    }

    foreach ($options as $key => $value) {
      if (is_array($value)) {
        // Ignore arrays with no definition.
        if (!$all && empty($definition[$key])) {
          continue;
        }

        if (!isset($storage[$key]) || !is_array($storage[$key])) {
          $storage[$key] = array();
        }

        // If we're just unpacking our known options, and we're dropping an
        // unknown array (as might happen for a dependent plugin fields) go
        // ahead and drop that in.
        if (!$all && isset($definition[$key]) && !isset($definition[$key]['contains'])) {
          $storage[$key] = $value;
          continue;
        }

251
        $this->unpackOptions($storage[$key], $value, isset($definition[$key]['contains']) ? $definition[$key]['contains'] : array(), $all, FALSE);
252
      }
253
      elseif ($all || !empty($definition[$key])) {
254 255 256 257 258
        $storage[$key] = $value;
      }
    }
  }

259
  /**
260
   * {@inheritdoc}
261
   */
262
  public function destroy() {
263
    unset($this->view, $this->display, $this->query);
264 265 266
  }

  /**
267
   * {@inheritdoc}
268
   */
269
  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
270
    // Some form elements belong in a fieldset for presentation, but can't
271
    // be moved into one because of the $form_state->getValues() hierarchy. Those
272
    // elements can add a #fieldset => 'fieldset_name' property, and they'll
273 274
    // be moved to their fieldset during pre_render.
    $form['#pre_render'][] = array(get_class($this), 'preRenderAddFieldsetMarkup');
275 276 277
  }

  /**
278
   * {@inheritdoc}
279
   */
280
  public function validateOptionsForm(&$form, FormStateInterface $form_state) { }
281 282

  /**
283
   * {@inheritdoc}
284
   */
285
  public function submitOptionsForm(&$form, FormStateInterface $form_state) { }
286 287

  /**
288
   * {@inheritdoc}
289
   */
290
  public function query() { }
291 292

  /**
293
   * {@inheritdoc}
294
   */
295
  public function themeFunctions() {
296
    return $this->view->buildThemeFunctions($this->definition['theme']);
297 298 299
  }

  /**
300
   * {@inheritdoc}
301
   */
302
  public function validate() { return array(); }
303 304

  /**
305
   * {@inheritdoc}
306
   */
307
  public function summaryTitle() {
308
    return $this->t('Settings');
309
  }
310

311
  /**
312
   * {@inheritdoc}
313
   */
314
  public function pluginTitle() {
315 316
    // Short_title is optional so its defaults to an empty string.
    if (!empty($this->definition['short_title'])) {
317
      return $this->definition['short_title'];
318
    }
319
    return $this->definition['title'];
320
  }
321

322
  /**
323
   * {@inheritdoc}
324
   */
325
  public function usesOptions() {
326 327 328
    return $this->usesOptions;
  }

329
  /**
330
   * {@inheritdoc}
331 332
   */
  public function globalTokenReplace($string = '', array $options = array()) {
333
    return \Drupal::token()->replace($string, array('view' => $this->view), $options);
334 335
  }

336
  /**
337 338
   * Replaces Views' tokens in a given string. The resulting string will be
   * sanitized with Xss::filterAdmin.
339 340
   *
   * @param $text
341
   *   Unsanitized string with possible tokens.
342 343 344 345 346 347
   * @param $tokens
   *   Array of token => replacement_value items.
   *
   * @return String
   */
  protected function viewsTokenReplace($text, $tokens) {
348 349 350 351
    if (!strlen($text)) {
      // No need to run filterAdmin on an empty string.
      return '';
    }
352
    if (empty($tokens)) {
353
      return Xss::filterAdmin($text);
354 355 356 357
    }

    $twig_tokens = array();
    foreach ($tokens as $token => $replacement) {
358 359 360
      // Twig wants a token replacement array stripped of curly-brackets.
      // Some Views tokens come with curly-braces, others do not.
      //@todo: https://www.drupal.org/node/2544392
361 362
      if (strpos($token, '{{') !== FALSE) {
        // Twig wants a token replacement array stripped of curly-brackets.
363 364
        $token = trim(str_replace(['{{', '}}'], '', $token));
      }
365

366 367 368 369
      // Check for arrays in Twig tokens. Internally these are passed as
      // dot-delimited strings, but need to be turned into associative arrays
      // for parsing.
      if (strpos($token, '.') === FALSE) {
370 371 372 373
        // We need to validate tokens are valid Twig variables. Twig uses the
        // same variable naming rules as PHP.
        // @see http://php.net/manual/en/language.variables.basics.php
        assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/\', $token) === 1', 'Tokens need to be valid Twig variables.');
374 375 376
        $twig_tokens[$token] = $replacement;
      }
      else {
377 378 379 380 381 382 383 384
        $parts = explode('.', $token);
        $top = array_shift($parts);
        assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/\', $top) === 1', 'Tokens need to be valid Twig variables.');
        $token_array = array(array_pop($parts) => $replacement);
        foreach(array_reverse($parts) as $key) {
          assert('preg_match(\'/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/\', $key) === 1', 'Tokens need to be valid Twig variables.');
          $token_array = array($key => $token_array);
        }
385 386 387 388
        if (!isset($twig_tokens[$top])) {
          $twig_tokens[$top] = [];
        }
        $twig_tokens[$top] += $token_array;
389 390 391
      }
    }

392 393 394 395
    if ($twig_tokens) {
      // Use the unfiltered text for the Twig template, then filter the output.
      // Otherwise, Xss::filterAdmin could remove valid Twig syntax before the
      // template is parsed.
396

397 398 399 400
      $build = array(
        '#type' => 'inline_template',
        '#template' => $text,
        '#context' => $twig_tokens,
401 402 403 404 405
        '#post_render' => [
          function ($children, $elements) {
            return Xss::filterAdmin($children);
          }
        ],
406
      );
407

408 409 410 411 412
      // Currently you cannot attach assets to tokens with
      // Renderer::renderPlain(). This may be unnecessarily limiting. Consider
      // using Renderer::executeInRenderContext() instead.
      // @todo: https://www.drupal.org/node/2566621
      return (string) $this->getRenderer()->renderPlain($build);
413 414
    }
    else {
415
      return Xss::filterAdmin($text);
416 417 418
    }
  }

419
  /**
420
   * {@inheritdoc}
421 422
   */
  public function getAvailableGlobalTokens($prepared = FALSE, array $types = array()) {
423
    $info = \Drupal::token()->getInfo();
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443
    // Site and view tokens should always be available.
    $types += array('site', 'view');
    $available = array_intersect_key($info['tokens'], array_flip($types));

    // Construct the token string for each token.
    if ($prepared) {
      $prepared = array();
      foreach ($available as $type => $tokens) {
        foreach (array_keys($tokens) as $token) {
          $prepared[$type][] = "[$type:$token]";
        }
      }

      return $prepared;
    }

    return $available;
  }

  /**
444
   * {@inheritdoc}
445
   */
446
  public function globalTokenForm(&$form, FormStateInterface $form_state) {
447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
    $token_items = array();

    foreach ($this->getAvailableGlobalTokens() as $type => $tokens) {
      $item = array(
        '#markup' => $type,
        'children' => array(),
      );
      foreach ($tokens as $name => $info) {
        $item['children'][$name] = "[$type:$name]" . ' - ' . $info['name'] . ': ' . $info['description'];
      }

      $token_items[$type] = $item;
    }

    $form['global_tokens'] = array(
462
      '#type' => 'details',
463
      '#title' => $this->t('Available global token replacements'),
464 465 466 467 468 469 470 471 472 473
    );
    $form['global_tokens']['list'] = array(
      '#theme' => 'item_list',
      '#items' => $token_items,
      '#attributes' => array(
        'class' => array('global-tokens'),
      ),
    );
  }

474
  /**
475
   * {@inheritdoc}
476 477
   */
  public static function preRenderAddFieldsetMarkup(array $form) {
478
    foreach (Element::children($form) as $key) {
479 480 481 482 483 484 485 486 487 488 489 490 491 492
      $element = $form[$key];
      // In our form builder functions, we added an arbitrary #fieldset property
      // to any element that belongs in a fieldset. If this form element has
      // that property, move it into its fieldset.
      if (isset($element['#fieldset']) && isset($form[$element['#fieldset']])) {
        $form[$element['#fieldset']][$key] = $element;
        // Remove the original element this duplicates.
        unset($form[$key]);
      }
    }
    return $form;
  }

  /**
493
   * {@inheritdoc}
494 495
   */
  public static function preRenderFlattenData($form) {
496
    foreach (Element::children($form) as $key) {
497 498
      $element = $form[$key];
      if (!empty($element['#flatten'])) {
499
        foreach (Element::children($element) as $child_key) {
500 501 502 503 504 505 506 507 508 509
          $form[$child_key] = $form[$key][$child_key];
        }
        // All done, remove the now-empty parent.
        unset($form[$key]);
      }
    }

    return $form;
  }

510
  /**
511
   * {@inheritdoc}
512
   */
513 514 515 516 517 518 519 520 521 522
  public function calculateDependencies() {
    return [];
  }

  /**
   * {@inheritdoc}
   */
  public function getProvider() {
    $definition = $this->getPluginDefinition();
    return $definition['provider'];
523 524
  }

525 526 527 528 529 530 531 532 533 534 535 536 537
  /**
   * Makes an array of languages, optionally including special languages.
   *
   * @param int $flags
   *   (optional) Flags for which languages to return (additive). Options:
   *   - \Drupal\Core\Language::STATE_ALL (default): All languages
   *     (configurable and default).
   *   - \Drupal\Core\Language::STATE_CONFIGURABLE: Configurable languages.
   *   - \Drupal\Core\Language::STATE_LOCKED: Locked languages.
   *   - \Drupal\Core\Language::STATE_SITE_DEFAULT: Add site default language;
   *     note that this is not included in STATE_ALL.
   *   - \Drupal\views\Plugin\views\PluginBase::INCLUDE_NEGOTIATED: Add
   *     negotiated language types.
538 539 540
   *   - \Drupal\views\Plugin\views\PluginBase::INCLUDE_ENTITY: Add
   *     entity row language types. Note that these are only supported for
   *     display options, not substituted in queries.
541 542
   * @param array|null $current_values
   *   The currently-selected options in the list, if available.
543 544 545 546
   *
   * @return array
   *   An array of language names, keyed by the language code. Negotiated and
   *   special languages have special codes that are substituted in queries by
547
   *   PluginBase::queryLanguageSubstitutions().
548 549
   *   Only configurable languages and languages that are in $current_values are
   *   included in the list.
550
   */
551
  protected function listLanguages($flags = LanguageInterface::STATE_ALL, array $current_values = NULL) {
552
    $manager = \Drupal::languageManager();
553
    $languages = $manager->getLanguages($flags);
554 555
    $list = array();

556 557 558 559 560 561
    // The entity languages should come first, if requested.
    if ($flags & PluginBase::INCLUDE_ENTITY) {
      $list['***LANGUAGE_entity_translation***'] = $this->t('Content language of view row');
      $list['***LANGUAGE_entity_default***'] = $this->t('Original language of content in view row');
    }

562 563
    // STATE_SITE_DEFAULT comes in with ID set
    // to LanguageInterface::LANGCODE_SITE_DEFAULT.
564 565
    // Since this is not a real language, surround it by '***LANGUAGE_...***',
    // like the negotiated languages below.
566
    if ($flags & LanguageInterface::STATE_SITE_DEFAULT) {
567 568 569 570
      $name = $languages[LanguageInterface::LANGCODE_SITE_DEFAULT]->getName();
      // The language name may have already been translated, no need to
      // translate it again.
      // @see Drupal\Core\Language::filterLanguages().
571
      if (!$name instanceof TranslatableMarkup) {
572 573 574
        $name = $this->t($name);
      }
      $list[PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT] = $name;
575 576 577
      // Remove site default language from $languages so it's not added
      // twice with the real languages below.
      unset($languages[LanguageInterface::LANGCODE_SITE_DEFAULT]);
578 579 580 581
    }

    // Add in negotiated languages, if requested.
    if ($flags & PluginBase::INCLUDE_NEGOTIATED) {
582 583 584 585 586 587 588 589
      $types_info = $manager->getDefinedLanguageTypesInfo();
      $types = $manager->getLanguageTypes();
      // We only go through the configured types.
      foreach ($types as $id) {
        if (isset($types_info[$id]['name'])) {
          $name = $types_info[$id]['name'];
          // Surround IDs by '***LANGUAGE_...***', to avoid query collisions.
          $id = '***LANGUAGE_' . $id . '***';
590
          $list[$id] = $this->t('@type language selected for page', array('@type' => $name));
591 592 593 594
        }
      }
      if (!empty($current_values)) {
        foreach ($types_info as $id => $type) {
595
          $id = '***LANGUAGE_' . $id . '***';
596 597 598 599
          // If this (non-configurable) type is among the current values,
          // add that option too, so it is not lost. If not among the current
          // values, skip displaying it to avoid user confusion.
          if (isset($type['name']) && !isset($list[$id]) && in_array($id, $current_values)) {
600
            $list[$id] = $this->t('@type language selected for page', array('@type' => $type['name']));
601
          }
602 603 604 605
        }
      }
    }

606 607
    // Add real languages.
    foreach ($languages as $id => $language) {
608
      $list[$id] = $language->getName();
609 610
    }

611 612 613 614 615 616 617
    return $list;
  }

  /**
   * Returns substitutions for Views queries for languages.
   *
   * This is needed so that the language options returned by
618
   * PluginBase::listLanguages() are able to be used in queries. It is called
619 620 621 622 623 624 625 626 627 628 629 630
   * by the Views module implementation of hook_views_query_substitutions()
   * to get the language-related substitutions.
   *
   * @return array
   *   An array in the format of hook_views_query_substitutions() that gives
   *   the query substitutions needed for the special language types.
   */
  public static function queryLanguageSubstitutions() {
    $changes = array();
    $manager = \Drupal::languageManager();

    // Handle default language.
631
    $default = $manager->getDefaultLanguage()->getId();
632
    $changes[PluginBase::VIEWS_QUERY_LANGUAGE_SITE_DEFAULT] = $default;
633 634 635 636 637

    // Handle negotiated languages.
    $types = $manager->getDefinedLanguageTypesInfo();
    foreach ($types as $id => $type) {
      if (isset($type['name'])) {
638
        $changes['***LANGUAGE_' . $id . '***'] = $manager->getCurrentLanguage($id)->getId();
639 640 641 642 643
      }
    }

    return $changes;
  }
644 645 646 647 648 649 650 651 652 653 654 655 656 657

  /**
   * Returns the render API renderer.
   *
   * @return \Drupal\Core\Render\RendererInterface
   */
  protected function getRenderer() {
    if (!isset($this->renderer)) {
      $this->renderer = \Drupal::service('renderer');
    }

    return $this->renderer;
  }

658
}