PageRenderTime 34ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/wordpress/wp-includes/formatting.php

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