PageRenderTime 94ms CodeModel.GetById 32ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/formatting.php

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