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