]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/formatting.php
Wordpress 3.2
[autoinstalls/wordpress.git] / wp-includes / formatting.php
1 <?php
2 /**
3  * Main WordPress Formatting API.
4  *
5  * Handles many functions for formatting output.
6  *
7  * @package WordPress
8  **/
9
10 /**
11  * Replaces common plain text characters into formatted entities
12  *
13  * As an example,
14  * <code>
15  * 'cause today's effort makes it worth tomorrow's "holiday"...
16  * </code>
17  * Becomes:
18  * <code>
19  * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221;&#8230;
20  * </code>
21  * Code within certain html blocks are skipped.
22  *
23  * @since 0.71
24  * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
25  *
26  * @param string $text The text to be formatted
27  * @return string The string replaced with html entities
28  */
29 function wptexturize($text) {
30         global $wp_cockneyreplace;
31         static $opening_quote, $closing_quote, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
32
33         // No need to set up these static variables more than once
34         if ( empty( $opening_quote ) ) {
35                 /* translators: opening curly quote */
36                 $opening_quote = _x('&#8220;', 'opening curly quote');
37                 /* translators: closing curly quote */
38                 $closing_quote = _x('&#8221;', 'closing curly quote');
39
40                 $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
41                 $default_no_texturize_shortcodes = array('code');
42
43                 // if a plugin has provided an autocorrect array, use it
44                 if ( isset($wp_cockneyreplace) ) {
45                         $cockney = array_keys($wp_cockneyreplace);
46                         $cockneyreplace = array_values($wp_cockneyreplace);
47                 } else {
48                         $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
49                         $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
50                 }
51
52                 $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', '\'\'', ' (tm)'), $cockney);
53                 $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', ' &#8211; ', 'xn--', '&#8230;', $opening_quote, $closing_quote, ' &#8482;'), $cockneyreplace);
54
55                 $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/\'(\d)/', '/(\s|\A|[([{<]|")\'/', '/(\d)"/', '/(\d)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
56                 $dynamic_replacements = array('&#8217;$1','&#8217;$1', '$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '&#8217;$1', '$1&#215;$2');
57         }
58
59         // Transform into regexp sub-expression used in _wptexturize_pushpop_element
60         // Must do this everytime in case plugins use these filters in a context sensitive manner
61         $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
62         $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
63
64         $no_texturize_tags_stack = array();
65         $no_texturize_shortcodes_stack = array();
66
67         $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
68
69         foreach ( $textarr as &$curl ) {
70                 if ( empty( $curl ) )
71                         continue;
72
73                 // Only call _wptexturize_pushpop_element if first char is correct tag opening
74                 $first = $curl[0];
75                 if ( '<' === $first ) {
76                         _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
77                 } elseif ( '[' === $first ) {
78                         _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
79                 } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
80                         // This is not a tag, nor is the texturization disabled static strings
81                         $curl = str_replace($static_characters, $static_replacements, $curl);
82                         // regular expressions
83                         $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
84                 }
85                 $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
86         }
87         return implode( '', $textarr );
88 }
89
90 /**
91  * Search for disabled element tags. Push element to stack on tag open and pop
92  * on tag close. Assumes first character of $text is tag opening.
93  *
94  * @access private
95  * @since 2.9.0
96  *
97  * @param string $text Text to check. First character is assumed to be $opening
98  * @param array $stack Array used as stack of opened tag elements
99  * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
100  * @param string $opening Tag opening character, assumed to be 1 character long
101  * @param string $opening Tag closing  character
102  * @return object
103  */
104 function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
105         // Check if it is a closing tag -- otherwise assume opening tag
106         if (strncmp($opening . '/', $text, 2)) {
107                 // Opening? Check $text+1 against disabled elements
108                 if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
109                         /*
110                          * This disables texturize until we find a closing tag of our type
111                          * (e.g. <pre>) even if there was invalid nesting before that
112                          *
113                          * Example: in the case <pre>sadsadasd</code>"baba"</pre>
114                          *          "baba" won't be texturize
115                          */
116
117                         array_push($stack, $matches[1]);
118                 }
119         } else {
120                 // Closing? Check $text+2 against disabled elements
121                 $c = preg_quote($closing, '/');
122                 if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
123                         $last = array_pop($stack);
124
125                         // Make sure it matches the opening tag
126                         if ($last != $matches[1])
127                                 array_push($stack, $last);
128                 }
129         }
130 }
131
132 /**
133  * Accepts matches array from preg_replace_callback in wpautop() or a string.
134  *
135  * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
136  * converted into paragraphs or line-breaks.
137  *
138  * @since 1.2.0
139  *
140  * @param array|string $matches The array or string
141  * @return string The pre block without paragraph/line-break conversion.
142  */
143 function clean_pre($matches) {
144         if ( is_array($matches) )
145                 $text = $matches[1] . $matches[2] . "</pre>";
146         else
147                 $text = $matches;
148
149         $text = str_replace('<br />', '', $text);
150         $text = str_replace('<p>', "\n", $text);
151         $text = str_replace('</p>', '', $text);
152
153         return $text;
154 }
155
156 /**
157  * Replaces double line-breaks with paragraph elements.
158  *
159  * A group of regex replaces used to identify text formatted with newlines and
160  * replace double line-breaks with HTML paragraph tags. The remaining
161  * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
162  * or 'false'.
163  *
164  * @since 0.71
165  *
166  * @param string $pee The text which has to be formatted.
167  * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
168  * @return string Text which has been converted into correct paragraph tags.
169  */
170 function wpautop($pee, $br = 1) {
171
172         if ( trim($pee) === '' )
173                 return '';
174         $pee = $pee . "\n"; // just to make things a little easier, pad the end
175         $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
176         // Space things out a little
177         $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
178         $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
179         $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
180         $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
181         if ( strpos($pee, '<object') !== false ) {
182                 $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
183                 $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
184         }
185         $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
186         // make paragraphs, including one at the end
187         $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
188         $pee = '';
189         foreach ( $pees as $tinkle )
190                 $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
191         $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
192         $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
193         $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
194         $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
195         $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
196         $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
197         $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
198         $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
199         if ($br) {
200                 $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
201                 $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
202                 $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
203         }
204         $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
205         $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
206         if (strpos($pee, '<pre') !== false)
207                 $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
208         $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
209
210         return $pee;
211 }
212
213 /**
214  * Newline preservation help function for wpautop
215  *
216  * @since 3.1.0
217  * @access private
218  * @param array $matches preg_replace_callback matches array
219  * @returns string
220  */
221 function _autop_newline_preservation_helper( $matches ) {
222         return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
223 }
224
225 /**
226  * Don't auto-p wrap shortcodes that stand alone
227  *
228  * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
229  *
230  * @since 2.9.0
231  *
232  * @param string $pee The content.
233  * @return string The filtered content.
234  */
235 function shortcode_unautop($pee) {
236         global $shortcode_tags;
237
238         if ( !empty($shortcode_tags) && is_array($shortcode_tags) ) {
239                 $tagnames = array_keys($shortcode_tags);
240                 $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
241                 $pee = preg_replace('/<p>\\s*?(\\[(' . $tagregexp . ')\\b.*?\\/?\\](?:.+?\\[\\/\\2\\])?)\\s*<\\/p>/s', '$1', $pee);
242         }
243
244         return $pee;
245 }
246
247 /**
248  * Checks to see if a string is utf8 encoded.
249  *
250  * NOTE: This function checks for 5-Byte sequences, UTF8
251  *       has Bytes Sequences with a maximum length of 4.
252  *
253  * @author bmorel at ssi dot fr (modified)
254  * @since 1.2.1
255  *
256  * @param string $str The string to be checked
257  * @return bool True if $str fits a UTF-8 model, false otherwise.
258  */
259 function seems_utf8($str) {
260         $length = strlen($str);
261         for ($i=0; $i < $length; $i++) {
262                 $c = ord($str[$i]);
263                 if ($c < 0x80) $n = 0; # 0bbbbbbb
264                 elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
265                 elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
266                 elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
267                 elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
268                 elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
269                 else return false; # Does not match any model
270                 for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
271                         if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
272                                 return false;
273                 }
274         }
275         return true;
276 }
277
278 /**
279  * Converts a number of special characters into their HTML entities.
280  *
281  * Specifically deals with: &, <, >, ", and '.
282  *
283  * $quote_style can be set to ENT_COMPAT to encode " to
284  * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
285  *
286  * @since 1.2.2
287  *
288  * @param string $string The text which is to be encoded.
289  * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
290  * @param string $charset Optional. The character encoding of the string. Default is false.
291  * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
292  * @return string The encoded text with HTML entities.
293  */
294 function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
295         $string = (string) $string;
296
297         if ( 0 === strlen( $string ) ) {
298                 return '';
299         }
300
301         // Don't bother if there are no specialchars - saves some processing
302         if ( !preg_match( '/[&<>"\']/', $string ) ) {
303                 return $string;
304         }
305
306         // Account for the previous behaviour of the function when the $quote_style is not an accepted value
307         if ( empty( $quote_style ) ) {
308                 $quote_style = ENT_NOQUOTES;
309         } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
310                 $quote_style = ENT_QUOTES;
311         }
312
313         // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
314         if ( !$charset ) {
315                 static $_charset;
316                 if ( !isset( $_charset ) ) {
317                         $alloptions = wp_load_alloptions();
318                         $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
319                 }
320                 $charset = $_charset;
321         }
322         if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
323                 $charset = 'UTF-8';
324         }
325
326         $_quote_style = $quote_style;
327
328         if ( $quote_style === 'double' ) {
329                 $quote_style = ENT_COMPAT;
330                 $_quote_style = ENT_COMPAT;
331         } elseif ( $quote_style === 'single' ) {
332                 $quote_style = ENT_NOQUOTES;
333         }
334
335         // Handle double encoding ourselves
336         if ( !$double_encode ) {
337                 $string = wp_specialchars_decode( $string, $_quote_style );
338
339                 /* Critical */
340                 // The previous line decodes &amp;phrase; into &phrase;  We must guarantee that &phrase; is valid before proceeding.
341                 $string = wp_kses_normalize_entities($string);
342
343                 // Now proceed with custom double-encoding silliness
344                 $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
345         }
346
347         $string = @htmlspecialchars( $string, $quote_style, $charset );
348
349         // Handle double encoding ourselves
350         if ( !$double_encode ) {
351                 $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
352         }
353
354         // Backwards compatibility
355         if ( 'single' === $_quote_style ) {
356                 $string = str_replace( "'", '&#039;', $string );
357         }
358
359         return $string;
360 }
361
362 /**
363  * Converts a number of HTML entities into their special characters.
364  *
365  * Specifically deals with: &, <, >, ", and '.
366  *
367  * $quote_style can be set to ENT_COMPAT to decode " entities,
368  * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
369  *
370  * @since 2.8
371  *
372  * @param string $string The text which is to be decoded.
373  * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
374  * @return string The decoded text without HTML entities.
375  */
376 function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
377         $string = (string) $string;
378
379         if ( 0 === strlen( $string ) ) {
380                 return '';
381         }
382
383         // Don't bother if there are no entities - saves a lot of processing
384         if ( strpos( $string, '&' ) === false ) {
385                 return $string;
386         }
387
388         // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
389         if ( empty( $quote_style ) ) {
390                 $quote_style = ENT_NOQUOTES;
391         } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
392                 $quote_style = ENT_QUOTES;
393         }
394
395         // More complete than get_html_translation_table( HTML_SPECIALCHARS )
396         $single = array( '&#039;'  => '\'', '&#x27;' => '\'' );
397         $single_preg = array( '/&#0*39;/'  => '&#039;', '/&#x0*27;/i' => '&#x27;' );
398         $double = array( '&quot;' => '"', '&#034;'  => '"', '&#x22;' => '"' );
399         $double_preg = array( '/&#0*34;/'  => '&#034;', '/&#x0*22;/i' => '&#x22;' );
400         $others = array( '&lt;'   => '<', '&#060;'  => '<', '&gt;'   => '>', '&#062;'  => '>', '&amp;'  => '&', '&#038;'  => '&', '&#x26;' => '&' );
401         $others_preg = array( '/&#0*60;/'  => '&#060;', '/&#0*62;/'  => '&#062;', '/&#0*38;/'  => '&#038;', '/&#x0*26;/i' => '&#x26;' );
402
403         if ( $quote_style === ENT_QUOTES ) {
404                 $translation = array_merge( $single, $double, $others );
405                 $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
406         } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
407                 $translation = array_merge( $double, $others );
408                 $translation_preg = array_merge( $double_preg, $others_preg );
409         } elseif ( $quote_style === 'single' ) {
410                 $translation = array_merge( $single, $others );
411                 $translation_preg = array_merge( $single_preg, $others_preg );
412         } elseif ( $quote_style === ENT_NOQUOTES ) {
413                 $translation = $others;
414                 $translation_preg = $others_preg;
415         }
416
417         // Remove zero padding on numeric entities
418         $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
419
420         // Replace characters according to translation table
421         return strtr( $string, $translation );
422 }
423
424 /**
425  * Checks for invalid UTF8 in a string.
426  *
427  * @since 2.8
428  *
429  * @param string $string The text which is to be checked.
430  * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
431  * @return string The checked text.
432  */
433 function wp_check_invalid_utf8( $string, $strip = false ) {
434         $string = (string) $string;
435
436         if ( 0 === strlen( $string ) ) {
437                 return '';
438         }
439
440         // Store the site charset as a static to avoid multiple calls to get_option()
441         static $is_utf8;
442         if ( !isset( $is_utf8 ) ) {
443                 $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
444         }
445         if ( !$is_utf8 ) {
446                 return $string;
447         }
448
449         // Check for support for utf8 in the installed PCRE library once and store the result in a static
450         static $utf8_pcre;
451         if ( !isset( $utf8_pcre ) ) {
452                 $utf8_pcre = @preg_match( '/^./u', 'a' );
453         }
454         // We can't demand utf8 in the PCRE installation, so just return the string in those cases
455         if ( !$utf8_pcre ) {
456                 return $string;
457         }
458
459         // preg_match fails when it encounters invalid UTF8 in $string
460         if ( 1 === @preg_match( '/^./us', $string ) ) {
461                 return $string;
462         }
463
464         // Attempt to strip the bad chars if requested (not recommended)
465         if ( $strip && function_exists( 'iconv' ) ) {
466                 return iconv( 'utf-8', 'utf-8', $string );
467         }
468
469         return '';
470 }
471
472 /**
473  * Encode the Unicode values to be used in the URI.
474  *
475  * @since 1.5.0
476  *
477  * @param string $utf8_string
478  * @param int $length Max length of the string
479  * @return string String with Unicode encoded for URI.
480  */
481 function utf8_uri_encode( $utf8_string, $length = 0 ) {
482         $unicode = '';
483         $values = array();
484         $num_octets = 1;
485         $unicode_length = 0;
486
487         $string_length = strlen( $utf8_string );
488         for ($i = 0; $i < $string_length; $i++ ) {
489
490                 $value = ord( $utf8_string[ $i ] );
491
492                 if ( $value < 128 ) {
493                         if ( $length && ( $unicode_length >= $length ) )
494                                 break;
495                         $unicode .= chr($value);
496                         $unicode_length++;
497                 } else {
498                         if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
499
500                         $values[] = $value;
501
502                         if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
503                                 break;
504                         if ( count( $values ) == $num_octets ) {
505                                 if ($num_octets == 3) {
506                                         $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
507                                         $unicode_length += 9;
508                                 } else {
509                                         $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
510                                         $unicode_length += 6;
511                                 }
512
513                                 $values = array();
514                                 $num_octets = 1;
515                         }
516                 }
517         }
518
519         return $unicode;
520 }
521
522 /**
523  * Converts all accent characters to ASCII characters.
524  *
525  * If there are no accent characters, then the string given is just returned.
526  *
527  * @since 1.2.1
528  *
529  * @param string $string Text that might have accent characters
530  * @return string Filtered string with replaced "nice" characters.
531  */
532 function remove_accents($string) {
533         if ( !preg_match('/[\x80-\xff]/', $string) )
534                 return $string;
535
536         if (seems_utf8($string)) {
537                 $chars = array(
538                 // Decompositions for Latin-1 Supplement
539                 chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
540                 chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
541                 chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
542                 chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
543                 chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
544                 chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
545                 chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
546                 chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
547                 chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
548                 chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
549                 chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
550                 chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
551                 chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
552                 chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
553                 chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
554                 chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
555                 chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
556                 chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
557                 chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
558                 chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
559                 chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
560                 chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
561                 chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
562                 chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
563                 chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
564                 chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
565                 chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
566                 chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
567                 chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
568                 chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
569                 chr(195).chr(191) => 'y',
570                 // Decompositions for Latin Extended-A
571                 chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
572                 chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
573                 chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
574                 chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
575                 chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
576                 chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
577                 chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
578                 chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
579                 chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
580                 chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
581                 chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
582                 chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
583                 chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
584                 chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
585                 chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
586                 chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
587                 chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
588                 chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
589                 chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
590                 chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
591                 chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
592                 chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
593                 chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
594                 chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
595                 chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
596                 chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
597                 chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
598                 chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
599                 chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
600                 chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
601                 chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
602                 chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
603                 chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
604                 chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
605                 chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
606                 chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
607                 chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
608                 chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
609                 chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
610                 chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
611                 chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
612                 chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
613                 chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
614                 chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
615                 chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
616                 chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
617                 chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
618                 chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
619                 chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
620                 chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
621                 chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
622                 chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
623                 chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
624                 chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
625                 chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
626                 chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
627                 chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
628                 chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
629                 chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
630                 chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
631                 chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
632                 chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
633                 chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
634                 chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
635                 // Decompositions for Latin Extended-B
636                 chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
637                 chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
638                 // Euro Sign
639                 chr(226).chr(130).chr(172) => 'E',
640                 // GBP (Pound) Sign
641                 chr(194).chr(163) => '');
642
643                 $string = strtr($string, $chars);
644         } else {
645                 // Assume ISO-8859-1 if not UTF-8
646                 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
647                         .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
648                         .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
649                         .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
650                         .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
651                         .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
652                         .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
653                         .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
654                         .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
655                         .chr(252).chr(253).chr(255);
656
657                 $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
658
659                 $string = strtr($string, $chars['in'], $chars['out']);
660                 $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
661                 $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
662                 $string = str_replace($double_chars['in'], $double_chars['out'], $string);
663         }
664
665         return $string;
666 }
667
668 /**
669  * Sanitizes a filename replacing whitespace with dashes
670  *
671  * Removes special characters that are illegal in filenames on certain
672  * operating systems and special characters requiring special escaping
673  * to manipulate at the command line. Replaces spaces and consecutive
674  * dashes with a single dash. Trim period, dash and underscore from beginning
675  * and end of filename.
676  *
677  * @since 2.1.0
678  *
679  * @param string $filename The filename to be sanitized
680  * @return string The sanitized filename
681  */
682 function sanitize_file_name( $filename ) {
683         $filename_raw = $filename;
684         $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
685         $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
686         $filename = str_replace($special_chars, '', $filename);
687         $filename = preg_replace('/[\s-]+/', '-', $filename);
688         $filename = trim($filename, '.-_');
689
690         // Split the filename into a base and extension[s]
691         $parts = explode('.', $filename);
692
693         // Return if only one extension
694         if ( count($parts) <= 2 )
695                 return apply_filters('sanitize_file_name', $filename, $filename_raw);
696
697         // Process multiple extensions
698         $filename = array_shift($parts);
699         $extension = array_pop($parts);
700         $mimes = get_allowed_mime_types();
701
702         // Loop over any intermediate extensions.  Munge them with a trailing underscore if they are a 2 - 5 character
703         // long alpha string not in the extension whitelist.
704         foreach ( (array) $parts as $part) {
705                 $filename .= '.' . $part;
706
707                 if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
708                         $allowed = false;
709                         foreach ( $mimes as $ext_preg => $mime_match ) {
710                                 $ext_preg = '!^(' . $ext_preg . ')$!i';
711                                 if ( preg_match( $ext_preg, $part ) ) {
712                                         $allowed = true;
713                                         break;
714                                 }
715                         }
716                         if ( !$allowed )
717                                 $filename .= '_';
718                 }
719         }
720         $filename .= '.' . $extension;
721
722         return apply_filters('sanitize_file_name', $filename, $filename_raw);
723 }
724
725 /**
726  * Sanitize username stripping out unsafe characters.
727  *
728  * Removes tags, octets, entities, and if strict is enabled, will only keep
729  * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
730  * raw username (the username in the parameter), and the value of $strict as
731  * parameters for the 'sanitize_user' filter.
732  *
733  * @since 2.0.0
734  * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
735  *              and $strict parameter.
736  *
737  * @param string $username The username to be sanitized.
738  * @param bool $strict If set limits $username to specific characters. Default false.
739  * @return string The sanitized username, after passing through filters.
740  */
741 function sanitize_user( $username, $strict = false ) {
742         $raw_username = $username;
743         $username = wp_strip_all_tags( $username );
744         $username = remove_accents( $username );
745         // Kill octets
746         $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
747         $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
748
749         // If strict, reduce to ASCII for max portability.
750         if ( $strict )
751                 $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
752
753         $username = trim( $username );
754         // Consolidate contiguous whitespace
755         $username = preg_replace( '|\s+|', ' ', $username );
756
757         return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
758 }
759
760 /**
761  * Sanitize a string key.
762  *
763  * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
764  *
765  * @since 3.0.0
766  *
767  * @param string $key String key
768  * @return string Sanitized key
769  */
770 function sanitize_key( $key ) {
771         $raw_key = $key;
772         $key = strtolower( $key );
773         $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
774         return apply_filters( 'sanitize_key', $key, $raw_key );
775 }
776
777 /**
778  * Sanitizes title or use fallback title.
779  *
780  * Specifically, HTML and PHP tags are stripped. Further actions can be added
781  * via the plugin API. If $title is empty and $fallback_title is set, the latter
782  * will be used.
783  *
784  * @since 1.0.0
785  *
786  * @param string $title The string to be sanitized.
787  * @param string $fallback_title Optional. A title to use if $title is empty.
788  * @param string $context Optional. The operation for which the string is sanitized
789  * @return string The sanitized string.
790  */
791 function sanitize_title($title, $fallback_title = '', $context = 'save') {
792         $raw_title = $title;
793
794         if ( 'save' == $context )
795                 $title = remove_accents($title);
796
797         $title = apply_filters('sanitize_title', $title, $raw_title, $context);
798
799         if ( '' === $title || false === $title )
800                 $title = $fallback_title;
801
802         return $title;
803 }
804
805 function sanitize_title_for_query($title) {
806         return sanitize_title($title, '', 'query');
807 }
808
809 /**
810  * Sanitizes title, replacing whitespace with dashes.
811  *
812  * Limits the output to alphanumeric characters, underscore (_) and dash (-).
813  * Whitespace becomes a dash.
814  *
815  * @since 1.2.0
816  *
817  * @param string $title The title to be sanitized.
818  * @return string The sanitized title.
819  */
820 function sanitize_title_with_dashes($title) {
821         $title = strip_tags($title);
822         // Preserve escaped octets.
823         $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
824         // Remove percent signs that are not part of an octet.
825         $title = str_replace('%', '', $title);
826         // Restore octets.
827         $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
828
829         if (seems_utf8($title)) {
830                 if (function_exists('mb_strtolower')) {
831                         $title = mb_strtolower($title, 'UTF-8');
832                 }
833                 $title = utf8_uri_encode($title, 200);
834         }
835
836         $title = strtolower($title);
837         $title = preg_replace('/&.+?;/', '', $title); // kill entities
838         $title = str_replace('.', '-', $title);
839         $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
840         $title = preg_replace('/\s+/', '-', $title);
841         $title = preg_replace('|-+|', '-', $title);
842         $title = trim($title, '-');
843
844         return $title;
845 }
846
847 /**
848  * Ensures a string is a valid SQL order by clause.
849  *
850  * Accepts one or more columns, with or without ASC/DESC, and also accepts
851  * RAND().
852  *
853  * @since 2.5.1
854  *
855  * @param string $orderby Order by string to be checked.
856  * @return string|false Returns the order by clause if it is a match, false otherwise.
857  */
858 function sanitize_sql_orderby( $orderby ){
859         preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
860         if ( !$obmatches )
861                 return false;
862         return $orderby;
863 }
864
865 /**
866  * Santizes a html classname to ensure it only contains valid characters
867  *
868  * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
869  * string then it will return the alternative value supplied.
870  *
871  * @todo Expand to support the full range of CDATA that a class attribute can contain.
872  *
873  * @since 2.8.0
874  *
875  * @param string $class The classname to be sanitized
876  * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
877  *      Defaults to an empty string.
878  * @return string The sanitized value
879  */
880 function sanitize_html_class( $class, $fallback = '' ) {
881         //Strip out any % encoded octets
882         $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
883
884         //Limit to A-Z,a-z,0-9,_,-
885         $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
886
887         if ( '' == $sanitized )
888                 $sanitized = $fallback;
889
890         return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
891 }
892
893 /**
894  * Converts a number of characters from a string.
895  *
896  * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
897  * converted into correct XHTML and Unicode characters are converted to the
898  * valid range.
899  *
900  * @since 0.71
901  *
902  * @param string $content String of characters to be converted.
903  * @param string $deprecated Not used.
904  * @return string Converted string.
905  */
906 function convert_chars($content, $deprecated = '') {
907         if ( !empty( $deprecated ) )
908                 _deprecated_argument( __FUNCTION__, '0.71' );
909
910         // Translation of invalid Unicode references range to valid range
911         $wp_htmltranswinuni = array(
912         '&#128;' => '&#8364;', // the Euro sign
913         '&#129;' => '',
914         '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
915         '&#131;' => '&#402;',  // they would look weird on non-Windows browsers
916         '&#132;' => '&#8222;',
917         '&#133;' => '&#8230;',
918         '&#134;' => '&#8224;',
919         '&#135;' => '&#8225;',
920         '&#136;' => '&#710;',
921         '&#137;' => '&#8240;',
922         '&#138;' => '&#352;',
923         '&#139;' => '&#8249;',
924         '&#140;' => '&#338;',
925         '&#141;' => '',
926         '&#142;' => '&#382;',
927         '&#143;' => '',
928         '&#144;' => '',
929         '&#145;' => '&#8216;',
930         '&#146;' => '&#8217;',
931         '&#147;' => '&#8220;',
932         '&#148;' => '&#8221;',
933         '&#149;' => '&#8226;',
934         '&#150;' => '&#8211;',
935         '&#151;' => '&#8212;',
936         '&#152;' => '&#732;',
937         '&#153;' => '&#8482;',
938         '&#154;' => '&#353;',
939         '&#155;' => '&#8250;',
940         '&#156;' => '&#339;',
941         '&#157;' => '',
942         '&#158;' => '',
943         '&#159;' => '&#376;'
944         );
945
946         // Remove metadata tags
947         $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
948         $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
949
950         // Converts lone & characters into &#38; (a.k.a. &amp;)
951         $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
952
953         // Fix Word pasting
954         $content = strtr($content, $wp_htmltranswinuni);
955
956         // Just a little XHTML help
957         $content = str_replace('<br>', '<br />', $content);
958         $content = str_replace('<hr>', '<hr />', $content);
959
960         return $content;
961 }
962
963 /**
964  * Will only balance the tags if forced to and the option is set to balance tags.
965  *
966  * The option 'use_balanceTags' is used for whether the tags will be balanced.
967  * Both the $force parameter and 'use_balanceTags' option will have to be true
968  * before the tags will be balanced.
969  *
970  * @since 0.71
971  *
972  * @param string $text Text to be balanced
973  * @param bool $force Forces balancing, ignoring the value of the option. Default false.
974  * @return string Balanced text
975  */
976 function balanceTags( $text, $force = false ) {
977         if ( !$force && get_option('use_balanceTags') == 0 )
978                 return $text;
979         return force_balance_tags( $text );
980 }
981
982 /**
983  * Balances tags of string using a modified stack.
984  *
985  * @since 2.0.4
986  *
987  * @author Leonard Lin <leonard@acm.org>
988  * @license GPL
989  * @copyright November 4, 2001
990  * @version 1.1
991  * @todo Make better - change loop condition to $text in 1.2
992  * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
993  *              1.1  Fixed handling of append/stack pop order of end text
994  *                       Added Cleaning Hooks
995  *              1.0  First Version
996  *
997  * @param string $text Text to be balanced.
998  * @return string Balanced text.
999  */
1000 function force_balance_tags( $text ) {
1001         $tagstack = array();
1002         $stacksize = 0;
1003         $tagqueue = '';
1004         $newtext = '';
1005         $single_tags = array('br', 'hr', 'img', 'input'); // Known single-entity/self-closing tags
1006         $nestable_tags = array('blockquote', 'div', 'span'); // Tags that can be immediately nested within themselves
1007
1008         // WP bug fix for comments - in case you REALLY meant to type '< !--'
1009         $text = str_replace('< !--', '<    !--', $text);
1010         // WP bug fix for LOVE <3 (and other situations with '<' before a number)
1011         $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
1012
1013         while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
1014                 $newtext .= $tagqueue;
1015
1016                 $i = strpos($text, $regex[0]);
1017                 $l = strlen($regex[0]);
1018
1019                 // clear the shifter
1020                 $tagqueue = '';
1021                 // Pop or Push
1022                 if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
1023                         $tag = strtolower(substr($regex[1],1));
1024                         // if too many closing tags
1025                         if( $stacksize <= 0 ) {
1026                                 $tag = '';
1027                                 // or close to be safe $tag = '/' . $tag;
1028                         }
1029                         // if stacktop value = tag close value then pop
1030                         else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
1031                                 $tag = '</' . $tag . '>'; // Close Tag
1032                                 // Pop
1033                                 array_pop( $tagstack );
1034                                 $stacksize--;
1035                         } else { // closing tag not at top, search for it
1036                                 for ( $j = $stacksize-1; $j >= 0; $j-- ) {
1037                                         if ( $tagstack[$j] == $tag ) {
1038                                         // add tag to tagqueue
1039                                                 for ( $k = $stacksize-1; $k >= $j; $k--) {
1040                                                         $tagqueue .= '</' . array_pop( $tagstack ) . '>';
1041                                                         $stacksize--;
1042                                                 }
1043                                                 break;
1044                                         }
1045                                 }
1046                                 $tag = '';
1047                         }
1048                 } else { // Begin Tag
1049                         $tag = strtolower($regex[1]);
1050
1051                         // Tag Cleaning
1052
1053                         // If self-closing or '', don't do anything.
1054                         if ( substr($regex[2],-1) == '/' || $tag == '' ) {
1055                                 // do nothing
1056                         }
1057                         // ElseIf it's a known single-entity tag but it doesn't close itself, do so
1058                         elseif ( in_array($tag, $single_tags) ) {
1059                                 $regex[2] .= '/';
1060                         } else {        // Push the tag onto the stack
1061                                 // If the top of the stack is the same as the tag we want to push, close previous tag
1062                                 if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
1063                                         $tagqueue = '</' . array_pop ($tagstack) . '>';
1064                                         $stacksize--;
1065                                 }
1066                                 $stacksize = array_push ($tagstack, $tag);
1067                         }
1068
1069                         // Attributes
1070                         $attributes = $regex[2];
1071                         if( !empty($attributes) )
1072                                 $attributes = ' '.$attributes;
1073
1074                         $tag = '<' . $tag . $attributes . '>';
1075                         //If already queuing a close tag, then put this tag on, too
1076                         if ( !empty($tagqueue) ) {
1077                                 $tagqueue .= $tag;
1078                                 $tag = '';
1079                         }
1080                 }
1081                 $newtext .= substr($text, 0, $i) . $tag;
1082                 $text = substr($text, $i + $l);
1083         }
1084
1085         // Clear Tag Queue
1086         $newtext .= $tagqueue;
1087
1088         // Add Remaining text
1089         $newtext .= $text;
1090
1091         // Empty Stack
1092         while( $x = array_pop($tagstack) )
1093                 $newtext .= '</' . $x . '>'; // Add remaining tags to close
1094
1095         // WP fix for the bug with HTML comments
1096         $newtext = str_replace("< !--","<!--",$newtext);
1097         $newtext = str_replace("<    !--","< !--",$newtext);
1098
1099         return $newtext;
1100 }
1101
1102 /**
1103  * Acts on text which is about to be edited.
1104  *
1105  * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
1106  * filter. If $richedit is set true htmlspecialchars(), through esc_textarea(),
1107  * will be run on the content, converting special characters to HTML entities.
1108  *
1109  * @since 0.71
1110  *
1111  * @param string $content The text about to be edited.
1112  * @param bool $richedit Whether the $content should pass through htmlspecialchars(). Default false.
1113  * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
1114  */
1115 function format_to_edit( $content, $richedit = false ) {
1116         $content = apply_filters( 'format_to_edit', $content );
1117         if ( ! $richedit )
1118                 $content = esc_textarea( $content );
1119         return $content;
1120 }
1121
1122 /**
1123  * Holder for the 'format_to_post' filter.
1124  *
1125  * @since 0.71
1126  *
1127  * @param string $content The text to pass through the filter.
1128  * @return string Text returned from the 'format_to_post' filter.
1129  */
1130 function format_to_post($content) {
1131         $content = apply_filters('format_to_post', $content);
1132         return $content;
1133 }
1134
1135 /**
1136  * Add leading zeros when necessary.
1137  *
1138  * If you set the threshold to '4' and the number is '10', then you will get
1139  * back '0010'. If you set the number to '4' and the number is '5000', then you
1140  * will get back '5000'.
1141  *
1142  * Uses sprintf to append the amount of zeros based on the $threshold parameter
1143  * and the size of the number. If the number is large enough, then no zeros will
1144  * be appended.
1145  *
1146  * @since 0.71
1147  *
1148  * @param mixed $number Number to append zeros to if not greater than threshold.
1149  * @param int $threshold Digit places number needs to be to not have zeros added.
1150  * @return string Adds leading zeros to number if needed.
1151  */
1152 function zeroise($number, $threshold) {
1153         return sprintf('%0'.$threshold.'s', $number);
1154 }
1155
1156 /**
1157  * Adds backslashes before letters and before a number at the start of a string.
1158  *
1159  * @since 0.71
1160  *
1161  * @param string $string Value to which backslashes will be added.
1162  * @return string String with backslashes inserted.
1163  */
1164 function backslashit($string) {
1165         $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
1166         $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
1167         return $string;
1168 }
1169
1170 /**
1171  * Appends a trailing slash.
1172  *
1173  * Will remove trailing slash if it exists already before adding a trailing
1174  * slash. This prevents double slashing a string or path.
1175  *
1176  * The primary use of this is for paths and thus should be used for paths. It is
1177  * not restricted to paths and offers no specific path support.
1178  *
1179  * @since 1.2.0
1180  * @uses untrailingslashit() Unslashes string if it was slashed already.
1181  *
1182  * @param string $string What to add the trailing slash to.
1183  * @return string String with trailing slash added.
1184  */
1185 function trailingslashit($string) {
1186         return untrailingslashit($string) . '/';
1187 }
1188
1189 /**
1190  * Removes trailing slash if it exists.
1191  *
1192  * The primary use of this is for paths and thus should be used for paths. It is
1193  * not restricted to paths and offers no specific path support.
1194  *
1195  * @since 2.2.0
1196  *
1197  * @param string $string What to remove the trailing slash from.
1198  * @return string String without the trailing slash.
1199  */
1200 function untrailingslashit($string) {
1201         return rtrim($string, '/');
1202 }
1203
1204 /**
1205  * Adds slashes to escape strings.
1206  *
1207  * Slashes will first be removed if magic_quotes_gpc is set, see {@link
1208  * http://www.php.net/magic_quotes} for more details.
1209  *
1210  * @since 0.71
1211  *
1212  * @param string $gpc The string returned from HTTP request data.
1213  * @return string Returns a string escaped with slashes.
1214  */
1215 function addslashes_gpc($gpc) {
1216         if ( get_magic_quotes_gpc() )
1217                 $gpc = stripslashes($gpc);
1218
1219         return esc_sql($gpc);
1220 }
1221
1222 /**
1223  * Navigates through an array and removes slashes from the values.
1224  *
1225  * If an array is passed, the array_map() function causes a callback to pass the
1226  * value back to the function. The slashes from this value will removed.
1227  *
1228  * @since 2.0.0
1229  *
1230  * @param array|string $value The array or string to be stripped.
1231  * @return array|string Stripped array (or string in the callback).
1232  */
1233 function stripslashes_deep($value) {
1234         if ( is_array($value) ) {
1235                 $value = array_map('stripslashes_deep', $value);
1236         } elseif ( is_object($value) ) {
1237                 $vars = get_object_vars( $value );
1238                 foreach ($vars as $key=>$data) {
1239                         $value->{$key} = stripslashes_deep( $data );
1240                 }
1241         } else {
1242                 $value = stripslashes($value);
1243         }
1244
1245         return $value;
1246 }
1247
1248 /**
1249  * Navigates through an array and encodes the values to be used in a URL.
1250  *
1251  * Uses a callback to pass the value of the array back to the function as a
1252  * string.
1253  *
1254  * @since 2.2.0
1255  *
1256  * @param array|string $value The array or string to be encoded.
1257  * @return array|string $value The encoded array (or string from the callback).
1258  */
1259 function urlencode_deep($value) {
1260         $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
1261         return $value;
1262 }
1263
1264 /**
1265  * Converts email addresses characters to HTML entities to block spam bots.
1266  *
1267  * @since 0.71
1268  *
1269  * @param string $emailaddy Email address.
1270  * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
1271  * @return string Converted email address.
1272  */
1273 function antispambot($emailaddy, $mailto=0) {
1274         $emailNOSPAMaddy = '';
1275         srand ((float) microtime() * 1000000);
1276         for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
1277                 $j = floor(rand(0, 1+$mailto));
1278                 if ($j==0) {
1279                         $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
1280                 } elseif ($j==1) {
1281                         $emailNOSPAMaddy .= substr($emailaddy,$i,1);
1282                 } elseif ($j==2) {
1283                         $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
1284                 }
1285         }
1286         $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
1287         return $emailNOSPAMaddy;
1288 }
1289
1290 /**
1291  * Callback to convert URI match to HTML A element.
1292  *
1293  * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1294  * make_clickable()}.
1295  *
1296  * @since 2.3.2
1297  * @access private
1298  *
1299  * @param array $matches Single Regex Match.
1300  * @return string HTML A element with URI address.
1301  */
1302 function _make_url_clickable_cb($matches) {
1303         $url = $matches[2];
1304         $suffix = '';
1305
1306         /** Include parentheses in the URL only if paired **/
1307         while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1308                 $suffix = strrchr( $url, ')' ) . $suffix;
1309                 $url = substr( $url, 0, strrpos( $url, ')' ) );
1310         }
1311
1312         $url = esc_url($url);
1313         if ( empty($url) )
1314                 return $matches[0];
1315
1316         return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1317 }
1318
1319 /**
1320  * Callback to convert URL match to HTML A element.
1321  *
1322  * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1323  * make_clickable()}.
1324  *
1325  * @since 2.3.2
1326  * @access private
1327  *
1328  * @param array $matches Single Regex Match.
1329  * @return string HTML A element with URL address.
1330  */
1331 function _make_web_ftp_clickable_cb($matches) {
1332         $ret = '';
1333         $dest = $matches[2];
1334         $dest = 'http://' . $dest;
1335         $dest = esc_url($dest);
1336         if ( empty($dest) )
1337                 return $matches[0];
1338
1339         // removed trailing [.,;:)] from URL
1340         if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1341                 $ret = substr($dest, -1);
1342                 $dest = substr($dest, 0, strlen($dest)-1);
1343         }
1344         return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1345 }
1346
1347 /**
1348  * Callback to convert email address match to HTML A element.
1349  *
1350  * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1351  * make_clickable()}.
1352  *
1353  * @since 2.3.2
1354  * @access private
1355  *
1356  * @param array $matches Single Regex Match.
1357  * @return string HTML A element with email address.
1358  */
1359 function _make_email_clickable_cb($matches) {
1360         $email = $matches[2] . '@' . $matches[3];
1361         return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1362 }
1363
1364 /**
1365  * Convert plaintext URI to HTML links.
1366  *
1367  * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1368  * within links.
1369  *
1370  * @since 0.71
1371  *
1372  * @param string $ret Content to convert URIs.
1373  * @return string Content with converted URIs.
1374  */
1375 function make_clickable($ret) {
1376         $ret = ' ' . $ret;
1377         // in testing, using arrays here was found to be faster
1378         $save = @ini_set('pcre.recursion_limit', 10000);
1379         $retval = preg_replace_callback('#(?<!=[\'"])(?<=[*\')+.,;:!&$\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#%~/?@\[\]-]{1,2000}|[\'*(+.,;:!=&$](?![\b\)]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1380         if (null !== $retval )
1381                 $ret = $retval;
1382         @ini_set('pcre.recursion_limit', $save);
1383         $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1384         $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1385         // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1386         $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1387         $ret = trim($ret);
1388         return $ret;
1389 }
1390
1391 /**
1392  * Adds rel nofollow string to all HTML A elements in content.
1393  *
1394  * @since 1.5.0
1395  *
1396  * @param string $text Content that may contain HTML A elements.
1397  * @return string Converted content.
1398  */
1399 function wp_rel_nofollow( $text ) {
1400         // This is a pre save filter, so text is already escaped.
1401         $text = stripslashes($text);
1402         $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1403         $text = esc_sql($text);
1404         return $text;
1405 }
1406
1407 /**
1408  * Callback to used to add rel=nofollow string to HTML A element.
1409  *
1410  * Will remove already existing rel="nofollow" and rel='nofollow' from the
1411  * string to prevent from invalidating (X)HTML.
1412  *
1413  * @since 2.3.0
1414  *
1415  * @param array $matches Single Match
1416  * @return string HTML A Element with rel nofollow.
1417  */
1418 function wp_rel_nofollow_callback( $matches ) {
1419         $text = $matches[1];
1420         $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1421         return "<a $text rel=\"nofollow\">";
1422 }
1423
1424 /**
1425  * Convert one smiley code to the icon graphic file equivalent.
1426  *
1427  * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1428  * <img> string for that smiley.
1429  *
1430  * @global array $wpsmiliestrans
1431  * @since 2.8.0
1432  *
1433  * @param string $smiley Smiley code to convert to image.
1434  * @return string Image string for smiley.
1435  */
1436 function translate_smiley($smiley) {
1437         global $wpsmiliestrans;
1438
1439         if (count($smiley) == 0) {
1440                 return '';
1441         }
1442
1443         $smiley = trim(reset($smiley));
1444         $img = $wpsmiliestrans[$smiley];
1445         $smiley_masked = esc_attr($smiley);
1446
1447         $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url());
1448
1449         return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1450 }
1451
1452 /**
1453  * Convert text equivalent of smilies to images.
1454  *
1455  * Will only convert smilies if the option 'use_smilies' is true and the global
1456  * used in the function isn't empty.
1457  *
1458  * @since 0.71
1459  * @uses $wp_smiliessearch
1460  *
1461  * @param string $text Content to convert smilies from text.
1462  * @return string Converted content with text smilies replaced with images.
1463  */
1464 function convert_smilies($text) {
1465         global $wp_smiliessearch;
1466         $output = '';
1467         if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1468                 // HTML loop taken from texturize function, could possible be consolidated
1469                 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1470                 $stop = count($textarr);// loop stuff
1471                 for ($i = 0; $i < $stop; $i++) {
1472                         $content = $textarr[$i];
1473                         if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag
1474                                 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1475                         }
1476                         $output .= $content;
1477                 }
1478         } else {
1479                 // return default text.
1480                 $output = $text;
1481         }
1482         return $output;
1483 }
1484
1485 /**
1486  * Verifies that an email is valid.
1487  *
1488  * Does not grok i18n domains. Not RFC compliant.
1489  *
1490  * @since 0.71
1491  *
1492  * @param string $email Email address to verify.
1493  * @param boolean $deprecated Deprecated.
1494  * @return string|bool Either false or the valid email address.
1495  */
1496 function is_email( $email, $deprecated = false ) {
1497         if ( ! empty( $deprecated ) )
1498                 _deprecated_argument( __FUNCTION__, '3.0' );
1499
1500         // Test for the minimum length the email can be
1501         if ( strlen( $email ) < 3 ) {
1502                 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1503         }
1504
1505         // Test for an @ character after the first position
1506         if ( strpos( $email, '@', 1 ) === false ) {
1507                 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1508         }
1509
1510         // Split out the local and domain parts
1511         list( $local, $domain ) = explode( '@', $email, 2 );
1512
1513         // LOCAL PART
1514         // Test for invalid characters
1515         if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1516                 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1517         }
1518
1519         // DOMAIN PART
1520         // Test for sequences of periods
1521         if ( preg_match( '/\.{2,}/', $domain ) ) {
1522                 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1523         }
1524
1525         // Test for leading and trailing periods and whitespace
1526         if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1527                 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1528         }
1529
1530         // Split the domain into subs
1531         $subs = explode( '.', $domain );
1532
1533         // Assume the domain will have at least two subs
1534         if ( 2 > count( $subs ) ) {
1535                 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1536         }
1537
1538         // Loop through each sub
1539         foreach ( $subs as $sub ) {
1540                 // Test for leading and trailing hyphens and whitespace
1541                 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1542                         return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1543                 }
1544
1545                 // Test for invalid characters
1546                 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1547                         return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1548                 }
1549         }
1550
1551         // Congratulations your email made it!
1552         return apply_filters( 'is_email', $email, $email, null );
1553 }
1554
1555 /**
1556  * Convert to ASCII from email subjects.
1557  *
1558  * @since 1.2.0
1559  * @usedby wp_mail() handles charsets in email subjects
1560  *
1561  * @param string $string Subject line
1562  * @return string Converted string to ASCII
1563  */
1564 function wp_iso_descrambler($string) {
1565         /* this may only work with iso-8859-1, I'm afraid */
1566         if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1567                 return $string;
1568         } else {
1569                 $subject = str_replace('_', ' ', $matches[2]);
1570                 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
1571                 return $subject;
1572         }
1573 }
1574
1575 /**
1576  * Helper function to convert hex encoded chars to ascii
1577  *
1578  * @since 3.1.0
1579  * @access private
1580  * @param array $match the preg_replace_callback matches array
1581  */
1582 function _wp_iso_convert( $match ) {
1583         return chr( hexdec( strtolower( $match[1] ) ) );
1584 }
1585
1586 /**
1587  * Returns a date in the GMT equivalent.
1588  *
1589  * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1590  * value of the 'gmt_offset' option. Return format can be overridden using the
1591  * $format parameter. The DateTime and DateTimeZone classes are used to respect
1592  * time zone differences in DST.
1593  *
1594  * @since 1.2.0
1595  *
1596  * @uses get_option() to retrieve the the value of 'gmt_offset'.
1597  * @param string $string The date to be converted.
1598  * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1599  * @return string GMT version of the date provided.
1600  */
1601 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1602         preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches);
1603         $tz = get_option('timezone_string');
1604         if ( $tz ) {
1605                 date_default_timezone_set( $tz );
1606                 $datetime = new DateTime( $string );
1607                 $datetime->setTimezone( new DateTimeZone('UTC') );
1608                 $offset = $datetime->getOffset();
1609                 $datetime->modify( '+' . $offset / 3600 . ' hours');
1610                 $string_gmt = gmdate($format, $datetime->format('U'));
1611
1612                 date_default_timezone_set('UTC');
1613         } else {
1614                 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1615                 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1616         }
1617         return $string_gmt;
1618 }
1619
1620 /**
1621  * Converts a GMT date into the correct format for the blog.
1622  *
1623  * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1624  * gmt_offset.Return format can be overridden using the $format parameter
1625  *
1626  * @since 1.2.0
1627  *
1628  * @param string $string The date to be converted.
1629  * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1630  * @return string Formatted date relative to the GMT offset.
1631  */
1632 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1633         preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches);
1634         $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1635         $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1636         return $string_localtime;
1637 }
1638
1639 /**
1640  * Computes an offset in seconds from an iso8601 timezone.
1641  *
1642  * @since 1.5.0
1643  *
1644  * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1645  * @return int|float The offset in seconds.
1646  */
1647 function iso8601_timezone_to_offset($timezone) {
1648         // $timezone is either 'Z' or '[+|-]hhmm'
1649         if ($timezone == 'Z') {
1650                 $offset = 0;
1651         } else {
1652                 $sign    = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1653                 $hours   = intval(substr($timezone, 1, 2));
1654                 $minutes = intval(substr($timezone, 3, 4)) / 60;
1655                 $offset  = $sign * 3600 * ($hours + $minutes);
1656         }
1657         return $offset;
1658 }
1659
1660 /**
1661  * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1662  *
1663  * @since 1.5.0
1664  *
1665  * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1666  * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1667  * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1668  */
1669 function iso8601_to_datetime($date_string, $timezone = 'user') {
1670         $timezone = strtolower($timezone);
1671
1672         if ($timezone == 'gmt') {
1673
1674                 preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
1675
1676                 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1677                         $offset = iso8601_timezone_to_offset($date_bits[7]);
1678                 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1679                         $offset = 3600 * get_option('gmt_offset');
1680                 }
1681
1682                 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1683                 $timestamp -= $offset;
1684
1685                 return gmdate('Y-m-d H:i:s', $timestamp);
1686
1687         } else if ($timezone == 'user') {
1688                 return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
1689         }
1690 }
1691
1692 /**
1693  * Adds a element attributes to open links in new windows.
1694  *
1695  * Comment text in popup windows should be filtered through this. Right now it's
1696  * a moderately dumb function, ideally it would detect whether a target or rel
1697  * attribute was already there and adjust its actions accordingly.
1698  *
1699  * @since 0.71
1700  *
1701  * @param string $text Content to replace links to open in a new window.
1702  * @return string Content that has filtered links.
1703  */
1704 function popuplinks($text) {
1705         $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1706         return $text;
1707 }
1708
1709 /**
1710  * Strips out all characters that are not allowable in an email.
1711  *
1712  * @since 1.5.0
1713  *
1714  * @param string $email Email address to filter.
1715  * @return string Filtered email address.
1716  */
1717 function sanitize_email( $email ) {
1718         // Test for the minimum length the email can be
1719         if ( strlen( $email ) < 3 ) {
1720                 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1721         }
1722
1723         // Test for an @ character after the first position
1724         if ( strpos( $email, '@', 1 ) === false ) {
1725                 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1726         }
1727
1728         // Split out the local and domain parts
1729         list( $local, $domain ) = explode( '@', $email, 2 );
1730
1731         // LOCAL PART
1732         // Test for invalid characters
1733         $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1734         if ( '' === $local ) {
1735                 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1736         }
1737
1738         // DOMAIN PART
1739         // Test for sequences of periods
1740         $domain = preg_replace( '/\.{2,}/', '', $domain );
1741         if ( '' === $domain ) {
1742                 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1743         }
1744
1745         // Test for leading and trailing periods and whitespace
1746         $domain = trim( $domain, " \t\n\r\0\x0B." );
1747         if ( '' === $domain ) {
1748                 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1749         }
1750
1751         // Split the domain into subs
1752         $subs = explode( '.', $domain );
1753
1754         // Assume the domain will have at least two subs
1755         if ( 2 > count( $subs ) ) {
1756                 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1757         }
1758
1759         // Create an array that will contain valid subs
1760         $new_subs = array();
1761
1762         // Loop through each sub
1763         foreach ( $subs as $sub ) {
1764                 // Test for leading and trailing hyphens
1765                 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1766
1767                 // Test for invalid characters
1768                 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
1769
1770                 // If there's anything left, add it to the valid subs
1771                 if ( '' !== $sub ) {
1772                         $new_subs[] = $sub;
1773                 }
1774         }
1775
1776         // If there aren't 2 or more valid subs
1777         if ( 2 > count( $new_subs ) ) {
1778                 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1779         }
1780
1781         // Join valid subs into the new domain
1782         $domain = join( '.', $new_subs );
1783
1784         // Put the email back together
1785         $email = $local . '@' . $domain;
1786
1787         // Congratulations your email made it!
1788         return apply_filters( 'sanitize_email', $email, $email, null );
1789 }
1790
1791 /**
1792  * Determines the difference between two timestamps.
1793  *
1794  * The difference is returned in a human readable format such as "1 hour",
1795  * "5 mins", "2 days".
1796  *
1797  * @since 1.5.0
1798  *
1799  * @param int $from Unix timestamp from which the difference begins.
1800  * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1801  * @return string Human readable time difference.
1802  */
1803 function human_time_diff( $from, $to = '' ) {
1804         if ( empty($to) )
1805                 $to = time();
1806         $diff = (int) abs($to - $from);
1807         if ($diff <= 3600) {
1808                 $mins = round($diff / 60);
1809                 if ($mins <= 1) {
1810                         $mins = 1;
1811                 }
1812                 /* translators: min=minute */
1813                 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1814         } else if (($diff <= 86400) && ($diff > 3600)) {
1815                 $hours = round($diff / 3600);
1816                 if ($hours <= 1) {
1817                         $hours = 1;
1818                 }
1819                 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1820         } elseif ($diff >= 86400) {
1821                 $days = round($diff / 86400);
1822                 if ($days <= 1) {
1823                         $days = 1;
1824                 }
1825                 $since = sprintf(_n('%s day', '%s days', $days), $days);
1826         }
1827         return $since;
1828 }
1829
1830 /**
1831  * Generates an excerpt from the content, if needed.
1832  *
1833  * The excerpt word amount will be 55 words and if the amount is greater than
1834  * that, then the string ' [...]' will be appended to the excerpt. If the string
1835  * is less than 55 words, then the content will be returned as is.
1836  *
1837  * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1838  * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1839  *
1840  * @since 1.5.0
1841  *
1842  * @param string $text The excerpt. If set to empty an excerpt is generated.
1843  * @return string The excerpt.
1844  */
1845 function wp_trim_excerpt($text) {
1846         $raw_excerpt = $text;
1847         if ( '' == $text ) {
1848                 $text = get_the_content('');
1849
1850                 $text = strip_shortcodes( $text );
1851
1852                 $text = apply_filters('the_content', $text);
1853                 $text = str_replace(']]>', ']]&gt;', $text);
1854                 $text = strip_tags($text);
1855                 $excerpt_length = apply_filters('excerpt_length', 55);
1856                 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1857                 $words = preg_split("/[\n\r\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
1858                 if ( count($words) > $excerpt_length ) {
1859                         array_pop($words);
1860                         $text = implode(' ', $words);
1861                         $text = $text . $excerpt_more;
1862                 } else {
1863                         $text = implode(' ', $words);
1864                 }
1865         }
1866         return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1867 }
1868
1869 /**
1870  * Converts named entities into numbered entities.
1871  *
1872  * @since 1.5.1
1873  *
1874  * @param string $text The text within which entities will be converted.
1875  * @return string Text with converted entities.
1876  */
1877 function ent2ncr($text) {
1878         $to_ncr = array(
1879                 '&quot;' => '&#34;',
1880                 '&amp;' => '&#38;',
1881                 '&frasl;' => '&#47;',
1882                 '&lt;' => '&#60;',
1883                 '&gt;' => '&#62;',
1884                 '|' => '&#124;',
1885                 '&nbsp;' => '&#160;',
1886                 '&iexcl;' => '&#161;',
1887                 '&cent;' => '&#162;',
1888                 '&pound;' => '&#163;',
1889                 '&curren;' => '&#164;',
1890                 '&yen;' => '&#165;',
1891                 '&brvbar;' => '&#166;',
1892                 '&brkbar;' => '&#166;',
1893                 '&sect;' => '&#167;',
1894                 '&uml;' => '&#168;',
1895                 '&die;' => '&#168;',
1896                 '&copy;' => '&#169;',
1897                 '&ordf;' => '&#170;',
1898                 '&laquo;' => '&#171;',
1899                 '&not;' => '&#172;',
1900                 '&shy;' => '&#173;',
1901                 '&reg;' => '&#174;',
1902                 '&macr;' => '&#175;',
1903                 '&hibar;' => '&#175;',
1904                 '&deg;' => '&#176;',
1905                 '&plusmn;' => '&#177;',
1906                 '&sup2;' => '&#178;',
1907                 '&sup3;' => '&#179;',
1908                 '&acute;' => '&#180;',
1909                 '&micro;' => '&#181;',
1910                 '&para;' => '&#182;',
1911                 '&middot;' => '&#183;',
1912                 '&cedil;' => '&#184;',
1913                 '&sup1;' => '&#185;',
1914                 '&ordm;' => '&#186;',
1915                 '&raquo;' => '&#187;',
1916                 '&frac14;' => '&#188;',
1917                 '&frac12;' => '&#189;',
1918                 '&frac34;' => '&#190;',
1919                 '&iquest;' => '&#191;',
1920                 '&Agrave;' => '&#192;',
1921                 '&Aacute;' => '&#193;',
1922                 '&Acirc;' => '&#194;',
1923                 '&Atilde;' => '&#195;',
1924                 '&Auml;' => '&#196;',
1925                 '&Aring;' => '&#197;',
1926                 '&AElig;' => '&#198;',
1927                 '&Ccedil;' => '&#199;',
1928                 '&Egrave;' => '&#200;',
1929                 '&Eacute;' => '&#201;',
1930                 '&Ecirc;' => '&#202;',
1931                 '&Euml;' => '&#203;',
1932                 '&Igrave;' => '&#204;',
1933                 '&Iacute;' => '&#205;',
1934                 '&Icirc;' => '&#206;',
1935                 '&Iuml;' => '&#207;',
1936                 '&ETH;' => '&#208;',
1937                 '&Ntilde;' => '&#209;',
1938                 '&Ograve;' => '&#210;',
1939                 '&Oacute;' => '&#211;',
1940                 '&Ocirc;' => '&#212;',
1941                 '&Otilde;' => '&#213;',
1942                 '&Ouml;' => '&#214;',
1943                 '&times;' => '&#215;',
1944                 '&Oslash;' => '&#216;',
1945                 '&Ugrave;' => '&#217;',
1946                 '&Uacute;' => '&#218;',
1947                 '&Ucirc;' => '&#219;',
1948                 '&Uuml;' => '&#220;',
1949                 '&Yacute;' => '&#221;',
1950                 '&THORN;' => '&#222;',
1951                 '&szlig;' => '&#223;',
1952                 '&agrave;' => '&#224;',
1953                 '&aacute;' => '&#225;',
1954                 '&acirc;' => '&#226;',
1955                 '&atilde;' => '&#227;',
1956                 '&auml;' => '&#228;',
1957                 '&aring;' => '&#229;',
1958                 '&aelig;' => '&#230;',
1959                 '&ccedil;' => '&#231;',
1960                 '&egrave;' => '&#232;',
1961                 '&eacute;' => '&#233;',
1962                 '&ecirc;' => '&#234;',
1963                 '&euml;' => '&#235;',
1964                 '&igrave;' => '&#236;',
1965                 '&iacute;' => '&#237;',
1966                 '&icirc;' => '&#238;',
1967                 '&iuml;' => '&#239;',
1968                 '&eth;' => '&#240;',
1969                 '&ntilde;' => '&#241;',
1970                 '&ograve;' => '&#242;',
1971                 '&oacute;' => '&#243;',
1972                 '&ocirc;' => '&#244;',
1973                 '&otilde;' => '&#245;',
1974                 '&ouml;' => '&#246;',
1975                 '&divide;' => '&#247;',
1976                 '&oslash;' => '&#248;',
1977                 '&ugrave;' => '&#249;',
1978                 '&uacute;' => '&#250;',
1979                 '&ucirc;' => '&#251;',
1980                 '&uuml;' => '&#252;',
1981                 '&yacute;' => '&#253;',
1982                 '&thorn;' => '&#254;',
1983                 '&yuml;' => '&#255;',
1984                 '&OElig;' => '&#338;',
1985                 '&oelig;' => '&#339;',
1986                 '&Scaron;' => '&#352;',
1987                 '&scaron;' => '&#353;',
1988                 '&Yuml;' => '&#376;',
1989                 '&fnof;' => '&#402;',
1990                 '&circ;' => '&#710;',
1991                 '&tilde;' => '&#732;',
1992                 '&Alpha;' => '&#913;',
1993                 '&Beta;' => '&#914;',
1994                 '&Gamma;' => '&#915;',
1995                 '&Delta;' => '&#916;',
1996                 '&Epsilon;' => '&#917;',
1997                 '&Zeta;' => '&#918;',
1998                 '&Eta;' => '&#919;',
1999                 '&Theta;' => '&#920;',
2000                 '&Iota;' => '&#921;',
2001                 '&Kappa;' => '&#922;',
2002                 '&Lambda;' => '&#923;',
2003                 '&Mu;' => '&#924;',
2004                 '&Nu;' => '&#925;',
2005                 '&Xi;' => '&#926;',
2006                 '&Omicron;' => '&#927;',
2007                 '&Pi;' => '&#928;',
2008                 '&Rho;' => '&#929;',
2009                 '&Sigma;' => '&#931;',
2010                 '&Tau;' => '&#932;',
2011                 '&Upsilon;' => '&#933;',
2012                 '&Phi;' => '&#934;',
2013                 '&Chi;' => '&#935;',
2014                 '&Psi;' => '&#936;',
2015                 '&Omega;' => '&#937;',
2016                 '&alpha;' => '&#945;',
2017                 '&beta;' => '&#946;',
2018                 '&gamma;' => '&#947;',
2019                 '&delta;' => '&#948;',
2020                 '&epsilon;' => '&#949;',
2021                 '&zeta;' => '&#950;',
2022                 '&eta;' => '&#951;',
2023                 '&theta;' => '&#952;',
2024                 '&iota;' => '&#953;',
2025                 '&kappa;' => '&#954;',
2026                 '&lambda;' => '&#955;',
2027                 '&mu;' => '&#956;',
2028                 '&nu;' => '&#957;',
2029                 '&xi;' => '&#958;',
2030                 '&omicron;' => '&#959;',
2031                 '&pi;' => '&#960;',
2032                 '&rho;' => '&#961;',
2033                 '&sigmaf;' => '&#962;',
2034                 '&sigma;' => '&#963;',
2035                 '&tau;' => '&#964;',
2036                 '&upsilon;' => '&#965;',
2037                 '&phi;' => '&#966;',
2038                 '&chi;' => '&#967;',
2039                 '&psi;' => '&#968;',
2040                 '&omega;' => '&#969;',
2041                 '&thetasym;' => '&#977;',
2042                 '&upsih;' => '&#978;',
2043                 '&piv;' => '&#982;',
2044                 '&ensp;' => '&#8194;',
2045                 '&emsp;' => '&#8195;',
2046                 '&thinsp;' => '&#8201;',
2047                 '&zwnj;' => '&#8204;',
2048                 '&zwj;' => '&#8205;',
2049                 '&lrm;' => '&#8206;',
2050                 '&rlm;' => '&#8207;',
2051                 '&ndash;' => '&#8211;',
2052                 '&mdash;' => '&#8212;',
2053                 '&lsquo;' => '&#8216;',
2054                 '&rsquo;' => '&#8217;',
2055                 '&sbquo;' => '&#8218;',
2056                 '&ldquo;' => '&#8220;',
2057                 '&rdquo;' => '&#8221;',
2058                 '&bdquo;' => '&#8222;',
2059                 '&dagger;' => '&#8224;',
2060                 '&Dagger;' => '&#8225;',
2061                 '&bull;' => '&#8226;',
2062                 '&hellip;' => '&#8230;',
2063                 '&permil;' => '&#8240;',
2064                 '&prime;' => '&#8242;',
2065                 '&Prime;' => '&#8243;',
2066                 '&lsaquo;' => '&#8249;',
2067                 '&rsaquo;' => '&#8250;',
2068                 '&oline;' => '&#8254;',
2069                 '&frasl;' => '&#8260;',
2070                 '&euro;' => '&#8364;',
2071                 '&image;' => '&#8465;',
2072                 '&weierp;' => '&#8472;',
2073                 '&real;' => '&#8476;',
2074                 '&trade;' => '&#8482;',
2075                 '&alefsym;' => '&#8501;',
2076                 '&crarr;' => '&#8629;',
2077                 '&lArr;' => '&#8656;',
2078                 '&uArr;' => '&#8657;',
2079                 '&rArr;' => '&#8658;',
2080                 '&dArr;' => '&#8659;',
2081                 '&hArr;' => '&#8660;',
2082                 '&forall;' => '&#8704;',
2083                 '&part;' => '&#8706;',
2084                 '&exist;' => '&#8707;',
2085                 '&empty;' => '&#8709;',
2086                 '&nabla;' => '&#8711;',
2087                 '&isin;' => '&#8712;',
2088                 '&notin;' => '&#8713;',
2089                 '&ni;' => '&#8715;',
2090                 '&prod;' => '&#8719;',
2091                 '&sum;' => '&#8721;',
2092                 '&minus;' => '&#8722;',
2093                 '&lowast;' => '&#8727;',
2094                 '&radic;' => '&#8730;',
2095                 '&prop;' => '&#8733;',
2096                 '&infin;' => '&#8734;',
2097                 '&ang;' => '&#8736;',
2098                 '&and;' => '&#8743;',
2099                 '&or;' => '&#8744;',
2100                 '&cap;' => '&#8745;',
2101                 '&cup;' => '&#8746;',
2102                 '&int;' => '&#8747;',
2103                 '&there4;' => '&#8756;',
2104                 '&sim;' => '&#8764;',
2105                 '&cong;' => '&#8773;',
2106                 '&asymp;' => '&#8776;',
2107                 '&ne;' => '&#8800;',
2108                 '&equiv;' => '&#8801;',
2109                 '&le;' => '&#8804;',
2110                 '&ge;' => '&#8805;',
2111                 '&sub;' => '&#8834;',
2112                 '&sup;' => '&#8835;',
2113                 '&nsub;' => '&#8836;',
2114                 '&sube;' => '&#8838;',
2115                 '&supe;' => '&#8839;',
2116                 '&oplus;' => '&#8853;',
2117                 '&otimes;' => '&#8855;',
2118                 '&perp;' => '&#8869;',
2119                 '&sdot;' => '&#8901;',
2120                 '&lceil;' => '&#8968;',
2121                 '&rceil;' => '&#8969;',
2122                 '&lfloor;' => '&#8970;',
2123                 '&rfloor;' => '&#8971;',
2124                 '&lang;' => '&#9001;',
2125                 '&rang;' => '&#9002;',
2126                 '&larr;' => '&#8592;',
2127                 '&uarr;' => '&#8593;',
2128                 '&rarr;' => '&#8594;',
2129                 '&darr;' => '&#8595;',
2130                 '&harr;' => '&#8596;',
2131                 '&loz;' => '&#9674;',
2132                 '&spades;' => '&#9824;',
2133                 '&clubs;' => '&#9827;',
2134                 '&hearts;' => '&#9829;',
2135                 '&diams;' => '&#9830;'
2136         );
2137
2138         return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2139 }
2140
2141 /**
2142  * Formats text for the rich text editor.
2143  *
2144  * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2145  * be applied to an empty string.
2146  *
2147  * @since 2.0.0
2148  *
2149  * @param string $text The text to be formatted.
2150  * @return string The formatted text after filter is applied.
2151  */
2152 function wp_richedit_pre($text) {
2153         // Filtering a blank results in an annoying <br />\n
2154         if ( empty($text) ) return apply_filters('richedit_pre', '');
2155
2156         $output = convert_chars($text);
2157         $output = wpautop($output);
2158         $output = htmlspecialchars($output, ENT_NOQUOTES);
2159
2160         return apply_filters('richedit_pre', $output);
2161 }
2162
2163 /**
2164  * Formats text for the HTML editor.
2165  *
2166  * Unless $output is empty it will pass through htmlspecialchars before the
2167  * 'htmledit_pre' filter is applied.
2168  *
2169  * @since 2.5.0
2170  *
2171  * @param string $output The text to be formatted.
2172  * @return string Formatted text after filter applied.
2173  */
2174 function wp_htmledit_pre($output) {
2175         if ( !empty($output) )
2176                 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2177
2178         return apply_filters('htmledit_pre', $output);
2179 }
2180
2181 /**
2182  * Perform a deep string replace operation to ensure the values in $search are no longer present
2183  *
2184  * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2185  * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2186  * str_replace would return
2187  *
2188  * @since 2.8.1
2189  * @access private
2190  *
2191  * @param string|array $search
2192  * @param string $subject
2193  * @return string The processed string
2194  */
2195 function _deep_replace( $search, $subject ) {
2196         $found = true;
2197         $subject = (string) $subject;
2198         while ( $found ) {
2199                 $found = false;
2200                 foreach ( (array) $search as $val ) {
2201                         while ( strpos( $subject, $val ) !== false ) {
2202                                 $found = true;
2203                                 $subject = str_replace( $val, '', $subject );
2204                         }
2205                 }
2206         }
2207
2208         return $subject;
2209 }
2210
2211 /**
2212  * Escapes data for use in a MySQL query
2213  *
2214  * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2215  *
2216  * @since 2.8.0
2217  * @param string $sql Unescaped SQL data
2218  * @return string The cleaned $sql
2219  */
2220 function esc_sql( $sql ) {
2221         global $wpdb;
2222         return $wpdb->escape( $sql );
2223 }
2224
2225 /**
2226  * Checks and cleans a URL.
2227  *
2228  * A number of characters are removed from the URL. If the URL is for displaying
2229  * (the default behaviour) amperstands are also replaced. The 'clean_url' filter
2230  * is applied to the returned cleaned URL.
2231  *
2232  * @since 2.8.0
2233  * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2234  *              via $protocols or the common ones set in the function.
2235  *
2236  * @param string $url The URL to be cleaned.
2237  * @param array $protocols Optional. An array of acceptable protocols.
2238  *              Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet' if not set.
2239  * @param string $_context Private. Use esc_url_raw() for database usage.
2240  * @return string The cleaned $url after the 'clean_url' filter is applied.
2241  */
2242 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2243         $original_url = $url;
2244
2245         if ( '' == $url )
2246                 return $url;
2247         $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2248         $strip = array('%0d', '%0a', '%0D', '%0A');
2249         $url = _deep_replace($strip, $url);
2250         $url = str_replace(';//', '://', $url);
2251         /* If the URL doesn't appear to contain a scheme, we
2252          * presume it needs http:// appended (unless a relative
2253          * link starting with / or a php file).
2254          */
2255         if ( strpos($url, ':') === false &&
2256                 substr( $url, 0, 1 ) != '/' && substr( $url, 0, 1 ) != '#' && !preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2257                 $url = 'http://' . $url;
2258
2259         // Replace ampersands and single quotes only when displaying.
2260         if ( 'display' == $_context ) {
2261                 $url = wp_kses_normalize_entities( $url );
2262                 $url = str_replace( '&amp;', '&#038;', $url );
2263                 $url = str_replace( "'", '&#039;', $url );
2264         }
2265
2266         if ( !is_array($protocols) )
2267                 $protocols = array ('http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn');
2268         if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2269                 return '';
2270
2271         return apply_filters('clean_url', $url, $original_url, $_context);
2272 }
2273
2274 /**
2275  * Performs esc_url() for database usage.
2276  *
2277  * @since 2.8.0
2278  * @uses esc_url()
2279  *
2280  * @param string $url The URL to be cleaned.
2281  * @param array $protocols An array of acceptable protocols.
2282  * @return string The cleaned URL.
2283  */
2284 function esc_url_raw( $url, $protocols = null ) {
2285         return esc_url( $url, $protocols, 'db' );
2286 }
2287
2288 /**
2289  * Convert entities, while preserving already-encoded entities.
2290  *
2291  * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2292  *
2293  * @since 1.2.2
2294  *
2295  * @param string $myHTML The text to be converted.
2296  * @return string Converted text.
2297  */
2298 function htmlentities2($myHTML) {
2299         $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2300         $translation_table[chr(38)] = '&';
2301         return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
2302 }
2303
2304 /**
2305  * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2306  *
2307  * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2308  * (in a tag attribute, for example onclick="..."). Note that the strings have to
2309  * be in single quotes. The filter 'js_escape' is also applied here.
2310  *
2311  * @since 2.8.0
2312  *
2313  * @param string $text The text to be escaped.
2314  * @return string Escaped text.
2315  */
2316 function esc_js( $text ) {
2317         $safe_text = wp_check_invalid_utf8( $text );
2318         $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2319         $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2320         $safe_text = str_replace( "\r", '', $safe_text );
2321         $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2322         return apply_filters( 'js_escape', $safe_text, $text );
2323 }
2324
2325 /**
2326  * Escaping for HTML blocks.
2327  *
2328  * @since 2.8.0
2329  *
2330  * @param string $text
2331  * @return string
2332  */
2333 function esc_html( $text ) {
2334         $safe_text = wp_check_invalid_utf8( $text );
2335         $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2336         return apply_filters( 'esc_html', $safe_text, $text );
2337 }
2338
2339 /**
2340  * Escaping for HTML attributes.
2341  *
2342  * @since 2.8.0
2343  *
2344  * @param string $text
2345  * @return string
2346  */
2347 function esc_attr( $text ) {
2348         $safe_text = wp_check_invalid_utf8( $text );
2349         $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2350         return apply_filters( 'attribute_escape', $safe_text, $text );
2351 }
2352
2353 /**
2354  * Escaping for textarea values.
2355  *
2356  * @since 3.1
2357  *
2358  * @param string $text
2359  * @return string
2360  */
2361 function esc_textarea( $text ) {
2362         $safe_text = htmlspecialchars( $text, ENT_QUOTES );
2363         return apply_filters( 'esc_textarea', $safe_text, $text );
2364 }
2365
2366 /**
2367  * Escape a HTML tag name.
2368  *
2369  * @since 2.5.0
2370  *
2371  * @param string $tag_name
2372  * @return string
2373  */
2374 function tag_escape($tag_name) {
2375         $safe_tag = strtolower( preg_replace('/[^a-zA-Z_:]/', '', $tag_name) );
2376         return apply_filters('tag_escape', $safe_tag, $tag_name);
2377 }
2378
2379 /**
2380  * Escapes text for SQL LIKE special characters % and _.
2381  *
2382  * @since 2.5.0
2383  *
2384  * @param string $text The text to be escaped.
2385  * @return string text, safe for inclusion in LIKE query.
2386  */
2387 function like_escape($text) {
2388         return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2389 }
2390
2391 /**
2392  * Convert full URL paths to absolute paths.
2393  *
2394  * Removes the http or https protocols and the domain. Keeps the path '/' at the
2395  * beginning, so it isn't a true relative link, but from the web root base.
2396  *
2397  * @since 2.1.0
2398  *
2399  * @param string $link Full URL path.
2400  * @return string Absolute path.
2401  */
2402 function wp_make_link_relative( $link ) {
2403         return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2404 }
2405
2406 /**
2407  * Sanitises various option values based on the nature of the option.
2408  *
2409  * This is basically a switch statement which will pass $value through a number
2410  * of functions depending on the $option.
2411  *
2412  * @since 2.0.5
2413  *
2414  * @param string $option The name of the option.
2415  * @param string $value The unsanitised value.
2416  * @return string Sanitized value.
2417  */
2418 function sanitize_option($option, $value) {
2419
2420         switch ( $option ) {
2421                 case 'admin_email':
2422                         $value = sanitize_email($value);
2423                         if ( !is_email($value) ) {
2424                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2425                                 if ( function_exists('add_settings_error') )
2426                                         add_settings_error('admin_email', 'invalid_admin_email', __('The email address entered did not appear to be a valid email address. Please enter a valid email address.'));
2427                         }
2428                         break;
2429                 case 'new_admin_email':
2430                         $value = sanitize_email($value);
2431                         if ( !is_email($value) ) {
2432                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2433                                 if ( function_exists('add_settings_error') )
2434                                         add_settings_error('new_admin_email', 'invalid_admin_email', __('The email address entered did not appear to be a valid email address. Please enter a valid email address.'));
2435                         }
2436                         break;
2437                 case 'thumbnail_size_w':
2438                 case 'thumbnail_size_h':
2439                 case 'medium_size_w':
2440                 case 'medium_size_h':
2441                 case 'large_size_w':
2442                 case 'large_size_h':
2443                 case 'embed_size_h':
2444                 case 'default_post_edit_rows':
2445                 case 'mailserver_port':
2446                 case 'comment_max_links':
2447                 case 'page_on_front':
2448                 case 'page_for_posts':
2449                 case 'rss_excerpt_length':
2450                 case 'default_category':
2451                 case 'default_email_category':
2452                 case 'default_link_category':
2453                 case 'close_comments_days_old':
2454                 case 'comments_per_page':
2455                 case 'thread_comments_depth':
2456                 case 'users_can_register':
2457                 case 'start_of_week':
2458                         $value = absint( $value );
2459                         break;
2460
2461                 case 'embed_size_w':
2462                         if ( '' !== $value )
2463                                 $value = absint( $value );
2464                         break;
2465
2466                 case 'posts_per_page':
2467                 case 'posts_per_rss':
2468                         $value = (int) $value;
2469                         if ( empty($value) )
2470                                 $value = 1;
2471                         if ( $value < -1 )
2472                                 $value = abs($value);
2473                         break;
2474
2475                 case 'default_ping_status':
2476                 case 'default_comment_status':
2477                         // Options that if not there have 0 value but need to be something like "closed"
2478                         if ( $value == '0' || $value == '')
2479                                 $value = 'closed';
2480                         break;
2481
2482                 case 'blogdescription':
2483                 case 'blogname':
2484                         $value = addslashes($value);
2485                         $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2486                         $value = stripslashes($value);
2487                         $value = esc_html( $value );
2488                         break;
2489
2490                 case 'blog_charset':
2491                         $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2492                         break;
2493
2494                 case 'date_format':
2495                 case 'time_format':
2496                 case 'mailserver_url':
2497                 case 'mailserver_login':
2498                 case 'mailserver_pass':
2499                 case 'ping_sites':
2500                 case 'upload_path':
2501                         $value = strip_tags($value);
2502                         $value = addslashes($value);
2503                         $value = wp_filter_kses($value); // calls stripslashes then addslashes
2504                         $value = stripslashes($value);
2505                         break;
2506
2507                 case 'gmt_offset':
2508                         $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2509                         break;
2510
2511                 case 'siteurl':
2512                         if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2513                                 $value = esc_url_raw($value);
2514                         } else {
2515                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2516                                 if ( function_exists('add_settings_error') )
2517                                         add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2518                         }
2519                         break;
2520
2521                 case 'home':
2522                         if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2523                                 $value = esc_url_raw($value);
2524                         } else {
2525                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2526                                 if ( function_exists('add_settings_error') )
2527                                         add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2528                         }
2529                         break;
2530                 case 'WPLANG':
2531                         $allowed = get_available_languages();
2532                         if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
2533                                 $value = get_option( $option );
2534                         break;
2535
2536                 case 'timezone_string':
2537                         $allowed_zones = timezone_identifiers_list();
2538                         if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
2539                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2540                                 if ( function_exists('add_settings_error') )
2541                                         add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
2542                         }
2543                         break;
2544
2545                 default :
2546                         $value = apply_filters("sanitize_option_{$option}", $value, $option);
2547                         break;
2548         }
2549
2550         return $value;
2551 }
2552
2553 /**
2554  * Parses a string into variables to be stored in an array.
2555  *
2556  * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2557  * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2558  *
2559  * @since 2.2.1
2560  * @uses apply_filters() for the 'wp_parse_str' filter.
2561  *
2562  * @param string $string The string to be parsed.
2563  * @param array $array Variables will be stored in this array.
2564  */
2565 function wp_parse_str( $string, &$array ) {
2566         parse_str( $string, $array );
2567         if ( get_magic_quotes_gpc() )
2568                 $array = stripslashes_deep( $array );
2569         $array = apply_filters( 'wp_parse_str', $array );
2570 }
2571
2572 /**
2573  * Convert lone less than signs.
2574  *
2575  * KSES already converts lone greater than signs.
2576  *
2577  * @uses wp_pre_kses_less_than_callback in the callback function.
2578  * @since 2.3.0
2579  *
2580  * @param string $text Text to be converted.
2581  * @return string Converted text.
2582  */
2583 function wp_pre_kses_less_than( $text ) {
2584         return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2585 }
2586
2587 /**
2588  * Callback function used by preg_replace.
2589  *
2590  * @uses esc_html to format the $matches text.
2591  * @since 2.3.0
2592  *
2593  * @param array $matches Populated by matches to preg_replace.
2594  * @return string The text returned after esc_html if needed.
2595  */
2596 function wp_pre_kses_less_than_callback( $matches ) {
2597         if ( false === strpos($matches[0], '>') )
2598                 return esc_html($matches[0]);
2599         return $matches[0];
2600 }
2601
2602 /**
2603  * WordPress implementation of PHP sprintf() with filters.
2604  *
2605  * @since 2.5.0
2606  * @link http://www.php.net/sprintf
2607  *
2608  * @param string $pattern The string which formatted args are inserted.
2609  * @param mixed $args,... Arguments to be formatted into the $pattern string.
2610  * @return string The formatted string.
2611  */
2612 function wp_sprintf( $pattern ) {
2613         $args = func_get_args( );
2614         $len = strlen($pattern);
2615         $start = 0;
2616         $result = '';
2617         $arg_index = 0;
2618         while ( $len > $start ) {
2619                 // Last character: append and break
2620                 if ( strlen($pattern) - 1 == $start ) {
2621                         $result .= substr($pattern, -1);
2622                         break;
2623                 }
2624
2625                 // Literal %: append and continue
2626                 if ( substr($pattern, $start, 2) == '%%' ) {
2627                         $start += 2;
2628                         $result .= '%';
2629                         continue;
2630                 }
2631
2632                 // Get fragment before next %
2633                 $end = strpos($pattern, '%', $start + 1);
2634                 if ( false === $end )
2635                         $end = $len;
2636                 $fragment = substr($pattern, $start, $end - $start);
2637
2638                 // Fragment has a specifier
2639                 if ( $pattern[$start] == '%' ) {
2640                         // Find numbered arguments or take the next one in order
2641                         if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2642                                 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2643                                 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2644                         } else {
2645                                 ++$arg_index;
2646                                 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2647                         }
2648
2649                         // Apply filters OR sprintf
2650                         $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2651                         if ( $_fragment != $fragment )
2652                                 $fragment = $_fragment;
2653                         else
2654                                 $fragment = sprintf($fragment, strval($arg) );
2655                 }
2656
2657                 // Append to result and move to next fragment
2658                 $result .= $fragment;
2659                 $start = $end;
2660         }
2661         return $result;
2662 }
2663
2664 /**
2665  * Localize list items before the rest of the content.
2666  *
2667  * The '%l' must be at the first characters can then contain the rest of the
2668  * content. The list items will have ', ', ', and', and ' and ' added depending
2669  * on the amount of list items in the $args parameter.
2670  *
2671  * @since 2.5.0
2672  *
2673  * @param string $pattern Content containing '%l' at the beginning.
2674  * @param array $args List items to prepend to the content and replace '%l'.
2675  * @return string Localized list items and rest of the content.
2676  */
2677 function wp_sprintf_l($pattern, $args) {
2678         // Not a match
2679         if ( substr($pattern, 0, 2) != '%l' )
2680                 return $pattern;
2681
2682         // Nothing to work with
2683         if ( empty($args) )
2684                 return '';
2685
2686         // Translate and filter the delimiter set (avoid ampersands and entities here)
2687         $l = apply_filters('wp_sprintf_l', array(
2688                 /* translators: used between list items, there is a space after the comma */
2689                 'between'          => __(', '),
2690                 /* translators: used between list items, there is a space after the and */
2691                 'between_last_two' => __(', and '),
2692                 /* translators: used between only two list items, there is a space after the and */
2693                 'between_only_two' => __(' and '),
2694                 ));
2695
2696         $args = (array) $args;
2697         $result = array_shift($args);
2698         if ( count($args) == 1 )
2699                 $result .= $l['between_only_two'] . array_shift($args);
2700         // Loop when more than two args
2701         $i = count($args);
2702         while ( $i ) {
2703                 $arg = array_shift($args);
2704                 $i--;
2705                 if ( 0 == $i )
2706                         $result .= $l['between_last_two'] . $arg;
2707                 else
2708                         $result .= $l['between'] . $arg;
2709         }
2710         return $result . substr($pattern, 2);
2711 }
2712
2713 /**
2714  * Safely extracts not more than the first $count characters from html string.
2715  *
2716  * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2717  * be counted as one character. For example &amp; will be counted as 4, &lt; as
2718  * 3, etc.
2719  *
2720  * @since 2.5.0
2721  *
2722  * @param integer $str String to get the excerpt from.
2723  * @param integer $count Maximum number of characters to take.
2724  * @return string The excerpt.
2725  */
2726 function wp_html_excerpt( $str, $count ) {
2727         $str = wp_strip_all_tags( $str, true );
2728         $str = mb_substr( $str, 0, $count );
2729         // remove part of an entity at the end
2730         $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2731         return $str;
2732 }
2733
2734 /**
2735  * Add a Base url to relative links in passed content.
2736  *
2737  * By default it supports the 'src' and 'href' attributes. However this can be
2738  * changed via the 3rd param.
2739  *
2740  * @since 2.7.0
2741  *
2742  * @param string $content String to search for links in.
2743  * @param string $base The base URL to prefix to links.
2744  * @param array $attrs The attributes which should be processed.
2745  * @return string The processed content.
2746  */
2747 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2748         global $_links_add_base;
2749         $_links_add_base = $base;
2750         $attrs = implode('|', (array)$attrs);
2751         return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
2752 }
2753
2754 /**
2755  * Callback to add a base url to relative links in passed content.
2756  *
2757  * @since 2.7.0
2758  * @access private
2759  *
2760  * @param string $m The matched link.
2761  * @return string The processed link.
2762  */
2763 function _links_add_base($m) {
2764         global $_links_add_base;
2765         //1 = attribute name  2 = quotation mark  3 = URL
2766         return $m[1] . '=' . $m[2] .
2767                 (strpos($m[3], 'http://') === false ?
2768                         path_join($_links_add_base, $m[3]) :
2769                         $m[3])
2770                 . $m[2];
2771 }
2772
2773 /**
2774  * Adds a Target attribute to all links in passed content.
2775  *
2776  * This function by default only applies to <a> tags, however this can be
2777  * modified by the 3rd param.
2778  *
2779  * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
2780  *
2781  * @since 2.7.0
2782  *
2783  * @param string $content String to search for links in.
2784  * @param string $target The Target to add to the links.
2785  * @param array $tags An array of tags to apply to.
2786  * @return string The processed content.
2787  */
2788 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2789         global $_links_add_target;
2790         $_links_add_target = $target;
2791         $tags = implode('|', (array)$tags);
2792         return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content );
2793 }
2794
2795 /**
2796  * Callback to add a target attribute to all links in passed content.
2797  *
2798  * @since 2.7.0
2799  * @access private
2800  *
2801  * @param string $m The matched link.
2802  * @return string The processed link.
2803  */
2804 function _links_add_target( $m ) {
2805         global $_links_add_target;
2806         $tag = $m[1];
2807         $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2808         return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
2809 }
2810
2811 // normalize EOL characters and strip duplicate whitespace
2812 function normalize_whitespace( $str ) {
2813         $str  = trim($str);
2814         $str  = str_replace("\r", "\n", $str);
2815         $str  = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2816         return $str;
2817 }
2818
2819 /**
2820  * Properly strip all HTML tags including script and style
2821  *
2822  * @since 2.9.0
2823  *
2824  * @param string $string String containing HTML tags
2825  * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2826  * @return string The processed string.
2827  */
2828 function wp_strip_all_tags($string, $remove_breaks = false) {
2829         $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2830         $string = strip_tags($string);
2831
2832         if ( $remove_breaks )
2833                 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2834
2835         return trim($string);
2836 }
2837
2838 /**
2839  * Sanitize a string from user input or from the db
2840  *
2841  * check for invalid UTF-8,
2842  * Convert single < characters to entity,
2843  * strip all tags,
2844  * remove line breaks, tabs and extra white space,
2845  * strip octets.
2846  *
2847  * @since 2.9.0
2848  *
2849  * @param string $str
2850  * @return string
2851  */
2852 function sanitize_text_field($str) {
2853         $filtered = wp_check_invalid_utf8( $str );
2854
2855         if ( strpos($filtered, '<') !== false ) {
2856                 $filtered = wp_pre_kses_less_than( $filtered );
2857                 // This will strip extra whitespace for us.
2858                 $filtered = wp_strip_all_tags( $filtered, true );
2859         } else {
2860                 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2861         }
2862
2863         $match = array();
2864         $found = false;
2865         while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
2866                 $filtered = str_replace($match[0], '', $filtered);
2867                 $found = true;
2868         }
2869
2870         if ( $found ) {
2871                 // Strip out the whitespace that may now exist after removing the octets.
2872                 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
2873         }
2874
2875         return apply_filters('sanitize_text_field', $filtered, $str);
2876 }
2877
2878 /**
2879  * i18n friendly version of basename()
2880  *
2881  * @since 3.1.0
2882  *
2883  * @param string $path A path.
2884  * @param string $suffix If the filename ends in suffix this will also be cut off.
2885  * @return string
2886  */
2887 function wp_basename( $path, $suffix = '' ) {
2888         return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
2889 }
2890
2891 /**
2892  * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
2893  *
2894  * Violating our coding standards for a good function name.
2895  *
2896  * @since 3.0.0
2897  */
2898 function capital_P_dangit( $text ) {
2899         // Simple replacement for titles
2900         if ( 'the_title' === current_filter() )
2901                 return str_replace( 'Wordpress', 'WordPress', $text );
2902         // Still here? Use the more judicious replacement
2903         static $dblq = false;
2904         if ( false === $dblq )
2905                 $dblq = _x('&#8220;', 'opening curly quote');
2906         return str_replace(
2907                 array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
2908                 array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
2909         $text );
2910
2911 }
2912
2913 /**
2914  * Sanitize a mime type
2915  *
2916  * @since 3.1.3
2917  *
2918  * @param string $mime_type Mime type
2919  * @return string Sanitized mime type
2920  */
2921 function sanitize_mime_type( $mime_type ) {
2922         $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
2923         return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
2924 }
2925
2926 ?>