Projet

Général

Profil

Paste
Télécharger (87,7 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / filter / filter.test @ 582db59d

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
    // Add a new format to check for Xss in format name.
75
    $format = new stdClass();
76
    $format->format = 'xss_format';
77
    $format->name = '<script>alert(123)</script>';
78
    filter_format_save($format);
79
    user_role_change_permissions(DRUPAL_ANONYMOUS_RID, array(filter_permission_name($format) => 1));
80
    $this->drupalGet('filter/tips');
81
    $this->assertNoRaw($format->name, 'Text format name contains no xss.');
82
  }
83

    
84
  /**
85
   * Verifies that a text format is properly stored.
86
   */
87
  function verifyTextFormat($format) {
88
    $t_args = array('%format' => $format->name);
89
    // Verify text format database record.
90
    $db_format = db_select('filter_format', 'ff')
91
      ->fields('ff')
92
      ->condition('format', $format->format)
93
      ->execute()
94
      ->fetchObject();
95
    $this->assertEqual($db_format->format, $format->format, format_string('Database: Proper format id for text format %format.', $t_args));
96
    $this->assertEqual($db_format->name, $format->name, format_string('Database: Proper title for text format %format.', $t_args));
97
    $this->assertEqual($db_format->cache, $format->cache, format_string('Database: Proper cache indicator for text format %format.', $t_args));
98
    $this->assertEqual($db_format->weight, $format->weight, format_string('Database: Proper weight for text format %format.', $t_args));
99

    
100
    // Verify filter_format_load().
101
    $filter_format = filter_format_load($format->format);
102
    $this->assertEqual($filter_format->format, $format->format, format_string('filter_format_load: Proper format id for text format %format.', $t_args));
103
    $this->assertEqual($filter_format->name, $format->name, format_string('filter_format_load: Proper title for text format %format.', $t_args));
104
    $this->assertEqual($filter_format->cache, $format->cache, format_string('filter_format_load: Proper cache indicator for text format %format.', $t_args));
105
    $this->assertEqual($filter_format->weight, $format->weight, format_string('filter_format_load: Proper weight for text format %format.', $t_args));
106

    
107
    // Verify the 'cache' text format property according to enabled filters.
108
    $filter_info = filter_get_filters();
109
    $filters = filter_list_format($filter_format->format);
110
    $cacheable = TRUE;
111
    foreach ($filters as $name => $filter) {
112
      // If this filter is not cacheable, update $cacheable accordingly, so we
113
      // can verify $format->cache after iterating over all filters.
114
      if ($filter->status && isset($filter_info[$name]['cache']) && !$filter_info[$name]['cache']) {
115
        $cacheable = FALSE;
116
        break;
117
      }
118
    }
119
    $this->assertEqual($filter_format->cache, $cacheable, 'Text format contains proper cache property.');
120
  }
121

    
122
  /**
123
   * Verifies that filters are properly stored for a text format.
124
   */
125
  function verifyFilters($format) {
126
    // Verify filter database records.
127
    $filters = db_query("SELECT * FROM {filter} WHERE format = :format", array(':format' => $format->format))->fetchAllAssoc('name');
128
    $format_filters = $format->filters;
129
    foreach ($filters as $name => $filter) {
130
      $t_args = array('%format' => $format->name, '%filter' => $name);
131

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

    
135
      // Verify that filter settings were properly stored.
136
      $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));
137

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

    
141
      // Remove the filter from the copy of saved $format to check whether all
142
      // filters have been processed later.
143
      unset($format_filters[$name]);
144
    }
145
    // Verify that all filters have been processed.
146
    $this->assertTrue(empty($format_filters), 'Database contains values for all filters in the saved format.');
147

    
148
    // Verify filter_list_format().
149
    $filters = filter_list_format($format->format);
150
    $format_filters = $format->filters;
151
    foreach ($filters as $name => $filter) {
152
      $t_args = array('%format' => $format->name, '%filter' => $name);
153

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

    
157
      // Verify that filter settings were properly stored.
158
      $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));
159

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

    
163
      // Remove the filter from the copy of saved $format to check whether all
164
      // filters have been processed later.
165
      unset($format_filters[$name]);
166
    }
167
    // Verify that all filters have been processed.
168
    $this->assertTrue(empty($format_filters), 'filter_list_format: Loaded filters contain values for all filters in the saved format.');
169
  }
170
}
171

    
172
/**
173
 * Tests the administrative functionality of the Filter module.
174
 */
175
class FilterAdminTestCase extends DrupalWebTestCase {
176
  public static function getInfo() {
177
    return array(
178
      'name' => 'Filter administration functionality',
179
      'description' => 'Thoroughly test the administrative interface of the filter module.',
180
      'group' => 'Filter',
181
    );
182
  }
183

    
184
  function setUp() {
185
    parent::setUp();
186

    
187
    // Create users.
188
    $filtered_html_format = filter_format_load('filtered_html');
189
    $full_html_format = filter_format_load('full_html');
190
    $this->admin_user = $this->drupalCreateUser(array(
191
      'administer filters',
192
      filter_permission_name($filtered_html_format),
193
      filter_permission_name($full_html_format),
194
    ));
195

    
196
    $this->web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
197
    $this->drupalLogin($this->admin_user);
198
  }
199

    
200
  /**
201
   * Tests the format administration functionality.
202
   */
203
  function testFormatAdmin() {
204
    // Add text format.
205
    $this->drupalGet('admin/config/content/formats');
206
    $this->clickLink('Add text format');
207
    $format_id = drupal_strtolower($this->randomName());
208
    $name = $this->randomName();
209
    $edit = array(
210
      'format' => $format_id,
211
      'name' => $name,
212
    );
213
    $this->drupalPost(NULL, $edit, t('Save configuration'));
214

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

    
219
    // Change the weight of the text format.
220
    $edit = array(
221
      "formats[$format_id][weight]" => 5,
222
    );
223
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
224
    $this->assertFieldByName("formats[$format_id][weight]", 5, 'Text format weight was saved.');
225

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

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

    
236
    // Disable text format.
237
    $this->assertLinkByHref('admin/config/content/formats/' . $format_id . '/disable');
238
    $this->drupalGet('admin/config/content/formats/' . $format_id . '/disable');
239
    $this->drupalPost(NULL, array(), t('Disable'));
240

    
241
    // Verify that disabled text format no longer exists.
242
    $this->drupalGet('admin/config/content/formats/' . $format_id);
243
    $this->assertResponse(404, 'Disabled text format no longer exists.');
244

    
245
    // Attempt to create a format of the same machine name as the disabled
246
    // format but with a different human readable name.
247
    $edit = array(
248
      'format' => $format_id,
249
      'name' => 'New format',
250
    );
251
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
252
    $this->assertText('The machine-readable name is already in use. It must be unique.');
253

    
254
    // Attempt to create a format of the same human readable name as the
255
    // disabled format but with a different machine name.
256
    $edit = array(
257
      'format' => 'new_format',
258
      'name' => $name,
259
    );
260
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
261
    $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', array(
262
      '%name' => $name,
263
    )));
264
  }
265

    
266
  /**
267
   * Tests filter administration functionality.
268
   */
269
  function testFilterAdmin() {
270
    // URL filter.
271
    $first_filter = 'filter_url';
272
    // Line filter.
273
    $second_filter = 'filter_autop';
274

    
275
    $filtered = 'filtered_html';
276
    $full = 'full_html';
277
    $plain = 'plain_text';
278

    
279
    // Check that the fallback format exists and cannot be disabled.
280
    $this->assertTrue($plain == filter_fallback_format(), 'The fallback format is set to plain text.');
281
    $this->drupalGet('admin/config/content/formats');
282
    $this->assertNoRaw('admin/config/content/formats/' . $plain . '/disable', 'Disable link for the fallback format not found.');
283
    $this->drupalGet('admin/config/content/formats/' . $plain . '/disable');
284
    $this->assertResponse(403, 'The fallback format cannot be disabled.');
285

    
286
    // Verify access permissions to Full HTML format.
287
    $this->assertTrue(filter_access(filter_format_load($full), $this->admin_user), 'Admin user may use Full HTML.');
288
    $this->assertFalse(filter_access(filter_format_load($full), $this->web_user), 'Web user may not use Full HTML.');
289

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

    
296
    $result = db_query('SELECT * FROM {cache_filter}')->fetchObject();
297
    $this->assertFalse($result, 'Cache cleared.');
298

    
299
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
300
      ':first' => 'filters[' . $first_filter . '][weight]',
301
      ':second' => 'filters[' . $second_filter . '][weight]',
302
    ));
303
    $this->assertTrue(!empty($elements), 'Order confirmed in admin interface.');
304

    
305
    // Reorder filters.
306
    $edit = array();
307
    $edit['filters[' . $second_filter . '][weight]'] = 1;
308
    $edit['filters[' . $first_filter . '][weight]'] = 2;
309
    $this->drupalPost(NULL, $edit, t('Save configuration'));
310
    $this->assertFieldByName('filters[' . $second_filter . '][weight]', 1, 'Order saved successfully.');
311
    $this->assertFieldByName('filters[' . $first_filter . '][weight]', 2, 'Order saved successfully.');
312

    
313
    $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
314
      ':first' => 'filters[' . $second_filter . '][weight]',
315
      ':second' => 'filters[' . $first_filter . '][weight]',
316
    ));
317
    $this->assertTrue(!empty($elements), 'Reorder confirmed in admin interface.');
318

    
319
    $result = db_query('SELECT * FROM {filter} WHERE format = :format ORDER BY weight ASC', array(':format' => $filtered));
320
    $filters = array();
321
    foreach ($result as $filter) {
322
      if ($filter->name == $second_filter || $filter->name == $first_filter) {
323
        $filters[] = $filter;
324
      }
325
    }
326
    $this->assertTrue(($filters[0]->name == $second_filter && $filters[1]->name == $first_filter), 'Order confirmed in database.');
327

    
328
    // Add format.
329
    $edit = array();
330
    $edit['format'] = drupal_strtolower($this->randomName());
331
    $edit['name'] = $this->randomName();
332
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
333
    $edit['filters[' . $second_filter . '][status]'] = TRUE;
334
    $edit['filters[' . $first_filter . '][status]'] = TRUE;
335
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
336
    $this->assertRaw(t('Added text format %format.', array('%format' => $edit['name'])), 'New filter created.');
337

    
338
    drupal_static_reset('filter_formats');
339
    $format = filter_format_load($edit['format']);
340
    $this->assertNotNull($format, 'Format found in database.');
341

    
342
    $this->assertFieldByName('roles[' . DRUPAL_AUTHENTICATED_RID . ']', '', 'Role found.');
343
    $this->assertFieldByName('filters[' . $second_filter . '][status]', '', 'Line break filter found.');
344
    $this->assertFieldByName('filters[' . $first_filter . '][status]', '', 'Url filter found.');
345

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

    
350
    // Allow authenticated users on full HTML.
351
    $format = filter_format_load($full);
352
    $edit = array();
353
    $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 0;
354
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
355
    $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
356
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), 'Full HTML format successfully updated.');
357

    
358
    // Switch user.
359
    $this->drupalLogout();
360
    $this->drupalLogin($this->web_user);
361

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

    
365
    // Use filtered HTML and see if it removes tags that are not allowed.
366
    $body = '<em>' . $this->randomName() . '</em>';
367
    $extra_text = 'text';
368
    $text = $body . '<random>' . $extra_text . '</random>';
369

    
370
    $edit = array();
371
    $langcode = LANGUAGE_NONE;
372
    $edit["title"] = $this->randomName();
373
    $edit["body[$langcode][0][value]"] = $text;
374
    $edit["body[$langcode][0][format]"] = $filtered;
375
    $this->drupalPost('node/add/page', $edit, t('Save'));
376
    $this->assertRaw(t('Basic page %title has been created.', array('%title' => $edit["title"])), 'Filtered node created.');
377

    
378
    $node = $this->drupalGetNodeByTitle($edit["title"]);
379
    $this->assertTrue($node, 'Node found in database.');
380

    
381
    $this->drupalGet('node/' . $node->nid);
382
    $this->assertRaw($body . $extra_text, 'Filter removed invalid tag.');
383

    
384
    // Use plain text and see if it escapes all tags, whether allowed or not.
385
    $edit = array();
386
    $edit["body[$langcode][0][format]"] = $plain;
387
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
388
    $this->drupalGet('node/' . $node->nid);
389
    $this->assertText(check_plain($text), 'The "Plain text" text format escapes all HTML tags.');
390

    
391
    // Switch user.
392
    $this->drupalLogout();
393
    $this->drupalLogin($this->admin_user);
394

    
395
    // Clean up.
396
    // Allowed tags.
397
    $edit = array();
398
    $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
399
    $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
400
    $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], 'Changes reverted.');
401

    
402
    // Full HTML.
403
    $edit = array();
404
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = FALSE;
405
    $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
406
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), 'Full HTML format successfully reverted.');
407
    $this->assertFieldByName('roles[' . DRUPAL_AUTHENTICATED_RID . ']', $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'], 'Changes reverted.');
408

    
409
    // Filter order.
410
    $edit = array();
411
    $edit['filters[' . $second_filter . '][weight]'] = 2;
412
    $edit['filters[' . $first_filter . '][weight]'] = 1;
413
    $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
414
    $this->assertFieldByName('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]'], 'Changes reverted.');
415
    $this->assertFieldByName('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]'], 'Changes reverted.');
416
  }
417

    
418
  /**
419
   * Tests the URL filter settings form is properly validated.
420
   */
421
  function testUrlFilterAdmin() {
422
    // The form does not save with an invalid filter URL length.
423
    $edit = array(
424
      'filters[filter_url][settings][filter_url_length]' => $this->randomName(4),
425
    );
426
    $this->drupalPost('admin/config/content/formats/filtered_html', $edit, t('Save configuration'));
427
    $this->assertNoRaw(t('The text format %format has been updated.', array('%format' => 'Filtered HTML')));
428
  }
429
}
430

    
431
/**
432
 * Tests the filter format access functionality in the Filter module.
433
 */
434
class FilterFormatAccessTestCase extends DrupalWebTestCase {
435
  /**
436
   * A user with administrative permissions.
437
   *
438
   * @var object
439
   */
440
  protected $admin_user;
441

    
442
  /**
443
   * A user with 'administer filters' permission.
444
   *
445
   * @var object
446
   */
447
  protected $filter_admin_user;
448

    
449
  /**
450
   * A user with permission to create and edit own content.
451
   *
452
   * @var object
453
   */
454
  protected $web_user;
455

    
456
  /**
457
   * An object representing an allowed text format.
458
   *
459
   * @var object
460
   */
461
  protected $allowed_format;
462

    
463
  /**
464
   * An object representing a disallowed text format.
465
   *
466
   * @var object
467
   */
468
  protected $disallowed_format;
469

    
470
  public static function getInfo() {
471
    return array(
472
      'name' => 'Filter format access',
473
      'description' => 'Tests access to text formats.',
474
      'group' => 'Filter',
475
    );
476
  }
477

    
478
  function setUp() {
479
    parent::setUp();
480

    
481
    // Create a user who can administer text formats, but does not have
482
    // specific permission to use any of them.
483
    $this->filter_admin_user = $this->drupalCreateUser(array(
484
      'administer filters',
485
      'create page content',
486
      'edit any page content',
487
    ));
488

    
489
    // Create two text formats.
490
    $this->drupalLogin($this->filter_admin_user);
491
    $formats = array();
492
    for ($i = 0; $i < 2; $i++) {
493
      $edit = array(
494
        'format' => drupal_strtolower($this->randomName()),
495
        'name' => $this->randomName(),
496
      );
497
      $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
498
      $this->resetFilterCaches();
499
      $formats[] = filter_format_load($edit['format']);
500
    }
501
    list($this->allowed_format, $this->disallowed_format) = $formats;
502
    $this->drupalLogout();
503

    
504
    // Create a regular user with access to one of the formats.
505
    $this->web_user = $this->drupalCreateUser(array(
506
      'create page content',
507
      'edit any page content',
508
      filter_permission_name($this->allowed_format),
509
    ));
510

    
511
    // Create an administrative user who has access to use both formats.
512
    $this->admin_user = $this->drupalCreateUser(array(
513
      'administer filters',
514
      'create page content',
515
      'edit any page content',
516
      filter_permission_name($this->allowed_format),
517
      filter_permission_name($this->disallowed_format),
518
    ));
519
  }
520

    
521
  /**
522
   * Tests the Filter format access permissions functionality.
523
   */
524
  function testFormatPermissions() {
525
    // Make sure that a regular user only has access to the text format they
526
    // were granted access to, as well to the fallback format.
527
    $this->assertTrue(filter_access($this->allowed_format, $this->web_user), 'A regular user has access to a text format they were granted access to.');
528
    $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.');
529
    $this->assertTrue(filter_access(filter_format_load(filter_fallback_format()), $this->web_user), 'A regular user has access to the fallback format.');
530

    
531
    // Perform similar checks as above, but now against the entire list of
532
    // available formats for this user.
533
    $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.');
534
    $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.');
535
    $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.');
536

    
537
    // Make sure that a regular user only has permission to use the format
538
    // they were granted access to.
539
    $this->assertTrue(user_access(filter_permission_name($this->allowed_format), $this->web_user), 'A regular user has permission to use the allowed text format.');
540
    $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.');
541

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

    
559
    // Check regular user access to the filter tips pages.
560
    $this->drupalGet('filter/tips/' . $this->allowed_format->format);
561
    $this->assertResponse(200);
562
    $this->drupalGet('filter/tips/' . $this->disallowed_format->format);
563
    $this->assertResponse(403);
564
    $this->drupalGet('filter/tips/' . filter_fallback_format());
565
    $this->assertResponse(200);
566
    $this->drupalGet('filter/tips/invalid-format');
567
    $this->assertResponse(404);
568

    
569
    // Check admin user access to the filter tips pages.
570
    $this->drupalLogin($this->admin_user);
571
    $this->drupalGet('filter/tips/' . $this->allowed_format->format);
572
    $this->assertResponse(200);
573
    $this->drupalGet('filter/tips/' . $this->disallowed_format->format);
574
    $this->assertResponse(200);
575
    $this->drupalGet('filter/tips/' . filter_fallback_format());
576
    $this->assertResponse(200);
577
    $this->drupalGet('filter/tips/invalid-format');
578
    $this->assertResponse(404);
579
  }
580

    
581
  /**
582
   * Tests if text format is available to a role.
583
   */
584
  function testFormatRoles() {
585
    // Get the role ID assigned to the regular user; it must be the maximum.
586
    $rid = max(array_keys($this->web_user->roles));
587

    
588
    // Check that this role appears in the list of roles that have access to an
589
    // allowed text format, but does not appear in the list of roles that have
590
    // access to a disallowed text format.
591
    $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.');
592
    $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.');
593

    
594
    // Check that the correct text format appears in the list of formats
595
    // available to that role.
596
    $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.');
597
    $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.');
598

    
599
    // Check that the fallback format is always allowed.
600
    $this->assertEqual(filter_get_roles_by_format(filter_format_load(filter_fallback_format())), user_roles(), 'All roles have access to the fallback format.');
601
    $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.');
602
  }
603

    
604
  /**
605
   * Tests editing a page using a disallowed text format.
606
   *
607
   * Verifies that regular users and administrators are able to edit a page, but
608
   * not allowed to change the fields which use an inaccessible text format.
609
   * Also verifies that fields which use a text format that does not exist can
610
   * be edited by administrators only, but that the administrator is forced to
611
   * choose a new format before saving the page.
612
   */
613
  function testFormatWidgetPermissions() {
614
    $langcode = LANGUAGE_NONE;
615
    $title_key = "title";
616
    $body_value_key = "body[$langcode][0][value]";
617
    $body_format_key = "body[$langcode][0][format]";
618

    
619
    // Create node to edit.
620
    $this->drupalLogin($this->admin_user);
621
    $edit = array();
622
    $edit['title'] = $this->randomName(8);
623
    $edit[$body_value_key] = $this->randomName(16);
624
    $edit[$body_format_key] = $this->disallowed_format->format;
625
    $this->drupalPost('node/add/page', $edit, t('Save'));
626
    $node = $this->drupalGetNodeByTitle($edit['title']);
627

    
628
    // Try to edit with a less privileged user.
629
    $this->drupalLogin($this->web_user);
630
    $this->drupalGet('node/' . $node->nid);
631
    $this->clickLink(t('Edit'));
632

    
633
    // Verify that body field is read-only and contains replacement value.
634
    $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.');
635

    
636
    // Verify that title can be changed, but preview displays original body.
637
    $new_edit = array();
638
    $new_edit['title'] = $this->randomName(8);
639
    $this->drupalPost(NULL, $new_edit, t('Preview'));
640
    $this->assertText($edit[$body_value_key], 'Old body found in preview.');
641

    
642
    // Save and verify that only the title was changed.
643
    $this->drupalPost(NULL, $new_edit, t('Save'));
644
    $this->assertNoText($edit['title'], 'Old title not found.');
645
    $this->assertText($new_edit['title'], 'New title found.');
646
    $this->assertText($edit[$body_value_key], 'Old body found.');
647

    
648
    // Check that even an administrator with "administer filters" permission
649
    // cannot edit the body field if they do not have specific permission to
650
    // use its stored format. (This must be disallowed so that the
651
    // administrator is never forced to switch the text format to something
652
    // else.)
653
    $this->drupalLogin($this->filter_admin_user);
654
    $this->drupalGet('node/' . $node->nid . '/edit');
655
    $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.');
656

    
657
    // Disable the text format used above.
658
    filter_format_disable($this->disallowed_format);
659
    $this->resetFilterCaches();
660

    
661
    // Log back in as the less privileged user and verify that the body field
662
    // is still disabled, since the less privileged user should not be able to
663
    // edit content that does not have an assigned format.
664
    $this->drupalLogin($this->web_user);
665
    $this->drupalGet('node/' . $node->nid . '/edit');
666
    $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.');
667

    
668
    // Log back in as the filter administrator and verify that the body field
669
    // can be edited.
670
    $this->drupalLogin($this->filter_admin_user);
671
    $this->drupalGet('node/' . $node->nid . '/edit');
672
    $this->assertNoFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", NULL, 'Text format access denied message not found.');
673
    $this->assertFieldByXPath("//select[@name='$body_format_key']", NULL, 'Text format selector found.');
674

    
675
    // Verify that trying to save the node without selecting a new text format
676
    // produces an error message, and does not result in the node being saved.
677
    $old_title = $new_edit['title'];
678
    $new_title = $this->randomName(8);
679
    $edit = array('title' => $new_title);
680
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
681
    $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
682
    $this->drupalGet('node/' . $node->nid);
683
    $this->assertText($old_title, 'Old title found.');
684
    $this->assertNoText($new_title, 'New title not found.');
685

    
686
    // Now select a new text format and make sure the node can be saved.
687
    $edit[$body_format_key] = filter_fallback_format();
688
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
689
    $this->assertUrl('node/' . $node->nid);
690
    $this->assertText($new_title, 'New title found.');
691
    $this->assertNoText($old_title, 'Old title not found.');
692

    
693
    // Switch the text format to a new one, then disable that format and all
694
    // other formats on the site (leaving only the fallback format).
695
    $this->drupalLogin($this->admin_user);
696
    $edit = array($body_format_key => $this->allowed_format->format);
697
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
698
    $this->assertUrl('node/' . $node->nid);
699
    foreach (filter_formats() as $format) {
700
      if ($format->format != filter_fallback_format()) {
701
        filter_format_disable($format);
702
      }
703
    }
704

    
705
    // Since there is now only one available text format, the widget for
706
    // selecting a text format would normally not display when the content is
707
    // edited. However, we need to verify that the filter administrator still
708
    // is forced to make a conscious choice to reassign the text to a different
709
    // format.
710
    $this->drupalLogin($this->filter_admin_user);
711
    $old_title = $new_title;
712
    $new_title = $this->randomName(8);
713
    $edit = array('title' => $new_title);
714
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
715
    $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
716
    $this->drupalGet('node/' . $node->nid);
717
    $this->assertText($old_title, 'Old title found.');
718
    $this->assertNoText($new_title, 'New title not found.');
719
    $edit[$body_format_key] = filter_fallback_format();
720
    $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
721
    $this->assertUrl('node/' . $node->nid);
722
    $this->assertText($new_title, 'New title found.');
723
    $this->assertNoText($old_title, 'Old title not found.');
724
  }
725

    
726
  /**
727
   * Rebuilds text format and permission caches in the thread running the tests.
728
   */
729
  protected function resetFilterCaches() {
730
    filter_formats_reset();
731
    $this->checkPermissions(array(), TRUE);
732
  }
733
}
734

    
735
/**
736
 * Tests the default filter functionality in the Filter module.
737
 */
738
class FilterDefaultFormatTestCase extends DrupalWebTestCase {
739
  public static function getInfo() {
740
    return array(
741
      'name' => 'Default text format functionality',
742
      'description' => 'Test the default text formats for different users.',
743
      'group' => 'Filter',
744
    );
745
  }
746

    
747
  /**
748
   * Tests if the default text format is accessible to users.
749
   */
750
  function testDefaultTextFormats() {
751
    // Create two text formats, and two users. The first user has access to
752
    // both formats, but the second user only has access to the second one.
753
    $admin_user = $this->drupalCreateUser(array('administer filters'));
754
    $this->drupalLogin($admin_user);
755
    $formats = array();
756
    for ($i = 0; $i < 2; $i++) {
757
      $edit = array(
758
        'format' => drupal_strtolower($this->randomName()),
759
        'name' => $this->randomName(),
760
      );
761
      $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
762
      $this->resetFilterCaches();
763
      $formats[] = filter_format_load($edit['format']);
764
    }
765
    list($first_format, $second_format) = $formats;
766
    $first_user = $this->drupalCreateUser(array(filter_permission_name($first_format), filter_permission_name($second_format)));
767
    $second_user = $this->drupalCreateUser(array(filter_permission_name($second_format)));
768

    
769
    // Adjust the weights so that the first and second formats (in that order)
770
    // are the two lowest weighted formats available to any user.
771
    $minimum_weight = db_query("SELECT MIN(weight) FROM {filter_format}")->fetchField();
772
    $edit = array();
773
    $edit['formats[' . $first_format->format . '][weight]'] = $minimum_weight - 2;
774
    $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 1;
775
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
776
    $this->resetFilterCaches();
777

    
778
    // Check that each user's default format is the lowest weighted format that
779
    // the user has access to.
780
    $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.");
781
    $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.");
782

    
783
    // Reorder the two formats, and check that both users now have the same
784
    // default.
785
    $edit = array();
786
    $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 3;
787
    $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
788
    $this->resetFilterCaches();
789
    $this->assertEqual(filter_default_format($first_user), filter_default_format($second_user), 'After the formats are reordered, both users have the same default format.');
790
  }
791

    
792
  /**
793
   * Rebuilds text format and permission caches in the thread running the tests.
794
   */
795
  protected function resetFilterCaches() {
796
    filter_formats_reset();
797
    $this->checkPermissions(array(), TRUE);
798
  }
799
}
800

    
801
/**
802
 * Tests the behavior of check_markup() when it is called without text format.
803
 */
804
class FilterNoFormatTestCase extends DrupalWebTestCase {
805
  public static function getInfo() {
806
    return array(
807
      'name' => 'Unassigned text format functionality',
808
      'description' => 'Test the behavior of check_markup() when it is called without a text format.',
809
      'group' => 'Filter',
810
    );
811
  }
812

    
813
  /**
814
   * Tests text without format.
815
   *
816
   * Tests if text with no format is filtered the same way as text in the
817
   * fallback format.
818
   */
819
  function testCheckMarkupNoFormat() {
820
    // Create some text. Include some HTML and line breaks, so we get a good
821
    // test of the filtering that is applied to it.
822
    $text = "<strong>" . $this->randomName(32) . "</strong>\n\n<div>" . $this->randomName(32) . "</div>";
823

    
824
    // Make sure that when this text is run through check_markup() with no text
825
    // format, it is filtered as though it is in the fallback format.
826
    $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.');
827
  }
828
}
829

    
830
/**
831
 * Security tests for missing/vanished text formats or filters.
832
 */
833
class FilterSecurityTestCase extends DrupalWebTestCase {
834
  public static function getInfo() {
835
    return array(
836
      'name' => 'Security',
837
      'description' => 'Test the behavior of check_markup() when a filter or text format vanishes.',
838
      'group' => 'Filter',
839
    );
840
  }
841

    
842
  function setUp() {
843
    parent::setUp('php', 'filter_test');
844
    $this->admin_user = $this->drupalCreateUser(array('administer modules', 'administer filters', 'administer site configuration'));
845
    $this->drupalLogin($this->admin_user);
846
  }
847

    
848
  /**
849
   * Tests removal of filtered content when an active filter is disabled.
850
   *
851
   * Tests that filtered content is emptied when an actively used filter module
852
   * is disabled.
853
   */
854
  function testDisableFilterModule() {
855
    // Create a new node.
856
    $node = $this->drupalCreateNode(array('promote' => 1));
857
    $body_raw = $node->body[LANGUAGE_NONE][0]['value'];
858
    $format_id = $node->body[LANGUAGE_NONE][0]['format'];
859
    $this->drupalGet('node/' . $node->nid);
860
    $this->assertText($body_raw, 'Node body found.');
861

    
862
    // Enable the filter_test_replace filter.
863
    $edit = array(
864
      'filters[filter_test_replace][status]' => 1,
865
    );
866
    $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
867

    
868
    // Verify that filter_test_replace filter replaced the content.
869
    $this->drupalGet('node/' . $node->nid);
870
    $this->assertNoText($body_raw, 'Node body not found.');
871
    $this->assertText('Filter: Testing filter', 'Testing filter output found.');
872

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

    
876
    // Verify that the content is empty, because the text format does not exist.
877
    $this->drupalGet('node/' . $node->nid);
878
    $this->assertNoText($body_raw, 'Node body not found.');
879
  }
880
}
881

    
882
/**
883
 * Unit tests for core filters.
884
 */
885
class FilterUnitTestCase extends DrupalUnitTestCase {
886
  public static function getInfo() {
887
    return array(
888
      'name' => 'Filter module filters',
889
      'description' => 'Tests Filter module filters individually.',
890
      'group' => 'Filter',
891
    );
892
  }
893

    
894
  /**
895
   * Tests the line break filter.
896
   */
897
  function testLineBreakFilter() {
898
    // Setup dummy filter object.
899
    $filter = new stdClass();
900
    $filter->callback = '_filter_autop';
901

    
902
    // Since the line break filter naturally needs plenty of newlines in test
903
    // strings and expectations, we're using "\n" instead of regular newlines
904
    // here.
905
    $tests = array(
906
      // Single line breaks should be changed to <br /> tags, while paragraphs
907
      // separated with double line breaks should be enclosed with <p></p> tags.
908
      "aaa\nbbb\n\nccc" => array(
909
        "<p>aaa<br />\nbbb</p>\n<p>ccc</p>" => TRUE,
910
      ),
911
      // Skip contents of certain block tags entirely.
912
      "<script>aaa\nbbb\n\nccc</script>
913
<style>aaa\nbbb\n\nccc</style>
914
<pre>aaa\nbbb\n\nccc</pre>
915
<object>aaa\nbbb\n\nccc</object>
916
<iframe>aaa\nbbb\n\nccc</iframe>
917
" => array(
918
        "<script>aaa\nbbb\n\nccc</script>" => TRUE,
919
        "<style>aaa\nbbb\n\nccc</style>" => TRUE,
920
        "<pre>aaa\nbbb\n\nccc</pre>" => TRUE,
921
        "<object>aaa\nbbb\n\nccc</object>" => TRUE,
922
        "<iframe>aaa\nbbb\n\nccc</iframe>" => TRUE,
923
      ),
924
      // Skip comments entirely.
925
      "One. <!-- comment --> Two.\n<!--\nThree.\n-->\n" => array(
926
        '<!-- comment -->' => TRUE,
927
        "<!--\nThree.\n-->" => TRUE,
928
      ),
929
      // Resulting HTML should produce matching paragraph tags.
930
      '<p><div>  </div></p>' => array(
931
        "<p>\n<div>  </div>\n</p>" => TRUE,
932
      ),
933
      '<div><p>  </p></div>' => array(
934
        "<div>\n</div>" => TRUE,
935
      ),
936
      '<blockquote><pre>aaa</pre></blockquote>' => array(
937
        "<blockquote><pre>aaa</pre></blockquote>" => TRUE,
938
      ),
939
      "<pre>aaa\nbbb\nccc</pre>\nddd\neee" => array(
940
        "<pre>aaa\nbbb\nccc</pre>" => TRUE,
941
        "<p>ddd<br />\neee</p>" => TRUE,
942
      ),
943
      // Comments remain unchanged and subsequent lines/paragraphs are
944
      // transformed normally.
945
      "aaa<!--comment-->\n\nbbb\n\nccc\n\nddd<!--comment\nwith linebreak-->\n\neee\n\nfff" => array(
946
        "<p>aaa</p>\n<!--comment--><p>\nbbb</p>\n<p>ccc</p>\n<p>ddd</p>" => TRUE,
947
        "<!--comment\nwith linebreak--><p>\neee</p>\n<p>fff</p>" => TRUE,
948
      ),
949
      // Check that a comment in a PRE will result that the text after
950
      // the comment, but still in PRE, is not transformed.
951
      "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>\nddd" => array(
952
        "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>" => TRUE,
953
      ),
954
      // Bug 810824, paragraphs were appearing around iframe tags.
955
      "<iframe>aaa</iframe>\n\n" => array(
956
        "<p><iframe>aaa</iframe></p>" => FALSE,
957
      ),
958
    );
959
    $this->assertFilteredString($filter, $tests);
960

    
961
    // Very long string hitting PCRE limits.
962
    $limit = max(ini_get('pcre.backtrack_limit'), ini_get('pcre.recursion_limit'));
963
    $source = $this->randomName($limit);
964
    $result = _filter_autop($source);
965
    $success = $this->assertEqual($result, '<p>' . $source . "</p>\n", 'Line break filter can process very long strings.');
966
    if (!$success) {
967
      $this->verbose("\n" . $source . "\n<hr />\n" . $result);
968
    }
969
  }
970

    
971
  /**
972
   * Tests limiting allowed tags and XSS prevention.
973
   *
974
   * XSS tests assume that script is disallowed by default and src is allowed
975
   * by default, but on* and style attributes are disallowed.
976
   *
977
   * Script injection vectors mostly adopted from http://ha.ckers.org/xss.html.
978
   *
979
   * Relevant CVEs:
980
   * - CVE-2002-1806, ~CVE-2005-0682, ~CVE-2005-2106, CVE-2005-3973,
981
   *   CVE-2006-1226 (= rev. 1.112?), CVE-2008-0273, CVE-2008-3740.
982
   */
983
  function testFilterXSS() {
984
    // Tag stripping, different ways to work around removal of HTML tags.
985
    $f = filter_xss('<script>alert(0)</script>');
986
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping -- simple script without special characters.');
987

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

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

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

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

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

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

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

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

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

    
1016
    // DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
1017
    // work consistently.
1018
    $f = filter_xss('<script>>');
1019
    $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- double closing tag.');
1020

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1094
    $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'));
1095
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 decimal encoding.');
1096

    
1097
    $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'));
1098
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- long UTF-8 encoding.');
1099

    
1100
    $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'));
1101
    $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 hex encoding.');
1102

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

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

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

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

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

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

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

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

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

    
1132
    // Netscape 4.x javascript entities.
1133
    $f = filter_xss('<br size="&{alert(0)}">', array('br'));
1134
    $this->assertNoNormalized($f, 'alert', 'Netscape 4.x javascript entities.');
1135

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

    
1141
    $f = filter_xss("\xc0aaa");
1142
    $this->assertEqual($f, '', 'HTML filter -- overlong UTF-8 sequences.');
1143

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

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

    
1150
    $f = filter_xss("Who&amp;amp;#039; Online");
1151
    $this->assertNormalized($f, "who&amp;#039; online", 'HTML filter -- double encoded html entity number');
1152
  }
1153

    
1154
  /**
1155
   * Tests filter settings, defaults, access restrictions and similar.
1156
   *
1157
   * @todo This is for functions like filter_filter and check_markup, whose
1158
   *   functionality is not completely focused on filtering. Some ideas:
1159
   *   restricting formats according to user permissions, proper cache
1160
   *   handling, defaults -- allowed tags/attributes/protocols.
1161
   *
1162
   * @todo It is possible to add script, iframe etc. to allowed tags, but this
1163
   *   makes HTML filter completely ineffective.
1164
   *
1165
   * @todo Class, id, name and xmlns should be added to disallowed attributes,
1166
   *   or better a whitelist approach should be used for that too.
1167
   */
1168
  function testHtmlFilter() {
1169
    // Setup dummy filter object.
1170
    $filter = new stdClass();
1171
    $filter->settings = array(
1172
      'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <test-element>',
1173
      'filter_html_help' => 1,
1174
      'filter_html_nofollow' => 0,
1175
    );
1176

    
1177
    // HTML filter is not able to secure some tags, these should never be
1178
    // allowed.
1179
    $f = _filter_html('<script />', $filter);
1180
    $this->assertNoNormalized($f, 'script', 'HTML filter should always remove script tags.');
1181

    
1182
    $f = _filter_html('<iframe />', $filter);
1183
    $this->assertNoNormalized($f, 'iframe', 'HTML filter should always remove iframe tags.');
1184

    
1185
    $f = _filter_html('<object />', $filter);
1186
    $this->assertNoNormalized($f, 'object', 'HTML filter should always remove object tags.');
1187

    
1188
    $f = _filter_html('<style />', $filter);
1189
    $this->assertNoNormalized($f, 'style', 'HTML filter should always remove style tags.');
1190

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

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

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

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

    
1206
    $f = _filter_html('<code onerror>&nbsp;</code>', $filter);
1207
    $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove empty on* attributes on default.');
1208

    
1209
    // Custom tags are supported and should be allowed through.
1210
    $f = _filter_html('<test-element></test-element>', $filter);
1211
    $this->assertNormalized($f, 'test-element', 'HTML filter should allow custom elements.');
1212
  }
1213

    
1214
  /**
1215
   * Tests the spam deterrent.
1216
   */
1217
  function testNoFollowFilter() {
1218
    // Setup dummy filter object.
1219
    $filter = new stdClass();
1220
    $filter->settings = array(
1221
      'allowed_html' => '<a>',
1222
      'filter_html_help' => 1,
1223
      'filter_html_nofollow' => 1,
1224
    );
1225

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

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

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

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

    
1240
    $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', $filter);
1241
    $this->assertNoNormalized($f, 'rel="follow"', 'Spam deterrent evasion -- with rel set - rel="follow" removed.');
1242
    $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- with rel set - rel="nofollow" added.');
1243
  }
1244

    
1245
  /**
1246
   * Tests the loose, admin HTML filter.
1247
   */
1248
  function testFilterXSSAdmin() {
1249
    // DRUPAL-SA-2008-044
1250
    $f = filter_xss_admin('<object />');
1251
    $this->assertNoNormalized($f, 'object', 'Admin HTML filter -- should not allow object tag.');
1252

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

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

    
1260
  /**
1261
   * Tests the HTML escaping filter.
1262
   *
1263
   * check_plain() is not tested here.
1264
   */
1265
  function testHtmlEscapeFilter() {
1266
    // Setup dummy filter object.
1267
    $filter = new stdClass();
1268
    $filter->callback = '_filter_html_escape';
1269

    
1270
    $tests = array(
1271
      "   One. <!-- \"comment\" --> Two'.\n<p>Three.</p>\n    " => array(
1272
        "One. &lt;!-- &quot;comment&quot; --&gt; Two&#039;.\n&lt;p&gt;Three.&lt;/p&gt;" => TRUE,
1273
        '   One.' => FALSE,
1274
        "</p>\n    " => FALSE,
1275
      ),
1276
    );
1277
    $this->assertFilteredString($filter, $tests);
1278
  }
1279

    
1280
  /**
1281
   * Tests the URL filter.
1282
   */
1283
  function testUrlFilter() {
1284
    // Setup dummy filter object.
1285
    $filter = new stdClass();
1286
    $filter->callback = '_filter_url';
1287
    $filter->settings = array(
1288
      'filter_url_length' => 496,
1289
    );
1290
    // @todo Possible categories:
1291
    // - absolute, mail, partial
1292
    // - characters/encoding, surrounding markup, security
1293

    
1294
    // Create a e-mail that is too long.
1295
    $long_email = str_repeat('a', 254) . '@example.com';
1296
    $too_long_email = str_repeat('b', 255) . '@example.com';
1297
    $email_with_plus_sign = 'one+two@example.com';
1298

    
1299

    
1300
    // Filter selection/pattern matching.
1301
    $tests = array(
1302
      // HTTP URLs.
1303
      '
1304
http://example.com or www.example.com
1305
' => array(
1306
        '<a href="http://example.com">http://example.com</a>' => TRUE,
1307
        '<a href="http://www.example.com">www.example.com</a>' => TRUE,
1308
      ),
1309
      // MAILTO URLs.
1310
      '
1311
person@example.com or mailto:person2@example.com or ' . $email_with_plus_sign . ' or ' . $long_email . ' but not ' . $too_long_email . '
1312
' => array(
1313
        '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
1314
        '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
1315
        '<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
1316
        '<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
1317
        '<a href="mailto:' . $email_with_plus_sign . '">' . $email_with_plus_sign . '</a>' => TRUE,
1318
      ),
1319
      // URI parts and special characters.
1320
      '
1321
http://trailingslash.com/ or www.trailingslash.com/
1322
http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
1323
http://twitter.com/#!/example/status/22376963142324226
1324
ftp://user:pass@ftp.example.com/~home/dir1
1325
sftp://user@nonstandardport:222/dir
1326
ssh://192.168.0.100/srv/git/drupal.git
1327
' => array(
1328
        '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
1329
        '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
1330
        '<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,
1331
        '<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,
1332
        '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
1333
        '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
1334
        '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
1335
        '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
1336
      ),
1337
      // Encoding.
1338
      '
1339
http://ampersand.com/?a=1&b=2
1340
http://encoded.com/?a=1&amp;b=2
1341
' => array(
1342
        '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
1343
        '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
1344
      ),
1345
      // Domain name length.
1346
      '
1347
www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
1348
me@me.tv
1349
' => array(
1350
        '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
1351
        '<a href="http://www.example.example">www.example.example</a>' => TRUE,
1352
        'http://www.toolong' => FALSE,
1353
        '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
1354
      ),
1355
      // Absolute URL protocols.
1356
      // The list to test is found in the beginning of _filter_url() at
1357
      // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
1358
      '
1359
https://example.com,
1360
ftp://ftp.example.com,
1361
news://example.net,
1362
telnet://example,
1363
irc://example.host,
1364
ssh://odd.geek,
1365
sftp://secure.host?,
1366
webcal://calendar,
1367
rtsp://127.0.0.1,
1368
not foo://disallowed.com.
1369
' => array(
1370
        'href="https://example.com"' => TRUE,
1371
        'href="ftp://ftp.example.com"' => TRUE,
1372
        'href="news://example.net"' => TRUE,
1373
        'href="telnet://example"' => TRUE,
1374
        'href="irc://example.host"' => TRUE,
1375
        'href="ssh://odd.geek"' => TRUE,
1376
        'href="sftp://secure.host"' => TRUE,
1377
        'href="webcal://calendar"' => TRUE,
1378
        'href="rtsp://127.0.0.1"' => TRUE,
1379
        'href="foo://disallowed.com"' => FALSE,
1380
        'not foo://disallowed.com.' => TRUE,
1381
      ),
1382
    );
1383
    $this->assertFilteredString($filter, $tests);
1384

    
1385
    // Surrounding text/punctuation.
1386
    $tests = array(
1387
      '
1388
Partial URL with trailing period www.partial.com.
1389
E-mail with trailing comma person@example.com,
1390
Absolute URL with trailing question http://www.absolute.com?
1391
Query string with trailing exclamation www.query.com/index.php?a=!
1392
Partial URL with 3 trailing www.partial.periods...
1393
E-mail with 3 trailing exclamations@example.com!!!
1394
Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
1395
' => array(
1396
        'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
1397
        'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
1398
        'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
1399
        'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
1400
        'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
1401
        'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
1402
        'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
1403
      ),
1404
      '
1405
(www.parenthesis.com/dir?a=1&b=2#a)
1406
' => array(
1407
        '(<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,
1408
      ),
1409
    );
1410
    $this->assertFilteredString($filter, $tests);
1411

    
1412
    // Surrounding markup.
1413
    $tests = array(
1414
      '
1415
<p xmlns="www.namespace.com" />
1416
<p xmlns="http://namespace.com">
1417
An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
1418
</p>
1419
' => array(
1420
        '<p xmlns="www.namespace.com" />' => TRUE,
1421
        '<p xmlns="http://namespace.com">' => TRUE,
1422
        'href="http://www.namespace.com"' => FALSE,
1423
        'href="http://namespace.com"' => FALSE,
1424
        'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
1425
      ),
1426
      '
1427
Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
1428
but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
1429
' => array(
1430
        '<a href="foo">www.relative.com</a>' => TRUE,
1431
        'href="http://www.relative.com"' => FALSE,
1432
        '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
1433
        '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
1434
        '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
1435
      ),
1436
      '
1437
Test <code>using www.example.com the code tag</code>.
1438
' => array(
1439
        'href' => FALSE,
1440
        'http' => FALSE,
1441
      ),
1442
      '
1443
Intro.
1444
<blockquote>
1445
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>.
1446
</blockquote>
1447

    
1448
Outro.
1449
' => array(
1450
        'href="http://www.example.com"' => TRUE,
1451
        'href="mailto:person@example.com"' => TRUE,
1452
        'href="http://origin.example.com"' => TRUE,
1453
        'http://www.usage.example.com' => FALSE,
1454
        'http://www.example.info' => FALSE,
1455
        'Intro.' => TRUE,
1456
        'Outro.' => TRUE,
1457
      ),
1458
      '
1459
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>
1460
' => array(
1461
        'href="http://www.example.com"' => TRUE,
1462
        'href="http://www.example.pooh"' => TRUE,
1463
      ),
1464
      '
1465
<p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
1466
 It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
1467
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.
1468
' => array(
1469
        'href="http://www.example17.com"' => TRUE,
1470
        'href="http://www.example18.com"' => TRUE,
1471
        'href="http://www.example19.com"' => TRUE,
1472
        'href="http://www.example20.com"' => TRUE,
1473
        'href="http://www.example21.com"' => TRUE,
1474
        'href="mailto:person@example22.com"' => TRUE,
1475
        'href="http://www.example23.com"' => TRUE,
1476
        'href="http://www.example24.com"' => TRUE,
1477
        'href="http://www.example25.com"' => TRUE,
1478
        'href="http://www.example26.com"' => TRUE,
1479
        'href="mailto:person@example27.com"' => TRUE,
1480
        'href="http://www.example28.com"' => TRUE,
1481
      ),
1482
      '
1483
<script>
1484
<!--
1485
  // @see www.example.com
1486
  var exampleurl = "http://example.net";
1487
-->
1488
<!--//--><![CDATA[//><!--
1489
  // @see www.example.com
1490
  var exampleurl = "http://example.net";
1491
//--><!]]>
1492
</script>
1493
' => array(
1494
        'href="http://www.example.com"' => FALSE,
1495
        'href="http://example.net"' => FALSE,
1496
      ),
1497
      '
1498
<style>body {
1499
  background: url(http://example.com/pixel.gif);
1500
}</style>
1501
' => array(
1502
        'href' => FALSE,
1503
      ),
1504
      '
1505
<!-- Skip any URLs like www.example.com in comments -->
1506
' => array(
1507
        'href' => FALSE,
1508
      ),
1509
      '
1510
<!-- Skip any URLs like
1511
www.example.com with a newline in comments -->
1512
' => array(
1513
        'href' => FALSE,
1514
      ),
1515
      '
1516
<!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
1517
' => array(
1518
        'href' => FALSE,
1519
      ),
1520
      '
1521
<dl>
1522
<dt>www.example.com</dt>
1523
<dd>http://example.com</dd>
1524
<dd>person@example.com</dd>
1525
<dt>Check www.example.net</dt>
1526
<dd>Some text around http://www.example.info by person@example.info?</dd>
1527
</dl>
1528
' => array(
1529
        'href="http://www.example.com"' => TRUE,
1530
        'href="http://example.com"' => TRUE,
1531
        'href="mailto:person@example.com"' => TRUE,
1532
        'href="http://www.example.net"' => TRUE,
1533
        'href="http://www.example.info"' => TRUE,
1534
        'href="mailto:person@example.info"' => TRUE,
1535
      ),
1536
      '
1537
<div>www.div.com</div>
1538
<ul>
1539
<li>http://listitem.com</li>
1540
<li class="odd">www.class.listitem.com</li>
1541
</ul>
1542
' => array(
1543
        '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
1544
        '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
1545
        '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
1546
      ),
1547
    );
1548
    $this->assertFilteredString($filter, $tests);
1549

    
1550
    // URL trimming.
1551
    $filter->settings['filter_url_length'] = 20;
1552
    $tests = array(
1553
      'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
1554
        '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
1555
      ),
1556
    );
1557
    $this->assertFilteredString($filter, $tests);
1558
  }
1559

    
1560
  /**
1561
   * Asserts multiple filter output expectations for multiple input strings.
1562
   *
1563
   * @param $filter
1564
   *   A input filter object.
1565
   * @param $tests
1566
   *   An associative array, whereas each key is an arbitrary input string and
1567
   *   each value is again an associative array whose keys are filter output
1568
   *   strings and whose values are Booleans indicating whether the output is
1569
   *   expected or not.
1570
   *
1571
   * For example:
1572
   * @code
1573
   * $tests = array(
1574
   *   'Input string' => array(
1575
   *     '<p>Input string</p>' => TRUE,
1576
   *     'Input string<br' => FALSE,
1577
   *   ),
1578
   * );
1579
   * @endcode
1580
   */
1581
  function assertFilteredString($filter, $tests) {
1582
    foreach ($tests as $source => $tasks) {
1583
      $function = $filter->callback;
1584
      $result = $function($source, $filter);
1585
      foreach ($tasks as $value => $is_expected) {
1586
        // Not using assertIdentical, since combination with strpos() is hard to grok.
1587
        if ($is_expected) {
1588
          $success = $this->assertTrue(strpos($result, $value) !== FALSE, format_string('@source: @value found.', array(
1589
            '@source' => var_export($source, TRUE),
1590
            '@value' => var_export($value, TRUE),
1591
          )));
1592
        }
1593
        else {
1594
          $success = $this->assertTrue(strpos($result, $value) === FALSE, format_string('@source: @value not found.', array(
1595
            '@source' => var_export($source, TRUE),
1596
            '@value' => var_export($value, TRUE),
1597
          )));
1598
        }
1599
        if (!$success) {
1600
          $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
1601
            . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
1602
            . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
1603
            . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
1604
          );
1605
        }
1606
      }
1607
    }
1608
  }
1609

    
1610
  /**
1611
   * Tests URL filter on longer content.
1612
   *
1613
   * Filters based on regular expressions should also be tested with a more
1614
   * complex content than just isolated test lines.
1615
   * The most common errors are:
1616
   * - accidental '*' (greedy) match instead of '*?' (minimal) match.
1617
   * - only matching first occurrence instead of all.
1618
   * - newlines not matching '.*'.
1619
   *
1620
   * This test covers:
1621
   * - Document with multiple newlines and paragraphs (two newlines).
1622
   * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
1623
   *   comments.
1624
   * - Empty HTML tags (BR, IMG).
1625
   * - Mix of absolute and partial URLs, and e-mail addresses in one content.
1626
   */
1627
  function testUrlFilterContent() {
1628
    // Setup dummy filter object.
1629
    $filter = new stdClass();
1630
    $filter->settings = array(
1631
      'filter_url_length' => 496,
1632
    );
1633
    $path = drupal_get_path('module', 'filter') . '/tests';
1634

    
1635
    $input = file_get_contents($path . '/filter.url-input.txt');
1636
    $expected = file_get_contents($path . '/filter.url-output.txt');
1637
    $result = _filter_url($input, $filter);
1638
    $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
1639
  }
1640

    
1641
  /**
1642
   * Tests the HTML corrector filter.
1643
   *
1644
   * @todo This test could really use some validity checking function.
1645
   */
1646
  function testHtmlCorrectorFilter() {
1647
    // Tag closing.
1648
    $f = _filter_htmlcorrector('<p>text');
1649
    $this->assertEqual($f, '<p>text</p>', 'HTML corrector -- tag closing at the end of input.');
1650

    
1651
    $f = _filter_htmlcorrector('<p>text<p><p>text');
1652
    $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', 'HTML corrector -- tag closing.');
1653

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

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

    
1660
    // XHTML slash for empty elements.
1661
    $f = _filter_htmlcorrector('<hr><br>');
1662
    $this->assertEqual($f, '<hr /><br />', 'HTML corrector -- XHTML closing slash.');
1663

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

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

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

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

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

    
1679
    $f = _filter_htmlcorrector('<span class="test" />');
1680
    $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.');
1681

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

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

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

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

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

    
1697
    $f = _filter_htmlcorrector('<div></div>');
1698
    $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.");
1699

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

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

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

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

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

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

    
1718
    $f = _filter_htmlcorrector('test <!-- comment <p>another
1719
    <strong>multiple</strong> line
1720
    comment</p> -->');
1721
    $this->assertEqual($f, 'test <!-- comment <p>another
1722
    <strong>multiple</strong> line
1723
    comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
1724

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

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

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

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

    
1737
    $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
1738
    $this->assertEqual($f, '<script type="text/javascript">
1739
<!--//--><![CDATA[// ><!--
1740
alert("test")
1741
//--><!]]>
1742
</script>', 'HTML corrector -- CDATA added to script element');
1743

    
1744
    $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
1745
    $this->assertEqual($f, '<p><script type="text/javascript">
1746
<!--//--><![CDATA[// ><!--
1747
alert("test")
1748
//--><!]]>
1749
</script></p>', 'HTML corrector -- CDATA added to a nested script element');
1750

    
1751
    $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
1752
    $this->assertEqual($f, '<p><style>
1753
<!--/*--><![CDATA[/* ><!--*/
1754
 /* Styling */ body {color:red}
1755
/*--><!]]>*/
1756
</style></p>', 'HTML corrector -- CDATA added to a style element.');
1757

    
1758
    $filtered_data = _filter_htmlcorrector('<p><style>
1759
/*<![CDATA[*/
1760
/* Styling */
1761
body {color:red}
1762
/*]]>*/
1763
</style></p>');
1764
    $this->assertEqual($filtered_data, '<p><style>
1765
<!--/*--><![CDATA[/* ><!--*/
1766

    
1767
/*<![CDATA[*/
1768
/* Styling */
1769
body {color:red}
1770
/*]]]]><![CDATA[>*/
1771

    
1772
/*--><!]]>*/
1773
</style></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><style>
1778
  <!--/*--><![CDATA[/* ><!--*/
1779
  /* Styling */
1780
  body {color:red}
1781
  /*--><!]]>*/
1782
</style></p>');
1783
    $this->assertEqual($filtered_data, '<p><style>
1784
<!--/*--><![CDATA[/* ><!--*/
1785

    
1786
  <!--/*--><![CDATA[/* ><!--*/
1787
  /* Styling */
1788
  body {color:red}
1789
  /*--><!]]]]><![CDATA[>*/
1790

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

    
1796
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1797
<!--//--><![CDATA[// ><!--
1798
  alert("test");
1799
//--><!]]>
1800
</script></p>');
1801
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1802
<!--//--><![CDATA[// ><!--
1803

    
1804
<!--//--><![CDATA[// ><!--
1805
  alert("test");
1806
//--><!]]]]><![CDATA[>
1807

    
1808
//--><!]]>
1809
</script></p>',
1810
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
1811
    );
1812

    
1813
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1814
// <![CDATA[
1815
  alert("test");
1816
// ]]>
1817
</script></p>');
1818
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1819
<!--//--><![CDATA[// ><!--
1820

    
1821
// <![CDATA[
1822
  alert("test");
1823
// ]]]]><![CDATA[>
1824

    
1825
//--><!]]>
1826
</script></p>',
1827
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
1828
    );
1829

    
1830
  }
1831

    
1832
  /**
1833
   * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
1834
   *
1835
   * Otherwise fails the test with a given message, similar to all the
1836
   * SimpleTest assert* functions.
1837
   *
1838
   * Note that this does not remove nulls, new lines and other characters that
1839
   * could be used to obscure a tag or an attribute name.
1840
   *
1841
   * @param $haystack
1842
   *   Text to look in.
1843
   * @param $needle
1844
   *   Lowercase, plain text to look for.
1845
   * @param $message
1846
   *   (optional) Message to display if failed. Defaults to an empty string.
1847
   * @param $group
1848
   *   (optional) The group this message belongs to. Defaults to 'Other'.
1849
   * @return
1850
   *   TRUE on pass, FALSE on fail.
1851
   */
1852
  function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
1853
    return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
1854
  }
1855

    
1856
  /**
1857
   * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
1858
   *
1859
   * Otherwise fails the test with a given message, similar to all the
1860
   * SimpleTest assert* functions.
1861
   *
1862
   * Note that this does not remove nulls, new lines, and other character that
1863
   * could be used to obscure a tag or an attribute name.
1864
   *
1865
   * @param $haystack
1866
   *   Text to look in.
1867
   * @param $needle
1868
   *   Lowercase, plain text to look for.
1869
   * @param $message
1870
   *   (optional) Message to display if failed. Defaults to an empty string.
1871
   * @param $group
1872
   *   (optional) The group this message belongs to. Defaults to 'Other'.
1873
   * @return
1874
   *   TRUE on pass, FALSE on fail.
1875
   */
1876
  function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
1877
    return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
1878
  }
1879
}
1880

    
1881
/**
1882
 * Tests for Filter's hook invocations.
1883
 */
1884
class FilterHooksTestCase extends DrupalWebTestCase {
1885
  public static function getInfo() {
1886
    return array(
1887
      'name' => 'Filter format hooks',
1888
      'description' => 'Test hooks for text formats insert/update/disable.',
1889
      'group' => 'Filter',
1890
    );
1891
  }
1892

    
1893
  function setUp() {
1894
    parent::setUp('block', 'filter_test');
1895
    $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
1896
    $this->drupalLogin($admin_user);
1897
  }
1898

    
1899
  /**
1900
   * Tests hooks on format management.
1901
   *
1902
   * Tests that hooks run correctly on creating, editing, and deleting a text
1903
   * format.
1904
   */
1905
  function testFilterHooks() {
1906
    // Add a text format.
1907
    $name = $this->randomName();
1908
    $edit = array();
1909
    $edit['format'] = drupal_strtolower($this->randomName());
1910
    $edit['name'] = $name;
1911
    $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 1;
1912
    $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
1913
    $this->assertRaw(t('Added text format %format.', array('%format' => $name)), 'New format created.');
1914
    $this->assertText('hook_filter_format_insert invoked.', 'hook_filter_format_insert was invoked.');
1915

    
1916
    $format_id = $edit['format'];
1917

    
1918
    // Update text format.
1919
    $edit = array();
1920
    $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
1921
    $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
1922
    $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), 'Format successfully updated.');
1923
    $this->assertText('hook_filter_format_update invoked.', 'hook_filter_format_update() was invoked.');
1924

    
1925
    // Add a new custom block.
1926
    $custom_block = array();
1927
    $custom_block['info'] = $this->randomName(8);
1928
    $custom_block['title'] = $this->randomName(8);
1929
    $custom_block['body[value]'] = $this->randomName(32);
1930
    // Use the format created.
1931
    $custom_block['body[format]'] = $format_id;
1932
    $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
1933
    $this->assertText(t('The block has been created.'), 'New block successfully created.');
1934

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

    
1939
    // Disable the text format.
1940
    $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
1941
    $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), 'Format successfully disabled.');
1942
    $this->assertText('hook_filter_format_disable invoked.', 'hook_filter_format_disable() was invoked.');
1943
  }
1944
}
1945

    
1946
/**
1947
 * Tests filter settings.
1948
 */
1949
class FilterSettingsTestCase extends DrupalWebTestCase {
1950
  /**
1951
   * The installation profile to use with this test class.
1952
   *
1953
   * @var string
1954
   */
1955
  protected $profile = 'testing';
1956

    
1957
  public static function getInfo() {
1958
    return array(
1959
      'name' => 'Filter settings',
1960
      'description' => 'Tests filter settings.',
1961
      'group' => 'Filter',
1962
    );
1963
  }
1964

    
1965
  /**
1966
   * Tests explicit and implicit default settings for filters.
1967
   */
1968
  function testFilterDefaults() {
1969
    $filter_info = filter_filter_info();
1970
    $filters = array_fill_keys(array_keys($filter_info), array());
1971

    
1972
    // Create text format using filter default settings.
1973
    $filter_defaults_format = (object) array(
1974
      'format' => 'filter_defaults',
1975
      'name' => 'Filter defaults',
1976
      'filters' => $filters,
1977
    );
1978
    filter_format_save($filter_defaults_format);
1979

    
1980
    // Verify that default weights defined in hook_filter_info() were applied.
1981
    $saved_settings = array();
1982
    foreach ($filter_defaults_format->filters as $name => $settings) {
1983
      $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
1984
      $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
1985
        '@name' => $name,
1986
        '%saved' => $settings['weight'],
1987
        '%default' => $expected_weight,
1988
      )));
1989
      $saved_settings[$name]['weight'] = $expected_weight;
1990
    }
1991

    
1992
    // Re-save the text format.
1993
    filter_format_save($filter_defaults_format);
1994
    // Reload it from scratch.
1995
    filter_formats_reset();
1996
    $filter_defaults_format = filter_format_load($filter_defaults_format->format);
1997
    $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
1998

    
1999
    // Verify that saved filter settings have not been changed.
2000
    foreach ($filter_defaults_format->filters as $name => $settings) {
2001
      $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
2002
        '@name' => $name,
2003
        '%saved' => $settings->weight,
2004
        '%previous' => $saved_settings[$name]['weight'],
2005
      )));
2006
    }
2007
  }
2008
}
2009

    
2010
/**
2011
 * Tests DOMDocument serialization.
2012
 */
2013
class FilterDOMSerializeTestCase extends DrupalWebTestCase {
2014

    
2015
  public static function getInfo() {
2016
    return array(
2017
      'name' => 'Serialization',
2018
      'description' => 'Test serialization of DOMDocument objects.',
2019
      'group' => 'Filter',
2020
    );
2021
  }
2022

    
2023
  /**
2024
   * Tests empty DOMDocument object.
2025
   */
2026
  function testFilterEmptyDOMSerialization() {
2027
    $document = new DOMDocument();
2028
    $result = filter_dom_serialize($document);
2029
    $this->assertEqual('', $result);
2030
  }
2031
}