PageRenderTime 71ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/formatting.php

https://github.com/acadambi/WordPress
PHP | 3934 lines | 2291 code | 324 blank | 1319 comment | 325 complexity | c579bbeb83e2d0e4af6034b7bdd6aa3c MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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. * @param bool $reset Set to true for unit testing. Translated patterns will reset.
  27. * @return string The string replaced with html entities
  28. */
  29. function wptexturize($text, $reset = false) {
  30. global $wp_cockneyreplace;
  31. static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements,
  32. $default_no_texturize_tags, $default_no_texturize_shortcodes, $run_texturize = true;
  33. // If there's nothing to do, just stop.
  34. if ( empty( $text ) || false === $run_texturize ) {
  35. return $text;
  36. }
  37. // Set up static variables. Run once only.
  38. if ( $reset || ! isset( $static_characters ) ) {
  39. /**
  40. * Filter whether to skip running `wptexturize()`.
  41. *
  42. * Passing false to the filter will effectively short-circuit `wptexturize()`.
  43. * returning the original text passed to the function instead.
  44. *
  45. * The filter runs only once, the first time `wptexturize()` is called.
  46. *
  47. * @since 4.0.0
  48. *
  49. * @param bool $run_texturize Whether to short-circuit `wptexturize()`.
  50. */
  51. $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
  52. if ( false === $run_texturize ) {
  53. return $text;
  54. }
  55. /* translators: opening curly double quote */
  56. $opening_quote = _x( '&#8220;', 'opening curly double quote' );
  57. /* translators: closing curly double quote */
  58. $closing_quote = _x( '&#8221;', 'closing curly double quote' );
  59. /* translators: apostrophe, for example in 'cause or can't */
  60. $apos = _x( '&#8217;', 'apostrophe' );
  61. /* translators: prime, for example in 9' (nine feet) */
  62. $prime = _x( '&#8242;', 'prime' );
  63. /* translators: double prime, for example in 9" (nine inches) */
  64. $double_prime = _x( '&#8243;', 'double prime' );
  65. /* translators: opening curly single quote */
  66. $opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
  67. /* translators: closing curly single quote */
  68. $closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
  69. /* translators: en dash */
  70. $en_dash = _x( '&#8211;', 'en dash' );
  71. /* translators: em dash */
  72. $em_dash = _x( '&#8212;', 'em dash' );
  73. $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
  74. $default_no_texturize_shortcodes = array('code');
  75. // if a plugin has provided an autocorrect array, use it
  76. if ( isset($wp_cockneyreplace) ) {
  77. $cockney = array_keys($wp_cockneyreplace);
  78. $cockneyreplace = array_values($wp_cockneyreplace);
  79. } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement.
  80. $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" );
  81. $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" );
  82. } else {
  83. $cockney = $cockneyreplace = array();
  84. }
  85. $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
  86. $static_replacements = array_merge( array( '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
  87. $spaces = wp_spaces_regexp();
  88. // Pattern-based replacements of characters.
  89. $dynamic = array();
  90. // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
  91. if ( "'" !== $apos || "'" !== $closing_single_quote ) {
  92. $dynamic[ '/\'(\d\d)\'(?=\Z|[.,)}>\-\]]|' . $spaces . ')/' ] = $apos . '$1' . $closing_single_quote;
  93. }
  94. if ( "'" !== $apos || '"' !== $closing_quote ) {
  95. $dynamic[ '/\'(\d\d)"(?=\Z|[.,)}>\-\]]|' . $spaces . ')/' ] = $apos . '$1' . $closing_quote;
  96. }
  97. // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
  98. if ( "'" !== $apos ) {
  99. $dynamic[ '/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/' ] = $apos;
  100. }
  101. // Quoted Numbers like "42" or '42.00'
  102. if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
  103. $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $opening_quote . '$1' . $closing_quote;
  104. }
  105. if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
  106. $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $opening_single_quote . '$1' . $closing_single_quote;
  107. }
  108. // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
  109. if ( "'" !== $opening_single_quote ) {
  110. $dynamic[ '/(?<=\A|[([{<"\-]|' . $spaces . ')\'/' ] = $opening_single_quote;
  111. }
  112. // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
  113. if ( "'" !== $apos ) {
  114. $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;"\'(){}<>[\]\-]|' . $spaces . ')/' ] = $apos;
  115. }
  116. // 9" (double prime)
  117. if ( '"' !== $double_prime ) {
  118. $dynamic[ '/(?<=\d)"/' ] = $double_prime;
  119. }
  120. // 9' (prime)
  121. if ( "'" !== $prime ) {
  122. $dynamic[ '/(?<=\d)\'/' ] = $prime;
  123. }
  124. // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
  125. if ( '"' !== $opening_quote ) {
  126. $dynamic[ '/(?<=\A|[([{<\-]|' . $spaces . ')"(?!' . $spaces . ')/' ] = $opening_quote;
  127. }
  128. // Any remaining double quotes.
  129. if ( '"' !== $closing_quote ) {
  130. $dynamic[ '/"/' ] = $closing_quote;
  131. }
  132. // Single quotes followed by spaces or ending punctuation.
  133. if ( "'" !== $closing_single_quote ) {
  134. $dynamic[ '/\'(?=\Z|[.,)}>\-\]]|' . $spaces . ')/' ] = $closing_single_quote;
  135. }
  136. // Dashes and spaces
  137. $dynamic[ '/---/' ] = $em_dash;
  138. $dynamic[ '/(?<=' . $spaces . ')--(?=' . $spaces . ')/' ] = $em_dash;
  139. $dynamic[ '/(?<!xn)--/' ] = $en_dash;
  140. $dynamic[ '/(?<=' . $spaces . ')-(?=' . $spaces . ')/' ] = $en_dash;
  141. $dynamic_characters = array_keys( $dynamic );
  142. $dynamic_replacements = array_values( $dynamic );
  143. }
  144. // Transform into regexp sub-expression used in _wptexturize_pushpop_element
  145. // Must do this every time in case plugins use these filters in a context sensitive manner
  146. /**
  147. * Filter the list of HTML elements not to texturize.
  148. *
  149. * @since 2.8.0
  150. *
  151. * @param array $default_no_texturize_tags An array of HTML element names.
  152. */
  153. $no_texturize_tags = '(' . implode( '|', apply_filters( 'no_texturize_tags', $default_no_texturize_tags ) ) . ')';
  154. /**
  155. * Filter the list of shortcodes not to texturize.
  156. *
  157. * @since 2.8.0
  158. *
  159. * @param array $default_no_texturize_shortcodes An array of shortcode names.
  160. */
  161. $no_texturize_shortcodes = '(' . implode( '|', apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes ) ) . ')';
  162. $no_texturize_tags_stack = array();
  163. $no_texturize_shortcodes_stack = array();
  164. // Look for shortcodes and HTML elements.
  165. $regex = '/(' // Capture the entire match.
  166. . '<' // Find start of element.
  167. . '(?(?=!--)' // Is this a comment?
  168. . '.+?--\s*>' // Find end of comment
  169. . '|'
  170. . '.+?>' // Find end of element
  171. . ')'
  172. . '|'
  173. . '\[' // Find start of shortcode.
  174. . '\[?' // Shortcodes may begin with [[
  175. . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes or HTML elements.
  176. . '\]' // Find end of shortcode.
  177. . '\]?' // Shortcodes may end with ]]
  178. . ')/s';
  179. $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  180. foreach ( $textarr as &$curl ) {
  181. // Only call _wptexturize_pushpop_element if $curl is a delimeter.
  182. $first = $curl[0];
  183. if ( '<' === $first && '>' === substr( $curl, -1 ) ) {
  184. // This is an HTML delimeter.
  185. if ( '<!--' !== substr( $curl, 0, 4 ) ) {
  186. _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>' );
  187. }
  188. } elseif ( '[' === $first && 1 === preg_match( '/^\[[^\[\]<>]+\]$/', $curl ) ) {
  189. // This is a shortcode delimeter.
  190. _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']' );
  191. } elseif ( '[' === $first && 1 === preg_match( '/^\[\[?[^\[\]<>]+\]\]?$/', $curl ) ) {
  192. // This is an escaped shortcode delimeter.
  193. // Do not texturize.
  194. // Do not push to the shortcodes stack.
  195. } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
  196. // This is neither a delimeter, nor is this content inside of no_texturize pairs. Do texturize.
  197. $curl = str_replace($static_characters, $static_replacements, $curl);
  198. $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
  199. // 9x9 (times), but never 0x9999
  200. if ( 1 === preg_match( '/(?<=\d)x-?\d/', $text ) ) {
  201. // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
  202. $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(-?\d[\d\.,]*)\b/', '$1&#215;$2', $curl );
  203. }
  204. }
  205. // Replace each & with &#038; unless it already looks like an entity.
  206. $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
  207. }
  208. return implode( '', $textarr );
  209. }
  210. /**
  211. * Search for disabled element tags. Push element to stack on tag open and pop
  212. * on tag close. Assumes first character of $text is tag opening.
  213. *
  214. * @since 2.9.0
  215. * @access private
  216. *
  217. * @param string $text Text to check. First character is assumed to be $opening
  218. * @param array $stack Array used as stack of opened tag elements
  219. * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
  220. * @param string $opening Tag opening character, assumed to be 1 character long
  221. * @param string $closing Tag closing character
  222. */
  223. function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
  224. // Check if it is a closing tag -- otherwise assume opening tag
  225. if (strncmp($opening . '/', $text, 2)) {
  226. // Opening? Check $text+1 against disabled elements
  227. if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
  228. /*
  229. * This disables texturize until we find a closing tag of our type
  230. * (e.g. <pre>) even if there was invalid nesting before that
  231. *
  232. * Example: in the case <pre>sadsadasd</code>"baba"</pre>
  233. * "baba" won't be texturize
  234. */
  235. array_push($stack, $matches[1]);
  236. }
  237. } elseif ( 0 == count( $stack ) ) {
  238. // Stack is empty. Just stop.
  239. } else {
  240. // Closing? Check $text+2 against disabled elements
  241. $c = preg_quote($closing, '/');
  242. if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
  243. $last = array_pop($stack);
  244. // Make sure it matches the opening tag
  245. if ( $last != $matches[1] ) {
  246. array_push( $stack, $last );
  247. }
  248. }
  249. }
  250. }
  251. /**
  252. * Replaces double line-breaks with paragraph elements.
  253. *
  254. * A group of regex replaces used to identify text formatted with newlines and
  255. * replace double line-breaks with HTML paragraph tags. The remaining
  256. * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
  257. * or 'false'.
  258. *
  259. * @since 0.71
  260. *
  261. * @param string $pee The text which has to be formatted.
  262. * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
  263. * @return string Text which has been converted into correct paragraph tags.
  264. */
  265. function wpautop($pee, $br = true) {
  266. $pre_tags = array();
  267. if ( trim($pee) === '' )
  268. return '';
  269. $pee = $pee . "\n"; // just to make things a little easier, pad the end
  270. if ( strpos($pee, '<pre') !== false ) {
  271. $pee_parts = explode( '</pre>', $pee );
  272. $last_pee = array_pop($pee_parts);
  273. $pee = '';
  274. $i = 0;
  275. foreach ( $pee_parts as $pee_part ) {
  276. $start = strpos($pee_part, '<pre');
  277. // Malformed html?
  278. if ( $start === false ) {
  279. $pee .= $pee_part;
  280. continue;
  281. }
  282. $name = "<pre wp-pre-tag-$i></pre>";
  283. $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>';
  284. $pee .= substr( $pee_part, 0, $start ) . $name;
  285. $i++;
  286. }
  287. $pee .= $last_pee;
  288. }
  289. $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
  290. // Space things out a little
  291. $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|legend|section|article|aside|hgroup|header|footer|nav|figure|details|menu|summary)';
  292. $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
  293. $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
  294. $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
  295. if ( strpos( $pee, '</object>' ) !== false ) {
  296. // no P/BR around param and embed
  297. $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
  298. $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
  299. $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
  300. }
  301. if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
  302. // no P/BR around source and track
  303. $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
  304. $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
  305. $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
  306. }
  307. $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
  308. // make paragraphs, including one at the end
  309. $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
  310. $pee = '';
  311. foreach ( $pees as $tinkle ) {
  312. $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
  313. }
  314. $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
  315. $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
  316. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
  317. $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
  318. $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
  319. $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
  320. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
  321. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
  322. if ( $br ) {
  323. $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
  324. $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
  325. $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
  326. }
  327. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
  328. $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
  329. $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
  330. if ( !empty($pre_tags) )
  331. $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee);
  332. return $pee;
  333. }
  334. /**
  335. * Newline preservation help function for wpautop
  336. *
  337. * @since 3.1.0
  338. * @access private
  339. *
  340. * @param array $matches preg_replace_callback matches array
  341. * @return string
  342. */
  343. function _autop_newline_preservation_helper( $matches ) {
  344. return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
  345. }
  346. /**
  347. * Don't auto-p wrap shortcodes that stand alone
  348. *
  349. * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
  350. *
  351. * @since 2.9.0
  352. *
  353. * @param string $pee The content.
  354. * @return string The filtered content.
  355. */
  356. function shortcode_unautop( $pee ) {
  357. global $shortcode_tags;
  358. if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) {
  359. return $pee;
  360. }
  361. $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
  362. $spaces = wp_spaces_regexp();
  363. $pattern =
  364. '/'
  365. . '<p>' // Opening paragraph
  366. . '(?:' . $spaces . ')*+' // Optional leading whitespace
  367. . '(' // 1: The shortcode
  368. . '\\[' // Opening bracket
  369. . "($tagregexp)" // 2: Shortcode name
  370. . '(?![\\w-])' // Not followed by word character or hyphen
  371. // Unroll the loop: Inside the opening shortcode tag
  372. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  373. . '(?:'
  374. . '\\/(?!\\])' // A forward slash not followed by a closing bracket
  375. . '[^\\]\\/]*' // Not a closing bracket or forward slash
  376. . ')*?'
  377. . '(?:'
  378. . '\\/\\]' // Self closing tag and closing bracket
  379. . '|'
  380. . '\\]' // Closing bracket
  381. . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags
  382. . '[^\\[]*+' // Not an opening bracket
  383. . '(?:'
  384. . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag
  385. . '[^\\[]*+' // Not an opening bracket
  386. . ')*+'
  387. . '\\[\\/\\2\\]' // Closing shortcode tag
  388. . ')?'
  389. . ')'
  390. . ')'
  391. . '(?:' . $spaces . ')*+' // optional trailing whitespace
  392. . '<\\/p>' // closing paragraph
  393. . '/s';
  394. return preg_replace( $pattern, '$1', $pee );
  395. }
  396. /**
  397. * Checks to see if a string is utf8 encoded.
  398. *
  399. * NOTE: This function checks for 5-Byte sequences, UTF8
  400. * has Bytes Sequences with a maximum length of 4.
  401. *
  402. * @author bmorel at ssi dot fr (modified)
  403. * @since 1.2.1
  404. *
  405. * @param string $str The string to be checked
  406. * @return bool True if $str fits a UTF-8 model, false otherwise.
  407. */
  408. function seems_utf8($str) {
  409. $length = strlen($str);
  410. for ($i=0; $i < $length; $i++) {
  411. $c = ord($str[$i]);
  412. if ($c < 0x80) $n = 0; # 0bbbbbbb
  413. elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
  414. elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
  415. elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
  416. elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
  417. elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
  418. else return false; # Does not match any model
  419. for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
  420. if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
  421. return false;
  422. }
  423. }
  424. return true;
  425. }
  426. /**
  427. * Converts a number of special characters into their HTML entities.
  428. *
  429. * Specifically deals with: &, <, >, ", and '.
  430. *
  431. * $quote_style can be set to ENT_COMPAT to encode " to
  432. * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
  433. *
  434. * @since 1.2.2
  435. * @access private
  436. *
  437. * @param string $string The text which is to be encoded.
  438. * @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.
  439. * @param string $charset Optional. The character encoding of the string. Default is false.
  440. * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
  441. * @return string The encoded text with HTML entities.
  442. */
  443. function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
  444. $string = (string) $string;
  445. if ( 0 === strlen( $string ) )
  446. return '';
  447. // Don't bother if there are no specialchars - saves some processing
  448. if ( ! preg_match( '/[&<>"\']/', $string ) )
  449. return $string;
  450. // Account for the previous behaviour of the function when the $quote_style is not an accepted value
  451. if ( empty( $quote_style ) )
  452. $quote_style = ENT_NOQUOTES;
  453. elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) )
  454. $quote_style = ENT_QUOTES;
  455. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
  456. if ( ! $charset ) {
  457. static $_charset;
  458. if ( ! isset( $_charset ) ) {
  459. $alloptions = wp_load_alloptions();
  460. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  461. }
  462. $charset = $_charset;
  463. }
  464. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) )
  465. $charset = 'UTF-8';
  466. $_quote_style = $quote_style;
  467. if ( $quote_style === 'double' ) {
  468. $quote_style = ENT_COMPAT;
  469. $_quote_style = ENT_COMPAT;
  470. } elseif ( $quote_style === 'single' ) {
  471. $quote_style = ENT_NOQUOTES;
  472. }
  473. // Handle double encoding ourselves
  474. if ( $double_encode ) {
  475. $string = @htmlspecialchars( $string, $quote_style, $charset );
  476. } else {
  477. // Decode &amp; into &
  478. $string = wp_specialchars_decode( $string, $_quote_style );
  479. // Guarantee every &entity; is valid or re-encode the &
  480. $string = wp_kses_normalize_entities( $string );
  481. // Now re-encode everything except &entity;
  482. $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE );
  483. for ( $i = 0; $i < count( $string ); $i += 2 )
  484. $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset );
  485. $string = implode( '', $string );
  486. }
  487. // Backwards compatibility
  488. if ( 'single' === $_quote_style )
  489. $string = str_replace( "'", '&#039;', $string );
  490. return $string;
  491. }
  492. /**
  493. * Converts a number of HTML entities into their special characters.
  494. *
  495. * Specifically deals with: &, <, >, ", and '.
  496. *
  497. * $quote_style can be set to ENT_COMPAT to decode " entities,
  498. * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
  499. *
  500. * @since 2.8.0
  501. *
  502. * @param string $string The text which is to be decoded.
  503. * @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.
  504. * @return string The decoded text without HTML entities.
  505. */
  506. function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
  507. $string = (string) $string;
  508. if ( 0 === strlen( $string ) ) {
  509. return '';
  510. }
  511. // Don't bother if there are no entities - saves a lot of processing
  512. if ( strpos( $string, '&' ) === false ) {
  513. return $string;
  514. }
  515. // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
  516. if ( empty( $quote_style ) ) {
  517. $quote_style = ENT_NOQUOTES;
  518. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  519. $quote_style = ENT_QUOTES;
  520. }
  521. // More complete than get_html_translation_table( HTML_SPECIALCHARS )
  522. $single = array( '&#039;' => '\'', '&#x27;' => '\'' );
  523. $single_preg = array( '/&#0*39;/' => '&#039;', '/&#x0*27;/i' => '&#x27;' );
  524. $double = array( '&quot;' => '"', '&#034;' => '"', '&#x22;' => '"' );
  525. $double_preg = array( '/&#0*34;/' => '&#034;', '/&#x0*22;/i' => '&#x22;' );
  526. $others = array( '&lt;' => '<', '&#060;' => '<', '&gt;' => '>', '&#062;' => '>', '&amp;' => '&', '&#038;' => '&', '&#x26;' => '&' );
  527. $others_preg = array( '/&#0*60;/' => '&#060;', '/&#0*62;/' => '&#062;', '/&#0*38;/' => '&#038;', '/&#x0*26;/i' => '&#x26;' );
  528. if ( $quote_style === ENT_QUOTES ) {
  529. $translation = array_merge( $single, $double, $others );
  530. $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
  531. } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
  532. $translation = array_merge( $double, $others );
  533. $translation_preg = array_merge( $double_preg, $others_preg );
  534. } elseif ( $quote_style === 'single' ) {
  535. $translation = array_merge( $single, $others );
  536. $translation_preg = array_merge( $single_preg, $others_preg );
  537. } elseif ( $quote_style === ENT_NOQUOTES ) {
  538. $translation = $others;
  539. $translation_preg = $others_preg;
  540. }
  541. // Remove zero padding on numeric entities
  542. $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
  543. // Replace characters according to translation table
  544. return strtr( $string, $translation );
  545. }
  546. /**
  547. * Checks for invalid UTF8 in a string.
  548. *
  549. * @since 2.8.0
  550. *
  551. * @param string $string The text which is to be checked.
  552. * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
  553. * @return string The checked text.
  554. */
  555. function wp_check_invalid_utf8( $string, $strip = false ) {
  556. $string = (string) $string;
  557. if ( 0 === strlen( $string ) ) {
  558. return '';
  559. }
  560. // Store the site charset as a static to avoid multiple calls to get_option()
  561. static $is_utf8;
  562. if ( !isset( $is_utf8 ) ) {
  563. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
  564. }
  565. if ( !$is_utf8 ) {
  566. return $string;
  567. }
  568. // Check for support for utf8 in the installed PCRE library once and store the result in a static
  569. static $utf8_pcre;
  570. if ( !isset( $utf8_pcre ) ) {
  571. $utf8_pcre = @preg_match( '/^./u', 'a' );
  572. }
  573. // We can't demand utf8 in the PCRE installation, so just return the string in those cases
  574. if ( !$utf8_pcre ) {
  575. return $string;
  576. }
  577. // preg_match fails when it encounters invalid UTF8 in $string
  578. if ( 1 === @preg_match( '/^./us', $string ) ) {
  579. return $string;
  580. }
  581. // Attempt to strip the bad chars if requested (not recommended)
  582. if ( $strip && function_exists( 'iconv' ) ) {
  583. return iconv( 'utf-8', 'utf-8', $string );
  584. }
  585. return '';
  586. }
  587. /**
  588. * Encode the Unicode values to be used in the URI.
  589. *
  590. * @since 1.5.0
  591. *
  592. * @param string $utf8_string
  593. * @param int $length Max length of the string
  594. * @return string String with Unicode encoded for URI.
  595. */
  596. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  597. $unicode = '';
  598. $values = array();
  599. $num_octets = 1;
  600. $unicode_length = 0;
  601. $string_length = strlen( $utf8_string );
  602. for ($i = 0; $i < $string_length; $i++ ) {
  603. $value = ord( $utf8_string[ $i ] );
  604. if ( $value < 128 ) {
  605. if ( $length && ( $unicode_length >= $length ) )
  606. break;
  607. $unicode .= chr($value);
  608. $unicode_length++;
  609. } else {
  610. if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
  611. $values[] = $value;
  612. if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
  613. break;
  614. if ( count( $values ) == $num_octets ) {
  615. if ($num_octets == 3) {
  616. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
  617. $unicode_length += 9;
  618. } else {
  619. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
  620. $unicode_length += 6;
  621. }
  622. $values = array();
  623. $num_octets = 1;
  624. }
  625. }
  626. }
  627. return $unicode;
  628. }
  629. /**
  630. * Converts all accent characters to ASCII characters.
  631. *
  632. * If there are no accent characters, then the string given is just returned.
  633. *
  634. * @since 1.2.1
  635. *
  636. * @param string $string Text that might have accent characters
  637. * @return string Filtered string with replaced "nice" characters.
  638. */
  639. function remove_accents($string) {
  640. if ( !preg_match('/[\x80-\xff]/', $string) )
  641. return $string;
  642. if (seems_utf8($string)) {
  643. $chars = array(
  644. // Decompositions for Latin-1 Supplement
  645. chr(194).chr(170) => 'a', chr(194).chr(186) => 'o',
  646. chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
  647. chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
  648. chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
  649. chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
  650. chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
  651. chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
  652. chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
  653. chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
  654. chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
  655. chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
  656. chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
  657. chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
  658. chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
  659. chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
  660. chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
  661. chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
  662. chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
  663. chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
  664. chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
  665. chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
  666. chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
  667. chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
  668. chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
  669. chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
  670. chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
  671. chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
  672. chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
  673. chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
  674. chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
  675. chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
  676. chr(195).chr(191) => 'y', chr(195).chr(152) => 'O',
  677. // Decompositions for Latin Extended-A
  678. chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
  679. chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
  680. chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
  681. chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
  682. chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
  683. chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
  684. chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
  685. chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
  686. chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
  687. chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
  688. chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
  689. chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
  690. chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
  691. chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
  692. chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
  693. chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
  694. chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
  695. chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
  696. chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
  697. chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
  698. chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
  699. chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
  700. chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
  701. chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
  702. chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
  703. chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
  704. chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
  705. chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
  706. chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
  707. chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
  708. chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
  709. chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
  710. chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
  711. chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
  712. chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
  713. chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
  714. chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
  715. chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
  716. chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
  717. chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
  718. chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
  719. chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
  720. chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
  721. chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
  722. chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
  723. chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
  724. chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
  725. chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
  726. chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
  727. chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
  728. chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
  729. chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
  730. chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
  731. chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
  732. chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
  733. chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
  734. chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
  735. chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
  736. chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
  737. chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
  738. chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
  739. chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
  740. chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
  741. chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
  742. // Decompositions for Latin Extended-B
  743. chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
  744. chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
  745. // Euro Sign
  746. chr(226).chr(130).chr(172) => 'E',
  747. // GBP (Pound) Sign
  748. chr(194).chr(163) => '',
  749. // Vowels with diacritic (Vietnamese)
  750. // unmarked
  751. chr(198).chr(160) => 'O', chr(198).chr(161) => 'o',
  752. chr(198).chr(175) => 'U', chr(198).chr(176) => 'u',
  753. // grave accent
  754. chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a',
  755. chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a',
  756. chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e',
  757. chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o',
  758. chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o',
  759. chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u',
  760. chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y',
  761. // hook
  762. chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a',
  763. chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a',
  764. chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a',
  765. chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e',
  766. chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e',
  767. chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i',
  768. chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o',
  769. chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o',
  770. chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o',
  771. chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u',
  772. chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u',
  773. chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y',
  774. // tilde
  775. chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a',
  776. chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a',
  777. chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e',
  778. chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e',
  779. chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o',
  780. chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o',
  781. chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u',
  782. chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y',
  783. // acute accent
  784. chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a',
  785. chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a',
  786. chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e',
  787. chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o',
  788. chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o',
  789. chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u',
  790. // dot below
  791. chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a',
  792. chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a',
  793. chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a',
  794. chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e',
  795. chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e',
  796. chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i',
  797. chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o',
  798. chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o',
  799. chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o',
  800. chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u',
  801. chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u',
  802. chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y',
  803. // Vowels with diacritic (Chinese, Hanyu Pinyin)
  804. chr(201).chr(145) => 'a',
  805. // macron
  806. chr(199).chr(149) => 'U', chr(199).chr(150) => 'u',
  807. // acute accent
  808. chr(199).chr(151) => 'U', chr(199).chr(152) => 'u',
  809. // caron
  810. chr(199).chr(141) => 'A', chr(199).chr(142) => 'a',
  811. chr(199).chr(143) => 'I', chr(199).chr(144) => 'i',
  812. chr(199).chr(145) => 'O', chr(199).chr(146) => 'o',
  813. chr(199).chr(147) => 'U', chr(199).chr(148) => 'u',
  814. chr(199).chr(153) => 'U', chr(199).chr(154) => 'u',
  815. // grave accent
  816. chr(199).chr(155) => 'U', chr(199).chr(156) => 'u',
  817. );
  818. // Used for locale-specific rules
  819. $locale = get_locale();
  820. if ( 'de_DE' == $locale ) {
  821. $chars[ chr(195).chr(132) ] = 'Ae';
  822. $chars[ chr(195).chr(164) ] = 'ae';
  823. $chars[ chr(195).chr(150) ] = 'Oe';
  824. $chars[ chr(195).chr(182) ] = 'oe';
  825. $chars[ chr(195).chr(156) ] = 'Ue';
  826. $chars[ chr(195).chr(188) ] = 'ue';
  827. $chars[ chr(195).chr(159) ] = 'ss';
  828. } elseif ( 'da_DK' === $locale ) {
  829. $chars[ chr(195).chr(134) ] = 'Ae';
  830. $chars[ chr(195).chr(166) ] = 'ae';
  831. $chars[ chr(195).chr(152) ] = 'Oe';
  832. $chars[ chr(195).chr(184) ] = 'oe';
  833. $chars[ chr(195).chr(133) ] = 'Aa';
  834. $chars[ chr(195).chr(165) ] = 'aa';
  835. }
  836. $string = strtr($string, $chars);
  837. } else {
  838. // Assume ISO-8859-1 if not UTF-8
  839. $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
  840. .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
  841. .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
  842. .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
  843. .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
  844. .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
  845. .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
  846. .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
  847. .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
  848. .chr(252).chr(253).chr(255);
  849. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  850. $string = strtr($string, $chars['in'], $chars['out']);
  851. $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
  852. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  853. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  854. }
  855. return $string;
  856. }
  857. /**
  858. * Sanitizes a filename, replacing whitespace with dashes.
  859. *
  860. * Removes special characters that are illegal in filenames on certain
  861. * operating systems and special characters requiring special escaping
  862. * to manipulate at the command line. Replaces spaces and consecutive
  863. * dashes with a single dash. Trims period, dash and underscore from beginning
  864. * and end of filename.
  865. *
  866. * @since 2.1.0
  867. *
  868. * @param string $filename The filename to be sanitized
  869. * @return string The sanitized filename
  870. */
  871. function sanitize_file_name( $filename ) {
  872. $filename_raw = $filename;
  873. $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
  874. /**
  875. * Filter the list of characters to remove from a filename.
  876. *
  877. * @since 2.8.0
  878. *
  879. * @param array $special_chars Characters to remove.
  880. * @param string $filename_raw Filename as it was passed into sanitize_file_name().
  881. */
  882. $special_chars = apply_filters( 'sanitize_file_name_chars', $special_chars, $filename_raw );
  883. $filename = preg_replace( "#\x{00a0}#siu", ' ', $filename );
  884. $filename = str_replace($special_chars, '', $filename);
  885. $filename = preg_replace('/[\s-]+/', '-', $filename);
  886. $filename = trim($filename, '.-_');
  887. // Split the filename into a base and extension[s]
  888. $parts = explode('.', $filename);
  889. // Return if only one extension
  890. if ( count( $parts ) <= 2 ) {
  891. /**
  892. * Filter a sanitized filename string.
  893. *
  894. * @since 2.8.0
  895. *
  896. * @param string $filename Sanitized filename.
  897. * @param string $filename_raw The filename prior to sanitization.
  898. */
  899. return apply_filters( 'sanitize_file_name', $filename, $filename_raw );
  900. }
  901. // Process multiple extensions
  902. $filename = array_shift($parts);
  903. $extension = array_pop($parts);
  904. $mimes = get_allowed_mime_types();
  905. /*
  906. * Loop over any intermediate extensions. Postfix them with a trailing underscore
  907. * if they are a 2 - 5 character long alpha string not in the extension whitelist.
  908. */
  909. foreach ( (array) $parts as $part) {
  910. $filename .= '.' . $part;
  911. if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
  912. $allowed = false;
  913. foreach ( $mimes as $ext_preg => $mime_match ) {
  914. $ext_preg = '!^(' . $ext_preg . ')$!i';
  915. if ( preg_match( $ext_preg, $part ) ) {
  916. $allowed = true;
  917. break;
  918. }
  919. }
  920. if ( !$allowed )
  921. $filename .= '_';
  922. }
  923. }
  924. $filename .= '.' . $extension;
  925. /** This filter is documented in wp-includes/formatting.php */
  926. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  927. }
  928. /**
  929. * Sanitizes a username, stripping out unsafe characters.
  930. *
  931. * Removes tags, octets, entities, and if strict is enabled, will only keep
  932. * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
  933. * raw username (the username in the parameter), and the value of $strict as
  934. * parameters for the 'sanitize_user' filter.
  935. *
  936. * @since 2.0.0
  937. *
  938. * @param string $username The username to be sanitized.
  939. * @param bool $strict If set limits $username to specific characters. Default false.
  940. * @return string The sanitized username, after passing through filters.
  941. */
  942. function sanitize_user( $username, $strict = false ) {
  943. $raw_username = $username;
  944. $username = wp_strip_all_tags( $username );
  945. $username = remove_accents( $username );
  946. // Kill octets
  947. $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
  948. $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
  949. // If strict, reduce to ASCII for max portability.
  950. if ( $strict )
  951. $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
  952. $username = trim( $username );
  953. // Consolidate contiguous whitespace
  954. $username = preg_replace( '|\s+|', ' ', $username );
  955. /**
  956. * Filter a sanitized username string.
  957. *
  958. * @since 2.0.1
  959. *
  960. * @param string $username Sanitized username.
  961. * @param string $raw_username The username prior to sanitization.
  962. * @param bool $strict Whether to limit the sanitization to specific characters. Default false.
  963. */
  964. return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
  965. }
  966. /**
  967. * Sanitizes a string key.
  968. *
  969. * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
  970. *
  971. * @since 3.0.0
  972. *
  973. * @param string $key String key
  974. * @return string Sanitized key
  975. */
  976. function sanitize_key( $key ) {
  977. $raw_key = $key;
  978. $key = strtolower( $key );
  979. $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
  980. /**
  981. * Filter a sanitized key string.
  982. *
  983. * @since 3.0.0
  984. *
  985. * @param string $key Sanitized key.
  986. * @param string $raw_key The key prior to sanitization.
  987. */
  988. return apply_filters( 'sanitize_key', $key, $raw_key );
  989. }
  990. /**
  991. * Sanitizes a title, or returns a fallback title.
  992. *
  993. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  994. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  995. * will be used.
  996. *
  997. * @since 1.0.0
  998. *
  999. * @param string $title The string to be sanitized.
  1000. * @param string $fallback_title Optional. A title to use if $title is empty.
  1001. * @param string $context Optional. The operation for which the string is sanitized
  1002. * @return string The sanitized string.
  1003. */
  1004. function sanitize_title( $title, $fallback_title = '', $context = 'save' ) {
  1005. $raw_title = $title;
  1006. if ( 'save' == $context )
  1007. $title = remove_accents($title);
  1008. /**
  1009. * Filter a sanitized title string.
  1010. *
  1011. * @since 1.2.0
  1012. *
  1013. * @param string $title Sanitized title.
  1014. * @param string $raw_title The title prior to sanitization.
  1015. * @param string $context The context for which the title is being sanitized.
  1016. */
  1017. $title = apply_filters( 'sanitize_title', $title, $raw_title, $context );
  1018. if ( '' === $title || false === $title )
  1019. $title = $fallback_title;
  1020. return $title;
  1021. }
  1022. /**
  1023. * Sanitizes a title with the 'query' context.
  1024. *
  1025. * Used for querying the database for a value from URL.
  1026. *
  1027. * @since 3.1.0
  1028. * @uses sanitize_title()
  1029. *
  1030. * @param string $title The string to be sanitized.
  1031. * @return string The sanitized string.
  1032. */
  1033. function sanitize_title_for_query( $title ) {
  1034. return sanitize_title( $title, '', 'query' );
  1035. }
  1036. /**
  1037. * Sanitizes a title, replacing whitespace and a few other characters with dashes.
  1038. *
  1039. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  1040. * Whitespace becomes a dash.
  1041. *
  1042. * @since 1.2.0
  1043. *
  1044. * @param string $title The title to be sanitized.
  1045. * @param string $raw_title Optional. Not used.
  1046. * @param string $context Optional. The operation for which the string is sanitized.
  1047. * @return string The sanitized title.
  1048. */
  1049. function sanitize_title_with_dashes( $title, $raw_title = '', $context = 'display' ) {
  1050. $title = strip_tags($title);
  1051. // Preserve escaped octets.
  1052. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  1053. // Remove percent signs that are not part of an octet.
  1054. $title = str_replace('%', '', $title);
  1055. // Restore octets.
  1056. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  1057. if (seems_utf8($title)) {
  1058. if (function_exists('mb_strtolower')) {
  1059. $title = mb_strtolower($title, 'UTF-8');
  1060. }
  1061. $title = utf8_uri_encode($title, 200);
  1062. }
  1063. $title = strtolower($title);
  1064. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  1065. $title = str_replace('.', '-', $title);
  1066. if ( 'save' == $context ) {
  1067. // Convert nbsp, ndash and mdash to hyphens
  1068. $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title );
  1069. // Strip these characters entirely
  1070. $title = str_replace( array(
  1071. // iexcl and iquest
  1072. '%c2%a1', '%c2%bf',
  1073. // angle quotes
  1074. '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba',
  1075. // curly quotes
  1076. '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d',
  1077. '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f',
  1078. // copy, reg, deg, hellip and trade
  1079. '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2',
  1080. // acute accents
  1081. '%c2%b4', '%cb%8a', '%cc%81', '%cd%81',
  1082. // grave accent, macron, caron
  1083. '%cc%80', '%cc%84', '%cc%8c',
  1084. ), '', $title );
  1085. // Convert times to x
  1086. $title = str_replace( '%c3%97', 'x', $title );
  1087. }
  1088. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  1089. $title = preg_replace('/\s+/', '-', $title);
  1090. $title = preg_replace('|-+|', '-', $title);
  1091. $title = trim($title, '-');
  1092. return $title;
  1093. }
  1094. /**
  1095. * Ensures a string is a valid SQL order by clause.
  1096. *
  1097. * Accepts one or more columns, with or without ASC/DESC, and also accepts
  1098. * RAND().
  1099. *
  1100. * @since 2.5.1
  1101. *
  1102. * @param string $orderby Order by string to be checked.
  1103. * @return string|bool Returns the order by clause if it is a match, false otherwise.
  1104. */
  1105. function sanitize_sql_orderby( $orderby ){
  1106. preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
  1107. if ( !$obmatches )
  1108. return false;
  1109. return $orderby;
  1110. }
  1111. /**
  1112. * Sanitizes an HTML classname to ensure it only contains valid characters.
  1113. *
  1114. * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
  1115. * string then it will return the alternative value supplied.
  1116. *
  1117. * @todo Expand to support the full range of CDATA that a class attribute can contain.
  1118. *
  1119. * @since 2.8.0
  1120. *
  1121. * @param string $class The classname to be sanitized
  1122. * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
  1123. * Defaults to an empty string.
  1124. * @return string The sanitized value
  1125. */
  1126. function sanitize_html_class( $class, $fallback = '' ) {
  1127. //Strip out any % encoded octets
  1128. $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
  1129. //Limit to A-Z,a-z,0-9,_,-
  1130. $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
  1131. if ( '' == $sanitized )
  1132. $sanitized = $fallback;
  1133. /**
  1134. * Filter a sanitized HTML class string.
  1135. *
  1136. * @since 2.8.0
  1137. *
  1138. * @param string $sanitized The sanitized HTML class.
  1139. * @param string $class HTML class before sanitization.
  1140. * @param string $fallback The fallback string.
  1141. */
  1142. return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
  1143. }
  1144. /**
  1145. * Converts a number of characters from a string.
  1146. *
  1147. * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
  1148. * converted into correct XHTML and Unicode characters are converted to the
  1149. * valid range.
  1150. *
  1151. * @since 0.71
  1152. *
  1153. * @param string $content String of characters to be converted.
  1154. * @param string $deprecated Not used.
  1155. * @return string Converted string.
  1156. */
  1157. function convert_chars($content, $deprecated = '') {
  1158. if ( !empty( $deprecated ) )
  1159. _deprecated_argument( __FUNCTION__, '0.71' );
  1160. // Translation of invalid Unicode references range to valid range
  1161. $wp_htmltranswinuni = array(
  1162. '&#128;' => '&#8364;', // the Euro sign
  1163. '&#129;' => '',
  1164. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  1165. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  1166. '&#132;' => '&#8222;',
  1167. '&#133;' => '&#8230;',
  1168. '&#134;' => '&#8224;',
  1169. '&#135;' => '&#8225;',
  1170. '&#136;' => '&#710;',
  1171. '&#137;' => '&#8240;',
  1172. '&#138;' => '&#352;',
  1173. '&#139;' => '&#8249;',
  1174. '&#140;' => '&#338;',
  1175. '&#141;' => '',
  1176. '&#142;' => '&#381;',
  1177. '&#143;' => '',
  1178. '&#144;' => '',
  1179. '&#145;' => '&#8216;',
  1180. '&#146;' => '&#8217;',
  1181. '&#147;' => '&#8220;',
  1182. '&#148;' => '&#8221;',
  1183. '&#149;' => '&#8226;',
  1184. '&#150;' => '&#8211;',
  1185. '&#151;' => '&#8212;',
  1186. '&#152;' => '&#732;',
  1187. '&#153;' => '&#8482;',
  1188. '&#154;' => '&#353;',
  1189. '&#155;' => '&#8250;',
  1190. '&#156;' => '&#339;',
  1191. '&#157;' => '',
  1192. '&#158;' => '&#382;',
  1193. '&#159;' => '&#376;'
  1194. );
  1195. // Remove metadata tags
  1196. $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
  1197. $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
  1198. // Converts lone & characters into &#38; (a.k.a. &amp;)
  1199. $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
  1200. // Fix Word pasting
  1201. $content = strtr($content, $wp_htmltranswinuni);
  1202. // Just a little XHTML help
  1203. $content = str_replace('<br>', '<br />', $content);
  1204. $content = str_replace('<hr>', '<hr />', $content);
  1205. return $content;
  1206. }
  1207. /**
  1208. * Balances tags if forced to, or if the 'use_balanceTags' option is set to true.
  1209. *
  1210. * @since 0.71
  1211. *
  1212. * @param string $text Text to be balanced
  1213. * @param bool $force If true, forces balancing, ignoring the value of the option. Default false.
  1214. * @return string Balanced text
  1215. */
  1216. function balanceTags( $text, $force = false ) {
  1217. if ( $force || get_option('use_balanceTags') == 1 ) {
  1218. return force_balance_tags( $text );
  1219. } else {
  1220. return $text;
  1221. }
  1222. }
  1223. /**
  1224. * Balances tags of string using a modified stack.
  1225. *
  1226. * @since 2.0.4
  1227. *
  1228. * @author Leonard Lin <leonard@acm.org>
  1229. * @license GPL
  1230. * @copyright November 4, 2001
  1231. * @version 1.1
  1232. * @todo Make better - change loop condition to $text in 1.2
  1233. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  1234. * 1.1 Fixed handling of append/stack pop order of end text
  1235. * Added Cleaning Hooks
  1236. * 1.0 First Version
  1237. *
  1238. * @param string $text Text to be balanced.
  1239. * @return string Balanced text.
  1240. */
  1241. function force_balance_tags( $text ) {
  1242. $tagstack = array();
  1243. $stacksize = 0;
  1244. $tagqueue = '';
  1245. $newtext = '';
  1246. // Known single-entity/self-closing tags
  1247. $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' );
  1248. // Tags that can be immediately nested within themselves
  1249. $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' );
  1250. // WP bug fix for comments - in case you REALLY meant to type '< !--'
  1251. $text = str_replace('< !--', '< !--', $text);
  1252. // WP bug fix for LOVE <3 (and other situations with '<' before a number)
  1253. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  1254. while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
  1255. $newtext .= $tagqueue;
  1256. $i = strpos($text, $regex[0]);
  1257. $l = strlen($regex[0]);
  1258. // clear the shifter
  1259. $tagqueue = '';
  1260. // Pop or Push
  1261. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  1262. $tag = strtolower(substr($regex[1],1));
  1263. // if too many closing tags
  1264. if( $stacksize <= 0 ) {
  1265. $tag = '';
  1266. // or close to be safe $tag = '/' . $tag;
  1267. }
  1268. // if stacktop value = tag close value then pop
  1269. else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
  1270. $tag = '</' . $tag . '>'; // Close Tag
  1271. // Pop
  1272. array_pop( $tagstack );
  1273. $stacksize--;
  1274. } else { // closing tag not at top, search for it
  1275. for ( $j = $stacksize-1; $j >= 0; $j-- ) {
  1276. if ( $tagstack[$j] == $tag ) {
  1277. // add tag to tagqueue
  1278. for ( $k = $stacksize-1; $k >= $j; $k--) {
  1279. $tagqueue .= '</' . array_pop( $tagstack ) . '>';
  1280. $stacksize--;
  1281. }
  1282. break;
  1283. }
  1284. }
  1285. $tag = '';
  1286. }
  1287. } else { // Begin Tag
  1288. $tag = strtolower($regex[1]);
  1289. // Tag Cleaning
  1290. // If it's an empty tag "< >", do nothing
  1291. if ( '' == $tag ) {
  1292. // do nothing
  1293. }
  1294. // ElseIf it presents itself as a self-closing tag...
  1295. elseif ( substr( $regex[2], -1 ) == '/' ) {
  1296. // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and
  1297. // immediately close it with a closing tag (the tag will encapsulate no text as a result)
  1298. if ( ! in_array( $tag, $single_tags ) )
  1299. $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag";
  1300. }
  1301. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  1302. elseif ( in_array($tag, $single_tags) ) {
  1303. $regex[2] .= '/';
  1304. }
  1305. // Else it's not a single-entity tag
  1306. else {
  1307. // If the top of the stack is the same as the tag we want to push, close previous tag
  1308. if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
  1309. $tagqueue = '</' . array_pop( $tagstack ) . '>';
  1310. $stacksize--;
  1311. }
  1312. $stacksize = array_push( $tagstack, $tag );
  1313. }
  1314. // Attributes
  1315. $attributes = $regex[2];
  1316. if( ! empty( $attributes ) && $attributes[0] != '>' )
  1317. $attributes = ' ' . $attributes;
  1318. $tag = '<' . $tag . $attributes . '>';
  1319. //If already queuing a close tag, then put this tag on, too
  1320. if ( !empty($tagqueue) ) {
  1321. $tagqueue .= $tag;
  1322. $tag = '';
  1323. }
  1324. }
  1325. $newtext .= substr($text, 0, $i) . $tag;
  1326. $text = substr($text, $i + $l);
  1327. }
  1328. // Clear Tag Queue
  1329. $newtext .= $tagqueue;
  1330. // Add Remaining text
  1331. $newtext .= $text;
  1332. // Empty Stack
  1333. while( $x = array_pop($tagstack) )
  1334. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  1335. // WP fix for the bug with HTML comments
  1336. $newtext = str_replace("< !--","<!--",$newtext);
  1337. $newtext = str_replace("< !--","< !--",$newtext);
  1338. return $newtext;
  1339. }
  1340. /**
  1341. * Acts on text which is about to be edited.
  1342. *
  1343. * The $content is run through esc_textarea(), which uses htmlspecialchars()
  1344. * to convert special characters to HTML entities. If $richedit is set to true,
  1345. * it is simply a holder for the 'format_to_edit' filter.
  1346. *
  1347. * @since 0.71
  1348. *
  1349. * @param string $content The text about to be edited.
  1350. * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed).
  1351. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  1352. */
  1353. function format_to_edit( $content, $richedit = false ) {
  1354. /**
  1355. * Filter the text to be formatted for editing.
  1356. *
  1357. * @since 1.2.0
  1358. *
  1359. * @param string $content The text, prior to formatting for editing.
  1360. */
  1361. $content = apply_filters( 'format_to_edit', $content );
  1362. if ( ! $richedit )
  1363. $content = esc_textarea( $content );
  1364. return $content;
  1365. }
  1366. /**
  1367. * Add leading zeros when necessary.
  1368. *
  1369. * If you set the threshold to '4' and the number is '10', then you will get
  1370. * back '0010'. If you set the threshold to '4' and the number is '5000', then you
  1371. * will get back '5000'.
  1372. *
  1373. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  1374. * and the size of the number. If the number is large enough, then no zeros will
  1375. * be appended.
  1376. *
  1377. * @since 0.71
  1378. *
  1379. * @param mixed $number Number to append zeros to if not greater than threshold.
  1380. * @param int $threshold Digit places number needs to be to not have zeros added.
  1381. * @return string Adds leading zeros to number if needed.
  1382. */
  1383. function zeroise($number, $threshold) {
  1384. return sprintf('%0'.$threshold.'s', $number);
  1385. }
  1386. /**
  1387. * Adds backslashes before letters and before a number at the start of a string.
  1388. *
  1389. * @since 0.71
  1390. *
  1391. * @param string $string Value to which backslashes will be added.
  1392. * @return string String with backslashes inserted.
  1393. */
  1394. function backslashit($string) {
  1395. if ( isset( $string[0] ) && $string[0] >= '0' && $string[0] <= '9' )
  1396. $string = '\\\\' . $string;
  1397. return addcslashes( $string, 'A..Za..z' );
  1398. }
  1399. /**
  1400. * Appends a trailing slash.
  1401. *
  1402. * Will remove trailing forward and backslashes if it exists already before adding
  1403. * a trailing forward slash. This prevents double slashing a string or path.
  1404. *
  1405. * The primary use of this is for paths and thus should be used for paths. It is
  1406. * not restricted to paths and offers no specific path support.
  1407. *
  1408. * @since 1.2.0
  1409. *
  1410. * @param string $string What to add the trailing slash to.
  1411. * @return string String with trailing slash added.
  1412. */
  1413. function trailingslashit( $string ) {
  1414. return untrailingslashit( $string ) . '/';
  1415. }
  1416. /**
  1417. * Removes trailing forward slashes and backslashes if they exist.
  1418. *
  1419. * The primary use of this is for paths and thus should be used for paths. It is
  1420. * not restricted to paths and offers no specific path support.
  1421. *
  1422. * @since 2.2.0
  1423. *
  1424. * @param string $string What to remove the trailing slashes from.
  1425. * @return string String without the trailing slashes.
  1426. */
  1427. function untrailingslashit( $string ) {
  1428. return rtrim( $string, '/\\' );
  1429. }
  1430. /**
  1431. * Adds slashes to escape strings.
  1432. *
  1433. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  1434. * http://www.php.net/magic_quotes} for more details.
  1435. *
  1436. * @since 0.71
  1437. *
  1438. * @param string $gpc The string returned from HTTP request data.
  1439. * @return string Returns a string escaped with slashes.
  1440. */
  1441. function addslashes_gpc($gpc) {
  1442. if ( get_magic_quotes_gpc() )
  1443. $gpc = stripslashes($gpc);
  1444. return wp_slash($gpc);
  1445. }
  1446. /**
  1447. * Navigates through an array and removes slashes from the values.
  1448. *
  1449. * If an array is passed, the array_map() function causes a callback to pass the
  1450. * value back to the function. The slashes from this value will removed.
  1451. *
  1452. * @since 2.0.0
  1453. *
  1454. * @param mixed $value The value to be stripped.
  1455. * @return mixed Stripped value.
  1456. */
  1457. function stripslashes_deep($value) {
  1458. if ( is_array($value) ) {
  1459. $value = array_map('stripslashes_deep', $value);
  1460. } elseif ( is_object($value) ) {
  1461. $vars = get_object_vars( $value );
  1462. foreach ($vars as $key=>$data) {
  1463. $value->{$key} = stripslashes_deep( $data );
  1464. }
  1465. } elseif ( is_string( $value ) ) {
  1466. $value = stripslashes($value);
  1467. }
  1468. return $value;
  1469. }
  1470. /**
  1471. * Navigates through an array and encodes the values to be used in a URL.
  1472. *
  1473. *
  1474. * @since 2.2.0
  1475. *
  1476. * @param array|string $value The array or string to be encoded.
  1477. * @return array|string $value The encoded array (or string from the callback).
  1478. */
  1479. function urlencode_deep($value) {
  1480. $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
  1481. return $value;
  1482. }
  1483. /**
  1484. * Navigates through an array and raw encodes the values to be used in a URL.
  1485. *
  1486. * @since 3.4.0
  1487. *
  1488. * @param array|string $value The array or string to be encoded.
  1489. * @return array|string $value The encoded array (or string from the callback).
  1490. */
  1491. function rawurlencode_deep( $value ) {
  1492. return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value );
  1493. }
  1494. /**
  1495. * Converts email addresses characters to HTML entities to block spam bots.
  1496. *
  1497. * @since 0.71
  1498. *
  1499. * @param string $email_address Email address.
  1500. * @param int $hex_encoding Optional. Set to 1 to enable hex encoding.
  1501. * @return string Converted email address.
  1502. */
  1503. function antispambot( $email_address, $hex_encoding = 0 ) {
  1504. $email_no_spam_address = '';
  1505. for ( $i = 0; $i < strlen( $email_address ); $i++ ) {
  1506. $j = rand( 0, 1 + $hex_encoding );
  1507. if ( $j == 0 ) {
  1508. $email_no_spam_address .= '&#' . ord( $email_address[$i] ) . ';';
  1509. } elseif ( $j == 1 ) {
  1510. $email_no_spam_address .= $email_address[$i];
  1511. } elseif ( $j == 2 ) {
  1512. $email_no_spam_address .= '%' . zeroise( dechex( ord( $email_address[$i] ) ), 2 );
  1513. }
  1514. }
  1515. $email_no_spam_address = str_replace( '@', '&#64;', $email_no_spam_address );
  1516. return $email_no_spam_address;
  1517. }
  1518. /**
  1519. * Callback to convert URI match to HTML A element.
  1520. *
  1521. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1522. * make_clickable()}.
  1523. *
  1524. * @since 2.3.2
  1525. * @access private
  1526. *
  1527. * @param array $matches Single Regex Match.
  1528. * @return string HTML A element with URI address.
  1529. */
  1530. function _make_url_clickable_cb($matches) {
  1531. $url = $matches[2];
  1532. if ( ')' == $matches[3] && strpos( $url, '(' ) ) {
  1533. // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL.
  1534. // Then we can let the parenthesis balancer do its thing below.
  1535. $url .= $matches[3];
  1536. $suffix = '';
  1537. } else {
  1538. $suffix = $matches[3];
  1539. }
  1540. // Include parentheses in the URL only if paired
  1541. while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
  1542. $suffix = strrchr( $url, ')' ) . $suffix;
  1543. $url = substr( $url, 0, strrpos( $url, ')' ) );
  1544. }
  1545. $url = esc_url($url);
  1546. if ( empty($url) )
  1547. return $matches[0];
  1548. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
  1549. }
  1550. /**
  1551. * Callback to convert URL match to HTML A element.
  1552. *
  1553. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1554. * make_clickable()}.
  1555. *
  1556. * @since 2.3.2
  1557. * @access private
  1558. *
  1559. * @param array $matches Single Regex Match.
  1560. * @return string HTML A element with URL address.
  1561. */
  1562. function _make_web_ftp_clickable_cb($matches) {
  1563. $ret = '';
  1564. $dest = $matches[2];
  1565. $dest = 'http://' . $dest;
  1566. $dest = esc_url($dest);
  1567. if ( empty($dest) )
  1568. return $matches[0];
  1569. // removed trailing [.,;:)] from URL
  1570. if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
  1571. $ret = substr($dest, -1);
  1572. $dest = substr($dest, 0, strlen($dest)-1);
  1573. }
  1574. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  1575. }
  1576. /**
  1577. * Callback to convert email address match to HTML A element.
  1578. *
  1579. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1580. * make_clickable()}.
  1581. *
  1582. * @since 2.3.2
  1583. * @access private
  1584. *
  1585. * @param array $matches Single Regex Match.
  1586. * @return string HTML A element with email address.
  1587. */
  1588. function _make_email_clickable_cb($matches) {
  1589. $email = $matches[2] . '@' . $matches[3];
  1590. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  1591. }
  1592. /**
  1593. * Convert plaintext URI to HTML links.
  1594. *
  1595. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  1596. * within links.
  1597. *
  1598. * @since 0.71
  1599. *
  1600. * @param string $text Content to convert URIs.
  1601. * @return string Content with converted URIs.
  1602. */
  1603. function make_clickable( $text ) {
  1604. $r = '';
  1605. $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags
  1606. $nested_code_pre = 0; // Keep track of how many levels link is nested inside <pre> or <code>
  1607. foreach ( $textarr as $piece ) {
  1608. if ( preg_match( '|^<code[\s>]|i', $piece ) || preg_match( '|^<pre[\s>]|i', $piece ) )
  1609. $nested_code_pre++;
  1610. elseif ( ( '</code>' === strtolower( $piece ) || '</pre>' === strtolower( $piece ) ) && $nested_code_pre )
  1611. $nested_code_pre--;
  1612. if ( $nested_code_pre || empty( $piece ) || ( $piece[0] === '<' && ! preg_match( '|^<\s*[\w]{1,20}+://|', $piece ) ) ) {
  1613. $r .= $piece;
  1614. continue;
  1615. }
  1616. // Long strings might contain expensive edge cases ...
  1617. if ( 10000 < strlen( $piece ) ) {
  1618. // ... break it up
  1619. foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses
  1620. if ( 2101 < strlen( $chunk ) ) {
  1621. $r .= $chunk; // Too big, no whitespace: bail.
  1622. } else {
  1623. $r .= make_clickable( $chunk );
  1624. }
  1625. }
  1626. } else {
  1627. $ret = " $piece "; // Pad with whitespace to simplify the regexes
  1628. $url_clickable = '~
  1629. ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation
  1630. ( # 2: URL
  1631. [\\w]{1,20}+:// # Scheme and hier-part prefix
  1632. (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long
  1633. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character
  1634. (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character
  1635. [\'.,;:!?)] # Punctuation URL character
  1636. [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character
  1637. )*
  1638. )
  1639. (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing)
  1640. ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character.
  1641. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times.
  1642. $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret );
  1643. $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret );
  1644. $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret );
  1645. $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding.
  1646. $r .= $ret;
  1647. }
  1648. }
  1649. // Cleanup of accidental links within links
  1650. $r = preg_replace( '#(<a([ \r\n\t]+[^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r );
  1651. return $r;
  1652. }
  1653. /**
  1654. * Breaks a string into chunks by splitting at whitespace characters.
  1655. * The length of each returned chunk is as close to the specified length goal as possible,
  1656. * with the caveat that each chunk includes its trailing delimiter.
  1657. * Chunks longer than the goal are guaranteed to not have any inner whitespace.
  1658. *
  1659. * Joining the returned chunks with empty delimiters reconstructs the input string losslessly.
  1660. *
  1661. * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)
  1662. *
  1663. * <code>
  1664. * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) ==
  1665. * array (
  1666. * 0 => '1234 67890 ', // 11 characters: Perfect split
  1667. * 1 => '1234 ', // 5 characters: '1234 67890a' was too long
  1668. * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long
  1669. * 3 => '1234 890 ', // 11 characters: Perfect split
  1670. * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long
  1671. * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split
  1672. * 6 => ' 45678 ', // 11 characters: Perfect split
  1673. * 7 => '1 3 5 7 9', // 9 characters: End of $string
  1674. * );
  1675. * </code>
  1676. *
  1677. * @since 3.4.0
  1678. * @access private
  1679. *
  1680. * @param string $string The string to split.
  1681. * @param int $goal The desired chunk length.
  1682. * @return array Numeric array of chunks.
  1683. */
  1684. function _split_str_by_whitespace( $string, $goal ) {
  1685. $chunks = array();
  1686. $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" );
  1687. while ( $goal < strlen( $string_nullspace ) ) {
  1688. $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" );
  1689. if ( false === $pos ) {
  1690. $pos = strpos( $string_nullspace, "\000", $goal + 1 );
  1691. if ( false === $pos ) {
  1692. break;
  1693. }
  1694. }
  1695. $chunks[] = substr( $string, 0, $pos + 1 );
  1696. $string = substr( $string, $pos + 1 );
  1697. $string_nullspace = substr( $string_nullspace, $pos + 1 );
  1698. }
  1699. if ( $string ) {
  1700. $chunks[] = $string;
  1701. }
  1702. return $chunks;
  1703. }
  1704. /**
  1705. * Adds rel nofollow string to all HTML A elements in content.
  1706. *
  1707. * @since 1.5.0
  1708. *
  1709. * @param string $text Content that may contain HTML A elements.
  1710. * @return string Converted content.
  1711. */
  1712. function wp_rel_nofollow( $text ) {
  1713. // This is a pre save filter, so text is already escaped.
  1714. $text = stripslashes($text);
  1715. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  1716. $text = wp_slash($text);
  1717. return $text;
  1718. }
  1719. /**
  1720. * Callback to add rel=nofollow string to HTML A element.
  1721. *
  1722. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  1723. * string to prevent from invalidating (X)HTML.
  1724. *
  1725. * @since 2.3.0
  1726. *
  1727. * @param array $matches Single Match
  1728. * @return string HTML A Element with rel nofollow.
  1729. */
  1730. function wp_rel_nofollow_callback( $matches ) {
  1731. $text = $matches[1];
  1732. $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
  1733. return "<a $text rel=\"nofollow\">";
  1734. }
  1735. /**
  1736. * Convert one smiley code to the icon graphic file equivalent.
  1737. *
  1738. * Callback handler for {@link convert_smilies()}.
  1739. * Looks up one smiley code in the $wpsmiliestrans global array and returns an
  1740. * <img> string for that smiley.
  1741. *
  1742. * @global array $wpsmiliestrans
  1743. * @since 2.8.0
  1744. *
  1745. * @param array $matches Single match. Smiley code to convert to image.
  1746. * @return string Image string for smiley.
  1747. */
  1748. function translate_smiley( $matches ) {
  1749. global $wpsmiliestrans;
  1750. if ( count( $matches ) == 0 )
  1751. return '';
  1752. $smiley = trim( reset( $matches ) );
  1753. $img = $wpsmiliestrans[ $smiley ];
  1754. /**
  1755. * Filter the Smiley image URL before it's used in the image element.
  1756. *
  1757. * @since 2.9.0
  1758. *
  1759. * @param string $smiley_url URL for the smiley image.
  1760. * @param string $img Filename for the smiley image.
  1761. * @param string $site_url Site URL, as returned by site_url().
  1762. */
  1763. $src_url = apply_filters( 'smilies_src', includes_url( "images/smilies/$img" ), $img, site_url() );
  1764. return sprintf( '<img src="%s" alt="%s" class="wp-smiley" />', esc_url( $src_url ), esc_attr( $smiley ) );
  1765. }
  1766. /**
  1767. * Convert text equivalent of smilies to images.
  1768. *
  1769. * Will only convert smilies if the option 'use_smilies' is true and the global
  1770. * used in the function isn't empty.
  1771. *
  1772. * @since 0.71
  1773. * @uses $wp_smiliessearch
  1774. *
  1775. * @param string $text Content to convert smilies from text.
  1776. * @return string Converted content with text smilies replaced with images.
  1777. */
  1778. function convert_smilies( $text ) {
  1779. global $wp_smiliessearch;
  1780. $output = '';
  1781. if ( get_option( 'use_smilies' ) && ! empty( $wp_smiliessearch ) ) {
  1782. // HTML loop taken from texturize function, could possible be consolidated
  1783. $textarr = preg_split( '/(<.*>)/U', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // capture the tags as well as in between
  1784. $stop = count( $textarr );// loop stuff
  1785. // Ignore proessing of specific tags
  1786. $tags_to_ignore = 'code|pre|style|script|textarea';
  1787. $ignore_block_element = '';
  1788. for ( $i = 0; $i < $stop; $i++ ) {
  1789. $content = $textarr[$i];
  1790. // If we're in an ignore block, wait until we find its closing tag
  1791. if ( '' == $ignore_block_element && preg_match( '/^<(' . $tags_to_ignore . ')>/', $content, $matches ) ) {
  1792. $ignore_block_element = $matches[1];
  1793. }
  1794. // If it's not a tag and not in ignore block
  1795. if ( '' == $ignore_block_element && strlen( $content ) > 0 && '<' != $content[0] ) {
  1796. $content = preg_replace_callback( $wp_smiliessearch, 'translate_smiley', $content );
  1797. }
  1798. // did we exit ignore block
  1799. if ( '' != $ignore_block_element && '</' . $ignore_block_element . '>' == $content ) {
  1800. $ignore_block_element = '';
  1801. }
  1802. $output .= $content;
  1803. }
  1804. } else {
  1805. // return default text.
  1806. $output = $text;
  1807. }
  1808. return $output;
  1809. }
  1810. /**
  1811. * Verifies that an email is valid.
  1812. *
  1813. * Does not grok i18n domains. Not RFC compliant.
  1814. *
  1815. * @since 0.71
  1816. *
  1817. * @param string $email Email address to verify.
  1818. * @param boolean $deprecated Deprecated.
  1819. * @return string|bool Either false or the valid email address.
  1820. */
  1821. function is_email( $email, $deprecated = false ) {
  1822. if ( ! empty( $deprecated ) )
  1823. _deprecated_argument( __FUNCTION__, '3.0' );
  1824. // Test for the minimum length the email can be
  1825. if ( strlen( $email ) < 3 ) {
  1826. /**
  1827. * Filter whether an email address is valid.
  1828. *
  1829. * This filter is evaluated under several different contexts, such as 'email_too_short',
  1830. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  1831. * 'domain_no_periods', 'sub_hyphen_limits', 'sub_invalid_chars', or no specific context.
  1832. *
  1833. * @since 2.8.0
  1834. *
  1835. * @param bool $is_email Whether the email address has passed the is_email() checks. Default false.
  1836. * @param string $email The email address being checked.
  1837. * @param string $message An explanatory message to the user.
  1838. * @param string $context Context under which the email was tested.
  1839. */
  1840. return apply_filters( 'is_email', false, $email, 'email_too_short' );
  1841. }
  1842. // Test for an @ character after the first position
  1843. if ( strpos( $email, '@', 1 ) === false ) {
  1844. /** This filter is documented in wp-includes/formatting.php */
  1845. return apply_filters( 'is_email', false, $email, 'email_no_at' );
  1846. }
  1847. // Split out the local and domain parts
  1848. list( $local, $domain ) = explode( '@', $email, 2 );
  1849. // LOCAL PART
  1850. // Test for invalid characters
  1851. if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) {
  1852. /** This filter is documented in wp-includes/formatting.php */
  1853. return apply_filters( 'is_email', false, $email, 'local_invalid_chars' );
  1854. }
  1855. // DOMAIN PART
  1856. // Test for sequences of periods
  1857. if ( preg_match( '/\.{2,}/', $domain ) ) {
  1858. /** This filter is documented in wp-includes/formatting.php */
  1859. return apply_filters( 'is_email', false, $email, 'domain_period_sequence' );
  1860. }
  1861. // Test for leading and trailing periods and whitespace
  1862. if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) {
  1863. /** This filter is documented in wp-includes/formatting.php */
  1864. return apply_filters( 'is_email', false, $email, 'domain_period_limits' );
  1865. }
  1866. // Split the domain into subs
  1867. $subs = explode( '.', $domain );
  1868. // Assume the domain will have at least two subs
  1869. if ( 2 > count( $subs ) ) {
  1870. /** This filter is documented in wp-includes/formatting.php */
  1871. return apply_filters( 'is_email', false, $email, 'domain_no_periods' );
  1872. }
  1873. // Loop through each sub
  1874. foreach ( $subs as $sub ) {
  1875. // Test for leading and trailing hyphens and whitespace
  1876. if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) {
  1877. /** This filter is documented in wp-includes/formatting.php */
  1878. return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' );
  1879. }
  1880. // Test for invalid characters
  1881. if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) {
  1882. /** This filter is documented in wp-includes/formatting.php */
  1883. return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' );
  1884. }
  1885. }
  1886. // Congratulations your email made it!
  1887. /** This filter is documented in wp-includes/formatting.php */
  1888. return apply_filters( 'is_email', $email, $email, null );
  1889. }
  1890. /**
  1891. * Convert to ASCII from email subjects.
  1892. *
  1893. * @since 1.2.0
  1894. *
  1895. * @param string $string Subject line
  1896. * @return string Converted string to ASCII
  1897. */
  1898. function wp_iso_descrambler($string) {
  1899. /* this may only work with iso-8859-1, I'm afraid */
  1900. if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) {
  1901. return $string;
  1902. } else {
  1903. $subject = str_replace('_', ' ', $matches[2]);
  1904. $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject);
  1905. return $subject;
  1906. }
  1907. }
  1908. /**
  1909. * Helper function to convert hex encoded chars to ASCII
  1910. *
  1911. * @since 3.1.0
  1912. * @access private
  1913. *
  1914. * @param array $match The preg_replace_callback matches array
  1915. * @return array Converted chars
  1916. */
  1917. function _wp_iso_convert( $match ) {
  1918. return chr( hexdec( strtolower( $match[1] ) ) );
  1919. }
  1920. /**
  1921. * Returns a date in the GMT equivalent.
  1922. *
  1923. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  1924. * timezone_string available, the date is assumed to be in that timezone,
  1925. * otherwise it simply subtracts the value of the 'gmt_offset' option. Return
  1926. * format can be overridden using the $format parameter.
  1927. *
  1928. * @since 1.2.0
  1929. *
  1930. * @uses get_option() to retrieve the value of 'gmt_offset'.
  1931. * @param string $string The date to be converted.
  1932. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  1933. * @return string GMT version of the date provided.
  1934. */
  1935. function get_gmt_from_date( $string, $format = 'Y-m-d H:i:s' ) {
  1936. $tz = get_option( 'timezone_string' );
  1937. if ( $tz ) {
  1938. $datetime = date_create( $string, new DateTimeZone( $tz ) );
  1939. if ( ! $datetime )
  1940. return gmdate( $format, 0 );
  1941. $datetime->setTimezone( new DateTimeZone( 'UTC' ) );
  1942. $string_gmt = $datetime->format( $format );
  1943. } else {
  1944. if ( ! preg_match( '#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches ) )
  1945. return gmdate( $format, 0 );
  1946. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  1947. $string_gmt = gmdate( $format, $string_time - get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  1948. }
  1949. return $string_gmt;
  1950. }
  1951. /**
  1952. * Converts a GMT date into the correct format for the blog.
  1953. *
  1954. * Requires and returns a date in the Y-m-d H:i:s format. If there is a
  1955. * timezone_string available, the returned date is in that timezone, otherwise
  1956. * it simply adds the value of gmt_offset. Return format can be overridden
  1957. * using the $format parameter
  1958. *
  1959. * @since 1.2.0
  1960. *
  1961. * @param string $string The date to be converted.
  1962. * @param string $format The format string for the returned date (default is Y-m-d H:i:s)
  1963. * @return string Formatted date relative to the timezone / GMT offset.
  1964. */
  1965. function get_date_from_gmt( $string, $format = 'Y-m-d H:i:s' ) {
  1966. $tz = get_option( 'timezone_string' );
  1967. if ( $tz ) {
  1968. $datetime = date_create( $string, new DateTimeZone( 'UTC' ) );
  1969. if ( ! $datetime )
  1970. return date( $format, 0 );
  1971. $datetime->setTimezone( new DateTimeZone( $tz ) );
  1972. $string_localtime = $datetime->format( $format );
  1973. } else {
  1974. if ( ! preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches) )
  1975. return date( $format, 0 );
  1976. $string_time = gmmktime( $matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1] );
  1977. $string_localtime = gmdate( $format, $string_time + get_option( 'gmt_offset' ) * HOUR_IN_SECONDS );
  1978. }
  1979. return $string_localtime;
  1980. }
  1981. /**
  1982. * Computes an offset in seconds from an iso8601 timezone.
  1983. *
  1984. * @since 1.5.0
  1985. *
  1986. * @param string $timezone Either 'Z' for 0 offset or 'Âąhhmm'.
  1987. * @return int|float The offset in seconds.
  1988. */
  1989. function iso8601_timezone_to_offset($timezone) {
  1990. // $timezone is either 'Z' or '[+|-]hhmm'
  1991. if ($timezone == 'Z') {
  1992. $offset = 0;
  1993. } else {
  1994. $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1;
  1995. $hours = intval(substr($timezone, 1, 2));
  1996. $minutes = intval(substr($timezone, 3, 4)) / 60;
  1997. $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes);
  1998. }
  1999. return $offset;
  2000. }
  2001. /**
  2002. * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt].
  2003. *
  2004. * @since 1.5.0
  2005. *
  2006. * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}.
  2007. * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'.
  2008. * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s.
  2009. */
  2010. function iso8601_to_datetime($date_string, $timezone = 'user') {
  2011. $timezone = strtolower($timezone);
  2012. if ($timezone == 'gmt') {
  2013. preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits);
  2014. if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset
  2015. $offset = iso8601_timezone_to_offset($date_bits[7]);
  2016. } else { // we don't have a timezone, so we assume user local timezone (not server's!)
  2017. $offset = HOUR_IN_SECONDS * get_option('gmt_offset');
  2018. }
  2019. $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]);
  2020. $timestamp -= $offset;
  2021. return gmdate('Y-m-d H:i:s', $timestamp);
  2022. } else if ($timezone == 'user') {
  2023. return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string);
  2024. }
  2025. }
  2026. /**
  2027. * Adds a element attributes to open links in new windows.
  2028. *
  2029. * Comment text in popup windows should be filtered through this. Right now it's
  2030. * a moderately dumb function, ideally it would detect whether a target or rel
  2031. * attribute was already there and adjust its actions accordingly.
  2032. *
  2033. * @since 0.71
  2034. *
  2035. * @param string $text Content to replace links to open in a new window.
  2036. * @return string Content that has filtered links.
  2037. */
  2038. function popuplinks($text) {
  2039. $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text);
  2040. return $text;
  2041. }
  2042. /**
  2043. * Strips out all characters that are not allowable in an email.
  2044. *
  2045. * @since 1.5.0
  2046. *
  2047. * @param string $email Email address to filter.
  2048. * @return string Filtered email address.
  2049. */
  2050. function sanitize_email( $email ) {
  2051. // Test for the minimum length the email can be
  2052. if ( strlen( $email ) < 3 ) {
  2053. /**
  2054. * Filter a sanitized email address.
  2055. *
  2056. * This filter is evaluated under several contexts, including 'email_too_short',
  2057. * 'email_no_at', 'local_invalid_chars', 'domain_period_sequence', 'domain_period_limits',
  2058. * 'domain_no_periods', 'domain_no_valid_subs', or no context.
  2059. *
  2060. * @since 2.8.0
  2061. *
  2062. * @param string $email The sanitized email address.
  2063. * @param string $email The email address, as provided to sanitize_email().
  2064. * @param string $message A message to pass to the user.
  2065. */
  2066. return apply_filters( 'sanitize_email', '', $email, 'email_too_short' );
  2067. }
  2068. // Test for an @ character after the first position
  2069. if ( strpos( $email, '@', 1 ) === false ) {
  2070. /** This filter is documented in wp-includes/formatting.php */
  2071. return apply_filters( 'sanitize_email', '', $email, 'email_no_at' );
  2072. }
  2073. // Split out the local and domain parts
  2074. list( $local, $domain ) = explode( '@', $email, 2 );
  2075. // LOCAL PART
  2076. // Test for invalid characters
  2077. $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local );
  2078. if ( '' === $local ) {
  2079. /** This filter is documented in wp-includes/formatting.php */
  2080. return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' );
  2081. }
  2082. // DOMAIN PART
  2083. // Test for sequences of periods
  2084. $domain = preg_replace( '/\.{2,}/', '', $domain );
  2085. if ( '' === $domain ) {
  2086. /** This filter is documented in wp-includes/formatting.php */
  2087. return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' );
  2088. }
  2089. // Test for leading and trailing periods and whitespace
  2090. $domain = trim( $domain, " \t\n\r\0\x0B." );
  2091. if ( '' === $domain ) {
  2092. /** This filter is documented in wp-includes/formatting.php */
  2093. return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' );
  2094. }
  2095. // Split the domain into subs
  2096. $subs = explode( '.', $domain );
  2097. // Assume the domain will have at least two subs
  2098. if ( 2 > count( $subs ) ) {
  2099. /** This filter is documented in wp-includes/formatting.php */
  2100. return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' );
  2101. }
  2102. // Create an array that will contain valid subs
  2103. $new_subs = array();
  2104. // Loop through each sub
  2105. foreach ( $subs as $sub ) {
  2106. // Test for leading and trailing hyphens
  2107. $sub = trim( $sub, " \t\n\r\0\x0B-" );
  2108. // Test for invalid characters
  2109. $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub );
  2110. // If there's anything left, add it to the valid subs
  2111. if ( '' !== $sub ) {
  2112. $new_subs[] = $sub;
  2113. }
  2114. }
  2115. // If there aren't 2 or more valid subs
  2116. if ( 2 > count( $new_subs ) ) {
  2117. /** This filter is documented in wp-includes/formatting.php */
  2118. return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' );
  2119. }
  2120. // Join valid subs into the new domain
  2121. $domain = join( '.', $new_subs );
  2122. // Put the email back together
  2123. $email = $local . '@' . $domain;
  2124. // Congratulations your email made it!
  2125. /** This filter is documented in wp-includes/formatting.php */
  2126. return apply_filters( 'sanitize_email', $email, $email, null );
  2127. }
  2128. /**
  2129. * Determines the difference between two timestamps.
  2130. *
  2131. * The difference is returned in a human readable format such as "1 hour",
  2132. * "5 mins", "2 days".
  2133. *
  2134. * @since 1.5.0
  2135. *
  2136. * @param int $from Unix timestamp from which the difference begins.
  2137. * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set.
  2138. * @return string Human readable time difference.
  2139. */
  2140. function human_time_diff( $from, $to = '' ) {
  2141. if ( empty( $to ) ) {
  2142. $to = time();
  2143. }
  2144. $diff = (int) abs( $to - $from );
  2145. if ( $diff < HOUR_IN_SECONDS ) {
  2146. $mins = round( $diff / MINUTE_IN_SECONDS );
  2147. if ( $mins <= 1 )
  2148. $mins = 1;
  2149. /* translators: min=minute */
  2150. $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
  2151. } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
  2152. $hours = round( $diff / HOUR_IN_SECONDS );
  2153. if ( $hours <= 1 )
  2154. $hours = 1;
  2155. $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
  2156. } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
  2157. $days = round( $diff / DAY_IN_SECONDS );
  2158. if ( $days <= 1 )
  2159. $days = 1;
  2160. $since = sprintf( _n( '%s day', '%s days', $days ), $days );
  2161. } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
  2162. $weeks = round( $diff / WEEK_IN_SECONDS );
  2163. if ( $weeks <= 1 )
  2164. $weeks = 1;
  2165. $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
  2166. } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
  2167. $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
  2168. if ( $months <= 1 )
  2169. $months = 1;
  2170. $since = sprintf( _n( '%s month', '%s months', $months ), $months );
  2171. } elseif ( $diff >= YEAR_IN_SECONDS ) {
  2172. $years = round( $diff / YEAR_IN_SECONDS );
  2173. if ( $years <= 1 )
  2174. $years = 1;
  2175. $since = sprintf( _n( '%s year', '%s years', $years ), $years );
  2176. }
  2177. /**
  2178. * Filter the human readable difference between two timestamps.
  2179. *
  2180. * @since 4.0.0
  2181. *
  2182. * @param string $since The difference in human readable text.
  2183. * @param int $diff The difference in seconds.
  2184. * @param int $from Unix timestamp from which the difference begins.
  2185. * @param int $to Unix timestamp to end the time difference.
  2186. */
  2187. return apply_filters( 'human_time_diff', $since, $diff, $from, $to );
  2188. }
  2189. /**
  2190. * Generates an excerpt from the content, if needed.
  2191. *
  2192. * The excerpt word amount will be 55 words and if the amount is greater than
  2193. * that, then the string ' [&hellip;]' will be appended to the excerpt. If the string
  2194. * is less than 55 words, then the content will be returned as is.
  2195. *
  2196. * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
  2197. * The ' [&hellip;]' string can be modified by plugins/themes using the excerpt_more filter
  2198. *
  2199. * @since 1.5.0
  2200. *
  2201. * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
  2202. * @return string The excerpt.
  2203. */
  2204. function wp_trim_excerpt($text = '') {
  2205. $raw_excerpt = $text;
  2206. if ( '' == $text ) {
  2207. $text = get_the_content('');
  2208. $text = strip_shortcodes( $text );
  2209. /** This filter is documented in wp-includes/post-template.php */
  2210. $text = apply_filters( 'the_content', $text );
  2211. $text = str_replace(']]>', ']]&gt;', $text);
  2212. /**
  2213. * Filter the number of words in an excerpt.
  2214. *
  2215. * @since 2.7.0
  2216. *
  2217. * @param int $number The number of words. Default 55.
  2218. */
  2219. $excerpt_length = apply_filters( 'excerpt_length', 55 );
  2220. /**
  2221. * Filter the string in the "more" link displayed after a trimmed excerpt.
  2222. *
  2223. * @since 2.9.0
  2224. *
  2225. * @param string $more_string The string shown within the more link.
  2226. */
  2227. $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
  2228. $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
  2229. }
  2230. /**
  2231. * Filter the trimmed excerpt string.
  2232. *
  2233. * @since 2.8.0
  2234. *
  2235. * @param string $text The trimmed text.
  2236. * @param string $raw_excerpt The text prior to trimming.
  2237. */
  2238. return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
  2239. }
  2240. /**
  2241. * Trims text to a certain number of words.
  2242. *
  2243. * This function is localized. For languages that count 'words' by the individual
  2244. * character (such as East Asian languages), the $num_words argument will apply
  2245. * to the number of individual characters.
  2246. *
  2247. * @since 3.3.0
  2248. *
  2249. * @param string $text Text to trim.
  2250. * @param int $num_words Number of words. Default 55.
  2251. * @param string $more Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
  2252. * @return string Trimmed text.
  2253. */
  2254. function wp_trim_words( $text, $num_words = 55, $more = null ) {
  2255. if ( null === $more )
  2256. $more = __( '&hellip;' );
  2257. $original_text = $text;
  2258. $text = wp_strip_all_tags( $text );
  2259. /* translators: If your word count is based on single characters (East Asian characters),
  2260. enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
  2261. if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
  2262. $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
  2263. preg_match_all( '/./u', $text, $words_array );
  2264. $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
  2265. $sep = '';
  2266. } else {
  2267. $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
  2268. $sep = ' ';
  2269. }
  2270. if ( count( $words_array ) > $num_words ) {
  2271. array_pop( $words_array );
  2272. $text = implode( $sep, $words_array );
  2273. $text = $text . $more;
  2274. } else {
  2275. $text = implode( $sep, $words_array );
  2276. }
  2277. /**
  2278. * Filter the text content after words have been trimmed.
  2279. *
  2280. * @since 3.3.0
  2281. *
  2282. * @param string $text The trimmed text.
  2283. * @param int $num_words The number of words to trim the text to. Default 5.
  2284. * @param string $more An optional string to append to the end of the trimmed text, e.g. &hellip;.
  2285. * @param string $original_text The text before it was trimmed.
  2286. */
  2287. return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
  2288. }
  2289. /**
  2290. * Converts named entities into numbered entities.
  2291. *
  2292. * @since 1.5.1
  2293. *
  2294. * @param string $text The text within which entities will be converted.
  2295. * @return string Text with converted entities.
  2296. */
  2297. function ent2ncr($text) {
  2298. /**
  2299. * Filter text before named entities are converted into numbered entities.
  2300. *
  2301. * A non-null string must be returned for the filter to be evaluated.
  2302. *
  2303. * @since 3.3.0
  2304. *
  2305. * @param null $converted_text The text to be converted. Default null.
  2306. * @param string $text The text prior to entity conversion.
  2307. */
  2308. $filtered = apply_filters( 'pre_ent2ncr', null, $text );
  2309. if( null !== $filtered )
  2310. return $filtered;
  2311. $to_ncr = array(
  2312. '&quot;' => '&#34;',
  2313. '&amp;' => '&#38;',
  2314. '&lt;' => '&#60;',
  2315. '&gt;' => '&#62;',
  2316. '|' => '&#124;',
  2317. '&nbsp;' => '&#160;',
  2318. '&iexcl;' => '&#161;',
  2319. '&cent;' => '&#162;',
  2320. '&pound;' => '&#163;',
  2321. '&curren;' => '&#164;',
  2322. '&yen;' => '&#165;',
  2323. '&brvbar;' => '&#166;',
  2324. '&brkbar;' => '&#166;',
  2325. '&sect;' => '&#167;',
  2326. '&uml;' => '&#168;',
  2327. '&die;' => '&#168;',
  2328. '&copy;' => '&#169;',
  2329. '&ordf;' => '&#170;',
  2330. '&laquo;' => '&#171;',
  2331. '&not;' => '&#172;',
  2332. '&shy;' => '&#173;',
  2333. '&reg;' => '&#174;',
  2334. '&macr;' => '&#175;',
  2335. '&hibar;' => '&#175;',
  2336. '&deg;' => '&#176;',
  2337. '&plusmn;' => '&#177;',
  2338. '&sup2;' => '&#178;',
  2339. '&sup3;' => '&#179;',
  2340. '&acute;' => '&#180;',
  2341. '&micro;' => '&#181;',
  2342. '&para;' => '&#182;',
  2343. '&middot;' => '&#183;',
  2344. '&cedil;' => '&#184;',
  2345. '&sup1;' => '&#185;',
  2346. '&ordm;' => '&#186;',
  2347. '&raquo;' => '&#187;',
  2348. '&frac14;' => '&#188;',
  2349. '&frac12;' => '&#189;',
  2350. '&frac34;' => '&#190;',
  2351. '&iquest;' => '&#191;',
  2352. '&Agrave;' => '&#192;',
  2353. '&Aacute;' => '&#193;',
  2354. '&Acirc;' => '&#194;',
  2355. '&Atilde;' => '&#195;',
  2356. '&Auml;' => '&#196;',
  2357. '&Aring;' => '&#197;',
  2358. '&AElig;' => '&#198;',
  2359. '&Ccedil;' => '&#199;',
  2360. '&Egrave;' => '&#200;',
  2361. '&Eacute;' => '&#201;',
  2362. '&Ecirc;' => '&#202;',
  2363. '&Euml;' => '&#203;',
  2364. '&Igrave;' => '&#204;',
  2365. '&Iacute;' => '&#205;',
  2366. '&Icirc;' => '&#206;',
  2367. '&Iuml;' => '&#207;',
  2368. '&ETH;' => '&#208;',
  2369. '&Ntilde;' => '&#209;',
  2370. '&Ograve;' => '&#210;',
  2371. '&Oacute;' => '&#211;',
  2372. '&Ocirc;' => '&#212;',
  2373. '&Otilde;' => '&#213;',
  2374. '&Ouml;' => '&#214;',
  2375. '&times;' => '&#215;',
  2376. '&Oslash;' => '&#216;',
  2377. '&Ugrave;' => '&#217;',
  2378. '&Uacute;' => '&#218;',
  2379. '&Ucirc;' => '&#219;',
  2380. '&Uuml;' => '&#220;',
  2381. '&Yacute;' => '&#221;',
  2382. '&THORN;' => '&#222;',
  2383. '&szlig;' => '&#223;',
  2384. '&agrave;' => '&#224;',
  2385. '&aacute;' => '&#225;',
  2386. '&acirc;' => '&#226;',
  2387. '&atilde;' => '&#227;',
  2388. '&auml;' => '&#228;',
  2389. '&aring;' => '&#229;',
  2390. '&aelig;' => '&#230;',
  2391. '&ccedil;' => '&#231;',
  2392. '&egrave;' => '&#232;',
  2393. '&eacute;' => '&#233;',
  2394. '&ecirc;' => '&#234;',
  2395. '&euml;' => '&#235;',
  2396. '&igrave;' => '&#236;',
  2397. '&iacute;' => '&#237;',
  2398. '&icirc;' => '&#238;',
  2399. '&iuml;' => '&#239;',
  2400. '&eth;' => '&#240;',
  2401. '&ntilde;' => '&#241;',
  2402. '&ograve;' => '&#242;',
  2403. '&oacute;' => '&#243;',
  2404. '&ocirc;' => '&#244;',
  2405. '&otilde;' => '&#245;',
  2406. '&ouml;' => '&#246;',
  2407. '&divide;' => '&#247;',
  2408. '&oslash;' => '&#248;',
  2409. '&ugrave;' => '&#249;',
  2410. '&uacute;' => '&#250;',
  2411. '&ucirc;' => '&#251;',
  2412. '&uuml;' => '&#252;',
  2413. '&yacute;' => '&#253;',
  2414. '&thorn;' => '&#254;',
  2415. '&yuml;' => '&#255;',
  2416. '&OElig;' => '&#338;',
  2417. '&oelig;' => '&#339;',
  2418. '&Scaron;' => '&#352;',
  2419. '&scaron;' => '&#353;',
  2420. '&Yuml;' => '&#376;',
  2421. '&fnof;' => '&#402;',
  2422. '&circ;' => '&#710;',
  2423. '&tilde;' => '&#732;',
  2424. '&Alpha;' => '&#913;',
  2425. '&Beta;' => '&#914;',
  2426. '&Gamma;' => '&#915;',
  2427. '&Delta;' => '&#916;',
  2428. '&Epsilon;' => '&#917;',
  2429. '&Zeta;' => '&#918;',
  2430. '&Eta;' => '&#919;',
  2431. '&Theta;' => '&#920;',
  2432. '&Iota;' => '&#921;',
  2433. '&Kappa;' => '&#922;',
  2434. '&Lambda;' => '&#923;',
  2435. '&Mu;' => '&#924;',
  2436. '&Nu;' => '&#925;',
  2437. '&Xi;' => '&#926;',
  2438. '&Omicron;' => '&#927;',
  2439. '&Pi;' => '&#928;',
  2440. '&Rho;' => '&#929;',
  2441. '&Sigma;' => '&#931;',
  2442. '&Tau;' => '&#932;',
  2443. '&Upsilon;' => '&#933;',
  2444. '&Phi;' => '&#934;',
  2445. '&Chi;' => '&#935;',
  2446. '&Psi;' => '&#936;',
  2447. '&Omega;' => '&#937;',
  2448. '&alpha;' => '&#945;',
  2449. '&beta;' => '&#946;',
  2450. '&gamma;' => '&#947;',
  2451. '&delta;' => '&#948;',
  2452. '&epsilon;' => '&#949;',
  2453. '&zeta;' => '&#950;',
  2454. '&eta;' => '&#951;',
  2455. '&theta;' => '&#952;',
  2456. '&iota;' => '&#953;',
  2457. '&kappa;' => '&#954;',
  2458. '&lambda;' => '&#955;',
  2459. '&mu;' => '&#956;',
  2460. '&nu;' => '&#957;',
  2461. '&xi;' => '&#958;',
  2462. '&omicron;' => '&#959;',
  2463. '&pi;' => '&#960;',
  2464. '&rho;' => '&#961;',
  2465. '&sigmaf;' => '&#962;',
  2466. '&sigma;' => '&#963;',
  2467. '&tau;' => '&#964;',
  2468. '&upsilon;' => '&#965;',
  2469. '&phi;' => '&#966;',
  2470. '&chi;' => '&#967;',
  2471. '&psi;' => '&#968;',
  2472. '&omega;' => '&#969;',
  2473. '&thetasym;' => '&#977;',
  2474. '&upsih;' => '&#978;',
  2475. '&piv;' => '&#982;',
  2476. '&ensp;' => '&#8194;',
  2477. '&emsp;' => '&#8195;',
  2478. '&thinsp;' => '&#8201;',
  2479. '&zwnj;' => '&#8204;',
  2480. '&zwj;' => '&#8205;',
  2481. '&lrm;' => '&#8206;',
  2482. '&rlm;' => '&#8207;',
  2483. '&ndash;' => '&#8211;',
  2484. '&mdash;' => '&#8212;',
  2485. '&lsquo;' => '&#8216;',
  2486. '&rsquo;' => '&#8217;',
  2487. '&sbquo;' => '&#8218;',
  2488. '&ldquo;' => '&#8220;',
  2489. '&rdquo;' => '&#8221;',
  2490. '&bdquo;' => '&#8222;',
  2491. '&dagger;' => '&#8224;',
  2492. '&Dagger;' => '&#8225;',
  2493. '&bull;' => '&#8226;',
  2494. '&hellip;' => '&#8230;',
  2495. '&permil;' => '&#8240;',
  2496. '&prime;' => '&#8242;',
  2497. '&Prime;' => '&#8243;',
  2498. '&lsaquo;' => '&#8249;',
  2499. '&rsaquo;' => '&#8250;',
  2500. '&oline;' => '&#8254;',
  2501. '&frasl;' => '&#8260;',
  2502. '&euro;' => '&#8364;',
  2503. '&image;' => '&#8465;',
  2504. '&weierp;' => '&#8472;',
  2505. '&real;' => '&#8476;',
  2506. '&trade;' => '&#8482;',
  2507. '&alefsym;' => '&#8501;',
  2508. '&crarr;' => '&#8629;',
  2509. '&lArr;' => '&#8656;',
  2510. '&uArr;' => '&#8657;',
  2511. '&rArr;' => '&#8658;',
  2512. '&dArr;' => '&#8659;',
  2513. '&hArr;' => '&#8660;',
  2514. '&forall;' => '&#8704;',
  2515. '&part;' => '&#8706;',
  2516. '&exist;' => '&#8707;',
  2517. '&empty;' => '&#8709;',
  2518. '&nabla;' => '&#8711;',
  2519. '&isin;' => '&#8712;',
  2520. '&notin;' => '&#8713;',
  2521. '&ni;' => '&#8715;',
  2522. '&prod;' => '&#8719;',
  2523. '&sum;' => '&#8721;',
  2524. '&minus;' => '&#8722;',
  2525. '&lowast;' => '&#8727;',
  2526. '&radic;' => '&#8730;',
  2527. '&prop;' => '&#8733;',
  2528. '&infin;' => '&#8734;',
  2529. '&ang;' => '&#8736;',
  2530. '&and;' => '&#8743;',
  2531. '&or;' => '&#8744;',
  2532. '&cap;' => '&#8745;',
  2533. '&cup;' => '&#8746;',
  2534. '&int;' => '&#8747;',
  2535. '&there4;' => '&#8756;',
  2536. '&sim;' => '&#8764;',
  2537. '&cong;' => '&#8773;',
  2538. '&asymp;' => '&#8776;',
  2539. '&ne;' => '&#8800;',
  2540. '&equiv;' => '&#8801;',
  2541. '&le;' => '&#8804;',
  2542. '&ge;' => '&#8805;',
  2543. '&sub;' => '&#8834;',
  2544. '&sup;' => '&#8835;',
  2545. '&nsub;' => '&#8836;',
  2546. '&sube;' => '&#8838;',
  2547. '&supe;' => '&#8839;',
  2548. '&oplus;' => '&#8853;',
  2549. '&otimes;' => '&#8855;',
  2550. '&perp;' => '&#8869;',
  2551. '&sdot;' => '&#8901;',
  2552. '&lceil;' => '&#8968;',
  2553. '&rceil;' => '&#8969;',
  2554. '&lfloor;' => '&#8970;',
  2555. '&rfloor;' => '&#8971;',
  2556. '&lang;' => '&#9001;',
  2557. '&rang;' => '&#9002;',
  2558. '&larr;' => '&#8592;',
  2559. '&uarr;' => '&#8593;',
  2560. '&rarr;' => '&#8594;',
  2561. '&darr;' => '&#8595;',
  2562. '&harr;' => '&#8596;',
  2563. '&loz;' => '&#9674;',
  2564. '&spades;' => '&#9824;',
  2565. '&clubs;' => '&#9827;',
  2566. '&hearts;' => '&#9829;',
  2567. '&diams;' => '&#9830;'
  2568. );
  2569. return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
  2570. }
  2571. /**
  2572. * Formats text for the rich text editor.
  2573. *
  2574. * The filter 'richedit_pre' is applied here. If $text is empty the filter will
  2575. * be applied to an empty string.
  2576. *
  2577. * @since 2.0.0
  2578. *
  2579. * @param string $text The text to be formatted.
  2580. * @return string The formatted text after filter is applied.
  2581. */
  2582. function wp_richedit_pre($text) {
  2583. if ( empty( $text ) ) {
  2584. /**
  2585. * Filter text returned for the rich text editor.
  2586. *
  2587. * This filter is first evaluated, and the value returned, if an empty string
  2588. * is passed to wp_richedit_pre(). If an empty string is passed, it results
  2589. * in a break tag and line feed.
  2590. *
  2591. * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
  2592. * return after being formatted.
  2593. *
  2594. * @since 2.0.0
  2595. *
  2596. * @param string $output Text for the rich text editor.
  2597. */
  2598. return apply_filters( 'richedit_pre', '' );
  2599. }
  2600. $output = convert_chars($text);
  2601. $output = wpautop($output);
  2602. $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
  2603. /** This filter is documented in wp-includes/formatting.php */
  2604. return apply_filters( 'richedit_pre', $output );
  2605. }
  2606. /**
  2607. * Formats text for the HTML editor.
  2608. *
  2609. * Unless $output is empty it will pass through htmlspecialchars before the
  2610. * 'htmledit_pre' filter is applied.
  2611. *
  2612. * @since 2.5.0
  2613. *
  2614. * @param string $output The text to be formatted.
  2615. * @return string Formatted text after filter applied.
  2616. */
  2617. function wp_htmledit_pre($output) {
  2618. if ( !empty($output) )
  2619. $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
  2620. /**
  2621. * Filter the text before it is formatted for the HTML editor.
  2622. *
  2623. * @since 2.5.0
  2624. *
  2625. * @param string $output The HTML-formatted text.
  2626. */
  2627. return apply_filters( 'htmledit_pre', $output );
  2628. }
  2629. /**
  2630. * Perform a deep string replace operation to ensure the values in $search are no longer present
  2631. *
  2632. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  2633. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  2634. * str_replace would return
  2635. *
  2636. * @since 2.8.1
  2637. * @access private
  2638. *
  2639. * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
  2640. * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
  2641. * @return string The string with the replaced svalues.
  2642. */
  2643. function _deep_replace( $search, $subject ) {
  2644. $subject = (string) $subject;
  2645. $count = 1;
  2646. while ( $count ) {
  2647. $subject = str_replace( $search, '', $subject, $count );
  2648. }
  2649. return $subject;
  2650. }
  2651. /**
  2652. * Escapes data for use in a MySQL query.
  2653. *
  2654. * Usually you should prepare queries using wpdb::prepare().
  2655. * Sometimes, spot-escaping is required or useful. One example
  2656. * is preparing an array for use in an IN clause.
  2657. *
  2658. * @since 2.8.0
  2659. * @param string|array $data Unescaped data
  2660. * @return string|array Escaped data
  2661. */
  2662. function esc_sql( $data ) {
  2663. global $wpdb;
  2664. return $wpdb->_escape( $data );
  2665. }
  2666. /**
  2667. * Checks and cleans a URL.
  2668. *
  2669. * A number of characters are removed from the URL. If the URL is for displaying
  2670. * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
  2671. * is applied to the returned cleaned URL.
  2672. *
  2673. * @since 2.8.0
  2674. * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
  2675. * via $protocols or the common ones set in the function.
  2676. *
  2677. * @param string $url The URL to be cleaned.
  2678. * @param array $protocols Optional. An array of acceptable protocols.
  2679. * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
  2680. * @param string $_context Private. Use esc_url_raw() for database usage.
  2681. * @return string The cleaned $url after the 'clean_url' filter is applied.
  2682. */
  2683. function esc_url( $url, $protocols = null, $_context = 'display' ) {
  2684. $original_url = $url;
  2685. if ( '' == $url )
  2686. return $url;
  2687. $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
  2688. $strip = array('%0d', '%0a', '%0D', '%0A');
  2689. $url = _deep_replace($strip, $url);
  2690. $url = str_replace(';//', '://', $url);
  2691. /* If the URL doesn't appear to contain a scheme, we
  2692. * presume it needs http:// appended (unless a relative
  2693. * link starting with /, # or ? or a php file).
  2694. */
  2695. if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
  2696. ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
  2697. $url = 'http://' . $url;
  2698. // Replace ampersands and single quotes only when displaying.
  2699. if ( 'display' == $_context ) {
  2700. $url = wp_kses_normalize_entities( $url );
  2701. $url = str_replace( '&amp;', '&#038;', $url );
  2702. $url = str_replace( "'", '&#039;', $url );
  2703. }
  2704. if ( '/' === $url[0] ) {
  2705. $good_protocol_url = $url;
  2706. } else {
  2707. if ( ! is_array( $protocols ) )
  2708. $protocols = wp_allowed_protocols();
  2709. $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
  2710. if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
  2711. return '';
  2712. }
  2713. /**
  2714. * Filter a string cleaned and escaped for output as a URL.
  2715. *
  2716. * @since 2.3.0
  2717. *
  2718. * @param string $good_protocol_url The cleaned URL to be returned.
  2719. * @param string $original_url The URL prior to cleaning.
  2720. * @param string $_context If 'display', replace ampersands and single quotes only.
  2721. */
  2722. return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
  2723. }
  2724. /**
  2725. * Performs esc_url() for database usage.
  2726. *
  2727. * @since 2.8.0
  2728. * @uses esc_url()
  2729. *
  2730. * @param string $url The URL to be cleaned.
  2731. * @param array $protocols An array of acceptable protocols.
  2732. * @return string The cleaned URL.
  2733. */
  2734. function esc_url_raw( $url, $protocols = null ) {
  2735. return esc_url( $url, $protocols, 'db' );
  2736. }
  2737. /**
  2738. * Convert entities, while preserving already-encoded entities.
  2739. *
  2740. * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
  2741. *
  2742. * @since 1.2.2
  2743. *
  2744. * @param string $myHTML The text to be converted.
  2745. * @return string Converted text.
  2746. */
  2747. function htmlentities2($myHTML) {
  2748. $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
  2749. $translation_table[chr(38)] = '&';
  2750. return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
  2751. }
  2752. /**
  2753. * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
  2754. *
  2755. * Escapes text strings for echoing in JS. It is intended to be used for inline JS
  2756. * (in a tag attribute, for example onclick="..."). Note that the strings have to
  2757. * be in single quotes. The filter 'js_escape' is also applied here.
  2758. *
  2759. * @since 2.8.0
  2760. *
  2761. * @param string $text The text to be escaped.
  2762. * @return string Escaped text.
  2763. */
  2764. function esc_js( $text ) {
  2765. $safe_text = wp_check_invalid_utf8( $text );
  2766. $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
  2767. $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
  2768. $safe_text = str_replace( "\r", '', $safe_text );
  2769. $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
  2770. /**
  2771. * Filter a string cleaned and escaped for output in JavaScript.
  2772. *
  2773. * Text passed to esc_js() is stripped of invalid or special characters,
  2774. * and properly slashed for output.
  2775. *
  2776. * @since 2.0.6
  2777. *
  2778. * @param string $safe_text The text after it has been escaped.
  2779. * @param string $text The text prior to being escaped.
  2780. */
  2781. return apply_filters( 'js_escape', $safe_text, $text );
  2782. }
  2783. /**
  2784. * Escaping for HTML blocks.
  2785. *
  2786. * @since 2.8.0
  2787. *
  2788. * @param string $text
  2789. * @return string
  2790. */
  2791. function esc_html( $text ) {
  2792. $safe_text = wp_check_invalid_utf8( $text );
  2793. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  2794. /**
  2795. * Filter a string cleaned and escaped for output in HTML.
  2796. *
  2797. * Text passed to esc_html() is stripped of invalid or special characters
  2798. * before output.
  2799. *
  2800. * @since 2.8.0
  2801. *
  2802. * @param string $safe_text The text after it has been escaped.
  2803. * @param string $text The text prior to being escaped.
  2804. */
  2805. return apply_filters( 'esc_html', $safe_text, $text );
  2806. }
  2807. /**
  2808. * Escaping for HTML attributes.
  2809. *
  2810. * @since 2.8.0
  2811. *
  2812. * @param string $text
  2813. * @return string
  2814. */
  2815. function esc_attr( $text ) {
  2816. $safe_text = wp_check_invalid_utf8( $text );
  2817. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  2818. /**
  2819. * Filter a string cleaned and escaped for output in an HTML attribute.
  2820. *
  2821. * Text passed to esc_attr() is stripped of invalid or special characters
  2822. * before output.
  2823. *
  2824. * @since 2.0.6
  2825. *
  2826. * @param string $safe_text The text after it has been escaped.
  2827. * @param string $text The text prior to being escaped.
  2828. */
  2829. return apply_filters( 'attribute_escape', $safe_text, $text );
  2830. }
  2831. /**
  2832. * Escaping for textarea values.
  2833. *
  2834. * @since 3.1.0
  2835. *
  2836. * @param string $text
  2837. * @return string
  2838. */
  2839. function esc_textarea( $text ) {
  2840. $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
  2841. /**
  2842. * Filter a string cleaned and escaped for output in a textarea element.
  2843. *
  2844. * @since 3.1.0
  2845. *
  2846. * @param string $safe_text The text after it has been escaped.
  2847. * @param string $text The text prior to being escaped.
  2848. */
  2849. return apply_filters( 'esc_textarea', $safe_text, $text );
  2850. }
  2851. /**
  2852. * Escape an HTML tag name.
  2853. *
  2854. * @since 2.5.0
  2855. *
  2856. * @param string $tag_name
  2857. * @return string
  2858. */
  2859. function tag_escape($tag_name) {
  2860. $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
  2861. /**
  2862. * Filter a string cleaned and escaped for output as an HTML tag.
  2863. *
  2864. * @since 2.8.0
  2865. *
  2866. * @param string $safe_tag The tag name after it has been escaped.
  2867. * @param string $tag_name The text before it was escaped.
  2868. */
  2869. return apply_filters( 'tag_escape', $safe_tag, $tag_name );
  2870. }
  2871. /**
  2872. * Convert full URL paths to absolute paths.
  2873. *
  2874. * Removes the http or https protocols and the domain. Keeps the path '/' at the
  2875. * beginning, so it isn't a true relative link, but from the web root base.
  2876. *
  2877. * @since 2.1.0
  2878. *
  2879. * @param string $link Full URL path.
  2880. * @return string Absolute path.
  2881. */
  2882. function wp_make_link_relative( $link ) {
  2883. return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
  2884. }
  2885. /**
  2886. * Sanitises various option values based on the nature of the option.
  2887. *
  2888. * This is basically a switch statement which will pass $value through a number
  2889. * of functions depending on the $option.
  2890. *
  2891. * @since 2.0.5
  2892. *
  2893. * @param string $option The name of the option.
  2894. * @param string $value The unsanitised value.
  2895. * @return string Sanitized value.
  2896. */
  2897. function sanitize_option($option, $value) {
  2898. switch ( $option ) {
  2899. case 'admin_email' :
  2900. case 'new_admin_email' :
  2901. $value = sanitize_email( $value );
  2902. if ( ! is_email( $value ) ) {
  2903. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2904. if ( function_exists( 'add_settings_error' ) )
  2905. add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) );
  2906. }
  2907. break;
  2908. case 'thumbnail_size_w':
  2909. case 'thumbnail_size_h':
  2910. case 'medium_size_w':
  2911. case 'medium_size_h':
  2912. case 'large_size_w':
  2913. case 'large_size_h':
  2914. case 'mailserver_port':
  2915. case 'comment_max_links':
  2916. case 'page_on_front':
  2917. case 'page_for_posts':
  2918. case 'rss_excerpt_length':
  2919. case 'default_category':
  2920. case 'default_email_category':
  2921. case 'default_link_category':
  2922. case 'close_comments_days_old':
  2923. case 'comments_per_page':
  2924. case 'thread_comments_depth':
  2925. case 'users_can_register':
  2926. case 'start_of_week':
  2927. $value = absint( $value );
  2928. break;
  2929. case 'posts_per_page':
  2930. case 'posts_per_rss':
  2931. $value = (int) $value;
  2932. if ( empty($value) )
  2933. $value = 1;
  2934. if ( $value < -1 )
  2935. $value = abs($value);
  2936. break;
  2937. case 'default_ping_status':
  2938. case 'default_comment_status':
  2939. // Options that if not there have 0 value but need to be something like "closed"
  2940. if ( $value == '0' || $value == '')
  2941. $value = 'closed';
  2942. break;
  2943. case 'blogdescription':
  2944. case 'blogname':
  2945. $value = wp_kses_post( $value );
  2946. $value = esc_html( $value );
  2947. break;
  2948. case 'blog_charset':
  2949. $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
  2950. break;
  2951. case 'blog_public':
  2952. // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
  2953. if ( null === $value )
  2954. $value = 1;
  2955. else
  2956. $value = intval( $value );
  2957. break;
  2958. case 'date_format':
  2959. case 'time_format':
  2960. case 'mailserver_url':
  2961. case 'mailserver_login':
  2962. case 'mailserver_pass':
  2963. case 'upload_path':
  2964. $value = strip_tags( $value );
  2965. $value = wp_kses_data( $value );
  2966. break;
  2967. case 'ping_sites':
  2968. $value = explode( "\n", $value );
  2969. $value = array_filter( array_map( 'trim', $value ) );
  2970. $value = array_filter( array_map( 'esc_url_raw', $value ) );
  2971. $value = implode( "\n", $value );
  2972. break;
  2973. case 'gmt_offset':
  2974. $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
  2975. break;
  2976. case 'siteurl':
  2977. if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
  2978. $value = esc_url_raw($value);
  2979. } else {
  2980. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2981. if ( function_exists('add_settings_error') )
  2982. add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
  2983. }
  2984. break;
  2985. case 'home':
  2986. if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
  2987. $value = esc_url_raw($value);
  2988. } else {
  2989. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2990. if ( function_exists('add_settings_error') )
  2991. add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
  2992. }
  2993. break;
  2994. case 'WPLANG':
  2995. $allowed = get_available_languages();
  2996. if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
  2997. $value = get_option( $option );
  2998. break;
  2999. case 'illegal_names':
  3000. if ( ! is_array( $value ) )
  3001. $value = explode( ' ', $value );
  3002. $value = array_values( array_filter( array_map( 'trim', $value ) ) );
  3003. if ( ! $value )
  3004. $value = '';
  3005. break;
  3006. case 'limited_email_domains':
  3007. case 'banned_email_domains':
  3008. if ( ! is_array( $value ) )
  3009. $value = explode( "\n", $value );
  3010. $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
  3011. $value = array();
  3012. foreach ( $domains as $domain ) {
  3013. if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
  3014. $value[] = $domain;
  3015. }
  3016. if ( ! $value )
  3017. $value = '';
  3018. break;
  3019. case 'timezone_string':
  3020. $allowed_zones = timezone_identifiers_list();
  3021. if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
  3022. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  3023. if ( function_exists('add_settings_error') )
  3024. add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
  3025. }
  3026. break;
  3027. case 'permalink_structure':
  3028. case 'category_base':
  3029. case 'tag_base':
  3030. $value = esc_url_raw( $value );
  3031. $value = str_replace( 'http://', '', $value );
  3032. break;
  3033. case 'default_role' :
  3034. if ( ! get_role( $value ) && get_role( 'subscriber' ) )
  3035. $value = 'subscriber';
  3036. break;
  3037. case 'moderation_keys':
  3038. case 'blacklist_keys':
  3039. $value = explode( "\n", $value );
  3040. $value = array_filter( array_map( 'trim', $value ) );
  3041. $value = array_unique( $value );
  3042. $value = implode( "\n", $value );
  3043. break;
  3044. }
  3045. /**
  3046. * Filter an option value following sanitization.
  3047. *
  3048. * @since 2.3.0
  3049. *
  3050. * @param string $value The sanitized option value.
  3051. * @param string $option The option name.
  3052. */
  3053. $value = apply_filters( "sanitize_option_{$option}", $value, $option );
  3054. return $value;
  3055. }
  3056. /**
  3057. * Parses a string into variables to be stored in an array.
  3058. *
  3059. * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
  3060. * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
  3061. *
  3062. * @since 2.2.1
  3063. *
  3064. * @param string $string The string to be parsed.
  3065. * @param array $array Variables will be stored in this array.
  3066. */
  3067. function wp_parse_str( $string, &$array ) {
  3068. parse_str( $string, $array );
  3069. if ( get_magic_quotes_gpc() )
  3070. $array = stripslashes_deep( $array );
  3071. /**
  3072. * Filter the array of variables derived from a parsed string.
  3073. *
  3074. * @since 2.3.0
  3075. *
  3076. * @param array $array The array populated with variables.
  3077. */
  3078. $array = apply_filters( 'wp_parse_str', $array );
  3079. }
  3080. /**
  3081. * Convert lone less than signs.
  3082. *
  3083. * KSES already converts lone greater than signs.
  3084. *
  3085. * @uses wp_pre_kses_less_than_callback in the callback function.
  3086. * @since 2.3.0
  3087. *
  3088. * @param string $text Text to be converted.
  3089. * @return string Converted text.
  3090. */
  3091. function wp_pre_kses_less_than( $text ) {
  3092. return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
  3093. }
  3094. /**
  3095. * Callback function used by preg_replace.
  3096. *
  3097. * @uses esc_html to format the $matches text.
  3098. * @since 2.3.0
  3099. *
  3100. * @param array $matches Populated by matches to preg_replace.
  3101. * @return string The text returned after esc_html if needed.
  3102. */
  3103. function wp_pre_kses_less_than_callback( $matches ) {
  3104. if ( false === strpos($matches[0], '>') )
  3105. return esc_html($matches[0]);
  3106. return $matches[0];
  3107. }
  3108. /**
  3109. * WordPress implementation of PHP sprintf() with filters.
  3110. *
  3111. * @since 2.5.0
  3112. * @link http://www.php.net/sprintf
  3113. *
  3114. * @param string $pattern The string which formatted args are inserted.
  3115. * @param mixed $args,... Arguments to be formatted into the $pattern string.
  3116. * @return string The formatted string.
  3117. */
  3118. function wp_sprintf( $pattern ) {
  3119. $args = func_get_args();
  3120. $len = strlen($pattern);
  3121. $start = 0;
  3122. $result = '';
  3123. $arg_index = 0;
  3124. while ( $len > $start ) {
  3125. // Last character: append and break
  3126. if ( strlen($pattern) - 1 == $start ) {
  3127. $result .= substr($pattern, -1);
  3128. break;
  3129. }
  3130. // Literal %: append and continue
  3131. if ( substr($pattern, $start, 2) == '%%' ) {
  3132. $start += 2;
  3133. $result .= '%';
  3134. continue;
  3135. }
  3136. // Get fragment before next %
  3137. $end = strpos($pattern, '%', $start + 1);
  3138. if ( false === $end )
  3139. $end = $len;
  3140. $fragment = substr($pattern, $start, $end - $start);
  3141. // Fragment has a specifier
  3142. if ( $pattern[$start] == '%' ) {
  3143. // Find numbered arguments or take the next one in order
  3144. if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
  3145. $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
  3146. $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
  3147. } else {
  3148. ++$arg_index;
  3149. $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
  3150. }
  3151. /**
  3152. * Filter a fragment from the pattern passed to wp_sprintf().
  3153. *
  3154. * If the fragment is unchanged, then sprintf() will be run on the fragment.
  3155. *
  3156. * @since 2.5.0
  3157. *
  3158. * @param string $fragment A fragment from the pattern.
  3159. * @param string $arg The argument.
  3160. */
  3161. $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
  3162. if ( $_fragment != $fragment )
  3163. $fragment = $_fragment;
  3164. else
  3165. $fragment = sprintf($fragment, strval($arg) );
  3166. }
  3167. // Append to result and move to next fragment
  3168. $result .= $fragment;
  3169. $start = $end;
  3170. }
  3171. return $result;
  3172. }
  3173. /**
  3174. * Localize list items before the rest of the content.
  3175. *
  3176. * The '%l' must be at the first characters can then contain the rest of the
  3177. * content. The list items will have ', ', ', and', and ' and ' added depending
  3178. * on the amount of list items in the $args parameter.
  3179. *
  3180. * @since 2.5.0
  3181. *
  3182. * @param string $pattern Content containing '%l' at the beginning.
  3183. * @param array $args List items to prepend to the content and replace '%l'.
  3184. * @return string Localized list items and rest of the content.
  3185. */
  3186. function wp_sprintf_l($pattern, $args) {
  3187. // Not a match
  3188. if ( substr($pattern, 0, 2) != '%l' )
  3189. return $pattern;
  3190. // Nothing to work with
  3191. if ( empty($args) )
  3192. return '';
  3193. /**
  3194. * Filter the translated delimiters used by wp_sprintf_l().
  3195. * Placeholders (%s) are included to assist translators and then
  3196. * removed before the array of strings reaches the filter.
  3197. *
  3198. * Please note: Ampersands and entities should be avoided here.
  3199. *
  3200. * @since 2.5.0
  3201. *
  3202. * @param array $delimiters An array of translated delimiters.
  3203. */
  3204. $l = apply_filters( 'wp_sprintf_l', array(
  3205. /* translators: used to join items in a list with more than 2 items */
  3206. 'between' => sprintf( __('%s, %s'), '', '' ),
  3207. /* translators: used to join last two items in a list with more than 2 times */
  3208. 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
  3209. /* translators: used to join items in a list with only 2 items */
  3210. 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
  3211. ) );
  3212. $args = (array) $args;
  3213. $result = array_shift($args);
  3214. if ( count($args) == 1 )
  3215. $result .= $l['between_only_two'] . array_shift($args);
  3216. // Loop when more than two args
  3217. $i = count($args);
  3218. while ( $i ) {
  3219. $arg = array_shift($args);
  3220. $i--;
  3221. if ( 0 == $i )
  3222. $result .= $l['between_last_two'] . $arg;
  3223. else
  3224. $result .= $l['between'] . $arg;
  3225. }
  3226. return $result . substr($pattern, 2);
  3227. }
  3228. /**
  3229. * Safely extracts not more than the first $count characters from html string.
  3230. *
  3231. * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
  3232. * be counted as one character. For example &amp; will be counted as 4, &lt; as
  3233. * 3, etc.
  3234. *
  3235. * @since 2.5.0
  3236. *
  3237. * @param string $str String to get the excerpt from.
  3238. * @param integer $count Maximum number of characters to take.
  3239. * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
  3240. * @return string The excerpt.
  3241. */
  3242. function wp_html_excerpt( $str, $count, $more = null ) {
  3243. if ( null === $more )
  3244. $more = '';
  3245. $str = wp_strip_all_tags( $str, true );
  3246. $excerpt = mb_substr( $str, 0, $count );
  3247. // remove part of an entity at the end
  3248. $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
  3249. if ( $str != $excerpt )
  3250. $excerpt = trim( $excerpt ) . $more;
  3251. return $excerpt;
  3252. }
  3253. /**
  3254. * Add a Base url to relative links in passed content.
  3255. *
  3256. * By default it supports the 'src' and 'href' attributes. However this can be
  3257. * changed via the 3rd param.
  3258. *
  3259. * @since 2.7.0
  3260. *
  3261. * @param string $content String to search for links in.
  3262. * @param string $base The base URL to prefix to links.
  3263. * @param array $attrs The attributes which should be processed.
  3264. * @return string The processed content.
  3265. */
  3266. function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
  3267. global $_links_add_base;
  3268. $_links_add_base = $base;
  3269. $attrs = implode('|', (array)$attrs);
  3270. return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
  3271. }
  3272. /**
  3273. * Callback to add a base url to relative links in passed content.
  3274. *
  3275. * @since 2.7.0
  3276. * @access private
  3277. *
  3278. * @param string $m The matched link.
  3279. * @return string The processed link.
  3280. */
  3281. function _links_add_base($m) {
  3282. global $_links_add_base;
  3283. //1 = attribute name 2 = quotation mark 3 = URL
  3284. return $m[1] . '=' . $m[2] .
  3285. ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
  3286. $m[3] :
  3287. path_join( $_links_add_base, $m[3] ) )
  3288. . $m[2];
  3289. }
  3290. /**
  3291. * Adds a Target attribute to all links in passed content.
  3292. *
  3293. * This function by default only applies to <a> tags, however this can be
  3294. * modified by the 3rd param.
  3295. *
  3296. * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
  3297. *
  3298. * @since 2.7.0
  3299. *
  3300. * @param string $content String to search for links in.
  3301. * @param string $target The Target to add to the links.
  3302. * @param array $tags An array of tags to apply to.
  3303. * @return string The processed content.
  3304. */
  3305. function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
  3306. global $_links_add_target;
  3307. $_links_add_target = $target;
  3308. $tags = implode('|', (array)$tags);
  3309. return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
  3310. }
  3311. /**
  3312. * Callback to add a target attribute to all links in passed content.
  3313. *
  3314. * @since 2.7.0
  3315. * @access private
  3316. *
  3317. * @param string $m The matched link.
  3318. * @return string The processed link.
  3319. */
  3320. function _links_add_target( $m ) {
  3321. global $_links_add_target;
  3322. $tag = $m[1];
  3323. $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
  3324. return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
  3325. }
  3326. /**
  3327. * Normalize EOL characters and strip duplicate whitespace.
  3328. *
  3329. * @since 2.7.0
  3330. *
  3331. * @param string $str The string to normalize.
  3332. * @return string The normalized string.
  3333. */
  3334. function normalize_whitespace( $str ) {
  3335. $str = trim( $str );
  3336. $str = str_replace( "\r", "\n", $str );
  3337. $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
  3338. return $str;
  3339. }
  3340. /**
  3341. * Properly strip all HTML tags including script and style
  3342. *
  3343. * This differs from strip_tags() because it removes the contents of
  3344. * the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
  3345. * will return 'something'. wp_strip_all_tags will return ''
  3346. *
  3347. * @since 2.9.0
  3348. *
  3349. * @param string $string String containing HTML tags
  3350. * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
  3351. * @return string The processed string.
  3352. */
  3353. function wp_strip_all_tags($string, $remove_breaks = false) {
  3354. $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
  3355. $string = strip_tags($string);
  3356. if ( $remove_breaks )
  3357. $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
  3358. return trim( $string );
  3359. }
  3360. /**
  3361. * Sanitize a string from user input or from the db
  3362. *
  3363. * check for invalid UTF-8,
  3364. * Convert single < characters to entity,
  3365. * strip all tags,
  3366. * remove line breaks, tabs and extra white space,
  3367. * strip octets.
  3368. *
  3369. * @since 2.9.0
  3370. *
  3371. * @param string $str
  3372. * @return string
  3373. */
  3374. function sanitize_text_field($str) {
  3375. $filtered = wp_check_invalid_utf8( $str );
  3376. if ( strpos($filtered, '<') !== false ) {
  3377. $filtered = wp_pre_kses_less_than( $filtered );
  3378. // This will strip extra whitespace for us.
  3379. $filtered = wp_strip_all_tags( $filtered, true );
  3380. } else {
  3381. $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
  3382. }
  3383. $found = false;
  3384. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
  3385. $filtered = str_replace($match[0], '', $filtered);
  3386. $found = true;
  3387. }
  3388. if ( $found ) {
  3389. // Strip out the whitespace that may now exist after removing the octets.
  3390. $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
  3391. }
  3392. /**
  3393. * Filter a sanitized text field string.
  3394. *
  3395. * @since 2.9.0
  3396. *
  3397. * @param string $filtered The sanitized string.
  3398. * @param string $str The string prior to being sanitized.
  3399. */
  3400. return apply_filters( 'sanitize_text_field', $filtered, $str );
  3401. }
  3402. /**
  3403. * i18n friendly version of basename()
  3404. *
  3405. * @since 3.1.0
  3406. *
  3407. * @param string $path A path.
  3408. * @param string $suffix If the filename ends in suffix this will also be cut off.
  3409. * @return string
  3410. */
  3411. function wp_basename( $path, $suffix = '' ) {
  3412. return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
  3413. }
  3414. /**
  3415. * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
  3416. *
  3417. * Violating our coding standards for a good function name.
  3418. *
  3419. * @since 3.0.0
  3420. */
  3421. function capital_P_dangit( $text ) {
  3422. // Simple replacement for titles
  3423. $current_filter = current_filter();
  3424. if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
  3425. return str_replace( 'Wordpress', 'WordPress', $text );
  3426. // Still here? Use the more judicious replacement
  3427. static $dblq = false;
  3428. if ( false === $dblq )
  3429. $dblq = _x( '&#8220;', 'opening curly double quote' );
  3430. return str_replace(
  3431. array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
  3432. array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
  3433. $text );
  3434. }
  3435. /**
  3436. * Sanitize a mime type
  3437. *
  3438. * @since 3.1.3
  3439. *
  3440. * @param string $mime_type Mime type
  3441. * @return string Sanitized mime type
  3442. */
  3443. function sanitize_mime_type( $mime_type ) {
  3444. $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
  3445. /**
  3446. * Filter a mime type following sanitization.
  3447. *
  3448. * @since 3.1.3
  3449. *
  3450. * @param string $sani_mime_type The sanitized mime type.
  3451. * @param string $mime_type The mime type prior to sanitization.
  3452. */
  3453. return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
  3454. }
  3455. /**
  3456. * Sanitize space or carriage return separated URLs that are used to send trackbacks.
  3457. *
  3458. * @since 3.4.0
  3459. *
  3460. * @param string $to_ping Space or carriage return separated URLs
  3461. * @return string URLs starting with the http or https protocol, separated by a carriage return.
  3462. */
  3463. function sanitize_trackback_urls( $to_ping ) {
  3464. $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
  3465. foreach ( $urls_to_ping as $k => $url ) {
  3466. if ( !preg_match( '#^https?://.#i', $url ) )
  3467. unset( $urls_to_ping[$k] );
  3468. }
  3469. $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
  3470. $urls_to_ping = implode( "\n", $urls_to_ping );
  3471. /**
  3472. * Filter a list of trackback URLs following sanitization.
  3473. *
  3474. * The string returned here consists of a space or carriage return-delimited list
  3475. * of trackback URLs.
  3476. *
  3477. * @since 3.4.0
  3478. *
  3479. * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
  3480. * @param string $to_ping Space or carriage return separated URLs before sanitization.
  3481. */
  3482. return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
  3483. }
  3484. /**
  3485. * Add slashes to a string or array of strings.
  3486. *
  3487. * This should be used when preparing data for core API that expects slashed data.
  3488. * This should not be used to escape data going directly into an SQL query.
  3489. *
  3490. * @since 3.6.0
  3491. *
  3492. * @param string|array $value String or array of strings to slash.
  3493. * @return string|array Slashed $value
  3494. */
  3495. function wp_slash( $value ) {
  3496. if ( is_array( $value ) ) {
  3497. foreach ( $value as $k => $v ) {
  3498. if ( is_array( $v ) ) {
  3499. $value[$k] = wp_slash( $v );
  3500. } else {
  3501. $value[$k] = addslashes( $v );
  3502. }
  3503. }
  3504. } else {
  3505. $value = addslashes( $value );
  3506. }
  3507. return $value;
  3508. }
  3509. /**
  3510. * Remove slashes from a string or array of strings.
  3511. *
  3512. * This should be used to remove slashes from data passed to core API that
  3513. * expects data to be unslashed.
  3514. *
  3515. * @since 3.6.0
  3516. *
  3517. * @param string|array $value String or array of strings to unslash.
  3518. * @return string|array Unslashed $value
  3519. */
  3520. function wp_unslash( $value ) {
  3521. return stripslashes_deep( $value );
  3522. }
  3523. /**
  3524. * Extract and return the first URL from passed content.
  3525. *
  3526. * @since 3.6.0
  3527. *
  3528. * @param string $content A string which might contain a URL.
  3529. * @return string The found URL.
  3530. */
  3531. function get_url_in_content( $content ) {
  3532. if ( empty( $content ) ) {
  3533. return false;
  3534. }
  3535. if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
  3536. return esc_url_raw( $matches[2] );
  3537. }
  3538. return false;
  3539. }
  3540. /**
  3541. * Returns the regexp for common whitespace characters.
  3542. *
  3543. * By default, spaces include new lines, tabs, nbsp entities, and the UTF-8 nbsp.
  3544. * This is designed to replace the PCRE \s sequence. In ticket #22692, that
  3545. * sequence was found to be unreliable due to random inclusion of the A0 byte.
  3546. *
  3547. * @since 4.0.0
  3548. *
  3549. * @return string The spaces regexp.
  3550. */
  3551. function wp_spaces_regexp() {
  3552. static $spaces;
  3553. if ( empty( $spaces ) ) {
  3554. /**
  3555. * Filter the regexp for common whitespace characters.
  3556. *
  3557. * This string is substituted for the \s sequence as needed in regular
  3558. * expressions. For websites not written in English, different characters
  3559. * may represent whitespace. For websites not encoded in UTF-8, the 0xC2 0xA0
  3560. * sequence may not be in use.
  3561. *
  3562. * @since 4.0.0
  3563. *
  3564. * @param string $spaces Regexp pattern for matching common whitespace characters.
  3565. */
  3566. $spaces = apply_filters( 'wp_spaces_regexp', '[\r\n\t ]|\xC2\xA0|&nbsp;' );
  3567. }
  3568. return $spaces;
  3569. }