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