[ 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   * When using this constant, make sure to set all of these globals to arrays:
  40   *
  41   *  - `$allowedposttags`
  42   *  - `$allowedtags`
  43   *  - `$allowedentitynames`
  44   *  - `$allowedxmlentitynames`
  45   *
  46   * @see wp_kses_allowed_html()
  47   * @since 1.2.0
  48   *
  49   * @var array[]|false Array of default allowable HTML tags, or false to use the defaults.
  50   */
  51  if ( ! defined( 'CUSTOM_TAGS' ) ) {
  52      define( 'CUSTOM_TAGS', false );
  53  }
  54  
  55  // Ensure that these variables are added to the global namespace
  56  // (e.g. if using namespaces / autoload in the current PHP environment).
  57  global $allowedposttags, $allowedtags, $allowedentitynames, $allowedxmlentitynames;
  58  
  59  if ( ! CUSTOM_TAGS ) {
  60      /**
  61       * KSES global for default allowable HTML tags.
  62       *
  63       * Can be overridden with the `CUSTOM_TAGS` constant.
  64       *
  65       * @var array[] $allowedposttags Array of default allowable HTML tags.
  66       * @since 2.0.0
  67       */
  68      $allowedposttags = array(
  69          'address'    => array(),
  70          'a'          => array(
  71              'href'     => true,
  72              'rel'      => true,
  73              'rev'      => true,
  74              'name'     => true,
  75              'target'   => true,
  76              'download' => array(
  77                  'valueless' => 'y',
  78              ),
  79          ),
  80          'abbr'       => array(),
  81          'acronym'    => array(),
  82          'area'       => array(
  83              'alt'    => true,
  84              'coords' => true,
  85              'href'   => true,
  86              'nohref' => true,
  87              'shape'  => true,
  88              'target' => true,
  89          ),
  90          'article'    => array(
  91              'align' => true,
  92          ),
  93          'aside'      => array(
  94              'align' => true,
  95          ),
  96          'audio'      => array(
  97              'autoplay' => true,
  98              'controls' => true,
  99              'loop'     => true,
 100              'muted'    => true,
 101              'preload'  => true,
 102              'src'      => true,
 103          ),
 104          'b'          => array(),
 105          'bdo'        => array(),
 106          'big'        => array(),
 107          'blockquote' => array(
 108              'cite' => true,
 109          ),
 110          'br'         => array(),
 111          'button'     => array(
 112              'command'             => true,
 113              'commandfor'          => true,
 114              'disabled'            => true,
 115              'name'                => true,
 116              'type'                => true,
 117              'value'               => true,
 118              'popovertarget'       => true,
 119              'popovertargetaction' => true,
 120              'aria-haspopup'       => true,
 121          ),
 122          'caption'    => array(
 123              'align' => true,
 124          ),
 125          'cite'       => array(),
 126          'code'       => array(),
 127          'col'        => array(
 128              'align'   => true,
 129              'char'    => true,
 130              'charoff' => true,
 131              'span'    => true,
 132              'valign'  => true,
 133              'width'   => true,
 134          ),
 135          'colgroup'   => array(
 136              'align'   => true,
 137              'char'    => true,
 138              'charoff' => true,
 139              'span'    => true,
 140              'valign'  => true,
 141              'width'   => true,
 142          ),
 143          'data'       => array(
 144              'value' => true,
 145          ),
 146          'del'        => array(
 147              'datetime' => true,
 148          ),
 149          'dd'         => array(),
 150          'dfn'        => array(),
 151          'details'    => array(
 152              'align' => true,
 153              'open'  => true,
 154              'name'  => true,
 155          ),
 156          'div'        => array(
 157              'align'   => true,
 158              'popover' => true,
 159          ),
 160          'dialog'     => array(
 161              'closedby'  => true,
 162              'open'      => true,
 163              'popover'   => true,
 164              'autofocus' => true,
 165          ),
 166          'dl'         => array(),
 167          'dt'         => array(),
 168          'em'         => array(),
 169          'fieldset'   => array(),
 170          'figure'     => array(
 171              'align' => true,
 172          ),
 173          'figcaption' => array(
 174              'align' => true,
 175          ),
 176          'font'       => array(
 177              'color' => true,
 178              'face'  => true,
 179              'size'  => true,
 180          ),
 181          'footer'     => array(
 182              'align' => true,
 183          ),
 184          'h1'         => array(
 185              'align' => true,
 186          ),
 187          'h2'         => array(
 188              'align' => true,
 189          ),
 190          'h3'         => array(
 191              'align' => true,
 192          ),
 193          'h4'         => array(
 194              'align' => true,
 195          ),
 196          'h5'         => array(
 197              'align' => true,
 198          ),
 199          'h6'         => array(
 200              'align' => true,
 201          ),
 202          'header'     => array(
 203              'align' => true,
 204          ),
 205          'hgroup'     => array(
 206              'align' => true,
 207          ),
 208          'hr'         => array(
 209              'align'   => true,
 210              'noshade' => true,
 211              'size'    => true,
 212              'width'   => true,
 213          ),
 214          'i'          => array(),
 215          'img'        => array(
 216              'alt'      => true,
 217              'align'    => true,
 218              'border'   => true,
 219              'height'   => true,
 220              'hspace'   => true,
 221              'loading'  => true,
 222              'longdesc' => true,
 223              'vspace'   => true,
 224              'src'      => true,
 225              'usemap'   => true,
 226              'width'    => true,
 227          ),
 228          'ins'        => array(
 229              'datetime' => true,
 230              'cite'     => true,
 231          ),
 232          'kbd'        => array(),
 233          'label'      => array(
 234              'for' => true,
 235          ),
 236          'legend'     => array(
 237              'align' => true,
 238          ),
 239          'li'         => array(
 240              'align' => true,
 241              'value' => true,
 242          ),
 243          'main'       => array(
 244              'align' => true,
 245          ),
 246          'map'        => array(
 247              'name' => true,
 248          ),
 249          'mark'       => array(),
 250          'menu'       => array(
 251              'type' => true,
 252          ),
 253          'meter'      => array(
 254              'high'    => true,
 255              'low'     => true,
 256              'max'     => true,
 257              'min'     => true,
 258              'optimum' => true,
 259              'value'   => true,
 260          ),
 261          'nav'        => array(
 262              'align' => true,
 263          ),
 264          'object'     => array(
 265              'data' => array(
 266                  'required'       => true,
 267                  'value_callback' => '_wp_kses_allow_pdf_objects',
 268              ),
 269              'type' => array(
 270                  'required' => true,
 271                  'values'   => array( 'application/pdf' ),
 272              ),
 273          ),
 274          'p'          => array(
 275              'align' => true,
 276          ),
 277          'pre'        => array(
 278              'width' => true,
 279          ),
 280          'progress'   => array(
 281              'max'   => true,
 282              'value' => true,
 283          ),
 284          'q'          => array(
 285              'cite' => true,
 286          ),
 287          'rb'         => array(),
 288          'rp'         => array(),
 289          'rt'         => array(),
 290          'rtc'        => array(),
 291          'ruby'       => array(),
 292          's'          => array(),
 293          'samp'       => array(),
 294          'search'     => array(),
 295          'span'       => array(
 296              'align' => true,
 297          ),
 298          'section'    => array(
 299              'align' => true,
 300          ),
 301          'small'      => array(),
 302          'strike'     => array(),
 303          'strong'     => array(),
 304          'sub'        => array(),
 305          'summary'    => array(
 306              'align' => true,
 307          ),
 308          'sup'        => array(),
 309          'table'      => array(
 310              'align'       => true,
 311              'bgcolor'     => true,
 312              'border'      => true,
 313              'cellpadding' => true,
 314              'cellspacing' => true,
 315              'rules'       => true,
 316              'summary'     => true,
 317              'width'       => true,
 318          ),
 319          'tbody'      => array(
 320              'align'   => true,
 321              'char'    => true,
 322              'charoff' => true,
 323              'valign'  => true,
 324          ),
 325          'td'         => array(
 326              'abbr'    => true,
 327              'align'   => true,
 328              'axis'    => true,
 329              'bgcolor' => true,
 330              'char'    => true,
 331              'charoff' => true,
 332              'colspan' => true,
 333              'headers' => true,
 334              'height'  => true,
 335              'nowrap'  => true,
 336              'rowspan' => true,
 337              'scope'   => true,
 338              'valign'  => true,
 339              'width'   => true,
 340          ),
 341          'textarea'   => array(
 342              'cols'     => true,
 343              'rows'     => true,
 344              'disabled' => true,
 345              'name'     => true,
 346              'readonly' => true,
 347          ),
 348          'tfoot'      => array(
 349              'align'   => true,
 350              'char'    => true,
 351              'charoff' => true,
 352              'valign'  => true,
 353          ),
 354          'th'         => array(
 355              'abbr'    => true,
 356              'align'   => true,
 357              'axis'    => true,
 358              'bgcolor' => true,
 359              'char'    => true,
 360              'charoff' => true,
 361              'colspan' => true,
 362              'headers' => true,
 363              'height'  => true,
 364              'nowrap'  => true,
 365              'rowspan' => true,
 366              'scope'   => true,
 367              'valign'  => true,
 368              'width'   => true,
 369          ),
 370          'thead'      => array(
 371              'align'   => true,
 372              'char'    => true,
 373              'charoff' => true,
 374              'valign'  => true,
 375          ),
 376          'time'       => array(
 377              'datetime' => true,
 378          ),
 379          'title'      => array(),
 380          'tr'         => array(
 381              'align'   => true,
 382              'bgcolor' => true,
 383              'char'    => true,
 384              'charoff' => true,
 385              'valign'  => true,
 386          ),
 387          'track'      => array(
 388              'default' => true,
 389              'kind'    => true,
 390              'label'   => true,
 391              'src'     => true,
 392              'srclang' => true,
 393          ),
 394          'tt'         => array(),
 395          'u'          => array(),
 396          'ul'         => array(
 397              'type'    => true,
 398              'popover' => true,
 399              'role'    => true,
 400          ),
 401          'ol'         => array(
 402              'start'    => true,
 403              'type'     => true,
 404              'reversed' => true,
 405          ),
 406          'var'        => array(),
 407          'video'      => array(
 408              'autoplay'    => true,
 409              'controls'    => true,
 410              'height'      => true,
 411              'loop'        => true,
 412              'muted'       => true,
 413              'playsinline' => true,
 414              'poster'      => true,
 415              'preload'     => true,
 416              'src'         => true,
 417              'width'       => true,
 418          ),
 419          'wbr'        => array(),
 420      );
 421  
 422      // https://www.w3.org/TR/mathml-core/#global-attributes
 423      // Except common attributes added by _wp_add_global_attributes.
 424      $math_global_attributes = array(
 425          'displaystyle'   => true,
 426          'scriptlevel'    => true,
 427          'mathbackground' => true,
 428          'mathcolor'      => true,
 429          'mathsize'       => true,
 430          // Common attributes also defined by _wp_add_global_attributes.
 431          // We do not want to add all those global attributes though.
 432          'class'          => true,
 433          'data-*'         => true,
 434          'dir'            => true,
 435          'id'             => true,
 436          'style'          => true,
 437      );
 438  
 439      $math_overunder_attributes = array(
 440          'accentunder' => true,
 441          'accent'      => true,
 442      );
 443  
 444      $allowedposttags = array_merge(
 445          $allowedposttags,
 446          array(
 447              // https://www.w3.org/TR/mathml-core/#the-top-level-math-element
 448              'math'          => array_merge(
 449                  $math_global_attributes,
 450                  array(
 451                      'display' => true,
 452                  )
 453              ),
 454  
 455              // https://www.w3.org/TR/mathml-core/#token-elements
 456              // https://www.w3.org/TR/mathml-core/#text-mtext
 457              'mtext'         => $math_global_attributes,
 458              // https://www.w3.org/TR/mathml-core/#the-mi-element
 459              'mi'            => array_merge(
 460                  $math_global_attributes,
 461                  array(
 462                      'mathvariant' => true,
 463                  )
 464              ),
 465              // https://www.w3.org/TR/mathml-core/#number-mn
 466              'mn'            => $math_global_attributes,
 467              // https://www.w3.org/TR/mathml-core/#operator-fence-separator-or-accent-mo
 468              'mo'            => array_merge(
 469                  $math_global_attributes,
 470                  array(
 471                      'form'          => true,
 472                      'fence'         => true,
 473                      'separator'     => true,
 474                      'lspace'        => true,
 475                      'rspace'        => true,
 476                      'stretchy'      => true,
 477                      'symmetric'     => true,
 478                      'maxsize'       => true,
 479                      'minsize'       => true,
 480                      'largeop'       => true,
 481                      'movablelimits' => true,
 482                  )
 483              ),
 484              // https://www.w3.org/TR/mathml-core/#space-mspace
 485              'mspace'        => array_merge(
 486                  $math_global_attributes,
 487                  array(
 488                      'width'  => true,
 489                      'height' => true,
 490                      'depth'  => true,
 491                  )
 492              ),
 493              // https://www.w3.org/TR/mathml-core/#string-literal-ms
 494              'ms'            => $math_global_attributes,
 495  
 496              // https://www.w3.org/TR/mathml-core/#general-layout-schemata
 497              // https://www.w3.org/TR/mathml-core/#horizontally-group-sub-expressions-mrow
 498              'mrow'          => $math_global_attributes,
 499              // https://www.w3.org/TR/mathml-core/#fractions-mfrac
 500              'mfrac'         => array_merge(
 501                  $math_global_attributes,
 502                  array(
 503                      'linethickness' => true,
 504                  )
 505              ),
 506              // https://www.w3.org/TR/mathml-core/#radicals-msqrt-mroot
 507              'msqrt'         => $math_global_attributes,
 508              'mroot'         => $math_global_attributes,
 509              // https://www.w3.org/TR/mathml-core/#style-change-mstyle
 510              'mstyle'        => $math_global_attributes,
 511              // https://www.w3.org/TR/mathml-core/#error-message-merror
 512              'merror'        => $math_global_attributes,
 513              // https://www.w3.org/TR/mathml-core/#adjust-space-around-content-mpadded
 514              'mpadded'       => array_merge(
 515                  $math_global_attributes,
 516                  array(
 517                      'width'   => true,
 518                      'height'  => true,
 519                      'depth'   => true,
 520                      'lspace'  => true,
 521                      'voffset' => true,
 522                  )
 523              ),
 524              // https://www.w3.org/TR/mathml-core/#making-sub-expressions-invisible-mphantom
 525              'mphantom'      => $math_global_attributes,
 526  
 527              // https://www.w3.org/TR/mathml-core/#script-and-limit-schemata
 528              // https://www.w3.org/TR/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup
 529              'msub'          => $math_global_attributes,
 530              'msup'          => $math_global_attributes,
 531              'msubsup'       => $math_global_attributes,
 532              // https://www.w3.org/TR/mathml-core/#underscripts-and-overscripts-munder-mover-munderover
 533              'munder'        => array_merge( $math_global_attributes, $math_overunder_attributes ),
 534              'mover'         => array_merge( $math_global_attributes, $math_overunder_attributes ),
 535              'munderover'    => array_merge( $math_global_attributes, $math_overunder_attributes ),
 536              // https://www.w3.org/TR/mathml-core/#prescripts-and-tensor-indices-mmultiscripts
 537              'mmultiscripts' => $math_global_attributes,
 538              'mprescripts'   => $math_global_attributes,
 539  
 540              // https://www.w3.org/TR/mathml-core/#tabular-math
 541              // https://www.w3.org/TR/mathml-core/#table-or-matrix-mtable
 542              'mtable'        => array_merge(
 543                  $math_global_attributes,
 544                  array(
 545                      // Non-standard, used by temml/katex.
 546                      // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtable
 547                      'columnalign'   => true,
 548                      'rowspacing'    => true,
 549                      'columnspacing' => true,
 550                      'align'         => true,
 551                      'rowalign'      => true,
 552                      'columnlines'   => true,
 553                      'rowlines'      => true,
 554                      'frame'         => true,
 555                      'framespacing'  => true,
 556                      'width'         => true,
 557                  )
 558              ),
 559              // https://www.w3.org/TR/mathml-core/#row-in-table-or-matrix-mtr
 560              'mtr'           => array_merge(
 561                  $math_global_attributes,
 562                  array(
 563                      // Non-standard, used by temml/katex.
 564                      // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtr
 565                      'columnalign' => true,
 566                      'rowalign'    => true,
 567                  )
 568              ),
 569              // https://www.w3.org/TR/mathml-core/#entry-in-table-or-matrix-mtd
 570              'mtd'           => array_merge(
 571                  $math_global_attributes,
 572                  array(
 573                      'columnspan'  => true,
 574                      'rowspan'     => true,
 575                      // Non-standard, used by temml/katex.
 576                      // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtd
 577                      'columnalign' => true,
 578                      'rowalign'    => true,
 579                  )
 580              ),
 581  
 582              // https://www.w3.org/TR/mathml-core/#semantics-and-presentation
 583              'semantics'     => $math_global_attributes,
 584              'annotation'    => array_merge(
 585                  $math_global_attributes,
 586                  array(
 587                      'encoding' => true,
 588                  )
 589              ),
 590  
 591              // Non-standard but widely supported, used by temml/katex.
 592              'menclose'      => array_merge(
 593                  $math_global_attributes,
 594                  array(
 595                      'notation' => true,
 596                  )
 597              ),
 598          )
 599      );
 600  
 601      /**
 602       * @var array[] $allowedtags Array of KSES allowed HTML elements.
 603       * @since 1.0.0
 604       */
 605      $allowedtags = array(
 606          'a'          => array(
 607              'href'  => true,
 608              'title' => true,
 609          ),
 610          'abbr'       => array(
 611              'title' => true,
 612          ),
 613          'acronym'    => array(
 614              'title' => true,
 615          ),
 616          'b'          => array(),
 617          'blockquote' => array(
 618              'cite' => true,
 619          ),
 620          'cite'       => array(),
 621          'code'       => array(),
 622          'del'        => array(
 623              'datetime' => true,
 624          ),
 625          'em'         => array(),
 626          'i'          => array(),
 627          'q'          => array(
 628              'cite' => true,
 629          ),
 630          's'          => array(),
 631          'strike'     => array(),
 632          'strong'     => array(),
 633      );
 634  
 635      /**
 636       * @var string[] $allowedentitynames Array of KSES allowed HTML entity names.
 637       * @since 1.0.0
 638       */
 639      $allowedentitynames = array(
 640          'nbsp',
 641          'iexcl',
 642          'cent',
 643          'pound',
 644          'curren',
 645          'yen',
 646          'brvbar',
 647          'sect',
 648          'uml',
 649          'copy',
 650          'ordf',
 651          'laquo',
 652          'not',
 653          'shy',
 654          'reg',
 655          'macr',
 656          'deg',
 657          'plusmn',
 658          'acute',
 659          'micro',
 660          'para',
 661          'middot',
 662          'cedil',
 663          'ordm',
 664          'raquo',
 665          'iquest',
 666          'Agrave',
 667          'Aacute',
 668          'Acirc',
 669          'Atilde',
 670          'Auml',
 671          'Aring',
 672          'AElig',
 673          'Ccedil',
 674          'Egrave',
 675          'Eacute',
 676          'Ecirc',
 677          'Euml',
 678          'Igrave',
 679          'Iacute',
 680          'Icirc',
 681          'Iuml',
 682          'ETH',
 683          'Ntilde',
 684          'Ograve',
 685          'Oacute',
 686          'Ocirc',
 687          'Otilde',
 688          'Ouml',
 689          'times',
 690          'Oslash',
 691          'Ugrave',
 692          'Uacute',
 693          'Ucirc',
 694          'Uuml',
 695          'Yacute',
 696          'THORN',
 697          'szlig',
 698          'agrave',
 699          'aacute',
 700          'acirc',
 701          'atilde',
 702          'auml',
 703          'aring',
 704          'aelig',
 705          'ccedil',
 706          'egrave',
 707          'eacute',
 708          'ecirc',
 709          'euml',
 710          'igrave',
 711          'iacute',
 712          'icirc',
 713          'iuml',
 714          'eth',
 715          'ntilde',
 716          'ograve',
 717          'oacute',
 718          'ocirc',
 719          'otilde',
 720          'ouml',
 721          'divide',
 722          'oslash',
 723          'ugrave',
 724          'uacute',
 725          'ucirc',
 726          'uuml',
 727          'yacute',
 728          'thorn',
 729          'yuml',
 730          'quot',
 731          'amp',
 732          'lt',
 733          'gt',
 734          'apos',
 735          'OElig',
 736          'oelig',
 737          'Scaron',
 738          'scaron',
 739          'Yuml',
 740          'circ',
 741          'tilde',
 742          'ensp',
 743          'emsp',
 744          'thinsp',
 745          'zwnj',
 746          'zwj',
 747          'lrm',
 748          'rlm',
 749          'ndash',
 750          'mdash',
 751          'lsquo',
 752          'rsquo',
 753          'sbquo',
 754          'ldquo',
 755          'rdquo',
 756          'bdquo',
 757          'dagger',
 758          'Dagger',
 759          'permil',
 760          'lsaquo',
 761          'rsaquo',
 762          'euro',
 763          'fnof',
 764          'Alpha',
 765          'Beta',
 766          'Gamma',
 767          'Delta',
 768          'Epsilon',
 769          'Zeta',
 770          'Eta',
 771          'Theta',
 772          'Iota',
 773          'Kappa',
 774          'Lambda',
 775          'Mu',
 776          'Nu',
 777          'Xi',
 778          'Omicron',
 779          'Pi',
 780          'Rho',
 781          'Sigma',
 782          'Tau',
 783          'Upsilon',
 784          'Phi',
 785          'Chi',
 786          'Psi',
 787          'Omega',
 788          'alpha',
 789          'beta',
 790          'gamma',
 791          'delta',
 792          'epsilon',
 793          'zeta',
 794          'eta',
 795          'theta',
 796          'iota',
 797          'kappa',
 798          'lambda',
 799          'mu',
 800          'nu',
 801          'xi',
 802          'omicron',
 803          'pi',
 804          'rho',
 805          'sigmaf',
 806          'sigma',
 807          'tau',
 808          'upsilon',
 809          'phi',
 810          'chi',
 811          'psi',
 812          'omega',
 813          'thetasym',
 814          'upsih',
 815          'piv',
 816          'bull',
 817          'hellip',
 818          'prime',
 819          'Prime',
 820          'oline',
 821          'frasl',
 822          'weierp',
 823          'image',
 824          'real',
 825          'trade',
 826          'alefsym',
 827          'larr',
 828          'uarr',
 829          'rarr',
 830          'darr',
 831          'harr',
 832          'crarr',
 833          'lArr',
 834          'uArr',
 835          'rArr',
 836          'dArr',
 837          'hArr',
 838          'forall',
 839          'part',
 840          'exist',
 841          'empty',
 842          'nabla',
 843          'isin',
 844          'notin',
 845          'ni',
 846          'prod',
 847          'sum',
 848          'minus',
 849          'lowast',
 850          'radic',
 851          'prop',
 852          'infin',
 853          'ang',
 854          'and',
 855          'or',
 856          'cap',
 857          'cup',
 858          'int',
 859          'sim',
 860          'cong',
 861          'asymp',
 862          'ne',
 863          'equiv',
 864          'le',
 865          'ge',
 866          'sub',
 867          'sup',
 868          'nsub',
 869          'sube',
 870          'supe',
 871          'oplus',
 872          'otimes',
 873          'perp',
 874          'sdot',
 875          'lceil',
 876          'rceil',
 877          'lfloor',
 878          'rfloor',
 879          'lang',
 880          'rang',
 881          'loz',
 882          'spades',
 883          'clubs',
 884          'hearts',
 885          'diams',
 886          'sup1',
 887          'sup2',
 888          'sup3',
 889          'frac14',
 890          'frac12',
 891          'frac34',
 892          'there4',
 893      );
 894  
 895      /**
 896       * @var string[] $allowedxmlentitynames Array of KSES allowed XML entity names.
 897       * @since 5.5.0
 898       */
 899      $allowedxmlentitynames = array(
 900          'amp',
 901          'lt',
 902          'gt',
 903          'apos',
 904          'quot',
 905      );
 906  
 907      $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
 908  } else {
 909      $required_kses_globals = array(
 910          'allowedposttags',
 911          'allowedtags',
 912          'allowedentitynames',
 913          'allowedxmlentitynames',
 914      );
 915      $missing_kses_globals  = array();
 916  
 917      foreach ( $required_kses_globals as $global_name ) {
 918          if ( ! isset( $GLOBALS[ $global_name ] ) || ! is_array( $GLOBALS[ $global_name ] ) ) {
 919              $missing_kses_globals[] = '<code>$' . $global_name . '</code>';
 920          }
 921      }
 922  
 923      if ( $missing_kses_globals ) {
 924          _doing_it_wrong(
 925              'wp_kses_allowed_html',
 926              sprintf(
 927                  /* translators: 1: CUSTOM_TAGS, 2: Global variable names. */
 928                  __( 'When using the %1$s constant, make sure to set these globals to an array: %2$s.' ),
 929                  '<code>CUSTOM_TAGS</code>',
 930                  implode( ', ', $missing_kses_globals )
 931              ),
 932              '6.2.0'
 933          );
 934      }
 935  
 936      $allowedtags     = wp_kses_array_lc( $allowedtags );
 937      $allowedposttags = wp_kses_array_lc( $allowedposttags );
 938  }
 939  
 940  /**
 941   * Filters text content and strips out disallowed HTML.
 942   *
 943   * This function makes sure that only the allowed HTML element names, attribute
 944   * names, attribute values, and HTML entities will occur in the given text string.
 945   *
 946   * This function expects unslashed data.
 947   *
 948   * @see wp_kses_post() for specifically filtering post content and fields.
 949   * @see wp_allowed_protocols() for the default allowed protocols in link URLs.
 950   *
 951   * @since 1.0.0
 952   *
 953   * @param string         $content           Text content to filter.
 954   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
 955   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
 956   *                                          for the list of accepted context names.
 957   * @param string[]       $allowed_protocols Optional. Array of allowed URL protocols.
 958   *                                          Defaults to the result of wp_allowed_protocols().
 959   * @return string Filtered content containing only the allowed HTML.
 960   */
 961  function wp_kses( $content, $allowed_html, $allowed_protocols = array() ) {
 962      if ( empty( $allowed_protocols ) ) {
 963          $allowed_protocols = wp_allowed_protocols();
 964      }
 965  
 966      $content = wp_kses_no_null( $content, array( 'slash_zero' => 'keep' ) );
 967      $content = wp_kses_normalize_entities( $content );
 968      $content = wp_kses_hook( $content, $allowed_html, $allowed_protocols );
 969  
 970      return wp_kses_split( $content, $allowed_html, $allowed_protocols );
 971  }
 972  
 973  /**
 974   * Filters one HTML attribute and ensures its value is allowed.
 975   *
 976   * This function can escape data in some situations where `wp_kses()` must strip the whole attribute.
 977   *
 978   * @since 4.2.3
 979   *
 980   * @param string $attr    The 'whole' attribute, including name and value.
 981   * @param string $element The HTML element name to which the attribute belongs.
 982   * @return string Filtered attribute.
 983   */
 984  function wp_kses_one_attr( $attr, $element ) {
 985      $uris              = wp_kses_uri_attributes();
 986      $allowed_html      = wp_kses_allowed_html( 'post' );
 987      $allowed_protocols = wp_allowed_protocols();
 988      $attr              = wp_kses_no_null( $attr, array( 'slash_zero' => 'keep' ) );
 989  
 990      // Preserve leading and trailing whitespace.
 991      $matches = array();
 992      preg_match( '/^\s*/', $attr, $matches );
 993      $lead = $matches[0];
 994      preg_match( '/\s*$/', $attr, $matches );
 995      $trail = $matches[0];
 996      if ( empty( $trail ) ) {
 997          $attr = substr( $attr, strlen( $lead ) );
 998      } else {
 999          $attr = substr( $attr, strlen( $lead ), -strlen( $trail ) );
1000      }
1001  
1002      // Parse attribute name and value from input.
1003      $split = preg_split( '/\s*=\s*/', $attr, 2 );
1004      $name  = $split[0];
1005      if ( count( $split ) === 2 ) {
1006          $value = $split[1];
1007  
1008          /*
1009           * Remove quotes surrounding $value.
1010           * Also guarantee correct quoting in $attr for this one attribute.
1011           */
1012          if ( '' === $value ) {
1013              $quote = '';
1014          } else {
1015              $quote = $value[0];
1016          }
1017          if ( '"' === $quote || "'" === $quote ) {
1018              if ( ! str_ends_with( $value, $quote ) ) {
1019                  return '';
1020              }
1021              $value = substr( $value, 1, -1 );
1022          } else {
1023              $quote = '"';
1024          }
1025  
1026          // Sanitize quotes, angle braces, and entities.
1027          $value = esc_attr( $value );
1028  
1029          // Sanitize URI values.
1030          if ( in_array( strtolower( $name ), $uris, true ) ) {
1031              $value = wp_kses_bad_protocol( $value, $allowed_protocols );
1032          }
1033  
1034          $attr  = "$name=$quote$value$quote";
1035          $vless = 'n';
1036      } else {
1037          $value = '';
1038          $vless = 'y';
1039      }
1040  
1041      // Sanitize attribute by name.
1042      wp_kses_attr_check( $name, $value, $attr, $vless, $element, $allowed_html );
1043  
1044      // Restore whitespace.
1045      return $lead . $attr . $trail;
1046  }
1047  
1048  /**
1049   * Returns an array of allowed HTML tags and attributes for a given context.
1050   *
1051   * @since 3.5.0
1052   * @since 5.0.1 `form` removed as allowable HTML tag.
1053   *
1054   * @global array $allowedposttags
1055   * @global array $allowedtags
1056   * @global array $allowedentitynames
1057   *
1058   * @param string|array $context The context for which to retrieve tags. Allowed values are 'post',
1059   *                              'strip', 'data', 'entities', or the name of a field filter such as
1060   *                              'pre_user_description', or an array of allowed HTML elements and attributes.
1061   * @return array Array of allowed HTML tags and their allowed attributes.
1062   */
1063  function wp_kses_allowed_html( $context = '' ) {
1064      global $allowedposttags, $allowedtags, $allowedentitynames;
1065  
1066      if ( is_array( $context ) ) {
1067          // When `$context` is an array it's actually an array of allowed HTML elements and attributes.
1068          $html    = $context;
1069          $context = 'explicit';
1070  
1071          /**
1072           * Filters the HTML tags that are allowed for a given context.
1073           *
1074           * HTML tags and attribute names are case-insensitive in HTML but must be
1075           * added to the KSES allow list in lowercase. An item added to the allow list
1076           * in upper or mixed case will not recognized as permitted by KSES.
1077           *
1078           * @since 3.5.0
1079           *
1080           * @param array[] $html    Allowed HTML tags.
1081           * @param string  $context Context name.
1082           */
1083          return apply_filters( 'wp_kses_allowed_html', $html, $context );
1084      }
1085  
1086      switch ( $context ) {
1087          case 'post':
1088              /** This filter is documented in wp-includes/kses.php */
1089              $tags = apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
1090  
1091              // 5.0.1 removed the `<form>` tag, allow it if a filter is allowing it's sub-elements `<input>` or `<select>`.
1092              if ( ! CUSTOM_TAGS && ! isset( $tags['form'] ) && ( isset( $tags['input'] ) || isset( $tags['select'] ) ) ) {
1093                  $tags = $allowedposttags;
1094  
1095                  $tags['form'] = array(
1096                      'action'         => true,
1097                      'accept'         => true,
1098                      'accept-charset' => true,
1099                      'enctype'        => true,
1100                      'method'         => true,
1101                      'name'           => true,
1102                      'target'         => true,
1103                  );
1104  
1105                  /** This filter is documented in wp-includes/kses.php */
1106                  $tags = apply_filters( 'wp_kses_allowed_html', $tags, $context );
1107              }
1108  
1109              return $tags;
1110  
1111          case 'user_description':
1112          case 'pre_term_description':
1113          case 'pre_user_description':
1114              $tags                = $allowedtags;
1115              $tags['a']['rel']    = true;
1116              $tags['a']['target'] = true;
1117              /** This filter is documented in wp-includes/kses.php */
1118              return apply_filters( 'wp_kses_allowed_html', $tags, $context );
1119  
1120          case 'strip':
1121              /** This filter is documented in wp-includes/kses.php */
1122              return apply_filters( 'wp_kses_allowed_html', array(), $context );
1123  
1124          case 'entities':
1125              /** This filter is documented in wp-includes/kses.php */
1126              return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context );
1127  
1128          case 'data':
1129          default:
1130              /** This filter is documented in wp-includes/kses.php */
1131              return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
1132      }
1133  }
1134  
1135  /**
1136   * Allows the note mention chip markup in comment content.
1137   *
1138   * The notes `@` mention completer stores a mention as a chip carrying the
1139   * mentioned user's ID in a class token:
1140   * `<span class="wp-note-mention user-N">@Name</span>`. The default comment
1141   * allowlist does not allow `span` at all, so for users without
1142   * `unfiltered_html` the mention would be stripped on save.
1143   *
1144   * The allowance is deliberately narrow and always on: `span` is a
1145   * semantics-free element and _wp_kses_sanitize_note_mention_classes()
1146   * reduces its `class` to the two mention tokens right after kses runs, so
1147   * regular (including anonymous) commenters gain nothing beyond the inert
1148   * mention markup itself.
1149   *
1150   * @since 7.1.0
1151   * @access private
1152   *
1153   * @param array<string, array<string, bool>> $allowed The allowed tags structure for the context.
1154   * @param string                             $context The kses context.
1155   * @return array<string, array<string, bool>> Modified allowed tags structure.
1156   */
1157  function _wp_kses_allow_note_mention_span( $allowed, $context ): array {
1158      if ( ! is_array( $allowed ) ) {
1159          $allowed = array();
1160      }
1161      if ( 'pre_comment_content' !== $context ) {
1162          return $allowed;
1163      }
1164  
1165      if ( ! isset( $allowed['span'] ) || ! is_array( $allowed['span'] ) ) {
1166          $allowed['span'] = array();
1167      }
1168  
1169      $allowed['span']['class'] = true;
1170  
1171      return $allowed;
1172  }
1173  
1174  /**
1175   * Reduces `span` classes in comment content to the note mention tokens.
1176   *
1177   * _wp_kses_allow_note_mention_span() lets `class` through kses on `span` so
1178   * the mention chip survives, but `class` is an open-ended styling and
1179   * scripting hook, so this companion pass - running right after
1180   * `wp_filter_kses` at priority 10 - strips every class token except the two
1181   * the mention markup uses: `wp-note-mention` and `user-N`. `span` is the only
1182   * comment tag allowed to carry `class` at all, so walking `span` tags covers
1183   * the entire allowance.
1184   *
1185   * The pass only applies while the restrictive comment allowlist is active:
1186   * users with `unfiltered_html` are filtered through `wp_filter_post_kses`
1187   * (or not at all), where arbitrary classes are already permitted, and
1188   * narrowing their markup here would restrict what core allows them to post.
1189   *
1190   * @since 7.1.0
1191   * @access private
1192   *
1193   * @param string $content Slashed comment content, already filtered by kses.
1194   * @return string Slashed comment content with span classes reduced.
1195   */
1196  function _wp_kses_sanitize_note_mention_classes( $content ): string {
1197      if ( ! is_string( $content ) ) {
1198          $content = '';
1199      }
1200      if ( false === has_filter( 'pre_comment_content', 'wp_filter_kses' ) ) {
1201          return $content;
1202      }
1203  
1204      $processor = new WP_HTML_Tag_Processor( wp_unslash( $content ) );
1205  
1206      while ( $processor->next_tag( 'SPAN' ) ) {
1207          foreach ( $processor->class_list() as $token ) {
1208              if ( 'wp-note-mention' !== $token && ! preg_match( '/^user-[1-9][0-9]*$/', $token ) ) {
1209                  // Removing the last class also removes the attribute itself.
1210                  $processor->remove_class( $token );
1211              }
1212          }
1213      }
1214  
1215      return wp_slash( $processor->get_updated_html() );
1216  }
1217  
1218  /**
1219   * You add any KSES hooks here.
1220   *
1221   * There is currently only one KSES WordPress hook, {@see 'pre_kses'}, and it is called here.
1222   * All parameters are passed to the hooks and expected to receive a string.
1223   *
1224   * @since 1.0.0
1225   *
1226   * @param string         $content           Content to filter through KSES.
1227   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1228   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1229   *                                          for the list of accepted context names.
1230   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1231   * @return string Filtered content through {@see 'pre_kses'} hook.
1232   */
1233  function wp_kses_hook( $content, $allowed_html, $allowed_protocols ) {
1234      /**
1235       * Filters content to be run through KSES.
1236       *
1237       * @since 2.3.0
1238       *
1239       * @param string         $content           Content to filter through KSES.
1240       * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1241       *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1242       *                                          for the list of accepted context names.
1243       * @param string[]       $allowed_protocols Array of allowed URL protocols.
1244       */
1245      return apply_filters( 'pre_kses', $content, $allowed_html, $allowed_protocols );
1246  }
1247  
1248  /**
1249   * Returns the version number of KSES.
1250   *
1251   * @since 1.0.0
1252   *
1253   * @return string KSES version number.
1254   */
1255  function wp_kses_version() {
1256      return '0.2.2';
1257  }
1258  
1259  /**
1260   * Searches for HTML tags, no matter how malformed.
1261   *
1262   * It also matches stray `>` characters.
1263   *
1264   * @since 1.0.0
1265   * @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments.
1266   *
1267   * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
1268   *                                                or a context name such as 'post'.
1269   * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
1270   *
1271   * @param string         $content           Content to filter.
1272   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1273   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1274   *                                          for the list of accepted context names.
1275   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1276   * @return string Content with fixed HTML tags
1277   */
1278  function wp_kses_split( $content, $allowed_html, $allowed_protocols ) {
1279      global $pass_allowed_html, $pass_allowed_protocols;
1280  
1281      $pass_allowed_html      = $allowed_html;
1282      $pass_allowed_protocols = $allowed_protocols;
1283  
1284      $token_pattern = <<<REGEX
1285  ~
1286      (                      # Detect comments of various flavors before attempting to find tags.
1287          (<!--.*?(-->|$))   #  - Normative HTML comments.
1288          |
1289          </[^a-zA-Z][^>]*>  #  - Closing tags with invalid tag names.
1290          |
1291          <![^>]*>           #  - Invalid markup declaration nodes. Not all invalid nodes
1292                             #    are matched so as to avoid breaking legacy behaviors.
1293      )
1294      |
1295      (<[^>]*(>|$)|>)        # Tag-like spans of text.
1296  ~x
1297  REGEX;
1298      return preg_replace_callback( $token_pattern, '_wp_kses_split_callback', $content );
1299  }
1300  
1301  /**
1302   * Returns an array of HTML attribute names whose value contains a URL.
1303   *
1304   * This function returns a list of all HTML attributes that must contain
1305   * a URL according to the HTML specification.
1306   *
1307   * This list includes URI attributes both allowed and disallowed by KSES.
1308   *
1309   * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
1310   *
1311   * @since 5.0.1
1312   *
1313   * @return string[] HTML attribute names whose value contains a URL.
1314   */
1315  function wp_kses_uri_attributes() {
1316      $uri_attributes = array(
1317          'action',
1318          'archive',
1319          'background',
1320          'cite',
1321          'classid',
1322          'codebase',
1323          'data',
1324          'formaction',
1325          'href',
1326          'icon',
1327          'longdesc',
1328          'manifest',
1329          'poster',
1330          'profile',
1331          'src',
1332          'usemap',
1333          'xmlns',
1334      );
1335  
1336      /**
1337       * Filters the list of attributes that are required to contain a URL.
1338       *
1339       * Use this filter to add any `data-` attributes that are required to be
1340       * validated as a URL.
1341       *
1342       * @since 5.0.1
1343       *
1344       * @param string[] $uri_attributes HTML attribute names whose value contains a URL.
1345       */
1346      $uri_attributes = apply_filters( 'wp_kses_uri_attributes', $uri_attributes );
1347  
1348      return $uri_attributes;
1349  }
1350  
1351  /**
1352   * Callback for `wp_kses_split()`.
1353   *
1354   * @since 3.1.0
1355   * @access private
1356   * @ignore
1357   *
1358   * @global array[]|string $pass_allowed_html      An array of allowed HTML elements and attributes,
1359   *                                                or a context name such as 'post'.
1360   * @global string[]       $pass_allowed_protocols Array of allowed URL protocols.
1361   *
1362   * @param array $matches preg_replace regexp matches
1363   * @return string
1364   */
1365  function _wp_kses_split_callback( $matches ) {
1366      global $pass_allowed_html, $pass_allowed_protocols;
1367  
1368      return wp_kses_split2( $matches[0], $pass_allowed_html, $pass_allowed_protocols );
1369  }
1370  
1371  /**
1372   * Callback for `wp_kses_split()` for fixing malformed HTML tags.
1373   *
1374   * This function does a lot of work. It rejects some very malformed things like
1375   * `<:::>`. It returns an empty string, if the element isn't allowed (look ma, no
1376   * `strip_tags()`!). Otherwise it splits the tag into an element and an attribute
1377   * list.
1378   *
1379   * After the tag is split into an element and an attribute list, it is run
1380   * through another filter which will remove illegal attributes and once that is
1381   * completed, will be returned.
1382   *
1383   * @access private
1384   * @ignore
1385   * @since 1.0.0
1386   * @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments.
1387   *
1388   * @param string         $content           Content to filter.
1389   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1390   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1391   *                                          for the list of accepted context names.
1392   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1393   * @return string Fixed HTML element
1394   */
1395  function wp_kses_split2( $content, $allowed_html, $allowed_protocols ) {
1396      $content = wp_kses_stripslashes( $content );
1397  
1398      /*
1399       * The regex pattern used to split HTML into chunks attempts
1400       * to split on HTML token boundaries. This function should
1401       * thus receive chunks that _either_ start with meaningful
1402       * syntax tokens, like a tag `<div>` or a comment `<!-- ... -->`.
1403       *
1404       * If the first character of the `$content` chunk _isn't_ one
1405       * of these syntax elements, which always starts with `<`, then
1406       * the match had to be for the final alternation of `>`. In such
1407       * case, it's probably standing on its own and could be encoded
1408       * with a character reference to remove ambiguity.
1409       *
1410       * In other words, if this chunk isn't from a match of a syntax
1411       * token, it's just a plaintext greater-than (`>`) sign.
1412       */
1413      if ( ! str_starts_with( $content, '<' ) ) {
1414          return '&gt;';
1415      }
1416  
1417      /*
1418       * When certain invalid syntax constructs appear, the HTML parser
1419       * shifts into what's called the "bogus comment state." This is a
1420       * plaintext state that consumes everything until the nearest `>`
1421       * and then transforms the entire span into an HTML comment.
1422       *
1423       * Preserve these comments and do not treat them like tags.
1424       *
1425       * @see https://html.spec.whatwg.org/#bogus-comment-state
1426       */
1427      if ( 1 === preg_match( '~^(?:</[^a-zA-Z][^>]*>|<![a-z][^>]*>)$~', $content ) ) {
1428          /**
1429           * Since the pattern matches `</…>` and also `<!…>`, this will
1430           * preserve the type of the cleaned-up token in the output.
1431           */
1432          $opener  = $content[1];
1433          $content = substr( $content, 2, -1 );
1434  
1435          do {
1436              $prev    = $content;
1437              $content = wp_kses( $content, $allowed_html, $allowed_protocols );
1438          } while ( $prev !== $content );
1439  
1440          // Recombine the modified inner content with the original token structure.
1441          return "<{$opener}{$content}>";
1442      }
1443  
1444      /*
1445       * Normative HTML comments should be handled separately as their
1446       * parsing rules differ from those for tags and text nodes.
1447       */
1448      if ( str_starts_with( $content, '<!--' ) ) {
1449          $content = str_replace( array( '<!--', '-->' ), '', $content );
1450  
1451          while ( ( $newstring = wp_kses( $content, $allowed_html, $allowed_protocols ) ) !== $content ) {
1452              $content = $newstring;
1453          }
1454  
1455          if ( '' === $content ) {
1456              return '';
1457          }
1458  
1459          // Prevent multiple dashes in comments.
1460          $content = preg_replace( '/--+/', '-', $content );
1461          // Prevent three dashes closing a comment.
1462          $content = preg_replace( '/-$/', '', $content );
1463  
1464          return "<!--{$content}-->";
1465      }
1466  
1467      // It's seriously malformed.
1468      if ( ! preg_match( '%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $content, $matches ) ) {
1469          return '';
1470      }
1471  
1472      $slash    = trim( $matches[1] );
1473      $elem     = $matches[2];
1474      $attrlist = $matches[3];
1475  
1476      if ( ! is_array( $allowed_html ) ) {
1477          $allowed_html = wp_kses_allowed_html( $allowed_html );
1478      }
1479  
1480      // They are using a not allowed HTML element.
1481      if ( ! isset( $allowed_html[ strtolower( $elem ) ] ) ) {
1482          return '';
1483      }
1484  
1485      // No attributes are allowed for closing elements.
1486      if ( '' !== $slash ) {
1487          return "</$elem>";
1488      }
1489  
1490      return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
1491  }
1492  
1493  /**
1494   * Removes all attributes, if none are allowed for this element.
1495   *
1496   * If some are allowed it calls `wp_kses_hair()` to split them further, and then
1497   * it builds up new HTML code from the data that `wp_kses_hair()` returns. It also
1498   * removes `<` and `>` characters, if there are any left. One more thing it does
1499   * is to check if the tag has a closing XHTML slash, and if it does, it puts one
1500   * in the returned code as well.
1501   *
1502   * An array of allowed values can be defined for attributes. If the attribute value
1503   * doesn't fall into the list, the attribute will be removed from the tag.
1504   *
1505   * Attributes can be marked as required. If a required attribute is not present,
1506   * KSES will remove all attributes from the tag. As KSES doesn't match opening and
1507   * closing tags, it's not possible to safely remove the tag itself, the safest
1508   * fallback is to strip all attributes from the tag, instead.
1509   *
1510   * @since 1.0.0
1511   * @since 5.9.0 Added support for an array of allowed values for attributes.
1512   *              Added support for required attributes.
1513   *
1514   * @param string         $element           HTML element/tag.
1515   * @param string         $attr              HTML attributes from HTML element to closing HTML element tag.
1516   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1517   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1518   *                                          for the list of accepted context names.
1519   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1520   * @return string Sanitized HTML element.
1521   */
1522  function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) {
1523      if ( ! is_array( $allowed_html ) ) {
1524          $allowed_html = wp_kses_allowed_html( $allowed_html );
1525      }
1526  
1527      // Is there a closing XHTML slash at the end of the attributes?
1528      $xhtml_slash = '';
1529      if ( preg_match( '%\s*/\s*$%', $attr ) ) {
1530          $xhtml_slash = ' /';
1531      }
1532  
1533      // Are any attributes allowed at all for this element?
1534      $element_low = strtolower( $element );
1535      if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) {
1536          return "<$element$xhtml_slash>";
1537      }
1538  
1539      // Split it.
1540      $attrarr = wp_kses_hair( $attr, $allowed_protocols );
1541  
1542      // Check if there are attributes that are required.
1543      $required_attrs = array_filter(
1544          $allowed_html[ $element_low ],
1545          static function ( $required_attr_limits ) {
1546              return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required'];
1547          }
1548      );
1549  
1550      /*
1551       * If a required attribute check fails, we can return nothing for a self-closing tag,
1552       * but for a non-self-closing tag the best option is to return the element with attributes,
1553       * as KSES doesn't handle matching the relevant closing tag.
1554       */
1555      $stripped_tag = '';
1556      if ( empty( $xhtml_slash ) ) {
1557          $stripped_tag = "<$element>";
1558      }
1559  
1560      // Go through $attrarr, and save the allowed attributes for this element in $attr2.
1561      $attr2 = '';
1562      foreach ( $attrarr as $arreach ) {
1563          // Check if this attribute is required.
1564          $required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1565  
1566          if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
1567              $attr2 .= ' ' . $arreach['whole'];
1568  
1569              // If this was a required attribute, we can mark it as found.
1570              if ( $required ) {
1571                  unset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1572              }
1573          } elseif ( $required ) {
1574              // This attribute was required, but didn't pass the check. The entire tag is not allowed.
1575              return $stripped_tag;
1576          }
1577      }
1578  
1579      // If some required attributes weren't set, the entire tag is not allowed.
1580      if ( ! empty( $required_attrs ) ) {
1581          return $stripped_tag;
1582      }
1583  
1584      // Remove any "<" or ">" characters.
1585      $attr2 = preg_replace( '/[<>]/', '', $attr2 );
1586  
1587      return "<$element$attr2$xhtml_slash>";
1588  }
1589  
1590  /**
1591   * Determines whether an attribute is allowed.
1592   *
1593   * @since 4.2.3
1594   * @since 5.0.0 Added support for `data-*` wildcard attributes.
1595   *
1596   * @param string $name         The attribute name. Passed by reference. Returns empty string when not allowed.
1597   * @param string $value        The attribute value. Passed by reference. Returns a filtered value.
1598   * @param string $whole        The `name=value` input. Passed by reference. Returns filtered input.
1599   * @param string $vless        Whether the attribute is valueless. Use 'y' or 'n'.
1600   * @param string $element      The name of the element to which this attribute belongs.
1601   * @param array  $allowed_html The full list of allowed elements and attributes.
1602   * @return bool Whether or not the attribute is allowed.
1603   */
1604  function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
1605      $name_low    = strtolower( $name );
1606      $element_low = strtolower( $element );
1607  
1608      if ( ! isset( $allowed_html[ $element_low ] ) ) {
1609          $name  = '';
1610          $value = '';
1611          $whole = '';
1612          return false;
1613      }
1614  
1615      $allowed_attr = $allowed_html[ $element_low ];
1616  
1617      if ( ! isset( $allowed_attr[ $name_low ] ) || '' === $allowed_attr[ $name_low ] ) {
1618          /*
1619           * Allow `data-*` attributes.
1620           *
1621           * When specifying `$allowed_html`, the attribute name should be set as
1622           * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
1623           * https://www.w3.org/TR/html40/struct/objects.html#adef-data).
1624           *
1625           * Note: the attribute name should only contain `A-Za-z0-9_-` chars.
1626           */
1627          if ( str_starts_with( $name_low, 'data-' ) && ! empty( $allowed_attr['data-*'] )
1628              && preg_match( '/^data-[a-z0-9_-]+$/', $name_low, $match )
1629          ) {
1630              /*
1631               * Add the whole attribute name to the allowed attributes and set any restrictions
1632               * for the `data-*` attribute values for the current element.
1633               */
1634              $allowed_attr[ $match[0] ] = $allowed_attr['data-*'];
1635          } else {
1636              $name  = '';
1637              $value = '';
1638              $whole = '';
1639              return false;
1640          }
1641      }
1642  
1643      if ( 'style' === $name_low ) {
1644          $decoded_value = WP_HTML_Decoder::decode_attribute( $value );
1645          $new_value     = safecss_filter_attr( $decoded_value );
1646  
1647          if ( empty( $new_value ) ) {
1648              $name  = '';
1649              $value = '';
1650              $whole = '';
1651              return false;
1652          }
1653  
1654          if ( $new_value !== $decoded_value ) {
1655              $encoded_value = esc_attr( $new_value );
1656              $whole         = str_replace( $value, $encoded_value, $whole );
1657              $value         = $encoded_value;
1658          }
1659      }
1660  
1661      if ( is_array( $allowed_attr[ $name_low ] ) ) {
1662          // There are some checks.
1663          foreach ( $allowed_attr[ $name_low ] as $currkey => $currval ) {
1664              if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
1665                  $name  = '';
1666                  $value = '';
1667                  $whole = '';
1668                  return false;
1669              }
1670          }
1671      }
1672  
1673      return true;
1674  }
1675  
1676  /**
1677   * Given a string of HTML attributes and values, parse into a structured attribute list.
1678   *
1679   * This function performs a number of transformations while parsing attribute strings:
1680   *  - It normalizes attribute values and surrounds them with double quotes.
1681   *  - It normalizes HTML character references inside attribute values.
1682   *  - It removes “bad” URL protocols from attribute values.
1683   *
1684   * Otherwise this reads the attributes as if they were part of an HTML tag. It performs
1685   * these transformations to lower the risk of mis-parsing down the line and to perform
1686   * URL sanitization in line with the rest of the `kses` subsystem. Importantly, it does
1687   * not decode the attribute values, meaning that special HTML syntax characters will
1688   * be left with character references in the `value` property.
1689   *
1690   * Example:
1691   *
1692   *     $attrs = wp_kses_hair( 'class="is-wide" inert data-lazy=\'&lt;img&#00062\' =/🐮=/' );
1693   *     $attrs === array(
1694   *         'class'     => array( 'name' => 'class', 'value' => 'is-wide', 'whole' => 'class="is-wide"', 'vless' => 'n' ),
1695   *         'inert'     => array( 'name' => 'inert', 'value' => '', 'whole' => 'inert', 'vless' => 'y' ),
1696   *         'data-lazy' => array( 'name' => 'data-lazy', 'value' => '&lt;img&gt;', 'whole' => 'data-lazy="&lt;img&gt;"', 'vless' => 'n' ),
1697   *         '='         => array( 'name' => '=', 'value' => '', 'whole' => '=', 'vless' => 'y' ),
1698   *         '🐮'        => array( 'name' => '🐮', 'value' => '/', 'whole' => '🐮="/"', 'vless' => 'n' ),
1699   *     );
1700   *
1701   * @since 1.0.0
1702   * @since 7.0.0 Reliably parses HTML via the HTML API.
1703   *
1704   * @param string   $attr              Attribute list from HTML element to closing HTML element tag.
1705   * @param string[] $allowed_protocols Array of allowed URL protocols.
1706   * @return array<string, array{name: string, value: string, whole: string, vless: 'y'|'n'}> Array of attribute information after parsing.
1707   */
1708  function wp_kses_hair( $attr, $allowed_protocols ) {
1709      $attributes = array();
1710      $uris       = wp_kses_uri_attributes();
1711  
1712      $processor = new WP_HTML_Tag_Processor( "<wp {$attr}>" );
1713      $processor->next_token();
1714  
1715      $attribute_names = $processor->get_attribute_names_with_prefix( '' );
1716      if ( null === $attribute_names || 0 === count( $attribute_names ) ) {
1717          return $attributes;
1718      }
1719  
1720      $syntax_characters = array(
1721          '&' => '&amp;',
1722          '<' => '&lt;',
1723          '>' => '&gt;',
1724          "'" => '&apos;',
1725          '"' => '&quot;',
1726      );
1727  
1728      foreach ( $attribute_names as $name ) {
1729          $value   = $processor->get_attribute( $name );
1730          $is_bool = true === $value;
1731          if ( is_string( $value ) && in_array( $name, $uris, true ) ) {
1732              $value = wp_kses_bad_protocol( $value, $allowed_protocols );
1733          }
1734  
1735          // Reconstruct and normalize the attribute value.
1736          $recoded = $is_bool ? '' : strtr( $value, $syntax_characters );
1737          $whole   = $is_bool ? $name : "{$name}=\"{$recoded}\"";
1738  
1739          $attributes[ $name ] = array(
1740              'name'  => $name,
1741              'value' => $recoded,
1742              'whole' => $whole,
1743              'vless' => $is_bool ? 'y' : 'n',
1744          );
1745      }
1746  
1747      return $attributes;
1748  }
1749  
1750  /**
1751   * Finds all attributes of an HTML element.
1752   *
1753   * Does not modify input.  May return "evil" output.
1754   *
1755   * Based on `wp_kses_split2()` and `wp_kses_attr()`.
1756   *
1757   * @since 4.2.3
1758   *
1759   * @param string $element HTML element.
1760   * @return array|false List of attributes found in the element. Returns false on failure.
1761   */
1762  function wp_kses_attr_parse( $element ) {
1763      $valid = preg_match( '%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches );
1764      if ( 1 !== $valid ) {
1765          return false;
1766      }
1767  
1768      $begin  = $matches[1];
1769      $slash  = $matches[2];
1770      $elname = $matches[3];
1771      $attr   = $matches[4];
1772      $end    = $matches[5];
1773  
1774      if ( '' !== $slash ) {
1775          // Closing elements do not get parsed.
1776          return false;
1777      }
1778  
1779      // Is there a closing XHTML slash at the end of the attributes?
1780      if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
1781          $xhtml_slash = $matches[0];
1782          $attr        = substr( $attr, 0, -strlen( $xhtml_slash ) );
1783      } else {
1784          $xhtml_slash = '';
1785      }
1786  
1787      // Split it.
1788      $attrarr = wp_kses_hair_parse( $attr );
1789      if ( false === $attrarr ) {
1790          return false;
1791      }
1792  
1793      // Make sure all input is returned by adding front and back matter.
1794      array_unshift( $attrarr, $begin . $slash . $elname );
1795      array_push( $attrarr, $xhtml_slash . $end );
1796  
1797      return $attrarr;
1798  }
1799  
1800  /**
1801   * Builds an attribute list from string containing attributes.
1802   *
1803   * Does not modify input.  May return "evil" output.
1804   * In case of unexpected input, returns false instead of stripping things.
1805   *
1806   * Based on `wp_kses_hair()` but does not return a multi-dimensional array.
1807   *
1808   * @since 4.2.3
1809   *
1810   * @param string $attr Attribute list from HTML element to closing HTML element tag.
1811   * @return array|false List of attributes found in $attr. Returns false on failure.
1812   */
1813  function wp_kses_hair_parse( $attr ) {
1814      if ( '' === $attr ) {
1815          return array();
1816      }
1817  
1818      $regex =
1819          '(?:
1820                  [_a-zA-Z][-_a-zA-Z0-9:.]* # Attribute name.
1821              |
1822                  \[\[?[^\[\]]+\]\]?        # Shortcode in the name position implies unfiltered_html.
1823          )
1824          (?:                               # Attribute value.
1825              \s*=\s*                       # All values begin with "=".
1826              (?:
1827                  "[^"]*"                   # Double-quoted.
1828              |
1829                  \'[^\']*\'                # Single-quoted.
1830              |
1831                  [^\s"\']+                 # Non-quoted.
1832                  (?:\s|$)                  # Must have a space.
1833              )
1834          |
1835              (?:\s|$)                      # If attribute has no value, space is required.
1836          )
1837          \s*                               # Trailing space is optional except as mentioned above.
1838          ';
1839  
1840      /*
1841       * Although it is possible to reduce this procedure to a single regexp,
1842       * we must run that regexp twice to get exactly the expected result.
1843       *
1844       * Note: do NOT remove the `x` modifiers as they are essential for the above regex!
1845       */
1846  
1847      $validation = "/^($regex)+$/x";
1848      $extraction = "/$regex/x";
1849  
1850      if ( 1 === preg_match( $validation, $attr ) ) {
1851          preg_match_all( $extraction, $attr, $attrarr );
1852          return $attrarr[0];
1853      } else {
1854          return false;
1855      }
1856  }
1857  
1858  /**
1859   * Performs different checks for attribute values.
1860   *
1861   * The currently implemented checks are "maxlen", "minlen", "maxval", "minval",
1862   * and "valueless".
1863   *
1864   * @since 1.0.0
1865   *
1866   * @param string $value      Attribute value.
1867   * @param string $vless      Whether the attribute is valueless. Use 'y' or 'n'.
1868   * @param string $checkname  What $checkvalue is checking for.
1869   * @param mixed  $checkvalue What constraint the value should pass.
1870   * @return bool Whether check passes.
1871   */
1872  function wp_kses_check_attr_val( $value, $vless, $checkname, $checkvalue ) {
1873      $ok = true;
1874  
1875      switch ( strtolower( $checkname ) ) {
1876          case 'maxlen':
1877              /*
1878               * The maxlen check makes sure that the attribute value has a length not
1879               * greater than the given value. This can be used to avoid Buffer Overflows
1880               * in WWW clients and various Internet servers.
1881               */
1882  
1883              if ( strlen( $value ) > $checkvalue ) {
1884                  $ok = false;
1885              }
1886              break;
1887  
1888          case 'minlen':
1889              /*
1890               * The minlen check makes sure that the attribute value has a length not
1891               * smaller than the given value.
1892               */
1893  
1894              if ( strlen( $value ) < $checkvalue ) {
1895                  $ok = false;
1896              }
1897              break;
1898  
1899          case 'maxval':
1900              /*
1901               * The maxval check does two things: it checks that the attribute value is
1902               * an integer from 0 and up, without an excessive amount of zeroes or
1903               * whitespace (to avoid Buffer Overflows). It also checks that the attribute
1904               * value is not greater than the given value.
1905               * This check can be used to avoid Denial of Service attacks.
1906               */
1907  
1908              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1909                  $ok = false;
1910              }
1911              if ( $value > $checkvalue ) {
1912                  $ok = false;
1913              }
1914              break;
1915  
1916          case 'minval':
1917              /*
1918               * The minval check makes sure that the attribute value is a positive integer,
1919               * and that it is not smaller than the given value.
1920               */
1921  
1922              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1923                  $ok = false;
1924              }
1925              if ( $value < $checkvalue ) {
1926                  $ok = false;
1927              }
1928              break;
1929  
1930          case 'valueless':
1931              /*
1932               * The valueless check makes sure if the attribute has a value
1933               * (like `<a href="blah">`) or not (`<option selected>`). If the given value
1934               * is a "y" or a "Y", the attribute must not have a value.
1935               * If the given value is an "n" or an "N", the attribute must have a value.
1936               */
1937  
1938              if ( strtolower( $checkvalue ) !== $vless ) {
1939                  $ok = false;
1940              }
1941              break;
1942  
1943          case 'values':
1944              /*
1945               * The values check is used when you want to make sure that the attribute
1946               * has one of the given values.
1947               */
1948  
1949              if ( ! in_array( strtolower( $value ), $checkvalue, true ) ) {
1950                  $ok = false;
1951              }
1952              break;
1953  
1954          case 'value_callback':
1955              /*
1956               * The value_callback check is used when you want to make sure that the attribute
1957               * value is accepted by the callback function.
1958               */
1959  
1960              if ( ! call_user_func( $checkvalue, $value ) ) {
1961                  $ok = false;
1962              }
1963              break;
1964      } // End switch.
1965  
1966      return $ok;
1967  }
1968  
1969  /**
1970   * Sanitizes a string and removed disallowed URL protocols.
1971   *
1972   * This function removes all non-allowed protocols from the beginning of the
1973   * string. It ignores whitespace and the case of the letters, and it does
1974   * understand HTML entities. It does its work recursively, so it won't be
1975   * fooled by a string like `javascript:javascript:alert(57)`.
1976   *
1977   * @since 1.0.0
1978   *
1979   * @param string   $content           Content to filter bad protocols from.
1980   * @param string[] $allowed_protocols Array of allowed URL protocols.
1981   * @return string Filtered content.
1982   */
1983  function wp_kses_bad_protocol( $content, $allowed_protocols ) {
1984      $content = wp_kses_no_null( $content );
1985  
1986      // Short-circuit if the string starts with `https://` or `http://`. Most common cases.
1987      if (
1988          ( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) ||
1989          ( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) )
1990      ) {
1991          return $content;
1992      }
1993  
1994      $iterations = 0;
1995  
1996      do {
1997          $original_content = $content;
1998          $content          = wp_kses_bad_protocol_once( $content, $allowed_protocols );
1999      } while ( $original_content !== $content && ++$iterations < 6 );
2000  
2001      if ( $original_content !== $content ) {
2002          return '';
2003      }
2004  
2005      return $content;
2006  }
2007  
2008  /**
2009   * Removes any invalid control characters in a text string.
2010   *
2011   * Also removes any instance of the `\0` string.
2012   *
2013   * @since 1.0.0
2014   *
2015   * @param string $content Content to filter null characters from.
2016   * @param array  $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
2017   * @return string Filtered content.
2018   */
2019  function wp_kses_no_null( $content, $options = null ) {
2020      if ( ! isset( $options['slash_zero'] ) ) {
2021          $options = array( 'slash_zero' => 'remove' );
2022      }
2023  
2024      $content = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $content );
2025      if ( 'remove' === $options['slash_zero'] ) {
2026          $content = preg_replace( '/\\\\+0+/', '', $content );
2027      }
2028  
2029      return $content;
2030  }
2031  
2032  /**
2033   * Strips slashes from in front of quotes.
2034   *
2035   * This function changes the character sequence `\"` to just `"`. It leaves all other
2036   * slashes alone. The quoting from `preg_replace(//e)` requires this.
2037   *
2038   * @since 1.0.0
2039   *
2040   * @param string $content String to strip slashes from.
2041   * @return string Fixed string with quoted slashes.
2042   */
2043  function wp_kses_stripslashes( $content ) {
2044      return preg_replace( '%\\\\"%', '"', $content );
2045  }
2046  
2047  /**
2048   * Converts the keys of an array to lowercase.
2049   *
2050   * @since 1.0.0
2051   *
2052   * @param array $inarray Unfiltered array.
2053   * @return array Fixed array with all lowercase keys.
2054   */
2055  function wp_kses_array_lc( $inarray ) {
2056      $outarray = array();
2057  
2058      foreach ( (array) $inarray as $inkey => $inval ) {
2059          $outkey              = strtolower( $inkey );
2060          $outarray[ $outkey ] = array();
2061  
2062          foreach ( (array) $inval as $inkey2 => $inval2 ) {
2063              $outkey2                         = strtolower( $inkey2 );
2064              $outarray[ $outkey ][ $outkey2 ] = $inval2;
2065          }
2066      }
2067  
2068      return $outarray;
2069  }
2070  
2071  /**
2072   * Sanitizes content from bad protocols and other characters.
2073   *
2074   * This function searches for URL protocols at the beginning of the string, while
2075   * handling whitespace and HTML entities.
2076   *
2077   * @since 1.0.0
2078   *
2079   * @param string   $content           Content to check for bad protocols.
2080   * @param string[] $allowed_protocols Array of allowed URL protocols.
2081   * @param int      $count             Depth of call recursion to this function.
2082   * @return string Sanitized content.
2083   */
2084  function wp_kses_bad_protocol_once( $content, $allowed_protocols, $count = 1 ) {
2085      $content  = preg_replace( '/(&#0*58(?![;0-9])|&#x0*3a(?![;a-f0-9]))/i', '$1;', $content );
2086      $content2 = preg_split( '/:|&#0*58;|&#x0*3a;|&colon;/i', $content, 2 );
2087  
2088      if ( isset( $content2[1] ) && ! preg_match( '%/\?%', $content2[0] ) ) {
2089          $content  = trim( $content2[1] );
2090          $protocol = wp_kses_bad_protocol_once2( $content2[0], $allowed_protocols );
2091          if ( 'feed:' === $protocol ) {
2092              if ( $count > 2 ) {
2093                  return '';
2094              }
2095              $content = wp_kses_bad_protocol_once( $content, $allowed_protocols, ++$count );
2096              if ( empty( $content ) ) {
2097                  return $content;
2098              }
2099          }
2100          $content = $protocol . $content;
2101      }
2102  
2103      return $content;
2104  }
2105  
2106  /**
2107   * Callback for `wp_kses_bad_protocol_once()` regular expression.
2108   *
2109   * This function processes URL protocols, checks to see if they're in the
2110   * list of allowed protocols or not, and returns different data depending
2111   * on the answer.
2112   *
2113   * @access private
2114   * @ignore
2115   * @since 1.0.0
2116   *
2117   * @param string   $scheme            URI scheme to check against the list of allowed protocols.
2118   * @param string[] $allowed_protocols Array of allowed URL protocols.
2119   * @return string Sanitized content.
2120   */
2121  function wp_kses_bad_protocol_once2( $scheme, $allowed_protocols ) {
2122      $scheme = wp_kses_decode_entities( $scheme );
2123      $scheme = preg_replace( '/\s/', '', $scheme );
2124      $scheme = wp_kses_no_null( $scheme );
2125      $scheme = strtolower( $scheme );
2126  
2127      $allowed = array_any( (array) $allowed_protocols, fn( $protocol ) => strtolower( $protocol ) === $scheme );
2128  
2129      if ( $allowed ) {
2130          return "$scheme:";
2131      } else {
2132          return '';
2133      }
2134  }
2135  
2136  /**
2137   * Converts and fixes HTML entities.
2138   *
2139   * This function normalizes HTML entities. It will convert `AT&T` to the correct
2140   * `AT&amp;T`, `&#00058;` to `&#058;`, `&#XYZZY;` to `&amp;#XYZZY;` and so on.
2141   *
2142   * When `$context` is set to 'xml', HTML entities are converted to their code points.  For
2143   * example, `AT&T&hellip;&#XYZZY;` is converted to `AT&amp;T…&amp;#XYZZY;`.
2144   *
2145   * @since 1.0.0
2146   * @since 5.5.0 Added `$context` parameter.
2147   *
2148   * @param string $content Content to normalize entities.
2149   * @param string $context Context for normalization. Can be either 'html' or 'xml'.
2150   *                        Default 'html'.
2151   * @return string Content with normalized entities.
2152   */
2153  function wp_kses_normalize_entities( $content, $context = 'html' ) {
2154      // Disarm all entities by converting & to &amp;
2155      $content = str_replace( '&', '&amp;', $content );
2156  
2157      /*
2158       * Decode any character references that are now double-encoded.
2159       *
2160       * It's important that the following normalizations happen in the correct order.
2161       *
2162       * At this point, all `&` have been transformed to `&amp;`. Double-encoded named character
2163       * references like `&amp;amp;` will be decoded back to their single-encoded form `&amp;`.
2164       *
2165       * First, numeric (decimal and hexadecimal) character references must be handled so that
2166       * `&amp;#09;` becomes `&#9;`. If the named character references were handled first, there
2167       * would be no way to know whether the double-encoded character reference had been produced
2168       * in this function or was the original input.
2169       *
2170       * Consider the two examples, first with named entity decoding followed by numeric
2171       * entity decoding. We'll use U+002E FULL STOP (.) in our example, this table follows the
2172       * string processing from left to right:
2173       *
2174       * | Input        | &-encoded        | Named ref double-decoded  | Numeric ref double-decoded |
2175       * | ------------ | ---------------- | ------------------------- | -------------------------- |
2176       * | `&#x2E;`     | `&amp;#x2E;`     | `&amp;#x2E;`              | `&#x2E;`                   |
2177       * | `&amp;#x2E;` | `&amp;amp;#x2E;` | `&amp;#x2E;`              | `&#x2E;`                   |
2178       *
2179       * Notice in the example above that different inputs result in the same result. The second case
2180       * was not normalized and produced HTML that is semantically different from the input.
2181       *
2182       * | Input        | &-encoded        |  Numeric ref double-decoded | Named ref double-decoded |
2183       * | ------------ | ---------------- | --------------------------- | ------------------------ |
2184       * | `&#x2E;`     | `&amp;#x2E;`     | `&#x2E;`                    | `&#x2E;`                 |
2185       * | `&amp;#x2E;` | `&amp;amp;#x2E;` | `&amp;amp;#x2E;`            | `&amp;#x2E;`             |
2186       *
2187       * Here, each input is normalized to an appropriate output.
2188       */
2189      $content = preg_replace_callback( '/&amp;#(0*[1-9][0-9]{0,6});/', 'wp_kses_normalize_entities2', $content );
2190      $content = preg_replace_callback( '/&amp;#[Xx](0*[1-9A-Fa-f][0-9A-Fa-f]{0,5});/', 'wp_kses_normalize_entities3', $content );
2191      if ( 'xml' === $context ) {
2192          $content = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $content );
2193      } else {
2194          $content = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $content );
2195      }
2196  
2197      return $content;
2198  }
2199  
2200  /**
2201   * Callback for `wp_kses_normalize_entities()` regular expression.
2202   *
2203   * This function only accepts valid named entity references, which are finite,
2204   * case-sensitive, and highly scrutinized by HTML and XML validators.
2205   *
2206   * @since 3.0.0
2207   *
2208   * @global array $allowedentitynames
2209   *
2210   * @param array $matches preg_replace_callback() matches array.
2211   * @return string Correctly encoded entity.
2212   */
2213  function wp_kses_named_entities( $matches ) {
2214      global $allowedentitynames;
2215  
2216      if ( empty( $matches[1] ) ) {
2217          return '';
2218      }
2219  
2220      $i = $matches[1];
2221      return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&amp;$i;" : "&$i;";
2222  }
2223  
2224  /**
2225   * Callback for `wp_kses_normalize_entities()` regular expression.
2226   *
2227   * This function only accepts valid named entity references, which are finite,
2228   * case-sensitive, and highly scrutinized by XML validators.  HTML named entity
2229   * references are converted to their code points.
2230   *
2231   * @since 5.5.0
2232   *
2233   * @global array $allowedentitynames
2234   * @global array $allowedxmlentitynames
2235   *
2236   * @param array $matches preg_replace_callback() matches array.
2237   * @return string Correctly encoded entity.
2238   */
2239  function wp_kses_xml_named_entities( $matches ) {
2240      global $allowedentitynames, $allowedxmlentitynames;
2241  
2242      if ( empty( $matches[1] ) ) {
2243          return '';
2244      }
2245  
2246      $i = $matches[1];
2247  
2248      if ( in_array( $i, $allowedxmlentitynames, true ) ) {
2249          return "&$i;";
2250      } elseif ( in_array( $i, $allowedentitynames, true ) ) {
2251          return html_entity_decode( "&$i;", ENT_HTML5 );
2252      }
2253  
2254      return "&amp;$i;";
2255  }
2256  
2257  /**
2258   * Callback for `wp_kses_normalize_entities()` regular expression.
2259   *
2260   * This function helps `wp_kses_normalize_entities()` to only accept 16-bit
2261   * values and nothing more for `&#number;` entities.
2262   *
2263   * @access private
2264   * @ignore
2265   * @since 1.0.0
2266   *
2267   * @param array $matches `preg_replace_callback()` matches array.
2268   * @return string Correctly encoded entity.
2269   */
2270  function wp_kses_normalize_entities2( $matches ) {
2271      if ( empty( $matches[1] ) ) {
2272          return '';
2273      }
2274  
2275      $i = $matches[1];
2276  
2277      if ( valid_unicode( $i ) ) {
2278          $i = str_pad( ltrim( $i, '0' ), 3, '0', STR_PAD_LEFT );
2279          $i = "&#$i;";
2280      } else {
2281          $i = "&amp;#$i;";
2282      }
2283  
2284      return $i;
2285  }
2286  
2287  /**
2288   * Callback for `wp_kses_normalize_entities()` for regular expression.
2289   *
2290   * This function helps `wp_kses_normalize_entities()` to only accept valid Unicode
2291   * numeric entities in hex form.
2292   *
2293   * @since 2.7.0
2294   * @access private
2295   * @ignore
2296   *
2297   * @param array $matches `preg_replace_callback()` matches array.
2298   * @return string Correctly encoded entity.
2299   */
2300  function wp_kses_normalize_entities3( $matches ) {
2301      if ( empty( $matches[1] ) ) {
2302          return '';
2303      }
2304  
2305      $hexchars = $matches[1];
2306  
2307      return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&amp;#x$hexchars;" : '&#x' . ltrim( $hexchars, '0' ) . ';';
2308  }
2309  
2310  /**
2311   * Determines if a Unicode codepoint is valid.
2312   *
2313   * The definition of a valid Unicode codepoint is taken from the XML definition:
2314   *
2315   * > Characters
2316   * >
2317   * > …
2318   * > Legal characters are tab, carriage return, line feed, and the legal characters of
2319   * > Unicode and ISO/IEC 10646.
2320   * > …
2321   * > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
2322   *
2323   * @since 2.7.0
2324   *
2325   * @see https://www.w3.org/TR/xml/#charsets
2326   *
2327   * @param int $i Unicode codepoint.
2328   * @return bool Whether or not the codepoint is a valid Unicode codepoint.
2329   */
2330  function valid_unicode( $i ) {
2331      $i = (int) $i;
2332  
2333      return (
2334          0x9 === $i || // U+0009 HORIZONTAL TABULATION (HT)
2335          0xA === $i || // U+000A LINE FEED (LF)
2336          0xD === $i || // U+000D CARRIAGE RETURN (CR)
2337          /*
2338           * The valid Unicode characters according to the XML specification:
2339           *
2340           * > any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
2341           */
2342          ( 0x20 <= $i && $i <= 0xD7FF ) ||
2343          ( 0xE000 <= $i && $i <= 0xFFFD ) ||
2344          ( 0x10000 <= $i && $i <= 0x10FFFF )
2345      );
2346  }
2347  
2348  /**
2349   * Converts all numeric HTML entities to their named counterparts.
2350   *
2351   * This function decodes numeric HTML entities (`&#65;` and `&#x41;`).
2352   * It doesn't do anything with named entities like `&auml;`, but we don't
2353   * need them in the allowed URL protocols system anyway.
2354   *
2355   * @since 1.0.0
2356   *
2357   * @param string $content Content to change entities.
2358   * @return string Content after decoded entities.
2359   */
2360  function wp_kses_decode_entities( $content ) {
2361      $content = preg_replace_callback( '/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $content );
2362      $content = preg_replace_callback( '/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $content );
2363  
2364      return $content;
2365  }
2366  
2367  /**
2368   * Regex callback for `wp_kses_decode_entities()`.
2369   *
2370   * @since 2.9.0
2371   * @access private
2372   * @ignore
2373   *
2374   * @param array $matches preg match
2375   * @return string
2376   */
2377  function _wp_kses_decode_entities_chr( $matches ) {
2378      return chr( $matches[1] );
2379  }
2380  
2381  /**
2382   * Regex callback for `wp_kses_decode_entities()`.
2383   *
2384   * @since 2.9.0
2385   * @access private
2386   * @ignore
2387   *
2388   * @param array $matches preg match
2389   * @return string
2390   */
2391  function _wp_kses_decode_entities_chr_hexdec( $matches ) {
2392      return chr( hexdec( $matches[1] ) );
2393  }
2394  
2395  /**
2396   * Sanitize content with allowed HTML KSES rules.
2397   *
2398   * This function expects slashed data.
2399   *
2400   * @since 1.0.0
2401   *
2402   * @param string $data Content to filter, expected to be escaped with slashes.
2403   * @return string Filtered content.
2404   */
2405  function wp_filter_kses( $data ) {
2406      return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
2407  }
2408  
2409  /**
2410   * Sanitize content with allowed HTML KSES rules.
2411   *
2412   * This function expects unslashed data.
2413   *
2414   * @since 2.9.0
2415   *
2416   * @param string $data Content to filter, expected to not be escaped.
2417   * @return string Filtered content.
2418   */
2419  function wp_kses_data( $data ) {
2420      return wp_kses( $data, current_filter() );
2421  }
2422  
2423  /**
2424   * Sanitizes content for allowed HTML tags for post content.
2425   *
2426   * Post content refers to the page contents of the 'post' type and not `$_POST`
2427   * data from forms.
2428   *
2429   * This function expects slashed data.
2430   *
2431   * @since 2.0.0
2432   *
2433   * @param string $data Post content to filter, expected to be escaped with slashes.
2434   * @return string Filtered post content with allowed HTML tags and attributes intact.
2435   */
2436  function wp_filter_post_kses( $data ) {
2437      return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
2438  }
2439  
2440  /**
2441   * Sanitizes global styles user content removing unsafe rules.
2442   *
2443   * @since 5.9.0
2444   *
2445   * @param string $data Post content to filter.
2446   * @return string Filtered post content with unsafe rules removed.
2447   */
2448  function wp_filter_global_styles_post( $data ) {
2449      $decoded_data        = json_decode( wp_unslash( $data ), true );
2450      $json_decoding_error = json_last_error();
2451      if (
2452          JSON_ERROR_NONE === $json_decoding_error &&
2453          is_array( $decoded_data ) &&
2454          isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) &&
2455          $decoded_data['isGlobalStylesUserThemeJSON']
2456      ) {
2457          unset( $decoded_data['isGlobalStylesUserThemeJSON'] );
2458  
2459          $data_to_encode = WP_Theme_JSON::remove_insecure_properties( $decoded_data, 'custom' );
2460  
2461          $data_to_encode['isGlobalStylesUserThemeJSON'] = true;
2462          /**
2463           * JSON encode the data stored in post content.
2464           * Escape characters that are likely to be mangled by HTML filters: "<>&".
2465           *
2466           * This matches the escaping in {@see WP_REST_Global_Styles_Controller::prepare_item_for_database()}.
2467           */
2468          return wp_slash( wp_json_encode( $data_to_encode, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) );
2469      }
2470      return $data;
2471  }
2472  
2473  /**
2474   * Sanitizes content for allowed HTML tags for post content.
2475   *
2476   * Post content refers to the page contents of the 'post' type and not `$_POST`
2477   * data from forms.
2478   *
2479   * This function expects unslashed data.
2480   *
2481   * @since 2.9.0
2482   *
2483   * @param string $data Post content to filter.
2484   * @return string Filtered post content with allowed HTML tags and attributes intact.
2485   */
2486  function wp_kses_post( $data ) {
2487      return wp_kses( $data, 'post' );
2488  }
2489  
2490  /**
2491   * Navigates through an array, object, or scalar, and sanitizes content for
2492   * allowed HTML tags for post content.
2493   *
2494   * @since 4.4.2
2495   *
2496   * @see map_deep()
2497   *
2498   * @param mixed $data The array, object, or scalar value to inspect.
2499   * @return mixed The filtered content.
2500   */
2501  function wp_kses_post_deep( $data ) {
2502      return map_deep( $data, 'wp_kses_post' );
2503  }
2504  
2505  /**
2506   * Strips all HTML from a text string.
2507   *
2508   * This function expects slashed data.
2509   *
2510   * @since 2.1.0
2511   *
2512   * @param string $data Content to strip all HTML from.
2513   * @return string Filtered content without any HTML.
2514   */
2515  function wp_filter_nohtml_kses( $data ) {
2516      return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
2517  }
2518  
2519  /**
2520   * Adds all KSES input form content filters.
2521   *
2522   * All hooks have default priority. The `wp_filter_kses()` function is added to
2523   * the 'pre_comment_content' and 'title_save_pre' hooks.
2524   *
2525   * The `wp_filter_post_kses()` function is added to the 'content_save_pre',
2526   * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
2527   *
2528   * @since 2.0.0
2529   */
2530  function kses_init_filters() {
2531      // Normal filtering.
2532      add_filter( 'title_save_pre', 'wp_filter_kses' );
2533  
2534      // Comment filtering.
2535      if ( current_user_can( 'unfiltered_html' ) ) {
2536          add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2537      } else {
2538          add_filter( 'pre_comment_content', 'wp_filter_kses' );
2539      }
2540  
2541      // Global Styles filtering: Global Styles filters should be executed before normal post_kses HTML filters.
2542      add_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2543      add_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2544  
2545      // Post filtering.
2546      add_filter( 'content_save_pre', 'wp_filter_post_kses' );
2547      add_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2548      add_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2549  }
2550  
2551  /**
2552   * Removes all KSES input form content filters.
2553   *
2554   * A quick procedural method to removing all of the filters that KSES uses for
2555   * content in WordPress Loop.
2556   *
2557   * Does not remove the `kses_init()` function from {@see 'init'} hook (priority is
2558   * default). Also does not remove `kses_init()` function from {@see 'set_current_user'}
2559   * hook (priority is also default).
2560   *
2561   * @since 2.0.6
2562   */
2563  function kses_remove_filters() {
2564      // Normal filtering.
2565      remove_filter( 'title_save_pre', 'wp_filter_kses' );
2566  
2567      // Comment filtering.
2568      remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2569      remove_filter( 'pre_comment_content', 'wp_filter_kses' );
2570  
2571      // Global Styles filtering.
2572      remove_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2573      remove_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2574  
2575      // Post filtering.
2576      remove_filter( 'content_save_pre', 'wp_filter_post_kses' );
2577      remove_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2578      remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2579  }
2580  
2581  /**
2582   * Sets up most of the KSES filters for input form content.
2583   *
2584   * First removes all of the KSES filters in case the current user does not need
2585   * to have KSES filter the content. If the user does not have `unfiltered_html`
2586   * capability, then KSES filters are added.
2587   *
2588   * @since 2.0.0
2589   */
2590  function kses_init() {
2591      kses_remove_filters();
2592  
2593      if ( ! current_user_can( 'unfiltered_html' ) ) {
2594          kses_init_filters();
2595      }
2596  }
2597  
2598  /**
2599   * Filters an inline style attribute and removes disallowed rules.
2600   *
2601   * @since 2.8.1
2602   * @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
2603   * @since 4.6.0 Added support for `list-style-type`.
2604   * @since 5.0.0 Added support for `background-image`.
2605   * @since 5.1.0 Added support for `text-transform`.
2606   * @since 5.2.0 Added support for `background-position` and `grid-template-columns`.
2607   * @since 5.3.0 Added support for `grid`, `flex` and `column` layout properties.
2608   *              Extended `background-*` support for individual properties.
2609   * @since 5.3.1 Added support for gradient backgrounds.
2610   * @since 5.7.1 Added support for `object-position`.
2611   * @since 5.8.0 Added support for `calc()` and `var()` values.
2612   * @since 6.1.0 Added support for `min()`, `max()`, `minmax()`, `clamp()`,
2613   *              nested `var()` values, and assigning values to CSS variables.
2614   *              Added support for `object-fit`, `gap`, `column-gap`, `row-gap`, and `flex-wrap`.
2615   *              Extended `margin-*` and `padding-*` support for logical properties.
2616   * @since 6.2.0 Added support for `aspect-ratio`, `position`, `top`, `right`, `bottom`, `left`,
2617   *              and `z-index` CSS properties.
2618   * @since 6.3.0 Extended support for `filter` to accept a URL and added support for repeat().
2619   *              Added support for `box-shadow`.
2620   * @since 6.4.0 Added support for `writing-mode`.
2621   * @since 6.5.0 Added support for `background-repeat`.
2622   * @since 6.6.0 Added support for `grid-column`, `grid-row`, and `container-type`.
2623   * @since 6.9.0 Added support for `white-space`.
2624   * @since 7.1.0 Extended gradient support to allow any single-level nested function.
2625   *              Added support for transform functions, `clip-path` basic shapes,
2626   *              and URLs in the SVG element reference properties.
2627   * @since 7.2.0 Added support for CSS anchor positioning properties and `text-shadow`.
2628   *
2629   * @param string $css        A string of CSS rules, decoded from an HTML `style` attribute.
2630   * @param string $deprecated Not used.
2631   * @return string Filtered string of CSS rules, needing HTML escaping before sending back to a `style` attribute.
2632   */
2633  function safecss_filter_attr( $css, $deprecated = '' ) {
2634      if ( ! empty( $deprecated ) ) {
2635          _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented.
2636      }
2637  
2638      $css = wp_kses_no_null( $css );
2639      $css = str_replace( array( "\n", "\r", "\t" ), '', $css );
2640  
2641      $allowed_protocols = wp_allowed_protocols();
2642  
2643      /** @todo Parse enough CSS to split rules without breaking on things like quoted strings. */
2644      $css_array = explode( ';', trim( $css ) );
2645  
2646      /**
2647       * Filters the list of allowed CSS attributes.
2648       *
2649       * @since 2.8.1
2650       * @since 7.1.0 Added support for SVG presentation attributes.
2651       *
2652       * @param string[] $attr Array of allowed CSS attributes.
2653       */
2654      $allowed_attr = apply_filters(
2655          'safe_style_css',
2656          array(
2657              'background',
2658              'background-color',
2659              'background-image',
2660              'background-position',
2661              'background-repeat',
2662              'background-size',
2663              'background-attachment',
2664              'background-blend-mode',
2665  
2666              'border',
2667              'border-radius',
2668              'border-width',
2669              'border-color',
2670              'border-style',
2671              'border-right',
2672              'border-right-color',
2673              'border-right-style',
2674              'border-right-width',
2675              'border-bottom',
2676              'border-bottom-color',
2677              'border-bottom-left-radius',
2678              'border-bottom-right-radius',
2679              'border-bottom-style',
2680              'border-bottom-width',
2681              'border-bottom-right-radius',
2682              'border-bottom-left-radius',
2683              'border-left',
2684              'border-left-color',
2685              'border-left-style',
2686              'border-left-width',
2687              'border-top',
2688              'border-top-color',
2689              'border-top-left-radius',
2690              'border-top-right-radius',
2691              'border-top-style',
2692              'border-top-width',
2693              'border-top-left-radius',
2694              'border-top-right-radius',
2695  
2696              'border-spacing',
2697              'border-collapse',
2698              'caption-side',
2699  
2700              'columns',
2701              'column-count',
2702              'column-fill',
2703              'column-gap',
2704              'column-rule',
2705              'column-span',
2706              'column-width',
2707  
2708              'display',
2709  
2710              'color',
2711              'filter',
2712              'font',
2713              'font-family',
2714              'font-size',
2715              'font-style',
2716              'font-variant',
2717              'font-weight',
2718              'letter-spacing',
2719              'line-height',
2720              'text-align',
2721              'text-decoration',
2722              'text-indent',
2723              'text-shadow',
2724              'text-transform',
2725              'white-space',
2726  
2727              'height',
2728              'min-height',
2729              'max-height',
2730  
2731              'width',
2732              'min-width',
2733              'max-width',
2734  
2735              'margin',
2736              'margin-right',
2737              'margin-bottom',
2738              'margin-left',
2739              'margin-top',
2740              'margin-block-start',
2741              'margin-block-end',
2742              'margin-inline-start',
2743              'margin-inline-end',
2744  
2745              'padding',
2746              'padding-right',
2747              'padding-bottom',
2748              'padding-left',
2749              'padding-top',
2750              'padding-block-start',
2751              'padding-block-end',
2752              'padding-inline-start',
2753              'padding-inline-end',
2754  
2755              'flex',
2756              'flex-basis',
2757              'flex-direction',
2758              'flex-flow',
2759              'flex-grow',
2760              'flex-shrink',
2761              'flex-wrap',
2762  
2763              'gap',
2764              'column-gap',
2765              'row-gap',
2766  
2767              'grid-template-columns',
2768              'grid-auto-columns',
2769              'grid-column-start',
2770              'grid-column-end',
2771              'grid-column',
2772              'grid-column-gap',
2773              'grid-template-rows',
2774              'grid-auto-rows',
2775              'grid-row-start',
2776              'grid-row-end',
2777              'grid-row',
2778              'grid-row-gap',
2779              'grid-gap',
2780  
2781              'justify-content',
2782              'justify-items',
2783              'justify-self',
2784              'align-content',
2785              'align-items',
2786              'align-self',
2787  
2788              'clear',
2789              'cursor',
2790              'direction',
2791              'float',
2792              'list-style-type',
2793              'object-fit',
2794              'object-position',
2795              'opacity',
2796              'overflow',
2797              'vertical-align',
2798              'writing-mode',
2799  
2800              'position',
2801              'top',
2802              'right',
2803              'bottom',
2804              'left',
2805              'z-index',
2806              'box-shadow',
2807              'aspect-ratio',
2808              'container-type',
2809  
2810              'fill',
2811              'fill-opacity',
2812              'fill-rule',
2813  
2814              'stroke',
2815              'stroke-dasharray',
2816              'stroke-dashoffset',
2817              'stroke-linecap',
2818              'stroke-linejoin',
2819              'stroke-miterlimit',
2820              'stroke-opacity',
2821              'stroke-width',
2822  
2823              'color-interpolation',
2824              'color-interpolation-filters',
2825              'paint-order',
2826              'stop-color',
2827              'stop-opacity',
2828              'flood-color',
2829              'flood-opacity',
2830              'lighting-color',
2831  
2832              'marker',
2833              'marker-end',
2834              'marker-mid',
2835              'marker-start',
2836  
2837              'clip-path',
2838              'clip-rule',
2839              'mask',
2840              'mask-type',
2841  
2842              'cx',
2843              'cy',
2844              'r',
2845              'rx',
2846              'ry',
2847              'x',
2848              'y',
2849              'd',
2850  
2851              'alignment-baseline',
2852              'baseline-shift',
2853              'dominant-baseline',
2854              'glyph-orientation-horizontal',
2855              'glyph-orientation-vertical',
2856              'text-anchor',
2857              'unicode-bidi',
2858              'word-spacing',
2859  
2860              'font-size-adjust',
2861              'font-stretch',
2862  
2863              'color-rendering',
2864              'image-rendering',
2865              'shape-rendering',
2866              'text-rendering',
2867              'vector-effect',
2868  
2869              'transform',
2870              'transform-origin',
2871  
2872              'pointer-events',
2873              'visibility',
2874  
2875              'anchor-name',
2876              'anchor-scope',
2877              'position-anchor',
2878              'position-area',
2879              'position-try',
2880              'position-try-fallbacks',
2881              'position-try-order',
2882              'position-visibility',
2883  
2884              // Custom CSS properties.
2885              '--*',
2886          )
2887      );
2888  
2889      /*
2890       * CSS attributes that accept URL data types.
2891       *
2892       * This is in accordance to the CSS spec and unrelated to
2893       * the sub-set of supported attributes above.
2894       *
2895       * See: https://developer.mozilla.org/en-US/docs/Web/CSS/url
2896       */
2897      $css_url_data_types = array(
2898          'background',
2899          'background-image',
2900  
2901          'cursor',
2902          'filter',
2903  
2904          'list-style',
2905          'list-style-image',
2906  
2907          // SVG presentation properties that accept url() references.
2908          'clip-path',
2909          'fill',
2910          'marker',
2911          'marker-end',
2912          'marker-mid',
2913          'marker-start',
2914          'mask',
2915          'stroke',
2916      );
2917  
2918      /*
2919       * CSS attributes that accept gradient data types.
2920       *
2921       */
2922      $css_gradient_data_types = array(
2923          'background',
2924          'background-image',
2925      );
2926  
2927      if ( empty( $allowed_attr ) ) {
2928          return $css;
2929      }
2930  
2931      $css = '';
2932      foreach ( $css_array as $css_item ) {
2933          if ( '' === $css_item ) {
2934              continue;
2935          }
2936  
2937          $css_item        = trim( $css_item );
2938          $css_test_string = $css_item;
2939          $found           = false;
2940          $url_attr        = false;
2941          $gradient_attr   = false;
2942          $is_custom_var   = false;
2943  
2944          if ( ! str_contains( $css_item, ':' ) ) {
2945              $found = true;
2946          } else {
2947              $parts        = explode( ':', $css_item, 2 );
2948              $css_selector = trim( $parts[0] );
2949  
2950              // Allow assigning values to CSS variables.
2951              if ( in_array( '--*', $allowed_attr, true ) && preg_match( '/^--[a-zA-Z0-9-_]+$/', $css_selector ) ) {
2952                  $allowed_attr[] = $css_selector;
2953                  $is_custom_var  = true;
2954              }
2955  
2956              if ( in_array( $css_selector, $allowed_attr, true ) ) {
2957                  $found         = true;
2958                  $url_attr      = in_array( $css_selector, $css_url_data_types, true );
2959                  $gradient_attr = in_array( $css_selector, $css_gradient_data_types, true );
2960              }
2961  
2962              if ( $is_custom_var ) {
2963                  $css_value     = trim( $parts[1] );
2964                  $url_attr      = str_starts_with( $css_value, 'url(' );
2965                  $gradient_attr = str_contains( $css_value, '-gradient(' );
2966              }
2967          }
2968  
2969          if ( $found && $url_attr ) {
2970              // Simplified: matches the sequence `url(*)`.
2971              preg_match_all( '/url\([^)]+\)/', $parts[1], $url_matches );
2972  
2973              foreach ( $url_matches[0] as $url_match ) {
2974                  // Clean up the URL from each of the matches above.
2975                  preg_match( '/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces );
2976  
2977                  if ( empty( $url_pieces[2] ) ) {
2978                      $found = false;
2979                      break;
2980                  }
2981  
2982                  $url = trim( $url_pieces[2] );
2983  
2984                  if ( empty( $url ) || wp_kses_bad_protocol( $url, $allowed_protocols ) !== $url ) {
2985                      $found = false;
2986                      break;
2987                  } else {
2988                      // Remove the whole `url(*)` bit that was matched above from the CSS.
2989                      $css_test_string = str_replace( $url_match, '', $css_test_string );
2990                  }
2991              }
2992          }
2993  
2994          if ( $found && $gradient_attr ) {
2995              /*
2996               * Match every `*-gradient()` in the value, allowing one level of nested functions
2997               * (e.g. rgb(), hsl(), var()). Matching each occurrence, rather than requiring the
2998               * whole value to be a single gradient, lets a gradient combine with a url() image.
2999               */
3000              preg_match_all( '/(?:repeating-)?(?:linear|radial|conic)-gradient\((?:[^()]|\([^()]*\))*\)/', $css_test_string, $gradient_matches );
3001  
3002              foreach ( $gradient_matches[0] as $gradient_match ) {
3003                  // Remove each `gradient()` bit that was matched above from the CSS.
3004                  $css_test_string = str_replace( $gradient_match, '', $css_test_string );
3005              }
3006          }
3007  
3008          if ( $found ) {
3009              /*
3010               * Allow CSS functions like var(), calc(), etc. by removing them from the test string.
3011               * Nested functions and parentheses are also removed, so long as the parentheses are balanced.
3012               */
3013              $css_test_string = preg_replace(
3014                  '/\b(?:'
3015                      // General purpose value functions.
3016                      . 'var|calc|min|max|minmax|clamp|repeat'
3017                      // Transform functions.
3018                      . '|matrix|matrix3d|perspective'
3019                      . '|rotate|rotate3d|rotateX|rotateY|rotateZ'
3020                      . '|scale|scale3d|scaleX|scaleY|scaleZ'
3021                      . '|skew|skewX|skewY'
3022                      . '|translate|translate3d|translateX|translateY|translateZ'
3023                      // Basic shape functions, as used by `clip-path`.
3024                      . '|circle|ellipse|inset|path|polygon|rect|shape|xywh'
3025                  . ')(\((?:[^()]|(?1))*\))/',
3026                  '',
3027                  $css_test_string
3028              );
3029  
3030              // Bail if the recursive function stripping hit a PCRE error (e.g. stack/backtrack limit).
3031              if ( null === $css_test_string ) {
3032                  continue;
3033              }
3034  
3035              /*
3036               * Disallow CSS containing \ ( & } = or comments, except for within url(), var(), calc(), etc.
3037               * which were removed from the test string above.
3038               */
3039              $allow_css = 0 === preg_match( '%[\\\(&=}]|/\*%', $css_test_string );
3040  
3041              /**
3042               * Filters the check for unsafe CSS in `safecss_filter_attr`.
3043               *
3044               * Enables developers to determine whether a section of CSS should be allowed or discarded.
3045               * By default, the value will be false if the part contains \ ( & } = or comments.
3046               * Return true to allow the CSS part to be included in the output.
3047               *
3048               * @since 5.5.0
3049               *
3050               * @param bool   $allow_css       Whether the CSS in the test string is considered safe.
3051               * @param string $css_test_string The CSS string to test.
3052               */
3053              $allow_css = apply_filters( 'safecss_filter_attr_allow_css', $allow_css, $css_test_string );
3054  
3055              // Only add the CSS part if it passes the regex check.
3056              if ( $allow_css ) {
3057                  if ( '' !== $css ) {
3058                      $css .= ';';
3059                  }
3060  
3061                  $css .= $css_item;
3062              }
3063          }
3064      }
3065  
3066      return $css;
3067  }
3068  
3069  /**
3070   * Helper function to add global attributes to a tag in the allowed HTML list.
3071   *
3072   * @since 3.5.0
3073   * @since 5.0.0 Added support for `data-*` wildcard attributes.
3074   * @since 6.0.0 Added `dir`, `lang`, and `xml:lang` to global attributes.
3075   * @since 6.3.0 Added `aria-controls`, `aria-current`, and `aria-expanded` attributes.
3076   * @since 6.4.0 Added `aria-live` and `hidden` attributes.
3077   * @since 7.1.0 Added `tabindex` attribute.
3078   *
3079   * @access private
3080   * @ignore
3081   *
3082   * @param array $value An array of attributes.
3083   * @return array The array of attributes with global attributes added.
3084   */
3085  function _wp_add_global_attributes( $value ) {
3086      $global_attributes = array(
3087          'aria-controls'    => true,
3088          'aria-current'     => true,
3089          'aria-describedby' => true,
3090          'aria-details'     => true,
3091          'aria-expanded'    => true,
3092          'aria-hidden'      => true,
3093          'aria-label'       => true,
3094          'aria-labelledby'  => true,
3095          'aria-live'        => true,
3096          'class'            => true,
3097          'data-*'           => true,
3098          'dir'              => true,
3099          'hidden'           => true,
3100          'id'               => true,
3101          'lang'             => true,
3102          'style'            => true,
3103          'tabindex'         => true,
3104          'title'            => true,
3105          'role'             => true,
3106          'xml:lang'         => true,
3107      );
3108  
3109      if ( true === $value ) {
3110          $value = array();
3111      }
3112  
3113      if ( is_array( $value ) ) {
3114          return array_merge( $value, $global_attributes );
3115      }
3116  
3117      return $value;
3118  }
3119  
3120  /**
3121   * Helper function to check if this is a safe PDF URL.
3122   *
3123   * @since 5.9.0
3124   * @access private
3125   * @ignore
3126   *
3127   * @param string $url The URL to check.
3128   * @return bool True if the URL is safe, false otherwise.
3129   */
3130  function _wp_kses_allow_pdf_objects( $url ) {
3131      // We're not interested in URLs that contain query strings or fragments.
3132      if ( str_contains( $url, '?' ) || str_contains( $url, '#' ) ) {
3133          return false;
3134      }
3135  
3136      // If it doesn't have a PDF extension, it's not safe.
3137      if ( ! str_ends_with( $url, '.pdf' ) ) {
3138          return false;
3139      }
3140  
3141      // If the URL host matches the current site's media URL, it's safe.
3142      $upload_info = wp_upload_dir( null, false );
3143      $parsed_url  = wp_parse_url( $upload_info['url'] );
3144      $upload_host = $parsed_url['host'] ?? '';
3145      $upload_port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : '';
3146  
3147      if ( str_starts_with( $url, "http://$upload_host$upload_port/" )
3148          || str_starts_with( $url, "https://$upload_host$upload_port/" )
3149      ) {
3150          return true;
3151      }
3152  
3153      return false;
3154  }


Generated : Tue Oct 6 08:20:33 2026 Cross-referenced by PHPXref