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