filter.test 84 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902
  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[' . DRUPAL_AUTHENTICATED_RID . ']'] = 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[' . DRUPAL_AUTHENTICATED_RID . ']', '', 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[' . DRUPAL_ANONYMOUS_RID . ']'] = 0;
  289. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 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[' . DRUPAL_AUTHENTICATED_RID . ']'] = 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[' . DRUPAL_AUTHENTICATED_RID . ']', $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'], 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. // Create a e-mail that is too long.
  1012. $long_email = str_repeat('a', 254) . '@example.com';
  1013. $too_long_email = str_repeat('b', 255) . '@example.com';
  1014. // Filter selection/pattern matching.
  1015. $tests = array(
  1016. // HTTP URLs.
  1017. '
  1018. http://example.com or www.example.com
  1019. ' => array(
  1020. '<a href="http://example.com">http://example.com</a>' => TRUE,
  1021. '<a href="http://www.example.com">www.example.com</a>' => TRUE,
  1022. ),
  1023. // MAILTO URLs.
  1024. '
  1025. person@example.com or mailto:person2@example.com or ' . $long_email . ' but not ' . $too_long_email . '
  1026. ' => array(
  1027. '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
  1028. '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
  1029. '<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
  1030. '<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
  1031. ),
  1032. // URI parts and special characters.
  1033. '
  1034. http://trailingslash.com/ or www.trailingslash.com/
  1035. http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
  1036. http://twitter.com/#!/example/status/22376963142324226
  1037. ftp://user:pass@ftp.example.com/~home/dir1
  1038. sftp://user@nonstandardport:222/dir
  1039. ssh://192.168.0.100/srv/git/drupal.git
  1040. ' => array(
  1041. '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
  1042. '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
  1043. '<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,
  1044. '<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,
  1045. '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
  1046. '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
  1047. '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
  1048. '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
  1049. ),
  1050. // Encoding.
  1051. '
  1052. http://ampersand.com/?a=1&b=2
  1053. http://encoded.com/?a=1&amp;b=2
  1054. ' => array(
  1055. '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
  1056. '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
  1057. ),
  1058. // Domain name length.
  1059. '
  1060. www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
  1061. me@me.tv
  1062. ' => array(
  1063. '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
  1064. '<a href="http://www.example.example">www.example.example</a>' => TRUE,
  1065. 'http://www.toolong' => FALSE,
  1066. '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
  1067. ),
  1068. // Absolute URL protocols.
  1069. // The list to test is found in the beginning of _filter_url() at
  1070. // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
  1071. '
  1072. https://example.com,
  1073. ftp://ftp.example.com,
  1074. news://example.net,
  1075. telnet://example,
  1076. irc://example.host,
  1077. ssh://odd.geek,
  1078. sftp://secure.host?,
  1079. webcal://calendar,
  1080. rtsp://127.0.0.1,
  1081. not foo://disallowed.com.
  1082. ' => array(
  1083. 'href="https://example.com"' => TRUE,
  1084. 'href="ftp://ftp.example.com"' => TRUE,
  1085. 'href="news://example.net"' => TRUE,
  1086. 'href="telnet://example"' => TRUE,
  1087. 'href="irc://example.host"' => TRUE,
  1088. 'href="ssh://odd.geek"' => TRUE,
  1089. 'href="sftp://secure.host"' => TRUE,
  1090. 'href="webcal://calendar"' => TRUE,
  1091. 'href="rtsp://127.0.0.1"' => TRUE,
  1092. 'href="foo://disallowed.com"' => FALSE,
  1093. 'not foo://disallowed.com.' => TRUE,
  1094. ),
  1095. );
  1096. $this->assertFilteredString($filter, $tests);
  1097. // Surrounding text/punctuation.
  1098. $tests = array(
  1099. '
  1100. Partial URL with trailing period www.partial.com.
  1101. E-mail with trailing comma person@example.com,
  1102. Absolute URL with trailing question http://www.absolute.com?
  1103. Query string with trailing exclamation www.query.com/index.php?a=!
  1104. Partial URL with 3 trailing www.partial.periods...
  1105. E-mail with 3 trailing exclamations@example.com!!!
  1106. Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
  1107. ' => array(
  1108. 'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
  1109. 'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
  1110. 'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
  1111. 'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
  1112. 'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
  1113. 'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
  1114. 'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
  1115. ),
  1116. '
  1117. (www.parenthesis.com/dir?a=1&b=2#a)
  1118. ' => array(
  1119. '(<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,
  1120. ),
  1121. );
  1122. $this->assertFilteredString($filter, $tests);
  1123. // Surrounding markup.
  1124. $tests = array(
  1125. '
  1126. <p xmlns="www.namespace.com" />
  1127. <p xmlns="http://namespace.com">
  1128. An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
  1129. </p>
  1130. ' => array(
  1131. '<p xmlns="www.namespace.com" />' => TRUE,
  1132. '<p xmlns="http://namespace.com">' => TRUE,
  1133. 'href="http://www.namespace.com"' => FALSE,
  1134. 'href="http://namespace.com"' => FALSE,
  1135. 'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
  1136. ),
  1137. '
  1138. Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
  1139. but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
  1140. ' => array(
  1141. '<a href="foo">www.relative.com</a>' => TRUE,
  1142. 'href="http://www.relative.com"' => FALSE,
  1143. '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
  1144. '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
  1145. '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
  1146. ),
  1147. '
  1148. Test <code>using www.example.com the code tag</code>.
  1149. ' => array(
  1150. 'href' => FALSE,
  1151. 'http' => FALSE,
  1152. ),
  1153. '
  1154. Intro.
  1155. <blockquote>
  1156. 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>.
  1157. </blockquote>
  1158. Outro.
  1159. ' => array(
  1160. 'href="http://www.example.com"' => TRUE,
  1161. 'href="mailto:person@example.com"' => TRUE,
  1162. 'href="http://origin.example.com"' => TRUE,
  1163. 'http://www.usage.example.com' => FALSE,
  1164. 'http://www.example.info' => FALSE,
  1165. 'Intro.' => TRUE,
  1166. 'Outro.' => TRUE,
  1167. ),
  1168. '
  1169. 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>
  1170. ' => array(
  1171. 'href="http://www.example.com"' => TRUE,
  1172. 'href="http://www.example.pooh"' => TRUE,
  1173. ),
  1174. '
  1175. <p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
  1176. It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
  1177. 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.
  1178. ' => array(
  1179. 'href="http://www.example17.com"' => TRUE,
  1180. 'href="http://www.example18.com"' => TRUE,
  1181. 'href="http://www.example19.com"' => TRUE,
  1182. 'href="http://www.example20.com"' => TRUE,
  1183. 'href="http://www.example21.com"' => TRUE,
  1184. 'href="mailto:person@example22.com"' => TRUE,
  1185. 'href="http://www.example23.com"' => TRUE,
  1186. 'href="http://www.example24.com"' => TRUE,
  1187. 'href="http://www.example25.com"' => TRUE,
  1188. 'href="http://www.example26.com"' => TRUE,
  1189. 'href="mailto:person@example27.com"' => TRUE,
  1190. 'href="http://www.example28.com"' => TRUE,
  1191. ),
  1192. '
  1193. <script>
  1194. <!--
  1195. // @see www.example.com
  1196. var exampleurl = "http://example.net";
  1197. -->
  1198. <!--//--><![CDATA[//><!--
  1199. // @see www.example.com
  1200. var exampleurl = "http://example.net";
  1201. //--><!]]>
  1202. </script>
  1203. ' => array(
  1204. 'href="http://www.example.com"' => FALSE,
  1205. 'href="http://example.net"' => FALSE,
  1206. ),
  1207. '
  1208. <style>body {
  1209. background: url(http://example.com/pixel.gif);
  1210. }</style>
  1211. ' => array(
  1212. 'href' => FALSE,
  1213. ),
  1214. '
  1215. <!-- Skip any URLs like www.example.com in comments -->
  1216. ' => array(
  1217. 'href' => FALSE,
  1218. ),
  1219. '
  1220. <!-- Skip any URLs like
  1221. www.example.com with a newline in comments -->
  1222. ' => array(
  1223. 'href' => FALSE,
  1224. ),
  1225. '
  1226. <!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
  1227. ' => array(
  1228. 'href' => FALSE,
  1229. ),
  1230. '
  1231. <dl>
  1232. <dt>www.example.com</dt>
  1233. <dd>http://example.com</dd>
  1234. <dd>person@example.com</dd>
  1235. <dt>Check www.example.net</dt>
  1236. <dd>Some text around http://www.example.info by person@example.info?</dd>
  1237. </dl>
  1238. ' => array(
  1239. 'href="http://www.example.com"' => TRUE,
  1240. 'href="http://example.com"' => TRUE,
  1241. 'href="mailto:person@example.com"' => TRUE,
  1242. 'href="http://www.example.net"' => TRUE,
  1243. 'href="http://www.example.info"' => TRUE,
  1244. 'href="mailto:person@example.info"' => TRUE,
  1245. ),
  1246. '
  1247. <div>www.div.com</div>
  1248. <ul>
  1249. <li>http://listitem.com</li>
  1250. <li class="odd">www.class.listitem.com</li>
  1251. </ul>
  1252. ' => array(
  1253. '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
  1254. '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
  1255. '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
  1256. ),
  1257. );
  1258. $this->assertFilteredString($filter, $tests);
  1259. // URL trimming.
  1260. $filter->settings['filter_url_length'] = 20;
  1261. $tests = array(
  1262. 'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
  1263. '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
  1264. ),
  1265. );
  1266. $this->assertFilteredString($filter, $tests);
  1267. }
  1268. /**
  1269. * Asserts multiple filter output expectations for multiple input strings.
  1270. *
  1271. * @param $filter
  1272. * A input filter object.
  1273. * @param $tests
  1274. * An associative array, whereas each key is an arbitrary input string and
  1275. * each value is again an associative array whose keys are filter output
  1276. * strings and whose values are Booleans indicating whether the output is
  1277. * expected or not.
  1278. *
  1279. * For example:
  1280. * @code
  1281. * $tests = array(
  1282. * 'Input string' => array(
  1283. * '<p>Input string</p>' => TRUE,
  1284. * 'Input string<br' => FALSE,
  1285. * ),
  1286. * );
  1287. * @endcode
  1288. */
  1289. function assertFilteredString($filter, $tests) {
  1290. foreach ($tests as $source => $tasks) {
  1291. $function = $filter->callback;
  1292. $result = $function($source, $filter);
  1293. foreach ($tasks as $value => $is_expected) {
  1294. // Not using assertIdentical, since combination with strpos() is hard to grok.
  1295. if ($is_expected) {
  1296. $success = $this->assertTrue(strpos($result, $value) !== FALSE, t('@source: @value found.', array(
  1297. '@source' => var_export($source, TRUE),
  1298. '@value' => var_export($value, TRUE),
  1299. )));
  1300. }
  1301. else {
  1302. $success = $this->assertTrue(strpos($result, $value) === FALSE, t('@source: @value not found.', array(
  1303. '@source' => var_export($source, TRUE),
  1304. '@value' => var_export($value, TRUE),
  1305. )));
  1306. }
  1307. if (!$success) {
  1308. $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
  1309. . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
  1310. . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
  1311. . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
  1312. );
  1313. }
  1314. }
  1315. }
  1316. }
  1317. /**
  1318. * Tests URL filter on longer content.
  1319. *
  1320. * Filters based on regular expressions should also be tested with a more
  1321. * complex content than just isolated test lines.
  1322. * The most common errors are:
  1323. * - accidental '*' (greedy) match instead of '*?' (minimal) match.
  1324. * - only matching first occurrence instead of all.
  1325. * - newlines not matching '.*'.
  1326. *
  1327. * This test covers:
  1328. * - Document with multiple newlines and paragraphs (two newlines).
  1329. * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
  1330. * comments.
  1331. * - Empty HTML tags (BR, IMG).
  1332. * - Mix of absolute and partial URLs, and e-mail addresses in one content.
  1333. */
  1334. function testUrlFilterContent() {
  1335. // Setup dummy filter object.
  1336. $filter = new stdClass();
  1337. $filter->settings = array(
  1338. 'filter_url_length' => 496,
  1339. );
  1340. $path = drupal_get_path('module', 'filter') . '/tests';
  1341. $input = file_get_contents($path . '/filter.url-input.txt');
  1342. $expected = file_get_contents($path . '/filter.url-output.txt');
  1343. $result = _filter_url($input, $filter);
  1344. $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
  1345. }
  1346. /**
  1347. * Test the HTML corrector filter.
  1348. *
  1349. * @todo This test could really use some validity checking function.
  1350. */
  1351. function testHtmlCorrectorFilter() {
  1352. // Tag closing.
  1353. $f = _filter_htmlcorrector('<p>text');
  1354. $this->assertEqual($f, '<p>text</p>', t('HTML corrector -- tag closing at the end of input.'));
  1355. $f = _filter_htmlcorrector('<p>text<p><p>text');
  1356. $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', t('HTML corrector -- tag closing.'));
  1357. $f = _filter_htmlcorrector("<ul><li>e1<li>e2");
  1358. $this->assertEqual($f, "<ul><li>e1</li><li>e2</li></ul>", t('HTML corrector -- unclosed list tags.'));
  1359. $f = _filter_htmlcorrector('<div id="d">content');
  1360. $this->assertEqual($f, '<div id="d">content</div>', t('HTML corrector -- unclosed tag with attribute.'));
  1361. // XHTML slash for empty elements.
  1362. $f = _filter_htmlcorrector('<hr><br>');
  1363. $this->assertEqual($f, '<hr /><br />', t('HTML corrector -- XHTML closing slash.'));
  1364. $f = _filter_htmlcorrector('<P>test</P>');
  1365. $this->assertEqual($f, '<p>test</p>', t('HTML corrector -- Convert uppercased tags to proper lowercased ones.'));
  1366. $f = _filter_htmlcorrector('<P>test</p>');
  1367. $this->assertEqual($f, '<p>test</p>', t('HTML corrector -- Convert uppercased tags to proper lowercased ones.'));
  1368. $f = _filter_htmlcorrector('test<hr />');
  1369. $this->assertEqual($f, 'test<hr />', t('HTML corrector -- Let proper XHTML pass through.'));
  1370. $f = _filter_htmlcorrector('test<hr/>');
  1371. $this->assertEqual($f, 'test<hr />', t('HTML corrector -- Let proper XHTML pass through, but ensure there is a single space before the closing slash.'));
  1372. $f = _filter_htmlcorrector('test<hr />');
  1373. $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.'));
  1374. $f = _filter_htmlcorrector('<span class="test" />');
  1375. $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.'));
  1376. $f = _filter_htmlcorrector('test1<br class="test">test2');
  1377. $this->assertEqual($f, 'test1<br class="test" />test2', t('HTML corrector -- Automatically close single tags.'));
  1378. $f = _filter_htmlcorrector('line1<hr>line2');
  1379. $this->assertEqual($f, 'line1<hr />line2', t('HTML corrector -- Automatically close single tags.'));
  1380. $f = _filter_htmlcorrector('line1<HR>line2');
  1381. $this->assertEqual($f, 'line1<hr />line2', t('HTML corrector -- Automatically close single tags.'));
  1382. $f = _filter_htmlcorrector('<img src="http://example.com/test.jpg">test</img>');
  1383. $this->assertEqual($f, '<img src="http://example.com/test.jpg" />test', t('HTML corrector -- Automatically close single tags.'));
  1384. $f = _filter_htmlcorrector('<br></br>');
  1385. $this->assertEqual($f, '<br />', t("HTML corrector -- Transform empty tags to a single closed tag if the tag's content model is EMPTY."));
  1386. $f = _filter_htmlcorrector('<div></div>');
  1387. $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."));
  1388. $f = _filter_htmlcorrector('<p>line1<br/><hr/>line2</p>');
  1389. $this->assertEqual($f, '<p>line1<br /></p><hr />line2', t('HTML corrector -- Move non-inline elements outside of inline containers.'));
  1390. $f = _filter_htmlcorrector('<p>line1<div>line2</div></p>');
  1391. $this->assertEqual($f, '<p>line1</p><div>line2</div>', t('HTML corrector -- Move non-inline elements outside of inline containers.'));
  1392. $f = _filter_htmlcorrector('<p>test<p>test</p>\n');
  1393. $this->assertEqual($f, '<p>test</p><p>test</p>\n', t('HTML corrector -- Auto-close improperly nested tags.'));
  1394. $f = _filter_htmlcorrector('<p>Line1<br><STRONG>bold stuff</b>');
  1395. $this->assertEqual($f, '<p>Line1<br /><strong>bold stuff</strong></p>', t('HTML corrector -- Properly close unclosed tags, and remove useless closing tags.'));
  1396. $f = _filter_htmlcorrector('test <!-- this is a comment -->');
  1397. $this->assertEqual($f, 'test <!-- this is a comment -->', t('HTML corrector -- Do not touch HTML comments.'));
  1398. $f = _filter_htmlcorrector('test <!--this is a comment-->');
  1399. $this->assertEqual($f, 'test <!--this is a comment-->', t('HTML corrector -- Do not touch HTML comments.'));
  1400. $f = _filter_htmlcorrector('test <!-- comment <p>another
  1401. <strong>multiple</strong> line
  1402. comment</p> -->');
  1403. $this->assertEqual($f, 'test <!-- comment <p>another
  1404. <strong>multiple</strong> line
  1405. comment</p> -->', t('HTML corrector -- Do not touch HTML comments.'));
  1406. $f = _filter_htmlcorrector('test <!-- comment <p>another comment</p> -->');
  1407. $this->assertEqual($f, 'test <!-- comment <p>another comment</p> -->', t('HTML corrector -- Do not touch HTML comments.'));
  1408. $f = _filter_htmlcorrector('test <!--break-->');
  1409. $this->assertEqual($f, 'test <!--break-->', t('HTML corrector -- Do not touch HTML comments.'));
  1410. $f = _filter_htmlcorrector('<p>test\n</p>\n');
  1411. $this->assertEqual($f, '<p>test\n</p>\n', t('HTML corrector -- New-lines are accepted and kept as-is.'));
  1412. $f = _filter_htmlcorrector('<p>دروبال');
  1413. $this->assertEqual($f, '<p>دروبال</p>', t('HTML corrector -- Encoding is correctly kept.'));
  1414. $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
  1415. $this->assertEqual($f, '<script type="text/javascript">
  1416. <!--//--><![CDATA[// ><!--
  1417. alert("test")
  1418. //--><!]]>
  1419. </script>', t('HTML corrector -- CDATA added to script element'));
  1420. $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
  1421. $this->assertEqual($f, '<p><script type="text/javascript">
  1422. <!--//--><![CDATA[// ><!--
  1423. alert("test")
  1424. //--><!]]>
  1425. </script></p>', t('HTML corrector -- CDATA added to a nested script element'));
  1426. $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
  1427. $this->assertEqual($f, '<p><style>
  1428. <!--/*--><![CDATA[/* ><!--*/
  1429. /* Styling */ body {color:red}
  1430. /*--><!]]>*/
  1431. </style></p>', t('HTML corrector -- CDATA added to a style element.'));
  1432. $filtered_data = _filter_htmlcorrector('<p><style>
  1433. /*<![CDATA[*/
  1434. /* Styling */
  1435. body {color:red}
  1436. /*]]>*/
  1437. </style></p>');
  1438. $this->assertEqual($filtered_data, '<p><style>
  1439. <!--/*--><![CDATA[/* ><!--*/
  1440. /*<![CDATA[*/
  1441. /* Styling */
  1442. body {color:red}
  1443. /*]]]]><![CDATA[>*/
  1444. /*--><!]]>*/
  1445. </style></p>',
  1446. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
  1447. );
  1448. $filtered_data = _filter_htmlcorrector('<p><style>
  1449. <!--/*--><![CDATA[/* ><!--*/
  1450. /* Styling */
  1451. body {color:red}
  1452. /*--><!]]>*/
  1453. </style></p>');
  1454. $this->assertEqual($filtered_data, '<p><style>
  1455. <!--/*--><![CDATA[/* ><!--*/
  1456. <!--/*--><![CDATA[/* ><!--*/
  1457. /* Styling */
  1458. body {color:red}
  1459. /*--><!]]]]><![CDATA[>*/
  1460. /*--><!]]>*/
  1461. </style></p>',
  1462. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
  1463. );
  1464. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1465. <!--//--><![CDATA[// ><!--
  1466. alert("test");
  1467. //--><!]]>
  1468. </script></p>');
  1469. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1470. <!--//--><![CDATA[// ><!--
  1471. <!--//--><![CDATA[// ><!--
  1472. alert("test");
  1473. //--><!]]]]><![CDATA[>
  1474. //--><!]]>
  1475. </script></p>',
  1476. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
  1477. );
  1478. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1479. // <![CDATA[
  1480. alert("test");
  1481. // ]]>
  1482. </script></p>');
  1483. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1484. <!--//--><![CDATA[// ><!--
  1485. // <![CDATA[
  1486. alert("test");
  1487. // ]]]]><![CDATA[>
  1488. //--><!]]>
  1489. </script></p>',
  1490. t('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
  1491. );
  1492. }
  1493. /**
  1494. * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
  1495. *
  1496. * Otherwise fails the test with a given message, similar to all the
  1497. * SimpleTest assert* functions.
  1498. *
  1499. * Note that this does not remove nulls, new lines and other characters that
  1500. * could be used to obscure a tag or an attribute name.
  1501. *
  1502. * @param $haystack
  1503. * Text to look in.
  1504. * @param $needle
  1505. * Lowercase, plain text to look for.
  1506. * @param $message
  1507. * Message to display if failed.
  1508. * @param $group
  1509. * The group this message belongs to, defaults to 'Other'.
  1510. * @return
  1511. * TRUE on pass, FALSE on fail.
  1512. */
  1513. function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1514. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
  1515. }
  1516. /**
  1517. * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
  1518. *
  1519. * Otherwise fails the test with a given message, similar to all the
  1520. * SimpleTest assert* functions.
  1521. *
  1522. * Note that this does not remove nulls, new lines, and other character that
  1523. * could be used to obscure a tag or an attribute name.
  1524. *
  1525. * @param $haystack
  1526. * Text to look in.
  1527. * @param $needle
  1528. * Lowercase, plain text to look for.
  1529. * @param $message
  1530. * Message to display if failed.
  1531. * @param $group
  1532. * The group this message belongs to, defaults to 'Other'.
  1533. * @return
  1534. * TRUE on pass, FALSE on fail.
  1535. */
  1536. function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1537. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
  1538. }
  1539. }
  1540. /**
  1541. * Tests for filter hook invocation.
  1542. */
  1543. class FilterHooksTestCase extends DrupalWebTestCase {
  1544. public static function getInfo() {
  1545. return array(
  1546. 'name' => 'Filter format hooks',
  1547. 'description' => 'Test hooks for text formats insert/update/disable.',
  1548. 'group' => 'Filter',
  1549. );
  1550. }
  1551. function setUp() {
  1552. parent::setUp('block', 'filter_test');
  1553. $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
  1554. $this->drupalLogin($admin_user);
  1555. }
  1556. /**
  1557. * Test that hooks run correctly on creating, editing, and deleting a text format.
  1558. */
  1559. function testFilterHooks() {
  1560. // Add a text format.
  1561. $name = $this->randomName();
  1562. $edit = array();
  1563. $edit['format'] = drupal_strtolower($this->randomName());
  1564. $edit['name'] = $name;
  1565. $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 1;
  1566. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  1567. $this->assertRaw(t('Added text format %format.', array('%format' => $name)), t('New format created.'));
  1568. $this->assertText('hook_filter_format_insert invoked.', t('hook_filter_format_insert was invoked.'));
  1569. $format_id = $edit['format'];
  1570. // Update text format.
  1571. $edit = array();
  1572. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
  1573. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  1574. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), t('Format successfully updated.'));
  1575. $this->assertText('hook_filter_format_update invoked.', t('hook_filter_format_update() was invoked.'));
  1576. // Add a new custom block.
  1577. $custom_block = array();
  1578. $custom_block['info'] = $this->randomName(8);
  1579. $custom_block['title'] = $this->randomName(8);
  1580. $custom_block['body[value]'] = $this->randomName(32);
  1581. // Use the format created.
  1582. $custom_block['body[format]'] = $format_id;
  1583. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  1584. $this->assertText(t('The block has been created.'), t('New block successfully created.'));
  1585. // Verify the new block is in the database.
  1586. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  1587. $this->assertNotNull($bid, t('New block found in database'));
  1588. // Disable the text format.
  1589. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  1590. $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), t('Format successfully disabled.'));
  1591. $this->assertText('hook_filter_format_disable invoked.', t('hook_filter_format_disable() was invoked.'));
  1592. }
  1593. }
  1594. /**
  1595. * Tests filter settings.
  1596. */
  1597. class FilterSettingsTestCase extends DrupalWebTestCase {
  1598. protected $profile = 'testing';
  1599. public static function getInfo() {
  1600. return array(
  1601. 'name' => 'Filter settings',
  1602. 'description' => 'Tests filter settings.',
  1603. 'group' => 'Filter',
  1604. );
  1605. }
  1606. /**
  1607. * Tests explicit and implicit default settings for filters.
  1608. */
  1609. function testFilterDefaults() {
  1610. $filter_info = filter_filter_info();
  1611. $filters = array_fill_keys(array_keys($filter_info), array());
  1612. // Create text format using filter default settings.
  1613. $filter_defaults_format = (object) array(
  1614. 'format' => 'filter_defaults',
  1615. 'name' => 'Filter defaults',
  1616. 'filters' => $filters,
  1617. );
  1618. filter_format_save($filter_defaults_format);
  1619. // Verify that default weights defined in hook_filter_info() were applied.
  1620. $saved_settings = array();
  1621. foreach ($filter_defaults_format->filters as $name => $settings) {
  1622. $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
  1623. $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
  1624. '@name' => $name,
  1625. '%saved' => $settings['weight'],
  1626. '%default' => $expected_weight,
  1627. )));
  1628. $saved_settings[$name]['weight'] = $expected_weight;
  1629. }
  1630. // Re-save the text format.
  1631. filter_format_save($filter_defaults_format);
  1632. // Reload it from scratch.
  1633. filter_formats_reset();
  1634. $filter_defaults_format = filter_format_load($filter_defaults_format->format);
  1635. $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
  1636. // Verify that saved filter settings have not been changed.
  1637. foreach ($filter_defaults_format->filters as $name => $settings) {
  1638. $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
  1639. '@name' => $name,
  1640. '%saved' => $settings->weight,
  1641. '%previous' => $saved_settings[$name]['weight'],
  1642. )));
  1643. }
  1644. }
  1645. }