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