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

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

https://bitbucket.org/thejeshgn/kindle-fire
PHP | 2679 lines | 1591 code | 205 blank | 883 comment | 208 complexity | 004286e364dd12eebb41c7bbb48b0da1 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-2.0, AGPL-1.0, LGPL-2.1, Apache-2.0, AGPL-3.0, LGPL-3.0, GPL-2.0, BSD-3-Clause, GPL-3.0, 0BSD

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

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