PageRenderTime 38ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

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