[ 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   *
1394   * @return string Fixed HTML element
1395   */
1396  function wp_kses_split2( $content, $allowed_html, $allowed_protocols ) {
1397      $content = wp_kses_stripslashes( $content );
1398  
1399      /*
1400       * The regex pattern used to split HTML into chunks attempts
1401       * to split on HTML token boundaries. This function should
1402       * thus receive chunks that _either_ start with meaningful
1403       * syntax tokens, like a tag `<div>` or a comment `<!-- ... -->`.
1404       *
1405       * If the first character of the `$content` chunk _isn't_ one
1406       * of these syntax elements, which always starts with `<`, then
1407       * the match had to be for the final alternation of `>`. In such
1408       * case, it's probably standing on its own and could be encoded
1409       * with a character reference to remove ambiguity.
1410       *
1411       * In other words, if this chunk isn't from a match of a syntax
1412       * token, it's just a plaintext greater-than (`>`) sign.
1413       */
1414      if ( ! str_starts_with( $content, '<' ) ) {
1415          return '&gt;';
1416      }
1417  
1418      /*
1419       * When certain invalid syntax constructs appear, the HTML parser
1420       * shifts into what's called the "bogus comment state." This is a
1421       * plaintext state that consumes everything until the nearest `>`
1422       * and then transforms the entire span into an HTML comment.
1423       *
1424       * Preserve these comments and do not treat them like tags.
1425       *
1426       * @see https://html.spec.whatwg.org/#bogus-comment-state
1427       */
1428      if ( 1 === preg_match( '~^(?:</[^a-zA-Z][^>]*>|<![a-z][^>]*>)$~', $content ) ) {
1429          /**
1430           * Since the pattern matches `</…>` and also `<!…>`, this will
1431           * preserve the type of the cleaned-up token in the output.
1432           */
1433          $opener  = $content[1];
1434          $content = substr( $content, 2, -1 );
1435  
1436          do {
1437              $prev    = $content;
1438              $content = wp_kses( $content, $allowed_html, $allowed_protocols );
1439          } while ( $prev !== $content );
1440  
1441          // Recombine the modified inner content with the original token structure.
1442          return "<{$opener}{$content}>";
1443      }
1444  
1445      /*
1446       * Normative HTML comments should be handled separately as their
1447       * parsing rules differ from those for tags and text nodes.
1448       */
1449      if ( str_starts_with( $content, '<!--' ) ) {
1450          $content = str_replace( array( '<!--', '-->' ), '', $content );
1451  
1452          while ( ( $newstring = wp_kses( $content, $allowed_html, $allowed_protocols ) ) !== $content ) {
1453              $content = $newstring;
1454          }
1455  
1456          if ( '' === $content ) {
1457              return '';
1458          }
1459  
1460          // Prevent multiple dashes in comments.
1461          $content = preg_replace( '/--+/', '-', $content );
1462          // Prevent three dashes closing a comment.
1463          $content = preg_replace( '/-$/', '', $content );
1464  
1465          return "<!--{$content}-->";
1466      }
1467  
1468      // It's seriously malformed.
1469      if ( ! preg_match( '%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $content, $matches ) ) {
1470          return '';
1471      }
1472  
1473      $slash    = trim( $matches[1] );
1474      $elem     = $matches[2];
1475      $attrlist = $matches[3];
1476  
1477      if ( ! is_array( $allowed_html ) ) {
1478          $allowed_html = wp_kses_allowed_html( $allowed_html );
1479      }
1480  
1481      // They are using a not allowed HTML element.
1482      if ( ! isset( $allowed_html[ strtolower( $elem ) ] ) ) {
1483          return '';
1484      }
1485  
1486      // No attributes are allowed for closing elements.
1487      if ( '' !== $slash ) {
1488          return "</$elem>";
1489      }
1490  
1491      return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
1492  }
1493  
1494  /**
1495   * Removes all attributes, if none are allowed for this element.
1496   *
1497   * If some are allowed it calls `wp_kses_hair()` to split them further, and then
1498   * it builds up new HTML code from the data that `wp_kses_hair()` returns. It also
1499   * removes `<` and `>` characters, if there are any left. One more thing it does
1500   * is to check if the tag has a closing XHTML slash, and if it does, it puts one
1501   * in the returned code as well.
1502   *
1503   * An array of allowed values can be defined for attributes. If the attribute value
1504   * doesn't fall into the list, the attribute will be removed from the tag.
1505   *
1506   * Attributes can be marked as required. If a required attribute is not present,
1507   * KSES will remove all attributes from the tag. As KSES doesn't match opening and
1508   * closing tags, it's not possible to safely remove the tag itself, the safest
1509   * fallback is to strip all attributes from the tag, instead.
1510   *
1511   * @since 1.0.0
1512   * @since 5.9.0 Added support for an array of allowed values for attributes.
1513   *              Added support for required attributes.
1514   *
1515   * @param string         $element           HTML element/tag.
1516   * @param string         $attr              HTML attributes from HTML element to closing HTML element tag.
1517   * @param array[]|string $allowed_html      An array of allowed HTML elements and attributes,
1518   *                                          or a context name such as 'post'. See wp_kses_allowed_html()
1519   *                                          for the list of accepted context names.
1520   * @param string[]       $allowed_protocols Array of allowed URL protocols.
1521   * @return string Sanitized HTML element.
1522   */
1523  function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) {
1524      if ( ! is_array( $allowed_html ) ) {
1525          $allowed_html = wp_kses_allowed_html( $allowed_html );
1526      }
1527  
1528      // Is there a closing XHTML slash at the end of the attributes?
1529      $xhtml_slash = '';
1530      if ( preg_match( '%\s*/\s*$%', $attr ) ) {
1531          $xhtml_slash = ' /';
1532      }
1533  
1534      // Are any attributes allowed at all for this element?
1535      $element_low = strtolower( $element );
1536      if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) {
1537          return "<$element$xhtml_slash>";
1538      }
1539  
1540      // Split it.
1541      $attrarr = wp_kses_hair( $attr, $allowed_protocols );
1542  
1543      // Check if there are attributes that are required.
1544      $required_attrs = array_filter(
1545          $allowed_html[ $element_low ],
1546          static function ( $required_attr_limits ) {
1547              return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required'];
1548          }
1549      );
1550  
1551      /*
1552       * If a required attribute check fails, we can return nothing for a self-closing tag,
1553       * but for a non-self-closing tag the best option is to return the element with attributes,
1554       * as KSES doesn't handle matching the relevant closing tag.
1555       */
1556      $stripped_tag = '';
1557      if ( empty( $xhtml_slash ) ) {
1558          $stripped_tag = "<$element>";
1559      }
1560  
1561      // Go through $attrarr, and save the allowed attributes for this element in $attr2.
1562      $attr2 = '';
1563      foreach ( $attrarr as $arreach ) {
1564          // Check if this attribute is required.
1565          $required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1566  
1567          if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
1568              $attr2 .= ' ' . $arreach['whole'];
1569  
1570              // If this was a required attribute, we can mark it as found.
1571              if ( $required ) {
1572                  unset( $required_attrs[ strtolower( $arreach['name'] ) ] );
1573              }
1574          } elseif ( $required ) {
1575              // This attribute was required, but didn't pass the check. The entire tag is not allowed.
1576              return $stripped_tag;
1577          }
1578      }
1579  
1580      // If some required attributes weren't set, the entire tag is not allowed.
1581      if ( ! empty( $required_attrs ) ) {
1582          return $stripped_tag;
1583      }
1584  
1585      // Remove any "<" or ">" characters.
1586      $attr2 = preg_replace( '/[<>]/', '', $attr2 );
1587  
1588      return "<$element$attr2$xhtml_slash>";
1589  }
1590  
1591  /**
1592   * Determines whether an attribute is allowed.
1593   *
1594   * @since 4.2.3
1595   * @since 5.0.0 Added support for `data-*` wildcard attributes.
1596   *
1597   * @param string $name         The attribute name. Passed by reference. Returns empty string when not allowed.
1598   * @param string $value        The attribute value. Passed by reference. Returns a filtered value.
1599   * @param string $whole        The `name=value` input. Passed by reference. Returns filtered input.
1600   * @param string $vless        Whether the attribute is valueless. Use 'y' or 'n'.
1601   * @param string $element      The name of the element to which this attribute belongs.
1602   * @param array  $allowed_html The full list of allowed elements and attributes.
1603   * @return bool Whether or not the attribute is allowed.
1604   */
1605  function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
1606      $name_low    = strtolower( $name );
1607      $element_low = strtolower( $element );
1608  
1609      if ( ! isset( $allowed_html[ $element_low ] ) ) {
1610          $name  = '';
1611          $value = '';
1612          $whole = '';
1613          return false;
1614      }
1615  
1616      $allowed_attr = $allowed_html[ $element_low ];
1617  
1618      if ( ! isset( $allowed_attr[ $name_low ] ) || '' === $allowed_attr[ $name_low ] ) {
1619          /*
1620           * Allow `data-*` attributes.
1621           *
1622           * When specifying `$allowed_html`, the attribute name should be set as
1623           * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
1624           * https://www.w3.org/TR/html40/struct/objects.html#adef-data).
1625           *
1626           * Note: the attribute name should only contain `A-Za-z0-9_-` chars.
1627           */
1628          if ( str_starts_with( $name_low, 'data-' ) && ! empty( $allowed_attr['data-*'] )
1629              && preg_match( '/^data-[a-z0-9_-]+$/', $name_low, $match )
1630          ) {
1631              /*
1632               * Add the whole attribute name to the allowed attributes and set any restrictions
1633               * for the `data-*` attribute values for the current element.
1634               */
1635              $allowed_attr[ $match[0] ] = $allowed_attr['data-*'];
1636          } else {
1637              $name  = '';
1638              $value = '';
1639              $whole = '';
1640              return false;
1641          }
1642      }
1643  
1644      if ( 'style' === $name_low ) {
1645          $decoded_value = WP_HTML_Decoder::decode_attribute( $value );
1646          $new_value     = safecss_filter_attr( $decoded_value );
1647  
1648          if ( empty( $new_value ) ) {
1649              $name  = '';
1650              $value = '';
1651              $whole = '';
1652              return false;
1653          }
1654  
1655          if ( $new_value !== $decoded_value ) {
1656              $encoded_value = esc_attr( $new_value );
1657              $whole         = str_replace( $value, $encoded_value, $whole );
1658              $value         = $encoded_value;
1659          }
1660      }
1661  
1662      if ( is_array( $allowed_attr[ $name_low ] ) ) {
1663          // There are some checks.
1664          foreach ( $allowed_attr[ $name_low ] as $currkey => $currval ) {
1665              if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
1666                  $name  = '';
1667                  $value = '';
1668                  $whole = '';
1669                  return false;
1670              }
1671          }
1672      }
1673  
1674      return true;
1675  }
1676  
1677  /**
1678   * Given a string of HTML attributes and values, parse into a structured attribute list.
1679   *
1680   * This function performs a number of transformations while parsing attribute strings:
1681   *  - It normalizes attribute values and surrounds them with double quotes.
1682   *  - It normalizes HTML character references inside attribute values.
1683   *  - It removes “bad” URL protocols from attribute values.
1684   *
1685   * Otherwise this reads the attributes as if they were part of an HTML tag. It performs
1686   * these transformations to lower the risk of mis-parsing down the line and to perform
1687   * URL sanitization in line with the rest of the `kses` subsystem. Importantly, it does
1688   * not decode the attribute values, meaning that special HTML syntax characters will
1689   * be left with character references in the `value` property.
1690   *
1691   * Example:
1692   *
1693   *     $attrs = wp_kses_hair( 'class="is-wide" inert data-lazy=\'&lt;img&#00062\' =/🐮=/' );
1694   *     $attrs === array(
1695   *         'class'     => array( 'name' => 'class', 'value' => 'is-wide', 'whole' => 'class="is-wide"', 'vless' => 'n' ),
1696   *         'inert'     => array( 'name' => 'inert', 'value' => '', 'whole' => 'inert', 'vless' => 'y' ),
1697   *         'data-lazy' => array( 'name' => 'data-lazy', 'value' => '&lt;img&gt;', 'whole' => 'data-lazy="&lt;img&gt;"', 'vless' => 'n' ),
1698   *         '='         => array( 'name' => '=', 'value' => '', 'whole' => '=', 'vless' => 'y' ),
1699   *         '🐮'        => array( 'name' => '🐮', 'value' => '/', 'whole' => '🐮="/"', 'vless' => 'n' ),
1700   *     );
1701   *
1702   * @since 1.0.0
1703   * @since 7.0.0 Reliably parses HTML via the HTML API.
1704   *
1705   * @param string   $attr              Attribute list from HTML element to closing HTML element tag.
1706   * @param string[] $allowed_protocols Array of allowed URL protocols.
1707   * @return array<string, array{name: string, value: string, whole: string, vless: 'y'|'n'}> Array of attribute information after parsing.
1708   */
1709  function wp_kses_hair( $attr, $allowed_protocols ) {
1710      $attributes = array();
1711      $uris       = wp_kses_uri_attributes();
1712  
1713      $processor = new WP_HTML_Tag_Processor( "<wp {$attr}>" );
1714      $processor->next_token();
1715  
1716      $attribute_names = $processor->get_attribute_names_with_prefix( '' );
1717      if ( null === $attribute_names || 0 === count( $attribute_names ) ) {
1718          return $attributes;
1719      }
1720  
1721      $syntax_characters = array(
1722          '&' => '&amp;',
1723          '<' => '&lt;',
1724          '>' => '&gt;',
1725          "'" => '&apos;',
1726          '"' => '&quot;',
1727      );
1728  
1729      foreach ( $attribute_names as $name ) {
1730          $value   = $processor->get_attribute( $name );
1731          $is_bool = true === $value;
1732          if ( is_string( $value ) && in_array( $name, $uris, true ) ) {
1733              $value = wp_kses_bad_protocol( $value, $allowed_protocols );
1734          }
1735  
1736          // Reconstruct and normalize the attribute value.
1737          $recoded = $is_bool ? '' : strtr( $value, $syntax_characters );
1738          $whole   = $is_bool ? $name : "{$name}=\"{$recoded}\"";
1739  
1740          $attributes[ $name ] = array(
1741              'name'  => $name,
1742              'value' => $recoded,
1743              'whole' => $whole,
1744              'vless' => $is_bool ? 'y' : 'n',
1745          );
1746      }
1747  
1748      return $attributes;
1749  }
1750  
1751  /**
1752   * Finds all attributes of an HTML element.
1753   *
1754   * Does not modify input.  May return "evil" output.
1755   *
1756   * Based on `wp_kses_split2()` and `wp_kses_attr()`.
1757   *
1758   * @since 4.2.3
1759   *
1760   * @param string $element HTML element.
1761   * @return array|false List of attributes found in the element. Returns false on failure.
1762   */
1763  function wp_kses_attr_parse( $element ) {
1764      $valid = preg_match( '%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches );
1765      if ( 1 !== $valid ) {
1766          return false;
1767      }
1768  
1769      $begin  = $matches[1];
1770      $slash  = $matches[2];
1771      $elname = $matches[3];
1772      $attr   = $matches[4];
1773      $end    = $matches[5];
1774  
1775      if ( '' !== $slash ) {
1776          // Closing elements do not get parsed.
1777          return false;
1778      }
1779  
1780      // Is there a closing XHTML slash at the end of the attributes?
1781      if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
1782          $xhtml_slash = $matches[0];
1783          $attr        = substr( $attr, 0, -strlen( $xhtml_slash ) );
1784      } else {
1785          $xhtml_slash = '';
1786      }
1787  
1788      // Split it.
1789      $attrarr = wp_kses_hair_parse( $attr );
1790      if ( false === $attrarr ) {
1791          return false;
1792      }
1793  
1794      // Make sure all input is returned by adding front and back matter.
1795      array_unshift( $attrarr, $begin . $slash . $elname );
1796      array_push( $attrarr, $xhtml_slash . $end );
1797  
1798      return $attrarr;
1799  }
1800  
1801  /**
1802   * Builds an attribute list from string containing attributes.
1803   *
1804   * Does not modify input.  May return "evil" output.
1805   * In case of unexpected input, returns false instead of stripping things.
1806   *
1807   * Based on `wp_kses_hair()` but does not return a multi-dimensional array.
1808   *
1809   * @since 4.2.3
1810   *
1811   * @param string $attr Attribute list from HTML element to closing HTML element tag.
1812   * @return array|false List of attributes found in $attr. Returns false on failure.
1813   */
1814  function wp_kses_hair_parse( $attr ) {
1815      if ( '' === $attr ) {
1816          return array();
1817      }
1818  
1819      $regex =
1820          '(?:
1821                  [_a-zA-Z][-_a-zA-Z0-9:.]* # Attribute name.
1822              |
1823                  \[\[?[^\[\]]+\]\]?        # Shortcode in the name position implies unfiltered_html.
1824          )
1825          (?:                               # Attribute value.
1826              \s*=\s*                       # All values begin with "=".
1827              (?:
1828                  "[^"]*"                   # Double-quoted.
1829              |
1830                  \'[^\']*\'                # Single-quoted.
1831              |
1832                  [^\s"\']+                 # Non-quoted.
1833                  (?:\s|$)                  # Must have a space.
1834              )
1835          |
1836              (?:\s|$)                      # If attribute has no value, space is required.
1837          )
1838          \s*                               # Trailing space is optional except as mentioned above.
1839          ';
1840  
1841      /*
1842       * Although it is possible to reduce this procedure to a single regexp,
1843       * we must run that regexp twice to get exactly the expected result.
1844       *
1845       * Note: do NOT remove the `x` modifiers as they are essential for the above regex!
1846       */
1847  
1848      $validation = "/^($regex)+$/x";
1849      $extraction = "/$regex/x";
1850  
1851      if ( 1 === preg_match( $validation, $attr ) ) {
1852          preg_match_all( $extraction, $attr, $attrarr );
1853          return $attrarr[0];
1854      } else {
1855          return false;
1856      }
1857  }
1858  
1859  /**
1860   * Performs different checks for attribute values.
1861   *
1862   * The currently implemented checks are "maxlen", "minlen", "maxval", "minval",
1863   * and "valueless".
1864   *
1865   * @since 1.0.0
1866   *
1867   * @param string $value      Attribute value.
1868   * @param string $vless      Whether the attribute is valueless. Use 'y' or 'n'.
1869   * @param string $checkname  What $checkvalue is checking for.
1870   * @param mixed  $checkvalue What constraint the value should pass.
1871   * @return bool Whether check passes.
1872   */
1873  function wp_kses_check_attr_val( $value, $vless, $checkname, $checkvalue ) {
1874      $ok = true;
1875  
1876      switch ( strtolower( $checkname ) ) {
1877          case 'maxlen':
1878              /*
1879               * The maxlen check makes sure that the attribute value has a length not
1880               * greater than the given value. This can be used to avoid Buffer Overflows
1881               * in WWW clients and various Internet servers.
1882               */
1883  
1884              if ( strlen( $value ) > $checkvalue ) {
1885                  $ok = false;
1886              }
1887              break;
1888  
1889          case 'minlen':
1890              /*
1891               * The minlen check makes sure that the attribute value has a length not
1892               * smaller than the given value.
1893               */
1894  
1895              if ( strlen( $value ) < $checkvalue ) {
1896                  $ok = false;
1897              }
1898              break;
1899  
1900          case 'maxval':
1901              /*
1902               * The maxval check does two things: it checks that the attribute value is
1903               * an integer from 0 and up, without an excessive amount of zeroes or
1904               * whitespace (to avoid Buffer Overflows). It also checks that the attribute
1905               * value is not greater than the given value.
1906               * This check can be used to avoid Denial of Service attacks.
1907               */
1908  
1909              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1910                  $ok = false;
1911              }
1912              if ( $value > $checkvalue ) {
1913                  $ok = false;
1914              }
1915              break;
1916  
1917          case 'minval':
1918              /*
1919               * The minval check makes sure that the attribute value is a positive integer,
1920               * and that it is not smaller than the given value.
1921               */
1922  
1923              if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
1924                  $ok = false;
1925              }
1926              if ( $value < $checkvalue ) {
1927                  $ok = false;
1928              }
1929              break;
1930  
1931          case 'valueless':
1932              /*
1933               * The valueless check makes sure if the attribute has a value
1934               * (like `<a href="blah">`) or not (`<option selected>`). If the given value
1935               * is a "y" or a "Y", the attribute must not have a value.
1936               * If the given value is an "n" or an "N", the attribute must have a value.
1937               */
1938  
1939              if ( strtolower( $checkvalue ) !== $vless ) {
1940                  $ok = false;
1941              }
1942              break;
1943  
1944          case 'values':
1945              /*
1946               * The values check is used when you want to make sure that the attribute
1947               * has one of the given values.
1948               */
1949  
1950              if ( ! in_array( strtolower( $value ), $checkvalue, true ) ) {
1951                  $ok = false;
1952              }
1953              break;
1954  
1955          case 'value_callback':
1956              /*
1957               * The value_callback check is used when you want to make sure that the attribute
1958               * value is accepted by the callback function.
1959               */
1960  
1961              if ( ! call_user_func( $checkvalue, $value ) ) {
1962                  $ok = false;
1963              }
1964              break;
1965      } // End switch.
1966  
1967      return $ok;
1968  }
1969  
1970  /**
1971   * Sanitizes a string and removed disallowed URL protocols.
1972   *
1973   * This function removes all non-allowed protocols from the beginning of the
1974   * string. It ignores whitespace and the case of the letters, and it does
1975   * understand HTML entities. It does its work recursively, so it won't be
1976   * fooled by a string like `javascript:javascript:alert(57)`.
1977   *
1978   * @since 1.0.0
1979   *
1980   * @param string   $content           Content to filter bad protocols from.
1981   * @param string[] $allowed_protocols Array of allowed URL protocols.
1982   * @return string Filtered content.
1983   */
1984  function wp_kses_bad_protocol( $content, $allowed_protocols ) {
1985      $content = wp_kses_no_null( $content );
1986  
1987      // Short-circuit if the string starts with `https://` or `http://`. Most common cases.
1988      if (
1989          ( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) ||
1990          ( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) )
1991      ) {
1992          return $content;
1993      }
1994  
1995      $iterations = 0;
1996  
1997      do {
1998          $original_content = $content;
1999          $content          = wp_kses_bad_protocol_once( $content, $allowed_protocols );
2000      } while ( $original_content !== $content && ++$iterations < 6 );
2001  
2002      if ( $original_content !== $content ) {
2003          return '';
2004      }
2005  
2006      return $content;
2007  }
2008  
2009  /**
2010   * Removes any invalid control characters in a text string.
2011   *
2012   * Also removes any instance of the `\0` string.
2013   *
2014   * @since 1.0.0
2015   *
2016   * @param string $content Content to filter null characters from.
2017   * @param array  $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
2018   * @return string Filtered content.
2019   */
2020  function wp_kses_no_null( $content, $options = null ) {
2021      if ( ! isset( $options['slash_zero'] ) ) {
2022          $options = array( 'slash_zero' => 'remove' );
2023      }
2024  
2025      $content = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $content );
2026      if ( 'remove' === $options['slash_zero'] ) {
2027          $content = preg_replace( '/\\\\+0+/', '', $content );
2028      }
2029  
2030      return $content;
2031  }
2032  
2033  /**
2034   * Strips slashes from in front of quotes.
2035   *
2036   * This function changes the character sequence `\"` to just `"`. It leaves all other
2037   * slashes alone. The quoting from `preg_replace(//e)` requires this.
2038   *
2039   * @since 1.0.0
2040   *
2041   * @param string $content String to strip slashes from.
2042   * @return string Fixed string with quoted slashes.
2043   */
2044  function wp_kses_stripslashes( $content ) {
2045      return preg_replace( '%\\\\"%', '"', $content );
2046  }
2047  
2048  /**
2049   * Converts the keys of an array to lowercase.
2050   *
2051   * @since 1.0.0
2052   *
2053   * @param array $inarray Unfiltered array.
2054   * @return array Fixed array with all lowercase keys.
2055   */
2056  function wp_kses_array_lc( $inarray ) {
2057      $outarray = array();
2058  
2059      foreach ( (array) $inarray as $inkey => $inval ) {
2060          $outkey              = strtolower( $inkey );
2061          $outarray[ $outkey ] = array();
2062  
2063          foreach ( (array) $inval as $inkey2 => $inval2 ) {
2064              $outkey2                         = strtolower( $inkey2 );
2065              $outarray[ $outkey ][ $outkey2 ] = $inval2;
2066          }
2067      }
2068  
2069      return $outarray;
2070  }
2071  
2072  /**
2073   * Handles parsing errors in `wp_kses_hair()`.
2074   *
2075   * The general plan is to remove everything to and including some whitespace,
2076   * but it deals with quotes and apostrophes as well.
2077   *
2078   * @since 1.0.0
2079   *
2080   * @param string $attr
2081   * @return string
2082   */
2083  function wp_kses_html_error( $attr ) {
2084      return preg_replace( '/^("[^"]*("|$)|\'[^\']*(\'|$)|\S)*\s*/', '', $attr );
2085  }
2086  
2087  /**
2088   * Sanitizes content from bad protocols and other characters.
2089   *
2090   * This function searches for URL protocols at the beginning of the string, while
2091   * handling whitespace and HTML entities.
2092   *
2093   * @since 1.0.0
2094   *
2095   * @param string   $content           Content to check for bad protocols.
2096   * @param string[] $allowed_protocols Array of allowed URL protocols.
2097   * @param int      $count             Depth of call recursion to this function.
2098   * @return string Sanitized content.
2099   */
2100  function wp_kses_bad_protocol_once( $content, $allowed_protocols, $count = 1 ) {
2101      $content  = preg_replace( '/(&#0*58(?![;0-9])|&#x0*3a(?![;a-f0-9]))/i', '$1;', $content );
2102      $content2 = preg_split( '/:|&#0*58;|&#x0*3a;|&colon;/i', $content, 2 );
2103  
2104      if ( isset( $content2[1] ) && ! preg_match( '%/\?%', $content2[0] ) ) {
2105          $content  = trim( $content2[1] );
2106          $protocol = wp_kses_bad_protocol_once2( $content2[0], $allowed_protocols );
2107          if ( 'feed:' === $protocol ) {
2108              if ( $count > 2 ) {
2109                  return '';
2110              }
2111              $content = wp_kses_bad_protocol_once( $content, $allowed_protocols, ++$count );
2112              if ( empty( $content ) ) {
2113                  return $content;
2114              }
2115          }
2116          $content = $protocol . $content;
2117      }
2118  
2119      return $content;
2120  }
2121  
2122  /**
2123   * Callback for `wp_kses_bad_protocol_once()` regular expression.
2124   *
2125   * This function processes URL protocols, checks to see if they're in the
2126   * list of allowed protocols or not, and returns different data depending
2127   * on the answer.
2128   *
2129   * @access private
2130   * @ignore
2131   * @since 1.0.0
2132   *
2133   * @param string   $scheme            URI scheme to check against the list of allowed protocols.
2134   * @param string[] $allowed_protocols Array of allowed URL protocols.
2135   * @return string Sanitized content.
2136   */
2137  function wp_kses_bad_protocol_once2( $scheme, $allowed_protocols ) {
2138      $scheme = wp_kses_decode_entities( $scheme );
2139      $scheme = preg_replace( '/\s/', '', $scheme );
2140      $scheme = wp_kses_no_null( $scheme );
2141      $scheme = strtolower( $scheme );
2142  
2143      $allowed = array_any( (array) $allowed_protocols, fn( $protocol ) => strtolower( $protocol ) === $scheme );
2144  
2145      if ( $allowed ) {
2146          return "$scheme:";
2147      } else {
2148          return '';
2149      }
2150  }
2151  
2152  /**
2153   * Converts and fixes HTML entities.
2154   *
2155   * This function normalizes HTML entities. It will convert `AT&T` to the correct
2156   * `AT&amp;T`, `&#00058;` to `&#058;`, `&#XYZZY;` to `&amp;#XYZZY;` and so on.
2157   *
2158   * When `$context` is set to 'xml', HTML entities are converted to their code points.  For
2159   * example, `AT&T&hellip;&#XYZZY;` is converted to `AT&amp;T…&amp;#XYZZY;`.
2160   *
2161   * @since 1.0.0
2162   * @since 5.5.0 Added `$context` parameter.
2163   *
2164   * @param string $content Content to normalize entities.
2165   * @param string $context Context for normalization. Can be either 'html' or 'xml'.
2166   *                        Default 'html'.
2167   * @return string Content with normalized entities.
2168   */
2169  function wp_kses_normalize_entities( $content, $context = 'html' ) {
2170      // Disarm all entities by converting & to &amp;
2171      $content = str_replace( '&', '&amp;', $content );
2172  
2173      /*
2174       * Decode any character references that are now double-encoded.
2175       *
2176       * It's important that the following normalizations happen in the correct order.
2177       *
2178       * At this point, all `&` have been transformed to `&amp;`. Double-encoded named character
2179       * references like `&amp;amp;` will be decoded back to their single-encoded form `&amp;`.
2180       *
2181       * First, numeric (decimal and hexadecimal) character references must be handled so that
2182       * `&amp;#09;` becomes `&#9;`. If the named character references were handled first, there
2183       * would be no way to know whether the double-encoded character reference had been produced
2184       * in this function or was the original input.
2185       *
2186       * Consider the two examples, first with named entity decoding followed by numeric
2187       * entity decoding. We'll use U+002E FULL STOP (.) in our example, this table follows the
2188       * string processing from left to right:
2189       *
2190       * | Input        | &-encoded        | Named ref double-decoded  | Numeric ref double-decoded |
2191       * | ------------ | ---------------- | ------------------------- | -------------------------- |
2192       * | `&#x2E;`     | `&amp;#x2E;`     | `&amp;#x2E;`              | `&#x2E;`                   |
2193       * | `&amp;#x2E;` | `&amp;amp;#x2E;` | `&amp;#x2E;`              | `&#x2E;`                   |
2194       *
2195       * Notice in the example above that different inputs result in the same result. The second case
2196       * was not normalized and produced HTML that is semantically different from the input.
2197       *
2198       * | Input        | &-encoded        |  Numeric ref double-decoded | Named ref double-decoded |
2199       * | ------------ | ---------------- | --------------------------- | ------------------------ |
2200       * | `&#x2E;`     | `&amp;#x2E;`     | `&#x2E;`                    | `&#x2E;`                 |
2201       * | `&amp;#x2E;` | `&amp;amp;#x2E;` | `&amp;amp;#x2E;`            | `&amp;#x2E;`             |
2202       *
2203       * Here, each input is normalized to an appropriate output.
2204       */
2205      $content = preg_replace_callback( '/&amp;#(0*[1-9][0-9]{0,6});/', 'wp_kses_normalize_entities2', $content );
2206      $content = preg_replace_callback( '/&amp;#[Xx](0*[1-9A-Fa-f][0-9A-Fa-f]{0,5});/', 'wp_kses_normalize_entities3', $content );
2207      if ( 'xml' === $context ) {
2208          $content = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $content );
2209      } else {
2210          $content = preg_replace_callback( '/&amp;([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $content );
2211      }
2212  
2213      return $content;
2214  }
2215  
2216  /**
2217   * Callback for `wp_kses_normalize_entities()` regular expression.
2218   *
2219   * This function only accepts valid named entity references, which are finite,
2220   * case-sensitive, and highly scrutinized by HTML and XML validators.
2221   *
2222   * @since 3.0.0
2223   *
2224   * @global array $allowedentitynames
2225   *
2226   * @param array $matches preg_replace_callback() matches array.
2227   * @return string Correctly encoded entity.
2228   */
2229  function wp_kses_named_entities( $matches ) {
2230      global $allowedentitynames;
2231  
2232      if ( empty( $matches[1] ) ) {
2233          return '';
2234      }
2235  
2236      $i = $matches[1];
2237      return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&amp;$i;" : "&$i;";
2238  }
2239  
2240  /**
2241   * Callback for `wp_kses_normalize_entities()` regular expression.
2242   *
2243   * This function only accepts valid named entity references, which are finite,
2244   * case-sensitive, and highly scrutinized by XML validators.  HTML named entity
2245   * references are converted to their code points.
2246   *
2247   * @since 5.5.0
2248   *
2249   * @global array $allowedentitynames
2250   * @global array $allowedxmlentitynames
2251   *
2252   * @param array $matches preg_replace_callback() matches array.
2253   * @return string Correctly encoded entity.
2254   */
2255  function wp_kses_xml_named_entities( $matches ) {
2256      global $allowedentitynames, $allowedxmlentitynames;
2257  
2258      if ( empty( $matches[1] ) ) {
2259          return '';
2260      }
2261  
2262      $i = $matches[1];
2263  
2264      if ( in_array( $i, $allowedxmlentitynames, true ) ) {
2265          return "&$i;";
2266      } elseif ( in_array( $i, $allowedentitynames, true ) ) {
2267          return html_entity_decode( "&$i;", ENT_HTML5 );
2268      }
2269  
2270      return "&amp;$i;";
2271  }
2272  
2273  /**
2274   * Callback for `wp_kses_normalize_entities()` regular expression.
2275   *
2276   * This function helps `wp_kses_normalize_entities()` to only accept 16-bit
2277   * values and nothing more for `&#number;` entities.
2278   *
2279   * @access private
2280   * @ignore
2281   * @since 1.0.0
2282   *
2283   * @param array $matches `preg_replace_callback()` matches array.
2284   * @return string Correctly encoded entity.
2285   */
2286  function wp_kses_normalize_entities2( $matches ) {
2287      if ( empty( $matches[1] ) ) {
2288          return '';
2289      }
2290  
2291      $i = $matches[1];
2292  
2293      if ( valid_unicode( $i ) ) {
2294          $i = str_pad( ltrim( $i, '0' ), 3, '0', STR_PAD_LEFT );
2295          $i = "&#$i;";
2296      } else {
2297          $i = "&amp;#$i;";
2298      }
2299  
2300      return $i;
2301  }
2302  
2303  /**
2304   * Callback for `wp_kses_normalize_entities()` for regular expression.
2305   *
2306   * This function helps `wp_kses_normalize_entities()` to only accept valid Unicode
2307   * numeric entities in hex form.
2308   *
2309   * @since 2.7.0
2310   * @access private
2311   * @ignore
2312   *
2313   * @param array $matches `preg_replace_callback()` matches array.
2314   * @return string Correctly encoded entity.
2315   */
2316  function wp_kses_normalize_entities3( $matches ) {
2317      if ( empty( $matches[1] ) ) {
2318          return '';
2319      }
2320  
2321      $hexchars = $matches[1];
2322  
2323      return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&amp;#x$hexchars;" : '&#x' . ltrim( $hexchars, '0' ) . ';';
2324  }
2325  
2326  /**
2327   * Determines if a Unicode codepoint is valid.
2328   *
2329   * The definition of a valid Unicode codepoint is taken from the XML definition:
2330   *
2331   * > Characters
2332   * >
2333   * > …
2334   * > Legal characters are tab, carriage return, line feed, and the legal characters of
2335   * > Unicode and ISO/IEC 10646.
2336   * > …
2337   * > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
2338   *
2339   * @since 2.7.0
2340   *
2341   * @see https://www.w3.org/TR/xml/#charsets
2342   *
2343   * @param int $i Unicode codepoint.
2344   * @return bool Whether or not the codepoint is a valid Unicode codepoint.
2345   */
2346  function valid_unicode( $i ) {
2347      $i = (int) $i;
2348  
2349      return (
2350          0x9 === $i || // U+0009 HORIZONTAL TABULATION (HT)
2351          0xA === $i || // U+000A LINE FEED (LF)
2352          0xD === $i || // U+000D CARRIAGE RETURN (CR)
2353          /*
2354           * The valid Unicode characters according to the XML specification:
2355           *
2356           * > any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
2357           */
2358          ( 0x20 <= $i && $i <= 0xD7FF ) ||
2359          ( 0xE000 <= $i && $i <= 0xFFFD ) ||
2360          ( 0x10000 <= $i && $i <= 0x10FFFF )
2361      );
2362  }
2363  
2364  /**
2365   * Converts all numeric HTML entities to their named counterparts.
2366   *
2367   * This function decodes numeric HTML entities (`&#65;` and `&#x41;`).
2368   * It doesn't do anything with named entities like `&auml;`, but we don't
2369   * need them in the allowed URL protocols system anyway.
2370   *
2371   * @since 1.0.0
2372   *
2373   * @param string $content Content to change entities.
2374   * @return string Content after decoded entities.
2375   */
2376  function wp_kses_decode_entities( $content ) {
2377      $content = preg_replace_callback( '/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $content );
2378      $content = preg_replace_callback( '/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $content );
2379  
2380      return $content;
2381  }
2382  
2383  /**
2384   * Regex callback for `wp_kses_decode_entities()`.
2385   *
2386   * @since 2.9.0
2387   * @access private
2388   * @ignore
2389   *
2390   * @param array $matches preg match
2391   * @return string
2392   */
2393  function _wp_kses_decode_entities_chr( $matches ) {
2394      return chr( $matches[1] );
2395  }
2396  
2397  /**
2398   * Regex callback for `wp_kses_decode_entities()`.
2399   *
2400   * @since 2.9.0
2401   * @access private
2402   * @ignore
2403   *
2404   * @param array $matches preg match
2405   * @return string
2406   */
2407  function _wp_kses_decode_entities_chr_hexdec( $matches ) {
2408      return chr( hexdec( $matches[1] ) );
2409  }
2410  
2411  /**
2412   * Sanitize content with allowed HTML KSES rules.
2413   *
2414   * This function expects slashed data.
2415   *
2416   * @since 1.0.0
2417   *
2418   * @param string $data Content to filter, expected to be escaped with slashes.
2419   * @return string Filtered content.
2420   */
2421  function wp_filter_kses( $data ) {
2422      return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
2423  }
2424  
2425  /**
2426   * Sanitize content with allowed HTML KSES rules.
2427   *
2428   * This function expects unslashed data.
2429   *
2430   * @since 2.9.0
2431   *
2432   * @param string $data Content to filter, expected to not be escaped.
2433   * @return string Filtered content.
2434   */
2435  function wp_kses_data( $data ) {
2436      return wp_kses( $data, current_filter() );
2437  }
2438  
2439  /**
2440   * Sanitizes content for allowed HTML tags for post content.
2441   *
2442   * Post content refers to the page contents of the 'post' type and not `$_POST`
2443   * data from forms.
2444   *
2445   * This function expects slashed data.
2446   *
2447   * @since 2.0.0
2448   *
2449   * @param string $data Post content to filter, expected to be escaped with slashes.
2450   * @return string Filtered post content with allowed HTML tags and attributes intact.
2451   */
2452  function wp_filter_post_kses( $data ) {
2453      return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
2454  }
2455  
2456  /**
2457   * Sanitizes global styles user content removing unsafe rules.
2458   *
2459   * @since 5.9.0
2460   *
2461   * @param string $data Post content to filter.
2462   * @return string Filtered post content with unsafe rules removed.
2463   */
2464  function wp_filter_global_styles_post( $data ) {
2465      $decoded_data        = json_decode( wp_unslash( $data ), true );
2466      $json_decoding_error = json_last_error();
2467      if (
2468          JSON_ERROR_NONE === $json_decoding_error &&
2469          is_array( $decoded_data ) &&
2470          isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) &&
2471          $decoded_data['isGlobalStylesUserThemeJSON']
2472      ) {
2473          unset( $decoded_data['isGlobalStylesUserThemeJSON'] );
2474  
2475          $data_to_encode = WP_Theme_JSON::remove_insecure_properties( $decoded_data, 'custom' );
2476  
2477          $data_to_encode['isGlobalStylesUserThemeJSON'] = true;
2478          /**
2479           * JSON encode the data stored in post content.
2480           * Escape characters that are likely to be mangled by HTML filters: "<>&".
2481           *
2482           * This matches the escaping in {@see WP_REST_Global_Styles_Controller::prepare_item_for_database()}.
2483           */
2484          return wp_slash( wp_json_encode( $data_to_encode, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) );
2485      }
2486      return $data;
2487  }
2488  
2489  /**
2490   * Sanitizes content for allowed HTML tags for post content.
2491   *
2492   * Post content refers to the page contents of the 'post' type and not `$_POST`
2493   * data from forms.
2494   *
2495   * This function expects unslashed data.
2496   *
2497   * @since 2.9.0
2498   *
2499   * @param string $data Post content to filter.
2500   * @return string Filtered post content with allowed HTML tags and attributes intact.
2501   */
2502  function wp_kses_post( $data ) {
2503      return wp_kses( $data, 'post' );
2504  }
2505  
2506  /**
2507   * Navigates through an array, object, or scalar, and sanitizes content for
2508   * allowed HTML tags for post content.
2509   *
2510   * @since 4.4.2
2511   *
2512   * @see map_deep()
2513   *
2514   * @param mixed $data The array, object, or scalar value to inspect.
2515   * @return mixed The filtered content.
2516   */
2517  function wp_kses_post_deep( $data ) {
2518      return map_deep( $data, 'wp_kses_post' );
2519  }
2520  
2521  /**
2522   * Strips all HTML from a text string.
2523   *
2524   * This function expects slashed data.
2525   *
2526   * @since 2.1.0
2527   *
2528   * @param string $data Content to strip all HTML from.
2529   * @return string Filtered content without any HTML.
2530   */
2531  function wp_filter_nohtml_kses( $data ) {
2532      return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
2533  }
2534  
2535  /**
2536   * Adds all KSES input form content filters.
2537   *
2538   * All hooks have default priority. The `wp_filter_kses()` function is added to
2539   * the 'pre_comment_content' and 'title_save_pre' hooks.
2540   *
2541   * The `wp_filter_post_kses()` function is added to the 'content_save_pre',
2542   * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
2543   *
2544   * @since 2.0.0
2545   */
2546  function kses_init_filters() {
2547      // Normal filtering.
2548      add_filter( 'title_save_pre', 'wp_filter_kses' );
2549  
2550      // Comment filtering.
2551      if ( current_user_can( 'unfiltered_html' ) ) {
2552          add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2553      } else {
2554          add_filter( 'pre_comment_content', 'wp_filter_kses' );
2555      }
2556  
2557      // Global Styles filtering: Global Styles filters should be executed before normal post_kses HTML filters.
2558      add_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2559      add_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2560  
2561      // Post filtering.
2562      add_filter( 'content_save_pre', 'wp_filter_post_kses' );
2563      add_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2564      add_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2565  }
2566  
2567  /**
2568   * Removes all KSES input form content filters.
2569   *
2570   * A quick procedural method to removing all of the filters that KSES uses for
2571   * content in WordPress Loop.
2572   *
2573   * Does not remove the `kses_init()` function from {@see 'init'} hook (priority is
2574   * default). Also does not remove `kses_init()` function from {@see 'set_current_user'}
2575   * hook (priority is also default).
2576   *
2577   * @since 2.0.6
2578   */
2579  function kses_remove_filters() {
2580      // Normal filtering.
2581      remove_filter( 'title_save_pre', 'wp_filter_kses' );
2582  
2583      // Comment filtering.
2584      remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
2585      remove_filter( 'pre_comment_content', 'wp_filter_kses' );
2586  
2587      // Global Styles filtering.
2588      remove_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
2589      remove_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
2590  
2591      // Post filtering.
2592      remove_filter( 'content_save_pre', 'wp_filter_post_kses' );
2593      remove_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
2594      remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
2595  }
2596  
2597  /**
2598   * Sets up most of the KSES filters for input form content.
2599   *
2600   * First removes all of the KSES filters in case the current user does not need
2601   * to have KSES filter the content. If the user does not have `unfiltered_html`
2602   * capability, then KSES filters are added.
2603   *
2604   * @since 2.0.0
2605   */
2606  function kses_init() {
2607      kses_remove_filters();
2608  
2609      if ( ! current_user_can( 'unfiltered_html' ) ) {
2610          kses_init_filters();
2611      }
2612  }
2613  
2614  /**
2615   * Filters an inline style attribute and removes disallowed rules.
2616   *
2617   * @since 2.8.1
2618   * @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
2619   * @since 4.6.0 Added support for `list-style-type`.
2620   * @since 5.0.0 Added support for `background-image`.
2621   * @since 5.1.0 Added support for `text-transform`.
2622   * @since 5.2.0 Added support for `background-position` and `grid-template-columns`.
2623   * @since 5.3.0 Added support for `grid`, `flex` and `column` layout properties.
2624   *              Extended `background-*` support for individual properties.
2625   * @since 5.3.1 Added support for gradient backgrounds.
2626   * @since 5.7.1 Added support for `object-position`.
2627   * @since 5.8.0 Added support for `calc()` and `var()` values.
2628   * @since 6.1.0 Added support for `min()`, `max()`, `minmax()`, `clamp()`,
2629   *              nested `var()` values, and assigning values to CSS variables.
2630   *              Added support for `object-fit`, `gap`, `column-gap`, `row-gap`, and `flex-wrap`.
2631   *              Extended `margin-*` and `padding-*` support for logical properties.
2632   * @since 6.2.0 Added support for `aspect-ratio`, `position`, `top`, `right`, `bottom`, `left`,
2633   *              and `z-index` CSS properties.
2634   * @since 6.3.0 Extended support for `filter` to accept a URL and added support for repeat().
2635   *              Added support for `box-shadow`.
2636   * @since 6.4.0 Added support for `writing-mode`.
2637   * @since 6.5.0 Added support for `background-repeat`.
2638   * @since 6.6.0 Added support for `grid-column`, `grid-row`, and `container-type`.
2639   * @since 6.9.0 Added support for `white-space`.
2640   * @since 7.1.0 Extended gradient support to allow any single-level nested function.
2641   *
2642   * @param string $css        A string of CSS rules, decoded from an HTML `style` attribute.
2643   * @param string $deprecated Not used.
2644   * @return string Filtered string of CSS rules, needing HTML escaping before sending back to a `style` attribute.
2645   */
2646  function safecss_filter_attr( $css, $deprecated = '' ) {
2647      if ( ! empty( $deprecated ) ) {
2648          _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented.
2649      }
2650  
2651      $css = wp_kses_no_null( $css );
2652      $css = str_replace( array( "\n", "\r", "\t" ), '', $css );
2653  
2654      $allowed_protocols = wp_allowed_protocols();
2655  
2656      /** @todo Parse enough CSS to split rules without breaking on things like quoted strings. */
2657      $css_array = explode( ';', trim( $css ) );
2658  
2659      /**
2660       * Filters the list of allowed CSS attributes.
2661       *
2662       * @since 2.8.1
2663       * @since 7.1.0 Added support for SVG presentation attributes.
2664       *
2665       * @param string[] $attr Array of allowed CSS attributes.
2666       */
2667      $allowed_attr = apply_filters(
2668          'safe_style_css',
2669          array(
2670              'background',
2671              'background-color',
2672              'background-image',
2673              'background-position',
2674              'background-repeat',
2675              'background-size',
2676              'background-attachment',
2677              'background-blend-mode',
2678  
2679              'border',
2680              'border-radius',
2681              'border-width',
2682              'border-color',
2683              'border-style',
2684              'border-right',
2685              'border-right-color',
2686              'border-right-style',
2687              'border-right-width',
2688              'border-bottom',
2689              'border-bottom-color',
2690              'border-bottom-left-radius',
2691              'border-bottom-right-radius',
2692              'border-bottom-style',
2693              'border-bottom-width',
2694              'border-bottom-right-radius',
2695              'border-bottom-left-radius',
2696              'border-left',
2697              'border-left-color',
2698              'border-left-style',
2699              'border-left-width',
2700              'border-top',
2701              'border-top-color',
2702              'border-top-left-radius',
2703              'border-top-right-radius',
2704              'border-top-style',
2705              'border-top-width',
2706              'border-top-left-radius',
2707              'border-top-right-radius',
2708  
2709              'border-spacing',
2710              'border-collapse',
2711              'caption-side',
2712  
2713              'columns',
2714              'column-count',
2715              'column-fill',
2716              'column-gap',
2717              'column-rule',
2718              'column-span',
2719              'column-width',
2720  
2721              'display',
2722  
2723              'color',
2724              'filter',
2725              'font',
2726              'font-family',
2727              'font-size',
2728              'font-style',
2729              'font-variant',
2730              'font-weight',
2731              'letter-spacing',
2732              'line-height',
2733              'text-align',
2734              'text-decoration',
2735              'text-indent',
2736              'text-transform',
2737              'white-space',
2738  
2739              'height',
2740              'min-height',
2741              'max-height',
2742  
2743              'width',
2744              'min-width',
2745              'max-width',
2746  
2747              'margin',
2748              'margin-right',
2749              'margin-bottom',
2750              'margin-left',
2751              'margin-top',
2752              'margin-block-start',
2753              'margin-block-end',
2754              'margin-inline-start',
2755              'margin-inline-end',
2756  
2757              'padding',
2758              'padding-right',
2759              'padding-bottom',
2760              'padding-left',
2761              'padding-top',
2762              'padding-block-start',
2763              'padding-block-end',
2764              'padding-inline-start',
2765              'padding-inline-end',
2766  
2767              'flex',
2768              'flex-basis',
2769              'flex-direction',
2770              'flex-flow',
2771              'flex-grow',
2772              'flex-shrink',
2773              'flex-wrap',
2774  
2775              'gap',
2776              'column-gap',
2777              'row-gap',
2778  
2779              'grid-template-columns',
2780              'grid-auto-columns',
2781              'grid-column-start',
2782              'grid-column-end',
2783              'grid-column',
2784              'grid-column-gap',
2785              'grid-template-rows',
2786              'grid-auto-rows',
2787              'grid-row-start',
2788              'grid-row-end',
2789              'grid-row',
2790              'grid-row-gap',
2791              'grid-gap',
2792  
2793              'justify-content',
2794              'justify-items',
2795              'justify-self',
2796              'align-content',
2797              'align-items',
2798              'align-self',
2799  
2800              'clear',
2801              'cursor',
2802              'direction',
2803              'float',
2804              'list-style-type',
2805              'object-fit',
2806              'object-position',
2807              'opacity',
2808              'overflow',
2809              'vertical-align',
2810              'writing-mode',
2811  
2812              'position',
2813              'top',
2814              'right',
2815              'bottom',
2816              'left',
2817              'z-index',
2818              'box-shadow',
2819              'aspect-ratio',
2820              'container-type',
2821  
2822              'fill',
2823              'fill-opacity',
2824              'fill-rule',
2825  
2826              'stroke',
2827              'stroke-dasharray',
2828              'stroke-dashoffset',
2829              'stroke-linecap',
2830              'stroke-linejoin',
2831              'stroke-miterlimit',
2832              'stroke-opacity',
2833              'stroke-width',
2834  
2835              'color-interpolation',
2836              'color-interpolation-filters',
2837              'paint-order',
2838              'stop-color',
2839              'stop-opacity',
2840              'flood-color',
2841              'flood-opacity',
2842              'lighting-color',
2843  
2844              'marker',
2845              'marker-end',
2846              'marker-mid',
2847              'marker-start',
2848  
2849              'clip-path',
2850              'clip-rule',
2851              'mask',
2852              'mask-type',
2853  
2854              'cx',
2855              'cy',
2856              'r',
2857              'rx',
2858              'ry',
2859              'x',
2860              'y',
2861              'd',
2862  
2863              'alignment-baseline',
2864              'baseline-shift',
2865              'dominant-baseline',
2866              'glyph-orientation-horizontal',
2867              'glyph-orientation-vertical',
2868              'text-anchor',
2869              'unicode-bidi',
2870              'word-spacing',
2871  
2872              'font-size-adjust',
2873              'font-stretch',
2874  
2875              'color-rendering',
2876              'image-rendering',
2877              'shape-rendering',
2878              'text-rendering',
2879              'vector-effect',
2880  
2881              'transform',
2882              'transform-origin',
2883  
2884              'pointer-events',
2885              'visibility',
2886  
2887              // Custom CSS properties.
2888              '--*',
2889          )
2890      );
2891  
2892      /*
2893       * CSS attributes that accept URL data types.
2894       *
2895       * This is in accordance to the CSS spec and unrelated to
2896       * the sub-set of supported attributes above.
2897       *
2898       * See: https://developer.mozilla.org/en-US/docs/Web/CSS/url
2899       */
2900      $css_url_data_types = array(
2901          'background',
2902          'background-image',
2903  
2904          'cursor',
2905          'filter',
2906  
2907          'list-style',
2908          'list-style-image',
2909      );
2910  
2911      /*
2912       * CSS attributes that accept gradient data types.
2913       *
2914       */
2915      $css_gradient_data_types = array(
2916          'background',
2917          'background-image',
2918      );
2919  
2920      if ( empty( $allowed_attr ) ) {
2921          return $css;
2922      }
2923  
2924      $css = '';
2925      foreach ( $css_array as $css_item ) {
2926          if ( '' === $css_item ) {
2927              continue;
2928          }
2929  
2930          $css_item        = trim( $css_item );
2931          $css_test_string = $css_item;
2932          $found           = false;
2933          $url_attr        = false;
2934          $gradient_attr   = false;
2935          $is_custom_var   = false;
2936  
2937          if ( ! str_contains( $css_item, ':' ) ) {
2938              $found = true;
2939          } else {
2940              $parts        = explode( ':', $css_item, 2 );
2941              $css_selector = trim( $parts[0] );
2942  
2943              // Allow assigning values to CSS variables.
2944              if ( in_array( '--*', $allowed_attr, true ) && preg_match( '/^--[a-zA-Z0-9-_]+$/', $css_selector ) ) {
2945                  $allowed_attr[] = $css_selector;
2946                  $is_custom_var  = true;
2947              }
2948  
2949              if ( in_array( $css_selector, $allowed_attr, true ) ) {
2950                  $found         = true;
2951                  $url_attr      = in_array( $css_selector, $css_url_data_types, true );
2952                  $gradient_attr = in_array( $css_selector, $css_gradient_data_types, true );
2953              }
2954  
2955              if ( $is_custom_var ) {
2956                  $css_value     = trim( $parts[1] );
2957                  $url_attr      = str_starts_with( $css_value, 'url(' );
2958                  $gradient_attr = str_contains( $css_value, '-gradient(' );
2959              }
2960          }
2961  
2962          if ( $found && $url_attr ) {
2963              // Simplified: matches the sequence `url(*)`.
2964              preg_match_all( '/url\([^)]+\)/', $parts[1], $url_matches );
2965  
2966              foreach ( $url_matches[0] as $url_match ) {
2967                  // Clean up the URL from each of the matches above.
2968                  preg_match( '/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces );
2969  
2970                  if ( empty( $url_pieces[2] ) ) {
2971                      $found = false;
2972                      break;
2973                  }
2974  
2975                  $url = trim( $url_pieces[2] );
2976  
2977                  if ( empty( $url ) || wp_kses_bad_protocol( $url, $allowed_protocols ) !== $url ) {
2978                      $found = false;
2979                      break;
2980                  } else {
2981                      // Remove the whole `url(*)` bit that was matched above from the CSS.
2982                      $css_test_string = str_replace( $url_match, '', $css_test_string );
2983                  }
2984              }
2985          }
2986  
2987          if ( $found && $gradient_attr ) {
2988              /*
2989               * Match every `*-gradient()` in the value, allowing one level of nested functions
2990               * (e.g. rgb(), hsl(), var()). Matching each occurrence, rather than requiring the
2991               * whole value to be a single gradient, lets a gradient combine with a url() image.
2992               */
2993              preg_match_all( '/(?:repeating-)?(?:linear|radial|conic)-gradient\((?:[^()]|\([^()]*\))*\)/', $css_test_string, $gradient_matches );
2994  
2995              foreach ( $gradient_matches[0] as $gradient_match ) {
2996                  // Remove each `gradient()` bit that was matched above from the CSS.
2997                  $css_test_string = str_replace( $gradient_match, '', $css_test_string );
2998              }
2999          }
3000  
3001          if ( $found ) {
3002              /*
3003               * Allow CSS functions like var(), calc(), etc. by removing them from the test string.
3004               * Nested functions and parentheses are also removed, so long as the parentheses are balanced.
3005               */
3006              $css_test_string = preg_replace(
3007                  '/\b(?:var|calc|min|max|minmax|clamp|repeat)(\((?:[^()]|(?1))*\))/',
3008                  '',
3009                  $css_test_string
3010              );
3011  
3012              /*
3013               * Disallow CSS containing \ ( & } = or comments, except for within url(), var(), calc(), etc.
3014               * which were removed from the test string above.
3015               */
3016              $allow_css = ! preg_match( '%[\\\(&=}]|/\*%', $css_test_string );
3017  
3018              /**
3019               * Filters the check for unsafe CSS in `safecss_filter_attr`.
3020               *
3021               * Enables developers to determine whether a section of CSS should be allowed or discarded.
3022               * By default, the value will be false if the part contains \ ( & } = or comments.
3023               * Return true to allow the CSS part to be included in the output.
3024               *
3025               * @since 5.5.0
3026               *
3027               * @param bool   $allow_css       Whether the CSS in the test string is considered safe.
3028               * @param string $css_test_string The CSS string to test.
3029               */
3030              $allow_css = apply_filters( 'safecss_filter_attr_allow_css', $allow_css, $css_test_string );
3031  
3032              // Only add the CSS part if it passes the regex check.
3033              if ( $allow_css ) {
3034                  if ( '' !== $css ) {
3035                      $css .= ';';
3036                  }
3037  
3038                  $css .= $css_item;
3039              }
3040          }
3041      }
3042  
3043      return $css;
3044  }
3045  
3046  /**
3047   * Helper function to add global attributes to a tag in the allowed HTML list.
3048   *
3049   * @since 3.5.0
3050   * @since 5.0.0 Added support for `data-*` wildcard attributes.
3051   * @since 6.0.0 Added `dir`, `lang`, and `xml:lang` to global attributes.
3052   * @since 6.3.0 Added `aria-controls`, `aria-current`, and `aria-expanded` attributes.
3053   * @since 6.4.0 Added `aria-live` and `hidden` attributes.
3054   * @since 7.1.0 Added `tabindex` attribute.
3055   *
3056   * @access private
3057   * @ignore
3058   *
3059   * @param array $value An array of attributes.
3060   * @return array The array of attributes with global attributes added.
3061   */
3062  function _wp_add_global_attributes( $value ) {
3063      $global_attributes = array(
3064          'aria-controls'    => true,
3065          'aria-current'     => true,
3066          'aria-describedby' => true,
3067          'aria-details'     => true,
3068          'aria-expanded'    => true,
3069          'aria-hidden'      => true,
3070          'aria-label'       => true,
3071          'aria-labelledby'  => true,
3072          'aria-live'        => true,
3073          'class'            => true,
3074          'data-*'           => true,
3075          'dir'              => true,
3076          'hidden'           => true,
3077          'id'               => true,
3078          'lang'             => true,
3079          'style'            => true,
3080          'tabindex'         => true,
3081          'title'            => true,
3082          'role'             => true,
3083          'xml:lang'         => true,
3084      );
3085  
3086      if ( true === $value ) {
3087          $value = array();
3088      }
3089  
3090      if ( is_array( $value ) ) {
3091          return array_merge( $value, $global_attributes );
3092      }
3093  
3094      return $value;
3095  }
3096  
3097  /**
3098   * Helper function to check if this is a safe PDF URL.
3099   *
3100   * @since 5.9.0
3101   * @access private
3102   * @ignore
3103   *
3104   * @param string $url The URL to check.
3105   * @return bool True if the URL is safe, false otherwise.
3106   */
3107  function _wp_kses_allow_pdf_objects( $url ) {
3108      // We're not interested in URLs that contain query strings or fragments.
3109      if ( str_contains( $url, '?' ) || str_contains( $url, '#' ) ) {
3110          return false;
3111      }
3112  
3113      // If it doesn't have a PDF extension, it's not safe.
3114      if ( ! str_ends_with( $url, '.pdf' ) ) {
3115          return false;
3116      }
3117  
3118      // If the URL host matches the current site's media URL, it's safe.
3119      $upload_info = wp_upload_dir( null, false );
3120      $parsed_url  = wp_parse_url( $upload_info['url'] );
3121      $upload_host = $parsed_url['host'] ?? '';
3122      $upload_port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : '';
3123  
3124      if ( str_starts_with( $url, "http://$upload_host$upload_port/" )
3125          || str_starts_with( $url, "https://$upload_host$upload_port/" )
3126      ) {
3127          return true;
3128      }
3129  
3130      return false;
3131  }


Generated : Tue Jul 28 08:20:19 2026 Cross-referenced by PHPXref