PageRenderTime 68ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/formatting.php

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