21431e7969a341f0f284d352f32d163215027aa0
[yaffs-website] / web / core / modules / filter / tests / src / Functional / FilterAdminTest.php
1 <?php
2
3 namespace Drupal\Tests\filter\Functional;
4
5 use Drupal\Component\Utility\Html;
6 use Drupal\Component\Utility\Unicode;
7 use Drupal\filter\Entity\FilterFormat;
8 use Drupal\node\Entity\Node;
9 use Drupal\node\Entity\NodeType;
10 use Drupal\Tests\BrowserTestBase;
11 use Drupal\user\RoleInterface;
12
13 /**
14  * Thoroughly test the administrative interface of the filter module.
15  *
16  * @group filter
17  */
18 class FilterAdminTest extends BrowserTestBase {
19
20   /**
21    * {@inheritdoc}
22    */
23   public static $modules = ['block', 'filter', 'node', 'filter_test_plugin', 'dblog'];
24
25   /**
26    * An user with administration permissions.
27    *
28    * @var \Drupal\user\UserInterface
29    */
30   protected $adminUser;
31
32   /**
33    * An user with permissions to create pages.
34    *
35    * @var \Drupal\user\UserInterface
36    */
37   protected $webUser;
38
39   /**
40    * {@inheritdoc}
41    */
42   protected function setUp() {
43     parent::setUp();
44
45     $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
46
47     // Set up the filter formats used by this test.
48     $basic_html_format = FilterFormat::create([
49       'format' => 'basic_html',
50       'name' => 'Basic HTML',
51       'filters' => [
52         'filter_html' => [
53           'status' => 1,
54           'settings' => [
55             'allowed_html' => '<p> <br> <strong> <a> <em>',
56           ],
57         ],
58       ],
59     ]);
60     $basic_html_format->save();
61     $restricted_html_format = FilterFormat::create([
62       'format' => 'restricted_html',
63       'name' => 'Restricted HTML',
64       'filters' => [
65         'filter_html' => [
66           'status' => TRUE,
67           'weight' => -10,
68           'settings' => [
69             'allowed_html' => '<p> <br> <strong> <a> <em> <h4>',
70           ],
71         ],
72         'filter_autop' => [
73           'status' => TRUE,
74           'weight' => 0,
75         ],
76         'filter_url' => [
77           'status' => TRUE,
78           'weight' => 0,
79         ],
80         'filter_htmlcorrector' => [
81           'status' => TRUE,
82           'weight' => 10,
83         ],
84       ],
85     ]);
86     $restricted_html_format->save();
87     $full_html_format = FilterFormat::create([
88       'format' => 'full_html',
89       'name' => 'Full HTML',
90       'weight' => 1,
91       'filters' => [],
92     ]);
93     $full_html_format->save();
94
95     $this->adminUser = $this->drupalCreateUser([
96       'administer filters',
97       $basic_html_format->getPermissionName(),
98       $restricted_html_format->getPermissionName(),
99       $full_html_format->getPermissionName(),
100       'access site reports',
101     ]);
102
103     $this->webUser = $this->drupalCreateUser(['create page content', 'edit own page content']);
104     user_role_grant_permissions('authenticated', [$basic_html_format->getPermissionName()]);
105     user_role_grant_permissions('anonymous', [$restricted_html_format->getPermissionName()]);
106     $this->drupalLogin($this->adminUser);
107     $this->drupalPlaceBlock('local_actions_block');
108   }
109
110   /**
111    * Tests the format administration functionality.
112    */
113   public function testFormatAdmin() {
114     // Add text format.
115     $this->drupalGet('admin/config/content/formats');
116     $this->clickLink('Add text format');
117     $format_id = Unicode::strtolower($this->randomMachineName());
118     $name = $this->randomMachineName();
119     $edit = [
120       'format' => $format_id,
121       'name' => $name,
122     ];
123     $this->drupalPostForm(NULL, $edit, t('Save configuration'));
124
125     // Verify default weight of the text format.
126     $this->drupalGet('admin/config/content/formats');
127     $this->assertFieldByName("formats[$format_id][weight]", 0, 'Text format weight was saved.');
128
129     // Change the weight of the text format.
130     $edit = [
131       "formats[$format_id][weight]" => 5,
132     ];
133     $this->drupalPostForm('admin/config/content/formats', $edit, t('Save'));
134     $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was saved.');
135
136     // Edit text format.
137     $this->drupalGet('admin/config/content/formats');
138     // Cannot use the assertNoLinkByHref method as it does partial url matching
139     // and 'admin/config/content/formats/manage/' . $format_id . '/disable'
140     // exists.
141     // @todo: See https://www.drupal.org/node/2031223 for the above.
142     $edit_link = $this->xpath('//a[@href=:href]', [
143       ':href' => \Drupal::url('entity.filter_format.edit_form', ['filter_format' => $format_id])
144     ]);
145     $this->assertNotEmpty($edit_link, format_string('Link href %href found.',
146       ['%href' => 'admin/config/content/formats/manage/' . $format_id]
147     ));
148     $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
149     $this->drupalPostForm(NULL, [], t('Save configuration'));
150
151     // Verify that the custom weight of the text format has been retained.
152     $this->drupalGet('admin/config/content/formats');
153     $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was retained.');
154
155     // Disable text format.
156     $this->assertLinkByHref('admin/config/content/formats/manage/' . $format_id . '/disable');
157     $this->drupalGet('admin/config/content/formats/manage/' . $format_id . '/disable');
158     $this->drupalPostForm(NULL, [], t('Disable'));
159
160     // Verify that disabled text format no longer exists.
161     $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
162     $this->assertResponse(404, 'Disabled text format no longer exists.');
163
164     // Attempt to create a format of the same machine name as the disabled
165     // format but with a different human readable name.
166     $edit = [
167       'format' => $format_id,
168       'name' => 'New format',
169     ];
170     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
171     $this->assertText('The machine-readable name is already in use. It must be unique.');
172
173     // Attempt to create a format of the same human readable name as the
174     // disabled format but with a different machine name.
175     $edit = [
176       'format' => 'new_format',
177       'name' => $name,
178     ];
179     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
180     $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', [
181       '%name' => $name,
182     ]));
183   }
184
185   /**
186    * Tests filter administration functionality.
187    */
188   public function testFilterAdmin() {
189     $first_filter = 'filter_autop';
190     $second_filter = 'filter_url';
191
192     $basic = 'basic_html';
193     $restricted = 'restricted_html';
194     $full = 'full_html';
195     $plain = 'plain_text';
196
197     // Check that the fallback format exists and cannot be disabled.
198     $this->assertTrue($plain == filter_fallback_format(), 'The fallback format is set to plain text.');
199     $this->drupalGet('admin/config/content/formats');
200     $this->assertNoRaw('admin/config/content/formats/manage/' . $plain . '/disable', 'Disable link for the fallback format not found.');
201     $this->drupalGet('admin/config/content/formats/manage/' . $plain . '/disable');
202     $this->assertResponse(403, 'The fallback format cannot be disabled.');
203
204     // Verify access permissions to Full HTML format.
205     $full_format = FilterFormat::load($full);
206     $this->assertTrue($full_format->access('use', $this->adminUser), 'Admin user may use Full HTML.');
207     $this->assertFalse($full_format->access('use', $this->webUser), 'Web user may not use Full HTML.');
208
209     // Add an additional tag and extra spaces and returns.
210     $edit = [];
211     $edit['filters[filter_html][settings][allowed_html]'] = "<a>   <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>\r\n<quote>";
212     $this->drupalPostForm('admin/config/content/formats/manage/' . $restricted, $edit, t('Save configuration'));
213     $this->assertUrl('admin/config/content/formats');
214     $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
215     $this->assertFieldByName('filters[filter_html][settings][allowed_html]', "<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <quote>", 'Allowed HTML tag added.');
216
217     $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
218       ':first' => 'filters[' . $first_filter . '][weight]',
219       ':second' => 'filters[' . $second_filter . '][weight]',
220     ]);
221     $this->assertNotEmpty($elements, 'Order confirmed in admin interface.');
222
223     // Reorder filters.
224     $edit = [];
225     $edit['filters[' . $second_filter . '][weight]'] = 1;
226     $edit['filters[' . $first_filter . '][weight]'] = 2;
227     $this->drupalPostForm(NULL, $edit, t('Save configuration'));
228     $this->assertUrl('admin/config/content/formats');
229     $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
230     $this->assertFieldByName('filters[' . $second_filter . '][weight]', 1, 'Order saved successfully.');
231     $this->assertFieldByName('filters[' . $first_filter . '][weight]', 2, 'Order saved successfully.');
232
233     $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
234       ':first' => 'filters[' . $second_filter . '][weight]',
235       ':second' => 'filters[' . $first_filter . '][weight]',
236     ]);
237     $this->assertNotEmpty($elements, 'Reorder confirmed in admin interface.');
238
239     $filter_format = FilterFormat::load($restricted);
240     foreach ($filter_format->filters() as $filter_name => $filter) {
241       if ($filter_name == $second_filter || $filter_name == $first_filter) {
242         $filters[] = $filter_name;
243       }
244     }
245     // Ensure that the second filter is now before the first filter.
246     $this->assertEqual($filter_format->filters($second_filter)->weight + 1, $filter_format->filters($first_filter)->weight, 'Order confirmed in configuration.');
247
248     // Add format.
249     $edit = [];
250     $edit['format'] = Unicode::strtolower($this->randomMachineName());
251     $edit['name'] = $this->randomMachineName();
252     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
253     $edit['filters[' . $second_filter . '][status]'] = TRUE;
254     $edit['filters[' . $first_filter . '][status]'] = TRUE;
255     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
256     $this->assertUrl('admin/config/content/formats');
257     $this->assertRaw(t('Added text format %format.', ['%format' => $edit['name']]), 'New filter created.');
258
259     filter_formats_reset();
260     $format = FilterFormat::load($edit['format']);
261     $this->assertNotNull($format, 'Format found in database.');
262     $this->drupalGet('admin/config/content/formats/manage/' . $format->id());
263     $this->assertSession()->checkboxChecked('roles[' . RoleInterface::AUTHENTICATED_ID . ']');
264     $this->assertSession()->checkboxChecked('filters[' . $second_filter . '][status]');
265     $this->assertSession()->checkboxChecked('filters[' . $first_filter . '][status]');
266
267     // Disable new filter.
268     $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', [], t('Disable'));
269     $this->assertUrl('admin/config/content/formats');
270     $this->assertRaw(t('Disabled text format %format.', ['%format' => $edit['name']]), 'Format successfully disabled.');
271
272     // Allow authenticated users on full HTML.
273     $format = FilterFormat::load($full);
274     $edit = [];
275     $edit['roles[' . RoleInterface::ANONYMOUS_ID . ']'] = 0;
276     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
277     $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, t('Save configuration'));
278     $this->assertUrl('admin/config/content/formats');
279     $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]), 'Full HTML format successfully updated.');
280
281     // Switch user.
282     $this->drupalLogin($this->webUser);
283
284     $this->drupalGet('node/add/page');
285     $this->assertRaw('<option value="' . $full . '">Full HTML</option>', 'Full HTML filter accessible.');
286
287     // Use basic HTML and see if it removes tags that are not allowed.
288     $body = '<em>' . $this->randomMachineName() . '</em>';
289     $extra_text = 'text';
290     $text = $body . '<random>' . $extra_text . '</random>';
291
292     $edit = [];
293     $edit['title[0][value]'] = $this->randomMachineName();
294     $edit['body[0][value]'] = $text;
295     $edit['body[0][format]'] = $basic;
296     $this->drupalPostForm('node/add/page', $edit, t('Save'));
297     $this->assertText(t('Basic page @title has been created.', ['@title' => $edit['title[0][value]']]), 'Filtered node created.');
298
299     // Verify that the creation message contains a link to a node.
300     $view_link = $this->xpath('//div[contains(@class, "messages")]//a[contains(@href, :href)]', [':href' => 'node/']);
301     $this->assertNotEmpty($view_link, 'The message area contains a link to a node');
302
303     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
304     $this->assertTrue($node, 'Node found in database.');
305
306     $this->drupalGet('node/' . $node->id());
307     $this->assertRaw($body . $extra_text, 'Filter removed invalid tag.');
308
309     // Use plain text and see if it escapes all tags, whether allowed or not.
310     // In order to test plain text, we have to enable the hidden variable for
311     // "show_fallback_format", which displays plain text in the format list.
312     $this->config('filter.settings')
313       ->set('always_show_fallback_choice', TRUE)
314       ->save();
315     $edit = [];
316     $edit['body[0][format]'] = $plain;
317     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
318     $this->drupalGet('node/' . $node->id());
319     $this->assertEscaped($text, 'The "Plain text" text format escapes all HTML tags.');
320     $this->config('filter.settings')
321       ->set('always_show_fallback_choice', FALSE)
322       ->save();
323
324     // Switch user.
325     $this->drupalLogin($this->adminUser);
326
327     // Clean up.
328     // Allowed tags.
329     $edit = [];
330     $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
331     $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, t('Save configuration'));
332     $this->assertUrl('admin/config/content/formats');
333     $this->drupalGet('admin/config/content/formats/manage/' . $basic);
334     $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], 'Changes reverted.');
335
336     // Full HTML.
337     $edit = [];
338     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = FALSE;
339     $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, t('Save configuration'));
340     $this->assertUrl('admin/config/content/formats');
341     $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]), 'Full HTML format successfully reverted.');
342     $this->drupalGet('admin/config/content/formats/manage/' . $full);
343     $this->assertFieldByName('roles[' . RoleInterface::AUTHENTICATED_ID . ']', $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'], 'Changes reverted.');
344
345     // Filter order.
346     $edit = [];
347     $edit['filters[' . $second_filter . '][weight]'] = 2;
348     $edit['filters[' . $first_filter . '][weight]'] = 1;
349     $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, t('Save configuration'));
350     $this->assertUrl('admin/config/content/formats');
351     $this->drupalGet('admin/config/content/formats/manage/' . $basic);
352     $this->assertFieldByName('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]'], 'Changes reverted.');
353     $this->assertFieldByName('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]'], 'Changes reverted.');
354   }
355
356   /**
357    * Tests the URL filter settings form is properly validated.
358    */
359   public function testUrlFilterAdmin() {
360     // The form does not save with an invalid filter URL length.
361     $edit = [
362       'filters[filter_url][settings][filter_url_length]' => $this->randomMachineName(4),
363     ];
364     $this->drupalPostForm('admin/config/content/formats/manage/basic_html', $edit, t('Save configuration'));
365     $this->assertNoRaw(t('The text format %format has been updated.', ['%format' => 'Basic HTML']));
366   }
367
368   /**
369    * Tests whether filter tips page is not HTML escaped.
370    */
371   public function testFilterTipHtmlEscape() {
372     $this->drupalLogin($this->adminUser);
373     global $base_url;
374
375     $site_name_with_markup = 'Filter test <script>alert(\'here\');</script> site name';
376     $this->config('system.site')->set('name', $site_name_with_markup)->save();
377
378     // It is not possible to test the whole filter tip page.
379     // Therefore we test only some parts.
380     $link = '<a href="' . $base_url . '">' . Html::escape($site_name_with_markup) . '</a>';
381     $ampersand = '&amp;';
382     $link_as_code = '<code>' . Html::escape($link) . '</code>';
383     $ampersand_as_code = '<code>' . Html::escape($ampersand) . '</code>';
384
385     $this->drupalGet('filter/tips');
386
387     $this->assertRaw('<td class="type">' . $link_as_code . '</td>');
388     $this->assertRaw('<td class="get">' . $link . '</td>');
389     $this->assertRaw('<td class="type">' . $ampersand_as_code . '</td>');
390     $this->assertRaw('<td class="get">' . $ampersand . '</td>');
391   }
392
393   /**
394    * Tests whether a field using a disabled format is rendered.
395    */
396   public function testDisabledFormat() {
397     // Create a node type and add a standard body field.
398     $node_type = NodeType::create(['type' => Unicode::strtolower($this->randomMachineName())]);
399     $node_type->save();
400     node_add_body_field($node_type, $this->randomString());
401
402     // Create a text format with a filter that returns a static string.
403     $format = FilterFormat::create([
404       'name' => $this->randomString(),
405       'format' => $format_id = Unicode::strtolower($this->randomMachineName()),
406     ]);
407     $format->setFilterConfig('filter_static_text', ['status' => TRUE]);
408     $format->save();
409
410     // Create a new node of the new node type.
411     $node = Node::create([
412       'type' => $node_type->id(),
413       'title' => $this->randomString(),
414     ]);
415     $body_value = $this->randomString();
416     $node->body->value = $body_value;
417     $node->body->format = $format_id;
418     $node->save();
419
420     // The format is used and we should see the static text instead of the body
421     // value.
422     $this->drupalGet($node->urlInfo());
423     $this->assertText('filtered text');
424
425     // Disable the format.
426     $format->disable()->save();
427
428     $this->drupalGet($node->urlInfo());
429
430     // The format is not used anymore.
431     $this->assertNoText('filtered text');
432     // The text is not displayed unfiltered or escaped.
433     $this->assertNoRaw($body_value);
434     $this->assertNoEscaped($body_value);
435
436     // Visit the dblog report page.
437     $this->drupalLogin($this->adminUser);
438     $this->drupalGet('admin/reports/dblog');
439     // The correct message has been logged.
440     $this->assertRaw(sprintf('Disabled text format: %s.', $format_id));
441
442     // Programmatically change the text format to something random so we trigger
443     // the missing text format message.
444     $format_id = $this->randomMachineName();
445     $node->body->format = $format_id;
446     $node->save();
447     $this->drupalGet($node->urlInfo());
448     // The text is not displayed unfiltered or escaped.
449     $this->assertNoRaw($body_value);
450     $this->assertNoEscaped($body_value);
451
452     // Visit the dblog report page.
453     $this->drupalGet('admin/reports/dblog');
454     // The missing text format message has been logged.
455     $this->assertRaw(sprintf('Missing text format: %s.', $format_id));
456   }
457
458 }