Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / filter / tests / src / Kernel / FilterAPITest.php
1 <?php
2
3 namespace Drupal\Tests\filter\Kernel;
4
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;
14
15 /**
16  * Tests the behavior of the API of the Filter module.
17  *
18  * @group filter
19  */
20 class FilterAPITest extends EntityKernelTestBase {
21
22   public static $modules = ['system', 'filter', 'filter_test', 'user'];
23
24   protected function setUp() {
25     parent::setUp();
26
27     $this->installConfig(['system', 'filter', 'filter_test']);
28   }
29
30   /**
31    * Tests that the filter order is respected.
32    */
33   public function testCheckMarkupFilterOrder() {
34     // Create crazy HTML format.
35     $crazy_format = FilterFormat::create([
36       'format' => 'crazy',
37       'name' => 'Crazy',
38       'weight' => 1,
39       'filters' => [
40         'filter_html_escape' => [
41           'weight' => 10,
42           'status' => 1,
43         ],
44         'filter_html' => [
45           'weight' => -10,
46           'status' => 1,
47           'settings' => [
48             'allowed_html' => '<p>',
49           ],
50         ],
51       ],
52     ]);
53     $crazy_format->save();
54
55     $text = "<p>Llamas are <not> awesome!</p>";
56     $expected_filtered_text = "&lt;p&gt;Llamas are  awesome!&lt;/p&gt;";
57
58     $this->assertEqual(check_markup($text, 'crazy'), $expected_filtered_text, 'Filters applied in correct order.');
59   }
60
61   /**
62    * Tests the ability to apply only a subset of filters.
63    */
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!";
68
69     $actual_filtered_text = check_markup($text, 'filtered_html', '', []);
70     $this->verbose("Actual:<pre>$actual_filtered_text</pre>Expected:<pre>$expected_filtered_text</pre>");
71     $this->assertEqual(
72       $actual_filtered_text,
73       $expected_filtered_text,
74       'Expected filter result.'
75     );
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>");
78     $this->assertEqual(
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.'
82     );
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>");
89     $this->assertEqual(
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.'
93     );
94   }
95
96   /**
97    * Tests the following functions for a variety of formats:
98    *   - \Drupal\filter\Entity\FilterFormatInterface::getHtmlRestrictions()
99    *   - \Drupal\filter\Entity\FilterFormatInterface::getFilterTypes()
100    */
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(),
106       [
107         'allowed' => [
108           'p' => FALSE,
109           'br' => FALSE,
110           'strong' => FALSE,
111           'a' => ['href' => TRUE, 'hreflang' => TRUE],
112           '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
113         ],
114       ],
115       'FilterFormatInterface::getHtmlRestrictions() works as expected for the filtered_html format.'
116     );
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.'
121     );
122
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.
128       FALSE,
129       'FilterFormatInterface::getHtmlRestrictions() works as expected for the full_html format.'
130     );
131     $this->assertIdentical(
132       $full_html_format->getFilterTypes(),
133       [],
134       'FilterFormatInterface::getFilterTypes() works as expected for the full_html format.'
135     );
136
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',
141       'filters' => [
142         'filter_html' => [
143           'status' => 1,
144           'settings' => [
145             // Nothing is allowed.
146             'allowed_html' => '',
147           ],
148         ],
149       ],
150     ]);
151     $stupid_filtered_html_format->save();
152     $this->assertIdentical(
153       $stupid_filtered_html_format->getHtmlRestrictions(),
154       // No tag is allowed.
155       ['allowed' => []],
156       'FilterFormatInterface::getHtmlRestrictions() works as expected for the stupid_filtered_html format.'
157     );
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.'
162     );
163
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',
169       'filters' => [
170         'filter_html' => [
171           'status' => 1,
172           'settings' => [
173             'allowed_html' => '<p> <br> <a href> <strong>',
174           ],
175         ],
176         'filter_test_restrict_tags_and_attributes' => [
177           'status' => 1,
178           'settings' => [
179             'restrictions' => [
180               'allowed' => [
181                 'p' => TRUE,
182                 'br' => FALSE,
183                 'a' => ['href' => TRUE],
184                 'em' => TRUE,
185               ],
186             ],
187           ],
188         ],
189       ],
190     ]);
191     $very_restricted_html_format->save();
192     $this->assertIdentical(
193       $very_restricted_html_format->getHtmlRestrictions(),
194       [
195         'allowed' => [
196           'p' => FALSE,
197           'br' => FALSE,
198           'a' => ['href' => TRUE],
199           '*' => ['style' => FALSE, 'on*' => FALSE, 'lang' => TRUE, 'dir' => ['ltr' => TRUE, 'rtl' => TRUE]],
200         ],
201       ],
202       'FilterFormatInterface::getHtmlRestrictions() works as expected for the very_restricted_html format.'
203     );
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.'
208     );
209
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',
216       'filters' => [
217         'filter_html' => [
218           'status' => 1,
219           'settings' => [
220             'allowed_html' => '<a> <b class> <c class="*"> <d class="foo bar-* *">',
221           ],
222         ],
223       ],
224     ]);
225     $nonsensical_restricted_html->save();
226     $this->assertIdentical(
227       $nonsensical_restricted_html->getHtmlRestrictions(),
228       [
229         'allowed' => [
230           'a' => FALSE,
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]],
235         ],
236       ],
237       'FilterFormatInterface::getHtmlRestrictions() works as expected for the nonsensical_restricted_html format.'
238     );
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.'
243     );
244   }
245
246   /**
247    * Tests the 'processed_text' element.
248    *
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.
254    */
255   public function testProcessedTextElement() {
256     FilterFormat::create([
257       'format' => 'element_test',
258       'name' => 'processed_text element test format',
259       'filters' => [
260         'filter_test_assets' => [
261           'weight' => -1,
262           'status' => TRUE,
263         ],
264         'filter_test_cache_tags' => [
265           'weight' => 0,
266           'status' => TRUE,
267         ],
268         'filter_test_cache_contexts' => [
269           'weight' => 0,
270           'status' => TRUE,
271         ],
272         'filter_test_cache_merge' => [
273           'weight' => 0,
274           'status' => TRUE,
275         ],
276         'filter_test_placeholders' => [
277           'weight' => 1,
278           'status' => TRUE,
279         ],
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' => [
283           'weight' => 10,
284           'status' => TRUE,
285         ],
286       ],
287     ])->save();
288
289     $build = [
290       '#type' => 'processed_text',
291       '#text' => '<p>Hello, world!</p>',
292       '#format' => 'element_test',
293     ];
294     drupal_render_root($build);
295
296     // Verify the attachments and cacheability metadata.
297     $expected_attachments = [
298       // The assets attached by the filter_test_assets filter.
299       'library' => [
300         'filter/caption',
301       ],
302       // The placeholders attached that still need to be processed.
303       'placeholders' => [],
304     ];
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.
310       'foo:bar',
311       'foo:baz',
312       // The cache tags set by the filter_test_cache_merge filter.
313       'merge:tag',
314     ];
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,
321       'theme',
322       // The cache tags set by the filter_test_cache_merge filter.
323       'user.permissions',
324     ];
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.');
328   }
329
330   /**
331    * Tests the function of the typed data type.
332    */
333   public function testTypedDataAPI() {
334     $definition = DataDefinition::create('filter_format');
335     $data = \Drupal::typedDataManager()->create($definition);
336
337     $this->assertTrue($data instanceof OptionsProviderInterface, 'Typed data object implements \Drupal\Core\TypedData\OptionsProviderInterface');
338
339     $filtered_html_user = $this->createUser(['uid' => 2], [
340       FilterFormat::load('filtered_html')->getPermissionName(),
341     ]);
342
343     // Test with anonymous user.
344     $user = new AnonymousUserSession();
345     \Drupal::currentUser()->setAccount($user);
346
347     $expected_available_options = [
348       'filtered_html' => 'Filtered HTML',
349       'full_html' => 'Full HTML',
350       'filter_test' => 'Test format',
351       'plain_text' => 'Plain text',
352     ];
353
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);
358
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']);
363
364     $data->setValue('foo');
365     $violations = $data->validate();
366     $this->assertFilterFormatViolation($violations, 'foo');
367
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.');
373
374     $data->setValue('plain_text');
375     $violations = $data->validate();
376     $this->assertEqual(count($violations), 0, "No validation violation for format 'plain_text' found");
377
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');
382
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.");
387
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',
394     ];
395     $this->assertEqual($allowed_options, $expected_allowed_options);
396   }
397
398   /**
399    * Tests that FilterFormat::preSave() only saves customized plugins.
400    */
401   public function testFilterFormatPreSave() {
402     /** @var \Drupal\filter\FilterFormatInterface $crazy_format */
403     $crazy_format = FilterFormat::create([
404       'format' => 'crazy',
405       'name' => 'Crazy',
406       'weight' => 1,
407       'filters' => [
408         'filter_html_escape' => [
409           'weight' => 10,
410           'status' => 1,
411         ],
412         'filter_html' => [
413           'weight' => -10,
414           'status' => 1,
415           'settings' => [
416             'allowed_html' => '<p>',
417           ],
418         ],
419       ],
420     ]);
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));
426
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));
433
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));
440   }
441
442   /**
443    * Checks if an expected violation exists in the given violations.
444    *
445    * @param \Symfony\Component\Validator\ConstraintViolationListInterface $violations
446    *   The violations to assert.
447    * @param mixed $invalid_value
448    *   The expected invalid value.
449    */
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;
455         break;
456       }
457     }
458     $this->assertTrue($filter_format_violation_found, format_string('Validation violation for invalid value "%invalid_value" found', ['%invalid_value' => $invalid_value]));
459   }
460
461   /**
462    * Tests that filter format dependency removal works.
463    *
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
467    * deleted.
468    *
469    * @see \Drupal\filter\Entity\FilterFormat::onDependencyRemoval()
470    * @see filter_system_info_alter()
471    */
472   public function testDependencyRemoval() {
473     $this->installSchema('user', ['users_data']);
474     $filter_format = FilterFormat::load('filtered_html');
475
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.
479     $filter_config = [
480       'weight' => 20,
481       'status' => 0,
482     ];
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
485     // uninstalled.
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.');
488
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.');
493
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());
497
498     // Uninstall the module.
499     \Drupal::service('module_installer')->uninstall(['filter_test']);
500
501     // Verify the filter format still exists but the dependency and filter is
502     // gone.
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
507     // existing plugins.
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.');
510   }
511
512 }