[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Wed Jan 19 01:00:04 2022 Cross-referenced by PHPXref 0.7.1