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

/wordpress/wp-includes/formatting.php

https://github.com/whatcould/three20.info
PHP | 2712 lines | 1624 code | 205 blank | 883 comment | 208 complexity | d3d168382db4a7b5426b93de535d9f48 MD5 | raw file
Possible License(s): Apache-2.0

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. // Split the filename into a base and extension[s]
  550. $parts = explode('.', $filename);
  551. // Return if only one extension
  552. if ( count($parts) <= 2 )
  553. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  554. // Process multiple extensions
  555. $filename = array_shift($parts);
  556. $extension = array_pop($parts);
  557. $mimes = get_allowed_mime_types();
  558. // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
  559. // long alpha string not in the extension whitelist.
  560. foreach ( (array) $parts as $part) {
  561. $filename .= '.' . $part;
  562. if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
  563. $allowed = false;
  564. foreach ( $mimes as $ext_preg => $mime_match ) {
  565. $ext_preg = '!(^' . $ext_preg . ')$!i';
  566. if ( preg_match( $ext_preg, $part ) ) {
  567. $allowed = true;
  568. break;
  569. }
  570. }
  571. if ( !$allowed )
  572. $filename .= '_';
  573. }
  574. }
  575. $filename .= '.' . $extension;
  576. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  577. }
  578. /**
  579. * Sanitize username stripping out unsafe characters.
  580. *
  581. * If $strict is true, only alphanumeric characters (as well as _, space, ., -,
  582. * @) are returned.
  583. * Removes tags, octets, entities, and if strict is enabled, will remove all
  584. * non-ASCII characters. After sanitizing, it passes the username, raw username
  585. * (the username in the parameter), and the strict parameter as parameters for
  586. * the filter.
  587. *
  588. * @since 2.0.0
  589. * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
  590. * and $strict parameter.
  591. *
  592. * @param string $username The username to be sanitized.
  593. * @param bool $strict If set limits $username to specific characters. Default false.
  594. * @return string The sanitized username, after passing through filters.
  595. */
  596. function sanitize_user( $username, $strict = false ) {
  597. $raw_username = $username;
  598. $username = strip_tags($username);
  599. // Kill octets
  600. $username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $username);
  601. $username = preg_replace('/&.+?;/', '', $username); // Kill entities
  602. // If strict, reduce to ASCII for max portability.
  603. if ( $strict )
  604. $username = preg_replace('|[^a-z0-9 _.\-@]|i', '', $username);
  605. // Consolidate contiguous whitespace
  606. $username = preg_replace('|\s+|', ' ', $username);
  607. return apply_filters('sanitize_user', $username, $raw_username, $strict);
  608. }
  609. /**
  610. * Sanitizes title or use fallback title.
  611. *
  612. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  613. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  614. * will be used.
  615. *
  616. * @since 1.0.0
  617. *
  618. * @param string $title The string to be sanitized.
  619. * @param string $fallback_title Optional. A title to use if $title is empty.
  620. * @return string The sanitized string.
  621. */
  622. function sanitize_title($title, $fallback_title = '') {
  623. $raw_title = $title;
  624. $title = strip_tags($title);
  625. $title = apply_filters('sanitize_title', $title, $raw_title);
  626. if ( '' === $title || false === $title )
  627. $title = $fallback_title;
  628. return $title;
  629. }
  630. /**
  631. * Sanitizes title, replacing whitespace with dashes.
  632. *
  633. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  634. * Whitespace becomes a dash.
  635. *
  636. * @since 1.2.0
  637. *
  638. * @param string $title The title to be sanitized.
  639. * @return string The sanitized title.
  640. */
  641. function sanitize_title_with_dashes($title) {
  642. $title = strip_tags($title);
  643. // Preserve escaped octets.
  644. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  645. // Remove percent signs that are not part of an octet.
  646. $title = str_replace('%', '', $title);
  647. // Restore octets.
  648. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  649. $title = remove_accents($title);
  650. if (seems_utf8($title)) {
  651. if (function_exists('mb_strtolower')) {
  652. $title = mb_strtolower($title, 'UTF-8');
  653. }
  654. $title = utf8_uri_encode($title, 200);
  655. }
  656. $title = strtolower($title);
  657. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  658. $title = str_replace('.', '-', $title);
  659. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  660. $title = preg_replace('/\s+/', '-', $title);
  661. $title = preg_replace('|-+|', '-', $title);
  662. $title = trim($title, '-');
  663. return $title;
  664. }
  665. /**
  666. * Ensures a string is a valid SQL order by clause.
  667. *
  668. * Accepts one or more columns, with or without ASC/DESC, and also accepts
  669. * RAND().
  670. *
  671. * @since 2.5.1
  672. *
  673. * @param string $orderby Order by string to be checked.
  674. * @return string|false Returns the order by clause if it is a match, false otherwise.
  675. */
  676. function sanitize_sql_orderby( $orderby ){
  677. preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
  678. if ( !$obmatches )
  679. return false;
  680. return $orderby;
  681. }
  682. /**
  683. * Santizes a html classname to ensure it only contains valid characters
  684. *
  685. * Strips the string down to A-Z,a-z,0-9,'-' if this results in an empty
  686. * string then it will return the alternative value supplied.
  687. *
  688. * @todo Expand to support the full range of CDATA that a class attribute can contain.
  689. *
  690. * @since 2.8.0
  691. *
  692. * @param string $class The classname to be sanitized
  693. * @param string $fallback The value to return if the sanitization end's up as an empty string.
  694. * @return string The sanitized value
  695. */
  696. function sanitize_html_class($class, $fallback){
  697. //Strip out any % encoded octets
  698. $sanitized = preg_replace('|%[a-fA-F0-9][a-fA-F0-9]|', '', $class);
  699. //Limit to A-Z,a-z,0-9,'-'
  700. $sanitized = preg_replace('/[^A-Za-z0-9-]/', '', $sanitized);
  701. if ('' == $sanitized)
  702. $sanitized = $fallback;
  703. return apply_filters('sanitize_html_class',$sanitized, $class, $fallback);
  704. }
  705. /**
  706. * Converts a number of characters from a string.
  707. *
  708. * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
  709. * converted into correct XHTML and Unicode characters are converted to the
  710. * valid range.
  711. *
  712. * @since 0.71
  713. *
  714. * @param string $content String of characters to be converted.
  715. * @param string $deprecated Not used.
  716. * @return string Converted string.
  717. */
  718. function convert_chars($content, $deprecated = '') {
  719. // Translation of invalid Unicode references range to valid range
  720. $wp_htmltranswinuni = array(
  721. '&#128;' => '&#8364;', // the Euro sign
  722. '&#129;' => '',
  723. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  724. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  725. '&#132;' => '&#8222;',
  726. '&#133;' => '&#8230;',
  727. '&#134;' => '&#8224;',
  728. '&#135;' => '&#8225;',
  729. '&#136;' => '&#710;',
  730. '&#137;' => '&#8240;',
  731. '&#138;' => '&#352;',
  732. '&#139;' => '&#8249;',
  733. '&#140;' => '&#338;',
  734. '&#141;' => '',
  735. '&#142;' => '&#382;',
  736. '&#143;' => '',
  737. '&#144;' => '',
  738. '&#145;' => '&#8216;',
  739. '&#146;' => '&#8217;',
  740. '&#147;' => '&#8220;',
  741. '&#148;' => '&#8221;',
  742. '&#149;' => '&#8226;',
  743. '&#150;' => '&#8211;',
  744. '&#151;' => '&#8212;',
  745. '&#152;' => '&#732;',
  746. '&#153;' => '&#8482;',
  747. '&#154;' => '&#353;',
  748. '&#155;' => '&#8250;',
  749. '&#156;' => '&#339;',
  750. '&#157;' => '',
  751. '&#158;' => '',
  752. '&#159;' => '&#376;'
  753. );
  754. // Remove metadata tags
  755. $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
  756. $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
  757. // Converts lone & characters into &#38; (a.k.a. &amp;)
  758. $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
  759. // Fix Word pasting
  760. $content = strtr($content, $wp_htmltranswinuni);
  761. // Just a little XHTML help
  762. $content = str_replace('<br>', '<br />', $content);
  763. $content = str_replace('<hr>', '<hr />', $content);
  764. return $content;
  765. }
  766. /**
  767. * Callback used to change %uXXXX to &#YYY; syntax
  768. *
  769. * @since 2.8?
  770. *
  771. * @param array $matches Single Match
  772. * @return string An HTML entity
  773. */
  774. function funky_javascript_callback($matches) {
  775. return "&#".base_convert($matches[1],16,10).";";
  776. }
  777. /**
  778. * Fixes javascript bugs in browsers.
  779. *
  780. * Converts unicode characters to HTML numbered entities.
  781. *
  782. * @since 1.5.0
  783. * @uses $is_macIE
  784. * @uses $is_winIE
  785. *
  786. * @param string $text Text to be made safe.
  787. * @return string Fixed text.
  788. */
  789. function funky_javascript_fix($text) {
  790. // Fixes for browsers' javascript bugs
  791. global $is_macIE, $is_winIE;
  792. if ( $is_winIE || $is_macIE )
  793. $text = preg_replace_callback("/\%u([0-9A-F]{4,4})/",
  794. "funky_javascript_callback",
  795. $text);
  796. return $text;
  797. }
  798. /**
  799. * Will only balance the tags if forced to and the option is set to balance tags.
  800. *
  801. * The option 'use_balanceTags' is used for whether the tags will be balanced.
  802. * Both the $force parameter and 'use_balanceTags' option will have to be true
  803. * before the tags will be balanced.
  804. *
  805. * @since 0.71
  806. *
  807. * @param string $text Text to be balanced
  808. * @param bool $force Forces balancing, ignoring the value of the option. Default false.
  809. * @return string Balanced text
  810. */
  811. function balanceTags( $text, $force = false ) {
  812. if ( !$force && get_option('use_balanceTags') == 0 )
  813. return $text;
  814. return force_balance_tags( $text );
  815. }
  816. /**
  817. * Balances tags of string using a modified stack.
  818. *
  819. * @since 2.0.4
  820. *
  821. * @author Leonard Lin <leonard@acm.org>
  822. * @license GPL v2.0
  823. * @copyright November 4, 2001
  824. * @version 1.1
  825. * @todo Make better - change loop condition to $text in 1.2
  826. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  827. * 1.1 Fixed handling of append/stack pop order of end text
  828. * Added Cleaning Hooks
  829. * 1.0 First Version
  830. *
  831. * @param string $text Text to be balanced.
  832. * @return string Balanced text.
  833. */
  834. function force_balance_tags( $text ) {
  835. $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = '';
  836. $single_tags = array('br', 'hr', 'img', 'input'); //Known single-entity/self-closing tags
  837. $nestable_tags = array('blockquote', 'div', 'span'); //Tags that can be immediately nested within themselves
  838. # WP bug fix for comments - in case you REALLY meant to type '< !--'
  839. $text = str_replace('< !--', '< !--', $text);
  840. # WP bug fix for LOVE <3 (and other situations with '<' before a number)
  841. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  842. while (preg_match("/<(\/?\w*)\s*([^>]*)>/",$text,$regex)) {
  843. $newtext .= $tagqueue;
  844. $i = strpos($text,$regex[0]);
  845. $l = strlen($regex[0]);
  846. // clear the shifter
  847. $tagqueue = '';
  848. // Pop or Push
  849. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  850. $tag = strtolower(substr($regex[1],1));
  851. // if too many closing tags
  852. if($stacksize <= 0) {
  853. $tag = '';
  854. //or close to be safe $tag = '/' . $tag;
  855. }
  856. // if stacktop value = tag close value then pop
  857. else if ($tagstack[$stacksize - 1] == $tag) { // found closing tag
  858. $tag = '</' . $tag . '>'; // Close Tag
  859. // Pop
  860. array_pop ($tagstack);
  861. $stacksize--;
  862. } else { // closing tag not at top, search for it
  863. for ($j=$stacksize-1;$j>=0;$j--) {
  864. if ($tagstack[$j] == $tag) {
  865. // add tag to tagqueue
  866. for ($k=$stacksize-1;$k>=$j;$k--){
  867. $tagqueue .= '</' . array_pop ($tagstack) . '>';
  868. $stacksize--;
  869. }
  870. break;
  871. }
  872. }
  873. $tag = '';
  874. }
  875. } else { // Begin Tag
  876. $tag = strtolower($regex[1]);
  877. // Tag Cleaning
  878. // If self-closing or '', don't do anything.
  879. if((substr($regex[2],-1) == '/') || ($tag == '')) {
  880. }
  881. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  882. elseif ( in_array($tag, $single_tags) ) {
  883. $regex[2] .= '/';
  884. } else { // Push the tag onto the stack
  885. // If the top of the stack is the same as the tag we want to push, close previous tag
  886. if (($stacksize > 0) && !in_array($tag, $nestable_tags) && ($tagstack[$stacksize - 1] == $tag)) {
  887. $tagqueue = '</' . array_pop ($tagstack) . '>';
  888. $stacksize--;
  889. }
  890. $stacksize = array_push ($tagstack, $tag);
  891. }
  892. // Attributes
  893. $attributes = $regex[2];
  894. if($attributes) {
  895. $attributes = ' '.$attributes;
  896. }
  897. $tag = '<'.$tag.$attributes.'>';
  898. //If already queuing a close tag, then put this tag on, too
  899. if ($tagqueue) {
  900. $tagqueue .= $tag;
  901. $tag = '';
  902. }
  903. }
  904. $newtext .= substr($text,0,$i) . $tag;
  905. $text = substr($text,$i+$l);
  906. }
  907. // Clear Tag Queue
  908. $newtext .= $tagqueue;
  909. // Add Remaining text
  910. $newtext .= $text;
  911. // Empty Stack
  912. while($x = array_pop($tagstack)) {
  913. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  914. }
  915. // WP fix for the bug with HTML comments
  916. $newtext = str_replace("< !--","<!--",$newtext);
  917. $newtext = str_replace("< !--","< !--",$newtext);
  918. return $newtext;
  919. }
  920. /**
  921. * Acts on text which is about to be edited.
  922. *
  923. * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
  924. * filter. If $richedit is set true htmlspecialchars() will be run on the
  925. * content, converting special characters to HTMl entities.
  926. *
  927. * @since 0.71
  928. *
  929. * @param string $content The text about to be edited.
  930. * @param bool $richedit Whether or not the $content should pass through htmlspecialchars(). Default false.
  931. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  932. */
  933. function format_to_edit($content, $richedit = false) {
  934. $content = apply_filters('format_to_edit', $content);
  935. if (! $richedit )
  936. $content = htmlspecialchars($content);
  937. return $content;
  938. }
  939. /**
  940. * Holder for the 'format_to_post' filter.
  941. *
  942. * @since 0.71
  943. *
  944. * @param string $content The text to pass through the filter.
  945. * @return string Text returned from the 'format_to_post' filter.
  946. */
  947. function format_to_post($content) {
  948. $content = apply_filters('format_to_post', $content);
  949. return $content;
  950. }
  951. /**
  952. * Add leading zeros when necessary.
  953. *
  954. * If you set the threshold to '4' and the number is '10', then you will get
  955. * back '0010'. If you set the number to '4' and the number is '5000', then you
  956. * will get back '5000'.
  957. *
  958. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  959. * and the size of the number. If the number is large enough, then no zeros will
  960. * be appended.
  961. *
  962. * @since 0.71
  963. *
  964. * @param mixed $number Number to append zeros to if not greater than threshold.
  965. * @param int $threshold Digit places number needs to be to not have zeros added.
  966. * @return string Adds leading zeros to number if needed.
  967. */
  968. function zeroise($number, $threshold) {
  969. return sprintf('%0'.$threshold.'s', $number);
  970. }
  971. /**
  972. * Adds backslashes before letters and before a number at the start of a string.
  973. *
  974. * @since 0.71
  975. *
  976. * @param string $string Value to which backslashes will be added.
  977. * @return string String with backslashes inserted.
  978. */
  979. function backslashit($string) {
  980. $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
  981. $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
  982. return $string;
  983. }
  984. /**
  985. * Appends a trailing slash.
  986. *
  987. * Will remove trailing slash if it exists already before adding a trailing
  988. * slash. This prevents double slashing a string or path.
  989. *
  990. * The primary use of this is for paths and thus should be used for paths. It is
  991. * not restricted to paths and offers no specific path support.
  992. *
  993. * @since 1.2.0
  994. * @uses untrailingslashit() Unslashes string if it was slashed already.
  995. *
  996. * @param string $string What to add the trailing slash to.
  997. * @return string String with trailing slash added.
  998. */
  999. function trailingslashit($string) {
  1000. return untrailingslashit($string) . '/';
  1001. }
  1002. /**
  1003. * Removes trailing slash if it exists.
  1004. *
  1005. * The primary use of this is for paths and thus should be used for paths. It is
  1006. * not restricted to paths and offers no specific path support.
  1007. *
  1008. * @since 2.2.0
  1009. *
  1010. * @param string $string What to remove the trailing slash from.
  1011. * @return string String without the trailing slash.
  1012. */
  1013. function untrailingslashit($string) {
  1014. return rtrim($string, '/');
  1015. }
  1016. /**
  1017. * Adds slashes to escape strings.
  1018. *
  1019. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  1020. * http://www.php.net/magic_quotes} for more details.
  1021. *
  1022. * @since 0.71
  1023. *
  1024. * @param string $gpc The string returned from HTTP request data.
  1025. * @return string Returns a string escaped with slashes.
  1026. */
  1027. function addslashes_gpc($gpc) {
  1028. global $wpdb;
  1029. if (get_magic_quotes_gpc()) {
  1030. $gpc = stripslashes($gpc);
  1031. }
  1032. return $wpdb->escape($gpc);
  1033. }
  1034. /**
  1035. * Navigates through an array and removes slashes from the values.
  1036. *
  1037. * If an array is passed, the array_map() function causes a callback to pass the
  1038. * value back to the function. The slashes from this value will removed.
  1039. *
  1040. * @since 2.0.0
  1041. *
  1042. * @param array|string $value The array or string to be striped.
  1043. * @return array|string Stripped array (or string in the callback).
  1044. */
  1045. function stripslashes_deep($value) {
  1046. $value = is_array($value) ? array_map('stripslashes_deep', $value) : stripslashes($value);
  1047. return $value;
  1048. }
  1049. /**
  1050. * Navigates through an array and encodes the values to be used in a URL.
  1051. *
  1052. * Uses a callback to pass the value of the array back to the function as a
  1053. * string.
  1054. *
  1055. * @since 2.2.0
  1056. *
  1057. * @param array|string $value The array or string to be encoded.
  1058. * @return array|string $value The encoded array (or string from the callback).
  1059. */
  1060. function urlencode_deep($value) {
  1061. $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
  1062. return $value;
  1063. }
  1064. /**
  1065. * Converts email addresses characters to HTML entities to block spam bots.
  1066. *
  1067. * @since 0.71
  1068. *
  1069. * @param string $emailaddy Email address.
  1070. * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
  1071. * @return string Converted email address.
  1072. */
  1073. function antispambot($emailaddy, $mailto=0) {
  1074. $emailNOSPAMaddy = '';
  1075. srand ((float) microtime() * 1000000);
  1076. for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
  1077. $j = floor(rand(0, 1+$mailto));
  1078. if ($j==0) {
  1079. $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
  1080. } elseif ($j==1) {
  1081. $emailNOSPAMaddy .= substr($emailaddy,$i,1);
  1082. } elseif ($j==2) {
  1083. $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
  1084. }
  1085. }
  1086. $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
  1087. return $emailNOSPAMaddy;
  1088. }
  1089. /**
  1090. * Callback to convert URI match to HTML A element.
  1091. *
  1092. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1093. * make_clickable()}.
  1094. *
  1095. * @since 2.3.2
  1096. * @access private
  1097. *
  1098. * @param array $matches Single Regex Match.
  1099. * @return string HTML A element with URI address.
  1100. */
  1101. function _make_url_clickable_cb($matches) {
  1102. $url = $matches[2];
  1103. $url = esc_url($url);
  1104. if ( empty($url) )
  1105. return $matches[0];
  1106. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>";
  1107. }
  1108. /**
  1109. * Callback to convert URL match to HTML A element.
  1110. *
  1111. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1112. * make_clickable()}.
  1113. *
  1114. * @since 2.3.2
  1115. * @access private
  1116. *
  1117. * @param array $matches Single Regex Match.
  1118. * @return string HTML A element with URL address.
  1119. */
  1120. function _make_web_ftp_clickable_cb($matches) {
  1121. $ret = '';
  1122. $dest = $matches[2];
  1123. $dest = 'http://' . $dest;
  1124. $dest = esc_url($dest);
  1125. if ( empty($dest) )
  1126. return $matches[0];
  1127. // removed trailing [,;:] from URL
  1128. if ( in_array(substr($dest, -1), array('.', ',', ';', ':')) === true ) {
  1129. $ret = substr($dest, -1);
  1130. $dest = substr($dest, 0, strlen($dest)-1);
  1131. }
  1132. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>" . $ret;
  1133. }
  1134. /**
  1135. * Callback to convert email address match to HTML A element.
  1136. *
  1137. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1138. * make_clickable()}.
  1139. *
  1140. * @since 2.3.2
  1141. * @access private
  1142. *
  1143. * @param array $matches Single Regex Match.
  1144. * @return string HTML A element with email address.
  1145. */
  1146. function _make_email_clickable_cb($matches) {
  1147. $email = $matches[2] . '@' . $matches[3];
  1148. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  1149. }
  1150. /**
  1151. * Convert plaintext URI to HTML links.
  1152. *
  1153. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  1154. * within links.
  1155. *
  1156. * @since 0.71
  1157. *
  1158. * @param string $ret Content to convert URIs.
  1159. * @return string Content with converted URIs.
  1160. */
  1161. function make_clickable($ret) {
  1162. $ret = ' ' . $ret;
  1163. // in testing, using arrays here was found to be faster
  1164. $ret = preg_replace_callback('#(?<=[\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#$%&~/\-=?@\[\](+]|[.,;:](?![\s<])|(?(1)\)(?![\s<])|\)))+)#is', '_make_url_clickable_cb', $ret);
  1165. $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
  1166. $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  1167. // this one is not in an array because we need it to run last, for cleanup of accidental links within links
  1168. $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
  1169. $ret = trim($ret);
  1170. return $ret;
  1171. }
  1172. /**
  1173. * Adds rel nofollow string to all HTML A elements in content.
  1174. *
  1175. * @since 1.5.0
  1176. *
  1177. * @param string $text Content that may contain HTML A elements.
  1178. * @return string Converted content.
  1179. */
  1180. function wp_rel_nofollow( $text ) {
  1181. global $wpdb;
  1182. // This is a pre save filter, so text is already escaped.
  1183. $text = stripslashes($text);
  1184. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  1185. $text = $wpdb->escape($text);
  1186. return $text;
  1187. }
  1188. /**
  1189. * Callback to used to add rel=nofollow string to HTML A element.
  1190. *
  1191. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  1192. * string to prevent from invalidating (X)HTML.
  1193. *
  1194. * @since 2.3.0
  1195. *
  1196. * @param array $matches Single Match
  1197. * @return string HTML A Element with rel nofollow.
  1198. */
  1199. function wp_rel_nofollow_callback( $matches ) {
  1200. $text = $matches[1];
  1201. $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
  1202. return "<a $text rel=\"nofollow\">";
  1203. }
  1204. /**
  1205. * Convert one smiley code to the icon graphic file equivalent.
  1206. *
  1207. * Looks up one smiley code in the $wpsmiliestrans global array and returns an
  1208. * <img> string for that smiley.
  1209. *
  1210. * @global array $wpsmiliestrans
  1211. * @since 2.8.0
  1212. *
  1213. * @param string $smiley Smiley code to convert to image.
  1214. * @return string Image string for smiley.
  1215. */
  1216. function translate_smiley($smiley) {
  1217. global $wpsmiliestrans;
  1218. if (count($smiley) == 0) {
  1219. return '';
  1220. }
  1221. $siteurl = get_option( 'siteurl' );
  1222. $smiley = trim(reset($smiley));
  1223. $img = $wpsmiliestrans[$smiley];
  1224. $smiley_masked = esc_attr($smiley);
  1225. return " <img src='$siteurl/wp-includes/images/smilies/$img' alt='$smiley_masked' class='wp-smiley' /> ";
  1226. }
  1227. /**
  1228. * Convert text equivalent of smilies to images.
  1229. *
  1230. * Will only convert smilies if the option 'use_smilies' is true and the global
  1231. * used in the function isn't empty.
  1232. *
  1233. * @since 0.71
  1234. * @uses $wp_smiliessearch
  1235. *
  1236. * @param string $text Content to convert smilies from text.
  1237. * @return string Converted content with text smilies replaced with images.
  1238. */
  1239. function convert_smilies($text) {
  1240. global $wp_smiliessearch;
  1241. $output = '';
  1242. if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) {
  1243. // HTML loop taken from texturize function, could possible be consolidated
  1244. $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between
  1245. $stop = count($textarr);// loop stuff
  1246. for ($i = 0; $i < $stop; $i++) {
  1247. $content = $textarr[$i];
  1248. if ((strlen($content) > 0) && ('<' != $content{0})) { // If it's not a tag
  1249. $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content);
  1250. }
  1251. $output .= $content;
  1252. }
  1253. } else {
  1254. // return default text.
  1255. $output = $text;
  1256. }
  1257. return $output;
  1258. }
  1259. /**
  1260. * Verifies that an email is valid.
  1261. *
  1262. * Does not grok i18n domains. Not RFC compliant.
  1263. *
  1264. * @since 0.71
  1265. *
  1266. * @param string $email Email address to verify.
  1267. * @param boolean $check_dns Whether to check the DNS for the domain using checkdnsrr().
  1268. * @return string|bool Either false or the valid email address.
  1269. */
  1270. function is_email( $email, $check_dns = false ) {
  1271. // Test for the minimum length the email can be
  1272. if ( strlen( $email ) < 3 ) {
  1273. return apply_filters( 'is_email', false, $email, 'email_too_short' );
  1274. }
  1275. // Test for an @ character after the first position
  1276. if ( strpos( $email, '@', 1 ) === false ) {
  1277. return apply_filters( 'is_email', false, $email, 'email_no_at' );
  1278. }
  1279. // Split out the local and domain parts
  1280. list( $local, $domain ) = explode( '@', $email, 2 );
  1281. // LOCAL PART
  1282. // Test for invalid characters
  1283. if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
  1284. return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
  1285. }
  1286. // DOMAIN PART
  1287. // Test for sequences of periods
  1288. if ( preg_match( '/\.{2,}/', $domain ) ) {
  1289. return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
  1290. }
  1291. // Test for leading and trailing periods and whitespace
  1292. if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
  1293. return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
  1294. }
  1295. // Split the domain into subs
  1296. $subs = explode( '.', $domain );
  1297. // Assume the domain will have at least two subs
  1298. if ( 2 > count( $subs ) ) {
  1299. return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
  1300. }
  1301. // Loop through each sub
  1302. foreach ( $subs as $sub ) {
  1303. // Test for leading and trailing hyphens and whitespace
  1304. if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
  1305. return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
  1306. }
  1307. // Test for invalid characters
  1308. if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
  1309. return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
  1310. }
  1311. }
  1312. // DNS
  1313. // Check the domain has a valid MX and A …

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