filter.test

  1. drupal
    1. 7 modules/filter/filter.test
    2. 8 core/modules/filter/filter.test

Tests for filter.module.

Classes

NameDescription
FilterAdminTestCase
FilterCRUDTestCaseTests for text format and filter CRUD operations.
FilterDefaultFormatTestCase
FilterFormatAccessTestCase
FilterHooksTestCaseTests for filter hook invocation.
FilterNoFormatTestCase
FilterSecurityTestCaseSecurity tests for missing/vanished text formats or filters.
FilterSettingsTestCaseTests filter settings.
FilterUnitTestCaseUnit tests for core filters.

File

modules/filter/filter.test
View source
  1. <?php
  2. /**
  3. * @file
  4. * Tests for filter.module.
  5. */
  6. /**
  7. * Tests for text format and filter CRUD operations.
  8. */
  9. class FilterCRUDTestCase extends DrupalWebTestCase {
  10. public static function getInfo() {
  11. return array(
  12. 'name' => 'Filter CRUD operations',
  13. 'description' => 'Test creation, loading, updating, deleting of text formats and filters.',
  14. 'group' => 'Filter',
  15. );
  16. }
  17. function setUp() {
  18. parent::setUp('filter_test');
  19. }
  20. /**
  21. * Test CRUD operations for text formats and filters.
  22. */
  23. function testTextFormatCRUD() {
  24. // Add a text format with minimum data only.
  25. $format = new stdClass();
  26. $format->format = 'empty_format';
  27. $format->name = 'Empty format';
  28. filter_format_save($format);
  29. $this->verifyTextFormat($format);
  30. $this->verifyFilters($format);
  31. // Add another text format specifying all possible properties.
  32. $format = new stdClass();
  33. $format->format = 'custom_format';
  34. $format->name = 'Custom format';
  35. $format->filters = array(
  36. 'filter_url' => array(
  37. 'status' => 1,
  38. 'settings' => array(
  39. 'filter_url_length' => 30,
  40. ),
  41. ),
  42. );
  43. filter_format_save($format);
  44. $this->verifyTextFormat($format);
  45. $this->verifyFilters($format);
  46. // Alter some text format properties and save again.
  47. $format->name = 'Altered format';
  48. $format->filters['filter_url']['status'] = 0;
  49. $format->filters['filter_autop']['status'] = 1;
  50. filter_format_save($format);
  51. $this->verifyTextFormat($format);
  52. $this->verifyFilters($format);
  53. // Add a uncacheable filter and save again.
  54. $format->filters['filter_test_uncacheable']['status'] = 1;
  55. filter_format_save($format);
  56. $this->verifyTextFormat($format);
  57. $this->verifyFilters($format);
  58. // Disable the text format.
  59. filter_format_disable($format);
  60. $db_format = db_query("SELECT * FROM {filter_format} WHERE format = :format", array(':format' => $format->format))->fetchObject();
  61. $this->assertFalse($db_format->status, t('Database: Disabled text format is marked as disabled.'));
  62. $formats = filter_formats();
  63. $this->assertTrue(!isset($formats[$format->format]), t('filter_formats: Disabled text format no longer exists.'));
  64. }
  65. /**
  66. * Verify that a text format is properly stored.
  67. */
  68. function verifyTextFormat($format) {
  69. $t_args = array('%format' => $format->name);
  70. // Verify text format database record.
  71. $db_format = db_select('filter_format', 'ff')
  72. ->fields('ff')
  73. ->condition('format', $format->format)
  74. ->execute()
  75. ->fetchObject();
  76. $this->assertEqual($db_format->format, $format->format, t('Database: Proper format id for text format %format.', $t_args));
  77. $this->assertEqual($db_format->name, $format->name, t('Database: Proper title for text format %format.', $t_args));
  78. $this->assertEqual($db_format->cache, $format->cache, t('Database: Proper cache indicator for text format %format.', $t_args));
  79. $this->assertEqual($db_format->weight, $format->weight, t('Database: Proper weight for text format %format.', $t_args));
  80. // Verify filter_format_load().
  81. $filter_format = filter_format_load($format->format);
  82. $this->assertEqual($filter_format->format, $format->format, t('filter_format_load: Proper format id for text format %format.', $t_args));
  83. $this->assertEqual($filter_format->name, $format->name, t('filter_format_load: Proper title for text format %format.', $t_args));
  84. $this->assertEqual($filter_format->cache, $format->cache, t('filter_format_load: Proper cache indicator for text format %format.', $t_args));
  85. $this->assertEqual($filter_format->weight, $format->weight, t('filter_format_load: Proper weight for text format %format.', $t_args));
  86. // Verify the 'cache' text format property according to enabled filters.
  87. $filter_info = filter_get_filters();
  88. $filters = filter_list_format($filter_format->format);
  89. $cacheable = TRUE;
  90. foreach ($filters as $name => $filter) {
  91. // If this filter is not cacheable, update $cacheable accordingly, so we
  92. // can verify $format->cache after iterating over all filters.
  93. if ($filter->status && isset($filter_info[$name]['cache']) && !$filter_info[$name]['cache']) {
  94. $cacheable = FALSE;
  95. break;
  96. }
  97. }
  98. $this->assertEqual($filter_format->cache, $cacheable, t('Text format contains proper cache property.'));
  99. }
  100. /**
  101. * Verify that filters are properly stored for a text format.
  102. */
  103. function verifyFilters($format) {
  104. // Verify filter database records.
  105. $filters = db_query("SELECT * FROM {filter} WHERE format = :format", array(':format' => $format->format))->fetchAllAssoc('name');
  106. $format_filters = $format->filters;
  107. foreach ($filters as $name => $filter) {
  108. $t_args = array('%format' => $format->name, '%filter' => $name);
  109. // Verify that filter status is properly stored.
  110. $this->assertEqual($filter->status, $format_filters[$name]['status'], t('Database: Proper status for %filter in text format %format.', $t_args));
  111. // Verify that filter settings were properly stored.
  112. $this->assertEqual(unserialize($filter->settings), isset($format_filters[$name]['settings']) ? $format_filters[$name]['settings'] : array(), t('Database: Proper filter settings for %filter in text format %format.', $t_args));
  113. // Verify that each filter has a module name assigned.
  114. $this->assertTrue(!empty($filter->module), t('Database: Proper module name for %filter in text format %format.', $t_args));
  115. // Remove the filter from the copy of saved $format to check whether all
  116. // filters have been processed later.
  117. unset($format_filters[$name]);
  118. }
  119. // Verify that all filters have been processed.
  120. $this->assertTrue(empty($format_filters), t('Database contains values for all filters in the saved format.'));
  121. // Verify filter_list_format().
  122. $filters = filter_list_format($format->format);
  123. $format_filters = $format->filters;
  124. foreach ($filters as $name => $filter) {
  125. $t_args = array('%format' => $format->name, '%filter' => $name);
  126. // Verify that filter status is properly stored.
  127. $this->assertEqual($filter->status, $format_filters[$name]['status'], t('filter_list_format: Proper status for %filter in text format %format.', $t_args));
  128. // Verify that filter settings were properly stored.
  129. $this->assertEqual($filter->settings, isset($format_filters[$name]['settings']) ? $format_filters[$name]['settings'] : array(), t('filter_list_format: Proper filter settings for %filter in text format %format.', $t_args));
  130. // Verify that each filter has a module name assigned.
  131. $this->assertTrue(!empty($filter->module), t('filter_list_format: Proper module name for %filter in text format %format.', $t_args));
  132. // Remove the filter from the copy of saved $format to check whether all
  133. // filters have been processed later.
  134. unset($format_filters[$name]);
  135. }
  136. // Verify that all filters have been processed.
  137. $this->assertTrue(empty($format_filters), t('filter_list_format: Loaded filters contain values for all filters in the saved format.'));
  138. }
  139. }
  140. class FilterAdminTestCase extends DrupalWebTestCase {
  141. public static function getInfo() {
  142. return array(
  143. 'name' => 'Filter administration functionality',
  144. 'description' => 'Thoroughly test the administrative interface of the filter module.',
  145. 'group' => 'Filter',
  146. );
  147. }
  148. function setUp() {
  149. parent::setUp();
  150. // Create users.
  151. $filtered_html_format = filter_format_load('filtered_html');
  152. $full_html_format = filter_format_load('full_html');
  153. $this->admin_user = $this->drupalCreateUser(array(
  154. 'administer filters',
  155. filter_permission_name($filtered_html_format),
  156. filter_permission_name($full_html_format),
  157. ));
  158. $this->web_user = $this->drupalCreateUser(array('create page content', 'edit own page content'));
  159. $this->drupalLogin($this->admin_user);
  160. }
  161. function testFormatAdmin() {
  162. // Add text format.
  163. $this->drupalGet('admin/config/content/formats');
  164. $this->clickLink('Add text format');
  165. $format_id = drupal_strtolower($this->randomName());
  166. $name = $this->randomName();
  167. $edit = array(
  168. 'format' => $format_id,
  169. 'name' => $name,
  170. );
  171. $this->drupalPost(NULL, $edit, t('Save configuration'));
  172. // Verify default weight of the text format.
  173. $this->drupalGet('admin/config/content/formats');
  174. $this->assertFieldByName("formats[$format_id][weight]", 0, t('Text format weight was saved.'));
  175. // Change the weight of the text format.
  176. $edit = array(
  177. "formats[$format_id][weight]" => 5,
  178. );
  179. $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
  180. $this->assertFieldByName("formats[$format_id][weight]", 5, t('Text format weight was saved.'));
  181. // Edit text format.
  182. $this->drupalGet('admin/config/content/formats');
  183. $this->assertLinkByHref('admin/config/content/formats/' . $format_id);
  184. $this->drupalGet('admin/config/content/formats/' . $format_id);
  185. $this->drupalPost(NULL, array(), t('Save configuration'));
  186. // Verify that the custom weight of the text format has been retained.
  187. $this->drupalGet('admin/config/content/formats');
  188. $this->assertFieldByName("formats[$format_id][weight]", 5, t('Text format weight was retained.'));
  189. // Disable text format.
  190. $this->assertLinkByHref('admin/config/content/formats/' . $format_id . '/disable');
  191. $this->drupalGet('admin/config/content/formats/' . $format_id . '/disable');
  192. $this->drupalPost(NULL, array(), t('Disable'));
  193. // Verify that disabled text format no longer exists.
  194. $this->drupalGet('admin/config/content/formats/' . $format_id);
  195. $this->assertResponse(404, t('Disabled text format no longer exists.'));
  196. // Attempt to create a format of the same machine name as the disabled
  197. // format but with a different human readable name.
  198. $edit = array(
  199. 'format' => $format_id,
  200. 'name' => 'New format',
  201. );
  202. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  203. $this->assertText('The machine-readable name is already in use. It must be unique.');
  204. // Attempt to create a format of the same human readable name as the
  205. // disabled format but with a different machine name.
  206. $edit = array(
  207. 'format' => 'new_format',
  208. 'name' => $name,
  209. );
  210. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  211. $this->assertRaw(t('Text format names must be unique. A format named %name already exists.', array(
  212. '%name' => $name,
  213. )));
  214. }
  215. /**
  216. * Test filter administration functionality.
  217. */
  218. function testFilterAdmin() {
  219. // URL filter.
  220. $first_filter = 'filter_url';
  221. // Line filter.
  222. $second_filter = 'filter_autop';
  223. $filtered = 'filtered_html';
  224. $full = 'full_html';
  225. $plain = 'plain_text';
  226. // Check that the fallback format exists and cannot be disabled.
  227. $this->assertTrue($plain == filter_fallback_format(), t('The fallback format is set to plain text.'));
  228. $this->drupalGet('admin/config/content/formats');
  229. $this->assertNoRaw('admin/config/content/formats/' . $plain . '/disable', t('Disable link for the fallback format not found.'));
  230. $this->drupalGet('admin/config/content/formats/' . $plain . '/disable');
  231. $this->assertResponse(403, t('The fallback format cannot be disabled.'));
  232. // Verify access permissions to Full HTML format.
  233. $this->assertTrue(filter_access(filter_format_load($full), $this->admin_user), t('Admin user may use Full HTML.'));
  234. $this->assertFalse(filter_access(filter_format_load($full), $this->web_user), t('Web user may not use Full HTML.'));
  235. // Add an additional tag.
  236. $edit = array();
  237. $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <quote>';
  238. $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
  239. $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], t('Allowed HTML tag added.'));
  240. $result = db_query('SELECT * FROM {cache_filter}')->fetchObject();
  241. $this->assertFalse($result, t('Cache cleared.'));
  242. $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
  243. ':first' => 'filters[' . $first_filter . '][weight]',
  244. ':second' => 'filters[' . $second_filter . '][weight]',
  245. ));
  246. $this->assertTrue(!empty($elements), t('Order confirmed in admin interface.'));
  247. // Reorder filters.
  248. $edit = array();
  249. $edit['filters[' . $second_filter . '][weight]'] = 1;
  250. $edit['filters[' . $first_filter . '][weight]'] = 2;
  251. $this->drupalPost(NULL, $edit, t('Save configuration'));
  252. $this->assertFieldByName('filters[' . $second_filter . '][weight]', 1, t('Order saved successfully.'));
  253. $this->assertFieldByName('filters[' . $first_filter . '][weight]', 2, t('Order saved successfully.'));
  254. $elements = $this->xpath('//select[@name=:first]/following::select[@name=:second]', array(
  255. ':first' => 'filters[' . $second_filter . '][weight]',
  256. ':second' => 'filters[' . $first_filter . '][weight]',
  257. ));
  258. $this->assertTrue(!empty($elements), t('Reorder confirmed in admin interface.'));
  259. $result = db_query('SELECT * FROM {filter} WHERE format = :format ORDER BY weight ASC', array(':format' => $filtered));
  260. $filters = array();
  261. foreach ($result as $filter) {
  262. if ($filter->name == $second_filter || $filter->name == $first_filter) {
  263. $filters[] = $filter;
  264. }
  265. }
  266. $this->assertTrue(($filters[0]->name == $second_filter && $filters[1]->name == $first_filter), t('Order confirmed in database.'));
  267. // Add format.
  268. $edit = array();
  269. $edit['format'] = drupal_strtolower($this->randomName());
  270. $edit['name'] = $this->randomName();
  271. $edit['roles[2]'] = 1;
  272. $edit['filters[' . $second_filter . '][status]'] = TRUE;
  273. $edit['filters[' . $first_filter . '][status]'] = TRUE;
  274. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  275. $this->assertRaw(t('Added text format %format.', array('%format' => $edit['name'])), t('New filter created.'));
  276. drupal_static_reset('filter_formats');
  277. $format = filter_format_load($edit['format']);
  278. $this->assertNotNull($format, t('Format found in database.'));
  279. $this->assertFieldByName('roles[2]', '', t('Role found.'));
  280. $this->assertFieldByName('filters[' . $second_filter . '][status]', '', t('Line break filter found.'));
  281. $this->assertFieldByName('filters[' . $first_filter . '][status]', '', t('Url filter found.'));
  282. // Disable new filter.
  283. $this->drupalPost('admin/config/content/formats/' . $format->format . '/disable', array(), t('Disable'));
  284. $this->assertRaw(t('Disabled text format %format.', array('%format' => $edit['name'])), t('Format successfully disabled.'));
  285. // Allow authenticated users on full HTML.
  286. $format = filter_format_load($full);
  287. $edit = array();
  288. $edit['roles[1]'] = 0;
  289. $edit['roles[2]'] = 1;
  290. $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
  291. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), t('Full HTML format successfully updated.'));
  292. // Switch user.
  293. $this->drupalLogout();
  294. $this->drupalLogin($this->web_user);
  295. $this->drupalGet('node/add/page');
  296. $this->assertRaw('<option value="' . $full . '">Full HTML</option>', t('Full HTML filter accessible.'));
  297. // Use filtered HTML and see if it removes tags that are not allowed.
  298. $body = '<em>' . $this->randomName() . '</em>';
  299. $extra_text = 'text';
  300. $text = $body . '<random>' . $extra_text . '</random>';
  301. $edit = array();
  302. $langcode = LANGUAGE_NONE;
  303. $edit["title"] = $this->randomName();
  304. $edit["body[$langcode][0][value]"] = $text;
  305. $edit["body[$langcode][0][format]"] = $filtered;
  306. $this->drupalPost('node/add/page', $edit, t('Save'));
  307. $this->assertRaw(t('Basic page %title has been created.', array('%title' => $edit["title"])), t('Filtered node created.'));
  308. $node = $this->drupalGetNodeByTitle($edit["title"]);
  309. $this->assertTrue($node, t('Node found in database.'));
  310. $this->drupalGet('node/' . $node->nid);
  311. $this->assertRaw($body . $extra_text, t('Filter removed invalid tag.'));
  312. // Use plain text and see if it escapes all tags, whether allowed or not.
  313. $edit = array();
  314. $edit["body[$langcode][0][format]"] = $plain;
  315. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  316. $this->drupalGet('node/' . $node->nid);
  317. $this->assertText(check_plain($text), t('The "Plain text" text format escapes all HTML tags.'));
  318. // Switch user.
  319. $this->drupalLogout();
  320. $this->drupalLogin($this->admin_user);
  321. // Clean up.
  322. // Allowed tags.
  323. $edit = array();
  324. $edit['filters[filter_html][settings][allowed_html]'] = '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>';
  325. $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
  326. $this->assertFieldByName('filters[filter_html][settings][allowed_html]', $edit['filters[filter_html][settings][allowed_html]'], t('Changes reverted.'));
  327. // Full HTML.
  328. $edit = array();
  329. $edit['roles[2]'] = FALSE;
  330. $this->drupalPost('admin/config/content/formats/' . $full, $edit, t('Save configuration'));
  331. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $format->name)), t('Full HTML format successfully reverted.'));
  332. $this->assertFieldByName('roles[2]', $edit['roles[2]'], t('Changes reverted.'));
  333. // Filter order.
  334. $edit = array();
  335. $edit['filters[' . $second_filter . '][weight]'] = 2;
  336. $edit['filters[' . $first_filter . '][weight]'] = 1;
  337. $this->drupalPost('admin/config/content/formats/' . $filtered, $edit, t('Save configuration'));
  338. $this->assertFieldByName('filters[' . $second_filter . '][weight]', $edit['filters[' . $second_filter . '][weight]'], t('Changes reverted.'));
  339. $this->assertFieldByName('filters[' . $first_filter . '][weight]', $edit['filters[' . $first_filter . '][weight]'], t('Changes reverted.'));
  340. }
  341. /**
  342. * Tests the URL filter settings form is properly validated.
  343. */
  344. function testUrlFilterAdmin() {
  345. // The form does not save with an invalid filter URL length.
  346. $edit = array(
  347. 'filters[filter_url][settings][filter_url_length]' => $this->randomName(4),
  348. );
  349. $this->drupalPost('admin/config/content/formats/filtered_html', $edit, t('Save configuration'));
  350. $this->assertNoRaw(t('The text format %format has been updated.', array('%format' => 'Filtered HTML')));
  351. }
  352. }
  353. class FilterFormatAccessTestCase extends DrupalWebTestCase {
  354. protected $admin_user;
  355. protected $filter_admin_user;
  356. protected $web_user;
  357. protected $allowed_format;
  358. protected $disallowed_format;
  359. public static function getInfo() {
  360. return array(
  361. 'name' => 'Filter format access',
  362. 'description' => 'Tests access to text formats.',
  363. 'group' => 'Filter',
  364. );
  365. }
  366. function setUp() {
  367. parent::setUp();
  368. // Create a user who can administer text formats, but does not have
  369. // specific permission to use any of them.
  370. $this->filter_admin_user = $this->drupalCreateUser(array(
  371. 'administer filters',
  372. 'create page content',
  373. 'edit any page content',
  374. ));
  375. // Create two text formats.
  376. $this->drupalLogin($this->filter_admin_user);
  377. $formats = array();
  378. for ($i = 0; $i < 2; $i++) {
  379. $edit = array(
  380. 'format' => drupal_strtolower($this->randomName()),
  381. 'name' => $this->randomName(),
  382. );
  383. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  384. $this->resetFilterCaches();
  385. $formats[] = filter_format_load($edit['format']);
  386. }
  387. list($this->allowed_format, $this->disallowed_format) = $formats;
  388. $this->drupalLogout();
  389. // Create a regular user with access to one of the formats.
  390. $this->web_user = $this->drupalCreateUser(array(
  391. 'create page content',
  392. 'edit any page content',
  393. filter_permission_name($this->allowed_format),
  394. ));
  395. // Create an administrative user who has access to use both formats.
  396. $this->admin_user = $this->drupalCreateUser(array(
  397. 'administer filters',
  398. 'create page content',
  399. 'edit any page content',
  400. filter_permission_name($this->allowed_format),
  401. filter_permission_name($this->disallowed_format),
  402. ));
  403. }
  404. function testFormatPermissions() {
  405. // Make sure that a regular user only has access to the text format they
  406. // were granted access to, as well to the fallback format.
  407. $this->assertTrue(filter_access($this->allowed_format, $this->web_user), t('A regular user has access to a text format they were granted access to.'));
  408. $this->assertFalse(filter_access($this->disallowed_format, $this->web_user), t('A regular user does not have access to a text format they were not granted access to.'));
  409. $this->assertTrue(filter_access(filter_format_load(filter_fallback_format()), $this->web_user), t('A regular user has access to the fallback format.'));
  410. // Perform similar checks as above, but now against the entire list of
  411. // available formats for this user.
  412. $this->assertTrue(in_array($this->allowed_format->format, array_keys(filter_formats($this->web_user))), t('The allowed format appears in the list of available formats for a regular user.'));
  413. $this->assertFalse(in_array($this->disallowed_format->format, array_keys(filter_formats($this->web_user))), t('The disallowed format does not appear in the list of available formats for a regular user.'));
  414. $this->assertTrue(in_array(filter_fallback_format(), array_keys(filter_formats($this->web_user))), t('The fallback format appears in the list of available formats for a regular user.'));
  415. // Make sure that a regular user only has permission to use the format
  416. // they were granted access to.
  417. $this->assertTrue(user_access(filter_permission_name($this->allowed_format), $this->web_user), t('A regular user has permission to use the allowed text format.'));
  418. $this->assertFalse(user_access(filter_permission_name($this->disallowed_format), $this->web_user), t('A regular user does not have permission to use the disallowed text format.'));
  419. // Make sure that the allowed format appears on the node form and that
  420. // the disallowed format does not.
  421. $this->drupalLogin($this->web_user);
  422. $this->drupalGet('node/add/page');
  423. $langcode = LANGUAGE_NONE;
  424. $elements = $this->xpath('//select[@name=:name]/option', array(
  425. ':name' => "body[$langcode][0][format]",
  426. ':option' => $this->allowed_format->format,
  427. ));
  428. $options = array();
  429. foreach ($elements as $element) {
  430. $options[(string) $element['value']] = $element;
  431. }
  432. $this->assertTrue(isset($options[$this->allowed_format->format]), t('The allowed text format appears as an option when adding a new node.'));
  433. $this->assertFalse(isset($options[$this->disallowed_format->format]), t('The disallowed text format does not appear as an option when adding a new node.'));
  434. $this->assertTrue(isset($options[filter_fallback_format()]), t('The fallback format appears as an option when adding a new node.'));
  435. }
  436. function testFormatRoles() {
  437. // Get the role ID assigned to the regular user; it must be the maximum.
  438. $rid = max(array_keys($this->web_user->roles));
  439. // Check that this role appears in the list of roles that have access to an
  440. // allowed text format, but does not appear in the list of roles that have
  441. // access to a disallowed text format.
  442. $this->assertTrue(in_array($rid, array_keys(filter_get_roles_by_format($this->allowed_format))), t('A role which has access to a text format appears in the list of roles that have access to that format.'));
  443. $this->assertFalse(in_array($rid, array_keys(filter_get_roles_by_format($this->disallowed_format))), t('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.'));
  444. // Check that the correct text format appears in the list of formats
  445. // available to that role.
  446. $this->assertTrue(in_array($this->allowed_format->format, array_keys(filter_get_formats_by_role($rid))), t('A text format which a role has access to appears in the list of formats available to that role.'));
  447. $this->assertFalse(in_array($this->disallowed_format->format, array_keys(filter_get_formats_by_role($rid))), t('A text format which a role does not have access to does not appear in the list of formats available to that role.'));
  448. // Check that the fallback format is always allowed.
  449. $this->assertEqual(filter_get_roles_by_format(filter_format_load(filter_fallback_format())), user_roles(), t('All roles have access to the fallback format.'));
  450. $this->assertTrue(in_array(filter_fallback_format(), array_keys(filter_get_formats_by_role($rid))), t('The fallback format appears in the list of allowed formats for any role.'));
  451. }
  452. /**
  453. * Test editing a page using a disallowed text format.
  454. *
  455. * Verifies that regular users and administrators are able to edit a page,
  456. * but not allowed to change the fields which use an inaccessible text
  457. * format. Also verifies that fields which use a text format that does not
  458. * exist can be edited by administrators only, but that the administrator is
  459. * forced to choose a new format before saving the page.
  460. */
  461. function testFormatWidgetPermissions() {
  462. $langcode = LANGUAGE_NONE;
  463. $title_key = "title";
  464. $body_value_key = "body[$langcode][0][value]";
  465. $body_format_key = "body[$langcode][0][format]";
  466. // Create node to edit.
  467. $this->drupalLogin($this->admin_user);
  468. $edit = array();
  469. $edit['title'] = $this->randomName(8);
  470. $edit[$body_value_key] = $this->randomName(16);
  471. $edit[$body_format_key] = $this->disallowed_format->format;
  472. $this->drupalPost('node/add/page', $edit, t('Save'));
  473. $node = $this->drupalGetNodeByTitle($edit['title']);
  474. // Try to edit with a less privileged user.
  475. $this->drupalLogin($this->web_user);
  476. $this->drupalGet('node/' . $node->nid);
  477. $this->clickLink(t('Edit'));
  478. // Verify that body field is read-only and contains replacement value.
  479. $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.'), t('Text format access denied message found.'));
  480. // Verify that title can be changed, but preview displays original body.
  481. $new_edit = array();
  482. $new_edit['title'] = $this->randomName(8);
  483. $this->drupalPost(NULL, $new_edit, t('Preview'));
  484. $this->assertText($edit[$body_value_key], t('Old body found in preview.'));
  485. // Save and verify that only the title was changed.
  486. $this->drupalPost(NULL, $new_edit, t('Save'));
  487. $this->assertNoText($edit['title'], t('Old title not found.'));
  488. $this->assertText($new_edit['title'], t('New title found.'));
  489. $this->assertText($edit[$body_value_key], t('Old body found.'));
  490. // Check that even an administrator with "administer filters" permission
  491. // cannot edit the body field if they do not have specific permission to
  492. // use its stored format. (This must be disallowed so that the
  493. // administrator is never forced to switch the text format to something
  494. // else.)
  495. $this->drupalLogin($this->filter_admin_user);
  496. $this->drupalGet('node/' . $node->nid . '/edit');
  497. $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.'), t('Text format access denied message found.'));
  498. // Disable the text format used above.
  499. filter_format_disable($this->disallowed_format);
  500. $this->resetFilterCaches();
  501. // Log back in as the less privileged user and verify that the body field
  502. // is still disabled, since the less privileged user should not be able to
  503. // edit content that does not have an assigned format.
  504. $this->drupalLogin($this->web_user);
  505. $this->drupalGet('node/' . $node->nid . '/edit');
  506. $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.'), t('Text format access denied message found.'));
  507. // Log back in as the filter administrator and verify that the body field
  508. // can be edited.
  509. $this->drupalLogin($this->filter_admin_user);
  510. $this->drupalGet('node/' . $node->nid . '/edit');
  511. $this->assertNoFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", NULL, t('Text format access denied message not found.'));
  512. $this->assertFieldByXPath("//select[@name='$body_format_key']", NULL, t('Text format selector found.'));
  513. // Verify that trying to save the node without selecting a new text format
  514. // produces an error message, and does not result in the node being saved.
  515. $old_title = $new_edit['title'];
  516. $new_title = $this->randomName(8);
  517. $edit = array('title' => $new_title);
  518. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  519. $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), t('Error message is displayed.'));
  520. $this->drupalGet('node/' . $node->nid);
  521. $this->assertText($old_title, t('Old title found.'));
  522. $this->assertNoText($new_title, t('New title not found.'));
  523. // Now select a new text format and make sure the node can be saved.
  524. $edit[$body_format_key] = filter_fallback_format();
  525. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  526. $this->assertUrl('node/' . $node->nid);
  527. $this->assertText($new_title, t('New title found.'));
  528. $this->assertNoText($old_title, t('Old title not found.'));
  529. // Switch the text format to a new one, then disable that format and all
  530. // other formats on the site (leaving only the fallback format).
  531. $this->drupalLogin($this->admin_user);
  532. $edit = array($body_format_key => $this->allowed_format->format);
  533. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  534. $this->assertUrl('node/' . $node->nid);
  535. foreach (filter_formats() as $format) {
  536. if ($format->format != filter_fallback_format()) {
  537. filter_format_disable($format);
  538. }
  539. }
  540. // Since there is now only one available text format, the widget for
  541. // selecting a text format would normally not display when the content is
  542. // edited. However, we need to verify that the filter administrator still
  543. // is forced to make a conscious choice to reassign the text to a different
  544. // format.
  545. $this->drupalLogin($this->filter_admin_user);
  546. $old_title = $new_title;
  547. $new_title = $this->randomName(8);
  548. $edit = array('title' => $new_title);
  549. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  550. $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), t('Error message is displayed.'));
  551. $this->drupalGet('node/' . $node->nid);
  552. $this->assertText($old_title, t('Old title found.'));
  553. $this->assertNoText($new_title, t('New title not found.'));
  554. $edit[$body_format_key] = filter_fallback_format();
  555. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  556. $this->assertUrl('node/' . $node->nid);
  557. $this->assertText($new_title, t('New title found.'));
  558. $this->assertNoText($old_title, t('Old title not found.'));
  559. }
  560. /**
  561. * Rebuild text format and permission caches in the thread running the tests.
  562. */
  563. protected function resetFilterCaches() {
  564. filter_formats_reset();
  565. $this->checkPermissions(array(), TRUE);
  566. }
  567. }
  568. class FilterDefaultFormatTestCase extends DrupalWebTestCase {
  569. public static function getInfo() {
  570. return array(
  571. 'name' => 'Default text format functionality',
  572. 'description' => 'Test the default text formats for different users.',
  573. 'group' => 'Filter',
  574. );
  575. }
  576. function testDefaultTextFormats() {
  577. // Create two text formats, and two users. The first user has access to
  578. // both formats, but the second user only has access to the second one.
  579. $admin_user = $this->drupalCreateUser(array('administer filters'));
  580. $this->drupalLogin($admin_user);
  581. $formats = array();
  582. for ($i = 0; $i < 2; $i++) {
  583. $edit = array(
  584. 'format' => drupal_strtolower($this->randomName()),
  585. 'name' => $this->randomName(),
  586. );
  587. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  588. $this->resetFilterCaches();
  589. $formats[] = filter_format_load($edit['format']);
  590. }
  591. list($first_format, $second_format) = $formats;
  592. $first_user = $this->drupalCreateUser(array(filter_permission_name($first_format), filter_permission_name($second_format)));
  593. $second_user = $this->drupalCreateUser(array(filter_permission_name($second_format)));
  594. // Adjust the weights so that the first and second formats (in that order)
  595. // are the two lowest weighted formats available to any user.
  596. $minimum_weight = db_query("SELECT MIN(weight) FROM {filter_format}")->fetchField();
  597. $edit = array();
  598. $edit['formats[' . $first_format->format . '][weight]'] = $minimum_weight - 2;
  599. $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 1;
  600. $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
  601. $this->resetFilterCaches();
  602. // Check that each user's default format is the lowest weighted format that
  603. // the user has access to.
  604. $this->assertEqual(filter_default_format($first_user), $first_format->format, t("The first user's default format is the lowest weighted format that the user has access to."));
  605. $this->assertEqual(filter_default_format($second_user), $second_format->format, t("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."));
  606. // Reorder the two formats, and check that both users now have the same
  607. // default.
  608. $edit = array();
  609. $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 3;
  610. $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
  611. $this->resetFilterCaches();
  612. $this->assertEqual(filter_default_format($first_user), filter_default_format($second_user), t('After the formats are reordered, both users have the same default format.'));
  613. }
  614. /**
  615. * Rebuild text format and permission caches in the thread running the tests.
  616. */
  617. protected function resetFilterCaches() {
  618. filter_formats_reset();
  619. $this->checkPermissions(array(), TRUE);
  620. }
  621. }
  622. class FilterNoFormatTestCase extends DrupalWebTestCase {
  623. public static function getInfo() {
  624. return array(
  625. 'name' => 'Unassigned text format functionality',
  626. 'description' => 'Test the behavior of check_markup() when it is called without a text format.',
  627. 'group' => 'Filter',
  628. );
  629. }
  630. function testCheckMarkupNoFormat() {
  631. // Create some text. Include some HTML and line breaks, so we get a good
  632. // test of the filtering that is applied to it.
  633. $text = "<strong>" . $this->randomName(32) . "</strong>\n\n<div>" . $this->randomName(32) . "</div>";
  634. // Make sure that when this text is run through check_markup() with no text
  635. // format, it is filtered as though it is in the fallback format.
  636. $this->assertEqual(check_markup($text), check_markup($text, filter_fallback_format()), t('Text with no format is filtered the same as text in the fallback format.'));
  637. }
  638. }
  639. /**
  640. * Security tests for missing/vanished text formats or filters.
  641. */
  642. class FilterSecurityTestCase extends DrupalWebTestCase {
  643. public static function getInfo() {
  644. return array(
  645. 'name' => 'Security',
  646. 'description' => 'Test the behavior of check_markup() when a filter or text format vanishes.',
  647. 'group' => 'Filter',
  648. );
  649. }
  650. function setUp() {
  651. parent::setUp('php', 'filter_test');
  652. $this->admin_user = $this->drupalCreateUser(array('administer modules', 'administer filters', 'administer site configuration'));
  653. $this->drupalLogin($this->admin_user);
  654. }
  655. /**
  656. * Test that filtered content is emptied when an actively used filter module is disabled.
  657. */
  658. function testDisableFilterModule() {
  659. // Create a new node.
  660. $node = $this->drupalCreateNode(array('promote' => 1));
  661. $body_raw = $node->body[LANGUAGE_NONE][0]['value'];
  662. $format_id = $node->body[LANGUAGE_NONE][0]['format'];
  663. $this->drupalGet('node/' . $node->nid);
  664. $this->assertText($body_raw, t('Node body found.'));
  665. // Enable the filter_test_replace filter.
  666. $edit = array(
  667. 'filters[filter_test_replace][status]' => 1,
  668. );
  669. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  670. // Verify that filter_test_replace filter replaced the content.
  671. $this->drupalGet('node/' . $node->nid);
  672. $this->assertNoText($body_raw, t('Node body not found.'));
  673. $this->assertText('Filter: Testing filter', t('Testing filter output found.'));
  674. // Disable the text format entirely.
  675. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  676. // Verify that the content is empty, because the text format does not exist.
  677. $this->drupalGet('node/' . $node->nid);
  678. $this->assertNoText($body_raw, t('Node body not found.'));
  679. }
  680. }
  681. /**
  682. * Unit tests for core filters.
  683. */
  684. class FilterUnitTestCase extends DrupalUnitTestCase {
  685. public static function getInfo() {
  686. return array(
  687. 'name' => 'Filter module filters',
  688. 'description' => 'Tests Filter module filters individually.',
  689. 'group' => 'Filter',
  690. );
  691. }
  692. /**
  693. * Test the line break filter.
  694. */
  695. function testLineBreakFilter() {
  696. // Setup dummy filter object.
  697. $filter = new stdClass();
  698. $filter->callback = '_filter_autop';
  699. // Since the line break filter naturally needs plenty of newlines in test
  700. // strings and expectations, we're using "\n" instead of regular newlines
  701. // here.
  702. $tests = array(
  703. // Single line breaks should be changed to <br /> tags, while paragraphs
  704. // separated with double line breaks should be enclosed with <p></p> tags.
  705. "aaa\nbbb\n\nccc" => array(
  706. "<p>aaa<br />\nbbb</p>\n<p>ccc</p>" => TRUE,
  707. ),
  708. // Skip contents of certain block tags entirely.
  709. "<script>aaa\nbbb\n\nccc</script>
  710. <style>aaa\nbbb\n\nccc</style>
  711. <pre>aaa\nbbb\n\nccc</pre>
  712. <object>aaa\nbbb\n\nccc</object>
  713. <iframe>aaa\nbbb\n\nccc</iframe>
  714. " => array(
  715. "<script>aaa\nbbb\n\nccc</script>" => TRUE,
  716. "<style>aaa\nbbb\n\nccc</style>" => TRUE,
  717. "<pre>aaa\nbbb\n\nccc</pre>" => TRUE,
  718. "<object>aaa\nbbb\n\nccc</object>" => TRUE,
  719. "<iframe>aaa\nbbb\n\nccc</iframe>" => TRUE,
  720. ),
  721. // Skip comments entirely.
  722. "One. <!-- comment --> Two.\n<!--\nThree.\n-->\n" => array(
  723. '<!-- comment -->' => TRUE,
  724. "<!--\nThree.\n-->" => TRUE,
  725. ),
  726. // Resulting HTML should produce matching paragraph tags.
  727. '<p><div> </div></p>' => array(
  728. "<p>\n<div> </div>\n</p>" => TRUE,
  729. ),
  730. '<div><p> </p></div>' => array(
  731. "<div>\n</div>" => TRUE,
  732. ),
  733. '<blockquote><pre>aaa</pre></blockquote>' => array(
  734. "<blockquote><pre>aaa</pre></blockquote>" => TRUE,
  735. ),
  736. "<pre>aaa\nbbb\nccc</pre>\nddd\neee" => array(
  737. "<pre>aaa\nbbb\nccc</pre>" => TRUE,
  738. "<p>ddd<br />\neee</p>" => TRUE,
  739. ),
  740. // Comments remain unchanged and subsequent lines/paragraphs are
  741. // transformed normally.
  742. "aaa<!--comment-->\n\nbbb\n\nccc\n\nddd<!--comment\nwith linebreak-->\n\neee\n\nfff" => array(
  743. "<p>aaa</p>\n<!--comment--><p>\nbbb</p>\n<p>ccc</p>\n<p>ddd</p>" => TRUE,
  744. "<!--comment\nwith linebreak--><p>\neee</p>\n<p>fff</p>" => TRUE,
  745. ),
  746. // Check that a comment in a PRE will result that the text after
  747. // the comment, but still in PRE, is not transformed.
  748. "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>\nddd" => array(
  749. "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>" => TRUE,
  750. ),
  751. // Bug 810824, paragraphs were appearing around iframe tags.
  752. "<iframe>aaa</iframe>\n\n" => array(
  753. "<p><iframe>aaa</iframe></p>" => FALSE,
  754. ),
  755. );
  756. $this->assertFilteredString($filter, $tests);
  757. // Very long string hitting PCRE limits.
  758. $limit = max(ini_get('pcre.backtrack_limit'), ini_get('pcre.recursion_limit'));
  759. $source = $this->randomName($limit);
  760. $result = _filter_autop($source);
  761. $success = $this->assertEqual($result, '<p>' . $source . "</p>\n", t('Line break filter can process very long strings.'));
  762. if (!$success) {
  763. $this->verbose("\n" . $source . "\n<hr />\n" . $result);
  764. }
  765. }
  766. /**
  767. * Tests limiting allowed tags and XSS prevention.
  768. *
  769. * XSS tests assume that script is disallowed by default and src is allowed
  770. * by default, but on* and style attributes are disallowed.
  771. *
  772. * Script injection vectors mostly adopted from http://ha.ckers.org/xss.html.
  773. *
  774. * Relevant CVEs:
  775. * - CVE-2002-1806, ~CVE-2005-0682, ~CVE-2005-2106, CVE-2005-3973,
  776. * CVE-2006-1226 (= rev. 1.112?), CVE-2008-0273, CVE-2008-3740.
  777. */
  778. function testFilterXSS() {
  779. // Tag stripping, different ways to work around removal of HTML tags.
  780. $f = filter_xss('<script>alert(0)</script>');
  781. $this->assertNoNormalized($f, 'script', t('HTML tag stripping -- simple script without special characters.'));
  782. $f = filter_xss('<script src="http://www.example.com" />');
  783. $this->assertNoNormalized($f, 'script', t('HTML tag stripping -- empty script with source.'));
  784. $f = filter_xss('<ScRipt sRc=http://www.example.com/>');
  785. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- varying case.'));
  786. $f = filter_xss("<script\nsrc\n=\nhttp://www.example.com/\n>");
  787. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- multiline tag.'));
  788. $f = filter_xss('<script/a src=http://www.example.com/a.js></script>');
  789. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- non whitespace character after tag name.'));
  790. $f = filter_xss('<script/src=http://www.example.com/a.js></script>');
  791. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- no space between tag and attribute.'));
  792. // Null between < and tag name works at least with IE6.
  793. $f = filter_xss("<\0scr\0ipt>alert(0)</script>");
  794. $this->assertNoNormalized($f, 'ipt', t('HTML tag stripping evasion -- breaking HTML with nulls.'));
  795. $f = filter_xss("<scrscriptipt src=http://www.example.com/a.js>");
  796. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- filter just removing "script".'));
  797. $f = filter_xss('<<script>alert(0);//<</script>');
  798. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- double opening brackets.'));
  799. $f = filter_xss('<script src=http://www.example.com/a.js?<b>');
  800. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- no closing tag.'));
  801. // DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
  802. // work consistently.
  803. $f = filter_xss('<script>>');
  804. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- double closing tag.'));
  805. $f = filter_xss('<script src=//www.example.com/.a>');
  806. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- no scheme or ending slash.'));
  807. $f = filter_xss('<script src=http://www.example.com/.a');
  808. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- no closing bracket.'));
  809. $f = filter_xss('<script src=http://www.example.com/ <');
  810. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- opening instead of closing bracket.'));
  811. $f = filter_xss('<nosuchtag attribute="newScriptInjectionVector">');
  812. $this->assertNoNormalized($f, 'nosuchtag', t('HTML tag stripping evasion -- unknown tag.'));
  813. $f = filter_xss('<?xml:namespace ns="urn:schemas-microsoft-com:time">');
  814. $this->assertTrue(stripos($f, '<?xml') === FALSE, t('HTML tag stripping evasion -- starting with a question sign (processing instructions).'));
  815. $f = filter_xss('<t:set attributeName="innerHTML" to="&lt;script defer&gt;alert(0)&lt;/script&gt;">');
  816. $this->assertNoNormalized($f, 't:set', t('HTML tag stripping evasion -- colon in the tag name (namespaces\' tricks).'));
  817. $f = filter_xss('<img """><script>alert(0)</script>', array('img'));
  818. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- a malformed image tag.'));
  819. $f = filter_xss('<blockquote><script>alert(0)</script></blockquote>', array('blockquote'));
  820. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- script in a blockqoute.'));
  821. $f = filter_xss("<!--[if true]><script>alert(0)</script><![endif]-->");
  822. $this->assertNoNormalized($f, 'script', t('HTML tag stripping evasion -- script within a comment.'));
  823. // Dangerous attributes removal.
  824. $f = filter_xss('<p onmouseover="http://www.example.com/">', array('p'));
  825. $this->assertNoNormalized($f, 'onmouseover', t('HTML filter attributes removal -- events, no evasion.'));
  826. $f = filter_xss('<li style="list-style-image: url(javascript:alert(0))">', array('li'));
  827. $this->assertNoNormalized($f, 'style', t('HTML filter attributes removal -- style, no evasion.'));
  828. $f = filter_xss('<img onerror =alert(0)>', array('img'));
  829. $this->assertNoNormalized($f, 'onerror', t('HTML filter attributes removal evasion -- spaces before equals sign.'));
  830. $f = filter_xss('<img onabort!#$%&()*~+-_.,:;?@[/|\]^`=alert(0)>', array('img'));
  831. $this->assertNoNormalized($f, 'onabort', t('HTML filter attributes removal evasion -- non alphanumeric characters before equals sign.'));
  832. $f = filter_xss('<img oNmediAError=alert(0)>', array('img'));
  833. $this->assertNoNormalized($f, 'onmediaerror', t('HTML filter attributes removal evasion -- varying case.'));
  834. // Works at least with IE6.
  835. $f = filter_xss("<img o\0nfocus\0=alert(0)>", array('img'));
  836. $this->assertNoNormalized($f, 'focus', t('HTML filter attributes removal evasion -- breaking with nulls.'));
  837. // Only whitelisted scheme names allowed in attributes.
  838. $f = filter_xss('<img src="javascript:alert(0)">', array('img'));
  839. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing -- no evasion.'));
  840. $f = filter_xss('<img src=javascript:alert(0)>', array('img'));
  841. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- no quotes.'));
  842. // A bit like CVE-2006-0070.
  843. $f = filter_xss('<img src="javascript:confirm(0)">', array('img'));
  844. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- no alert ;)'));
  845. $f = filter_xss('<img src=`javascript:alert(0)`>', array('img'));
  846. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- grave accents.'));
  847. $f = filter_xss('<img dynsrc="javascript:alert(0)">', array('img'));
  848. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing -- rare attribute.'));
  849. $f = filter_xss('<table background="javascript:alert(0)">', array('table'));
  850. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing -- another tag.'));
  851. $f = filter_xss('<base href="javascript:alert(0);//">', array('base'));
  852. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing -- one more attribute and tag.'));
  853. $f = filter_xss('<img src="jaVaSCriPt:alert(0)">', array('img'));
  854. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- varying case.'));
  855. $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'));
  856. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- UTF-8 decimal encoding.'));
  857. $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'));
  858. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- long UTF-8 encoding.'));
  859. $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'));
  860. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- UTF-8 hex encoding.'));
  861. $f = filter_xss("<img src=\"jav\tascript:alert(0)\">", array('img'));
  862. $this->assertNoNormalized($f, 'script', t('HTML scheme clearing evasion -- an embedded tab.'));
  863. $f = filter_xss('<img src="jav&#x09;ascript:alert(0)">', array('img'));
  864. $this->assertNoNormalized($f, 'script', t('HTML scheme clearing evasion -- an encoded, embedded tab.'));
  865. $f = filter_xss('<img src="jav&#x000000A;ascript:alert(0)">', array('img'));
  866. $this->assertNoNormalized($f, 'script', t('HTML scheme clearing evasion -- an encoded, embedded newline.'));
  867. // With &#xD; this test would fail, but the entity gets turned into
  868. // &amp;#xD;, so it's OK.
  869. $f = filter_xss('<img src="jav&#x0D;ascript:alert(0)">', array('img'));
  870. $this->assertNoNormalized($f, 'script', t('HTML scheme clearing evasion -- an encoded, embedded carriage return.'));
  871. $f = filter_xss("<img src=\"\n\n\nj\na\nva\ns\ncript:alert(0)\">", array('img'));
  872. $this->assertNoNormalized($f, 'cript', t('HTML scheme clearing evasion -- broken into many lines.'));
  873. $f = filter_xss("<img src=\"jav\0a\0\0cript:alert(0)\">", array('img'));
  874. $this->assertNoNormalized($f, 'cript', t('HTML scheme clearing evasion -- embedded nulls.'));
  875. $f = filter_xss('<img src=" &#14; javascript:alert(0)">', array('img'));
  876. $this->assertNoNormalized($f, 'javascript', t('HTML scheme clearing evasion -- spaces and metacharacters before scheme.'));
  877. $f = filter_xss('<img src="vbscript:msgbox(0)">', array('img'));
  878. $this->assertNoNormalized($f, 'vbscript', t('HTML scheme clearing evasion -- another scheme.'));
  879. $f = filter_xss('<img src="nosuchscheme:notice(0)">', array('img'));
  880. $this->assertNoNormalized($f, 'nosuchscheme', t('HTML scheme clearing evasion -- unknown scheme.'));
  881. // Netscape 4.x javascript entities.
  882. $f = filter_xss('<br size="&{alert(0)}">', array('br'));
  883. $this->assertNoNormalized($f, 'alert', t('Netscape 4.x javascript entities.'));
  884. // DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
  885. // Internet Explorer 6.
  886. $f = filter_xss("<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>", array('p'));
  887. $this->assertNoNormalized($f, 'style', t('HTML filter -- invalid UTF-8.'));
  888. $f = filter_xss("\xc0aaa");
  889. $this->assertEqual($f, '', t('HTML filter -- overlong UTF-8 sequences.'));
  890. $f = filter_xss("Who&#039;s Online");
  891. $this->assertNormalized($f, "who's online", t('HTML filter -- html entity number'));
  892. $f = filter_xss("Who&amp;#039;s Online");
  893. $this->assertNormalized($f, "who&#039;s online", t('HTML filter -- encoded html entity number'));
  894. $f = filter_xss("Who&amp;amp;#039; Online");
  895. $this->assertNormalized($f, "who&amp;#039; online", t('HTML filter -- double encoded html entity number'));
  896. }
  897. /**
  898. * Test filter settings, defaults, access restrictions and similar.
  899. *
  900. * @todo This is for functions like filter_filter and check_markup, whose
  901. * functionality is not completely focused on filtering. Some ideas:
  902. * restricting formats according to user permissions, proper cache
  903. * handling, defaults -- allowed tags/attributes/protocols.
  904. *
  905. * @todo It is possible to add script, iframe etc. to allowed tags, but this
  906. * makes HTML filter completely ineffective.
  907. *
  908. * @todo Class, id, name and xmlns should be added to disallowed attributes,
  909. * or better a whitelist approach should be used for that too.
  910. */
  911. function testHtmlFilter() {
  912. // Setup dummy filter object.
  913. $filter = new stdClass();
  914. $filter->settings = array(
  915. 'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>',
  916. 'filter_html_help' => 1,
  917. 'filter_html_nofollow' => 0,
  918. );
  919. // HTML filter is not able to secure some tags, these should never be
  920. // allowed.
  921. $f = _filter_html('<script />', $filter);
  922. $this->assertNoNormalized($f, 'script', t('HTML filter should always remove script tags.'));
  923. $f = _filter_html('<iframe />', $filter);
  924. $this->assertNoNormalized($f, 'iframe', t('HTML filter should always remove iframe tags.'));
  925. $f = _filter_html('<object />', $filter);
  926. $this->assertNoNormalized($f, 'object', t('HTML filter should always remove object tags.'));
  927. $f = _filter_html('<style />', $filter);
  928. $this->assertNoNormalized($f, 'style', t('HTML filter should always remove style tags.'));
  929. // Some tags make CSRF attacks easier, let the user take the risk herself.
  930. $f = _filter_html('<img />', $filter);
  931. $this->assertNoNormalized($f, 'img', t('HTML filter should remove img tags on default.'));
  932. $f = _filter_html('<input />', $filter);
  933. $this->assertNoNormalized($f, 'img', t('HTML filter should remove input tags on default.'));
  934. // Filtering content of some attributes is infeasible, these shouldn't be
  935. // allowed too.
  936. $f = _filter_html('<p style="display: none;" />', $filter);
  937. $this->assertNoNormalized($f, 'style', t('HTML filter should remove style attribute on default.'));
  938. $f = _filter_html('<p onerror="alert(0);" />', $filter);
  939. $this->assertNoNormalized($f, 'onerror', t('HTML filter should remove on* attributes on default.'));
  940. $f = _filter_html('<code onerror>&nbsp;</code>', $filter);
  941. $this->assertNoNormalized($f, 'onerror', t('HTML filter should remove empty on* attributes on default.'));
  942. }
  943. /**
  944. * Test the spam deterrent.
  945. */
  946. function testNoFollowFilter() {
  947. // Setup dummy filter object.
  948. $filter = new stdClass();
  949. $filter->settings = array(
  950. 'allowed_html' => '<a>',
  951. 'filter_html_help' => 1,
  952. 'filter_html_nofollow' => 1,
  953. );
  954. // Test if the rel="nofollow" attribute is added, even if we try to prevent
  955. // it.
  956. $f = _filter_html('<a href="http://www.example.com/">text</a>', $filter);
  957. $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent -- no evasion.'));
  958. $f = _filter_html('<A href="http://www.example.com/">text</a>', $filter);
  959. $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- capital A.'));
  960. $f = _filter_html("<a/href=\"http://www.example.com/\">text</a>", $filter);
  961. $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- non whitespace character after tag name.'));
  962. $f = _filter_html("<\0a\0 href=\"http://www.example.com/\">text</a>", $filter);
  963. $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- some nulls.'));
  964. $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', $filter);
  965. $this->assertNoNormalized($f, 'rel="follow"', t('Spam deterrent evasion -- with rel set - rel="follow" removed.'));
  966. $this->assertNormalized($f, 'rel="nofollow"', t('Spam deterrent evasion -- with rel set - rel="nofollow" added.'));
  967. }
  968. /**
  969. * Test the loose, admin HTML filter.
  970. */
  971. function testFilterXSSAdmin() {
  972. // DRUPAL-SA-2008-044
  973. $f = filter_xss_admin('<object />');
  974. $this->assertNoNormalized($f, 'object', t('Admin HTML filter -- should not allow object tag.'));
  975. $f = filter_xss_admin('<script />');
  976. $this->assertNoNormalized($f, 'script', t('Admin HTML filter -- should not allow script tag.'));
  977. $f = filter_xss_admin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
  978. $this->assertEqual($f, '', t('Admin HTML filter -- should never allow some tags.'));
  979. }
  980. /**
  981. * Tests the HTML escaping filter.
  982. *
  983. * check_plain() is not tested here.
  984. */
  985. function testHtmlEscapeFilter() {
  986. // Setup dummy filter object.
  987. $filter = new stdClass();
  988. $filter->callback = '_filter_html_escape';
  989. $tests = array(
  990. " One. <!-- \"comment\" --> Two'.\n<p>Three.</p>\n " => array(
  991. "One. &lt;!-- &quot;comment&quot; --&gt; Two&#039;.\n&lt;p&gt;Three.&lt;/p&gt;" => TRUE,
  992. ' One.' => FALSE,
  993. "</p>\n " => FALSE,
  994. ),
  995. );
  996. $this->assertFilteredString($filter, $tests);
  997. }
  998. /**
  999. * Tests the URL filter.
  1000. */
  1001. function testUrlFilter() {
  1002. // Setup dummy filter object.
  1003. $filter = new stdClass();
  1004. $filter->callback = '_filter_url';
  1005. $filter->settings = array(
  1006. 'filter_url_length' => 496,
  1007. );
  1008. // @todo Possible categories:
  1009. // - absolute, mail, partial
  1010. // - characters/encoding, surrounding markup, security
  1011. // Filter selection/pattern matching.
  1012. $tests = array(
  1013. // HTTP URLs.
  1014. '
  1015. http://example.com or www.example.com
  1016. ' => array(
  1017. '<a href="http://example.com">http://example.com</a>' => TRUE,
  1018. '<a href="http://www.example.com">www.example.com</a>' => TRUE,
  1019. ),
  1020. // MAILTO URLs.
  1021. '
  1022. person@example.com or mailto:person2@example.com
  1023. ' => array(
  1024. '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
  1025. '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
  1026. ),
  1027. // URI parts and special characters.
  1028. '
  1029. http://trailingslash.com/ or www.trailingslash.com/
  1030. http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
  1031. http://twitter.com/#!/example/status/22376963142324226
  1032. ftp://user:pass@ftp.example.com/~home/dir1
  1033. sftp://user@nonstandardport:222/dir
  1034. ssh://192.168.0.100/srv/git/drupal.git
  1035. ' => array(
  1036. '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
  1037. '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
  1038. '<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,
  1039. '<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,
  1040. '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
  1041. '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
  1042. '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
  1043. '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
  1044. ),
  1045. // Encoding.
  1046. '
  1047. http://ampersand.com/?a=1&b=2
  1048. http://encoded.com/?a=1&amp;b=2
  1049. ' => array(
  1050. '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
  1051. '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
  1052. ),
  1053. // Domain name length.
  1054. '
  1055. www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
  1056. me@me.tv
  1057. ' => array(
  1058. '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
  1059. '<a href="http://www.example.example">www.example.example</a>' => TRUE,
  1060. 'http://www.toolong' => FALSE,
  1061. '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
  1062. ),
  1063. // Absolute URL protocols.
  1064. // The list to test is found in the beginning of _filter_url() at
  1065. // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
  1066. '
  1067. https://example.com,
  1068. ftp://ftp.example.com,
  1069. news://example.net,
  1070. telnet://example,
  1071. irc://example.host,
  1072. ssh://odd.geek,
  1073. sftp://secure.host?,
  1074. webcal://calendar,
  1075. rtsp://127.0.0.1,
  1076. not foo://disallowed.com.
  1077. ' => array(
  1078. 'href="https://example.com"' => TRUE,
  1079. 'href="ftp://ftp.example.com"' => TRUE,
  1080. 'href="news://example.net"' => TRUE,
  1081. 'href="telnet://example"' => TRUE,
  1082. 'href="irc://example.host"' => TRUE,
  1083. 'href="ssh://odd.geek"' => TRUE,
  1084. 'href="sftp://secure.host"' => TRUE,
  1085. 'href="webcal://calendar"' => TRUE,
  1086. 'href="rtsp://127.0.0.1"' => TRUE,
  1087. 'href="foo://disallowed.com"' => FALSE,
  1088. 'not foo://disallowed.com.' => TRUE,
  1089. ),
  1090. );
  1091. $this->assertFilteredString($filter, $tests);
  1092. // Surrounding text/punctuation.
  1093. $tests = array(
  1094. '
  1095. Partial URL with trailing period www.partial.com.
  1096. E-mail with trailing comma person@example.com,
  1097. Absolute URL with trailing question http://www.absolute.com?
  1098. Query string with trailing exclamation www.query.com/index.php?a=!
  1099. Partial URL with 3 trailing www.partial.periods...
  1100. E-mail with 3 trailing exclamations@example.com!!!
  1101. Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
  1102. ' => array(
  1103. 'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
  1104. 'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
  1105. 'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
  1106. 'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
  1107. 'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
  1108. 'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
  1109. 'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
  1110. ),
  1111. '
  1112. (www.parenthesis.com/dir?a=1&b=2#a)
  1113. ' => array(
  1114. '(<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,
  1115. ),
  1116. );
  1117. $this->assertFilteredString($filter, $tests);
  1118. // Surrounding markup.
  1119. $tests = array(
  1120. '
  1121. <p xmlns="www.namespace.com" />
  1122. <p xmlns="http://namespace.com">
  1123. An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
  1124. </p>
  1125. ' => array(
  1126. '<p xmlns="www.namespace.com" />' => TRUE,
  1127. '<p xmlns="http://namespace.com">' => TRUE,
  1128. 'href="http://www.namespace.com"' => FALSE,
  1129. 'href="http://namespace.com"' => FALSE,
  1130. 'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
  1131. ),
  1132. '
  1133. Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
  1134. but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
  1135. ' => array(
  1136. '<a href="foo">www.relative.com</a>' => TRUE,
  1137. 'href="http://www.relative.com"' => FALSE,
  1138. '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
  1139. '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
  1140. '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
  1141. ),
  1142. '
  1143. Test <code>using www.example.com the code tag</code>.
  1144. ' => array(
  1145. 'href' => FALSE,
  1146. 'http' => FALSE,
  1147. ),
  1148. '
  1149. Intro.
  1150. <blockquote>
  1151. 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>.
  1152. </blockquote>
  1153. Outro.
  1154. ' => array(
  1155. 'href="http://www.example.com"' => TRUE,
  1156. 'href="mailto:person@example.com"' => TRUE,
  1157. 'href="http://origin.example.com"' => TRUE,
  1158. 'http://www.usage.example.com' => FALSE,
  1159. 'http://www.example.info' => FALSE,
  1160. 'Intro.' => TRUE,
  1161. 'Outro.' => TRUE,
  1162. ),
  1163. '
  1164. 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>
  1165. ' => array(
  1166. 'href="http://www.example.com"' => TRUE,
  1167. 'href="http://www.example.pooh"' => TRUE,
  1168. ),
  1169. '
  1170. <p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
  1171. It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
  1172. 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.
  1173. ' => array(
  1174. 'href="http://www.example17.com"' => TRUE,
  1175. 'href="http://www.example18.com"' => TRUE,
  1176. 'href="http://www.example19.com"' => TRUE,
  1177. 'href="http://www.example20.com"' => TRUE,
  1178. 'href="http://www.example21.com"' => TRUE,
  1179. 'href="mailto:person@example22.com"' => TRUE,
  1180. 'href="http://www.example23.com"' => TRUE,
  1181. 'href="http://www.example24.com"' => TRUE,
  1182. 'href="http://www.example25.com"' => TRUE,
  1183. 'href="http://www.example26.com"' => TRUE,
  1184. 'href="mailto:person@example27.com"' => TRUE,
  1185. 'href="http://www.example28.com"' => TRUE,
  1186. ),
  1187. '
  1188. <script>
  1189. <!--
  1190. // @see www.example.com
  1191. var exampleurl = "http://example.net";
  1192. -->
  1193. <!--//--><![CDATA[//><!--
  1194. // @see www.example.com
  1195. var exampleurl = "http://example.net";
  1196. //--><!]]>
  1197. </script>
  1198. ' => array(
  1199. 'href="http://www.example.com"' => FALSE,
  1200. 'href="http://example.net"' => FALSE,
  1201. ),
  1202. '
  1203. <style>body {
  1204. background: url(http://example.com/pixel.gif);
  1205. }</style>
  1206. ' => array(
  1207. 'href' => FALSE,
  1208. ),
  1209. '
  1210. <!-- Skip any URLs like www.example.com in comments -->
  1211. ' => array(
  1212. 'href' => FALSE,
  1213. ),
  1214. '
  1215. <!-- Skip any URLs like
  1216. www.example.com with a newline in comments -->
  1217. ' => array(
  1218. 'href' => FALSE,
  1219. ),
  1220. '
  1221. <!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
  1222. ' => array(
  1223. 'href' => FALSE,
  1224. ),
  1225. '
  1226. <dl>
  1227. <dt>www.example.com</dt>
  1228. <dd>http://example.com</dd>
  1229. <dd>person@example.com</dd>
  1230. <dt>Check www.example.net</dt>
  1231. <dd>Some text around http://www.example.info by person@example.info?</dd>
  1232. </dl>
  1233. ' => array(
  1234. 'href="http://www.example.com"' => TRUE,
  1235. 'href="http://example.com"' => TRUE,
  1236. 'href="mailto:person@example.com"' => TRUE,
  1237. 'href="http://www.example.net"' => TRUE,
  1238. 'href="http://www.example.info"' => TRUE,
  1239. 'href="mailto:person@example.info"' => TRUE,
  1240. ),
  1241. '
  1242. <div>www.div.com</div>
  1243. <ul>
  1244. <li>http://listitem.com</li>
  1245. <li class="odd">www.class.listitem.com</li>
  1246. </ul>
  1247. ' => array(
  1248. '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
  1249. '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
  1250. '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
  1251. ),
  1252. );
  1253. $this->assertFilteredString($filter, $tests);
  1254. // URL trimming.
  1255. $filter->settings['filter_url_length'] = 20;
  1256. $tests = array(
  1257. 'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
  1258. '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
  1259. ),
  1260. );
  1261. $this->assertFilteredString($filter, $tests);
  1262. }
  1263. /**
  1264. * Asserts multiple filter output expectations for multiple input strings.
  1265. *
  1266. * @param $filter
  1267. * A input filter object.
  1268. * @param $tests
  1269. * An associative array, whereas each key is an arbitrary input string and
  1270. * each value is again an associative array whose keys are filter output
  1271. * strings and whose values are Booleans indicating whether the output is
  1272. * expected or not.
  1273. *
  1274. * For example:
  1275. * @code
  1276. * $tests = array(
  1277. * 'Input string' => array(
  1278. * '<p>Input string</p>' => TRUE,
  1279. * 'Input string<br' => FALSE,
  1280. * ),
  1281. * );
  1282. * @endcode
  1283. */
  1284. function assertFilteredString($filter, $tests) {
  1285. foreach ($tests as $source => $tasks) {
  1286. $function = $filter->callback;
  1287. $result = $function($source, $filter);
  1288. foreach ($tasks as $value => $is_expected) {
  1289. // Not using assertIdentical, since combination with strpos() is hard to grok.
  1290. if ($is_expected) {
  1291. $success = $this->assertTrue(strpos($result, $value) !== FALSE, t('@source: @value found.', array(
  1292. '@source' => var_export($source, TRUE),
  1293. '@value' => var_export($value, TRUE),
  1294. )));
  1295. }
  1296. else {
  1297. $success = $this->assertTrue(strpos($result, $value) === FALSE, t('@source: @value not found.', array(
  1298. '@source' => var_export($source, TRUE),
  1299. '@value' => var_export($value, TRUE),
  1300. )));
  1301. }
  1302. if (!$success) {
  1303. $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
  1304. . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
  1305. . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
  1306. . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
  1307. );
  1308. }
  1309. }
  1310. }
  1311. }
  1312. /**
  1313. * Tests URL filter on longer content.
  1314. *
  1315. * Filters based on regular expressions should also be tested with a more
  1316. * complex content than just isolated test lines.
  1317. * The most common errors are:
  1318. * - accidental '*' (greedy) match instead of '*?' (minimal) match.
  1319. * - only matching first occurrence instead of all.
  1320. * - newlines not matching '.*'.
  1321. *
  1322. * This test covers:
  1323. * - Document with multiple newlines and paragraphs (two newlines).
  1324. * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
  1325. * comments.
  1326. * - Empty HTML tags (BR, IMG).
  1327. * - Mix of absolute and partial URLs, and e-mail addresses in one content.
  1328. */
  1329. function testUrlFilterContent() {
  1330. // Setup dummy filter object.
  1331. $filter = new stdClass();
  1332. $filter->settings = array(
  1333. 'filter_url_length' => 496,
  1334. );
  1335. $path = drupal_get_path('module', 'filter') . '/tests';
  1336. $input = file_get_contents($path . '/filter.url-input.txt');
  1337. $expected = file_get_contents($path . '/filter.url-output.txt');
  1338. $result = _filter_url($input, $filter);
  1339. $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
  1340. }
  1341. /**
  1342. * Test the HTML corrector filter.
  1343. *
  1344. * @todo This test could really use some validity checking function.
  1345. */
  1346. function testHtmlCorrectorFilter() {
  1347. // Tag closing.
  1348. $f = _filter_htmlcorrector('<p>text');
  1349. $this->assertEqual($f, '<p>text</p>', t('HTML corrector -- tag closing at the end of input.'));
  1350. $f = _filter_htmlcorrector('<p>text<p><p>text');
  1351. $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', t('HTML corrector -- tag closing.'));
  1352. $f = _filter_htmlcorrector("<ul><li>e1<li>e2");
  1353. $this->assertEqual($f, "<ul><li>e1</li><li>e2</li></ul>", t('HTML corrector -- unclosed list tags.'));
  1354. $f = _filter_htmlcorrector('<div id="d">content');
  1355. $this->assertEqual($f, '<div id="d">content</div>', t('HTML corrector -- unclosed tag with attribute.'));
  1356. // XHTML slash for empty elements.
  1357. $f = _filter_htmlcorrector('<hr><br>');
  1358. $this->assertEqual($f, '<hr /><br />', t('HTML corrector -- XHTML closing slash.'));
  1359. $f = _filter_htmlcorrector('<P>test</P>');
  1360. $this->assertEqual($f, '<p>test</p>', t('HTML corrector -- Convert uppercased tags to proper lowercased ones.'));
  1361. $f = _filter_htmlcorrector('<P>test</p>');
  1362. $this->assertEqual($f, '<p>test</p>', t('HTML corrector -- Convert uppercased tags to proper lowercased ones.'));
  1363. $f = _filter_htmlcorrector('test<hr />');
  1364. $this->assertEqual($f, 'test<hr />', t('HTML corrector -- Let proper XHTML pass through.'));
  1365. $f = _filter_htmlcorrector('test<hr/>');
  1366. $this->assertEqual($f, 'test<hr />', t('HTML corrector -- Let proper XHTML pass through, but ensure there is a single space before the closing slash.'));
  1367. $f = _filter_htmlcorrector('test<hr />');
  1368. $this->assertEqual($f, 'test<hr />', t('HTML corrector -- Let proper XHTML pass through, but ensure there are not too many spaces before the closing slash.'));
  1369. $f = _filter_htmlcorrector('<span class="test" />');
  1370. $this->assertEqual($f, '<span class="test"></span>', t('HTML corrector -- Convert XHTML that is properly formed but that would not be compatible with typical HTML user agents.'));
  1371. $f = _filter_htmlcorrector('test1<br class="test">test2');
  1372. $this->assertEqual($f, 'test1<br class="test" />test2', t('HTML corrector -- Automatically close single tags.'));
  1373. $f = _filter_htmlcorrector('line1<hr>line2');
  1374. $this->assertEqual($f, 'line1<hr />line2', t('HTML corrector -- Automatically close single tags.'));
  1375. $f = _filter_htmlcorrector('line1<HR>line2');
  1376. $this->assertEqual($f, 'line1<hr />line2', t('HTML corrector -- Automatically close single tags.'));
  1377. $f = _filter_htmlcorrector('<img src="http://example.com/test.jpg">test</img>');
  1378. $this->assertEqual($f, '<img src="http://example.com/test.jpg" />test', t('HTML corrector -- Automatically close single tags.'));
  1379. $f = _filter_htmlcorrector('<br></br>');
  1380. $this->assertEqual($f, '<br />', t("HTML corrector -- Transform empty tags to a single closed tag if the tag's content model is EMPTY."));
  1381. $f = _filter_htmlcorrector('<div></div>');
  1382. $this->assertEqual($f, '<div></div>', t("HTML corrector -- Do not transform empty tags to a single closed tag if the tag's content model is not EMPTY."));
  1383. $f = _filter_htmlcorrector('<p>line1<br/><hr/>line2</p>');
  1384. $this->assertEqual($f, '<p>line1<br /></p><hr />line2', t('HTML corrector -- Move non-inline elements outside of inline containers.'));
  1385. $f = _filter_htmlcorrector('<p>line1<div>line2</div></p>');
  1386. $this->assertEqual($f, '<p>line1</p><div>line2</div>', t('HTML corrector -- Move non-inline elements outside of inline containers.'));
  1387. $f = _filter_htmlcorrector('<p>test<p>test</p>\n');
  1388. $this->assertEqual($f, '<p>test</p><p>test</p>\n', t('HTML corrector -- Auto-close improperly nested tags.'));
  1389. $f = _filter_htmlcorrector('<p>Line1<br><STRONG>bold stuff</b>');
  1390. $this->assertEqual($f, '<p>Line1<br /><strong>bold stuff</strong></p>', t('HTML corrector -- Properly close unclosed tags, and remove useless closing tags.'));
  1391. $f = _filter_htmlcorrector('test <!-- this is a comment -->');
  1392. $this->assertEqual($f, 'test <!-- this is a comment -->', t('HTML corrector -- Do not touch HTML comments.'));
  1393. $f = _filter_htmlcorrector('test <!--this is a comment-->');
  1394. $this->assertEqual($f, 'test <!--this is a comment-->', t('HTML corrector -- Do not touch HTML comments.'));
  1395. $f = _filter_htmlcorrector('test <!-- comment <p>another
  1396. <strong>multiple</strong> line
  1397. comment</p> -->');
  1398. $this->assertEqual($f, 'test <!-- comment <p>another
  1399. <strong>multiple</strong> line
  1400. comment</p> -->', t('HTML corrector -- Do not touch HTML comments.'));
  1401. $f = _filter_htmlcorrector('test <!-- comment <p>another comment</p> -->');
  1402. $this->assertEqual($f, 'test <!-- comment <p>another comment</p> -->', t('HTML corrector -- Do not touch HTML comments.'));
  1403. $f = _filter_htmlcorrector('test <!--break-->');
  1404. $this->assertEqual($f, 'test <!--break-->', t('HTML corrector -- Do not touch HTML comments.'));
  1405. $f = _filter_htmlcorrector('<p>test\n</p>\n');
  1406. $this->assertEqual($f, '<p>test\n</p>\n', t('HTML corrector -- New-lines are accepted and kept as-is.'));
  1407. $f = _filter_htmlcorrector('<p>دروبال');
  1408. $this->assertEqual($f, '<p>دروبال</p>', t('HTML corrector -- Encoding is correctly kept.'));
  1409. $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
  1410. $this->assertEqual($f, '<script type="text/javascript">
  1411. <!--//--><![CDATA[// ><!--
  1412. alert("test")
  1413. //--><!]]>
  1414. </script>', t('HTML corrector -- CDATA added to script element'));
  1415. $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
  1416. $this->assertEqual($f, '<p><script type="text/javascript">
  1417. <!--//--><![CDATA[// ><!--
  1418. alert("test")
  1419. //--><!]]>
  1420. </script></p>', t('HTML corrector -- CDATA added to a nested script element'));
  1421. $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
  1422. $this->assertEqual($f, '<p><style>
  1423. <!--/*--><![CDATA[/* ><!--*/
  1424. /* Styling */ body {color:red}
  1425. /*--><!]]>*/
  1426. </style></p>', t('HTML corrector -- CDATA added to a style element.'));
  1427. $filtered_data = _filter_htmlcorrector('<p><style>
  1428. /*<![CDATA[*/
  1429. /* Styling */
  1430. body {color:red}
  1431. /*]]>*/
  1432. </style></p>');
  1433. $this->assertEqual($filtered_data, '<p><style>
  1434. <!--/*--><![CDATA[/* ><!--*/
  1435. /*<![CDATA[*/
  1436. /* Styling */
  1437. body {color:red}
  1438. /*]]]]><![CDATA[>*/
  1439. /*--><!]]>*/
  1440. </style></p>',
  1441. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
  1442. );
  1443. $filtered_data = _filter_htmlcorrector('<p><style>
  1444. <!--/*--><![CDATA[/* ><!--*/
  1445. /* Styling */
  1446. body {color:red}
  1447. /*--><!]]>*/
  1448. </style></p>');
  1449. $this->assertEqual($filtered_data, '<p><style>
  1450. <!--/*--><![CDATA[/* ><!--*/
  1451. <!--/*--><![CDATA[/* ><!--*/
  1452. /* Styling */
  1453. body {color:red}
  1454. /*--><!]]]]><![CDATA[>*/
  1455. /*--><!]]>*/
  1456. </style></p>',
  1457. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
  1458. );
  1459. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1460. <!--//--><![CDATA[// ><!--
  1461. alert("test");
  1462. //--><!]]>
  1463. </script></p>');
  1464. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1465. <!--//--><![CDATA[// ><!--
  1466. <!--//--><![CDATA[// ><!--
  1467. alert("test");
  1468. //--><!]]]]><![CDATA[>
  1469. //--><!]]>
  1470. </script></p>',
  1471. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
  1472. );
  1473. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1474. // <![CDATA[
  1475. alert("test");
  1476. // ]]>
  1477. </script></p>');
  1478. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1479. <!--//--><![CDATA[// ><!--
  1480. // <![CDATA[
  1481. alert("test");
  1482. // ]]]]><![CDATA[>
  1483. //--><!]]>
  1484. </script></p>',
  1485. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
  1486. );
  1487. }
  1488. /**
  1489. * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
  1490. *
  1491. * Otherwise fails the test with a given message, similar to all the
  1492. * SimpleTest assert* functions.
  1493. *
  1494. * Note that this does not remove nulls, new lines and other characters that
  1495. * could be used to obscure a tag or an attribute name.
  1496. *
  1497. * @param $haystack
  1498. * Text to look in.
  1499. * @param $needle
  1500. * Lowercase, plain text to look for.
  1501. * @param $message
  1502. * Message to display if failed.
  1503. * @param $group
  1504. * The group this message belongs to, defaults to 'Other'.
  1505. * @return
  1506. * TRUE on pass, FALSE on fail.
  1507. */
  1508. function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1509. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
  1510. }
  1511. /**
  1512. * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
  1513. *
  1514. * Otherwise fails the test with a given message, similar to all the
  1515. * SimpleTest assert* functions.
  1516. *
  1517. * Note that this does not remove nulls, new lines, and other character that
  1518. * could be used to obscure a tag or an attribute name.
  1519. *
  1520. * @param $haystack
  1521. * Text to look in.
  1522. * @param $needle
  1523. * Lowercase, plain text to look for.
  1524. * @param $message
  1525. * Message to display if failed.
  1526. * @param $group
  1527. * The group this message belongs to, defaults to 'Other'.
  1528. * @return
  1529. * TRUE on pass, FALSE on fail.
  1530. */
  1531. function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1532. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
  1533. }
  1534. }
  1535. /**
  1536. * Tests for filter hook invocation.
  1537. */
  1538. class FilterHooksTestCase extends DrupalWebTestCase {
  1539. public static function getInfo() {
  1540. return array(
  1541. 'name' => 'Filter format hooks',
  1542. 'description' => 'Test hooks for text formats insert/update/disable.',
  1543. 'group' => 'Filter',
  1544. );
  1545. }
  1546. function setUp() {
  1547. parent::setUp('block', 'filter_test');
  1548. $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
  1549. $this->drupalLogin($admin_user);
  1550. }
  1551. /**
  1552. * Test that hooks run correctly on creating, editing, and deleting a text format.
  1553. */
  1554. function testFilterHooks() {
  1555. // Add a text format.
  1556. $name = $this->randomName();
  1557. $edit = array();
  1558. $edit['format'] = drupal_strtolower($this->randomName());
  1559. $edit['name'] = $name;
  1560. $edit['roles[1]'] = 1;
  1561. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  1562. $this->assertRaw(t('Added text format %format.', array('%format' => $name)), t('New format created.'));
  1563. $this->assertText('hook_filter_format_insert invoked.', t('hook_filter_format_insert was invoked.'));
  1564. $format_id = $edit['format'];
  1565. // Update text format.
  1566. $edit = array();
  1567. $edit['roles[2]'] = 1;
  1568. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  1569. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), t('Format successfully updated.'));
  1570. $this->assertText('hook_filter_format_update invoked.', t('hook_filter_format_update() was invoked.'));
  1571. // Add a new custom block.
  1572. $custom_block = array();
  1573. $custom_block['info'] = $this->randomName(8);
  1574. $custom_block['title'] = $this->randomName(8);
  1575. $custom_block['body[value]'] = $this->randomName(32);
  1576. // Use the format created.
  1577. $custom_block['body[format]'] = $format_id;
  1578. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  1579. $this->assertText(t('The block has been created.'), t('New block successfully created.'));
  1580. // Verify the new block is in the database.
  1581. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  1582. $this->assertNotNull($bid, t('New block found in database'));
  1583. // Disable the text format.
  1584. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  1585. $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), t('Format successfully disabled.'));
  1586. $this->assertText('hook_filter_format_disable invoked.', t('hook_filter_format_disable() was invoked.'));
  1587. }
  1588. }
  1589. /**
  1590. * Tests filter settings.
  1591. */
  1592. class FilterSettingsTestCase extends DrupalWebTestCase {
  1593. protected $profile = 'testing';
  1594. public static function getInfo() {
  1595. return array(
  1596. 'name' => 'Filter settings',
  1597. 'description' => 'Tests filter settings.',
  1598. 'group' => 'Filter',
  1599. );
  1600. }
  1601. /**
  1602. * Tests explicit and implicit default settings for filters.
  1603. */
  1604. function testFilterDefaults() {
  1605. $filter_info = filter_filter_info();
  1606. $filters = array_fill_keys(array_keys($filter_info), array());
  1607. // Create text format using filter default settings.
  1608. $filter_defaults_format = (object) array(
  1609. 'format' => 'filter_defaults',
  1610. 'name' => 'Filter defaults',
  1611. 'filters' => $filters,
  1612. );
  1613. filter_format_save($filter_defaults_format);
  1614. // Verify that default weights defined in hook_filter_info() were applied.
  1615. $saved_settings = array();
  1616. foreach ($filter_defaults_format->filters as $name => $settings) {
  1617. $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
  1618. $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
  1619. '@name' => $name,
  1620. '%saved' => $settings['weight'],
  1621. '%default' => $expected_weight,
  1622. )));
  1623. $saved_settings[$name]['weight'] = $expected_weight;
  1624. }
  1625. // Re-save the text format.
  1626. filter_format_save($filter_defaults_format);
  1627. // Reload it from scratch.
  1628. filter_formats_reset();
  1629. $filter_defaults_format = filter_format_load($filter_defaults_format->format);
  1630. $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
  1631. // Verify that saved filter settings have not been changed.
  1632. foreach ($filter_defaults_format->filters as $name => $settings) {
  1633. $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
  1634. '@name' => $name,
  1635. '%saved' => $settings->weight,
  1636. '%previous' => $saved_settings[$name]['weight'],
  1637. )));
  1638. }
  1639. }
  1640. }
Login or register to post comments