Projet

Général

Profil

Paste
Télécharger (85,5 ko) Statistiques
| Branche: | Révision:

root / htmltest / modules / filter / filter.test @ 85ad3d82

1
<?php
2

    
3
/**
4
 * @file
5
 * Tests for filter.module.
6
 */
7

    
8
/**
9
 * Tests for text format and filter CRUD operations.
10
 */
11
class FilterCRUDTestCase extends DrupalWebTestCase {
12
  public static function getInfo() {
13
    return array(
14
      'name' => 'Filter CRUD operations',
15
      'description' => 'Test creation, loading, updating, deleting of text formats and filters.',
16
      'group' => 'Filter',
17
    );
18
  }
19

    
20
  function setUp() {
21
    parent::setUp('filter_test');
22
  }
23

    
24
  /**
25
   * Tests CRUD operations for text formats and filters.
26
   */
27
  function testTextFormatCRUD() {
28
    // Add a text format with minimum data only.
29
    $format = new stdClass();
30
    $format->format = 'empty_format';
31
    $format->name = 'Empty format';
32
    filter_format_save($format);
33
    $this->verifyTextFormat($format);
34
    $this->verifyFilters($format);
35

    
36
    // Add another text format specifying all possible properties.
37
    $format = new stdClass();
38
    $format->format = 'custom_format';
39
    $format->name = 'Custom format';
40
    $format->filters = array(
41
      'filter_url' => array(
42
        'status' => 1,
43
        'settings' => array(
44
          'filter_url_length' => 30,
45
        ),
46
      ),
47
    );
48
    filter_format_save($format);
49
    $this->verifyTextFormat($format);
50
    $this->verifyFilters($format);
51

    
52
    // Alter some text format properties and save again.
53
    $format->name = 'Altered format';
54
    $format->filters['filter_url']['status'] = 0;
55
    $format->filters['filter_autop']['status'] = 1;
56
    filter_format_save($format);
57
    $this->verifyTextFormat($format);
58
    $this->verifyFilters($format);
59

    
60
    // Add a uncacheable filter and save again.
61
    $format->filters['filter_test_uncacheable']['status'] = 1;
62
    filter_format_save($format);
63
    $this->verifyTextFormat($format);
64
    $this->verifyFilters($format);
65

    
66
    // Disable the text format.
67
    filter_format_disable($format);
68

    
69
    $db_format = db_query("SELECT * FROM {filter_format} WHERE format = :format", array(':format' => $format->format))->fetchObject();
70
    $this->assertFalse($db_format->status, 'Database: Disabled text format is marked as disabled.');
71
    $formats = filter_formats();
72
    $this->assertTrue(!isset($formats[$format->format]), 'filter_formats: Disabled text format no longer exists.');
73
  }
74

    
75
  /**
76
   * Verifies that a text format is properly stored.
77
   */
78
  function verifyTextFormat($format) {
79
    $t_args = array('%format' => $format->name);
80
    // Verify text format database record.
81
    $db_format = db_select('filter_format', 'ff')
82
      ->fields('ff')
83
      ->condition('format', $format->format)
84
      ->execute()
85
      ->fetchObject();
86
    $this->assertEqual($db_format->format, $format->format, format_string('Database: Proper format id for text format %format.', $t_args));
87
    $this->assertEqual($db_format->name, $format->name, format_string('Database: Proper title for text format %format.', $t_args));
88
    $this->assertEqual($db_format->cache, $format->cache, format_string('Database: Proper cache indicator for text format %format.', $t_args));
89
    $this->assertEqual($db_format->weight, $format->weight, format_string('Database: Proper weight for text format %format.', $t_args));
90

    
91
    // Verify filter_format_load().
92
    $filter_format = filter_format_load($format->format);
93
    $this->assertEqual($filter_format->format, $format->format, format_string('filter_format_load: Proper format id for text format %format.', $t_args));
94
    $this->assertEqual($filter_format->name, $format->name, format_string('filter_format_load: Proper title for text format %format.', $t_args));
95
    $this->assertEqual($filter_format->cache, $format->cache, format_string('filter_format_load: Proper cache indicator for text format %format.', $t_args));
96
    $this->assertEqual($filter_format->weight, $format->weight, format_string('filter_format_load: Proper weight for text format %format.', $t_args));
97

    
98
    // Verify the 'cache' text format property according to enabled filters.
99
    $filter_info = filter_get_filters();
100
    $filters = filter_list_format($filter_format->format);
101
    $cacheable = TRUE;
102
    foreach ($filters as $name => $filter) {
103
      // If this filter is not cacheable, update $cacheable accordingly, so we
104
      // can verify $format->cache after iterating over all filters.
105
      if ($filter->status && isset($filter_info[$name]['cache']) && !$filter_info[$name]['cache']) {
106
        $cacheable = FALSE;
107
        break;
108
      }
109
    }
110
    $this->assertEqual($filter_format->cache, $cacheable, 'Text format contains proper cache property.');
111
  }
112

    
113
  /**
114
   * Verifies that filters are properly stored for a text format.
115
   */
116
  function verifyFilters($format) {
117
    // Verify filter database records.
118
    $filters = db_query("SELECT * FROM {filter} WHERE format = :format", array(':format' => $format->format))->fetchAllAssoc('name');
119
    $format_filters = $format->filters;
120
    foreach ($filters as $name => $filter) {
121
      $t_args = array('%format' => $format->name, '%filter' => $name);
122

    
123
      // Verify that filter status is properly stored.
124
      $this->assertEqual($filter->status, $format_filters[$name]['status'], format_string('Database: Proper status for %filter in text format %format.', $t_args));
125

    
126
      // Verify that filter settings were properly stored.
127
      $this->assertEqual(unserialize($filter->settings), isset($format_filters[$name]['settings']) ? $format_filters[$name]['settings'] : array(), format_string('Database: Proper filter settings for %filter in text format %format.', $t_args));
128

    
129
      // Verify that each filter has a module name assigned.
130
      $this->assertTrue(!empty($filter->module), format_string('Database: Proper module name for %filter in text format %format.', $t_args));
131

    
132
      // Remove the filter from the copy of saved $format to check whether all
133
      // filters have been processed later.
134
      unset($format_filters[$name]);
135
    }
136
    // Verify that all filters have been processed.
137
    $this->assertTrue(empty($format_filters), 'Database contains values for all filters in the saved format.');
138

    
139
    // Verify filter_list_format().
140
    $filters = filter_list_format($format->format);
141
    $format_filters = $format->filters;
142
    foreach ($filters as $name => $filter) {
143
      $t_args = array('%format' => $format->name, '%filter' => $name);
144

    
145
      // Verify that filter status is properly stored.
146
      $this->assertEqual($filter->status, $format_filters[$name]['status'], format_string('filter_list_format: Proper status for %filter in text format %format.', $t_args));
147

    
148
      // Verify that filter settings were properly stored.
149
      $this->assertEqual($filter->settings, isset($format_filters[$name]['settings']) ? $format_filters[$name]['settings'] : array(), format_string('filter_list_format: Proper filter settings for %filter in text format %format.', $t_args));
150

    
151
      // Verify that each filter has a module name assigned.
152
      $this->assertTrue(!empty($filter->module), format_string('filter_list_format: Proper module name for %filter in text format %format.', $t_args));
153

    
154
      // Remove the filter from the copy of saved $format to check whether all
155
      // filters have been processed later.
156
      unset($format_filters[$name]);
157
    }
158
    // Verify that all filters have been processed.
159
    $this->assertTrue(empty($format_filters), 'filter_list_format: Loaded filters contain values for all filters in the saved format.');
160
  }
161
}
162

    
163
/**
164
 * Tests the administrative functionality of the Filter module.
165
 */
166
class FilterAdminTestCase extends DrupalWebTestCase {
167
  public static function getInfo() {
168
    return array(
169
      'name' => 'Filter administration functionality',
170
      'description' => 'Thoroughly test the administrative interface of the filter module.',
171
      'group' => 'Filter',
172
    );
173
  }
174

    
175
  function setUp() {
176
    parent::setUp();
177

    
178
    // Create users.
179
    $filtered_html_format = filter_format_load('filtered_html');
180
    $full_html_format = filter_format_load('full_html');
181
    $this->admin_user = $this->drupalCreateUser(array(
182
      'administer filters',
183
      filter_permission_name($filtered_html_format),
184
      filter_permission_name($full_html_format),
185
    ));
186

    
187
    $this->web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
188
    $this->drupalLogin($this->admin_user);
189
  }
190

    
191
  /**
192
   * Tests the format administration functionality.
193
   */
194
  function testFormatAdmin() {
195
    // Add text format.
196
    $this->drupalGet('admin/config/content/formats');
197
    $this->clickLink('Add text format');
198
    $format_id = drupal_strtolower($this->randomName());
199
    $name = $this->randomName();
200
    $edit = array(
201
      'format' => $format_id,
202
      'name' => $name,
203
    );
204
    $this->drupalPost(NULL, $edit, t('Save configuration'));
205

    
206
    // Verify default weight of the text format.
207
    $this->drupalGet('admin/config/content/formats');
208
    $this->assertFieldByName("formats[$format_id][weight]", 0, 'Text format weight was saved.');
209

    
210
    // Change the weight of the text format.
211
    $edit = array(
212
      "formats[$format_id][weight]" => 5,
213
    );
214
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
215
    $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was saved.');
216

    
217
    // Edit text format.
218
    $this->drupalGet('admin/config/content/formats');
219
    $this->assertLinkByHref('admin/config/content/formats/' . $format_id);
220
    $this->drupalGet('admin/config/content/formats/' . $format_id);
221
    $this->drupalPost(NULL, array(), t('Save configuration'));
222

    
223
    // Verify that the custom weight of the text format has been retained.
224
    $this->drupalGet('admin/config/content/formats');
225
    $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was retained.');
226

    
227
    // Disable text format.
228
    $this->assertLinkByHref('admin/config/content/formats/' . $format_id . '/disable');
229
    $this->drupalGet('admin/config/content/formats/' . $format_id . '/disable');
230
    $this->drupalPost(NULL, array(), t('Disable'));
231

    
232
    // Verify that disabled text format no longer exists.
233
    $this->drupalGet('admin/config/content/formats/' . $format_id);
234
    $this->assertResponse(404, 'Disabled text format no longer exists.');
235

    
236
    // Attempt to create a format of the same machine name as the disabled
237
    // format but with a different human readable name.
238
    $edit = array(
239
      'format' => $format_id,
240
      'name' => 'New format',
241
    );
242
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
243
    $this->assertText('The machine-readable name is already in use. It must be unique.');
244

    
245
    // Attempt to create a format of the same human readable name as the
246
    // disabled format but with a different machine name.
247
    $edit = array(
248
      'format' => 'new_format',
249
      'name' => $name,
250
    );
251
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
252
    $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', array(
253
      '%name' => $name,
254
    )));
255
  }
256

    
257
  /**
258
   * Tests filter administration functionality.
259
   */
260
  function testFilterAdmin() {
261
    // URL filter.
262
    $first_filter = 'filter_url';
263
    // Line filter.
264
    $second_filter = 'filter_autop';
265

    
266
    $filtered = 'filtered_html';
267
    $full = 'full_html';
268
    $plain = 'plain_text';
269

    
270
    // Check that the fallback format exists and cannot be disabled.
271
    $this->assertTrue($plain == filter_fallback_format(), 'The fallback format is set to plain text.');
272
    $this->drupalGet('admin/config/content/formats');
273
    $this->assertNoRaw('admin/config/content/formats/' . $plain . '/disable', 'Disable link for the fallback format not found.');
274
    $this->drupalGet('admin/config/content/formats/' . $plain . '/disable');
275
    $this->assertResponse(403, 'The fallback format cannot be disabled.');
276

    
277
    // Verify access permissions to Full HTML format.
278
    $this->assertTrue(filter_access(filter_format_load($full), $this->admin_user), 'Admin user may use Full HTML.');
279
    $this->assertFalse(filter_access(filter_format_load($full), $this->web_user), 'Web user may not use Full HTML.');
280

    
281
    // Add an additional tag.
282
    $edit = array();
283
    $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <quote>';
284
    $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
285
    $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], 'Allowed HTML tag added.');
286

    
287
    $result = db_query('SELECT * FROM {cache_filter}')->fetchObject();
288
    $this->assertFalse($result, 'Cache cleared.');
289

    
290
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
291
      ':first' => 'filters[' . $first_filter . '][weight]',
292
      ':second' => 'filters[' . $second_filter . '][weight]',
293
    ));
294
    $this->assertTrue(!empty($elements), 'Order confirmed in admin interface.');
295

    
296
    // Reorder filters.
297
    $edit = array();
298
    $edit['filters[' . $second_filter . '][weight]'] = 1;
299
    $edit['filters[' . $first_filter . '][weight]'] = 2;
300
    $this->drupalPost(NULL, $edit, t('Save configuration'));
301
    $this->assertFieldByName('filters[' . $second_filter . '][weight]', 1, 'Order saved successfully.');
302
    $this->assertFieldByName('filters[' . $first_filter . '][weight]', 2, 'Order saved successfully.');
303

    
304
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
305
      ':first' => 'filters[' . $second_filter . '][weight]',
306
      ':second' => 'filters[' . $first_filter . '][weight]',
307
    ));
308
    $this->assertTrue(!empty($elements), 'Reorder confirmed in admin interface.');
309

    
310
    $result = db_query('SELECT * FROM {filter} WHERE format = :format ORDER BY weight ASC', array(':format' => $filtered));
311
    $filters = array();
312
    foreach ($result as $filter) {
313
      if ($filter->name == $second_filter || $filter->name == $first_filter) {
314
        $filters[] = $filter;
315
      }
316
    }
317
    $this->assertTrue(($filters[0]->name == $second_filter && $filters[1]->name == $first_filter), 'Order confirmed in database.');
318

    
319
    // Add format.
320
    $edit = array();
321
    $edit['format'] = drupal_strtolower($this->randomName());
322
    $edit['name'] = $this->randomName();
323
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
324
    $edit['filters[' . $second_filter . '][status]'] = TRUE;
325
    $edit['filters[' . $first_filter . '][status]'] = TRUE;
326
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
327
    $this->assertRaw(t('Added text format %format.', array('%format' => $edit['name'])), 'New filter created.');
328

    
329
    drupal_static_reset('filter_formats');
330
    $format = filter_format_load($edit['format']);
331
    $this->assertNotNull($format, 'Format found in database.');
332

    
333
    $this->assertFieldByName('roles[' . DRUPAL_AUTHENTICATED_RID . ']', '', 'Role found.');
334
    $this->assertFieldByName('filters[' . $second_filter . '][status]', '', 'Line break filter found.');
335
    $this->assertFieldByName('filters[' . $first_filter . '][status]', '', 'Url filter found.');
336

    
337
    // Disable new filter.
338
    $this->drupalPost('admin/config/content/formats/' . $format->format . '/disable', array(), t('Disable'));
339
    $this->assertRaw(t('Disabled text format %format.', array('%format' => $edit['name'])), 'Format successfully disabled.');
340

    
341
    // Allow authenticated users on full HTML.
342
    $format = filter_format_load($full);
343
    $edit = array();
344
    $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 0;
345
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
346
    $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
347
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), 'Full HTML format successfully updated.');
348

    
349
    // Switch user.
350
    $this->drupalLogout();
351
    $this->drupalLogin($this->web_user);
352

    
353
    $this->drupalGet('node/add/page');
354
    $this->assertRaw('<option value="' . $full . '">Full HTML</option>', 'Full HTML filter accessible.');
355

    
356
    // Use filtered HTML and see if it removes tags that are not allowed.
357
    $body = '<em>' . $this->randomName() . '</em>';
358
    $extra_text = 'text';
359
    $text = $body . '<random>' . $extra_text . '</random>';
360

    
361
    $edit = array();
362
    $langcode = LANGUAGE_NONE;
363
    $edit["title"] = $this->randomName();
364
    $edit["body[$langcode][0][value]"] = $text;
365
    $edit["body[$langcode][0][format]"] = $filtered;
366
    $this->drupalPost('node/add/page', $edit, t('Save'));
367
    $this->assertRaw(t('Basic page %title has been created.', array('%title' => $edit["title"])), 'Filtered node created.');
368

    
369
    $node = $this->drupalGetNodeByTitle($edit["title"]);
370
    $this->assertTrue($node, 'Node found in database.');
371

    
372
    $this->drupalGet('node/' . $node->nid);
373
    $this->assertRaw($body . $extra_text, 'Filter removed invalid tag.');
374

    
375
    // Use plain text and see if it escapes all tags, whether allowed or not.
376
    $edit = array();
377
    $edit["body[$langcode][0][format]"] = $plain;
378
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
379
    $this->drupalGet('node/' . $node->nid);
380
    $this->assertText(check_plain($text), 'The "Plain text" text format escapes all HTML tags.');
381

    
382
    // Switch user.
383
    $this->drupalLogout();
384
    $this->drupalLogin($this->admin_user);
385

    
386
    // Clean up.
387
    // Allowed tags.
388
    $edit = array();
389
    $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
390
    $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
391
    $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], 'Changes reverted.');
392

    
393
    // Full HTML.
394
    $edit = array();
395
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = FALSE;
396
    $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
397
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), 'Full HTML format successfully reverted.');
398
    $this->assertFieldByName('roles[' . DRUPAL_AUTHENTICATED_RID . ']', $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'], 'Changes reverted.');
399

    
400
    // Filter order.
401
    $edit = array();
402
    $edit['filters[' . $second_filter . '][weight]'] = 2;
403
    $edit['filters[' . $first_filter . '][weight]'] = 1;
404
    $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
405
    $this->assertFieldByName('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]'], 'Changes reverted.');
406
    $this->assertFieldByName('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]'], 'Changes reverted.');
407
  }
408

    
409
  /**
410
   * Tests the URL filter settings form is properly validated.
411
   */
412
  function testUrlFilterAdmin() {
413
    // The form does not save with an invalid filter URL length.
414
    $edit = array(
415
      'filters[filter_url][settings][filter_url_length]' => $this->randomName(4),
416
    );
417
    $this->drupalPost('admin/config/content/formats/filtered_html', $edit, t('Save configuration'));
418
    $this->assertNoRaw(t('The text format %format has been updated.', array('%format' => 'Filtered HTML')));
419
  }
420
}
421

    
422
/**
423
 * Tests the filter format access functionality in the Filter module.
424
 */
425
class FilterFormatAccessTestCase extends DrupalWebTestCase {
426
  /**
427
   * A user with administrative permissions.
428
   *
429
   * @var object
430
   */
431
  protected $admin_user;
432

    
433
  /**
434
   * A user with 'administer filters' permission.
435
   *
436
   * @var object
437
   */
438
  protected $filter_admin_user;
439

    
440
  /**
441
   * A user with permission to create and edit own content.
442
   *
443
   * @var object
444
   */
445
  protected $web_user;
446

    
447
  /**
448
   * An object representing an allowed text format.
449
   *
450
   * @var object
451
   */
452
  protected $allowed_format;
453

    
454
  /**
455
   * An object representing a disallowed text format.
456
   *
457
   * @var object
458
   */
459
  protected $disallowed_format;
460

    
461
  public static function getInfo() {
462
    return array(
463
      'name' => 'Filter format access',
464
      'description' => 'Tests access to text formats.',
465
      'group' => 'Filter',
466
    );
467
  }
468

    
469
  function setUp() {
470
    parent::setUp();
471

    
472
    // Create a user who can administer text formats, but does not have
473
    // specific permission to use any of them.
474
    $this->filter_admin_user = $this->drupalCreateUser(array(
475
      'administer filters',
476
      'create page content',
477
      'edit any page content',
478
    ));
479

    
480
    // Create two text formats.
481
    $this->drupalLogin($this->filter_admin_user);
482
    $formats = array();
483
    for ($i = 0; $i < 2; $i++) {
484
      $edit = array(
485
        'format' => drupal_strtolower($this->randomName()),
486
        'name' => $this->randomName(),
487
      );
488
      $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
489
      $this->resetFilterCaches();
490
      $formats[] = filter_format_load($edit['format']);
491
    }
492
    list($this->allowed_format, $this->disallowed_format) = $formats;
493
    $this->drupalLogout();
494

    
495
    // Create a regular user with access to one of the formats.
496
    $this->web_user = $this->drupalCreateUser(array(
497
      'create page content',
498
      'edit any page content',
499
      filter_permission_name($this->allowed_format),
500
    ));
501

    
502
    // Create an administrative user who has access to use both formats.
503
    $this->admin_user = $this->drupalCreateUser(array(
504
      'administer filters',
505
      'create page content',
506
      'edit any page content',
507
      filter_permission_name($this->allowed_format),
508
      filter_permission_name($this->disallowed_format),
509
    ));
510
  }
511

    
512
  /**
513
   * Tests the Filter format access permissions functionality.
514
   */
515
  function testFormatPermissions() {
516
    // Make sure that a regular user only has access to the text format they
517
    // were granted access to, as well to the fallback format.
518
    $this->assertTrue(filter_access($this->allowed_format, $this->web_user), 'A regular user has access to a text format they were granted access to.');
519
    $this->assertFalse(filter_access($this->disallowed_format, $this->web_user), 'A regular user does not have access to a text format they were not granted access to.');
520
    $this->assertTrue(filter_access(filter_format_load(filter_fallback_format()), $this->web_user), 'A regular user has access to the fallback format.');
521

    
522
    // Perform similar checks as above, but now against the entire list of
523
    // available formats for this user.
524
    $this->assertTrue(in_array($this->allowed_format->format, array_keys(filter_formats($this->web_user))), 'The allowed format appears in the list of available formats for a regular user.');
525
    $this->assertFalse(in_array($this->disallowed_format->format, array_keys(filter_formats($this->web_user))), 'The disallowed format does not appear in the list of available formats for a regular user.');
526
    $this->assertTrue(in_array(filter_fallback_format(), array_keys(filter_formats($this->web_user))), 'The fallback format appears in the list of available formats for a regular user.');
527

    
528
    // Make sure that a regular user only has permission to use the format
529
    // they were granted access to.
530
    $this->assertTrue(user_access(filter_permission_name($this->allowed_format), $this->web_user), 'A regular user has permission to use the allowed text format.');
531
    $this->assertFalse(user_access(filter_permission_name($this->disallowed_format), $this->web_user), 'A regular user does not have permission to use the disallowed text format.');
532

    
533
    // Make sure that the allowed format appears on the node form and that
534
    // the disallowed format does not.
535
    $this->drupalLogin($this->web_user);
536
    $this->drupalGet('node/add/page');
537
    $langcode = LANGUAGE_NONE;
538
    $elements = $this->xpath('//select[@name=:name]/option', array(
539
      ':name' => "body[$langcode][0][format]",
540
      ':option' => $this->allowed_format->format,
541
    ));
542
    $options = array();
543
    foreach ($elements as $element) {
544
      $options[(string) $element['value']] = $element;
545
    }
546
    $this->assertTrue(isset($options[$this->allowed_format->format]), 'The allowed text format appears as an option when adding a new node.');
547
    $this->assertFalse(isset($options[$this->disallowed_format->format]), 'The disallowed text format does not appear as an option when adding a new node.');
548
    $this->assertTrue(isset($options[filter_fallback_format()]), 'The fallback format appears as an option when adding a new node.');
549
  }
550

    
551
  /**
552
   * Tests if text format is available to a role.
553
   */
554
  function testFormatRoles() {
555
    // Get the role ID assigned to the regular user; it must be the maximum.
556
    $rid = max(array_keys($this->web_user->roles));
557

    
558
    // Check that this role appears in the list of roles that have access to an
559
    // allowed text format, but does not appear in the list of roles that have
560
    // access to a disallowed text format.
561
    $this->assertTrue(in_array($rid, array_keys(filter_get_roles_by_format($this->allowed_format))), 'A role which has access to a text format appears in the list of roles that have access to that format.');
562
    $this->assertFalse(in_array($rid, array_keys(filter_get_roles_by_format($this->disallowed_format))), 'A role which does not have access to a text format does not appear in the list of roles that have access to that format.');
563

    
564
    // Check that the correct text format appears in the list of formats
565
    // available to that role.
566
    $this->assertTrue(in_array($this->allowed_format->format, array_keys(filter_get_formats_by_role($rid))), 'A text format which a role has access to appears in the list of formats available to that role.');
567
    $this->assertFalse(in_array($this->disallowed_format->format, array_keys(filter_get_formats_by_role($rid))), 'A text format which a role does not have access to does not appear in the list of formats available to that role.');
568

    
569
    // Check that the fallback format is always allowed.
570
    $this->assertEqual(filter_get_roles_by_format(filter_format_load(filter_fallback_format())), user_roles(), 'All roles have access to the fallback format.');
571
    $this->assertTrue(in_array(filter_fallback_format(), array_keys(filter_get_formats_by_role($rid))), 'The fallback format appears in the list of allowed formats for any role.');
572
  }
573

    
574
  /**
575
   * Tests editing a page using a disallowed text format.
576
   *
577
   * Verifies that regular users and administrators are able to edit a page, but
578
   * not allowed to change the fields which use an inaccessible text format.
579
   * Also verifies that fields which use a text format that does not exist can
580
   * be edited by administrators only, but that the administrator is forced to
581
   * choose a new format before saving the page.
582
   */
583
  function testFormatWidgetPermissions() {
584
    $langcode = LANGUAGE_NONE;
585
    $title_key = "title";
586
    $body_value_key = "body[$langcode][0][value]";
587
    $body_format_key = "body[$langcode][0][format]";
588

    
589
    // Create node to edit.
590
    $this->drupalLogin($this->admin_user);
591
    $edit = array();
592
    $edit['title'] = $this->randomName(8);
593
    $edit[$body_value_key] = $this->randomName(16);
594
    $edit[$body_format_key] = $this->disallowed_format->format;
595
    $this->drupalPost('node/add/page', $edit, t('Save'));
596
    $node = $this->drupalGetNodeByTitle($edit['title']);
597

    
598
    // Try to edit with a less privileged user.
599
    $this->drupalLogin($this->web_user);
600
    $this->drupalGet('node/' . $node->nid);
601
    $this->clickLink(t('Edit'));
602

    
603
    // Verify that body field is read-only and contains replacement value.
604
    $this->assertFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.');
605

    
606
    // Verify that title can be changed, but preview displays original body.
607
    $new_edit = array();
608
    $new_edit['title'] = $this->randomName(8);
609
    $this->drupalPost(NULL, $new_edit, t('Preview'));
610
    $this->assertText($edit[$body_value_key], 'Old body found in preview.');
611

    
612
    // Save and verify that only the title was changed.
613
    $this->drupalPost(NULL, $new_edit, t('Save'));
614
    $this->assertNoText($edit['title'], 'Old title not found.');
615
    $this->assertText($new_edit['title'], 'New title found.');
616
    $this->assertText($edit[$body_value_key], 'Old body found.');
617

    
618
    // Check that even an administrator with "administer filters" permission
619
    // cannot edit the body field if they do not have specific permission to
620
    // use its stored format. (This must be disallowed so that the
621
    // administrator is never forced to switch the text format to something
622
    // else.)
623
    $this->drupalLogin($this->filter_admin_user);
624
    $this->drupalGet('node/' . $node->nid . '/edit');
625
    $this->assertFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.');
626

    
627
    // Disable the text format used above.
628
    filter_format_disable($this->disallowed_format);
629
    $this->resetFilterCaches();
630

    
631
    // Log back in as the less privileged user and verify that the body field
632
    // is still disabled, since the less privileged user should not be able to
633
    // edit content that does not have an assigned format.
634
    $this->drupalLogin($this->web_user);
635
    $this->drupalGet('node/' . $node->nid . '/edit');
636
    $this->assertFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", t('This field has been disabled because you do not have sufficient permissions to edit it.'), 'Text format access denied message found.');
637

    
638
    // Log back in as the filter administrator and verify that the body field
639
    // can be edited.
640
    $this->drupalLogin($this->filter_admin_user);
641
    $this->drupalGet('node/' . $node->nid . '/edit');
642
    $this->assertNoFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", NULL, 'Text format access denied message not found.');
643
    $this->assertFieldByXPath("//select[@name='$body_format_key']", NULL, 'Text format selector found.');
644

    
645
    // Verify that trying to save the node without selecting a new text format
646
    // produces an error message, and does not result in the node being saved.
647
    $old_title = $new_edit['title'];
648
    $new_title = $this->randomName(8);
649
    $edit = array('title' => $new_title);
650
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
651
    $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
652
    $this->drupalGet('node/' . $node->nid);
653
    $this->assertText($old_title, 'Old title found.');
654
    $this->assertNoText($new_title, 'New title not found.');
655

    
656
    // Now select a new text format and make sure the node can be saved.
657
    $edit[$body_format_key] = filter_fallback_format();
658
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
659
    $this->assertUrl('node/' . $node->nid);
660
    $this->assertText($new_title, 'New title found.');
661
    $this->assertNoText($old_title, 'Old title not found.');
662

    
663
    // Switch the text format to a new one, then disable that format and all
664
    // other formats on the site (leaving only the fallback format).
665
    $this->drupalLogin($this->admin_user);
666
    $edit = array($body_format_key => $this->allowed_format->format);
667
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
668
    $this->assertUrl('node/' . $node->nid);
669
    foreach (filter_formats() as $format) {
670
      if ($format->format != filter_fallback_format()) {
671
        filter_format_disable($format);
672
      }
673
    }
674

    
675
    // Since there is now only one available text format, the widget for
676
    // selecting a text format would normally not display when the content is
677
    // edited. However, we need to verify that the filter administrator still
678
    // is forced to make a conscious choice to reassign the text to a different
679
    // format.
680
    $this->drupalLogin($this->filter_admin_user);
681
    $old_title = $new_title;
682
    $new_title = $this->randomName(8);
683
    $edit = array('title' => $new_title);
684
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
685
    $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
686
    $this->drupalGet('node/' . $node->nid);
687
    $this->assertText($old_title, 'Old title found.');
688
    $this->assertNoText($new_title, 'New title not found.');
689
    $edit[$body_format_key] = filter_fallback_format();
690
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
691
    $this->assertUrl('node/' . $node->nid);
692
    $this->assertText($new_title, 'New title found.');
693
    $this->assertNoText($old_title, 'Old title not found.');
694
  }
695

    
696
  /**
697
   * Rebuilds text format and permission caches in the thread running the tests.
698
   */
699
  protected function resetFilterCaches() {
700
    filter_formats_reset();
701
    $this->checkPermissions(array(), TRUE);
702
  }
703
}
704

    
705
/**
706
 * Tests the default filter functionality in the Filter module.
707
 */
708
class FilterDefaultFormatTestCase extends DrupalWebTestCase {
709
  public static function getInfo() {
710
    return array(
711
      'name' => 'Default text format functionality',
712
      'description' => 'Test the default text formats for different users.',
713
      'group' => 'Filter',
714
    );
715
  }
716

    
717
  /**
718
   * Tests if the default text format is accessible to users.
719
   */
720
  function testDefaultTextFormats() {
721
    // Create two text formats, and two users. The first user has access to
722
    // both formats, but the second user only has access to the second one.
723
    $admin_user = $this->drupalCreateUser(array('administer filters'));
724
    $this->drupalLogin($admin_user);
725
    $formats = array();
726
    for ($i = 0; $i < 2; $i++) {
727
      $edit = array(
728
        'format' => drupal_strtolower($this->randomName()),
729
        'name' => $this->randomName(),
730
      );
731
      $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
732
      $this->resetFilterCaches();
733
      $formats[] = filter_format_load($edit['format']);
734
    }
735
    list($first_format, $second_format) = $formats;
736
    $first_user = $this->drupalCreateUser(array(filter_permission_name($first_format), filter_permission_name($second_format)));
737
    $second_user = $this->drupalCreateUser(array(filter_permission_name($second_format)));
738

    
739
    // Adjust the weights so that the first and second formats (in that order)
740
    // are the two lowest weighted formats available to any user.
741
    $minimum_weight = db_query("SELECT MIN(weight) FROM {filter_format}")->fetchField();
742
    $edit = array();
743
    $edit['formats[' . $first_format->format . '][weight]'] = $minimum_weight - 2;
744
    $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 1;
745
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
746
    $this->resetFilterCaches();
747

    
748
    // Check that each user's default format is the lowest weighted format that
749
    // the user has access to.
750
    $this->assertEqual(filter_default_format($first_user), $first_format->format, "The first user's default format is the lowest weighted format that the user has access to.");
751
    $this->assertEqual(filter_default_format($second_user), $second_format->format, "The second user's default format is the lowest weighted format that the user has access to, and is different than the first user's.");
752

    
753
    // Reorder the two formats, and check that both users now have the same
754
    // default.
755
    $edit = array();
756
    $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 3;
757
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
758
    $this->resetFilterCaches();
759
    $this->assertEqual(filter_default_format($first_user), filter_default_format($second_user), 'After the formats are reordered, both users have the same default format.');
760
  }
761

    
762
  /**
763
   * Rebuilds text format and permission caches in the thread running the tests.
764
   */
765
  protected function resetFilterCaches() {
766
    filter_formats_reset();
767
    $this->checkPermissions(array(), TRUE);
768
  }
769
}
770

    
771
/**
772
 * Tests the behavior of check_markup() when it is called without text format.
773
 */
774
class FilterNoFormatTestCase extends DrupalWebTestCase {
775
  public static function getInfo() {
776
    return array(
777
      'name' => 'Unassigned text format functionality',
778
      'description' => 'Test the behavior of check_markup() when it is called without a text format.',
779
      'group' => 'Filter',
780
    );
781
  }
782

    
783
  /**
784
   * Tests text without format.
785
   *
786
   * Tests if text with no format is filtered the same way as text in the
787
   * fallback format.
788
   */
789
  function testCheckMarkupNoFormat() {
790
    // Create some text. Include some HTML and line breaks, so we get a good
791
    // test of the filtering that is applied to it.
792
    $text = "<strong>" . $this->randomName(32) . "</strong>\n\n<div>" . $this->randomName(32) . "</div>";
793

    
794
    // Make sure that when this text is run through check_markup() with no text
795
    // format, it is filtered as though it is in the fallback format.
796
    $this->assertEqual(check_markup($text), check_markup($text, filter_fallback_format()), 'Text with no format is filtered the same as text in the fallback format.');
797
  }
798
}
799

    
800
/**
801
 * Security tests for missing/vanished text formats or filters.
802
 */
803
class FilterSecurityTestCase extends DrupalWebTestCase {
804
  public static function getInfo() {
805
    return array(
806
      'name' => 'Security',
807
      'description' => 'Test the behavior of check_markup() when a filter or text format vanishes.',
808
      'group' => 'Filter',
809
    );
810
  }
811

    
812
  function setUp() {
813
    parent::setUp('php', 'filter_test');
814
    $this->admin_user = $this->drupalCreateUser(array('administer modules', 'administer filters', 'administer site configuration'));
815
    $this->drupalLogin($this->admin_user);
816
  }
817

    
818
  /**
819
   * Tests removal of filtered content when an active filter is disabled.
820
   *
821
   * Tests that filtered content is emptied when an actively used filter module
822
   * is disabled.
823
   */
824
  function testDisableFilterModule() {
825
    // Create a new node.
826
    $node = $this->drupalCreateNode(array('promote' => 1));
827
    $body_raw = $node->body[LANGUAGE_NONE][0]['value'];
828
    $format_id = $node->body[LANGUAGE_NONE][0]['format'];
829
    $this->drupalGet('node/' . $node->nid);
830
    $this->assertText($body_raw, 'Node body found.');
831

    
832
    // Enable the filter_test_replace filter.
833
    $edit = array(
834
      'filters[filter_test_replace][status]' => 1,
835
    );
836
    $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
837

    
838
    // Verify that filter_test_replace filter replaced the content.
839
    $this->drupalGet('node/' . $node->nid);
840
    $this->assertNoText($body_raw, 'Node body not found.');
841
    $this->assertText('Filter: Testing filter', 'Testing filter output found.');
842

    
843
    // Disable the text format entirely.
844
    $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
845

    
846
    // Verify that the content is empty, because the text format does not exist.
847
    $this->drupalGet('node/' . $node->nid);
848
    $this->assertNoText($body_raw, 'Node body not found.');
849
  }
850
}
851

    
852
/**
853
 * Unit tests for core filters.
854
 */
855
class FilterUnitTestCase extends DrupalUnitTestCase {
856
  public static function getInfo() {
857
    return array(
858
      'name' => 'Filter module filters',
859
      'description' => 'Tests Filter module filters individually.',
860
      'group' => 'Filter',
861
    );
862
  }
863

    
864
  /**
865
   * Tests the line break filter.
866
   */
867
  function testLineBreakFilter() {
868
    // Setup dummy filter object.
869
    $filter = new stdClass();
870
    $filter->callback = '_filter_autop';
871

    
872
    // Since the line break filter naturally needs plenty of newlines in test
873
    // strings and expectations, we're using "\n" instead of regular newlines
874
    // here.
875
    $tests = array(
876
      // Single line breaks should be changed to <br /> tags, while paragraphs
877
      // separated with double line breaks should be enclosed with <p></p> tags.
878
      "aaa\nbbb\n\nccc" => array(
879
        "<p>aaa<br />\nbbb</p>\n<p>ccc</p>" => TRUE,
880
      ),
881
      // Skip contents of certain block tags entirely.
882
      "<script>aaa\nbbb\n\nccc</script>
883
<style>aaa\nbbb\n\nccc</style>
884
<pre>aaa\nbbb\n\nccc</pre>
885
<object>aaa\nbbb\n\nccc</object>
886
<iframe>aaa\nbbb\n\nccc</iframe>
887
" => array(
888
        "<script>aaa\nbbb\n\nccc</script>" => TRUE,
889
        "<style>aaa\nbbb\n\nccc</style>" => TRUE,
890
        "<pre>aaa\nbbb\n\nccc</pre>" => TRUE,
891
        "<object>aaa\nbbb\n\nccc</object>" => TRUE,
892
        "<iframe>aaa\nbbb\n\nccc</iframe>" => TRUE,
893
      ),
894
      // Skip comments entirely.
895
      "One. <!-- comment --> Two.\n<!--\nThree.\n-->\n" => array(
896
        '<!-- comment -->' => TRUE,
897
        "<!--\nThree.\n-->" => TRUE,
898
      ),
899
      // Resulting HTML should produce matching paragraph tags.
900
      '<p><div>  </div></p>' => array(
901
        "<p>\n<div>  </div>\n</p>" => TRUE,
902
      ),
903
      '<div><p>  </p></div>' => array(
904
        "<div>\n</div>" => TRUE,
905
      ),
906
      '<blockquote><pre>aaa</pre></blockquote>' => array(
907
        "<blockquote><pre>aaa</pre></blockquote>" => TRUE,
908
      ),
909
      "<pre>aaa\nbbb\nccc</pre>\nddd\neee" => array(
910
        "<pre>aaa\nbbb\nccc</pre>" => TRUE,
911
        "<p>ddd<br />\neee</p>" => TRUE,
912
      ),
913
      // Comments remain unchanged and subsequent lines/paragraphs are
914
      // transformed normally.
915
      "aaa<!--comment-->\n\nbbb\n\nccc\n\nddd<!--comment\nwith linebreak-->\n\neee\n\nfff" => array(
916
        "<p>aaa</p>\n<!--comment--><p>\nbbb</p>\n<p>ccc</p>\n<p>ddd</p>" => TRUE,
917
        "<!--comment\nwith linebreak--><p>\neee</p>\n<p>fff</p>" => TRUE,
918
      ),
919
      // Check that a comment in a PRE will result that the text after
920
      // the comment, but still in PRE, is not transformed.
921
      "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>\nddd" => array(
922
        "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>" => TRUE,
923
      ),
924
      // Bug 810824, paragraphs were appearing around iframe tags.
925
      "<iframe>aaa</iframe>\n\n" => array(
926
        "<p><iframe>aaa</iframe></p>" => FALSE,
927
      ),
928
    );
929
    $this->assertFilteredString($filter, $tests);
930

    
931
    // Very long string hitting PCRE limits.
932
    $limit = max(ini_get('pcre.backtrack_limit'), ini_get('pcre.recursion_limit'));
933
    $source = $this->randomName($limit);
934
    $result = _filter_autop($source);
935
    $success = $this->assertEqual($result, '<p>' . $source . "</p>\n", 'Line break filter can process very long strings.');
936
    if (!$success) {
937
      $this->verbose("\n" . $source . "\n<hr />\n" . $result);
938
    }
939
  }
940

    
941
  /**
942
   * Tests limiting allowed tags and XSS prevention.
943
   *
944
   * XSS tests assume that script is disallowed by default and src is allowed
945
   * by default, but on* and style attributes are disallowed.
946
   *
947
   * Script injection vectors mostly adopted from http://ha.ckers.org/xss.html.
948
   *
949
   * Relevant CVEs:
950
   * - CVE-2002-1806, ~CVE-2005-0682, ~CVE-2005-2106, CVE-2005-3973,
951
   *   CVE-2006-1226 (= rev. 1.112?), CVE-2008-0273, CVE-2008-3740.
952
   */
953
  function testFilterXSS() {
954
    // Tag stripping, different ways to work around removal of HTML tags.
955
    $f = filter_xss('<script>alert(0)</script>');
956
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping -- simple script without special characters.');
957

    
958
    $f = filter_xss('<script src="http://www.example.com" />');
959
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping -- empty script with source.');
960

    
961
    $f = filter_xss('<ScRipt sRc=http://www.example.com/>');
962
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- varying case.');
963

    
964
    $f = filter_xss("<script\nsrc\n=\nhttp://www.example.com/\n>");
965
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- multiline tag.');
966

    
967
    $f = filter_xss('<script/a src=http://www.example.com/a.js></script>');
968
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- non whitespace character after tag name.');
969

    
970
    $f = filter_xss('<script/src=http://www.example.com/a.js></script>');
971
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no space between tag and attribute.');
972

    
973
    // Null between < and tag name works at least with IE6.
974
    $f = filter_xss("<\0scr\0ipt>alert(0)</script>");
975
    $this->assertNoNormalized($f, 'ipt', 'HTML tag stripping evasion -- breaking HTML with nulls.');
976

    
977
    $f = filter_xss("<scrscriptipt src=http://www.example.com/a.js>");
978
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- filter just removing "script".');
979

    
980
    $f = filter_xss('<<script>alert(0);//<</script>');
981
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- double opening brackets.');
982

    
983
    $f = filter_xss('<script src=http://www.example.com/a.js?<b>');
984
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no closing tag.');
985

    
986
    // DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
987
    // work consistently.
988
    $f = filter_xss('<script>>');
989
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- double closing tag.');
990

    
991
    $f = filter_xss('<script src=//www.example.com/.a>');
992
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no scheme or ending slash.');
993

    
994
    $f = filter_xss('<script src=http://www.example.com/.a');
995
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no closing bracket.');
996

    
997
    $f = filter_xss('<script src=http://www.example.com/ <');
998
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- opening instead of closing bracket.');
999

    
1000
    $f = filter_xss('<nosuchtag attribute="newScriptInjectionVector">');
1001
    $this->assertNoNormalized($f, 'nosuchtag', 'HTML tag stripping evasion -- unknown tag.');
1002

    
1003
    $f = filter_xss('<?xml:namespace ns="urn:schemas-microsoft-com:time">');
1004
    $this->assertTrue(stripos($f, '<?xml') === FALSE, 'HTML tag stripping evasion -- starting with a question sign (processing instructions).');
1005

    
1006
    $f = filter_xss('<t:set attributeName="innerHTML" to="&lt;script defer&gt;alert(0)&lt;/script&gt;">');
1007
    $this->assertNoNormalized($f, 't:set', 'HTML tag stripping evasion -- colon in the tag name (namespaces\' tricks).');
1008

    
1009
    $f = filter_xss('<img """><script>alert(0)</script>', array('img'));
1010
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- a malformed image tag.');
1011

    
1012
    $f = filter_xss('<blockquote><script>alert(0)</script></blockquote>', array('blockquote'));
1013
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- script in a blockqoute.');
1014

    
1015
    $f = filter_xss("<!--[if true]><script>alert(0)</script><![endif]-->");
1016
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- script within a comment.');
1017

    
1018
    // Dangerous attributes removal.
1019
    $f = filter_xss('<p onmouseover="http://www.example.com/">', array('p'));
1020
    $this->assertNoNormalized($f, 'onmouseover', 'HTML filter attributes removal -- events, no evasion.');
1021

    
1022
    $f = filter_xss('<li style="list-style-image: url(javascript:alert(0))">', array('li'));
1023
    $this->assertNoNormalized($f, 'style', 'HTML filter attributes removal -- style, no evasion.');
1024

    
1025
    $f = filter_xss('<img onerror   =alert(0)>', array('img'));
1026
    $this->assertNoNormalized($f, 'onerror', 'HTML filter attributes removal evasion -- spaces before equals sign.');
1027

    
1028
    $f = filter_xss('<img onabort!#$%&()*~+-_.,:;?@[/|\]^`=alert(0)>', array('img'));
1029
    $this->assertNoNormalized($f, 'onabort', 'HTML filter attributes removal evasion -- non alphanumeric characters before equals sign.');
1030

    
1031
    $f = filter_xss('<img oNmediAError=alert(0)>', array('img'));
1032
    $this->assertNoNormalized($f, 'onmediaerror', 'HTML filter attributes removal evasion -- varying case.');
1033

    
1034
    // Works at least with IE6.
1035
    $f = filter_xss("<img o\0nfocus\0=alert(0)>", array('img'));
1036
    $this->assertNoNormalized($f, 'focus', 'HTML filter attributes removal evasion -- breaking with nulls.');
1037

    
1038
    // Only whitelisted scheme names allowed in attributes.
1039
    $f = filter_xss('<img src="javascript:alert(0)">', array('img'));
1040
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- no evasion.');
1041

    
1042
    $f = filter_xss('<img src=javascript:alert(0)>', array('img'));
1043
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- no quotes.');
1044

    
1045
    // A bit like CVE-2006-0070.
1046
    $f = filter_xss('<img src="javascript:confirm(0)">', array('img'));
1047
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- no alert ;)');
1048

    
1049
    $f = filter_xss('<img src=`javascript:alert(0)`>', array('img'));
1050
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- grave accents.');
1051

    
1052
    $f = filter_xss('<img dynsrc="javascript:alert(0)">', array('img'));
1053
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- rare attribute.');
1054

    
1055
    $f = filter_xss('<table background="javascript:alert(0)">', array('table'));
1056
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- another tag.');
1057

    
1058
    $f = filter_xss('<base href="javascript:alert(0);//">', array('base'));
1059
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- one more attribute and tag.');
1060

    
1061
    $f = filter_xss('<img src="jaVaSCriPt:alert(0)">', array('img'));
1062
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- varying case.');
1063

    
1064
    $f = filter_xss('<img src=&#106;&#97;&#118;&#97;&#115;&#99;&#114;&#105;&#112;&#116;&#58;&#97;&#108;&#101;&#114;&#116;&#40;&#48;&#41;>', array('img'));
1065
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 decimal encoding.');
1066

    
1067
    $f = filter_xss('<img src=&#00000106&#0000097&#00000118&#0000097&#00000115&#0000099&#00000114&#00000105&#00000112&#00000116&#0000058&#0000097&#00000108&#00000101&#00000114&#00000116&#0000040&#0000048&#0000041>', array('img'));
1068
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- long UTF-8 encoding.');
1069

    
1070
    $f = filter_xss('<img src=&#x6A&#x61&#x76&#x61&#x73&#x63&#x72&#x69&#x70&#x74&#x3A&#x61&#x6C&#x65&#x72&#x74&#x28&#x30&#x29>', array('img'));
1071
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 hex encoding.');
1072

    
1073
    $f = filter_xss("<img src=\"jav\tascript:alert(0)\">", array('img'));
1074
    $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an embedded tab.');
1075

    
1076
    $f = filter_xss('<img src="jav&#x09;ascript:alert(0)">', array('img'));
1077
    $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded tab.');
1078

    
1079
    $f = filter_xss('<img src="jav&#x000000A;ascript:alert(0)">', array('img'));
1080
    $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded newline.');
1081

    
1082
    // With &#xD; this test would fail, but the entity gets turned into
1083
    // &amp;#xD;, so it's OK.
1084
    $f = filter_xss('<img src="jav&#x0D;ascript:alert(0)">', array('img'));
1085
    $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded carriage return.');
1086

    
1087
    $f = filter_xss("<img src=\"\n\n\nj\na\nva\ns\ncript:alert(0)\">", array('img'));
1088
    $this->assertNoNormalized($f, 'cript', 'HTML scheme clearing evasion -- broken into many lines.');
1089

    
1090
    $f = filter_xss("<img src=\"jav\0a\0\0cript:alert(0)\">", array('img'));
1091
    $this->assertNoNormalized($f, 'cript', 'HTML scheme clearing evasion -- embedded nulls.');
1092

    
1093
    $f = filter_xss('<img src=" &#14;  javascript:alert(0)">', array('img'));
1094
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
1095

    
1096
    $f = filter_xss('<img src="vbscript:msgbox(0)">', array('img'));
1097
    $this->assertNoNormalized($f, 'vbscript', 'HTML scheme clearing evasion -- another scheme.');
1098

    
1099
    $f = filter_xss('<img src="nosuchscheme:notice(0)">', array('img'));
1100
    $this->assertNoNormalized($f, 'nosuchscheme', 'HTML scheme clearing evasion -- unknown scheme.');
1101

    
1102
    // Netscape 4.x javascript entities.
1103
    $f = filter_xss('<br size="&{alert(0)}">', array('br'));
1104
    $this->assertNoNormalized($f, 'alert', 'Netscape 4.x javascript entities.');
1105

    
1106
    // DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
1107
    // Internet Explorer 6.
1108
    $f = filter_xss("<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>", array('p'));
1109
    $this->assertNoNormalized($f, 'style', 'HTML filter -- invalid UTF-8.');
1110

    
1111
    $f = filter_xss("\xc0aaa");
1112
    $this->assertEqual($f, '', 'HTML filter -- overlong UTF-8 sequences.');
1113

    
1114
    $f = filter_xss("Who&#039;s Online");
1115
    $this->assertNormalized($f, "who's online", 'HTML filter -- html entity number');
1116

    
1117
    $f = filter_xss("Who&amp;#039;s Online");
1118
    $this->assertNormalized($f, "who&#039;s online", 'HTML filter -- encoded html entity number');
1119

    
1120
    $f = filter_xss("Who&amp;amp;#039; Online");
1121
    $this->assertNormalized($f, "who&amp;#039; online", 'HTML filter -- double encoded html entity number');
1122
  }
1123

    
1124
  /**
1125
   * Tests filter settings, defaults, access restrictions and similar.
1126
   *
1127
   * @todo This is for functions like filter_filter and check_markup, whose
1128
   *   functionality is not completely focused on filtering. Some ideas:
1129
   *   restricting formats according to user permissions, proper cache
1130
   *   handling, defaults -- allowed tags/attributes/protocols.
1131
   *
1132
   * @todo It is possible to add script, iframe etc. to allowed tags, but this
1133
   *   makes HTML filter completely ineffective.
1134
   *
1135
   * @todo Class, id, name and xmlns should be added to disallowed attributes,
1136
   *   or better a whitelist approach should be used for that too.
1137
   */
1138
  function testHtmlFilter() {
1139
    // Setup dummy filter object.
1140
    $filter = new stdClass();
1141
    $filter->settings = array(
1142
      'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>',
1143
      'filter_html_help' => 1,
1144
      'filter_html_nofollow' => 0,
1145
    );
1146

    
1147
    // HTML filter is not able to secure some tags, these should never be
1148
    // allowed.
1149
    $f = _filter_html('<script />', $filter);
1150
    $this->assertNoNormalized($f, 'script', 'HTML filter should always remove script tags.');
1151

    
1152
    $f = _filter_html('<iframe />', $filter);
1153
    $this->assertNoNormalized($f, 'iframe', 'HTML filter should always remove iframe tags.');
1154

    
1155
    $f = _filter_html('<object />', $filter);
1156
    $this->assertNoNormalized($f, 'object', 'HTML filter should always remove object tags.');
1157

    
1158
    $f = _filter_html('<style />', $filter);
1159
    $this->assertNoNormalized($f, 'style', 'HTML filter should always remove style tags.');
1160

    
1161
    // Some tags make CSRF attacks easier, let the user take the risk herself.
1162
    $f = _filter_html('<img />', $filter);
1163
    $this->assertNoNormalized($f, 'img', 'HTML filter should remove img tags on default.');
1164

    
1165
    $f = _filter_html('<input />', $filter);
1166
    $this->assertNoNormalized($f, 'img', 'HTML filter should remove input tags on default.');
1167

    
1168
    // Filtering content of some attributes is infeasible, these shouldn't be
1169
    // allowed too.
1170
    $f = _filter_html('<p style="display: none;" />', $filter);
1171
    $this->assertNoNormalized($f, 'style', 'HTML filter should remove style attribute on default.');
1172

    
1173
    $f = _filter_html('<p onerror="alert(0);" />', $filter);
1174
    $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove on* attributes on default.');
1175

    
1176
    $f = _filter_html('<code onerror>&nbsp;</code>', $filter);
1177
    $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove empty on* attributes on default.');
1178
  }
1179

    
1180
  /**
1181
   * Tests the spam deterrent.
1182
   */
1183
  function testNoFollowFilter() {
1184
    // Setup dummy filter object.
1185
    $filter = new stdClass();
1186
    $filter->settings = array(
1187
      'allowed_html' => '<a>',
1188
      'filter_html_help' => 1,
1189
      'filter_html_nofollow' => 1,
1190
    );
1191

    
1192
    // Test if the rel="nofollow" attribute is added, even if we try to prevent
1193
    // it.
1194
    $f = _filter_html('<a href="http://www.example.com/">text</a>', $filter);
1195
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent -- no evasion.');
1196

    
1197
    $f = _filter_html('<A href="http://www.example.com/">text</a>', $filter);
1198
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- capital A.');
1199

    
1200
    $f = _filter_html("<a/href=\"http://www.example.com/\">text</a>", $filter);
1201
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- non whitespace character after tag name.');
1202

    
1203
    $f = _filter_html("<\0a\0 href=\"http://www.example.com/\">text</a>", $filter);
1204
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- some nulls.');
1205

    
1206
    $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', $filter);
1207
    $this->assertNoNormalized($f, 'rel="follow"', 'Spam deterrent evasion -- with rel set - rel="follow" removed.');
1208
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- with rel set - rel="nofollow" added.');
1209
  }
1210

    
1211
  /**
1212
   * Tests the loose, admin HTML filter.
1213
   */
1214
  function testFilterXSSAdmin() {
1215
    // DRUPAL-SA-2008-044
1216
    $f = filter_xss_admin('<object />');
1217
    $this->assertNoNormalized($f, 'object', 'Admin HTML filter -- should not allow object tag.');
1218

    
1219
    $f = filter_xss_admin('<script />');
1220
    $this->assertNoNormalized($f, 'script', 'Admin HTML filter -- should not allow script tag.');
1221

    
1222
    $f = filter_xss_admin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
1223
    $this->assertEqual($f, '', 'Admin HTML filter -- should never allow some tags.');
1224
  }
1225

    
1226
  /**
1227
   * Tests the HTML escaping filter.
1228
   *
1229
   * check_plain() is not tested here.
1230
   */
1231
  function testHtmlEscapeFilter() {
1232
    // Setup dummy filter object.
1233
    $filter = new stdClass();
1234
    $filter->callback = '_filter_html_escape';
1235

    
1236
    $tests = array(
1237
      "   One. <!-- \"comment\" --> Two'.\n<p>Three.</p>\n    " => array(
1238
        "One. &lt;!-- &quot;comment&quot; --&gt; Two&#039;.\n&lt;p&gt;Three.&lt;/p&gt;" => TRUE,
1239
        '   One.' => FALSE,
1240
        "</p>\n    " => FALSE,
1241
      ),
1242
    );
1243
    $this->assertFilteredString($filter, $tests);
1244
  }
1245

    
1246
  /**
1247
   * Tests the URL filter.
1248
   */
1249
  function testUrlFilter() {
1250
    // Setup dummy filter object.
1251
    $filter = new stdClass();
1252
    $filter->callback = '_filter_url';
1253
    $filter->settings = array(
1254
      'filter_url_length' => 496,
1255
    );
1256
    // @todo Possible categories:
1257
    // - absolute, mail, partial
1258
    // - characters/encoding, surrounding markup, security
1259

    
1260
    // Create a e-mail that is too long.
1261
    $long_email = str_repeat('a', 254) . '@example.com';
1262
    $too_long_email = str_repeat('b', 255) . '@example.com';
1263

    
1264

    
1265
    // Filter selection/pattern matching.
1266
    $tests = array(
1267
      // HTTP URLs.
1268
      '
1269
http://example.com or www.example.com
1270
' => array(
1271
        '<a href="http://example.com">http://example.com</a>' => TRUE,
1272
        '<a href="http://www.example.com">www.example.com</a>' => TRUE,
1273
      ),
1274
      // MAILTO URLs.
1275
      '
1276
person@example.com or mailto:person2@example.com or ' . $long_email . ' but not ' . $too_long_email . '
1277
' => array(
1278
        '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
1279
        '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
1280
        '<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
1281
        '<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
1282
      ),
1283
      // URI parts and special characters.
1284
      '
1285
http://trailingslash.com/ or www.trailingslash.com/
1286
http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
1287
http://twitter.com/#!/example/status/22376963142324226
1288
ftp://user:pass@ftp.example.com/~home/dir1
1289
sftp://user@nonstandardport:222/dir
1290
ssh://192.168.0.100/srv/git/drupal.git
1291
' => array(
1292
        '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
1293
        '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
1294
        '<a href="http://host.com/some/path?query=foo&amp;bar[baz]=beer#fragment">http://host.com/some/path?query=foo&amp;bar[baz]=beer#fragment</a>' => TRUE,
1295
        '<a href="http://www.host.com/some/path?query=foo&amp;bar[baz]=beer#fragment">www.host.com/some/path?query=foo&amp;bar[baz]=beer#fragment</a>' => TRUE,
1296
        '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
1297
        '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
1298
        '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
1299
        '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
1300
      ),
1301
      // Encoding.
1302
      '
1303
http://ampersand.com/?a=1&b=2
1304
http://encoded.com/?a=1&amp;b=2
1305
' => array(
1306
        '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
1307
        '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
1308
      ),
1309
      // Domain name length.
1310
      '
1311
www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
1312
me@me.tv
1313
' => array(
1314
        '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
1315
        '<a href="http://www.example.example">www.example.example</a>' => TRUE,
1316
        'http://www.toolong' => FALSE,
1317
        '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
1318
      ),
1319
      // Absolute URL protocols.
1320
      // The list to test is found in the beginning of _filter_url() at
1321
      // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
1322
      '
1323
https://example.com,
1324
ftp://ftp.example.com,
1325
news://example.net,
1326
telnet://example,
1327
irc://example.host,
1328
ssh://odd.geek,
1329
sftp://secure.host?,
1330
webcal://calendar,
1331
rtsp://127.0.0.1,
1332
not foo://disallowed.com.
1333
' => array(
1334
        'href="https://example.com"' => TRUE,
1335
        'href="ftp://ftp.example.com"' => TRUE,
1336
        'href="news://example.net"' => TRUE,
1337
        'href="telnet://example"' => TRUE,
1338
        'href="irc://example.host"' => TRUE,
1339
        'href="ssh://odd.geek"' => TRUE,
1340
        'href="sftp://secure.host"' => TRUE,
1341
        'href="webcal://calendar"' => TRUE,
1342
        'href="rtsp://127.0.0.1"' => TRUE,
1343
        'href="foo://disallowed.com"' => FALSE,
1344
        'not foo://disallowed.com.' => TRUE,
1345
      ),
1346
    );
1347
    $this->assertFilteredString($filter, $tests);
1348

    
1349
    // Surrounding text/punctuation.
1350
    $tests = array(
1351
      '
1352
Partial URL with trailing period www.partial.com.
1353
E-mail with trailing comma person@example.com,
1354
Absolute URL with trailing question http://www.absolute.com?
1355
Query string with trailing exclamation www.query.com/index.php?a=!
1356
Partial URL with 3 trailing www.partial.periods...
1357
E-mail with 3 trailing exclamations@example.com!!!
1358
Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
1359
' => array(
1360
        'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
1361
        'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
1362
        'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
1363
        'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
1364
        'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
1365
        'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
1366
        'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
1367
      ),
1368
      '
1369
(www.parenthesis.com/dir?a=1&b=2#a)
1370
' => array(
1371
        '(<a href="http://www.parenthesis.com/dir?a=1&amp;b=2#a">www.parenthesis.com/dir?a=1&amp;b=2#a</a>)' => TRUE,
1372
      ),
1373
    );
1374
    $this->assertFilteredString($filter, $tests);
1375

    
1376
    // Surrounding markup.
1377
    $tests = array(
1378
      '
1379
<p xmlns="www.namespace.com" />
1380
<p xmlns="http://namespace.com">
1381
An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
1382
</p>
1383
' => array(
1384
        '<p xmlns="www.namespace.com" />' => TRUE,
1385
        '<p xmlns="http://namespace.com">' => TRUE,
1386
        'href="http://www.namespace.com"' => FALSE,
1387
        'href="http://namespace.com"' => FALSE,
1388
        'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
1389
      ),
1390
      '
1391
Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
1392
but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
1393
' => array(
1394
        '<a href="foo">www.relative.com</a>' => TRUE,
1395
        'href="http://www.relative.com"' => FALSE,
1396
        '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
1397
        '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
1398
        '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
1399
      ),
1400
      '
1401
Test <code>using www.example.com the code tag</code>.
1402
' => array(
1403
        'href' => FALSE,
1404
        'http' => FALSE,
1405
      ),
1406
      '
1407
Intro.
1408
<blockquote>
1409
Quoted text linking to www.example.com, written by person@example.com, originating from http://origin.example.com. <code>@see www.usage.example.com or <em>www.example.info</em> bla bla</code>.
1410
</blockquote>
1411

    
1412
Outro.
1413
' => array(
1414
        'href="http://www.example.com"' => TRUE,
1415
        'href="mailto:person@example.com"' => TRUE,
1416
        'href="http://origin.example.com"' => TRUE,
1417
        'http://www.usage.example.com' => FALSE,
1418
        'http://www.example.info' => FALSE,
1419
        'Intro.' => TRUE,
1420
        'Outro.' => TRUE,
1421
      ),
1422
      '
1423
Unknown tag <x>containing x and www.example.com</x>? And a tag <pooh>beginning with p and containing www.example.pooh with p?</pooh>
1424
' => array(
1425
        'href="http://www.example.com"' => TRUE,
1426
        'href="http://www.example.pooh"' => TRUE,
1427
      ),
1428
      '
1429
<p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
1430
 It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
1431
HTML www.example21.com soup by person@example22.com can litererally http://www.example23.com contain *img*<img> anything. Just a www.example24.com with http://www.example25.com thrown in. www.example26.com from person@example27.com with extra http://www.example28.com.
1432
' => array(
1433
        'href="http://www.example17.com"' => TRUE,
1434
        'href="http://www.example18.com"' => TRUE,
1435
        'href="http://www.example19.com"' => TRUE,
1436
        'href="http://www.example20.com"' => TRUE,
1437
        'href="http://www.example21.com"' => TRUE,
1438
        'href="mailto:person@example22.com"' => TRUE,
1439
        'href="http://www.example23.com"' => TRUE,
1440
        'href="http://www.example24.com"' => TRUE,
1441
        'href="http://www.example25.com"' => TRUE,
1442
        'href="http://www.example26.com"' => TRUE,
1443
        'href="mailto:person@example27.com"' => TRUE,
1444
        'href="http://www.example28.com"' => TRUE,
1445
      ),
1446
      '
1447
<script>
1448
<!--
1449
  // @see www.example.com
1450
  var exampleurl = "http://example.net";
1451
-->
1452
<!--//--><![CDATA[//><!--
1453
  // @see www.example.com
1454
  var exampleurl = "http://example.net";
1455
//--><!]]>
1456
</script>
1457
' => array(
1458
        'href="http://www.example.com"' => FALSE,
1459
        'href="http://example.net"' => FALSE,
1460
      ),
1461
      '
1462
<style>body {
1463
  background: url(http://example.com/pixel.gif);
1464
}</style>
1465
' => array(
1466
        'href' => FALSE,
1467
      ),
1468
      '
1469
<!-- Skip any URLs like www.example.com in comments -->
1470
' => array(
1471
        'href' => FALSE,
1472
      ),
1473
      '
1474
<!-- Skip any URLs like
1475
www.example.com with a newline in comments -->
1476
' => array(
1477
        'href' => FALSE,
1478
      ),
1479
      '
1480
<!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
1481
' => array(
1482
        'href' => FALSE,
1483
      ),
1484
      '
1485
<dl>
1486
<dt>www.example.com</dt>
1487
<dd>http://example.com</dd>
1488
<dd>person@example.com</dd>
1489
<dt>Check www.example.net</dt>
1490
<dd>Some text around http://www.example.info by person@example.info?</dd>
1491
</dl>
1492
' => array(
1493
        'href="http://www.example.com"' => TRUE,
1494
        'href="http://example.com"' => TRUE,
1495
        'href="mailto:person@example.com"' => TRUE,
1496
        'href="http://www.example.net"' => TRUE,
1497
        'href="http://www.example.info"' => TRUE,
1498
        'href="mailto:person@example.info"' => TRUE,
1499
      ),
1500
      '
1501
<div>www.div.com</div>
1502
<ul>
1503
<li>http://listitem.com</li>
1504
<li class="odd">www.class.listitem.com</li>
1505
</ul>
1506
' => array(
1507
        '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
1508
        '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
1509
        '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
1510
      ),
1511
    );
1512
    $this->assertFilteredString($filter, $tests);
1513

    
1514
    // URL trimming.
1515
    $filter->settings['filter_url_length'] = 20;
1516
    $tests = array(
1517
      'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
1518
        '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
1519
      ),
1520
    );
1521
    $this->assertFilteredString($filter, $tests);
1522
  }
1523

    
1524
  /**
1525
   * Asserts multiple filter output expectations for multiple input strings.
1526
   *
1527
   * @param $filter
1528
   *   A input filter object.
1529
   * @param $tests
1530
   *   An associative array, whereas each key is an arbitrary input string and
1531
   *   each value is again an associative array whose keys are filter output
1532
   *   strings and whose values are Booleans indicating whether the output is
1533
   *   expected or not.
1534
   *
1535
   * For example:
1536
   * @code
1537
   * $tests = array(
1538
   *   'Input string' => array(
1539
   *     '<p>Input string</p>' => TRUE,
1540
   *     'Input string<br' => FALSE,
1541
   *   ),
1542
   * );
1543
   * @endcode
1544
   */
1545
  function assertFilteredString($filter, $tests) {
1546
    foreach ($tests as $source => $tasks) {
1547
      $function = $filter->callback;
1548
      $result = $function($source, $filter);
1549
      foreach ($tasks as $value => $is_expected) {
1550
        // Not using assertIdentical, since combination with strpos() is hard to grok.
1551
        if ($is_expected) {
1552
          $success = $this->assertTrue(strpos($result, $value) !== FALSE, format_string('@source: @value found.', array(
1553
            '@source' => var_export($source, TRUE),
1554
            '@value' => var_export($value, TRUE),
1555
          )));
1556
        }
1557
        else {
1558
          $success = $this->assertTrue(strpos($result, $value) === FALSE, format_string('@source: @value not found.', array(
1559
            '@source' => var_export($source, TRUE),
1560
            '@value' => var_export($value, TRUE),
1561
          )));
1562
        }
1563
        if (!$success) {
1564
          $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
1565
            . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
1566
            . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
1567
            . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
1568
          );
1569
        }
1570
      }
1571
    }
1572
  }
1573

    
1574
  /**
1575
   * Tests URL filter on longer content.
1576
   *
1577
   * Filters based on regular expressions should also be tested with a more
1578
   * complex content than just isolated test lines.
1579
   * The most common errors are:
1580
   * - accidental '*' (greedy) match instead of '*?' (minimal) match.
1581
   * - only matching first occurrence instead of all.
1582
   * - newlines not matching '.*'.
1583
   *
1584
   * This test covers:
1585
   * - Document with multiple newlines and paragraphs (two newlines).
1586
   * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
1587
   *   comments.
1588
   * - Empty HTML tags (BR, IMG).
1589
   * - Mix of absolute and partial URLs, and e-mail addresses in one content.
1590
   */
1591
  function testUrlFilterContent() {
1592
    // Setup dummy filter object.
1593
    $filter = new stdClass();
1594
    $filter->settings = array(
1595
      'filter_url_length' => 496,
1596
    );
1597
    $path = drupal_get_path('module', 'filter') . '/tests';
1598

    
1599
    $input = file_get_contents($path . '/filter.url-input.txt');
1600
    $expected = file_get_contents($path . '/filter.url-output.txt');
1601
    $result = _filter_url($input, $filter);
1602
    $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
1603
  }
1604

    
1605
  /**
1606
   * Tests the HTML corrector filter.
1607
   *
1608
   * @todo This test could really use some validity checking function.
1609
   */
1610
  function testHtmlCorrectorFilter() {
1611
    // Tag closing.
1612
    $f = _filter_htmlcorrector('<p>text');
1613
    $this->assertEqual($f, '<p>text</p>', 'HTML corrector -- tag closing at the end of input.');
1614

    
1615
    $f = _filter_htmlcorrector('<p>text<p><p>text');
1616
    $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', 'HTML corrector -- tag closing.');
1617

    
1618
    $f = _filter_htmlcorrector("<ul><li>e1<li>e2");
1619
    $this->assertEqual($f, "<ul><li>e1</li><li>e2</li></ul>", 'HTML corrector -- unclosed list tags.');
1620

    
1621
    $f = _filter_htmlcorrector('<div id="d">content');
1622
    $this->assertEqual($f, '<div id="d">content</div>', 'HTML corrector -- unclosed tag with attribute.');
1623

    
1624
    // XHTML slash for empty elements.
1625
    $f = _filter_htmlcorrector('<hr><br>');
1626
    $this->assertEqual($f, '<hr /><br />', 'HTML corrector -- XHTML closing slash.');
1627

    
1628
    $f = _filter_htmlcorrector('<P>test</P>');
1629
    $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
1630

    
1631
    $f = _filter_htmlcorrector('<P>test</p>');
1632
    $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
1633

    
1634
    $f = _filter_htmlcorrector('test<hr />');
1635
    $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through.');
1636

    
1637
    $f = _filter_htmlcorrector('test<hr/>');
1638
    $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there is a single space before the closing slash.');
1639

    
1640
    $f = _filter_htmlcorrector('test<hr    />');
1641
    $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there are not too many spaces before the closing slash.');
1642

    
1643
    $f = _filter_htmlcorrector('<span class="test" />');
1644
    $this->assertEqual($f, '<span class="test"></span>', 'HTML corrector -- Convert XHTML that is properly formed but that would not be compatible with typical HTML user agents.');
1645

    
1646
    $f = _filter_htmlcorrector('test1<br class="test">test2');
1647
    $this->assertEqual($f, 'test1<br class="test" />test2', 'HTML corrector -- Automatically close single tags.');
1648

    
1649
    $f = _filter_htmlcorrector('line1<hr>line2');
1650
    $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
1651

    
1652
    $f = _filter_htmlcorrector('line1<HR>line2');
1653
    $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
1654

    
1655
    $f = _filter_htmlcorrector('<img src="http://example.com/test.jpg">test</img>');
1656
    $this->assertEqual($f, '<img src="http://example.com/test.jpg" />test', 'HTML corrector -- Automatically close single tags.');
1657

    
1658
    $f = _filter_htmlcorrector('<br></br>');
1659
    $this->assertEqual($f, '<br />', "HTML corrector -- Transform empty tags to a single closed tag if the tag's content model is EMPTY.");
1660

    
1661
    $f = _filter_htmlcorrector('<div></div>');
1662
    $this->assertEqual($f, '<div></div>', "HTML corrector -- Do not transform empty tags to a single closed tag if the tag's content model is not EMPTY.");
1663

    
1664
    $f = _filter_htmlcorrector('<p>line1<br/><hr/>line2</p>');
1665
    $this->assertEqual($f, '<p>line1<br /></p><hr />line2', 'HTML corrector -- Move non-inline elements outside of inline containers.');
1666

    
1667
    $f = _filter_htmlcorrector('<p>line1<div>line2</div></p>');
1668
    $this->assertEqual($f, '<p>line1</p><div>line2</div>', 'HTML corrector -- Move non-inline elements outside of inline containers.');
1669

    
1670
    $f = _filter_htmlcorrector('<p>test<p>test</p>\n');
1671
    $this->assertEqual($f, '<p>test</p><p>test</p>\n', 'HTML corrector -- Auto-close improperly nested tags.');
1672

    
1673
    $f = _filter_htmlcorrector('<p>Line1<br><STRONG>bold stuff</b>');
1674
    $this->assertEqual($f, '<p>Line1<br /><strong>bold stuff</strong></p>', 'HTML corrector -- Properly close unclosed tags, and remove useless closing tags.');
1675

    
1676
    $f = _filter_htmlcorrector('test <!-- this is a comment -->');
1677
    $this->assertEqual($f, 'test <!-- this is a comment -->', 'HTML corrector -- Do not touch HTML comments.');
1678

    
1679
    $f = _filter_htmlcorrector('test <!--this is a comment-->');
1680
    $this->assertEqual($f, 'test <!--this is a comment-->', 'HTML corrector -- Do not touch HTML comments.');
1681

    
1682
    $f = _filter_htmlcorrector('test <!-- comment <p>another
1683
    <strong>multiple</strong> line
1684
    comment</p> -->');
1685
    $this->assertEqual($f, 'test <!-- comment <p>another
1686
    <strong>multiple</strong> line
1687
    comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
1688

    
1689
    $f = _filter_htmlcorrector('test <!-- comment <p>another comment</p> -->');
1690
    $this->assertEqual($f, 'test <!-- comment <p>another comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
1691

    
1692
    $f = _filter_htmlcorrector('test <!--break-->');
1693
    $this->assertEqual($f, 'test <!--break-->', 'HTML corrector -- Do not touch HTML comments.');
1694

    
1695
    $f = _filter_htmlcorrector('<p>test\n</p>\n');
1696
    $this->assertEqual($f, '<p>test\n</p>\n', 'HTML corrector -- New-lines are accepted and kept as-is.');
1697

    
1698
    $f = _filter_htmlcorrector('<p>دروبال');
1699
    $this->assertEqual($f, '<p>دروبال</p>', 'HTML corrector -- Encoding is correctly kept.');
1700

    
1701
    $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
1702
    $this->assertEqual($f, '<script type="text/javascript">
1703
<!--//--><![CDATA[// ><!--
1704
alert("test")
1705
//--><!]]>
1706
</script>', 'HTML corrector -- CDATA added to script element');
1707

    
1708
    $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
1709
    $this->assertEqual($f, '<p><script type="text/javascript">
1710
<!--//--><![CDATA[// ><!--
1711
alert("test")
1712
//--><!]]>
1713
</script></p>', 'HTML corrector -- CDATA added to a nested script element');
1714

    
1715
    $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
1716
    $this->assertEqual($f, '<p><style>
1717
<!--/*--><![CDATA[/* ><!--*/
1718
 /* Styling */ body {color:red}
1719
/*--><!]]>*/
1720
</style></p>', 'HTML corrector -- CDATA added to a style element.');
1721

    
1722
    $filtered_data = _filter_htmlcorrector('<p><style>
1723
/*<![CDATA[*/
1724
/* Styling */
1725
body {color:red}
1726
/*]]>*/
1727
</style></p>');
1728
    $this->assertEqual($filtered_data, '<p><style>
1729
<!--/*--><![CDATA[/* ><!--*/
1730

    
1731
/*<![CDATA[*/
1732
/* Styling */
1733
body {color:red}
1734
/*]]]]><![CDATA[>*/
1735

    
1736
/*--><!]]>*/
1737
</style></p>',
1738
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
1739
    );
1740

    
1741
    $filtered_data = _filter_htmlcorrector('<p><style>
1742
  <!--/*--><![CDATA[/* ><!--*/
1743
  /* Styling */
1744
  body {color:red}
1745
  /*--><!]]>*/
1746
</style></p>');
1747
    $this->assertEqual($filtered_data, '<p><style>
1748
<!--/*--><![CDATA[/* ><!--*/
1749

    
1750
  <!--/*--><![CDATA[/* ><!--*/
1751
  /* Styling */
1752
  body {color:red}
1753
  /*--><!]]]]><![CDATA[>*/
1754

    
1755
/*--><!]]>*/
1756
</style></p>',
1757
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
1758
    );
1759

    
1760
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1761
<!--//--><![CDATA[// ><!--
1762
  alert("test");
1763
//--><!]]>
1764
</script></p>');
1765
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1766
<!--//--><![CDATA[// ><!--
1767

    
1768
<!--//--><![CDATA[// ><!--
1769
  alert("test");
1770
//--><!]]]]><![CDATA[>
1771

    
1772
//--><!]]>
1773
</script></p>',
1774
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
1775
    );
1776

    
1777
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1778
// <![CDATA[
1779
  alert("test");
1780
// ]]>
1781
</script></p>');
1782
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1783
<!--//--><![CDATA[// ><!--
1784

    
1785
// <![CDATA[
1786
  alert("test");
1787
// ]]]]><![CDATA[>
1788

    
1789
//--><!]]>
1790
</script></p>',
1791
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
1792
    );
1793

    
1794
  }
1795

    
1796
  /**
1797
   * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
1798
   *
1799
   * Otherwise fails the test with a given message, similar to all the
1800
   * SimpleTest assert* functions.
1801
   *
1802
   * Note that this does not remove nulls, new lines and other characters that
1803
   * could be used to obscure a tag or an attribute name.
1804
   *
1805
   * @param $haystack
1806
   *   Text to look in.
1807
   * @param $needle
1808
   *   Lowercase, plain text to look for.
1809
   * @param $message
1810
   *   (optional) Message to display if failed. Defaults to an empty string.
1811
   * @param $group
1812
   *   (optional) The group this message belongs to. Defaults to 'Other'.
1813
   * @return
1814
   *   TRUE on pass, FALSE on fail.
1815
   */
1816
  function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
1817
    return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
1818
  }
1819

    
1820
  /**
1821
   * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
1822
   *
1823
   * Otherwise fails the test with a given message, similar to all the
1824
   * SimpleTest assert* functions.
1825
   *
1826
   * Note that this does not remove nulls, new lines, and other character that
1827
   * could be used to obscure a tag or an attribute name.
1828
   *
1829
   * @param $haystack
1830
   *   Text to look in.
1831
   * @param $needle
1832
   *   Lowercase, plain text to look for.
1833
   * @param $message
1834
   *   (optional) Message to display if failed. Defaults to an empty string.
1835
   * @param $group
1836
   *   (optional) The group this message belongs to. Defaults to 'Other'.
1837
   * @return
1838
   *   TRUE on pass, FALSE on fail.
1839
   */
1840
  function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
1841
    return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
1842
  }
1843
}
1844

    
1845
/**
1846
 * Tests for Filter's hook invocations.
1847
 */
1848
class FilterHooksTestCase extends DrupalWebTestCase {
1849
  public static function getInfo() {
1850
    return array(
1851
      'name' => 'Filter format hooks',
1852
      'description' => 'Test hooks for text formats insert/update/disable.',
1853
      'group' => 'Filter',
1854
    );
1855
  }
1856

    
1857
  function setUp() {
1858
    parent::setUp('block', 'filter_test');
1859
    $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
1860
    $this->drupalLogin($admin_user);
1861
  }
1862

    
1863
  /**
1864
   * Tests hooks on format management.
1865
   *
1866
   * Tests that hooks run correctly on creating, editing, and deleting a text
1867
   * format.
1868
   */
1869
  function testFilterHooks() {
1870
    // Add a text format.
1871
    $name = $this->randomName();
1872
    $edit = array();
1873
    $edit['format'] = drupal_strtolower($this->randomName());
1874
    $edit['name'] = $name;
1875
    $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 1;
1876
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
1877
    $this->assertRaw(t('Added text format %format.', array('%format' => $name)), 'New format created.');
1878
    $this->assertText('hook_filter_format_insert invoked.', 'hook_filter_format_insert was invoked.');
1879

    
1880
    $format_id = $edit['format'];
1881

    
1882
    // Update text format.
1883
    $edit = array();
1884
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
1885
    $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
1886
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), 'Format successfully updated.');
1887
    $this->assertText('hook_filter_format_update invoked.', 'hook_filter_format_update() was invoked.');
1888

    
1889
    // Add a new custom block.
1890
    $custom_block = array();
1891
    $custom_block['info'] = $this->randomName(8);
1892
    $custom_block['title'] = $this->randomName(8);
1893
    $custom_block['body[value]'] = $this->randomName(32);
1894
    // Use the format created.
1895
    $custom_block['body[format]'] = $format_id;
1896
    $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
1897
    $this->assertText(t('The block has been created.'), 'New block successfully created.');
1898

    
1899
    // Verify the new block is in the database.
1900
    $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
1901
    $this->assertNotNull($bid, 'New block found in database');
1902

    
1903
    // Disable the text format.
1904
    $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
1905
    $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), 'Format successfully disabled.');
1906
    $this->assertText('hook_filter_format_disable invoked.', 'hook_filter_format_disable() was invoked.');
1907
  }
1908
}
1909

    
1910
/**
1911
 * Tests filter settings.
1912
 */
1913
class FilterSettingsTestCase extends DrupalWebTestCase {
1914
  /**
1915
   * The installation profile to use with this test class.
1916
   *
1917
   * @var string
1918
   */
1919
  protected $profile = 'testing';
1920

    
1921
  public static function getInfo() {
1922
    return array(
1923
      'name' => 'Filter settings',
1924
      'description' => 'Tests filter settings.',
1925
      'group' => 'Filter',
1926
    );
1927
  }
1928

    
1929
  /**
1930
   * Tests explicit and implicit default settings for filters.
1931
   */
1932
  function testFilterDefaults() {
1933
    $filter_info = filter_filter_info();
1934
    $filters = array_fill_keys(array_keys($filter_info), array());
1935

    
1936
    // Create text format using filter default settings.
1937
    $filter_defaults_format = (object) array(
1938
      'format' => 'filter_defaults',
1939
      'name' => 'Filter defaults',
1940
      'filters' => $filters,
1941
    );
1942
    filter_format_save($filter_defaults_format);
1943

    
1944
    // Verify that default weights defined in hook_filter_info() were applied.
1945
    $saved_settings = array();
1946
    foreach ($filter_defaults_format->filters as $name => $settings) {
1947
      $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
1948
      $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
1949
        '@name' => $name,
1950
        '%saved' => $settings['weight'],
1951
        '%default' => $expected_weight,
1952
      )));
1953
      $saved_settings[$name]['weight'] = $expected_weight;
1954
    }
1955

    
1956
    // Re-save the text format.
1957
    filter_format_save($filter_defaults_format);
1958
    // Reload it from scratch.
1959
    filter_formats_reset();
1960
    $filter_defaults_format = filter_format_load($filter_defaults_format->format);
1961
    $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
1962

    
1963
    // Verify that saved filter settings have not been changed.
1964
    foreach ($filter_defaults_format->filters as $name => $settings) {
1965
      $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
1966
        '@name' => $name,
1967
        '%saved' => $settings->weight,
1968
        '%previous' => $saved_settings[$name]['weight'],
1969
      )));
1970
    }
1971
  }
1972
}