3 namespace Drupal\Tests\filter\Kernel;
5 use Drupal\Core\Language\LanguageInterface;
6 use Drupal\Core\Session\AnonymousUserSession;
7 use Drupal\Core\TypedData\OptionsProviderInterface;
8 use Drupal\Core\TypedData\DataDefinition;
9 use Drupal\filter\Entity\FilterFormat;
10 use Drupal\filter\Plugin\DataType\FilterFormat as FilterFormatDataType;
11 use Drupal\filter\Plugin\FilterInterface;
12 use Drupal\KernelTests\Core\Entity\EntityKernelTestBase;
13 use Symfony\Component\Validator\ConstraintViolationListInterface;
16 * Tests the behavior of the API of the Filter module.
20 class FilterAPITest extends EntityKernelTestBase {
22 public static $modules = ['system', 'filter', 'filter_test', 'user'];
24 protected function setUp() {
27 $this->installConfig(['system', 'filter', 'filter_test']);
31 * Tests that the filter order is respected.
33 public function testCheckMarkupFilterOrder() {
34 // Create crazy HTML format.
35 $crazy_format = FilterFormat::create([
40 'filter_html_escape' => [
48 'allowed_html' => '<p>',
53 $crazy_format->save();
55 $text = "<p>Llamas are <not> awesome!</p>";
56 $expected_filtered_text = "<p>Llamas are awesome!</p>";
58 $this->assertEqual(check_markup($text, 'crazy'), $expected_filtered_text, 'Filters applied in correct order.');
62 * Tests the ability to apply only a subset of filters.
64 public function testCheckMarkupFilterSubset() {
65 $text = "Text with <marquee>evil content and</marquee> a URL: https://www.drupal.org!";
66 $expected_filtered_text = "Text with evil content and a URL: <a href=\"https://www.drupal.org\">https://www.drupal.org</a>!";
67 $expected_filter_text_without_html_generators = "Text with evil content and a URL: https://www.drupal.org!";
69 $actual_filtered_text = check_markup($text, 'filtered_html', '', []);
70 $this->verbose("Actual:<pre>$actual_filtered_text</pre>Expected:<pre>$expected_filtered_text</pre>");
72 $actual_filtered_text,
73 $expected_filtered_text,
74 'Expected filter result.'
76 $actual_filtered_text_without_html_generators = check_markup($text, 'filtered_html', '', [FilterInterface::TYPE_MARKUP_LANGUAGE]);
77 $this->verbose("Actual:<pre>$actual_filtered_text_without_html_generators</pre>Expected:<pre>$expected_filter_text_without_html_generators</pre>");
79 $actual_filtered_text_without_html_generators,
80 $expected_filter_text_without_html_generators,
81 'Expected filter result when skipping FilterInterface::TYPE_MARKUP_LANGUAGE filters.'
83 // Related to @see FilterSecurityTest.php/testSkipSecurityFilters(), but
84 // this check focuses on the ability to filter multiple filter types at once.
85 // Drupal core only ships with these two types of filters, so this is the
86 // most extensive test possible.
87 $actual_filtered_text_without_html_generators = check_markup($text, 'filtered_html', '', [FilterInterface::TYPE_HTML_RESTRICTOR, FilterInterface::TYPE_MARKUP_LANGUAGE]);
88 $this->verbose("Actual:<pre>$actual_filtered_text_without_html_generators</pre>Expected:<pre>$expected_filter_text_without_html_generators</pre>");
90 $actual_filtered_text_without_html_generators,
91 $expected_filter_text_without_html_generators,
92 'Expected filter result when skipping FilterInterface::TYPE_MARKUP_LANGUAGE filters, even when trying to disable filters of the FilterInterface::TYPE_HTML_RESTRICTOR type.'
97 * Tests the following functions for a variety of formats:
98 * - \Drupal\filter\Entity\FilterFormatInterface::getHtmlRestrictions()
99 * - \Drupal\filter\Entity\FilterFormatInterface::getFilterTypes()
101 public function testFilterFormatAPI() {
102 // Test on filtered_html.
103 $filtered_html_format = FilterFormat::load('filtered_html');
104 $this->assertIdentical(
105 $filtered_html_format->getHtmlRestrictions(),
111 'a' => ['href' => TRUE, 'hreflang' => TRUE],
112 '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
115 'FilterFormatInterface::getHtmlRestrictions() works as expected for the filtered_html format.'
117 $this->assertIdentical(
118 $filtered_html_format->getFilterTypes(),
119 [FilterInterface::TYPE_HTML_RESTRICTOR, FilterInterface::TYPE_MARKUP_LANGUAGE],
120 'FilterFormatInterface::getFilterTypes() works as expected for the filtered_html format.'
123 // Test on full_html.
124 $full_html_format = FilterFormat::load('full_html');
125 $this->assertIdentical(
126 $full_html_format->getHtmlRestrictions(),
127 // Every tag is allowed.
129 'FilterFormatInterface::getHtmlRestrictions() works as expected for the full_html format.'
131 $this->assertIdentical(
132 $full_html_format->getFilterTypes(),
134 'FilterFormatInterface::getFilterTypes() works as expected for the full_html format.'
137 // Test on stupid_filtered_html, where nothing is allowed.
138 $stupid_filtered_html_format = FilterFormat::create([
139 'format' => 'stupid_filtered_html',
140 'name' => 'Stupid Filtered HTML',
145 // Nothing is allowed.
146 'allowed_html' => '',
151 $stupid_filtered_html_format->save();
152 $this->assertIdentical(
153 $stupid_filtered_html_format->getHtmlRestrictions(),
154 // No tag is allowed.
156 'FilterFormatInterface::getHtmlRestrictions() works as expected for the stupid_filtered_html format.'
158 $this->assertIdentical(
159 $stupid_filtered_html_format->getFilterTypes(),
160 [FilterInterface::TYPE_HTML_RESTRICTOR],
161 'FilterFormatInterface::getFilterTypes() works as expected for the stupid_filtered_html format.'
164 // Test on very_restricted_html, where there's two different filters of the
165 // FilterInterface::TYPE_HTML_RESTRICTOR type, each restricting in different ways.
166 $very_restricted_html_format = FilterFormat::create([
167 'format' => 'very_restricted_html',
168 'name' => 'Very Restricted HTML',
173 'allowed_html' => '<p> <br> <a href> <strong>',
176 'filter_test_restrict_tags_and_attributes' => [
183 'a' => ['href' => TRUE],
191 $very_restricted_html_format->save();
192 $this->assertIdentical(
193 $very_restricted_html_format->getHtmlRestrictions(),
198 'a' => ['href' => TRUE],
199 '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
202 'FilterFormatInterface::getHtmlRestrictions() works as expected for the very_restricted_html format.'
204 $this->assertIdentical(
205 $very_restricted_html_format->getFilterTypes(),
206 [FilterInterface::TYPE_HTML_RESTRICTOR],
207 'FilterFormatInterface::getFilterTypes() works as expected for the very_restricted_html format.'
210 // Test on nonsensical_restricted_html, where the allowed attribute values
211 // contain asterisks, which do not have any meaning, but which we also
212 // cannot prevent because configuration can be modified outside of forms.
213 $nonsensical_restricted_html = FilterFormat::create([
214 'format' => 'nonsensical_restricted_html',
215 'name' => 'Nonsensical Restricted HTML',
220 'allowed_html' => '<a> <b class> <c class="*"> <d class="foo bar-* *">',
225 $nonsensical_restricted_html->save();
226 $this->assertIdentical(
227 $nonsensical_restricted_html->getHtmlRestrictions(),
231 'b' => ['class' => TRUE],
232 'c' => ['class' => TRUE],
233 'd' => ['class' => ['foo' => TRUE, 'bar-*' => TRUE]],
234 '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
237 'FilterFormatInterface::getHtmlRestrictions() works as expected for the nonsensical_restricted_html format.'
239 $this->assertIdentical(
240 $very_restricted_html_format->getFilterTypes(),
241 [FilterInterface::TYPE_HTML_RESTRICTOR],
242 'FilterFormatInterface::getFilterTypes() works as expected for the very_restricted_html format.'
247 * Tests the 'processed_text' element.
249 * Function check_markup() is a wrapper for the 'processed_text' element, for
250 * use in simple scenarios; the 'processed_text' element has more advanced
251 * features: it lets filters attach assets, associate cache tags and define
252 * #lazy_builder callbacks.
253 * This test focuses solely on those advanced features.
255 public function testProcessedTextElement() {
256 FilterFormat::create([
257 'format' => 'element_test',
258 'name' => 'processed_text element test format',
260 'filter_test_assets' => [
264 'filter_test_cache_tags' => [
268 'filter_test_cache_contexts' => [
272 'filter_test_cache_merge' => [
276 'filter_test_placeholders' => [
280 // Run the HTML corrector filter last, because it has the potential to
281 // break the placeholders added by the filter_test_placeholders filter.
282 'filter_htmlcorrector' => [
290 '#type' => 'processed_text',
291 '#text' => '<p>Hello, world!</p>',
292 '#format' => 'element_test',
294 drupal_render_root($build);
296 // Verify the attachments and cacheability metadata.
297 $expected_attachments = [
298 // The assets attached by the filter_test_assets filter.
302 // The placeholders attached that still need to be processed.
303 'placeholders' => [],
305 $this->assertEqual($expected_attachments, $build['#attached'], 'Expected attachments present');
306 $expected_cache_tags = [
307 // The cache tag set by the processed_text element itself.
308 'config:filter.format.element_test',
309 // The cache tags set by the filter_test_cache_tags filter.
312 // The cache tags set by the filter_test_cache_merge filter.
315 $this->assertEqual($expected_cache_tags, $build['#cache']['tags'], 'Expected cache tags present.');
316 $expected_cache_contexts = [
317 // The cache context set by the filter_test_cache_contexts filter.
318 'languages:' . LanguageInterface::TYPE_CONTENT,
319 // The default cache contexts for Renderer.
320 'languages:' . LanguageInterface::TYPE_INTERFACE,
322 // The cache tags set by the filter_test_cache_merge filter.
325 $this->assertEqual($expected_cache_contexts, $build['#cache']['contexts'], 'Expected cache contexts present.');
326 $expected_markup = '<p>Hello, world!</p><p>This is a dynamic llama.</p>';
327 $this->assertEqual($expected_markup, $build['#markup'], 'Expected #lazy_builder callback has been applied.');
331 * Tests the function of the typed data type.
333 public function testTypedDataAPI() {
334 $definition = DataDefinition::create('filter_format');
335 $data = \Drupal::typedDataManager()->create($definition);
337 $this->assertTrue($data instanceof OptionsProviderInterface, 'Typed data object implements \Drupal\Core\TypedData\OptionsProviderInterface');
339 $filtered_html_user = $this->createUser(['uid' => 2], [
340 FilterFormat::load('filtered_html')->getPermissionName(),
343 // Test with anonymous user.
344 $user = new AnonymousUserSession();
345 \Drupal::currentUser()->setAccount($user);
347 $expected_available_options = [
348 'filtered_html' => 'Filtered HTML',
349 'full_html' => 'Full HTML',
350 'filter_test' => 'Test format',
351 'plain_text' => 'Plain text',
354 $available_values = $data->getPossibleValues();
355 $this->assertEqual($available_values, array_keys($expected_available_options));
356 $available_options = $data->getPossibleOptions();
357 $this->assertEqual($available_options, $expected_available_options);
359 $allowed_values = $data->getSettableValues($user);
360 $this->assertEqual($allowed_values, ['plain_text']);
361 $allowed_options = $data->getSettableOptions($user);
362 $this->assertEqual($allowed_options, ['plain_text' => 'Plain text']);
364 $data->setValue('foo');
365 $violations = $data->validate();
366 $this->assertFilterFormatViolation($violations, 'foo');
368 // Make sure the information provided by a violation is correct.
369 $violation = $violations[0];
370 $this->assertEqual($violation->getRoot(), $data, 'Violation root is filter format.');
371 $this->assertEqual($violation->getPropertyPath(), '', 'Violation property path is correct.');
372 $this->assertEqual($violation->getInvalidValue(), 'foo', 'Violation contains invalid value.');
374 $data->setValue('plain_text');
375 $violations = $data->validate();
376 $this->assertEqual(count($violations), 0, "No validation violation for format 'plain_text' found");
378 // Anonymous doesn't have access to the 'filtered_html' format.
379 $data->setValue('filtered_html');
380 $violations = $data->validate();
381 $this->assertFilterFormatViolation($violations, 'filtered_html');
383 // Set user with access to 'filtered_html' format.
384 \Drupal::currentUser()->setAccount($filtered_html_user);
385 $violations = $data->validate();
386 $this->assertEqual(count($violations), 0, "No validation violation for accessible format 'filtered_html' found.");
388 $allowed_values = $data->getSettableValues($filtered_html_user);
389 $this->assertEqual($allowed_values, ['filtered_html', 'plain_text']);
390 $allowed_options = $data->getSettableOptions($filtered_html_user);
391 $expected_allowed_options = [
392 'filtered_html' => 'Filtered HTML',
393 'plain_text' => 'Plain text',
395 $this->assertEqual($allowed_options, $expected_allowed_options);
399 * Tests that FilterFormat::preSave() only saves customized plugins.
401 public function testFilterFormatPreSave() {
402 /** @var \Drupal\filter\FilterFormatInterface $crazy_format */
403 $crazy_format = FilterFormat::create([
408 'filter_html_escape' => [
416 'allowed_html' => '<p>',
421 $crazy_format->save();
422 // Use config to directly load the configuration and check that only enabled
423 // or customized plugins are saved to configuration.
424 $filters = $this->config('filter.format.crazy')->get('filters');
425 $this->assertEqual(['filter_html_escape', 'filter_html'], array_keys($filters));
427 // Disable a plugin to ensure that disabled plugins with custom settings are
428 // stored in configuration.
429 $crazy_format->setFilterConfig('filter_html_escape', ['status' => FALSE]);
430 $crazy_format->save();
431 $filters = $this->config('filter.format.crazy')->get('filters');
432 $this->assertEqual(['filter_html_escape', 'filter_html'], array_keys($filters));
434 // Set the settings as per default to ensure that disable plugins in this
435 // state are not stored in configuration.
436 $crazy_format->setFilterConfig('filter_html_escape', ['weight' => -10]);
437 $crazy_format->save();
438 $filters = $this->config('filter.format.crazy')->get('filters');
439 $this->assertEqual(['filter_html'], array_keys($filters));
443 * Checks if an expected violation exists in the given violations.
445 * @param \Symfony\Component\Validator\ConstraintViolationListInterface $violations
446 * The violations to assert.
447 * @param mixed $invalid_value
448 * The expected invalid value.
450 public function assertFilterFormatViolation(ConstraintViolationListInterface $violations, $invalid_value) {
451 $filter_format_violation_found = FALSE;
452 foreach ($violations as $violation) {
453 if ($violation->getRoot() instanceof FilterFormatDataType && $violation->getInvalidValue() === $invalid_value) {
454 $filter_format_violation_found = TRUE;
458 $this->assertTrue($filter_format_violation_found, format_string('Validation violation for invalid value "%invalid_value" found', ['%invalid_value' => $invalid_value]));
462 * Tests that filter format dependency removal works.
464 * Ensure that modules providing filter plugins are required when the plugin
465 * is in use, and that only disabled plugins are removed from format
466 * configuration entities rather than the configuration entities being
469 * @see \Drupal\filter\Entity\FilterFormat::onDependencyRemoval()
470 * @see filter_system_info_alter()
472 public function testDependencyRemoval() {
473 $this->installSchema('user', ['users_data']);
474 $filter_format = FilterFormat::load('filtered_html');
476 // Disable the filter_test_restrict_tags_and_attributes filter plugin but
477 // have custom configuration so that the filter plugin is still configured
478 // in filtered_html the filter format.
483 $filter_format->setFilterConfig('filter_test_restrict_tags_and_attributes', $filter_config)->save();
484 // Use the get method to match the assert after the module has been
486 $filters = $filter_format->get('filters');
487 $this->assertTrue(isset($filters['filter_test_restrict_tags_and_attributes']), 'The filter plugin filter_test_restrict_tags_and_attributes is configured by the filtered_html filter format.');
489 drupal_static_reset('filter_formats');
490 \Drupal::entityManager()->getStorage('filter_format')->resetCache();
491 $module_data = \Drupal::service('extension.list.module')->reset()->getList();
492 $this->assertFalse(isset($module_data['filter_test']->info['required']), 'The filter_test module is required.');
494 // Verify that a dependency exists on the module that provides the filter
495 // plugin since it has configuration for the disabled plugin.
496 $this->assertEqual(['module' => ['filter_test']], $filter_format->getDependencies());
498 // Uninstall the module.
499 \Drupal::service('module_installer')->uninstall(['filter_test']);
501 // Verify the filter format still exists but the dependency and filter is
503 \Drupal::entityManager()->getStorage('filter_format')->resetCache();
504 $filter_format = FilterFormat::load('filtered_html');
505 $this->assertEqual([], $filter_format->getDependencies());
506 // Use the get method since the FilterFormat::filters() method only returns
508 $filters = $filter_format->get('filters');
509 $this->assertFalse(isset($filters['filter_test_restrict_tags_and_attributes']), 'The filter plugin filter_test_restrict_tags_and_attributes is not configured by the filtered_html filter format.');