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