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