PageRenderTime 71ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/APP/wp-includes/formatting.php

https://bitbucket.org/AFelipeTrujillo/goblog
PHP | 3827 lines | 2273 code | 302 blank | 1252 comment | 310 complexity | 19afd3e550fd94adeadaee57dab15718 MD5 | raw file
Possible License(s): GPL-2.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. $diff = (int) abs( $to - $from );
  2089. if ( $diff < HOUR_IN_SECONDS ) {
  2090. $mins = round( $diff / MINUTE_IN_SECONDS );
  2091. if ( $mins <= 1 )
  2092. $mins = 1;
  2093. /* translators: min=minute */
  2094. $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins );
  2095. } elseif ( $diff < DAY_IN_SECONDS && $diff >= HOUR_IN_SECONDS ) {
  2096. $hours = round( $diff / HOUR_IN_SECONDS );
  2097. if ( $hours <= 1 )
  2098. $hours = 1;
  2099. $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours );
  2100. } elseif ( $diff < WEEK_IN_SECONDS && $diff >= DAY_IN_SECONDS ) {
  2101. $days = round( $diff / DAY_IN_SECONDS );
  2102. if ( $days <= 1 )
  2103. $days = 1;
  2104. $since = sprintf( _n( '%s day', '%s days', $days ), $days );
  2105. } elseif ( $diff < 30 * DAY_IN_SECONDS && $diff >= WEEK_IN_SECONDS ) {
  2106. $weeks = round( $diff / WEEK_IN_SECONDS );
  2107. if ( $weeks <= 1 )
  2108. $weeks = 1;
  2109. $since = sprintf( _n( '%s week', '%s weeks', $weeks ), $weeks );
  2110. } elseif ( $diff < YEAR_IN_SECONDS && $diff >= 30 * DAY_IN_SECONDS ) {
  2111. $months = round( $diff / ( 30 * DAY_IN_SECONDS ) );
  2112. if ( $months <= 1 )
  2113. $months = 1;
  2114. $since = sprintf( _n( '%s month', '%s months', $months ), $months );
  2115. } elseif ( $diff >= YEAR_IN_SECONDS ) {
  2116. $years = round( $diff / YEAR_IN_SECONDS );
  2117. if ( $years <= 1 )
  2118. $years = 1;
  2119. $since = sprintf( _n( '%s year', '%s years', $years ), $years );
  2120. }
  2121. return $since;
  2122. }
  2123. /**
  2124. * Generates an excerpt from the content, if needed.
  2125. *
  2126. * The excerpt word amount will be 55 words and if the amount is greater than
  2127. * that, then the string ' [&hellip;]' will be appended to the excerpt. If the string
  2128. * is less than 55 words, then the content will be returned as is.
  2129. *
  2130. * The 55 word limit can be modified by plugins/themes using the excerpt_length filter
  2131. * The ' [&hellip;]' string can be modified by plugins/themes using the excerpt_more filter
  2132. *
  2133. * @since 1.5.0
  2134. *
  2135. * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated.
  2136. * @return string The excerpt.
  2137. */
  2138. function wp_trim_excerpt($text = '') {
  2139. $raw_excerpt = $text;
  2140. if ( '' == $text ) {
  2141. $text = get_the_content('');
  2142. $text = strip_shortcodes( $text );
  2143. /** This filter is documented in wp-includes/post-template.php */
  2144. $text = apply_filters( 'the_content', $text );
  2145. $text = str_replace(']]>', ']]&gt;', $text);
  2146. /**
  2147. * Filter the number of words in an excerpt.
  2148. *
  2149. * @since 2.7.0
  2150. *
  2151. * @param int $number The number of words. Default 55.
  2152. */
  2153. $excerpt_length = apply_filters( 'excerpt_length', 55 );
  2154. /**
  2155. * Filter the string in the "more" link displayed after a trimmed excerpt.
  2156. *
  2157. * @since 2.9.0
  2158. *
  2159. * @param string $more_string The string shown within the more link.
  2160. */
  2161. $excerpt_more = apply_filters( 'excerpt_more', ' ' . '[&hellip;]' );
  2162. $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
  2163. }
  2164. /**
  2165. * Filter the trimmed excerpt string.
  2166. *
  2167. * @since 2.8.0
  2168. *
  2169. * @param string $text The trimmed text.
  2170. * @param string $raw_excerpt The text prior to trimming.
  2171. */
  2172. return apply_filters( 'wp_trim_excerpt', $text, $raw_excerpt );
  2173. }
  2174. /**
  2175. * Trims text to a certain number of words.
  2176. *
  2177. * This function is localized. For languages that count 'words' by the individual
  2178. * character (such as East Asian languages), the $num_words argument will apply
  2179. * to the number of individual characters.
  2180. *
  2181. * @since 3.3.0
  2182. *
  2183. * @param string $text Text to trim.
  2184. * @param int $num_words Number of words. Default 55.
  2185. * @param string $more Optional. What to append if $text needs to be trimmed. Default '&hellip;'.
  2186. * @return string Trimmed text.
  2187. */
  2188. function wp_trim_words( $text, $num_words = 55, $more = null ) {
  2189. if ( null === $more )
  2190. $more = __( '&hellip;' );
  2191. $original_text = $text;
  2192. $text = wp_strip_all_tags( $text );
  2193. /* translators: If your word count is based on single characters (East Asian characters),
  2194. enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */
  2195. if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
  2196. $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
  2197. preg_match_all( '/./u', $text, $words_array );
  2198. $words_array = array_slice( $words_array[0], 0, $num_words + 1 );
  2199. $sep = '';
  2200. } else {
  2201. $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
  2202. $sep = ' ';
  2203. }
  2204. if ( count( $words_array ) > $num_words ) {
  2205. array_pop( $words_array );
  2206. $text = implode( $sep, $words_array );
  2207. $text = $text . $more;
  2208. } else {
  2209. $text = implode( $sep, $words_array );
  2210. }
  2211. /**
  2212. * Filter the text content after words have been trimmed.
  2213. *
  2214. * @since 3.3.0
  2215. *
  2216. * @param string $text The trimmed text.
  2217. * @param int $num_words The number of words to trim the text to. Default 5.
  2218. * @param string $more An optional string to append to the end of the trimmed text, e.g. &hellip;.
  2219. * @param string $original_text The text before it was trimmed.
  2220. */
  2221. return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text );
  2222. }
  2223. /**
  2224. * Converts named entities into numbered entities.
  2225. *
  2226. * @since 1.5.1
  2227. *
  2228. * @param string $text The text within which entities will be converted.
  2229. * @return string Text with converted entities.
  2230. */
  2231. function ent2ncr($text) {
  2232. /**
  2233. * Filter text before named entities are converted into numbered entities.
  2234. *
  2235. * A non-null string must be returned for the filter to be evaluated.
  2236. *
  2237. * @since 3.3.0
  2238. *
  2239. * @param null $converted_text The text to be converted. Default null.
  2240. * @param string $text The text prior to entity conversion.
  2241. */
  2242. $filtered = apply_filters( 'pre_ent2ncr', null, $text );
  2243. if( null !== $filtered )
  2244. return $filtered;
  2245. $to_ncr = array(
  2246. '&quot;' => '&#34;',
  2247. '&amp;' => '&#38;',
  2248. '&lt;' => '&#60;',
  2249. '&gt;' => '&#62;',
  2250. '|' => '&#124;',
  2251. '&nbsp;' => '&#160;',
  2252. '&iexcl;' => '&#161;',
  2253. '&cent;' => '&#162;',
  2254. '&pound;' => '&#163;',
  2255. '&curren;' => '&#164;',
  2256. '&yen;' => '&#165;',
  2257. '&brvbar;' => '&#166;',
  2258. '&brkbar;' => '&#166;',
  2259. '&sect;' => '&#167;',
  2260. '&uml;' => '&#168;',
  2261. '&die;' => '&#168;',
  2262. '&copy;' => '&#169;',
  2263. '&ordf;' => '&#170;',
  2264. '&laquo;' => '&#171;',
  2265. '&not;' => '&#172;',
  2266. '&shy;' => '&#173;',
  2267. '&reg;' => '&#174;',
  2268. '&macr;' => '&#175;',
  2269. '&hibar;' => '&#175;',
  2270. '&deg;' => '&#176;',
  2271. '&plusmn;' => '&#177;',
  2272. '&sup2;' => '&#178;',
  2273. '&sup3;' => '&#179;',
  2274. '&acute;' => '&#180;',
  2275. '&micro;' => '&#181;',
  2276. '&para;' => '&#182;',
  2277. '&middot;' => '&#183;',
  2278. '&cedil;' => '&#184;',
  2279. '&sup1;' => '&#185;',
  2280. '&ordm;' => '&#186;',
  2281. '&raquo;' => '&#187;',
  2282. '&frac14;' => '&#188;',
  2283. '&frac12;' => '&#189;',
  2284. '&frac34;' => '&#190;',
  2285. '&iquest;' => '&#191;',
  2286. '&Agrave;' => '&#192;',
  2287. '&Aacute;' => '&#193;',
  2288. '&Acirc;' => '&#194;',
  2289. '&Atilde;' => '&#195;',
  2290. '&Auml;' => '&#196;',
  2291. '&Aring;' => '&#197;',
  2292. '&AElig;' => '&#198;',
  2293. '&Ccedil;' => '&#199;',
  2294. '&Egrave;' => '&#200;',
  2295. '&Eacute;' => '&#201;',
  2296. '&Ecirc;' => '&#202;',
  2297. '&Euml;' => '&#203;',
  2298. '&Igrave;' => '&#204;',
  2299. '&Iacute;' => '&#205;',
  2300. '&Icirc;' => '&#206;',
  2301. '&Iuml;' => '&#207;',
  2302. '&ETH;' => '&#208;',
  2303. '&Ntilde;' => '&#209;',
  2304. '&Ograve;' => '&#210;',
  2305. '&Oacute;' => '&#211;',
  2306. '&Ocirc;' => '&#212;',
  2307. '&Otilde;' => '&#213;',
  2308. '&Ouml;' => '&#214;',
  2309. '&times;' => '&#215;',
  2310. '&Oslash;' => '&#216;',
  2311. '&Ugrave;' => '&#217;',
  2312. '&Uacute;' => '&#218;',
  2313. '&Ucirc;' => '&#219;',
  2314. '&Uuml;' => '&#220;',
  2315. '&Yacute;' => '&#221;',
  2316. '&THORN;' => '&#222;',
  2317. '&szlig;' => '&#223;',
  2318. '&agrave;' => '&#224;',
  2319. '&aacute;' => '&#225;',
  2320. '&acirc;' => '&#226;',
  2321. '&atilde;' => '&#227;',
  2322. '&auml;' => '&#228;',
  2323. '&aring;' => '&#229;',
  2324. '&aelig;' => '&#230;',
  2325. '&ccedil;' => '&#231;',
  2326. '&egrave;' => '&#232;',
  2327. '&eacute;' => '&#233;',
  2328. '&ecirc;' => '&#234;',
  2329. '&euml;' => '&#235;',
  2330. '&igrave;' => '&#236;',
  2331. '&iacute;' => '&#237;',
  2332. '&icirc;' => '&#238;',
  2333. '&iuml;' => '&#239;',
  2334. '&eth;' => '&#240;',
  2335. '&ntilde;' => '&#241;',
  2336. '&ograve;' => '&#242;',
  2337. '&oacute;' => '&#243;',
  2338. '&ocirc;' => '&#244;',
  2339. '&otilde;' => '&#245;',
  2340. '&ouml;' => '&#246;',
  2341. '&divide;' => '&#247;',
  2342. '&oslash;' => '&#248;',
  2343. '&ugrave;' => '&#249;',
  2344. '&uacute;' => '&#250;',
  2345. '&ucirc;' => '&#251;',
  2346. '&uuml;' => '&#252;',
  2347. '&yacute;' => '&#253;',
  2348. '&thorn;' => '&#254;',
  2349. '&yuml;' => '&#255;',
  2350. '&OElig;' => '&#338;',
  2351. '&oelig;' => '&#339;',
  2352. '&Scaron;' => '&#352;',
  2353. '&scaron;' => '&#353;',
  2354. '&Yuml;' => '&#376;',
  2355. '&fnof;' => '&#402;',
  2356. '&circ;' => '&#710;',
  2357. '&tilde;' => '&#732;',
  2358. '&Alpha;' => '&#913;',
  2359. '&Beta;' => '&#914;',
  2360. '&Gamma;' => '&#915;',
  2361. '&Delta;' => '&#916;',
  2362. '&Epsilon;' => '&#917;',
  2363. '&Zeta;' => '&#918;',
  2364. '&Eta;' => '&#919;',
  2365. '&Theta;' => '&#920;',
  2366. '&Iota;' => '&#921;',
  2367. '&Kappa;' => '&#922;',
  2368. '&Lambda;' => '&#923;',
  2369. '&Mu;' => '&#924;',
  2370. '&Nu;' => '&#925;',
  2371. '&Xi;' => '&#926;',
  2372. '&Omicron;' => '&#927;',
  2373. '&Pi;' => '&#928;',
  2374. '&Rho;' => '&#929;',
  2375. '&Sigma;' => '&#931;',
  2376. '&Tau;' => '&#932;',
  2377. '&Upsilon;' => '&#933;',
  2378. '&Phi;' => '&#934;',
  2379. '&Chi;' => '&#935;',
  2380. '&Psi;' => '&#936;',
  2381. '&Omega;' => '&#937;',
  2382. '&alpha;' => '&#945;',
  2383. '&beta;' => '&#946;',
  2384. '&gamma;' => '&#947;',
  2385. '&delta;' => '&#948;',
  2386. '&epsilon;' => '&#949;',
  2387. '&zeta;' => '&#950;',
  2388. '&eta;' => '&#951;',
  2389. '&theta;' => '&#952;',
  2390. '&iota;' => '&#953;',
  2391. '&kappa;' => '&#954;',
  2392. '&lambda;' => '&#955;',
  2393. '&mu;' => '&#956;',
  2394. '&nu;' => '&#957;',
  2395. '&xi;' => '&#958;',
  2396. '&omicron;' => '&#959;',
  2397. '&pi;' => '&#960;',
  2398. '&rho;' => '&#961;',
  2399. '&sigmaf;' => '&#962;',
  2400. '&sigma;' => '&#963;',
  2401. '&tau;' => '&#964;',
  2402. '&upsilon;' => '&#965;',
  2403. '&phi;' => '&#966;',
  2404. '&chi;' => '&#967;',
  2405. '&psi;' => '&#968;',
  2406. '&omega;' => '&#969;',
  2407. '&thetasym;' => '&#977;',
  2408. '&upsih;' => '&#978;',
  2409. '&piv;' => '&#982;',
  2410. '&ensp;' => '&#8194;',
  2411. '&emsp;' => '&#8195;',
  2412. '&thinsp;' => '&#8201;',
  2413. '&zwnj;' => '&#8204;',
  2414. '&zwj;' => '&#8205;',
  2415. '&lrm;' => '&#8206;',
  2416. '&rlm;' => '&#8207;',
  2417. '&ndash;' => '&#8211;',
  2418. '&mdash;' => '&#8212;',
  2419. '&lsquo;' => '&#8216;',
  2420. '&rsquo;' => '&#8217;',
  2421. '&sbquo;' => '&#8218;',
  2422. '&ldquo;' => '&#8220;',
  2423. '&rdquo;' => '&#8221;',
  2424. '&bdquo;' => '&#8222;',
  2425. '&dagger;' => '&#8224;',
  2426. '&Dagger;' => '&#8225;',
  2427. '&bull;' => '&#8226;',
  2428. '&hellip;' => '&#8230;',
  2429. '&permil;' => '&#8240;',
  2430. '&prime;' => '&#8242;',
  2431. '&Prime;' => '&#8243;',
  2432. '&lsaquo;' => '&#8249;',
  2433. '&rsaquo;' => '&#8250;',
  2434. '&oline;' => '&#8254;',
  2435. '&frasl;' => '&#8260;',
  2436. '&euro;' => '&#8364;',
  2437. '&image;' => '&#8465;',
  2438. '&weierp;' => '&#8472;',
  2439. '&real;' => '&#8476;',
  2440. '&trade;' => '&#8482;',
  2441. '&alefsym;' => '&#8501;',
  2442. '&crarr;' => '&#8629;',
  2443. '&lArr;' => '&#8656;',
  2444. '&uArr;' => '&#8657;',
  2445. '&rArr;' => '&#8658;',
  2446. '&dArr;' => '&#8659;',
  2447. '&hArr;' => '&#8660;',
  2448. '&forall;' => '&#8704;',
  2449. '&part;' => '&#8706;',
  2450. '&exist;' => '&#8707;',
  2451. '&empty;' => '&#8709;',
  2452. '&nabla;' => '&#8711;',
  2453. '&isin;' => '&#8712;',
  2454. '&notin;' => '&#8713;',
  2455. '&ni;' => '&#8715;',
  2456. '&prod;' => '&#8719;',
  2457. '&sum;' => '&#8721;',
  2458. '&minus;' => '&#8722;',
  2459. '&lowast;' => '&#8727;',
  2460. '&radic;' => '&#8730;',
  2461. '&prop;' => '&#8733;',
  2462. '&infin;' => '&#8734;',
  2463. '&ang;' => '&#8736;',
  2464. '&and;' => '&#8743;',
  2465. '&or;' => '&#8744;',
  2466. '&cap;' => '&#8745;',
  2467. '&cup;' => '&#8746;',
  2468. '&int;' => '&#8747;',
  2469. '&there4;' => '&#8756;',
  2470. '&sim;' => '&#8764;',
  2471. '&cong;' => '&#8773;',
  2472. '&asymp;' => '&#8776;',
  2473. '&ne;' => '&#8800;',
  2474. '&equiv;' => '&#8801;',
  2475. '&le;' => '&#8804;',
  2476. '&ge;' => '&#8805;',
  2477. '&sub;' => '&#8834;',
  2478. '&sup;' => '&#8835;',
  2479. '&nsub;' => '&#8836;',
  2480. '&sube;' => '&#8838;',
  2481. '&supe;' => '&#8839;',
  2482. '&oplus;' => '&#8853;',
  2483. '&otimes;' => '&#8855;',
  2484. '&perp;' => '&#8869;',
  2485. '&sdot;' => '&#8901;',
  2486. '&lceil;' => '&#8968;',
  2487. '&rceil;' => '&#8969;',
  2488. '&lfloor;' => '&#8970;',
  2489. '&rfloor;' => '&#8971;',
  2490. '&lang;' => '&#9001;',
  2491. '&rang;' => '&#9002;',
  2492. '&larr;' => '&#8592;',
  2493. '&uarr;' => '&#8593;',
  2494. '&rarr;' => '&#8594;',
  2495. '&darr;' => '&#8595;',
  2496. '&harr;' => '&#8596;',
  2497. '&loz;' => '&#9674;',
  2498. '&spades;' => '&#9824;',
  2499. '&clubs;' => '&#9827;',
  2500. '&hearts;' => '&#9829;',
  2501. '&diams;' => '&#9830;'
  2502. );
  2503. return str_replace( array_keys($to_ncr), array_values($to_ncr), $text );
  2504. }
  2505. /**
  2506. * Formats text for the rich text editor.
  2507. *
  2508. * The filter 'richedit_pre' is applied here. If $text is empty the filter will
  2509. * be applied to an empty string.
  2510. *
  2511. * @since 2.0.0
  2512. *
  2513. * @param string $text The text to be formatted.
  2514. * @return string The formatted text after filter is applied.
  2515. */
  2516. function wp_richedit_pre($text) {
  2517. if ( empty( $text ) ) {
  2518. /**
  2519. * Filter text returned for the rich text editor.
  2520. *
  2521. * This filter is first evaluated, and the value returned, if an empty string
  2522. * is passed to wp_richedit_pre(). If an empty string is passed, it results
  2523. * in a break tag and line feed.
  2524. *
  2525. * If a non-empty string is passed, the filter is evaluated on the wp_richedit_pre()
  2526. * return after being formatted.
  2527. *
  2528. * @since 2.0.0
  2529. *
  2530. * @param string $output Text for the rich text editor.
  2531. */
  2532. return apply_filters( 'richedit_pre', '' );
  2533. }
  2534. $output = convert_chars($text);
  2535. $output = wpautop($output);
  2536. $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) );
  2537. /** This filter is documented in wp-includes/formatting.php */
  2538. return apply_filters( 'richedit_pre', $output );
  2539. }
  2540. /**
  2541. * Formats text for the HTML editor.
  2542. *
  2543. * Unless $output is empty it will pass through htmlspecialchars before the
  2544. * 'htmledit_pre' filter is applied.
  2545. *
  2546. * @since 2.5.0
  2547. *
  2548. * @param string $output The text to be formatted.
  2549. * @return string Formatted text after filter applied.
  2550. */
  2551. function wp_htmledit_pre($output) {
  2552. if ( !empty($output) )
  2553. $output = htmlspecialchars($output, ENT_NOQUOTES, get_option( 'blog_charset' ) ); // convert only < > &
  2554. /**
  2555. * Filter the text before it is formatted for the HTML editor.
  2556. *
  2557. * @since 2.5.0
  2558. *
  2559. * @param string $output The HTML-formatted text.
  2560. */
  2561. return apply_filters( 'htmledit_pre', $output );
  2562. }
  2563. /**
  2564. * Perform a deep string replace operation to ensure the values in $search are no longer present
  2565. *
  2566. * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values
  2567. * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that
  2568. * str_replace would return
  2569. *
  2570. * @since 2.8.1
  2571. * @access private
  2572. *
  2573. * @param string|array $search The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
  2574. * @param string $subject The string being searched and replaced on, otherwise known as the haystack.
  2575. * @return string The string with the replaced svalues.
  2576. */
  2577. function _deep_replace( $search, $subject ) {
  2578. $subject = (string) $subject;
  2579. $count = 1;
  2580. while ( $count ) {
  2581. $subject = str_replace( $search, '', $subject, $count );
  2582. }
  2583. return $subject;
  2584. }
  2585. /**
  2586. * Escapes data for use in a MySQL query.
  2587. *
  2588. * Usually you should prepare queries using wpdb::prepare().
  2589. * Sometimes, spot-escaping is required or useful. One example
  2590. * is preparing an array for use in an IN clause.
  2591. *
  2592. * @since 2.8.0
  2593. * @param string|array $data Unescaped data
  2594. * @return string|array Escaped data
  2595. */
  2596. function esc_sql( $data ) {
  2597. global $wpdb;
  2598. return $wpdb->_escape( $data );
  2599. }
  2600. /**
  2601. * Checks and cleans a URL.
  2602. *
  2603. * A number of characters are removed from the URL. If the URL is for displaying
  2604. * (the default behaviour) ampersands are also replaced. The 'clean_url' filter
  2605. * is applied to the returned cleaned URL.
  2606. *
  2607. * @since 2.8.0
  2608. * @uses wp_kses_bad_protocol() To only permit protocols in the URL set
  2609. * via $protocols or the common ones set in the function.
  2610. *
  2611. * @param string $url The URL to be cleaned.
  2612. * @param array $protocols Optional. An array of acceptable protocols.
  2613. * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set.
  2614. * @param string $_context Private. Use esc_url_raw() for database usage.
  2615. * @return string The cleaned $url after the 'clean_url' filter is applied.
  2616. */
  2617. function esc_url( $url, $protocols = null, $_context = 'display' ) {
  2618. $original_url = $url;
  2619. if ( '' == $url )
  2620. return $url;
  2621. $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url);
  2622. $strip = array('%0d', '%0a', '%0D', '%0A');
  2623. $url = _deep_replace($strip, $url);
  2624. $url = str_replace(';//', '://', $url);
  2625. /* If the URL doesn't appear to contain a scheme, we
  2626. * presume it needs http:// appended (unless a relative
  2627. * link starting with /, # or ? or a php file).
  2628. */
  2629. if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) &&
  2630. ! preg_match('/^[a-z0-9-]+?\.php/i', $url) )
  2631. $url = 'http://' . $url;
  2632. // Replace ampersands and single quotes only when displaying.
  2633. if ( 'display' == $_context ) {
  2634. $url = wp_kses_normalize_entities( $url );
  2635. $url = str_replace( '&amp;', '&#038;', $url );
  2636. $url = str_replace( "'", '&#039;', $url );
  2637. }
  2638. if ( '/' === $url[0] ) {
  2639. $good_protocol_url = $url;
  2640. } else {
  2641. if ( ! is_array( $protocols ) )
  2642. $protocols = wp_allowed_protocols();
  2643. $good_protocol_url = wp_kses_bad_protocol( $url, $protocols );
  2644. if ( strtolower( $good_protocol_url ) != strtolower( $url ) )
  2645. return '';
  2646. }
  2647. /**
  2648. * Filter a string cleaned and escaped for output as a URL.
  2649. *
  2650. * @since 2.3.0
  2651. *
  2652. * @param string $good_protocol_url The cleaned URL to be returned.
  2653. * @param string $original_url The URL prior to cleaning.
  2654. * @param string $_context If 'display', replace ampersands and single quotes only.
  2655. */
  2656. return apply_filters( 'clean_url', $good_protocol_url, $original_url, $_context );
  2657. }
  2658. /**
  2659. * Performs esc_url() for database usage.
  2660. *
  2661. * @since 2.8.0
  2662. * @uses esc_url()
  2663. *
  2664. * @param string $url The URL to be cleaned.
  2665. * @param array $protocols An array of acceptable protocols.
  2666. * @return string The cleaned URL.
  2667. */
  2668. function esc_url_raw( $url, $protocols = null ) {
  2669. return esc_url( $url, $protocols, 'db' );
  2670. }
  2671. /**
  2672. * Convert entities, while preserving already-encoded entities.
  2673. *
  2674. * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes.
  2675. *
  2676. * @since 1.2.2
  2677. *
  2678. * @param string $myHTML The text to be converted.
  2679. * @return string Converted text.
  2680. */
  2681. function htmlentities2($myHTML) {
  2682. $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES );
  2683. $translation_table[chr(38)] = '&';
  2684. return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) );
  2685. }
  2686. /**
  2687. * Escape single quotes, htmlspecialchar " < > &, and fix line endings.
  2688. *
  2689. * Escapes text strings for echoing in JS. It is intended to be used for inline JS
  2690. * (in a tag attribute, for example onclick="..."). Note that the strings have to
  2691. * be in single quotes. The filter 'js_escape' is also applied here.
  2692. *
  2693. * @since 2.8.0
  2694. *
  2695. * @param string $text The text to be escaped.
  2696. * @return string Escaped text.
  2697. */
  2698. function esc_js( $text ) {
  2699. $safe_text = wp_check_invalid_utf8( $text );
  2700. $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT );
  2701. $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) );
  2702. $safe_text = str_replace( "\r", '', $safe_text );
  2703. $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) );
  2704. /**
  2705. * Filter a string cleaned and escaped for output in JavaScript.
  2706. *
  2707. * Text passed to esc_js() is stripped of invalid or special characters,
  2708. * and properly slashed for output.
  2709. *
  2710. * @since 2.0.6
  2711. *
  2712. * @param string $safe_text The text after it has been escaped.
  2713. * @param string $text The text prior to being escaped.
  2714. */
  2715. return apply_filters( 'js_escape', $safe_text, $text );
  2716. }
  2717. /**
  2718. * Escaping for HTML blocks.
  2719. *
  2720. * @since 2.8.0
  2721. *
  2722. * @param string $text
  2723. * @return string
  2724. */
  2725. function esc_html( $text ) {
  2726. $safe_text = wp_check_invalid_utf8( $text );
  2727. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  2728. /**
  2729. * Filter a string cleaned and escaped for output in HTML.
  2730. *
  2731. * Text passed to esc_html() is stripped of invalid or special characters
  2732. * before output.
  2733. *
  2734. * @since 2.8.0
  2735. *
  2736. * @param string $safe_text The text after it has been escaped.
  2737. * @param string $text The text prior to being escaped.
  2738. */
  2739. return apply_filters( 'esc_html', $safe_text, $text );
  2740. }
  2741. /**
  2742. * Escaping for HTML attributes.
  2743. *
  2744. * @since 2.8.0
  2745. *
  2746. * @param string $text
  2747. * @return string
  2748. */
  2749. function esc_attr( $text ) {
  2750. $safe_text = wp_check_invalid_utf8( $text );
  2751. $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES );
  2752. /**
  2753. * Filter a string cleaned and escaped for output in an HTML attribute.
  2754. *
  2755. * Text passed to esc_attr() is stripped of invalid or special characters
  2756. * before output.
  2757. *
  2758. * @since 2.0.6
  2759. *
  2760. * @param string $safe_text The text after it has been escaped.
  2761. * @param string $text The text prior to being escaped.
  2762. */
  2763. return apply_filters( 'attribute_escape', $safe_text, $text );
  2764. }
  2765. /**
  2766. * Escaping for textarea values.
  2767. *
  2768. * @since 3.1.0
  2769. *
  2770. * @param string $text
  2771. * @return string
  2772. */
  2773. function esc_textarea( $text ) {
  2774. $safe_text = htmlspecialchars( $text, ENT_QUOTES, get_option( 'blog_charset' ) );
  2775. /**
  2776. * Filter a string cleaned and escaped for output in a textarea element.
  2777. *
  2778. * @since 3.1.0
  2779. *
  2780. * @param string $safe_text The text after it has been escaped.
  2781. * @param string $text The text prior to being escaped.
  2782. */
  2783. return apply_filters( 'esc_textarea', $safe_text, $text );
  2784. }
  2785. /**
  2786. * Escape an HTML tag name.
  2787. *
  2788. * @since 2.5.0
  2789. *
  2790. * @param string $tag_name
  2791. * @return string
  2792. */
  2793. function tag_escape($tag_name) {
  2794. $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) );
  2795. /**
  2796. * Filter a string cleaned and escaped for output as an HTML tag.
  2797. *
  2798. * @since 2.8.0
  2799. *
  2800. * @param string $safe_tag The tag name after it has been escaped.
  2801. * @param string $tag_name The text before it was escaped.
  2802. */
  2803. return apply_filters( 'tag_escape', $safe_tag, $tag_name );
  2804. }
  2805. /**
  2806. * Escapes text for SQL LIKE special characters % and _.
  2807. *
  2808. * @since 2.5.0
  2809. *
  2810. * @param string $text The text to be escaped.
  2811. * @return string text, safe for inclusion in LIKE query.
  2812. */
  2813. function like_escape($text) {
  2814. return str_replace(array("%", "_"), array("\\%", "\\_"), $text);
  2815. }
  2816. /**
  2817. * Convert full URL paths to absolute paths.
  2818. *
  2819. * Removes the http or https protocols and the domain. Keeps the path '/' at the
  2820. * beginning, so it isn't a true relative link, but from the web root base.
  2821. *
  2822. * @since 2.1.0
  2823. *
  2824. * @param string $link Full URL path.
  2825. * @return string Absolute path.
  2826. */
  2827. function wp_make_link_relative( $link ) {
  2828. return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link );
  2829. }
  2830. /**
  2831. * Sanitises various option values based on the nature of the option.
  2832. *
  2833. * This is basically a switch statement which will pass $value through a number
  2834. * of functions depending on the $option.
  2835. *
  2836. * @since 2.0.5
  2837. *
  2838. * @param string $option The name of the option.
  2839. * @param string $value The unsanitised value.
  2840. * @return string Sanitized value.
  2841. */
  2842. function sanitize_option($option, $value) {
  2843. switch ( $option ) {
  2844. case 'admin_email' :
  2845. case 'new_admin_email' :
  2846. $value = sanitize_email( $value );
  2847. if ( ! is_email( $value ) ) {
  2848. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2849. if ( function_exists( 'add_settings_error' ) )
  2850. 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.' ) );
  2851. }
  2852. break;
  2853. case 'thumbnail_size_w':
  2854. case 'thumbnail_size_h':
  2855. case 'medium_size_w':
  2856. case 'medium_size_h':
  2857. case 'large_size_w':
  2858. case 'large_size_h':
  2859. case 'mailserver_port':
  2860. case 'comment_max_links':
  2861. case 'page_on_front':
  2862. case 'page_for_posts':
  2863. case 'rss_excerpt_length':
  2864. case 'default_category':
  2865. case 'default_email_category':
  2866. case 'default_link_category':
  2867. case 'close_comments_days_old':
  2868. case 'comments_per_page':
  2869. case 'thread_comments_depth':
  2870. case 'users_can_register':
  2871. case 'start_of_week':
  2872. $value = absint( $value );
  2873. break;
  2874. case 'posts_per_page':
  2875. case 'posts_per_rss':
  2876. $value = (int) $value;
  2877. if ( empty($value) )
  2878. $value = 1;
  2879. if ( $value < -1 )
  2880. $value = abs($value);
  2881. break;
  2882. case 'default_ping_status':
  2883. case 'default_comment_status':
  2884. // Options that if not there have 0 value but need to be something like "closed"
  2885. if ( $value == '0' || $value == '')
  2886. $value = 'closed';
  2887. break;
  2888. case 'blogdescription':
  2889. case 'blogname':
  2890. $value = wp_kses_post( $value );
  2891. $value = esc_html( $value );
  2892. break;
  2893. case 'blog_charset':
  2894. $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes
  2895. break;
  2896. case 'blog_public':
  2897. // This is the value if the settings checkbox is not checked on POST. Don't rely on this.
  2898. if ( null === $value )
  2899. $value = 1;
  2900. else
  2901. $value = intval( $value );
  2902. break;
  2903. case 'date_format':
  2904. case 'time_format':
  2905. case 'mailserver_url':
  2906. case 'mailserver_login':
  2907. case 'mailserver_pass':
  2908. case 'upload_path':
  2909. $value = strip_tags( $value );
  2910. $value = wp_kses_data( $value );
  2911. break;
  2912. case 'ping_sites':
  2913. $value = explode( "\n", $value );
  2914. $value = array_filter( array_map( 'trim', $value ) );
  2915. $value = array_filter( array_map( 'esc_url_raw', $value ) );
  2916. $value = implode( "\n", $value );
  2917. break;
  2918. case 'gmt_offset':
  2919. $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes
  2920. break;
  2921. case 'siteurl':
  2922. if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
  2923. $value = esc_url_raw($value);
  2924. } else {
  2925. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2926. if ( function_exists('add_settings_error') )
  2927. add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.'));
  2928. }
  2929. break;
  2930. case 'home':
  2931. if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) {
  2932. $value = esc_url_raw($value);
  2933. } else {
  2934. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2935. if ( function_exists('add_settings_error') )
  2936. add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.'));
  2937. }
  2938. break;
  2939. case 'WPLANG':
  2940. $allowed = get_available_languages();
  2941. if ( ! in_array( $value, $allowed ) && ! empty( $value ) )
  2942. $value = get_option( $option );
  2943. break;
  2944. case 'illegal_names':
  2945. if ( ! is_array( $value ) )
  2946. $value = explode( ' ', $value );
  2947. $value = array_values( array_filter( array_map( 'trim', $value ) ) );
  2948. if ( ! $value )
  2949. $value = '';
  2950. break;
  2951. case 'limited_email_domains':
  2952. case 'banned_email_domains':
  2953. if ( ! is_array( $value ) )
  2954. $value = explode( "\n", $value );
  2955. $domains = array_values( array_filter( array_map( 'trim', $value ) ) );
  2956. $value = array();
  2957. foreach ( $domains as $domain ) {
  2958. if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) )
  2959. $value[] = $domain;
  2960. }
  2961. if ( ! $value )
  2962. $value = '';
  2963. break;
  2964. case 'timezone_string':
  2965. $allowed_zones = timezone_identifiers_list();
  2966. if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) {
  2967. $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization
  2968. if ( function_exists('add_settings_error') )
  2969. add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') );
  2970. }
  2971. break;
  2972. case 'permalink_structure':
  2973. case 'category_base':
  2974. case 'tag_base':
  2975. $value = esc_url_raw( $value );
  2976. $value = str_replace( 'http://', '', $value );
  2977. break;
  2978. case 'default_role' :
  2979. if ( ! get_role( $value ) && get_role( 'subscriber' ) )
  2980. $value = 'subscriber';
  2981. break;
  2982. }
  2983. /**
  2984. * Filter an option value following sanitization.
  2985. *
  2986. * @since 2.3.0
  2987. *
  2988. * @param string $value The sanitized option value.
  2989. * @param string $option The option name.
  2990. */
  2991. $value = apply_filters( "sanitize_option_{$option}", $value, $option );
  2992. return $value;
  2993. }
  2994. /**
  2995. * Parses a string into variables to be stored in an array.
  2996. *
  2997. * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if
  2998. * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on.
  2999. *
  3000. * @since 2.2.1
  3001. *
  3002. * @param string $string The string to be parsed.
  3003. * @param array $array Variables will be stored in this array.
  3004. */
  3005. function wp_parse_str( $string, &$array ) {
  3006. parse_str( $string, $array );
  3007. if ( get_magic_quotes_gpc() )
  3008. $array = stripslashes_deep( $array );
  3009. /**
  3010. * Filter the array of variables derived from a parsed string.
  3011. *
  3012. * @since 2.3.0
  3013. *
  3014. * @param array $array The array populated with variables.
  3015. */
  3016. $array = apply_filters( 'wp_parse_str', $array );
  3017. }
  3018. /**
  3019. * Convert lone less than signs.
  3020. *
  3021. * KSES already converts lone greater than signs.
  3022. *
  3023. * @uses wp_pre_kses_less_than_callback in the callback function.
  3024. * @since 2.3.0
  3025. *
  3026. * @param string $text Text to be converted.
  3027. * @return string Converted text.
  3028. */
  3029. function wp_pre_kses_less_than( $text ) {
  3030. return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text);
  3031. }
  3032. /**
  3033. * Callback function used by preg_replace.
  3034. *
  3035. * @uses esc_html to format the $matches text.
  3036. * @since 2.3.0
  3037. *
  3038. * @param array $matches Populated by matches to preg_replace.
  3039. * @return string The text returned after esc_html if needed.
  3040. */
  3041. function wp_pre_kses_less_than_callback( $matches ) {
  3042. if ( false === strpos($matches[0], '>') )
  3043. return esc_html($matches[0]);
  3044. return $matches[0];
  3045. }
  3046. /**
  3047. * WordPress implementation of PHP sprintf() with filters.
  3048. *
  3049. * @since 2.5.0
  3050. * @link http://www.php.net/sprintf
  3051. *
  3052. * @param string $pattern The string which formatted args are inserted.
  3053. * @param mixed $args,... Arguments to be formatted into the $pattern string.
  3054. * @return string The formatted string.
  3055. */
  3056. function wp_sprintf( $pattern ) {
  3057. $args = func_get_args();
  3058. $len = strlen($pattern);
  3059. $start = 0;
  3060. $result = '';
  3061. $arg_index = 0;
  3062. while ( $len > $start ) {
  3063. // Last character: append and break
  3064. if ( strlen($pattern) - 1 == $start ) {
  3065. $result .= substr($pattern, -1);
  3066. break;
  3067. }
  3068. // Literal %: append and continue
  3069. if ( substr($pattern, $start, 2) == '%%' ) {
  3070. $start += 2;
  3071. $result .= '%';
  3072. continue;
  3073. }
  3074. // Get fragment before next %
  3075. $end = strpos($pattern, '%', $start + 1);
  3076. if ( false === $end )
  3077. $end = $len;
  3078. $fragment = substr($pattern, $start, $end - $start);
  3079. // Fragment has a specifier
  3080. if ( $pattern[$start] == '%' ) {
  3081. // Find numbered arguments or take the next one in order
  3082. if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) {
  3083. $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : '';
  3084. $fragment = str_replace("%{$matches[1]}$", '%', $fragment);
  3085. } else {
  3086. ++$arg_index;
  3087. $arg = isset($args[$arg_index]) ? $args[$arg_index] : '';
  3088. }
  3089. /**
  3090. * Filter a fragment from the pattern passed to wp_sprintf().
  3091. *
  3092. * If the fragment is unchanged, then sprintf() will be run on the fragment.
  3093. *
  3094. * @since 2.5.0
  3095. *
  3096. * @param string $fragment A fragment from the pattern.
  3097. * @param string $arg The argument.
  3098. */
  3099. $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg );
  3100. if ( $_fragment != $fragment )
  3101. $fragment = $_fragment;
  3102. else
  3103. $fragment = sprintf($fragment, strval($arg) );
  3104. }
  3105. // Append to result and move to next fragment
  3106. $result .= $fragment;
  3107. $start = $end;
  3108. }
  3109. return $result;
  3110. }
  3111. /**
  3112. * Localize list items before the rest of the content.
  3113. *
  3114. * The '%l' must be at the first characters can then contain the rest of the
  3115. * content. The list items will have ', ', ', and', and ' and ' added depending
  3116. * on the amount of list items in the $args parameter.
  3117. *
  3118. * @since 2.5.0
  3119. *
  3120. * @param string $pattern Content containing '%l' at the beginning.
  3121. * @param array $args List items to prepend to the content and replace '%l'.
  3122. * @return string Localized list items and rest of the content.
  3123. */
  3124. function wp_sprintf_l($pattern, $args) {
  3125. // Not a match
  3126. if ( substr($pattern, 0, 2) != '%l' )
  3127. return $pattern;
  3128. // Nothing to work with
  3129. if ( empty($args) )
  3130. return '';
  3131. /**
  3132. * Filter the translated delimiters used by wp_sprintf_l().
  3133. * Placeholders (%s) are included to assist translators and then
  3134. * removed before the array of strings reaches the filter.
  3135. *
  3136. * Please note: Ampersands and entities should be avoided here.
  3137. *
  3138. * @since 2.5.0
  3139. *
  3140. * @param array $delimiters An array of translated delimiters.
  3141. */
  3142. $l = apply_filters( 'wp_sprintf_l', array(
  3143. /* translators: used to join items in a list with more than 2 items */
  3144. 'between' => sprintf( __('%s, %s'), '', '' ),
  3145. /* translators: used to join last two items in a list with more than 2 times */
  3146. 'between_last_two' => sprintf( __('%s, and %s'), '', '' ),
  3147. /* translators: used to join items in a list with only 2 items */
  3148. 'between_only_two' => sprintf( __('%s and %s'), '', '' ),
  3149. ) );
  3150. $args = (array) $args;
  3151. $result = array_shift($args);
  3152. if ( count($args) == 1 )
  3153. $result .= $l['between_only_two'] . array_shift($args);
  3154. // Loop when more than two args
  3155. $i = count($args);
  3156. while ( $i ) {
  3157. $arg = array_shift($args);
  3158. $i--;
  3159. if ( 0 == $i )
  3160. $result .= $l['between_last_two'] . $arg;
  3161. else
  3162. $result .= $l['between'] . $arg;
  3163. }
  3164. return $result . substr($pattern, 2);
  3165. }
  3166. /**
  3167. * Safely extracts not more than the first $count characters from html string.
  3168. *
  3169. * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT*
  3170. * be counted as one character. For example &amp; will be counted as 4, &lt; as
  3171. * 3, etc.
  3172. *
  3173. * @since 2.5.0
  3174. *
  3175. * @param string $str String to get the excerpt from.
  3176. * @param integer $count Maximum number of characters to take.
  3177. * @param string $more Optional. What to append if $str needs to be trimmed. Defaults to empty string.
  3178. * @return string The excerpt.
  3179. */
  3180. function wp_html_excerpt( $str, $count, $more = null ) {
  3181. if ( null === $more )
  3182. $more = '';
  3183. $str = wp_strip_all_tags( $str, true );
  3184. $excerpt = mb_substr( $str, 0, $count );
  3185. // remove part of an entity at the end
  3186. $excerpt = preg_replace( '/&[^;\s]{0,6}$/', '', $excerpt );
  3187. if ( $str != $excerpt )
  3188. $excerpt = trim( $excerpt ) . $more;
  3189. return $excerpt;
  3190. }
  3191. /**
  3192. * Add a Base url to relative links in passed content.
  3193. *
  3194. * By default it supports the 'src' and 'href' attributes. However this can be
  3195. * changed via the 3rd param.
  3196. *
  3197. * @since 2.7.0
  3198. *
  3199. * @param string $content String to search for links in.
  3200. * @param string $base The base URL to prefix to links.
  3201. * @param array $attrs The attributes which should be processed.
  3202. * @return string The processed content.
  3203. */
  3204. function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) {
  3205. global $_links_add_base;
  3206. $_links_add_base = $base;
  3207. $attrs = implode('|', (array)$attrs);
  3208. return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content );
  3209. }
  3210. /**
  3211. * Callback to add a base url to relative links in passed content.
  3212. *
  3213. * @since 2.7.0
  3214. * @access private
  3215. *
  3216. * @param string $m The matched link.
  3217. * @return string The processed link.
  3218. */
  3219. function _links_add_base($m) {
  3220. global $_links_add_base;
  3221. //1 = attribute name 2 = quotation mark 3 = URL
  3222. return $m[1] . '=' . $m[2] .
  3223. ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ?
  3224. $m[3] :
  3225. path_join( $_links_add_base, $m[3] ) )
  3226. . $m[2];
  3227. }
  3228. /**
  3229. * Adds a Target attribute to all links in passed content.
  3230. *
  3231. * This function by default only applies to <a> tags, however this can be
  3232. * modified by the 3rd param.
  3233. *
  3234. * <b>NOTE:</b> Any current target attributed will be stripped and replaced.
  3235. *
  3236. * @since 2.7.0
  3237. *
  3238. * @param string $content String to search for links in.
  3239. * @param string $target The Target to add to the links.
  3240. * @param array $tags An array of tags to apply to.
  3241. * @return string The processed content.
  3242. */
  3243. function links_add_target( $content, $target = '_blank', $tags = array('a') ) {
  3244. global $_links_add_target;
  3245. $_links_add_target = $target;
  3246. $tags = implode('|', (array)$tags);
  3247. return preg_replace_callback( "!<($tags)([^>]*)>!i", '_links_add_target', $content );
  3248. }
  3249. /**
  3250. * Callback to add a target attribute to all links in passed content.
  3251. *
  3252. * @since 2.7.0
  3253. * @access private
  3254. *
  3255. * @param string $m The matched link.
  3256. * @return string The processed link.
  3257. */
  3258. function _links_add_target( $m ) {
  3259. global $_links_add_target;
  3260. $tag = $m[1];
  3261. $link = preg_replace('|( target=([\'"])(.*?)\2)|i', '', $m[2]);
  3262. return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">';
  3263. }
  3264. /**
  3265. * Normalize EOL characters and strip duplicate whitespace.
  3266. *
  3267. * @since 2.7.0
  3268. *
  3269. * @param string $str The string to normalize.
  3270. * @return string The normalized string.
  3271. */
  3272. function normalize_whitespace( $str ) {
  3273. $str = trim( $str );
  3274. $str = str_replace( "\r", "\n", $str );
  3275. $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str );
  3276. return $str;
  3277. }
  3278. /**
  3279. * Properly strip all HTML tags including script and style
  3280. *
  3281. * This differs from strip_tags() because it removes the contents of
  3282. * the <script> and <style> tags. E.g. strip_tags( '<script>something</script>' )
  3283. * will return 'something'. wp_strip_all_tags will return ''
  3284. *
  3285. * @since 2.9.0
  3286. *
  3287. * @param string $string String containing HTML tags
  3288. * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars
  3289. * @return string The processed string.
  3290. */
  3291. function wp_strip_all_tags($string, $remove_breaks = false) {
  3292. $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string );
  3293. $string = strip_tags($string);
  3294. if ( $remove_breaks )
  3295. $string = preg_replace('/[\r\n\t ]+/', ' ', $string);
  3296. return trim( $string );
  3297. }
  3298. /**
  3299. * Sanitize a string from user input or from the db
  3300. *
  3301. * check for invalid UTF-8,
  3302. * Convert single < characters to entity,
  3303. * strip all tags,
  3304. * remove line breaks, tabs and extra white space,
  3305. * strip octets.
  3306. *
  3307. * @since 2.9.0
  3308. *
  3309. * @param string $str
  3310. * @return string
  3311. */
  3312. function sanitize_text_field($str) {
  3313. $filtered = wp_check_invalid_utf8( $str );
  3314. if ( strpos($filtered, '<') !== false ) {
  3315. $filtered = wp_pre_kses_less_than( $filtered );
  3316. // This will strip extra whitespace for us.
  3317. $filtered = wp_strip_all_tags( $filtered, true );
  3318. } else {
  3319. $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) );
  3320. }
  3321. $found = false;
  3322. while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) {
  3323. $filtered = str_replace($match[0], '', $filtered);
  3324. $found = true;
  3325. }
  3326. if ( $found ) {
  3327. // Strip out the whitespace that may now exist after removing the octets.
  3328. $filtered = trim( preg_replace('/ +/', ' ', $filtered) );
  3329. }
  3330. /**
  3331. * Filter a sanitized text field string.
  3332. *
  3333. * @since 2.9.0
  3334. *
  3335. * @param string $filtered The sanitized string.
  3336. * @param string $str The string prior to being sanitized.
  3337. */
  3338. return apply_filters( 'sanitize_text_field', $filtered, $str );
  3339. }
  3340. /**
  3341. * i18n friendly version of basename()
  3342. *
  3343. * @since 3.1.0
  3344. *
  3345. * @param string $path A path.
  3346. * @param string $suffix If the filename ends in suffix this will also be cut off.
  3347. * @return string
  3348. */
  3349. function wp_basename( $path, $suffix = '' ) {
  3350. return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) );
  3351. }
  3352. /**
  3353. * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence).
  3354. *
  3355. * Violating our coding standards for a good function name.
  3356. *
  3357. * @since 3.0.0
  3358. */
  3359. function capital_P_dangit( $text ) {
  3360. // Simple replacement for titles
  3361. $current_filter = current_filter();
  3362. if ( 'the_title' === $current_filter || 'wp_title' === $current_filter )
  3363. return str_replace( 'Wordpress', 'WordPress', $text );
  3364. // Still here? Use the more judicious replacement
  3365. static $dblq = false;
  3366. if ( false === $dblq )
  3367. $dblq = _x( '&#8220;', 'opening curly double quote' );
  3368. return str_replace(
  3369. array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ),
  3370. array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ),
  3371. $text );
  3372. }
  3373. /**
  3374. * Sanitize a mime type
  3375. *
  3376. * @since 3.1.3
  3377. *
  3378. * @param string $mime_type Mime type
  3379. * @return string Sanitized mime type
  3380. */
  3381. function sanitize_mime_type( $mime_type ) {
  3382. $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type );
  3383. /**
  3384. * Filter a mime type following sanitization.
  3385. *
  3386. * @since 3.1.3
  3387. *
  3388. * @param string $sani_mime_type The sanitized mime type.
  3389. * @param string $mime_type The mime type prior to sanitization.
  3390. */
  3391. return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type );
  3392. }
  3393. /**
  3394. * Sanitize space or carriage return separated URLs that are used to send trackbacks.
  3395. *
  3396. * @since 3.4.0
  3397. *
  3398. * @param string $to_ping Space or carriage return separated URLs
  3399. * @return string URLs starting with the http or https protocol, separated by a carriage return.
  3400. */
  3401. function sanitize_trackback_urls( $to_ping ) {
  3402. $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY );
  3403. foreach ( $urls_to_ping as $k => $url ) {
  3404. if ( !preg_match( '#^https?://.#i', $url ) )
  3405. unset( $urls_to_ping[$k] );
  3406. }
  3407. $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping );
  3408. $urls_to_ping = implode( "\n", $urls_to_ping );
  3409. /**
  3410. * Filter a list of trackback URLs following sanitization.
  3411. *
  3412. * The string returned here consists of a space or carriage return-delimited list
  3413. * of trackback URLs.
  3414. *
  3415. * @since 3.4.0
  3416. *
  3417. * @param string $urls_to_ping Sanitized space or carriage return separated URLs.
  3418. * @param string $to_ping Space or carriage return separated URLs before sanitization.
  3419. */
  3420. return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping );
  3421. }
  3422. /**
  3423. * Add slashes to a string or array of strings.
  3424. *
  3425. * This should be used when preparing data for core API that expects slashed data.
  3426. * This should not be used to escape data going directly into an SQL query.
  3427. *
  3428. * @since 3.6.0
  3429. *
  3430. * @param string|array $value String or array of strings to slash.
  3431. * @return string|array Slashed $value
  3432. */
  3433. function wp_slash( $value ) {
  3434. if ( is_array( $value ) ) {
  3435. foreach ( $value as $k => $v ) {
  3436. if ( is_array( $v ) ) {
  3437. $value[$k] = wp_slash( $v );
  3438. } else {
  3439. $value[$k] = addslashes( $v );
  3440. }
  3441. }
  3442. } else {
  3443. $value = addslashes( $value );
  3444. }
  3445. return $value;
  3446. }
  3447. /**
  3448. * Remove slashes from a string or array of strings.
  3449. *
  3450. * This should be used to remove slashes from data passed to core API that
  3451. * expects data to be unslashed.
  3452. *
  3453. * @since 3.6.0
  3454. *
  3455. * @param string|array $value String or array of strings to unslash.
  3456. * @return string|array Unslashed $value
  3457. */
  3458. function wp_unslash( $value ) {
  3459. return stripslashes_deep( $value );
  3460. }
  3461. /**
  3462. * Extract and return the first URL from passed content.
  3463. *
  3464. * @since 3.6.0
  3465. *
  3466. * @param string $content A string which might contain a URL.
  3467. * @return string The found URL.
  3468. */
  3469. function get_url_in_content( $content ) {
  3470. if ( empty( $content ) ) {
  3471. return false;
  3472. }
  3473. if ( preg_match( '/<a\s[^>]*?href=([\'"])(.+?)\1/is', $content, $matches ) ) {
  3474. return esc_url_raw( $matches[2] );
  3475. }
  3476. return false;
  3477. }