PageRenderTime 78ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

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