PageRenderTime 66ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

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