PageRenderTime 67ms CodeModel.GetById 8ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

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