filter.module

You are here

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

Framework for handling filtering of content.

Functions

Namesort descending Description
check_markup Run all the enabled filters on a piece of text.
filter_access Returns TRUE if the user is allowed to access this format.
filter_admin_format_title Display a filter format form title.
filter_cron Implementation of hook_cron().
filter_filter Implementation of hook_filter().
filter_filter_tips Implementation of hook_filter_tips().
filter_form Generates a selector for choosing a format in a form.
filter_formats Retrieve a list of input formats.
filter_format_allowcache Check if text in a certain input format is allowed to be cached.
filter_format_load
filter_form_validate Validation callback for filter elements in a form.
filter_help Implementation of hook_help().
filter_list_all Build a list of all filters.
filter_list_format Retrieve a list of filters for a certain format.
filter_menu Implementation of hook_menu().
filter_perm Implementation of hook_perm().
filter_resolve_format Resolve a format id, including the default format.
filter_theme Implementation of hook_theme()
filter_xss Filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.
filter_xss_admin Very permissive XSS/HTML filter for admin-only use.
filter_xss_bad_protocol Processes an HTML attribute value and ensures it does not contain an URL with a disallowed protocol (e.g. javascript:)
theme_filter_tips_more_info Format a link to the more extensive filter tips.
_filter_autop Convert line breaks into <p> and <br> in an intelligent fashion. Based on: http://photomatt.net/scripts/autop
_filter_html HTML filter. Provides filtering of input into accepted HTML.
_filter_htmlcorrector Scan input and make sure that all HTML tags are properly closed and nested.
_filter_html_settings Settings for the HTML filter.
_filter_list_cmp Helper function for sorting the filter list by filter name.
_filter_tips Helper function for fetching filter tips.
_filter_url URL filter. Automatically converts text web addresses (URLs, e-mail addresses, FTP links, etc.) into hyperlinks.
_filter_url_parse_full_links Make links out of absolute URLs.
_filter_url_parse_partial_links Make links out of domain names starting with "www."
_filter_url_settings Settings for URL filter.
_filter_url_trim Shortens long URLs to http://www.example.com/long/url...
_filter_xss_attributes Processes a string of HTML attributes.
_filter_xss_split Processes an HTML tag.

Constants

File

modules/filter/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($path, $arg) {
  16. switch ($path) {
  17. case 'admin/help#filter':
  18. $output = '<p>'. t("The filter module allows administrators to configure text input formats for use on your site. An input format defines the HTML tags, codes, and other input allowed in both content and comments, and is a key feature in guarding against potentially damaging input from malicious users. Two input formats included by default are <em>Filtered HTML</em> (which allows only an administrator-approved subset of HTML tags) and <em>Full HTML</em> (which allows the full set of HTML tags). Additional input formats may be created by an administrator.") .'</p>';
  19. $output .= '<p>'. t('Each input format uses filters to manipulate text, and most input formats apply several different filters to text in a specific order. Each filter is designed for a specific purpose, and generally either adds, removes or transforms elements within user-entered text before it is displayed. A filter does not change the actual content of a post, but instead, modifies it temporarily before it is displayed. A filter may remove unapproved HTML tags, for instance, while another automatically adds HTML to make links referenced in text clickable.') .'</p>';
  20. $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.') .'</p>';
  21. $output .= '<p>'. t('For more information, see the online handbook entry for <a href="@filter">Filter module</a>.', array('@filter' => 'http://drupal.org/handbook/modules/filter/')) .'</p>';
  22. return $output;
  23. case 'admin/settings/filters':
  24. $output = '<p>'. t('<em>Input formats</em> define a way of processing user-supplied text in Drupal. Each input format uses filters to manipulate text, and most input formats apply several different filters to text, in a specific order. Each filter is designed to accomplish a specific purpose, and generally either removes elements from or adds elements to text before it is displayed. Users can choose between the available input formats when submitting content.') .'</p>';
  25. $output .= '<p>'. t('Use the list below to configure which input formats are available to which roles, as well as choose a default input format (used for imported content, for example). The default format is always available to users. All input formats are available to users in a role with the "administer filters" permission.') .'</p>';
  26. return $output;
  27. case 'admin/settings/filters/%':
  28. return '<p>'. t('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. If you notice some filters are causing conflicts in the output, you can <a href="@rearrange">rearrange them</a>.', array('@rearrange' => url('admin/settings/filters/'. $arg[3] .'/order'))) .'</p>';
  29. case 'admin/settings/filters/%/configure':
  30. return '<p>'. t('If you cannot find the settings for a certain filter, make sure you have enabled it on the <a href="@url">view tab</a> first.', array('@url' => url('admin/settings/filters/'. $arg[3]))) .'</p>';
  31. case 'admin/settings/filters/%/order':
  32. $output = '<p>'. t('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 to a clickable link. When this happens, rearrange the order of the filters.') .'</p>';
  33. $output .= '<p>'. t("Filters are executed from top-to-bottom. To change the order of the filters, modify the values in the <em>Weight</em> column or grab a drag-and-drop handle under the <em>Name</em> column and drag filters to new locations in the list. (Grab a handle by clicking and holding the mouse while hovering over a handle icon.) Remember that your changes will not be saved until you click the <em>Save configuration</em> button at the bottom of the page.") .'</p>';
  34. return $output;
  35. }
  36. }
  37. /**
  38. * Implementation of hook_theme()
  39. */
  40. function filter_theme() {
  41. return array(
  42. 'filter_admin_overview' => array(
  43. 'arguments' => array('form' => NULL),
  44. 'file' => 'filter.admin.inc',
  45. ),
  46. 'filter_admin_order' => array(
  47. 'arguments' => array('form' => NULL),
  48. 'file' => 'filter.admin.inc',
  49. ),
  50. 'filter_tips' => array(
  51. 'arguments' => array('tips' => NULL, 'long' => FALSE, 'extra' => ''),
  52. 'file' => 'filter.pages.inc',
  53. ),
  54. 'filter_tips_more_info' => array(
  55. 'arguments' => array(),
  56. ),
  57. );
  58. }
  59. /**
  60. * Implementation of hook_menu().
  61. */
  62. function filter_menu() {
  63. $items['admin/settings/filters'] = array(
  64. 'title' => 'Input formats',
  65. 'description' => 'Configure how content input by users is filtered, including allowed HTML tags. Also allows enabling of module-provided filters.',
  66. 'page callback' => 'drupal_get_form',
  67. 'page arguments' => array('filter_admin_overview'),
  68. 'access arguments' => array('administer filters'),
  69. 'file' => 'filter.admin.inc',
  70. );
  71. $items['admin/settings/filters/list'] = array(
  72. 'title' => 'List',
  73. 'type' => MENU_DEFAULT_LOCAL_TASK,
  74. );
  75. $items['admin/settings/filters/add'] = array(
  76. 'title' => 'Add input format',
  77. 'page callback' => 'filter_admin_format_page',
  78. 'access arguments' => array('administer filters'),
  79. 'type' => MENU_LOCAL_TASK,
  80. 'weight' => 1,
  81. 'file' => 'filter.admin.inc',
  82. );
  83. $items['admin/settings/filters/delete'] = array(
  84. 'title' => 'Delete input format',
  85. 'page callback' => 'drupal_get_form',
  86. 'page arguments' => array('filter_admin_delete'),
  87. 'access arguments' => array('administer filters'),
  88. 'type' => MENU_CALLBACK,
  89. 'file' => 'filter.admin.inc',
  90. );
  91. $items['filter/tips'] = array(
  92. 'title' => 'Compose tips',
  93. 'page callback' => 'filter_tips_long',
  94. 'access callback' => TRUE,
  95. 'type' => MENU_SUGGESTED_ITEM,
  96. 'file' => 'filter.pages.inc',
  97. );
  98. $items['admin/settings/filters/%filter_format'] = array(
  99. 'type' => MENU_CALLBACK,
  100. 'title callback' => 'filter_admin_format_title',
  101. 'title arguments' => array(3),
  102. 'page callback' => 'filter_admin_format_page',
  103. 'page arguments' => array(3),
  104. 'access arguments' => array('administer filters'),
  105. 'file' => 'filter.admin.inc',
  106. );
  107. $items['admin/settings/filters/%filter_format/edit'] = array(
  108. 'title' => 'Edit',
  109. 'type' => MENU_DEFAULT_LOCAL_TASK,
  110. 'weight' => 0,
  111. 'file' => 'filter.admin.inc',
  112. );
  113. $items['admin/settings/filters/%filter_format/configure'] = array(
  114. 'title' => 'Configure',
  115. 'page callback' => 'filter_admin_configure_page',
  116. 'page arguments' => array(3),
  117. 'access arguments' => array('administer filters'),
  118. 'type' => MENU_LOCAL_TASK,
  119. 'weight' => 1,
  120. 'file' => 'filter.admin.inc',
  121. );
  122. $items['admin/settings/filters/%filter_format/order'] = array(
  123. 'title' => 'Rearrange',
  124. 'page callback' => 'filter_admin_order_page',
  125. 'page arguments' => array(3),
  126. 'access arguments' => array('administer filters'),
  127. 'type' => MENU_LOCAL_TASK,
  128. 'weight' => 2,
  129. 'file' => 'filter.admin.inc',
  130. );
  131. return $items;
  132. }
  133. function filter_format_load($arg) {
  134. return filter_formats($arg);
  135. }
  136. /**
  137. * Display a filter format form title.
  138. */
  139. function filter_admin_format_title($format) {
  140. return $format->name;
  141. }
  142. /**
  143. * Implementation of hook_perm().
  144. */
  145. function filter_perm() {
  146. return array('administer filters');
  147. }
  148. /**
  149. * Implementation of hook_cron().
  150. *
  151. * Expire outdated filter cache entries
  152. */
  153. function filter_cron() {
  154. cache_clear_all(NULL, 'cache_filter');
  155. }
  156. /**
  157. * Implementation of hook_filter_tips().
  158. */
  159. function filter_filter_tips($delta, $format, $long = FALSE) {
  160. global $base_url;
  161. switch ($delta) {
  162. case 0:
  163. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
  164. if ($allowed_html = variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>')) {
  165. switch ($long) {
  166. case 0:
  167. return t('Allowed HTML tags: @tags', array('@tags' => $allowed_html));
  168. case 1:
  169. $output = '<p>'. t('Allowed HTML tags: @tags', array('@tags' => $allowed_html)) .'</p>';
  170. if (!variable_get("filter_html_help_$format", 1)) {
  171. return $output;
  172. }
  173. $output .= t('
  174. <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>
  175. <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>');
  176. $tips = array(
  177. 'a' => array( t('Anchors are used to make links to other pages.'), '<a href="'. $base_url .'">'. variable_get('site_name', 'Drupal') .'</a>'),
  178. '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')),
  179. '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>'),
  180. 'strong' => array( t('Strong'), '<strong>'. t('Strong') .'</strong>'),
  181. 'em' => array( t('Emphasized'), '<em>'. t('Emphasized') .'</em>'),
  182. 'cite' => array( t('Cited'), '<cite>'. t('Cited') .'</cite>'),
  183. 'code' => array( t('Coded text used to show programming source code'), '<code>'. t('Coded') .'</code>'),
  184. 'b' => array( t('Bolded'), '<b>'. t('Bolded') .'</b>'),
  185. 'u' => array( t('Underlined'), '<u>'. t('Underlined') .'</u>'),
  186. 'i' => array( t('Italicized'), '<i>'. t('Italicized') .'</i>'),
  187. 'sup' => array( t('Superscripted'), t('<sup>Super</sup>scripted')),
  188. 'sub' => array( t('Subscripted'), t('<sub>Sub</sub>scripted')),
  189. 'pre' => array( t('Preformatted'), '<pre>'. t('Preformatted') .'</pre>'),
  190. 'abbr' => array( t('Abbreviation'), t('<abbr title="Abbreviation">Abbrev.</abbr>')),
  191. 'acronym' => array( t('Acronym'), t('<acronym title="Three-Letter Acronym">TLA</acronym>')),
  192. 'blockquote' => array( t('Block quoted'), '<blockquote>'. t('Block quoted') .'</blockquote>'),
  193. 'q' => array( t('Quoted inline'), '<q>'. t('Quoted inline') .'</q>'),
  194. // Assumes and describes tr, td, th.
  195. 'table' => array( t('Table'), '<table> <tr><th>'. t('Table header') .'</th></tr> <tr><td>'. t('Table cell') .'</td></tr> </table>'),
  196. 'tr' => NULL, 'td' => NULL, 'th' => NULL,
  197. 'del' => array( t('Deleted'), '<del>'. t('Deleted') .'</del>'),
  198. 'ins' => array( t('Inserted'), '<ins>'. t('Inserted') .'</ins>'),
  199. // Assumes and describes li.
  200. '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>'),
  201. '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>'),
  202. 'li' => NULL,
  203. // Assumes and describes dt and dd.
  204. '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>'),
  205. 'dt' => NULL, 'dd' => NULL,
  206. 'h1' => array( t('Header'), '<h1>'. t('Title') .'</h1>'),
  207. 'h2' => array( t('Header'), '<h2>'. t('Subtitle') .'</h2>'),
  208. 'h3' => array( t('Header'), '<h3>'. t('Subtitle three') .'</h3>'),
  209. 'h4' => array( t('Header'), '<h4>'. t('Subtitle four') .'</h4>'),
  210. 'h5' => array( t('Header'), '<h5>'. t('Subtitle five') .'</h5>'),
  211. 'h6' => array( t('Header'), '<h6>'. t('Subtitle six') .'</h6>')
  212. );
  213. $header = array(t('Tag Description'), t('You Type'), t('You Get'));
  214. preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out);
  215. foreach ($out[1] as $tag) {
  216. if (array_key_exists($tag, $tips)) {
  217. if ($tips[$tag]) {
  218. $rows[] = array(
  219. array('data' => $tips[$tag][0], 'class' => 'description'),
  220. array('data' => '<code>'. check_plain($tips[$tag][1]) .'</code>', 'class' => 'type'),
  221. array('data' => $tips[$tag][1], 'class' => 'get')
  222. );
  223. }
  224. }
  225. else {
  226. $rows[] = array(
  227. array('data' => t('No help provided for tag %tag.', array('%tag' => $tag)), 'class' => 'description', 'colspan' => 3),
  228. );
  229. }
  230. }
  231. $output .= theme('table', $header, $rows);
  232. $output .= t('
  233. <p>Most unusual characters can be directly entered without any problems.</p>
  234. <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>');
  235. $entities = array(
  236. array( t('Ampersand'), '&amp;'),
  237. array( t('Greater than'), '&gt;'),
  238. array( t('Less than'), '&lt;'),
  239. array( t('Quotation mark'), '&quot;'),
  240. );
  241. $header = array(t('Character Description'), t('You Type'), t('You Get'));
  242. unset($rows);
  243. foreach ($entities as $entity) {
  244. $rows[] = array(
  245. array('data' => $entity[0], 'class' => 'description'),
  246. array('data' => '<code>'. check_plain($entity[1]) .'</code>', 'class' => 'type'),
  247. array('data' => $entity[1], 'class' => 'get')
  248. );
  249. }
  250. $output .= theme('table', $header, $rows);
  251. return $output;
  252. }
  253. }
  254. else {
  255. return t('No HTML tags allowed');
  256. }
  257. }
  258. break;
  259. case 1:
  260. switch ($long) {
  261. case 0:
  262. return t('Lines and paragraphs break automatically.');
  263. case 1:
  264. 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.');
  265. }
  266. break;
  267. case 2:
  268. return t('Web page addresses and e-mail addresses turn into links automatically.');
  269. }
  270. }
  271. /**
  272. * Retrieve a list of input formats.
  273. */
  274. function filter_formats($index = NULL) {
  275. global $user;
  276. static $formats;
  277. // Administrators can always use all input formats.
  278. $all = user_access('administer filters');
  279. if (!isset($formats)) {
  280. $formats = array();
  281. $query = 'SELECT * FROM {filter_formats}';
  282. // Build query for selecting the format(s) based on the user's roles.
  283. $args = array();
  284. if (!$all) {
  285. $where = array();
  286. foreach ($user->roles as $rid => $role) {
  287. $where[] = "roles LIKE '%%,%d,%%'";
  288. $args[] = $rid;
  289. }
  290. $query .= ' WHERE '. implode(' OR ', $where) .' OR format = %d';
  291. $args[] = variable_get('filter_default_format', 1);
  292. }
  293. $result = db_query($query, $args);
  294. while ($format = db_fetch_object($result)) {
  295. $formats[$format->format] = $format;
  296. }
  297. }
  298. if (isset($index)) {
  299. return isset($formats[$index]) ? $formats[$index] : FALSE;
  300. }
  301. return $formats;
  302. }
  303. /**
  304. * Build a list of all filters.
  305. */
  306. function filter_list_all() {
  307. $filters = array();
  308. foreach (module_list() as $module) {
  309. $list = module_invoke($module, 'filter', 'list');
  310. if (isset($list) && is_array($list)) {
  311. foreach ($list as $delta => $name) {
  312. $filters[$module .'/'. $delta] = (object)array('module' => $module, 'delta' => $delta, 'name' => $name);
  313. }
  314. }
  315. }
  316. uasort($filters, '_filter_list_cmp');
  317. return $filters;
  318. }
  319. /**
  320. * Helper function for sorting the filter list by filter name.
  321. */
  322. function _filter_list_cmp($a, $b) {
  323. return strcmp($a->name, $b->name);
  324. }
  325. /**
  326. * Resolve a format id, including the default format.
  327. */
  328. function filter_resolve_format($format) {
  329. return $format == FILTER_FORMAT_DEFAULT ? variable_get('filter_default_format', 1) : $format;
  330. }
  331. /**
  332. * Check if text in a certain input format is allowed to be cached.
  333. */
  334. function filter_format_allowcache($format) {
  335. static $cache = array();
  336. $format = filter_resolve_format($format);
  337. if (!isset($cache[$format])) {
  338. $cache[$format] = db_result(db_query('SELECT cache FROM {filter_formats} WHERE format = %d', $format));
  339. }
  340. return $cache[$format];
  341. }
  342. /**
  343. * Retrieve a list of filters for a certain format.
  344. */
  345. function filter_list_format($format) {
  346. static $filters = array();
  347. if (!isset($filters[$format])) {
  348. $result = db_query("SELECT * FROM {filters} WHERE format = %d ORDER BY weight, module, delta", $format);
  349. if (db_affected_rows($result) == 0 && !db_result(db_query("SELECT 1 FROM {filter_formats} WHERE format = %d", $format))) {
  350. // The format has no filters and does not exist, use the default input
  351. // format.
  352. $filters[$format] = filter_list_format(variable_get('filter_default_format', 1));
  353. }
  354. else {
  355. $filters[$format] = array();
  356. while ($filter = db_fetch_object($result)) {
  357. $list = module_invoke($filter->module, 'filter', 'list');
  358. if (isset($list) && is_array($list) && isset($list[$filter->delta])) {
  359. $filter->name = $list[$filter->delta];
  360. $filters[$format][$filter->module .'/'. $filter->delta] = $filter;
  361. }
  362. }
  363. }
  364. }
  365. return $filters[$format];
  366. }
  367. /**
  368. * @defgroup filtering_functions Filtering functions
  369. * @{
  370. * Functions for interacting with the content filtering system.
  371. *
  372. * For more info, see the hook_filter() documentation.
  373. *
  374. * Note: because filters can inject JavaScript or execute PHP code, security is
  375. * vital here. When a user supplies a $format, you should validate it with
  376. * filter_access($format) before accepting/using it. This is normally done in
  377. * the validation stage of the node system. You should for example never make a
  378. * preview of content in a disallowed format.
  379. */
  380. /**
  381. * Run all the enabled filters on a piece of text.
  382. *
  383. * @param $text
  384. * The text to be filtered.
  385. * @param $format
  386. * The format of the text to be filtered. Specify FILTER_FORMAT_DEFAULT for
  387. * the default format.
  388. * @param $check
  389. * Whether to check the $format with filter_access() first. Defaults to TRUE.
  390. * Note that this will check the permissions of the current user, so you
  391. * should specify $check = FALSE when viewing other people's content. When
  392. * showing content that is not (yet) stored in the database (eg. upon preview),
  393. * set to TRUE so the user's permissions are checked.
  394. */
  395. function check_markup($text, $format = FILTER_FORMAT_DEFAULT, $check = TRUE) {
  396. // When $check = TRUE, do an access check on $format.
  397. if (isset($text) && (!$check || filter_access($format))) {
  398. $format = filter_resolve_format($format);
  399. // Check for a cached version of this piece of text.
  400. $cache_id = $format .':'. md5($text);
  401. if ($cached = cache_get($cache_id, 'cache_filter')) {
  402. return $cached->data;
  403. }
  404. // See if caching is allowed for this format.
  405. $cache = filter_format_allowcache($format);
  406. // Convert all Windows and Mac newlines to a single newline,
  407. // so filters only need to deal with one possibility.
  408. $text = str_replace(array("\r\n", "\r"), "\n", $text);
  409. // Get a complete list of filters, ordered properly.
  410. $filters = filter_list_format($format);
  411. // Give filters the chance to escape HTML-like data such as code or formulas.
  412. foreach ($filters as $filter) {
  413. $text = module_invoke($filter->module, 'filter', 'prepare', $filter->delta, $format, $text, $cache_id);
  414. }
  415. // Perform filtering.
  416. foreach ($filters as $filter) {
  417. $text = module_invoke($filter->module, 'filter', 'process', $filter->delta, $format, $text, $cache_id);
  418. }
  419. // Store in cache with a minimum expiration time of 1 day.
  420. if ($cache) {
  421. cache_set($cache_id, $text, 'cache_filter', time() + (60 * 60 * 24));
  422. }
  423. }
  424. else {
  425. $text = t('n/a');
  426. }
  427. return $text;
  428. }
  429. /**
  430. * Generates a selector for choosing a format in a form.
  431. *
  432. * @param $value
  433. * The ID of the format that is currently selected; uses the default format
  434. * if not provided.
  435. * @param $weight
  436. * The weight of the form element within the form.
  437. * @param $parents
  438. * The parents array of the element. Required when defining multiple text
  439. * formats on a single form or having a different parent than 'format'.
  440. *
  441. * @return
  442. * Form API array for the form element.
  443. *
  444. * @see filter_form_validate()
  445. * @ingroup forms
  446. */
  447. function filter_form($value = FILTER_FORMAT_DEFAULT, $weight = NULL, $parents = array('format')) {
  448. $value = filter_resolve_format($value);
  449. $formats = filter_formats();
  450. $extra = theme('filter_tips_more_info');
  451. if (count($formats) > 1) {
  452. $form = array(
  453. '#type' => 'fieldset',
  454. '#title' => t('Input format'),
  455. '#collapsible' => TRUE,
  456. '#collapsed' => TRUE,
  457. '#weight' => $weight,
  458. '#element_validate' => array('filter_form_validate'),
  459. );
  460. // Multiple formats available: display radio buttons with tips.
  461. foreach ($formats as $format) {
  462. // Generate the parents as the autogenerator does, so we will have a
  463. // unique id for each radio button.
  464. $parents_for_id = array_merge($parents, array($format->format));
  465. $form[$format->format] = array(
  466. '#type' => 'radio',
  467. '#title' => $format->name,
  468. '#default_value' => $value,
  469. '#return_value' => $format->format,
  470. '#parents' => $parents,
  471. '#description' => theme('filter_tips', _filter_tips($format->format, FALSE)),
  472. '#id' => form_clean_id('edit-'. implode('-', $parents_for_id)),
  473. );
  474. }
  475. }
  476. else {
  477. // Only one format available: use a hidden form item and only show tips.
  478. $format = array_shift($formats);
  479. $form[$format->format] = array('#type' => 'value', '#value' => $format->format, '#parents' => $parents);
  480. $tips = _filter_tips(variable_get('filter_default_format', 1), FALSE);
  481. $form['format']['guidelines'] = array(
  482. '#title' => t('Formatting guidelines'),
  483. '#value' => theme('filter_tips', $tips, FALSE, $extra),
  484. );
  485. }
  486. $form[] = array('#value' => $extra);
  487. return $form;
  488. }
  489. /**
  490. * Validation callback for filter elements in a form.
  491. *
  492. * @see filter_form().
  493. */
  494. function filter_form_validate($form) {
  495. foreach (element_children($form) as $key) {
  496. if ($form[$key]['#value'] == $form[$key]['#return_value']) {
  497. return;
  498. }
  499. }
  500. form_error($form, t('An illegal choice has been detected. Please contact the site administrator.'));
  501. watchdog('form', 'Illegal choice %choice in %name element.', array('%choice' => $form[$key]['#value'], '%name' => empty($form['#title']) ? $form['#parents'][0] : $form['#title']), WATCHDOG_ERROR);
  502. }
  503. /**
  504. * Returns TRUE if the user is allowed to access this format.
  505. */
  506. function filter_access($format) {
  507. $format = filter_resolve_format($format);
  508. if (user_access('administer filters') || ($format == variable_get('filter_default_format', 1))) {
  509. return TRUE;
  510. }
  511. else {
  512. $formats = filter_formats();
  513. return isset($formats[$format]);
  514. }
  515. }
  516. /**
  517. * @} End of "Filtering functions".
  518. */
  519. /**
  520. * Helper function for fetching filter tips.
  521. */
  522. function _filter_tips($format, $long = FALSE) {
  523. if ($format == -1) {
  524. $formats = filter_formats();
  525. }
  526. else {
  527. $formats = array(db_fetch_object(db_query("SELECT * FROM {filter_formats} WHERE format = %d", $format)));
  528. }
  529. $tips = array();
  530. foreach ($formats as $format) {
  531. $filters = filter_list_format($format->format);
  532. $tips[$format->name] = array();
  533. foreach ($filters as $id => $filter) {
  534. if ($tip = module_invoke($filter->module, 'filter_tips', $filter->delta, $format->format, $long)) {
  535. $tips[$format->name][] = array('tip' => $tip, 'id' => $id);
  536. }
  537. }
  538. }
  539. return $tips;
  540. }
  541. /**
  542. * Format a link to the more extensive filter tips.
  543. *
  544. * @ingroup themeable
  545. */
  546. function theme_filter_tips_more_info() {
  547. return '<p>'. l(t('More information about formatting options'), 'filter/tips') .'</p>';
  548. }
  549. /**
  550. * @defgroup standard_filters Standard filters
  551. * @{
  552. * Filters implemented by the filter.module.
  553. */
  554. /**
  555. * Implementation of hook_filter().
  556. *
  557. * Sets up a basic set of essential filters.
  558. * - HTML filter: Restricts user-supplied HTML to certain tags, and removes
  559. * dangerous components in allowed tags.
  560. * - Line break converter: Converts newlines into paragraph and break tags.
  561. * - URL filter: Converts URLs and e-mail addresses into links.
  562. * - HTML corrector: Fixes faulty HTML.
  563. */
  564. function filter_filter($op, $delta = 0, $format = -1, $text = '') {
  565. switch ($op) {
  566. case 'list':
  567. return array(0 => t('HTML filter'), 1 => t('Line break converter'), 2 => t('URL filter'), 3 => t('HTML corrector'));
  568. case 'description':
  569. switch ($delta) {
  570. case 0:
  571. return t('Allows you to restrict whether users can post HTML and which tags to filter out. It will also remove harmful content such as JavaScript events, JavaScript URLs and CSS styles from those tags that are not removed.');
  572. case 1:
  573. return t('Converts line breaks into HTML (i.e. &lt;br&gt; and &lt;p&gt; tags).');
  574. case 2:
  575. return t('Turns web and e-mail addresses into clickable links.');
  576. case 3:
  577. return t('Corrects faulty and chopped off HTML in postings.');
  578. default:
  579. return;
  580. }
  581. case 'process':
  582. switch ($delta) {
  583. case 0:
  584. return _filter_html($text, $format);
  585. case 1:
  586. return _filter_autop($text);
  587. case 2:
  588. return _filter_url($text, $format);
  589. case 3:
  590. return _filter_htmlcorrector($text);
  591. default:
  592. return $text;
  593. }
  594. case 'settings':
  595. switch ($delta) {
  596. case 0:
  597. return _filter_html_settings($format);
  598. case 2:
  599. return _filter_url_settings($format);
  600. default:
  601. return;
  602. }
  603. default:
  604. return $text;
  605. }
  606. }
  607. /**
  608. * Settings for the HTML filter.
  609. */
  610. function _filter_html_settings($format) {
  611. $form['filter_html'] = array(
  612. '#type' => 'fieldset',
  613. '#title' => t('HTML filter'),
  614. '#collapsible' => TRUE,
  615. );
  616. $form['filter_html']["filter_html_$format"] = array(
  617. '#type' => 'radios',
  618. '#title' => t('Filter HTML tags'),
  619. '#default_value' => variable_get("filter_html_$format", FILTER_HTML_STRIP),
  620. '#options' => array(FILTER_HTML_STRIP => t('Strip disallowed tags'), FILTER_HTML_ESCAPE => t('Escape all tags')),
  621. '#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.'),
  622. );
  623. $form['filter_html']["allowed_html_$format"] = array(
  624. '#type' => 'textfield',
  625. '#title' => t('Allowed HTML tags'),
  626. '#default_value' => variable_get("allowed_html_$format", '<a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>'),
  627. '#size' => 64,
  628. '#maxlength' => 1024,
  629. '#description' => t('If "Strip disallowed tags" is selected, optionally specify tags which should not be stripped. JavaScript event attributes are always stripped.'),
  630. );
  631. $form['filter_html']["filter_html_help_$format"] = array(
  632. '#type' => 'checkbox',
  633. '#title' => t('Display HTML help'),
  634. '#default_value' => variable_get("filter_html_help_$format", 1),
  635. '#description' => t('If enabled, Drupal will display some basic HTML help in the long filter tips.'),
  636. );
  637. $form['filter_html']["filter_html_nofollow_$format"] = array(
  638. '#type' => 'checkbox',
  639. '#title' => t('Spam link deterrent'),
  640. '#default_value' => variable_get("filter_html_nofollow_$format", FALSE),
  641. '#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.'),
  642. );
  643. return $form;
  644. }
  645. /**
  646. * HTML filter. Provides filtering of input into accepted HTML.
  647. */
  648. function _filter_html($text, $format) {
  649. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_STRIP) {
  650. $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);
  651. $text = filter_xss($text, $allowed_tags);
  652. }
  653. if (variable_get("filter_html_$format", FILTER_HTML_STRIP) == FILTER_HTML_ESCAPE) {
  654. // Escape HTML
  655. $text = check_plain($text);
  656. }
  657. if (variable_get("filter_html_nofollow_$format", FALSE)) {
  658. $text = preg_replace('/<a([^>]+)>/i', '<a\\1 rel="nofollow">', $text);
  659. }
  660. return trim($text);
  661. }
  662. /**
  663. * Settings for URL filter.
  664. */
  665. function _filter_url_settings($format) {
  666. $form['filter_urlfilter'] = array(
  667. '#type' => 'fieldset',
  668. '#title' => t('URL filter'),
  669. '#collapsible' => TRUE,
  670. );
  671. $form['filter_urlfilter']['filter_url_length_'. $format] = array(
  672. '#type' => 'textfield',
  673. '#title' => t('Maximum link text length'),
  674. '#default_value' => variable_get('filter_url_length_'. $format, 72),
  675. '#maxlength' => 4,
  676. '#description' => t('URLs longer than this number of characters will be truncated to prevent long strings that break formatting. The link itself will be retained; just the text portion of the link will be truncated.'),
  677. );
  678. return $form;
  679. }
  680. /**
  681. * URL filter. Automatically converts text web addresses (URLs, e-mail addresses,
  682. * FTP links, etc.) into hyperlinks.
  683. */
  684. function _filter_url($text, $format) {
  685. // Pass length to regexp callback
  686. _filter_url_trim(NULL, variable_get('filter_url_length_'. $format, 72));
  687. $text = ' '. $text .' ';
  688. // Match absolute URLs.
  689. $text = preg_replace_callback("`(<p>|<li>|<br\s*/?>|[ \n\r\t\(])((http://|https://|ftp://|mailto:|smb://|afp://|file://|gopher://|news://|ssl://|sslv2://|sslv3://|tls://|tcp://|udp://)([a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+*~#&=/;-]))([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '_filter_url_parse_full_links', $text);
  690. // Match e-mail addresses.
  691. $text = preg_replace("`(<p>|<li>|<br\s*/?>|[ \n\r\t\(])([A-Za-z0-9._-]+@[A-Za-z0-9._+-]+\.[A-Za-z]{2,4})([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '\1<a href="mailto:\2">\2</a>\3', $text);
  692. // Match www domains/addresses.
  693. $text = preg_replace_callback("`(<p>|<li>|[ \n\r\t\(])(www\.[a-zA-Z0-9@:%_+*~#?&=.,/;-]*[a-zA-Z0-9@:%_+~#\&=/;-])([.,?!]*?)(?=(</p>|</li>|<br\s*/?>|[ \n\r\t\)]))`i", '_filter_url_parse_partial_links', $text);
  694. $text = substr($text, 1, -1);
  695. return $text;
  696. }
  697. /**
  698. * Scan input and make sure that all HTML tags are properly closed and nested.
  699. */
  700. function _filter_htmlcorrector($text) {
  701. // Prepare tag lists.
  702. static $no_nesting, $single_use;
  703. if (!isset($no_nesting)) {
  704. // Tags which cannot be nested but are typically left unclosed.
  705. $no_nesting = drupal_map_assoc(array('li', 'p'));
  706. // Single use tags in HTML4
  707. $single_use = drupal_map_assoc(array('base', 'meta', 'link', 'hr', 'br', 'param', 'img', 'area', 'input', 'col', 'frame'));
  708. }
  709. // Properly entify angles.
  710. $text = preg_replace('@<(?=[^a-zA-Z!/]|$)@', '&lt;', $text);
  711. // Split tags from text.
  712. $split = preg_split('/<(!--.*?--|[^>]+?)>/s', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  713. // Note: PHP ensures the array consists of alternating delimiters and literals
  714. // and begins and ends with a literal (inserting $null as required).
  715. $tag = false; // Odd/even counter. Tag or no tag.
  716. $stack = array();
  717. $output = '';
  718. foreach ($split as $value) {
  719. // Process HTML tags.
  720. if ($tag) {
  721. // Passthrough comments.
  722. if (substr($value, 0, 3) == '!--') {
  723. $output .= '<'. $value .'>';
  724. }
  725. else {
  726. list($tagname) = preg_split('/\s/', strtolower($value), 2);
  727. // Closing tag
  728. if ($tagname{0} == '/') {
  729. $tagname = substr($tagname, 1);
  730. // Discard XHTML closing tags for single use tags.
  731. if (!isset($single_use[$tagname])) {
  732. // See if we possibly have a matching opening tag on the stack.
  733. if (in_array($tagname, $stack)) {
  734. // Close other tags lingering first.
  735. do {
  736. $output .= '</'. $stack[0] .'>';
  737. } while (array_shift($stack) != $tagname);
  738. }
  739. // Otherwise, discard it.
  740. }
  741. }
  742. // Opening tag
  743. else {
  744. // See if we have an identical 'no nesting' tag already open and close it if found.
  745. if (count($stack) && ($stack[0] == $tagname) && isset($no_nesting[$stack[0]])) {
  746. $output .= '</'. array_shift($stack) .'>';
  747. }
  748. // Push non-single-use tags onto the stack
  749. if (!isset($single_use[$tagname])) {
  750. array_unshift($stack, $tagname);
  751. }
  752. // Add trailing slash to single-use tags as per X(HT)ML.
  753. else {
  754. $value = rtrim($value, ' /') .' /';
  755. }
  756. $output .= '<'. $value .'>';
  757. }
  758. }
  759. }
  760. else {
  761. // Passthrough all text.
  762. $output .= $value;
  763. }
  764. $tag = !$tag;
  765. }
  766. // Close remaining tags.
  767. while (count($stack) > 0) {
  768. $output .= '</'. array_shift($stack) .'>';
  769. }
  770. return $output;
  771. }
  772. /**
  773. * Make links out of absolute URLs.
  774. */
  775. function _filter_url_parse_full_links($match) {
  776. $match[2] = decode_entities($match[2]);
  777. $caption = check_plain(_filter_url_trim($match[2]));
  778. $match[2] = check_url($match[2]);
  779. return $match[1] .'<a href="'. $match[2] .'" title="'. $match[2] .'">'. $caption .'</a>'. $match[5];
  780. }
  781. /**
  782. * Make links out of domain names starting with "www."
  783. */
  784. function _filter_url_parse_partial_links($match) {
  785. $match[2] = decode_entities($match[2]);
  786. $caption = check_plain(_filter_url_trim($match[2]));
  787. $match[2] = check_plain($match[2]);
  788. return $match[1] .'<a href="http://'. $match[2] .'" title="'. $match[2] .'">'. $caption .'</a>'. $match[3];
  789. }
  790. /**
  791. * Shortens long URLs to http://www.example.com/long/url...
  792. */
  793. function _filter_url_trim($text, $length = NULL) {
  794. static $_length;
  795. if ($length !== NULL) {
  796. $_length = $length;
  797. }
  798. // Use +3 for '...' string length.
  799. if (strlen($text) > $_length + 3) {
  800. $text = substr($text, 0, $_length) .'...';
  801. }
  802. return $text;
  803. }
  804. /**
  805. * Convert line breaks into <p> and <br> in an intelligent fashion.
  806. * Based on: http://photomatt.net/scripts/autop
  807. */
  808. function _filter_autop($text) {
  809. // All block level tags
  810. $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]|hr)';
  811. // Split at <pre>, <script>, <style> and </pre>, </script>, </style> tags.
  812. // We don't apply any processing to the contents of these tags to avoid messing
  813. // up code. We look for matched pairs and allow basic nesting. For example:
  814. // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
  815. $chunks = preg_split('@(<(?:!--.*?--|/?(?:pre|script|style|object)[^>]*)>)@si', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  816. // Note: PHP ensures the array consists of alternating delimiters and literals
  817. // and begins and ends with a literal (inserting NULL as required).
  818. $ignore = FALSE;
  819. $ignoretag = '';
  820. $output = '';
  821. foreach ($chunks as $i => $chunk) {
  822. if ($i % 2) {
  823. // Passthrough comments.
  824. if (substr($chunk, 1, 3) == '!--') {
  825. $output .= $chunk;
  826. }
  827. else {
  828. // Opening or closing tag?
  829. $open = ($chunk[1] != '/');
  830. list($tag) = split('[ >]', substr($chunk, 2 - $open), 2);
  831. if (!$ignore) {
  832. if ($open) {
  833. $ignore = TRUE;
  834. $ignoretag = $tag;
  835. }
  836. }
  837. // Only allow a matching tag to close it.
  838. else if (!$open && $ignoretag == $tag) {
  839. $ignore = FALSE;
  840. $ignoretag = '';
  841. }
  842. }
  843. }
  844. else if (!$ignore) {
  845. $chunk = preg_replace('|\n*$|', '', $chunk) ."\n\n"; // just to make things a little easier, pad the end
  846. $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
  847. $chunk = preg_replace('!(<'. $block .'[^>]*>)!', "\n$1", $chunk); // Space things out a little
  848. $chunk = preg_replace('!(</'. $block .'>)!', "$1\n\n", $chunk); // Space things out a little
  849. $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
  850. $chunk = preg_replace('/^\n|\n\s*\n$/', '', $chunk);
  851. $chunk = '<p>'. preg_replace('/\n\s*\n\n?(.)/', "</p>\n<p>$1", $chunk) ."</p>\n"; // make paragraphs, including one at the end
  852. $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
  853. $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
  854. $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
  855. $chunk = preg_replace('|<p>\s*</p>\n?|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
  856. $chunk = preg_replace('!<p>\s*(</?'. $block .'[^>]*>)!', "$1", $chunk);
  857. $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*</p>!', "$1", $chunk);
  858. $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
  859. $chunk = preg_replace('!(</?'. $block .'[^>]*>)\s*<br />!', "$1", $chunk);
  860. $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
  861. $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
  862. }
  863. $output .= $chunk;
  864. }
  865. return $output;
  866. }
  867. /**
  868. * Very permissive XSS/HTML filter for admin-only use.
  869. *
  870. * Use only for fields where it is impractical to use the
  871. * whole filter system, but where some (mainly inline) mark-up
  872. * is desired (so check_plain() is not acceptable).
  873. *
  874. * Allows all tags that can be used inside an HTML body, save
  875. * for scripts and styles.
  876. */
  877. function filter_xss_admin($string) {
  878. 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', 'ol', 'p', 'pre', 'q', 'samp', 'small', 'span', 'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'tfoot', 'th', 'thead', 'tr', 'tt', 'ul', 'var'));
  879. }
  880. /**
  881. * Filters an HTML string to prevent cross-site-scripting (XSS) vulnerabilities.
  882. *
  883. * Based on kses by Ulf Harnhammar, see http://sourceforge.net/projects/kses.
  884. * For examples of various XSS attacks, see http://ha.ckers.org/xss.html.
  885. *
  886. * This code does four things:
  887. * - Removes characters and constructs that can trick browsers.
  888. * - Makes sure all HTML entities are well-formed.
  889. * - Makes sure all HTML tags and attributes are well-formed.
  890. * - Makes sure no HTML tags contain URLs with a disallowed protocol (e.g.
  891. * javascript:).
  892. *
  893. * @param $string
  894. * The string with raw HTML in it. It will be stripped of everything that can
  895. * cause an XSS attack.
  896. * @param $allowed_tags
  897. * An array of allowed tags.
  898. *
  899. * @return
  900. * An XSS safe version of $string, or an empty string if $string is not
  901. * valid UTF-8.
  902. *
  903. * @see drupal_validate_utf8()
  904. * @ingroup sanitization
  905. */
  906. function filter_xss($string, $allowed_tags = array('a', 'em', 'strong', 'cite', 'code', 'ul', 'ol', 'li', 'dl', 'dt', 'dd')) {
  907. // Only operate on valid UTF-8 strings. This is necessary to prevent cross
  908. // site scripting issues on Internet Explorer 6.
  909. if (!drupal_validate_utf8($string)) {
  910. return '';
  911. }
  912. // Store the input format
  913. _filter_xss_split($allowed_tags, TRUE);
  914. // Remove NUL characters (ignored by some browsers)
  915. $string = str_replace(chr(0), '', $string);
  916. // Remove Netscape 4 JS entities
  917. $string = preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
  918. // Defuse all HTML entities
  919. $string = str_replace('&', '&amp;', $string);
  920. // Change back only well-formed entities in our whitelist
  921. // Decimal numeric entities
  922. $string = preg_replace('/&amp;#([0-9]+;)/', '&#\1', $string);
  923. // Hexadecimal numeric entities
  924. $string = preg_replace('/&amp;#[Xx]0*((?:[0-9A-Fa-f]{2})+;)/', '&#x\1', $string);
  925. // Named entities
  926. $string = preg_replace('/&amp;([A-Za-z][A-Za-z0-9]*;)/', '&\1', $string);
  927. return preg_replace_callback('%
  928. (
  929. <(?=[^a-zA-Z!/]) # a lone <
  930. | # or
  931. <!--.*?--> # a comment
  932. | # or
  933. <[^>]*(>|$) # a string that starts with a <, up until the > or the end of the string
  934. | # or
  935. > # just a >
  936. )%x', '_filter_xss_split', $string);
  937. }
  938. /**
  939. * Processes an HTML tag.
  940. *
  941. * @param @m
  942. * An array with various meaning depending on the value of $store.
  943. * If $store is TRUE then the array contains the allowed tags.
  944. * If $store is FALSE then the array has one element, the HTML tag to process.
  945. * @param $store
  946. * Whether to store $m.
  947. * @return
  948. * If the element isn't allowed, an empty string. Otherwise, the cleaned up
  949. * version of the HTML element.
  950. */
  951. function _filter_xss_split($m, $store = FALSE) {
  952. static $allowed_html;
  953. if ($store) {
  954. $allowed_html = array_flip($m);
  955. return;
  956. }
  957. $string = $m[1];
  958. if (substr($string, 0, 1) != '<') {
  959. // We matched a lone ">" character
  960. return '&gt;';
  961. }
  962. else if (strlen($string) == 1) {
  963. // We matched a lone "<" character
  964. return '&lt;';
  965. }
  966. if (!preg_match('%^(?:<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?|(<!--.*?-->))$%', $string, $matches)) {
  967. // Seriously malformed
  968. return '';
  969. }
  970. $slash = trim($matches[1]);
  971. $elem = &$matches[2];
  972. $attrlist = &$matches[3];
  973. $comment = &$matches[4];
  974. if ($comment) {
  975. $elem = '!--';
  976. }
  977. if (!isset($allowed_html[strtolower($elem)])) {
  978. // Disallowed HTML element
  979. return '';
  980. }
  981. if ($comment) {
  982. return $comment;
  983. }
  984. if ($slash != '') {
  985. return "</$elem>";
  986. }
  987. // Is there a closing XHTML slash at the end of the attributes?
  988. // In PHP 5.1.0+ we could count the changes, currently we need a separate match
  989. $xhtml_slash = preg_match('%\s?/\s*$%', $attrlist) ? ' /' : '';
  990. $attrlist = preg_replace('%(\s?)/\s*$%', '\1', $attrlist);
  991. // Clean up attributes
  992. $attr2 = implode(' ', _filter_xss_attributes($attrlist));
  993. $attr2 = preg_replace('/[<>]/', '', $attr2);
  994. $attr2 = strlen($attr2) ? ' '. $attr2 : '';
  995. return "<$elem$attr2$xhtml_slash>";
  996. }
  997. /**
  998. * Processes a string of HTML attributes.
  999. *
  1000. * @return
  1001. * Cleaned up version of the HTML attributes.
  1002. */
  1003. function _filter_xss_attributes($attr) {
  1004. $attrarr = array();
  1005. $mode = 0;
  1006. $attrname = '';
  1007. while (strlen($attr) != 0) {
  1008. // Was the last operation successful?
  1009. $working = 0;
  1010. switch ($mode) {
  1011. case 0:
  1012. // Attribute name, href for instance
  1013. if (preg_match('/^([-a-zA-Z]+)/', $attr, $match)) {
  1014. $attrname = strtolower($match[1]);
  1015. $skip = ($attrname == 'style' || substr($attrname, 0, 2) == 'on');
  1016. $working = $mode = 1;
  1017. $attr = preg_replace('/^[-a-zA-Z]+/', '', $attr);
  1018. }
  1019. break;
  1020. case 1:
  1021. // Equals sign or valueless ("selected")
  1022. if (preg_match('/^\s*=\s*/', $attr)) {
  1023. $working = 1; $mode = 2;
  1024. $attr = preg_replace('/^\s*=\s*/', '', $attr);
  1025. break;
  1026. }
  1027. if (preg_match('/^\s+/', $attr)) {
  1028. $working = 1; $mode = 0;
  1029. if (!$skip) {
  1030. $attrarr[] = $attrname;
  1031. }
  1032. $attr = preg_replace('/^\s+/', '', $attr);
  1033. }
  1034. break;
  1035. case 2:
  1036. // Attribute value, a URL after href= for instance
  1037. if (preg_match('/^"([^"]*)"(\s+|$)/', $attr, $match)) {
  1038. $thisval = filter_xss_bad_protocol($match[1]);
  1039. if (!$skip) {
  1040. $attrarr[] = "$attrname=\"$thisval\"";
  1041. }
  1042. $working = 1;
  1043. $mode = 0;
  1044. $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
  1045. break;
  1046. }
  1047. if (preg_match("/^'([^']*)'(\s+|$)/", $attr, $match)) {
  1048. $thisval = filter_xss_bad_protocol($match[1]);
  1049. if (!$skip) {
  1050. $attrarr[] = "$attrname='$thisval'";;
  1051. }
  1052. $working = 1; $mode = 0;
  1053. $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
  1054. break;
  1055. }
  1056. if (preg_match("%^([^\s\"']+)(\s+|$)%", $attr, $match)) {
  1057. $thisval = filter_xss_bad_protocol($match[1]);
  1058. if (!$skip) {
  1059. $attrarr[] = "$attrname=\"$thisval\"";
  1060. }
  1061. $working = 1; $mode = 0;
  1062. $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
  1063. }
  1064. break;
  1065. }
  1066. if ($working == 0) {
  1067. // not well formed, remove and try again
  1068. $attr = preg_replace('/
  1069. ^
  1070. (
  1071. "[^"]*("|$) # - a string that starts with a double quote, up until the next double quote or the end of the string
  1072. | # or
  1073. \'[^\']*(\'|$)| # - a string that starts with a quote, up until the next quote or the end of the string
  1074. | # or
  1075. \S # - a non-whitespace character
  1076. )* # any number of the above three
  1077. \s* # any number of whitespaces
  1078. /x', '', $attr);
  1079. $mode = 0;
  1080. }
  1081. }
  1082. // the attribute list ends with a valueless attribute like "selected"
  1083. if ($mode == 1) {
  1084. $attrarr[] = $attrname;
  1085. }
  1086. return $attrarr;
  1087. }
  1088. /**
  1089. * Processes an HTML attribute value and ensures it does not contain an URL
  1090. * with a disallowed protocol (e.g. javascript:)
  1091. *
  1092. * @param $string
  1093. * The string with the attribute value.
  1094. * @param $decode
  1095. * Whether to decode entities in the $string. Set to FALSE if the $string
  1096. * is in plain text, TRUE otherwise. Defaults to TRUE.
  1097. * @return
  1098. * Cleaned up and HTML-escaped version of $string.
  1099. */
  1100. function filter_xss_bad_protocol($string, $decode = TRUE) {
  1101. static $allowed_protocols;
  1102. if (!isset($allowed_protocols)) {
  1103. $allowed_protocols = array_flip(variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'tel', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal', 'rtsp')));
  1104. }
  1105. // Get the plain text representation of the attribute value (i.e. its meaning).
  1106. if ($decode) {
  1107. $string = decode_entities($string);
  1108. }
  1109. // Iteratively remove any invalid protocol found.
  1110. do {
  1111. $before = $string;
  1112. $colonpos = strpos($string, ':');
  1113. if ($colonpos > 0) {
  1114. // We found a colon, possibly a protocol. Verify.
  1115. $protocol = substr($string, 0, $colonpos);
  1116. // If a colon is preceded by a slash, question mark or hash, it cannot
  1117. // possibly be part of the URL scheme. This must be a relative URL,
  1118. // which inherits the (safe) protocol of the base document.
  1119. if (preg_match('![/?#]!', $protocol)) {
  1120. break;
  1121. }
  1122. // Per RFC2616, section 3.2.3 (URI Comparison) scheme comparison must be case-insensitive
  1123. // Check if this is a disallowed protocol.
  1124. if (!isset($allowed_protocols[strtolower($protocol)])) {
  1125. $string = substr($string, $colonpos + 1);
  1126. }
  1127. }
  1128. } while ($before != $string);
  1129. return check_plain($string);
  1130. }
  1131. /**
  1132. * @} End of "Standard filters".
  1133. */