PageRenderTime 72ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/formatting.php

https://github.com/schr/wordpress
PHP | 2347 lines | 1338 code | 178 blank | 831 comment | 193 complexity | 360d088416a808a34cc6e747bab7abdd MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Main Wordpress Formatting API.
  4. *
  5. * Handles many functions for formatting output.
  6. *
  7. * @package WordPress
  8. **/
  9. /**
  10. * Replaces common plain text characters into formatted entities
  11. *
  12. * As an example,
  13. * <code>
  14. * 'cause today's effort makes it worth tomorrow's "holiday"...
  15. * </code>
  16. * Becomes:
  17. * <code>
  18. * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221;&#8230;
  19. * </code>
  20. * Code within certain html blocks are skipped.
  21. *
  22. * @since 0.71
  23. * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases
  24. *
  25. * @param string $text The text to be formatted
  26. * @return string The string replaced with html entities
  27. */
  28. function wptexturize($text) {
  29. global $wp_cockneyreplace;
  30. $next = true;
  31. $has_pre_parent = false;
  32. $output = '';
  33. $curl = '';
  34. $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  35. $stop = count($textarr);
  36. // if a plugin has provided an autocorrect array, use it
  37. if ( isset($wp_cockneyreplace) ) {
  38. $cockney = array_keys($wp_cockneyreplace);
  39. $cockneyreplace = array_values($wp_cockneyreplace);
  40. } else {
  41. $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
  42. $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
  43. }
  44. $static_characters = array_merge(array('---', ' -- ', '--', 'xn&#8211;', '...', '``', '\'s', '\'\'', ' (tm)'), $cockney);
  45. $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', 'xn--', '&#8230;', '&#8220;', '&#8217;s', '&#8221;', ' &#8482;'), $cockneyreplace);
  46. $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/(\s|\A|")\'/', '/(\d+)"/', '/(\d+)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A)"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/(\d+)x(\d+)/');
  47. $dynamic_replacements = array('&#8217;$1','$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1&#8220;$2', '&#8221;$1', '&#8217;$1', '$1&#215;$2');
  48. for ( $i = 0; $i < $stop; $i++ ) {
  49. $curl = $textarr[$i];
  50. if ( !empty($curl) && '<' != $curl{0} && '[' != $curl{0} && $next && !$has_pre_parent) { // If it's not a tag
  51. // static strings
  52. $curl = str_replace($static_characters, $static_replacements, $curl);
  53. // regular expressions
  54. $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
  55. } elseif (strpos($curl, '<code') !== false || strpos($curl, '<kbd') !== false || strpos($curl, '<style') !== false || strpos($curl, '<script') !== false) {
  56. $next = false;
  57. } elseif (strpos($curl, '<pre') !== false) {
  58. $has_pre_parent = true;
  59. } elseif (strpos($curl, '</pre>') !== false) {
  60. $has_pre_parent = false;
  61. } else {
  62. $next = true;
  63. }
  64. $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
  65. $output .= $curl;
  66. }
  67. return $output;
  68. }
  69. /**
  70. * Accepts matches array from preg_replace_callback in wpautop() or a string.
  71. *
  72. * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
  73. * converted into paragraphs or line-breaks.
  74. *
  75. * @since 1.2.0
  76. *
  77. * @param array|string $matches The array or string
  78. * @return string The pre block without paragraph/line-break conversion.
  79. */
  80. function clean_pre($matches) {
  81. if ( is_array($matches) )
  82. $text = $matches[1] . $matches[2] . "</pre>";
  83. else
  84. $text = $matches;
  85. $text = str_replace('<br />', '', $text);
  86. $text = str_replace('<p>', "\n", $text);
  87. $text = str_replace('</p>', '', $text);
  88. return $text;
  89. }
  90. /**
  91. * Replaces double line-breaks with paragraph elements.
  92. *
  93. * A group of regex replaces used to identify text formatted with newlines and
  94. * replace double line-breaks with HTML paragraph tags. The remaining
  95. * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
  96. * or 'false'.
  97. *
  98. * @since 0.71
  99. *
  100. * @param string $pee The text which has to be formatted.
  101. * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
  102. * @return string Text which has been converted into correct paragraph tags.
  103. */
  104. function wpautop($pee, $br = 1) {
  105. $pee = $pee . "\n"; // just to make things a little easier, pad the end
  106. $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
  107. // Space things out a little
  108. $allblocks = '(?:table|thead|tfoot|caption|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)';
  109. $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
  110. $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
  111. $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
  112. if ( strpos($pee, '<object') !== false ) {
  113. $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
  114. $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
  115. }
  116. $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
  117. // make paragraphs, including one at the end
  118. $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
  119. $pee = '';
  120. foreach ( $pees as $tinkle )
  121. $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
  122. $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
  123. $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
  124. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
  125. $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
  126. $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
  127. $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
  128. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
  129. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
  130. if ($br) {
  131. $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', create_function('$matches', 'return str_replace("\n", "<WPPreserveNewline />", $matches[0]);'), $pee);
  132. $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
  133. $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
  134. }
  135. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
  136. $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
  137. if (strpos($pee, '<pre') !== false)
  138. $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
  139. $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
  140. $pee = preg_replace('/<p>\s*?(' . get_shortcode_regex() . ')\s*<\/p>/s', '$1', $pee); // don't auto-p wrap shortcodes that stand alone
  141. return $pee;
  142. }
  143. /**
  144. * Checks to see if a string is utf8 encoded.
  145. *
  146. * @author bmorel at ssi dot fr
  147. *
  148. * @since 1.2.1
  149. *
  150. * @param string $Str The string to be checked
  151. * @return bool True if $Str fits a UTF-8 model, false otherwise.
  152. */
  153. function seems_utf8($Str) { # by bmorel at ssi dot fr
  154. $length = strlen($Str);
  155. for ($i=0; $i < $length; $i++) {
  156. if (ord($Str[$i]) < 0x80) continue; # 0bbbbbbb
  157. elseif ((ord($Str[$i]) & 0xE0) == 0xC0) $n=1; # 110bbbbb
  158. elseif ((ord($Str[$i]) & 0xF0) == 0xE0) $n=2; # 1110bbbb
  159. elseif ((ord($Str[$i]) & 0xF8) == 0xF0) $n=3; # 11110bbb
  160. elseif ((ord($Str[$i]) & 0xFC) == 0xF8) $n=4; # 111110bb
  161. elseif ((ord($Str[$i]) & 0xFE) == 0xFC) $n=5; # 1111110b
  162. else return false; # Does not match any model
  163. for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
  164. if ((++$i == $length) || ((ord($Str[$i]) & 0xC0) != 0x80))
  165. return false;
  166. }
  167. }
  168. return true;
  169. }
  170. /**
  171. * Converts a number of special characters into their HTML entities.
  172. *
  173. * Specifically deals with: &, <, >, ", and '.
  174. *
  175. * $quote_style can be set to ENT_COMPAT to encode " to
  176. * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
  177. *
  178. * @since 1.2.2
  179. *
  180. * @param string $string The text which is to be encoded.
  181. * @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.
  182. * @param string $charset Optional. The character encoding of the string. Default is false.
  183. * @param boolean $double_encode Optional. Whether or not to encode existing html entities. Default is false.
  184. * @return string The encoded text with HTML entities.
  185. */
  186. function wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false )
  187. {
  188. $string = (string) $string;
  189. if ( 0 === strlen( $string ) ) {
  190. return '';
  191. }
  192. // Don't bother if there are no specialchars - saves some processing
  193. if ( !preg_match( '/[&<>"\']/', $string ) ) {
  194. return $string;
  195. }
  196. // Account for the previous behaviour of the function when the $quote_style is not an accepted value
  197. if ( empty( $quote_style ) ) {
  198. $quote_style = ENT_NOQUOTES;
  199. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  200. $quote_style = ENT_QUOTES;
  201. }
  202. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
  203. if ( !$charset ) {
  204. static $_charset;
  205. if ( !isset( $_charset ) ) {
  206. $alloptions = wp_load_alloptions();
  207. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  208. }
  209. $charset = $_charset;
  210. }
  211. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
  212. $charset = 'UTF-8';
  213. }
  214. $_quote_style = $quote_style;
  215. if ( $quote_style === 'double' ) {
  216. $quote_style = ENT_COMPAT;
  217. $_quote_style = ENT_COMPAT;
  218. } elseif ( $quote_style === 'single' ) {
  219. $quote_style = ENT_NOQUOTES;
  220. }
  221. // Handle double encoding ourselves
  222. if ( !$double_encode ) {
  223. $string = wp_specialchars_decode( $string, $_quote_style );
  224. $string = preg_replace( '/&(#?x?[0-9]+|[a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
  225. }
  226. $string = @htmlspecialchars( $string, $quote_style, $charset );
  227. // Handle double encoding ourselves
  228. if ( !$double_encode ) {
  229. $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
  230. }
  231. // Backwards compatibility
  232. if ( 'single' === $_quote_style ) {
  233. $string = str_replace( "'", '&#039;', $string );
  234. }
  235. return $string;
  236. }
  237. /**
  238. * Converts a number of HTML entities into their special characters.
  239. *
  240. * Specifically deals with: &, <, >, ", and '.
  241. *
  242. * $quote_style can be set to ENT_COMPAT to decode " entities,
  243. * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
  244. *
  245. * @since 2.8
  246. *
  247. * @param string $string The text which is to be decoded.
  248. * @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.
  249. * @return string The decoded text without HTML entities.
  250. */
  251. function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES )
  252. {
  253. $string = (string) $string;
  254. if ( 0 === strlen( $string ) ) {
  255. return '';
  256. }
  257. // Don't bother if there are no entities - saves a lot of processing
  258. if ( strpos( $string, '&' ) === false ) {
  259. return $string;
  260. }
  261. // Match the previous behaviour of wp_specialchars() when the $quote_style is not an accepted value
  262. if ( empty( $quote_style ) ) {
  263. $quote_style = ENT_NOQUOTES;
  264. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  265. $quote_style = ENT_QUOTES;
  266. }
  267. // More complete than get_html_translation_table( HTML_SPECIALCHARS )
  268. $single = array( '&#039;' => '\'', '&#x27;' => '\'' );
  269. $single_preg = array( '/&#0*39;/' => '&#039;', '/&#x0*27;/i' => '&#x27;' );
  270. $double = array( '&quot;' => '"', '&#034;' => '"', '&#x22;' => '"' );
  271. $double_preg = array( '/&#0*34;/' => '&#034;', '/&#x0*22;/i' => '&#x22;' );
  272. $others = array( '&lt;' => '<', '&#060;' => '<', '&gt;' => '>', '&#062;' => '>', '&amp;' => '&', '&#038;' => '&', '&#x26;' => '&' );
  273. $others_preg = array( '/&#0*60;/' => '&#060;', '/&#0*62;/' => '&#062;', '/&#0*38;/' => '&#038;', '/&#x0*26;/i' => '&#x26;' );
  274. if ( $quote_style === ENT_QUOTES ) {
  275. $translation = array_merge( $single, $double, $others );
  276. $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
  277. } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
  278. $translation = array_merge( $double, $others );
  279. $translation_preg = array_merge( $double_preg, $others_preg );
  280. } elseif ( $quote_style === 'single' ) {
  281. $translation = array_merge( $single, $others );
  282. $translation_preg = array_merge( $single_preg, $others_preg );
  283. } elseif ( $quote_style === ENT_NOQUOTES ) {
  284. $translation = $others;
  285. $translation_preg = $others_preg;
  286. }
  287. // Remove zero padding on numeric entities
  288. $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
  289. // Replace characters according to translation table
  290. return strtr( $string, $translation );
  291. }
  292. /**
  293. * Checks for invalid UTF8 in a string.
  294. *
  295. * @since 2.8
  296. *
  297. * @param string $string The text which is to be checked.
  298. * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
  299. * @return string The checked text.
  300. */
  301. function wp_check_invalid_utf8( $string, $strip = false )
  302. {
  303. $string = (string) $string;
  304. if ( 0 === strlen( $string ) ) {
  305. return '';
  306. }
  307. // Store the site charset as a static to avoid multiple calls to get_option()
  308. static $is_utf8;
  309. if ( !isset( $is_utf8 ) ) {
  310. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
  311. }
  312. if ( !$is_utf8 ) {
  313. return $string;
  314. }
  315. // Check for support for utf8 in the installed PCRE library once and store the result in a static
  316. static $utf8_pcre;
  317. if ( !isset( $utf8_pcre ) ) {
  318. $utf8_pcre = @preg_match( '/^./u', 'a' );
  319. }
  320. // We can't demand utf8 in the PCRE installation, so just return the string in those cases
  321. if ( !$utf8_pcre ) {
  322. return $string;
  323. }
  324. // preg_match fails when it encounters invalid UTF8 in $string
  325. if ( 1 === @preg_match( '/^./us', $string ) ) {
  326. return $string;
  327. }
  328. // Attempt to strip the bad chars if requested (not recommended)
  329. if ( $strip && function_exists( 'iconv' ) ) {
  330. return iconv( 'utf-8', 'utf-8', $string );
  331. }
  332. return '';
  333. }
  334. /**
  335. * Encode the Unicode values to be used in the URI.
  336. *
  337. * @since 1.5.0
  338. *
  339. * @param string $utf8_string
  340. * @param int $length Max length of the string
  341. * @return string String with Unicode encoded for URI.
  342. */
  343. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  344. $unicode = '';
  345. $values = array();
  346. $num_octets = 1;
  347. $unicode_length = 0;
  348. $string_length = strlen( $utf8_string );
  349. for ($i = 0; $i < $string_length; $i++ ) {
  350. $value = ord( $utf8_string[ $i ] );
  351. if ( $value < 128 ) {
  352. if ( $length && ( $unicode_length >= $length ) )
  353. break;
  354. $unicode .= chr($value);
  355. $unicode_length++;
  356. } else {
  357. if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
  358. $values[] = $value;
  359. if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
  360. break;
  361. if ( count( $values ) == $num_octets ) {
  362. if ($num_octets == 3) {
  363. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
  364. $unicode_length += 9;
  365. } else {
  366. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
  367. $unicode_length += 6;
  368. }
  369. $values = array();
  370. $num_octets = 1;
  371. }
  372. }
  373. }
  374. return $unicode;
  375. }
  376. /**
  377. * Converts all accent characters to ASCII characters.
  378. *
  379. * If there are no accent characters, then the string given is just returned.
  380. *
  381. * @since 1.2.1
  382. *
  383. * @param string $string Text that might have accent characters
  384. * @return string Filtered string with replaced "nice" characters.
  385. */
  386. function remove_accents($string) {
  387. if ( !preg_match('/[\x80-\xff]/', $string) )
  388. return $string;
  389. if (seems_utf8($string)) {
  390. $chars = array(
  391. // Decompositions for Latin-1 Supplement
  392. chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
  393. chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
  394. chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
  395. chr(195).chr(135) => 'C', chr(195).chr(136) => 'E',
  396. chr(195).chr(137) => 'E', chr(195).chr(138) => 'E',
  397. chr(195).chr(139) => 'E', chr(195).chr(140) => 'I',
  398. chr(195).chr(141) => 'I', chr(195).chr(142) => 'I',
  399. chr(195).chr(143) => 'I', chr(195).chr(145) => 'N',
  400. chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
  401. chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
  402. chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
  403. chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
  404. chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
  405. chr(195).chr(159) => 's', chr(195).chr(160) => 'a',
  406. chr(195).chr(161) => 'a', chr(195).chr(162) => 'a',
  407. chr(195).chr(163) => 'a', chr(195).chr(164) => 'a',
  408. chr(195).chr(165) => 'a', chr(195).chr(167) => 'c',
  409. chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
  410. chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
  411. chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
  412. chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
  413. chr(195).chr(177) => 'n', chr(195).chr(178) => 'o',
  414. chr(195).chr(179) => 'o', chr(195).chr(180) => 'o',
  415. chr(195).chr(181) => 'o', chr(195).chr(182) => 'o',
  416. chr(195).chr(182) => 'o', chr(195).chr(185) => 'u',
  417. chr(195).chr(186) => 'u', chr(195).chr(187) => 'u',
  418. chr(195).chr(188) => 'u', chr(195).chr(189) => 'y',
  419. chr(195).chr(191) => 'y',
  420. // Decompositions for Latin Extended-A
  421. chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
  422. chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
  423. chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
  424. chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
  425. chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
  426. chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
  427. chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
  428. chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
  429. chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
  430. chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
  431. chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
  432. chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
  433. chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
  434. chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
  435. chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
  436. chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
  437. chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
  438. chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
  439. chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
  440. chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
  441. chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
  442. chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
  443. chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
  444. chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
  445. chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
  446. chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
  447. chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
  448. chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
  449. chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
  450. chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
  451. chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
  452. chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
  453. chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
  454. chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
  455. chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
  456. chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
  457. chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
  458. chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
  459. chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
  460. chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
  461. chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
  462. chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
  463. chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
  464. chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
  465. chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
  466. chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
  467. chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
  468. chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
  469. chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
  470. chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
  471. chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
  472. chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
  473. chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
  474. chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
  475. chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
  476. chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
  477. chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
  478. chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
  479. chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
  480. chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
  481. chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
  482. chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
  483. chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
  484. chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
  485. // Euro Sign
  486. chr(226).chr(130).chr(172) => 'E',
  487. // GBP (Pound) Sign
  488. chr(194).chr(163) => '');
  489. $string = strtr($string, $chars);
  490. } else {
  491. // Assume ISO-8859-1 if not UTF-8
  492. $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
  493. .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
  494. .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
  495. .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
  496. .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
  497. .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
  498. .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
  499. .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
  500. .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
  501. .chr(252).chr(253).chr(255);
  502. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  503. $string = strtr($string, $chars['in'], $chars['out']);
  504. $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
  505. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  506. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  507. }
  508. return $string;
  509. }
  510. /**
  511. * Filters certain characters from the file name.
  512. *
  513. * Turns all strings to lowercase removing most characters except alphanumeric
  514. * with spaces, dashes and periods. All spaces and underscores are converted to
  515. * dashes. Multiple dashes are converted to a single dash. Finally, if the file
  516. * name ends with a dash, it is removed.
  517. *
  518. * @since 2.1.0
  519. *
  520. * @param string $name The file name
  521. * @return string Sanitized file name
  522. */
  523. function sanitize_file_name( $name ) { // Like sanitize_title, but with periods
  524. $name = strtolower( $name );
  525. $name = preg_replace('/&.+?;/', '', $name); // kill entities
  526. $name = str_replace( '_', '-', $name );
  527. $name = preg_replace('/[^a-z0-9\s-.]/', '', $name);
  528. $name = preg_replace('/\s+/', '-', $name);
  529. $name = preg_replace('|-+|', '-', $name);
  530. $name = trim($name, '-');
  531. return $name;
  532. }
  533. /**
  534. * Sanitize username stripping out unsafe characters.
  535. *
  536. * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
  537. * @) are returned.
  538. * Removes tags, octets, entities, and if strict is enabled, will remove all
  539. * non-ASCII characters. After sanitizing, it passes the username, raw username
  540. * (the username in the parameter), and the strict parameter as parameters for
  541. * the filter.
  542. *
  543. * @since 2.0.0
  544. * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
  545. * and $strict parameter.
  546. *
  547. * @param string $username The username to be sanitized.
  548. * @param bool $strict If set limits $username to specific characters. Default false.
  549. * @return string The sanitized username, after passing through filters.
  550. */
  551. function sanitize_user( $username, $strict = false ) {
  552. $raw_username = $username;
  553. $username = strip_tags($username);
  554. // Kill octets
  555. $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
  556. $username = preg_replace('/&.+?;/', '', $username); // Kill entities
  557. // If strict, reduce to ASCII for max portability.
  558. if ( $strict )
  559. $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
  560. // Consolidate contiguous whitespace
  561. $username = preg_replace('|\s+|', ' ', $username);
  562. return apply_filters('sanitize_user', $username, $raw_username, $strict);
  563. }
  564. /**
  565. * Sanitizes title or use fallback title.
  566. *
  567. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  568. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  569. * will be used.
  570. *
  571. * @since 1.0.0
  572. *
  573. * @param string $title The string to be sanitized.
  574. * @param string $fallback_title Optional. A title to use if $title is empty.
  575. * @return string The sanitized string.
  576. */
  577. function sanitize_title($title, $fallback_title = '') {
  578. $title = strip_tags($title);
  579. $title = apply_filters('sanitize_title', $title);
  580. if ( '' === $title || false === $title )
  581. $title = $fallback_title;
  582. return $title;
  583. }
  584. /**
  585. * Sanitizes title, replacing whitespace with dashes.
  586. *
  587. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  588. * Whitespace becomes a dash.
  589. *
  590. * @since 1.2.0
  591. *
  592. * @param string $title The title to be sanitized.
  593. * @return string The sanitized title.
  594. */
  595. function sanitize_title_with_dashes($title) {
  596. $title = strip_tags($title);
  597. // Preserve escaped octets.
  598. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  599. // Remove percent signs that are not part of an octet.
  600. $title = str_replace('%', '', $title);
  601. // Restore octets.
  602. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  603. $title = remove_accents($title);
  604. if (seems_utf8($title)) {
  605. if (function_exists('mb_strtolower')) {
  606. $title = mb_strtolower($title, 'UTF-8');
  607. }
  608. $title = utf8_uri_encode($title, 200);
  609. }
  610. $title = strtolower($title);
  611. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  612. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  613. $title = preg_replace('/\s+/', '-', $title);
  614. $title = preg_replace('|-+|', '-', $title);
  615. $title = trim($title, '-');
  616. return $title;
  617. }
  618. /**
  619. * Ensures a string is a valid SQL order by clause.
  620. *
  621. * Accepts one or more columns, with or without ASC/DESC, and also accepts
  622. * RAND().
  623. *
  624. * @since 2.5.1
  625. *
  626. * @param string $orderby Order by string to be checked.
  627. * @return string|false Returns the order by clause if it is a match, false otherwise.
  628. */
  629. function sanitize_sql_orderby( $orderby ){
  630. preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
  631. if ( !$obmatches )
  632. return false;
  633. return $orderby;
  634. }
  635. /**
  636. * Converts a number of characters from a string.
  637. *
  638. * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
  639. * converted into correct XHTML and Unicode characters are converted to the
  640. * valid range.
  641. *
  642. * @since 0.71
  643. *
  644. * @param string $content String of characters to be converted.
  645. * @param string $deprecated Not used.
  646. * @return string Converted string.
  647. */
  648. function convert_chars($content, $deprecated = '') {
  649. // Translation of invalid Unicode references range to valid range
  650. $wp_htmltranswinuni = array(
  651. '&#128;' => '&#8364;', // the Euro sign
  652. '&#129;' => '',
  653. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  654. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  655. '&#132;' => '&#8222;',
  656. '&#133;' => '&#8230;',
  657. '&#134;' => '&#8224;',
  658. '&#135;' => '&#8225;',
  659. '&#136;' => '&#710;',
  660. '&#137;' => '&#8240;',
  661. '&#138;' => '&#352;',
  662. '&#139;' => '&#8249;',
  663. '&#140;' => '&#338;',
  664. '&#141;' => '',
  665. '&#142;' => '&#382;',
  666. '&#143;' => '',
  667. '&#144;' => '',
  668. '&#145;' => '&#8216;',
  669. '&#146;' => '&#8217;',
  670. '&#147;' => '&#8220;',
  671. '&#148;' => '&#8221;',
  672. '&#149;' => '&#8226;',
  673. '&#150;' => '&#8211;',
  674. '&#151;' => '&#8212;',
  675. '&#152;' => '&#732;',
  676. '&#153;' => '&#8482;',
  677. '&#154;' => '&#353;',
  678. '&#155;' => '&#8250;',
  679. '&#156;' => '&#339;',
  680. '&#157;' => '',
  681. '&#158;' => '',
  682. '&#159;' => '&#376;'
  683. );
  684. // Remove metadata tags
  685. $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
  686. $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
  687. // Converts lone & characters into &#38; (a.k.a. &amp;)
  688. $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
  689. // Fix Word pasting
  690. $content = strtr($content, $wp_htmltranswinuni);
  691. // Just a little XHTML help
  692. $content = str_replace('<br>', '<br />', $content);
  693. $content = str_replace('<hr>', '<hr />', $content);
  694. return $content;
  695. }
  696. /**
  697. * Fixes javascript bugs in browsers.
  698. *
  699. * Converts unicode characters to HTML numbered entities.
  700. *
  701. * @since 1.5.0
  702. * @uses $is_macIE
  703. * @uses $is_winIE
  704. *
  705. * @param string $text Text to be made safe.
  706. * @return string Fixed text.
  707. */
  708. function funky_javascript_fix($text) {
  709. // Fixes for browsers' javascript bugs
  710. global $is_macIE, $is_winIE;
  711. /** @todo use preg_replace_callback() instead */
  712. if ( $is_winIE || $is_macIE )
  713. $text = preg_replace("/\%u([0-9A-F]{4,4})/e", "'&#'.base_convert('\\1',16,10).';'", $text);
  714. return $text;
  715. }
  716. /**
  717. * Will only balance the tags if forced to and the option is set to balance tags.
  718. *
  719. * The option 'use_balanceTags' is used for whether the tags will be balanced.
  720. * Both the $force parameter and 'use_balanceTags' option will have to be true
  721. * before the tags will be balanced.
  722. *
  723. * @since 0.71
  724. *
  725. * @param string $text Text to be balanced
  726. * @param bool $force Forces balancing, ignoring the value of the option. Default false.
  727. * @return string Balanced text
  728. */
  729. function balanceTags( $text, $force = false ) {
  730. if ( !$force && get_option('use_balanceTags') == 0 )
  731. return $text;
  732. return force_balance_tags( $text );
  733. }
  734. /**
  735. * Balances tags of string using a modified stack.
  736. *
  737. * @since 2.0.4
  738. *
  739. * @author Leonard Lin <leonard@acm.org>
  740. * @license GPL v2.0
  741. * @copyright November 4, 2001
  742. * @version 1.1
  743. * @todo Make better - change loop condition to $text in 1.2
  744. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  745. * 1.1 Fixed handling of append/stack pop order of end text
  746. * Added Cleaning Hooks
  747. * 1.0 First Version
  748. *
  749. * @param string $text Text to be balanced.
  750. * @return string Balanced text.
  751. */
  752. function force_balance_tags( $text ) {
  753. $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
  754. $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
  755. $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
  756. # WP bug fix for comments - in case you REALLY meant to type '< !--'
  757. $text = str_replace('< !--', '< !--', $text);
  758. # WP bug fix for LOVE <3 (and other situations with '<' before a number)
  759. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  760. while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
  761. $newtext .= $tagqueue;
  762. $i = strpos($text,$regex[0]);
  763. $l = strlen($regex[0]);
  764. // clear the shifter
  765. $tagqueue = '';
  766. // Pop or Push
  767. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  768. $tag = strtolower(substr($regex[1],1));
  769. // if too many closing tags
  770. if($stacksize <= 0) {
  771. $tag = '';
  772. //or close to be safe $tag = '/' . $tag;
  773. }
  774. // if stacktop value = tag close value then pop
  775. else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
  776. $tag = '</' . $tag . '>'; // Close Tag
  777. // Pop
  778. array_pop ($tagstack);
  779. $stacksize--;
  780. } else { // closing tag not at top, search for it
  781. for ($j=$stacksize-1;$j>=0;$j--) {
  782. if ($tagstack[$j] == $tag) {
  783. // add tag to tagqueue
  784. for ($k=$stacksize-1;$k>=$j;$k--){
  785. $tagqueue .= '</' . array_pop ($tagstack) . '>';
  786. $stacksize--;
  787. }
  788. break;
  789. }
  790. }
  791. $tag = '';
  792. }
  793. } else { // Begin Tag
  794. $tag = strtolower($regex[1]);
  795. // Tag Cleaning
  796. // If self-closing or '', don't do anything.
  797. if((substr($regex[2],-1) == '/') || ($tag == '')) {
  798. }
  799. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  800. elseif ( in_array($tag, $single_tags) ) {
  801. $regex[2] .= '/';
  802. } else { // Push the tag onto the stack
  803. // If the top of the stack is the same as the tag we want to push, close previous tag
  804. if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
  805. $tagqueue = '</' . array_pop ($tagstack) . '>';
  806. $stacksize--;
  807. }
  808. $stacksize = array_push ($tagstack, $tag);
  809. }
  810. // Attributes
  811. $attributes = $regex[2];
  812. if($attributes) {
  813. $attributes = ' '.$attributes;
  814. }
  815. $tag = '<'.$tag.$attributes.'>';
  816. //If already queuing a close tag, then put this tag on, too
  817. if ($tagqueue) {
  818. $tagqueue .= $tag;
  819. $tag = '';
  820. }
  821. }
  822. $newtext .= substr($text,0,$i) . $tag;
  823. $text = substr($text,$i+$l);
  824. }
  825. // Clear Tag Queue
  826. $newtext .= $tagqueue;
  827. // Add Remaining text
  828. $newtext .= $text;
  829. // Empty Stack
  830. while($x = array_pop($tagstack)) {
  831. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  832. }
  833. // WP fix for the bug with HTML comments
  834. $newtext = str_replace("< !--","<!--",$newtext);
  835. $newtext = str_replace("< !--","< !--",$newtext);
  836. return $newtext;
  837. }
  838. /**
  839. * Acts on text which is about to be edited.
  840. *
  841. * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
  842. * filter. If $richedit is set true htmlspecialchars() will be run on the
  843. * content, converting special characters to HTMl entities.
  844. *
  845. * @since 0.71
  846. *
  847. * @param string $content The text about to be edited.
  848. * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false.
  849. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  850. */
  851. function format_to_edit($content, $richedit = false) {
  852. $content = apply_filters('format_to_edit', $content);
  853. if (! $richedit )
  854. $content = htmlspecialchars($content);
  855. return $content;
  856. }
  857. /**
  858. * Holder for the 'format_to_post' filter.
  859. *
  860. * @since 0.71
  861. *
  862. * @param string $content The text to pass through the filter.
  863. * @return string Text returned from the 'format_to_post' filter.
  864. */
  865. function format_to_post($content) {
  866. $content = apply_filters('format_to_post', $content);
  867. return $content;
  868. }
  869. /**
  870. * Add leading zeros when necessary.
  871. *
  872. * If you set the threshold to '4' and the number is '10', then you will get
  873. * back '0010'. If you set the number to '4' and the number is '5000', then you
  874. * will get back '5000'.
  875. *
  876. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  877. * and the size of the number. If the number is large enough, then no zeros will
  878. * be appended.
  879. *
  880. * @since 0.71
  881. *
  882. * @param mixed $number Number to append zeros to if not greater than threshold.
  883. * @param int $threshold Digit places number needs to be to not have zeros added.
  884. * @return string Adds leading zeros to number if needed.
  885. */
  886. function zeroise($number, $threshold) {
  887. return sprintf('%0'.$threshold.'s', $number);
  888. }
  889. /**
  890. * Adds backslashes before letters and before a number at the start of a string.
  891. *
  892. * @since 0.71
  893. *
  894. * @param string $string Value to which backslashes will be added.
  895. * @return string String with backslashes inserted.
  896. */
  897. function backslashit($string) {
  898. $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
  899. $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
  900. return $string;
  901. }
  902. /**
  903. * Appends a trailing slash.
  904. *
  905. * Will remove trailing slash if it exists already before adding a trailing
  906. * slash. This prevents double slashing a string or path.
  907. *
  908. * The primary use of this is for paths and thus should be used for paths. It is
  909. * not restricted to paths and offers no specific path support.
  910. *
  911. * @since 1.2.0
  912. * @uses untrailingslashit() Unslashes string if it was slashed already.
  913. *
  914. * @param string $string What to add the trailing slash to.
  915. * @return string String with trailing slash added.
  916. */
  917. function trailingslashit($string) {
  918. return untrailingslashit($string) . '/';
  919. }
  920. /**
  921. * Removes trailing slash if it exists.
  922. *
  923. * The primary use of this is for paths and thus should be used for paths. It is
  924. * not restricted to paths and offers no specific path support.
  925. *
  926. * @since 2.2.0
  927. *
  928. * @param string $string What to remove the trailing slash from.
  929. * @return string String without the trailing slash.
  930. */
  931. function untrailingslashit($string) {
  932. return rtrim($string, '/');
  933. }
  934. /**
  935. * Adds slashes to escape strings.
  936. *
  937. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  938. * http://www.php.net/magic_quotes} for more details.
  939. *
  940. * @since 0.71
  941. *
  942. * @param string $gpc The string returned from HTTP request data.
  943. * @return string Returns a string escaped with slashes.
  944. */
  945. function addslashes_gpc($gpc) {
  946. global $wpdb;
  947. if (get_magic_quotes_gpc()) {
  948. $gpc = stripslashes($gpc);
  949. }
  950. return $wpdb->escape($gpc);
  951. }
  952. /**
  953. * Navigates through an array and removes slashes from the values.
  954. *
  955. * If an array is passed, the array_map() function causes a callback to pass the
  956. * value back to the function. The slashes from this value will removed.
  957. *
  958. * @since 2.0.0
  959. *
  960. * @param array|string $value The array or string to be striped.
  961. * @return array|string Stripped array (or string in the callback).
  962. */
  963. function stripslashes_deep($value) {
  964. $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
  965. return $value;
  966. }
  967. /**
  968. * Navigates through an array and encodes the values to be used in a URL.
  969. *
  970. * Uses a callback to pass the value of the array back to the function as a
  971. * string.
  972. *
  973. * @since 2.2.0
  974. *
  975. * @param array|string $value The array or string to be encoded.
  976. * @return array|string $value The encoded array (or string from the callback).
  977. */
  978. function urlencode_deep($value) {
  979. $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
  980. return $value;
  981. }
  982. /**
  983. * Converts email addresses characters to HTML entities to block spam bots.
  984. *
  985. * @since 0.71
  986. *
  987. * @param string $emailaddy Email address.
  988. * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
  989. * @return string Converted email address.
  990. */
  991. function antispambot($emailaddy, $mailto=0) {
  992. $emailNOSPAMaddy = '';
  993. srand ((float) microtime() * 1000000);
  994. for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
  995. $j = floor(rand(0, 1+$mailto));
  996. if ($j==0) {
  997. $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
  998. } elseif ($j==1) {
  999. $emailNOSPAMaddy .= substr($emailaddy,$i,1);
  1000. } elseif ($j==2) {
  1001. $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
  1002. }
  1003. }
  1004. $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
  1005. return $emailNOSPAMaddy;
  1006. }
  1007. /**
  1008. * Callback to convert URI match to HTML A element.
  1009. *
  1010. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1011. * make_clickable()}.
  1012. *
  1013. * @since 2.3.2
  1014. * @access private
  1015. *
  1016. * @param array $matches Single Regex Match.
  1017. * @return string HTML A element with URI address.
  1018. */
  1019. function _make_url_clickable_cb($matches) {
  1020. $url = $matches[2];
  1021. $url = clean_url($url);
  1022. if ( empty($url) )
  1023. return $matches[0];
  1024. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
  1025. }
  1026. /**
  1027. * Callback to convert URL match to HTML A element.
  1028. *
  1029. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1030. * make_clickable()}.
  1031. *
  1032. * @since 2.3.2
  1033. * @access private
  1034. *
  1035. * @param array $matches Single Regex Match.
  1036. * @return string HTML A element with URL address.
  1037. */
  1038. function _make_web_ftp_clickable_cb($matches) {
  1039. $ret = '';
  1040. $dest = $matches[2];
  1041. $dest = 'http://' . $dest;
  1042. $dest = clean_url($dest);
  1043. if ( empty($dest) )
  1044. return $matches[0];
  1045. // removed trailing [,;:] from URL
  1046. if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
  1047. $ret = substr($dest, -1);
  1048. $dest = substr($dest, 0, strlen($dest)-1);
  1049. }
  1050. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
  1051. }
  1052. /**
  1053. * Callback to convert email address match to HTML A element.
  1054. *
  1055. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1056. * make_clickable()}.
  1057. *
  1058. * @since 2.3.2
  1059. * @access private
  1060. *
  1061. * @param array $matches Single Regex Match.
  1062. * @return string HTML A element with email address.
  1063. */
  1064. function _make_email_clickable_cb($matches) {
  1065. $email = $matches[2] . '@' . $matches[3];
  1066. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  1067. }
  1068. /**
  1069. * Convert plaintext URI to HTML links.
  1070. *
  1071. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  1072. * within links.
  1073. *
  1074. * @since 0.71
  1075. *
  1076. * @param string $ret Content to convert URIs.
  1077. * @return string Content with converted URIs.
  1078. */
  1079. function make_clickable($ret) {
  1080. $ret = ' ' . $ret;
  1081. // in testing, using arrays here was found to be faster
  1082. $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))*)#is', '_make_url_clickable_cb', $ret);
  1083. $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]*)#is', '_make_web_ftp_clickable_cb', $ret);
  1084. $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  1085. // this one is not in an array because we need it to run last, for cleanup of accidental links within links
  1086. $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
  1087. $ret = trim($ret);
  1088. return $ret;
  1089. }
  1090. /**
  1091. * Adds rel nofollow string to all HTML A elements in content.
  1092. *
  1093. * @since 1.5.0
  1094. *
  1095. * @param string $text Content that may contain HTML A elements.
  1096. * @return string Converted content.
  1097. */
  1098. function wp_rel_nofollow( $text ) {
  1099. global $wpdb;
  1100. // This is a pre save filter, so text is already escaped.
  1101. $text = stripslashes($text);
  1102. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  1103. $text = $wpdb->escape($text);
  1104. return $text;
  1105. }
  1106. /**
  1107. * Callback to used to add rel=nofollow string to HTML A element.
  1108. *
  1109. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  1110. * string to prevent from invalidating (X)HTML.
  1111. *
  1112. * @since 2.3.0
  1113. *
  1114. * @param array $matches Single Match
  1115. * @return string HTML A Element with rel nofollow.
  1116. */
  1117. function wp_rel_nofollow_callback( $matches ) {
  1118. $text = $matches[1];
  1119. $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
  1120. return "<a $text rel=\"nofollow\">";
  1121. }
  1122. /**
  1123. * Convert one smiley code to the icon graphic file equivalent.
  1124. *
  1125. * Looks up one smiley code in the $wpsmiliestrans global array and returns an
  1126. * <img> string for that smiley.
  1127. *
  1128. * @global array $wpsmiliestrans
  1129. * @since 2.8.0
  1130. *
  1131. * @param string $smiley Smiley code to convert to image.
  1132. * @return string Image string for smiley.
  1133. */
  1134. function translate_smiley($smiley) {
  1135. global $wpsmiliestrans;
  1136. if (count($smiley) == 0) {
  1137. return '';
  1138. }
  1139. $siteurl = get_option( 'siteurl' );
  1140. $smiley = trim(reset($smiley));
  1141. $img = $wpsmiliestrans[$smiley];
  1142. $smiley_masked = attribute_escape($smiley);
  1143. return " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
  1144. }
  1145. /**
  1146. * Convert text equivalent of smilies to images.
  1147. *
  1148. * Will only convert smilies if the option 'use_smilies' is true and the global
  1149. * used in the function isn't empty.
  1150. *
  1151. * @since 0.71
  1152. * @uses $wp_smiliessearch
  1153. *
  1154. * @param string $text Content to convert smilies from text.
  1155. * @return string Converted content with text smilies replaced with images.
  1156. */
  1157. function convert_smilies($text) {
  1158. global $wp_smiliessearch;
  1159. $output = '';
  1160. if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
  1161. // HTML loop taken from texturize function, could possible be consolidated
  1162. $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
  1163. $stop = count($textarr);// loop stuff
  1164. for ($i = 0; $i < $stop; $i++) {
  1165. $content = $textarr[$i];
  1166. if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
  1167. $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
  1168. }
  1169. $output .= $content;
  1170. }
  1171. } else {
  1172. // return default text.
  1173. $output = $text;
  1174. }
  1175. return $output;
  1176. }
  1177. /**
  1178. * Checks to see if the text is a valid email address.
  1179. *
  1180. * @since 0.71
  1181. *
  1182. * @param string $user_email The email address to be checked.
  1183. * @return bool Returns true if valid, otherwise false.
  1184. */
  1185. function is_email($user_email) {
  1186. $chars = "/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
  1187. if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false) {
  1188. if (preg_match($chars, $user_email)) {
  1189. return true;
  1190. } else {
  1191. return false;
  1192. }
  1193. } else {
  1194. return false;
  1195. }
  1196. }
  1197. /**
  1198. * Convert to ASCII from email subjects.
  1199. *
  1200. * @since 1.2.0
  1201. * @usedby wp_mail() handles charsets in email subjects
  1202. *
  1203. * @param string $string Subject line
  1204. * @return string Converted string to ASCII
  1205. */
  1206. function wp_iso_descrambler($string) {
  1207. /* this may only work with iso-8859-1, I'm afraid */
  1208. if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
  1209. return $string;
  1210. } else {
  1211. $subject = str_replace('_', ' ', $matches[2]);
  1212. $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', create_function('$match', 'return chr(hexdec(strtolower($match[1])));'), $subject);
  1213. return $subject;
  1214. }
  1215. }
  1216. /**
  1217. * Returns a date in the GMT equivalent.
  1218. *
  1219. * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the
  1220. * value of the 'gmt_offset' option.
  1221. *
  1222. * @since 1.2.0
  1223. *
  1224. * @uses get_option() to retrieve the the value of 'gmt_offset'.
  1225. * @param string $string The date to be converted.
  1226. * @return string GMT version of the date provided.
  1227. */
  1228. function get_gmt_from_date($string) {
  1229. 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);
  1230. $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
  1231. $string_gmt = gmdate('Y-m-d H:i:s', $string_time - get_option('gmt_offset') * 3600);
  1232. return $string_gmt;
  1233. }
  1234. /**
  1235. * Converts a GMT date into the correct format for the blog.
  1236. *
  1237. * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of
  1238. * gmt_offset.
  1239. *
  1240. * @since 1.2.0
  1241. *
  1242. * @param string $string The date to be converted.
  1243. * @return string Formatted date relative to the GMT offset.
  1244. */
  1245. function get_date_from_gmt($string) {
  1246. 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);
  1247. $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]);
  1248. $string_localtime = gmdate('Y-m-d H:i:s', $string_time + get_option('gmt_offset')*3600);
  1249. return $string_localtime;
  1250. }
  1251. /**
  1252. * Computes an offset in seconds from an iso8601 timezone.
  1253. *
  1254. * @since 1.5.0
  1255. *
  1256. * @param string $timezone Either 'Z' for 0 offset or '±hhmm'.
  1257. * @return int|float The offset in seconds.
  1258. */
  1259. function iso8601_timezone_to_offset($timezone) {
  1260. // $timezone is either 'Z' or '[+|-]hhmm'
  1261. if ($timezone == 'Z') {
  1262. $offset = 0;
  1263. } else {
  1264. $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
  1265. $hours = intval(substr($timezone, 1, 2));
  1266. $minutes = intval(substr($timezone, 3, 4)) / 60;
  1267. $offset = $sign * 3600 * ($hours + $minutes);
  1268. }
  1269. return $offset;
  1270. }
  1271. /**
  1272. * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
  1273. *
  1274. * @since 1.5.0
  1275. *
  1276. * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
  1277. * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
  1278. * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
  1279. */
  1280. function iso8601_to_datetime($date_string, $timezone = 'user') {
  1281. $timezone = strtolower($timezone);
  1282. if ($timezone == 'gmt') {
  1283. 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);
  1284. if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
  1285. $offset = iso8601_timezone_to_offset($date_bits[7]);
  1286. } else { // we don't have a timezone, so we assume user local timezone (not server's!)
  1287. $offset = 3600 * get_option('gmt_offset');
  1288. }
  1289. $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
  1290. $timestamp -= $offset;
  1291. return gmdate('Y-m-d H:i:s', $timestamp);
  1292. } else if ($timezone == 'user') {
  1293. 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);
  1294. }
  1295. }
  1296. /**
  1297. * Adds a element attributes to open links in new windows.
  1298. *
  1299. * Comment text in popup windows should be filtered through this. Right now it's
  1300. * a moderately dumb function, ideally it would detect whether a target or rel
  1301. * attribute was already there and adjust its actions accordingly.
  1302. *
  1303. * @since 0.71
  1304. *
  1305. * @param string $text Content to replace links to open in a new window.
  1306. * @return string Content that has filtered links.
  1307. */
  1308. function popuplinks($text) {
  1309. $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
  1310. return $text;
  1311. }
  1312. /**
  1313. * Strips out all characters that are not allowable in an email.
  1314. *
  1315. * @since 1.5.0
  1316. *
  1317. * @param string $email Email address to filter.
  1318. * @return string Filtered email address.
  1319. */
  1320. function sanitize_email($email) {
  1321. return preg_replace('/[^a-z0-9+_.@-]/i', '', $email);
  1322. }
  1323. /**
  1324. * Determines the difference between two timestamps.
  1325. *
  1326. * The difference is returned in a human readable format such as "1 hour",
  1327. * "5 mins", "2 days".
  1328. *
  1329. * @since 1.5.0
  1330. *
  1331. * @param int $from Unix timestamp from which the difference begins.
  1332. * @param int …

Large files files are truncated, but you can click here to view the full file