PageRenderTime 66ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/formatting.php

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