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