Make WordPress Core

Ticket #9994: formatting.3.php

File formatting.3.php, 80.9 KB (added by ryan, 17 years ago)

formatting.php minus 11345

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