PageRenderTime 73ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/formatting.php

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