PageRenderTime 70ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 2ms

/wp-includes/formatting.php

http://github.com/markjaquith/WordPress
PHP | 6022 lines | 3101 code | 535 blank | 2386 comment | 475 complexity | b072f0ab9db6c26824e3e7fad6cdc64e MD5 | raw file
Possible License(s): 0BSD

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * Main WordPress Formatting API.
  4. *
  5. * Handles many functions for formatting output.
  6. *
  7. * @package WordPress
  8. */
  9. /**
  10. * Replaces common plain text characters with formatted entities.
  11. *
  12. * Returns given text with transformations of quotes into smart quotes, apostrophes,
  13. * dashes, ellipses, the trademark symbol, and the multiplication symbol.
  14. *
  15. * As an example,
  16. *
  17. * 'cause today's effort makes it worth tomorrow's "holiday" ...
  18. *
  19. * Becomes:
  20. *
  21. * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221; &#8230;
  22. *
  23. * Code within certain HTML blocks are skipped.
  24. *
  25. * Do not use this function before the {@see 'init'} action hook; everything will break.
  26. *
  27. * @since 0.71
  28. *
  29. * @global array $wp_cockneyreplace Array of formatted entities for certain common phrases.
  30. * @global array $shortcode_tags
  31. * @staticvar array $static_characters
  32. * @staticvar array $static_replacements
  33. * @staticvar array $dynamic_characters
  34. * @staticvar array $dynamic_replacements
  35. * @staticvar array $default_no_texturize_tags
  36. * @staticvar array $default_no_texturize_shortcodes
  37. * @staticvar bool $run_texturize
  38. * @staticvar string $apos
  39. * @staticvar string $prime
  40. * @staticvar string $double_prime
  41. * @staticvar string $opening_quote
  42. * @staticvar string $closing_quote
  43. * @staticvar string $opening_single_quote
  44. * @staticvar string $closing_single_quote
  45. * @staticvar string $open_q_flag
  46. * @staticvar string $open_sq_flag
  47. * @staticvar string $apos_flag
  48. *
  49. * @param string $text The text to be formatted.
  50. * @param bool $reset Set to true for unit testing. Translated patterns will reset.
  51. * @return string The string replaced with HTML entities.
  52. */
  53. function wptexturize( $text, $reset = false ) {
  54. global $wp_cockneyreplace, $shortcode_tags;
  55. static $static_characters = null,
  56. $static_replacements = null,
  57. $dynamic_characters = null,
  58. $dynamic_replacements = null,
  59. $default_no_texturize_tags = null,
  60. $default_no_texturize_shortcodes = null,
  61. $run_texturize = true,
  62. $apos = null,
  63. $prime = null,
  64. $double_prime = null,
  65. $opening_quote = null,
  66. $closing_quote = null,
  67. $opening_single_quote = null,
  68. $closing_single_quote = null,
  69. $open_q_flag = '<!--oq-->',
  70. $open_sq_flag = '<!--osq-->',
  71. $apos_flag = '<!--apos-->';
  72. // If there's nothing to do, just stop.
  73. if ( empty( $text ) || false === $run_texturize ) {
  74. return $text;
  75. }
  76. // Set up static variables. Run once only.
  77. if ( $reset || ! isset( $static_characters ) ) {
  78. /**
  79. * Filters whether to skip running wptexturize().
  80. *
  81. * Passing false to the filter will effectively short-circuit wptexturize().
  82. * returning the original text passed to the function instead.
  83. *
  84. * The filter runs only once, the first time wptexturize() is called.
  85. *
  86. * @since 4.0.0
  87. *
  88. * @see wptexturize()
  89. *
  90. * @param bool $run_texturize Whether to short-circuit wptexturize().
  91. */
  92. $run_texturize = apply_filters( 'run_wptexturize', $run_texturize );
  93. if ( false === $run_texturize ) {
  94. return $text;
  95. }
  96. /* translators: Opening curly double quote. */
  97. $opening_quote = _x( '&#8220;', 'opening curly double quote' );
  98. /* translators: Closing curly double quote. */
  99. $closing_quote = _x( '&#8221;', 'closing curly double quote' );
  100. /* translators: Apostrophe, for example in 'cause or can't. */
  101. $apos = _x( '&#8217;', 'apostrophe' );
  102. /* translators: Prime, for example in 9' (nine feet). */
  103. $prime = _x( '&#8242;', 'prime' );
  104. /* translators: Double prime, for example in 9" (nine inches). */
  105. $double_prime = _x( '&#8243;', 'double prime' );
  106. /* translators: Opening curly single quote. */
  107. $opening_single_quote = _x( '&#8216;', 'opening curly single quote' );
  108. /* translators: Closing curly single quote. */
  109. $closing_single_quote = _x( '&#8217;', 'closing curly single quote' );
  110. /* translators: En dash. */
  111. $en_dash = _x( '&#8211;', 'en dash' );
  112. /* translators: Em dash. */
  113. $em_dash = _x( '&#8212;', 'em dash' );
  114. $default_no_texturize_tags = array( 'pre', 'code', 'kbd', 'style', 'script', 'tt' );
  115. $default_no_texturize_shortcodes = array( 'code' );
  116. // If a plugin has provided an autocorrect array, use it.
  117. if ( isset( $wp_cockneyreplace ) ) {
  118. $cockney = array_keys( $wp_cockneyreplace );
  119. $cockneyreplace = array_values( $wp_cockneyreplace );
  120. } else {
  121. /*
  122. * translators: This is a comma-separated list of words that defy the syntax of quotations in normal use,
  123. * for example... 'We do not have enough words yet'... is a typical quoted phrase. But when we write
  124. * lines of code 'til we have enough of 'em, then we need to insert apostrophes instead of quotes.
  125. */
  126. $cockney = explode(
  127. ',',
  128. _x(
  129. "'tain't,'twere,'twas,'tis,'twill,'til,'bout,'nuff,'round,'cause,'em",
  130. 'Comma-separated list of words to texturize in your language'
  131. )
  132. );
  133. $cockneyreplace = explode(
  134. ',',
  135. _x(
  136. '&#8217;tain&#8217;t,&#8217;twere,&#8217;twas,&#8217;tis,&#8217;twill,&#8217;til,&#8217;bout,&#8217;nuff,&#8217;round,&#8217;cause,&#8217;em',
  137. 'Comma-separated list of replacement words in your language'
  138. )
  139. );
  140. }
  141. $static_characters = array_merge( array( '...', '``', '\'\'', ' (tm)' ), $cockney );
  142. $static_replacements = array_merge( array( '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace );
  143. // Pattern-based replacements of characters.
  144. // Sort the remaining patterns into several arrays for performance tuning.
  145. $dynamic_characters = array(
  146. 'apos' => array(),
  147. 'quote' => array(),
  148. 'dash' => array(),
  149. );
  150. $dynamic_replacements = array(
  151. 'apos' => array(),
  152. 'quote' => array(),
  153. 'dash' => array(),
  154. );
  155. $dynamic = array();
  156. $spaces = wp_spaces_regexp();
  157. // '99' and '99" are ambiguous among other patterns; assume it's an abbreviated year at the end of a quotation.
  158. if ( "'" !== $apos || "'" !== $closing_single_quote ) {
  159. $dynamic[ '/\'(\d\d)\'(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_single_quote;
  160. }
  161. if ( "'" !== $apos || '"' !== $closing_quote ) {
  162. $dynamic[ '/\'(\d\d)"(?=\Z|[.,:;!?)}\-\]]|&gt;|' . $spaces . ')/' ] = $apos_flag . '$1' . $closing_quote;
  163. }
  164. // '99 '99s '99's (apostrophe) But never '9 or '99% or '999 or '99.0.
  165. if ( "'" !== $apos ) {
  166. $dynamic['/\'(?=\d\d(?:\Z|(?![%\d]|[.,]\d)))/'] = $apos_flag;
  167. }
  168. // Quoted numbers like '0.42'.
  169. if ( "'" !== $opening_single_quote && "'" !== $closing_single_quote ) {
  170. $dynamic[ '/(?<=\A|' . $spaces . ')\'(\d[.,\d]*)\'/' ] = $open_sq_flag . '$1' . $closing_single_quote;
  171. }
  172. // Single quote at start, or preceded by (, {, <, [, ", -, or spaces.
  173. if ( "'" !== $opening_single_quote ) {
  174. $dynamic[ '/(?<=\A|[([{"\-]|&lt;|' . $spaces . ')\'/' ] = $open_sq_flag;
  175. }
  176. // Apostrophe in a word. No spaces, double apostrophes, or other punctuation.
  177. if ( "'" !== $apos ) {
  178. $dynamic[ '/(?<!' . $spaces . ')\'(?!\Z|[.,:;!?"\'(){}[\]\-]|&[lg]t;|' . $spaces . ')/' ] = $apos_flag;
  179. }
  180. $dynamic_characters['apos'] = array_keys( $dynamic );
  181. $dynamic_replacements['apos'] = array_values( $dynamic );
  182. $dynamic = array();
  183. // Quoted numbers like "42".
  184. if ( '"' !== $opening_quote && '"' !== $closing_quote ) {
  185. $dynamic[ '/(?<=\A|' . $spaces . ')"(\d[.,\d]*)"/' ] = $open_q_flag . '$1' . $closing_quote;
  186. }
  187. // Double quote at start, or preceded by (, {, <, [, -, or spaces, and not followed by spaces.
  188. if ( '"' !== $opening_quote ) {
  189. $dynamic[ '/(?<=\A|[([{\-]|&lt;|' . $spaces . ')"(?!' . $spaces . ')/' ] = $open_q_flag;
  190. }
  191. $dynamic_characters['quote'] = array_keys( $dynamic );
  192. $dynamic_replacements['quote'] = array_values( $dynamic );
  193. $dynamic = array();
  194. // Dashes and spaces.
  195. $dynamic['/---/'] = $em_dash;
  196. $dynamic[ '/(?<=^|' . $spaces . ')--(?=$|' . $spaces . ')/' ] = $em_dash;
  197. $dynamic['/(?<!xn)--/'] = $en_dash;
  198. $dynamic[ '/(?<=^|' . $spaces . ')-(?=$|' . $spaces . ')/' ] = $en_dash;
  199. $dynamic_characters['dash'] = array_keys( $dynamic );
  200. $dynamic_replacements['dash'] = array_values( $dynamic );
  201. }
  202. // Must do this every time in case plugins use these filters in a context sensitive manner.
  203. /**
  204. * Filters the list of HTML elements not to texturize.
  205. *
  206. * @since 2.8.0
  207. *
  208. * @param string[] $default_no_texturize_tags An array of HTML element names.
  209. */
  210. $no_texturize_tags = apply_filters( 'no_texturize_tags', $default_no_texturize_tags );
  211. /**
  212. * Filters the list of shortcodes not to texturize.
  213. *
  214. * @since 2.8.0
  215. *
  216. * @param string[] $default_no_texturize_shortcodes An array of shortcode names.
  217. */
  218. $no_texturize_shortcodes = apply_filters( 'no_texturize_shortcodes', $default_no_texturize_shortcodes );
  219. $no_texturize_tags_stack = array();
  220. $no_texturize_shortcodes_stack = array();
  221. // Look for shortcodes and HTML elements.
  222. preg_match_all( '@\[/?([^<>&/\[\]\x00-\x20=]++)@', $text, $matches );
  223. $tagnames = array_intersect( array_keys( $shortcode_tags ), $matches[1] );
  224. $found_shortcodes = ! empty( $tagnames );
  225. $shortcode_regex = $found_shortcodes ? _get_wptexturize_shortcode_regex( $tagnames ) : '';
  226. $regex = _get_wptexturize_split_regex( $shortcode_regex );
  227. $textarr = preg_split( $regex, $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
  228. foreach ( $textarr as &$curl ) {
  229. // Only call _wptexturize_pushpop_element if $curl is a delimiter.
  230. $first = $curl[0];
  231. if ( '<' === $first ) {
  232. if ( '<!--' === substr( $curl, 0, 4 ) ) {
  233. // This is an HTML comment delimiter.
  234. continue;
  235. } else {
  236. // This is an HTML element delimiter.
  237. // Replace each & with &#038; unless it already looks like an entity.
  238. $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
  239. _wptexturize_pushpop_element( $curl, $no_texturize_tags_stack, $no_texturize_tags );
  240. }
  241. } elseif ( '' === trim( $curl ) ) {
  242. // This is a newline between delimiters. Performance improves when we check this.
  243. continue;
  244. } elseif ( '[' === $first && $found_shortcodes && 1 === preg_match( '/^' . $shortcode_regex . '$/', $curl ) ) {
  245. // This is a shortcode delimiter.
  246. if ( '[[' !== substr( $curl, 0, 2 ) && ']]' !== substr( $curl, -2 ) ) {
  247. // Looks like a normal shortcode.
  248. _wptexturize_pushpop_element( $curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes );
  249. } else {
  250. // Looks like an escaped shortcode.
  251. continue;
  252. }
  253. } elseif ( empty( $no_texturize_shortcodes_stack ) && empty( $no_texturize_tags_stack ) ) {
  254. // This is neither a delimiter, nor is this content inside of no_texturize pairs. Do texturize.
  255. $curl = str_replace( $static_characters, $static_replacements, $curl );
  256. if ( false !== strpos( $curl, "'" ) ) {
  257. $curl = preg_replace( $dynamic_characters['apos'], $dynamic_replacements['apos'], $curl );
  258. $curl = wptexturize_primes( $curl, "'", $prime, $open_sq_flag, $closing_single_quote );
  259. $curl = str_replace( $apos_flag, $apos, $curl );
  260. $curl = str_replace( $open_sq_flag, $opening_single_quote, $curl );
  261. }
  262. if ( false !== strpos( $curl, '"' ) ) {
  263. $curl = preg_replace( $dynamic_characters['quote'], $dynamic_replacements['quote'], $curl );
  264. $curl = wptexturize_primes( $curl, '"', $double_prime, $open_q_flag, $closing_quote );
  265. $curl = str_replace( $open_q_flag, $opening_quote, $curl );
  266. }
  267. if ( false !== strpos( $curl, '-' ) ) {
  268. $curl = preg_replace( $dynamic_characters['dash'], $dynamic_replacements['dash'], $curl );
  269. }
  270. // 9x9 (times), but never 0x9999.
  271. if ( 1 === preg_match( '/(?<=\d)x\d/', $curl ) ) {
  272. // Searching for a digit is 10 times more expensive than for the x, so we avoid doing this one!
  273. $curl = preg_replace( '/\b(\d(?(?<=0)[\d\.,]+|[\d\.,]*))x(\d[\d\.,]*)\b/', '$1&#215;$2', $curl );
  274. }
  275. // Replace each & with &#038; unless it already looks like an entity.
  276. $curl = preg_replace( '/&(?!#(?:\d+|x[a-f0-9]+);|[a-z1-4]{1,8};)/i', '&#038;', $curl );
  277. }
  278. }
  279. return implode( '', $textarr );
  280. }
  281. /**
  282. * Implements a logic tree to determine whether or not "7'." represents seven feet,
  283. * then converts the special char into either a prime char or a closing quote char.
  284. *
  285. * @since 4.3.0
  286. *
  287. * @param string $haystack The plain text to be searched.
  288. * @param string $needle The character to search for such as ' or ".
  289. * @param string $prime The prime char to use for replacement.
  290. * @param string $open_quote The opening quote char. Opening quote replacement must be
  291. * accomplished already.
  292. * @param string $close_quote The closing quote char to use for replacement.
  293. * @return string The $haystack value after primes and quotes replacements.
  294. */
  295. function wptexturize_primes( $haystack, $needle, $prime, $open_quote, $close_quote ) {
  296. $spaces = wp_spaces_regexp();
  297. $flag = '<!--wp-prime-or-quote-->';
  298. $quote_pattern = "/$needle(?=\\Z|[.,:;!?)}\\-\\]]|&gt;|" . $spaces . ')/';
  299. $prime_pattern = "/(?<=\\d)$needle/";
  300. $flag_after_digit = "/(?<=\\d)$flag/";
  301. $flag_no_digit = "/(?<!\\d)$flag/";
  302. $sentences = explode( $open_quote, $haystack );
  303. foreach ( $sentences as $key => &$sentence ) {
  304. if ( false === strpos( $sentence, $needle ) ) {
  305. continue;
  306. } elseif ( 0 !== $key && 0 === substr_count( $sentence, $close_quote ) ) {
  307. $sentence = preg_replace( $quote_pattern, $flag, $sentence, -1, $count );
  308. if ( $count > 1 ) {
  309. // This sentence appears to have multiple closing quotes. Attempt Vulcan logic.
  310. $sentence = preg_replace( $flag_no_digit, $close_quote, $sentence, -1, $count2 );
  311. if ( 0 === $count2 ) {
  312. // Try looking for a quote followed by a period.
  313. $count2 = substr_count( $sentence, "$flag." );
  314. if ( $count2 > 0 ) {
  315. // Assume the rightmost quote-period match is the end of quotation.
  316. $pos = strrpos( $sentence, "$flag." );
  317. } else {
  318. // When all else fails, make the rightmost candidate a closing quote.
  319. // This is most likely to be problematic in the context of bug #18549.
  320. $pos = strrpos( $sentence, $flag );
  321. }
  322. $sentence = substr_replace( $sentence, $close_quote, $pos, strlen( $flag ) );
  323. }
  324. // Use conventional replacement on any remaining primes and quotes.
  325. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  326. $sentence = preg_replace( $flag_after_digit, $prime, $sentence );
  327. $sentence = str_replace( $flag, $close_quote, $sentence );
  328. } elseif ( 1 == $count ) {
  329. // Found only one closing quote candidate, so give it priority over primes.
  330. $sentence = str_replace( $flag, $close_quote, $sentence );
  331. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  332. } else {
  333. // No closing quotes found. Just run primes pattern.
  334. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  335. }
  336. } else {
  337. $sentence = preg_replace( $prime_pattern, $prime, $sentence );
  338. $sentence = preg_replace( $quote_pattern, $close_quote, $sentence );
  339. }
  340. if ( '"' == $needle && false !== strpos( $sentence, '"' ) ) {
  341. $sentence = str_replace( '"', $close_quote, $sentence );
  342. }
  343. }
  344. return implode( $open_quote, $sentences );
  345. }
  346. /**
  347. * Search for disabled element tags. Push element to stack on tag open and pop
  348. * on tag close.
  349. *
  350. * Assumes first char of $text is tag opening and last char is tag closing.
  351. * Assumes second char of $text is optionally '/' to indicate closing as in </html>.
  352. *
  353. * @since 2.9.0
  354. * @access private
  355. *
  356. * @param string $text Text to check. Must be a tag like `<html>` or `[shortcode]`.
  357. * @param string[] $stack Array of open tag elements.
  358. * @param string[] $disabled_elements Array of tag names to match against. Spaces are not allowed in tag names.
  359. */
  360. function _wptexturize_pushpop_element( $text, &$stack, $disabled_elements ) {
  361. // Is it an opening tag or closing tag?
  362. if ( isset( $text[1] ) && '/' !== $text[1] ) {
  363. $opening_tag = true;
  364. $name_offset = 1;
  365. } elseif ( 0 == count( $stack ) ) {
  366. // Stack is empty. Just stop.
  367. return;
  368. } else {
  369. $opening_tag = false;
  370. $name_offset = 2;
  371. }
  372. // Parse out the tag name.
  373. $space = strpos( $text, ' ' );
  374. if ( false === $space ) {
  375. $space = -1;
  376. } else {
  377. $space -= $name_offset;
  378. }
  379. $tag = substr( $text, $name_offset, $space );
  380. // Handle disabled tags.
  381. if ( in_array( $tag, $disabled_elements, true ) ) {
  382. if ( $opening_tag ) {
  383. /*
  384. * This disables texturize until we find a closing tag of our type
  385. * (e.g. <pre>) even if there was invalid nesting before that.
  386. *
  387. * Example: in the case <pre>sadsadasd</code>"baba"</pre>
  388. * "baba" won't be texturized.
  389. */
  390. array_push( $stack, $tag );
  391. } elseif ( end( $stack ) == $tag ) {
  392. array_pop( $stack );
  393. }
  394. }
  395. }
  396. /**
  397. * Replaces double line-breaks with paragraph elements.
  398. *
  399. * A group of regex replaces used to identify text formatted with newlines and
  400. * replace double line-breaks with HTML paragraph tags. The remaining line-breaks
  401. * after conversion become <<br />> tags, unless $br is set to '0' or 'false'.
  402. *
  403. * @since 0.71
  404. *
  405. * @param string $pee The text which has to be formatted.
  406. * @param bool $br Optional. If set, this will convert all remaining line-breaks
  407. * after paragraphing. Default true.
  408. * @return string Text which has been converted into correct paragraph tags.
  409. */
  410. function wpautop( $pee, $br = true ) {
  411. $pre_tags = array();
  412. if ( trim( $pee ) === '' ) {
  413. return '';
  414. }
  415. // Just to make things a little easier, pad the end.
  416. $pee = $pee . "\n";
  417. /*
  418. * Pre tags shouldn't be touched by autop.
  419. * Replace pre tags with placeholders and bring them back after autop.
  420. */
  421. if ( strpos( $pee, '<pre' ) !== false ) {
  422. $pee_parts = explode( '</pre>', $pee );
  423. $last_pee = array_pop( $pee_parts );
  424. $pee = '';
  425. $i = 0;
  426. foreach ( $pee_parts as $pee_part ) {
  427. $start = strpos( $pee_part, '<pre' );
  428. // Malformed HTML?
  429. if ( false === $start ) {
  430. $pee .= $pee_part;
  431. continue;
  432. }
  433. $name = "<pre wp-pre-tag-$i></pre>";
  434. $pre_tags[ $name ] = substr( $pee_part, $start ) . '</pre>';
  435. $pee .= substr( $pee_part, 0, $start ) . $name;
  436. $i++;
  437. }
  438. $pee .= $last_pee;
  439. }
  440. // Change multiple <br>'s into two line breaks, which will turn into paragraphs.
  441. $pee = preg_replace( '|<br\s*/?>\s*<br\s*/?>|', "\n\n", $pee );
  442. $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)';
  443. // Add a double line break above block-level opening tags.
  444. $pee = preg_replace( '!(<' . $allblocks . '[\s/>])!', "\n\n$1", $pee );
  445. // Add a double line break below block-level closing tags.
  446. $pee = preg_replace( '!(</' . $allblocks . '>)!', "$1\n\n", $pee );
  447. // Add a double line break after hr tags, which are self closing.
  448. $pee = preg_replace( '!(<hr\s*?/?>)!', "$1\n\n", $pee );
  449. // Standardize newline characters to "\n".
  450. $pee = str_replace( array( "\r\n", "\r" ), "\n", $pee );
  451. // Find newlines in all elements and add placeholders.
  452. $pee = wp_replace_in_html_tags( $pee, array( "\n" => ' <!-- wpnl --> ' ) );
  453. // Collapse line breaks before and after <option> elements so they don't get autop'd.
  454. if ( strpos( $pee, '<option' ) !== false ) {
  455. $pee = preg_replace( '|\s*<option|', '<option', $pee );
  456. $pee = preg_replace( '|</option>\s*|', '</option>', $pee );
  457. }
  458. /*
  459. * Collapse line breaks inside <object> elements, before <param> and <embed> elements
  460. * so they don't get autop'd.
  461. */
  462. if ( strpos( $pee, '</object>' ) !== false ) {
  463. $pee = preg_replace( '|(<object[^>]*>)\s*|', '$1', $pee );
  464. $pee = preg_replace( '|\s*</object>|', '</object>', $pee );
  465. $pee = preg_replace( '%\s*(</?(?:param|embed)[^>]*>)\s*%', '$1', $pee );
  466. }
  467. /*
  468. * Collapse line breaks inside <audio> and <video> elements,
  469. * before and after <source> and <track> elements.
  470. */
  471. if ( strpos( $pee, '<source' ) !== false || strpos( $pee, '<track' ) !== false ) {
  472. $pee = preg_replace( '%([<\[](?:audio|video)[^>\]]*[>\]])\s*%', '$1', $pee );
  473. $pee = preg_replace( '%\s*([<\[]/(?:audio|video)[>\]])%', '$1', $pee );
  474. $pee = preg_replace( '%\s*(<(?:source|track)[^>]*>)\s*%', '$1', $pee );
  475. }
  476. // Collapse line breaks before and after <figcaption> elements.
  477. if ( strpos( $pee, '<figcaption' ) !== false ) {
  478. $pee = preg_replace( '|\s*(<figcaption[^>]*>)|', '$1', $pee );
  479. $pee = preg_replace( '|</figcaption>\s*|', '</figcaption>', $pee );
  480. }
  481. // Remove more than two contiguous line breaks.
  482. $pee = preg_replace( "/\n\n+/", "\n\n", $pee );
  483. // Split up the contents into an array of strings, separated by double line breaks.
  484. $pees = preg_split( '/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY );
  485. // Reset $pee prior to rebuilding.
  486. $pee = '';
  487. // Rebuild the content as a string, wrapping every bit with a <p>.
  488. foreach ( $pees as $tinkle ) {
  489. $pee .= '<p>' . trim( $tinkle, "\n" ) . "</p>\n";
  490. }
  491. // Under certain strange conditions it could create a P of entirely whitespace.
  492. $pee = preg_replace( '|<p>\s*</p>|', '', $pee );
  493. // Add a closing <p> inside <div>, <address>, or <form> tag if missing.
  494. $pee = preg_replace( '!<p>([^<]+)</(div|address|form)>!', '<p>$1</p></$2>', $pee );
  495. // If an opening or closing block element tag is wrapped in a <p>, unwrap it.
  496. $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
  497. // In some cases <li> may get wrapped in <p>, fix them.
  498. $pee = preg_replace( '|<p>(<li.+?)</p>|', '$1', $pee );
  499. // If a <blockquote> is wrapped with a <p>, move it inside the <blockquote>.
  500. $pee = preg_replace( '|<p><blockquote([^>]*)>|i', '<blockquote$1><p>', $pee );
  501. $pee = str_replace( '</blockquote></p>', '</p></blockquote>', $pee );
  502. // If an opening or closing block element tag is preceded by an opening <p> tag, remove it.
  503. $pee = preg_replace( '!<p>\s*(</?' . $allblocks . '[^>]*>)!', '$1', $pee );
  504. // If an opening or closing block element tag is followed by a closing <p> tag, remove it.
  505. $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*</p>!', '$1', $pee );
  506. // Optionally insert line breaks.
  507. if ( $br ) {
  508. // Replace newlines that shouldn't be touched with a placeholder.
  509. $pee = preg_replace_callback( '/<(script|style|svg).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee );
  510. // Normalize <br>
  511. $pee = str_replace( array( '<br>', '<br/>' ), '<br />', $pee );
  512. // Replace any new line characters that aren't preceded by a <br /> with a <br />.
  513. $pee = preg_replace( '|(?<!<br />)\s*\n|', "<br />\n", $pee );
  514. // Replace newline placeholders with newlines.
  515. $pee = str_replace( '<WPPreserveNewline />', "\n", $pee );
  516. }
  517. // If a <br /> tag is after an opening or closing block tag, remove it.
  518. $pee = preg_replace( '!(</?' . $allblocks . '[^>]*>)\s*<br />!', '$1', $pee );
  519. // If a <br /> tag is before a subset of opening or closing block tags, remove it.
  520. $pee = preg_replace( '!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee );
  521. $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
  522. // Replace placeholder <pre> tags with their original content.
  523. if ( ! empty( $pre_tags ) ) {
  524. $pee = str_replace( array_keys( $pre_tags ), array_values( $pre_tags ), $pee );
  525. }
  526. // Restore newlines in all elements.
  527. if ( false !== strpos( $pee, '<!-- wpnl -->' ) ) {
  528. $pee = str_replace( array( ' <!-- wpnl --> ', '<!-- wpnl -->' ), "\n", $pee );
  529. }
  530. return $pee;
  531. }
  532. /**
  533. * Separate HTML elements and comments from the text.
  534. *
  535. * @since 4.2.4
  536. *
  537. * @param string $input The text which has to be formatted.
  538. * @return string[] Array of the formatted text.
  539. */
  540. function wp_html_split( $input ) {
  541. return preg_split( get_html_split_regex(), $input, -1, PREG_SPLIT_DELIM_CAPTURE );
  542. }
  543. /**
  544. * Retrieve the regular expression for an HTML element.
  545. *
  546. * @since 4.4.0
  547. *
  548. * @staticvar string $regex
  549. *
  550. * @return string The regular expression
  551. */
  552. function get_html_split_regex() {
  553. static $regex;
  554. if ( ! isset( $regex ) ) {
  555. // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
  556. $comments =
  557. '!' // Start of comment, after the <.
  558. . '(?:' // Unroll the loop: Consume everything until --> is found.
  559. . '-(?!->)' // Dash not followed by end of comment.
  560. . '[^\-]*+' // Consume non-dashes.
  561. . ')*+' // Loop possessively.
  562. . '(?:-->)?'; // End of comment. If not found, match all input.
  563. $cdata =
  564. '!\[CDATA\[' // Start of comment, after the <.
  565. . '[^\]]*+' // Consume non-].
  566. . '(?:' // Unroll the loop: Consume everything until ]]> is found.
  567. . '](?!]>)' // One ] not followed by end of comment.
  568. . '[^\]]*+' // Consume non-].
  569. . ')*+' // Loop possessively.
  570. . '(?:]]>)?'; // End of comment. If not found, match all input.
  571. $escaped =
  572. '(?=' // Is the element escaped?
  573. . '!--'
  574. . '|'
  575. . '!\[CDATA\['
  576. . ')'
  577. . '(?(?=!-)' // If yes, which type?
  578. . $comments
  579. . '|'
  580. . $cdata
  581. . ')';
  582. $regex =
  583. '/(' // Capture the entire match.
  584. . '<' // Find start of element.
  585. . '(?' // Conditional expression follows.
  586. . $escaped // Find end of escaped element.
  587. . '|' // ...else...
  588. . '[^>]*>?' // Find end of normal element.
  589. . ')'
  590. . ')/';
  591. // phpcs:enable
  592. }
  593. return $regex;
  594. }
  595. /**
  596. * Retrieve the combined regular expression for HTML and shortcodes.
  597. *
  598. * @access private
  599. * @ignore
  600. * @internal This function will be removed in 4.5.0 per Shortcode API Roadmap.
  601. * @since 4.4.0
  602. *
  603. * @staticvar string $html_regex
  604. *
  605. * @param string $shortcode_regex The result from _get_wptexturize_shortcode_regex(). Optional.
  606. * @return string The regular expression
  607. */
  608. function _get_wptexturize_split_regex( $shortcode_regex = '' ) {
  609. static $html_regex;
  610. if ( ! isset( $html_regex ) ) {
  611. // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
  612. $comment_regex =
  613. '!' // Start of comment, after the <.
  614. . '(?:' // Unroll the loop: Consume everything until --> is found.
  615. . '-(?!->)' // Dash not followed by end of comment.
  616. . '[^\-]*+' // Consume non-dashes.
  617. . ')*+' // Loop possessively.
  618. . '(?:-->)?'; // End of comment. If not found, match all input.
  619. $html_regex = // Needs replaced with wp_html_split() per Shortcode API Roadmap.
  620. '<' // Find start of element.
  621. . '(?(?=!--)' // Is this a comment?
  622. . $comment_regex // Find end of comment.
  623. . '|'
  624. . '[^>]*>?' // Find end of element. If not found, match all input.
  625. . ')';
  626. // phpcs:enable
  627. }
  628. if ( empty( $shortcode_regex ) ) {
  629. $regex = '/(' . $html_regex . ')/';
  630. } else {
  631. $regex = '/(' . $html_regex . '|' . $shortcode_regex . ')/';
  632. }
  633. return $regex;
  634. }
  635. /**
  636. * Retrieve the regular expression for shortcodes.
  637. *
  638. * @access private
  639. * @ignore
  640. * @since 4.4.0
  641. *
  642. * @param string[] $tagnames Array of shortcodes to find.
  643. * @return string The regular expression
  644. */
  645. function _get_wptexturize_shortcode_regex( $tagnames ) {
  646. $tagregexp = join( '|', array_map( 'preg_quote', $tagnames ) );
  647. $tagregexp = "(?:$tagregexp)(?=[\\s\\]\\/])"; // Excerpt of get_shortcode_regex().
  648. // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
  649. $regex =
  650. '\[' // Find start of shortcode.
  651. . '[\/\[]?' // Shortcodes may begin with [/ or [[.
  652. . $tagregexp // Only match registered shortcodes, because performance.
  653. . '(?:'
  654. . '[^\[\]<>]+' // Shortcodes do not contain other shortcodes. Quantifier critical.
  655. . '|'
  656. . '<[^\[\]>]*>' // HTML elements permitted. Prevents matching ] before >.
  657. . ')*+' // Possessive critical.
  658. . '\]' // Find end of shortcode.
  659. . '\]?'; // Shortcodes may end with ]].
  660. // phpcs:enable
  661. return $regex;
  662. }
  663. /**
  664. * Replace characters or phrases within HTML elements only.
  665. *
  666. * @since 4.2.3
  667. *
  668. * @param string $haystack The text which has to be formatted.
  669. * @param array $replace_pairs In the form array('from' => 'to', ...).
  670. * @return string The formatted text.
  671. */
  672. function wp_replace_in_html_tags( $haystack, $replace_pairs ) {
  673. // Find all elements.
  674. $textarr = wp_html_split( $haystack );
  675. $changed = false;
  676. // Optimize when searching for one item.
  677. if ( 1 === count( $replace_pairs ) ) {
  678. // Extract $needle and $replace.
  679. foreach ( $replace_pairs as $needle => $replace ) {
  680. }
  681. // Loop through delimiters (elements) only.
  682. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
  683. if ( false !== strpos( $textarr[ $i ], $needle ) ) {
  684. $textarr[ $i ] = str_replace( $needle, $replace, $textarr[ $i ] );
  685. $changed = true;
  686. }
  687. }
  688. } else {
  689. // Extract all $needles.
  690. $needles = array_keys( $replace_pairs );
  691. // Loop through delimiters (elements) only.
  692. for ( $i = 1, $c = count( $textarr ); $i < $c; $i += 2 ) {
  693. foreach ( $needles as $needle ) {
  694. if ( false !== strpos( $textarr[ $i ], $needle ) ) {
  695. $textarr[ $i ] = strtr( $textarr[ $i ], $replace_pairs );
  696. $changed = true;
  697. // After one strtr() break out of the foreach loop and look at next element.
  698. break;
  699. }
  700. }
  701. }
  702. }
  703. if ( $changed ) {
  704. $haystack = implode( $textarr );
  705. }
  706. return $haystack;
  707. }
  708. /**
  709. * Newline preservation help function for wpautop
  710. *
  711. * @since 3.1.0
  712. * @access private
  713. *
  714. * @param array $matches preg_replace_callback matches array
  715. * @return string
  716. */
  717. function _autop_newline_preservation_helper( $matches ) {
  718. return str_replace( "\n", '<WPPreserveNewline />', $matches[0] );
  719. }
  720. /**
  721. * Don't auto-p wrap shortcodes that stand alone
  722. *
  723. * Ensures that shortcodes are not wrapped in `<p>...</p>`.
  724. *
  725. * @since 2.9.0
  726. *
  727. * @global array $shortcode_tags
  728. *
  729. * @param string $pee The content.
  730. * @return string The filtered content.
  731. */
  732. function shortcode_unautop( $pee ) {
  733. global $shortcode_tags;
  734. if ( empty( $shortcode_tags ) || ! is_array( $shortcode_tags ) ) {
  735. return $pee;
  736. }
  737. $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) );
  738. $spaces = wp_spaces_regexp();
  739. // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound,WordPress.WhiteSpace.PrecisionAlignment.Found -- don't remove regex indentation
  740. $pattern =
  741. '/'
  742. . '<p>' // Opening paragraph.
  743. . '(?:' . $spaces . ')*+' // Optional leading whitespace.
  744. . '(' // 1: The shortcode.
  745. . '\\[' // Opening bracket.
  746. . "($tagregexp)" // 2: Shortcode name.
  747. . '(?![\\w-])' // Not followed by word character or hyphen.
  748. // Unroll the loop: Inside the opening shortcode tag.
  749. . '[^\\]\\/]*' // Not a closing bracket or forward slash.
  750. . '(?:'
  751. . '\\/(?!\\])' // A forward slash not followed by a closing bracket.
  752. . '[^\\]\\/]*' // Not a closing bracket or forward slash.
  753. . ')*?'
  754. . '(?:'
  755. . '\\/\\]' // Self closing tag and closing bracket.
  756. . '|'
  757. . '\\]' // Closing bracket.
  758. . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags.
  759. . '[^\\[]*+' // Not an opening bracket.
  760. . '(?:'
  761. . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag.
  762. . '[^\\[]*+' // Not an opening bracket.
  763. . ')*+'
  764. . '\\[\\/\\2\\]' // Closing shortcode tag.
  765. . ')?'
  766. . ')'
  767. . ')'
  768. . '(?:' . $spaces . ')*+' // Optional trailing whitespace.
  769. . '<\\/p>' // Closing paragraph.
  770. . '/';
  771. // phpcs:enable
  772. return preg_replace( $pattern, '$1', $pee );
  773. }
  774. /**
  775. * Checks to see if a string is utf8 encoded.
  776. *
  777. * NOTE: This function checks for 5-Byte sequences, UTF8
  778. * has Bytes Sequences with a maximum length of 4.
  779. *
  780. * @author bmorel at ssi dot fr (modified)
  781. * @since 1.2.1
  782. *
  783. * @param string $str The string to be checked
  784. * @return bool True if $str fits a UTF-8 model, false otherwise.
  785. */
  786. function seems_utf8( $str ) {
  787. mbstring_binary_safe_encoding();
  788. $length = strlen( $str );
  789. reset_mbstring_encoding();
  790. for ( $i = 0; $i < $length; $i++ ) {
  791. $c = ord( $str[ $i ] );
  792. if ( $c < 0x80 ) {
  793. $n = 0; // 0bbbbbbb
  794. } elseif ( ( $c & 0xE0 ) == 0xC0 ) {
  795. $n = 1; // 110bbbbb
  796. } elseif ( ( $c & 0xF0 ) == 0xE0 ) {
  797. $n = 2; // 1110bbbb
  798. } elseif ( ( $c & 0xF8 ) == 0xF0 ) {
  799. $n = 3; // 11110bbb
  800. } elseif ( ( $c & 0xFC ) == 0xF8 ) {
  801. $n = 4; // 111110bb
  802. } elseif ( ( $c & 0xFE ) == 0xFC ) {
  803. $n = 5; // 1111110b
  804. } else {
  805. return false; // Does not match any model.
  806. }
  807. for ( $j = 0; $j < $n; $j++ ) { // n bytes matching 10bbbbbb follow ?
  808. if ( ( ++$i == $length ) || ( ( ord( $str[ $i ] ) & 0xC0 ) != 0x80 ) ) {
  809. return false;
  810. }
  811. }
  812. }
  813. return true;
  814. }
  815. /**
  816. * Converts a number of special characters into their HTML entities.
  817. *
  818. * Specifically deals with: &, <, >, ", and '.
  819. *
  820. * $quote_style can be set to ENT_COMPAT to encode " to
  821. * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
  822. *
  823. * @since 1.2.2
  824. * @access private
  825. *
  826. * @staticvar string $_charset
  827. *
  828. * @param string $string The text which is to be encoded.
  829. * @param int|string $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
  830. * both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES.
  831. * Also compatible with old values; converting single quotes if set to 'single',
  832. * double if set to 'double' or both if otherwise set.
  833. * Default is ENT_NOQUOTES.
  834. * @param false|string $charset Optional. The character encoding of the string. Default is false.
  835. * @param bool $double_encode Optional. Whether to encode existing html entities. Default is false.
  836. * @return string The encoded text with HTML entities.
  837. */
  838. function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
  839. $string = (string) $string;
  840. if ( 0 === strlen( $string ) ) {
  841. return '';
  842. }
  843. // Don't bother if there are no specialchars - saves some processing.
  844. if ( ! preg_match( '/[&<>"\']/', $string ) ) {
  845. return $string;
  846. }
  847. // Account for the previous behaviour of the function when the $quote_style is not an accepted value.
  848. if ( empty( $quote_style ) ) {
  849. $quote_style = ENT_NOQUOTES;
  850. } elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  851. $quote_style = ENT_QUOTES;
  852. }
  853. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions().
  854. if ( ! $charset ) {
  855. static $_charset = null;
  856. if ( ! isset( $_charset ) ) {
  857. $alloptions = wp_load_alloptions();
  858. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  859. }
  860. $charset = $_charset;
  861. }
  862. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ), true ) ) {
  863. $charset = 'UTF-8';
  864. }
  865. $_quote_style = $quote_style;
  866. if ( 'double' === $quote_style ) {
  867. $quote_style = ENT_COMPAT;
  868. $_quote_style = ENT_COMPAT;
  869. } elseif ( 'single' === $quote_style ) {
  870. $quote_style = ENT_NOQUOTES;
  871. }
  872. if ( ! $double_encode ) {
  873. // Guarantee every &entity; is valid, convert &garbage; into &amp;garbage;
  874. // This is required for PHP < 5.4.0 because ENT_HTML401 flag is unavailable.
  875. $string = wp_kses_normalize_entities( $string );
  876. }
  877. $string = htmlspecialchars( $string, $quote_style, $charset, $double_encode );
  878. // Back-compat.
  879. if ( 'single' === $_quote_style ) {
  880. $string = str_replace( "'", '&#039;', $string );
  881. }
  882. return $string;
  883. }
  884. /**
  885. * Converts a number of HTML entities into their special characters.
  886. *
  887. * Specifically deals with: &, <, >, ", and '.
  888. *
  889. * $quote_style can be set to ENT_COMPAT to decode " entities,
  890. * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
  891. *
  892. * @since 2.8.0
  893. *
  894. * @param string $string The text which is to be decoded.
  895. * @param string|int $quote_style Optional. Converts double quotes if set to ENT_COMPAT,
  896. * both single and double if set to ENT_QUOTES or
  897. * none if set to ENT_NOQUOTES.
  898. * Also compatible with old _wp_specialchars() values;
  899. * converting single quotes if set to 'single',
  900. * double if set to 'double' or both if otherwise set.
  901. * Default is ENT_NOQUOTES.
  902. * @return string The decoded text without HTML entities.
  903. */
  904. function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
  905. $string = (string) $string;
  906. if ( 0 === strlen( $string ) ) {
  907. return '';
  908. }
  909. // Don't bother if there are no entities - saves a lot of processing.
  910. if ( strpos( $string, '&' ) === false ) {
  911. return $string;
  912. }
  913. // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value.
  914. if ( empty( $quote_style ) ) {
  915. $quote_style = ENT_NOQUOTES;
  916. } elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  917. $quote_style = ENT_QUOTES;
  918. }
  919. // More complete than get_html_translation_table( HTML_SPECIALCHARS ).
  920. $single = array(
  921. '&#039;' => '\'',
  922. '&#x27;' => '\'',
  923. );
  924. $single_preg = array(
  925. '/&#0*39;/' => '&#039;',
  926. '/&#x0*27;/i' => '&#x27;',
  927. );
  928. $double = array(
  929. '&quot;' => '"',
  930. '&#034;' => '"',
  931. '&#x22;' => '"',
  932. );
  933. $double_preg = array(
  934. '/&#0*34;/' => '&#034;',
  935. '/&#x0*22;/i' => '&#x22;',
  936. );
  937. $others = array(
  938. '&lt;' => '<',
  939. '&#060;' => '<',
  940. '&gt;' => '>',
  941. '&#062;' => '>',
  942. '&amp;' => '&',
  943. '&#038;' => '&',
  944. '&#x26;' => '&',
  945. );
  946. $others_preg = array(
  947. '/&#0*60;/' => '&#060;',
  948. '/&#0*62;/' => '&#062;',
  949. '/&#0*38;/' => '&#038;',
  950. '/&#x0*26;/i' => '&#x26;',
  951. );
  952. if ( ENT_QUOTES === $quote_style ) {
  953. $translation = array_merge( $single, $double, $others );
  954. $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
  955. } elseif ( ENT_COMPAT === $quote_style || 'double' === $quote_style ) {
  956. $translation = array_merge( $double, $others );
  957. $translation_preg = array_merge( $double_preg, $others_preg );
  958. } elseif ( 'single' === $quote_style ) {
  959. $translation = array_merge( $single, $others );
  960. $translation_preg = array_merge( $single_preg, $others_preg );
  961. } elseif ( ENT_NOQUOTES === $quote_style ) {
  962. $translation = $others;
  963. $translation_preg = $others_preg;
  964. }
  965. // Remove zero padding on numeric entities.
  966. $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
  967. // Replace characters according to translation table.
  968. return strtr( $string, $translation );
  969. }
  970. /**
  971. * Checks for invalid UTF8 in a string.
  972. *
  973. * @since 2.8.0
  974. *
  975. * @staticvar bool $is_utf8
  976. * @staticvar bool $utf8_pcre
  977. *
  978. * @param string $string The text which is to be checked.
  979. * @param bool $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
  980. * @return string The checked text.
  981. */
  982. function wp_check_invalid_utf8( $string, $strip = false ) {
  983. $string = (string) $string;
  984. if ( 0 === strlen( $string ) ) {
  985. return '';
  986. }
  987. // Store the site charset as a static to avoid multiple calls to get_option().
  988. static $is_utf8 = null;
  989. if ( ! isset( $is_utf8 ) ) {
  990. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ), true );
  991. }
  992. if ( ! $is_utf8 ) {
  993. return $string;
  994. }
  995. // Check for support for utf8 in the installed PCRE library once and store the result in a static.
  996. static $utf8_pcre = null;
  997. if ( ! isset( $utf8_pcre ) ) {
  998. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  999. $utf8_pcre = @preg_match( '/^./u', 'a' );
  1000. }
  1001. // We can't demand utf8 in the PCRE installation, so just return the string in those cases.
  1002. if ( ! $utf8_pcre ) {
  1003. return $string;
  1004. }
  1005. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged -- preg_match fails when it encounters invalid UTF8 in $string.
  1006. if ( 1 === @preg_match( '/^./us', $string ) ) {
  1007. return $string;
  1008. }
  1009. // Attempt to strip the bad chars if requested (not recommended).
  1010. if ( $strip && function_exists( 'iconv' ) ) {
  1011. return iconv( 'utf-8', 'utf-8', $string );
  1012. }
  1013. return '';
  1014. }
  1015. /**
  1016. * Encode the Unicode values to be used in the URI.
  1017. *
  1018. * @since 1.5.0
  1019. *
  1020. * @param string $utf8_string
  1021. * @param int $length Max length of the string
  1022. * @return string String with Unicode encoded for URI.
  1023. */
  1024. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  1025. $unicode = '';
  1026. $values = array();
  1027. $num_octets = 1;
  1028. $unicode_length = 0;
  1029. mbstring_binary_safe_encoding();
  1030. $string_length = strlen( $utf8_string );
  1031. reset_mbstring_encoding();
  1032. for ( $i = 0; $i < $string_length; $i++ ) {
  1033. $value = ord( $utf8_string[ $i ] );
  1034. if ( $value < 128 ) {
  1035. if ( $length && ( $unicode_length >= $length ) ) {
  1036. break;
  1037. }
  1038. $unicode .= chr( $value );
  1039. $unicode_length++;
  1040. } else {
  1041. if ( count( $values ) == 0 ) {
  1042. if ( $value < 224 ) {
  1043. $num_octets = 2;
  1044. } elseif ( $value < 240 ) {
  1045. $num_octets = 3;
  1046. } else {
  1047. $num_octets = 4;
  1048. }
  1049. }
  1050. $values[] = $value;
  1051. if ( $length && ( $unicode_length + ( $num_octets * 3 ) ) > $length ) {
  1052. break;
  1053. }
  1054. if ( count( $values ) == $num_octets ) {
  1055. for ( $j = 0; $j < $num_octets; $j++ ) {
  1056. $unicode .= '%' . dechex( $values[ $j ] );
  1057. }
  1058. $unicode_length += $num_octets * 3;
  1059. $values = array();
  1060. $num_octets = 1;
  1061. }
  1062. }
  1063. }
  1064. return $unicode;
  1065. }
  1066. /**
  1067. * Converts all accent characters to ASCII characters.
  1068. *
  1069. * If there are no accent characters, then the string given is just returned.
  1070. *
  1071. * **Accent characters converted:**
  1072. *
  1073. * Currency signs:
  1074. *
  1075. * | Code | Glyph | Replacement | Description |
  1076. * | -------- | ----- | ----------- | ------------------- |
  1077. * | U+00A3 | £ | (empty) | British Pound sign |
  1078. * | U+20AC | € | E | Euro sign |
  1079. *
  1080. * Decompositions for Latin-1 Supplement:
  1081. *
  1082. * | Code | Glyph | Replacement | Description |
  1083. * | ------- | ----- | ----------- | -------------------------------------- |
  1084. * | U+00AA | ª | a | Feminine ordinal indicator |
  1085. * | U+00BA | º | o | Masculine ordinal indicator |
  1086. * | U+00C0 | À | A | Latin capital letter A with grave |
  1087. * | U+00C1 | Á | A | Latin capital letter A with acute |
  1088. * | U+00C2 | Â | A | Latin capital letter A with circumflex |
  1089. * | U+00C3 | Ã | A | Latin capital letter A with tilde |
  1090. * | U+00C4 | Ä | A | Latin capital letter A with diaeresis |
  1091. * | U+00C5 | Å | A | Latin capital letter A with ring above |
  1092. * | U+00C6 | Æ | AE | Latin capital letter AE |
  1093. * | U+00C7 | Ç | C | Latin capital letter C with cedilla |
  1094. * | U+00C8 | È | E | Latin capital letter E with grave |
  1095. * | U+00C9 | É | E | Latin capital letter E with acute |
  1096. * | U+00CA | Ê | E | Latin capital letter E with circumflex |
  1097. * | U+00CB | Ë | E | Latin capital letter E with diaeresis |
  1098. * | U+00CC | Ì | I | Latin capital letter I with grave |
  1099. * | U+00CD | Í | I | Latin capital letter I with acute |
  1100. * | U+00CE | Î | I | Latin capital letter I with circumflex |
  1101. * | U+00CF | Ï | I | Latin capital letter I with diaeresis |
  1102. * | U+00D0 | Ð | D | Latin capital letter Eth |
  1103. * | U+00D1 | Ñ | N | Latin capital letter N with tilde |
  1104. * | U+00D2 | Ò | O | Latin capital letter O with grave |
  1105. * | U+00D3 | Ó | O | Latin capital letter O with acute |
  1106. * | U+00D4 | Ô | O | Latin capital letter O with circumflex |
  1107. * | U+00D5 | Õ | O | Latin capital letter O with tilde |
  1108. * | U+00D6 | Ö | O | Latin capital letter O with diaeresis |
  1109. * | U+00D8 | Ø | O | Latin capital letter O with stroke |
  1110. * | U+00D9 | Ù | U | Latin capital letter U with grave |
  1111. * | U+00DA | Ú | U | Latin capital letter U with acute |
  1112. * | U+00DB | Û | U | Latin capital letter U with circumflex |
  1113. * | U+00DC | Ü | U | Latin capital letter U with diaeresis |
  1114. * | U+00DD | Ý | Y | Latin capital letter Y with acute |
  1115. * | U+00DE | Þ | TH | Latin capital letter Thorn |
  1116. * | U+00DF | ß | s | Latin small letter sharp s |
  1117. * | U+00E0 | à | a | Latin small letter a with grave |
  1118. * | U+00E1 | á | a | Latin small letter a with acute |
  1119. * | U+00E2 | â | a | Latin small letter a with circumflex |
  1120. * | U+00E3 | ã | a | Latin small letter a with tilde |
  1121. * | U+00E4 | ä | a | Latin small letter a with diaeresis |
  1122. * | U+00E5 | å | a | Latin small letter a with ring above |
  1123. * | U+00E6 | æ | ae | Latin small letter ae |
  1124. * | U+00E7 | ç | c | Latin small letter c with cedilla |
  1125. * | U+00E8 | è | e | Latin small letter e with grave |
  1126. * | U+00E9 | é | e | Latin small letter e with acute |
  1127. * | U+00EA | ê | e | Latin small letter e with circumflex |
  1128. * | U+00EB | ë | e | Latin small letter e with diaeresis |
  1129. * | U+00EC | ì | i | Latin small letter i with grave |
  1130. * | U+00ED | í | i | Latin small letter i with acute |
  1131. * | U+00EE | î | i | Latin small letter i with circumflex |
  1132. * | U+00EF | ï | i | Latin small letter i with diaeresis |
  1133. * | U+00F0 | ð | d | Latin small letter Eth |
  1134. * | U+00F1 | ñ | n | Latin small letter n with tilde |
  1135. * | U+00F2 | ò | o | Latin small letter o with grave |
  1136. * | U+00F3 | ó | o | Latin small letter o with acute |
  1137. * | U+00F4 | ô | o | Latin small letter o with circumflex |
  1138. * | U+00F5 | õ | o | Latin small letter o with tilde |
  1139. * | U+00F6 | ö | o | Latin small letter o with diaeresis |
  1140. * | U+00F8 | ø | o | Latin small letter o with stroke |
  1141. * | U+00F9 | ù | u | Latin small letter u with grave |
  1142. * | U+00FA | ú | u | Latin small letter u with acute |
  1143. * | U+00FB | û | u | Latin small letter u with circumflex |
  1144. * | U+00FC | ü | u | Latin small letter u with diaeresis |
  1145. * | U+00FD | ý | y | Latin small letter y with acute |
  1146. * | U+00FE | þ | th | Latin small letter Thorn |
  1147. * | U+00FF | ÿ | y | Latin small letter y with diaeresis |
  1148. *
  1149. * Decompositions for Latin Extended-A:
  1150. *
  1151. * | Code | Glyph | Replacement | Description |
  1152. * | ------- | ----- | ----------- | ------------------------------------------------- |
  1153. * | U+0100 | Ā | A | Latin capital letter A with macron |
  1154. * | U+0101 | ā | a | Latin small letter a with macron |
  1155. * | U+0102 | Ă | A | Latin capital letter A with breve |
  1156. * | U+0103 | ă | a | Latin small letter a with breve |
  1157. * | U+0104 | Ą | A | Latin capital letter A with ogonek |
  1158. * | U+0105 | ą | a | Latin small letter a with ogonek |
  1159. * | U+01006 | Ć | C | Latin capital letter C with acute |
  1160. * | U+0107 | ć | c | Latin small letter c with acute |
  1161. * | U+0108 | Ĉ | C | Latin capital letter C with circumflex |
  1162. * | U+0109 | ĉ | c | Latin small letter c with circumflex |
  1163. * | U+010A | Ċ | C | Latin capital letter C with dot above |
  1164. * | U+010B | ċ | c | Latin small letter c with dot above |
  1165. * | U+010C | Č | C | Latin capital letter C with caron |
  1166. * | U+010D | č | c | Latin small letter c with caron |
  1167. * | U+010E | Ď | D | Latin capital letter D with caron |
  1168. * | U+010F | ď | d | Latin small letter d with caron |
  1169. * | U+0110 | Đ | D | Latin capital letter D with stroke |
  1170. * | U+0111 | đ | d | Latin small letter…

Large files files are truncated, but you can click here to view the full file