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