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