filter.test 86 KB

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