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