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