PageRenderTime 64ms CodeModel.GetById 14ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

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