PageRenderTime 62ms CodeModel.GetById 20ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/formatting.php

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