Projet

Général

Profil

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

root / drupal7 / modules / filter / filter.test @ 01dfd3b5

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
    // @todo This dataset currently fails under 5.4 because of
1124
    //   https://www.drupal.org/node/1210798. Restore after it's fixed.
1125
    if (version_compare(PHP_VERSION, '5.4.0', '<')) {
1126
      $f = filter_xss('<img src=" &#14;  javascript:alert(0)">', array('img'));
1127
      $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
1128
    }
1129

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

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

    
1136
    // Netscape 4.x javascript entities.
1137
    $f = filter_xss('<br size="&{alert(0)}">', array('br'));
1138
    $this->assertNoNormalized($f, 'alert', 'Netscape 4.x javascript entities.');
1139

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

    
1145
    $f = filter_xss("\xc0aaa");
1146
    $this->assertEqual($f, '', 'HTML filter -- overlong UTF-8 sequences.');
1147

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

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

    
1154
    $f = filter_xss("Who&amp;amp;#039; Online");
1155
    $this->assertNormalized($f, "who&amp;#039; online", 'HTML filter -- double encoded html entity number');
1156
  }
1157

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

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

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

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

    
1192
    $f = _filter_html('<style />', $filter);
1193
    $this->assertNoNormalized($f, 'style', 'HTML filter should always remove style tags.');
1194

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1303

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

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

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

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

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

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

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

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

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

    
1655
    $f = _filter_htmlcorrector('<p>text<p><p>text');
1656
    $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', 'HTML corrector -- tag closing.');
1657

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

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

    
1664
    // XHTML slash for empty elements.
1665
    $f = _filter_htmlcorrector('<hr><br>');
1666
    $this->assertEqual($f, '<hr /><br />', 'HTML corrector -- XHTML closing slash.');
1667

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

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

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

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

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

    
1683
    $f = _filter_htmlcorrector('<span class="test" />');
1684
    $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.');
1685

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

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

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

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

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

    
1701
    $f = _filter_htmlcorrector('<div></div>');
1702
    $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.");
1703

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1771
/*<![CDATA[*/
1772
/* Styling */
1773
body {color:red}
1774
/*]]]]><![CDATA[>*/
1775

    
1776
/*--><!]]>*/
1777
</style></p>',
1778
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
1779
    );
1780

    
1781
    $filtered_data = _filter_htmlcorrector('<p><style>
1782
  <!--/*--><![CDATA[/* ><!--*/
1783
  /* Styling */
1784
  body {color:red}
1785
  /*--><!]]>*/
1786
</style></p>');
1787
    $this->assertEqual($filtered_data, '<p><style>
1788
<!--/*--><![CDATA[/* ><!--*/
1789

    
1790
  <!--/*--><![CDATA[/* ><!--*/
1791
  /* Styling */
1792
  body {color:red}
1793
  /*--><!]]]]><![CDATA[>*/
1794

    
1795
/*--><!]]>*/
1796
</style></p>',
1797
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
1798
    );
1799

    
1800
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1801
<!--//--><![CDATA[// ><!--
1802
  alert("test");
1803
//--><!]]>
1804
</script></p>');
1805
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1806
<!--//--><![CDATA[// ><!--
1807

    
1808
<!--//--><![CDATA[// ><!--
1809
  alert("test");
1810
//--><!]]]]><![CDATA[>
1811

    
1812
//--><!]]>
1813
</script></p>',
1814
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
1815
    );
1816

    
1817
    $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
1818
// <![CDATA[
1819
  alert("test");
1820
// ]]>
1821
</script></p>');
1822
    $this->assertEqual($filtered_data, '<p><script type="text/javascript">
1823
<!--//--><![CDATA[// ><!--
1824

    
1825
// <![CDATA[
1826
  alert("test");
1827
// ]]]]><![CDATA[>
1828

    
1829
//--><!]]>
1830
</script></p>',
1831
      format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
1832
    );
1833

    
1834
  }
1835

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

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

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

    
1897
  function setUp() {
1898
    parent::setUp('block', 'filter_test');
1899
    $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
1900
    $this->drupalLogin($admin_user);
1901
  }
1902

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

    
1920
    $format_id = $edit['format'];
1921

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

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

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

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

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

    
1961
  public static function getInfo() {
1962
    return array(
1963
      'name' => 'Filter settings',
1964
      'description' => 'Tests filter settings.',
1965
      'group' => 'Filter',
1966
    );
1967
  }
1968

    
1969
  /**
1970
   * Tests explicit and implicit default settings for filters.
1971
   */
1972
  function testFilterDefaults() {
1973
    $filter_info = filter_filter_info();
1974
    $filters = array_fill_keys(array_keys($filter_info), array());
1975

    
1976
    // Create text format using filter default settings.
1977
    $filter_defaults_format = (object) array(
1978
      'format' => 'filter_defaults',
1979
      'name' => 'Filter defaults',
1980
      'filters' => $filters,
1981
    );
1982
    filter_format_save($filter_defaults_format);
1983

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

    
1996
    // Re-save the text format.
1997
    filter_format_save($filter_defaults_format);
1998
    // Reload it from scratch.
1999
    filter_formats_reset();
2000
    $filter_defaults_format = filter_format_load($filter_defaults_format->format);
2001
    $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
2002

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

    
2014
/**
2015
 * Tests DOMDocument serialization.
2016
 */
2017
class FilterDOMSerializeTestCase extends DrupalWebTestCase {
2018

    
2019
  public static function getInfo() {
2020
    return array(
2021
      'name' => 'Serialization',
2022
      'description' => 'Test serialization of DOMDocument objects.',
2023
      'group' => 'Filter',
2024
    );
2025
  }
2026

    
2027
  /**
2028
   * Tests empty DOMDocument object.
2029
   */
2030
  function testFilterEmptyDOMSerialization() {
2031
    $document = new DOMDocument();
2032
    $result = filter_dom_serialize($document);
2033
    $this->assertEqual('', $result);
2034
  }
2035
}