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