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 FALSE, // Every tag is allowed.
128 'FilterFormatInterface::getHtmlRestrictions() works as expected for the full_html format.'
130 $this->assertIdentical(
131 $full_html_format->getFilterTypes(),
133 'FilterFormatInterface::getFilterTypes() works as expected for the full_html format.'
136 // Test on stupid_filtered_html, where nothing is allowed.
137 $stupid_filtered_html_format = FilterFormat::create([
138 'format' => 'stupid_filtered_html',
139 'name' => 'Stupid Filtered HTML',
144 'allowed_html' => '', // Nothing is allowed.
149 $stupid_filtered_html_format->save();
150 $this->assertIdentical(
151 $stupid_filtered_html_format->getHtmlRestrictions(),
152 ['allowed' => []], // No tag is allowed.
153 'FilterFormatInterface::getHtmlRestrictions() works as expected for the stupid_filtered_html format.'
155 $this->assertIdentical(
156 $stupid_filtered_html_format->getFilterTypes(),
157 [FilterInterface::TYPE_HTML_RESTRICTOR],
158 'FilterFormatInterface::getFilterTypes() works as expected for the stupid_filtered_html format.'
161 // Test on very_restricted_html, where there's two different filters of the
162 // FilterInterface::TYPE_HTML_RESTRICTOR type, each restricting in different ways.
163 $very_restricted_html_format = FilterFormat::create([
164 'format' => 'very_restricted_html',
165 'name' => 'Very Restricted HTML',
170 'allowed_html' => '<p> <br> <a href> <strong>',
173 'filter_test_restrict_tags_and_attributes' => [
180 'a' => ['href' => TRUE],
188 $very_restricted_html_format->save();
189 $this->assertIdentical(
190 $very_restricted_html_format->getHtmlRestrictions(),
195 'a' => ['href' => TRUE],
196 '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
199 'FilterFormatInterface::getHtmlRestrictions() works as expected for the very_restricted_html format.'
201 $this->assertIdentical(
202 $very_restricted_html_format->getFilterTypes(),
203 [FilterInterface::TYPE_HTML_RESTRICTOR],
204 'FilterFormatInterface::getFilterTypes() works as expected for the very_restricted_html format.'
207 // Test on nonsensical_restricted_html, where the allowed attribute values
208 // contain asterisks, which do not have any meaning, but which we also
209 // cannot prevent because configuration can be modified outside of forms.
210 $nonsensical_restricted_html = FilterFormat::create([
211 'format' => 'nonsensical_restricted_html',
212 'name' => 'Nonsensical Restricted HTML',
217 'allowed_html' => '<a> <b class> <c class="*"> <d class="foo bar-* *">',
222 $nonsensical_restricted_html->save();
223 $this->assertIdentical(
224 $nonsensical_restricted_html->getHtmlRestrictions(),
228 'b' => ['class' => TRUE],
229 'c' => ['class' => TRUE],
230 'd' => ['class' => ['foo' => TRUE, 'bar-*' => TRUE]],
231 '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
234 'FilterFormatInterface::getHtmlRestrictions() works as expected for the nonsensical_restricted_html format.'
236 $this->assertIdentical(
237 $very_restricted_html_format->getFilterTypes(),
238 [FilterInterface::TYPE_HTML_RESTRICTOR],
239 'FilterFormatInterface::getFilterTypes() works as expected for the very_restricted_html format.'
244 * Tests the 'processed_text' element.
246 * check_markup() is a wrapper for the 'processed_text' element, for use in
247 * simple scenarios; the 'processed_text' element has more advanced features:
248 * it lets filters attach assets, associate cache tags and define
249 * #lazy_builder callbacks.
250 * This test focuses solely on those advanced features.
252 public function testProcessedTextElement() {
253 FilterFormat::create([
254 'format' => 'element_test',
255 'name' => 'processed_text element test format',
257 'filter_test_assets' => [
261 'filter_test_cache_tags' => [
265 'filter_test_cache_contexts' => [
269 'filter_test_cache_merge' => [
273 'filter_test_placeholders' => [
277 // Run the HTML corrector filter last, because it has the potential to
278 // break the placeholders added by the filter_test_placeholders filter.
279 'filter_htmlcorrector' => [
287 '#type' => 'processed_text',
288 '#text' => '<p>Hello, world!</p>',
289 '#format' => 'element_test',
291 drupal_render_root($build);
293 // Verify the attachments and cacheability metadata.
294 $expected_attachments = [
295 // The assets attached by the filter_test_assets filter.
299 // The placeholders attached that still need to be processed.
300 'placeholders' => [],
302 $this->assertEqual($expected_attachments, $build['#attached'], 'Expected attachments present');
303 $expected_cache_tags = [
304 // The cache tag set by the processed_text element itself.
305 'config:filter.format.element_test',
306 // The cache tags set by the filter_test_cache_tags filter.
309 // The cache tags set by the filter_test_cache_merge filter.
312 $this->assertEqual($expected_cache_tags, $build['#cache']['tags'], 'Expected cache tags present.');
313 $expected_cache_contexts = [
314 // The cache context set by the filter_test_cache_contexts filter.
315 'languages:' . LanguageInterface::TYPE_CONTENT,
316 // The default cache contexts for Renderer.
317 'languages:' . LanguageInterface::TYPE_INTERFACE,
319 // The cache tags set by the filter_test_cache_merge filter.
322 $this->assertEqual($expected_cache_contexts, $build['#cache']['contexts'], 'Expected cache contexts present.');
323 $expected_markup = '<p>Hello, world!</p><p>This is a dynamic llama.</p>';
324 $this->assertEqual($expected_markup, $build['#markup'], 'Expected #lazy_builder callback has been applied.');
328 * Tests the function of the typed data type.
330 public function testTypedDataAPI() {
331 $definition = DataDefinition::create('filter_format');
332 $data = \Drupal::typedDataManager()->create($definition);
334 $this->assertTrue($data instanceof OptionsProviderInterface, 'Typed data object implements \Drupal\Core\TypedData\OptionsProviderInterface');
336 $filtered_html_user = $this->createUser(['uid' => 2], [
337 FilterFormat::load('filtered_html')->getPermissionName(),
340 // Test with anonymous user.
341 $user = new AnonymousUserSession();
342 \Drupal::currentUser()->setAccount($user);
344 $expected_available_options = [
345 'filtered_html' => 'Filtered HTML',
346 'full_html' => 'Full HTML',
347 'filter_test' => 'Test format',
348 'plain_text' => 'Plain text',
351 $available_values = $data->getPossibleValues();
352 $this->assertEqual($available_values, array_keys($expected_available_options));
353 $available_options = $data->getPossibleOptions();
354 $this->assertEqual($available_options, $expected_available_options);
356 $allowed_values = $data->getSettableValues($user);
357 $this->assertEqual($allowed_values, ['plain_text']);
358 $allowed_options = $data->getSettableOptions($user);
359 $this->assertEqual($allowed_options, ['plain_text' => 'Plain text']);
361 $data->setValue('foo');
362 $violations = $data->validate();
363 $this->assertFilterFormatViolation($violations, 'foo');
365 // Make sure the information provided by a violation is correct.
366 $violation = $violations[0];
367 $this->assertEqual($violation->getRoot(), $data, 'Violation root is filter format.');
368 $this->assertEqual($violation->getPropertyPath(), '', 'Violation property path is correct.');
369 $this->assertEqual($violation->getInvalidValue(), 'foo', 'Violation contains invalid value.');
371 $data->setValue('plain_text');
372 $violations = $data->validate();
373 $this->assertEqual(count($violations), 0, "No validation violation for format 'plain_text' found");
375 // Anonymous doesn't have access to the 'filtered_html' format.
376 $data->setValue('filtered_html');
377 $violations = $data->validate();
378 $this->assertFilterFormatViolation($violations, 'filtered_html');
380 // Set user with access to 'filtered_html' format.
381 \Drupal::currentUser()->setAccount($filtered_html_user);
382 $violations = $data->validate();
383 $this->assertEqual(count($violations), 0, "No validation violation for accessible format 'filtered_html' found.");
385 $allowed_values = $data->getSettableValues($filtered_html_user);
386 $this->assertEqual($allowed_values, ['filtered_html', 'plain_text']);
387 $allowed_options = $data->getSettableOptions($filtered_html_user);
388 $expected_allowed_options = [
389 'filtered_html' => 'Filtered HTML',
390 'plain_text' => 'Plain text',
392 $this->assertEqual($allowed_options, $expected_allowed_options);
396 * Tests that FilterFormat::preSave() only saves customized plugins.
398 public function testFilterFormatPreSave() {
399 /** @var \Drupal\filter\FilterFormatInterface $crazy_format */
400 $crazy_format = FilterFormat::create([
405 'filter_html_escape' => [
413 'allowed_html' => '<p>',
418 $crazy_format->save();
419 // Use config to directly load the configuration and check that only enabled
420 // or customized plugins are saved to configuration.
421 $filters = $this->config('filter.format.crazy')->get('filters');
422 $this->assertEqual(['filter_html_escape', 'filter_html'], array_keys($filters));
424 // Disable a plugin to ensure that disabled plugins with custom settings are
425 // stored in configuration.
426 $crazy_format->setFilterConfig('filter_html_escape', ['status' => FALSE]);
427 $crazy_format->save();
428 $filters = $this->config('filter.format.crazy')->get('filters');
429 $this->assertEqual(['filter_html_escape', 'filter_html'], array_keys($filters));
431 // Set the settings as per default to ensure that disable plugins in this
432 // state are not stored in configuration.
433 $crazy_format->setFilterConfig('filter_html_escape', ['weight' => -10]);
434 $crazy_format->save();
435 $filters = $this->config('filter.format.crazy')->get('filters');
436 $this->assertEqual(['filter_html'], array_keys($filters));
440 * Checks if an expected violation exists in the given violations.
442 * @param \Symfony\Component\Validator\ConstraintViolationListInterface $violations
443 * The violations to assert.
444 * @param mixed $invalid_value
445 * The expected invalid value.
447 public function assertFilterFormatViolation(ConstraintViolationListInterface $violations, $invalid_value) {
448 $filter_format_violation_found = FALSE;
449 foreach ($violations as $violation) {
450 if ($violation->getRoot() instanceof FilterFormatDataType && $violation->getInvalidValue() === $invalid_value) {
451 $filter_format_violation_found = TRUE;
455 $this->assertTrue($filter_format_violation_found, format_string('Validation violation for invalid value "%invalid_value" found', ['%invalid_value' => $invalid_value]));
459 * Tests that filter format dependency removal works.
461 * Ensure that modules providing filter plugins are required when the plugin
462 * is in use, and that only disabled plugins are removed from format
463 * configuration entities rather than the configuration entities being
466 * @see \Drupal\filter\Entity\FilterFormat::onDependencyRemoval()
467 * @see filter_system_info_alter()
469 public function testDependencyRemoval() {
470 $this->installSchema('user', ['users_data']);
471 $filter_format = FilterFormat::load('filtered_html');
473 // Disable the filter_test_restrict_tags_and_attributes filter plugin but
474 // have custom configuration so that the filter plugin is still configured
475 // in filtered_html the filter format.
480 $filter_format->setFilterConfig('filter_test_restrict_tags_and_attributes', $filter_config)->save();
481 // Use the get method to match the assert after the module has been
483 $filters = $filter_format->get('filters');
484 $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.');
486 drupal_static_reset('filter_formats');
487 \Drupal::entityManager()->getStorage('filter_format')->resetCache();
488 $module_data = _system_rebuild_module_data();
489 $this->assertFalse(isset($module_data['filter_test']->info['required']), 'The filter_test module is required.');
491 // Verify that a dependency exists on the module that provides the filter
492 // plugin since it has configuration for the disabled plugin.
493 $this->assertEqual(['module' => ['filter_test']], $filter_format->getDependencies());
495 // Uninstall the module.
496 \Drupal::service('module_installer')->uninstall(['filter_test']);
498 // Verify the filter format still exists but the dependency and filter is
500 \Drupal::entityManager()->getStorage('filter_format')->resetCache();
501 $filter_format = FilterFormat::load('filtered_html');
502 $this->assertEqual([], $filter_format->getDependencies());
503 // Use the get method since the FilterFormat::filters() method only returns
505 $filters = $filter_format->get('filters');
506 $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.');