You are here

function entity_embed_filter_format_edit_form_validate in Entity Embed 8

Validate callback to ensure filter order and allowed_html are compatible.

2 string references to 'entity_embed_filter_format_edit_form_validate'
entity_embed_form_filter_format_add_form_alter in ./entity_embed.module
Implements hook_form_FORM_ID_alter().
entity_embed_form_filter_format_edit_form_alter in ./entity_embed.module
Implements hook_form_FORM_ID_alter().

File

./entity_embed.module, line 117
Framework for allowing entities to be embedded in CKEditor.

Code

function entity_embed_filter_format_edit_form_validate($form, FormStateInterface $form_state) {

  // This validate handler is not applicable when using the 'Configure' button.
  if ($form_state
    ->getTriggeringElement()['#name'] === 'editor_configure') {
    return;
  }
  $allowed_html_path = [
    'filters',
    'filter_html',
    'settings',
    'allowed_html',
  ];
  $button_group_path = [
    'editor',
    'settings',
    'toolbar',
    'button_groups',
  ];
  $filter_html_settings_path = [
    'filters',
    'filter_html',
    'settings',
  ];
  $filter_html_enabled = $form_state
    ->getValue([
    'filters',
    'filter_html',
    'status',
  ]);
  $entity_embed_enabled = $form_state
    ->getValue([
    'filters',
    'entity_embed',
    'status',
  ]);
  if ($entity_embed_enabled && $filter_html_enabled && ($allowed_html = $form_state
    ->getValue($allowed_html_path))) {
    if ($button_groups = $form_state
      ->getValue($button_group_path)) {
      $buttons = [];
      $button_groups = json_decode($button_groups, TRUE);
      if (!empty($button_groups[0])) {
        foreach ($button_groups[0] as $button_group) {
          foreach ($button_group['items'] as $item) {
            $buttons[] = $item;
          }
        }
      }

      /** @var \Drupal\filter\Entity\FilterFormat $filter_format */
      $filter_format = $form_state
        ->getFormObject()
        ->getEntity();
      $filter_html = $filter_format
        ->filters()
        ->get('filter_html');
      $filter_html
        ->setConfiguration([
        'settings' => $form_state
          ->getValue($filter_html_settings_path),
      ]);
      $restrictions = $filter_html
        ->getHTMLRestrictions();
      $allowed = $restrictions['allowed'];
      $embeds = \Drupal::entityTypeManager()
        ->getStorage('embed_button')
        ->loadMultiple($buttons);

      /** @var \Drupal\embed\Entity\EmbedButton $embed */
      foreach ($embeds as $embed) {
        if ($embed
          ->getTypeId() !== 'entity') {
          continue;
        }

        // Require `<drupal-entity>` HTML tag if filter_html is enabled.
        if (!isset($allowed['drupal-entity'])) {
          $form_state
            ->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The %embed button requires <code>&lt;drupal-entity&gt;</code> among the allowed HTML tags.', [
            '%embed' => $embed
              ->label(),
          ]));
          break;
        }
        else {
          $required_attributes = [
            'data-entity-type',
            'data-entity-uuid',
            'data-entity-embed-display',
            'data-entity-embed-display-settings',
            'data-align',
            'data-caption',
            'data-embed-button',
            'alt',
            'title',
          ];

          // If there are no attributes, the allowed item is set to FALSE,
          // otherwise, it is set to an array.
          if ($allowed['drupal-entity'] === FALSE) {
            $missing_attributes = $required_attributes;
          }
          else {

            // If any of the attributes on the drupal-entity tag use wildcards,
            // iterate through and replace them with matching required
            // attributes.
            $wildcards = preg_grep('/\\*/', array_keys($allowed['drupal-entity']));
            if (!empty($wildcards)) {
              foreach ($wildcards as $wildcard) {
                $pattern = str_replace('*', '(.*)', $wildcard);
                $matches = preg_grep('/' . $pattern . '/', $required_attributes);
                foreach ($matches as $match) {
                  $allowed['drupal-entity'][$match] = 1;
                }
                unset($allowed['drupal-entity'][$wildcard]);
              }
            }
            $missing_attributes = array_diff($required_attributes, array_keys($allowed['drupal-entity']));
          }
          if ($missing_attributes) {
            $form_state
              ->setError($form['filters']['settings']['filter_html']['allowed_html'], t('The <code>&lt;drupal-entity&gt;</code> tag in the allowed HTML tags is missing the following attributes: <code>%list</code>.', [
              '%list' => implode(', ', $missing_attributes),
            ]));
            break;
          }
        }
      }
    }
  }
  $filters = $form_state
    ->getValue('filters');
  $get_filter_label = function ($filter_plugin_id) use ($form) {
    return (string) $form['filters']['order'][$filter_plugin_id]['filter']['#markup'];
  };

  // The "entity_embed" filter must run after "filter_align", "filter_caption",
  // and "filter_html_image_secure".
  if ($entity_embed_enabled) {
    $precedents = [
      'filter_align',
      'filter_caption',
      'filter_html_image_secure',
    ];
    $error_filters = [];
    foreach ($precedents as $filter_name) {

      // A filter that should run before entity embed filter.
      $precedent = $filters[$filter_name];
      if (empty($precedent['status']) || !isset($precedent['weight'])) {
        continue;
      }
      if ($precedent['weight'] >= $filters['entity_embed']['weight']) {
        $error_filters[$filter_name] = $get_filter_label($filter_name);
      }
    }
    if (!empty($error_filters)) {
      $singular = 'The %entity-embed-filter-label filter needs to be placed after the %filter filter.';
      $plural = 'The %entity-embed-filter-label filter needs to be placed after the following filters: %filters.';
      $error_message = \Drupal::translation()
        ->formatPlural(count($error_filters), $singular, $plural, [
        '%entity-embed-filter-label' => $get_filter_label('entity_embed'),
        '%filter' => reset($error_filters),
        '%filters' => implode(', ', $error_filters),
      ]);
      $form_state
        ->setErrorByName('filters', $error_message);
    }
  }
}