BlockBase.php 18.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
5
 * Contains \Drupal\Core\Block\BlockBase.
6 7
 */

8
namespace Drupal\Core\Block;
9

10
use Drupal\block\BlockInterface;
11 12 13
use Drupal\block\Event\BlockConditionContextEvent;
use Drupal\block\Event\BlockEvents;
use Drupal\Component\Plugin\ContextAwarePluginInterface;
14
use Drupal\Core\Access\AccessResult;
15 16
use Drupal\Core\Condition\ConditionAccessResolverTrait;
use Drupal\Core\Condition\ConditionPluginBag;
17 18
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
19
use Drupal\Core\Plugin\ContextAwarePluginBase;
20
use Drupal\Component\Utility\Unicode;
21
use Drupal\Component\Utility\NestedArray;
22
use Drupal\Core\Language\LanguageInterface;
23
use Drupal\Core\Cache\Cache;
24
use Drupal\Core\Session\AccountInterface;
25
use Drupal\Component\Transliteration\TransliterationInterface;
26 27 28 29 30 31 32

/**
 * Defines a base block implementation that most blocks plugins will extend.
 *
 * This abstract class provides the generic block configuration form, default
 * block settings, and handling for general user-defined block visibility
 * settings.
33 34
 *
 * @ingroup block_api
35
 */
36
abstract class BlockBase extends ContextAwarePluginBase implements BlockPluginInterface {
37

38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
  use ConditionAccessResolverTrait;

  /**
   * The condition plugin bag.
   *
   * @var \Drupal\Core\Condition\ConditionPluginBag
   */
  protected $conditionBag;

  /**
   * The condition plugin manager.
   *
   * @var \Drupal\Core\Executable\ExecutableManagerInterface
   */
  protected $conditionPluginManager;

54 55 56 57 58 59 60
  /**
   * The transliteration service.
   *
   * @var \Drupal\Component\Transliteration\TransliterationInterface
   */
  protected $transliteration;

61 62 63 64 65 66 67 68 69
  /**
   * {@inheritdoc}
   */
  public function label() {
    if (!empty($this->configuration['label'])) {
      return $this->configuration['label'];
    }

    $definition = $this->getPluginDefinition();
70 71 72
    // Cast the admin label to a string since it is an object.
    // @see \Drupal\Core\StringTranslation\TranslationWrapper
    return (string) $definition['admin_label'];
73 74
  }

75
  /**
76
   * {@inheritdoc}
77
   */
78
  public function __construct(array $configuration, $plugin_id, $plugin_definition) {
79
    parent::__construct($configuration, $plugin_id, $plugin_definition);
80
    $this->setConfiguration($configuration);
81 82 83
  }

  /**
84
   * {@inheritdoc}
85
   */
86
  public function getConfiguration() {
87 88 89
    return array(
      'visibility' => $this->getVisibilityConditions()->getConfiguration(),
    ) + $this->configuration;
90 91 92
  }

  /**
93 94 95
   * {@inheritdoc}
   */
  public function setConfiguration(array $configuration) {
96 97 98 99 100 101 102 103 104 105 106 107 108 109
    $this->configuration = NestedArray::mergeDeep(
      $this->baseConfigurationDefaults(),
      $this->defaultConfiguration(),
      $configuration
    );
  }

  /**
   * Returns generic default configuration for block plugins.
   *
   * @return array
   *   An associative array with the default configuration.
   */
  protected function baseConfigurationDefaults() {
110 111 112 113 114
    // @todo Allow list of conditions to be configured in
    //   https://drupal.org/node/2284687.
    $visibility = array_map(function ($definition) {
      return array('id' => $definition['id']);
    }, $this->conditionPluginManager()->getDefinitions());
115 116
    unset($visibility['current_theme']);

117
    return array(
118
      'id' => $this->getPluginId(),
119
      'label' => '',
120
      'provider' => $this->pluginDefinition['provider'],
121 122 123 124 125
      'label_display' => BlockInterface::BLOCK_LABEL_VISIBLE,
      'cache' => array(
        'max_age' => 0,
        'contexts' => array(),
      ),
126
      'visibility' => $visibility,
127
    );
128 129
  }

130 131 132 133 134 135 136
  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return array();
  }

137 138
  /**
   * {@inheritdoc}
139
   */
140
  public function setConfigurationValue($key, $value) {
141 142 143
    $this->configuration[$key] = $value;
  }

144 145 146 147 148 149 150
  /**
   * {@inheritdoc}
   */
  public function calculateDependencies() {
    return array();
  }

151
  /**
152
   * {@inheritdoc}
153
   */
154
  public function access(AccountInterface $account) {
155 156 157 158 159 160 161 162 163 164 165 166 167 168
    // @todo Add in a context mapping until the UI supports configuring them,
    //   see https://drupal.org/node/2284687.
    $mappings['user_role']['current_user'] = 'user';

    $conditions = $this->getVisibilityConditions();
    $contexts = $this->getConditionContexts();
    foreach ($conditions as $condition_id => $condition) {
      if ($condition instanceof ContextAwarePluginInterface) {
        if (!isset($mappings[$condition_id])) {
          $mappings[$condition_id] = array();
        }
        $this->contextHandler()->applyContextMapping($condition, $contexts, $mappings[$condition_id]);
      }
    }
169 170 171 172 173
    // This should not be hardcoded to an uncacheable access check result, but
    // in order to fix that, we need condition plugins to return cache contexts,
    // otherwise it will be impossible to determine by which cache contexts the
    // result should be varied.
    $access = AccessResult::create()->setCacheable(FALSE);
174
    if ($this->resolveConditions($conditions, 'and', $contexts, $mappings) === FALSE) {
175 176
      $access->forbid();
      return $access;
177
    }
178 179 180 181 182 183 184
    if ($this->blockAccess($account)) {
      $access->allow();
    }
    else {
      $access->forbid();
    }
    return $access;
185 186
  }

187 188 189 190 191 192 193 194 195 196 197 198
  /**
   * Gets the values for all defined contexts.
   *
   * @return \Drupal\Component\Plugin\Context\ContextInterface[]
   *   An array of set contexts, keyed by context name.
   */
  protected function getConditionContexts() {
    $conditions = $this->getVisibilityConditions();
    $this->eventDispatcher()->dispatch(BlockEvents::CONDITION_CONTEXT, new BlockConditionContextEvent($conditions));
    return $conditions->getConditionContexts();
  }

199 200 201 202 203 204 205 206 207 208 209 210 211
  /**
   * Indicates whether the block should be shown.
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The user session for which to check access.
   *
   * @return bool
   *   TRUE if the block should be shown, or FALSE otherwise.
   *
   * @see self::access()
   */
  protected function blockAccess(AccountInterface $account) {
    // By default, the block is visible.
212 213 214 215
    return TRUE;
  }

  /**
216
   * {@inheritdoc}
217 218 219 220 221 222
   *
   * Creates a generic configuration form for all block types. Individual
   * block plugins can add elements to this form by overriding
   * BlockBase::blockForm(). Most block plugins should not override this
   * method unless they need to alter the generic form elements.
   *
223
   * @see \Drupal\Core\Block\BlockBase::blockForm()
224
   */
225
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
226
    $definition = $this->getPluginDefinition();
227
    $form['provider'] = array(
228
      '#type' => 'value',
229
      '#value' => $definition['provider'],
230 231
    );

232 233 234 235 236
    $form['admin_label'] = array(
      '#type' => 'item',
      '#title' => t('Block description'),
      '#markup' => $definition['admin_label'],
    );
237
    $form['label'] = array(
238
      '#type' => 'textfield',
239
      '#title' => $this->t('Title'),
240
      '#maxlength' => 255,
241
      '#default_value' => $this->label(),
242 243 244 245
      '#required' => TRUE,
    );
    $form['label_display'] = array(
      '#type' => 'checkbox',
246
      '#title' => $this->t('Display title'),
247
      '#default_value' => ($this->configuration['label_display'] === BlockInterface::BLOCK_LABEL_VISIBLE),
248
      '#return_value' => BlockInterface::BLOCK_LABEL_VISIBLE,
249
    );
250 251 252
    // Identical options to the ones for page caching.
    // @see \Drupal\system\Form\PerformanceForm::buildForm()
    $period = array(0, 60, 180, 300, 600, 900, 1800, 2700, 3600, 10800, 21600, 32400, 43200, 86400);
253
    $period = array_map(array(\Drupal::service('date.formatter'), 'formatInterval'), array_combine($period, $period));
254 255
    $period[0] = '<' . t('no caching') . '>';
    $period[\Drupal\Core\Cache\Cache::PERMANENT] = t('Forever');
256
    $form['cache'] = array(
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
      '#type' => 'details',
      '#title' => t('Cache settings'),
    );
    $form['cache']['max_age'] = array(
      '#type' => 'select',
      '#title' => t('Maximum age'),
      '#description' => t('The maximum time this block may be cached.'),
      '#default_value' => $this->configuration['cache']['max_age'],
      '#options' => $period,
    );
    $contexts = \Drupal::service("cache_contexts")->getLabels();
    // Blocks are always rendered in a "per theme" cache context. No need to
    // show that option to the end user.
    unset($contexts['cache_context.theme']);
    $form['cache']['contexts'] = array(
      '#type' => 'checkboxes',
      '#title' => t('Vary by context'),
      '#description' => t('The contexts this cached block must be varied by.'),
      '#default_value' => $this->configuration['cache']['contexts'],
      '#options' => $contexts,
      '#states' => array(
        'disabled' => array(
          ':input[name="settings[cache][max_age]"]' => array('value' => (string) 0),
        ),
      ),
282
    );
283 284 285 286 287 288 289 290 291 292 293
    if (count($this->getRequiredCacheContexts()) > 0) {
      // Remove the required cache contexts from the list of contexts a user can
      // choose to modify by: they must always be applied.
      $context_labels = array();
      foreach ($this->getRequiredCacheContexts() as $context) {
        $context_labels[] = $form['cache']['contexts']['#options'][$context];
        unset($form['cache']['contexts']['#options'][$context]);
      }
      $required_context_list = implode(', ', $context_labels);
      $form['cache']['contexts']['#description'] .= ' ' . t('This block is <em>always</em> varied by the following contexts: %required-context-list.', array('%required-context-list' => $required_context_list));
    }
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
    $form['visibility_tabs'] = array(
      '#type' => 'vertical_tabs',
      '#title' => $this->t('Visibility'),
      '#parents' => array('visibility_tabs'),
      '#attached' => array(
        'library' => array(
          'block/drupal.block',
        ),
      ),
    );
    foreach ($this->getVisibilityConditions() as $condition_id => $condition) {
      $condition_form = $condition->buildConfigurationForm(array(), $form_state);
      $condition_form['#type'] = 'details';
      $condition_form['#title'] = $condition->getPluginDefinition()['label'];
      $condition_form['#group'] = 'visibility_tabs';
      $form['visibility'][$condition_id] = $condition_form;
    }

    // @todo Determine if there is a better way to rename the conditions.
    if (isset($form['visibility']['node_type'])) {
      $form['visibility']['node_type']['#title'] = $this->t('Content types');
      $form['visibility']['node_type']['bundles']['#title'] = $this->t('Content types');
      $form['visibility']['node_type']['negate']['#type'] = 'value';
      $form['visibility']['node_type']['negate']['#title_display'] = 'invisible';
      $form['visibility']['node_type']['negate']['#value'] = $form['visibility']['node_type']['negate']['#default_value'];
    }
    if (isset($form['visibility']['user_role'])) {
      $form['visibility']['user_role']['#title'] = $this->t('Roles');
      unset($form['visibility']['user_role']['roles']['#description']);
      $form['visibility']['user_role']['negate']['#type'] = 'value';
      $form['visibility']['user_role']['negate']['#value'] = $form['visibility']['user_role']['negate']['#default_value'];
    }
    if (isset($form['visibility']['request_path'])) {
      $form['visibility']['request_path']['#title'] = $this->t('Pages');
      $form['visibility']['request_path']['negate']['#type'] = 'radios';
      $form['visibility']['request_path']['negate']['#title_display'] = 'invisible';
      $form['visibility']['request_path']['negate']['#default_value'] = (int) $form['visibility']['request_path']['negate']['#default_value'];
      $form['visibility']['request_path']['negate']['#options'] = array(
        $this->t('Show for the listed pages'),
        $this->t('Hide for the listed pages'),
      );
    }
    if (isset($form['visibility']['language'])) {
      $form['visibility']['language']['negate']['#type'] = 'value';
      $form['visibility']['language']['negate']['#value'] = $form['visibility']['language']['negate']['#default_value'];
    }

342
    // Add plugin-specific settings for this block type.
343
    $form += $this->blockForm($form, $form_state);
344 345 346 347
    return $form;
  }

  /**
348
   * {@inheritdoc}
349
   */
350
  public function blockForm($form, FormStateInterface $form_state) {
351 352 353 354
    return array();
  }

  /**
355
   * {@inheritdoc}
356 357
   *
   * Most block plugins should not override this method. To add validation
358
   * for a specific block type, override BlockBase::blockValidate().
359
   *
360
   * @see \Drupal\Core\Block\BlockBase::blockValidate()
361
   */
362
  public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
363
    // Remove the admin_label form item element value so it will not persist.
364
    $form_state->unsetValue('admin_label');
365

366
    // Transform the #type = checkboxes value to a numerically indexed array.
367 368
    $contexts = $form_state->getValue(array('cache', 'contexts'));
    $form_state->setValue(array('cache', 'contexts'), array_values(array_filter($contexts)));
369

370 371
    foreach ($this->getVisibilityConditions() as $condition_id => $condition) {
      // Allow the condition to validate the form.
372 373
      $condition_values = (new FormState())
        ->setValues($form_state->getValue(['visibility', $condition_id]));
374
      $condition->validateConfigurationForm($form, $condition_values);
375
      // Update the original form values.
376
      $form_state->setValue(['visibility', $condition_id], $condition_values->getValues());
377 378
    }

379 380 381 382
    $this->blockValidate($form, $form_state);
  }

  /**
383
   * {@inheritdoc}
384
   */
385
  public function blockValidate($form, FormStateInterface $form_state) {}
386 387

  /**
388
   * {@inheritdoc}
389 390 391 392
   *
   * Most block plugins should not override this method. To add submission
   * handling for a specific block type, override BlockBase::blockSubmit().
   *
393
   * @see \Drupal\Core\Block\BlockBase::blockSubmit()
394
   */
395
  public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
396
    // Process the block's submission handling if no errors occurred only.
397
    if (!$form_state->getErrors()) {
398 399 400 401
      $this->configuration['label'] = $form_state->getValue('label');
      $this->configuration['label_display'] = $form_state->getValue('label_display');
      $this->configuration['provider'] = $form_state->getValue('provider');
      $this->configuration['cache'] = $form_state->getValue('cache');
402 403
      foreach ($this->getVisibilityConditions() as $condition_id => $condition) {
        // Allow the condition to submit the form.
404 405
        $condition_values = (new FormState())
          ->setValues($form_state->getValue(['visibility', $condition_id]));
406
        $condition->submitConfigurationForm($form, $condition_values);
407
        // Update the original form values.
408
        $form_state->setValue(['visibility', $condition_id], $condition_values->getValues());
409
      }
410 411 412 413 414
      $this->blockSubmit($form, $form_state);
    }
  }

  /**
415
   * {@inheritdoc}
416
   */
417
  public function blockSubmit($form, FormStateInterface $form_state) {}
418

419 420 421 422 423 424 425 426 427 428
  /**
   * {@inheritdoc}
   */
  public function getMachineNameSuggestion() {
    $definition = $this->getPluginDefinition();
    $admin_label = $definition['admin_label'];

    // @todo This is basically the same as what is done in
    //   \Drupal\system\MachineNameController::transliterate(), so it might make
    //   sense to provide a common service for the two.
429
    $transliterated = $this->transliteration()->transliterate($admin_label, LanguageInterface::LANGCODE_DEFAULT, '_');
430 431 432 433 434 435 436 437 438 439 440 441

    $replace_pattern = '[^a-z0-9_.]+';

    $transliterated = Unicode::strtolower($transliterated);

    if (isset($replace_pattern)) {
      $transliterated = preg_replace('@' . $replace_pattern . '@', '', $transliterated);
    }

    return $transliterated;
  }

442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
  /**
   * Wraps the transliteration service.
   *
   * @return \Drupal\Component\Transliteration\TransliterationInterface
   */
  protected function transliteration() {
    if (!$this->transliteration) {
      $this->transliteration = \Drupal::transliteration();
    }
    return $this->transliteration;
  }

  /**
   * Sets the transliteration service.
   *
   * @param \Drupal\Component\Transliteration\TransliterationInterface $transliteration
   *   The transliteration service.
   */
  public function setTransliteration(TransliterationInterface $transliteration) {
    $this->transliteration = $transliteration;
  }

464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
  /**
   * Returns the cache contexts required for this block.
   *
   * @return array
   *   The required cache contexts IDs.
   */
  protected function getRequiredCacheContexts() {
    return array();
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheKeys() {
    // Return the required cache contexts, merged with the user-configured cache
    // contexts, if any.
    return array_merge($this->getRequiredCacheContexts(), $this->configuration['cache']['contexts']);
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheTags() {
    // If a block plugin's output changes, then it must be able to invalidate a
    // cache tag that affects all instances of this block: across themes and
    // across regions.
    $block_plugin_cache_tag = str_replace(':', '__', $this->getPluginID());
    return array('block_plugin' => array($block_plugin_cache_tag));
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheBin() {
498
    return 'render';
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
  }

  /**
   * {@inheritdoc}
   */
  public function getCacheMaxAge() {
    return (int)$this->configuration['cache']['max_age'];
  }

  /**
   * {@inheritdoc}
   */
  public function isCacheable() {
    // Similar to the page cache, a block is cacheable if it has a max age.
    // Blocks that should never be cached can override this method to simply
    // return FALSE.
    $max_age = $this->getCacheMaxAge();
    return $max_age === Cache::PERMANENT || $max_age > 0;
  }

519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
  /**
   * {@inheritdoc}
   */
  public function getVisibilityConditions() {
    if (!isset($this->conditionBag)) {
      $this->conditionBag = new ConditionPluginBag($this->conditionPluginManager(), $this->configuration['visibility']);
    }
    return $this->conditionBag;
  }

  /**
   * {@inheritdoc}
   */
  public function getVisibilityCondition($instance_id) {
    return $this->getVisibilityConditions()->get($instance_id);
  }

  /**
   * {@inheritdoc}
   */
  public function setVisibilityConfig($instance_id, array $configuration) {
    $this->getVisibilityConditions()->setInstanceConfiguration($instance_id, $configuration);
    return $this;
  }

  /**
   * Gets the condition plugin manager.
   *
   * @return \Drupal\Core\Executable\ExecutableManagerInterface
   *   The condition plugin manager.
   */
  protected function conditionPluginManager() {
    if (!isset($this->conditionPluginManager)) {
      $this->conditionPluginManager = \Drupal::service('plugin.manager.condition');
    }
    return $this->conditionPluginManager;
  }

  /**
   * Wraps the event dispatcher.
   *
   * @return \Symfony\Component\EventDispatcher\EventDispatcherInterface
   *   The event dispatcher.
   */
  protected function eventDispatcher() {
    return \Drupal::service('event_dispatcher');
  }

  /**
   * Wraps the context handler.
   *
   * @return \Drupal\Core\Plugin\Context\ContextHandlerInterface
   */
  protected function contextHandler() {
    return \Drupal::service('context.handler');
  }

576
}