PageRenderTime 77ms CodeModel.GetById 0ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/formatting.php

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