PageRenderTime 106ms CodeModel.GetById 34ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/formatting.php

https://bitbucket.org/nlyn/mr.-peacocks
PHP | 2926 lines | 1753 code | 230 blank | 943 comment | 235 complexity | 2f1826802dfd6613c1aeac14f67e48cd MD5 | raw file
Possible License(s): GPL-2.0

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, $default_no_texturize_tags, $default_no_texturize_shortcodes, $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements;
  31. // No need to set up these static variables more than once
  32. if ( empty( $opening_quote ) ) {
  33. /* translators: opening curly quote */
  34. $opening_quote = _x('&#8220;', 'opening curly quote');
  35. /* translators: closing curly quote */
  36. $closing_quote = _x('&#8221;', 'closing curly quote');
  37. $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt');
  38. $default_no_texturize_shortcodes = array('code');
  39. // if a plugin has provided an autocorrect array, use it
  40. if ( isset($wp_cockneyreplace) ) {
  41. $cockney = array_keys($wp_cockneyreplace);
  42. $cockneyreplace = array_values($wp_cockneyreplace);
  43. } else {
  44. $cockney = array("'tain't","'twere","'twas","'tis","'twill","'til","'bout","'nuff","'round","'cause");
  45. $cockneyreplace = array("&#8217;tain&#8217;t","&#8217;twere","&#8217;twas","&#8217;tis","&#8217;twill","&#8217;til","&#8217;bout","&#8217;nuff","&#8217;round","&#8217;cause");
  46. }
  47. $static_characters = array_merge(array('---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', '\'\'', ' (tm)'), $cockney);
  48. $static_replacements = array_merge(array('&#8212;', ' &#8212; ', '&#8211;', ' &#8211; ', 'xn--', '&#8230;', $opening_quote, $closing_quote, ' &#8482;'), $cockneyreplace);
  49. $dynamic_characters = array('/\'(\d\d(?:&#8217;|\')?s)/', '/\'(\d)/', '/(\s|\A|[([{<]|")\'/', '/(\d)"/', '/(\d)\'/', '/(\S)\'([^\'\s])/', '/(\s|\A|[([{<])"(?!\s)/', '/"(\s|\S|\Z)/', '/\'([\s.]|\Z)/', '/\b(\d+)x(\d+)\b/');
  50. $dynamic_replacements = array('&#8217;$1','&#8217;$1', '$1&#8216;', '$1&#8243;', '$1&#8242;', '$1&#8217;$2', '$1' . $opening_quote . '$2', $closing_quote . '$1', '&#8217;$1', '$1&#215;$2');
  51. }
  52. // Transform into regexp sub-expression used in _wptexturize_pushpop_element
  53. // Must do this everytime in case plugins use these filters in a context sensitive manner
  54. $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')';
  55. $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')';
  56. $no_texturize_tags_stack = array();
  57. $no_texturize_shortcodes_stack = array();
  58. $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
  59. foreach ( $textarr as &$curl ) {
  60. if ( empty( $curl ) )
  61. continue;
  62. // Only call _wptexturize_pushpop_element if first char is correct tag opening
  63. $first = $curl[0];
  64. if ( '<' === $first ) {
  65. _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>');
  66. } elseif ( '[' === $first ) {
  67. _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']');
  68. } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) {
  69. // This is not a tag, nor is the texturization disabled static strings
  70. $curl = str_replace($static_characters, $static_replacements, $curl);
  71. // regular expressions
  72. $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl);
  73. }
  74. $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl);
  75. }
  76. return implode( '', $textarr );
  77. }
  78. /**
  79. * Search for disabled element tags. Push element to stack on tag open and pop
  80. * on tag close. Assumes first character of $text is tag opening.
  81. *
  82. * @access private
  83. * @since 2.9.0
  84. *
  85. * @param string $text Text to check. First character is assumed to be $opening
  86. * @param array $stack Array used as stack of opened tag elements
  87. * @param string $disabled_elements Tags to match against formatted as regexp sub-expression
  88. * @param string $opening Tag opening character, assumed to be 1 character long
  89. * @param string $opening Tag closing character
  90. * @return object
  91. */
  92. function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') {
  93. // Check if it is a closing tag -- otherwise assume opening tag
  94. if (strncmp($opening . '/', $text, 2)) {
  95. // Opening? Check $text+1 against disabled elements
  96. if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) {
  97. /*
  98. * This disables texturize until we find a closing tag of our type
  99. * (e.g. <pre>) even if there was invalid nesting before that
  100. *
  101. * Example: in the case <pre>sadsadasd</code>"baba"</pre>
  102. * "baba" won't be texturize
  103. */
  104. array_push($stack, $matches[1]);
  105. }
  106. } else {
  107. // Closing? Check $text+2 against disabled elements
  108. $c = preg_quote($closing, '/');
  109. if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) {
  110. $last = array_pop($stack);
  111. // Make sure it matches the opening tag
  112. if ($last != $matches[1])
  113. array_push($stack, $last);
  114. }
  115. }
  116. }
  117. /**
  118. * Accepts matches array from preg_replace_callback in wpautop() or a string.
  119. *
  120. * Ensures that the contents of a <<pre>>...<</pre>> HTML block are not
  121. * converted into paragraphs or line-breaks.
  122. *
  123. * @since 1.2.0
  124. *
  125. * @param array|string $matches The array or string
  126. * @return string The pre block without paragraph/line-break conversion.
  127. */
  128. function clean_pre($matches) {
  129. if ( is_array($matches) )
  130. $text = $matches[1] . $matches[2] . "</pre>";
  131. else
  132. $text = $matches;
  133. $text = str_replace('<br />', '', $text);
  134. $text = str_replace('<p>', "\n", $text);
  135. $text = str_replace('</p>', '', $text);
  136. return $text;
  137. }
  138. /**
  139. * Replaces double line-breaks with paragraph elements.
  140. *
  141. * A group of regex replaces used to identify text formatted with newlines and
  142. * replace double line-breaks with HTML paragraph tags. The remaining
  143. * line-breaks after conversion become <<br />> tags, unless $br is set to '0'
  144. * or 'false'.
  145. *
  146. * @since 0.71
  147. *
  148. * @param string $pee The text which has to be formatted.
  149. * @param int|bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true.
  150. * @return string Text which has been converted into correct paragraph tags.
  151. */
  152. function wpautop($pee, $br = 1) {
  153. if ( trim($pee) === '' )
  154. return '';
  155. $pee = $pee . "\n"; // just to make things a little easier, pad the end
  156. $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee);
  157. // Space things out a little
  158. $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|input|p|h[1-6]|hr|fieldset|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)';
  159. $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee);
  160. $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee);
  161. $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines
  162. if ( strpos($pee, '<object') !== false ) {
  163. $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed
  164. $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee);
  165. }
  166. $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates
  167. // make paragraphs, including one at the end
  168. $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY);
  169. $pee = '';
  170. foreach ( $pees as $tinkle )
  171. $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n";
  172. $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace
  173. $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee);
  174. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag
  175. $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists
  176. $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee);
  177. $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee);
  178. $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee);
  179. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee);
  180. if ($br) {
  181. $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee);
  182. $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks
  183. $pee = str_replace('<WPPreserveNewline />', "\n", $pee);
  184. }
  185. $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee);
  186. $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee);
  187. if (strpos($pee, '<pre') !== false)
  188. $pee = preg_replace_callback('!(<pre[^>]*>)(.*?)</pre>!is', 'clean_pre', $pee );
  189. $pee = preg_replace( "|\n</p>$|", '</p>', $pee );
  190. return $pee;
  191. }
  192. /**
  193. * Newline preservation help function for wpautop
  194. *
  195. * @since 3.1.0
  196. * @access private
  197. * @param array $matches preg_replace_callback matches array
  198. * @returns string
  199. */
  200. function _autop_newline_preservation_helper( $matches ) {
  201. return str_replace("\n", "<WPPreserveNewline />", $matches[0]);
  202. }
  203. /**
  204. * Don't auto-p wrap shortcodes that stand alone
  205. *
  206. * Ensures that shortcodes are not wrapped in <<p>>...<</p>>.
  207. *
  208. * @since 2.9.0
  209. *
  210. * @param string $pee The content.
  211. * @return string The filtered content.
  212. */
  213. function shortcode_unautop($pee) {
  214. global $shortcode_tags;
  215. if ( !empty($shortcode_tags) && is_array($shortcode_tags) ) {
  216. $tagnames = array_keys($shortcode_tags);
  217. $tagregexp = join( '|', array_map('preg_quote', $tagnames) );
  218. $pee = preg_replace('/<p>\\s*?(\\[(' . $tagregexp . ')\\b.*?\\/?\\](?:.+?\\[\\/\\2\\])?)\\s*<\\/p>/s', '$1', $pee);
  219. }
  220. return $pee;
  221. }
  222. /**
  223. * Checks to see if a string is utf8 encoded.
  224. *
  225. * NOTE: This function checks for 5-Byte sequences, UTF8
  226. * has Bytes Sequences with a maximum length of 4.
  227. *
  228. * @author bmorel at ssi dot fr (modified)
  229. * @since 1.2.1
  230. *
  231. * @param string $str The string to be checked
  232. * @return bool True if $str fits a UTF-8 model, false otherwise.
  233. */
  234. function seems_utf8($str) {
  235. $length = strlen($str);
  236. for ($i=0; $i < $length; $i++) {
  237. $c = ord($str[$i]);
  238. if ($c < 0x80) $n = 0; # 0bbbbbbb
  239. elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb
  240. elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb
  241. elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb
  242. elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb
  243. elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b
  244. else return false; # Does not match any model
  245. for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ?
  246. if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80))
  247. return false;
  248. }
  249. }
  250. return true;
  251. }
  252. /**
  253. * Converts a number of special characters into their HTML entities.
  254. *
  255. * Specifically deals with: &, <, >, ", and '.
  256. *
  257. * $quote_style can be set to ENT_COMPAT to encode " to
  258. * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded.
  259. *
  260. * @since 1.2.2
  261. *
  262. * @param string $string The text which is to be encoded.
  263. * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
  264. * @param string $charset Optional. The character encoding of the string. Default is false.
  265. * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false.
  266. * @return string The encoded text with HTML entities.
  267. */
  268. function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) {
  269. $string = (string) $string;
  270. if ( 0 === strlen( $string ) ) {
  271. return '';
  272. }
  273. // Don't bother if there are no specialchars - saves some processing
  274. if ( !preg_match( '/[&<>"\']/', $string ) ) {
  275. return $string;
  276. }
  277. // Account for the previous behaviour of the function when the $quote_style is not an accepted value
  278. if ( empty( $quote_style ) ) {
  279. $quote_style = ENT_NOQUOTES;
  280. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  281. $quote_style = ENT_QUOTES;
  282. }
  283. // Store the site charset as a static to avoid multiple calls to wp_load_alloptions()
  284. if ( !$charset ) {
  285. static $_charset;
  286. if ( !isset( $_charset ) ) {
  287. $alloptions = wp_load_alloptions();
  288. $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : '';
  289. }
  290. $charset = $_charset;
  291. }
  292. if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) {
  293. $charset = 'UTF-8';
  294. }
  295. $_quote_style = $quote_style;
  296. if ( $quote_style === 'double' ) {
  297. $quote_style = ENT_COMPAT;
  298. $_quote_style = ENT_COMPAT;
  299. } elseif ( $quote_style === 'single' ) {
  300. $quote_style = ENT_NOQUOTES;
  301. }
  302. // Handle double encoding ourselves
  303. if ( !$double_encode ) {
  304. $string = wp_specialchars_decode( $string, $_quote_style );
  305. /* Critical */
  306. // The previous line decodes &amp;phrase; into &phrase; We must guarantee that &phrase; is valid before proceeding.
  307. $string = wp_kses_normalize_entities($string);
  308. // Now proceed with custom double-encoding silliness
  309. $string = preg_replace( '/&(#?x?[0-9a-z]+);/i', '|wp_entity|$1|/wp_entity|', $string );
  310. }
  311. $string = @htmlspecialchars( $string, $quote_style, $charset );
  312. // Handle double encoding ourselves
  313. if ( !$double_encode ) {
  314. $string = str_replace( array( '|wp_entity|', '|/wp_entity|' ), array( '&', ';' ), $string );
  315. }
  316. // Backwards compatibility
  317. if ( 'single' === $_quote_style ) {
  318. $string = str_replace( "'", '&#039;', $string );
  319. }
  320. return $string;
  321. }
  322. /**
  323. * Converts a number of HTML entities into their special characters.
  324. *
  325. * Specifically deals with: &, <, >, ", and '.
  326. *
  327. * $quote_style can be set to ENT_COMPAT to decode " entities,
  328. * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded.
  329. *
  330. * @since 2.8
  331. *
  332. * @param string $string The text which is to be decoded.
  333. * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES.
  334. * @return string The decoded text without HTML entities.
  335. */
  336. function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) {
  337. $string = (string) $string;
  338. if ( 0 === strlen( $string ) ) {
  339. return '';
  340. }
  341. // Don't bother if there are no entities - saves a lot of processing
  342. if ( strpos( $string, '&' ) === false ) {
  343. return $string;
  344. }
  345. // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value
  346. if ( empty( $quote_style ) ) {
  347. $quote_style = ENT_NOQUOTES;
  348. } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) {
  349. $quote_style = ENT_QUOTES;
  350. }
  351. // More complete than get_html_translation_table( HTML_SPECIALCHARS )
  352. $single = array( '&#039;' => '\'', '&#x27;' => '\'' );
  353. $single_preg = array( '/&#0*39;/' => '&#039;', '/&#x0*27;/i' => '&#x27;' );
  354. $double = array( '&quot;' => '"', '&#034;' => '"', '&#x22;' => '"' );
  355. $double_preg = array( '/&#0*34;/' => '&#034;', '/&#x0*22;/i' => '&#x22;' );
  356. $others = array( '&lt;' => '<', '&#060;' => '<', '&gt;' => '>', '&#062;' => '>', '&amp;' => '&', '&#038;' => '&', '&#x26;' => '&' );
  357. $others_preg = array( '/&#0*60;/' => '&#060;', '/&#0*62;/' => '&#062;', '/&#0*38;/' => '&#038;', '/&#x0*26;/i' => '&#x26;' );
  358. if ( $quote_style === ENT_QUOTES ) {
  359. $translation = array_merge( $single, $double, $others );
  360. $translation_preg = array_merge( $single_preg, $double_preg, $others_preg );
  361. } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) {
  362. $translation = array_merge( $double, $others );
  363. $translation_preg = array_merge( $double_preg, $others_preg );
  364. } elseif ( $quote_style === 'single' ) {
  365. $translation = array_merge( $single, $others );
  366. $translation_preg = array_merge( $single_preg, $others_preg );
  367. } elseif ( $quote_style === ENT_NOQUOTES ) {
  368. $translation = $others;
  369. $translation_preg = $others_preg;
  370. }
  371. // Remove zero padding on numeric entities
  372. $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string );
  373. // Replace characters according to translation table
  374. return strtr( $string, $translation );
  375. }
  376. /**
  377. * Checks for invalid UTF8 in a string.
  378. *
  379. * @since 2.8
  380. *
  381. * @param string $string The text which is to be checked.
  382. * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false.
  383. * @return string The checked text.
  384. */
  385. function wp_check_invalid_utf8( $string, $strip = false ) {
  386. $string = (string) $string;
  387. if ( 0 === strlen( $string ) ) {
  388. return '';
  389. }
  390. // Store the site charset as a static to avoid multiple calls to get_option()
  391. static $is_utf8;
  392. if ( !isset( $is_utf8 ) ) {
  393. $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) );
  394. }
  395. if ( !$is_utf8 ) {
  396. return $string;
  397. }
  398. // Check for support for utf8 in the installed PCRE library once and store the result in a static
  399. static $utf8_pcre;
  400. if ( !isset( $utf8_pcre ) ) {
  401. $utf8_pcre = @preg_match( '/^./u', 'a' );
  402. }
  403. // We can't demand utf8 in the PCRE installation, so just return the string in those cases
  404. if ( !$utf8_pcre ) {
  405. return $string;
  406. }
  407. // preg_match fails when it encounters invalid UTF8 in $string
  408. if ( 1 === @preg_match( '/^./us', $string ) ) {
  409. return $string;
  410. }
  411. // Attempt to strip the bad chars if requested (not recommended)
  412. if ( $strip && function_exists( 'iconv' ) ) {
  413. return iconv( 'utf-8', 'utf-8', $string );
  414. }
  415. return '';
  416. }
  417. /**
  418. * Encode the Unicode values to be used in the URI.
  419. *
  420. * @since 1.5.0
  421. *
  422. * @param string $utf8_string
  423. * @param int $length Max length of the string
  424. * @return string String with Unicode encoded for URI.
  425. */
  426. function utf8_uri_encode( $utf8_string, $length = 0 ) {
  427. $unicode = '';
  428. $values = array();
  429. $num_octets = 1;
  430. $unicode_length = 0;
  431. $string_length = strlen( $utf8_string );
  432. for ($i = 0; $i < $string_length; $i++ ) {
  433. $value = ord( $utf8_string[ $i ] );
  434. if ( $value < 128 ) {
  435. if ( $length && ( $unicode_length >= $length ) )
  436. break;
  437. $unicode .= chr($value);
  438. $unicode_length++;
  439. } else {
  440. if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3;
  441. $values[] = $value;
  442. if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length )
  443. break;
  444. if ( count( $values ) == $num_octets ) {
  445. if ($num_octets == 3) {
  446. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]);
  447. $unicode_length += 9;
  448. } else {
  449. $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]);
  450. $unicode_length += 6;
  451. }
  452. $values = array();
  453. $num_octets = 1;
  454. }
  455. }
  456. }
  457. return $unicode;
  458. }
  459. /**
  460. * Converts all accent characters to ASCII characters.
  461. *
  462. * If there are no accent characters, then the string given is just returned.
  463. *
  464. * @since 1.2.1
  465. *
  466. * @param string $string Text that might have accent characters
  467. * @return string Filtered string with replaced "nice" characters.
  468. */
  469. function remove_accents($string) {
  470. if ( !preg_match('/[\x80-\xff]/', $string) )
  471. return $string;
  472. if (seems_utf8($string)) {
  473. $chars = array(
  474. // Decompositions for Latin-1 Supplement
  475. chr(195).chr(128) => 'A', chr(195).chr(129) => 'A',
  476. chr(195).chr(130) => 'A', chr(195).chr(131) => 'A',
  477. chr(195).chr(132) => 'A', chr(195).chr(133) => 'A',
  478. chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C',
  479. chr(195).chr(136) => 'E', chr(195).chr(137) => 'E',
  480. chr(195).chr(138) => 'E', chr(195).chr(139) => 'E',
  481. chr(195).chr(140) => 'I', chr(195).chr(141) => 'I',
  482. chr(195).chr(142) => 'I', chr(195).chr(143) => 'I',
  483. chr(195).chr(144) => 'D', chr(195).chr(145) => 'N',
  484. chr(195).chr(146) => 'O', chr(195).chr(147) => 'O',
  485. chr(195).chr(148) => 'O', chr(195).chr(149) => 'O',
  486. chr(195).chr(150) => 'O', chr(195).chr(153) => 'U',
  487. chr(195).chr(154) => 'U', chr(195).chr(155) => 'U',
  488. chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y',
  489. chr(195).chr(158) => 'TH',chr(195).chr(159) => 's',
  490. chr(195).chr(160) => 'a', chr(195).chr(161) => 'a',
  491. chr(195).chr(162) => 'a', chr(195).chr(163) => 'a',
  492. chr(195).chr(164) => 'a', chr(195).chr(165) => 'a',
  493. chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c',
  494. chr(195).chr(168) => 'e', chr(195).chr(169) => 'e',
  495. chr(195).chr(170) => 'e', chr(195).chr(171) => 'e',
  496. chr(195).chr(172) => 'i', chr(195).chr(173) => 'i',
  497. chr(195).chr(174) => 'i', chr(195).chr(175) => 'i',
  498. chr(195).chr(176) => 'd', chr(195).chr(177) => 'n',
  499. chr(195).chr(178) => 'o', chr(195).chr(179) => 'o',
  500. chr(195).chr(180) => 'o', chr(195).chr(181) => 'o',
  501. chr(195).chr(182) => 'o', chr(195).chr(184) => 'o',
  502. chr(195).chr(185) => 'u', chr(195).chr(186) => 'u',
  503. chr(195).chr(187) => 'u', chr(195).chr(188) => 'u',
  504. chr(195).chr(189) => 'y', chr(195).chr(190) => 'th',
  505. chr(195).chr(191) => 'y',
  506. // Decompositions for Latin Extended-A
  507. chr(196).chr(128) => 'A', chr(196).chr(129) => 'a',
  508. chr(196).chr(130) => 'A', chr(196).chr(131) => 'a',
  509. chr(196).chr(132) => 'A', chr(196).chr(133) => 'a',
  510. chr(196).chr(134) => 'C', chr(196).chr(135) => 'c',
  511. chr(196).chr(136) => 'C', chr(196).chr(137) => 'c',
  512. chr(196).chr(138) => 'C', chr(196).chr(139) => 'c',
  513. chr(196).chr(140) => 'C', chr(196).chr(141) => 'c',
  514. chr(196).chr(142) => 'D', chr(196).chr(143) => 'd',
  515. chr(196).chr(144) => 'D', chr(196).chr(145) => 'd',
  516. chr(196).chr(146) => 'E', chr(196).chr(147) => 'e',
  517. chr(196).chr(148) => 'E', chr(196).chr(149) => 'e',
  518. chr(196).chr(150) => 'E', chr(196).chr(151) => 'e',
  519. chr(196).chr(152) => 'E', chr(196).chr(153) => 'e',
  520. chr(196).chr(154) => 'E', chr(196).chr(155) => 'e',
  521. chr(196).chr(156) => 'G', chr(196).chr(157) => 'g',
  522. chr(196).chr(158) => 'G', chr(196).chr(159) => 'g',
  523. chr(196).chr(160) => 'G', chr(196).chr(161) => 'g',
  524. chr(196).chr(162) => 'G', chr(196).chr(163) => 'g',
  525. chr(196).chr(164) => 'H', chr(196).chr(165) => 'h',
  526. chr(196).chr(166) => 'H', chr(196).chr(167) => 'h',
  527. chr(196).chr(168) => 'I', chr(196).chr(169) => 'i',
  528. chr(196).chr(170) => 'I', chr(196).chr(171) => 'i',
  529. chr(196).chr(172) => 'I', chr(196).chr(173) => 'i',
  530. chr(196).chr(174) => 'I', chr(196).chr(175) => 'i',
  531. chr(196).chr(176) => 'I', chr(196).chr(177) => 'i',
  532. chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij',
  533. chr(196).chr(180) => 'J', chr(196).chr(181) => 'j',
  534. chr(196).chr(182) => 'K', chr(196).chr(183) => 'k',
  535. chr(196).chr(184) => 'k', chr(196).chr(185) => 'L',
  536. chr(196).chr(186) => 'l', chr(196).chr(187) => 'L',
  537. chr(196).chr(188) => 'l', chr(196).chr(189) => 'L',
  538. chr(196).chr(190) => 'l', chr(196).chr(191) => 'L',
  539. chr(197).chr(128) => 'l', chr(197).chr(129) => 'L',
  540. chr(197).chr(130) => 'l', chr(197).chr(131) => 'N',
  541. chr(197).chr(132) => 'n', chr(197).chr(133) => 'N',
  542. chr(197).chr(134) => 'n', chr(197).chr(135) => 'N',
  543. chr(197).chr(136) => 'n', chr(197).chr(137) => 'N',
  544. chr(197).chr(138) => 'n', chr(197).chr(139) => 'N',
  545. chr(197).chr(140) => 'O', chr(197).chr(141) => 'o',
  546. chr(197).chr(142) => 'O', chr(197).chr(143) => 'o',
  547. chr(197).chr(144) => 'O', chr(197).chr(145) => 'o',
  548. chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe',
  549. chr(197).chr(148) => 'R',chr(197).chr(149) => 'r',
  550. chr(197).chr(150) => 'R',chr(197).chr(151) => 'r',
  551. chr(197).chr(152) => 'R',chr(197).chr(153) => 'r',
  552. chr(197).chr(154) => 'S',chr(197).chr(155) => 's',
  553. chr(197).chr(156) => 'S',chr(197).chr(157) => 's',
  554. chr(197).chr(158) => 'S',chr(197).chr(159) => 's',
  555. chr(197).chr(160) => 'S', chr(197).chr(161) => 's',
  556. chr(197).chr(162) => 'T', chr(197).chr(163) => 't',
  557. chr(197).chr(164) => 'T', chr(197).chr(165) => 't',
  558. chr(197).chr(166) => 'T', chr(197).chr(167) => 't',
  559. chr(197).chr(168) => 'U', chr(197).chr(169) => 'u',
  560. chr(197).chr(170) => 'U', chr(197).chr(171) => 'u',
  561. chr(197).chr(172) => 'U', chr(197).chr(173) => 'u',
  562. chr(197).chr(174) => 'U', chr(197).chr(175) => 'u',
  563. chr(197).chr(176) => 'U', chr(197).chr(177) => 'u',
  564. chr(197).chr(178) => 'U', chr(197).chr(179) => 'u',
  565. chr(197).chr(180) => 'W', chr(197).chr(181) => 'w',
  566. chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y',
  567. chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z',
  568. chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z',
  569. chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z',
  570. chr(197).chr(190) => 'z', chr(197).chr(191) => 's',
  571. // Decompositions for Latin Extended-B
  572. chr(200).chr(152) => 'S', chr(200).chr(153) => 's',
  573. chr(200).chr(154) => 'T', chr(200).chr(155) => 't',
  574. // Euro Sign
  575. chr(226).chr(130).chr(172) => 'E',
  576. // GBP (Pound) Sign
  577. chr(194).chr(163) => '');
  578. $string = strtr($string, $chars);
  579. } else {
  580. // Assume ISO-8859-1 if not UTF-8
  581. $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158)
  582. .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194)
  583. .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202)
  584. .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210)
  585. .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218)
  586. .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227)
  587. .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235)
  588. .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243)
  589. .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251)
  590. .chr(252).chr(253).chr(255);
  591. $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy";
  592. $string = strtr($string, $chars['in'], $chars['out']);
  593. $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254));
  594. $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th');
  595. $string = str_replace($double_chars['in'], $double_chars['out'], $string);
  596. }
  597. return $string;
  598. }
  599. /**
  600. * Sanitizes a filename replacing whitespace with dashes
  601. *
  602. * Removes special characters that are illegal in filenames on certain
  603. * operating systems and special characters requiring special escaping
  604. * to manipulate at the command line. Replaces spaces and consecutive
  605. * dashes with a single dash. Trim period, dash and underscore from beginning
  606. * and end of filename.
  607. *
  608. * @since 2.1.0
  609. *
  610. * @param string $filename The filename to be sanitized
  611. * @return string The sanitized filename
  612. */
  613. function sanitize_file_name( $filename ) {
  614. $filename_raw = $filename;
  615. $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0));
  616. $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw);
  617. $filename = str_replace($special_chars, '', $filename);
  618. $filename = preg_replace('/[\s-]+/', '-', $filename);
  619. $filename = trim($filename, '.-_');
  620. // Split the filename into a base and extension[s]
  621. $parts = explode('.', $filename);
  622. // Return if only one extension
  623. if ( count($parts) <= 2 )
  624. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  625. // Process multiple extensions
  626. $filename = array_shift($parts);
  627. $extension = array_pop($parts);
  628. $mimes = get_allowed_mime_types();
  629. // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character
  630. // long alpha string not in the extension whitelist.
  631. foreach ( (array) $parts as $part) {
  632. $filename .= '.' . $part;
  633. if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) {
  634. $allowed = false;
  635. foreach ( $mimes as $ext_preg => $mime_match ) {
  636. $ext_preg = '!^(' . $ext_preg . ')$!i';
  637. if ( preg_match( $ext_preg, $part ) ) {
  638. $allowed = true;
  639. break;
  640. }
  641. }
  642. if ( !$allowed )
  643. $filename .= '_';
  644. }
  645. }
  646. $filename .= '.' . $extension;
  647. return apply_filters('sanitize_file_name', $filename, $filename_raw);
  648. }
  649. /**
  650. * Sanitize username stripping out unsafe characters.
  651. *
  652. * Removes tags, octets, entities, and if strict is enabled, will only keep
  653. * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username,
  654. * raw username (the username in the parameter), and the value of $strict as
  655. * parameters for the 'sanitize_user' filter.
  656. *
  657. * @since 2.0.0
  658. * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username,
  659. * and $strict parameter.
  660. *
  661. * @param string $username The username to be sanitized.
  662. * @param bool $strict If set limits $username to specific characters. Default false.
  663. * @return string The sanitized username, after passing through filters.
  664. */
  665. function sanitize_user( $username, $strict = false ) {
  666. $raw_username = $username;
  667. $username = wp_strip_all_tags( $username );
  668. $username = remove_accents( $username );
  669. // Kill octets
  670. $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username );
  671. $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities
  672. // If strict, reduce to ASCII for max portability.
  673. if ( $strict )
  674. $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username );
  675. $username = trim( $username );
  676. // Consolidate contiguous whitespace
  677. $username = preg_replace( '|\s+|', ' ', $username );
  678. return apply_filters( 'sanitize_user', $username, $raw_username, $strict );
  679. }
  680. /**
  681. * Sanitize a string key.
  682. *
  683. * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed.
  684. *
  685. * @since 3.0.0
  686. *
  687. * @param string $key String key
  688. * @return string Sanitized key
  689. */
  690. function sanitize_key( $key ) {
  691. $raw_key = $key;
  692. $key = strtolower( $key );
  693. $key = preg_replace( '/[^a-z0-9_\-]/', '', $key );
  694. return apply_filters( 'sanitize_key', $key, $raw_key );
  695. }
  696. /**
  697. * Sanitizes title or use fallback title.
  698. *
  699. * Specifically, HTML and PHP tags are stripped. Further actions can be added
  700. * via the plugin API. If $title is empty and $fallback_title is set, the latter
  701. * will be used.
  702. *
  703. * @since 1.0.0
  704. *
  705. * @param string $title The string to be sanitized.
  706. * @param string $fallback_title Optional. A title to use if $title is empty.
  707. * @param string $context Optional. The operation for which the string is sanitized
  708. * @return string The sanitized string.
  709. */
  710. function sanitize_title($title, $fallback_title = '', $context = 'save') {
  711. $raw_title = $title;
  712. if ( 'save' == $context )
  713. $title = remove_accents($title);
  714. $title = apply_filters('sanitize_title', $title, $raw_title, $context);
  715. if ( '' === $title || false === $title )
  716. $title = $fallback_title;
  717. return $title;
  718. }
  719. function sanitize_title_for_query($title) {
  720. return sanitize_title($title, '', 'query');
  721. }
  722. /**
  723. * Sanitizes title, replacing whitespace with dashes.
  724. *
  725. * Limits the output to alphanumeric characters, underscore (_) and dash (-).
  726. * Whitespace becomes a dash.
  727. *
  728. * @since 1.2.0
  729. *
  730. * @param string $title The title to be sanitized.
  731. * @return string The sanitized title.
  732. */
  733. function sanitize_title_with_dashes($title) {
  734. $title = strip_tags($title);
  735. // Preserve escaped octets.
  736. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title);
  737. // Remove percent signs that are not part of an octet.
  738. $title = str_replace('%', '', $title);
  739. // Restore octets.
  740. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title);
  741. if (seems_utf8($title)) {
  742. if (function_exists('mb_strtolower')) {
  743. $title = mb_strtolower($title, 'UTF-8');
  744. }
  745. $title = utf8_uri_encode($title, 200);
  746. }
  747. $title = strtolower($title);
  748. $title = preg_replace('/&.+?;/', '', $title); // kill entities
  749. $title = str_replace('.', '-', $title);
  750. $title = preg_replace('/[^%a-z0-9 _-]/', '', $title);
  751. $title = preg_replace('/\s+/', '-', $title);
  752. $title = preg_replace('|-+|', '-', $title);
  753. $title = trim($title, '-');
  754. return $title;
  755. }
  756. /**
  757. * Ensures a string is a valid SQL order by clause.
  758. *
  759. * Accepts one or more columns, with or without ASC/DESC, and also accepts
  760. * RAND().
  761. *
  762. * @since 2.5.1
  763. *
  764. * @param string $orderby Order by string to be checked.
  765. * @return string|false Returns the order by clause if it is a match, false otherwise.
  766. */
  767. function sanitize_sql_orderby( $orderby ){
  768. preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches);
  769. if ( !$obmatches )
  770. return false;
  771. return $orderby;
  772. }
  773. /**
  774. * Santizes a html classname to ensure it only contains valid characters
  775. *
  776. * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty
  777. * string then it will return the alternative value supplied.
  778. *
  779. * @todo Expand to support the full range of CDATA that a class attribute can contain.
  780. *
  781. * @since 2.8.0
  782. *
  783. * @param string $class The classname to be sanitized
  784. * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string.
  785. * Defaults to an empty string.
  786. * @return string The sanitized value
  787. */
  788. function sanitize_html_class( $class, $fallback = '' ) {
  789. //Strip out any % encoded octets
  790. $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class );
  791. //Limit to A-Z,a-z,0-9,_,-
  792. $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized );
  793. if ( '' == $sanitized )
  794. $sanitized = $fallback;
  795. return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback );
  796. }
  797. /**
  798. * Converts a number of characters from a string.
  799. *
  800. * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are
  801. * converted into correct XHTML and Unicode characters are converted to the
  802. * valid range.
  803. *
  804. * @since 0.71
  805. *
  806. * @param string $content String of characters to be converted.
  807. * @param string $deprecated Not used.
  808. * @return string Converted string.
  809. */
  810. function convert_chars($content, $deprecated = '') {
  811. if ( !empty( $deprecated ) )
  812. _deprecated_argument( __FUNCTION__, '0.71' );
  813. // Translation of invalid Unicode references range to valid range
  814. $wp_htmltranswinuni = array(
  815. '&#128;' => '&#8364;', // the Euro sign
  816. '&#129;' => '',
  817. '&#130;' => '&#8218;', // these are Windows CP1252 specific characters
  818. '&#131;' => '&#402;', // they would look weird on non-Windows browsers
  819. '&#132;' => '&#8222;',
  820. '&#133;' => '&#8230;',
  821. '&#134;' => '&#8224;',
  822. '&#135;' => '&#8225;',
  823. '&#136;' => '&#710;',
  824. '&#137;' => '&#8240;',
  825. '&#138;' => '&#352;',
  826. '&#139;' => '&#8249;',
  827. '&#140;' => '&#338;',
  828. '&#141;' => '',
  829. '&#142;' => '&#382;',
  830. '&#143;' => '',
  831. '&#144;' => '',
  832. '&#145;' => '&#8216;',
  833. '&#146;' => '&#8217;',
  834. '&#147;' => '&#8220;',
  835. '&#148;' => '&#8221;',
  836. '&#149;' => '&#8226;',
  837. '&#150;' => '&#8211;',
  838. '&#151;' => '&#8212;',
  839. '&#152;' => '&#732;',
  840. '&#153;' => '&#8482;',
  841. '&#154;' => '&#353;',
  842. '&#155;' => '&#8250;',
  843. '&#156;' => '&#339;',
  844. '&#157;' => '',
  845. '&#158;' => '',
  846. '&#159;' => '&#376;'
  847. );
  848. // Remove metadata tags
  849. $content = preg_replace('/<title>(.+?)<\/title>/','',$content);
  850. $content = preg_replace('/<category>(.+?)<\/category>/','',$content);
  851. // Converts lone & characters into &#38; (a.k.a. &amp;)
  852. $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content);
  853. // Fix Word pasting
  854. $content = strtr($content, $wp_htmltranswinuni);
  855. // Just a little XHTML help
  856. $content = str_replace('<br>', '<br />', $content);
  857. $content = str_replace('<hr>', '<hr />', $content);
  858. return $content;
  859. }
  860. /**
  861. * Will only balance the tags if forced to and the option is set to balance tags.
  862. *
  863. * The option 'use_balanceTags' is used for whether the tags will be balanced.
  864. * Both the $force parameter and 'use_balanceTags' option will have to be true
  865. * before the tags will be balanced.
  866. *
  867. * @since 0.71
  868. *
  869. * @param string $text Text to be balanced
  870. * @param bool $force Forces balancing, ignoring the value of the option. Default false.
  871. * @return string Balanced text
  872. */
  873. function balanceTags( $text, $force = false ) {
  874. if ( !$force && get_option('use_balanceTags') == 0 )
  875. return $text;
  876. return force_balance_tags( $text );
  877. }
  878. /**
  879. * Balances tags of string using a modified stack.
  880. *
  881. * @since 2.0.4
  882. *
  883. * @author Leonard Lin <leonard@acm.org>
  884. * @license GPL
  885. * @copyright November 4, 2001
  886. * @version 1.1
  887. * @todo Make better - change loop condition to $text in 1.2
  888. * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004
  889. * 1.1 Fixed handling of append/stack pop order of end text
  890. * Added Cleaning Hooks
  891. * 1.0 First Version
  892. *
  893. * @param string $text Text to be balanced.
  894. * @return string Balanced text.
  895. */
  896. function force_balance_tags( $text ) {
  897. $tagstack = array();
  898. $stacksize = 0;
  899. $tagqueue = '';
  900. $newtext = '';
  901. $single_tags = array('br', 'hr', 'img', 'input'); // Known single-entity/self-closing tags
  902. $nestable_tags = array('blockquote', 'div', 'span'); // Tags that can be immediately nested within themselves
  903. // WP bug fix for comments - in case you REALLY meant to type '< !--'
  904. $text = str_replace('< !--', '< !--', $text);
  905. // WP bug fix for LOVE <3 (and other situations with '<' before a number)
  906. $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text);
  907. while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) {
  908. $newtext .= $tagqueue;
  909. $i = strpos($text, $regex[0]);
  910. $l = strlen($regex[0]);
  911. // clear the shifter
  912. $tagqueue = '';
  913. // Pop or Push
  914. if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag
  915. $tag = strtolower(substr($regex[1],1));
  916. // if too many closing tags
  917. if( $stacksize <= 0 ) {
  918. $tag = '';
  919. // or close to be safe $tag = '/' . $tag;
  920. }
  921. // if stacktop value = tag close value then pop
  922. else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag
  923. $tag = '</' . $tag . '>'; // Close Tag
  924. // Pop
  925. array_pop( $tagstack );
  926. $stacksize--;
  927. } else { // closing tag not at top, search for it
  928. for ( $j = $stacksize-1; $j >= 0; $j-- ) {
  929. if ( $tagstack[$j] == $tag ) {
  930. // add tag to tagqueue
  931. for ( $k = $stacksize-1; $k >= $j; $k--) {
  932. $tagqueue .= '</' . array_pop( $tagstack ) . '>';
  933. $stacksize--;
  934. }
  935. break;
  936. }
  937. }
  938. $tag = '';
  939. }
  940. } else { // Begin Tag
  941. $tag = strtolower($regex[1]);
  942. // Tag Cleaning
  943. // If self-closing or '', don't do anything.
  944. if ( substr($regex[2],-1) == '/' || $tag == '' ) {
  945. // do nothing
  946. }
  947. // ElseIf it's a known single-entity tag but it doesn't close itself, do so
  948. elseif ( in_array($tag, $single_tags) ) {
  949. $regex[2] .= '/';
  950. } else { // Push the tag onto the stack
  951. // If the top of the stack is the same as the tag we want to push, close previous tag
  952. if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) {
  953. $tagqueue = '</' . array_pop ($tagstack) . '>';
  954. $stacksize--;
  955. }
  956. $stacksize = array_push ($tagstack, $tag);
  957. }
  958. // Attributes
  959. $attributes = $regex[2];
  960. if( !empty($attributes) )
  961. $attributes = ' '.$attributes;
  962. $tag = '<' . $tag . $attributes . '>';
  963. //If already queuing a close tag, then put this tag on, too
  964. if ( !empty($tagqueue) ) {
  965. $tagqueue .= $tag;
  966. $tag = '';
  967. }
  968. }
  969. $newtext .= substr($text, 0, $i) . $tag;
  970. $text = substr($text, $i + $l);
  971. }
  972. // Clear Tag Queue
  973. $newtext .= $tagqueue;
  974. // Add Remaining text
  975. $newtext .= $text;
  976. // Empty Stack
  977. while( $x = array_pop($tagstack) )
  978. $newtext .= '</' . $x . '>'; // Add remaining tags to close
  979. // WP fix for the bug with HTML comments
  980. $newtext = str_replace("< !--","<!--",$newtext);
  981. $newtext = str_replace("< !--","< !--",$newtext);
  982. return $newtext;
  983. }
  984. /**
  985. * Acts on text which is about to be edited.
  986. *
  987. * Unless $richedit is set, it is simply a holder for the 'format_to_edit'
  988. * filter. If $richedit is set true htmlspecialchars(), through esc_textarea(),
  989. * will be run on the content, converting special characters to HTML entities.
  990. *
  991. * @since 0.71
  992. *
  993. * @param string $content The text about to be edited.
  994. * @param bool $richedit Whether the $content should pass through htmlspecialchars(). Default false.
  995. * @return string The text after the filter (and possibly htmlspecialchars()) has been run.
  996. */
  997. function format_to_edit( $content, $richedit = false ) {
  998. $content = apply_filters( 'format_to_edit', $content );
  999. if ( ! $richedit )
  1000. $content = esc_textarea( $content );
  1001. return $content;
  1002. }
  1003. /**
  1004. * Holder for the 'format_to_post' filter.
  1005. *
  1006. * @since 0.71
  1007. *
  1008. * @param string $content The text to pass through the filter.
  1009. * @return string Text returned from the 'format_to_post' filter.
  1010. */
  1011. function format_to_post($content) {
  1012. $content = apply_filters('format_to_post', $content);
  1013. return $content;
  1014. }
  1015. /**
  1016. * Add leading zeros when necessary.
  1017. *
  1018. * If you set the threshold to '4' and the number is '10', then you will get
  1019. * back '0010'. If you set the number to '4' and the number is '5000', then you
  1020. * will get back '5000'.
  1021. *
  1022. * Uses sprintf to append the amount of zeros based on the $threshold parameter
  1023. * and the size of the number. If the number is large enough, then no zeros will
  1024. * be appended.
  1025. *
  1026. * @since 0.71
  1027. *
  1028. * @param mixed $number Number to append zeros to if not greater than threshold.
  1029. * @param int $threshold Digit places number needs to be to not have zeros added.
  1030. * @return string Adds leading zeros to number if needed.
  1031. */
  1032. function zeroise($number, $threshold) {
  1033. return sprintf('%0'.$threshold.'s', $number);
  1034. }
  1035. /**
  1036. * Adds backslashes before letters and before a number at the start of a string.
  1037. *
  1038. * @since 0.71
  1039. *
  1040. * @param string $string Value to which backslashes will be added.
  1041. * @return string String with backslashes inserted.
  1042. */
  1043. function backslashit($string) {
  1044. $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string);
  1045. $string = preg_replace('/([a-z])/i', '\\\\\1', $string);
  1046. return $string;
  1047. }
  1048. /**
  1049. * Appends a trailing slash.
  1050. *
  1051. * Will remove trailing slash if it exists already before adding a trailing
  1052. * slash. This prevents double slashing a string or path.
  1053. *
  1054. * The primary use of this is for paths and thus should be used for paths. It is
  1055. * not restricted to paths and offers no specific path support.
  1056. *
  1057. * @since 1.2.0
  1058. * @uses untrailingslashit() Unslashes string if it was slashed already.
  1059. *
  1060. * @param string $string What to add the trailing slash to.
  1061. * @return string String with trailing slash added.
  1062. */
  1063. function trailingslashit($string) {
  1064. return untrailingslashit($string) . '/';
  1065. }
  1066. /**
  1067. * Removes trailing slash if it exists.
  1068. *
  1069. * The primary use of this is for paths and thus should be used for paths. It is
  1070. * not restricted to paths and offers no specific path support.
  1071. *
  1072. * @since 2.2.0
  1073. *
  1074. * @param string $string What to remove the trailing slash from.
  1075. * @return string String without the trailing slash.
  1076. */
  1077. function untrailingslashit($string) {
  1078. return rtrim($string, '/');
  1079. }
  1080. /**
  1081. * Adds slashes to escape strings.
  1082. *
  1083. * Slashes will first be removed if magic_quotes_gpc is set, see {@link
  1084. * http://www.php.net/magic_quotes} for more details.
  1085. *
  1086. * @since 0.71
  1087. *
  1088. * @param string $gpc The string returned from HTTP request data.
  1089. * @return string Returns a string escaped with slashes.
  1090. */
  1091. function addslashes_gpc($gpc) {
  1092. if ( get_magic_quotes_gpc() )
  1093. $gpc = stripslashes($gpc);
  1094. return esc_sql($gpc);
  1095. }
  1096. /**
  1097. * Navigates through an array and removes slashes from the values.
  1098. *
  1099. * If an array is passed, the array_map() function causes a callback to pass the
  1100. * value back to the function. The slashes from this value will removed.
  1101. *
  1102. * @since 2.0.0
  1103. *
  1104. * @param array|string $value The array or string to be stripped.
  1105. * @return array|string Stripped array (or string in the callback).
  1106. */
  1107. function stripslashes_deep($value) {
  1108. if ( is_array($value) ) {
  1109. $value = array_map('stripslashes_deep', $value);
  1110. } elseif ( is_object($value) ) {
  1111. $vars = get_object_vars( $value );
  1112. foreach ($vars as $key=>$data) {
  1113. $value->{$key} = stripslashes_deep( $data );
  1114. }
  1115. } else {
  1116. $value = stripslashes($value);
  1117. }
  1118. return $value;
  1119. }
  1120. /**
  1121. * Navigates through an array and encodes the values to be used in a URL.
  1122. *
  1123. * Uses a callback to pass the value of the array back to the function as a
  1124. * string.
  1125. *
  1126. * @since 2.2.0
  1127. *
  1128. * @param array|string $value The array or string to be encoded.
  1129. * @return array|string $value The encoded array (or string from the callback).
  1130. */
  1131. function urlencode_deep($value) {
  1132. $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value);
  1133. return $value;
  1134. }
  1135. /**
  1136. * Converts email addresses characters to HTML entities to block spam bots.
  1137. *
  1138. * @since 0.71
  1139. *
  1140. * @param string $emailaddy Email address.
  1141. * @param int $mailto Optional. Range from 0 to 1. Used for encoding.
  1142. * @return string Converted email address.
  1143. */
  1144. function antispambot($emailaddy, $mailto=0) {
  1145. $emailNOSPAMaddy = '';
  1146. srand ((float) microtime() * 1000000);
  1147. for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) {
  1148. $j = floor(rand(0, 1+$mailto));
  1149. if ($j==0) {
  1150. $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';';
  1151. } elseif ($j==1) {
  1152. $emailNOSPAMaddy .= substr($emailaddy,$i,1);
  1153. } elseif ($j==2) {
  1154. $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2);
  1155. }
  1156. }
  1157. $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy);
  1158. return $emailNOSPAMaddy;
  1159. }
  1160. /**
  1161. * Callback to convert URI match to HTML A element.
  1162. *
  1163. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1164. * make_clickable()}.
  1165. *
  1166. * @since 2.3.2
  1167. * @access private
  1168. *
  1169. * @param array $matches Single Regex Match.
  1170. * @return string HTML A element with URI address.
  1171. */
  1172. function _make_url_clickable_cb($matches) {
  1173. $url = $matches[2];
  1174. $suffix = '';
  1175. /** Include parentheses in the URL only if paired **/
  1176. while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) {
  1177. $suffix = strrchr( $url, ')' ) . $suffix;
  1178. $url = substr( $url, 0, strrpos( $url, ')' ) );
  1179. }
  1180. $url = esc_url($url);
  1181. if ( empty($url) )
  1182. return $matches[0];
  1183. return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix;
  1184. }
  1185. /**
  1186. * Callback to convert URL match to HTML A element.
  1187. *
  1188. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1189. * make_clickable()}.
  1190. *
  1191. * @since 2.3.2
  1192. * @access private
  1193. *
  1194. * @param array $matches Single Regex Match.
  1195. * @return string HTML A element with URL address.
  1196. */
  1197. function _make_web_ftp_clickable_cb($matches) {
  1198. $ret = '';
  1199. $dest = $matches[2];
  1200. $dest = 'http://' . $dest;
  1201. $dest = esc_url($dest);
  1202. if ( empty($dest) )
  1203. return $matches[0];
  1204. // removed trailing [.,;:)] from URL
  1205. if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) {
  1206. $ret = substr($dest, -1);
  1207. $dest = substr($dest, 0, strlen($dest)-1);
  1208. }
  1209. return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret";
  1210. }
  1211. /**
  1212. * Callback to convert email address match to HTML A element.
  1213. *
  1214. * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link
  1215. * make_clickable()}.
  1216. *
  1217. * @since 2.3.2
  1218. * @access private
  1219. *
  1220. * @param array $matches Single Regex Match.
  1221. * @return string HTML A element with email address.
  1222. */
  1223. function _make_email_clickable_cb($matches) {
  1224. $email = $matches[2] . '@' . $matches[3];
  1225. return $matches[1] . "<a href=\"mailto:$email\">$email</a>";
  1226. }
  1227. /**
  1228. * Convert plaintext URI to HTML links.
  1229. *
  1230. * Converts URI, www and ftp, and email addresses. Finishes by fixing links
  1231. * within links.
  1232. *
  1233. * @since 0.71
  1234. *
  1235. * @param string $ret Content to convert URIs.
  1236. * @return string Content with converted URIs.
  1237. */
  1238. function make_clickable($ret) {
  1239. $ret = ' ' . $ret;
  1240. // in testing, using arrays here was found to be faster
  1241. $save = @ini_set('pcre.recursion_limit', 10000);
  1242. $retval = preg_replace_callback('#(?<!=[\'"])(?<=[*\')+.,;:!&$\s>])(\()?([\w]+?://(?:[\w\\x80-\\xff\#%~/?@\[\]-]{1,2000}|[\'*(+.,;:!=&$](?![\b\)]|(\))?([\s]|$))|(?(1)\)(?![\s<.,;:]|$)|\)))+)#is', '_make_url_clickable_cb', $ret);
  1243. if (null !== $retval )
  1244. $ret = $retval;
  1245. @ini_set('pcre.recursion_limit', $save);
  1246. $ret = preg_replace_callback('#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret);
  1247. $ret = preg_replace_callback('#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret);
  1248. // this one is not in an array because we need it to run last, for cleanup of accidental links within links
  1249. $ret = preg_replace("#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i", "$1$3</a>", $ret);
  1250. $ret = trim($ret);
  1251. return $ret;
  1252. }
  1253. /**
  1254. * Adds rel nofollow string to all HTML A elements in content.
  1255. *
  1256. * @since 1.5.0
  1257. *
  1258. * @param string $text Content that may contain HTML A elements.
  1259. * @return string Converted content.
  1260. */
  1261. function wp_rel_nofollow( $text ) {
  1262. // This is a pre save filter, so text is already escaped.
  1263. $text = stripslashes($text);
  1264. $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text);
  1265. $text = esc_sql($text);
  1266. return $text;
  1267. }
  1268. /**
  1269. * Callback to used to add rel=nofollow string to HTML A element.
  1270. *
  1271. * Will remove already existing rel="nofollow" and rel='nofollow' from the
  1272. * string to prevent from invalidating (X)HTML.
  1273. *
  1274. * @since 2.3.0
  1275. *
  1276. * @param array $matches Single Match
  1277. * @return string HTML A Element with rel nofollow.
  1278. */
  1279. function wp_rel_nofollow_callback( $matches ) {
  1280. $text = $matches[1];
  1281. $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text);
  1282. return "<a $text rel=\"nofollow\">";
  1283. }
  1284. /**
  1285. * Convert one smiley code to the icon graphic file equivalent.
  1286. *
  1287. * Looks up one smiley code in the $wpsmiliest…

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