filter.test 86 KB

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