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