/source/mydroid/external/webkit/WebKitSite/blog/wp-includes/formatting.php

https://bitbucket.org/thejeshgn/kindle-fire · PHP · 2679 lines · 1591 code · 205 blank · 883 comment · 208 complexity · 004286e364dd12eebb41c7bbb48b0da1 MD5 · raw file

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