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('admin/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('admin/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