Make WordPress Core

Ticket #9994: formatting.php

File formatting.php, 77.8 KB (added by kamiyeye, 17 years ago)

early version from a nightly build

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