]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/formatting.php
Wordpress 3.3.1-scripts
[autoinstalls/wordpress.git] / wp-includes / formatting.php
1 <?php
2 /**
3  * Main WordPress Formatting API.
4  *
5  * Handles many functions for formatting output.
6  *
7  * @package WordPress
8  **/
9
10 /**
11  * Replaces common plain text characters into formatted entities
12  *
13  * As an example,
14  * <code>
15  * 'cause today's effort makes it worth tomorrow's "holiday"...
16  * </code>
17  * Becomes:
18  * <code>
19  * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221;&#8230;
20  * </code>
21  * Code within certain html blocks are skipped.
22  *
23  * @since 0.71
24  * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
25  *
26  * @param string $text The text to be formatted
27  * @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         $suffix = '';
1354
1355         /** Include parentheses in the URL only if paired **/
1356         while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
1357                 $suffix = strrchr( $url, ')' ) . $suffix;
1358                 $url = substr( $url, 0, strrpos( $url, ')' ) );
1359         }
1360
1361         $url = esc_url($url);
1362         if ( empty($url) )
1363                 return $matches[0];
1364
1365         return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
1366 }
1367
1368 /**
1369  * Callback to convert URL match to HTML A element.
1370  *
1371  * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1372  * make_clickable()}.
1373  *
1374  * @since 2.3.2
1375  * @access private
1376  *
1377  * @param array $matches Single Regex Match.
1378  * @return string HTML A element with URL address.
1379  */
1380 function _make_web_ftp_clickable_cb($matches) {
1381         $ret = '';
1382         $dest = $matches[2];
1383         $dest = 'http://' . $dest;
1384         $dest = esc_url($dest);
1385         if ( empty($dest) )
1386                 return $matches[0];
1387
1388         // removed trailing [.,;:)] from URL
1389         if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
1390                 $ret = substr($dest, -1);
1391                 $dest = substr($dest, 0, strlen($dest)-1);
1392         }
1393         return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
1394 }
1395
1396 /**
1397  * Callback to convert email address match to HTML A element.
1398  *
1399  * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
1400  * make_clickable()}.
1401  *
1402  * @since 2.3.2
1403  * @access private
1404  *
1405  * @param array $matches Single Regex Match.
1406  * @return string HTML A element with email address.
1407  */
1408 function _make_email_clickable_cb($matches) {
1409         $email = $matches[2] . '@' . $matches[3];
1410         return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
1411 }
1412
1413 /**
1414  * Convert plaintext URI to HTML links.
1415  *
1416  * Converts URI, www and ftp, and email addresses. Finishes by fixing links
1417  * within links.
1418  *
1419  * @since 0.71
1420  *
1421  * @param string $ret Content to convert URIs.
1422  * @return string Content with converted URIs.
1423  */
1424 function make_clickable($ret) {
1425         $ret = ' ' . $ret;
1426         // in testing, using arrays here was found to be faster
1427         $save = @ini_set('pcre.recursion_limit', 10000);
1428         $retval = preg_replace_callback('#(?<!=[\'"])(?<=[*\')+.,;:!&$\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#%~/?@\[\]-]{1,2000}|[\'*(+.,;:!=&$](?![\b\)]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
1429         if (null !== $retval )
1430                 $ret = $retval;
1431         @ini_set('pcre.recursion_limit', $save);
1432         $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
1433         $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
1434         // this one is not in an array because we need it to run last, for cleanup of accidental links within links
1435         $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
1436         $ret = trim($ret);
1437         return $ret;
1438 }
1439
1440 /**
1441  * Adds rel nofollow string to all HTML A elements in content.
1442  *
1443  * @since 1.5.0
1444  *
1445  * @param string $text Content that may contain HTML A elements.
1446  * @return string Converted content.
1447  */
1448 function wp_rel_nofollow( $text ) {
1449         // This is a pre save filter, so text is already escaped.
1450         $text = stripslashes($text);
1451         $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
1452         $text = esc_sql($text);
1453         return $text;
1454 }
1455
1456 /**
1457  * Callback to used to add rel=nofollow string to HTML A element.
1458  *
1459  * Will remove already existing rel="nofollow" and rel='nofollow' from the
1460  * string to prevent from invalidating (X)HTML.
1461  *
1462  * @since 2.3.0
1463  *
1464  * @param array $matches Single Match
1465  * @return string HTML A Element with rel nofollow.
1466  */
1467 function wp_rel_nofollow_callback( $matches ) {
1468         $text = $matches[1];
1469         $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
1470         return "<a $text rel=\"nofollow\">";
1471 }
1472
1473 /**
1474  * Convert one smiley code to the icon graphic file equivalent.
1475  *
1476  * Looks up one smiley code in the $wpsmiliestrans global array and returns an
1477  * <img> string for that smiley.
1478  *
1479  * @global array $wpsmiliestrans
1480  * @since 2.8.0
1481  *
1482  * @param string $smiley Smiley code to convert to image.
1483  * @return string Image string for smiley.
1484  */
1485 function translate_smiley($smiley) {
1486         global $wpsmiliestrans;
1487
1488         if (count($smiley) == 0) {
1489                 return '';
1490         }
1491
1492         $smiley = trim(reset($smiley));
1493         $img = $wpsmiliestrans[$smiley];
1494         $smiley_masked = esc_attr($smiley);
1495
1496         $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url());
1497
1498         return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> ";
1499 }
1500
1501 /**
1502  * Convert text equivalent of smilies to images.
1503  *
1504  * Will only convert smilies if the option 'use_smilies' is true and the global
1505  * used in the function isn't empty.
1506  *
1507  * @since 0.71
1508  * @uses $wp_smiliessearch
1509  *
1510  * @param string $text Content to convert smilies from text.
1511  * @return string Converted content with text smilies replaced with images.
1512  */
1513 function convert_smilies($text) {
1514         global $wp_smiliessearch;
1515         $output = '';
1516         if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
1517                 // HTML loop taken from texturize function, could possible be consolidated
1518                 $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
1519                 $stop = count($textarr);// loop stuff
1520                 for ($i = 0; $i < $stop; $i++) {
1521                         $content = $textarr[$i];
1522                         if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag
1523                                 $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
1524                         }
1525                         $output .= $content;
1526                 }
1527         } else {
1528                 // return default text.
1529                 $output = $text;
1530         }
1531         return $output;
1532 }
1533
1534 /**
1535  * Verifies that an email is valid.
1536  *
1537  * Does not grok i18n domains. Not RFC compliant.
1538  *
1539  * @since 0.71
1540  *
1541  * @param string $email Email address to verify.
1542  * @param boolean $deprecated Deprecated.
1543  * @return string|bool Either false or the valid email address.
1544  */
1545 function is_email( $email, $deprecated = false ) {
1546         if ( ! empty( $deprecated ) )
1547                 _deprecated_argument( __FUNCTION__, '3.0' );
1548
1549         // Test for the minimum length the email can be
1550         if ( strlen( $email ) < 3 ) {
1551                 return apply_filters( 'is_email', false, $email, 'email_too_short' );
1552         }
1553
1554         // Test for an @ character after the first position
1555         if ( strpos( $email, '@', 1 ) === false ) {
1556                 return apply_filters( 'is_email', false, $email, 'email_no_at' );
1557         }
1558
1559         // Split out the local and domain parts
1560         list( $local, $domain ) = explode( '@', $email, 2 );
1561
1562         // LOCAL PART
1563         // Test for invalid characters
1564         if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
1565                 return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
1566         }
1567
1568         // DOMAIN PART
1569         // Test for sequences of periods
1570         if ( preg_match( '/\.{2,}/', $domain ) ) {
1571                 return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
1572         }
1573
1574         // Test for leading and trailing periods and whitespace
1575         if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
1576                 return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
1577         }
1578
1579         // Split the domain into subs
1580         $subs = explode( '.', $domain );
1581
1582         // Assume the domain will have at least two subs
1583         if ( 2 > count( $subs ) ) {
1584                 return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
1585         }
1586
1587         // Loop through each sub
1588         foreach ( $subs as $sub ) {
1589                 // Test for leading and trailing hyphens and whitespace
1590                 if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
1591                         return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
1592                 }
1593
1594                 // Test for invalid characters
1595                 if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
1596                         return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
1597                 }
1598         }
1599
1600         // Congratulations your email made it!
1601         return apply_filters( 'is_email', $email, $email, null );
1602 }
1603
1604 /**
1605  * Convert to ASCII from email subjects.
1606  *
1607  * @since 1.2.0
1608  * @usedby wp_mail() handles charsets in email subjects
1609  *
1610  * @param string $string Subject line
1611  * @return string Converted string to ASCII
1612  */
1613 function wp_iso_descrambler($string) {
1614         /* this may only work with iso-8859-1, I'm afraid */
1615         if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
1616                 return $string;
1617         } else {
1618                 $subject = str_replace('_', ' ', $matches[2]);
1619                 $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
1620                 return $subject;
1621         }
1622 }
1623
1624 /**
1625  * Helper function to convert hex encoded chars to ascii
1626  *
1627  * @since 3.1.0
1628  * @access private
1629  * @param array $match the preg_replace_callback matches array
1630  */
1631 function _wp_iso_convert( $match ) {
1632         return chr( hexdec( strtolower( $match[1] ) ) );
1633 }
1634
1635 /**
1636  * Returns a date in the GMT equivalent.
1637  *
1638  * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
1639  * value of the 'gmt_offset' option. Return format can be overridden using the
1640  * $format parameter. The DateTime and DateTimeZone classes are used to respect
1641  * time zone differences in DST.
1642  *
1643  * @since 1.2.0
1644  *
1645  * @uses get_option() to retrieve the the value of 'gmt_offset'.
1646  * @param string $string The date to be converted.
1647  * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1648  * @return string GMT version of the date provided.
1649  */
1650 function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') {
1651         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);
1652         $tz = get_option('timezone_string');
1653         if ( $tz ) {
1654                 date_default_timezone_set( $tz );
1655                 $datetime = new DateTime( $string );
1656                 $datetime->setTimezone( new DateTimeZone('UTC') );
1657                 $offset = $datetime->getOffset();
1658                 $datetime->modify( '+' . $offset / 3600 . ' hours');
1659                 $string_gmt = gmdate($format, $datetime->format('U'));
1660
1661                 date_default_timezone_set('UTC');
1662         } else {
1663                 $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1664                 $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * 3600);
1665         }
1666         return $string_gmt;
1667 }
1668
1669 /**
1670  * Converts a GMT date into the correct format for the blog.
1671  *
1672  * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
1673  * gmt_offset.Return format can be overridden using the $format parameter
1674  *
1675  * @since 1.2.0
1676  *
1677  * @param string $string The date to be converted.
1678  * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
1679  * @return string Formatted date relative to the GMT offset.
1680  */
1681 function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') {
1682         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);
1683         $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
1684         $string_localtime = gmdate($format, $string_time + get_option('gmt_offset')*3600);
1685         return $string_localtime;
1686 }
1687
1688 /**
1689  * Computes an offset in seconds from an iso8601 timezone.
1690  *
1691  * @since 1.5.0
1692  *
1693  * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
1694  * @return int|float The offset in seconds.
1695  */
1696 function iso8601_timezone_to_offset($timezone) {
1697         // $timezone is either 'Z' or '[+|-]hhmm'
1698         if ($timezone == 'Z') {
1699                 $offset = 0;
1700         } else {
1701                 $sign    = (substr($timezone, 0, 1) == '+') ? 1 : -1;
1702                 $hours   = intval(substr($timezone, 1, 2));
1703                 $minutes = intval(substr($timezone, 3, 4)) / 60;
1704                 $offset  = $sign * 3600 * ($hours + $minutes);
1705         }
1706         return $offset;
1707 }
1708
1709 /**
1710  * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
1711  *
1712  * @since 1.5.0
1713  *
1714  * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
1715  * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
1716  * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
1717  */
1718 function iso8601_to_datetime($date_string, $timezone = 'user') {
1719         $timezone = strtolower($timezone);
1720
1721         if ($timezone == 'gmt') {
1722
1723                 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);
1724
1725                 if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
1726                         $offset = iso8601_timezone_to_offset($date_bits[7]);
1727                 } else { // we don't have a timezone, so we assume user local timezone (not server's!)
1728                         $offset = 3600 * get_option('gmt_offset');
1729                 }
1730
1731                 $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
1732                 $timestamp -= $offset;
1733
1734                 return gmdate('Y-m-d H:i:s', $timestamp);
1735
1736         } else if ($timezone == 'user') {
1737                 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);
1738         }
1739 }
1740
1741 /**
1742  * Adds a element attributes to open links in new windows.
1743  *
1744  * Comment text in popup windows should be filtered through this. Right now it's
1745  * a moderately dumb function, ideally it would detect whether a target or rel
1746  * attribute was already there and adjust its actions accordingly.
1747  *
1748  * @since 0.71
1749  *
1750  * @param string $text Content to replace links to open in a new window.
1751  * @return string Content that has filtered links.
1752  */
1753 function popuplinks($text) {
1754         $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
1755         return $text;
1756 }
1757
1758 /**
1759  * Strips out all characters that are not allowable in an email.
1760  *
1761  * @since 1.5.0
1762  *
1763  * @param string $email Email address to filter.
1764  * @return string Filtered email address.
1765  */
1766 function sanitize_email( $email ) {
1767         // Test for the minimum length the email can be
1768         if ( strlen( $email ) < 3 ) {
1769                 return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
1770         }
1771
1772         // Test for an @ character after the first position
1773         if ( strpos( $email, '@', 1 ) === false ) {
1774                 return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
1775         }
1776
1777         // Split out the local and domain parts
1778         list( $local, $domain ) = explode( '@', $email, 2 );
1779
1780         // LOCAL PART
1781         // Test for invalid characters
1782         $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
1783         if ( '' === $local ) {
1784                 return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
1785         }
1786
1787         // DOMAIN PART
1788         // Test for sequences of periods
1789         $domain = preg_replace( '/\.{2,}/', '', $domain );
1790         if ( '' === $domain ) {
1791                 return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
1792         }
1793
1794         // Test for leading and trailing periods and whitespace
1795         $domain = trim( $domain, " \t\n\r\0\x0B." );
1796         if ( '' === $domain ) {
1797                 return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
1798         }
1799
1800         // Split the domain into subs
1801         $subs = explode( '.', $domain );
1802
1803         // Assume the domain will have at least two subs
1804         if ( 2 > count( $subs ) ) {
1805                 return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
1806         }
1807
1808         // Create an array that will contain valid subs
1809         $new_subs = array();
1810
1811         // Loop through each sub
1812         foreach ( $subs as $sub ) {
1813                 // Test for leading and trailing hyphens
1814                 $sub = trim( $sub, " \t\n\r\0\x0B-" );
1815
1816                 // Test for invalid characters
1817                 $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
1818
1819                 // If there's anything left, add it to the valid subs
1820                 if ( '' !== $sub ) {
1821                         $new_subs[] = $sub;
1822                 }
1823         }
1824
1825         // If there aren't 2 or more valid subs
1826         if ( 2 > count( $new_subs ) ) {
1827                 return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
1828         }
1829
1830         // Join valid subs into the new domain
1831         $domain = join( '.', $new_subs );
1832
1833         // Put the email back together
1834         $email = $local . '@' . $domain;
1835
1836         // Congratulations your email made it!
1837         return apply_filters( 'sanitize_email', $email, $email, null );
1838 }
1839
1840 /**
1841  * Determines the difference between two timestamps.
1842  *
1843  * The difference is returned in a human readable format such as "1 hour",
1844  * "5 mins", "2 days".
1845  *
1846  * @since 1.5.0
1847  *
1848  * @param int $from Unix timestamp from which the difference begins.
1849  * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
1850  * @return string Human readable time difference.
1851  */
1852 function human_time_diff( $from, $to = '' ) {
1853         if ( empty($to) )
1854                 $to = time();
1855         $diff = (int) abs($to - $from);
1856         if ($diff <= 3600) {
1857                 $mins = round($diff / 60);
1858                 if ($mins <= 1) {
1859                         $mins = 1;
1860                 }
1861                 /* translators: min=minute */
1862                 $since = sprintf(_n('%s min', '%s mins', $mins), $mins);
1863         } else if (($diff <= 86400) && ($diff > 3600)) {
1864                 $hours = round($diff / 3600);
1865                 if ($hours <= 1) {
1866                         $hours = 1;
1867                 }
1868                 $since = sprintf(_n('%s hour', '%s hours', $hours), $hours);
1869         } elseif ($diff >= 86400) {
1870                 $days = round($diff / 86400);
1871                 if ($days <= 1) {
1872                         $days = 1;
1873                 }
1874                 $since = sprintf(_n('%s day', '%s days', $days), $days);
1875         }
1876         return $since;
1877 }
1878
1879 /**
1880  * Generates an excerpt from the content, if needed.
1881  *
1882  * The excerpt word amount will be 55 words and if the amount is greater than
1883  * that, then the string ' [...]' will be appended to the excerpt. If the string
1884  * is less than 55 words, then the content will be returned as is.
1885  *
1886  * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
1887  * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter
1888  *
1889  * @since 1.5.0
1890  *
1891  * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
1892  * @return string The excerpt.
1893  */
1894 function wp_trim_excerpt($text = '') {
1895         $raw_excerpt = $text;
1896         if ( '' == $text ) {
1897                 $text = get_the_content('');
1898
1899                 $text = strip_shortcodes( $text );
1900
1901                 $text = apply_filters('the_content', $text);
1902                 $text = str_replace(']]>', ']]&gt;', $text);
1903                 $excerpt_length = apply_filters('excerpt_length', 55);
1904                 $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
1905                 $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
1906         }
1907         return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
1908 }
1909
1910 /**
1911  * Trims text to a certain number of words.
1912  *
1913  * @since 3.3.0
1914  *
1915  * @param string $text Text to trim.
1916  * @param int $num_words Number of words. Default 55.
1917  * @param string $more What to append if $text needs to be trimmed. Default '&hellip;'.
1918  * @return string Trimmed text.
1919  */
1920 function wp_trim_words( $text, $num_words = 55, $more = null ) {
1921         if ( null === $more )
1922                 $more = __( '&hellip;' );
1923         $original_text = $text;
1924         $text = wp_strip_all_tags( $text );
1925         $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
1926         if ( count( $words_array ) > $num_words ) {
1927                 array_pop( $words_array );
1928                 $text = implode( ' ', $words_array );
1929                 $text = $text . $more;
1930         } else {
1931                 $text = implode( ' ', $words_array );
1932         }
1933         return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
1934 }
1935
1936 /**
1937  * Converts named entities into numbered entities.
1938  *
1939  * @since 1.5.1
1940  *
1941  * @param string $text The text within which entities will be converted.
1942  * @return string Text with converted entities.
1943  */
1944 function ent2ncr($text) {
1945
1946         // Allow a plugin to short-circuit and override the mappings.
1947         $filtered = apply_filters( 'pre_ent2ncr', null, $text );
1948         if( null !== $filtered )
1949                 return $filtered;
1950
1951         $to_ncr = array(
1952                 '&quot;' => '&#34;',
1953                 '&amp;' => '&#38;',
1954                 '&frasl;' => '&#47;',
1955                 '&lt;' => '&#60;',
1956                 '&gt;' => '&#62;',
1957                 '|' => '&#124;',
1958                 '&nbsp;' => '&#160;',
1959                 '&iexcl;' => '&#161;',
1960                 '&cent;' => '&#162;',
1961                 '&pound;' => '&#163;',
1962                 '&curren;' => '&#164;',
1963                 '&yen;' => '&#165;',
1964                 '&brvbar;' => '&#166;',
1965                 '&brkbar;' => '&#166;',
1966                 '&sect;' => '&#167;',
1967                 '&uml;' => '&#168;',
1968                 '&die;' => '&#168;',
1969                 '&copy;' => '&#169;',
1970                 '&ordf;' => '&#170;',
1971                 '&laquo;' => '&#171;',
1972                 '&not;' => '&#172;',
1973                 '&shy;' => '&#173;',
1974                 '&reg;' => '&#174;',
1975                 '&macr;' => '&#175;',
1976                 '&hibar;' => '&#175;',
1977                 '&deg;' => '&#176;',
1978                 '&plusmn;' => '&#177;',
1979                 '&sup2;' => '&#178;',
1980                 '&sup3;' => '&#179;',
1981                 '&acute;' => '&#180;',
1982                 '&micro;' => '&#181;',
1983                 '&para;' => '&#182;',
1984                 '&middot;' => '&#183;',
1985                 '&cedil;' => '&#184;',
1986                 '&sup1;' => '&#185;',
1987                 '&ordm;' => '&#186;',
1988                 '&raquo;' => '&#187;',
1989                 '&frac14;' => '&#188;',
1990                 '&frac12;' => '&#189;',
1991                 '&frac34;' => '&#190;',
1992                 '&iquest;' => '&#191;',
1993                 '&Agrave;' => '&#192;',
1994                 '&Aacute;' => '&#193;',
1995                 '&Acirc;' => '&#194;',
1996                 '&Atilde;' => '&#195;',
1997                 '&Auml;' => '&#196;',
1998                 '&Aring;' => '&#197;',
1999                 '&AElig;' => '&#198;',
2000                 '&Ccedil;' => '&#199;',
2001                 '&Egrave;' => '&#200;',
2002                 '&Eacute;' => '&#201;',
2003                 '&Ecirc;' => '&#202;',
2004                 '&Euml;' => '&#203;',
2005                 '&Igrave;' => '&#204;',
2006                 '&Iacute;' => '&#205;',
2007                 '&Icirc;' => '&#206;',
2008                 '&Iuml;' => '&#207;',
2009                 '&ETH;' => '&#208;',
2010                 '&Ntilde;' => '&#209;',
2011                 '&Ograve;' => '&#210;',
2012                 '&Oacute;' => '&#211;',
2013                 '&Ocirc;' => '&#212;',
2014                 '&Otilde;' => '&#213;',
2015                 '&Ouml;' => '&#214;',
2016                 '&times;' => '&#215;',
2017                 '&Oslash;' => '&#216;',
2018                 '&Ugrave;' => '&#217;',
2019                 '&Uacute;' => '&#218;',
2020                 '&Ucirc;' => '&#219;',
2021                 '&Uuml;' => '&#220;',
2022                 '&Yacute;' => '&#221;',
2023                 '&THORN;' => '&#222;',
2024                 '&szlig;' => '&#223;',
2025                 '&agrave;' => '&#224;',
2026                 '&aacute;' => '&#225;',
2027                 '&acirc;' => '&#226;',
2028                 '&atilde;' => '&#227;',
2029                 '&auml;' => '&#228;',
2030                 '&aring;' => '&#229;',
2031                 '&aelig;' => '&#230;',
2032                 '&ccedil;' => '&#231;',
2033                 '&egrave;' => '&#232;',
2034                 '&eacute;' => '&#233;',
2035                 '&ecirc;' => '&#234;',
2036                 '&euml;' => '&#235;',
2037                 '&igrave;' => '&#236;',
2038                 '&iacute;' => '&#237;',
2039                 '&icirc;' => '&#238;',
2040                 '&iuml;' => '&#239;',
2041                 '&eth;' => '&#240;',
2042                 '&ntilde;' => '&#241;',
2043                 '&ograve;' => '&#242;',
2044                 '&oacute;' => '&#243;',
2045                 '&ocirc;' => '&#244;',
2046                 '&otilde;' => '&#245;',
2047                 '&ouml;' => '&#246;',
2048                 '&divide;' => '&#247;',
2049                 '&oslash;' => '&#248;',
2050                 '&ugrave;' => '&#249;',
2051                 '&uacute;' => '&#250;',
2052                 '&ucirc;' => '&#251;',
2053                 '&uuml;' => '&#252;',
2054                 '&yacute;' => '&#253;',
2055                 '&thorn;' => '&#254;',
2056                 '&yuml;' => '&#255;',
2057                 '&OElig;' => '&#338;',
2058                 '&oelig;' => '&#339;',
2059                 '&Scaron;' => '&#352;',
2060                 '&scaron;' => '&#353;',
2061                 '&Yuml;' => '&#376;',
2062                 '&fnof;' => '&#402;',
2063                 '&circ;' => '&#710;',
2064                 '&tilde;' => '&#732;',
2065                 '&Alpha;' => '&#913;',
2066                 '&Beta;' => '&#914;',
2067                 '&Gamma;' => '&#915;',
2068                 '&Delta;' => '&#916;',
2069                 '&Epsilon;' => '&#917;',
2070                 '&Zeta;' => '&#918;',
2071                 '&Eta;' => '&#919;',
2072                 '&Theta;' => '&#920;',
2073                 '&Iota;' => '&#921;',
2074                 '&Kappa;' => '&#922;',
2075                 '&Lambda;' => '&#923;',
2076                 '&Mu;' => '&#924;',
2077                 '&Nu;' => '&#925;',
2078                 '&Xi;' => '&#926;',
2079                 '&Omicron;' => '&#927;',
2080                 '&Pi;' => '&#928;',
2081                 '&Rho;' => '&#929;',
2082                 '&Sigma;' => '&#931;',
2083                 '&Tau;' => '&#932;',
2084                 '&Upsilon;' => '&#933;',
2085                 '&Phi;' => '&#934;',
2086                 '&Chi;' => '&#935;',
2087                 '&Psi;' => '&#936;',
2088                 '&Omega;' => '&#937;',
2089                 '&alpha;' => '&#945;',
2090                 '&beta;' => '&#946;',
2091                 '&gamma;' => '&#947;',
2092                 '&delta;' => '&#948;',
2093                 '&epsilon;' => '&#949;',
2094                 '&zeta;' => '&#950;',
2095                 '&eta;' => '&#951;',
2096                 '&theta;' => '&#952;',
2097                 '&iota;' => '&#953;',
2098                 '&kappa;' => '&#954;',
2099                 '&lambda;' => '&#955;',
2100                 '&mu;' => '&#956;',
2101                 '&nu;' => '&#957;',
2102                 '&xi;' => '&#958;',
2103                 '&omicron;' => '&#959;',
2104                 '&pi;' => '&#960;',
2105                 '&rho;' => '&#961;',
2106                 '&sigmaf;' => '&#962;',
2107                 '&sigma;' => '&#963;',
2108                 '&tau;' => '&#964;',
2109                 '&upsilon;' => '&#965;',
2110                 '&phi;' => '&#966;',
2111                 '&chi;' => '&#967;',
2112                 '&psi;' => '&#968;',
2113                 '&omega;' => '&#969;',
2114                 '&thetasym;' => '&#977;',
2115                 '&upsih;' => '&#978;',
2116                 '&piv;' => '&#982;',
2117                 '&ensp;' => '&#8194;',
2118                 '&emsp;' => '&#8195;',
2119                 '&thinsp;' => '&#8201;',
2120                 '&zwnj;' => '&#8204;',
2121                 '&zwj;' => '&#8205;',
2122                 '&lrm;' => '&#8206;',
2123                 '&rlm;' => '&#8207;',
2124                 '&ndash;' => '&#8211;',
2125                 '&mdash;' => '&#8212;',
2126                 '&lsquo;' => '&#8216;',
2127                 '&rsquo;' => '&#8217;',
2128                 '&sbquo;' => '&#8218;',
2129                 '&ldquo;' => '&#8220;',
2130                 '&rdquo;' => '&#8221;',
2131                 '&bdquo;' => '&#8222;',
2132                 '&dagger;' => '&#8224;',
2133                 '&Dagger;' => '&#8225;',
2134                 '&bull;' => '&#8226;',
2135                 '&hellip;' => '&#8230;',
2136                 '&permil;' => '&#8240;',
2137                 '&prime;' => '&#8242;',
2138                 '&Prime;' => '&#8243;',
2139                 '&lsaquo;' => '&#8249;',
2140                 '&rsaquo;' => '&#8250;',
2141                 '&oline;' => '&#8254;',
2142                 '&frasl;' => '&#8260;',
2143                 '&euro;' => '&#8364;',
2144                 '&image;' => '&#8465;',
2145                 '&weierp;' => '&#8472;',
2146                 '&real;' => '&#8476;',
2147                 '&trade;' => '&#8482;',
2148                 '&alefsym;' => '&#8501;',
2149                 '&crarr;' => '&#8629;',
2150                 '&lArr;' => '&#8656;',
2151                 '&uArr;' => '&#8657;',
2152                 '&rArr;' => '&#8658;',
2153                 '&dArr;' => '&#8659;',
2154                 '&hArr;' => '&#8660;',
2155                 '&forall;' => '&#8704;',
2156                 '&part;' => '&#8706;',
2157                 '&exist;' => '&#8707;',
2158                 '&empty;' => '&#8709;',
2159                 '&nabla;' => '&#8711;',
2160                 '&isin;' => '&#8712;',
2161                 '&notin;' => '&#8713;',
2162                 '&ni;' => '&#8715;',
2163                 '&prod;' => '&#8719;',
2164                 '&sum;' => '&#8721;',
2165                 '&minus;' => '&#8722;',
2166                 '&lowast;' => '&#8727;',
2167                 '&radic;' => '&#8730;',
2168                 '&prop;' => '&#8733;',
2169                 '&infin;' => '&#8734;',
2170                 '&ang;' => '&#8736;',
2171                 '&and;' => '&#8743;',
2172                 '&or;' => '&#8744;',
2173                 '&cap;' => '&#8745;',
2174                 '&cup;' => '&#8746;',
2175                 '&int;' => '&#8747;',
2176                 '&there4;' => '&#8756;',
2177                 '&sim;' => '&#8764;',
2178                 '&cong;' => '&#8773;',
2179                 '&asymp;' => '&#8776;',
2180                 '&ne;' => '&#8800;',
2181                 '&equiv;' => '&#8801;',
2182                 '&le;' => '&#8804;',
2183                 '&ge;' => '&#8805;',
2184                 '&sub;' => '&#8834;',
2185                 '&sup;' => '&#8835;',
2186                 '&nsub;' => '&#8836;',
2187                 '&sube;' => '&#8838;',
2188                 '&supe;' => '&#8839;',
2189                 '&oplus;' => '&#8853;',
2190                 '&otimes;' => '&#8855;',
2191                 '&perp;' => '&#8869;',
2192                 '&sdot;' => '&#8901;',
2193                 '&lceil;' => '&#8968;',
2194                 '&rceil;' => '&#8969;',
2195                 '&lfloor;' => '&#8970;',
2196                 '&rfloor;' => '&#8971;',
2197                 '&lang;' => '&#9001;',
2198                 '&rang;' => '&#9002;',
2199                 '&larr;' => '&#8592;',
2200                 '&uarr;' => '&#8593;',
2201                 '&rarr;' => '&#8594;',
2202                 '&darr;' => '&#8595;',
2203                 '&harr;' => '&#8596;',
2204                 '&loz;' => '&#9674;',
2205                 '&spades;' => '&#9824;',
2206                 '&clubs;' => '&#9827;',
2207                 '&hearts;' => '&#9829;',
2208                 '&diams;' => '&#9830;'
2209         );
2210
2211         return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
2212 }
2213
2214 /**
2215  * Formats text for the rich text editor.
2216  *
2217  * The filter 'richedit_pre' is applied here. If $text is empty the filter will
2218  * be applied to an empty string.
2219  *
2220  * @since 2.0.0
2221  *
2222  * @param string $text The text to be formatted.
2223  * @return string The formatted text after filter is applied.
2224  */
2225 function wp_richedit_pre($text) {
2226         // Filtering a blank results in an annoying <br />\n
2227         if ( empty($text) ) return apply_filters('richedit_pre', '');
2228
2229         $output = convert_chars($text);
2230         $output = wpautop($output);
2231         $output = htmlspecialchars($output, ENT_NOQUOTES);
2232
2233         return apply_filters('richedit_pre', $output);
2234 }
2235
2236 /**
2237  * Formats text for the HTML editor.
2238  *
2239  * Unless $output is empty it will pass through htmlspecialchars before the
2240  * 'htmledit_pre' filter is applied.
2241  *
2242  * @since 2.5.0
2243  *
2244  * @param string $output The text to be formatted.
2245  * @return string Formatted text after filter applied.
2246  */
2247 function wp_htmledit_pre($output) {
2248         if ( !empty($output) )
2249                 $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > &
2250
2251         return apply_filters('htmledit_pre', $output);
2252 }
2253
2254 /**
2255  * Perform a deep string replace operation to ensure the values in $search are no longer present
2256  *
2257  * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
2258  * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
2259  * str_replace would return
2260  *
2261  * @since 2.8.1
2262  * @access private
2263  *
2264  * @param string|array $search
2265  * @param string $subject
2266  * @return string The processed string
2267  */
2268 function _deep_replace( $search, $subject ) {
2269         $found = true;
2270         $subject = (string) $subject;
2271         while ( $found ) {
2272                 $found = false;
2273                 foreach ( (array) $search as $val ) {
2274                         while ( strpos( $subject, $val ) !== false ) {
2275                                 $found = true;
2276                                 $subject = str_replace( $val, '', $subject );
2277                         }
2278                 }
2279         }
2280
2281         return $subject;
2282 }
2283
2284 /**
2285  * Escapes data for use in a MySQL query
2286  *
2287  * This is just a handy shortcut for $wpdb->escape(), for completeness' sake
2288  *
2289  * @since 2.8.0
2290  * @param string $sql Unescaped SQL data
2291  * @return string The cleaned $sql
2292  */
2293 function esc_sql( $sql ) {
2294         global $wpdb;
2295         return $wpdb->escape( $sql );
2296 }
2297
2298 /**
2299  * Checks and cleans a URL.
2300  *
2301  * A number of characters are removed from the URL. If the URL is for displaying
2302  * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
2303  * is applied to the returned cleaned URL.
2304  *
2305  * @since 2.8.0
2306  * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
2307  *              via $protocols or the common ones set in the function.
2308  *
2309  * @param string $url The URL to be cleaned.
2310  * @param array $protocols Optional. An array of acceptable protocols.
2311  *              Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
2312  * @param string $_context Private. Use esc_url_raw() for database usage.
2313  * @return string The cleaned $url after the 'clean_url' filter is applied.
2314  */
2315 function esc_url( $url, $protocols = null, $_context = 'display' ) {
2316         $original_url = $url;
2317
2318         if ( '' == $url )
2319                 return $url;
2320         $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
2321         $strip = array('%0d', '%0a', '%0D', '%0A');
2322         $url = _deep_replace($strip, $url);
2323         $url = str_replace(';//', '://', $url);
2324         /* If the URL doesn't appear to contain a scheme, we
2325          * presume it needs http:// appended (unless a relative
2326          * link starting with /, # or ? or a php file).
2327          */
2328         if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
2329                 ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
2330                 $url = 'http://' . $url;
2331
2332         // Replace ampersands and single quotes only when displaying.
2333         if ( 'display' == $_context ) {
2334                 $url = wp_kses_normalize_entities( $url );
2335                 $url = str_replace( '&amp;', '&#038;', $url );
2336                 $url = str_replace( "'", '&#039;', $url );
2337         }
2338
2339         if ( ! is_array( $protocols ) )
2340                 $protocols = wp_allowed_protocols();
2341         if ( wp_kses_bad_protocol( $url, $protocols ) != $url )
2342                 return '';
2343
2344         return apply_filters('clean_url', $url, $original_url, $_context);
2345 }
2346
2347 /**
2348  * Performs esc_url() for database usage.
2349  *
2350  * @since 2.8.0
2351  * @uses esc_url()
2352  *
2353  * @param string $url The URL to be cleaned.
2354  * @param array $protocols An array of acceptable protocols.
2355  * @return string The cleaned URL.
2356  */
2357 function esc_url_raw( $url, $protocols = null ) {
2358         return esc_url( $url, $protocols, 'db' );
2359 }
2360
2361 /**
2362  * Convert entities, while preserving already-encoded entities.
2363  *
2364  * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
2365  *
2366  * @since 1.2.2
2367  *
2368  * @param string $myHTML The text to be converted.
2369  * @return string Converted text.
2370  */
2371 function htmlentities2($myHTML) {
2372         $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
2373         $translation_table[chr(38)] = '&';
2374         return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
2375 }
2376
2377 /**
2378  * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
2379  *
2380  * Escapes text strings for echoing in JS. It is intended to be used for inline JS
2381  * (in a tag attribute, for example onclick="..."). Note that the strings have to
2382  * be in single quotes. The filter 'js_escape' is also applied here.
2383  *
2384  * @since 2.8.0
2385  *
2386  * @param string $text The text to be escaped.
2387  * @return string Escaped text.
2388  */
2389 function esc_js( $text ) {
2390         $safe_text = wp_check_invalid_utf8( $text );
2391         $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
2392         $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
2393         $safe_text = str_replace( "\r", '', $safe_text );
2394         $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
2395         return apply_filters( 'js_escape', $safe_text, $text );
2396 }
2397
2398 /**
2399  * Escaping for HTML blocks.
2400  *
2401  * @since 2.8.0
2402  *
2403  * @param string $text
2404  * @return string
2405  */
2406 function esc_html( $text ) {
2407         $safe_text = wp_check_invalid_utf8( $text );
2408         $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2409         return apply_filters( 'esc_html', $safe_text, $text );
2410 }
2411
2412 /**
2413  * Escaping for HTML attributes.
2414  *
2415  * @since 2.8.0
2416  *
2417  * @param string $text
2418  * @return string
2419  */
2420 function esc_attr( $text ) {
2421         $safe_text = wp_check_invalid_utf8( $text );
2422         $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
2423         return apply_filters( 'attribute_escape', $safe_text, $text );
2424 }
2425
2426 /**
2427  * Escaping for textarea values.
2428  *
2429  * @since 3.1
2430  *
2431  * @param string $text
2432  * @return string
2433  */
2434 function esc_textarea( $text ) {
2435         $safe_text = htmlspecialchars( $text, ENT_QUOTES );
2436         return apply_filters( 'esc_textarea', $safe_text, $text );
2437 }
2438
2439 /**
2440  * Escape a HTML tag name.
2441  *
2442  * @since 2.5.0
2443  *
2444  * @param string $tag_name
2445  * @return string
2446  */
2447 function tag_escape($tag_name) {
2448         $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
2449         return apply_filters('tag_escape', $safe_tag, $tag_name);
2450 }
2451
2452 /**
2453  * Escapes text for SQL LIKE special characters % and _.
2454  *
2455  * @since 2.5.0
2456  *
2457  * @param string $text The text to be escaped.
2458  * @return string text, safe for inclusion in LIKE query.
2459  */
2460 function like_escape($text) {
2461         return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
2462 }
2463
2464 /**
2465  * Convert full URL paths to absolute paths.
2466  *
2467  * Removes the http or https protocols and the domain. Keeps the path '/' at the
2468  * beginning, so it isn't a true relative link, but from the web root base.
2469  *
2470  * @since 2.1.0
2471  *
2472  * @param string $link Full URL path.
2473  * @return string Absolute path.
2474  */
2475 function wp_make_link_relative( $link ) {
2476         return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
2477 }
2478
2479 /**
2480  * Sanitises various option values based on the nature of the option.
2481  *
2482  * This is basically a switch statement which will pass $value through a number
2483  * of functions depending on the $option.
2484  *
2485  * @since 2.0.5
2486  *
2487  * @param string $option The name of the option.
2488  * @param string $value The unsanitised value.
2489  * @return string Sanitized value.
2490  */
2491 function sanitize_option($option, $value) {
2492
2493         switch ( $option ) {
2494                 case 'admin_email':
2495                         $value = sanitize_email($value);
2496                         if ( !is_email($value) ) {
2497                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2498                                 if ( function_exists('add_settings_error') )
2499                                         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.'));
2500                         }
2501                         break;
2502
2503                 case 'new_admin_email':
2504                         $value = sanitize_email($value);
2505                         if ( !is_email($value) ) {
2506                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2507                                 if ( function_exists('add_settings_error') )
2508                                         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.'));
2509                         }
2510                         break;
2511
2512                 case 'thumbnail_size_w':
2513                 case 'thumbnail_size_h':
2514                 case 'medium_size_w':
2515                 case 'medium_size_h':
2516                 case 'large_size_w':
2517                 case 'large_size_h':
2518                 case 'embed_size_h':
2519                 case 'default_post_edit_rows':
2520                 case 'mailserver_port':
2521                 case 'comment_max_links':
2522                 case 'page_on_front':
2523                 case 'page_for_posts':
2524                 case 'rss_excerpt_length':
2525                 case 'default_category':
2526                 case 'default_email_category':
2527                 case 'default_link_category':
2528                 case 'close_comments_days_old':
2529                 case 'comments_per_page':
2530                 case 'thread_comments_depth':
2531                 case 'users_can_register':
2532                 case 'start_of_week':
2533                         $value = absint( $value );
2534                         break;
2535
2536                 case 'embed_size_w':
2537                         if ( '' !== $value )
2538                                 $value = absint( $value );
2539                         break;
2540
2541                 case 'posts_per_page':
2542                 case 'posts_per_rss':
2543                         $value = (int) $value;
2544                         if ( empty($value) )
2545                                 $value = 1;
2546                         if ( $value < -1 )
2547                                 $value = abs($value);
2548                         break;
2549
2550                 case 'default_ping_status':
2551                 case 'default_comment_status':
2552                         // Options that if not there have 0 value but need to be something like "closed"
2553                         if ( $value == '0' || $value == '')
2554                                 $value = 'closed';
2555                         break;
2556
2557                 case 'blogdescription':
2558                 case 'blogname':
2559                         $value = addslashes($value);
2560                         $value = wp_filter_post_kses( $value ); // calls stripslashes then addslashes
2561                         $value = stripslashes($value);
2562                         $value = esc_html( $value );
2563                         break;
2564
2565                 case 'blog_charset':
2566                         $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
2567                         break;
2568
2569                 case 'date_format':
2570                 case 'time_format':
2571                 case 'mailserver_url':
2572                 case 'mailserver_login':
2573                 case 'mailserver_pass':
2574                 case 'ping_sites':
2575                 case 'upload_path':
2576                         $value = strip_tags($value);
2577                         $value = addslashes($value);
2578                         $value = wp_filter_kses($value); // calls stripslashes then addslashes
2579                         $value = stripslashes($value);
2580                         break;
2581
2582                 case 'gmt_offset':
2583                         $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
2584                         break;
2585
2586                 case 'siteurl':
2587                         if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2588                                 $value = esc_url_raw($value);
2589                         } else {
2590                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2591                                 if ( function_exists('add_settings_error') )
2592                                         add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2593                         }
2594                         break;
2595
2596                 case 'home':
2597                         if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
2598                                 $value = esc_url_raw($value);
2599                         } else {
2600                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2601                                 if ( function_exists('add_settings_error') )
2602                                         add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
2603                         }
2604                         break;
2605
2606                 case 'WPLANG':
2607                         $allowed = get_available_languages();
2608                         if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
2609                                 $value = get_option( $option );
2610                         break;
2611
2612                 case 'timezone_string':
2613                         $allowed_zones = timezone_identifiers_list();
2614                         if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
2615                                 $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
2616                                 if ( function_exists('add_settings_error') )
2617                                         add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
2618                         }
2619                         break;
2620
2621                 case 'permalink_structure':
2622                 case 'category_base':
2623                 case 'tag_base':
2624                         $value = esc_url_raw( $value );
2625                         $value = str_replace( 'http://', '', $value );
2626                         break;
2627         }
2628
2629         $value = apply_filters("sanitize_option_{$option}", $value, $option);
2630
2631         return $value;
2632 }
2633
2634 /**
2635  * Parses a string into variables to be stored in an array.
2636  *
2637  * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
2638  * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
2639  *
2640  * @since 2.2.1
2641  * @uses apply_filters() for the 'wp_parse_str' filter.
2642  *
2643  * @param string $string The string to be parsed.
2644  * @param array $array Variables will be stored in this array.
2645  */
2646 function wp_parse_str( $string, &$array ) {
2647         parse_str( $string, $array );
2648         if ( get_magic_quotes_gpc() )
2649                 $array = stripslashes_deep( $array );
2650         $array = apply_filters( 'wp_parse_str', $array );
2651 }
2652
2653 /**
2654  * Convert lone less than signs.
2655  *
2656  * KSES already converts lone greater than signs.
2657  *
2658  * @uses wp_pre_kses_less_than_callback in the callback function.
2659  * @since 2.3.0
2660  *
2661  * @param string $text Text to be converted.
2662  * @return string Converted text.
2663  */
2664 function wp_pre_kses_less_than( $text ) {
2665         return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
2666 }
2667
2668 /**
2669  * Callback function used by preg_replace.
2670  *
2671  * @uses esc_html to format the $matches text.
2672  * @since 2.3.0
2673  *
2674  * @param array $matches Populated by matches to preg_replace.
2675  * @return string The text returned after esc_html if needed.
2676  */
2677 function wp_pre_kses_less_than_callback( $matches ) {
2678         if ( false === strpos($matches[0], '>') )
2679                 return esc_html($matches[0]);
2680         return $matches[0];
2681 }
2682
2683 /**
2684  * WordPress implementation of PHP sprintf() with filters.
2685  *
2686  * @since 2.5.0
2687  * @link http://www.php.net/sprintf
2688  *
2689  * @param string $pattern The string which formatted args are inserted.
2690  * @param mixed $args,... Arguments to be formatted into the $pattern string.
2691  * @return string The formatted string.
2692  */
2693 function wp_sprintf( $pattern ) {
2694         $args = func_get_args( );
2695         $len = strlen($pattern);
2696         $start = 0;
2697         $result = '';
2698         $arg_index = 0;
2699         while ( $len > $start ) {
2700                 // Last character: append and break
2701                 if ( strlen($pattern) - 1 == $start ) {
2702                         $result .= substr($pattern, -1);
2703                         break;
2704                 }
2705
2706                 // Literal %: append and continue
2707                 if ( substr($pattern, $start, 2) == '%%' ) {
2708                         $start += 2;
2709                         $result .= '%';
2710                         continue;
2711                 }
2712
2713                 // Get fragment before next %
2714                 $end = strpos($pattern, '%', $start + 1);
2715                 if ( false === $end )
2716                         $end = $len;
2717                 $fragment = substr($pattern, $start, $end - $start);
2718
2719                 // Fragment has a specifier
2720                 if ( $pattern[$start] == '%' ) {
2721                         // Find numbered arguments or take the next one in order
2722                         if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
2723                                 $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
2724                                 $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
2725                         } else {
2726                                 ++$arg_index;
2727                                 $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
2728                         }
2729
2730                         // Apply filters OR sprintf
2731                         $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
2732                         if ( $_fragment != $fragment )
2733                                 $fragment = $_fragment;
2734                         else
2735                                 $fragment = sprintf($fragment, strval($arg) );
2736                 }
2737
2738                 // Append to result and move to next fragment
2739                 $result .= $fragment;
2740                 $start = $end;
2741         }
2742         return $result;
2743 }
2744
2745 /**
2746  * Localize list items before the rest of the content.
2747  *
2748  * The '%l' must be at the first characters can then contain the rest of the
2749  * content. The list items will have ', ', ', and', and ' and ' added depending
2750  * on the amount of list items in the $args parameter.
2751  *
2752  * @since 2.5.0
2753  *
2754  * @param string $pattern Content containing '%l' at the beginning.
2755  * @param array $args List items to prepend to the content and replace '%l'.
2756  * @return string Localized list items and rest of the content.
2757  */
2758 function wp_sprintf_l($pattern, $args) {
2759         // Not a match
2760         if ( substr($pattern, 0, 2) != '%l' )
2761                 return $pattern;
2762
2763         // Nothing to work with
2764         if ( empty($args) )
2765                 return '';
2766
2767         // Translate and filter the delimiter set (avoid ampersands and entities here)
2768         $l = apply_filters('wp_sprintf_l', array(
2769                 /* translators: used between list items, there is a space after the comma */
2770                 'between'          => __(', '),
2771                 /* translators: used between list items, there is a space after the and */
2772                 'between_last_two' => __(', and '),
2773                 /* translators: used between only two list items, there is a space after the and */
2774                 'between_only_two' => __(' and '),
2775                 ));
2776
2777         $args = (array) $args;
2778         $result = array_shift($args);
2779         if ( count($args) == 1 )
2780                 $result .= $l['between_only_two'] . array_shift($args);
2781         // Loop when more than two args
2782         $i = count($args);
2783         while ( $i ) {
2784                 $arg = array_shift($args);
2785                 $i--;
2786                 if ( 0 == $i )
2787                         $result .= $l['between_last_two'] . $arg;
2788                 else
2789                         $result .= $l['between'] . $arg;
2790         }
2791         return $result . substr($pattern, 2);
2792 }
2793
2794 /**
2795  * Safely extracts not more than the first $count characters from html string.
2796  *
2797  * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
2798  * be counted as one character. For example &amp; will be counted as 4, &lt; as
2799  * 3, etc.
2800  *
2801  * @since 2.5.0
2802  *
2803  * @param integer $str String to get the excerpt from.
2804  * @param integer $count Maximum number of characters to take.
2805  * @return string The excerpt.
2806  */
2807 function wp_html_excerpt( $str, $count ) {
2808         $str = wp_strip_all_tags( $str, true );
2809         $str = mb_substr( $str, 0, $count );
2810         // remove part of an entity at the end
2811         $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str );
2812         return $str;
2813 }
2814
2815 /**
2816  * Add a Base url to relative links in passed content.
2817  *
2818  * By default it supports the 'src' and 'href' attributes. However this can be
2819  * changed via the 3rd param.
2820  *
2821  * @since 2.7.0
2822  *
2823  * @param string $content String to search for links in.
2824  * @param string $base The base URL to prefix to links.
2825  * @param array $attrs The attributes which should be processed.
2826  * @return string The processed content.
2827  */
2828 function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
2829         global $_links_add_base;
2830         $_links_add_base = $base;
2831         $attrs = implode('|', (array)$attrs);
2832         return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
2833 }
2834
2835 /**
2836  * Callback to add a base url to relative links in passed content.
2837  *
2838  * @since 2.7.0
2839  * @access private
2840  *
2841  * @param string $m The matched link.
2842  * @return string The processed link.
2843  */
2844 function _links_add_base($m) {
2845         global $_links_add_base;
2846         //1 = attribute name  2 = quotation mark  3 = URL
2847         return $m[1] . '=' . $m[2] .
2848                 (strpos($m[3], 'http://') === false ?
2849                         path_join($_links_add_base, $m[3]) :
2850                         $m[3])
2851                 . $m[2];
2852 }
2853
2854 /**
2855  * Adds a Target attribute to all links in passed content.
2856  *
2857  * This function by default only applies to <a> tags, however this can be
2858  * modified by the 3rd param.
2859  *
2860  * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
2861  *
2862  * @since 2.7.0
2863  *
2864  * @param string $content String to search for links in.
2865  * @param string $target The Target to add to the links.
2866  * @param array $tags An array of tags to apply to.
2867  * @return string The processed content.
2868  */
2869 function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
2870         global $_links_add_target;
2871         $_links_add_target = $target;
2872         $tags = implode('|', (array)$tags);
2873         return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content );
2874 }
2875
2876 /**
2877  * Callback to add a target attribute to all links in passed content.
2878  *
2879  * @since 2.7.0
2880  * @access private
2881  *
2882  * @param string $m The matched link.
2883  * @return string The processed link.
2884  */
2885 function _links_add_target( $m ) {
2886         global $_links_add_target;
2887         $tag = $m[1];
2888         $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]);
2889         return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
2890 }
2891
2892 // normalize EOL characters and strip duplicate whitespace
2893 function normalize_whitespace( $str ) {
2894         $str  = trim($str);
2895         $str  = str_replace("\r", "\n", $str);
2896         $str  = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
2897         return $str;
2898 }
2899
2900 /**
2901  * Properly strip all HTML tags including script and style
2902  *
2903  * @since 2.9.0
2904  *
2905  * @param string $string String containing HTML tags
2906  * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
2907  * @return string The processed string.
2908  */
2909 function wp_strip_all_tags($string, $remove_breaks = false) {
2910         $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
2911         $string = strip_tags($string);
2912
2913         if ( $remove_breaks )
2914                 $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
2915
2916         return trim($string);
2917 }
2918
2919 /**
2920  * Sanitize a string from user input or from the db
2921  *
2922  * check for invalid UTF-8,
2923  * Convert single < characters to entity,
2924  * strip all tags,
2925  * remove line breaks, tabs and extra white space,
2926  * strip octets.
2927  *
2928  * @since 2.9.0
2929  *
2930  * @param string $str
2931  * @return string
2932  */
2933 function sanitize_text_field($str) {
2934         $filtered = wp_check_invalid_utf8( $str );
2935
2936         if ( strpos($filtered, '<') !== false ) {
2937                 $filtered = wp_pre_kses_less_than( $filtered );
2938                 // This will strip extra whitespace for us.
2939                 $filtered = wp_strip_all_tags( $filtered, true );
2940         } else {
2941                 $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
2942         }
2943
2944         $match = array();
2945         $found = false;
2946         while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
2947                 $filtered = str_replace($match[0], '', $filtered);
2948                 $found = true;
2949         }
2950
2951         if ( $found ) {
2952                 // Strip out the whitespace that may now exist after removing the octets.
2953                 $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
2954         }
2955
2956         return apply_filters('sanitize_text_field', $filtered, $str);
2957 }
2958
2959 /**
2960  * i18n friendly version of basename()
2961  *
2962  * @since 3.1.0
2963  *
2964  * @param string $path A path.
2965  * @param string $suffix If the filename ends in suffix this will also be cut off.
2966  * @return string
2967  */
2968 function wp_basename( $path, $suffix = '' ) {
2969         return urldecode( basename( str_replace( '%2F', '/', urlencode( $path ) ), $suffix ) );
2970 }
2971
2972 /**
2973  * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
2974  *
2975  * Violating our coding standards for a good function name.
2976  *
2977  * @since 3.0.0
2978  */
2979 function capital_P_dangit( $text ) {
2980         // Simple replacement for titles
2981         if ( 'the_title' === current_filter() )
2982                 return str_replace( 'Wordpress', 'WordPress', $text );
2983         // Still here? Use the more judicious replacement
2984         static $dblq = false;
2985         if ( false === $dblq )
2986                 $dblq = _x('&#8220;', 'opening curly quote');
2987         return str_replace(
2988                 array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
2989                 array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
2990         $text );
2991
2992 }
2993
2994 /**
2995  * Sanitize a mime type
2996  *
2997  * @since 3.1.3
2998  *
2999  * @param string $mime_type Mime type
3000  * @return string Sanitized mime type
3001  */
3002 function sanitize_mime_type( $mime_type ) {
3003         $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
3004         return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
3005 }
3006
3007 ?>