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