Spike PHPCoverage Details: filter.module

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