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