Updated Drupal to 8.6. This goes with the following updates because it's possible...
[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\Core\Url;
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 = mb_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     $destination = Url::fromRoute('filter.admin_overview')->toString();
139     $edit_href = Url::fromRoute('entity.filter_format.edit_form', ['filter_format' => $format_id], ['query' => ['destination' => $destination]])->toString();
140     $this->assertSession()->linkByHrefExists($edit_href);
141     $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
142     $this->drupalPostForm(NULL, [], t('Save configuration'));
143
144     // Verify that the custom weight of the text format has been retained.
145     $this->drupalGet('admin/config/content/formats');
146     $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was retained.');
147
148     // Disable text format.
149     $this->assertLinkByHref('admin/config/content/formats/manage/' . $format_id . '/disable');
150     $this->drupalGet('admin/config/content/formats/manage/' . $format_id . '/disable');
151     $this->drupalPostForm(NULL, [], t('Disable'));
152
153     // Verify that disabled text format no longer exists.
154     $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
155     $this->assertResponse(404, 'Disabled text format no longer exists.');
156
157     // Attempt to create a format of the same machine name as the disabled
158     // format but with a different human readable name.
159     $edit = [
160       'format' => $format_id,
161       'name' => 'New format',
162     ];
163     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
164     $this->assertText('The machine-readable name is already in use. It must be unique.');
165
166     // Attempt to create a format of the same human readable name as the
167     // disabled format but with a different machine name.
168     $edit = [
169       'format' => 'new_format',
170       'name' => $name,
171     ];
172     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
173     $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', [
174       '%name' => $name,
175     ]));
176   }
177
178   /**
179    * Tests filter administration functionality.
180    */
181   public function testFilterAdmin() {
182     $first_filter = 'filter_autop';
183     $second_filter = 'filter_url';
184
185     $basic = 'basic_html';
186     $restricted = 'restricted_html';
187     $full = 'full_html';
188     $plain = 'plain_text';
189
190     // Check that the fallback format exists and cannot be disabled.
191     $this->assertTrue($plain == filter_fallback_format(), 'The fallback format is set to plain text.');
192     $this->drupalGet('admin/config/content/formats');
193     $this->assertNoRaw('admin/config/content/formats/manage/' . $plain . '/disable', 'Disable link for the fallback format not found.');
194     $this->drupalGet('admin/config/content/formats/manage/' . $plain . '/disable');
195     $this->assertResponse(403, 'The fallback format cannot be disabled.');
196
197     // Verify access permissions to Full HTML format.
198     $full_format = FilterFormat::load($full);
199     $this->assertTrue($full_format->access('use', $this->adminUser), 'Admin user may use Full HTML.');
200     $this->assertFalse($full_format->access('use', $this->webUser), 'Web user may not use Full HTML.');
201
202     // Add an additional tag and extra spaces and returns.
203     $edit = [];
204     $edit['filters[filter_html][settings][allowed_html]'] = "<a>   <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>\r\n<quote>";
205     $this->drupalPostForm('admin/config/content/formats/manage/' . $restricted, $edit, t('Save configuration'));
206     $this->assertUrl('admin/config/content/formats');
207     $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
208     $this->assertFieldByName('filters[filter_html][settings][allowed_html]', "<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <quote>", 'Allowed HTML tag added.');
209
210     $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
211       ':first' => 'filters[' . $first_filter . '][weight]',
212       ':second' => 'filters[' . $second_filter . '][weight]',
213     ]);
214     $this->assertNotEmpty($elements, 'Order confirmed in admin interface.');
215
216     // Reorder filters.
217     $edit = [];
218     $edit['filters[' . $second_filter . '][weight]'] = 1;
219     $edit['filters[' . $first_filter . '][weight]'] = 2;
220     $this->drupalPostForm(NULL, $edit, t('Save configuration'));
221     $this->assertUrl('admin/config/content/formats');
222     $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
223     $this->assertFieldByName('filters[' . $second_filter . '][weight]', 1, 'Order saved successfully.');
224     $this->assertFieldByName('filters[' . $first_filter . '][weight]', 2, 'Order saved successfully.');
225
226     $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
227       ':first' => 'filters[' . $second_filter . '][weight]',
228       ':second' => 'filters[' . $first_filter . '][weight]',
229     ]);
230     $this->assertNotEmpty($elements, 'Reorder confirmed in admin interface.');
231
232     $filter_format = FilterFormat::load($restricted);
233     foreach ($filter_format->filters() as $filter_name => $filter) {
234       if ($filter_name == $second_filter || $filter_name == $first_filter) {
235         $filters[] = $filter_name;
236       }
237     }
238     // Ensure that the second filter is now before the first filter.
239     $this->assertEqual($filter_format->filters($second_filter)->weight + 1, $filter_format->filters($first_filter)->weight, 'Order confirmed in configuration.');
240
241     // Add format.
242     $edit = [];
243     $edit['format'] = mb_strtolower($this->randomMachineName());
244     $edit['name'] = $this->randomMachineName();
245     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
246     $edit['filters[' . $second_filter . '][status]'] = TRUE;
247     $edit['filters[' . $first_filter . '][status]'] = TRUE;
248     $this->drupalPostForm('admin/config/content/formats/add', $edit, t('Save configuration'));
249     $this->assertUrl('admin/config/content/formats');
250     $this->assertRaw(t('Added text format %format.', ['%format' => $edit['name']]), 'New filter created.');
251
252     filter_formats_reset();
253     $format = FilterFormat::load($edit['format']);
254     $this->assertNotNull($format, 'Format found in database.');
255     $this->drupalGet('admin/config/content/formats/manage/' . $format->id());
256     $this->assertSession()->checkboxChecked('roles[' . RoleInterface::AUTHENTICATED_ID . ']');
257     $this->assertSession()->checkboxChecked('filters[' . $second_filter . '][status]');
258     $this->assertSession()->checkboxChecked('filters[' . $first_filter . '][status]');
259
260     // Disable new filter.
261     $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', [], t('Disable'));
262     $this->assertUrl('admin/config/content/formats');
263     $this->assertRaw(t('Disabled text format %format.', ['%format' => $edit['name']]), 'Format successfully disabled.');
264
265     // Allow authenticated users on full HTML.
266     $format = FilterFormat::load($full);
267     $edit = [];
268     $edit['roles[' . RoleInterface::ANONYMOUS_ID . ']'] = 0;
269     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
270     $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, t('Save configuration'));
271     $this->assertUrl('admin/config/content/formats');
272     $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]), 'Full HTML format successfully updated.');
273
274     // Switch user.
275     $this->drupalLogin($this->webUser);
276
277     $this->drupalGet('node/add/page');
278     $this->assertRaw('<option value="' . $full . '">Full HTML</option>', 'Full HTML filter accessible.');
279
280     // Use basic HTML and see if it removes tags that are not allowed.
281     $body = '<em>' . $this->randomMachineName() . '</em>';
282     $extra_text = 'text';
283     $text = $body . '<random>' . $extra_text . '</random>';
284
285     $edit = [];
286     $edit['title[0][value]'] = $this->randomMachineName();
287     $edit['body[0][value]'] = $text;
288     $edit['body[0][format]'] = $basic;
289     $this->drupalPostForm('node/add/page', $edit, t('Save'));
290     $this->assertText(t('Basic page @title has been created.', ['@title' => $edit['title[0][value]']]), 'Filtered node created.');
291
292     // Verify that the creation message contains a link to a node.
293     $view_link = $this->xpath('//div[contains(@class, "messages")]//a[contains(@href, :href)]', [':href' => 'node/']);
294     $this->assertNotEmpty($view_link, 'The message area contains a link to a node');
295
296     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
297     $this->assertTrue($node, 'Node found in database.');
298
299     $this->drupalGet('node/' . $node->id());
300     $this->assertRaw($body . $extra_text, 'Filter removed invalid tag.');
301
302     // Use plain text and see if it escapes all tags, whether allowed or not.
303     // In order to test plain text, we have to enable the hidden variable for
304     // "show_fallback_format", which displays plain text in the format list.
305     $this->config('filter.settings')
306       ->set('always_show_fallback_choice', TRUE)
307       ->save();
308     $edit = [];
309     $edit['body[0][format]'] = $plain;
310     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
311     $this->drupalGet('node/' . $node->id());
312     $this->assertEscaped($text, 'The "Plain text" text format escapes all HTML tags.');
313     $this->config('filter.settings')
314       ->set('always_show_fallback_choice', FALSE)
315       ->save();
316
317     // Switch user.
318     $this->drupalLogin($this->adminUser);
319
320     // Clean up.
321     // Allowed tags.
322     $edit = [];
323     $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
324     $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, t('Save configuration'));
325     $this->assertUrl('admin/config/content/formats');
326     $this->drupalGet('admin/config/content/formats/manage/' . $basic);
327     $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], 'Changes reverted.');
328
329     // Full HTML.
330     $edit = [];
331     $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = FALSE;
332     $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, t('Save configuration'));
333     $this->assertUrl('admin/config/content/formats');
334     $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]), 'Full HTML format successfully reverted.');
335     $this->drupalGet('admin/config/content/formats/manage/' . $full);
336     $this->assertFieldByName('roles[' . RoleInterface::AUTHENTICATED_ID . ']', $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'], 'Changes reverted.');
337
338     // Filter order.
339     $edit = [];
340     $edit['filters[' . $second_filter . '][weight]'] = 2;
341     $edit['filters[' . $first_filter . '][weight]'] = 1;
342     $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, t('Save configuration'));
343     $this->assertUrl('admin/config/content/formats');
344     $this->drupalGet('admin/config/content/formats/manage/' . $basic);
345     $this->assertFieldByName('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]'], 'Changes reverted.');
346     $this->assertFieldByName('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]'], 'Changes reverted.');
347   }
348
349   /**
350    * Tests the URL filter settings form is properly validated.
351    */
352   public function testUrlFilterAdmin() {
353     // The form does not save with an invalid filter URL length.
354     $edit = [
355       'filters[filter_url][settings][filter_url_length]' => $this->randomMachineName(4),
356     ];
357     $this->drupalPostForm('admin/config/content/formats/manage/basic_html', $edit, t('Save configuration'));
358     $this->assertNoRaw(t('The text format %format has been updated.', ['%format' => 'Basic HTML']));
359   }
360
361   /**
362    * Tests whether filter tips page is not HTML escaped.
363    */
364   public function testFilterTipHtmlEscape() {
365     $this->drupalLogin($this->adminUser);
366     global $base_url;
367
368     $site_name_with_markup = 'Filter test <script>alert(\'here\');</script> site name';
369     $this->config('system.site')->set('name', $site_name_with_markup)->save();
370
371     // It is not possible to test the whole filter tip page.
372     // Therefore we test only some parts.
373     $link = '<a href="' . $base_url . '">' . Html::escape($site_name_with_markup) . '</a>';
374     $ampersand = '&amp;';
375     $link_as_code = '<code>' . Html::escape($link) . '</code>';
376     $ampersand_as_code = '<code>' . Html::escape($ampersand) . '</code>';
377
378     $this->drupalGet('filter/tips');
379
380     $this->assertRaw('<td class="type">' . $link_as_code . '</td>');
381     $this->assertRaw('<td class="get">' . $link . '</td>');
382     $this->assertRaw('<td class="type">' . $ampersand_as_code . '</td>');
383     $this->assertRaw('<td class="get">' . $ampersand . '</td>');
384   }
385
386   /**
387    * Tests whether a field using a disabled format is rendered.
388    */
389   public function testDisabledFormat() {
390     // Create a node type and add a standard body field.
391     $node_type = NodeType::create(['type' => mb_strtolower($this->randomMachineName())]);
392     $node_type->save();
393     node_add_body_field($node_type, $this->randomString());
394
395     // Create a text format with a filter that returns a static string.
396     $format = FilterFormat::create([
397       'name' => $this->randomString(),
398       'format' => $format_id = mb_strtolower($this->randomMachineName()),
399     ]);
400     $format->setFilterConfig('filter_static_text', ['status' => TRUE]);
401     $format->save();
402
403     // Create a new node of the new node type.
404     $node = Node::create([
405       'type' => $node_type->id(),
406       'title' => $this->randomString(),
407     ]);
408     $body_value = $this->randomString();
409     $node->body->value = $body_value;
410     $node->body->format = $format_id;
411     $node->save();
412
413     // The format is used and we should see the static text instead of the body
414     // value.
415     $this->drupalGet($node->urlInfo());
416     $this->assertText('filtered text');
417
418     // Disable the format.
419     $format->disable()->save();
420
421     $this->drupalGet($node->urlInfo());
422
423     // The format is not used anymore.
424     $this->assertNoText('filtered text');
425     // The text is not displayed unfiltered or escaped.
426     $this->assertNoRaw($body_value);
427     $this->assertNoEscaped($body_value);
428
429     // Visit the dblog report page.
430     $this->drupalLogin($this->adminUser);
431     $this->drupalGet('admin/reports/dblog');
432     // The correct message has been logged.
433     $this->assertRaw(sprintf('Disabled text format: %s.', $format_id));
434
435     // Programmatically change the text format to something random so we trigger
436     // the missing text format message.
437     $format_id = $this->randomMachineName();
438     $node->body->format = $format_id;
439     $node->save();
440     $this->drupalGet($node->urlInfo());
441     // The text is not displayed unfiltered or escaped.
442     $this->assertNoRaw($body_value);
443     $this->assertNoEscaped($body_value);
444
445     // Visit the dblog report page.
446     $this->drupalGet('admin/reports/dblog');
447     // The missing text format message has been logged.
448     $this->assertRaw(sprintf('Missing text format: %s.', $format_id));
449   }
450
451 }