filters example


  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;
    }
/** * {@inheritdoc} */
  public function checkAccess(MediaLibraryState $state, AccountInterface $account) {
    $filter_format_id = $state->getOpenerParameters()['filter_format_id'];
    $filter_format = $this->filterStorage->load($filter_format_id);
    if (empty($filter_format)) {
      return AccessResult::forbidden()
        ->addCacheTags(['filter_format_list'])
        ->setReason("The text format '$filter_format_id' could not be loaded.");
    }
    $filters = $filter_format->filters();
    return $filter_format->access('use', $account, TRUE)
      ->andIf(AccessResult::allowedIf($filters->has('media_embed') && $filters->get('media_embed')->status === TRUE));
  }

  /** * {@inheritdoc} */
  public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
    $selected_media = $this->mediaStorage->load(reset($selected_ids));

    $response = new AjaxResponse();
    
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;

        

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
    // 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;
      }
      
/** * {@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');
      
'default_view_mode' => 'view_mode_1',
        'allowed_media_types' => [],
        'allowed_view_modes' => [
          'view_mode_1' => 'view_mode_1',
          '22222' => '22222',
          'view_mode_3' => 'view_mode_3',
        ],
      ],
    ])->save();

    if (!$with_alignment) {
      $filter_format->filters('filter_align')->setConfiguration(array_merge($filter_format->filters('filter_align')->getConfiguration()['status' => FALSE]));
    }

    // Test that view mode dependencies are returned from the MediaEmbed     // filter's ::getDependencies() method.     $expected_config_dependencies = [
      'core.entity_view_mode.media.view_mode_1',
      'core.entity_view_mode.media.22222',
      'core.entity_view_mode.media.view_mode_3',
    ];

    $dependencies = $filter_format->getDependencies();
    
if (stripos($attributes, 'method=') === false) {
            $attributes .= ' method="post"';
        }
        if (stripos($attributes, 'accept-charset=') === false) {
            $config = config(App::class);
            $attributes .= ' accept-charset="' . strtolower($config->charset) . '"';
        }

        $form = '<form action="' . $action . '"' . $attributes . ">\n";

        // Add CSRF field if enabled, but leave it out for GET requests and requests to external websites         $before = Services::filters()->getFilters()['before'];

        if ((in_array('csrf', $before, true) || array_key_exists('csrf', $before)) && strpos($actionbase_url()) !== false && ! stripos($form, 'method="get"')) {
            $form .= csrf_field($csrfId ?? null);
        }

        foreach ($hidden as $name => $value) {
            $form .= form_hidden($name$value);
        }

        return $form;
    }
}
$editor->setImageUploadSettings(['status' => FALSE]);
    }
    if (!$source_editing_is_already_enabled) {
      $settings = $editor->getSettings();
      // Remove the `sourceEditing` toolbar item.       unset($settings['toolbar']['items'][3]);
      // Remove the corresponding plugin settings (allowing `<img data-foo>`).       unset($settings['plugins']['ckeditor5_sourceEditing']);
      $editor->setSettings($settings);
      if ($filter_html_is_enabled) {
        // Stop allowing `<img data-foo>`.         $filter_html_config = $format->filters('filter_html')
          ->getConfiguration();
        $filter_html_config['settings']['allowed_html'] = str_replace('data-foo', '', $filter_html_config['settings']['allowed_html']);
        $format->setFilterConfig('filter_html', $filter_html_config);
      }
    }
    $format->trustData()->save();
    $editor->trustData()->save();

    // Run update path; snapshot the Text Format and Editor before and after.     $editor_before = Editor::load('test_format_image');
    $filter_format_before = $editor->getFilterFormat();
    
        if ($routes = $this->routes) {
            $routes = Services::routes()->loadRoutes();
        }

        $routes->setHTTPVerb($method);

        // Make sure any other classes that might call the request         // instance get the right one.         Services::injectMock('request', $request);

        // Make sure filters are reset between tests         Services::injectMock('filters', Services::filters(null, false));

        // Make sure validation is reset between tests         Services::injectMock('validation', Services::validation(null, false));

        $response = $this->app
            ->setContext('web')
            ->setRequest($request)
            ->run($routes, true);

        // Reset directory if it has been set         Services::router()->setDirectory(null);

        
        // if the page has been cached.         if (($response = $this->displayCache($cacheConfig)) instanceof ResponseInterface) {
            return $response;
        }

        $routeFilter = $this->tryToRouteIt($routes);

        $uri = $this->determinePath();

        if ($this->enableFilters) {
            // Start up the filters             $filters = Services::filters();

            // If any filters were specified within the routes file,             // we need to ensure it's active for the current request             if ($routeFilter !== null) {
                $multipleFiltersEnabled = config(Feature::class)->multipleFilters ?? false;
                if ($multipleFiltersEnabled) {
                    $filters->enableFilters($routeFilter, 'before');
                    $filters->enableFilters($routeFilter, 'after');
                } else {
                    // for backward compatibility                     $filters->enableFilter($routeFilter, 'before');
                    
        if ($routes = $this->routes) {
            $routes = Services::routes()->loadRoutes();
        }

        $routes->setHTTPVerb($method);

        // Make sure any other classes that might call the request         // instance get the right one.         Services::injectMock('request', $request);

        // Make sure filters are reset between tests         Services::injectMock('filters', Services::filters(null, false));

        $response = $this->app
            ->setContext('web')
            ->setRequest($request)
            ->run($routes, true);

        $output = \ob_get_contents();
        if (empty($response->getBody()) && ! empty($output)) {
            $response->setBody($output);
        }

        

  public function validate($toolbar_item, Constraint $constraint) {
    if (!$constraint instanceof CKEditor5MediaAndFilterSettingsInSyncConstraint) {
      throw new UnexpectedTypeException($constraint, __NAMESPACE__ . '\CKEditor5MediaAndFilterSettingsInSync');
    }
    $text_editor = $this->createTextEditorObjectFromContext();

    if (isset($text_editor->getSettings()['plugins']['media_media'])) {
      $cke5_plugin_overrides_allowed = $text_editor->getSettings()['plugins']['media_media']['allow_view_mode_override'];
      $filter_allowed_view_modes = $text_editor->getFilterFormat()->filters('media_embed')->getConfiguration()['settings']['allowed_view_modes'];
      $filter_media_plugin_label = $this->filterPluginManager->getDefinition('media_embed')['title']->render();
      $filter_media_allowed_view_modes_label = $this->typedConfigManager->getDefinition('filter_settings.media_embed')['mapping']['allowed_view_modes']['label'];

      // Whenever the CKEditor 5 plugin is configured to allow overrides, the       // filter must be configured to allow 2 or more view modes.       if ($cke5_plugin_overrides_allowed && count($filter_allowed_view_modes) < 2) {
        $this->context->addViolation($constraint->message, [
          '%cke5_media_plugin_label' => $this->t('Media'),
          '%cke5_allow_view_mode_override_label' => $this->t('Allow the user to override the default view mode'),
          '%filter_media_plugin_label' => $filter_media_plugin_label,
          '%filter_media_allowed_view_modes_label' => $filter_media_allowed_view_modes_label,
        ]);

    if (isset($instance_id)) {
      return $this->filterCollection->get($instance_id);
    }
    return $this->filterCollection;
  }

  /** * {@inheritdoc} */
  public function getPluginCollections() {
    return ['filters' => $this->filters()];
  }

  /** * {@inheritdoc} */
  public function setFilterConfig($instance_id, array $configuration) {
    $this->filters[$instance_id] = $configuration;
    if (isset($this->filterCollection)) {
      $this->filterCollection->setInstanceConfiguration($instance_id$configuration);
    }
    return $this;
  }
    // Allowed HTML field is readonly and its wrapper has a form-disabled class.     $this->assertNotEmpty($assert_session->waitForElement('css', '.js-form-item-filters-filter-html-settings-allowed-html.form-disabled'));
    $allowed_html_field = $assert_session->fieldExists('filters[filter_html][settings][allowed_html]');
    $this->assertTrue($allowed_html_field->hasAttribute('readonly'));
    $this->assertSame($this->allowedElements, $allowed_html_field->getValue());
    $this->saveNewTextFormat($page$assert_session);

    $assert_session->pageTextContains('Added text format ckeditor5');
    $assert_session->pageTextContains('Text formats and editors');

    // Confirm the filter config was updated with the correct allowed tags.     $this->assertSame($this->allowedElements, FilterFormat::load('ckeditor5')->filters('filter_html')->getConfiguration()['settings']['allowed_html']);

    $page->find('css', '[data-drupal-selector="edit-formats-ckeditor5"]')->clickLink('Configure');
    $assert_session->assertWaitOnAjaxRequest();

    // Add the block quote plugin to the CKEditor 5 toolbar.     $this->assertNotEmpty($assert_session->waitForElement('css', '.ckeditor5-toolbar-item-blockQuote'));
    $this->triggerKeyUp('.ckeditor5-toolbar-item-blockQuote', 'ArrowDown');
    $assert_session->assertWaitOnAjaxRequest();

    $allowed_with_blockquote = $this->allowedElements . ' <blockquote>';
    $assert_session->fieldExists('filters[filter_html][settings][allowed_html]');
    
Home | Imprint | This part of the site doesn't use cookies.