]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/kses.php
WordPress 4.3
[autoinstalls/wordpress.git] / wp-includes / kses.php
1 <?php
2 /**
3  * kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
4  * Copyright (C) 2002, 2003, 2005  Ulf Harnhammar
5  *
6  * This program is free software and open source software; you can redistribute
7  * it and/or modify it under the terms of the GNU General Public License as
8  * published by the Free Software Foundation; either version 2 of the License,
9  * or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
14  * more details.
15  *
16  * You should have received a copy of the GNU General Public License along
17  * with this program; if not, write to the Free Software Foundation, Inc.,
18  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  * http://www.gnu.org/licenses/gpl.html
20  *
21  * [kses strips evil scripts!]
22  *
23  * Added wp_ prefix to avoid conflicts with existing kses users
24  *
25  * @version 0.2.2
26  * @copyright (C) 2002, 2003, 2005
27  * @author Ulf Harnhammar <http://advogato.org/person/metaur/>
28  *
29  * @package External
30  * @subpackage KSES
31  *
32  */
33
34 /**
35  * You can override this in a plugin.
36  *
37  * The wp_kses_allowed_html filter is more powerful and supplies context.
38  * CUSTOM_TAGS is not recommended and should be considered deprecated.
39  *
40  * @see wp_kses_allowed_html()
41  *
42  * @since 1.2.0
43  */
44 if ( ! defined( 'CUSTOM_TAGS' ) )
45         define( 'CUSTOM_TAGS', false );
46
47 // Ensure that these variables are added to the global namespace
48 // (e.g. if using namespaces / autoload in the current PHP environment).
49 global $allowedposttags, $allowedtags, $allowedentitynames;
50
51 if ( ! CUSTOM_TAGS ) {
52         /**
53          * Kses global for default allowable HTML tags.
54          *
55          * Can be override by using CUSTOM_TAGS constant.
56          *
57          * @global array $allowedposttags
58          * @since 2.0.0
59          */
60         $allowedposttags = array(
61                 'address' => array(),
62                 'a' => array(
63                         'href' => true,
64                         'rel' => true,
65                         'rev' => true,
66                         'name' => true,
67                         'target' => true,
68                 ),
69                 'abbr' => array(),
70                 'acronym' => array(),
71                 'area' => array(
72                         'alt' => true,
73                         'coords' => true,
74                         'href' => true,
75                         'nohref' => true,
76                         'shape' => true,
77                         'target' => true,
78                 ),
79                 'article' => array(
80                         'align' => true,
81                         'dir' => true,
82                         'lang' => true,
83                         'xml:lang' => true,
84                 ),
85                 'aside' => array(
86                         'align' => true,
87                         'dir' => true,
88                         'lang' => true,
89                         'xml:lang' => true,
90                 ),
91                 'audio' => array(
92                         'autoplay' => true,
93                         'controls' => true,
94                         'loop' => true,
95                         'muted' => true,
96                         'preload' => true,
97                         'src' => true,
98                 ),
99                 'b' => array(),
100                 'big' => array(),
101                 'blockquote' => array(
102                         'cite' => true,
103                         'lang' => true,
104                         'xml:lang' => true,
105                 ),
106                 'br' => array(),
107                 'button' => array(
108                         'disabled' => true,
109                         'name' => true,
110                         'type' => true,
111                         'value' => true,
112                 ),
113                 'caption' => array(
114                         'align' => true,
115                 ),
116                 'cite' => array(
117                         'dir' => true,
118                         'lang' => true,
119                 ),
120                 'code' => array(),
121                 'col' => array(
122                         'align' => true,
123                         'char' => true,
124                         'charoff' => true,
125                         'span' => true,
126                         'dir' => true,
127                         'valign' => true,
128                         'width' => true,
129                 ),
130                 'colgroup' => array(
131                         'align' => true,
132                         'char' => true,
133                         'charoff' => true,
134                         'span' => true,
135                         'valign' => true,
136                         'width' => true,
137                 ),
138                 'del' => array(
139                         'datetime' => true,
140                 ),
141                 'dd' => array(),
142                 'dfn' => array(),
143                 'details' => array(
144                         'align' => true,
145                         'dir' => true,
146                         'lang' => true,
147                         'open' => true,
148                         'xml:lang' => true,
149                 ),
150                 'div' => array(
151                         'align' => true,
152                         'dir' => true,
153                         'lang' => true,
154                         'xml:lang' => true,
155                 ),
156                 'dl' => array(),
157                 'dt' => array(),
158                 'em' => array(),
159                 'fieldset' => array(),
160                 'figure' => array(
161                         'align' => true,
162                         'dir' => true,
163                         'lang' => true,
164                         'xml:lang' => true,
165                 ),
166                 'figcaption' => array(
167                         'align' => true,
168                         'dir' => true,
169                         'lang' => true,
170                         'xml:lang' => true,
171                 ),
172                 'font' => array(
173                         'color' => true,
174                         'face' => true,
175                         'size' => true,
176                 ),
177                 'footer' => array(
178                         'align' => true,
179                         'dir' => true,
180                         'lang' => true,
181                         'xml:lang' => true,
182                 ),
183                 'form' => array(
184                         'action' => true,
185                         'accept' => true,
186                         'accept-charset' => true,
187                         'enctype' => true,
188                         'method' => true,
189                         'name' => true,
190                         'target' => true,
191                 ),
192                 'h1' => array(
193                         'align' => true,
194                 ),
195                 'h2' => array(
196                         'align' => true,
197                 ),
198                 'h3' => array(
199                         'align' => true,
200                 ),
201                 'h4' => array(
202                         'align' => true,
203                 ),
204                 'h5' => array(
205                         'align' => true,
206                 ),
207                 'h6' => array(
208                         'align' => true,
209                 ),
210                 'header' => array(
211                         'align' => true,
212                         'dir' => true,
213                         'lang' => true,
214                         'xml:lang' => true,
215                 ),
216                 'hgroup' => array(
217                         'align' => true,
218                         'dir' => true,
219                         'lang' => true,
220                         'xml:lang' => true,
221                 ),
222                 'hr' => array(
223                         'align' => true,
224                         'noshade' => true,
225                         'size' => true,
226                         'width' => true,
227                 ),
228                 'i' => array(),
229                 'img' => array(
230                         'alt' => true,
231                         'align' => true,
232                         'border' => true,
233                         'height' => true,
234                         'hspace' => true,
235                         'longdesc' => true,
236                         'vspace' => true,
237                         'src' => true,
238                         'usemap' => true,
239                         'width' => true,
240                 ),
241                 'ins' => array(
242                         'datetime' => true,
243                         'cite' => true,
244                 ),
245                 'kbd' => array(),
246                 'label' => array(
247                         'for' => true,
248                 ),
249                 'legend' => array(
250                         'align' => true,
251                 ),
252                 'li' => array(
253                         'align' => true,
254                         'value' => true,
255                 ),
256                 'map' => array(
257                         'name' => true,
258                 ),
259                 'mark' => array(),
260                 'menu' => array(
261                         'type' => true,
262                 ),
263                 'nav' => array(
264                         'align' => true,
265                         'dir' => true,
266                         'lang' => true,
267                         'xml:lang' => true,
268                 ),
269                 'p' => array(
270                         'align' => true,
271                         'dir' => true,
272                         'lang' => true,
273                         'xml:lang' => true,
274                 ),
275                 'pre' => array(
276                         'width' => true,
277                 ),
278                 'q' => array(
279                         'cite' => true,
280                 ),
281                 's' => array(),
282                 'samp' => array(),
283                 'span' => array(
284                         'dir' => true,
285                         'align' => true,
286                         'lang' => true,
287                         'xml:lang' => true,
288                 ),
289                 'section' => array(
290                         'align' => true,
291                         'dir' => true,
292                         'lang' => true,
293                         'xml:lang' => true,
294                 ),
295                 'small' => array(),
296                 'strike' => array(),
297                 'strong' => array(),
298                 'sub' => array(),
299                 'summary' => array(
300                         'align' => true,
301                         'dir' => true,
302                         'lang' => true,
303                         'xml:lang' => true,
304                 ),
305                 'sup' => array(),
306                 'table' => array(
307                         'align' => true,
308                         'bgcolor' => true,
309                         'border' => true,
310                         'cellpadding' => true,
311                         'cellspacing' => true,
312                         'dir' => true,
313                         'rules' => true,
314                         'summary' => true,
315                         'width' => true,
316                 ),
317                 'tbody' => array(
318                         'align' => true,
319                         'char' => true,
320                         'charoff' => true,
321                         'valign' => true,
322                 ),
323                 'td' => array(
324                         'abbr' => true,
325                         'align' => true,
326                         'axis' => true,
327                         'bgcolor' => true,
328                         'char' => true,
329                         'charoff' => true,
330                         'colspan' => true,
331                         'dir' => true,
332                         'headers' => true,
333                         'height' => true,
334                         'nowrap' => true,
335                         'rowspan' => true,
336                         'scope' => true,
337                         'valign' => true,
338                         'width' => true,
339                 ),
340                 'textarea' => array(
341                         'cols' => true,
342                         'rows' => true,
343                         'disabled' => true,
344                         'name' => true,
345                         'readonly' => true,
346                 ),
347                 'tfoot' => array(
348                         'align' => true,
349                         'char' => true,
350                         'charoff' => true,
351                         'valign' => true,
352                 ),
353                 'th' => array(
354                         'abbr' => true,
355                         'align' => true,
356                         'axis' => true,
357                         'bgcolor' => true,
358                         'char' => true,
359                         'charoff' => true,
360                         'colspan' => true,
361                         'headers' => true,
362                         'height' => true,
363                         'nowrap' => true,
364                         'rowspan' => true,
365                         'scope' => true,
366                         'valign' => true,
367                         'width' => true,
368                 ),
369                 'thead' => array(
370                         'align' => true,
371                         'char' => true,
372                         'charoff' => true,
373                         'valign' => true,
374                 ),
375                 'title' => array(),
376                 'tr' => array(
377                         'align' => true,
378                         'bgcolor' => true,
379                         'char' => true,
380                         'charoff' => true,
381                         'valign' => true,
382                 ),
383                 'track' => array(
384                         'default' => true,
385                         'kind' => true,
386                         'label' => true,
387                         'src' => true,
388                         'srclang' => true,
389                 ),
390                 'tt' => array(),
391                 'u' => array(),
392                 'ul' => array(
393                         'type' => true,
394                 ),
395                 'ol' => array(
396                         'start' => true,
397                         'type' => true,
398                 ),
399                 'var' => array(),
400                 'video' => array(
401                         'autoplay' => true,
402                         'controls' => true,
403                         'height' => true,
404                         'loop' => true,
405                         'muted' => true,
406                         'poster' => true,
407                         'preload' => true,
408                         'src' => true,
409                         'width' => true,
410                 ),
411         );
412
413         /**
414          * Kses allowed HTML elements.
415          *
416          * @global array $allowedtags
417          * @since 1.0.0
418          */
419         $allowedtags = array(
420                 'a' => array(
421                         'href' => true,
422                         'title' => true,
423                 ),
424                 'abbr' => array(
425                         'title' => true,
426                 ),
427                 'acronym' => array(
428                         'title' => true,
429                 ),
430                 'b' => array(),
431                 'blockquote' => array(
432                         'cite' => true,
433                 ),
434                 'cite' => array(),
435                 'code' => array(),
436                 'del' => array(
437                         'datetime' => true,
438                 ),
439                 'em' => array(),
440                 'i' => array(),
441                 'q' => array(
442                         'cite' => true,
443                 ),
444                 's' => array(),
445                 'strike' => array(),
446                 'strong' => array(),
447         );
448
449         $allowedentitynames = array(
450                 'nbsp',    'iexcl',  'cent',    'pound',  'curren', 'yen',
451                 'brvbar',  'sect',   'uml',     'copy',   'ordf',   'laquo',
452                 'not',     'shy',    'reg',     'macr',   'deg',    'plusmn',
453                 'acute',   'micro',  'para',    'middot', 'cedil',  'ordm',
454                 'raquo',   'iquest', 'Agrave',  'Aacute', 'Acirc',  'Atilde',
455                 'Auml',    'Aring',  'AElig',   'Ccedil', 'Egrave', 'Eacute',
456                 'Ecirc',   'Euml',   'Igrave',  'Iacute', 'Icirc',  'Iuml',
457                 'ETH',     'Ntilde', 'Ograve',  'Oacute', 'Ocirc',  'Otilde',
458                 'Ouml',    'times',  'Oslash',  'Ugrave', 'Uacute', 'Ucirc',
459                 'Uuml',    'Yacute', 'THORN',   'szlig',  'agrave', 'aacute',
460                 'acirc',   'atilde', 'auml',    'aring',  'aelig',  'ccedil',
461                 'egrave',  'eacute', 'ecirc',   'euml',   'igrave', 'iacute',
462                 'icirc',   'iuml',   'eth',     'ntilde', 'ograve', 'oacute',
463                 'ocirc',   'otilde', 'ouml',    'divide', 'oslash', 'ugrave',
464                 'uacute',  'ucirc',  'uuml',    'yacute', 'thorn',  'yuml',
465                 'quot',    'amp',    'lt',      'gt',     'apos',   'OElig',
466                 'oelig',   'Scaron', 'scaron',  'Yuml',   'circ',   'tilde',
467                 'ensp',    'emsp',   'thinsp',  'zwnj',   'zwj',    'lrm',
468                 'rlm',     'ndash',  'mdash',   'lsquo',  'rsquo',  'sbquo',
469                 'ldquo',   'rdquo',  'bdquo',   'dagger', 'Dagger', 'permil',
470                 'lsaquo',  'rsaquo', 'euro',    'fnof',   'Alpha',  'Beta',
471                 'Gamma',   'Delta',  'Epsilon', 'Zeta',   'Eta',    'Theta',
472                 'Iota',    'Kappa',  'Lambda',  'Mu',     'Nu',     'Xi',
473                 'Omicron', 'Pi',     'Rho',     'Sigma',  'Tau',    'Upsilon',
474                 'Phi',     'Chi',    'Psi',     'Omega',  'alpha',  'beta',
475                 'gamma',   'delta',  'epsilon', 'zeta',   'eta',    'theta',
476                 'iota',    'kappa',  'lambda',  'mu',     'nu',     'xi',
477                 'omicron', 'pi',     'rho',     'sigmaf', 'sigma',  'tau',
478                 'upsilon', 'phi',    'chi',     'psi',    'omega',  'thetasym',
479                 'upsih',   'piv',    'bull',    'hellip', 'prime',  'Prime',
480                 'oline',   'frasl',  'weierp',  'image',  'real',   'trade',
481                 'alefsym', 'larr',   'uarr',    'rarr',   'darr',   'harr',
482                 'crarr',   'lArr',   'uArr',    'rArr',   'dArr',   'hArr',
483                 'forall',  'part',   'exist',   'empty',  'nabla',  'isin',
484                 'notin',   'ni',     'prod',    'sum',    'minus',  'lowast',
485                 'radic',   'prop',   'infin',   'ang',    'and',    'or',
486                 'cap',     'cup',    'int',     'sim',    'cong',   'asymp',
487                 'ne',      'equiv',  'le',      'ge',     'sub',    'sup',
488                 'nsub',    'sube',   'supe',    'oplus',  'otimes', 'perp',
489                 'sdot',    'lceil',  'rceil',   'lfloor', 'rfloor', 'lang',
490                 'rang',    'loz',    'spades',  'clubs',  'hearts', 'diams',
491                 'sup1',    'sup2',   'sup3',    'frac14', 'frac12', 'frac34',
492                 'there4',
493         );
494
495         $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
496 } else {
497         $allowedtags = wp_kses_array_lc( $allowedtags );
498         $allowedposttags = wp_kses_array_lc( $allowedposttags );
499 }
500
501 /**
502  * Filters content and keeps only allowable HTML elements.
503  *
504  * This function makes sure that only the allowed HTML element names, attribute
505  * names and attribute values plus only sane HTML entities will occur in
506  * $string. You have to remove any slashes from PHP's magic quotes before you
507  * call this function.
508  *
509  * The default allowed protocols are 'http', 'https', 'ftp', 'mailto', 'news',
510  * 'irc', 'gopher', 'nntp', 'feed', 'telnet, 'mms', 'rtsp' and 'svn'. This
511  * covers all common link protocols, except for 'javascript' which should not
512  * be allowed for untrusted users.
513  *
514  * @since 1.0.0
515  *
516  * @param string $string            Content to filter through kses
517  * @param array  $allowed_html      List of allowed HTML elements
518  * @param array  $allowed_protocols Optional. Allowed protocol in links.
519  * @return string Filtered content with only allowed HTML elements
520  */
521 function wp_kses( $string, $allowed_html, $allowed_protocols = array() ) {
522         if ( empty( $allowed_protocols ) )
523                 $allowed_protocols = wp_allowed_protocols();
524         $string = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
525         $string = wp_kses_js_entities($string);
526         $string = wp_kses_normalize_entities($string);
527         $string = wp_kses_hook($string, $allowed_html, $allowed_protocols); // WP changed the order of these funcs and added args to wp_kses_hook
528         return wp_kses_split($string, $allowed_html, $allowed_protocols);
529 }
530
531 /**
532  * Filters one attribute only and ensures its value is allowed.
533  *
534  * This function has the advantage of being more secure than esc_attr() and can
535  * escape data in some situations where wp_kses() must strip the whole attribute.
536  *
537  * @since 4.2.3
538  *
539  * @param string $string The 'whole' attribute, including name and value.
540  * @param string $element The element name to which the attribute belongs.
541  * @return string Filtered attribute.
542  */
543 function wp_kses_one_attr( $string, $element ) {
544         $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
545         $allowed_html = wp_kses_allowed_html( 'post' );
546         $allowed_protocols = wp_allowed_protocols();
547         $string = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
548         $string = wp_kses_js_entities( $string );
549         
550         // Preserve leading and trailing whitespace.
551         $matches = array();
552         preg_match('/^\s*/', $string, $matches);
553         $lead = $matches[0];
554         preg_match('/\s*$/', $string, $matches);
555         $trail = $matches[0];
556         if ( empty( $trail ) ) {
557                 $string = substr( $string, strlen( $lead ) );
558         } else {
559                 $string = substr( $string, strlen( $lead ), -strlen( $trail ) );
560         }
561         
562         // Parse attribute name and value from input.
563         $split = preg_split( '/\s*=\s*/', $string, 2 );
564         $name = $split[0];
565         if ( count( $split ) == 2 ) {
566                 $value = $split[1];
567
568                 // Remove quotes surrounding $value.
569                 // Also guarantee correct quoting in $string for this one attribute.
570                 if ( '' == $value ) {
571                         $quote = '';
572                 } else {
573                         $quote = $value[0];
574                 }
575                 if ( '"' == $quote || "'" == $quote ) {
576                         if ( substr( $value, -1 ) != $quote ) {
577                                 return '';
578                         }
579                         $value = substr( $value, 1, -1 );
580                 } else {
581                         $quote = '"';
582                 }
583
584                 // Sanitize quotes, angle braces, and entities.
585                 $value = esc_attr( $value );
586
587                 // Sanitize URI values.
588                 if ( in_array( strtolower( $name ), $uris ) ) {
589                         $value = wp_kses_bad_protocol( $value, $allowed_protocols );
590                 }
591
592                 $string = "$name=$quote$value$quote";
593                 $vless = 'n';
594         } else {
595                 $value = '';
596                 $vless = 'y';
597         }
598         
599         // Sanitize attribute by name.
600         wp_kses_attr_check( $name, $value, $string, $vless, $element, $allowed_html );
601
602         // Restore whitespace.
603         return $lead . $string . $trail;
604 }
605
606 /**
607  * Return a list of allowed tags and attributes for a given context.
608  *
609  * @since 3.5.0
610  *
611  * @global array $allowedposttags
612  * @global array $allowedtags
613  * @global array $allowedentitynames
614  *
615  * @param string $context The context for which to retrieve tags.
616  *                        Allowed values are post, strip, data,entities, or
617  *                        the name of a field filter such as pre_user_description.
618  * @return array List of allowed tags and their allowed attributes.
619  */
620 function wp_kses_allowed_html( $context = '' ) {
621         global $allowedposttags, $allowedtags, $allowedentitynames;
622
623         if ( is_array( $context ) ) {
624                 /**
625                  * Filter HTML elements allowed for a given context.
626                  *
627                  * @since 3.5.0
628                  *
629                  * @param string $tags    Allowed tags, attributes, and/or entities.
630                  * @param string $context Context to judge allowed tags by. Allowed values are 'post',
631                  *                        'data', 'strip', 'entities', 'explicit', or the name of a filter.
632                  */
633                 return apply_filters( 'wp_kses_allowed_html', $context, 'explicit' );
634         }
635
636         switch ( $context ) {
637                 case 'post':
638                         /** This filter is documented in wp-includes/kses.php */
639                         return apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
640
641                 case 'user_description':
642                 case 'pre_user_description':
643                         $tags = $allowedtags;
644                         $tags['a']['rel'] = true;
645                         /** This filter is documented in wp-includes/kses.php */
646                         return apply_filters( 'wp_kses_allowed_html', $tags, $context );
647
648                 case 'strip':
649                         /** This filter is documented in wp-includes/kses.php */
650                         return apply_filters( 'wp_kses_allowed_html', array(), $context );
651
652                 case 'entities':
653                         /** This filter is documented in wp-includes/kses.php */
654                         return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context);
655
656                 case 'data':
657                 default:
658                         /** This filter is documented in wp-includes/kses.php */
659                         return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
660         }
661 }
662
663 /**
664  * You add any kses hooks here.
665  *
666  * There is currently only one kses WordPress hook and it is called here. All
667  * parameters are passed to the hooks and expected to receive a string.
668  *
669  * @since 1.0.0
670  *
671  * @param string $string            Content to filter through kses
672  * @param array  $allowed_html      List of allowed HTML elements
673  * @param array  $allowed_protocols Allowed protocol in links
674  * @return string Filtered content through 'pre_kses' hook
675  */
676 function wp_kses_hook( $string, $allowed_html, $allowed_protocols ) {
677         /**
678          * Filter content to be run through kses.
679          *
680          * @since 2.3.0
681          *
682          * @param string $string            Content to run through kses.
683          * @param array  $allowed_html      Allowed HTML elements.
684          * @param array  $allowed_protocols Allowed protocol in links.
685          */
686         return apply_filters( 'pre_kses', $string, $allowed_html, $allowed_protocols );
687 }
688
689 /**
690  * This function returns kses' version number.
691  *
692  * @since 1.0.0
693  *
694  * @return string KSES Version Number
695  */
696 function wp_kses_version() {
697         return '0.2.2';
698 }
699
700 /**
701  * Searches for HTML tags, no matter how malformed.
702  *
703  * It also matches stray ">" characters.
704  *
705  * @since 1.0.0
706  *
707  * @global array $pass_allowed_html
708  * @global array $pass_allowed_protocols
709  *
710  * @param string $string            Content to filter
711  * @param array  $allowed_html      Allowed HTML elements
712  * @param array  $allowed_protocols Allowed protocols to keep
713  * @return string Content with fixed HTML tags
714  */
715 function wp_kses_split( $string, $allowed_html, $allowed_protocols ) {
716         global $pass_allowed_html, $pass_allowed_protocols;
717         $pass_allowed_html = $allowed_html;
718         $pass_allowed_protocols = $allowed_protocols;
719         return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
720 }
721
722 /**
723  * Callback for wp_kses_split.
724  *
725  * @since 3.1.0
726  * @access private
727  *
728  * @global array $pass_allowed_html
729  * @global array $pass_allowed_protocols
730  *
731  * @return string
732  */
733 function _wp_kses_split_callback( $match ) {
734         global $pass_allowed_html, $pass_allowed_protocols;
735         return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
736 }
737
738 /**
739  * Callback for wp_kses_split for fixing malformed HTML tags.
740  *
741  * This function does a lot of work. It rejects some very malformed things like
742  * <:::>. It returns an empty string, if the element isn't allowed (look ma, no
743  * strip_tags()!). Otherwise it splits the tag into an element and an attribute
744  * list.
745  *
746  * After the tag is split into an element and an attribute list, it is run
747  * through another filter which will remove illegal attributes and once that is
748  * completed, will be returned.
749  *
750  * @access private
751  * @since 1.0.0
752  *
753  * @param string $string            Content to filter
754  * @param array  $allowed_html      Allowed HTML elements
755  * @param array  $allowed_protocols Allowed protocols to keep
756  * @return string Fixed HTML element
757  */
758 function wp_kses_split2($string, $allowed_html, $allowed_protocols) {
759         $string = wp_kses_stripslashes($string);
760
761         if (substr($string, 0, 1) != '<')
762                 return '&gt;';
763         // It matched a ">" character
764
765         if ( '<!--' == substr( $string, 0, 4 ) ) {
766                 $string = str_replace( array('<!--', '-->'), '', $string );
767                 while ( $string != ($newstring = wp_kses($string, $allowed_html, $allowed_protocols)) )
768                         $string = $newstring;
769                 if ( $string == '' )
770                         return '';
771                 // prevent multiple dashes in comments
772                 $string = preg_replace('/--+/', '-', $string);
773                 // prevent three dashes closing a comment
774                 $string = preg_replace('/-$/', '', $string);
775                 return "<!--{$string}-->";
776         }
777         // Allow HTML comments
778
779         if (!preg_match('%^<\s*(/\s*)?([a-zA-Z0-9]+)([^>]*)>?$%', $string, $matches))
780                 return '';
781         // It's seriously malformed
782
783         $slash = trim($matches[1]);
784         $elem = $matches[2];
785         $attrlist = $matches[3];
786
787         if ( ! is_array( $allowed_html ) )
788                 $allowed_html = wp_kses_allowed_html( $allowed_html );
789
790         if ( ! isset($allowed_html[strtolower($elem)]) )
791                 return '';
792         // They are using a not allowed HTML element
793
794         if ($slash != '')
795                 return "</$elem>";
796         // No attributes are allowed for closing elements
797
798         return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
799 }
800
801 /**
802  * Removes all attributes, if none are allowed for this element.
803  *
804  * If some are allowed it calls wp_kses_hair() to split them further, and then
805  * it builds up new HTML code from the data that kses_hair() returns. It also
806  * removes "<" and ">" characters, if there are any left. One more thing it does
807  * is to check if the tag has a closing XHTML slash, and if it does, it puts one
808  * in the returned code as well.
809  *
810  * @since 1.0.0
811  *
812  * @param string $element           HTML element/tag
813  * @param string $attr              HTML attributes from HTML element to closing HTML element tag
814  * @param array  $allowed_html      Allowed HTML elements
815  * @param array  $allowed_protocols Allowed protocols to keep
816  * @return string Sanitized HTML element
817  */
818 function wp_kses_attr($element, $attr, $allowed_html, $allowed_protocols) {
819         if ( ! is_array( $allowed_html ) )
820                 $allowed_html = wp_kses_allowed_html( $allowed_html );
821
822         // Is there a closing XHTML slash at the end of the attributes?
823         $xhtml_slash = '';
824         if (preg_match('%\s*/\s*$%', $attr))
825                 $xhtml_slash = ' /';
826
827         // Are any attributes allowed at all for this element?
828         if ( ! isset($allowed_html[strtolower($element)]) || count($allowed_html[strtolower($element)]) == 0 )
829                 return "<$element$xhtml_slash>";
830
831         // Split it
832         $attrarr = wp_kses_hair($attr, $allowed_protocols);
833
834         // Go through $attrarr, and save the allowed attributes for this element
835         // in $attr2
836         $attr2 = '';
837         foreach ( $attrarr as $arreach ) {
838                 if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
839                         $attr2 .= ' '.$arreach['whole'];
840                 }
841         }
842
843         // Remove any "<" or ">" characters
844         $attr2 = preg_replace('/[<>]/', '', $attr2);
845
846         return "<$element$attr2$xhtml_slash>";
847 }
848
849 /**
850  * Determine whether an attribute is allowed.
851  *
852  * @since 4.2.3
853  *
854  * @param string $name The attribute name. Returns empty string when not allowed.
855  * @param string $value The attribute value. Returns a filtered value.
856  * @param string $whole The name=value input. Returns filtered input.
857  * @param string $vless 'y' when attribute like "enabled", otherwise 'n'.
858  * @param string $element The name of the element to which this attribute belongs.
859  * @param array $allowed_html The full list of allowed elements and attributes.
860  * @return bool Is the attribute allowed?
861  */
862 function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
863         $allowed_attr = $allowed_html[strtolower( $element )];
864
865         $name_low = strtolower( $name );
866         if ( ! isset( $allowed_attr[$name_low] ) || '' == $allowed_attr[$name_low] ) {
867                 $name = $value = $whole = '';
868                 return false;
869         }
870
871         if ( 'style' == $name_low ) {
872                 $new_value = safecss_filter_attr( $value );
873
874                 if ( empty( $new_value ) ) {
875                         $name = $value = $whole = '';
876                         return false;
877                 }
878
879                 $whole = str_replace( $value, $new_value, $whole );
880                 $value = $new_value;
881         }
882
883         if ( is_array( $allowed_attr[$name_low] ) ) {
884                 // there are some checks
885                 foreach ( $allowed_attr[$name_low] as $currkey => $currval ) {
886                         if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
887                                 $name = $value = $whole = '';
888                                 return false;
889                         }
890                 }
891         }
892
893         return true;
894 }
895
896 /**
897  * Builds an attribute list from string containing attributes.
898  *
899  * This function does a lot of work. It parses an attribute list into an array
900  * with attribute data, and tries to do the right thing even if it gets weird
901  * input. It will add quotes around attribute values that don't have any quotes
902  * or apostrophes around them, to make it easier to produce HTML code that will
903  * conform to W3C's HTML specification. It will also remove bad URL protocols
904  * from attribute values. It also reduces duplicate attributes by using the
905  * attribute defined first (foo='bar' foo='baz' will result in foo='bar').
906  *
907  * @since 1.0.0
908  *
909  * @param string $attr              Attribute list from HTML element to closing HTML element tag
910  * @param array  $allowed_protocols Allowed protocols to keep
911  * @return array List of attributes after parsing
912  */
913 function wp_kses_hair($attr, $allowed_protocols) {
914         $attrarr = array();
915         $mode = 0;
916         $attrname = '';
917         $uris = array('xmlns', 'profile', 'href', 'src', 'cite', 'classid', 'codebase', 'data', 'usemap', 'longdesc', 'action');
918
919         // Loop through the whole attribute list
920
921         while (strlen($attr) != 0) {
922                 $working = 0; // Was the last operation successful?
923
924                 switch ($mode) {
925                         case 0 : // attribute name, href for instance
926
927                                 if ( preg_match('/^([-a-zA-Z:]+)/', $attr, $match ) ) {
928                                         $attrname = $match[1];
929                                         $working = $mode = 1;
930                                         $attr = preg_replace( '/^[-a-zA-Z:]+/', '', $attr );
931                                 }
932
933                                 break;
934
935                         case 1 : // equals sign or valueless ("selected")
936
937                                 if (preg_match('/^\s*=\s*/', $attr)) // equals sign
938                                         {
939                                         $working = 1;
940                                         $mode = 2;
941                                         $attr = preg_replace('/^\s*=\s*/', '', $attr);
942                                         break;
943                                 }
944
945                                 if (preg_match('/^\s+/', $attr)) // valueless
946                                         {
947                                         $working = 1;
948                                         $mode = 0;
949                                         if(false === array_key_exists($attrname, $attrarr)) {
950                                                 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
951                                         }
952                                         $attr = preg_replace('/^\s+/', '', $attr);
953                                 }
954
955                                 break;
956
957                         case 2 : // attribute value, a URL after href= for instance
958
959                                 if (preg_match('%^"([^"]*)"(\s+|/?$)%', $attr, $match))
960                                         // "value"
961                                         {
962                                         $thisval = $match[1];
963                                         if ( in_array(strtolower($attrname), $uris) )
964                                                 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
965
966                                         if(false === array_key_exists($attrname, $attrarr)) {
967                                                 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
968                                         }
969                                         $working = 1;
970                                         $mode = 0;
971                                         $attr = preg_replace('/^"[^"]*"(\s+|$)/', '', $attr);
972                                         break;
973                                 }
974
975                                 if (preg_match("%^'([^']*)'(\s+|/?$)%", $attr, $match))
976                                         // 'value'
977                                         {
978                                         $thisval = $match[1];
979                                         if ( in_array(strtolower($attrname), $uris) )
980                                                 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
981
982                                         if(false === array_key_exists($attrname, $attrarr)) {
983                                                 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname='$thisval'", 'vless' => 'n');
984                                         }
985                                         $working = 1;
986                                         $mode = 0;
987                                         $attr = preg_replace("/^'[^']*'(\s+|$)/", '', $attr);
988                                         break;
989                                 }
990
991                                 if (preg_match("%^([^\s\"']+)(\s+|/?$)%", $attr, $match))
992                                         // value
993                                         {
994                                         $thisval = $match[1];
995                                         if ( in_array(strtolower($attrname), $uris) )
996                                                 $thisval = wp_kses_bad_protocol($thisval, $allowed_protocols);
997
998                                         if(false === array_key_exists($attrname, $attrarr)) {
999                                                 $attrarr[$attrname] = array ('name' => $attrname, 'value' => $thisval, 'whole' => "$attrname=\"$thisval\"", 'vless' => 'n');
1000                                         }
1001                                         // We add quotes to conform to W3C's HTML spec.
1002                                         $working = 1;
1003                                         $mode = 0;
1004                                         $attr = preg_replace("%^[^\s\"']+(\s+|$)%", '', $attr);
1005                                 }
1006
1007                                 break;
1008                 } // switch
1009
1010                 if ($working == 0) // not well formed, remove and try again
1011                 {
1012                         $attr = wp_kses_html_error($attr);
1013                         $mode = 0;
1014                 }
1015         } // while
1016
1017         if ($mode == 1 && false === array_key_exists($attrname, $attrarr))
1018                 // special case, for when the attribute list ends with a valueless
1019                 // attribute like "selected"
1020                 $attrarr[$attrname] = array ('name' => $attrname, 'value' => '', 'whole' => $attrname, 'vless' => 'y');
1021
1022         return $attrarr;
1023 }
1024
1025 /**
1026  * Finds all attributes of an HTML element.
1027  *
1028  * Does not modify input.  May return "evil" output.
1029  *
1030  * Based on wp_kses_split2() and wp_kses_attr()
1031  *
1032  * @since 4.2.3
1033  *
1034  * @param string $element HTML element/tag
1035  * @return array|bool List of attributes found in $element. Returns false on failure.
1036  */
1037 function wp_kses_attr_parse( $element ) {
1038         $valid = preg_match('%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches);
1039         if ( 1 !== $valid ) {
1040                 return false;
1041         }
1042
1043         $begin =  $matches[1];
1044         $slash =  $matches[2];
1045         $elname = $matches[3];
1046         $attr =   $matches[4];
1047         $end =    $matches[5];
1048
1049         if ( '' !== $slash ) {
1050                 // Closing elements do not get parsed.
1051                 return false;
1052         }
1053
1054         // Is there a closing XHTML slash at the end of the attributes?
1055         if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
1056                 $xhtml_slash = $matches[0];
1057                 $attr = substr( $attr, 0, -strlen( $xhtml_slash ) );
1058         } else {
1059                 $xhtml_slash = '';
1060         }
1061         
1062         // Split it
1063         $attrarr = wp_kses_hair_parse( $attr );
1064         if ( false === $attrarr ) {
1065                 return false;
1066         }
1067
1068         // Make sure all input is returned by adding front and back matter.
1069         array_unshift( $attrarr, $begin . $slash . $elname );
1070         array_push( $attrarr, $xhtml_slash . $end );
1071         
1072         return $attrarr;
1073 }
1074
1075 /**
1076  * Builds an attribute list from string containing attributes.
1077  *
1078  * Does not modify input.  May return "evil" output.
1079  * In case of unexpected input, returns false instead of stripping things.
1080  *
1081  * Based on wp_kses_hair() but does not return a multi-dimensional array.
1082  *
1083  * @since 4.2.3
1084  *
1085  * @param string $attr Attribute list from HTML element to closing HTML element tag
1086  * @return array|bool List of attributes found in $attr. Returns false on failure.
1087  */
1088 function wp_kses_hair_parse( $attr ) {
1089         if ( '' === $attr ) {
1090                 return array();
1091         }
1092
1093         $regex =
1094           '(?:'
1095         .     '[-a-zA-Z:]+'   // Attribute name.
1096         . '|'
1097         .     '\[\[?[^\[\]]+\]\]?' // Shortcode in the name position implies unfiltered_html.
1098         . ')'
1099         . '(?:'               // Attribute value.
1100         .     '\s*=\s*'       // All values begin with '='
1101         .     '(?:'
1102         .         '"[^"]*"'   // Double-quoted
1103         .     '|'
1104         .         "'[^']*'"   // Single-quoted
1105         .     '|'
1106         .         '[^\s"\']+' // Non-quoted
1107         .         '(?:\s|$)'  // Must have a space
1108         .     ')'
1109         . '|'
1110         .     '(?:\s|$)'      // If attribute has no value, space is required.
1111         . ')'
1112         . '\s*';              // Trailing space is optional except as mentioned above.
1113
1114         // Although it is possible to reduce this procedure to a single regexp,
1115         // we must run that regexp twice to get exactly the expected result.
1116
1117         $validation = "%^($regex)+$%";
1118         $extraction = "%$regex%";
1119
1120         if ( 1 === preg_match( $validation, $attr ) ) {
1121                 preg_match_all( $extraction, $attr, $attrarr );
1122                 return $attrarr[0];
1123         } else {
1124                 return false;
1125         }
1126 }
1127
1128 /**
1129  * Performs different checks for attribute values.
1130  *
1131  * The currently implemented checks are "maxlen", "minlen", "maxval", "minval"
1132  * and "valueless".
1133  *
1134  * @since 1.0.0
1135  *
1136  * @param string $value      Attribute value
1137  * @param string $vless      Whether the value is valueless. Use 'y' or 'n'
1138  * @param string $checkname  What $checkvalue is checking for.
1139  * @param mixed  $checkvalue What constraint the value should pass
1140  * @return bool Whether check passes
1141  */
1142 function wp_kses_check_attr_val($value, $vless, $checkname, $checkvalue) {
1143         $ok = true;
1144
1145         switch (strtolower($checkname)) {
1146                 case 'maxlen' :
1147                         // The maxlen check makes sure that the attribute value has a length not
1148                         // greater than the given value. This can be used to avoid Buffer Overflows
1149                         // in WWW clients and various Internet servers.
1150
1151                         if (strlen($value) > $checkvalue)
1152                                 $ok = false;
1153                         break;
1154
1155                 case 'minlen' :
1156                         // The minlen check makes sure that the attribute value has a length not
1157                         // smaller than the given value.
1158
1159                         if (strlen($value) < $checkvalue)
1160                                 $ok = false;
1161                         break;
1162
1163                 case 'maxval' :
1164                         // The maxval check does two things: it checks that the attribute value is
1165                         // an integer from 0 and up, without an excessive amount of zeroes or
1166                         // whitespace (to avoid Buffer Overflows). It also checks that the attribute
1167                         // value is not greater than the given value.
1168                         // This check can be used to avoid Denial of Service attacks.
1169
1170                         if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
1171                                 $ok = false;
1172                         if ($value > $checkvalue)
1173                                 $ok = false;
1174                         break;
1175
1176                 case 'minval' :
1177                         // The minval check makes sure that the attribute value is a positive integer,
1178                         // and that it is not smaller than the given value.
1179
1180                         if (!preg_match('/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value))
1181                                 $ok = false;
1182                         if ($value < $checkvalue)
1183                                 $ok = false;
1184                         break;
1185
1186                 case 'valueless' :
1187                         // The valueless check makes sure if the attribute has a value
1188                         // (like <a href="blah">) or not (<option selected>). If the given value
1189                         // is a "y" or a "Y", the attribute must not have a value.
1190                         // If the given value is an "n" or an "N", the attribute must have one.
1191
1192                         if (strtolower($checkvalue) != $vless)
1193                                 $ok = false;
1194                         break;
1195         } // switch
1196
1197         return $ok;
1198 }
1199
1200 /**
1201  * Sanitize string from bad protocols.
1202  *
1203  * This function removes all non-allowed protocols from the beginning of
1204  * $string. It ignores whitespace and the case of the letters, and it does
1205  * understand HTML entities. It does its work in a while loop, so it won't be
1206  * fooled by a string like "javascript:javascript:alert(57)".
1207  *
1208  * @since 1.0.0
1209  *
1210  * @param string $string            Content to filter bad protocols from
1211  * @param array  $allowed_protocols Allowed protocols to keep
1212  * @return string Filtered content
1213  */
1214 function wp_kses_bad_protocol($string, $allowed_protocols) {
1215         $string = wp_kses_no_null($string);
1216         $iterations = 0;
1217
1218         do {
1219                 $original_string = $string;
1220                 $string = wp_kses_bad_protocol_once($string, $allowed_protocols);
1221         } while ( $original_string != $string && ++$iterations < 6 );
1222
1223         if ( $original_string != $string )
1224                 return '';
1225
1226         return $string;
1227 }
1228
1229 /**
1230  * Removes any invalid control characters in $string.
1231  *
1232  * Also removes any instance of the '\0' string.
1233  *
1234  * @since 1.0.0
1235  *
1236  * @param string $string
1237  * @param array $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
1238  * @return string
1239  */
1240 function wp_kses_no_null( $string, $options = null ) {
1241         if ( ! isset( $options['slash_zero'] ) ) {
1242                 $options = array( 'slash_zero' => 'remove' );
1243         }
1244
1245         $string = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string );
1246         if ( 'remove' == $options['slash_zero'] ) {
1247                 $string = preg_replace( '/\\\\+0+/', '', $string );
1248         }
1249
1250         return $string;
1251 }
1252
1253 /**
1254  * Strips slashes from in front of quotes.
1255  *
1256  * This function changes the character sequence \" to just ". It leaves all
1257  * other slashes alone. It's really weird, but the quoting from
1258  * preg_replace(//e) seems to require this.
1259  *
1260  * @since 1.0.0
1261  *
1262  * @param string $string String to strip slashes
1263  * @return string Fixed string with quoted slashes
1264  */
1265 function wp_kses_stripslashes($string) {
1266         return preg_replace('%\\\\"%', '"', $string);
1267 }
1268
1269 /**
1270  * Goes through an array and changes the keys to all lower case.
1271  *
1272  * @since 1.0.0
1273  *
1274  * @param array $inarray Unfiltered array
1275  * @return array Fixed array with all lowercase keys
1276  */
1277 function wp_kses_array_lc($inarray) {
1278         $outarray = array ();
1279
1280         foreach ( (array) $inarray as $inkey => $inval) {
1281                 $outkey = strtolower($inkey);
1282                 $outarray[$outkey] = array ();
1283
1284                 foreach ( (array) $inval as $inkey2 => $inval2) {
1285                         $outkey2 = strtolower($inkey2);
1286                         $outarray[$outkey][$outkey2] = $inval2;
1287                 } // foreach $inval
1288         } // foreach $inarray
1289
1290         return $outarray;
1291 }
1292
1293 /**
1294  * Removes the HTML JavaScript entities found in early versions of Netscape 4.
1295  *
1296  * @since 1.0.0
1297  *
1298  * @param string $string
1299  * @return string
1300  */
1301 function wp_kses_js_entities($string) {
1302         return preg_replace('%&\s*\{[^}]*(\}\s*;?|$)%', '', $string);
1303 }
1304
1305 /**
1306  * Handles parsing errors in wp_kses_hair().
1307  *
1308  * The general plan is to remove everything to and including some whitespace,
1309  * but it deals with quotes and apostrophes as well.
1310  *
1311  * @since 1.0.0
1312  *
1313  * @param string $string
1314  * @return string
1315  */
1316 function wp_kses_html_error($string) {
1317         return preg_replace('/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string);
1318 }
1319
1320 /**
1321  * Sanitizes content from bad protocols and other characters.
1322  *
1323  * This function searches for URL protocols at the beginning of $string, while
1324  * handling whitespace and HTML entities.
1325  *
1326  * @since 1.0.0
1327  *
1328  * @param string $string            Content to check for bad protocols
1329  * @param string $allowed_protocols Allowed protocols
1330  * @return string Sanitized content
1331  */
1332 function wp_kses_bad_protocol_once($string, $allowed_protocols, $count = 1 ) {
1333         $string2 = preg_split( '/:|&#0*58;|&#x0*3a;/i', $string, 2 );
1334         if ( isset($string2[1]) && ! preg_match('%/\?%', $string2[0]) ) {
1335                 $string = trim( $string2[1] );
1336                 $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
1337                 if ( 'feed:' == $protocol ) {
1338                         if ( $count > 2 )
1339                                 return '';
1340                         $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
1341                         if ( empty( $string ) )
1342                                 return $string;
1343                 }
1344                 $string = $protocol . $string;
1345         }
1346
1347         return $string;
1348 }
1349
1350 /**
1351  * Callback for wp_kses_bad_protocol_once() regular expression.
1352  *
1353  * This function processes URL protocols, checks to see if they're in the
1354  * whitelist or not, and returns different data depending on the answer.
1355  *
1356  * @access private
1357  * @since 1.0.0
1358  *
1359  * @param string $string            URI scheme to check against the whitelist
1360  * @param string $allowed_protocols Allowed protocols
1361  * @return string Sanitized content
1362  */
1363 function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1364         $string2 = wp_kses_decode_entities($string);
1365         $string2 = preg_replace('/\s/', '', $string2);
1366         $string2 = wp_kses_no_null($string2);
1367         $string2 = strtolower($string2);
1368
1369         $allowed = false;
1370         foreach ( (array) $allowed_protocols as $one_protocol )
1371                 if ( strtolower($one_protocol) == $string2 ) {
1372                         $allowed = true;
1373                         break;
1374                 }
1375
1376         if ($allowed)
1377                 return "$string2:";
1378         else
1379                 return '';
1380 }
1381
1382 /**
1383  * Converts and fixes HTML entities.
1384  *
1385  * This function normalizes HTML entities. It will convert `AT&T` to the correct
1386  * `AT&amp;T`, `&#00058;` to `&#58;`, `&#XYZZY;` to `&amp;#XYZZY;` and so on.
1387  *
1388  * @since 1.0.0
1389  *
1390  * @param string $string Content to normalize entities
1391  * @return string Content with normalized entities
1392  */
1393 function wp_kses_normalize_entities($string) {
1394         // Disarm all entities by converting & to &amp;
1395         $string = str_replace('&', '&amp;', $string);
1396
1397         // Change back the allowed entities in our entity whitelist
1398         $string = preg_replace_callback('/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $string);
1399         $string = preg_replace_callback('/&amp;#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string);
1400         $string = preg_replace_callback('/&amp;#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string);
1401
1402         return $string;
1403 }
1404
1405 /**
1406  * Callback for wp_kses_normalize_entities() regular expression.
1407  *
1408  * This function only accepts valid named entity references, which are finite,
1409  * case-sensitive, and highly scrutinized by HTML and XML validators.
1410  *
1411  * @since 3.0.0
1412  *
1413  * @global array $allowedentitynames
1414  *
1415  * @param array $matches preg_replace_callback() matches array
1416  * @return string Correctly encoded entity
1417  */
1418 function wp_kses_named_entities($matches) {
1419         global $allowedentitynames;
1420
1421         if ( empty($matches[1]) )
1422                 return '';
1423
1424         $i = $matches[1];
1425         return ( ! in_array( $i, $allowedentitynames ) ) ? "&amp;$i;" : "&$i;";
1426 }
1427
1428 /**
1429  * Callback for wp_kses_normalize_entities() regular expression.
1430  *
1431  * This function helps {@see wp_kses_normalize_entities()} to only accept 16-bit
1432  * values and nothing more for `&#number;` entities.
1433  *
1434  * @access private
1435  * @since 1.0.0
1436  *
1437  * @param array $matches preg_replace_callback() matches array
1438  * @return string Correctly encoded entity
1439  */
1440 function wp_kses_normalize_entities2($matches) {
1441         if ( empty($matches[1]) )
1442                 return '';
1443
1444         $i = $matches[1];
1445         if (valid_unicode($i)) {
1446                 $i = str_pad(ltrim($i,'0'), 3, '0', STR_PAD_LEFT);
1447                 $i = "&#$i;";
1448         } else {
1449                 $i = "&amp;#$i;";
1450         }
1451
1452         return $i;
1453 }
1454
1455 /**
1456  * Callback for wp_kses_normalize_entities() for regular expression.
1457  *
1458  * This function helps wp_kses_normalize_entities() to only accept valid Unicode
1459  * numeric entities in hex form.
1460  *
1461  * @access private
1462  *
1463  * @param array $matches preg_replace_callback() matches array
1464  * @return string Correctly encoded entity
1465  */
1466 function wp_kses_normalize_entities3($matches) {
1467         if ( empty($matches[1]) )
1468                 return '';
1469
1470         $hexchars = $matches[1];
1471         return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&amp;#x$hexchars;" : '&#x'.ltrim($hexchars,'0').';';
1472 }
1473
1474 /**
1475  * Helper function to determine if a Unicode value is valid.
1476  *
1477  * @param int $i Unicode value
1478  * @return bool True if the value was a valid Unicode number
1479  */
1480 function valid_unicode($i) {
1481         return ( $i == 0x9 || $i == 0xa || $i == 0xd ||
1482                         ($i >= 0x20 && $i <= 0xd7ff) ||
1483                         ($i >= 0xe000 && $i <= 0xfffd) ||
1484                         ($i >= 0x10000 && $i <= 0x10ffff) );
1485 }
1486
1487 /**
1488  * Convert all entities to their character counterparts.
1489  *
1490  * This function decodes numeric HTML entities (`&#65;` and `&#x41;`).
1491  * It doesn't do anything with other entities like &auml;, but we don't
1492  * need them in the URL protocol whitelisting system anyway.
1493  *
1494  * @since 1.0.0
1495  *
1496  * @param string $string Content to change entities
1497  * @return string Content after decoded entities
1498  */
1499 function wp_kses_decode_entities($string) {
1500         $string = preg_replace_callback('/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string);
1501         $string = preg_replace_callback('/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string);
1502
1503         return $string;
1504 }
1505
1506 /**
1507  * Regex callback for wp_kses_decode_entities()
1508  *
1509  * @param array $match preg match
1510  * @return string
1511  */
1512 function _wp_kses_decode_entities_chr( $match ) {
1513         return chr( $match[1] );
1514 }
1515
1516 /**
1517  * Regex callback for wp_kses_decode_entities()
1518  *
1519  * @param array $match preg match
1520  * @return string
1521  */
1522 function _wp_kses_decode_entities_chr_hexdec( $match ) {
1523         return chr( hexdec( $match[1] ) );
1524 }
1525
1526 /**
1527  * Sanitize content with allowed HTML Kses rules.
1528  *
1529  * @since 1.0.0
1530  *
1531  * @param string $data Content to filter, expected to be escaped with slashes
1532  * @return string Filtered content
1533  */
1534 function wp_filter_kses( $data ) {
1535         return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
1536 }
1537
1538 /**
1539  * Sanitize content with allowed HTML Kses rules.
1540  *
1541  * @since 2.9.0
1542  *
1543  * @param string $data Content to filter, expected to not be escaped
1544  * @return string Filtered content
1545  */
1546 function wp_kses_data( $data ) {
1547         return wp_kses( $data, current_filter() );
1548 }
1549
1550 /**
1551  * Sanitize content for allowed HTML tags for post content.
1552  *
1553  * Post content refers to the page contents of the 'post' type and not $_POST
1554  * data from forms.
1555  *
1556  * @since 2.0.0
1557  *
1558  * @param string $data Post content to filter, expected to be escaped with slashes
1559  * @return string Filtered post content with allowed HTML tags and attributes intact.
1560  */
1561 function wp_filter_post_kses( $data ) {
1562         return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
1563 }
1564
1565 /**
1566  * Sanitize content for allowed HTML tags for post content.
1567  *
1568  * Post content refers to the page contents of the 'post' type and not $_POST
1569  * data from forms.
1570  *
1571  * @since 2.9.0
1572  *
1573  * @param string $data Post content to filter
1574  * @return string Filtered post content with allowed HTML tags and attributes intact.
1575  */
1576 function wp_kses_post( $data ) {
1577         return wp_kses( $data, 'post' );
1578 }
1579
1580 /**
1581  * Strips all of the HTML in the content.
1582  *
1583  * @since 2.1.0
1584  *
1585  * @param string $data Content to strip all HTML from
1586  * @return string Filtered content without any HTML
1587  */
1588 function wp_filter_nohtml_kses( $data ) {
1589         return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
1590 }
1591
1592 /**
1593  * Adds all Kses input form content filters.
1594  *
1595  * All hooks have default priority. The wp_filter_kses() function is added to
1596  * the 'pre_comment_content' and 'title_save_pre' hooks.
1597  *
1598  * The wp_filter_post_kses() function is added to the 'content_save_pre',
1599  * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
1600  *
1601  * @since 2.0.0
1602  */
1603 function kses_init_filters() {
1604         // Normal filtering
1605         add_filter('title_save_pre', 'wp_filter_kses');
1606
1607         // Comment filtering
1608         if ( current_user_can( 'unfiltered_html' ) )
1609                 add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1610         else
1611                 add_filter( 'pre_comment_content', 'wp_filter_kses' );
1612
1613         // Post filtering
1614         add_filter('content_save_pre', 'wp_filter_post_kses');
1615         add_filter('excerpt_save_pre', 'wp_filter_post_kses');
1616         add_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1617 }
1618
1619 /**
1620  * Removes all Kses input form content filters.
1621  *
1622  * A quick procedural method to removing all of the filters that kses uses for
1623  * content in WordPress Loop.
1624  *
1625  * Does not remove the kses_init() function from 'init' hook (priority is
1626  * default). Also does not remove kses_init() function from 'set_current_user'
1627  * hook (priority is also default).
1628  *
1629  * @since 2.0.6
1630  */
1631 function kses_remove_filters() {
1632         // Normal filtering
1633         remove_filter('title_save_pre', 'wp_filter_kses');
1634
1635         // Comment filtering
1636         remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
1637         remove_filter( 'pre_comment_content', 'wp_filter_kses' );
1638
1639         // Post filtering
1640         remove_filter('content_save_pre', 'wp_filter_post_kses');
1641         remove_filter('excerpt_save_pre', 'wp_filter_post_kses');
1642         remove_filter('content_filtered_save_pre', 'wp_filter_post_kses');
1643 }
1644
1645 /**
1646  * Sets up most of the Kses filters for input form content.
1647  *
1648  * If you remove the kses_init() function from 'init' hook and
1649  * 'set_current_user' (priority is default), then none of the Kses filter hooks
1650  * will be added.
1651  *
1652  * First removes all of the Kses filters in case the current user does not need
1653  * to have Kses filter the content. If the user does not have unfiltered_html
1654  * capability, then Kses filters are added.
1655  *
1656  * @since 2.0.0
1657  */
1658 function kses_init() {
1659         kses_remove_filters();
1660
1661         if ( ! current_user_can( 'unfiltered_html' ) ) {
1662                 kses_init_filters();
1663         }
1664 }
1665
1666 /**
1667  * Inline CSS filter
1668  *
1669  * @since 2.8.1
1670  */
1671 function safecss_filter_attr( $css, $deprecated = '' ) {
1672         if ( !empty( $deprecated ) )
1673                 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented
1674
1675         $css = wp_kses_no_null($css);
1676         $css = str_replace(array("\n","\r","\t"), '', $css);
1677
1678         if ( preg_match( '%[\\\\(&=}]|/\*%', $css ) ) // remove any inline css containing \ ( & } = or comments
1679                 return '';
1680
1681         $css_array = explode( ';', trim( $css ) );
1682
1683         /**
1684          * Filter list of allowed CSS attributes.
1685          *
1686          * @since 2.8.1
1687          *
1688          * @param array $attr List of allowed CSS attributes.
1689          */
1690         $allowed_attr = apply_filters( 'safe_style_css', array( 'text-align', 'margin', 'color', 'float',
1691         'border', 'background', 'background-color', 'border-bottom', 'border-bottom-color',
1692         'border-bottom-style', 'border-bottom-width', 'border-collapse', 'border-color', 'border-left',
1693         'border-left-color', 'border-left-style', 'border-left-width', 'border-right', 'border-right-color',
1694         'border-right-style', 'border-right-width', 'border-spacing', 'border-style', 'border-top',
1695         'border-top-color', 'border-top-style', 'border-top-width', 'border-width', 'caption-side',
1696         'clear', 'cursor', 'direction', 'font', 'font-family', 'font-size', 'font-style',
1697         'font-variant', 'font-weight', 'height', 'letter-spacing', 'line-height', 'margin-bottom',
1698         'margin-left', 'margin-right', 'margin-top', 'overflow', 'padding', 'padding-bottom',
1699         'padding-left', 'padding-right', 'padding-top', 'text-decoration', 'text-indent', 'vertical-align',
1700         'width' ) );
1701
1702         if ( empty($allowed_attr) )
1703                 return $css;
1704
1705         $css = '';
1706         foreach ( $css_array as $css_item ) {
1707                 if ( $css_item == '' )
1708                         continue;
1709                 $css_item = trim( $css_item );
1710                 $found = false;
1711                 if ( strpos( $css_item, ':' ) === false ) {
1712                         $found = true;
1713                 } else {
1714                         $parts = explode( ':', $css_item );
1715                         if ( in_array( trim( $parts[0] ), $allowed_attr ) )
1716                                 $found = true;
1717                 }
1718                 if ( $found ) {
1719                         if( $css != '' )
1720                                 $css .= ';';
1721                         $css .= $css_item;
1722                 }
1723         }
1724
1725         return $css;
1726 }
1727
1728 /**
1729  * Helper function to add global attributes to a tag in the allowed html list.
1730  *
1731  * @since 3.5.0
1732  * @access private
1733  *
1734  * @param array $value An array of attributes.
1735  * @return array The array of attributes with global attributes added.
1736  */
1737 function _wp_add_global_attributes( $value ) {
1738         $global_attributes = array(
1739                 'class' => true,
1740                 'id' => true,
1741                 'style' => true,
1742                 'title' => true,
1743                 'role' => true,
1744         );
1745
1746         if ( true === $value )
1747                 $value = array();
1748
1749         if ( is_array( $value ) )
1750                 return array_merge( $value, $global_attributes );
1751
1752         return $value;
1753 }