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