filter.test 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035
  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. // Check regular user access to the filter tips pages.
  481. $this->drupalGet('filter/tips/' . $this->allowed_format->format);
  482. $this->assertResponse(200);
  483. $this->drupalGet('filter/tips/' . $this->disallowed_format->format);
  484. $this->assertResponse(403);
  485. $this->drupalGet('filter/tips/' . filter_fallback_format());
  486. $this->assertResponse(200);
  487. $this->drupalGet('filter/tips/invalid-format');
  488. $this->assertResponse(404);
  489. // Check admin user access to the filter tips pages.
  490. $this->drupalLogin($this->admin_user);
  491. $this->drupalGet('filter/tips/' . $this->allowed_format->format);
  492. $this->assertResponse(200);
  493. $this->drupalGet('filter/tips/' . $this->disallowed_format->format);
  494. $this->assertResponse(200);
  495. $this->drupalGet('filter/tips/' . filter_fallback_format());
  496. $this->assertResponse(200);
  497. $this->drupalGet('filter/tips/invalid-format');
  498. $this->assertResponse(404);
  499. }
  500. /**
  501. * Tests if text format is available to a role.
  502. */
  503. function testFormatRoles() {
  504. // Get the role ID assigned to the regular user; it must be the maximum.
  505. $rid = max(array_keys($this->web_user->roles));
  506. // Check that this role appears in the list of roles that have access to an
  507. // allowed text format, but does not appear in the list of roles that have
  508. // access to a disallowed text format.
  509. $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.');
  510. $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.');
  511. // Check that the correct text format appears in the list of formats
  512. // available to that role.
  513. $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.');
  514. $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.');
  515. // Check that the fallback format is always allowed.
  516. $this->assertEqual(filter_get_roles_by_format(filter_format_load(filter_fallback_format())), user_roles(), 'All roles have access to the fallback format.');
  517. $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.');
  518. }
  519. /**
  520. * Tests editing a page using a disallowed text format.
  521. *
  522. * Verifies that regular users and administrators are able to edit a page, but
  523. * not allowed to change the fields which use an inaccessible text format.
  524. * Also verifies that fields which use a text format that does not exist can
  525. * be edited by administrators only, but that the administrator is forced to
  526. * choose a new format before saving the page.
  527. */
  528. function testFormatWidgetPermissions() {
  529. $langcode = LANGUAGE_NONE;
  530. $title_key = "title";
  531. $body_value_key = "body[$langcode][0][value]";
  532. $body_format_key = "body[$langcode][0][format]";
  533. // Create node to edit.
  534. $this->drupalLogin($this->admin_user);
  535. $edit = array();
  536. $edit['title'] = $this->randomName(8);
  537. $edit[$body_value_key] = $this->randomName(16);
  538. $edit[$body_format_key] = $this->disallowed_format->format;
  539. $this->drupalPost('node/add/page', $edit, t('Save'));
  540. $node = $this->drupalGetNodeByTitle($edit['title']);
  541. // Try to edit with a less privileged user.
  542. $this->drupalLogin($this->web_user);
  543. $this->drupalGet('node/' . $node->nid);
  544. $this->clickLink(t('Edit'));
  545. // Verify that body field is read-only and contains replacement value.
  546. $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.');
  547. // Verify that title can be changed, but preview displays original body.
  548. $new_edit = array();
  549. $new_edit['title'] = $this->randomName(8);
  550. $this->drupalPost(NULL, $new_edit, t('Preview'));
  551. $this->assertText($edit[$body_value_key], 'Old body found in preview.');
  552. // Save and verify that only the title was changed.
  553. $this->drupalPost(NULL, $new_edit, t('Save'));
  554. $this->assertNoText($edit['title'], 'Old title not found.');
  555. $this->assertText($new_edit['title'], 'New title found.');
  556. $this->assertText($edit[$body_value_key], 'Old body found.');
  557. // Check that even an administrator with "administer filters" permission
  558. // cannot edit the body field if they do not have specific permission to
  559. // use its stored format. (This must be disallowed so that the
  560. // administrator is never forced to switch the text format to something
  561. // else.)
  562. $this->drupalLogin($this->filter_admin_user);
  563. $this->drupalGet('node/' . $node->nid . '/edit');
  564. $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.');
  565. // Disable the text format used above.
  566. filter_format_disable($this->disallowed_format);
  567. $this->resetFilterCaches();
  568. // Log back in as the less privileged user and verify that the body field
  569. // is still disabled, since the less privileged user should not be able to
  570. // edit content that does not have an assigned format.
  571. $this->drupalLogin($this->web_user);
  572. $this->drupalGet('node/' . $node->nid . '/edit');
  573. $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.');
  574. // Log back in as the filter administrator and verify that the body field
  575. // can be edited.
  576. $this->drupalLogin($this->filter_admin_user);
  577. $this->drupalGet('node/' . $node->nid . '/edit');
  578. $this->assertNoFieldByXPath("//textarea[@name='$body_value_key' and @disabled='disabled']", NULL, 'Text format access denied message not found.');
  579. $this->assertFieldByXPath("//select[@name='$body_format_key']", NULL, 'Text format selector found.');
  580. // Verify that trying to save the node without selecting a new text format
  581. // produces an error message, and does not result in the node being saved.
  582. $old_title = $new_edit['title'];
  583. $new_title = $this->randomName(8);
  584. $edit = array('title' => $new_title);
  585. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  586. $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
  587. $this->drupalGet('node/' . $node->nid);
  588. $this->assertText($old_title, 'Old title found.');
  589. $this->assertNoText($new_title, 'New title not found.');
  590. // Now select a new text format and make sure the node can be saved.
  591. $edit[$body_format_key] = filter_fallback_format();
  592. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  593. $this->assertUrl('node/' . $node->nid);
  594. $this->assertText($new_title, 'New title found.');
  595. $this->assertNoText($old_title, 'Old title not found.');
  596. // Switch the text format to a new one, then disable that format and all
  597. // other formats on the site (leaving only the fallback format).
  598. $this->drupalLogin($this->admin_user);
  599. $edit = array($body_format_key => $this->allowed_format->format);
  600. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  601. $this->assertUrl('node/' . $node->nid);
  602. foreach (filter_formats() as $format) {
  603. if ($format->format != filter_fallback_format()) {
  604. filter_format_disable($format);
  605. }
  606. }
  607. // Since there is now only one available text format, the widget for
  608. // selecting a text format would normally not display when the content is
  609. // edited. However, we need to verify that the filter administrator still
  610. // is forced to make a conscious choice to reassign the text to a different
  611. // format.
  612. $this->drupalLogin($this->filter_admin_user);
  613. $old_title = $new_title;
  614. $new_title = $this->randomName(8);
  615. $edit = array('title' => $new_title);
  616. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  617. $this->assertText(t('!name field is required.', array('!name' => t('Text format'))), 'Error message is displayed.');
  618. $this->drupalGet('node/' . $node->nid);
  619. $this->assertText($old_title, 'Old title found.');
  620. $this->assertNoText($new_title, 'New title not found.');
  621. $edit[$body_format_key] = filter_fallback_format();
  622. $this->drupalPost('node/' . $node->nid . '/edit', $edit, t('Save'));
  623. $this->assertUrl('node/' . $node->nid);
  624. $this->assertText($new_title, 'New title found.');
  625. $this->assertNoText($old_title, 'Old title not found.');
  626. }
  627. /**
  628. * Rebuilds text format and permission caches in the thread running the tests.
  629. */
  630. protected function resetFilterCaches() {
  631. filter_formats_reset();
  632. $this->checkPermissions(array(), TRUE);
  633. }
  634. }
  635. /**
  636. * Tests the default filter functionality in the Filter module.
  637. */
  638. class FilterDefaultFormatTestCase extends DrupalWebTestCase {
  639. public static function getInfo() {
  640. return array(
  641. 'name' => 'Default text format functionality',
  642. 'description' => 'Test the default text formats for different users.',
  643. 'group' => 'Filter',
  644. );
  645. }
  646. /**
  647. * Tests if the default text format is accessible to users.
  648. */
  649. function testDefaultTextFormats() {
  650. // Create two text formats, and two users. The first user has access to
  651. // both formats, but the second user only has access to the second one.
  652. $admin_user = $this->drupalCreateUser(array('administer filters'));
  653. $this->drupalLogin($admin_user);
  654. $formats = array();
  655. for ($i = 0; $i < 2; $i++) {
  656. $edit = array(
  657. 'format' => drupal_strtolower($this->randomName()),
  658. 'name' => $this->randomName(),
  659. );
  660. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  661. $this->resetFilterCaches();
  662. $formats[] = filter_format_load($edit['format']);
  663. }
  664. list($first_format, $second_format) = $formats;
  665. $first_user = $this->drupalCreateUser(array(filter_permission_name($first_format), filter_permission_name($second_format)));
  666. $second_user = $this->drupalCreateUser(array(filter_permission_name($second_format)));
  667. // Adjust the weights so that the first and second formats (in that order)
  668. // are the two lowest weighted formats available to any user.
  669. $minimum_weight = db_query("SELECT MIN(weight) FROM {filter_format}")->fetchField();
  670. $edit = array();
  671. $edit['formats[' . $first_format->format . '][weight]'] = $minimum_weight - 2;
  672. $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 1;
  673. $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
  674. $this->resetFilterCaches();
  675. // Check that each user's default format is the lowest weighted format that
  676. // the user has access to.
  677. $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.");
  678. $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.");
  679. // Reorder the two formats, and check that both users now have the same
  680. // default.
  681. $edit = array();
  682. $edit['formats[' . $second_format->format . '][weight]'] = $minimum_weight - 3;
  683. $this->drupalPost('admin/config/content/formats', $edit, t('Save changes'));
  684. $this->resetFilterCaches();
  685. $this->assertEqual(filter_default_format($first_user), filter_default_format($second_user), 'After the formats are reordered, both users have the same default format.');
  686. }
  687. /**
  688. * Rebuilds text format and permission caches in the thread running the tests.
  689. */
  690. protected function resetFilterCaches() {
  691. filter_formats_reset();
  692. $this->checkPermissions(array(), TRUE);
  693. }
  694. }
  695. /**
  696. * Tests the behavior of check_markup() when it is called without text format.
  697. */
  698. class FilterNoFormatTestCase extends DrupalWebTestCase {
  699. public static function getInfo() {
  700. return array(
  701. 'name' => 'Unassigned text format functionality',
  702. 'description' => 'Test the behavior of check_markup() when it is called without a text format.',
  703. 'group' => 'Filter',
  704. );
  705. }
  706. /**
  707. * Tests text without format.
  708. *
  709. * Tests if text with no format is filtered the same way as text in the
  710. * fallback format.
  711. */
  712. function testCheckMarkupNoFormat() {
  713. // Create some text. Include some HTML and line breaks, so we get a good
  714. // test of the filtering that is applied to it.
  715. $text = "<strong>" . $this->randomName(32) . "</strong>\n\n<div>" . $this->randomName(32) . "</div>";
  716. // Make sure that when this text is run through check_markup() with no text
  717. // format, it is filtered as though it is in the fallback format.
  718. $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.');
  719. }
  720. }
  721. /**
  722. * Security tests for missing/vanished text formats or filters.
  723. */
  724. class FilterSecurityTestCase extends DrupalWebTestCase {
  725. public static function getInfo() {
  726. return array(
  727. 'name' => 'Security',
  728. 'description' => 'Test the behavior of check_markup() when a filter or text format vanishes.',
  729. 'group' => 'Filter',
  730. );
  731. }
  732. function setUp() {
  733. parent::setUp('php', 'filter_test');
  734. $this->admin_user = $this->drupalCreateUser(array('administer modules', 'administer filters', 'administer site configuration'));
  735. $this->drupalLogin($this->admin_user);
  736. }
  737. /**
  738. * Tests removal of filtered content when an active filter is disabled.
  739. *
  740. * Tests that filtered content is emptied when an actively used filter module
  741. * is disabled.
  742. */
  743. function testDisableFilterModule() {
  744. // Create a new node.
  745. $node = $this->drupalCreateNode(array('promote' => 1));
  746. $body_raw = $node->body[LANGUAGE_NONE][0]['value'];
  747. $format_id = $node->body[LANGUAGE_NONE][0]['format'];
  748. $this->drupalGet('node/' . $node->nid);
  749. $this->assertText($body_raw, 'Node body found.');
  750. // Enable the filter_test_replace filter.
  751. $edit = array(
  752. 'filters[filter_test_replace][status]' => 1,
  753. );
  754. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  755. // Verify that filter_test_replace filter replaced the content.
  756. $this->drupalGet('node/' . $node->nid);
  757. $this->assertNoText($body_raw, 'Node body not found.');
  758. $this->assertText('Filter: Testing filter', 'Testing filter output found.');
  759. // Disable the text format entirely.
  760. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  761. // Verify that the content is empty, because the text format does not exist.
  762. $this->drupalGet('node/' . $node->nid);
  763. $this->assertNoText($body_raw, 'Node body not found.');
  764. }
  765. }
  766. /**
  767. * Unit tests for core filters.
  768. */
  769. class FilterUnitTestCase extends DrupalUnitTestCase {
  770. public static function getInfo() {
  771. return array(
  772. 'name' => 'Filter module filters',
  773. 'description' => 'Tests Filter module filters individually.',
  774. 'group' => 'Filter',
  775. );
  776. }
  777. /**
  778. * Tests the line break filter.
  779. */
  780. function testLineBreakFilter() {
  781. // Setup dummy filter object.
  782. $filter = new stdClass();
  783. $filter->callback = '_filter_autop';
  784. // Since the line break filter naturally needs plenty of newlines in test
  785. // strings and expectations, we're using "\n" instead of regular newlines
  786. // here.
  787. $tests = array(
  788. // Single line breaks should be changed to <br /> tags, while paragraphs
  789. // separated with double line breaks should be enclosed with <p></p> tags.
  790. "aaa\nbbb\n\nccc" => array(
  791. "<p>aaa<br />\nbbb</p>\n<p>ccc</p>" => TRUE,
  792. ),
  793. // Skip contents of certain block tags entirely.
  794. "<script>aaa\nbbb\n\nccc</script>
  795. <style>aaa\nbbb\n\nccc</style>
  796. <pre>aaa\nbbb\n\nccc</pre>
  797. <object>aaa\nbbb\n\nccc</object>
  798. <iframe>aaa\nbbb\n\nccc</iframe>
  799. " => array(
  800. "<script>aaa\nbbb\n\nccc</script>" => TRUE,
  801. "<style>aaa\nbbb\n\nccc</style>" => TRUE,
  802. "<pre>aaa\nbbb\n\nccc</pre>" => TRUE,
  803. "<object>aaa\nbbb\n\nccc</object>" => TRUE,
  804. "<iframe>aaa\nbbb\n\nccc</iframe>" => TRUE,
  805. ),
  806. // Skip comments entirely.
  807. "One. <!-- comment --> Two.\n<!--\nThree.\n-->\n" => array(
  808. '<!-- comment -->' => TRUE,
  809. "<!--\nThree.\n-->" => TRUE,
  810. ),
  811. // Resulting HTML should produce matching paragraph tags.
  812. '<p><div> </div></p>' => array(
  813. "<p>\n<div> </div>\n</p>" => TRUE,
  814. ),
  815. '<div><p> </p></div>' => array(
  816. "<div>\n</div>" => TRUE,
  817. ),
  818. '<blockquote><pre>aaa</pre></blockquote>' => array(
  819. "<blockquote><pre>aaa</pre></blockquote>" => TRUE,
  820. ),
  821. "<pre>aaa\nbbb\nccc</pre>\nddd\neee" => array(
  822. "<pre>aaa\nbbb\nccc</pre>" => TRUE,
  823. "<p>ddd<br />\neee</p>" => TRUE,
  824. ),
  825. // Comments remain unchanged and subsequent lines/paragraphs are
  826. // transformed normally.
  827. "aaa<!--comment-->\n\nbbb\n\nccc\n\nddd<!--comment\nwith linebreak-->\n\neee\n\nfff" => array(
  828. "<p>aaa</p>\n<!--comment--><p>\nbbb</p>\n<p>ccc</p>\n<p>ddd</p>" => TRUE,
  829. "<!--comment\nwith linebreak--><p>\neee</p>\n<p>fff</p>" => TRUE,
  830. ),
  831. // Check that a comment in a PRE will result that the text after
  832. // the comment, but still in PRE, is not transformed.
  833. "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>\nddd" => array(
  834. "<pre>aaa\nbbb<!-- comment -->\n\nccc</pre>" => TRUE,
  835. ),
  836. // Bug 810824, paragraphs were appearing around iframe tags.
  837. "<iframe>aaa</iframe>\n\n" => array(
  838. "<p><iframe>aaa</iframe></p>" => FALSE,
  839. ),
  840. );
  841. $this->assertFilteredString($filter, $tests);
  842. // Very long string hitting PCRE limits.
  843. $limit = max(ini_get('pcre.backtrack_limit'), ini_get('pcre.recursion_limit'));
  844. $source = $this->randomName($limit);
  845. $result = _filter_autop($source);
  846. $success = $this->assertEqual($result, '<p>' . $source . "</p>\n", 'Line break filter can process very long strings.');
  847. if (!$success) {
  848. $this->verbose("\n" . $source . "\n<hr />\n" . $result);
  849. }
  850. }
  851. /**
  852. * Tests limiting allowed tags and XSS prevention.
  853. *
  854. * XSS tests assume that script is disallowed by default and src is allowed
  855. * by default, but on* and style attributes are disallowed.
  856. *
  857. * Script injection vectors mostly adopted from http://ha.ckers.org/xss.html.
  858. *
  859. * Relevant CVEs:
  860. * - CVE-2002-1806, ~CVE-2005-0682, ~CVE-2005-2106, CVE-2005-3973,
  861. * CVE-2006-1226 (= rev. 1.112?), CVE-2008-0273, CVE-2008-3740.
  862. */
  863. function testFilterXSS() {
  864. // Tag stripping, different ways to work around removal of HTML tags.
  865. $f = filter_xss('<script>alert(0)</script>');
  866. $this->assertNoNormalized($f, 'script', 'HTML tag stripping -- simple script without special characters.');
  867. $f = filter_xss('<script src="http://www.example.com" />');
  868. $this->assertNoNormalized($f, 'script', 'HTML tag stripping -- empty script with source.');
  869. $f = filter_xss('<ScRipt sRc=http://www.example.com/>');
  870. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- varying case.');
  871. $f = filter_xss("<script\nsrc\n=\nhttp://www.example.com/\n>");
  872. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- multiline tag.');
  873. $f = filter_xss('<script/a src=http://www.example.com/a.js></script>');
  874. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- non whitespace character after tag name.');
  875. $f = filter_xss('<script/src=http://www.example.com/a.js></script>');
  876. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no space between tag and attribute.');
  877. // Null between < and tag name works at least with IE6.
  878. $f = filter_xss("<\0scr\0ipt>alert(0)</script>");
  879. $this->assertNoNormalized($f, 'ipt', 'HTML tag stripping evasion -- breaking HTML with nulls.');
  880. $f = filter_xss("<scrscriptipt src=http://www.example.com/a.js>");
  881. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- filter just removing "script".');
  882. $f = filter_xss('<<script>alert(0);//<</script>');
  883. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- double opening brackets.');
  884. $f = filter_xss('<script src=http://www.example.com/a.js?<b>');
  885. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no closing tag.');
  886. // DRUPAL-SA-2008-047: This doesn't seem exploitable, but the filter should
  887. // work consistently.
  888. $f = filter_xss('<script>>');
  889. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- double closing tag.');
  890. $f = filter_xss('<script src=//www.example.com/.a>');
  891. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no scheme or ending slash.');
  892. $f = filter_xss('<script src=http://www.example.com/.a');
  893. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- no closing bracket.');
  894. $f = filter_xss('<script src=http://www.example.com/ <');
  895. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- opening instead of closing bracket.');
  896. $f = filter_xss('<nosuchtag attribute="newScriptInjectionVector">');
  897. $this->assertNoNormalized($f, 'nosuchtag', 'HTML tag stripping evasion -- unknown tag.');
  898. $f = filter_xss('<?xml:namespace ns="urn:schemas-microsoft-com:time">');
  899. $this->assertTrue(stripos($f, '<?xml') === FALSE, 'HTML tag stripping evasion -- starting with a question sign (processing instructions).');
  900. $f = filter_xss('<t:set attributeName="innerHTML" to="&lt;script defer&gt;alert(0)&lt;/script&gt;">');
  901. $this->assertNoNormalized($f, 't:set', 'HTML tag stripping evasion -- colon in the tag name (namespaces\' tricks).');
  902. $f = filter_xss('<img """><script>alert(0)</script>', array('img'));
  903. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- a malformed image tag.');
  904. $f = filter_xss('<blockquote><script>alert(0)</script></blockquote>', array('blockquote'));
  905. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- script in a blockqoute.');
  906. $f = filter_xss("<!--[if true]><script>alert(0)</script><![endif]-->");
  907. $this->assertNoNormalized($f, 'script', 'HTML tag stripping evasion -- script within a comment.');
  908. // Dangerous attributes removal.
  909. $f = filter_xss('<p onmouseover="http://www.example.com/">', array('p'));
  910. $this->assertNoNormalized($f, 'onmouseover', 'HTML filter attributes removal -- events, no evasion.');
  911. $f = filter_xss('<li style="list-style-image: url(javascript:alert(0))">', array('li'));
  912. $this->assertNoNormalized($f, 'style', 'HTML filter attributes removal -- style, no evasion.');
  913. $f = filter_xss('<img onerror =alert(0)>', array('img'));
  914. $this->assertNoNormalized($f, 'onerror', 'HTML filter attributes removal evasion -- spaces before equals sign.');
  915. $f = filter_xss('<img onabort!#$%&()*~+-_.,:;?@[/|\]^`=alert(0)>', array('img'));
  916. $this->assertNoNormalized($f, 'onabort', 'HTML filter attributes removal evasion -- non alphanumeric characters before equals sign.');
  917. $f = filter_xss('<img oNmediAError=alert(0)>', array('img'));
  918. $this->assertNoNormalized($f, 'onmediaerror', 'HTML filter attributes removal evasion -- varying case.');
  919. // Works at least with IE6.
  920. $f = filter_xss("<img o\0nfocus\0=alert(0)>", array('img'));
  921. $this->assertNoNormalized($f, 'focus', 'HTML filter attributes removal evasion -- breaking with nulls.');
  922. // Only whitelisted scheme names allowed in attributes.
  923. $f = filter_xss('<img src="javascript:alert(0)">', array('img'));
  924. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- no evasion.');
  925. $f = filter_xss('<img src=javascript:alert(0)>', array('img'));
  926. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- no quotes.');
  927. // A bit like CVE-2006-0070.
  928. $f = filter_xss('<img src="javascript:confirm(0)">', array('img'));
  929. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- no alert ;)');
  930. $f = filter_xss('<img src=`javascript:alert(0)`>', array('img'));
  931. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- grave accents.');
  932. $f = filter_xss('<img dynsrc="javascript:alert(0)">', array('img'));
  933. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- rare attribute.');
  934. $f = filter_xss('<table background="javascript:alert(0)">', array('table'));
  935. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- another tag.');
  936. $f = filter_xss('<base href="javascript:alert(0);//">', array('base'));
  937. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing -- one more attribute and tag.');
  938. $f = filter_xss('<img src="jaVaSCriPt:alert(0)">', array('img'));
  939. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- varying case.');
  940. $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'));
  941. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 decimal encoding.');
  942. $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'));
  943. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- long UTF-8 encoding.');
  944. $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'));
  945. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- UTF-8 hex encoding.');
  946. $f = filter_xss("<img src=\"jav\tascript:alert(0)\">", array('img'));
  947. $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an embedded tab.');
  948. $f = filter_xss('<img src="jav&#x09;ascript:alert(0)">', array('img'));
  949. $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded tab.');
  950. $f = filter_xss('<img src="jav&#x000000A;ascript:alert(0)">', array('img'));
  951. $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded newline.');
  952. // With &#xD; this test would fail, but the entity gets turned into
  953. // &amp;#xD;, so it's OK.
  954. $f = filter_xss('<img src="jav&#x0D;ascript:alert(0)">', array('img'));
  955. $this->assertNoNormalized($f, 'script', 'HTML scheme clearing evasion -- an encoded, embedded carriage return.');
  956. $f = filter_xss("<img src=\"\n\n\nj\na\nva\ns\ncript:alert(0)\">", array('img'));
  957. $this->assertNoNormalized($f, 'cript', 'HTML scheme clearing evasion -- broken into many lines.');
  958. $f = filter_xss("<img src=\"jav\0a\0\0cript:alert(0)\">", array('img'));
  959. $this->assertNoNormalized($f, 'cript', 'HTML scheme clearing evasion -- embedded nulls.');
  960. // @todo This dataset currently fails under 5.4 because of
  961. // https://www.drupal.org/node/1210798. Restore after it's fixed.
  962. if (version_compare(PHP_VERSION, '5.4.0', '<')) {
  963. $f = filter_xss('<img src=" &#14; javascript:alert(0)">', array('img'));
  964. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
  965. }
  966. $f = filter_xss('<img src="vbscript:msgbox(0)">', array('img'));
  967. $this->assertNoNormalized($f, 'vbscript', 'HTML scheme clearing evasion -- another scheme.');
  968. $f = filter_xss('<img src="nosuchscheme:notice(0)">', array('img'));
  969. $this->assertNoNormalized($f, 'nosuchscheme', 'HTML scheme clearing evasion -- unknown scheme.');
  970. // Netscape 4.x javascript entities.
  971. $f = filter_xss('<br size="&{alert(0)}">', array('br'));
  972. $this->assertNoNormalized($f, 'alert', 'Netscape 4.x javascript entities.');
  973. // DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
  974. // Internet Explorer 6.
  975. $f = filter_xss("<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>", array('p'));
  976. $this->assertNoNormalized($f, 'style', 'HTML filter -- invalid UTF-8.');
  977. $f = filter_xss("\xc0aaa");
  978. $this->assertEqual($f, '', 'HTML filter -- overlong UTF-8 sequences.');
  979. $f = filter_xss("Who&#039;s Online");
  980. $this->assertNormalized($f, "who's online", 'HTML filter -- html entity number');
  981. $f = filter_xss("Who&amp;#039;s Online");
  982. $this->assertNormalized($f, "who&#039;s online", 'HTML filter -- encoded html entity number');
  983. $f = filter_xss("Who&amp;amp;#039; Online");
  984. $this->assertNormalized($f, "who&amp;#039; online", 'HTML filter -- double encoded html entity number');
  985. }
  986. /**
  987. * Tests filter settings, defaults, access restrictions and similar.
  988. *
  989. * @todo This is for functions like filter_filter and check_markup, whose
  990. * functionality is not completely focused on filtering. Some ideas:
  991. * restricting formats according to user permissions, proper cache
  992. * handling, defaults -- allowed tags/attributes/protocols.
  993. *
  994. * @todo It is possible to add script, iframe etc. to allowed tags, but this
  995. * makes HTML filter completely ineffective.
  996. *
  997. * @todo Class, id, name and xmlns should be added to disallowed attributes,
  998. * or better a whitelist approach should be used for that too.
  999. */
  1000. function testHtmlFilter() {
  1001. // Setup dummy filter object.
  1002. $filter = new stdClass();
  1003. $filter->settings = array(
  1004. 'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <test-element>',
  1005. 'filter_html_help' => 1,
  1006. 'filter_html_nofollow' => 0,
  1007. );
  1008. // HTML filter is not able to secure some tags, these should never be
  1009. // allowed.
  1010. $f = _filter_html('<script />', $filter);
  1011. $this->assertNoNormalized($f, 'script', 'HTML filter should always remove script tags.');
  1012. $f = _filter_html('<iframe />', $filter);
  1013. $this->assertNoNormalized($f, 'iframe', 'HTML filter should always remove iframe tags.');
  1014. $f = _filter_html('<object />', $filter);
  1015. $this->assertNoNormalized($f, 'object', 'HTML filter should always remove object tags.');
  1016. $f = _filter_html('<style />', $filter);
  1017. $this->assertNoNormalized($f, 'style', 'HTML filter should always remove style tags.');
  1018. // Some tags make CSRF attacks easier, let the user take the risk herself.
  1019. $f = _filter_html('<img />', $filter);
  1020. $this->assertNoNormalized($f, 'img', 'HTML filter should remove img tags on default.');
  1021. $f = _filter_html('<input />', $filter);
  1022. $this->assertNoNormalized($f, 'img', 'HTML filter should remove input tags on default.');
  1023. // Filtering content of some attributes is infeasible, these shouldn't be
  1024. // allowed too.
  1025. $f = _filter_html('<p style="display: none;" />', $filter);
  1026. $this->assertNoNormalized($f, 'style', 'HTML filter should remove style attribute on default.');
  1027. $f = _filter_html('<p onerror="alert(0);" />', $filter);
  1028. $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove on* attributes on default.');
  1029. $f = _filter_html('<code onerror>&nbsp;</code>', $filter);
  1030. $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove empty on* attributes on default.');
  1031. // Custom tags are supported and should be allowed through.
  1032. $f = _filter_html('<test-element></test-element>', $filter);
  1033. $this->assertNormalized($f, 'test-element', 'HTML filter should allow custom elements.');
  1034. }
  1035. /**
  1036. * Tests the spam deterrent.
  1037. */
  1038. function testNoFollowFilter() {
  1039. // Setup dummy filter object.
  1040. $filter = new stdClass();
  1041. $filter->settings = array(
  1042. 'allowed_html' => '<a>',
  1043. 'filter_html_help' => 1,
  1044. 'filter_html_nofollow' => 1,
  1045. );
  1046. // Test if the rel="nofollow" attribute is added, even if we try to prevent
  1047. // it.
  1048. $f = _filter_html('<a href="http://www.example.com/">text</a>', $filter);
  1049. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent -- no evasion.');
  1050. $f = _filter_html('<A href="http://www.example.com/">text</a>', $filter);
  1051. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- capital A.');
  1052. $f = _filter_html("<a/href=\"http://www.example.com/\">text</a>", $filter);
  1053. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- non whitespace character after tag name.');
  1054. $f = _filter_html("<\0a\0 href=\"http://www.example.com/\">text</a>", $filter);
  1055. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- some nulls.');
  1056. $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', $filter);
  1057. $this->assertNoNormalized($f, 'rel="follow"', 'Spam deterrent evasion -- with rel set - rel="follow" removed.');
  1058. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- with rel set - rel="nofollow" added.');
  1059. }
  1060. /**
  1061. * Tests the loose, admin HTML filter.
  1062. */
  1063. function testFilterXSSAdmin() {
  1064. // DRUPAL-SA-2008-044
  1065. $f = filter_xss_admin('<object />');
  1066. $this->assertNoNormalized($f, 'object', 'Admin HTML filter -- should not allow object tag.');
  1067. $f = filter_xss_admin('<script />');
  1068. $this->assertNoNormalized($f, 'script', 'Admin HTML filter -- should not allow script tag.');
  1069. $f = filter_xss_admin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
  1070. $this->assertEqual($f, '', 'Admin HTML filter -- should never allow some tags.');
  1071. }
  1072. /**
  1073. * Tests the HTML escaping filter.
  1074. *
  1075. * check_plain() is not tested here.
  1076. */
  1077. function testHtmlEscapeFilter() {
  1078. // Setup dummy filter object.
  1079. $filter = new stdClass();
  1080. $filter->callback = '_filter_html_escape';
  1081. $tests = array(
  1082. " One. <!-- \"comment\" --> Two'.\n<p>Three.</p>\n " => array(
  1083. "One. &lt;!-- &quot;comment&quot; --&gt; Two&#039;.\n&lt;p&gt;Three.&lt;/p&gt;" => TRUE,
  1084. ' One.' => FALSE,
  1085. "</p>\n " => FALSE,
  1086. ),
  1087. );
  1088. $this->assertFilteredString($filter, $tests);
  1089. }
  1090. /**
  1091. * Tests the URL filter.
  1092. */
  1093. function testUrlFilter() {
  1094. // Setup dummy filter object.
  1095. $filter = new stdClass();
  1096. $filter->callback = '_filter_url';
  1097. $filter->settings = array(
  1098. 'filter_url_length' => 496,
  1099. );
  1100. // @todo Possible categories:
  1101. // - absolute, mail, partial
  1102. // - characters/encoding, surrounding markup, security
  1103. // Create a e-mail that is too long.
  1104. $long_email = str_repeat('a', 254) . '@example.com';
  1105. $too_long_email = str_repeat('b', 255) . '@example.com';
  1106. $email_with_plus_sign = 'one+two@example.com';
  1107. // Filter selection/pattern matching.
  1108. $tests = array(
  1109. // HTTP URLs.
  1110. '
  1111. http://example.com or www.example.com
  1112. ' => array(
  1113. '<a href="http://example.com">http://example.com</a>' => TRUE,
  1114. '<a href="http://www.example.com">www.example.com</a>' => TRUE,
  1115. ),
  1116. // MAILTO URLs.
  1117. '
  1118. person@example.com or mailto:person2@example.com or ' . $email_with_plus_sign . ' or ' . $long_email . ' but not ' . $too_long_email . '
  1119. ' => array(
  1120. '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
  1121. '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
  1122. '<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
  1123. '<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
  1124. '<a href="mailto:' . $email_with_plus_sign . '">' . $email_with_plus_sign . '</a>' => TRUE,
  1125. ),
  1126. // URI parts and special characters.
  1127. '
  1128. http://trailingslash.com/ or www.trailingslash.com/
  1129. http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
  1130. http://twitter.com/#!/example/status/22376963142324226
  1131. ftp://user:pass@ftp.example.com/~home/dir1
  1132. sftp://user@nonstandardport:222/dir
  1133. ssh://192.168.0.100/srv/git/drupal.git
  1134. ' => array(
  1135. '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
  1136. '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
  1137. '<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,
  1138. '<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,
  1139. '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
  1140. '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
  1141. '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
  1142. '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
  1143. ),
  1144. // Encoding.
  1145. '
  1146. http://ampersand.com/?a=1&b=2
  1147. http://encoded.com/?a=1&amp;b=2
  1148. ' => array(
  1149. '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
  1150. '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
  1151. ),
  1152. // Domain name length.
  1153. '
  1154. www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
  1155. me@me.tv
  1156. ' => array(
  1157. '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
  1158. '<a href="http://www.example.example">www.example.example</a>' => TRUE,
  1159. 'http://www.toolong' => FALSE,
  1160. '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
  1161. ),
  1162. // Absolute URL protocols.
  1163. // The list to test is found in the beginning of _filter_url() at
  1164. // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
  1165. '
  1166. https://example.com,
  1167. ftp://ftp.example.com,
  1168. news://example.net,
  1169. telnet://example,
  1170. irc://example.host,
  1171. ssh://odd.geek,
  1172. sftp://secure.host?,
  1173. webcal://calendar,
  1174. rtsp://127.0.0.1,
  1175. not foo://disallowed.com.
  1176. ' => array(
  1177. 'href="https://example.com"' => TRUE,
  1178. 'href="ftp://ftp.example.com"' => TRUE,
  1179. 'href="news://example.net"' => TRUE,
  1180. 'href="telnet://example"' => TRUE,
  1181. 'href="irc://example.host"' => TRUE,
  1182. 'href="ssh://odd.geek"' => TRUE,
  1183. 'href="sftp://secure.host"' => TRUE,
  1184. 'href="webcal://calendar"' => TRUE,
  1185. 'href="rtsp://127.0.0.1"' => TRUE,
  1186. 'href="foo://disallowed.com"' => FALSE,
  1187. 'not foo://disallowed.com.' => TRUE,
  1188. ),
  1189. );
  1190. $this->assertFilteredString($filter, $tests);
  1191. // Surrounding text/punctuation.
  1192. $tests = array(
  1193. '
  1194. Partial URL with trailing period www.partial.com.
  1195. E-mail with trailing comma person@example.com,
  1196. Absolute URL with trailing question http://www.absolute.com?
  1197. Query string with trailing exclamation www.query.com/index.php?a=!
  1198. Partial URL with 3 trailing www.partial.periods...
  1199. E-mail with 3 trailing exclamations@example.com!!!
  1200. Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
  1201. ' => array(
  1202. 'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
  1203. 'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
  1204. 'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
  1205. 'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
  1206. 'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
  1207. 'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
  1208. 'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
  1209. ),
  1210. '
  1211. (www.parenthesis.com/dir?a=1&b=2#a)
  1212. ' => array(
  1213. '(<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,
  1214. ),
  1215. );
  1216. $this->assertFilteredString($filter, $tests);
  1217. // Surrounding markup.
  1218. $tests = array(
  1219. '
  1220. <p xmlns="www.namespace.com" />
  1221. <p xmlns="http://namespace.com">
  1222. An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
  1223. </p>
  1224. ' => array(
  1225. '<p xmlns="www.namespace.com" />' => TRUE,
  1226. '<p xmlns="http://namespace.com">' => TRUE,
  1227. 'href="http://www.namespace.com"' => FALSE,
  1228. 'href="http://namespace.com"' => FALSE,
  1229. 'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
  1230. ),
  1231. '
  1232. Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
  1233. but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
  1234. ' => array(
  1235. '<a href="foo">www.relative.com</a>' => TRUE,
  1236. 'href="http://www.relative.com"' => FALSE,
  1237. '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
  1238. '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
  1239. '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
  1240. ),
  1241. '
  1242. Test <code>using www.example.com the code tag</code>.
  1243. ' => array(
  1244. 'href' => FALSE,
  1245. 'http' => FALSE,
  1246. ),
  1247. '
  1248. Intro.
  1249. <blockquote>
  1250. 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>.
  1251. </blockquote>
  1252. Outro.
  1253. ' => array(
  1254. 'href="http://www.example.com"' => TRUE,
  1255. 'href="mailto:person@example.com"' => TRUE,
  1256. 'href="http://origin.example.com"' => TRUE,
  1257. 'http://www.usage.example.com' => FALSE,
  1258. 'http://www.example.info' => FALSE,
  1259. 'Intro.' => TRUE,
  1260. 'Outro.' => TRUE,
  1261. ),
  1262. '
  1263. 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>
  1264. ' => array(
  1265. 'href="http://www.example.com"' => TRUE,
  1266. 'href="http://www.example.pooh"' => TRUE,
  1267. ),
  1268. '
  1269. <p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
  1270. It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
  1271. 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.
  1272. ' => array(
  1273. 'href="http://www.example17.com"' => TRUE,
  1274. 'href="http://www.example18.com"' => TRUE,
  1275. 'href="http://www.example19.com"' => TRUE,
  1276. 'href="http://www.example20.com"' => TRUE,
  1277. 'href="http://www.example21.com"' => TRUE,
  1278. 'href="mailto:person@example22.com"' => TRUE,
  1279. 'href="http://www.example23.com"' => TRUE,
  1280. 'href="http://www.example24.com"' => TRUE,
  1281. 'href="http://www.example25.com"' => TRUE,
  1282. 'href="http://www.example26.com"' => TRUE,
  1283. 'href="mailto:person@example27.com"' => TRUE,
  1284. 'href="http://www.example28.com"' => TRUE,
  1285. ),
  1286. '
  1287. <script>
  1288. <!--
  1289. // @see www.example.com
  1290. var exampleurl = "http://example.net";
  1291. -->
  1292. <!--//--><![CDATA[//><!--
  1293. // @see www.example.com
  1294. var exampleurl = "http://example.net";
  1295. //--><!]]>
  1296. </script>
  1297. ' => array(
  1298. 'href="http://www.example.com"' => FALSE,
  1299. 'href="http://example.net"' => FALSE,
  1300. ),
  1301. '
  1302. <style>body {
  1303. background: url(http://example.com/pixel.gif);
  1304. }</style>
  1305. ' => array(
  1306. 'href' => FALSE,
  1307. ),
  1308. '
  1309. <!-- Skip any URLs like www.example.com in comments -->
  1310. ' => array(
  1311. 'href' => FALSE,
  1312. ),
  1313. '
  1314. <!-- Skip any URLs like
  1315. www.example.com with a newline in comments -->
  1316. ' => array(
  1317. 'href' => FALSE,
  1318. ),
  1319. '
  1320. <!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
  1321. ' => array(
  1322. 'href' => FALSE,
  1323. ),
  1324. '
  1325. <dl>
  1326. <dt>www.example.com</dt>
  1327. <dd>http://example.com</dd>
  1328. <dd>person@example.com</dd>
  1329. <dt>Check www.example.net</dt>
  1330. <dd>Some text around http://www.example.info by person@example.info?</dd>
  1331. </dl>
  1332. ' => array(
  1333. 'href="http://www.example.com"' => TRUE,
  1334. 'href="http://example.com"' => TRUE,
  1335. 'href="mailto:person@example.com"' => TRUE,
  1336. 'href="http://www.example.net"' => TRUE,
  1337. 'href="http://www.example.info"' => TRUE,
  1338. 'href="mailto:person@example.info"' => TRUE,
  1339. ),
  1340. '
  1341. <div>www.div.com</div>
  1342. <ul>
  1343. <li>http://listitem.com</li>
  1344. <li class="odd">www.class.listitem.com</li>
  1345. </ul>
  1346. ' => array(
  1347. '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
  1348. '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
  1349. '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
  1350. ),
  1351. );
  1352. $this->assertFilteredString($filter, $tests);
  1353. // URL trimming.
  1354. $filter->settings['filter_url_length'] = 20;
  1355. $tests = array(
  1356. 'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
  1357. '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
  1358. ),
  1359. );
  1360. $this->assertFilteredString($filter, $tests);
  1361. }
  1362. /**
  1363. * Asserts multiple filter output expectations for multiple input strings.
  1364. *
  1365. * @param $filter
  1366. * A input filter object.
  1367. * @param $tests
  1368. * An associative array, whereas each key is an arbitrary input string and
  1369. * each value is again an associative array whose keys are filter output
  1370. * strings and whose values are Booleans indicating whether the output is
  1371. * expected or not.
  1372. *
  1373. * For example:
  1374. * @code
  1375. * $tests = array(
  1376. * 'Input string' => array(
  1377. * '<p>Input string</p>' => TRUE,
  1378. * 'Input string<br' => FALSE,
  1379. * ),
  1380. * );
  1381. * @endcode
  1382. */
  1383. function assertFilteredString($filter, $tests) {
  1384. foreach ($tests as $source => $tasks) {
  1385. $function = $filter->callback;
  1386. $result = $function($source, $filter);
  1387. foreach ($tasks as $value => $is_expected) {
  1388. // Not using assertIdentical, since combination with strpos() is hard to grok.
  1389. if ($is_expected) {
  1390. $success = $this->assertTrue(strpos($result, $value) !== FALSE, format_string('@source: @value found.', array(
  1391. '@source' => var_export($source, TRUE),
  1392. '@value' => var_export($value, TRUE),
  1393. )));
  1394. }
  1395. else {
  1396. $success = $this->assertTrue(strpos($result, $value) === FALSE, format_string('@source: @value not found.', array(
  1397. '@source' => var_export($source, TRUE),
  1398. '@value' => var_export($value, TRUE),
  1399. )));
  1400. }
  1401. if (!$success) {
  1402. $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
  1403. . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
  1404. . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
  1405. . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
  1406. );
  1407. }
  1408. }
  1409. }
  1410. }
  1411. /**
  1412. * Tests URL filter on longer content.
  1413. *
  1414. * Filters based on regular expressions should also be tested with a more
  1415. * complex content than just isolated test lines.
  1416. * The most common errors are:
  1417. * - accidental '*' (greedy) match instead of '*?' (minimal) match.
  1418. * - only matching first occurrence instead of all.
  1419. * - newlines not matching '.*'.
  1420. *
  1421. * This test covers:
  1422. * - Document with multiple newlines and paragraphs (two newlines).
  1423. * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
  1424. * comments.
  1425. * - Empty HTML tags (BR, IMG).
  1426. * - Mix of absolute and partial URLs, and e-mail addresses in one content.
  1427. */
  1428. function testUrlFilterContent() {
  1429. // Setup dummy filter object.
  1430. $filter = new stdClass();
  1431. $filter->settings = array(
  1432. 'filter_url_length' => 496,
  1433. );
  1434. $path = drupal_get_path('module', 'filter') . '/tests';
  1435. $input = file_get_contents($path . '/filter.url-input.txt');
  1436. $expected = file_get_contents($path . '/filter.url-output.txt');
  1437. $result = _filter_url($input, $filter);
  1438. $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
  1439. }
  1440. /**
  1441. * Tests the HTML corrector filter.
  1442. *
  1443. * @todo This test could really use some validity checking function.
  1444. */
  1445. function testHtmlCorrectorFilter() {
  1446. // Tag closing.
  1447. $f = _filter_htmlcorrector('<p>text');
  1448. $this->assertEqual($f, '<p>text</p>', 'HTML corrector -- tag closing at the end of input.');
  1449. $f = _filter_htmlcorrector('<p>text<p><p>text');
  1450. $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', 'HTML corrector -- tag closing.');
  1451. $f = _filter_htmlcorrector("<ul><li>e1<li>e2");
  1452. $this->assertEqual($f, "<ul><li>e1</li><li>e2</li></ul>", 'HTML corrector -- unclosed list tags.');
  1453. $f = _filter_htmlcorrector('<div id="d">content');
  1454. $this->assertEqual($f, '<div id="d">content</div>', 'HTML corrector -- unclosed tag with attribute.');
  1455. // XHTML slash for empty elements.
  1456. $f = _filter_htmlcorrector('<hr><br>');
  1457. $this->assertEqual($f, '<hr /><br />', 'HTML corrector -- XHTML closing slash.');
  1458. $f = _filter_htmlcorrector('<P>test</P>');
  1459. $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
  1460. $f = _filter_htmlcorrector('<P>test</p>');
  1461. $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
  1462. $f = _filter_htmlcorrector('test<hr />');
  1463. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through.');
  1464. $f = _filter_htmlcorrector('test<hr/>');
  1465. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there is a single space before the closing slash.');
  1466. $f = _filter_htmlcorrector('test<hr />');
  1467. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there are not too many spaces before the closing slash.');
  1468. $f = _filter_htmlcorrector('<span class="test" />');
  1469. $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.');
  1470. $f = _filter_htmlcorrector('test1<br class="test">test2');
  1471. $this->assertEqual($f, 'test1<br class="test" />test2', 'HTML corrector -- Automatically close single tags.');
  1472. $f = _filter_htmlcorrector('line1<hr>line2');
  1473. $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
  1474. $f = _filter_htmlcorrector('line1<HR>line2');
  1475. $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
  1476. $f = _filter_htmlcorrector('<img src="http://example.com/test.jpg">test</img>');
  1477. $this->assertEqual($f, '<img src="http://example.com/test.jpg" />test', 'HTML corrector -- Automatically close single tags.');
  1478. $f = _filter_htmlcorrector('<br></br>');
  1479. $this->assertEqual($f, '<br />', "HTML corrector -- Transform empty tags to a single closed tag if the tag's content model is EMPTY.");
  1480. $f = _filter_htmlcorrector('<div></div>');
  1481. $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.");
  1482. $f = _filter_htmlcorrector('<p>line1<br/><hr/>line2</p>');
  1483. $this->assertEqual($f, '<p>line1<br /></p><hr />line2', 'HTML corrector -- Move non-inline elements outside of inline containers.');
  1484. $f = _filter_htmlcorrector('<p>line1<div>line2</div></p>');
  1485. $this->assertEqual($f, '<p>line1</p><div>line2</div>', 'HTML corrector -- Move non-inline elements outside of inline containers.');
  1486. $f = _filter_htmlcorrector('<p>test<p>test</p>\n');
  1487. $this->assertEqual($f, '<p>test</p><p>test</p>\n', 'HTML corrector -- Auto-close improperly nested tags.');
  1488. $f = _filter_htmlcorrector('<p>Line1<br><STRONG>bold stuff</b>');
  1489. $this->assertEqual($f, '<p>Line1<br /><strong>bold stuff</strong></p>', 'HTML corrector -- Properly close unclosed tags, and remove useless closing tags.');
  1490. $f = _filter_htmlcorrector('test <!-- this is a comment -->');
  1491. $this->assertEqual($f, 'test <!-- this is a comment -->', 'HTML corrector -- Do not touch HTML comments.');
  1492. $f = _filter_htmlcorrector('test <!--this is a comment-->');
  1493. $this->assertEqual($f, 'test <!--this is a comment-->', 'HTML corrector -- Do not touch HTML comments.');
  1494. $f = _filter_htmlcorrector('test <!-- comment <p>another
  1495. <strong>multiple</strong> line
  1496. comment</p> -->');
  1497. $this->assertEqual($f, 'test <!-- comment <p>another
  1498. <strong>multiple</strong> line
  1499. comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
  1500. $f = _filter_htmlcorrector('test <!-- comment <p>another comment</p> -->');
  1501. $this->assertEqual($f, 'test <!-- comment <p>another comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
  1502. $f = _filter_htmlcorrector('test <!--break-->');
  1503. $this->assertEqual($f, 'test <!--break-->', 'HTML corrector -- Do not touch HTML comments.');
  1504. $f = _filter_htmlcorrector('<p>test\n</p>\n');
  1505. $this->assertEqual($f, '<p>test\n</p>\n', 'HTML corrector -- New-lines are accepted and kept as-is.');
  1506. $f = _filter_htmlcorrector('<p>دروبال');
  1507. $this->assertEqual($f, '<p>دروبال</p>', 'HTML corrector -- Encoding is correctly kept.');
  1508. $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
  1509. $this->assertEqual($f, '<script type="text/javascript">
  1510. <!--//--><![CDATA[// ><!--
  1511. alert("test")
  1512. //--><!]]>
  1513. </script>', 'HTML corrector -- CDATA added to script element');
  1514. $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
  1515. $this->assertEqual($f, '<p><script type="text/javascript">
  1516. <!--//--><![CDATA[// ><!--
  1517. alert("test")
  1518. //--><!]]>
  1519. </script></p>', 'HTML corrector -- CDATA added to a nested script element');
  1520. $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
  1521. $this->assertEqual($f, '<p><style>
  1522. <!--/*--><![CDATA[/* ><!--*/
  1523. /* Styling */ body {color:red}
  1524. /*--><!]]>*/
  1525. </style></p>', 'HTML corrector -- CDATA added to a style element.');
  1526. $filtered_data = _filter_htmlcorrector('<p><style>
  1527. /*<![CDATA[*/
  1528. /* Styling */
  1529. body {color:red}
  1530. /*]]>*/
  1531. </style></p>');
  1532. $this->assertEqual($filtered_data, '<p><style>
  1533. <!--/*--><![CDATA[/* ><!--*/
  1534. /*<![CDATA[*/
  1535. /* Styling */
  1536. body {color:red}
  1537. /*]]]]><![CDATA[>*/
  1538. /*--><!]]>*/
  1539. </style></p>',
  1540. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
  1541. );
  1542. $filtered_data = _filter_htmlcorrector('<p><style>
  1543. <!--/*--><![CDATA[/* ><!--*/
  1544. /* Styling */
  1545. body {color:red}
  1546. /*--><!]]>*/
  1547. </style></p>');
  1548. $this->assertEqual($filtered_data, '<p><style>
  1549. <!--/*--><![CDATA[/* ><!--*/
  1550. <!--/*--><![CDATA[/* ><!--*/
  1551. /* Styling */
  1552. body {color:red}
  1553. /*--><!]]]]><![CDATA[>*/
  1554. /*--><!]]>*/
  1555. </style></p>',
  1556. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
  1557. );
  1558. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1559. <!--//--><![CDATA[// ><!--
  1560. alert("test");
  1561. //--><!]]>
  1562. </script></p>');
  1563. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1564. <!--//--><![CDATA[// ><!--
  1565. <!--//--><![CDATA[// ><!--
  1566. alert("test");
  1567. //--><!]]]]><![CDATA[>
  1568. //--><!]]>
  1569. </script></p>',
  1570. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
  1571. );
  1572. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1573. // <![CDATA[
  1574. alert("test");
  1575. // ]]>
  1576. </script></p>');
  1577. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1578. <!--//--><![CDATA[// ><!--
  1579. // <![CDATA[
  1580. alert("test");
  1581. // ]]]]><![CDATA[>
  1582. //--><!]]>
  1583. </script></p>',
  1584. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
  1585. );
  1586. }
  1587. /**
  1588. * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
  1589. *
  1590. * Otherwise fails the test with a given message, similar to all the
  1591. * SimpleTest assert* functions.
  1592. *
  1593. * Note that this does not remove nulls, new lines and other characters that
  1594. * could be used to obscure a tag or an attribute name.
  1595. *
  1596. * @param $haystack
  1597. * Text to look in.
  1598. * @param $needle
  1599. * Lowercase, plain text to look for.
  1600. * @param $message
  1601. * (optional) Message to display if failed. Defaults to an empty string.
  1602. * @param $group
  1603. * (optional) The group this message belongs to. Defaults to 'Other'.
  1604. * @return
  1605. * TRUE on pass, FALSE on fail.
  1606. */
  1607. function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1608. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
  1609. }
  1610. /**
  1611. * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
  1612. *
  1613. * Otherwise fails the test with a given message, similar to all the
  1614. * SimpleTest assert* functions.
  1615. *
  1616. * Note that this does not remove nulls, new lines, and other character that
  1617. * could be used to obscure a tag or an attribute name.
  1618. *
  1619. * @param $haystack
  1620. * Text to look in.
  1621. * @param $needle
  1622. * Lowercase, plain text to look for.
  1623. * @param $message
  1624. * (optional) Message to display if failed. Defaults to an empty string.
  1625. * @param $group
  1626. * (optional) The group this message belongs to. Defaults to 'Other'.
  1627. * @return
  1628. * TRUE on pass, FALSE on fail.
  1629. */
  1630. function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1631. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
  1632. }
  1633. }
  1634. /**
  1635. * Tests for Filter's hook invocations.
  1636. */
  1637. class FilterHooksTestCase extends DrupalWebTestCase {
  1638. public static function getInfo() {
  1639. return array(
  1640. 'name' => 'Filter format hooks',
  1641. 'description' => 'Test hooks for text formats insert/update/disable.',
  1642. 'group' => 'Filter',
  1643. );
  1644. }
  1645. function setUp() {
  1646. parent::setUp('block', 'filter_test');
  1647. $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
  1648. $this->drupalLogin($admin_user);
  1649. }
  1650. /**
  1651. * Tests hooks on format management.
  1652. *
  1653. * Tests that hooks run correctly on creating, editing, and deleting a text
  1654. * format.
  1655. */
  1656. function testFilterHooks() {
  1657. // Add a text format.
  1658. $name = $this->randomName();
  1659. $edit = array();
  1660. $edit['format'] = drupal_strtolower($this->randomName());
  1661. $edit['name'] = $name;
  1662. $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 1;
  1663. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  1664. $this->assertRaw(t('Added text format %format.', array('%format' => $name)), 'New format created.');
  1665. $this->assertText('hook_filter_format_insert invoked.', 'hook_filter_format_insert was invoked.');
  1666. $format_id = $edit['format'];
  1667. // Update text format.
  1668. $edit = array();
  1669. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
  1670. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  1671. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), 'Format successfully updated.');
  1672. $this->assertText('hook_filter_format_update invoked.', 'hook_filter_format_update() was invoked.');
  1673. // Add a new custom block.
  1674. $custom_block = array();
  1675. $custom_block['info'] = $this->randomName(8);
  1676. $custom_block['title'] = $this->randomName(8);
  1677. $custom_block['body[value]'] = $this->randomName(32);
  1678. // Use the format created.
  1679. $custom_block['body[format]'] = $format_id;
  1680. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  1681. $this->assertText(t('The block has been created.'), 'New block successfully created.');
  1682. // Verify the new block is in the database.
  1683. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  1684. $this->assertNotNull($bid, 'New block found in database');
  1685. // Disable the text format.
  1686. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  1687. $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), 'Format successfully disabled.');
  1688. $this->assertText('hook_filter_format_disable invoked.', 'hook_filter_format_disable() was invoked.');
  1689. }
  1690. }
  1691. /**
  1692. * Tests filter settings.
  1693. */
  1694. class FilterSettingsTestCase extends DrupalWebTestCase {
  1695. /**
  1696. * The installation profile to use with this test class.
  1697. *
  1698. * @var string
  1699. */
  1700. protected $profile = 'testing';
  1701. public static function getInfo() {
  1702. return array(
  1703. 'name' => 'Filter settings',
  1704. 'description' => 'Tests filter settings.',
  1705. 'group' => 'Filter',
  1706. );
  1707. }
  1708. /**
  1709. * Tests explicit and implicit default settings for filters.
  1710. */
  1711. function testFilterDefaults() {
  1712. $filter_info = filter_filter_info();
  1713. $filters = array_fill_keys(array_keys($filter_info), array());
  1714. // Create text format using filter default settings.
  1715. $filter_defaults_format = (object) array(
  1716. 'format' => 'filter_defaults',
  1717. 'name' => 'Filter defaults',
  1718. 'filters' => $filters,
  1719. );
  1720. filter_format_save($filter_defaults_format);
  1721. // Verify that default weights defined in hook_filter_info() were applied.
  1722. $saved_settings = array();
  1723. foreach ($filter_defaults_format->filters as $name => $settings) {
  1724. $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
  1725. $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
  1726. '@name' => $name,
  1727. '%saved' => $settings['weight'],
  1728. '%default' => $expected_weight,
  1729. )));
  1730. $saved_settings[$name]['weight'] = $expected_weight;
  1731. }
  1732. // Re-save the text format.
  1733. filter_format_save($filter_defaults_format);
  1734. // Reload it from scratch.
  1735. filter_formats_reset();
  1736. $filter_defaults_format = filter_format_load($filter_defaults_format->format);
  1737. $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
  1738. // Verify that saved filter settings have not been changed.
  1739. foreach ($filter_defaults_format->filters as $name => $settings) {
  1740. $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
  1741. '@name' => $name,
  1742. '%saved' => $settings->weight,
  1743. '%previous' => $saved_settings[$name]['weight'],
  1744. )));
  1745. }
  1746. }
  1747. }
  1748. /**
  1749. * Tests DOMDocument serialization.
  1750. */
  1751. class FilterDOMSerializeTestCase extends DrupalWebTestCase {
  1752. public static function getInfo() {
  1753. return array(
  1754. 'name' => 'Serialization',
  1755. 'description' => 'Test serialization of DOMDocument objects.',
  1756. 'group' => 'Filter',
  1757. );
  1758. }
  1759. /**
  1760. * Tests empty DOMDocument object.
  1761. */
  1762. function testFilterEmptyDOMSerialization() {
  1763. $document = new DOMDocument();
  1764. $result = filter_dom_serialize($document);
  1765. $this->assertEqual('', $result);
  1766. }
  1767. }