PageRenderTime 125ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 1ms

/wp-includes/formatting.php

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