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

/wp-includes/formatting.php

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