getFilterFormat example


class EditorAccessControlHandler extends EntityAccessControlHandler {

  /** * {@inheritdoc} */
  protected function checkAccess(EntityInterface $editor$operation, AccountInterface $account) {
    /** @var \Drupal\editor\EditorInterface $editor */
    return $editor->getFilterFormat()->access($operation$account, TRUE);
  }

}
$plugin_ids = array_keys($this->manager->getEnabledDefinitions($editor));
    $default_plugins_with_layercake = array_merge($default_plugins['ckeditor5_test_layercake']);

    // Sort on plugin id.     asort($default_plugins_with_layercake);
    $this->assertSame(array_values($default_plugins_with_layercake)$plugin_ids);
    $default_libraries_with_layercake = array_merge($default_libraries['ckeditor5_test/layercake']);
    sort($default_libraries_with_layercake);
    $this->assertSame($default_libraries_with_layercake$this->manager->getEnabledLibraries($editor));

    // Enable media embed filter which the CKEditor 5 media plugin requires.     $editor->getFilterFormat()->setFilterConfig('media_embed', ['status' => TRUE])->save();

    // Case 4: The CKEditor 5 media plugin should be enabled and the library     // should be available now that the media_embed is enabled.     $plugin_ids = array_keys($this->manager->getEnabledDefinitions($editor));
    $expected_plugins = array_merge($default_plugins[
      'ckeditor5_drupalMediaCaption',
      'ckeditor5_test_layercake',
      'media_media',
      'media_mediaAlign',
    ]);
    sort($expected_plugins);
    
'format' => $text_format->id(),
        // @see \Drupal\editor\Entity\Editor::__construct()         // @see \Drupal\ckeditor5\Plugin\Editor\CKEditor5::getDefaultSettings()         'editor' => 'ckeditor5',
      ]);
    $editor->setEditor('ckeditor5');

    $source_editing_additions = HTMLRestrictions::emptySet();
    // Compute the appropriate settings based on the CKEditor 4 configuration     // if it exists.     $old_editor = $editor->id() ? Editor::load($editor->id()) : NULL;
    $old_editor_restrictions = $old_editor ? HTMLRestrictions::fromTextFormat($old_editor->getFilterFormat()) : HTMLRestrictions::emptySet();
    // @todo Remove in https://www.drupal.org/project/drupal/issues/3245351     if ($old_editor) {
      $editor->setImageUploadSettings($old_editor->getImageUploadSettings());
    }
    if ($old_editor && $old_editor->getEditor() === 'ckeditor') {
      [$upgraded_settings$messages] = $this->createSettingsFromCKEditor4($old_editor->getSettings(), HTMLRestrictions::fromTextFormat($old_editor->getFilterFormat()));
      $editor->setSettings($upgraded_settings);
      // *Before* determining which elements are still needed for this text       // format, ensure that all already enabled plugins that are configurable       // have valid settings.       // For all already enabled plugins, find the ones that are configurable,

  private function configureViewModes(EditorInterface $editor) {
    $element_style_configuration = [];
    $toolbar_configuration = [];

    $media_embed_filter = $editor->getFilterFormat()->filters('media_embed');
    $media_bundles = MediaType::loadMultiple();
    $bundles_per_view_mode = [];
    $all_view_modes = $this->entityDisplayRepository->getViewModeOptions('media');
    $allowed_view_modes = $media_embed_filter->settings['allowed_view_modes'];
    $default_view_mode = $media_embed_filter->settings['default_view_mode'];
    // @todo Remove in https://www.drupal.org/project/drupal/issues/3277049.     // This is a workaround until the above issue is fixed to prevent the     // editor from crashing because the frontend expects the default view mode     // to exist in drupalElementStyles.     if (!array_key_exists($default_view_mode$allowed_view_modes)) {
      $allowed_view_modes[$default_view_mode] = $default_view_mode;
    }

class GlobalAttribute extends CKEditor5PluginDefault {

  /** * {@inheritdoc} */
  public function getDynamicPluginConfig(array $static_plugin_config, EditorInterface $editor): array {
    // This plugin is only loaded when filter_html is enabled.     assert($editor->getFilterFormat()->filters()->has('filter_html'));
    $filter_html = $editor->getFilterFormat()->filters('filter_html');
    $restrictions = HTMLRestrictions::fromFilterPluginInstance($filter_html);

    // Determine which tags are allowed by filter_html, excluding the global     // attribute `*` HTML tag, because that's what we're expanding this to right     // now.     $allowed_elements = $restrictions->getAllowedElements();
    unset($allowed_elements['*']);
    $allowed_tags = array_keys($allowed_elements);

    // Update the static plugin configuration: generate a `name` regular
/** * {@inheritdoc} */
  public function getDynamicPluginConfig(array $static_plugin_config, EditorInterface $editor): array {
    $media_type_ids = $this->mediaTypeStorage->getQuery()->execute();

    // Making the title for editor drupal media embed translatable.     $static_plugin_config['drupalMedia']['dialogSettings']['title'] = $this->t('Add or select media');

    if ($editor->hasAssociatedFilterFormat()) {
      $media_embed_filter = $editor->getFilterFormat()->filters()->get('media_embed');
      // Optionally limit the allowed media types based on the MediaEmbed       // setting. If the setting is empty, do not limit the options.       if (!empty($media_embed_filter->settings['allowed_media_types'])) {
        $media_type_ids = array_intersect_key($media_type_ids$media_embed_filter->settings['allowed_media_types']);
      }
    }
    if (in_array('image', $media_type_ids, TRUE)) {
      // Move image to first position.       // This workaround can be removed once this issue is fixed:       // @see https://www.drupal.org/project/drupal/issues/3073799       array_unshift($media_type_ids, 'image');
      
// @todo add current request as an argument after     // https://www.drupal.org/project/drupal/issues/2786941 has been resolved.     $request = $this->requestStack->getCurrentRequest();
    $uuid = $request->query->get('uuid');
    if (!$uuid || !Uuid::isValid($uuid)) {
      throw new BadRequestHttpException();
    }
    $media = $this->entityRepository->loadEntityByUuid('media', $uuid);
    if (!$media) {
      throw new NotFoundHttpException();
    }
    $filters = $editor->getFilterFormat()->filters();

    return AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status)
      ->andIf($media->access('view', $this->currentUser, TRUE))
      ->addCacheableDependency($editor->getFilterFormat());
  }

  /** * Gets the name of an image media item's source field. * * @param \Drupal\media\MediaInterface $media * The media item being embedded. * * @return string|null * The name of the image source field configured for the media item, or * NULL if the source field is not an image field. */
    // to be active AND the plugins it depends on are enabled (if any) AND the     // filter it depends on is enabled (if any).     // 2 - A conditionally enabled plugin that does depend on a toolbar item,     // and that toolbar item is active.     if ($definition->hasConditions()) {
      $conditions = $definition->getConditions();
      if (!array_key_exists('toolbarItem', $conditions)) {
        $conclusion = TRUE;
        // The filter this plugin depends on must be enabled.         if (array_key_exists('filter', $conditions)) {
          $required_filter = $conditions['filter'];
          $format_filters = $editor->getFilterFormat()->filters();
          $conclusion = $conclusion && $format_filters->has($required_filter) && $format_filters->get($required_filter)->status;
        }
        // The CKEditor 5 plugins this plugin depends on must be enabled.         if (array_key_exists('plugins', $conditions)) {
          $all_plugins = $this->ckeditor5PluginManager->getDefinitions();
          $dependencies = array_intersect_key($all_pluginsarray_flip($conditions['plugins']));
          $unmet_dependencies = array_diff_key($dependencies$enabled_plugins);
          $conclusion = $conclusion && empty($unmet_dependencies);
        }
        return $conclusion;
      }
      
      elseif ($definition->hasToolbarItems()) {
        if (empty(array_intersect($editor->getSettings()['toolbar']['items']array_keys($definition->getToolbarItems())))) {
          unset($definitions[$plugin_id]);
        }
      }
    }

    // Only enable the arbitrary HTML Support plugin on text formats with no     // HTML restrictions.     // @see https://ckeditor.com/docs/ckeditor5/latest/api/html-support.html     // @see https://github.com/ckeditor/ckeditor5/issues/9856     if ($editor->getFilterFormat()->getHtmlRestrictions() !== FALSE) {
      unset($definitions['ckeditor5_arbitraryHtmlSupport']);
    }

    // Evaluate `plugins` condition.     foreach ($definitions_with_plugins_condition as $plugin_id => $definition) {
      if (!empty(array_diff($definition->getConditions()['plugins']array_keys($definitions)))) {
        unset($definitions[$plugin_id]);
      }
    }

    if (!isset($definitions['ckeditor5_arbitraryHtmlSupport'])) {
      

  public function validate($toolbar_item, Constraint $constraint) {
    if (!$constraint instanceof FundamentalCompatibilityConstraint) {
      throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\FundamentalCompatibility');
    }

    $text_editor = $this->createTextEditorObjectFromContext();

    // First: the two fundamental checks against the text format. If any of     // them adds a constraint violation, return early, because it is a     // fundamental compatibility problem.     $this->checkNoMarkupFilters($text_editor->getFilterFormat()$constraint);
    if ($this->context->getViolations()->count() > 0) {
      return;
    }
    $this->checkHtmlRestrictionsAreCompatible($text_editor->getFilterFormat()$constraint);
    if ($this->context->getViolations()->count() > 0) {
      return;
    }

    // Second: ensure that all tags can actually be created.     $this->checkAllHtmlTagsAreCreatable($text_editor$constraint);

    
    // attributes are allowed (TRUE) or no attributes are allowed (FALSE),     // return early. Only proceed when some attributes are allowed (an array).     $allowed_elements = $restrictions->getAllowedElements(FALSE);
    assert(count($allowed_elements) === 1);
    $tag = array_key_first($allowed_elements);
    $attribute_restrictions = $allowed_elements[$tag];
    if (!is_array($attribute_restrictions)) {
      return;
    }

    $text_editor = $this->createTextEditorObjectFromContext();
    $text_format_allowed_elements = HTMLRestrictions::fromTextFormat($text_editor->getFilterFormat())
      ->getAllowedElements();
    // Any XSS-prevention related measures imposed by filter plugins are relayed     // through their ::getHtmlRestrictions() return value. The global attribute     // `*` HTML tag allows attributes to be forbidden.     // @see https://html.spec.whatwg.org/multipage/dom.html#global-attributes     // @see \Drupal\ckeditor5\HTMLRestrictions::validateAllowedRestrictionsPhase4()     // @see \Drupal\filter\Plugin\Filter\FilterHtml::getHTMLRestrictions()     $forbidden_attributes = [];
    if (array_key_exists('*', $text_format_allowed_elements)) {
      $forbidden_attributes = array_keys(array_filter($text_format_allowed_elements['*']function D$attribute_value_restriction, string $attribute_name) {
        return $attribute_value_restriction === FALSE;
      },
$editor = Editor::load('test_format');
    $settings = $editor->getSettings();

    // Allow the data-foo attribute in drupal-media via GHS. Also, add support     // for div's with data-foo attribute to ensure that drupal-media elements     // can be wrapped with other block elements.     $settings['plugins']['ckeditor5_sourceEditing']['allowed_tags'] = ['<drupal-media data-foo>', '<div data-bar>'];
    $editor->setSettings($settings);
    $editor->save();

    $filter_format = $editor->getFilterFormat();
    $filter_format->setFilterConfig('filter_html', [
      'status' => TRUE,
      'settings' => [
        'allowed_html' => '<p> <br> <strong> <em> <a href> <drupal-media data-entity-type data-entity-uuid data-align data-caption alt data-foo data-view-mode> <div data-bar>',
      ],
    ]);
    $filter_format->save();
    $this->assertSame([]array_map(
      function DConstraintViolation $v) {
        return (string) $v->getMessage();
      },
      
case 'imageUploadStatus':
          $image_upload_settings = $text_editor->getImageUploadSettings();
          if (!isset($image_upload_settings['status']) || (bool) $image_upload_settings['status'] !== TRUE) {
            $this->context->buildViolation($constraint->imageUploadStatusRequiredMessage)
              ->setParameter('%toolbar_item', (string) $toolbar_item_label)
              ->setInvalidValue($toolbar_item)
              ->addViolation();
          }
          break;

        case 'filter':
          $filters = $text_editor->getFilterFormat()->filters();
          if (!$filters->has($required_value) || !$filters->get($required_value)->status) {
            $filter_label = $filters->has($required_value)
              ? $filters->get($required_value)->getLabel()
              : $required_value;
            $this->context->buildViolation($constraint->filterRequiredMessage)
              ->setParameter('%toolbar_item', (string) $toolbar_item_label)
              ->setParameter('%filter', (string) $filter_label)
              ->setInvalidValue($toolbar_item)
              ->addViolation();
          }
          break;

        
'#title' => $this->t('Alternative text'),
      '#description' => $this->t('Short description of the image used by screen readers and displayed when the image is not loaded. This is important for accessibility.'),
      '#type' => 'textfield',
      '#required' => TRUE,
      '#required_error' => $this->t('Alternative text is required.<br />(Only in rare cases should this be left empty. To create empty alternative text, enter <code>""</code> — two double quotes without any content).'),
      '#default_value' => $alt,
      '#maxlength' => 2048,
    ];

    // When Drupal core's filter_align is being used, the text editor may     // offer the ability to change the alignment.     if (isset($image_element['data-align']) && $editor->getFilterFormat()->filters('filter_align')->status) {
      $form['align'] = [
        '#title' => $this->t('Align'),
        '#type' => 'radios',
        '#options' => [
          'none' => $this->t('None'),
          'left' => $this->t('Left'),
          'center' => $this->t('Center'),
          'right' => $this->t('Right'),
        ],
        '#default_value' => $image_element['data-align'] === '' ? 'none' : $image_element['data-align'],
        '#wrapper_attributes' => ['class' => ['container-inline']],
        
else {
      // Retrieve the user input from form state.       $media_embed_element = $form_state->get('media_embed_element');
      $has_caption = $form_state->get('hasCaption');
    }

    $form['#tree'] = TRUE;
    $form['#attached']['library'][] = 'editor/drupal.editor.dialog';
    $form['#prefix'] = '<div id="editor-media-dialog-form">';
    $form['#suffix'] = '</div>';

    $filters = $editor->getFilterFormat()->filters();
    $filter_html = $filters->get('filter_html');
    $filter_align = $filters->get('filter_align');
    $filter_caption = $filters->get('filter_caption');
    $media_embed_filter = $filters->get('media_embed');

    $allowed_attributes = [];
    if ($filter_html->status) {
      $restrictions = $filter_html->getHTMLRestrictions();
      $allowed_attributes = $restrictions['allowed']['drupal-media'];
    }

    
Home | Imprint | This part of the site doesn't use cookies.