filter.module

  1. drupal
    1. 4.6 modules/filter.module
    2. 4.7 modules/filter.module
    3. 5 modules/filter/filter.module
    4. 6 modules/filter/filter.module
    5. 7 modules/filter/filter.module
    6. 8 core/modules/filter/filter.module

Framework for handling filtering of content.

Functions & methods

NameDescription
check_markupRun all the enabled filters on a piece of text.
filter_accessReturns true if the user is allowed to access this format.
filter_admin_configureMenu callback; display settings defined by filters.
filter_admin_deleteMenu callback; confirm deletion of a format.
filter_admin_delete_submitProcess filter delete form submission.
filter_admin_format_formGenerate a filter format form.
filter_admin_format_form_submitProcess filter format form submissions.
filter_admin_format_form_validateValidate filter format form submissions.
filter_admin_orderMenu callback; display form for ordering filters for a format.
filter_admin_order_submitProcess filter order configuration form submission.
filter_admin_overviewDisplays a list of all input formats and which one is the default
filter_admin_overview_submit
filter_filterImplementation of hook_filter(). Contains a basic set of essential filters.
filter_filter_tipsImplementation of hook_filter_tips().
filter_formGenerate a selector for choosing a format in a form.
filter_formatsRetrieve a list of input formats.
filter_format_allowcacheCheck if text in a certain input format is allowed to be cached.
filter_form_validate
filter_helpImplementation of hook_help().
filter_list_allBuild a list of all filters.
filter_list_formatRetrieve a list of filters for a certain format.
filter_menuImplementation of hook_menu().
filter_permImplementation of hook_perm().
filter_resolve_formatResolve a format id, including the default format.
filter_tips_longMenu callback; show a page with long filter tips.
filter_xssFilters XSS. Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses
filter_xss_adminVery permissive XSS/HTML filter for admin-only use.
filter_xss_bad_protocolProcesses an HTML attribute value and ensures it does not contain an URL with a disallowed protocol (e.g. javascript:)
theme_filter_admin_orderTheme filter order configuration form.
theme_filter_admin_overview
theme_filter_tipsFormat a set of filter tips.
_filter_autopConvert line breaks into <p> and <br> in an intelligent fashion. Based on: http://photomatt.net/scripts/autop
_filter_htmlHTML filter. Provides filtering of input into accepted HTML.
_filter_html_settingsSettings for the HTML filter.
_filter_list_cmpHelper function for sorting the filter list by filter name.
_filter_tipsHelper function for fetching filter tips.
_filter_xss_attributesProcesses a string of HTML attributes.
_filter_xss_splitProcesses an HTML tag.

Constants

NameDescription
FILTER_FORMAT_DEFAULT
FILTER_HTML_ESCAPE
FILTER_HTML_STRIP

File

modules/filter.module
View source
  1. <?php
  2. /**
  3. * @file
  4. * Framework for handling filtering of content.
  5. */
  6. // This is a special format ID which means "use the default format". This value
  7. // can be passed to the filter APIs as a format ID: this is equivalent to not
  8. // passing an explicit format at all.
  9. define('FILTER_FORMAT_DEFAULT', 0);
  10. define('FILTER_HTML_STRIP', 1);
  11. define('FILTER_HTML_ESCAPE', 2);
  12. /**
  13. * Implementation of hook_help().
  14. */
  15. function filter_help($section) {
  16. switch ($section) {
  17. case 'admin/help#filter':
  18. $output = '<p>'. t('The filter module allows administrators to configure text input formats for the site. For example, an administrator may want a filter to strip out malicious HTML from user\'s comments. Administrators may also want to make URLs linkable even if they are only entered in an unlinked format.') .'</p>';
  19. $output .= '<p>'. t('Users can choose between the available input formats when creating or editing content. Administrators can configure which input formats are available to which user roles, as well as choose a default input format. Administrators can also create new input formats. Each input format can be configured to use a selection of filters.') .'</p>';
  20. $output .= t('<p>You can</p>
  21. <ul>
  22. <li>administer input format permissions and settings at <a href="%admin-filters">administer &gt;&gt; input formats</a>.</li>
  23. <li>configure the filters for each input format at <a href="%admin-filters">administer &gt;&gt; input formats &gt;&gt; configure</a>.</li>
  24. </ul>
  25. ', array('%admin-filters' => url('admin/filters')));
  26. $output .= '<p>'. t('For more information please read the configuration and customization handbook <a href="%filter">Filter page</a>.', array('%filter' => 'http://drupal.org/handbook/modules/filter/')) .'</p>';
  27. return $output;
  28. case 'admin/modules#description':
  29. return t('Handles the filtering of content in preparation for display.');
  30. case 'admin/filters':
  31. return t('
  32. <p><em>Input formats</em> define a way of processing user-supplied text in Drupal. Every input format has its own settings of which <em>filters</em> to apply. Possible filters include stripping out malicious HTML and making URLs clickable.</p>
  33. <p>Users can choose between the available input formats when submitting content.</p>
  34. <p>Below you can configure which input formats are available to which roles, as well as choose a default input format (used for imported content, for example).</p>
  35. <p>Note that (1) the default format is always available to all roles, and (2) all filter formats can always be used by roles with the "administer filters" permission even if they are not explicitly listed in the Roles column of this table.</p>');
  36. case 'admin/filters/'. arg(2):
  37. return t('
  38. <p>Every <em>filter</em> performs one particular change on the user input, for example stripping out malicious HTML or making URLs clickable. Choose which filters you want to apply to text in this input format.</p>
  39. <p>If you notice some filters are causing conflicts in the output, you can <a href="%rearrange">rearrange them</a>.</p>', array('%rearrange' => check_url(url('admin/filters/'. arg(2) .'/order'))));
  40. case 'admin/filters/'. arg(2) .'/configure':
  41. return t('
  42. <p>If you cannot find the settings for a certain filter, make sure you\'ve enabled it on the <a href="%url">view tab</a> first.</p>', array('%url' => check_url(url('admin/filters/'. arg(2)))));
  43. case 'admin/filters/'. arg(2) .'/order':
  44. return t('
  45. <p>Because of the flexible filtering system, you might encounter a situation where one filter prevents another from doing its job. For example: a word in an URL gets converted into a glossary term, before the URL can be converted in a clickable link. When this happens, you will need to rearrange the order in which filters get executed.</p>
  46. <p>Filters are executed from top-to-bottom. You can use the weight column to rearrange them: heavier filters \'sink\' to the bottom.</p>');
  47. }
  48. }
  49. /**
  50. * Implementation of hook_menu().
  51. */
  52. function filter_menu($may_cache) {
  53. $items = array();
  54. if ($may_cache) {
  55. $items[] = array('path' => 'admin/filters',
  56. 'title' => t('input formats'),
  57. 'callback' => 'filter_admin_overview',
  58. 'access' => user_access('administer filters'),
  59. );
  60. $items[] = array('path' => 'admin/filters/list',
  61. 'title' => t('list'),
  62. 'callback' => 'filter_admin_overview',
  63. 'type' => MENU_DEFAULT_LOCAL_TASK,
  64. 'access' => user_access('administer filters'),
  65. );
  66. $items[] = array('path' => 'admin/filters/add',
  67. 'title' => t('add input format'),
  68. 'callback' => 'filter_admin_format_form',
  69. 'type' => MENU_LOCAL_TASK,
  70. 'weight' => 1,
  71. 'access' => user_access('administer filters'),
  72. );
  73. $items[] = array('path' => 'admin/filters/delete',
  74. 'title' => t('delete input format'),
  75. 'callback' => 'filter_admin_delete',
  76. 'type' => MENU_CALLBACK,
  77. 'access' => user_access('administer filters'),
  78. );
  79. $items[] = array('path' => 'filter/tips',
  80. 'title' => t('compose tips'),
  81. 'callback' => 'filter_tips_long',
  82. 'access' => TRUE,
  83. 'type' => MENU_SUGGESTED_ITEM,
  84. );
  85. }
  86. else {
  87. if (arg(0) == 'admin' && arg(1) == 'filters' && is_numeric(arg(2))) {
  88. $formats = filter_formats();
  89. if (isset($formats[arg(2)])) {
  90. $items[] = array('path' => 'admin/filters/'. arg(2),
  91. 'title' => t("'%format' input format", array('%format' => $formats[arg(2)]->name)),
  92. 'callback' => 'filter_admin_format_form',
  93. 'callback arguments' => array('format' => $formats[arg(2)]),
  94. 'type' => MENU_CALLBACK,
  95. 'access' => user_access('administer filters'),
  96. );
  97. $items[] = array('path' => 'admin/filters/'. arg(2) .'/list',
  98. 'title' => t('view'),
  99. 'callback' => 'filter_admin_format_form',
  100. 'callback arguments' => array('format' => $formats[arg(2)]),
  101. 'type' => MENU_DEFAULT_LOCAL_TASK,
  102. 'weight' => 0,
  103. 'access' => user_access('administer filters'),
  104. );
  105. $items[] = array('path' => 'admin/filters/'. arg(2) .'/configure',
  106. 'title' => t('configure'),
  107. 'callback' => 'filter_admin_configure',
  108. 'type' => MENU_LOCAL_TASK,
  109. 'weight' => 1,
  110. 'access' => user_access('administer filters'),
  111. );
  112. $items[] = array('path' => 'admin/filters/'. arg(2) .'/order',
  113. 'title' => t('rearrange'),
  114. 'callback' => 'filter_admin_order',
  115. 'callback arguments' => array('format' => $formats[arg(2)]),
  116. 'type' => MENU_LOCAL_TASK,
  117. 'weight' => 2,
  118. 'access' => user_access('administer filters'),
  119. );
  120. }
  121. }
  122. }
  123. return $items;
  124. }
  125. /**
  126. * Implementation of hook_perm().
  127. */
  128. function filter_perm() {
  129. return array('administer filters');
  130. }
  131. /**
  132. * Implementation of hook_filter_tips().
  133. */
  134. function filter_filter_tips($delta, $format, $long = false) {
  135. global $base_url;
  136. switch ($delta) {
  137. case 0:
  138. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
  139. if ($allowed_html = variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>')) {
  140. switch ($long) {
  141. case 0:
  142. return t('Allowed HTML tags') .': '. check_plain($allowed_html);
  143. case 1:
  144. $output = '<p>'. t('Allowed HTML tags') .': '. check_plain($allowed_html) .'</p>';
  145. if (!variable_get("filter_html_help_$format", 1)) {
  146. return $output;
  147. }
  148. $output .= t('
  149. <p>This site allows HTML content. While learning all of HTML may feel intimidating, learning how to use a very small number of the most basic HTML "tags" is very easy. This table provides examples for each tag that is enabled on this site.</p>
  150. <p>For more information see W3C\'s <a href="http://www.w3.org/TR/html/">HTML Specifications</a> or use your favorite search engine to find other sites that explain HTML.</p>');
  151. $tips = array(
  152. 'a' => array( t('Anchors are used to make links to other pages.'), '<a href="'. $base_url .'">'. variable_get('site_name', 'drupal') .'</a>'),
  153. 'br' => array( t('By default line break tags are automatically added, so use this tag to add additional ones. Use of this tag is different because it is not used with an open/close pair like all the others. Use the extra " /" inside the tag to maintain XHTML 1.0 compatibility'), t('Text with <br />line break')),
  154. 'p' => array( t('By default paragraph tags are automatically added, so use this tag to add additional ones.'), '<p>'. t('Paragraph one.') .'</p> <p>'. t('Paragraph two.') .'</p>'),
  155. 'strong' => array( t('Strong'), '<strong>'. t('Strong'). '</strong>'),
  156. 'em' => array( t('Emphasized'), '<em>'. t('Emphasized') .'</em>'),
  157. 'cite' => array( t('Cited'), '<cite>'. t('Cited') .'</cite>'),
  158. 'code' => array( t('Coded text used to show programming source code'), '<code>'. t('Coded') .'</code>'),
  159. 'b' => array( t('Bolded'), '<b>'. t('Bolded') .'</b>'),
  160. 'u' => array( t('Underlined'), '<u>'. t('Underlined') .'</u>'),
  161. 'i' => array( t('Italicized'), '<i>'. t('Italicized') .'</i>'),
  162. 'sup' => array( t('Superscripted'), t('<sup>Super</sup>scripted')),
  163. 'sub' => array( t('Subscripted'), t('<sub>Sub</sub>scripted')),
  164. 'pre' => array( t('Preformatted'), '<pre>'. t('Preformatted') .'</pre>'),
  165. 'abbr' => array( t('Abbreviation'), t('<abbr title="Abbreviation">Abbrev.</abbr>')),
  166. 'acronym' => array( t('Acronym'), t('<acronym title="Three-Letter Acronym">TLA</acronym>')),
  167. 'blockquote' => array( t('Block quoted'), '<blockquote>'. t('Block quoted') .'</blockquote>'),
  168. 'q' => array( t('Quoted inline'), '<q>'. t('Quoted inline') .'</q>'),
  169. // Assumes and describes tr, td, th.
  170. 'table' => array( t('Table'), '<table> <tr><th>'. t('Table header') .'</th></tr> <tr><td>'. t('Table cell') .'</td></tr> </table>'),
  171. 'tr' => NULL, 'td' => NULL, 'th' => NULL,
  172. 'del' => array( t('Deleted'), '<del>'. t('Deleted') .'</del>'),
  173. 'ins' => array( t('Inserted'), '<ins>'. t('Inserted') .'</ins>'),
  174. // Assumes and describes li.
  175. 'ol' => array( t('Ordered list - use the &lt;li&gt; to begin each list item'), '<ol> <li>'. t('First item') .'</li> <li>'. t('Second item') .'</li> </ol>'),
  176. 'ul' => array( t('Unordered list - use the &lt;li&gt; to begin each list item'), '<ul> <li>'. t('First item') .'</li> <li>'. t('Second item') .'</li> </ul>'),
  177. 'li' => NULL,
  178. // Assumes and describes dt and dd.
  179. 'dl' => array( t('Definition lists are similar to other HTML lists. &lt;dl&gt; begins the definition list, &lt;dt&gt; begins the definition term and &lt;dd&gt; begins the definition description.'), '<dl> <dt>'. t('First term') .'</dt> <dd>'. t('First definition') .'</dd> <dt>'. t('Second term') .'</dt> <dd>'. t('Second definition') .'</dd> </dl>'),
  180. 'dt' => NULL, 'dd' => NULL,
  181. 'h1' => array( t('Header'), '<h1>'. t('Title') .'</h1>'),
  182. 'h2' => array( t('Header'), '<h2>'. t('Subtitle') .'</h2>'),
  183. 'h3' => array( t('Header'), '<h3>'. t('Subtitle three') .'</h3>'),
  184. 'h4' => array( t('Header'), '<h4>'. t('Subtitle four') .'</h4>'),
  185. 'h5' => array( t('Header'), '<h5>'. t('Subtitle five') .'</h5>'),
  186. 'h6' => array( t('Header'), '<h6>'. t('Subtitle six') .'</h6>')
  187. );
  188. $header = array(t('Tag Description'), t('You Type'), t('You Get'));
  189. preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out);
  190. foreach ($out[1] as $tag) {
  191. if (array_key_exists($tag, $tips)) {
  192. if ($tips[$tag]) {
  193. $rows[] = array(
  194. array('data' => $tips[$tag][0], 'class' => 'description'),
  195. array('data' => '<code>'. check_plain($tips[$tag][1]) .'</code>', 'class' => 'type'),
  196. array('data' => $tips[$tag][1], 'class' => 'get')
  197. );
  198. }
  199. }
  200. else {
  201. $rows[] = array(
  202. array('data' => t('No help provided for tag %tag.', array('%tag' => check_plain($tag))), 'class' => 'description', 'colspan' => 3),
  203. );
  204. }
  205. }
  206. $output .= theme('table', $header, $rows);
  207. $output .= t('
  208. <p>Most unusual characters can be directly entered without any problems.</p>
  209. <p>If you do encounter problems, try using HTML character entities. A common example looks like &amp;amp; for an ampersand &amp; character. For a full list of entities see HTML\'s <a href="http://www.w3.org/TR/html4/sgml/entities.html">entities</a> page. Some of the available characters include:</p>');
  210. $entities = array(
  211. array( t('Ampersand'), '&amp;'),
  212. array( t('Greater than'), '&gt;'),
  213. array( t('Less than'), '&lt;'),
  214. array( t('Quotation mark'), '&quot;'),
  215. );
  216. $header = array(t('Character Description'), t('You Type'), t('You Get'));
  217. unset($rows);
  218. foreach ($entities as $entity) {
  219. $rows[] = array(
  220. array('data' => $entity[0], 'class' => 'description'),
  221. array('data' => '<code>'. check_plain($entity[1]) .'</code>', 'class' => 'type'),
  222. array('data' => $entity[1], 'class' => 'get')
  223. );
  224. }
  225. $output .= theme('table', $header, $rows);
  226. return $output;
  227. }
  228. }
  229. else {
  230. return t('No HTML tags allowed');
  231. }
  232. }
  233. break;
  234. case 1:
  235. switch ($long) {
  236. case 0:
  237. return t('You may post PHP code. You should include &lt;?php ?&gt; tags.');
  238. case 1:
  239. return t('
  240. <h4>Using custom PHP code</h4>
  241. <p>If you know how to script in PHP, Drupal gives you the power to embed any script you like. It will be executed when the page is viewed and dynamically embedded into the page. This gives you amazing flexibility and power, but of course with that comes danger and insecurity if you don\'t write good code. If you are not familiar with PHP, SQL or with the site engine, avoid experimenting with PHP because you can corrupt your database or render your site insecure or even unusable! If you don\'t plan to do fancy stuff with your content then you\'re probably better off with straight HTML.</p>
  242. <p>Remember that the code within each PHP item must be valid PHP code - including things like correctly terminating statements with a semicolon. It is highly recommended that you develop your code separately using a simple test script on top of a test database before migrating to your production environment.</p>
  243. <p>Notes:</p><ul><li>You can use global variables, such as configuration parameters, within the scope of your PHP code but remember that global variables which have been given values in your code will retain these values in the engine afterwards.</li><li>register_globals is now set to <strong>off</strong> by default. If you need form information you need to get it from the "superglobals" $_POST, $_GET, etc.</li><li>You can either use the <code>print</code> or <code>return</code> statement to output the actual content for your item.</li></ul>
  244. <p>A basic example:</p>
  245. <blockquote><p>You want to have a box with the title "Welcome" that you use to greet your visitors. The content for this box could be created by going:</p>
  246. <pre>
  247. print t("Welcome visitor, ... welcome message goes here ...");
  248. </pre>
  249. <p>If we are however dealing with a registered user, we can customize the message by using:</p>
  250. <pre>
  251. global $user;
  252. if ($user->uid) {
  253. print t("Welcome $user->name, ... welcome message goes here ...");
  254. }
  255. else {
  256. print t("Welcome visitor, ... welcome message goes here ...");
  257. }
  258. </pre></blockquote>
  259. <p>For more in-depth examples, we recommend that you check the existing Drupal code and use it as a starting point, especially for sidebar boxes.</p>');
  260. }
  261. case 2:
  262. switch ($long) {
  263. case 0:
  264. return t('Lines and paragraphs break automatically.');
  265. case 1:
  266. return t('Lines and paragraphs are automatically recognized. The &lt;br /&gt; line break, &lt;p&gt; paragraph and &lt;/p&gt; close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.');
  267. }
  268. }
  269. }
  270. /**
  271. * Displays a list of all input formats and which one is the default
  272. */
  273. function filter_admin_overview() {
  274. // Overview of all formats.
  275. $formats = filter_formats();
  276. $error = false;
  277. foreach ($formats as $id => $format) {
  278. $roles = array();
  279. foreach (user_roles() as $rid => $name) {
  280. // Prepare a roles array with roles that may access the filter
  281. if (strstr($format->roles, ",$rid,")) {
  282. $roles[] = $name;
  283. }
  284. }
  285. $default = ($id == variable_get('filter_default_format', 1));
  286. $options[$id] = '';
  287. $form[$format->name]['id'] = array('#value' => $id);
  288. $form[$format->name]['roles'] = array('#value' => $default ? t('All roles may use default format') : ($roles ? implode(', ',$roles) : t('No roles may use this format')));
  289. $form[$format->name]['configure'] = array('#value' => l(t('configure'), 'admin/filters/'. $id));
  290. $form[$format->name]['delete'] = array('#value' => $default ? '' : l(t('delete'), 'admin/filters/delete/'. $id));
  291. }
  292. $form['default'] = array('#type' => 'radios', '#options' => $options, '#default_value' => variable_get('filter_default_format', 1));
  293. $form['submit'] = array('#type' => 'submit', '#value' => t('Set default format'));
  294. return drupal_get_form('filter_admin_overview', $form);
  295. }
  296. function filter_admin_overview_submit($form_id, $form_values) {
  297. // Process form submission to set the default format
  298. if (is_numeric($form_values['default'])) {
  299. drupal_set_message(t('Default format updated.'));
  300. variable_set('filter_default_format', $form_values['default']);
  301. }
  302. }
  303. function theme_filter_admin_overview($form) {
  304. $rows = array();
  305. foreach ($form as $name => $element) {
  306. if (isset($element['roles']) && is_array($element['roles'])) {
  307. $rows[] = array(
  308. form_render($form['default'][$element['id']['#value']]),
  309. check_plain($name),
  310. form_render($element['roles']),
  311. form_render($element['configure']),
  312. form_render($element['delete'])
  313. );
  314. unset($form[$name]);
  315. }
  316. }
  317. $header = array(t('Default'), t('Name'), t('Roles'), array('data' => t('Operations'), 'colspan' => 2));
  318. $output = theme('table', $header, $rows);
  319. $output .= form_render($form);
  320. return $output;
  321. }
  322. /**
  323. * Menu callback; confirm deletion of a format.
  324. */
  325. function filter_admin_delete() {
  326. $format = arg(3);
  327. $format = db_fetch_object(db_query('SELECT * FROM {filter_formats} WHERE format = %d', $format));
  328. if ($format) {
  329. if ($format->format != variable_get('filter_default_format', 1)) {
  330. $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
  331. $form['name'] = array('#type' => 'hidden', '#value' => $format->name);
  332. return confirm_form('filter_admin_delete', $form, t('Are you sure you want to delete the input format %format?', array('%format' => theme('placeholder', $format->name))), 'admin/filters', t('If you have any content left in this input format, it will be switched to the default input format. This action cannot be undone.'), t('Delete'), t('Cancel'));
  333. }
  334. else {
  335. drupal_set_message(t('The default format cannot be deleted.'));
  336. drupal_goto('admin/filters');
  337. }
  338. }
  339. else {
  340. drupal_not_found();
  341. }
  342. }
  343. /**
  344. * Process filter delete form submission.
  345. */
  346. function filter_admin_delete_submit($form_id, $form_values) {
  347. db_query("DELETE FROM {filter_formats} WHERE format = %d", $form_values['format']);
  348. db_query("DELETE FROM {filters} WHERE format = %d", $form_values['format']);
  349. $default = variable_get('filter_default_format', 1);
  350. // Replace existing instances of the deleted format with the default format.
  351. db_query("UPDATE {node_revisions} SET format = %d WHERE format = %d", $default, $form_values['format']);
  352. db_query("UPDATE {comments} SET format = %d WHERE format = %d", $default, $form_values['format']);
  353. db_query("UPDATE {boxes} SET format = %d WHERE format = %d", $default, $form_values['format']);
  354. cache_clear_all('filter:'. $form_values['format'], true);
  355. drupal_set_message(t('Deleted input format %format.', array('%format' => theme('placeholder', $form_values['name']))));
  356. return 'admin/filters';
  357. }
  358. /**
  359. * Generate a filter format form.
  360. */
  361. function filter_admin_format_form($format = NULL) {
  362. $default = ($format->format == variable_get('filter_default_format', 1));
  363. if ($default) {
  364. $help = t('All roles for the default format must be enabled and cannot be changed.');
  365. $form['default_format'] = array('#type' => 'hidden', '#value' => 1);
  366. }
  367. $form['name'] = array('#type' => 'textfield',
  368. '#title' => 'Name',
  369. '#default_value' => $format->name,
  370. '#description' => t('Specify a unique name for this filter format.'),
  371. '#required' => TRUE,
  372. );
  373. // Add a row of checkboxes for form group.
  374. $form['roles'] = array('#type' => 'fieldset',
  375. '#title' => t('Roles'),
  376. '#description' => $default ? $help : t('Choose which roles may use this filter format. Note that roles with the "administer filters" permission can always use all the filter formats.'),
  377. '#tree' => TRUE,
  378. );
  379. foreach (user_roles() as $rid => $name) {
  380. $checked = strstr($format->roles, ",$rid,");
  381. $form['roles'][$rid] = array('#type' => 'checkbox',
  382. '#title' => $name,
  383. '#default_value' => ($default || $checked),
  384. );
  385. if ($default) {
  386. $form['roles'][$rid]['#attributes'] = array('disabled' => 'disabled');
  387. }
  388. }
  389. // Table with filters
  390. $all = filter_list_all();
  391. $enabled = filter_list_format($format->format);
  392. $form['filters'] = array('#type' => 'fieldset',
  393. '#title' => t('Filters'),
  394. '#description' => t('Choose the filters that will be used in this filter format.'),
  395. '#tree' => TRUE,
  396. );
  397. foreach ($all as $id => $filter) {
  398. $form['filters'][$id] = array('#type' => 'checkbox',
  399. '#title' => $filter->name,
  400. '#default_value' => isset($enabled[$id]),
  401. '#description' => module_invoke($filter->module, 'filter', 'description', $filter->delta),
  402. );
  403. }
  404. $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
  405. if (isset($format)) {
  406. $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
  407. // Composition tips (guidelines)
  408. $tips = _filter_tips($format->format, false);
  409. $extra = l(t('More information about formatting options'), 'filter/tips');
  410. $tiplist = theme('filter_tips', $tips, false, $extra);
  411. if (!$tiplist) {
  412. $tiplist = t('<p>No guidelines available.</p>');
  413. }
  414. $group = t('<p>These are the guidelines that users will see for posting in this input format. They are automatically generated from the filter settings.</p>');
  415. $group .= $tiplist;
  416. $output = '<h2>'. t('Formatting guidelines') .'</h2>'. $group;
  417. }
  418. $output = drupal_get_form('filter_admin_format_form', $form) . $output;
  419. return $output;
  420. }
  421. /**
  422. * Validate filter format form submissions.
  423. */
  424. function filter_admin_format_form_validate($form_id, $form_values) {
  425. if (!isset($form_values['format'])) {
  426. $name = trim($form_values['name']);
  427. $result = db_fetch_object(db_query("SELECT format FROM {filter_formats} WHERE name='%s'", $name));
  428. if ($result) {
  429. form_set_error('name', t('Filter format names need to be unique. A format named %name already exists.', array('%name' => theme('placeholder', $name))));
  430. }
  431. }
  432. }
  433. /**
  434. * Process filter format form submissions.
  435. */
  436. function filter_admin_format_form_submit($form_id, $form_values) {
  437. $format = isset($form_values['format']) ? $form_values['format'] : NULL;
  438. $current = filter_list_format($format);
  439. $name = trim($form_values['name']);
  440. $cache = TRUE;
  441. // Add a new filter format.
  442. if (!$format) {
  443. $new = TRUE;
  444. db_query("INSERT INTO {filter_formats} (name) VALUES ('%s')", $name);
  445. $result = db_fetch_object(db_query("SELECT MAX(format) AS format FROM {filter_formats}"));
  446. $format = $result->format;
  447. drupal_set_message(t('Added input format %format.', array('%format' => theme('placeholder', $name))));
  448. }
  449. else {
  450. drupal_set_message(t('The input format settings have been updated.'));
  451. }
  452. db_query("DELETE FROM {filters} WHERE format = %d", $format);
  453. foreach ($form_values['filters'] as $id => $checked) {
  454. if ($checked) {
  455. list($module, $delta) = explode('/', $id);
  456. // Add new filters to the bottom.
  457. $weight = isset($current[$id]->weight) ? $current[$id]->weight : 10;
  458. db_query("INSERT INTO {filters} (format, module, delta, weight) VALUES (%d, '%s', %d, %d)", $format, $module, $delta, $weight);
  459. // Check if there are any 'no cache' filters.
  460. $cache &= !module_invoke($module, 'filter', 'no cache', $delta);
  461. }
  462. }
  463. // We store the roles as a string for ease of use.
  464. // We should always set all roles to true when saving a default role.
  465. // We use leading and trailing comma's to allow easy substring matching.
  466. $roles = array();
  467. if (isset($form_values['roles'])) {
  468. foreach ($form_values['roles'] as $id => $checked) {
  469. if ($checked) {
  470. $roles[] = $id;
  471. }
  472. }
  473. }
  474. $roles = ','. implode(',', ($form_values['default_format'] ? user_roles() : $roles)) .',';
  475. db_query("UPDATE {filter_formats} SET cache = %d, name='%s', roles = '%s' WHERE format = %d", $cache, $name, $roles, $format);
  476. cache_clear_all('filter:'. $format, true);
  477. // If a new filter was added, return to the main list of filters. Otherwise, stay on edit filter page to show new changes.
  478. if ($new) {
  479. return 'admin/filters/';
  480. }
  481. else {
  482. return 'admin/filters/'. $format;
  483. }
  484. }
  485. /**
  486. * Menu callback; display form for ordering filters for a format.
  487. */
  488. function filter_admin_order($format = NULL) {
  489. // Get list (with forced refresh)
  490. $filters = filter_list_format($format->format);
  491. $form['weights'] = array('#tree' => TRUE);
  492. foreach ($filters as $id => $filter) {
  493. $form['names'][$id] = array('#value' => $filter->name);
  494. $form['weights'][$id] = array('#type' => 'weight', '#default_value' => $filter->weight);
  495. }
  496. $form['format'] = array('#type' => 'hidden', '#value' => $format->format);
  497. $form['submit'] = array('#type' => 'submit', '#value' => t('Save configuration'));
  498. return drupal_get_form('filter_admin_order', $form);
  499. }
  500. /**
  501. * Theme filter order configuration form.
  502. */
  503. function theme_filter_admin_order($form) {
  504. $header = array(t('Name'), t('Weight'));
  505. $rows = array();
  506. foreach (element_children($form['names']) as $id) {
  507. // Don't take form control structures
  508. if (is_array($form['names'][$id])) {
  509. $rows[] = array(form_render($form['names'][$id]), form_render($form['weights'][$id]));
  510. }
  511. }
  512. $output = theme('table', $header, $rows);
  513. $output .= form_render($form);
  514. return $output;
  515. }
  516. /**
  517. * Process filter order configuration form submission.
  518. */
  519. function filter_admin_order_submit($form_id, $form_values) {
  520. foreach ($form_values['weights'] as $id => $weight) {
  521. list($module, $delta) = explode('/', $id);
  522. db_query("UPDATE {filters} SET weight = %d WHERE format = %d AND module = '%s' AND delta = %d", $weight, $form_values['format'], $module, $delta);
  523. }
  524. drupal_set_message(t('The filter ordering has been saved.'));
  525. cache_clear_all('filter:'. $form_values['format'], true);
  526. }
  527. /**
  528. * Menu callback; display settings defined by filters.
  529. */
  530. function filter_admin_configure() {
  531. $format = arg(2);
  532. $list = filter_list_format($format);
  533. $form = array();
  534. foreach ($list as $filter) {
  535. $form_module = module_invoke($filter->module, 'filter', 'settings', $filter->delta, $format);
  536. if (isset($form_module) && is_array($form_module)) {
  537. $form = array_merge($form, $form_module);
  538. }
  539. }
  540. if (!empty($form)) {
  541. $output = system_settings_form('filter_admin_configure', $form);
  542. }
  543. else {
  544. $output = t('No settings are available.');
  545. }
  546. return $output;
  547. }
  548. /**
  549. * Retrieve a list of input formats.
  550. */
  551. function filter_formats() {
  552. global $user;
  553. static $formats;
  554. // Administrators can always use all input formats.
  555. $all = user_access('administer filters');
  556. if (!isset($formats)) {
  557. $formats = array();
  558. $query = 'SELECT * FROM {filter_formats}';
  559. // Build query for selecting the format(s) based on the user's roles.
  560. if (!$all) {
  561. $where = array();
  562. foreach ($user->roles as $rid => $role) {
  563. $where[] = "roles LIKE '%%,%d,%%'";
  564. $args[] = $rid;
  565. }
  566. $query .= ' WHERE '. implode(' OR ', $where) . ' OR format = %d';
  567. $args[] = variable_get('filter_default_format', 1);
  568. }
  569. $result = db_query($query, $args);
  570. while ($format = db_fetch_object($result)) {
  571. $formats[$format->format] = $format;
  572. }
  573. }
  574. return $formats;
  575. }
  576. /**
  577. * Build a list of all filters.
  578. */
  579. function filter_list_all() {
  580. $filters = array();
  581. foreach (module_list() as $module) {
  582. $list = module_invoke($module, 'filter', 'list');
  583. if (isset($list) && is_array($list)) {
  584. foreach ($list as $delta => $name) {
  585. $filters[$module .'/'. $delta] = (object)array('module' => $module, 'delta' => $delta, 'name' => $name);
  586. }
  587. }
  588. }
  589. uasort($filters, '_filter_list_cmp');
  590. return $filters;
  591. }
  592. /**
  593. * Helper function for sorting the filter list by filter name.
  594. */
  595. function _filter_list_cmp($a, $b) {
  596. return strcmp($a->name, $b->name);
  597. }
  598. /**
  599. * Resolve a format id, including the default format.
  600. */
  601. function filter_resolve_format($format) {
  602. return $format == FILTER_FORMAT_DEFAULT ? variable_get('filter_default_format', 1) : $format;
  603. }
  604. /**
  605. * Check if text in a certain input format is allowed to be cached.
  606. */
  607. function filter_format_allowcache($format) {
  608. static $cache = array();
  609. $format = filter_resolve_format($format);
  610. if (!isset($cache[$format])) {
  611. $cache[$format] = db_result(db_query('SELECT cache FROM {filter_formats} WHERE format = %d', $format));
  612. }
  613. return $cache[$format];
  614. }
  615. /**
  616. * Retrieve a list of filters for a certain format.
  617. */
  618. function filter_list_format($format) {
  619. static $filters = array();
  620. if (!isset($filters[$format])) {
  621. $filters[$format] = array();
  622. $result = db_query("SELECT * FROM {filters} WHERE format = %d ORDER BY weight ASC", $format);
  623. while ($filter = db_fetch_object($result)) {
  624. $list = module_invoke($filter->module, 'filter', 'list');
  625. if (isset($list) && is_array($list) && isset($list[$filter->delta])) {
  626. $filter->name = $list[$filter->delta];
  627. $filters[$format][$filter->module .'/'. $filter->delta] = $filter;
  628. }
  629. }
  630. }
  631. return $filters[$format];
  632. }
  633. /**
  634. * @name Filtering functions
  635. * @{
  636. * Modules which need to have content filtered can use these functions to
  637. * interact with the filter system.
  638. *
  639. * For more info, see the hook_filter() documentation.
  640. *
  641. * Note: because filters can inject JavaScript or execute PHP code, security is
  642. * vital here. When a user supplies a $format, you should validate it with
  643. * filter_access($format) before accepting/using it. This is normally done in
  644. * the validation stage of the node system. You should for example never make a
  645. * preview of content in a disallowed format.
  646. */
  647. /**
  648. * Run all the enabled filters on a piece of text.
  649. *
  650. * @param $text
  651. * The text to be filtered.
  652. * @param $format
  653. * The format of the text to be filtered. Specify FILTER_FORMAT_DEFAULT for
  654. * the default format.
  655. * @param $check
  656. * Whether to check the $format with filter_access() first. Defaults to TRUE.
  657. * Note that this will check the permissions of the current user, so you
  658. * should specify $check = FALSE when viewing other people's content. When
  659. * showing content that is not (yet) stored in the database (eg. upon preview),
  660. * set to TRUE so the user's permissions are checked.
  661. */
  662. function check_markup($text, $format = FILTER_FORMAT_DEFAULT, $check = TRUE) {
  663. // When $check = true, do an access check on $format.
  664. if (isset($text) && (!$check || filter_access($format))) {
  665. $format = filter_resolve_format($format);
  666. // Check for a cached version of this piece of text.
  667. $id = 'filter:'. $format .':'. md5($text);
  668. if ($cached = cache_get($id)) {
  669. return $cached->data;
  670. }
  671. // See if caching is allowed for this format.
  672. $cache = filter_format_allowcache($format);
  673. // Convert all Windows and Mac newlines to a single newline,
  674. // so filters only need to deal with one possibility.
  675. $text = str_replace(array("\r\n", "\r"), "\n", $text);
  676. // Get a complete list of filters, ordered properly.
  677. $filters = filter_list_format($format);
  678. // Give filters the chance to escape HTML-like data such as code or formulas.
  679. foreach ($filters as $filter) {
  680. $text = module_invoke($filter->module, 'filter', 'prepare', $filter->delta, $format, $text);
  681. }
  682. // Perform filtering.
  683. foreach ($filters as $filter) {
  684. $text = module_invoke($filter->module, 'filter', 'process', $filter->delta, $format, $text);
  685. }
  686. // Store in cache with a minimum expiration time of 1 day.
  687. if ($cache) {
  688. cache_set($id, $text, time() + (60 * 60 * 24));
  689. }
  690. }
  691. else {
  692. $text = message_na();
  693. }
  694. return $text;
  695. }
  696. /**
  697. * Generate a selector for choosing a format in a form.
  698. *
  699. * @param $value
  700. * The ID of the format that is currently selected.
  701. * @param $weight
  702. * The weight of the input format.
  703. * @param $parents
  704. * Required when defining multiple input formats on a single node or having a different parent than 'format'.
  705. * @return
  706. * HTML for the form element.
  707. */
  708. function filter_form($value = FILTER_FORMAT_DEFAULT, $weight = NULL, $parents = array('format')) {
  709. $value = filter_resolve_format($value);
  710. $formats = filter_formats();
  711. $extra = l(t('More information about formatting options'), 'filter/tips');
  712. if (count($formats) > 1) {
  713. $form = array(
  714. '#type' => 'fieldset',
  715. '#title' => t('Input format'),
  716. '#collapsible' => TRUE,
  717. '#collapsed' => TRUE,
  718. '#weight' => $weight,
  719. '#validate' => array('filter_form_validate' => array()),
  720. );
  721. // Multiple formats available: display radio buttons with tips.
  722. foreach ($formats as $format) {
  723. $form[$format->format] = array(
  724. '#type' => 'radio',
  725. '#title' => $format->name,
  726. '#default_value' => $value,
  727. '#return_value' => $format->format,
  728. '#parents' => $parents,
  729. '#description' => theme('filter_tips', _filter_tips($format->format, false)),
  730. );
  731. }
  732. }
  733. else {
  734. // Only one format available: use a hidden form item and only show tips.
  735. $format = array_shift($formats);
  736. $form[$format->format] = array('#type' => 'value', '#value' => $format->format, '#parents' => $parents);
  737. $tips = _filter_tips(variable_get('filter_default_format', 1), false);
  738. $form['format']['guidelines'] = array(
  739. '#title' => t('Formatting guidelines'),
  740. '#value' => theme('filter_tips', $tips, false, $extra),
  741. );
  742. }
  743. $form[] = array(
  744. '#type' => 'markup',
  745. '#value' => $extra,
  746. );
  747. return $form;
  748. }
  749. function filter_form_validate($form) {
  750. foreach (element_children($form) as $key) {
  751. if ($form[$key]['#value'] == $form[$key]['#return_value']) {
  752. return;
  753. }
  754. }
  755. form_error($form, t('An illegal choice has been detected. Please contact the site administrator.'));
  756. watchdog('form', t('Illegal choice %choice in %name element.', array('%choice' => theme('placeholder', check_plain($v)), '%name' => theme('placeholder', empty($form['#title']) ? $form['#parents'][0] : $form['#title']))), WATCHDOG_ERROR);
  757. }
  758. /**
  759. * Returns true if the user is allowed to access this format.
  760. */
  761. function filter_access($format) {
  762. $format = filter_resolve_format($format);
  763. if (user_access('administer filters') || ($format == variable_get('filter_default_format', 1))) {
  764. return true;
  765. }
  766. else {
  767. $formats = filter_formats();
  768. return isset($formats[$format]);
  769. }
  770. }
  771. /**
  772. * @} End of "Filtering functions".
  773. */
  774. /**
  775. * Menu callback; show a page with long filter tips.
  776. */
  777. function filter_tips_long() {
  778. $format = arg(2);
  779. if ($format) {
  780. $output = theme('filter_tips', _filter_tips($format, true), true);
  781. }
  782. else {
  783. $output = theme('filter_tips', _filter_tips(-1, true), true);
  784. }
  785. return $output;
  786. }
  787. /**
  788. * Helper function for fetching filter tips.
  789. */
  790. function _filter_tips($format, $long = false) {
  791. if ($format == -1) {
  792. $formats = filter_formats();
  793. }
  794. else {
  795. $formats = array(db_fetch_object(db_query("SELECT * FROM {filter_formats} WHERE format = %d", $format)));
  796. }
  797. $tips = array();
  798. foreach ($formats as $format) {
  799. $filters = filter_list_format($format->format);
  800. $tips[$format->name] = array();
  801. foreach ($filters as $id => $filter) {
  802. if ($tip = module_invoke($filter->module, 'filter_tips', $filter->delta, $format->format, $long)) {
  803. $tips[$format->name][] = array('tip' => $tip, 'id' => $id);
  804. }
  805. }
  806. }
  807. return $tips;
  808. }
  809. /**
  810. * Format a set of filter tips.
  811. *
  812. * @ingroup themeable
  813. */
  814. function theme_filter_tips($tips, $long = false, $extra = '') {
  815. $output = '';
  816. $multiple = count($tips) > 1;
  817. if ($multiple) {
  818. $output = t('input formats') .':';
  819. }
  820. if (count($tips)) {
  821. if ($multiple) {
  822. $output .= '<ul>';
  823. }
  824. foreach ($tips as $name => $tiplist) {
  825. if ($multiple) {
  826. $output .= '<li>';
  827. $output .= '<strong>'. $name .'</strong>:<br />';
  828. }
  829. $tips = '';
  830. foreach ($tiplist as $tip) {
  831. $tips .= '<li'. ($long ? ' id="filter-'. str_replace("/", "-", $tip['id']) .'">' : '>') . $tip['tip'] . '</li>';
  832. }
  833. if ($tips) {
  834. $output .= "<ul class=\"tips\">$tips</ul>";
  835. }
  836. if ($multiple) {
  837. $output .= '</li>';
  838. }
  839. }
  840. if ($multiple) {
  841. $output .= '</ul>';
  842. }
  843. }
  844. return $output;
  845. }
  846. /**
  847. * @name Standard filters
  848. * @{
  849. * Filters implemented by the filter.module.
  850. */
  851. /**
  852. * Implementation of hook_filter(). Contains a basic set of essential filters.
  853. * - HTML filter:
  854. * Validates user-supplied HTML, transforming it as necessary.
  855. * - PHP evaluator:
  856. * Executes PHP code.
  857. * - Line break converter:
  858. * Converts newlines into paragraph and break tags.
  859. */
  860. function filter_filter($op, $delta = 0, $format = -1, $text = '') {
  861. switch ($op) {
  862. case 'list':
  863. return array(0 => t('HTML filter'), 1 => t('PHP evaluator'), 2 => t('Line break converter'));
  864. case 'no cache':
  865. return $delta == 1; // No caching for the PHP evaluator.
  866. case 'description':
  867. switch ($delta) {
  868. case 0:
  869. return t('Allows you to restrict if users can post HTML and which tags to filter out.');
  870. case 1:
  871. return t('Runs a piece of PHP code. The usage of this filter should be restricted to administrators only!');
  872. case 2:
  873. return t('Converts line breaks into HTML (i.e. &lt;br&gt; and &lt;p&gt; tags).');
  874. default:
  875. return;
  876. }
  877. case 'process':
  878. switch ($delta) {
  879. case 0:
  880. return _filter_html($text, $format);
  881. case 1:
  882. return drupal_eval($text);
  883. case 2:
  884. return _filter_autop($text);
  885. default:
  886. return $text;
  887. }
  888. case 'settings':
  889. switch ($delta) {
  890. case 0:
  891. return _filter_html_settings($format);
  892. default:
  893. return;
  894. }
  895. default:
  896. return $text;
  897. }
  898. }
  899. /**
  900. * Settings for the HTML filter.
  901. */
  902. function _filter_html_settings($format) {
  903. $form['filter_html'] = array('#type' => 'fieldset', '#title' => t('HTML filter'), '#collapsible' => TRUE, '#collapsed' => TRUE);
  904. $form['filter_html']["filter_html_$format"] = array('#type' => 'radios', '#title' => t('Filter HTML tags'), '#default_value' => variable_get("filter_html_$format", FILTER_HTML_STRIP), '#options' => array(FILTER_HTML_STRIP => t('Strip disallowed tags'), FILTER_HTML_ESCAPE => t('Escape all tags')), '#description' => t('How to deal with HTML tags in user-contributed content. If set to "Strip disallowed tags", dangerous tags are removed (see below). If set to "Escape tags", all HTML is escaped and presented as it was typed.'));
  905. $form['filter_html']["allowed_html_$format"] = array('#type' => 'textfield', '#title' => t('Allowed HTML tags'), '#default_value' => variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>'), '#size' => 64, '#maxlength' => 255, '#description' => t('If "Strip disallowed tags" is selected, optionally specify tags which should not be stripped. JavaScript event attributes are always stripped.'));
  906. $form['filter_html']["filter_html_help_$format"] = array('#type' => 'checkbox', '#title' => t('Display HTML help'), '#default_value' => variable_get("filter_html_help_$format", 1), '#description' => t('If enabled, Drupal will display some basic HTML help in the long filter tips.'));
  907. $form['filter_html']["filter_html_nofollow_$format"] = array('#type' => 'checkbox', '#title' => t('Spam link deterrent'), '#default_value' => variable_get("filter_html_nofollow_$format", FALSE), '#description' => t('If enabled, Drupal will add rel="nofollow" to all links, as a measure to reduce the effectiveness of spam links. Note: this will also prevent valid links from being followed by search engines, therefore it is likely most effective when enabled for anonymous users.'));
  908. return $form;
  909. }
  910. /**
  911. * HTML filter. Provides filtering of input into accepted HTML.
  912. */
  913. function _filter_html($text, $format) {
  914. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
  915. $allowed_tags = preg_split('/\s+|<|>/', variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>'), -1, PREG_SPLIT_NO_EMPTY);
  916. $text = filter_xss($text, $allowed_tags);
  917. }
  918. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_ESCAPE) {
  919. // Escape HTML
  920. $text = check_plain($text);
  921. }
  922. if (variable_get("filter_html_nofollow_$format", FALSE)) {
  923. $text = preg_replace('/<a([^>]+)>/i', '<a\\1 rel="nofollow">', $text);
  924. }
  925. return trim($text);
  926. }
  927. /**
  928. * Convert line breaks into <p> and <br> in an intelligent fashion.
  929. * Based on: http://photomatt.net/scripts/autop
  930. */
  931. function _filter_autop($text) {
  932. // All block level tags
  933. $block = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|p|h[1-6])';
  934. // Split at <pre>, <script>, <style> and </pre>, </script>, </style> tags.
  935. // We don't apply any processing to the contents of these tags to avoid messing
  936. // up code. We look for matched pairs and allow basic nesting. For example:
  937. // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
  938. $chunks = preg_split('@(</?(?:pre|script|style)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  939. // Note: PHP ensures the array consists of alternating delimiters and literals
  940. // and begins and ends with a literal (inserting NULL as required).
  941. $ignore = false;
  942. $ignoretag = '';
  943. $output = '';
  944. foreach ($chunks as $i => $chunk) {
  945. if ($i % 2) {
  946. // Opening or closing tag?
  947. $open = ($chunk[1] != '/');
  948. list($tag) = split('[ >]', substr($chunk, 2 - $open), 2);
  949. if (!$ignore) {
  950. if ($open) {
  951. $ignore = true;
  952. $ignoretag = $tag;
  953. }
  954. }
  955. // Only allow a matching tag to close it.
  956. else if (!$open && $ignoretag == $tag) {
  957. $ignore = false;
  958. $ignoretag = '';
  959. }
  960. }
  961. else if (!$ignore) {
  962. $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
  963. $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
  964. $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
  965. $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
  966. $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
  967. $chunk = preg_replace('/\n?(.+?)(?:\n\s*\n|\z)/s', "<p>$1</p>\n", $chunk); // make paragraphs, including one at the end
  968. $chunk = preg_replace('|<p>\s*</p>\n|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
  969. $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
  970. $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
  971. $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
  972. $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
  973. $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
  974. $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
  975. $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
  976. $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
  977. $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
  978. }
  979. $output .= $chunk;
  980. }
  981. return $output;
  982. }
  983. /**
  984. * Very permissive XSS/HTML filter for admin-only use.
  985. *
  986. * Use only for fields where it is impractical to use the
  987. * whole filter system, but where some (mainly inline) mark-up
  988. * is desired (so check_plain() is not acceptable).
  989. *
  990. * Allows all tags that can be used inside an HTML body, save
  991. * for scripts and styles.
  992. */
  993. function filter_xss_admin($string) {
  994. return filter_xss($string, array('a', 'abbr', 'acronym', 'address', 'b', 'bdo', 'big', 'blockquote', 'br', 'caption', 'cite', 'code', 'col', 'colgroup', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'ins', 'kbd', 'li', 'object', 'ol', 'p', 'param', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var'));
  995. }
  996. /**
  997. * Filters XSS. Based on kses by Ulf Harnhammar, see
  998. * http://sourceforge.net/projects/kses
  999. *
  1000. * For examples of various XSS attacks, see:
  1001. * http://ha.ckers.org/xss.html
  1002. *
  1003. * This code does four things:
  1004. * - Removes characters and constructs that can trick browsers
  1005. * - Makes sure all HTML entities are well-formed
  1006. * - Makes sure all HTML tags and attributes are well-formed
  1007. * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g. javascript:)
  1008. *
  1009. * @param $string
  1010. * The string with raw HTML in it. It will be stripped of everything that can cause
  1011. * an XSS attack.
  1012. * @param $allowed_tags
  1013. * An array of allowed tags.
  1014. * @param $format
  1015. * The format to use.
  1016. */
  1017. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
  1018. // Only operate on valid UTF-8 strings. This is necessary to prevent cross
  1019. // site scripting issues on Internet Explorer 6.
  1020. if (!drupal_validate_utf8($string)) {
  1021. return '';
  1022. }
  1023. // Store the input format
  1024. _filter_xss_split($allowed_tags, TRUE);
  1025. // Remove NUL characters (ignored by some browsers)
  1026. $string = str_replace(chr(0), '', $string);
  1027. // Remove Netscape 4 JS entities
  1028. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  1029. // Defuse all HTML entities
  1030. $string = str_replace('&', '&amp;', $string);
  1031. // Change back only well-formed entities in our whitelist
  1032. // Named entities
  1033. $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
  1034. // Decimal numeric entities
  1035. $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
  1036. // Hexadecimal numeric entities
  1037. $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
  1038. return preg_replace_callback('%
  1039. (
  1040. <[^>]*.(>|$) # a string that starts with a <, up until the > or the end of the string
  1041. | # or
  1042. > # just a >
  1043. )%x', '_filter_xss_split', $string);
  1044. }
  1045. /**
  1046. * Processes an HTML tag.
  1047. *
  1048. * @param @m
  1049. * An array with various meaning depending on the value of $store.
  1050. * If $store is TRUE then the array contains the allowed tags.
  1051. * If $store is FALSE then the array has one element, the HTML tag to process.
  1052. * @param $store
  1053. * Whether to store $m.
  1054. * @return
  1055. * If the element isn't allowed, an empty string. Otherwise, the cleaned up
  1056. * version of the HTML element.
  1057. */
  1058. function _filter_xss_split($m, $store = FALSE) {
  1059. static $allowed_html;
  1060. if ($store) {
  1061. $allowed_html = array_flip($m);
  1062. return;
  1063. }
  1064. $string = $m[1];
  1065. if (substr($string, 0, 1) != '<') {
  1066. // We matched a lone ">" character
  1067. return '&gt;';
  1068. }
  1069. if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches)) {
  1070. // Seriously malformed
  1071. return '';
  1072. }
  1073. $slash = trim($matches[1]);
  1074. $elem = &$matches[2];
  1075. $attrlist = &$matches[3];
  1076. if (!isset($allowed_html[strtolower($elem)])) {
  1077. // Disallowed HTML element
  1078. return '';
  1079. }
  1080. if ($slash != '') {
  1081. return "</$elem>";
  1082. }
  1083. // Is there a closing XHTML slash at the end of the attributes?
  1084. // In PHP 5.1.0+ we could count the changes, currently we need a separate match
  1085. $xhtml_slash = preg_match('%\s?/\s*$%', $attrlist) ? ' /' : '';
  1086. $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist);
  1087. // Clean up attributes
  1088. $attr2 = implode(' ', _filter_xss_attributes($attrlist));
  1089. $attr2 = preg_replace('/[<>]/', '', $attr2);
  1090. $attr2 = strlen($attr2) ? ' '. $attr2 : '';
  1091. return "<$elem$attr2$xhtml_slash>";
  1092. }
  1093. /**
  1094. * Processes a string of HTML attributes.
  1095. *
  1096. * @return
  1097. * Cleaned up version of the HTML attributes.
  1098. */
  1099. function _filter_xss_attributes($attr) {
  1100. $attrarr = array();
  1101. $mode = 0;
  1102. $attrname = '';
  1103. while (strlen($attr) != 0) {
  1104. // Was the last operation successful?
  1105. $working = 0;
  1106. switch ($mode) {
  1107. case 0:
  1108. // Attribute name, href for instance
  1109. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
  1110. $attrname = strtolower($match[1]);
  1111. $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
  1112. $working = $mode = 1;
  1113. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  1114. }
  1115. break;
  1116. case 1:
  1117. // Equals sign or valueless ("selected")
  1118. if (preg_match('/^\s*=\s*/', $attr)) {
  1119. $working = 1; $mode = 2;
  1120. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  1121. break;
  1122. }
  1123. if (preg_match('/^\s+/', $attr)) {
  1124. $working = 1; $mode = 0;
  1125. if (!$skip) {
  1126. $attrarr[] = $attrname;
  1127. }
  1128. $attr = preg_replace('/^\s+/', '', $attr);
  1129. }
  1130. break;
  1131. case 2:
  1132. // Attribute value, a URL after href= for instance
  1133. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
  1134. $thisval = filter_xss_bad_protocol($match[1]);
  1135. if (!$skip) {
  1136. $attrarr[] = "$attrname=\"$thisval\"";
  1137. }
  1138. $working = 1;
  1139. $mode = 0;
  1140. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  1141. break;
  1142. }
  1143. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
  1144. $thisval = filter_xss_bad_protocol($match[1]);
  1145. if (!$skip) {
  1146. $attrarr[] = "$attrname='$thisval'";;
  1147. }
  1148. $working = 1; $mode = 0;
  1149. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  1150. break;
  1151. }
  1152. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
  1153. $thisval = filter_xss_bad_protocol($match[1]);
  1154. if (!$skip) {
  1155. $attrarr[] = "$attrname=\"$thisval\"";
  1156. }
  1157. $working = 1; $mode = 0;
  1158. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  1159. }
  1160. break;
  1161. }
  1162. if ($working == 0) {
  1163. // not well formed, remove and try again
  1164. $attr = preg_replace('/
  1165. ^
  1166. (
  1167. "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
  1168. | # or
  1169. \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
  1170. | # or
  1171. \S # - a non-whitespace character
  1172. )* # any number of the above three
  1173. \s* # any number of whitespaces
  1174. /x', '', $attr);
  1175. $mode = 0;
  1176. }
  1177. }
  1178. // the attribute list ends with a valueless attribute like "selected"
  1179. if ($mode == 1) {
  1180. $attrarr[] = $attrname;
  1181. }
  1182. return $attrarr;
  1183. }
  1184. /**
  1185. * Processes an HTML attribute value and ensures it does not contain an URL
  1186. * with a disallowed protocol (e.g. javascript:)
  1187. *
  1188. * @param $string
  1189. * The string with the attribute value.
  1190. * @param $decode
  1191. * Whether to decode entities in the $string. Set to FALSE if the $string
  1192. * is in plain text, TRUE otherwise. Defaults to TRUE.
  1193. * @return
  1194. * Cleaned up and HTML-escaped version of $string.
  1195. */
  1196. function filter_xss_bad_protocol($string, $decode = TRUE) {
  1197. static $allowed_protocols;
  1198. if (!isset($allowed_protocols)) {
  1199. $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal')));
  1200. }
  1201. // Get the plain text representation of the attribute value (i.e. its meaning)
  1202. if ($decode) {
  1203. $string = decode_entities($string);
  1204. }
  1205. // Iteratively remove any invalid protocol found.
  1206. do {
  1207. $before = $string;
  1208. $colonpos = strpos($string, ':');
  1209. if ($colonpos > 0) {
  1210. // We found a colon, possibly a protocol. Verify.
  1211. $protocol = substr($string, 0, $colonpos);
  1212. // If a colon is preceded by a slash, question mark or hash, it cannot
  1213. // possibly be part of the URL scheme. This must be a relative URL,
  1214. // which inherits the (safe) protocol of the base document.
  1215. if (preg_match('![/?#]!', $protocol)) {
  1216. break;
  1217. }
  1218. // Check if this is a disallowed protocol
  1219. if (!isset($allowed_protocols[$protocol])) {
  1220. $string = substr($string, $colonpos + 1);
  1221. }
  1222. }
  1223. } while ($before != $string);
  1224. return check_plain($string);
  1225. }
  1226. /**
  1227. * @} End of "Standard filters".
  1228. */
Login or register to post comments