filter.test 88 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031
  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. $f = filter_xss('<img src=" &#14; javascript:alert(0)">', array('img'));
  961. $this->assertNoNormalized($f, 'javascript', 'HTML scheme clearing evasion -- spaces and metacharacters before scheme.');
  962. $f = filter_xss('<img src="vbscript:msgbox(0)">', array('img'));
  963. $this->assertNoNormalized($f, 'vbscript', 'HTML scheme clearing evasion -- another scheme.');
  964. $f = filter_xss('<img src="nosuchscheme:notice(0)">', array('img'));
  965. $this->assertNoNormalized($f, 'nosuchscheme', 'HTML scheme clearing evasion -- unknown scheme.');
  966. // Netscape 4.x javascript entities.
  967. $f = filter_xss('<br size="&{alert(0)}">', array('br'));
  968. $this->assertNoNormalized($f, 'alert', 'Netscape 4.x javascript entities.');
  969. // DRUPAL-SA-2008-006: Invalid UTF-8, these only work as reflected XSS with
  970. // Internet Explorer 6.
  971. $f = filter_xss("<p arg=\"\xe0\">\" style=\"background-image: url(javascript:alert(0));\"\xe0<p>", array('p'));
  972. $this->assertNoNormalized($f, 'style', 'HTML filter -- invalid UTF-8.');
  973. $f = filter_xss("\xc0aaa");
  974. $this->assertEqual($f, '', 'HTML filter -- overlong UTF-8 sequences.');
  975. $f = filter_xss("Who&#039;s Online");
  976. $this->assertNormalized($f, "who's online", 'HTML filter -- html entity number');
  977. $f = filter_xss("Who&amp;#039;s Online");
  978. $this->assertNormalized($f, "who&#039;s online", 'HTML filter -- encoded html entity number');
  979. $f = filter_xss("Who&amp;amp;#039; Online");
  980. $this->assertNormalized($f, "who&amp;#039; online", 'HTML filter -- double encoded html entity number');
  981. }
  982. /**
  983. * Tests filter settings, defaults, access restrictions and similar.
  984. *
  985. * @todo This is for functions like filter_filter and check_markup, whose
  986. * functionality is not completely focused on filtering. Some ideas:
  987. * restricting formats according to user permissions, proper cache
  988. * handling, defaults -- allowed tags/attributes/protocols.
  989. *
  990. * @todo It is possible to add script, iframe etc. to allowed tags, but this
  991. * makes HTML filter completely ineffective.
  992. *
  993. * @todo Class, id, name and xmlns should be added to disallowed attributes,
  994. * or better a whitelist approach should be used for that too.
  995. */
  996. function testHtmlFilter() {
  997. // Setup dummy filter object.
  998. $filter = new stdClass();
  999. $filter->settings = array(
  1000. 'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <test-element>',
  1001. 'filter_html_help' => 1,
  1002. 'filter_html_nofollow' => 0,
  1003. );
  1004. // HTML filter is not able to secure some tags, these should never be
  1005. // allowed.
  1006. $f = _filter_html('<script />', $filter);
  1007. $this->assertNoNormalized($f, 'script', 'HTML filter should always remove script tags.');
  1008. $f = _filter_html('<iframe />', $filter);
  1009. $this->assertNoNormalized($f, 'iframe', 'HTML filter should always remove iframe tags.');
  1010. $f = _filter_html('<object />', $filter);
  1011. $this->assertNoNormalized($f, 'object', 'HTML filter should always remove object tags.');
  1012. $f = _filter_html('<style />', $filter);
  1013. $this->assertNoNormalized($f, 'style', 'HTML filter should always remove style tags.');
  1014. // Some tags make CSRF attacks easier, let the user take the risk herself.
  1015. $f = _filter_html('<img />', $filter);
  1016. $this->assertNoNormalized($f, 'img', 'HTML filter should remove img tags on default.');
  1017. $f = _filter_html('<input />', $filter);
  1018. $this->assertNoNormalized($f, 'img', 'HTML filter should remove input tags on default.');
  1019. // Filtering content of some attributes is infeasible, these shouldn't be
  1020. // allowed too.
  1021. $f = _filter_html('<p style="display: none;" />', $filter);
  1022. $this->assertNoNormalized($f, 'style', 'HTML filter should remove style attribute on default.');
  1023. $f = _filter_html('<p onerror="alert(0);" />', $filter);
  1024. $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove on* attributes on default.');
  1025. $f = _filter_html('<code onerror>&nbsp;</code>', $filter);
  1026. $this->assertNoNormalized($f, 'onerror', 'HTML filter should remove empty on* attributes on default.');
  1027. // Custom tags are supported and should be allowed through.
  1028. $f = _filter_html('<test-element></test-element>', $filter);
  1029. $this->assertNormalized($f, 'test-element', 'HTML filter should allow custom elements.');
  1030. }
  1031. /**
  1032. * Tests the spam deterrent.
  1033. */
  1034. function testNoFollowFilter() {
  1035. // Setup dummy filter object.
  1036. $filter = new stdClass();
  1037. $filter->settings = array(
  1038. 'allowed_html' => '<a>',
  1039. 'filter_html_help' => 1,
  1040. 'filter_html_nofollow' => 1,
  1041. );
  1042. // Test if the rel="nofollow" attribute is added, even if we try to prevent
  1043. // it.
  1044. $f = _filter_html('<a href="http://www.example.com/">text</a>', $filter);
  1045. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent -- no evasion.');
  1046. $f = _filter_html('<A href="http://www.example.com/">text</a>', $filter);
  1047. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- capital A.');
  1048. $f = _filter_html("<a/href=\"http://www.example.com/\">text</a>", $filter);
  1049. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- non whitespace character after tag name.');
  1050. $f = _filter_html("<\0a\0 href=\"http://www.example.com/\">text</a>", $filter);
  1051. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- some nulls.');
  1052. $f = _filter_html('<a href="http://www.example.com/" rel="follow">text</a>', $filter);
  1053. $this->assertNoNormalized($f, 'rel="follow"', 'Spam deterrent evasion -- with rel set - rel="follow" removed.');
  1054. $this->assertNormalized($f, 'rel="nofollow"', 'Spam deterrent evasion -- with rel set - rel="nofollow" added.');
  1055. }
  1056. /**
  1057. * Tests the loose, admin HTML filter.
  1058. */
  1059. function testFilterXSSAdmin() {
  1060. // DRUPAL-SA-2008-044
  1061. $f = filter_xss_admin('<object />');
  1062. $this->assertNoNormalized($f, 'object', 'Admin HTML filter -- should not allow object tag.');
  1063. $f = filter_xss_admin('<script />');
  1064. $this->assertNoNormalized($f, 'script', 'Admin HTML filter -- should not allow script tag.');
  1065. $f = filter_xss_admin('<style /><iframe /><frame /><frameset /><meta /><link /><embed /><applet /><param /><layer />');
  1066. $this->assertEqual($f, '', 'Admin HTML filter -- should never allow some tags.');
  1067. }
  1068. /**
  1069. * Tests the HTML escaping filter.
  1070. *
  1071. * check_plain() is not tested here.
  1072. */
  1073. function testHtmlEscapeFilter() {
  1074. // Setup dummy filter object.
  1075. $filter = new stdClass();
  1076. $filter->callback = '_filter_html_escape';
  1077. $tests = array(
  1078. " One. <!-- \"comment\" --> Two'.\n<p>Three.</p>\n " => array(
  1079. "One. &lt;!-- &quot;comment&quot; --&gt; Two&#039;.\n&lt;p&gt;Three.&lt;/p&gt;" => TRUE,
  1080. ' One.' => FALSE,
  1081. "</p>\n " => FALSE,
  1082. ),
  1083. );
  1084. $this->assertFilteredString($filter, $tests);
  1085. }
  1086. /**
  1087. * Tests the URL filter.
  1088. */
  1089. function testUrlFilter() {
  1090. // Setup dummy filter object.
  1091. $filter = new stdClass();
  1092. $filter->callback = '_filter_url';
  1093. $filter->settings = array(
  1094. 'filter_url_length' => 496,
  1095. );
  1096. // @todo Possible categories:
  1097. // - absolute, mail, partial
  1098. // - characters/encoding, surrounding markup, security
  1099. // Create a e-mail that is too long.
  1100. $long_email = str_repeat('a', 254) . '@example.com';
  1101. $too_long_email = str_repeat('b', 255) . '@example.com';
  1102. $email_with_plus_sign = 'one+two@example.com';
  1103. // Filter selection/pattern matching.
  1104. $tests = array(
  1105. // HTTP URLs.
  1106. '
  1107. http://example.com or www.example.com
  1108. ' => array(
  1109. '<a href="http://example.com">http://example.com</a>' => TRUE,
  1110. '<a href="http://www.example.com">www.example.com</a>' => TRUE,
  1111. ),
  1112. // MAILTO URLs.
  1113. '
  1114. person@example.com or mailto:person2@example.com or ' . $email_with_plus_sign . ' or ' . $long_email . ' but not ' . $too_long_email . '
  1115. ' => array(
  1116. '<a href="mailto:person@example.com">person@example.com</a>' => TRUE,
  1117. '<a href="mailto:person2@example.com">mailto:person2@example.com</a>' => TRUE,
  1118. '<a href="mailto:' . $long_email . '">' . $long_email . '</a>' => TRUE,
  1119. '<a href="mailto:' . $too_long_email . '">' . $too_long_email . '</a>' => FALSE,
  1120. '<a href="mailto:' . $email_with_plus_sign . '">' . $email_with_plus_sign . '</a>' => TRUE,
  1121. ),
  1122. // URI parts and special characters.
  1123. '
  1124. http://trailingslash.com/ or www.trailingslash.com/
  1125. http://host.com/some/path?query=foo&bar[baz]=beer#fragment or www.host.com/some/path?query=foo&bar[baz]=beer#fragment
  1126. http://twitter.com/#!/example/status/22376963142324226
  1127. ftp://user:pass@ftp.example.com/~home/dir1
  1128. sftp://user@nonstandardport:222/dir
  1129. ssh://192.168.0.100/srv/git/drupal.git
  1130. ' => array(
  1131. '<a href="http://trailingslash.com/">http://trailingslash.com/</a>' => TRUE,
  1132. '<a href="http://www.trailingslash.com/">www.trailingslash.com/</a>' => TRUE,
  1133. '<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,
  1134. '<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,
  1135. '<a href="http://twitter.com/#!/example/status/22376963142324226">http://twitter.com/#!/example/status/22376963142324226</a>' => TRUE,
  1136. '<a href="ftp://user:pass@ftp.example.com/~home/dir1">ftp://user:pass@ftp.example.com/~home/dir1</a>' => TRUE,
  1137. '<a href="sftp://user@nonstandardport:222/dir">sftp://user@nonstandardport:222/dir</a>' => TRUE,
  1138. '<a href="ssh://192.168.0.100/srv/git/drupal.git">ssh://192.168.0.100/srv/git/drupal.git</a>' => TRUE,
  1139. ),
  1140. // Encoding.
  1141. '
  1142. http://ampersand.com/?a=1&b=2
  1143. http://encoded.com/?a=1&amp;b=2
  1144. ' => array(
  1145. '<a href="http://ampersand.com/?a=1&amp;b=2">http://ampersand.com/?a=1&amp;b=2</a>' => TRUE,
  1146. '<a href="http://encoded.com/?a=1&amp;b=2">http://encoded.com/?a=1&amp;b=2</a>' => TRUE,
  1147. ),
  1148. // Domain name length.
  1149. '
  1150. www.ex.ex or www.example.example or www.toolongdomainexampledomainexampledomainexampledomainexampledomain or
  1151. me@me.tv
  1152. ' => array(
  1153. '<a href="http://www.ex.ex">www.ex.ex</a>' => TRUE,
  1154. '<a href="http://www.example.example">www.example.example</a>' => TRUE,
  1155. 'http://www.toolong' => FALSE,
  1156. '<a href="mailto:me@me.tv">me@me.tv</a>' => TRUE,
  1157. ),
  1158. // Absolute URL protocols.
  1159. // The list to test is found in the beginning of _filter_url() at
  1160. // $protocols = variable_get('filter_allowed_protocols'... (approx line 1325).
  1161. '
  1162. https://example.com,
  1163. ftp://ftp.example.com,
  1164. news://example.net,
  1165. telnet://example,
  1166. irc://example.host,
  1167. ssh://odd.geek,
  1168. sftp://secure.host?,
  1169. webcal://calendar,
  1170. rtsp://127.0.0.1,
  1171. not foo://disallowed.com.
  1172. ' => array(
  1173. 'href="https://example.com"' => TRUE,
  1174. 'href="ftp://ftp.example.com"' => TRUE,
  1175. 'href="news://example.net"' => TRUE,
  1176. 'href="telnet://example"' => TRUE,
  1177. 'href="irc://example.host"' => TRUE,
  1178. 'href="ssh://odd.geek"' => TRUE,
  1179. 'href="sftp://secure.host"' => TRUE,
  1180. 'href="webcal://calendar"' => TRUE,
  1181. 'href="rtsp://127.0.0.1"' => TRUE,
  1182. 'href="foo://disallowed.com"' => FALSE,
  1183. 'not foo://disallowed.com.' => TRUE,
  1184. ),
  1185. );
  1186. $this->assertFilteredString($filter, $tests);
  1187. // Surrounding text/punctuation.
  1188. $tests = array(
  1189. '
  1190. Partial URL with trailing period www.partial.com.
  1191. E-mail with trailing comma person@example.com,
  1192. Absolute URL with trailing question http://www.absolute.com?
  1193. Query string with trailing exclamation www.query.com/index.php?a=!
  1194. Partial URL with 3 trailing www.partial.periods...
  1195. E-mail with 3 trailing exclamations@example.com!!!
  1196. Absolute URL and query string with 2 different punctuation characters (http://www.example.com/q=abc).
  1197. ' => array(
  1198. 'period <a href="http://www.partial.com">www.partial.com</a>.' => TRUE,
  1199. 'comma <a href="mailto:person@example.com">person@example.com</a>,' => TRUE,
  1200. 'question <a href="http://www.absolute.com">http://www.absolute.com</a>?' => TRUE,
  1201. 'exclamation <a href="http://www.query.com/index.php?a=">www.query.com/index.php?a=</a>!' => TRUE,
  1202. 'trailing <a href="http://www.partial.periods">www.partial.periods</a>...' => TRUE,
  1203. 'trailing <a href="mailto:exclamations@example.com">exclamations@example.com</a>!!!' => TRUE,
  1204. 'characters (<a href="http://www.example.com/q=abc">http://www.example.com/q=abc</a>).' => TRUE,
  1205. ),
  1206. '
  1207. (www.parenthesis.com/dir?a=1&b=2#a)
  1208. ' => array(
  1209. '(<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,
  1210. ),
  1211. );
  1212. $this->assertFilteredString($filter, $tests);
  1213. // Surrounding markup.
  1214. $tests = array(
  1215. '
  1216. <p xmlns="www.namespace.com" />
  1217. <p xmlns="http://namespace.com">
  1218. An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.
  1219. </p>
  1220. ' => array(
  1221. '<p xmlns="www.namespace.com" />' => TRUE,
  1222. '<p xmlns="http://namespace.com">' => TRUE,
  1223. 'href="http://www.namespace.com"' => FALSE,
  1224. 'href="http://namespace.com"' => FALSE,
  1225. 'An <a href="http://example.com" title="Read more at www.example.info...">anchor</a>.' => TRUE,
  1226. ),
  1227. '
  1228. Not <a href="foo">www.relative.com</a> or <a href="http://absolute.com">www.absolute.com</a>
  1229. but <strong>http://www.strong.net</strong> or <em>www.emphasis.info</em>
  1230. ' => array(
  1231. '<a href="foo">www.relative.com</a>' => TRUE,
  1232. 'href="http://www.relative.com"' => FALSE,
  1233. '<a href="http://absolute.com">www.absolute.com</a>' => TRUE,
  1234. '<strong><a href="http://www.strong.net">http://www.strong.net</a></strong>' => TRUE,
  1235. '<em><a href="http://www.emphasis.info">www.emphasis.info</a></em>' => TRUE,
  1236. ),
  1237. '
  1238. Test <code>using www.example.com the code tag</code>.
  1239. ' => array(
  1240. 'href' => FALSE,
  1241. 'http' => FALSE,
  1242. ),
  1243. '
  1244. Intro.
  1245. <blockquote>
  1246. 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>.
  1247. </blockquote>
  1248. Outro.
  1249. ' => array(
  1250. 'href="http://www.example.com"' => TRUE,
  1251. 'href="mailto:person@example.com"' => TRUE,
  1252. 'href="http://origin.example.com"' => TRUE,
  1253. 'http://www.usage.example.com' => FALSE,
  1254. 'http://www.example.info' => FALSE,
  1255. 'Intro.' => TRUE,
  1256. 'Outro.' => TRUE,
  1257. ),
  1258. '
  1259. 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>
  1260. ' => array(
  1261. 'href="http://www.example.com"' => TRUE,
  1262. 'href="http://www.example.pooh"' => TRUE,
  1263. ),
  1264. '
  1265. <p>Test &lt;br/&gt;: This is a www.example17.com example <strong>with</strong> various http://www.example18.com tags. *<br/>
  1266. It is important www.example19.com to *<br/>test different URLs and http://www.example20.com in the same paragraph. *<br>
  1267. 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.
  1268. ' => array(
  1269. 'href="http://www.example17.com"' => TRUE,
  1270. 'href="http://www.example18.com"' => TRUE,
  1271. 'href="http://www.example19.com"' => TRUE,
  1272. 'href="http://www.example20.com"' => TRUE,
  1273. 'href="http://www.example21.com"' => TRUE,
  1274. 'href="mailto:person@example22.com"' => TRUE,
  1275. 'href="http://www.example23.com"' => TRUE,
  1276. 'href="http://www.example24.com"' => TRUE,
  1277. 'href="http://www.example25.com"' => TRUE,
  1278. 'href="http://www.example26.com"' => TRUE,
  1279. 'href="mailto:person@example27.com"' => TRUE,
  1280. 'href="http://www.example28.com"' => TRUE,
  1281. ),
  1282. '
  1283. <script>
  1284. <!--
  1285. // @see www.example.com
  1286. var exampleurl = "http://example.net";
  1287. -->
  1288. <!--//--><![CDATA[//><!--
  1289. // @see www.example.com
  1290. var exampleurl = "http://example.net";
  1291. //--><!]]>
  1292. </script>
  1293. ' => array(
  1294. 'href="http://www.example.com"' => FALSE,
  1295. 'href="http://example.net"' => FALSE,
  1296. ),
  1297. '
  1298. <style>body {
  1299. background: url(http://example.com/pixel.gif);
  1300. }</style>
  1301. ' => array(
  1302. 'href' => FALSE,
  1303. ),
  1304. '
  1305. <!-- Skip any URLs like www.example.com in comments -->
  1306. ' => array(
  1307. 'href' => FALSE,
  1308. ),
  1309. '
  1310. <!-- Skip any URLs like
  1311. www.example.com with a newline in comments -->
  1312. ' => array(
  1313. 'href' => FALSE,
  1314. ),
  1315. '
  1316. <!-- Skip any URLs like www.comment.com in comments. <p>Also ignore http://commented.out/markup.</p> -->
  1317. ' => array(
  1318. 'href' => FALSE,
  1319. ),
  1320. '
  1321. <dl>
  1322. <dt>www.example.com</dt>
  1323. <dd>http://example.com</dd>
  1324. <dd>person@example.com</dd>
  1325. <dt>Check www.example.net</dt>
  1326. <dd>Some text around http://www.example.info by person@example.info?</dd>
  1327. </dl>
  1328. ' => array(
  1329. 'href="http://www.example.com"' => TRUE,
  1330. 'href="http://example.com"' => TRUE,
  1331. 'href="mailto:person@example.com"' => TRUE,
  1332. 'href="http://www.example.net"' => TRUE,
  1333. 'href="http://www.example.info"' => TRUE,
  1334. 'href="mailto:person@example.info"' => TRUE,
  1335. ),
  1336. '
  1337. <div>www.div.com</div>
  1338. <ul>
  1339. <li>http://listitem.com</li>
  1340. <li class="odd">www.class.listitem.com</li>
  1341. </ul>
  1342. ' => array(
  1343. '<div><a href="http://www.div.com">www.div.com</a></div>' => TRUE,
  1344. '<li><a href="http://listitem.com">http://listitem.com</a></li>' => TRUE,
  1345. '<li class="odd"><a href="http://www.class.listitem.com">www.class.listitem.com</a></li>' => TRUE,
  1346. ),
  1347. );
  1348. $this->assertFilteredString($filter, $tests);
  1349. // URL trimming.
  1350. $filter->settings['filter_url_length'] = 20;
  1351. $tests = array(
  1352. 'www.trimmed.com/d/ff.ext?a=1&b=2#a1' => array(
  1353. '<a href="http://www.trimmed.com/d/ff.ext?a=1&amp;b=2#a1">www.trimmed.com/d/ff...</a>' => TRUE,
  1354. ),
  1355. );
  1356. $this->assertFilteredString($filter, $tests);
  1357. }
  1358. /**
  1359. * Asserts multiple filter output expectations for multiple input strings.
  1360. *
  1361. * @param $filter
  1362. * A input filter object.
  1363. * @param $tests
  1364. * An associative array, whereas each key is an arbitrary input string and
  1365. * each value is again an associative array whose keys are filter output
  1366. * strings and whose values are Booleans indicating whether the output is
  1367. * expected or not.
  1368. *
  1369. * For example:
  1370. * @code
  1371. * $tests = array(
  1372. * 'Input string' => array(
  1373. * '<p>Input string</p>' => TRUE,
  1374. * 'Input string<br' => FALSE,
  1375. * ),
  1376. * );
  1377. * @endcode
  1378. */
  1379. function assertFilteredString($filter, $tests) {
  1380. foreach ($tests as $source => $tasks) {
  1381. $function = $filter->callback;
  1382. $result = $function($source, $filter);
  1383. foreach ($tasks as $value => $is_expected) {
  1384. // Not using assertIdentical, since combination with strpos() is hard to grok.
  1385. if ($is_expected) {
  1386. $success = $this->assertTrue(strpos($result, $value) !== FALSE, format_string('@source: @value found.', array(
  1387. '@source' => var_export($source, TRUE),
  1388. '@value' => var_export($value, TRUE),
  1389. )));
  1390. }
  1391. else {
  1392. $success = $this->assertTrue(strpos($result, $value) === FALSE, format_string('@source: @value not found.', array(
  1393. '@source' => var_export($source, TRUE),
  1394. '@value' => var_export($value, TRUE),
  1395. )));
  1396. }
  1397. if (!$success) {
  1398. $this->verbose('Source:<pre>' . check_plain(var_export($source, TRUE)) . '</pre>'
  1399. . '<hr />' . 'Result:<pre>' . check_plain(var_export($result, TRUE)) . '</pre>'
  1400. . '<hr />' . ($is_expected ? 'Expected:' : 'Not expected:')
  1401. . '<pre>' . check_plain(var_export($value, TRUE)) . '</pre>'
  1402. );
  1403. }
  1404. }
  1405. }
  1406. }
  1407. /**
  1408. * Tests URL filter on longer content.
  1409. *
  1410. * Filters based on regular expressions should also be tested with a more
  1411. * complex content than just isolated test lines.
  1412. * The most common errors are:
  1413. * - accidental '*' (greedy) match instead of '*?' (minimal) match.
  1414. * - only matching first occurrence instead of all.
  1415. * - newlines not matching '.*'.
  1416. *
  1417. * This test covers:
  1418. * - Document with multiple newlines and paragraphs (two newlines).
  1419. * - Mix of several HTML tags, invalid non-HTML tags, tags to ignore and HTML
  1420. * comments.
  1421. * - Empty HTML tags (BR, IMG).
  1422. * - Mix of absolute and partial URLs, and e-mail addresses in one content.
  1423. */
  1424. function testUrlFilterContent() {
  1425. // Setup dummy filter object.
  1426. $filter = new stdClass();
  1427. $filter->settings = array(
  1428. 'filter_url_length' => 496,
  1429. );
  1430. $path = drupal_get_path('module', 'filter') . '/tests';
  1431. $input = file_get_contents($path . '/filter.url-input.txt');
  1432. $expected = file_get_contents($path . '/filter.url-output.txt');
  1433. $result = _filter_url($input, $filter);
  1434. $this->assertIdentical($result, $expected, 'Complex HTML document was correctly processed.');
  1435. }
  1436. /**
  1437. * Tests the HTML corrector filter.
  1438. *
  1439. * @todo This test could really use some validity checking function.
  1440. */
  1441. function testHtmlCorrectorFilter() {
  1442. // Tag closing.
  1443. $f = _filter_htmlcorrector('<p>text');
  1444. $this->assertEqual($f, '<p>text</p>', 'HTML corrector -- tag closing at the end of input.');
  1445. $f = _filter_htmlcorrector('<p>text<p><p>text');
  1446. $this->assertEqual($f, '<p>text</p><p></p><p>text</p>', 'HTML corrector -- tag closing.');
  1447. $f = _filter_htmlcorrector("<ul><li>e1<li>e2");
  1448. $this->assertEqual($f, "<ul><li>e1</li><li>e2</li></ul>", 'HTML corrector -- unclosed list tags.');
  1449. $f = _filter_htmlcorrector('<div id="d">content');
  1450. $this->assertEqual($f, '<div id="d">content</div>', 'HTML corrector -- unclosed tag with attribute.');
  1451. // XHTML slash for empty elements.
  1452. $f = _filter_htmlcorrector('<hr><br>');
  1453. $this->assertEqual($f, '<hr /><br />', 'HTML corrector -- XHTML closing slash.');
  1454. $f = _filter_htmlcorrector('<P>test</P>');
  1455. $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
  1456. $f = _filter_htmlcorrector('<P>test</p>');
  1457. $this->assertEqual($f, '<p>test</p>', 'HTML corrector -- Convert uppercased tags to proper lowercased ones.');
  1458. $f = _filter_htmlcorrector('test<hr />');
  1459. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through.');
  1460. $f = _filter_htmlcorrector('test<hr/>');
  1461. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there is a single space before the closing slash.');
  1462. $f = _filter_htmlcorrector('test<hr />');
  1463. $this->assertEqual($f, 'test<hr />', 'HTML corrector -- Let proper XHTML pass through, but ensure there are not too many spaces before the closing slash.');
  1464. $f = _filter_htmlcorrector('<span class="test" />');
  1465. $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.');
  1466. $f = _filter_htmlcorrector('test1<br class="test">test2');
  1467. $this->assertEqual($f, 'test1<br class="test" />test2', 'HTML corrector -- Automatically close single tags.');
  1468. $f = _filter_htmlcorrector('line1<hr>line2');
  1469. $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
  1470. $f = _filter_htmlcorrector('line1<HR>line2');
  1471. $this->assertEqual($f, 'line1<hr />line2', 'HTML corrector -- Automatically close single tags.');
  1472. $f = _filter_htmlcorrector('<img src="http://example.com/test.jpg">test</img>');
  1473. $this->assertEqual($f, '<img src="http://example.com/test.jpg" />test', 'HTML corrector -- Automatically close single tags.');
  1474. $f = _filter_htmlcorrector('<br></br>');
  1475. $this->assertEqual($f, '<br />', "HTML corrector -- Transform empty tags to a single closed tag if the tag's content model is EMPTY.");
  1476. $f = _filter_htmlcorrector('<div></div>');
  1477. $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.");
  1478. $f = _filter_htmlcorrector('<p>line1<br/><hr/>line2</p>');
  1479. $this->assertEqual($f, '<p>line1<br /></p><hr />line2', 'HTML corrector -- Move non-inline elements outside of inline containers.');
  1480. $f = _filter_htmlcorrector('<p>line1<div>line2</div></p>');
  1481. $this->assertEqual($f, '<p>line1</p><div>line2</div>', 'HTML corrector -- Move non-inline elements outside of inline containers.');
  1482. $f = _filter_htmlcorrector('<p>test<p>test</p>\n');
  1483. $this->assertEqual($f, '<p>test</p><p>test</p>\n', 'HTML corrector -- Auto-close improperly nested tags.');
  1484. $f = _filter_htmlcorrector('<p>Line1<br><STRONG>bold stuff</b>');
  1485. $this->assertEqual($f, '<p>Line1<br /><strong>bold stuff</strong></p>', 'HTML corrector -- Properly close unclosed tags, and remove useless closing tags.');
  1486. $f = _filter_htmlcorrector('test <!-- this is a comment -->');
  1487. $this->assertEqual($f, 'test <!-- this is a comment -->', 'HTML corrector -- Do not touch HTML comments.');
  1488. $f = _filter_htmlcorrector('test <!--this is a comment-->');
  1489. $this->assertEqual($f, 'test <!--this is a comment-->', 'HTML corrector -- Do not touch HTML comments.');
  1490. $f = _filter_htmlcorrector('test <!-- comment <p>another
  1491. <strong>multiple</strong> line
  1492. comment</p> -->');
  1493. $this->assertEqual($f, 'test <!-- comment <p>another
  1494. <strong>multiple</strong> line
  1495. comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
  1496. $f = _filter_htmlcorrector('test <!-- comment <p>another comment</p> -->');
  1497. $this->assertEqual($f, 'test <!-- comment <p>another comment</p> -->', 'HTML corrector -- Do not touch HTML comments.');
  1498. $f = _filter_htmlcorrector('test <!--break-->');
  1499. $this->assertEqual($f, 'test <!--break-->', 'HTML corrector -- Do not touch HTML comments.');
  1500. $f = _filter_htmlcorrector('<p>test\n</p>\n');
  1501. $this->assertEqual($f, '<p>test\n</p>\n', 'HTML corrector -- New-lines are accepted and kept as-is.');
  1502. $f = _filter_htmlcorrector('<p>دروبال');
  1503. $this->assertEqual($f, '<p>دروبال</p>', 'HTML corrector -- Encoding is correctly kept.');
  1504. $f = _filter_htmlcorrector('<script type="text/javascript">alert("test")</script>');
  1505. $this->assertEqual($f, '<script type="text/javascript">
  1506. <!--//--><![CDATA[// ><!--
  1507. alert("test")
  1508. //--><!]]>
  1509. </script>', 'HTML corrector -- CDATA added to script element');
  1510. $f = _filter_htmlcorrector('<p><script type="text/javascript">alert("test")</script></p>');
  1511. $this->assertEqual($f, '<p><script type="text/javascript">
  1512. <!--//--><![CDATA[// ><!--
  1513. alert("test")
  1514. //--><!]]>
  1515. </script></p>', 'HTML corrector -- CDATA added to a nested script element');
  1516. $f = _filter_htmlcorrector('<p><style> /* Styling */ body {color:red}</style></p>');
  1517. $this->assertEqual($f, '<p><style>
  1518. <!--/*--><![CDATA[/* ><!--*/
  1519. /* Styling */ body {color:red}
  1520. /*--><!]]>*/
  1521. </style></p>', 'HTML corrector -- CDATA added to a style element.');
  1522. $filtered_data = _filter_htmlcorrector('<p><style>
  1523. /*<![CDATA[*/
  1524. /* Styling */
  1525. body {color:red}
  1526. /*]]>*/
  1527. </style></p>');
  1528. $this->assertEqual($filtered_data, '<p><style>
  1529. <!--/*--><![CDATA[/* ><!--*/
  1530. /*<![CDATA[*/
  1531. /* Styling */
  1532. body {color:red}
  1533. /*]]]]><![CDATA[>*/
  1534. /*--><!]]>*/
  1535. </style></p>',
  1536. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '/*<![CDATA[*/'))
  1537. );
  1538. $filtered_data = _filter_htmlcorrector('<p><style>
  1539. <!--/*--><![CDATA[/* ><!--*/
  1540. /* Styling */
  1541. body {color:red}
  1542. /*--><!]]>*/
  1543. </style></p>');
  1544. $this->assertEqual($filtered_data, '<p><style>
  1545. <!--/*--><![CDATA[/* ><!--*/
  1546. <!--/*--><![CDATA[/* ><!--*/
  1547. /* Styling */
  1548. body {color:red}
  1549. /*--><!]]]]><![CDATA[>*/
  1550. /*--><!]]>*/
  1551. </style></p>',
  1552. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--/*--><![CDATA[/* ><!--*/'))
  1553. );
  1554. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1555. <!--//--><![CDATA[// ><!--
  1556. alert("test");
  1557. //--><!]]>
  1558. </script></p>');
  1559. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1560. <!--//--><![CDATA[// ><!--
  1561. <!--//--><![CDATA[// ><!--
  1562. alert("test");
  1563. //--><!]]]]><![CDATA[>
  1564. //--><!]]>
  1565. </script></p>',
  1566. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '<!--//--><![CDATA[// ><!--'))
  1567. );
  1568. $filtered_data = _filter_htmlcorrector('<p><script type="text/javascript">
  1569. // <![CDATA[
  1570. alert("test");
  1571. // ]]>
  1572. </script></p>');
  1573. $this->assertEqual($filtered_data, '<p><script type="text/javascript">
  1574. <!--//--><![CDATA[// ><!--
  1575. // <![CDATA[
  1576. alert("test");
  1577. // ]]]]><![CDATA[>
  1578. //--><!]]>
  1579. </script></p>',
  1580. format_string('HTML corrector -- Existing cdata section @pattern_name properly escaped', array('@pattern_name' => '// <![CDATA['))
  1581. );
  1582. }
  1583. /**
  1584. * Asserts that a text transformed to lowercase with HTML entities decoded does contains a given string.
  1585. *
  1586. * Otherwise fails the test with a given message, similar to all the
  1587. * SimpleTest assert* functions.
  1588. *
  1589. * Note that this does not remove nulls, new lines and other characters that
  1590. * could be used to obscure a tag or an attribute name.
  1591. *
  1592. * @param $haystack
  1593. * Text to look in.
  1594. * @param $needle
  1595. * Lowercase, plain text to look for.
  1596. * @param $message
  1597. * (optional) Message to display if failed. Defaults to an empty string.
  1598. * @param $group
  1599. * (optional) The group this message belongs to. Defaults to 'Other'.
  1600. * @return
  1601. * TRUE on pass, FALSE on fail.
  1602. */
  1603. function assertNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1604. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) !== FALSE, $message, $group);
  1605. }
  1606. /**
  1607. * Asserts that text transformed to lowercase with HTML entities decoded does not contain a given string.
  1608. *
  1609. * Otherwise fails the test with a given message, similar to all the
  1610. * SimpleTest assert* functions.
  1611. *
  1612. * Note that this does not remove nulls, new lines, and other character that
  1613. * could be used to obscure a tag or an attribute name.
  1614. *
  1615. * @param $haystack
  1616. * Text to look in.
  1617. * @param $needle
  1618. * Lowercase, plain text to look for.
  1619. * @param $message
  1620. * (optional) Message to display if failed. Defaults to an empty string.
  1621. * @param $group
  1622. * (optional) The group this message belongs to. Defaults to 'Other'.
  1623. * @return
  1624. * TRUE on pass, FALSE on fail.
  1625. */
  1626. function assertNoNormalized($haystack, $needle, $message = '', $group = 'Other') {
  1627. return $this->assertTrue(strpos(strtolower(decode_entities($haystack)), $needle) === FALSE, $message, $group);
  1628. }
  1629. }
  1630. /**
  1631. * Tests for Filter's hook invocations.
  1632. */
  1633. class FilterHooksTestCase extends DrupalWebTestCase {
  1634. public static function getInfo() {
  1635. return array(
  1636. 'name' => 'Filter format hooks',
  1637. 'description' => 'Test hooks for text formats insert/update/disable.',
  1638. 'group' => 'Filter',
  1639. );
  1640. }
  1641. function setUp() {
  1642. parent::setUp('block', 'filter_test');
  1643. $admin_user = $this->drupalCreateUser(array('administer filters', 'administer blocks'));
  1644. $this->drupalLogin($admin_user);
  1645. }
  1646. /**
  1647. * Tests hooks on format management.
  1648. *
  1649. * Tests that hooks run correctly on creating, editing, and deleting a text
  1650. * format.
  1651. */
  1652. function testFilterHooks() {
  1653. // Add a text format.
  1654. $name = $this->randomName();
  1655. $edit = array();
  1656. $edit['format'] = drupal_strtolower($this->randomName());
  1657. $edit['name'] = $name;
  1658. $edit['roles[' . DRUPAL_ANONYMOUS_RID . ']'] = 1;
  1659. $this->drupalPost('admin/config/content/formats/add', $edit, t('Save configuration'));
  1660. $this->assertRaw(t('Added text format %format.', array('%format' => $name)), 'New format created.');
  1661. $this->assertText('hook_filter_format_insert invoked.', 'hook_filter_format_insert was invoked.');
  1662. $format_id = $edit['format'];
  1663. // Update text format.
  1664. $edit = array();
  1665. $edit['roles[' . DRUPAL_AUTHENTICATED_RID . ']'] = 1;
  1666. $this->drupalPost('admin/config/content/formats/' . $format_id, $edit, t('Save configuration'));
  1667. $this->assertRaw(t('The text format %format has been updated.', array('%format' => $name)), 'Format successfully updated.');
  1668. $this->assertText('hook_filter_format_update invoked.', 'hook_filter_format_update() was invoked.');
  1669. // Add a new custom block.
  1670. $custom_block = array();
  1671. $custom_block['info'] = $this->randomName(8);
  1672. $custom_block['title'] = $this->randomName(8);
  1673. $custom_block['body[value]'] = $this->randomName(32);
  1674. // Use the format created.
  1675. $custom_block['body[format]'] = $format_id;
  1676. $this->drupalPost('admin/structure/block/add', $custom_block, t('Save block'));
  1677. $this->assertText(t('The block has been created.'), 'New block successfully created.');
  1678. // Verify the new block is in the database.
  1679. $bid = db_query("SELECT bid FROM {block_custom} WHERE info = :info", array(':info' => $custom_block['info']))->fetchField();
  1680. $this->assertNotNull($bid, 'New block found in database');
  1681. // Disable the text format.
  1682. $this->drupalPost('admin/config/content/formats/' . $format_id . '/disable', array(), t('Disable'));
  1683. $this->assertRaw(t('Disabled text format %format.', array('%format' => $name)), 'Format successfully disabled.');
  1684. $this->assertText('hook_filter_format_disable invoked.', 'hook_filter_format_disable() was invoked.');
  1685. }
  1686. }
  1687. /**
  1688. * Tests filter settings.
  1689. */
  1690. class FilterSettingsTestCase extends DrupalWebTestCase {
  1691. /**
  1692. * The installation profile to use with this test class.
  1693. *
  1694. * @var string
  1695. */
  1696. protected $profile = 'testing';
  1697. public static function getInfo() {
  1698. return array(
  1699. 'name' => 'Filter settings',
  1700. 'description' => 'Tests filter settings.',
  1701. 'group' => 'Filter',
  1702. );
  1703. }
  1704. /**
  1705. * Tests explicit and implicit default settings for filters.
  1706. */
  1707. function testFilterDefaults() {
  1708. $filter_info = filter_filter_info();
  1709. $filters = array_fill_keys(array_keys($filter_info), array());
  1710. // Create text format using filter default settings.
  1711. $filter_defaults_format = (object) array(
  1712. 'format' => 'filter_defaults',
  1713. 'name' => 'Filter defaults',
  1714. 'filters' => $filters,
  1715. );
  1716. filter_format_save($filter_defaults_format);
  1717. // Verify that default weights defined in hook_filter_info() were applied.
  1718. $saved_settings = array();
  1719. foreach ($filter_defaults_format->filters as $name => $settings) {
  1720. $expected_weight = (isset($filter_info[$name]['weight']) ? $filter_info[$name]['weight'] : 0);
  1721. $this->assertEqual($settings['weight'], $expected_weight, format_string('@name filter weight %saved equals %default', array(
  1722. '@name' => $name,
  1723. '%saved' => $settings['weight'],
  1724. '%default' => $expected_weight,
  1725. )));
  1726. $saved_settings[$name]['weight'] = $expected_weight;
  1727. }
  1728. // Re-save the text format.
  1729. filter_format_save($filter_defaults_format);
  1730. // Reload it from scratch.
  1731. filter_formats_reset();
  1732. $filter_defaults_format = filter_format_load($filter_defaults_format->format);
  1733. $filter_defaults_format->filters = filter_list_format($filter_defaults_format->format);
  1734. // Verify that saved filter settings have not been changed.
  1735. foreach ($filter_defaults_format->filters as $name => $settings) {
  1736. $this->assertEqual($settings->weight, $saved_settings[$name]['weight'], format_string('@name filter weight %saved equals %previous', array(
  1737. '@name' => $name,
  1738. '%saved' => $settings->weight,
  1739. '%previous' => $saved_settings[$name]['weight'],
  1740. )));
  1741. }
  1742. }
  1743. }
  1744. /**
  1745. * Tests DOMDocument serialization.
  1746. */
  1747. class FilterDOMSerializeTestCase extends DrupalWebTestCase {
  1748. public static function getInfo() {
  1749. return array(
  1750. 'name' => 'Serialization',
  1751. 'description' => 'Test serialization of DOMDocument objects.',
  1752. 'group' => 'Filter',
  1753. );
  1754. }
  1755. /**
  1756. * Tests empty DOMDocument object.
  1757. */
  1758. function testFilterEmptyDOMSerialization() {
  1759. $document = new DOMDocument();
  1760. $result = filter_dom_serialize($document);
  1761. $this->assertEqual('', $result);
  1762. }
  1763. }