PageRenderTime 61ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/Web/wp-includes/formatting.php

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