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