PageRenderTime 65ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 0ms

/msw/dev/wp-includes/formatting.php

https://github.com/chrissiebrodigan/USC
PHP | 2810 lines | 1678 code | 225 blank | 907 comment | 231 complexity | d4bda5cc7b56fbdcedb5cb4b7c774e2e MD5 | raw file

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

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