PageRenderTime 52ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/formatting.php

https://bitbucket.org/aqge/deptandashboard
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

Large files files are truncated, but you can click here to view the full file

  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 …

Large files files are truncated, but you can click here to view the full file