[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/ -> kses.php (source)

   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   * Specifies the default allowable HTML tags.
  35   *
  36   * Using `CUSTOM_TAGS` is not recommended and should be considered deprecated. The
  37   * {@see 'wp_kses_allowed_html'} filter is more powerful and supplies context.
  38   *
  39   * @see wp_kses_allowed_html()
  40   * @since 1.2.0
  41   *
  42   * @var array[]|false Array of default allowable HTML tags, or false to use the defaults.
  43   */
  44  if ( ! defined( 'CUSTOM_TAGS' ) ) {
  45      define( 'CUSTOM_TAGS', false );
  46  }
  47  
  48  // Ensure that these variables are added to the global namespace
  49  // (e.g. if using namespaces / autoload in the current PHP environment).
  50  global $allowedposttags, $allowedtags, $allowedentitynames, $allowedxmlentitynames;
  51  
  52  if ( ! CUSTOM_TAGS ) {
  53      /**
  54       * KSES global for default allowable HTML tags.
  55       *
  56       * Can be overridden with the `CUSTOM_TAGS` constant.
  57       *
  58       * @var array[] $allowedposttags Array of default allowable HTML tags.
  59       * @since 2.0.0
  60       */
  61      $allowedposttags = array(
  62          'address'    => array(),
  63          'a'          => array(
  64              'href'     => true,
  65              'rel'      => true,
  66              'rev'      => true,
  67              'name'     => true,
  68              'target'   => true,
  69              'download' => array(
  70                  'valueless' => 'y',
  71              ),
  72          ),
  73          'abbr'       => array(),
  74          'acronym'    => array(),
  75          'area'       => array(
  76              'alt'    => true,
  77              'coords' => true,
  78              'href'   => true,
  79              'nohref' => true,
  80              'shape'  => true,
  81              'target' => true,
  82          ),
  83          'article'    => array(
  84              'align' => true,
  85          ),
  86          'aside'      => array(
  87              'align' => true,
  88          ),
  89          'audio'      => array(
  90              'autoplay' => true,
  91              'controls' => true,
  92              'loop'     => true,
  93              'muted'    => true,
  94              'preload'  => true,
  95              'src'      => true,
  96          ),
  97          'b'          => array(),
  98          'bdo'        => array(),
  99          'big'        => array(),
 100          'blockquote' => array(
 101              'cite' => true,
 102          ),
 103          'br'         => array(),
 104          'button'     => array(
 105              'disabled' => true,
 106              'name'     => true,
 107              'type'     => true,
 108              'value'    => true,
 109          ),
 110          'caption'    => array(
 111              'align' => true,
 112          ),
 113          'cite'       => array(),
 114          'code'       => array(),
 115          'col'        => array(
 116              'align'   => true,
 117              'char'    => true,
 118              'charoff' => true,
 119              'span'    => true,
 120              'valign'  => true,
 121              'width'   => true,
 122          ),
 123          'colgroup'   => array(
 124              'align'   => true,
 125              'char'    => true,
 126              'charoff' => true,
 127              'span'    => true,
 128              'valign'  => true,
 129              'width'   => true,
 130          ),
 131          'del'        => array(
 132              'datetime' => true,
 133          ),
 134          'dd'         => array(),
 135          'dfn'        => array(),
 136          'details'    => array(
 137              'align' => true,
 138              'open'  => true,
 139          ),
 140          'div'        => array(
 141              'align' => true,
 142          ),
 143          'dl'         => array(),
 144          'dt'         => array(),
 145          'em'         => array(),
 146          'fieldset'   => array(),
 147          'figure'     => array(
 148              'align' => true,
 149          ),
 150          'figcaption' => array(
 151              'align' => true,
 152          ),
 153          'font'       => array(
 154              'color' => true,
 155              'face'  => true,
 156              'size'  => true,
 157          ),
 158          'footer'     => array(
 159              'align' => true,
 160          ),
 161          'h1'         => array(
 162              'align' => true,
 163          ),
 164          'h2'         => array(
 165              'align' => true,
 166          ),
 167          'h3'         => array(
 168              'align' => true,
 169          ),
 170          'h4'         => array(
 171              'align' => true,
 172          ),
 173          'h5'         => array(
 174              'align' => true,
 175          ),
 176          'h6'         => array(
 177              'align' => true,
 178          ),
 179          'header'     => array(
 180              'align' => true,
 181          ),
 182          'hgroup'     => array(
 183              'align' => true,
 184          ),
 185          'hr'         => array(
 186              'align'   => true,
 187              'noshade' => true,
 188              'size'    => true,
 189              'width'   => true,
 190          ),
 191          'i'          => array(),
 192          'img'        => array(
 193              'alt'      => true,
 194              'align'    => true,
 195              'border'   => true,
 196              'height'   => true,
 197              'hspace'   => true,
 198              'loading'  => true,
 199              'longdesc' => true,
 200              'vspace'   => true,
 201              'src'      => true,
 202              'usemap'   => true,
 203              'width'    => true,
 204          ),
 205          'ins'        => array(
 206              'datetime' => true,
 207              'cite'     => true,
 208          ),
 209          'kbd'        => array(),
 210          'label'      => array(
 211              'for' => true,
 212          ),
 213          'legend'     => array(
 214              'align' => true,
 215          ),
 216          'li'         => array(
 217              'align' => true,
 218              'value' => true,
 219          ),
 220          'main'       => array(
 221              'align' => true,
 222          ),
 223          'map'        => array(
 224              'name' => true,
 225          ),
 226          'mark'       => array(),
 227          'menu'       => array(
 228              'type' => true,
 229          ),
 230          'nav'        => array(
 231              'align' => true,
 232          ),
 233          'object'     => array(
 234              'data' => array(
 235                  'required'       => true,
 236                  'value_callback' => '_wp_kses_allow_pdf_objects',
 237              ),
 238              'type' => array(
 239                  'required' => true,
 240                  'values'   => array( 'application/pdf' ),
 241              ),
 242          ),
 243          'p'          => array(
 244              'align' => true,
 245          ),
 246          'pre'        => array(
 247              'width' => true,
 248          ),
 249          'q'          => array(
 250              'cite' => true,
 251          ),
 252          'rb'         => array(),
 253          'rp'         => array(),
 254          'rt'         => array(),
 255          'rtc'        => array(),
 256          'ruby'       => array(),
 257          's'          => array(),
 258          'samp'       => array(),
 259          'span'       => array(
 260              'align' => true,
 261          ),
 262          'section'    => array(
 263              'align' => true,
 264          ),
 265          'small'      => array(),
 266          'strike'     => array(),
 267          'strong'     => array(),
 268          'sub'        => array(),
 269          'summary'    => array(
 270              'align' => true,
 271          ),
 272          'sup'        => array(),
 273          'table'      => array(
 274              'align'       => true,
 275              'bgcolor'     => true,
 276              'border'      => true,
 277              'cellpadding' => true,
 278              'cellspacing' => true,
 279              'rules'       => true,
 280              'summary'     => true,
 281              'width'       => true,
 282          ),
 283          'tbody'      => array(
 284              'align'   => true,
 285              'char'    => true,
 286              'charoff' => true,
 287              'valign'  => true,
 288          ),
 289          'td'         => array(
 290              'abbr'    => true,
 291              'align'   => true,
 292              'axis'    => true,
 293              'bgcolor' => true,
 294              'char'    => true,
 295              'charoff' => true,
 296              'colspan' => true,
 297              'headers' => true,
 298              'height'  => true,
 299              'nowrap'  => true,
 300              'rowspan' => true,
 301              'scope'   => true,
 302              'valign'  => true,
 303              'width'   => true,
 304          ),
 305          'textarea'   => array(
 306              'cols'     => true,
 307              'rows'     => true,
 308              'disabled' => true,
 309              'name'     => true,
 310              'readonly' => true,
 311          ),
 312          'tfoot'      => array(
 313              'align'   => true,
 314              'char'    => true,
 315              'charoff' => true,
 316              'valign'  => true,
 317          ),
 318          'th'         => array(
 319              'abbr'    => true,
 320              'align'   => true,
 321              'axis'    => true,
 322              'bgcolor' => true,
 323              'char'    => true,
 324              'charoff' => true,
 325              'colspan' => true,
 326              'headers' => true,
 327              'height'  => true,
 328              'nowrap'  => true,
 329              'rowspan' => true,
 330              'scope'   => true,
 331              'valign'  => true,
 332              'width'   => true,
 333          ),
 334          'thead'      => array(
 335              'align'   => true,
 336              'char'    => true,
 337              'charoff' => true,
 338              'valign'  => true,
 339          ),
 340          'title'      => array(),
 341          'tr'         => array(
 342              'align'   => true,
 343              'bgcolor' => true,
 344              'char'    => true,
 345              'charoff' => true,
 346              'valign'  => true,
 347          ),
 348          'track'      => array(
 349              'default' => true,
 350              'kind'    => true,
 351              'label'   => true,
 352              'src'     => true,
 353              'srclang' => true,
 354          ),
 355          'tt'         => array(),
 356          'u'          => array(),
 357          'ul'         => array(
 358              'type' => true,
 359          ),
 360          'ol'         => array(
 361              'start'    => true,
 362              'type'     => true,
 363              'reversed' => true,
 364          ),
 365          'var'        => array(),
 366          'video'      => array(
 367              'autoplay'    => true,
 368              'controls'    => true,
 369              'height'      => true,
 370              'loop'        => true,
 371              'muted'       => true,
 372              'playsinline' => true,
 373              'poster'      => true,
 374              'preload'     => true,
 375              'src'         => true,
 376              'width'       => true,
 377          ),
 378      );
 379  
 380      /**
 381       * @var array[] $allowedtags Array of KSES allowed HTML elements.
 382       * @since 1.0.0
 383       */
 384      $allowedtags = array(
 385          'a'          => array(
 386              'href'  => true,
 387              'title' => true,
 388          ),
 389          'abbr'       => array(
 390              'title' => true,
 391          ),
 392          'acronym'    => array(
 393              'title' => true,
 394          ),
 395          'b'          => array(),
 396          'blockquote' => array(
 397              'cite' => true,
 398          ),
 399          'cite'       => array(),
 400          'code'       => array(),
 401          'del'        => array(
 402              'datetime' => true,
 403          ),
 404          'em'         => array(),
 405          'i'          => array(),
 406          'q'          => array(
 407              'cite' => true,
 408          ),
 409          's'          => array(),
 410          'strike'     => array(),
 411          'strong'     => array(),
 412      );
 413  
 414      /**
 415       * @var string[] $allowedentitynames Array of KSES allowed HTML entity names.
 416       * @since 1.0.0
 417       */
 418      $allowedentitynames = array(
 419          'nbsp',
 420          'iexcl',
 421          'cent',
 422          'pound',
 423          'curren',
 424          'yen',
 425          'brvbar',
 426          'sect',
 427          'uml',
 428          'copy',
 429          'ordf',
 430          'laquo',
 431          'not',
 432          'shy',
 433          'reg',
 434          'macr',
 435          'deg',
 436          'plusmn',
 437          'acute',
 438          'micro',
 439          'para',
 440          'middot',
 441          'cedil',
 442          'ordm',
 443          'raquo',
 444          'iquest',
 445          'Agrave',
 446          'Aacute',
 447          'Acirc',
 448          'Atilde',
 449          'Auml',
 450          'Aring',
 451          'AElig',
 452          'Ccedil',
 453          'Egrave',
 454          'Eacute',
 455          'Ecirc',
 456          'Euml',
 457          'Igrave',
 458          'Iacute',
 459          'Icirc',
 460          'Iuml',
 461          'ETH',
 462          'Ntilde',
 463          'Ograve',
 464          'Oacute',
 465          'Ocirc',
 466          'Otilde',
 467          'Ouml',
 468          'times',
 469          'Oslash',
 470          'Ugrave',
 471          'Uacute',
 472          'Ucirc',
 473          'Uuml',
 474          'Yacute',
 475          'THORN',
 476          'szlig',
 477          'agrave',
 478          'aacute',
 479          'acirc',
 480          'atilde',
 481          'auml',
 482          'aring',
 483          'aelig',
 484          'ccedil',
 485          'egrave',
 486          'eacute',
 487          'ecirc',
 488          'euml',
 489          'igrave',
 490          'iacute',
 491          'icirc',
 492          'iuml',
 493          'eth',
 494          'ntilde',
 495          'ograve',
 496          'oacute',
 497          'ocirc',
 498          'otilde',
 499          'ouml',
 500          'divide',
 501          'oslash',
 502          'ugrave',
 503          'uacute',
 504          'ucirc',
 505          'uuml',
 506          'yacute',
 507          'thorn',
 508          'yuml',
 509          'quot',
 510          'amp',
 511          'lt',
 512          'gt',
 513          'apos',
 514          'OElig',
 515          'oelig',
 516          'Scaron',
 517          'scaron',
 518          'Yuml',
 519          'circ',
 520          'tilde',
 521          'ensp',
 522          'emsp',
 523          'thinsp',
 524          'zwnj',
 525          'zwj',
 526          'lrm',
 527          'rlm',
 528          'ndash',
 529          'mdash',
 530          'lsquo',
 531          'rsquo',
 532          'sbquo',
 533          'ldquo',
 534          'rdquo',
 535          'bdquo',
 536          'dagger',
 537          'Dagger',
 538          'permil',
 539          'lsaquo',
 540          'rsaquo',
 541          'euro',
 542          'fnof',
 543          'Alpha',
 544          'Beta',
 545          'Gamma',
 546          'Delta',
 547          'Epsilon',
 548          'Zeta',
 549          'Eta',
 550          'Theta',
 551          'Iota',
 552          'Kappa',
 553          'Lambda',
 554          'Mu',
 555          'Nu',
 556          'Xi',
 557          'Omicron',
 558          'Pi',
 559          'Rho',
 560          'Sigma',
 561          'Tau',
 562          'Upsilon',
 563          'Phi',
 564          'Chi',
 565          'Psi',
 566          'Omega',
 567          'alpha',
 568          'beta',
 569          'gamma',
 570          'delta',
 571          'epsilon',
 572          'zeta',
 573          'eta',
 574          'theta',
 575          'iota',
 576          'kappa',
 577          'lambda',
 578          'mu',
 579          'nu',
 580          'xi',
 581          'omicron',
 582          'pi',
 583          'rho',
 584          'sigmaf',
 585          'sigma',
 586          'tau',
 587          'upsilon',
 588          'phi',
 589          'chi',
 590          'psi',
 591          'omega',
 592          'thetasym',
 593          'upsih',
 594          'piv',
 595          'bull',
 596          'hellip',
 597          'prime',
 598          'Prime',
 599          'oline',
 600          'frasl',
 601          'weierp',
 602          'image',
 603          'real',
 604          'trade',
 605          'alefsym',
 606          'larr',
 607          'uarr',
 608          'rarr',
 609          'darr',
 610          'harr',
 611          'crarr',
 612          'lArr',
 613          'uArr',
 614          'rArr',
 615          'dArr',
 616          'hArr',
 617          'forall',
 618          'part',
 619          'exist',
 620          'empty',
 621          'nabla',
 622          'isin',
 623          'notin',
 624          'ni',
 625          'prod',
 626          'sum',
 627          'minus',
 628          'lowast',
 629          'radic',
 630          'prop',
 631          'infin',
 632          'ang',
 633          'and',
 634          'or',
 635          'cap',
 636          'cup',
 637          'int',
 638          'sim',
 639          'cong',
 640          'asymp',
 641          'ne',
 642          'equiv',
 643          'le',
 644          'ge',
 645          'sub',
 646          'sup',
 647          'nsub',
 648          'sube',
 649          'supe',
 650          'oplus',
 651          'otimes',
 652          'perp',
 653          'sdot',
 654          'lceil',
 655          'rceil',
 656          'lfloor',
 657          'rfloor',
 658          'lang',
 659          'rang',
 660          'loz',
 661          'spades',
 662          'clubs',
 663          'hearts',
 664          'diams',
 665          'sup1',
 666          'sup2',
 667          'sup3',
 668          'frac14',
 669          'frac12',
 670          'frac34',
 671          'there4',
 672      );
 673  
 674      /**
 675       * @var string[] $allowedxmlentitynames Array of KSES allowed XML entity names.
 676       * @since 5.5.0
 677       */
 678      $allowedxmlentitynames = array(
 679          'amp',
 680          'lt',
 681          'gt',
 682          'apos',
 683          'quot',
 684      );
 685  
 686      $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
 687  } else {
 688      $allowedtags     = wp_kses_array_lc( $allowedtags );
 689      $allowedposttags = wp_kses_array_lc( $allowedposttags );
 690  }
 691  
 692  /**
 693   * Filters text content and strips out disallowed HTML.
 694   *
 695   * This function makes sure that only the allowed HTML element names, attribute
 696   * names, attribute values, and HTML entities will occur in the given text string.
 697   *
 698   * This function expects unslashed data.
 699   *
 700   * @see wp_kses_post() for specifically filtering post content and fields.
 701   * @see wp_allowed_protocols() for the default allowed protocols in link URLs.
 702   *
 703   * @since 1.0.0
 704   *
 705   * @param string         $string            Text content to filter.
 706   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 707   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 708   *                                          for the list of accepted context names.
 709   * @param string[]       $allowed_protocols Optional. Array of allowed URL protocols.
 710   *                                          Defaults to the result of wp_allowed_protocols().
 711   * @return string Filtered content containing only the allowed HTML.
 712   */
 713  function wp_kses( $string, $allowed_html, $allowed_protocols = array() ) {
 714      if ( empty( $allowed_protocols ) ) {
 715          $allowed_protocols = wp_allowed_protocols();
 716      }
 717  
 718      $string = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
 719      $string = wp_kses_normalize_entities( $string );
 720      $string = wp_kses_hook( $string, $allowed_html, $allowed_protocols );
 721  
 722      return wp_kses_split( $string, $allowed_html, $allowed_protocols );
 723  }
 724  
 725  /**
 726   * Filters one HTML attribute and ensures its value is allowed.
 727   *
 728   * This function can escape data in some situations where `wp_kses()` must strip the whole attribute.
 729   *
 730   * @since 4.2.3
 731   *
 732   * @param string $string  The 'whole' attribute, including name and value.
 733   * @param string $element The HTML element name to which the attribute belongs.
 734   * @return string Filtered attribute.
 735   */
 736  function wp_kses_one_attr( $string, $element ) {
 737      $uris              = wp_kses_uri_attributes();
 738      $allowed_html      = wp_kses_allowed_html( 'post' );
 739      $allowed_protocols = wp_allowed_protocols();
 740      $string            = wp_kses_no_null( $string, array( 'slash_zero' => 'keep' ) );
 741  
 742      // Preserve leading and trailing whitespace.
 743      $matches = array();
 744      preg_match( '/^\s*/', $string, $matches );
 745      $lead = $matches[0];
 746      preg_match( '/\s*$/', $string, $matches );
 747      $trail = $matches[0];
 748      if ( empty( $trail ) ) {
 749          $string = substr( $string, strlen( $lead ) );
 750      } else {
 751          $string = substr( $string, strlen( $lead ), -strlen( $trail ) );
 752      }
 753  
 754      // Parse attribute name and value from input.
 755      $split = preg_split( '/\s*=\s*/', $string, 2 );
 756      $name  = $split[0];
 757      if ( count( $split ) == 2 ) {
 758          $value = $split[1];
 759  
 760          // Remove quotes surrounding $value.
 761          // Also guarantee correct quoting in $string for this one attribute.
 762          if ( '' === $value ) {
 763              $quote = '';
 764          } else {
 765              $quote = $value[0];
 766          }
 767          if ( '"' === $quote || "'" === $quote ) {
 768              if ( substr( $value, -1 ) != $quote ) {
 769                  return '';
 770              }
 771              $value = substr( $value, 1, -1 );
 772          } else {
 773              $quote = '"';
 774          }
 775  
 776          // Sanitize quotes, angle braces, and entities.
 777          $value = esc_attr( $value );
 778  
 779          // Sanitize URI values.
 780          if ( in_array( strtolower( $name ), $uris, true ) ) {
 781              $value = wp_kses_bad_protocol( $value, $allowed_protocols );
 782          }
 783  
 784          $string = "$name=$quote$value$quote";
 785          $vless  = 'n';
 786      } else {
 787          $value = '';
 788          $vless = 'y';
 789      }
 790  
 791      // Sanitize attribute by name.
 792      wp_kses_attr_check( $name, $value, $string, $vless, $element, $allowed_html );
 793  
 794      // Restore whitespace.
 795      return $lead . $string . $trail;
 796  }
 797  
 798  /**
 799   * Returns an array of allowed HTML tags and attributes for a given context.
 800   *
 801   * @since 3.5.0
 802   * @since 5.0.1 `form` removed as allowable HTML tag.
 803   *
 804   * @global array $allowedposttags
 805   * @global array $allowedtags
 806   * @global array $allowedentitynames
 807   *
 808   * @param string|array $context The context for which to retrieve tags. Allowed values are 'post',
 809   *                              'strip', 'data', 'entities', or the name of a field filter such as
 810   *                              'pre_user_description', or an array of allowed HTML elements and attributes.
 811   * @return array Array of allowed HTML tags and their allowed attributes.
 812   */
 813  function wp_kses_allowed_html( $context = '' ) {
 814      global $allowedposttags, $allowedtags, $allowedentitynames;
 815  
 816      if ( is_array( $context ) ) {
 817          // When `$context` is an array it's actually an array of allowed HTML elements and attributes.
 818          $html    = $context;
 819          $context = 'explicit';
 820  
 821          /**
 822           * Filters the HTML tags that are allowed for a given context.
 823           *
 824           * HTML tags and attribute names are case-insensitive in HTML but must be
 825           * added to the KSES allow list in lowercase. An item added to the allow list
 826           * in upper or mixed case will not recognized as permitted by KSES.
 827           *
 828           * @since 3.5.0
 829           *
 830           * @param array[] $html    Allowed HTML tags.
 831           * @param string  $context Context name.
 832           */
 833          return apply_filters( 'wp_kses_allowed_html', $html, $context );
 834      }
 835  
 836      switch ( $context ) {
 837          case 'post':
 838              /** This filter is documented in wp-includes/kses.php */
 839              $tags = apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
 840  
 841              // 5.0.1 removed the `<form>` tag, allow it if a filter is allowing it's sub-elements `<input>` or `<select>`.
 842              if ( ! CUSTOM_TAGS && ! isset( $tags['form'] ) && ( isset( $tags['input'] ) || isset( $tags['select'] ) ) ) {
 843                  $tags = $allowedposttags;
 844  
 845                  $tags['form'] = array(
 846                      'action'         => true,
 847                      'accept'         => true,
 848                      'accept-charset' => true,
 849                      'enctype'        => true,
 850                      'method'         => true,
 851                      'name'           => true,
 852                      'target'         => true,
 853                  );
 854  
 855                  /** This filter is documented in wp-includes/kses.php */
 856                  $tags = apply_filters( 'wp_kses_allowed_html', $tags, $context );
 857              }
 858  
 859              return $tags;
 860  
 861          case 'user_description':
 862          case 'pre_user_description':
 863              $tags             = $allowedtags;
 864              $tags['a']['rel'] = true;
 865              /** This filter is documented in wp-includes/kses.php */
 866              return apply_filters( 'wp_kses_allowed_html', $tags, $context );
 867  
 868          case 'strip':
 869              /** This filter is documented in wp-includes/kses.php */
 870              return apply_filters( 'wp_kses_allowed_html', array(), $context );
 871  
 872          case 'entities':
 873              /** This filter is documented in wp-includes/kses.php */
 874              return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context );
 875  
 876          case 'data':
 877          default:
 878              /** This filter is documented in wp-includes/kses.php */
 879              return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
 880      }
 881  }
 882  
 883  /**
 884   * You add any KSES hooks here.
 885   *
 886   * There is currently only one KSES WordPress hook, {@see 'pre_kses'}, and it is called here.
 887   * All parameters are passed to the hooks and expected to receive a string.
 888   *
 889   * @since 1.0.0
 890   *
 891   * @param string         $string            Content to filter through KSES.
 892   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 893   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 894   *                                          for the list of accepted context names.
 895   * @param string[]       $allowed_protocols Array of allowed URL protocols.
 896   * @return string Filtered content through {@see 'pre_kses'} hook.
 897   */
 898  function wp_kses_hook( $string, $allowed_html, $allowed_protocols ) {
 899      /**
 900       * Filters content to be run through KSES.
 901       *
 902       * @since 2.3.0
 903       *
 904       * @param string         $string            Content to filter through KSES.
 905       * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 906       *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 907       *                                          for the list of accepted context names.
 908       * @param string[]       $allowed_protocols Array of allowed URL protocols.
 909       */
 910      return apply_filters( 'pre_kses', $string, $allowed_html, $allowed_protocols );
 911  }
 912  
 913  /**
 914   * Returns the version number of KSES.
 915   *
 916   * @since 1.0.0
 917   *
 918   * @return string KSES version number.
 919   */
 920  function wp_kses_version() {
 921      return '0.2.2';
 922  }
 923  
 924  /**
 925   * Searches for HTML tags, no matter how malformed.
 926   *
 927   * It also matches stray `>` characters.
 928   *
 929   * @since 1.0.0
 930   *
 931   * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
 932   *                                                or a context name such as 'post'.
 933   * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
 934   *
 935   * @param string         $string            Content to filter.
 936   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 937   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 938   *                                          for the list of accepted context names.
 939   * @param string[]       $allowed_protocols Array of allowed URL protocols.
 940   * @return string Content with fixed HTML tags
 941   */
 942  function wp_kses_split( $string, $allowed_html, $allowed_protocols ) {
 943      global $pass_allowed_html, $pass_allowed_protocols;
 944  
 945      $pass_allowed_html      = $allowed_html;
 946      $pass_allowed_protocols = $allowed_protocols;
 947  
 948      return preg_replace_callback( '%(<!--.*?(-->|$))|(<[^>]*(>|$)|>)%', '_wp_kses_split_callback', $string );
 949  }
 950  
 951  /**
 952   * Returns an array of HTML attribute names whose value contains a URL.
 953   *
 954   * This function returns a list of all HTML attributes that must contain
 955   * a URL according to the HTML specification.
 956   *
 957   * This list includes URI attributes both allowed and disallowed by KSES.
 958   *
 959   * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
 960   *
 961   * @since 5.0.1
 962   *
 963   * @return string[] HTML attribute names whose value contains a URL.
 964   */
 965  function wp_kses_uri_attributes() {
 966      $uri_attributes = array(
 967          'action',
 968          'archive',
 969          'background',
 970          'cite',
 971          'classid',
 972          'codebase',
 973          'data',
 974          'formaction',
 975          'href',
 976          'icon',
 977          'longdesc',
 978          'manifest',
 979          'poster',
 980          'profile',
 981          'src',
 982          'usemap',
 983          'xmlns',
 984      );
 985  
 986      /**
 987       * Filters the list of attributes that are required to contain a URL.
 988       *
 989       * Use this filter to add any `data-` attributes that are required to be
 990       * validated as a URL.
 991       *
 992       * @since 5.0.1
 993       *
 994       * @param string[] $uri_attributes HTML attribute names whose value contains a URL.
 995       */
 996      $uri_attributes = apply_filters( 'wp_kses_uri_attributes', $uri_attributes );
 997  
 998      return $uri_attributes;
 999  }
1000  
1001  /**
1002   * Callback for `wp_kses_split()`.
1003   *
1004   * @since 3.1.0
1005   * @access private
1006   * @ignore
1007   *
1008   * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
1009   *                                                or a context name such as 'post'.
1010   * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
1011   *
1012   * @param array $match preg_replace regexp matches
1013   * @return string
1014   */
1015  function _wp_kses_split_callback( $match ) {
1016      global $pass_allowed_html, $pass_allowed_protocols;
1017  
1018      return wp_kses_split2( $match[0], $pass_allowed_html, $pass_allowed_protocols );
1019  }
1020  
1021  /**
1022   * Callback for `wp_kses_split()` for fixing malformed HTML tags.
1023   *
1024   * This function does a lot of work. It rejects some very malformed things like
1025   * `<:::>`. It returns an empty string, if the element isn't allowed (look ma, no
1026   * `strip_tags()`!). Otherwise it splits the tag into an element and an attribute
1027   * list.
1028   *
1029   * After the tag is split into an element and an attribute list, it is run
1030   * through another filter which will remove illegal attributes and once that is
1031   * completed, will be returned.
1032   *
1033   * @access private
1034   * @ignore
1035   * @since 1.0.0
1036   *
1037   * @param string         $string            Content to filter.
1038   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1039   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1040   *                                          for the list of accepted context names.
1041   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1042   * @return string Fixed HTML element
1043   */
1044  function wp_kses_split2( $string, $allowed_html, $allowed_protocols ) {
1045      $string = wp_kses_stripslashes( $string );
1046  
1047      // It matched a ">" character.
1048      if ( '<' !== substr( $string, 0, 1 ) ) {
1049          return '&gt;';
1050      }
1051  
1052      // Allow HTML comments.
1053      if ( '<!--' === substr( $string, 0, 4 ) ) {
1054          $string = str_replace( array( '<!--', '-->' ), '', $string );
1055          while ( ( $newstring = wp_kses( $string, $allowed_html, $allowed_protocols ) ) != $string ) {
1056              $string = $newstring;
1057          }
1058          if ( '' === $string ) {
1059              return '';
1060          }
1061          // Prevent multiple dashes in comments.
1062          $string = preg_replace( '/--+/', '-', $string );
1063          // Prevent three dashes closing a comment.
1064          $string = preg_replace( '/-$/', '', $string );
1065          return "<!--{$string}-->";
1066      }
1067  
1068      // It's seriously malformed.
1069      if ( ! preg_match( '%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $string, $matches ) ) {
1070          return '';
1071      }
1072  
1073      $slash    = trim( $matches[1] );
1074      $elem     = $matches[2];
1075      $attrlist = $matches[3];
1076  
1077      if ( ! is_array( $allowed_html ) ) {
1078          $allowed_html = wp_kses_allowed_html( $allowed_html );
1079      }
1080  
1081      // They are using a not allowed HTML element.
1082      if ( ! isset( $allowed_html[ strtolower( $elem ) ] ) ) {
1083          return '';
1084      }
1085  
1086      // No attributes are allowed for closing elements.
1087      if ( '' !== $slash ) {
1088          return "</$elem>";
1089      }
1090  
1091      return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
1092  }
1093  
1094  /**
1095   * Removes all attributes, if none are allowed for this element.
1096   *
1097   * If some are allowed it calls `wp_kses_hair()` to split them further, and then
1098   * it builds up new HTML code from the data that `wp_kses_hair()` returns. It also
1099   * removes `<` and `>` characters, if there are any left. One more thing it does
1100   * is to check if the tag has a closing XHTML slash, and if it does, it puts one
1101   * in the returned code as well.
1102   *
1103   * An array of allowed values can be defined for attributes. If the attribute value
1104   * doesn't fall into the list, the attribute will be removed from the tag.
1105   *
1106   * Attributes can be marked as required. If a required attribute is not present,
1107   * KSES will remove all attributes from the tag. As KSES doesn't match opening and
1108   * closing tags, it's not possible to safely remove the tag itself, the safest
1109   * fallback is to strip all attributes from the tag, instead.
1110   *
1111   * @since 1.0.0
1112   * @since 5.9.0 Added support for an array of allowed values for attributes.
1113   *              Added support for required attributes.
1114   *
1115   * @param string         $element           HTML element/tag.
1116   * @param string         $attr              HTML attributes from HTML element to closing HTML element tag.
1117   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1118   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1119   *                                          for the list of accepted context names.
1120   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1121   * @return string Sanitized HTML element.
1122   */
1123  function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) {
1124      if ( ! is_array( $allowed_html ) ) {
1125          $allowed_html = wp_kses_allowed_html( $allowed_html );
1126      }
1127  
1128      // Is there a closing XHTML slash at the end of the attributes?
1129      $xhtml_slash = '';
1130      if ( preg_match( '%\s*/\s*$%', $attr ) ) {
1131          $xhtml_slash = ' /';
1132      }
1133  
1134      // Are any attributes allowed at all for this element?
1135      $element_low = strtolower( $element );
1136      if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) {
1137          return "<$element$xhtml_slash>";
1138      }
1139  
1140      // Split it.
1141      $attrarr = wp_kses_hair( $attr, $allowed_protocols );
1142  
1143      // Check if there are attributes that are required.
1144      $required_attrs = array_filter(
1145          $allowed_html[ $element_low ],
1146          function( $required_attr_limits ) {
1147              return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required'];
1148          }
1149      );
1150  
1151      /*
1152       * If a required attribute check fails, we can return nothing for a self-closing tag,
1153       * but for a non-self-closing tag the best option is to return the element with attributes,
1154       * as KSES doesn't handle matching the relevant closing tag.
1155       */
1156      $stripped_tag = '';
1157      if ( empty( $xhtml_slash ) ) {
1158          $stripped_tag = "<$element>";
1159      }
1160  
1161      // Go through $attrarr, and save the allowed attributes for this element in $attr2.
1162      $attr2 = '';
1163      foreach ( $attrarr as $arreach ) {
1164          // Check if this attribute is required.
1165          $required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1166  
1167          if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
1168              $attr2 .= ' ' . $arreach['whole'];
1169  
1170              // If this was a required attribute, we can mark it as found.
1171              if ( $required ) {
1172                  unset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1173              }
1174          } elseif ( $required ) {
1175              // This attribute was required, but didn't pass the check. The entire tag is not allowed.
1176              return $stripped_tag;
1177          }
1178      }
1179  
1180      // If some required attributes weren't set, the entire tag is not allowed.
1181      if ( ! empty( $required_attrs ) ) {
1182          return $stripped_tag;
1183      }
1184  
1185      // Remove any "<" or ">" characters.
1186      $attr2 = preg_replace( '/[<>]/', '', $attr2 );
1187  
1188      return "<$element$attr2$xhtml_slash>";
1189  }
1190  
1191  /**
1192   * Determines whether an attribute is allowed.
1193   *
1194   * @since 4.2.3
1195   * @since 5.0.0 Added support for `data-*` wildcard attributes.
1196   *
1197   * @param string $name         The attribute name. Passed by reference. Returns empty string when not allowed.
1198   * @param string $value        The attribute value. Passed by reference. Returns a filtered value.
1199   * @param string $whole        The `name=value` input. Passed by reference. Returns filtered input.
1200   * @param string $vless        Whether the attribute is valueless. Use 'y' or 'n'.
1201   * @param string $element      The name of the element to which this attribute belongs.
1202   * @param array  $allowed_html The full list of allowed elements and attributes.
1203   * @return bool Whether or not the attribute is allowed.
1204   */
1205  function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
1206      $name_low    = strtolower( $name );
1207      $element_low = strtolower( $element );
1208  
1209      if ( ! isset( $allowed_html[ $element_low ] ) ) {
1210          $name  = '';
1211          $value = '';
1212          $whole = '';
1213          return false;
1214      }
1215  
1216      $allowed_attr = $allowed_html[ $element_low ];
1217  
1218      if ( ! isset( $allowed_attr[ $name_low ] ) || '' === $allowed_attr[ $name_low ] ) {
1219          /*
1220           * Allow `data-*` attributes.
1221           *
1222           * When specifying `$allowed_html`, the attribute name should be set as
1223           * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
1224           * https://www.w3.org/TR/html40/struct/objects.html#adef-data).
1225           *
1226           * Note: the attribute name should only contain `A-Za-z0-9_-` chars,
1227           * double hyphens `--` are not accepted by WordPress.
1228           */
1229          if ( strpos( $name_low, 'data-' ) === 0 && ! empty( $allowed_attr['data-*'] )
1230              && preg_match( '/^data(?:-[a-z0-9_]+)+$/', $name_low, $match )
1231          ) {
1232              /*
1233               * Add the whole attribute name to the allowed attributes and set any restrictions
1234               * for the `data-*` attribute values for the current element.
1235               */
1236              $allowed_attr[ $match[0] ] = $allowed_attr['data-*'];
1237          } else {
1238              $name  = '';
1239              $value = '';
1240              $whole = '';
1241              return false;
1242          }
1243      }
1244  
1245      if ( 'style' === $name_low ) {
1246          $new_value = safecss_filter_attr( $value );
1247  
1248          if ( empty( $new_value ) ) {
1249              $name  = '';
1250              $value = '';
1251              $whole = '';
1252              return false;
1253          }
1254  
1255          $whole = str_replace( $value, $new_value, $whole );
1256          $value = $new_value;
1257      }
1258  
1259      if ( is_array( $allowed_attr[ $name_low ] ) ) {
1260          // There are some checks.
1261          foreach ( $allowed_attr[ $name_low ] as $currkey => $currval ) {
1262              if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
1263                  $name  = '';
1264                  $value = '';
1265                  $whole = '';
1266                  return false;
1267              }
1268          }
1269      }
1270  
1271      return true;
1272  }
1273  
1274  /**
1275   * Builds an attribute list from string containing attributes.
1276   *
1277   * This function does a lot of work. It parses an attribute list into an array
1278   * with attribute data, and tries to do the right thing even if it gets weird
1279   * input. It will add quotes around attribute values that don't have any quotes
1280   * or apostrophes around them, to make it easier to produce HTML code that will
1281   * conform to W3C's HTML specification. It will also remove bad URL protocols
1282   * from attribute values. It also reduces duplicate attributes by using the
1283   * attribute defined first (`foo='bar' foo='baz'` will result in `foo='bar'`).
1284   *
1285   * @since 1.0.0
1286   *
1287   * @param string   $attr              Attribute list from HTML element to closing HTML element tag.
1288   * @param string[] $allowed_protocols Array of allowed URL protocols.
1289   * @return array[] Array of attribute information after parsing.
1290   */
1291  function wp_kses_hair( $attr, $allowed_protocols ) {
1292      $attrarr  = array();
1293      $mode     = 0;
1294      $attrname = '';
1295      $uris     = wp_kses_uri_attributes();
1296  
1297      // Loop through the whole attribute list.
1298  
1299      while ( strlen( $attr ) != 0 ) {
1300          $working = 0; // Was the last operation successful?
1301  
1302          switch ( $mode ) {
1303              case 0:
1304                  if ( preg_match( '/^([_a-zA-Z][-_a-zA-Z0-9:.]*)/', $attr, $match ) ) {
1305                      $attrname = $match[1];
1306                      $working  = 1;
1307                      $mode     = 1;
1308                      $attr     = preg_replace( '/^[_a-zA-Z][-_a-zA-Z0-9:.]*/', '', $attr );
1309                  }
1310  
1311                  break;
1312  
1313              case 1:
1314                  if ( preg_match( '/^\s*=\s*/', $attr ) ) { // Equals sign.
1315                      $working = 1;
1316                      $mode    = 2;
1317                      $attr    = preg_replace( '/^\s*=\s*/', '', $attr );
1318                      break;
1319                  }
1320  
1321                  if ( preg_match( '/^\s+/', $attr ) ) { // Valueless.
1322                      $working = 1;
1323                      $mode    = 0;
1324                      if ( false === array_key_exists( $attrname, $attrarr ) ) {
1325                          $attrarr[ $attrname ] = array(
1326                              'name'  => $attrname,
1327                              'value' => '',
1328                              'whole' => $attrname,
1329                              'vless' => 'y',
1330                          );
1331                      }
1332                      $attr = preg_replace( '/^\s+/', '', $attr );
1333                  }
1334  
1335                  break;
1336  
1337              case 2:
1338                  if ( preg_match( '%^"([^"]*)"(\s+|/?$)%', $attr, $match ) ) {
1339                      // "value"
1340                      $thisval = $match[1];
1341                      if ( in_array( strtolower( $attrname ), $uris, true ) ) {
1342                          $thisval = wp_kses_bad_protocol( $thisval, $allowed_protocols );
1343                      }
1344  
1345                      if ( false === array_key_exists( $attrname, $attrarr ) ) {
1346                          $attrarr[ $attrname ] = array(
1347                              'name'  => $attrname,
1348                              'value' => $thisval,
1349                              'whole' => "$attrname=\"$thisval\"",
1350                              'vless' => 'n',
1351                          );
1352                      }
1353                      $working = 1;
1354                      $mode    = 0;
1355                      $attr    = preg_replace( '/^"[^"]*"(\s+|$)/', '', $attr );
1356                      break;
1357                  }
1358  
1359                  if ( preg_match( "%^'([^']*)'(\s+|/?$)%", $attr, $match ) ) {
1360                      // 'value'
1361                      $thisval = $match[1];
1362                      if ( in_array( strtolower( $attrname ), $uris, true ) ) {
1363                          $thisval = wp_kses_bad_protocol( $thisval, $allowed_protocols );
1364                      }
1365  
1366                      if ( false === array_key_exists( $attrname, $attrarr ) ) {
1367                          $attrarr[ $attrname ] = array(
1368                              'name'  => $attrname,
1369                              'value' => $thisval,
1370                              'whole' => "$attrname='$thisval'",
1371                              'vless' => 'n',
1372                          );
1373                      }
1374                      $working = 1;
1375                      $mode    = 0;
1376                      $attr    = preg_replace( "/^'[^']*'(\s+|$)/", '', $attr );
1377                      break;
1378                  }
1379  
1380                  if ( preg_match( "%^([^\s\"']+)(\s+|/?$)%", $attr, $match ) ) {
1381                      // value
1382                      $thisval = $match[1];
1383                      if ( in_array( strtolower( $attrname ), $uris, true ) ) {
1384                          $thisval = wp_kses_bad_protocol( $thisval, $allowed_protocols );
1385                      }
1386  
1387                      if ( false === array_key_exists( $attrname, $attrarr ) ) {
1388                          $attrarr[ $attrname ] = array(
1389                              'name'  => $attrname,
1390                              'value' => $thisval,
1391                              'whole' => "$attrname=\"$thisval\"",
1392                              'vless' => 'n',
1393                          );
1394                      }
1395                      // We add quotes to conform to W3C's HTML spec.
1396                      $working = 1;
1397                      $mode    = 0;
1398                      $attr    = preg_replace( "%^[^\s\"']+(\s+|$)%", '', $attr );
1399                  }
1400  
1401                  break;
1402          } // End switch.
1403  
1404          if ( 0 == $working ) { // Not well-formed, remove and try again.
1405              $attr = wp_kses_html_error( $attr );
1406              $mode = 0;
1407          }
1408      } // End while.
1409  
1410      if ( 1 == $mode && false === array_key_exists( $attrname, $attrarr ) ) {
1411          // Special case, for when the attribute list ends with a valueless
1412          // attribute like "selected".
1413          $attrarr[ $attrname ] = array(
1414              'name'  => $attrname,
1415              'value' => '',
1416              'whole' => $attrname,
1417              'vless' => 'y',
1418          );
1419      }
1420  
1421      return $attrarr;
1422  }
1423  
1424  /**
1425   * Finds all attributes of an HTML element.
1426   *
1427   * Does not modify input.  May return "evil" output.
1428   *
1429   * Based on `wp_kses_split2()` and `wp_kses_attr()`.
1430   *
1431   * @since 4.2.3
1432   *
1433   * @param string $element HTML element.
1434   * @return array|false List of attributes found in the element. Returns false on failure.
1435   */
1436  function wp_kses_attr_parse( $element ) {
1437      $valid = preg_match( '%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches );
1438      if ( 1 !== $valid ) {
1439          return false;
1440      }
1441  
1442      $begin  = $matches[1];
1443      $slash  = $matches[2];
1444      $elname = $matches[3];
1445      $attr   = $matches[4];
1446      $end    = $matches[5];
1447  
1448      if ( '' !== $slash ) {
1449          // Closing elements do not get parsed.
1450          return false;
1451      }
1452  
1453      // Is there a closing XHTML slash at the end of the attributes?
1454      if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
1455          $xhtml_slash = $matches[0];
1456          $attr        = substr( $attr, 0, -strlen( $xhtml_slash ) );
1457      } else {
1458          $xhtml_slash = '';
1459      }
1460  
1461      // Split it.
1462      $attrarr = wp_kses_hair_parse( $attr );
1463      if ( false === $attrarr ) {
1464          return false;
1465      }
1466  
1467      // Make sure all input is returned by adding front and back matter.
1468      array_unshift( $attrarr, $begin . $slash . $elname );
1469      array_push( $attrarr, $xhtml_slash . $end );
1470  
1471      return $attrarr;
1472  }
1473  
1474  /**
1475   * Builds an attribute list from string containing attributes.
1476   *
1477   * Does not modify input.  May return "evil" output.
1478   * In case of unexpected input, returns false instead of stripping things.
1479   *
1480   * Based on `wp_kses_hair()` but does not return a multi-dimensional array.
1481   *
1482   * @since 4.2.3
1483   *
1484   * @param string $attr Attribute list from HTML element to closing HTML element tag.
1485   * @return array|false List of attributes found in $attr. Returns false on failure.
1486   */
1487  function wp_kses_hair_parse( $attr ) {
1488      if ( '' === $attr ) {
1489          return array();
1490      }
1491  
1492      // phpcs:disable Squiz.Strings.ConcatenationSpacing.PaddingFound -- don't remove regex indentation
1493      $regex =
1494          '(?:'
1495          .     '[_a-zA-Z][-_a-zA-Z0-9:.]*' // Attribute name.
1496          . '|'
1497          .     '\[\[?[^\[\]]+\]\]?'        // Shortcode in the name position implies unfiltered_html.
1498          . ')'
1499          . '(?:'               // Attribute value.
1500          .     '\s*=\s*'       // All values begin with '='.
1501          .     '(?:'
1502          .         '"[^"]*"'   // Double-quoted.
1503          .     '|'
1504          .         "'[^']*'"   // Single-quoted.
1505          .     '|'
1506          .         '[^\s"\']+' // Non-quoted.
1507          .         '(?:\s|$)'  // Must have a space.
1508          .     ')'
1509          . '|'
1510          .     '(?:\s|$)'      // If attribute has no value, space is required.
1511          . ')'
1512          . '\s*';              // Trailing space is optional except as mentioned above.
1513      // phpcs:enable
1514  
1515      // Although it is possible to reduce this procedure to a single regexp,
1516      // we must run that regexp twice to get exactly the expected result.
1517  
1518      $validation = "%^($regex)+$%";
1519      $extraction = "%$regex%";
1520  
1521      if ( 1 === preg_match( $validation, $attr ) ) {
1522          preg_match_all( $extraction, $attr, $attrarr );
1523          return $attrarr[0];
1524      } else {
1525          return false;
1526      }
1527  }
1528  
1529  /**
1530   * Performs different checks for attribute values.
1531   *
1532   * The currently implemented checks are "maxlen", "minlen", "maxval", "minval",
1533   * and "valueless".
1534   *
1535   * @since 1.0.0
1536   *
1537   * @param string $value      Attribute value.
1538   * @param string $vless      Whether the attribute is valueless. Use 'y' or 'n'.
1539   * @param string $checkname  What $checkvalue is checking for.
1540   * @param mixed  $checkvalue What constraint the value should pass.
1541   * @return bool Whether check passes.
1542   */
1543  function wp_kses_check_attr_val( $value, $vless, $checkname, $checkvalue ) {
1544      $ok = true;
1545  
1546      switch ( strtolower( $checkname ) ) {
1547          case 'maxlen':
1548              /*
1549               * The maxlen check makes sure that the attribute value has a length not
1550               * greater than the given value. This can be used to avoid Buffer Overflows
1551               * in WWW clients and various Internet servers.
1552               */
1553  
1554              if ( strlen( $value ) > $checkvalue ) {
1555                  $ok = false;
1556              }
1557              break;
1558  
1559          case 'minlen':
1560              /*
1561               * The minlen check makes sure that the attribute value has a length not
1562               * smaller than the given value.
1563               */
1564  
1565              if ( strlen( $value ) < $checkvalue ) {
1566                  $ok = false;
1567              }
1568              break;
1569  
1570          case 'maxval':
1571              /*
1572               * The maxval check does two things: it checks that the attribute value is
1573               * an integer from 0 and up, without an excessive amount of zeroes or
1574               * whitespace (to avoid Buffer Overflows). It also checks that the attribute
1575               * value is not greater than the given value.
1576               * This check can be used to avoid Denial of Service attacks.
1577               */
1578  
1579              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1580                  $ok = false;
1581              }
1582              if ( $value > $checkvalue ) {
1583                  $ok = false;
1584              }
1585              break;
1586  
1587          case 'minval':
1588              /*
1589               * The minval check makes sure that the attribute value is a positive integer,
1590               * and that it is not smaller than the given value.
1591               */
1592  
1593              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1594                  $ok = false;
1595              }
1596              if ( $value < $checkvalue ) {
1597                  $ok = false;
1598              }
1599              break;
1600  
1601          case 'valueless':
1602              /*
1603               * The valueless check makes sure if the attribute has a value
1604               * (like `<a href="blah">`) or not (`<option selected>`). If the given value
1605               * is a "y" or a "Y", the attribute must not have a value.
1606               * If the given value is an "n" or an "N", the attribute must have a value.
1607               */
1608  
1609              if ( strtolower( $checkvalue ) != $vless ) {
1610                  $ok = false;
1611              }
1612              break;
1613  
1614          case 'values':
1615              /*
1616               * The values check is used when you want to make sure that the attribute
1617               * has one of the given values.
1618               */
1619  
1620              if ( false === array_search( strtolower( $value ), $checkvalue, true ) ) {
1621                  $ok = false;
1622              }
1623              break;
1624  
1625          case 'value_callback':
1626              /*
1627               * The value_callback check is used when you want to make sure that the attribute
1628               * value is accepted by the callback function.
1629               */
1630  
1631              if ( ! call_user_func( $checkvalue, $value ) ) {
1632                  $ok = false;
1633              }
1634              break;
1635      } // End switch.
1636  
1637      return $ok;
1638  }
1639  
1640  /**
1641   * Sanitizes a string and removed disallowed URL protocols.
1642   *
1643   * This function removes all non-allowed protocols from the beginning of the
1644   * string. It ignores whitespace and the case of the letters, and it does
1645   * understand HTML entities. It does its work recursively, so it won't be
1646   * fooled by a string like `javascript:javascript:alert(57)`.
1647   *
1648   * @since 1.0.0
1649   *
1650   * @param string   $string            Content to filter bad protocols from.
1651   * @param string[] $allowed_protocols Array of allowed URL protocols.
1652   * @return string Filtered content.
1653   */
1654  function wp_kses_bad_protocol( $string, $allowed_protocols ) {
1655      $string     = wp_kses_no_null( $string );
1656      $iterations = 0;
1657  
1658      do {
1659          $original_string = $string;
1660          $string          = wp_kses_bad_protocol_once( $string, $allowed_protocols );
1661      } while ( $original_string != $string && ++$iterations < 6 );
1662  
1663      if ( $original_string != $string ) {
1664          return '';
1665      }
1666  
1667      return $string;
1668  }
1669  
1670  /**
1671   * Removes any invalid control characters in a text string.
1672   *
1673   * Also removes any instance of the `\0` string.
1674   *
1675   * @since 1.0.0
1676   *
1677   * @param string $string  Content to filter null characters from.
1678   * @param array  $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
1679   * @return string Filtered content.
1680   */
1681  function wp_kses_no_null( $string, $options = null ) {
1682      if ( ! isset( $options['slash_zero'] ) ) {
1683          $options = array( 'slash_zero' => 'remove' );
1684      }
1685  
1686      $string = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $string );
1687      if ( 'remove' === $options['slash_zero'] ) {
1688          $string = preg_replace( '/\\\\+0+/', '', $string );
1689      }
1690  
1691      return $string;
1692  }
1693  
1694  /**
1695   * Strips slashes from in front of quotes.
1696   *
1697   * This function changes the character sequence `\"` to just `"`. It leaves all other
1698   * slashes alone. The quoting from `preg_replace(//e)` requires this.
1699   *
1700   * @since 1.0.0
1701   *
1702   * @param string $string String to strip slashes from.
1703   * @return string Fixed string with quoted slashes.
1704   */
1705  function wp_kses_stripslashes( $string ) {
1706      return preg_replace( '%\\\\"%', '"', $string );
1707  }
1708  
1709  /**
1710   * Converts the keys of an array to lowercase.
1711   *
1712   * @since 1.0.0
1713   *
1714   * @param array $inarray Unfiltered array.
1715   * @return array Fixed array with all lowercase keys.
1716   */
1717  function wp_kses_array_lc( $inarray ) {
1718      $outarray = array();
1719  
1720      foreach ( (array) $inarray as $inkey => $inval ) {
1721          $outkey              = strtolower( $inkey );
1722          $outarray[ $outkey ] = array();
1723  
1724          foreach ( (array) $inval as $inkey2 => $inval2 ) {
1725              $outkey2                         = strtolower( $inkey2 );
1726              $outarray[ $outkey ][ $outkey2 ] = $inval2;
1727          }
1728      }
1729  
1730      return $outarray;
1731  }
1732  
1733  /**
1734   * Handles parsing errors in `wp_kses_hair()`.
1735   *
1736   * The general plan is to remove everything to and including some whitespace,
1737   * but it deals with quotes and apostrophes as well.
1738   *
1739   * @since 1.0.0
1740   *
1741   * @param string $string
1742   * @return string
1743   */
1744  function wp_kses_html_error( $string ) {
1745      return preg_replace( '/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $string );
1746  }
1747  
1748  /**
1749   * Sanitizes content from bad protocols and other characters.
1750   *
1751   * This function searches for URL protocols at the beginning of the string, while
1752   * handling whitespace and HTML entities.
1753   *
1754   * @since 1.0.0
1755   *
1756   * @param string   $string            Content to check for bad protocols.
1757   * @param string[] $allowed_protocols Array of allowed URL protocols.
1758   * @param int      $count             Depth of call recursion to this function.
1759   * @return string Sanitized content.
1760   */
1761  function wp_kses_bad_protocol_once( $string, $allowed_protocols, $count = 1 ) {
1762      $string  = preg_replace( '/(&#0*58(?![;0-9])|&#x0*3a(?![;a-f0-9]))/i', '$1;', $string );
1763      $string2 = preg_split( '/:|&#0*58;|&#x0*3a;|&colon;/i', $string, 2 );
1764      if ( isset( $string2[1] ) && ! preg_match( '%/\?%', $string2[0] ) ) {
1765          $string   = trim( $string2[1] );
1766          $protocol = wp_kses_bad_protocol_once2( $string2[0], $allowed_protocols );
1767          if ( 'feed:' === $protocol ) {
1768              if ( $count > 2 ) {
1769                  return '';
1770              }
1771              $string = wp_kses_bad_protocol_once( $string, $allowed_protocols, ++$count );
1772              if ( empty( $string ) ) {
1773                  return $string;
1774              }
1775          }
1776          $string = $protocol . $string;
1777      }
1778  
1779      return $string;
1780  }
1781  
1782  /**
1783   * Callback for `wp_kses_bad_protocol_once()` regular expression.
1784   *
1785   * This function processes URL protocols, checks to see if they're in the
1786   * list of allowed protocols or not, and returns different data depending
1787   * on the answer.
1788   *
1789   * @access private
1790   * @ignore
1791   * @since 1.0.0
1792   *
1793   * @param string   $string            URI scheme to check against the list of allowed protocols.
1794   * @param string[] $allowed_protocols Array of allowed URL protocols.
1795   * @return string Sanitized content.
1796   */
1797  function wp_kses_bad_protocol_once2( $string, $allowed_protocols ) {
1798      $string2 = wp_kses_decode_entities( $string );
1799      $string2 = preg_replace( '/\s/', '', $string2 );
1800      $string2 = wp_kses_no_null( $string2 );
1801      $string2 = strtolower( $string2 );
1802  
1803      $allowed = false;
1804      foreach ( (array) $allowed_protocols as $one_protocol ) {
1805          if ( strtolower( $one_protocol ) == $string2 ) {
1806              $allowed = true;
1807              break;
1808          }
1809      }
1810  
1811      if ( $allowed ) {
1812          return "$string2:";
1813      } else {
1814          return '';
1815      }
1816  }
1817  
1818  /**
1819   * Converts and fixes HTML entities.
1820   *
1821   * This function normalizes HTML entities. It will convert `AT&T` to the correct
1822   * `AT&amp;T`, `&#00058;` to `&#058;`, `&#XYZZY;` to `&amp;#XYZZY;` and so on.
1823   *
1824   * When `$context` is set to 'xml', HTML entities are converted to their code points.  For
1825   * example, `AT&T&hellip;&#XYZZY;` is converted to `AT&amp;T…&amp;#XYZZY;`.
1826   *
1827   * @since 1.0.0
1828   * @since 5.5.0 Added `$context` parameter.
1829   *
1830   * @param string $string  Content to normalize entities.
1831   * @param string $context Context for normalization. Can be either 'html' or 'xml'.
1832   *                        Default 'html'.
1833   * @return string Content with normalized entities.
1834   */
1835  function wp_kses_normalize_entities( $string, $context = 'html' ) {
1836      // Disarm all entities by converting & to &amp;
1837      $string = str_replace( '&', '&amp;', $string );
1838  
1839      // Change back the allowed entities in our list of allowed entities.
1840      if ( 'xml' === $context ) {
1841          $string = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $string );
1842      } else {
1843          $string = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $string );
1844      }
1845      $string = preg_replace_callback( '/&amp;#(0*[0-9]{1,7});/', 'wp_kses_normalize_entities2', $string );
1846      $string = preg_replace_callback( '/&amp;#[Xx](0*[0-9A-Fa-f]{1,6});/', 'wp_kses_normalize_entities3', $string );
1847  
1848      return $string;
1849  }
1850  
1851  /**
1852   * Callback for `wp_kses_normalize_entities()` regular expression.
1853   *
1854   * This function only accepts valid named entity references, which are finite,
1855   * case-sensitive, and highly scrutinized by HTML and XML validators.
1856   *
1857   * @since 3.0.0
1858   *
1859   * @global array $allowedentitynames
1860   *
1861   * @param array $matches preg_replace_callback() matches array.
1862   * @return string Correctly encoded entity.
1863   */
1864  function wp_kses_named_entities( $matches ) {
1865      global $allowedentitynames;
1866  
1867      if ( empty( $matches[1] ) ) {
1868          return '';
1869      }
1870  
1871      $i = $matches[1];
1872      return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&amp;$i;" : "&$i;";
1873  }
1874  
1875  /**
1876   * Callback for `wp_kses_normalize_entities()` regular expression.
1877   *
1878   * This function only accepts valid named entity references, which are finite,
1879   * case-sensitive, and highly scrutinized by XML validators.  HTML named entity
1880   * references are converted to their code points.
1881   *
1882   * @since 5.5.0
1883   *
1884   * @global array $allowedentitynames
1885   * @global array $allowedxmlentitynames
1886   *
1887   * @param array $matches preg_replace_callback() matches array.
1888   * @return string Correctly encoded entity.
1889   */
1890  function wp_kses_xml_named_entities( $matches ) {
1891      global $allowedentitynames, $allowedxmlentitynames;
1892  
1893      if ( empty( $matches[1] ) ) {
1894          return '';
1895      }
1896  
1897      $i = $matches[1];
1898  
1899      if ( in_array( $i, $allowedxmlentitynames, true ) ) {
1900          return "&$i;";
1901      } elseif ( in_array( $i, $allowedentitynames, true ) ) {
1902          return html_entity_decode( "&$i;", ENT_HTML5 );
1903      }
1904  
1905      return "&amp;$i;";
1906  }
1907  
1908  /**
1909   * Callback for `wp_kses_normalize_entities()` regular expression.
1910   *
1911   * This function helps `wp_kses_normalize_entities()` to only accept 16-bit
1912   * values and nothing more for `&#number;` entities.
1913   *
1914   * @access private
1915   * @ignore
1916   * @since 1.0.0
1917   *
1918   * @param array $matches `preg_replace_callback()` matches array.
1919   * @return string Correctly encoded entity.
1920   */
1921  function wp_kses_normalize_entities2( $matches ) {
1922      if ( empty( $matches[1] ) ) {
1923          return '';
1924      }
1925  
1926      $i = $matches[1];
1927      if ( valid_unicode( $i ) ) {
1928          $i = str_pad( ltrim( $i, '0' ), 3, '0', STR_PAD_LEFT );
1929          $i = "&#$i;";
1930      } else {
1931          $i = "&amp;#$i;";
1932      }
1933  
1934      return $i;
1935  }
1936  
1937  /**
1938   * Callback for `wp_kses_normalize_entities()` for regular expression.
1939   *
1940   * This function helps `wp_kses_normalize_entities()` to only accept valid Unicode
1941   * numeric entities in hex form.
1942   *
1943   * @since 2.7.0
1944   * @access private
1945   * @ignore
1946   *
1947   * @param array $matches `preg_replace_callback()` matches array.
1948   * @return string Correctly encoded entity.
1949   */
1950  function wp_kses_normalize_entities3( $matches ) {
1951      if ( empty( $matches[1] ) ) {
1952          return '';
1953      }
1954  
1955      $hexchars = $matches[1];
1956      return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&amp;#x$hexchars;" : '&#x' . ltrim( $hexchars, '0' ) . ';';
1957  }
1958  
1959  /**
1960   * Determines if a Unicode codepoint is valid.
1961   *
1962   * @since 2.7.0
1963   *
1964   * @param int $i Unicode codepoint.
1965   * @return bool Whether or not the codepoint is a valid Unicode codepoint.
1966   */
1967  function valid_unicode( $i ) {
1968      return ( 0x9 == $i || 0xa == $i || 0xd == $i ||
1969              ( 0x20 <= $i && $i <= 0xd7ff ) ||
1970              ( 0xe000 <= $i && $i <= 0xfffd ) ||
1971              ( 0x10000 <= $i && $i <= 0x10ffff ) );
1972  }
1973  
1974  /**
1975   * Converts all numeric HTML entities to their named counterparts.
1976   *
1977   * This function decodes numeric HTML entities (`&#65;` and `&#x41;`).
1978   * It doesn't do anything with named entities like `&auml;`, but we don't
1979   * need them in the allowed URL protocols system anyway.
1980   *
1981   * @since 1.0.0
1982   *
1983   * @param string $string Content to change entities.
1984   * @return string Content after decoded entities.
1985   */
1986  function wp_kses_decode_entities( $string ) {
1987      $string = preg_replace_callback( '/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $string );
1988      $string = preg_replace_callback( '/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $string );
1989  
1990      return $string;
1991  }
1992  
1993  /**
1994   * Regex callback for `wp_kses_decode_entities()`.
1995   *
1996   * @since 2.9.0
1997   * @access private
1998   * @ignore
1999   *
2000   * @param array $match preg match
2001   * @return string
2002   */
2003  function _wp_kses_decode_entities_chr( $match ) {
2004      return chr( $match[1] );
2005  }
2006  
2007  /**
2008   * Regex callback for `wp_kses_decode_entities()`.
2009   *
2010   * @since 2.9.0
2011   * @access private
2012   * @ignore
2013   *
2014   * @param array $match preg match
2015   * @return string
2016   */
2017  function _wp_kses_decode_entities_chr_hexdec( $match ) {
2018      return chr( hexdec( $match[1] ) );
2019  }
2020  
2021  /**
2022   * Sanitize content with allowed HTML KSES rules.
2023   *
2024   * This function expects slashed data.
2025   *
2026   * @since 1.0.0
2027   *
2028   * @param string $data Content to filter, expected to be escaped with slashes.
2029   * @return string Filtered content.
2030   */
2031  function wp_filter_kses( $data ) {
2032      return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
2033  }
2034  
2035  /**
2036   * Sanitize content with allowed HTML KSES rules.
2037   *
2038   * This function expects unslashed data.
2039   *
2040   * @since 2.9.0
2041   *
2042   * @param string $data Content to filter, expected to not be escaped.
2043   * @return string Filtered content.
2044   */
2045  function wp_kses_data( $data ) {
2046      return wp_kses( $data, current_filter() );
2047  }
2048  
2049  /**
2050   * Sanitizes content for allowed HTML tags for post content.
2051   *
2052   * Post content refers to the page contents of the 'post' type and not `$_POST`
2053   * data from forms.
2054   *
2055   * This function expects slashed data.
2056   *
2057   * @since 2.0.0
2058   *
2059   * @param string $data Post content to filter, expected to be escaped with slashes.
2060   * @return string Filtered post content with allowed HTML tags and attributes intact.
2061   */
2062  function wp_filter_post_kses( $data ) {
2063      return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
2064  }
2065  
2066  /**
2067   * Sanitizes global styles user content removing unsafe rules.
2068   *
2069   * @since 5.9.0
2070   *
2071   * @param string $data Post content to filter.
2072   * @return string Filtered post content with unsafe rules removed.
2073   */
2074  function wp_filter_global_styles_post( $data ) {
2075      $decoded_data        = json_decode( wp_unslash( $data ), true );
2076      $json_decoding_error = json_last_error();
2077      if (
2078          JSON_ERROR_NONE === $json_decoding_error &&
2079          is_array( $decoded_data ) &&
2080          isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) &&
2081          $decoded_data['isGlobalStylesUserThemeJSON']
2082      ) {
2083          unset( $decoded_data['isGlobalStylesUserThemeJSON'] );
2084  
2085          $data_to_encode = WP_Theme_JSON::remove_insecure_properties( $decoded_data );
2086  
2087          $data_to_encode['isGlobalStylesUserThemeJSON'] = true;
2088          return wp_slash( wp_json_encode( $data_to_encode ) );
2089      }
2090      return $data;
2091  }
2092  
2093  /**
2094   * Sanitizes content for allowed HTML tags for post content.
2095   *
2096   * Post content refers to the page contents of the 'post' type and not `$_POST`
2097   * data from forms.
2098   *
2099   * This function expects unslashed data.
2100   *
2101   * @since 2.9.0
2102   *
2103   * @param string $data Post content to filter.
2104   * @return string Filtered post content with allowed HTML tags and attributes intact.
2105   */
2106  function wp_kses_post( $data ) {
2107      return wp_kses( $data, 'post' );
2108  }
2109  
2110  /**
2111   * Navigates through an array, object, or scalar, and sanitizes content for
2112   * allowed HTML tags for post content.
2113   *
2114   * @since 4.4.2
2115   *
2116   * @see map_deep()
2117   *
2118   * @param mixed $data The array, object, or scalar value to inspect.
2119   * @return mixed The filtered content.
2120   */
2121  function wp_kses_post_deep( $data ) {
2122      return map_deep( $data, 'wp_kses_post' );
2123  }
2124  
2125  /**
2126   * Strips all HTML from a text string.
2127   *
2128   * This function expects slashed data.
2129   *
2130   * @since 2.1.0
2131   *
2132   * @param string $data Content to strip all HTML from.
2133   * @return string Filtered content without any HTML.
2134   */
2135  function wp_filter_nohtml_kses( $data ) {
2136      return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
2137  }
2138  
2139  /**
2140   * Adds all KSES input form content filters.
2141   *
2142   * All hooks have default priority. The `wp_filter_kses()` function is added to
2143   * the 'pre_comment_content' and 'title_save_pre' hooks.
2144   *
2145   * The `wp_filter_post_kses()` function is added to the 'content_save_pre',
2146   * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
2147   *
2148   * @since 2.0.0
2149   */
2150  function kses_init_filters() {
2151      // Normal filtering.
2152      add_filter( 'title_save_pre', 'wp_filter_kses' );
2153  
2154      // Comment filtering.
2155      if ( current_user_can( 'unfiltered_html' ) ) {
2156          add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2157      } else {
2158          add_filter( 'pre_comment_content', 'wp_filter_kses' );
2159      }
2160  
2161      // Global Styles filtering: Global Styles filters should be executed before normal post_kses HTML filters.
2162      add_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2163      add_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2164  
2165      // Post filtering.
2166      add_filter( 'content_save_pre', 'wp_filter_post_kses' );
2167      add_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2168      add_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2169  }
2170  
2171  /**
2172   * Removes all KSES input form content filters.
2173   *
2174   * A quick procedural method to removing all of the filters that KSES uses for
2175   * content in WordPress Loop.
2176   *
2177   * Does not remove the `kses_init()` function from {@see 'init'} hook (priority is
2178   * default). Also does not remove `kses_init()` function from {@see 'set_current_user'}
2179   * hook (priority is also default).
2180   *
2181   * @since 2.0.6
2182   */
2183  function kses_remove_filters() {
2184      // Normal filtering.
2185      remove_filter( 'title_save_pre', 'wp_filter_kses' );
2186  
2187      // Comment filtering.
2188      remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2189      remove_filter( 'pre_comment_content', 'wp_filter_kses' );
2190  
2191      // Global Styles filtering.
2192      remove_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2193      remove_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2194  
2195      // Post filtering.
2196      remove_filter( 'content_save_pre', 'wp_filter_post_kses' );
2197      remove_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2198      remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2199  }
2200  
2201  /**
2202   * Sets up most of the KSES filters for input form content.
2203   *
2204   * First removes all of the KSES filters in case the current user does not need
2205   * to have KSES filter the content. If the user does not have `unfiltered_html`
2206   * capability, then KSES filters are added.
2207   *
2208   * @since 2.0.0
2209   */
2210  function kses_init() {
2211      kses_remove_filters();
2212  
2213      if ( ! current_user_can( 'unfiltered_html' ) ) {
2214          kses_init_filters();
2215      }
2216  }
2217  
2218  /**
2219   * Filters an inline style attribute and removes disallowed rules.
2220   *
2221   * @since 2.8.1
2222   * @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
2223   * @since 4.6.0 Added support for `list-style-type`.
2224   * @since 5.0.0 Added support for `background-image`.
2225   * @since 5.1.0 Added support for `text-transform`.
2226   * @since 5.2.0 Added support for `background-position` and `grid-template-columns`.
2227   * @since 5.3.0 Added support for `grid`, `flex` and `column` layout properties.
2228   *              Extended `background-*` support for individual properties.
2229   * @since 5.3.1 Added support for gradient backgrounds.
2230   * @since 5.7.1 Added support for `object-position`.
2231   * @since 5.8.0 Added support for `calc()` and `var()` values.
2232   * @since 6.1.0 Added support for `min()`, `max()`, `minmax()`, `clamp()`,
2233   *              nested `var()` values, and assigning values to CSS variables.
2234   *              Added support for `gap`, `column-gap`, `row-gap`, and `flex-wrap`.
2235   *              Extended `margin-*` and `padding-*` support for logical properties.
2236   *
2237   * @param string $css        A string of CSS rules.
2238   * @param string $deprecated Not used.
2239   * @return string Filtered string of CSS rules.
2240   */
2241  function safecss_filter_attr( $css, $deprecated = '' ) {
2242      if ( ! empty( $deprecated ) ) {
2243          _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented.
2244      }
2245  
2246      $css = wp_kses_no_null( $css );
2247      $css = str_replace( array( "\n", "\r", "\t" ), '', $css );
2248  
2249      $allowed_protocols = wp_allowed_protocols();
2250  
2251      $css_array = explode( ';', trim( $css ) );
2252  
2253      /**
2254       * Filters the list of allowed CSS attributes.
2255       *
2256       * @since 2.8.1
2257       *
2258       * @param string[] $attr Array of allowed CSS attributes.
2259       */
2260      $allowed_attr = apply_filters(
2261          'safe_style_css',
2262          array(
2263              'background',
2264              'background-color',
2265              'background-image',
2266              'background-position',
2267              'background-size',
2268              'background-attachment',
2269              'background-blend-mode',
2270  
2271              'border',
2272              'border-radius',
2273              'border-width',
2274              'border-color',
2275              'border-style',
2276              'border-right',
2277              'border-right-color',
2278              'border-right-style',
2279              'border-right-width',
2280              'border-bottom',
2281              'border-bottom-color',
2282              'border-bottom-left-radius',
2283              'border-bottom-right-radius',
2284              'border-bottom-style',
2285              'border-bottom-width',
2286              'border-bottom-right-radius',
2287              'border-bottom-left-radius',
2288              'border-left',
2289              'border-left-color',
2290              'border-left-style',
2291              'border-left-width',
2292              'border-top',
2293              'border-top-color',
2294              'border-top-left-radius',
2295              'border-top-right-radius',
2296              'border-top-style',
2297              'border-top-width',
2298              'border-top-left-radius',
2299              'border-top-right-radius',
2300  
2301              'border-spacing',
2302              'border-collapse',
2303              'caption-side',
2304  
2305              'columns',
2306              'column-count',
2307              'column-fill',
2308              'column-gap',
2309              'column-rule',
2310              'column-span',
2311              'column-width',
2312  
2313              'color',
2314              'filter',
2315              'font',
2316              'font-family',
2317              'font-size',
2318              'font-style',
2319              'font-variant',
2320              'font-weight',
2321              'letter-spacing',
2322              'line-height',
2323              'text-align',
2324              'text-decoration',
2325              'text-indent',
2326              'text-transform',
2327  
2328              'height',
2329              'min-height',
2330              'max-height',
2331  
2332              'width',
2333              'min-width',
2334              'max-width',
2335  
2336              'margin',
2337              'margin-right',
2338              'margin-bottom',
2339              'margin-left',
2340              'margin-top',
2341              'margin-block-start',
2342              'margin-block-end',
2343              'margin-inline-start',
2344              'margin-inline-end',
2345  
2346              'padding',
2347              'padding-right',
2348              'padding-bottom',
2349              'padding-left',
2350              'padding-top',
2351              'padding-block-start',
2352              'padding-block-end',
2353              'padding-inline-start',
2354              'padding-inline-end',
2355  
2356              'flex',
2357              'flex-basis',
2358              'flex-direction',
2359              'flex-flow',
2360              'flex-grow',
2361              'flex-shrink',
2362              'flex-wrap',
2363  
2364              'gap',
2365              'column-gap',
2366              'row-gap',
2367  
2368              'grid-template-columns',
2369              'grid-auto-columns',
2370              'grid-column-start',
2371              'grid-column-end',
2372              'grid-column-gap',
2373              'grid-template-rows',
2374              'grid-auto-rows',
2375              'grid-row-start',
2376              'grid-row-end',
2377              'grid-row-gap',
2378              'grid-gap',
2379  
2380              'justify-content',
2381              'justify-items',
2382              'justify-self',
2383              'align-content',
2384              'align-items',
2385              'align-self',
2386  
2387              'clear',
2388              'cursor',
2389              'direction',
2390              'float',
2391              'list-style-type',
2392              'object-position',
2393              'overflow',
2394              'vertical-align',
2395  
2396              // Custom CSS properties.
2397              '--*',
2398          )
2399      );
2400  
2401      /*
2402       * CSS attributes that accept URL data types.
2403       *
2404       * This is in accordance to the CSS spec and unrelated to
2405       * the sub-set of supported attributes above.
2406       *
2407       * See: https://developer.mozilla.org/en-US/docs/Web/CSS/url
2408       */
2409      $css_url_data_types = array(
2410          'background',
2411          'background-image',
2412  
2413          'cursor',
2414  
2415          'list-style',
2416          'list-style-image',
2417      );
2418  
2419      /*
2420       * CSS attributes that accept gradient data types.
2421       *
2422       */
2423      $css_gradient_data_types = array(
2424          'background',
2425          'background-image',
2426      );
2427  
2428      if ( empty( $allowed_attr ) ) {
2429          return $css;
2430      }
2431  
2432      $css = '';
2433      foreach ( $css_array as $css_item ) {
2434          if ( '' === $css_item ) {
2435              continue;
2436          }
2437  
2438          $css_item        = trim( $css_item );
2439          $css_test_string = $css_item;
2440          $found           = false;
2441          $url_attr        = false;
2442          $gradient_attr   = false;
2443          $is_custom_var   = false;
2444  
2445          if ( strpos( $css_item, ':' ) === false ) {
2446              $found = true;
2447          } else {
2448              $parts        = explode( ':', $css_item, 2 );
2449              $css_selector = trim( $parts[0] );
2450  
2451              // Allow assigning values to CSS variables.
2452              if ( in_array( '--*', $allowed_attr, true ) && preg_match( '/^--[a-zA-Z0-9-_]+$/', $css_selector ) ) {
2453                  $allowed_attr[] = $css_selector;
2454                  $is_custom_var  = true;
2455              }
2456  
2457              if ( in_array( $css_selector, $allowed_attr, true ) ) {
2458                  $found         = true;
2459                  $url_attr      = in_array( $css_selector, $css_url_data_types, true );
2460                  $gradient_attr = in_array( $css_selector, $css_gradient_data_types, true );
2461              }
2462  
2463              if ( $is_custom_var ) {
2464                  $css_value     = trim( $parts[1] );
2465                  $url_attr      = str_starts_with( $css_value, 'url(' );
2466                  $gradient_attr = str_contains( $css_value, '-gradient(' );
2467              }
2468          }
2469  
2470          if ( $found && $url_attr ) {
2471              // Simplified: matches the sequence `url(*)`.
2472              preg_match_all( '/url\([^)]+\)/', $parts[1], $url_matches );
2473  
2474              foreach ( $url_matches[0] as $url_match ) {
2475                  // Clean up the URL from each of the matches above.
2476                  preg_match( '/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces );
2477  
2478                  if ( empty( $url_pieces[2] ) ) {
2479                      $found = false;
2480                      break;
2481                  }
2482  
2483                  $url = trim( $url_pieces[2] );
2484  
2485                  if ( empty( $url ) || wp_kses_bad_protocol( $url, $allowed_protocols ) !== $url ) {
2486                      $found = false;
2487                      break;
2488                  } else {
2489                      // Remove the whole `url(*)` bit that was matched above from the CSS.
2490                      $css_test_string = str_replace( $url_match, '', $css_test_string );
2491                  }
2492              }
2493          }
2494  
2495          if ( $found && $gradient_attr ) {
2496              $css_value = trim( $parts[1] );
2497              if ( preg_match( '/^(repeating-)?(linear|radial|conic)-gradient\(([^()]|rgb[a]?\([^()]*\))*\)$/', $css_value ) ) {
2498                  // Remove the whole `gradient` bit that was matched above from the CSS.
2499                  $css_test_string = str_replace( $css_value, '', $css_test_string );
2500              }
2501          }
2502  
2503          if ( $found ) {
2504              /*
2505               * Allow CSS functions like var(), calc(), etc. by removing them from the test string.
2506               * Nested functions and parentheses are also removed, so long as the parentheses are balanced.
2507               */
2508              $css_test_string = preg_replace(
2509                  '/\b(?:var|calc|min|max|minmax|clamp)(\((?:[^()]|(?1))*\))/',
2510                  '',
2511                  $css_test_string
2512              );
2513  
2514              /*
2515               * Disallow CSS containing \ ( & } = or comments, except for within url(), var(), calc(), etc.
2516               * which were removed from the test string above.
2517               */
2518              $allow_css = ! preg_match( '%[\\\(&=}]|/\*%', $css_test_string );
2519  
2520              /**
2521               * Filters the check for unsafe CSS in `safecss_filter_attr`.
2522               *
2523               * Enables developers to determine whether a section of CSS should be allowed or discarded.
2524               * By default, the value will be false if the part contains \ ( & } = or comments.
2525               * Return true to allow the CSS part to be included in the output.
2526               *
2527               * @since 5.5.0
2528               *
2529               * @param bool   $allow_css       Whether the CSS in the test string is considered safe.
2530               * @param string $css_test_string The CSS string to test.
2531               */
2532              $allow_css = apply_filters( 'safecss_filter_attr_allow_css', $allow_css, $css_test_string );
2533  
2534              // Only add the CSS part if it passes the regex check.
2535              if ( $allow_css ) {
2536                  if ( '' !== $css ) {
2537                      $css .= ';';
2538                  }
2539  
2540                  $css .= $css_item;
2541              }
2542          }
2543      }
2544  
2545      return $css;
2546  }
2547  
2548  /**
2549   * Helper function to add global attributes to a tag in the allowed HTML list.
2550   *
2551   * @since 3.5.0
2552   * @since 5.0.0 Added support for `data-*` wildcard attributes.
2553   * @since 6.0.0 Added `dir`, `lang`, and `xml:lang` to global attributes.
2554   *
2555   * @access private
2556   * @ignore
2557   *
2558   * @param array $value An array of attributes.
2559   * @return array The array of attributes with global attributes added.
2560   */
2561  function _wp_add_global_attributes( $value ) {
2562      $global_attributes = array(
2563          'aria-describedby' => true,
2564          'aria-details'     => true,
2565          'aria-label'       => true,
2566          'aria-labelledby'  => true,
2567          'aria-hidden'      => true,
2568          'class'            => true,
2569          'data-*'           => true,
2570          'dir'              => true,
2571          'id'               => true,
2572          'lang'             => true,
2573          'style'            => true,
2574          'title'            => true,
2575          'role'             => true,
2576          'xml:lang'         => true,
2577      );
2578  
2579      if ( true === $value ) {
2580          $value = array();
2581      }
2582  
2583      if ( is_array( $value ) ) {
2584          return array_merge( $value, $global_attributes );
2585      }
2586  
2587      return $value;
2588  }
2589  
2590  /**
2591   * Helper function to check if this is a safe PDF URL.
2592   *
2593   * @since 5.9.0
2594   * @access private
2595   * @ignore
2596   *
2597   * @param string $url The URL to check.
2598   * @return bool True if the URL is safe, false otherwise.
2599   */
2600  function _wp_kses_allow_pdf_objects( $url ) {
2601      // We're not interested in URLs that contain query strings or fragments.
2602      if ( str_contains( $url, '?' ) || str_contains( $url, '#' ) ) {
2603          return false;
2604      }
2605  
2606      // If it doesn't have a PDF extension, it's not safe.
2607      if ( ! str_ends_with( $url, '.pdf' ) ) {
2608          return false;
2609      }
2610  
2611      // If the URL host matches the current site's media URL, it's safe.
2612      $upload_info = wp_upload_dir( null, false );
2613      $parsed_url  = wp_parse_url( $upload_info['url'] );
2614      $upload_host = isset( $parsed_url['host'] ) ? $parsed_url['host'] : '';
2615      $upload_port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : '';
2616  
2617      if ( str_starts_with( $url, "http://$upload_host$upload_port/" )
2618          || str_starts_with( $url, "https://$upload_host$upload_port/" )
2619      ) {
2620          return true;
2621      }
2622  
2623      return false;
2624  }


Generated : Thu Sep 29 08:20:02 2022 Cross-referenced by PHPXref