PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/formatting.php

https://github.com/kristenhazard/MJ-Brackin-SEA-Fund
PHP | 2919 lines | 1738 code | 232 blank | 949 comment | 237 complexity | b82d24a6cf87c438313dea3f5c451c64 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1

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

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

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