FilterAdminTest.php 18.4 KB
Newer Older
1 2
<?php

3
namespace Drupal\Tests\filter\Functional;
4

5
use Drupal\Component\Utility\Html;
6
use Drupal\Core\Url;
7 8 9
use Drupal\filter\Entity\FilterFormat;
use Drupal\node\Entity\Node;
use Drupal\node\Entity\NodeType;
10
use Drupal\Tests\BrowserTestBase;
11
use Drupal\user\RoleInterface;
12

13
/**
14 15 16
 * Thoroughly test the administrative interface of the filter module.
 *
 * @group filter
17
 */
18
class FilterAdminTest extends BrowserTestBase {
19 20

  /**
21
   * {@inheritdoc}
22
   */
23 24 25 26 27 28 29
  protected static $modules = [
    'block',
    'filter',
    'node',
    'filter_test_plugin',
    'dblog',
  ];
30

31 32 33 34 35
  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'classy';

36
  /**
37
   * A user with administration permissions.
38 39 40 41 42 43
   *
   * @var \Drupal\user\UserInterface
   */
  protected $adminUser;

  /**
44
   * A user with permissions to create pages.
45 46 47 48 49
   *
   * @var \Drupal\user\UserInterface
   */
  protected $webUser;

50 51 52
  /**
   * {@inheritdoc}
   */
53
  protected function setUp(): void {
54 55
    parent::setUp();

56
    $this->drupalCreateContentType(['type' => 'page', 'name' => 'Basic page']);
57 58

    // Set up the filter formats used by this test.
59
    $basic_html_format = FilterFormat::create([
60 61
      'format' => 'basic_html',
      'name' => 'Basic HTML',
62 63
      'filters' => [
        'filter_html' => [
64
          'status' => 1,
65
          'settings' => [
66
            'allowed_html' => '<p> <br> <strong> <a> <em>',
67 68 69 70
          ],
        ],
      ],
    ]);
71
    $basic_html_format->save();
72
    $restricted_html_format = FilterFormat::create([
73 74
      'format' => 'restricted_html',
      'name' => 'Restricted HTML',
75 76
      'filters' => [
        'filter_html' => [
77 78
          'status' => TRUE,
          'weight' => -10,
79
          'settings' => [
80
            'allowed_html' => '<p> <br> <strong> <a> <em> <h4>',
81 82 83
          ],
        ],
        'filter_autop' => [
84 85
          'status' => TRUE,
          'weight' => 0,
86 87
        ],
        'filter_url' => [
88 89
          'status' => TRUE,
          'weight' => 0,
90 91
        ],
        'filter_htmlcorrector' => [
92 93
          'status' => TRUE,
          'weight' => 10,
94 95 96
        ],
      ],
    ]);
97
    $restricted_html_format->save();
98
    $full_html_format = FilterFormat::create([
99 100 101
      'format' => 'full_html',
      'name' => 'Full HTML',
      'weight' => 1,
102 103
      'filters' => [],
    ]);
104 105
    $full_html_format->save();

106
    $this->adminUser = $this->drupalCreateUser([
107
      'administer filters',
108 109 110
      $basic_html_format->getPermissionName(),
      $restricted_html_format->getPermissionName(),
      $full_html_format->getPermissionName(),
111
      'access site reports',
112
    ]);
113

114 115 116 117
    $this->webUser = $this->drupalCreateUser([
      'create page content',
      'edit own page content',
    ]);
118 119
    user_role_grant_permissions('authenticated', [$basic_html_format->getPermissionName()]);
    user_role_grant_permissions('anonymous', [$restricted_html_format->getPermissionName()]);
120
    $this->drupalLogin($this->adminUser);
121
    $this->drupalPlaceBlock('local_actions_block');
122 123
  }

124 125 126
  /**
   * Tests the format administration functionality.
   */
127
  public function testFormatAdmin() {
128 129 130
    // Add text format.
    $this->drupalGet('admin/config/content/formats');
    $this->clickLink('Add text format');
131
    $format_id = mb_strtolower($this->randomMachineName());
132
    $name = $this->randomMachineName();
133
    $edit = [
134 135
      'format' => $format_id,
      'name' => $name,
136
    ];
137
    $this->submitForm($edit, 'Save configuration');
138 139 140

    // Verify default weight of the text format.
    $this->drupalGet('admin/config/content/formats');
141
    $this->assertSession()->fieldValueEquals("formats[$format_id][weight]", 0);
142 143

    // Change the weight of the text format.
144
    $edit = [
145
      "formats[$format_id][weight]" => 5,
146
    ];
147
    $this->drupalPostForm('admin/config/content/formats', $edit, 'Save');
148
    $this->assertSession()->fieldValueEquals("formats[$format_id][weight]", 5);
149 150 151

    // Edit text format.
    $this->drupalGet('admin/config/content/formats');
152 153 154
    $destination = Url::fromRoute('filter.admin_overview')->toString();
    $edit_href = Url::fromRoute('entity.filter_format.edit_form', ['filter_format' => $format_id], ['query' => ['destination' => $destination]])->toString();
    $this->assertSession()->linkByHrefExists($edit_href);
155
    $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
156
    $this->submitForm([], 'Save configuration');
157 158 159

    // Verify that the custom weight of the text format has been retained.
    $this->drupalGet('admin/config/content/formats');
160
    $this->assertSession()->fieldValueEquals("formats[$format_id][weight]", 5);
161 162

    // Disable text format.
163
    $this->assertSession()->linkByHrefExists('admin/config/content/formats/manage/' . $format_id . '/disable');
164
    $this->drupalGet('admin/config/content/formats/manage/' . $format_id . '/disable');
165
    $this->submitForm([], 'Disable');
166 167

    // Verify that disabled text format no longer exists.
168
    $this->drupalGet('admin/config/content/formats/manage/' . $format_id);
169
    $this->assertSession()->statusCodeEquals(404);
170 171 172

    // Attempt to create a format of the same machine name as the disabled
    // format but with a different human readable name.
173
    $edit = [
174 175
      'format' => $format_id,
      'name' => 'New format',
176
    ];
177
    $this->drupalPostForm('admin/config/content/formats/add', $edit, 'Save configuration');
178 179 180 181
    $this->assertText('The machine-readable name is already in use. It must be unique.');

    // Attempt to create a format of the same human readable name as the
    // disabled format but with a different machine name.
182
    $edit = [
183 184
      'format' => 'new_format',
      'name' => $name,
185
    ];
186
    $this->drupalPostForm('admin/config/content/formats/add', $edit, 'Save configuration');
187
    $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', [
188
      '%name' => $name,
189
    ]));
190 191 192
  }

  /**
193
   * Tests filter administration functionality.
194
   */
195
  public function testFilterAdmin() {
196 197
    $first_filter = 'filter_autop';
    $second_filter = 'filter_url';
198

199
    $basic = 'basic_html';
200
    $restricted = 'restricted_html';
201 202 203 204
    $full = 'full_html';
    $plain = 'plain_text';

    // Check that the fallback format exists and cannot be disabled.
205
    $this->assertSame($plain, filter_fallback_format(), 'The fallback format is set to plain text.');
206
    $this->drupalGet('admin/config/content/formats');
207
    $this->assertNoRaw('admin/config/content/formats/manage/' . $plain . '/disable');
208
    $this->drupalGet('admin/config/content/formats/manage/' . $plain . '/disable');
209
    $this->assertSession()->statusCodeEquals(403);
210 211

    // Verify access permissions to Full HTML format.
212
    $full_format = FilterFormat::load($full);
213 214
    $this->assertTrue($full_format->access('use', $this->adminUser), 'Admin user may use Full HTML.');
    $this->assertFalse($full_format->access('use', $this->webUser), 'Web user may not use Full HTML.');
215

216
    // Add an additional tag and extra spaces and returns.
217
    $edit = [];
218
    $edit['filters[filter_html][settings][allowed_html]'] = "<a>   <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>\r\n<quote>";
219
    $this->drupalPostForm('admin/config/content/formats/manage/' . $restricted, $edit, 'Save configuration');
220
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $restricted);
221
    $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
222 223
    // Check that the allowed HTML tag was added and the string reformatted.
    $this->assertSession()->fieldValueEquals('filters[filter_html][settings][allowed_html]', "<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <quote>");
224

225
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
226 227
      ':first' => 'filters[' . $first_filter . '][weight]',
      ':second' => 'filters[' . $second_filter . '][weight]',
228
    ]);
229
    $this->assertNotEmpty($elements, 'Order confirmed in admin interface.');
230 231

    // Reorder filters.
232
    $edit = [];
233 234
    $edit['filters[' . $second_filter . '][weight]'] = 1;
    $edit['filters[' . $first_filter . '][weight]'] = 2;
235
    $this->submitForm($edit, 'Save configuration');
236
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $restricted);
237
    $this->drupalGet('admin/config/content/formats/manage/' . $restricted);
238 239
    $this->assertSession()->fieldValueEquals('filters[' . $second_filter . '][weight]', 1);
    $this->assertSession()->fieldValueEquals('filters[' . $first_filter . '][weight]', 2);
240

241
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', [
242 243
      ':first' => 'filters[' . $second_filter . '][weight]',
      ':second' => 'filters[' . $first_filter . '][weight]',
244
    ]);
245
    $this->assertNotEmpty($elements, 'Reorder confirmed in admin interface.');
246

247
    $filter_format = FilterFormat::load($restricted);
248
    foreach ($filter_format->filters() as $filter_name => $filter) {
249 250
      if ($filter_name == $second_filter || $filter_name == $first_filter) {
        $filters[] = $filter_name;
251 252
      }
    }
253 254
    // Ensure that the second filter is now before the first filter.
    $this->assertEqual($filter_format->filters($second_filter)->weight + 1, $filter_format->filters($first_filter)->weight, 'Order confirmed in configuration.');
255 256

    // Add format.
257
    $edit = [];
258
    $edit['format'] = mb_strtolower($this->randomMachineName());
259
    $edit['name'] = $this->randomMachineName();
260
    $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
261 262
    $edit['filters[' . $second_filter . '][status]'] = TRUE;
    $edit['filters[' . $first_filter . '][status]'] = TRUE;
263
    $this->drupalPostForm('admin/config/content/formats/add', $edit, 'Save configuration');
264
    $this->assertSession()->addressEquals('admin/config/content/formats');
265
    $this->assertRaw(t('Added text format %format.', ['%format' => $edit['name']]));
266

267
    filter_formats_reset();
268
    $format = FilterFormat::load($edit['format']);
269
    $this->assertNotNull($format, 'Format found in database.');
270
    $this->drupalGet('admin/config/content/formats/manage/' . $format->id());
271 272 273
    $this->assertSession()->checkboxChecked('roles[' . RoleInterface::AUTHENTICATED_ID . ']');
    $this->assertSession()->checkboxChecked('filters[' . $second_filter . '][status]');
    $this->assertSession()->checkboxChecked('filters[' . $first_filter . '][status]');
274 275

    // Disable new filter.
276
    $this->drupalPostForm('admin/config/content/formats/manage/' . $format->id() . '/disable', [], 'Disable');
277
    $this->assertSession()->addressEquals('admin/config/content/formats');
278
    $this->assertRaw(t('Disabled text format %format.', ['%format' => $edit['name']]));
279 280

    // Allow authenticated users on full HTML.
281
    $format = FilterFormat::load($full);
282
    $edit = [];
283 284
    $edit['roles[' . RoleInterface::ANONYMOUS_ID . ']'] = 0;
    $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = 1;
285
    $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, 'Save configuration');
286
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $full);
287
    $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]));
288 289

    // Switch user.
290
    $this->drupalLogin($this->webUser);
291 292

    $this->drupalGet('node/add/page');
293
    $this->assertRaw('<option value="' . $full . '">Full HTML</option>');
294

295
    // Use basic HTML and see if it removes tags that are not allowed.
296
    $body = '<em>' . $this->randomMachineName() . '</em>';
297 298 299
    $extra_text = 'text';
    $text = $body . '<random>' . $extra_text . '</random>';

300
    $edit = [];
301
    $edit['title[0][value]'] = $this->randomMachineName();
302 303
    $edit['body[0][value]'] = $text;
    $edit['body[0][format]'] = $basic;
304
    $this->drupalPostForm('node/add/page', $edit, 'Save');
305
    $this->assertText('Basic page ' . $edit['title[0][value]'] . ' has been created.');
306 307

    // Verify that the creation message contains a link to a node.
308
    $this->assertSession()->elementExists('xpath', '//div[contains(@class, "messages")]//a[contains(@href, "node/")]');
309

310
    $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
311
    $this->assertNotEmpty($node, 'Node found in database.');
312

313
    $this->drupalGet('node/' . $node->id());
314 315
    // Check that filter removed invalid tag.
    $this->assertRaw($body . $extra_text);
316 317

    // Use plain text and see if it escapes all tags, whether allowed or not.
318 319
    // In order to test plain text, we have to enable the hidden variable for
    // "show_fallback_format", which displays plain text in the format list.
320
    $this->config('filter.settings')
321 322
      ->set('always_show_fallback_choice', TRUE)
      ->save();
323
    $edit = [];
324
    $edit['body[0][format]'] = $plain;
325
    $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, 'Save');
326
    $this->drupalGet('node/' . $node->id());
327
    $this->assertSession()->assertEscaped($text);
328
    $this->config('filter.settings')
329 330
      ->set('always_show_fallback_choice', FALSE)
      ->save();
331 332

    // Switch user.
333
    $this->drupalLogin($this->adminUser);
334 335 336

    // Clean up.
    // Allowed tags.
337
    $edit = [];
338
    $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
339
    $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, 'Save configuration');
340
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $basic);
341
    $this->drupalGet('admin/config/content/formats/manage/' . $basic);
342
    $this->assertSession()->fieldValueEquals('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]']);
343 344

    // Full HTML.
345
    $edit = [];
346
    $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']'] = FALSE;
347
    $this->drupalPostForm('admin/config/content/formats/manage/' . $full, $edit, 'Save configuration');
348
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $full);
349
    $this->assertRaw(t('The text format %format has been updated.', ['%format' => $format->label()]));
350
    $this->drupalGet('admin/config/content/formats/manage/' . $full);
351
    $this->assertSession()->fieldValueEquals('roles[' . RoleInterface::AUTHENTICATED_ID . ']', $edit['roles[' . RoleInterface::AUTHENTICATED_ID . ']']);
352 353

    // Filter order.
354
    $edit = [];
355 356
    $edit['filters[' . $second_filter . '][weight]'] = 2;
    $edit['filters[' . $first_filter . '][weight]'] = 1;
357
    $this->drupalPostForm('admin/config/content/formats/manage/' . $basic, $edit, 'Save configuration');
358
    $this->assertSession()->addressEquals('admin/config/content/formats/manage/' . $basic);
359
    $this->drupalGet('admin/config/content/formats/manage/' . $basic);
360 361
    $this->assertSession()->fieldValueEquals('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]']);
    $this->assertSession()->fieldValueEquals('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]']);
362 363 364 365 366
  }

  /**
   * Tests the URL filter settings form is properly validated.
   */
367
  public function testUrlFilterAdmin() {
368
    // The form does not save with an invalid filter URL length.
369
    $edit = [
370
      'filters[filter_url][settings][filter_url_length]' => $this->randomMachineName(4),
371
    ];
372
    $this->drupalPostForm('admin/config/content/formats/manage/basic_html', $edit, 'Save configuration');
373
    $this->assertNoRaw(t('The text format %format has been updated.', ['%format' => 'Basic HTML']));
374
  }
375

376 377 378
  /**
   * Tests whether filter tips page is not HTML escaped.
   */
379
  public function testFilterTipHtmlEscape() {
380 381 382
    $this->drupalLogin($this->adminUser);
    global $base_url;

383 384 385
    $site_name_with_markup = 'Filter test <script>alert(\'here\');</script> site name';
    $this->config('system.site')->set('name', $site_name_with_markup)->save();

386 387
    // It is not possible to test the whole filter tip page.
    // Therefore we test only some parts.
388
    $link = '<a href="' . $base_url . '">' . Html::escape($site_name_with_markup) . '</a>';
389
    $ampersand = '&amp;';
390 391
    $link_as_code = '<code>' . Html::escape($link) . '</code>';
    $ampersand_as_code = '<code>' . Html::escape($ampersand) . '</code>';
392 393 394 395 396 397 398 399 400

    $this->drupalGet('filter/tips');

    $this->assertRaw('<td class="type">' . $link_as_code . '</td>');
    $this->assertRaw('<td class="get">' . $link . '</td>');
    $this->assertRaw('<td class="type">' . $ampersand_as_code . '</td>');
    $this->assertRaw('<td class="get">' . $ampersand . '</td>');
  }

401 402 403 404 405
  /**
   * Tests whether a field using a disabled format is rendered.
   */
  public function testDisabledFormat() {
    // Create a node type and add a standard body field.
406
    $node_type = NodeType::create(['type' => mb_strtolower($this->randomMachineName())]);
407 408 409 410 411 412
    $node_type->save();
    node_add_body_field($node_type, $this->randomString());

    // Create a text format with a filter that returns a static string.
    $format = FilterFormat::create([
      'name' => $this->randomString(),
413
      'format' => $format_id = mb_strtolower($this->randomMachineName()),
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429
    ]);
    $format->setFilterConfig('filter_static_text', ['status' => TRUE]);
    $format->save();

    // Create a new node of the new node type.
    $node = Node::create([
      'type' => $node_type->id(),
      'title' => $this->randomString(),
    ]);
    $body_value = $this->randomString();
    $node->body->value = $body_value;
    $node->body->format = $format_id;
    $node->save();

    // The format is used and we should see the static text instead of the body
    // value.
430
    $this->drupalGet($node->toUrl());
431 432 433 434 435
    $this->assertText('filtered text');

    // Disable the format.
    $format->disable()->save();

436
    $this->drupalGet($node->toUrl());
437 438 439 440 441

    // The format is not used anymore.
    $this->assertNoText('filtered text');
    // The text is not displayed unfiltered or escaped.
    $this->assertNoRaw($body_value);
442
    $this->assertSession()->assertNoEscaped($body_value);
443 444 445 446 447 448 449 450 451 452 453 454

    // Visit the dblog report page.
    $this->drupalLogin($this->adminUser);
    $this->drupalGet('admin/reports/dblog');
    // The correct message has been logged.
    $this->assertRaw(sprintf('Disabled text format: %s.', $format_id));

    // Programmatically change the text format to something random so we trigger
    // the missing text format message.
    $format_id = $this->randomMachineName();
    $node->body->format = $format_id;
    $node->save();
455
    $this->drupalGet($node->toUrl());
456 457
    // The text is not displayed unfiltered or escaped.
    $this->assertNoRaw($body_value);
458
    $this->assertSession()->assertNoEscaped($body_value);
459 460 461 462 463 464 465

    // Visit the dblog report page.
    $this->drupalGet('admin/reports/dblog');
    // The missing text format message has been logged.
    $this->assertRaw(sprintf('Missing text format: %s.', $format_id));
  }

466
}