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