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