| [ Index ] |
PHP Cross Reference of WordPress Trunk (Updated Daily) |
[Summary view] [Print] [Text view]
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 * Whether to use custom allowed HTML tags from the KSES globals. 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 * To use custom tags, define this constant as `true` and set all of these globals to arrays: 40 * 41 * - `$allowedposttags` 42 * - `$allowedtags` 43 * - `$allowedentitynames` 44 * - `$allowedxmlentitynames` 45 * 46 * @see wp_kses_allowed_html() 47 * @since 1.2.0 48 */ 49 if ( ! defined( 'CUSTOM_TAGS' ) ) { 50 define( 'CUSTOM_TAGS', false ); 51 } 52 53 // Ensure that these variables are added to the global namespace 54 // (e.g. if using namespaces / autoload in the current PHP environment). 55 global $allowedposttags, $allowedtags, $allowedentitynames, $allowedxmlentitynames; 56 57 /** 58 * Indicates which implementation of {@see \wp_kses()} is running. 59 * 60 * Nominally `legacy` unless temporarily-switched for {@see \wp_sanitize_html_kses()}. 61 * It’s safe to latch this into `legacy`. 62 * 63 * @global 'legacy'|'html-api' $wp_kses_operating_mode 64 * 65 * @since 7.2.0 66 */ 67 global $wp_kses_operating_mode; 68 $wp_kses_operating_mode = 'legacy'; 69 70 if ( ! CUSTOM_TAGS ) { 71 /** 72 * KSES global for default allowable HTML tags. 73 * 74 * Can be overridden with the `CUSTOM_TAGS` constant. 75 * 76 * @var array[] $allowedposttags Array of default allowable HTML tags. 77 * @since 2.0.0 78 */ 79 $allowedposttags = array( 80 'address' => array(), 81 'a' => array( 82 'href' => true, 83 'rel' => true, 84 'rev' => true, 85 'name' => true, 86 'target' => true, 87 'download' => array( 88 'valueless' => 'y', 89 ), 90 ), 91 'abbr' => array(), 92 'acronym' => array(), 93 'area' => array( 94 'alt' => true, 95 'coords' => true, 96 'href' => true, 97 'nohref' => true, 98 'shape' => true, 99 'target' => true, 100 ), 101 'article' => array( 102 'align' => true, 103 ), 104 'aside' => array( 105 'align' => true, 106 ), 107 'audio' => array( 108 'autoplay' => true, 109 'controls' => true, 110 'loop' => true, 111 'muted' => true, 112 'preload' => true, 113 'src' => true, 114 ), 115 'b' => array(), 116 'bdo' => array(), 117 'big' => array(), 118 'blockquote' => array( 119 'cite' => true, 120 ), 121 'br' => array(), 122 'button' => array( 123 'command' => true, 124 'commandfor' => true, 125 'disabled' => true, 126 'name' => true, 127 'type' => true, 128 'value' => true, 129 'popovertarget' => true, 130 'popovertargetaction' => true, 131 'aria-haspopup' => true, 132 ), 133 'caption' => array( 134 'align' => true, 135 ), 136 'cite' => array(), 137 'code' => array(), 138 'col' => array( 139 'align' => true, 140 'char' => true, 141 'charoff' => true, 142 'span' => true, 143 'valign' => true, 144 'width' => true, 145 ), 146 'colgroup' => array( 147 'align' => true, 148 'char' => true, 149 'charoff' => true, 150 'span' => true, 151 'valign' => true, 152 'width' => true, 153 ), 154 'data' => array( 155 'value' => true, 156 ), 157 'del' => array( 158 'datetime' => true, 159 ), 160 'dd' => array(), 161 'dfn' => array(), 162 'details' => array( 163 'align' => true, 164 'open' => true, 165 'name' => true, 166 ), 167 'div' => array( 168 'align' => true, 169 'popover' => true, 170 ), 171 'dialog' => array( 172 'closedby' => true, 173 'open' => true, 174 'popover' => true, 175 'autofocus' => true, 176 ), 177 'dl' => array(), 178 'dt' => array(), 179 'em' => array(), 180 'fieldset' => array(), 181 'figure' => array( 182 'align' => true, 183 ), 184 'figcaption' => array( 185 'align' => true, 186 ), 187 'font' => array( 188 'color' => true, 189 'face' => true, 190 'size' => true, 191 ), 192 'footer' => array( 193 'align' => true, 194 ), 195 'h1' => array( 196 'align' => true, 197 ), 198 'h2' => array( 199 'align' => true, 200 ), 201 'h3' => array( 202 'align' => true, 203 ), 204 'h4' => array( 205 'align' => true, 206 ), 207 'h5' => array( 208 'align' => true, 209 ), 210 'h6' => array( 211 'align' => true, 212 ), 213 'header' => array( 214 'align' => true, 215 ), 216 'hgroup' => array( 217 'align' => true, 218 ), 219 'hr' => array( 220 'align' => true, 221 'noshade' => true, 222 'size' => true, 223 'width' => true, 224 ), 225 'i' => array(), 226 'img' => array( 227 'alt' => true, 228 'align' => true, 229 'border' => true, 230 'height' => true, 231 'hspace' => true, 232 'loading' => true, 233 'longdesc' => true, 234 'vspace' => true, 235 'src' => true, 236 'usemap' => true, 237 'width' => true, 238 ), 239 'ins' => array( 240 'datetime' => true, 241 'cite' => true, 242 ), 243 'kbd' => array(), 244 'label' => array( 245 'for' => true, 246 ), 247 'legend' => array( 248 'align' => true, 249 ), 250 'li' => array( 251 'align' => true, 252 'value' => true, 253 ), 254 'main' => array( 255 'align' => true, 256 ), 257 'map' => array( 258 'name' => true, 259 ), 260 'mark' => array(), 261 'menu' => array( 262 'type' => true, 263 ), 264 'meter' => array( 265 'high' => true, 266 'low' => true, 267 'max' => true, 268 'min' => true, 269 'optimum' => true, 270 'value' => true, 271 ), 272 'nav' => array( 273 'align' => true, 274 ), 275 'object' => array( 276 'data' => array( 277 'required' => true, 278 'value_callback' => '_wp_kses_allow_pdf_objects', 279 ), 280 'type' => array( 281 'required' => true, 282 'values' => array( 'application/pdf' ), 283 ), 284 ), 285 'p' => array( 286 'align' => true, 287 ), 288 'pre' => array( 289 'width' => true, 290 ), 291 'progress' => array( 292 'max' => true, 293 'value' => true, 294 ), 295 'q' => array( 296 'cite' => true, 297 ), 298 'rb' => array(), 299 'rp' => array(), 300 'rt' => array(), 301 'rtc' => array(), 302 'ruby' => array(), 303 's' => array(), 304 'samp' => array(), 305 'search' => array(), 306 'span' => array( 307 'align' => true, 308 ), 309 'section' => array( 310 'align' => true, 311 ), 312 'small' => array(), 313 'strike' => array(), 314 'strong' => array(), 315 'sub' => array(), 316 'summary' => array( 317 'align' => true, 318 ), 319 'sup' => array(), 320 'table' => array( 321 'align' => true, 322 'bgcolor' => true, 323 'border' => true, 324 'cellpadding' => true, 325 'cellspacing' => true, 326 'rules' => true, 327 'summary' => true, 328 'width' => true, 329 ), 330 'tbody' => array( 331 'align' => true, 332 'char' => true, 333 'charoff' => true, 334 'valign' => true, 335 ), 336 'td' => array( 337 'abbr' => true, 338 'align' => true, 339 'axis' => true, 340 'bgcolor' => true, 341 'char' => true, 342 'charoff' => true, 343 'colspan' => true, 344 'headers' => true, 345 'height' => true, 346 'nowrap' => true, 347 'rowspan' => true, 348 'scope' => true, 349 'valign' => true, 350 'width' => true, 351 ), 352 'textarea' => array( 353 'cols' => true, 354 'rows' => true, 355 'disabled' => true, 356 'name' => true, 357 'readonly' => true, 358 ), 359 'tfoot' => array( 360 'align' => true, 361 'char' => true, 362 'charoff' => true, 363 'valign' => true, 364 ), 365 'th' => array( 366 'abbr' => true, 367 'align' => true, 368 'axis' => true, 369 'bgcolor' => true, 370 'char' => true, 371 'charoff' => true, 372 'colspan' => true, 373 'headers' => true, 374 'height' => true, 375 'nowrap' => true, 376 'rowspan' => true, 377 'scope' => true, 378 'valign' => true, 379 'width' => true, 380 ), 381 'thead' => array( 382 'align' => true, 383 'char' => true, 384 'charoff' => true, 385 'valign' => true, 386 ), 387 'time' => array( 388 'datetime' => 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 'popover' => true, 410 'role' => true, 411 ), 412 'ol' => array( 413 'start' => true, 414 'type' => true, 415 'reversed' => true, 416 ), 417 'var' => array(), 418 'video' => array( 419 'autoplay' => true, 420 'controls' => true, 421 'height' => true, 422 'loop' => true, 423 'muted' => true, 424 'playsinline' => true, 425 'poster' => true, 426 'preload' => true, 427 'src' => true, 428 'width' => true, 429 ), 430 'wbr' => array(), 431 ); 432 433 // https://www.w3.org/TR/mathml-core/#global-attributes 434 // Except common attributes added by _wp_add_global_attributes. 435 $math_global_attributes = array( 436 'displaystyle' => true, 437 'scriptlevel' => true, 438 'mathbackground' => true, 439 'mathcolor' => true, 440 'mathsize' => true, 441 // Common attributes also defined by _wp_add_global_attributes. 442 // We do not want to add all those global attributes though. 443 'class' => true, 444 'data-*' => true, 445 'dir' => true, 446 'id' => true, 447 'style' => true, 448 ); 449 450 $math_overunder_attributes = array( 451 'accentunder' => true, 452 'accent' => true, 453 ); 454 455 $allowedposttags = array_merge( 456 $allowedposttags, 457 array( 458 // https://www.w3.org/TR/mathml-core/#the-top-level-math-element 459 'math' => array_merge( 460 $math_global_attributes, 461 array( 462 'display' => true, 463 ) 464 ), 465 466 // https://www.w3.org/TR/mathml-core/#token-elements 467 // https://www.w3.org/TR/mathml-core/#text-mtext 468 'mtext' => $math_global_attributes, 469 // https://www.w3.org/TR/mathml-core/#the-mi-element 470 'mi' => array_merge( 471 $math_global_attributes, 472 array( 473 'mathvariant' => true, 474 ) 475 ), 476 // https://www.w3.org/TR/mathml-core/#number-mn 477 'mn' => $math_global_attributes, 478 // https://www.w3.org/TR/mathml-core/#operator-fence-separator-or-accent-mo 479 'mo' => array_merge( 480 $math_global_attributes, 481 array( 482 'form' => true, 483 'fence' => true, 484 'separator' => true, 485 'lspace' => true, 486 'rspace' => true, 487 'stretchy' => true, 488 'symmetric' => true, 489 'maxsize' => true, 490 'minsize' => true, 491 'largeop' => true, 492 'movablelimits' => true, 493 ) 494 ), 495 // https://www.w3.org/TR/mathml-core/#space-mspace 496 'mspace' => array_merge( 497 $math_global_attributes, 498 array( 499 'width' => true, 500 'height' => true, 501 'depth' => true, 502 ) 503 ), 504 // https://www.w3.org/TR/mathml-core/#string-literal-ms 505 'ms' => $math_global_attributes, 506 507 // https://www.w3.org/TR/mathml-core/#general-layout-schemata 508 // https://www.w3.org/TR/mathml-core/#horizontally-group-sub-expressions-mrow 509 'mrow' => $math_global_attributes, 510 // https://www.w3.org/TR/mathml-core/#fractions-mfrac 511 'mfrac' => array_merge( 512 $math_global_attributes, 513 array( 514 'linethickness' => true, 515 ) 516 ), 517 // https://www.w3.org/TR/mathml-core/#radicals-msqrt-mroot 518 'msqrt' => $math_global_attributes, 519 'mroot' => $math_global_attributes, 520 // https://www.w3.org/TR/mathml-core/#style-change-mstyle 521 'mstyle' => $math_global_attributes, 522 // https://www.w3.org/TR/mathml-core/#error-message-merror 523 'merror' => $math_global_attributes, 524 // https://www.w3.org/TR/mathml-core/#adjust-space-around-content-mpadded 525 'mpadded' => array_merge( 526 $math_global_attributes, 527 array( 528 'width' => true, 529 'height' => true, 530 'depth' => true, 531 'lspace' => true, 532 'voffset' => true, 533 ) 534 ), 535 // https://www.w3.org/TR/mathml-core/#making-sub-expressions-invisible-mphantom 536 'mphantom' => $math_global_attributes, 537 538 // https://www.w3.org/TR/mathml-core/#script-and-limit-schemata 539 // https://www.w3.org/TR/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup 540 'msub' => $math_global_attributes, 541 'msup' => $math_global_attributes, 542 'msubsup' => $math_global_attributes, 543 // https://www.w3.org/TR/mathml-core/#underscripts-and-overscripts-munder-mover-munderover 544 'munder' => array_merge( $math_global_attributes, $math_overunder_attributes ), 545 'mover' => array_merge( $math_global_attributes, $math_overunder_attributes ), 546 'munderover' => array_merge( $math_global_attributes, $math_overunder_attributes ), 547 // https://www.w3.org/TR/mathml-core/#prescripts-and-tensor-indices-mmultiscripts 548 'mmultiscripts' => $math_global_attributes, 549 'mprescripts' => $math_global_attributes, 550 551 // https://www.w3.org/TR/mathml-core/#tabular-math 552 // https://www.w3.org/TR/mathml-core/#table-or-matrix-mtable 553 'mtable' => array_merge( 554 $math_global_attributes, 555 array( 556 // Non-standard, used by temml/katex. 557 // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtable 558 'columnalign' => true, 559 'rowspacing' => true, 560 'columnspacing' => true, 561 'align' => true, 562 'rowalign' => true, 563 'columnlines' => true, 564 'rowlines' => true, 565 'frame' => true, 566 'framespacing' => true, 567 'width' => true, 568 ) 569 ), 570 // https://www.w3.org/TR/mathml-core/#row-in-table-or-matrix-mtr 571 'mtr' => array_merge( 572 $math_global_attributes, 573 array( 574 // Non-standard, used by temml/katex. 575 // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtr 576 'columnalign' => true, 577 'rowalign' => true, 578 ) 579 ), 580 // https://www.w3.org/TR/mathml-core/#entry-in-table-or-matrix-mtd 581 'mtd' => array_merge( 582 $math_global_attributes, 583 array( 584 'columnspan' => true, 585 'rowspan' => true, 586 // Non-standard, used by temml/katex. 587 // https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtd 588 'columnalign' => true, 589 'rowalign' => true, 590 ) 591 ), 592 593 // https://www.w3.org/TR/mathml-core/#semantics-and-presentation 594 'semantics' => $math_global_attributes, 595 'annotation' => array_merge( 596 $math_global_attributes, 597 array( 598 'encoding' => true, 599 ) 600 ), 601 602 // Non-standard but widely supported, used by temml/katex. 603 'menclose' => array_merge( 604 $math_global_attributes, 605 array( 606 'notation' => true, 607 ) 608 ), 609 ) 610 ); 611 612 /** 613 * @var array[] $allowedtags Array of KSES allowed HTML elements. 614 * @since 1.0.0 615 */ 616 $allowedtags = array( 617 'a' => array( 618 'href' => true, 619 'title' => true, 620 ), 621 'abbr' => array( 622 'title' => true, 623 ), 624 'acronym' => array( 625 'title' => true, 626 ), 627 'b' => array(), 628 'blockquote' => array( 629 'cite' => true, 630 ), 631 'cite' => array(), 632 'code' => array(), 633 'del' => array( 634 'datetime' => true, 635 ), 636 'em' => array(), 637 'i' => array(), 638 'q' => array( 639 'cite' => true, 640 ), 641 's' => array(), 642 'strike' => array(), 643 'strong' => array(), 644 ); 645 646 /** 647 * @var string[] $allowedentitynames Array of KSES allowed HTML entity names. 648 * @since 1.0.0 649 */ 650 $allowedentitynames = array( 651 'nbsp', 652 'iexcl', 653 'cent', 654 'pound', 655 'curren', 656 'yen', 657 'brvbar', 658 'sect', 659 'uml', 660 'copy', 661 'ordf', 662 'laquo', 663 'not', 664 'shy', 665 'reg', 666 'macr', 667 'deg', 668 'plusmn', 669 'acute', 670 'micro', 671 'para', 672 'middot', 673 'cedil', 674 'ordm', 675 'raquo', 676 'iquest', 677 'Agrave', 678 'Aacute', 679 'Acirc', 680 'Atilde', 681 'Auml', 682 'Aring', 683 'AElig', 684 'Ccedil', 685 'Egrave', 686 'Eacute', 687 'Ecirc', 688 'Euml', 689 'Igrave', 690 'Iacute', 691 'Icirc', 692 'Iuml', 693 'ETH', 694 'Ntilde', 695 'Ograve', 696 'Oacute', 697 'Ocirc', 698 'Otilde', 699 'Ouml', 700 'times', 701 'Oslash', 702 'Ugrave', 703 'Uacute', 704 'Ucirc', 705 'Uuml', 706 'Yacute', 707 'THORN', 708 'szlig', 709 'agrave', 710 'aacute', 711 'acirc', 712 'atilde', 713 'auml', 714 'aring', 715 'aelig', 716 'ccedil', 717 'egrave', 718 'eacute', 719 'ecirc', 720 'euml', 721 'igrave', 722 'iacute', 723 'icirc', 724 'iuml', 725 'eth', 726 'ntilde', 727 'ograve', 728 'oacute', 729 'ocirc', 730 'otilde', 731 'ouml', 732 'divide', 733 'oslash', 734 'ugrave', 735 'uacute', 736 'ucirc', 737 'uuml', 738 'yacute', 739 'thorn', 740 'yuml', 741 'quot', 742 'amp', 743 'lt', 744 'gt', 745 'apos', 746 'OElig', 747 'oelig', 748 'Scaron', 749 'scaron', 750 'Yuml', 751 'circ', 752 'tilde', 753 'ensp', 754 'emsp', 755 'thinsp', 756 'zwnj', 757 'zwj', 758 'lrm', 759 'rlm', 760 'ndash', 761 'mdash', 762 'lsquo', 763 'rsquo', 764 'sbquo', 765 'ldquo', 766 'rdquo', 767 'bdquo', 768 'dagger', 769 'Dagger', 770 'permil', 771 'lsaquo', 772 'rsaquo', 773 'euro', 774 'fnof', 775 'Alpha', 776 'Beta', 777 'Gamma', 778 'Delta', 779 'Epsilon', 780 'Zeta', 781 'Eta', 782 'Theta', 783 'Iota', 784 'Kappa', 785 'Lambda', 786 'Mu', 787 'Nu', 788 'Xi', 789 'Omicron', 790 'Pi', 791 'Rho', 792 'Sigma', 793 'Tau', 794 'Upsilon', 795 'Phi', 796 'Chi', 797 'Psi', 798 'Omega', 799 'alpha', 800 'beta', 801 'gamma', 802 'delta', 803 'epsilon', 804 'zeta', 805 'eta', 806 'theta', 807 'iota', 808 'kappa', 809 'lambda', 810 'mu', 811 'nu', 812 'xi', 813 'omicron', 814 'pi', 815 'rho', 816 'sigmaf', 817 'sigma', 818 'tau', 819 'upsilon', 820 'phi', 821 'chi', 822 'psi', 823 'omega', 824 'thetasym', 825 'upsih', 826 'piv', 827 'bull', 828 'hellip', 829 'prime', 830 'Prime', 831 'oline', 832 'frasl', 833 'weierp', 834 'image', 835 'real', 836 'trade', 837 'alefsym', 838 'larr', 839 'uarr', 840 'rarr', 841 'darr', 842 'harr', 843 'crarr', 844 'lArr', 845 'uArr', 846 'rArr', 847 'dArr', 848 'hArr', 849 'forall', 850 'part', 851 'exist', 852 'empty', 853 'nabla', 854 'isin', 855 'notin', 856 'ni', 857 'prod', 858 'sum', 859 'minus', 860 'lowast', 861 'radic', 862 'prop', 863 'infin', 864 'ang', 865 'and', 866 'or', 867 'cap', 868 'cup', 869 'int', 870 'sim', 871 'cong', 872 'asymp', 873 'ne', 874 'equiv', 875 'le', 876 'ge', 877 'sub', 878 'sup', 879 'nsub', 880 'sube', 881 'supe', 882 'oplus', 883 'otimes', 884 'perp', 885 'sdot', 886 'lceil', 887 'rceil', 888 'lfloor', 889 'rfloor', 890 'lang', 891 'rang', 892 'loz', 893 'spades', 894 'clubs', 895 'hearts', 896 'diams', 897 'sup1', 898 'sup2', 899 'sup3', 900 'frac14', 901 'frac12', 902 'frac34', 903 'there4', 904 ); 905 906 /** 907 * @var string[] $allowedxmlentitynames Array of KSES allowed XML entity names. 908 * @since 5.5.0 909 */ 910 $allowedxmlentitynames = array( 911 'amp', 912 'lt', 913 'gt', 914 'apos', 915 'quot', 916 ); 917 918 $allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags ); 919 } else { 920 $required_kses_globals = array( 921 'allowedposttags', 922 'allowedtags', 923 'allowedentitynames', 924 'allowedxmlentitynames', 925 ); 926 $missing_kses_globals = array(); 927 928 foreach ( $required_kses_globals as $global_name ) { 929 if ( ! isset( $GLOBALS[ $global_name ] ) || ! is_array( $GLOBALS[ $global_name ] ) ) { 930 $missing_kses_globals[] = '<code>$' . $global_name . '</code>'; 931 } 932 } 933 934 if ( $missing_kses_globals ) { 935 _doing_it_wrong( 936 'wp_kses_allowed_html', 937 sprintf( 938 /* translators: 1: CUSTOM_TAGS, 2: Global variable names. */ 939 __( 'When using the %1$s constant, make sure to set these globals to an array: %2$s.' ), 940 '<code>CUSTOM_TAGS</code>', 941 implode( ', ', $missing_kses_globals ) 942 ), 943 '6.2.0' 944 ); 945 } 946 947 $allowedtags = wp_kses_array_lc( $allowedtags ); 948 $allowedposttags = wp_kses_array_lc( $allowedposttags ); 949 } 950 951 /** 952 * Filters text content and strips out disallowed HTML. 953 * 954 * This function makes sure that only the allowed HTML element names, attribute 955 * names, attribute values, and HTML entities will occur in the given text string. 956 * 957 * This function expects unslashed data. 958 * 959 * @see wp_kses_post() for specifically filtering post content and fields. 960 * @see wp_allowed_protocols() for the default allowed protocols in link URLs. 961 * 962 * @see 'wp_kses_force_legacy_parser' to opt-out of the new HTML-API-based implementation. 963 * 964 * @since 1.0.0 965 * @since 7.2.0 Rewritten with the HTML API for more reliable parsing. 966 * 967 * @global string $wp_kses_operating_mode 968 * 969 * @param string $content Text content to filter. 970 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 971 * or a context name such as 'post'. {@see wp_kses_allowed_html()} 972 * for the list of accepted context names. 973 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 974 * Defaults to the result of wp_allowed_protocols(). 975 * @return string Filtered content containing only the allowed HTML. 976 */ 977 function wp_kses( $content, $allowed_html, $allowed_protocols = array() ) { 978 global $wp_kses_operating_mode; 979 980 /** 981 * Filters whether to rely on the legacy parsing inside `wp_kses()`. 982 * 983 * @since 7.2.0 984 * 985 * @param bool $force_legacy_parser Whether to force using the legacy parser 986 * instead of relying on the HTML API. 987 */ 988 if ( ! apply_filters( 'wp_kses_force_legacy_parser', true ) ) { 989 return wp_sanitize_html_kses( (string) $content, $allowed_html, $allowed_protocols ); 990 } 991 992 if ( empty( $allowed_protocols ) ) { 993 $allowed_protocols = wp_allowed_protocols(); 994 } 995 996 $content = wp_kses_no_null( $content, array( 'slash_zero' => 'keep' ) ); 997 $content = wp_kses_normalize_entities( $content ); 998 999 // Ensure that the legacy pre-kses filters run by setting the operating mode appropriately. 1000 try { 1001 $previous_kses_mode = $wp_kses_operating_mode; 1002 $wp_kses_operating_mode = 'legacy'; 1003 $content = wp_kses_hook( $content, $allowed_html, $allowed_protocols ); 1004 } finally { 1005 $wp_kses_operating_mode = $previous_kses_mode; 1006 } 1007 1008 return wp_kses_split( $content, $allowed_html, $allowed_protocols ); 1009 } 1010 1011 /** 1012 * Filters HTML content, sanitizing according to given policies. 1013 * 1014 * Modern implementation of {@see wp_kses()} built with the HTML API. 1015 * 1016 * @since 7.2.0 1017 * 1018 * @global string $wp_kses_operating_mode 1019 * 1020 * @access private This function should not be called directly, as it serves a transitionary 1021 * role while replacing the implementation of {@see \wp_kses()}. 1022 * 1023 * @param string $content Text content to filter. 1024 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 1025 * or a context name such as 'post'. See wp_kses_allowed_html() 1026 * for the list of accepted context names. 1027 * @param string[] $allowed_protocols Optional. Array of allowed URL protocols. 1028 * Defaults to the result of wp_allowed_protocols(). 1029 * @return string Filtered content containing only the allowed HTML. 1030 */ 1031 function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = array() ) { 1032 global $wp_kses_operating_mode; 1033 1034 $specified_allowed_html = $allowed_html; 1035 1036 $allowed_protocols = empty( $allowed_protocols ) 1037 ? wp_allowed_protocols() 1038 : $allowed_protocols; 1039 1040 // Preserve legacy behavior of stripping unwanted C0 control characters. 1041 $content = preg_replace( '/[\x01-\x08\x0B\x0C\x0E-\x1F]/', '', $content ); 1042 1043 /* 1044 * Call legacy pre-kses filters that might have been added by plugins. 1045 * 1046 * Also set the operating mode to bypass the pre-filters from the legacy 1047 * implementation of `wp_kses()`, as these filters are now run in-band 1048 * during the processing of the input document. 1049 */ 1050 try { 1051 $previous_kses_mode = $wp_kses_operating_mode; 1052 $wp_kses_operating_mode = 'html-api'; 1053 $content = wp_kses_hook( $content, $specified_allowed_html, $allowed_protocols ); 1054 } finally { 1055 $wp_kses_operating_mode = $previous_kses_mode; 1056 } 1057 1058 $allowed_html = is_array( $allowed_html ) 1059 ? $allowed_html 1060 : wp_kses_allowed_html( $allowed_html ); 1061 1062 /* 1063 * The explanation for this call is that “the quoting from `preg_replace(//e)` 1064 * requires” it, but this version of `wp_kses()` doesn’t rely on PCRE functions 1065 * to parse HTML. Given that this corrupts text, it will be skipped. 1066 */ 1067 //$content = wp_kses_stripslashes( $content ); 1068 1069 $processor = new class( $content, $specified_allowed_html, $allowed_html, $allowed_protocols, wp_kses_uri_attributes() ) extends WP_HTML_Tag_Processor { 1070 /** 1071 * An array of allowed HTML elements and attributes, or a context name such as 'post'. 1072 * 1073 * It’s important to store this alongside the resolved allowable HTML because some 1074 * filters in some plugins look for the string values, e.g. for “post” instead of 1075 * the resolved array, and apply logic based on that context. 1076 * 1077 * @see wp_kses_allowed_html() for the list of accepted context names. 1078 * @see self::$allowed_html for the resolved array of allowable HTML elements and attributes. 1079 * 1080 * @since 7.2.0 1081 * 1082 * @var array[]|string 1083 */ 1084 private $specified_allowed_html; 1085 1086 /** 1087 * An array of allowed HTML elements and attributes. 1088 * 1089 * This array of allowable HTML elements and attributes is resolved from the value provided 1090 * to the sanitizer function. It’s resolved at the start to avoid repeatedly calling the 1091 * filter stack and array-merging computations. However, it’s still necessary to carry along 1092 * the provided context so that filters expecting the array-or-string version continue to 1093 * operate properly. 1094 * 1095 * @see self::$specified_allowed_html 1096 * 1097 * @since 7.2.0 1098 * 1099 * @var array[] 1100 */ 1101 private $allowed_html; 1102 1103 /** 1104 * Array of allowed URL protocols. 1105 * 1106 * @see \wp_allowed_protocols() 1107 * 1108 * @since 7.2.0 1109 * 1110 * @var string[] 1111 */ 1112 private $allowed_protocols; 1113 1114 /** 1115 * List of attributes whose values are expected to be considered URLs. 1116 * 1117 * @see \wp_kses_uri_attributes() 1118 * 1119 * @since 7.2.0 1120 * 1121 * @var string[] 1122 */ 1123 private $uri_attributes; 1124 1125 /** 1126 * Tracks balanced tags when inside foreign content. 1127 * 1128 * @since 7.2.0 1129 * 1130 * @var string[] 1131 */ 1132 private $foreign_content_stack = array(); 1133 1134 /** 1135 * Tracks how deeply into a MathML ANNOTATION-XML element the current token is; 1136 * an optimization to avoid checking up the open-element stack on every token. 1137 * 1138 * @since 7.2.0 1139 * 1140 * @var int 1141 */ 1142 private $math_annotation_xml_depth = 0; 1143 1144 /** 1145 * Tracks, for each TEMPLATE element open in the output, whether a browser parses 1146 * its contents in the "in column group" insertion mode, which ignores the start 1147 * tags of special atomic elements. 1148 * 1149 * Each entry is `null` until the first start tag written into the template decides 1150 * it: a COL element starts a column group, while most other start tags start other 1151 * insertion modes, none of which ignore these start tags. 1152 * 1153 * @since 7.2.0 1154 * 1155 * @var array<bool|null> 1156 */ 1157 private $template_column_groups = array(); 1158 1159 /** 1160 * Constructor function, used internally. 1161 * 1162 * @since 7.2.0 1163 * @access private 1164 * 1165 * @param string $html Content to filter. 1166 * @param array[]|string $specified_allowed_html Context passed into sanitizer. 1167 * @param array[] $allowed_html Resolved allowable HTML. 1168 * @param string[] $allowed_protocols Resolved allowable protocols. 1169 * @param string[] $uri_attributes Resolved URI attributes. 1170 */ 1171 public function __construct( $html, $specified_allowed_html, $allowed_html, $allowed_protocols, $uri_attributes ) { 1172 parent::__construct( $html ); 1173 1174 $this->specified_allowed_html = $specified_allowed_html; 1175 $this->allowed_html = $allowed_html; 1176 $this->allowed_protocols = $allowed_protocols; 1177 $this->uri_attributes = $uri_attributes; 1178 } 1179 1180 /** 1181 * Returns the raw byte-span of the currently-matched token, 1182 * assuming that the parser is matched on a token. 1183 * 1184 * @since 7.2.0 1185 * @access private 1186 * 1187 * @return WP_HTML_Span|null 1188 */ 1189 private function get_span() { 1190 $this->set_bookmark( 'here' ); 1191 1192 if ( ! isset( $this->bookmarks['here'] ) ) { 1193 return null; 1194 } 1195 1196 return $this->bookmarks['here']; 1197 } 1198 1199 /** 1200 * Returns a representation of the given substring of input HTML text content where the 1201 * character references are normalized and unescaped syntax characters are escaped. 1202 * 1203 * @since 7.2.0 1204 * @access private 1205 * @ignore 1206 * 1207 * @param 'data'|'attribute' $context Apply decoding rules pertaining to the appropriate context. 1208 * @param string $html Raw HTML document containing the referenced text content. 1209 * @param int $start The text span starts here. 1210 * @param int $length The text span extends this many bytes. 1211 * @return string Normalized text node content. 1212 */ 1213 private static function normalize_text( string $context, string $html, int $start, int $length ): string { 1214 $output = ''; 1215 $ref_length = 0; 1216 $at = $start; 1217 $was_at = $start; 1218 $end = $start + $length; 1219 1220 while ( $at < $end ) { 1221 $next_at = $at + strcspn( $html, '&', $at, $end - $at ); 1222 if ( $next_at >= $end ) { 1223 break; 1224 } 1225 1226 $decoded = WP_HTML_Decoder::read_character_reference( $context, $html, $next_at, $ref_length ); 1227 1228 /** 1229 * Decoding past the end of the text span might return a different decode than 1230 * one which decodes a truncated string. 1231 * 1232 * In the cases of a failure to decode, the length of seven bytes comes from the 1233 * fact that the longest matchable named character references containing no 1234 * semicolons are seven ASCII bytes long. It’s exactly these situations within 1235 * attributes where the following character might impact what’s decoded; this is 1236 * what {@see WP_HTML_Decoder::read_character_reference()} might see since it 1237 * doesn’t allow specifying a final offset at which to stop searching. 1238 * 1239 * Therefore, if a match failed within that distance from the end inside an HTML 1240 * attribute’s value, then it is best to cut off the trailing part of the input 1241 * and normalize that separately. 1242 * 1243 * Example: 1244 * 1245 * '·=' is rejected when the length is seven because the following '=' 1246 * is not unambiguous. However, that '=' was not part of the span 1247 * of text to decode. 1248 * 1249 * '·' on the other hand, has no ambiguous follower, and will thus be 1250 * decoded in attribute value contexts. 1251 */ 1252 $remaining_length = $start + $length - $next_at; 1253 if ( 1254 $end < strlen( $html ) && 1255 ( 1256 ( null !== $decoded && $ref_length > $remaining_length ) || 1257 ( null === $decoded && 'attribute' === $context && $remaining_length <= 7 ) 1258 ) 1259 ) { 1260 $output .= substr( $html, $was_at, $next_at - $was_at ); 1261 $output .= self::normalize_text( $context, substr( $html, $next_at, $remaining_length ), 0, $remaining_length ); 1262 $was_at = $end; 1263 break; 1264 } 1265 1266 /* 1267 * Failure to decode implies that there’s an unescaped AMPERSAND character; escape it. 1268 */ 1269 if ( null === $decoded ) { 1270 $output .= substr( $html, $was_at, $next_at - $was_at ); 1271 $output .= '&'; 1272 $at = $next_at + 1; 1273 $was_at = $at; 1274 continue; 1275 } 1276 1277 $has_semicolon = ';' === $html[ $next_at + $ref_length - 1 ]; 1278 1279 if ( '#' === $html[ $next_at + 1 ] ) { 1280 /* 1281 * Given that the character decoded at least partially, there are 1282 * certain guarantees on the syntax forms here. The only exceptions 1283 * are where the decoder returns U+FFFD because the digits failed 1284 * to represent a valid code point. 1285 */ 1286 $digits_end = $next_at + $ref_length - ( $has_semicolon ? 1 : 0 ); 1287 $hex_sigil = $html[ $next_at + 2 ]; 1288 $is_hex = 'x' === $hex_sigil || 'X' === $hex_sigil; 1289 $digits_at = $next_at + ( $is_hex ? 3 : 2 ); 1290 $zero_count = strspn( $html, '0', $digits_at, $digits_end - $digits_at ); 1291 $non_zero_start = $digits_at + $zero_count; 1292 $digit_count = $digits_end - $non_zero_start; 1293 $has_no_lowers = strcspn( $html, 'abcdef', $digits_at + $zero_count, $digit_count ) === $digit_count; 1294 1295 /* 1296 * Only an actual numeric character reference indicating U+FFFD should be retained; 1297 * other malformed sequences should actually receive the U+FFFD in the output. 1298 */ 1299 if ( 1300 "\u{FFFD}" === $decoded && 1301 ( 0 === $digit_count || 0 !== substr_compare( $html, $is_hex ? 'FFFD' : '65533', $digits_at + $zero_count, $digit_count, true ) ) 1302 ) { 1303 $output .= substr( $html, $was_at, $next_at - $was_at ); 1304 $output .= "\u{FFFD}"; 1305 $at = $next_at + $ref_length; 1306 $was_at = $at; 1307 continue; 1308 } 1309 1310 // Fully-normalized numeric character references may be passed through. 1311 if ( 0 === $zero_count && $has_semicolon && ( ! $is_hex || ( 'x' === $hex_sigil && $has_no_lowers ) ) ) { 1312 $at = $next_at + $ref_length; 1313 continue; 1314 } 1315 1316 // Otherwise rebuild them. 1317 $sigil = $is_hex ? 'x' : ''; 1318 $digits = strtoupper( substr( $html, $digits_at + $zero_count, $digit_count ) ); 1319 $output .= substr( $html, $was_at, $next_at - $was_at ); 1320 $output .= "&#{$sigil}{$digits};"; 1321 $at = $next_at + $ref_length; 1322 $was_at = $at; 1323 continue; 1324 } 1325 1326 // Semicolon-terminated named character references may pass through. 1327 if ( $has_semicolon ) { 1328 $at = $next_at + $ref_length; 1329 continue; 1330 } 1331 1332 // Otherwise add the missing semicolon. 1333 $output .= substr( $html, $was_at, $next_at + $ref_length - $was_at ); 1334 $output .= ';'; 1335 $at = $next_at + $ref_length; 1336 $was_at = $at; 1337 } 1338 1339 if ( $start === $was_at ) { 1340 $output = substr( $html, $start, $length ); 1341 } elseif ( $was_at < $end ) { 1342 $output .= substr( $html, $was_at, $end - $was_at ); 1343 } 1344 1345 return strtr( 1346 $output, 1347 'attribute' === $context 1348 ? array( 1349 '<' => '<', 1350 '>' => '>', 1351 '"' => '"', 1352 "'" => ''', 1353 ) 1354 : array( 1355 '<' => '<', 1356 '>' => '>', 1357 ) 1358 ); 1359 } 1360 1361 /** 1362 * Indicates if the currently-matched token, given the parsed context, would require more 1363 * complicated parsing rules to proceed without risking escape from foreign content. 1364 * 1365 * @since 7.2.0 1366 * @access private 1367 * 1368 * @param bool $is_inside_mathml_text_integration_point Whether the token is inside a MathML text integration point. 1369 * @param bool $is_inside_svg_html_integration_point Whether the token is inside an SVG HTML integration point. 1370 * @return bool Whether the current token risks escaping foreign content. 1371 */ 1372 private function could_escape_foreign_content( bool $is_inside_mathml_text_integration_point, bool $is_inside_svg_html_integration_point ): bool { 1373 $token_name = $this->get_token_name(); 1374 $is_closer = $this->is_tag_closer(); 1375 $namespace = $this->get_namespace(); 1376 $self_closing = ! $is_closer && $this->has_self_closing_flag(); 1377 1378 if ( ! $is_closer && $is_inside_svg_html_integration_point ) { 1379 return true; 1380 } 1381 1382 /* 1383 * These two elements are excepted in HTML from the normal processing 1384 * rules because they function in similar ways to character data. 1385 * 1386 * > The mglyph element is used to represent non-standard characters or 1387 * > symbols by images; the malignmark element establishes an alignment 1388 * > point for use within table constructs, and is otherwise invisible. 1389 * 1390 * They must contain no elements, so only allow self-closing tags. 1391 */ 1392 if ( ! $is_closer && $is_inside_mathml_text_integration_point ) { 1393 return ! ( $self_closing && ( 'MGLYPH' === $token_name || 'MALIGNMARK' === $token_name ) ); 1394 } 1395 1396 if ( 1397 ! $is_closer && 1398 'FONT' === $token_name && 1399 ( 1400 null !== $this->get_attribute( 'color' ) || 1401 null !== $this->get_attribute( 'face' ) || 1402 null !== $this->get_attribute( 'size' ) 1403 ) 1404 ) { 1405 return true; 1406 } 1407 1408 if ( 1409 ! $is_closer && 1410 in_array( 1411 $token_name, 1412 array( 1413 'B', 1414 'BIG', 1415 'BLOCKQUOTE', 1416 'BODY', 1417 'BR', 1418 'CENTER', 1419 'CODE', 1420 'DD', 1421 'DIV', 1422 'DL', 1423 'DT', 1424 'EM', 1425 'EMBED', 1426 'H1', 1427 'H2', 1428 'H3', 1429 'H4', 1430 'H5', 1431 'H6', 1432 'HEAD', 1433 'HR', 1434 'I', 1435 'IMG', 1436 'LI', 1437 'LISTING', 1438 'MENU', 1439 'META', 1440 'NOBR', 1441 'OL', 1442 'P', 1443 'PRE', 1444 'RUBY', 1445 'S', 1446 'SMALL', 1447 'SPAN', 1448 'STRONG', 1449 'STRIKE', 1450 'SUB', 1451 'SUP', 1452 'TABLE', 1453 'TT', 1454 'U', 1455 'UL', 1456 'VAR', 1457 ), 1458 true 1459 ) || 1460 ( 1461 $is_closer && 1462 in_array( 1463 $token_name, 1464 array( 1465 'BR', 1466 'P', 1467 ), 1468 true 1469 ) 1470 ) 1471 ) { 1472 return true; 1473 } 1474 1475 if ( 'math' === $namespace && ! $is_closer && ! $self_closing ) { 1476 $encoding = $this->get_attribute( 'encoding' ); 1477 if ( 1478 'ANNOTATION-XML' === $token_name && 1479 is_string( $encoding ) && 1480 ( 1481 0 === strcasecmp( $encoding, 'text/html' ) || 1482 0 === strcasecmp( $encoding, 'application/xhtml+xml' ) 1483 ) 1484 ) { 1485 return true; 1486 } 1487 1488 /* 1489 * When SVG becomes a direct descendant of a MathML ANNOTATION-XML, 1490 * the namespace remains `math` but there could be an SVG element 1491 * with an HTML integration point. Conservatively reject any child 1492 * SVG element inside a MathML ANNOTATION-XML to prevent this. 1493 */ 1494 if ( 'SVG' === $token_name && $this->math_annotation_xml_depth > 0 ) { 1495 return true; 1496 } 1497 } 1498 1499 return false; 1500 } 1501 1502 /** 1503 * Indicates if a given string contains text that would parse as a block delimiter. 1504 * 1505 * @since 7.2.0 1506 * @access private 1507 * 1508 * @param string $text Text to check for a block comment delimiter. 1509 * @return bool Whether a block comment delimiter of any kind was found in the given string. 1510 */ 1511 private static function contains_a_block_delimiter( string $text ): bool { 1512 if ( '' === $text ) { 1513 return false; 1514 } 1515 1516 $processor = new WP_Block_Processor( $text ); 1517 1518 return $processor->next_delimiter(); 1519 } 1520 1521 /** 1522 * Finds the next token, first telling the tokenizer which special atomic elements a 1523 * browser would insert from their start tags, given the output written so far. 1524 * 1525 * Where a browser ignores one of these start tags, it parses what follows as markup 1526 * instead of as the element's text, so it must be sanitized as markup. 1527 * 1528 * @since 7.2.0 1529 * @access private 1530 * 1531 * @return bool Whether a token was parsed. 1532 */ 1533 public function next_token(): bool { 1534 $this->inserts_special_atomic_elements = true !== end( $this->template_column_groups ); 1535 1536 return parent::next_token(); 1537 } 1538 1539 /** 1540 * Records how a start tag written to the output affects the parsing of special 1541 * atomic elements in a browser. 1542 * 1543 * @since 7.2.0 1544 * @access private 1545 * 1546 * @param string $token_name Name of the start tag written to the output. 1547 * @param string $token_namespace Namespace of the start tag. 1548 * @phpstan-param non-falsy-string $token_name 1549 * @phpstan-param non-falsy-string $token_namespace 1550 */ 1551 private function note_written_start_tag( string $token_name, string $token_namespace ): void { 1552 $innermost = count( $this->template_column_groups ) - 1; 1553 if ( $innermost < 0 || null !== $this->template_column_groups[ $innermost ] ) { 1554 return; 1555 } 1556 1557 // These start tags are processed without deciding how the template contents are parsed. 1558 if ( 1559 'html' === $token_namespace && 1560 in_array( $token_name, array( 'BASE', 'BASEFONT', 'BGSOUND', 'LINK', 'META', 'NOFRAMES', 'SCRIPT', 'STYLE', 'TEMPLATE', 'TITLE' ), true ) 1561 ) { 1562 return; 1563 } 1564 1565 $this->template_column_groups[ $innermost ] = 'html' === $token_namespace && 'COL' === $token_name; 1566 } 1567 1568 /** 1569 * Returns a sanitized copy of the input HTML. 1570 * 1571 * @since 7.2.0 1572 * @access private 1573 * 1574 * @return string Sanitized copy of given input HTML. 1575 */ 1576 public function sanitize() { 1577 $template_depth = 0; 1578 $output = ''; 1579 $input_special_newline_at = PHP_INT_MIN; 1580 $special_newline_at = PHP_INT_MIN; 1581 $foreign_content_starts_at = PHP_INT_MAX; 1582 $open_blocks = array(); 1583 $open_blocks_at = array(); 1584 $foreign_closed_blocks = array(); 1585 1586 $is_in_mathml_text_integration_point = false; 1587 $is_in_svg_html_integration_point = false; 1588 1589 /** 1590 * These are treated as void elements inside the HTML API 1591 * due to the special handling of their inner text content. 1592 */ 1593 $special_atomic_elements = array( 1594 'IFRAME', 1595 'NOEMBED', 1596 'NOFRAMES', 1597 'SCRIPT', 1598 'STYLE', 1599 'TEXTAREA', 1600 'TITLE', 1601 'XMP', 1602 ); 1603 1604 while ( $this->next_token() ) { 1605 $token_name = $this->get_token_name(); 1606 $token_type = $this->get_token_type(); 1607 $namespace = $this->get_namespace(); 1608 $is_closer = $this->is_tag_closer(); 1609 $here = $this->get_span(); 1610 1611 if ( ! $is_closer && 'html' === $namespace && ( 'PRE' === $token_name || 'LISTING' === $token_name ) ) { 1612 $input_special_newline_at = $here->start + $here->length; 1613 } 1614 1615 /* 1616 * Prevent allowing NOSCRIPT elements whose parsing rules change 1617 * based on whether the scripting flag is enabled in a browser. 1618 * Rely on trusted inputs for producing the appropriate NOSCRIPT 1619 * content, and prevent untrusted inputs from generating it. 1620 */ 1621 if ( 'NOSCRIPT' === $token_name && ! $is_closer ) { 1622 break; 1623 } 1624 1625 /* 1626 * Output should only ever render inside a BODY element or its 1627 * descendants, where FRAMESET is ignored. Prevent untrusted 1628 * sources from creating these tags to avoid further confusion. 1629 */ 1630 if ( 'FRAMESET' === $token_name && 'html' === $namespace ) { 1631 continue; 1632 } 1633 1634 /* 1635 * PLAINTEXT is unique in that it changes the tokenization. Everything in 1636 * a document following the PLAINTEXT opening tag is interpreted as character 1637 * data, meaning there are no more tags, comments, or anything. Because of 1638 * this, it is the only element without a closing tag. 1639 * 1640 * Because of its unique role, it’s risky to leave in place because very few 1641 * parsers are going to recognize the tag and properly switch modes for the 1642 * rest of the document. Instead, the PLAINTEXT tag is removed and its content 1643 * is re-written as an escaped text node. 1644 * 1645 * This changes the structure of the document, because no PLAINTEXT element 1646 * will appear, and it won’t be possible to style its contents, but the element 1647 * is discouraged anyway and should not be allowed from untrusted inputs. 1648 */ 1649 if ( 'PLAINTEXT' === $token_name && 'html' === $namespace && ! $is_closer ) { 1650 if ( $template_depth > 0 && ! isset( $this->allowed_html['template'] ) ) { 1651 break; 1652 } 1653 1654 $text = substr( $this->html, $here->start + $here->length ); 1655 1656 $needs_special_newline = ( 1657 strlen( $output ) === $special_newline_at && 1658 1 === strspn( $text, "\n\r", 0, 1 ) 1659 ); 1660 1661 if ( $needs_special_newline ) { 1662 $output .= "\n"; 1663 } 1664 1665 $output .= strtr( 1666 $text, 1667 array( 1668 "\x00" => "\u{FFFD}", 1669 "\r\n" => "\n", 1670 "\r" => "\n", 1671 '<' => '<', 1672 '&' => '&', 1673 '>' => '>', 1674 ) 1675 ); 1676 1677 break; 1678 } 1679 1680 $is_in_text_integration_point = ( 1681 $is_in_mathml_text_integration_point || 1682 ( ! $is_closer && $is_in_svg_html_integration_point ) 1683 ); 1684 1685 $text = ( '#text' !== $token_type ) ? $this->get_modifiable_text() : ''; 1686 1687 /* 1688 * Enter the foreign content and change the parsing namespace 1689 * so that the parser recognizes real self-closing elements. 1690 */ 1691 $is_svg_or_math = 'MATH' === $token_name || 'SVG' === $token_name; 1692 $has_self_closing_flag = ! $is_closer && $this->has_self_closing_flag(); 1693 if ( $is_svg_or_math && ! $is_closer && 'html' === $namespace ) { 1694 $this->change_parsing_namespace( strtolower( $token_name ) ); 1695 $namespace = $this->get_namespace(); 1696 } 1697 1698 if ( 'html' !== $namespace && '#tag' === $token_type ) { 1699 /* 1700 * Ensure that only well-formed foreign content is allowed. 1701 * Since un-balanced closing tags might implicitly close the 1702 * open foreign-content element, these must be rejected. 1703 */ 1704 if ( $is_closer ) { 1705 $open_element = array_pop( $this->foreign_content_stack ); 1706 if ( null === $open_element || $token_name !== $open_element ) { 1707 break; 1708 } 1709 1710 if ( 'math' === $namespace && 'ANNOTATION-XML' === $open_element ) { 1711 --$this->math_annotation_xml_depth; 1712 } 1713 1714 /* 1715 * Reset the foreign content tracker so it doesn’t truncate 1716 * unintentionally after foreign content has properly closed. 1717 */ 1718 if ( empty( $this->foreign_content_stack ) ) { 1719 $foreign_content_starts_at = PHP_INT_MAX; 1720 } 1721 } else { 1722 /* 1723 * Track the opening of the last transition into foreign 1724 * content so that it can be discarded when encountering 1725 * tags that would require more substantial parsing. 1726 */ 1727 if ( empty( $this->foreign_content_stack ) ) { 1728 $foreign_content_starts_at = strlen( $output ); 1729 } 1730 1731 $this->foreign_content_stack[] = $token_name; 1732 1733 if ( 'math' === $namespace && 'ANNOTATION-XML' === $token_name ) { 1734 ++$this->math_annotation_xml_depth; 1735 } 1736 } 1737 } 1738 1739 if ( 'TEMPLATE' === $token_name && 'html' === $namespace && ! $is_closer ) { 1740 ++$template_depth; 1741 $this->template_column_groups[] = null; 1742 } 1743 1744 $skip_token = ( 1745 ( 1746 $template_depth > 0 && 1747 ! isset( $this->allowed_html['template'] ) 1748 ) || 1749 ( 1750 ! empty( $this->foreign_content_stack ) && 1751 ! isset( $this->allowed_html[ strtolower( $this->foreign_content_stack[0] ) ] ) 1752 ) 1753 ); 1754 1755 switch ( $token_type ) { 1756 case '#text': 1757 if ( $skip_token ) { 1758 break; 1759 } 1760 1761 $text = self::normalize_text( 'data', $this->html, $here->start, $here->length ); 1762 $text = str_replace( array( "\r\n", "\r" ), "\n", $text ); 1763 1764 /* 1765 * A PRE or LISTING element consumes a leading newline even if stripped from the 1766 * output, so detect and remove one, remembering the original leading newline. 1767 */ 1768 $special_newline = "\n"; 1769 if ( $here->start === $input_special_newline_at ) { 1770 $starting_char = $text[0] ?? ''; 1771 $newline_length = 1; 1772 if ( '&' === $starting_char ) { 1773 $starting_char = WP_HTML_Decoder::read_character_reference( 'data', $text, 0, $newline_length ); 1774 } 1775 1776 if ( "\n" === $starting_char ) { 1777 $special_newline = substr( $text, 0, $newline_length ); 1778 $text = substr( $text, $newline_length ); 1779 } 1780 } 1781 1782 $text = ( 'html' === $namespace || $is_in_text_integration_point ) 1783 ? str_replace( "\x00", '', $text ) 1784 : str_replace( "\x00", "\u{FFFD}", $text ); 1785 1786 if ( strlen( $output ) === $special_newline_at && strlen( $text ) > 0 ) { 1787 $starting_char = $text[0]; 1788 if ( '&' === $starting_char ) { 1789 $starting_char = WP_HTML_Decoder::read_character_reference( 'data', $text ); 1790 } 1791 1792 if ( 1 === strspn( $starting_char, "\r\n", 0, 1 ) ) { 1793 $output .= $special_newline; 1794 } 1795 } 1796 1797 $output .= $text; 1798 break; 1799 1800 /* 1801 * Untrusted sources should not be creating these kinds of tokens, 1802 * so remove them entirely from the output. 1803 */ 1804 case '#doctype': 1805 case '#presumptuous-tag': 1806 case '#processing-instruction': 1807 break; 1808 1809 /* 1810 * It’s questionable whether these should be allowed through, but 1811 * the legacy behavior supports it. Therefore, allow them as long 1812 * as they don’t contain potentially confusing syntax characters. 1813 */ 1814 case '#funky-comment': 1815 if ( ! $skip_token && ! str_contains( $text, '<' ) ) { 1816 $output .= substr( $this->html, $here->start, $here->length ); 1817 } 1818 break; 1819 1820 /* 1821 * `wp_kses()` runs iteratively on the content inside of these tokens, 1822 * but the content is benign in a browser. 1823 */ 1824 case '#comment': 1825 if ( $skip_token ) { 1826 break; 1827 } 1828 1829 /* 1830 * There are several kinds of malformed HTML which are handled by interpreting 1831 * them as HTML comments. For example, `<?>` is called a “bogus comment” by the 1832 * HTML specification, but when loaded by a browser is equivalent to `<!--?-->`. 1833 * In this way, interacting with the DOM via JavaScript differs from handling 1834 * the textual representation of a page in PHP. 1835 * 1836 * Ignore these non-normative comment forms to protect downstream parsers which 1837 * might not be expecting their kinds of syntax. This prevents mis-parses for 1838 * code which over-simplifies HTML parsing. 1839 */ 1840 if ( WP_HTML_Tag_Processor::COMMENT_AS_HTML_COMMENT !== $this->get_comment_type() ) { 1841 break; 1842 } 1843 1844 // Apply special filtering for block comment delimiters with JSON attributes. 1845 $comment = substr( $this->html, $here->start, $here->length ); 1846 1847 /* 1848 * A comment like `<!-- notes --!>` still appears as a normative HTML comment, 1849 * but as an incorrectly-closed comment. Ignore these as well, as part of only 1850 * allowing normative comment contents. 1851 */ 1852 $was_incorrectly_closed = '!' === $comment[ strlen( $comment ) - 2 ]; 1853 if ( $was_incorrectly_closed ) { 1854 break; 1855 } 1856 1857 $block_processor = new WP_Block_Processor( $comment ); 1858 if ( $block_processor->next_token() && ! $block_processor->is_html() ) { 1859 $block_type = $block_processor->get_block_type(); 1860 $implicit_block_type = str_starts_with( $block_type, 'core/' ) 1861 ? substr( $block_type, /* 'core/' */ 5 ) 1862 : $block_type; 1863 1864 switch ( $block_processor->get_delimiter_type() ) { 1865 // Track when blocks open and when they don’t self-close. 1866 case WP_Block_Processor::OPENER: 1867 $open_blocks[] = $implicit_block_type; 1868 $open_blocks_at[] = strlen( $output ); 1869 break; 1870 1871 // Track when blocks close. 1872 case WP_Block_Processor::CLOSER: 1873 if ( empty( $open_blocks ) ) { 1874 break 2; 1875 } 1876 1877 /* 1878 * The default parser closes any open block, even when 1879 * the names don’t match. Preserve this behavior here 1880 * to avoid differences in sanitization and parsing. 1881 */ 1882 $closed_block = array_pop( $open_blocks ); 1883 $closed_block_at = array_pop( $open_blocks_at ); 1884 1885 if ( 'html' !== $namespace && $closed_block_at < $foreign_content_starts_at ) { 1886 $foreign_closed_blocks[] = $closed_block; 1887 } 1888 } 1889 1890 // Filter block attributes for opening delimiters. 1891 $attributes = $block_processor->allocate_and_return_parsed_attributes(); 1892 $voider = WP_Block_Processor::VOID === $block_processor->get_delimiter_type() ? '/' : ''; 1893 if ( $block_processor->opens_block() ) { 1894 if ( isset( $attributes ) ) { 1895 $attributes = filter_block_kses_value( 1896 $attributes, 1897 $this->specified_allowed_html, 1898 $this->allowed_protocols, 1899 array( 'blockName' => $block_type ) 1900 ); 1901 } 1902 } 1903 1904 // Fully normalize all block delimiters: name, whitespace, attributes, flags. 1905 if ( WP_Block_Processor::CLOSER === $block_processor->get_delimiter_type() ) { 1906 $text = " /wp:{$implicit_block_type} "; 1907 } elseif ( ! empty( $attributes ) ) { 1908 $serialized_attributes = serialize_block_attributes( $attributes ); 1909 1910 $text = " wp:{$implicit_block_type} {$serialized_attributes} {$voider}"; 1911 } else { 1912 $text = " wp:{$implicit_block_type} {$voider}"; 1913 } 1914 } 1915 1916 /* 1917 * Legacy `wp_kses()` recursively calls itself on the contents of comments. 1918 * Since comment content is not escaped, this changes the meaning of those 1919 * comments when parsed. Still, code often expects to find tag-like syntax 1920 * only when they are real tags. This legacy defect is preserved to avoid 1921 * presenting content that downstream parsers might misinterpret as markup. 1922 */ 1923 $text = strtr( $text, array( '<' => '<' ) ); 1924 1925 $output .= "<!--{$text}-->"; 1926 break; 1927 1928 /* 1929 * True CDATA sections only exist within embedded SVG and MathML content, 1930 * where they represent text data without any escaping. However, because 1931 * parsers tend to vary on how to parse these, for untrusted inputs, 1932 * rewrite all CDATA sections as normal escaped text. 1933 */ 1934 case '#cdata-section': 1935 if ( ! $skip_token ) { 1936 $output .= strtr( 1937 $text, 1938 array( 1939 "\x00" => "\u{FFFD}", 1940 '<' => '<', 1941 '&' => '&', 1942 '>' => '>', 1943 ) 1944 ); 1945 } 1946 1947 break; 1948 1949 case '#tag': 1950 /* 1951 * Any failures inside foreign content should return the part of 1952 * the post processed up until the entrance of the foreign content. 1953 * This is necessary because it’s only inside foreign content that 1954 * the self-closing flag indicates a self-closing element. 1955 * 1956 * While the HTML Processor can enter into SVG and MATH and track 1957 * when they close, it’s substantially more complicated and requires 1958 * considerable accounting. To avoid all of that, and to accept the 1959 * kind of content that is nominal and safe, track only when the 1960 * next tag _could_ lead to implicit changing of the parsing namespace 1961 * or insertion mode. 1962 */ 1963 if ( 1964 'html' !== $namespace && 1965 $this->could_escape_foreign_content( 1966 $is_in_mathml_text_integration_point, 1967 $is_in_svg_html_integration_point 1968 ) 1969 ) { 1970 break 2; 1971 } 1972 1973 if ( $skip_token ) { 1974 break; 1975 } 1976 1977 $tag_name = strtolower( $token_name ); 1978 1979 // Skip unallowed elements by tag name 1980 if ( ! isset( $this->allowed_html[ $tag_name ] ) ) { 1981 break; 1982 } 1983 1984 if ( $is_closer ) { 1985 $output .= "</{$tag_name}>"; 1986 break; 1987 } 1988 1989 $is_special_atomic_element = ( 1990 'html' === $namespace && 1991 in_array( $token_name, $special_atomic_elements, true ) 1992 ); 1993 1994 // A browser ignores this start tag, so leave it out; its contents were parsed as markup. 1995 if ( 1996 $is_special_atomic_element && 1997 true !== $this->inserts_special_atomic_elements && 1998 $token_name !== $this->inserts_special_atomic_elements 1999 ) { 2000 break; 2001 } 2002 2003 $expects_closer = ! ( 2004 'html' === $namespace 2005 ? ( WP_HTML_Processor::is_void( $token_name ) || $is_special_atomic_element ) 2006 : $has_self_closing_flag 2007 ); 2008 2009 $self_closer = ( 'html' !== $namespace && $has_self_closing_flag ) ? ' /' : ''; 2010 $closing_tag = $is_special_atomic_element ? "</{$tag_name}>" : ''; 2011 2012 $attribute_names = $this->get_attribute_names_with_prefix( '' ); 2013 $element_attributes = $this->allowed_html[ $tag_name ]; 2014 2015 // Check for required attributes. 2016 $required_attributes = array(); 2017 if ( is_array( $element_attributes ) ) { 2018 foreach ( $element_attributes as $name => $spec ) { 2019 if ( true === ( $spec['required'] ?? false ) ) { 2020 $required_attributes[ $name ] = true; 2021 } 2022 } 2023 } 2024 2025 /* 2026 * Allow `data-*` attributes. 2027 * 2028 * When specifying `$allowed_html`, the attribute name should be set as 2029 * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see 2030 * https://www.w3.org/TR/html40/struct/objects.html#adef-data). 2031 * 2032 * Note: the attribute name should only contain `A-Za-z0-9_-` chars. 2033 */ 2034 if ( ! empty( $element_attributes['data-*'] ) ) { 2035 if ( is_array( $attribute_names ) ) { 2036 foreach ( $attribute_names as $name ) { 2037 if ( 2038 1 === preg_match( '/^data-[a-z0-9_-]+$/', $name ) && 2039 ( 2040 ! isset( $element_attributes[ $name ] ) || 2041 '' === $element_attributes[ $name ] 2042 ) 2043 ) { 2044 $element_attributes[ $name ] = $element_attributes['data-*']; 2045 } 2046 } 2047 } 2048 2049 unset( $element_attributes['data-*'] ); 2050 } 2051 2052 $tag_maker = new self( 2053 "<{$tag_name}{$self_closer}>{$closing_tag}", 2054 $this->specified_allowed_html, 2055 $this->allowed_html, 2056 $this->allowed_protocols, 2057 $this->uri_attributes 2058 ); 2059 $tag_maker->change_parsing_namespace( $namespace ); 2060 $tag_maker->next_token(); 2061 if ( is_array( $attribute_names ) ) { 2062 foreach ( $attribute_names as $name ) { 2063 $spec = $element_attributes[ $name ] ?? null; 2064 2065 // This attribute is not specified, thus not allowed. Skip it. 2066 if ( null === $spec || '' === $spec ) { 2067 continue; 2068 } 2069 2070 /* 2071 * An Interactivity API binding replaces an attribute value when the content 2072 * is rendered, after KSES has checked it. Where KSES restricts attribute values 2073 * on an element, only bindings of attributes it allows there with any value 2074 * are kept. 2075 */ 2076 if ( 2077 str_starts_with( $name, 'data-wp-bind--' ) && 2078 _wp_kses_directive_binds_value_restricted_attribute( $name, $this->allowed_html[ $tag_name ] ) 2079 ) { 2080 continue; 2081 } 2082 2083 $raw_value = $this->get_attribute( $name ); 2084 $value = is_string( $raw_value ) ? $raw_value : ''; 2085 $given_value = $value; 2086 2087 // Process the style attribute through CSS sanitization. 2088 if ( 'style' === $name ) { 2089 if ( ! is_string( $raw_value ) ) { 2090 continue; 2091 } 2092 2093 $value = safecss_filter_attr( $value ); 2094 if ( '' === trim( $value ) ) { 2095 continue; 2096 } 2097 } 2098 2099 $is_url_ish = in_array( strtolower( $name ), $this->uri_attributes, true ); 2100 if ( $is_url_ish ) { 2101 $value = wp_kses_bad_protocol( $value, $this->allowed_protocols ); 2102 } 2103 2104 /* 2105 * Process the remaining attributes according to their policies. 2106 * 2107 * Non-array values for the attribute specification are assumed 2108 * to be `true`, thus permitting the attribute. 2109 */ 2110 if ( is_array( $spec ) ) { 2111 foreach ( $spec as $property => $constraint ) { 2112 $vless = true === $raw_value ? 'y' : 'n'; 2113 2114 if ( ! wp_kses_check_attr_val( $value, $vless, $property, $constraint ) ) { 2115 continue 2; 2116 } 2117 } 2118 } 2119 2120 // All updates are enqueued as boolean placeholders. 2121 if ( ! $tag_maker->set_attribute( $name, true ) ) { 2122 continue; 2123 } 2124 2125 $should_remain_true = true === $raw_value && '' === $value; 2126 2127 if ( ! $should_remain_true ) { 2128 $lower_name = strtolower( $name ); 2129 $escaped = null; 2130 2131 /* 2132 * If the value did not change through sanitization, then preserve 2133 * as much of the original escaping as possible. 2134 * 2135 * Fetch the original value by modifying it from the input string, 2136 * reading the span, and then erasing the update. 2137 */ 2138 if ( 2139 is_string( $raw_value ) && 2140 $given_value === $value && 2141 $this->set_attribute( $lower_name, true ) 2142 ) { 2143 $original = $this->lexical_updates[ $lower_name ]; 2144 $original_at = $original->start; 2145 $original_end = $original->start + $original->length; 2146 unset( $this->lexical_updates[ $lower_name ] ); 2147 2148 // Assignment follows the first `=` not at the beginning of the attribute name. 2149 $equals_at = $original_at + 1 + strcspn( $this->html, '=', $original_at + 1, $original->length - 1 ); 2150 if ( $equals_at < $original_end && 1 === strspn( $this->html, '"\'', $original_end - 1, 1 ) ) { 2151 // This might be a quoted attribute; find the opening quote. 2152 $quoting_at = $equals_at + 1 + strspn( $this->html, " \t\f\r\n", $equals_at + 1, $original_end - $equals_at - 1 ); 2153 if ( $this->html[ $original_end - 1 ] === $this->html[ $quoting_at ] ) { 2154 $escaped = self::normalize_text( 'attribute', $this->html, $quoting_at + 1, $original_end - $quoting_at - 2 ); 2155 $escaped = str_replace( "\r\n", "\n", $escaped ); 2156 $escaped = str_replace( "\r", "\n", $escaped ); 2157 $escaped = str_replace( "\x00", "\u{FFFD}", $escaped ); 2158 } 2159 } 2160 } 2161 2162 if ( ! isset( $escaped ) ) { 2163 $escaped = strtr( 2164 $value, 2165 array( 2166 "\r" => '
', 2167 '"' => '"', 2168 "'" => ''', 2169 '<' => '<', 2170 '&' => '&', 2171 '>' => '>', 2172 '[' => '[', 2173 ']' => ']', 2174 ) 2175 ); 2176 } 2177 2178 $tag_maker->lexical_updates[ $lower_name ]->text = " {$lower_name}=\"{$escaped}\""; 2179 } 2180 2181 unset( $required_attributes[ $name ] ); 2182 } 2183 } 2184 2185 $needs_special_newline = 'html' === $namespace && ( 'PRE' === $token_name || 'LISTING' === $token_name ); 2186 2187 if ( ! empty( $required_attributes ) ) { 2188 if ( ! $expects_closer ) { 2189 break; 2190 } 2191 2192 /* 2193 * Since this processor cannot track nesting of HTML elements 2194 * generally, leave opening tags when required attributes are 2195 * missing, but strip them of their attributes. 2196 */ 2197 $output .= "<{$tag_name}>"; 2198 $this->note_written_start_tag( $token_name, $namespace ); 2199 if ( $needs_special_newline ) { 2200 $special_newline_at = strlen( $output ); 2201 } 2202 break; 2203 } 2204 2205 if ( $is_special_atomic_element ) { 2206 switch ( $token_name ) { 2207 case 'IFRAME': 2208 /* 2209 * IFRAME contents are ignored, so there is no reason to allow 2210 * them from untrusted inputs. 2211 */ 2212 $tag_maker->set_modifiable_text( '' ); 2213 break; 2214 2215 case 'TEXTAREA': 2216 case 'TITLE': 2217 // Extract the raw text span via temporarily modifying the modifiable text. 2218 $this->set_modifiable_text( '' ); 2219 $raw_text_bounds = $this->lexical_updates['modifiable text']; 2220 unset( $this->lexical_updates['modifiable text'] ); 2221 2222 $normalized_text = self::normalize_text( 'data', $this->html, $raw_text_bounds->start, $raw_text_bounds->length ); 2223 $normalized_text = strtr( 2224 $normalized_text, 2225 array( 2226 "\x00" => "\u{FFFD}", 2227 "\r" => '
', 2228 ) 2229 ); 2230 2231 /* 2232 * RCDATA nodes can be safely escaped, but this must be 2233 * done after enqueuing the update to avoid double-escaping. 2234 */ 2235 $tag_maker->set_modifiable_text( '' ); 2236 $tag_maker->lexical_updates['modifiable text']->text = $normalized_text; 2237 break; 2238 2239 case 'NOEMBED': 2240 case 'NOFRAMES': 2241 case 'XMP': 2242 /* 2243 * These elements are obsolete and their contents are not 2244 * unescaped; therefore make a visual change to prevent 2245 * downstream parsers from interpreting content as markup. 2246 * The alternative is rejecting the elements entirely, which 2247 * is the default behavior unless they are specifically allowed. 2248 * 2249 * Replacing angle brackets with U+27E8 and U+27E9 is a practical 2250 * content degradation that will mostly preserve the contents 2251 * perceptually while retaining as much as is safely possible. 2252 */ 2253 $text = strtr( 2254 $text, 2255 array( 2256 '<' => '⟨', 2257 '>' => '⟩', 2258 ) 2259 ); 2260 $tag_maker->set_modifiable_text( $text ); 2261 break; 2262 2263 default: 2264 if ( self::contains_a_block_delimiter( $text ) ) { 2265 /* 2266 * Reject special atomic elements whose contents contain the syntax 2267 * for a block comment delimiter to prevent accidental parses. There 2268 * is no reliable way to escape their content, so rejecting it is a 2269 * more fitting approach for untrusted inputs. 2270 */ 2271 $tag_maker->set_modifiable_text( '' ); 2272 } else { 2273 // Otherwise consider the contents safe to pass through. 2274 $tag_maker->set_modifiable_text( $text ); 2275 } 2276 } 2277 } 2278 2279 $output .= $tag_maker->get_updated_html(); 2280 $this->note_written_start_tag( $token_name, $namespace ); 2281 if ( $needs_special_newline ) { 2282 $special_newline_at = strlen( $output ); 2283 } 2284 2285 break; 2286 } 2287 2288 // Re-enter the HTML namespace. 2289 if ( 'html' !== $namespace ) { 2290 if ( $has_self_closing_flag ) { 2291 array_pop( $this->foreign_content_stack ); 2292 2293 if ( 'math' === $namespace && 'ANNOTATION-XML' === $token_name ) { 2294 --$this->math_annotation_xml_depth; 2295 } 2296 } 2297 2298 if ( empty( $this->foreign_content_stack ) ) { 2299 $is_in_mathml_text_integration_point = false; 2300 $is_in_svg_html_integration_point = false; 2301 $this->change_parsing_namespace( 'html' ); 2302 $foreign_content_starts_at = PHP_INT_MAX; 2303 $foreign_closed_blocks = array(); 2304 } elseif ( '#tag' === $token_type && ! $has_self_closing_flag ) { 2305 switch ( $token_name ) { 2306 case 'MI': 2307 case 'MN': 2308 case 'MO': 2309 case 'MS': 2310 case 'MTEXT': 2311 $is_in_mathml_text_integration_point = ! $is_closer && 'math' === $namespace; 2312 break; 2313 2314 case 'DESC': 2315 case 'FOREIGNOBJECT': 2316 case 'TITLE': 2317 $is_in_svg_html_integration_point = ! $is_closer && 'svg' === $namespace; 2318 break; 2319 } 2320 } 2321 } 2322 2323 if ( 'TEMPLATE' === $token_name && $template_depth > 0 && $is_closer && 'html' === $namespace ) { 2324 --$template_depth; 2325 array_pop( $this->template_column_groups ); 2326 } 2327 } 2328 2329 /* 2330 * While there might have been an incomplete token in the output stream, 2331 * there is no need to render it to the output. They would disappear on 2332 * their own in a browser if they ended the document, but here they do 2333 * not end the document; instead, they are likely being inserted into an 2334 * existing document, where the incomplete token might mess with the rest 2335 * of the page’s HTML structure. 2336 */ 2337 2338 $sanitized = substr( $output, 0, $foreign_content_starts_at ); 2339 2340 // Templates should be contained within blocks, so close them first. 2341 if ( $template_depth > 0 && isset( $this->allowed_html['template'] ) ) { 2342 $sanitized .= str_repeat( '</template>', $template_depth ); 2343 } 2344 2345 // Close any remaining-open blocks ensure isolation of block content. 2346 foreach ( $foreign_closed_blocks as $block_name ) { 2347 $sanitized .= "<!-- /wp:{$block_name} -->"; 2348 } 2349 2350 for ( $i = count( $open_blocks ) - 1; $i >= 0; $i-- ) { 2351 // Skip blocks that were opened when inside truncated foreign content. 2352 if ( $open_blocks_at[ $i ] >= $foreign_content_starts_at ) { 2353 continue; 2354 } 2355 2356 $block_name = $open_blocks[ $i ]; 2357 $sanitized .= "<!-- /wp:{$block_name} -->"; 2358 } 2359 2360 return $sanitized; 2361 } 2362 }; 2363 2364 return $processor->sanitize(); 2365 } 2366 2367 /** 2368 * Filters one HTML attribute and ensures its value is allowed. 2369 * 2370 * This function can escape data in some situations where `wp_kses()` must strip the whole attribute. 2371 * 2372 * @since 4.2.3 2373 * 2374 * @param string $attr The 'whole' attribute, including name and value. 2375 * @param string $element The HTML element name to which the attribute belongs. 2376 * @return string Filtered attribute. 2377 */ 2378 function wp_kses_one_attr( $attr, $element ) { 2379 $uris = wp_kses_uri_attributes(); 2380 $allowed_html = wp_kses_allowed_html( 'post' ); 2381 $allowed_protocols = wp_allowed_protocols(); 2382 $attr = wp_kses_no_null( $attr, array( 'slash_zero' => 'keep' ) ); 2383 2384 // Preserve leading and trailing whitespace. 2385 $matches = array(); 2386 preg_match( '/^\s*/', $attr, $matches ); 2387 $lead = $matches[0]; 2388 preg_match( '/\s*$/', $attr, $matches ); 2389 $trail = $matches[0]; 2390 if ( empty( $trail ) ) { 2391 $attr = substr( $attr, strlen( $lead ) ); 2392 } else { 2393 $attr = substr( $attr, strlen( $lead ), -strlen( $trail ) ); 2394 } 2395 2396 // Parse attribute name and value from input. 2397 $split = preg_split( '/\s*=\s*/', $attr, 2 ); 2398 $name = $split[0]; 2399 if ( count( $split ) === 2 ) { 2400 $value = $split[1]; 2401 2402 /* 2403 * Remove quotes surrounding $value. 2404 * Also guarantee correct quoting in $attr for this one attribute. 2405 */ 2406 if ( '' === $value ) { 2407 $quote = ''; 2408 } else { 2409 $quote = $value[0]; 2410 } 2411 if ( '"' === $quote || "'" === $quote ) { 2412 if ( ! str_ends_with( $value, $quote ) ) { 2413 return ''; 2414 } 2415 $value = substr( $value, 1, -1 ); 2416 } else { 2417 $quote = '"'; 2418 } 2419 2420 // Sanitize quotes, angle braces, and entities. 2421 $value = esc_attr( $value ); 2422 2423 // Sanitize URI values. 2424 if ( in_array( strtolower( $name ), $uris, true ) ) { 2425 $value = wp_kses_bad_protocol( $value, $allowed_protocols ); 2426 } 2427 2428 $attr = "$name=$quote$value$quote"; 2429 $vless = 'n'; 2430 } else { 2431 $value = ''; 2432 $vless = 'y'; 2433 } 2434 2435 // Sanitize attribute by name. 2436 wp_kses_attr_check( $name, $value, $attr, $vless, $element, $allowed_html ); 2437 2438 // Restore whitespace. 2439 return $lead . $attr . $trail; 2440 } 2441 2442 /** 2443 * Returns an array of allowed HTML tags and attributes for a given context. 2444 * 2445 * @since 3.5.0 2446 * @since 5.0.1 `form` removed as allowable HTML tag. 2447 * 2448 * @global array $allowedposttags 2449 * @global array $allowedtags 2450 * @global array $allowedentitynames 2451 * 2452 * @param string|array $context The context for which to retrieve tags. Allowed values are 'post', 2453 * 'strip', 'data', 'entities', or the name of a field filter such as 2454 * 'pre_user_description', or an array of allowed HTML elements and attributes. 2455 * @return array Array of allowed HTML tags and their allowed attributes. 2456 */ 2457 function wp_kses_allowed_html( $context = '' ) { 2458 global $allowedposttags, $allowedtags, $allowedentitynames; 2459 2460 if ( is_array( $context ) ) { 2461 // When `$context` is an array it's actually an array of allowed HTML elements and attributes. 2462 $html = $context; 2463 $context = 'explicit'; 2464 2465 /** 2466 * Filters the HTML tags that are allowed for a given context. 2467 * 2468 * HTML tags and attribute names are case-insensitive in HTML but must be 2469 * added to the KSES allow list in lowercase. An item added to the allow list 2470 * in upper or mixed case will not recognized as permitted by KSES. 2471 * 2472 * @since 3.5.0 2473 * 2474 * @param array[] $html Allowed HTML tags. 2475 * @param string $context Context name. 2476 */ 2477 return apply_filters( 'wp_kses_allowed_html', $html, $context ); 2478 } 2479 2480 switch ( $context ) { 2481 case 'post': 2482 /** This filter is documented in wp-includes/kses.php */ 2483 $tags = apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context ); 2484 2485 // 5.0.1 removed the `<form>` tag, allow it if a filter is allowing it's sub-elements `<input>` or `<select>`. 2486 if ( ! CUSTOM_TAGS && ! isset( $tags['form'] ) && ( isset( $tags['input'] ) || isset( $tags['select'] ) ) ) { 2487 $tags = $allowedposttags; 2488 2489 $tags['form'] = array( 2490 'action' => true, 2491 'accept' => true, 2492 'accept-charset' => true, 2493 'enctype' => true, 2494 'method' => true, 2495 'name' => true, 2496 'target' => true, 2497 ); 2498 2499 /** This filter is documented in wp-includes/kses.php */ 2500 $tags = apply_filters( 'wp_kses_allowed_html', $tags, $context ); 2501 } 2502 2503 return $tags; 2504 2505 case 'user_description': 2506 case 'pre_term_description': 2507 case 'pre_user_description': 2508 $tags = $allowedtags; 2509 $tags['a']['rel'] = true; 2510 $tags['a']['target'] = true; 2511 /** This filter is documented in wp-includes/kses.php */ 2512 return apply_filters( 'wp_kses_allowed_html', $tags, $context ); 2513 2514 case 'strip': 2515 /** This filter is documented in wp-includes/kses.php */ 2516 return apply_filters( 'wp_kses_allowed_html', array(), $context ); 2517 2518 case 'entities': 2519 /** This filter is documented in wp-includes/kses.php */ 2520 return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context ); 2521 2522 case 'data': 2523 default: 2524 /** This filter is documented in wp-includes/kses.php */ 2525 return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context ); 2526 } 2527 } 2528 2529 /** 2530 * Allows the note mention chip markup in comment content. 2531 * 2532 * The notes `@` mention completer stores a mention as a chip carrying the 2533 * mentioned user's ID in a class token: 2534 * `<span class="wp-note-mention user-N">@Name</span>`. The default comment 2535 * allowlist does not allow `span` at all, so for users without 2536 * `unfiltered_html` the mention would be stripped on save. 2537 * 2538 * The allowance is deliberately narrow and always on: `span` is a 2539 * semantics-free element and _wp_kses_sanitize_note_mention_classes() 2540 * reduces its `class` to the two mention tokens right after kses runs, so 2541 * regular (including anonymous) commenters gain nothing beyond the inert 2542 * mention markup itself. 2543 * 2544 * @since 7.1.0 2545 * @access private 2546 * 2547 * @param array<string, array<string, bool>> $allowed The allowed tags structure for the context. 2548 * @param string $context The kses context. 2549 * @return array<string, array<string, bool>> Modified allowed tags structure. 2550 */ 2551 function _wp_kses_allow_note_mention_span( $allowed, $context ): array { 2552 if ( ! is_array( $allowed ) ) { 2553 $allowed = array(); 2554 } 2555 if ( 'pre_comment_content' !== $context ) { 2556 return $allowed; 2557 } 2558 2559 if ( ! isset( $allowed['span'] ) || ! is_array( $allowed['span'] ) ) { 2560 $allowed['span'] = array(); 2561 } 2562 2563 $allowed['span']['class'] = true; 2564 2565 return $allowed; 2566 } 2567 2568 /** 2569 * Reduces `span` classes in comment content to the note mention tokens. 2570 * 2571 * _wp_kses_allow_note_mention_span() lets `class` through kses on `span` so 2572 * the mention chip survives, but `class` is an open-ended styling and 2573 * scripting hook, so this companion pass - running right after 2574 * `wp_filter_kses` at priority 10 - strips every class token except the two 2575 * the mention markup uses: `wp-note-mention` and `user-N`. `span` is the only 2576 * comment tag allowed to carry `class` at all, so walking `span` tags covers 2577 * the entire allowance. 2578 * 2579 * The pass only applies while the restrictive comment allowlist is active: 2580 * users with `unfiltered_html` are filtered through `wp_filter_post_kses` 2581 * (or not at all), where arbitrary classes are already permitted, and 2582 * narrowing their markup here would restrict what core allows them to post. 2583 * 2584 * @since 7.1.0 2585 * @access private 2586 * 2587 * @param string $content Slashed comment content, already filtered by kses. 2588 * @return string Slashed comment content with span classes reduced. 2589 */ 2590 function _wp_kses_sanitize_note_mention_classes( $content ): string { 2591 if ( ! is_string( $content ) ) { 2592 $content = ''; 2593 } 2594 if ( false === has_filter( 'pre_comment_content', 'wp_filter_kses' ) ) { 2595 return $content; 2596 } 2597 2598 $processor = new WP_HTML_Tag_Processor( wp_unslash( $content ) ); 2599 2600 while ( $processor->next_tag( 'SPAN' ) ) { 2601 foreach ( $processor->class_list() as $token ) { 2602 if ( 'wp-note-mention' !== $token && ! preg_match( '/^user-[1-9][0-9]*$/', $token ) ) { 2603 // Removing the last class also removes the attribute itself. 2604 $processor->remove_class( $token ); 2605 } 2606 } 2607 } 2608 2609 return wp_slash( $processor->get_updated_html() ); 2610 } 2611 2612 /** 2613 * You add any KSES hooks here. 2614 * 2615 * There is currently only one KSES WordPress hook, {@see 'pre_kses'}, and it is called here. 2616 * All parameters are passed to the hooks and expected to receive a string. 2617 * 2618 * @since 1.0.0 2619 * 2620 * @param string $content Content to filter through KSES. 2621 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2622 * or a context name such as 'post'. See wp_kses_allowed_html() 2623 * for the list of accepted context names. 2624 * @param string[] $allowed_protocols Array of allowed URL protocols. 2625 * @return string Filtered content through {@see 'pre_kses'} hook. 2626 */ 2627 function wp_kses_hook( $content, $allowed_html, $allowed_protocols ) { 2628 /** 2629 * Filters content to be run through KSES. 2630 * 2631 * @since 2.3.0 2632 * 2633 * @param string $content Content to filter through KSES. 2634 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2635 * or a context name such as 'post'. See wp_kses_allowed_html() 2636 * for the list of accepted context names. 2637 * @param string[] $allowed_protocols Array of allowed URL protocols. 2638 */ 2639 return apply_filters( 'pre_kses', $content, $allowed_html, $allowed_protocols ); 2640 } 2641 2642 /** 2643 * Returns the version number of KSES. 2644 * 2645 * @since 1.0.0 2646 * 2647 * @return string KSES version number. 2648 */ 2649 function wp_kses_version() { 2650 return '0.2.2'; 2651 } 2652 2653 /** 2654 * Searches for HTML tags, no matter how malformed. 2655 * 2656 * It also matches stray `>` characters. 2657 * 2658 * @since 1.0.0 2659 * @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments. 2660 * 2661 * @global array[]|string $pass_allowed_html An array of allowed HTML elements and attributes, 2662 * or a context name such as 'post'. 2663 * @global string[] $pass_allowed_protocols Array of allowed URL protocols. 2664 * 2665 * @param string $content Content to filter. 2666 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2667 * or a context name such as 'post'. See wp_kses_allowed_html() 2668 * for the list of accepted context names. 2669 * @param string[] $allowed_protocols Array of allowed URL protocols. 2670 * @return string Content with fixed HTML tags 2671 */ 2672 function wp_kses_split( $content, $allowed_html, $allowed_protocols ) { 2673 global $pass_allowed_html, $pass_allowed_protocols; 2674 2675 $pass_allowed_html = $allowed_html; 2676 $pass_allowed_protocols = $allowed_protocols; 2677 2678 $token_pattern = <<<REGEX 2679 ~ 2680 ( # Detect comments of various flavors before attempting to find tags. 2681 (<!--.*?(-->|$)) # - Normative HTML comments. 2682 | 2683 </[^a-zA-Z][^>]*> # - Closing tags with invalid tag names. 2684 | 2685 <![^>]*> # - Invalid markup declaration nodes. Not all invalid nodes 2686 # are matched so as to avoid breaking legacy behaviors. 2687 ) 2688 | 2689 (<[^>]*(>|$)|>) # Tag-like spans of text. 2690 ~x 2691 REGEX; 2692 return preg_replace_callback( $token_pattern, '_wp_kses_split_callback', $content ); 2693 } 2694 2695 /** 2696 * Returns an array of HTML attribute names whose value contains a URL. 2697 * 2698 * This function returns a list of all HTML attributes that must contain 2699 * a URL according to the HTML specification. 2700 * 2701 * This list includes URI attributes both allowed and disallowed by KSES. 2702 * 2703 * @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes 2704 * 2705 * @since 5.0.1 2706 * 2707 * @return string[] HTML attribute names whose value contains a URL. 2708 */ 2709 function wp_kses_uri_attributes() { 2710 $uri_attributes = array( 2711 'action', 2712 'archive', 2713 'background', 2714 'cite', 2715 'classid', 2716 'codebase', 2717 'data', 2718 'formaction', 2719 'href', 2720 'icon', 2721 'longdesc', 2722 'manifest', 2723 'poster', 2724 'profile', 2725 'src', 2726 'usemap', 2727 'xmlns', 2728 ); 2729 2730 /** 2731 * Filters the list of attributes that are required to contain a URL. 2732 * 2733 * Use this filter to add any `data-` attributes that are required to be 2734 * validated as a URL. 2735 * 2736 * @since 5.0.1 2737 * 2738 * @param string[] $uri_attributes HTML attribute names whose value contains a URL. 2739 */ 2740 $uri_attributes = apply_filters( 'wp_kses_uri_attributes', $uri_attributes ); 2741 2742 return $uri_attributes; 2743 } 2744 2745 /** 2746 * Callback for `wp_kses_split()`. 2747 * 2748 * @since 3.1.0 2749 * @access private 2750 * @ignore 2751 * 2752 * @global array[]|string $pass_allowed_html An array of allowed HTML elements and attributes, 2753 * or a context name such as 'post'. 2754 * @global string[] $pass_allowed_protocols Array of allowed URL protocols. 2755 * 2756 * @param array $matches preg_replace regexp matches 2757 * @return string 2758 */ 2759 function _wp_kses_split_callback( $matches ) { 2760 global $pass_allowed_html, $pass_allowed_protocols; 2761 2762 return wp_kses_split2( $matches[0], $pass_allowed_html, $pass_allowed_protocols ); 2763 } 2764 2765 /** 2766 * Callback for `wp_kses_split()` for fixing malformed HTML tags. 2767 * 2768 * This function does a lot of work. It rejects some very malformed things like 2769 * `<:::>`. It returns an empty string, if the element isn't allowed (look ma, no 2770 * `strip_tags()`!). Otherwise it splits the tag into an element and an attribute 2771 * list. 2772 * 2773 * After the tag is split into an element and an attribute list, it is run 2774 * through another filter which will remove illegal attributes and once that is 2775 * completed, will be returned. 2776 * 2777 * @access private 2778 * @ignore 2779 * @since 1.0.0 2780 * @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments. 2781 * 2782 * @param string $content Content to filter. 2783 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2784 * or a context name such as 'post'. See wp_kses_allowed_html() 2785 * for the list of accepted context names. 2786 * @param string[] $allowed_protocols Array of allowed URL protocols. 2787 * @return string Fixed HTML element 2788 */ 2789 function wp_kses_split2( $content, $allowed_html, $allowed_protocols ) { 2790 $content = wp_kses_stripslashes( $content ); 2791 2792 /* 2793 * The regex pattern used to split HTML into chunks attempts 2794 * to split on HTML token boundaries. This function should 2795 * thus receive chunks that _either_ start with meaningful 2796 * syntax tokens, like a tag `<div>` or a comment `<!-- ... -->`. 2797 * 2798 * If the first character of the `$content` chunk _isn't_ one 2799 * of these syntax elements, which always starts with `<`, then 2800 * the match had to be for the final alternation of `>`. In such 2801 * case, it's probably standing on its own and could be encoded 2802 * with a character reference to remove ambiguity. 2803 * 2804 * In other words, if this chunk isn't from a match of a syntax 2805 * token, it's just a plaintext greater-than (`>`) sign. 2806 */ 2807 if ( ! str_starts_with( $content, '<' ) ) { 2808 return '>'; 2809 } 2810 2811 /* 2812 * When certain invalid syntax constructs appear, the HTML parser 2813 * shifts into what's called the "bogus comment state." This is a 2814 * plaintext state that consumes everything until the nearest `>` 2815 * and then transforms the entire span into an HTML comment. 2816 * 2817 * Preserve these comments and do not treat them like tags. 2818 * 2819 * @link https://html.spec.whatwg.org/#bogus-comment-state 2820 */ 2821 if ( 1 === preg_match( '~^(?:</[^a-zA-Z][^>]*>|<![a-z][^>]*>)$~', $content ) ) { 2822 /** 2823 * Since the pattern matches `</…>` and also `<!…>`, this will 2824 * preserve the type of the cleaned-up token in the output. 2825 */ 2826 $opener = $content[1]; 2827 $content = substr( $content, 2, -1 ); 2828 2829 do { 2830 $prev = $content; 2831 $content = wp_kses( $content, $allowed_html, $allowed_protocols ); 2832 } while ( $prev !== $content ); 2833 2834 // Recombine the modified inner content with the original token structure. 2835 return "<{$opener}{$content}>"; 2836 } 2837 2838 /* 2839 * Normative HTML comments should be handled separately as their 2840 * parsing rules differ from those for tags and text nodes. 2841 */ 2842 if ( str_starts_with( $content, '<!--' ) ) { 2843 $content = str_replace( array( '<!--', '-->' ), '', $content ); 2844 2845 while ( ( $newstring = wp_kses( $content, $allowed_html, $allowed_protocols ) ) !== $content ) { 2846 $content = $newstring; 2847 } 2848 2849 if ( '' === $content ) { 2850 return ''; 2851 } 2852 2853 // Prevent multiple dashes in comments. 2854 $content = preg_replace( '/--+/', '-', $content ); 2855 // Prevent three dashes closing a comment. 2856 $content = preg_replace( '/-$/', '', $content ); 2857 2858 return "<!--{$content}-->"; 2859 } 2860 2861 // It's seriously malformed. 2862 if ( ! preg_match( '%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $content, $matches ) ) { 2863 return ''; 2864 } 2865 2866 $slash = trim( $matches[1] ); 2867 $elem = $matches[2]; 2868 $attrlist = $matches[3]; 2869 2870 if ( ! is_array( $allowed_html ) ) { 2871 $allowed_html = wp_kses_allowed_html( $allowed_html ); 2872 } 2873 2874 // They are using a not allowed HTML element. 2875 if ( ! isset( $allowed_html[ strtolower( $elem ) ] ) ) { 2876 return ''; 2877 } 2878 2879 // No attributes are allowed for closing elements. 2880 if ( '' !== $slash ) { 2881 return "</$elem>"; 2882 } 2883 2884 return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols ); 2885 } 2886 2887 /** 2888 * Removes all attributes, if none are allowed for this element. 2889 * 2890 * If some are allowed it calls `wp_kses_hair()` to split them further, and then 2891 * it builds up new HTML code from the data that `wp_kses_hair()` returns. It also 2892 * removes `<` and `>` characters, if there are any left. One more thing it does 2893 * is to check if the tag has a closing XHTML slash, and if it does, it puts one 2894 * in the returned code as well. 2895 * 2896 * An array of allowed values can be defined for attributes. If the attribute value 2897 * doesn't fall into the list, the attribute will be removed from the tag. 2898 * 2899 * Attributes can be marked as required. If a required attribute is not present, 2900 * KSES will remove all attributes from the tag. As KSES doesn't match opening and 2901 * closing tags, it's not possible to safely remove the tag itself, the safest 2902 * fallback is to strip all attributes from the tag, instead. 2903 * 2904 * @since 1.0.0 2905 * @since 5.9.0 Added support for an array of allowed values for attributes. 2906 * Added support for required attributes. 2907 * 2908 * @param string $element HTML element/tag. 2909 * @param string $attr HTML attributes from HTML element to closing HTML element tag. 2910 * @param array[]|string $allowed_html An array of allowed HTML elements and attributes, 2911 * or a context name such as 'post'. See wp_kses_allowed_html() 2912 * for the list of accepted context names. 2913 * @param string[] $allowed_protocols Array of allowed URL protocols. 2914 * @return string Sanitized HTML element. 2915 */ 2916 function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) { 2917 if ( ! is_array( $allowed_html ) ) { 2918 $allowed_html = wp_kses_allowed_html( $allowed_html ); 2919 } 2920 2921 // Is there a closing XHTML slash at the end of the attributes? 2922 $xhtml_slash = ''; 2923 if ( preg_match( '%\s*/\s*$%', $attr ) ) { 2924 $xhtml_slash = ' /'; 2925 } 2926 2927 // Are any attributes allowed at all for this element? 2928 $element_low = strtolower( $element ); 2929 if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) { 2930 return "<$element$xhtml_slash>"; 2931 } 2932 2933 // Split it. 2934 $attrarr = wp_kses_hair( $attr, $allowed_protocols ); 2935 2936 // Check if there are attributes that are required. 2937 $required_attrs = array_filter( 2938 $allowed_html[ $element_low ], 2939 static function ( $required_attr_limits ) { 2940 return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required']; 2941 } 2942 ); 2943 2944 /* 2945 * If a required attribute check fails, we can return nothing for a self-closing tag, 2946 * but for a non-self-closing tag the best option is to return the element with attributes, 2947 * as KSES doesn't handle matching the relevant closing tag. 2948 */ 2949 $stripped_tag = ''; 2950 if ( empty( $xhtml_slash ) ) { 2951 $stripped_tag = "<$element>"; 2952 } 2953 2954 // Go through $attrarr, and save the allowed attributes for this element in $attr2. 2955 $attr2 = ''; 2956 foreach ( $attrarr as $arreach ) { 2957 // Check if this attribute is required. 2958 $required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] ); 2959 2960 if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) { 2961 $attr2 .= ' ' . $arreach['whole']; 2962 2963 // If this was a required attribute, we can mark it as found. 2964 if ( $required ) { 2965 unset( $required_attrs[ strtolower( $arreach['name'] ) ] ); 2966 } 2967 } elseif ( $required ) { 2968 // This attribute was required, but didn't pass the check. The entire tag is not allowed. 2969 return $stripped_tag; 2970 } 2971 } 2972 2973 // If some required attributes weren't set, the entire tag is not allowed. 2974 if ( ! empty( $required_attrs ) ) { 2975 return $stripped_tag; 2976 } 2977 2978 // Remove any "<" or ">" characters. 2979 $attr2 = preg_replace( '/[<>]/', '', $attr2 ); 2980 2981 return "<$element$attr2$xhtml_slash>"; 2982 } 2983 2984 /** 2985 * Determines whether an attribute is allowed. 2986 * 2987 * @since 4.2.3 2988 * @since 5.0.0 Added support for `data-*` wildcard attributes. 2989 * 2990 * @param string $name The attribute name. Passed by reference. Returns empty string when not allowed. 2991 * @param string $value The attribute value. Passed by reference. Returns a filtered value. 2992 * @param string $whole The `name=value` input. Passed by reference. Returns filtered input. 2993 * @param string $vless Whether the attribute is valueless. Use 'y' or 'n'. 2994 * @param string $element The name of the element to which this attribute belongs. 2995 * @param array $allowed_html The full list of allowed elements and attributes. 2996 * @return bool Whether or not the attribute is allowed. 2997 */ 2998 function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) { 2999 $name_low = strtolower( $name ); 3000 $element_low = strtolower( $element ); 3001 3002 if ( ! isset( $allowed_html[ $element_low ] ) ) { 3003 $name = ''; 3004 $value = ''; 3005 $whole = ''; 3006 return false; 3007 } 3008 3009 $allowed_attr = $allowed_html[ $element_low ]; 3010 3011 if ( ! isset( $allowed_attr[ $name_low ] ) || '' === $allowed_attr[ $name_low ] ) { 3012 /* 3013 * Allow `data-*` attributes. 3014 * 3015 * When specifying `$allowed_html`, the attribute name should be set as 3016 * `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see 3017 * https://www.w3.org/TR/html40/struct/objects.html#adef-data). 3018 * 3019 * Note: the attribute name should only contain `A-Za-z0-9_-` chars. 3020 */ 3021 if ( str_starts_with( $name_low, 'data-' ) && ! empty( $allowed_attr['data-*'] ) 3022 && preg_match( '/^data-[a-z0-9_-]+$/', $name_low, $match ) 3023 ) { 3024 /* 3025 * Add the whole attribute name to the allowed attributes and set any restrictions 3026 * for the `data-*` attribute values for the current element. 3027 */ 3028 $allowed_attr[ $match[0] ] = $allowed_attr['data-*']; 3029 } else { 3030 $name = ''; 3031 $value = ''; 3032 $whole = ''; 3033 return false; 3034 } 3035 } 3036 3037 /* 3038 * An Interactivity API binding replaces an attribute value when the content is rendered, 3039 * after KSES has checked it. Where KSES restricts attribute values on an element, only 3040 * bindings of attributes it allows there with any value are kept. 3041 */ 3042 if ( 3043 str_starts_with( $name_low, 'data-wp-bind--' ) && 3044 _wp_kses_directive_binds_value_restricted_attribute( $name_low, $allowed_attr ) 3045 ) { 3046 $name = ''; 3047 $value = ''; 3048 $whole = ''; 3049 return false; 3050 } 3051 3052 if ( 'style' === $name_low ) { 3053 $decoded_value = WP_HTML_Decoder::decode_attribute( $value ); 3054 $new_value = safecss_filter_attr( $decoded_value ); 3055 3056 if ( empty( $new_value ) ) { 3057 $name = ''; 3058 $value = ''; 3059 $whole = ''; 3060 return false; 3061 } 3062 3063 if ( $new_value !== $decoded_value ) { 3064 $encoded_value = esc_attr( $new_value ); 3065 $whole = str_replace( $value, $encoded_value, $whole ); 3066 $value = $encoded_value; 3067 } 3068 } 3069 3070 if ( is_array( $allowed_attr[ $name_low ] ) ) { 3071 // There are some checks. 3072 foreach ( $allowed_attr[ $name_low ] as $currkey => $currval ) { 3073 if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) { 3074 $name = ''; 3075 $value = ''; 3076 $whole = ''; 3077 return false; 3078 } 3079 } 3080 } 3081 3082 return true; 3083 } 3084 3085 /** 3086 * Given a string of HTML attributes and values, parse into a structured attribute list. 3087 * 3088 * This function performs a number of transformations while parsing attribute strings: 3089 * - It normalizes attribute values and surrounds them with double quotes. 3090 * - It normalizes HTML character references inside attribute values. 3091 * - It removes “bad” URL protocols from attribute values. 3092 * 3093 * Otherwise this reads the attributes as if they were part of an HTML tag. It performs 3094 * these transformations to lower the risk of mis-parsing down the line and to perform 3095 * URL sanitization in line with the rest of the `kses` subsystem. Importantly, it does 3096 * not decode the attribute values, meaning that special HTML syntax characters will 3097 * be left with character references in the `value` property. 3098 * 3099 * Example: 3100 * 3101 * $attrs = wp_kses_hair( 'class="is-wide" inert data-lazy=\'<img>\' =/🐮=/' ); 3102 * $attrs === array( 3103 * 'class' => array( 'name' => 'class', 'value' => 'is-wide', 'whole' => 'class="is-wide"', 'vless' => 'n' ), 3104 * 'inert' => array( 'name' => 'inert', 'value' => '', 'whole' => 'inert', 'vless' => 'y' ), 3105 * 'data-lazy' => array( 'name' => 'data-lazy', 'value' => '<img>', 'whole' => 'data-lazy="<img>"', 'vless' => 'n' ), 3106 * '=' => array( 'name' => '=', 'value' => '', 'whole' => '=', 'vless' => 'y' ), 3107 * '🐮' => array( 'name' => '🐮', 'value' => '/', 'whole' => '🐮="/"', 'vless' => 'n' ), 3108 * ); 3109 * 3110 * @since 1.0.0 3111 * @since 7.0.0 Reliably parses HTML via the HTML API. 3112 * 3113 * @param string $attr Attribute list from HTML element to closing HTML element tag. 3114 * @param string[] $allowed_protocols Array of allowed URL protocols. 3115 * @return array<string, array{name: string, value: string, whole: string, vless: 'y'|'n'}> Array of attribute information after parsing. 3116 */ 3117 function wp_kses_hair( $attr, $allowed_protocols ) { 3118 $attributes = array(); 3119 $uris = wp_kses_uri_attributes(); 3120 3121 $processor = new WP_HTML_Tag_Processor( "<wp {$attr}>" ); 3122 $processor->next_token(); 3123 3124 $attribute_names = $processor->get_attribute_names_with_prefix( '' ); 3125 if ( null === $attribute_names || 0 === count( $attribute_names ) ) { 3126 return $attributes; 3127 } 3128 3129 $syntax_characters = array( 3130 '&' => '&', 3131 '<' => '<', 3132 '>' => '>', 3133 "'" => ''', 3134 '"' => '"', 3135 ); 3136 3137 foreach ( $attribute_names as $name ) { 3138 $value = $processor->get_attribute( $name ); 3139 $is_bool = true === $value; 3140 if ( is_string( $value ) && in_array( $name, $uris, true ) ) { 3141 $value = wp_kses_bad_protocol( $value, $allowed_protocols ); 3142 } 3143 3144 // Reconstruct and normalize the attribute value. 3145 $recoded = $is_bool ? '' : strtr( $value, $syntax_characters ); 3146 $whole = $is_bool ? $name : "{$name}=\"{$recoded}\""; 3147 3148 $attributes[ $name ] = array( 3149 'name' => $name, 3150 'value' => $recoded, 3151 'whole' => $whole, 3152 'vless' => $is_bool ? 'y' : 'n', 3153 ); 3154 } 3155 3156 return $attributes; 3157 } 3158 3159 /** 3160 * Finds all attributes of an HTML element. 3161 * 3162 * Does not modify input. May return "evil" output. 3163 * 3164 * Based on `wp_kses_split2()` and `wp_kses_attr()`. 3165 * 3166 * @since 4.2.3 3167 * 3168 * @param string $element HTML element. 3169 * @return array|false List of attributes found in the element. Returns false on failure. 3170 */ 3171 function wp_kses_attr_parse( $element ) { 3172 $valid = preg_match( '%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches ); 3173 if ( 1 !== $valid ) { 3174 return false; 3175 } 3176 3177 $begin = $matches[1]; 3178 $slash = $matches[2]; 3179 $elname = $matches[3]; 3180 $attr = $matches[4]; 3181 $end = $matches[5]; 3182 3183 if ( '' !== $slash ) { 3184 // Closing elements do not get parsed. 3185 return false; 3186 } 3187 3188 // Is there a closing XHTML slash at the end of the attributes? 3189 if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) { 3190 $xhtml_slash = $matches[0]; 3191 $attr = substr( $attr, 0, -strlen( $xhtml_slash ) ); 3192 } else { 3193 $xhtml_slash = ''; 3194 } 3195 3196 // Split it. 3197 $attrarr = wp_kses_hair_parse( $attr ); 3198 if ( false === $attrarr ) { 3199 return false; 3200 } 3201 3202 // Make sure all input is returned by adding front and back matter. 3203 array_unshift( $attrarr, $begin . $slash . $elname ); 3204 array_push( $attrarr, $xhtml_slash . $end ); 3205 3206 return $attrarr; 3207 } 3208 3209 /** 3210 * Builds an attribute list from string containing attributes. 3211 * 3212 * Does not modify input. May return "evil" output. 3213 * In case of unexpected input, returns false instead of stripping things. 3214 * 3215 * Based on `wp_kses_hair()` but does not return a multi-dimensional array. 3216 * 3217 * @since 4.2.3 3218 * 3219 * @param string $attr Attribute list from HTML element to closing HTML element tag. 3220 * @return array|false List of attributes found in $attr. Returns false on failure. 3221 */ 3222 function wp_kses_hair_parse( $attr ) { 3223 if ( '' === $attr ) { 3224 return array(); 3225 } 3226 3227 $regex = 3228 '(?: 3229 [_a-zA-Z][-_a-zA-Z0-9:.]* # Attribute name. 3230 | 3231 \[\[?[^\[\]]+\]\]? # Shortcode in the name position implies unfiltered_html. 3232 ) 3233 (?: # Attribute value. 3234 \s*=\s* # All values begin with "=". 3235 (?: 3236 "[^"]*" # Double-quoted. 3237 | 3238 \'[^\']*\' # Single-quoted. 3239 | 3240 [^\s"\']+ # Non-quoted. 3241 (?:\s|$) # Must have a space. 3242 ) 3243 | 3244 (?:\s|$) # If attribute has no value, space is required. 3245 ) 3246 \s* # Trailing space is optional except as mentioned above. 3247 '; 3248 3249 /* 3250 * Although it is possible to reduce this procedure to a single regexp, 3251 * we must run that regexp twice to get exactly the expected result. 3252 * 3253 * Note: do NOT remove the `x` modifiers as they are essential for the above regex! 3254 */ 3255 3256 $validation = "/^($regex)+$/x"; 3257 $extraction = "/$regex/x"; 3258 3259 if ( 1 === preg_match( $validation, $attr ) ) { 3260 preg_match_all( $extraction, $attr, $attrarr ); 3261 return $attrarr[0]; 3262 } else { 3263 return false; 3264 } 3265 } 3266 3267 /** 3268 * Performs different checks for attribute values. 3269 * 3270 * The currently implemented checks are "maxlen", "minlen", "maxval", "minval", 3271 * and "valueless". 3272 * 3273 * @since 1.0.0 3274 * 3275 * @param string $value Attribute value. 3276 * @param string $vless Whether the attribute is valueless. Use 'y' or 'n'. 3277 * @param string $checkname What $checkvalue is checking for. 3278 * @param mixed $checkvalue What constraint the value should pass. 3279 * @return bool Whether check passes. 3280 */ 3281 function wp_kses_check_attr_val( $value, $vless, $checkname, $checkvalue ) { 3282 $ok = true; 3283 3284 switch ( strtolower( $checkname ) ) { 3285 case 'maxlen': 3286 /* 3287 * The maxlen check makes sure that the attribute value has a length not 3288 * greater than the given value. This can be used to avoid Buffer Overflows 3289 * in WWW clients and various Internet servers. 3290 */ 3291 3292 if ( strlen( $value ) > $checkvalue ) { 3293 $ok = false; 3294 } 3295 break; 3296 3297 case 'minlen': 3298 /* 3299 * The minlen check makes sure that the attribute value has a length not 3300 * smaller than the given value. 3301 */ 3302 3303 if ( strlen( $value ) < $checkvalue ) { 3304 $ok = false; 3305 } 3306 break; 3307 3308 case 'maxval': 3309 /* 3310 * The maxval check does two things: it checks that the attribute value is 3311 * an integer from 0 and up, without an excessive amount of zeroes or 3312 * whitespace (to avoid Buffer Overflows). It also checks that the attribute 3313 * value is not greater than the given value. 3314 * This check can be used to avoid Denial of Service attacks. 3315 */ 3316 3317 if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) { 3318 $ok = false; 3319 } 3320 if ( $value > $checkvalue ) { 3321 $ok = false; 3322 } 3323 break; 3324 3325 case 'minval': 3326 /* 3327 * The minval check makes sure that the attribute value is a positive integer, 3328 * and that it is not smaller than the given value. 3329 */ 3330 3331 if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) { 3332 $ok = false; 3333 } 3334 if ( $value < $checkvalue ) { 3335 $ok = false; 3336 } 3337 break; 3338 3339 case 'valueless': 3340 /* 3341 * The valueless check makes sure if the attribute has a value 3342 * (like `<a href="blah">`) or not (`<option selected>`). If the given value 3343 * is a "y" or a "Y", the attribute must not have a value. 3344 * If the given value is an "n" or an "N", the attribute must have a value. 3345 */ 3346 3347 if ( strtolower( $checkvalue ) !== $vless ) { 3348 $ok = false; 3349 } 3350 break; 3351 3352 case 'values': 3353 /* 3354 * The values check is used when you want to make sure that the attribute 3355 * has one of the given values. 3356 */ 3357 3358 if ( ! in_array( strtolower( $value ), $checkvalue, true ) ) { 3359 $ok = false; 3360 } 3361 break; 3362 3363 case 'value_callback': 3364 /* 3365 * The value_callback check is used when you want to make sure that the attribute 3366 * value is accepted by the callback function. 3367 */ 3368 3369 if ( ! call_user_func( $checkvalue, $value ) ) { 3370 $ok = false; 3371 } 3372 break; 3373 } // End switch. 3374 3375 return $ok; 3376 } 3377 3378 /** 3379 * Sanitizes a string and removed disallowed URL protocols. 3380 * 3381 * This function removes all non-allowed protocols from the beginning of the 3382 * string. It ignores whitespace and the case of the letters, and it does 3383 * understand HTML entities. It does its work recursively, so it won't be 3384 * fooled by a string like `javascript:javascript:alert(57)`. 3385 * 3386 * @since 1.0.0 3387 * 3388 * @param string $content Content to filter bad protocols from. 3389 * @param string[] $allowed_protocols Array of allowed URL protocols. 3390 * @return string Filtered content. 3391 */ 3392 function wp_kses_bad_protocol( $content, $allowed_protocols ) { 3393 $content = wp_kses_no_null( $content ); 3394 3395 // Short-circuit if the string starts with `https://` or `http://`. Most common cases. 3396 if ( 3397 ( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) || 3398 ( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) ) 3399 ) { 3400 return $content; 3401 } 3402 3403 $iterations = 0; 3404 3405 do { 3406 $original_content = $content; 3407 $content = wp_kses_bad_protocol_once( $content, $allowed_protocols ); 3408 } while ( $original_content !== $content && ++$iterations < 6 ); 3409 3410 if ( $original_content !== $content ) { 3411 return ''; 3412 } 3413 3414 return $content; 3415 } 3416 3417 /** 3418 * Removes any invalid control characters in a text string. 3419 * 3420 * Also removes any instance of the `\0` string. 3421 * 3422 * @since 1.0.0 3423 * 3424 * @param string $content Content to filter null characters from. 3425 * @param array $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'. 3426 * @return string Filtered content. 3427 */ 3428 function wp_kses_no_null( $content, $options = null ) { 3429 if ( ! isset( $options['slash_zero'] ) ) { 3430 $options = array( 'slash_zero' => 'remove' ); 3431 } 3432 3433 $content = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $content ); 3434 if ( 'remove' === $options['slash_zero'] ) { 3435 $content = preg_replace( '/\\\\+0+/', '', $content ); 3436 } 3437 3438 return $content; 3439 } 3440 3441 /** 3442 * Strips slashes from in front of quotes. 3443 * 3444 * This function changes the character sequence `\"` to just `"`. It leaves all other 3445 * slashes alone. The quoting from `preg_replace(//e)` requires this. 3446 * 3447 * @since 1.0.0 3448 * 3449 * @param string $content String to strip slashes from. 3450 * @return string Fixed string with quoted slashes. 3451 */ 3452 function wp_kses_stripslashes( $content ) { 3453 return preg_replace( '%\\\\"%', '"', $content ); 3454 } 3455 3456 /** 3457 * Converts the keys of an array to lowercase. 3458 * 3459 * @since 1.0.0 3460 * 3461 * @param array $inarray Unfiltered array. 3462 * @return array Fixed array with all lowercase keys. 3463 */ 3464 function wp_kses_array_lc( $inarray ) { 3465 $outarray = array(); 3466 3467 foreach ( (array) $inarray as $inkey => $inval ) { 3468 $outkey = strtolower( $inkey ); 3469 $outarray[ $outkey ] = array(); 3470 3471 foreach ( (array) $inval as $inkey2 => $inval2 ) { 3472 $outkey2 = strtolower( $inkey2 ); 3473 $outarray[ $outkey ][ $outkey2 ] = $inval2; 3474 } 3475 } 3476 3477 return $outarray; 3478 } 3479 3480 /** 3481 * Sanitizes content from bad protocols and other characters. 3482 * 3483 * This function searches for URL protocols at the beginning of the string, while 3484 * handling whitespace and HTML entities. 3485 * 3486 * @since 1.0.0 3487 * 3488 * @param string $content Content to check for bad protocols. 3489 * @param string[] $allowed_protocols Array of allowed URL protocols. 3490 * @param int $count Depth of call recursion to this function. 3491 * @return string Sanitized content. 3492 */ 3493 function wp_kses_bad_protocol_once( $content, $allowed_protocols, $count = 1 ) { 3494 $content = preg_replace( '/(�*58(?![;0-9])|�*3a(?![;a-f0-9]))/i', '$1;', $content ); 3495 $content2 = preg_split( '/:|�*58;|�*3a;|:/i', $content, 2 ); 3496 3497 if ( isset( $content2[1] ) && ! preg_match( '%/\?%', $content2[0] ) ) { 3498 $content = trim( $content2[1] ); 3499 $protocol = wp_kses_bad_protocol_once2( $content2[0], $allowed_protocols ); 3500 if ( 'feed:' === $protocol ) { 3501 if ( $count > 2 ) { 3502 return ''; 3503 } 3504 $content = wp_kses_bad_protocol_once( $content, $allowed_protocols, ++$count ); 3505 if ( empty( $content ) ) { 3506 return $content; 3507 } 3508 } 3509 $content = $protocol . $content; 3510 } 3511 3512 return $content; 3513 } 3514 3515 /** 3516 * Callback for `wp_kses_bad_protocol_once()` regular expression. 3517 * 3518 * This function processes URL protocols, checks to see if they're in the 3519 * list of allowed protocols or not, and returns different data depending 3520 * on the answer. 3521 * 3522 * @access private 3523 * @ignore 3524 * @since 1.0.0 3525 * 3526 * @param string $scheme URI scheme to check against the list of allowed protocols. 3527 * @param string[] $allowed_protocols Array of allowed URL protocols. 3528 * @return string Sanitized content. 3529 */ 3530 function wp_kses_bad_protocol_once2( $scheme, $allowed_protocols ) { 3531 $scheme = wp_kses_decode_entities( $scheme ); 3532 $scheme = preg_replace( '/\s/', '', $scheme ); 3533 $scheme = wp_kses_no_null( $scheme ); 3534 $scheme = strtolower( $scheme ); 3535 3536 $allowed = array_any( (array) $allowed_protocols, fn( $protocol ) => strtolower( $protocol ) === $scheme ); 3537 3538 if ( $allowed ) { 3539 return "$scheme:"; 3540 } else { 3541 return ''; 3542 } 3543 } 3544 3545 /** 3546 * Converts and fixes HTML entities. 3547 * 3548 * This function normalizes HTML entities. It will convert `AT&T` to the correct 3549 * `AT&T`, `:` to `:`, `&#XYZZY;` to `&#XYZZY;` and so on. 3550 * 3551 * When `$context` is set to 'xml', HTML entities are converted to their code points. For 3552 * example, `AT&T…&#XYZZY;` is converted to `AT&T…&#XYZZY;`. 3553 * 3554 * @since 1.0.0 3555 * @since 5.5.0 Added `$context` parameter. 3556 * 3557 * @param string $content Content to normalize entities. 3558 * @param string $context Context for normalization. Can be either 'html' or 'xml'. 3559 * Default 'html'. 3560 * @return string Content with normalized entities. 3561 */ 3562 function wp_kses_normalize_entities( $content, $context = 'html' ) { 3563 // Disarm all entities by converting & to & 3564 $content = str_replace( '&', '&', $content ); 3565 3566 /* 3567 * Decode any character references that are now double-encoded. 3568 * 3569 * It's important that the following normalizations happen in the correct order. 3570 * 3571 * At this point, all `&` have been transformed to `&`. Double-encoded named character 3572 * references like `&amp;` will be decoded back to their single-encoded form `&`. 3573 * 3574 * First, numeric (decimal and hexadecimal) character references must be handled so that 3575 * `&#09;` becomes `	`. If the named character references were handled first, there 3576 * would be no way to know whether the double-encoded character reference had been produced 3577 * in this function or was the original input. 3578 * 3579 * Consider the two examples, first with named entity decoding followed by numeric 3580 * entity decoding. We'll use U+002E FULL STOP (.) in our example, this table follows the 3581 * string processing from left to right: 3582 * 3583 * | Input | &-encoded | Named ref double-decoded | Numeric ref double-decoded | 3584 * | ------------ | ---------------- | ------------------------- | -------------------------- | 3585 * | `.` | `&#x2E;` | `&#x2E;` | `.` | 3586 * | `&#x2E;` | `&amp;#x2E;` | `&#x2E;` | `.` | 3587 * 3588 * Notice in the example above that different inputs result in the same result. The second case 3589 * was not normalized and produced HTML that is semantically different from the input. 3590 * 3591 * | Input | &-encoded | Numeric ref double-decoded | Named ref double-decoded | 3592 * | ------------ | ---------------- | --------------------------- | ------------------------ | 3593 * | `.` | `&#x2E;` | `.` | `.` | 3594 * | `&#x2E;` | `&amp;#x2E;` | `&amp;#x2E;` | `&#x2E;` | 3595 * 3596 * Here, each input is normalized to an appropriate output. 3597 */ 3598 $content = preg_replace_callback( '/&#(0*[1-9][0-9]{0,6});/', 'wp_kses_normalize_entities2', $content ); 3599 $content = preg_replace_callback( '/&#[Xx](0*[1-9A-Fa-f][0-9A-Fa-f]{0,5});/', 'wp_kses_normalize_entities3', $content ); 3600 if ( 'xml' === $context ) { 3601 $content = preg_replace_callback( '/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $content ); 3602 } else { 3603 $content = preg_replace_callback( '/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $content ); 3604 } 3605 3606 return $content; 3607 } 3608 3609 /** 3610 * Callback for `wp_kses_normalize_entities()` regular expression. 3611 * 3612 * This function only accepts valid named entity references, which are finite, 3613 * case-sensitive, and highly scrutinized by HTML and XML validators. 3614 * 3615 * @since 3.0.0 3616 * 3617 * @global array $allowedentitynames 3618 * 3619 * @param array $matches preg_replace_callback() matches array. 3620 * @return string Correctly encoded entity. 3621 */ 3622 function wp_kses_named_entities( $matches ) { 3623 global $allowedentitynames; 3624 3625 if ( empty( $matches[1] ) ) { 3626 return ''; 3627 } 3628 3629 $i = $matches[1]; 3630 return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&$i;" : "&$i;"; 3631 } 3632 3633 /** 3634 * Callback for `wp_kses_normalize_entities()` regular expression. 3635 * 3636 * This function only accepts valid named entity references, which are finite, 3637 * case-sensitive, and highly scrutinized by XML validators. HTML named entity 3638 * references are converted to their code points. 3639 * 3640 * @since 5.5.0 3641 * 3642 * @global array $allowedentitynames 3643 * @global array $allowedxmlentitynames 3644 * 3645 * @param array $matches preg_replace_callback() matches array. 3646 * @return string Correctly encoded entity. 3647 */ 3648 function wp_kses_xml_named_entities( $matches ) { 3649 global $allowedentitynames, $allowedxmlentitynames; 3650 3651 if ( empty( $matches[1] ) ) { 3652 return ''; 3653 } 3654 3655 $i = $matches[1]; 3656 3657 if ( in_array( $i, $allowedxmlentitynames, true ) ) { 3658 return "&$i;"; 3659 } elseif ( in_array( $i, $allowedentitynames, true ) ) { 3660 return html_entity_decode( "&$i;", ENT_HTML5 ); 3661 } 3662 3663 return "&$i;"; 3664 } 3665 3666 /** 3667 * Callback for `wp_kses_normalize_entities()` regular expression. 3668 * 3669 * This function helps `wp_kses_normalize_entities()` to only accept 16-bit 3670 * values and nothing more for `&#number;` entities. 3671 * 3672 * @access private 3673 * @ignore 3674 * @since 1.0.0 3675 * 3676 * @param array $matches `preg_replace_callback()` matches array. 3677 * @return string Correctly encoded entity. 3678 */ 3679 function wp_kses_normalize_entities2( $matches ) { 3680 if ( empty( $matches[1] ) ) { 3681 return ''; 3682 } 3683 3684 $i = $matches[1]; 3685 3686 if ( valid_unicode( $i ) ) { 3687 $i = str_pad( ltrim( $i, '0' ), 3, '0', STR_PAD_LEFT ); 3688 $i = "&#$i;"; 3689 } else { 3690 $i = "&#$i;"; 3691 } 3692 3693 return $i; 3694 } 3695 3696 /** 3697 * Callback for `wp_kses_normalize_entities()` for regular expression. 3698 * 3699 * This function helps `wp_kses_normalize_entities()` to only accept valid Unicode 3700 * numeric entities in hex form. 3701 * 3702 * @since 2.7.0 3703 * @access private 3704 * @ignore 3705 * 3706 * @param array $matches `preg_replace_callback()` matches array. 3707 * @return string Correctly encoded entity. 3708 */ 3709 function wp_kses_normalize_entities3( $matches ) { 3710 if ( empty( $matches[1] ) ) { 3711 return ''; 3712 } 3713 3714 $hexchars = $matches[1]; 3715 3716 return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&#x$hexchars;" : '&#x' . ltrim( $hexchars, '0' ) . ';'; 3717 } 3718 3719 /** 3720 * Determines whether a code point is allowed by the XML Char production. 3721 * 3722 * Despite its name, this helper does not report whether a code point is valid 3723 * Unicode. It follows the XML Char production: C0 controls other than 3724 * HT/LF/CR are rejected even though they are valid Unicode (for example 3725 * U+0008 BACKSPACE), as are surrogates and U+FFFE/U+FFFF. 3726 * 3727 * Prefer the newer Unicode/UTF-8 helpers (for example {@see wp_is_valid_utf8()}) 3728 * rather than extending call sites here. 3729 * 3730 * > Characters 3731 * > 3732 * > … 3733 * > Legal characters are tab, carriage return, line feed, and the legal characters of 3734 * > Unicode and ISO/IEC 10646. 3735 * > … 3736 * > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF] 3737 * 3738 * @since 2.7.0 3739 * 3740 * @link https://www.w3.org/TR/xml/#charsets 3741 * 3742 * @param int $i Code point to check. 3743 * @return bool Whether the code point is allowed by the XML Char production. 3744 */ 3745 function valid_unicode( $i ) { 3746 $i = (int) $i; 3747 3748 return ( 3749 0x9 === $i || // U+0009 HORIZONTAL TABULATION (HT) 3750 0xA === $i || // U+000A LINE FEED (LF) 3751 0xD === $i || // U+000D CARRIAGE RETURN (CR) 3752 /* 3753 * The valid Unicode characters according to the XML specification: 3754 * 3755 * > any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. 3756 */ 3757 ( 0x20 <= $i && $i <= 0xD7FF ) || 3758 ( 0xE000 <= $i && $i <= 0xFFFD ) || 3759 ( 0x10000 <= $i && $i <= 0x10FFFF ) 3760 ); 3761 } 3762 3763 /** 3764 * Converts all numeric HTML entities to their named counterparts. 3765 * 3766 * This function decodes numeric HTML entities (`A` and `A`). 3767 * It doesn't do anything with named entities like `ä`, but we don't 3768 * need them in the allowed URL protocols system anyway. 3769 * 3770 * @since 1.0.0 3771 * 3772 * @param string $content Content to change entities. 3773 * @return string Content after decoded entities. 3774 */ 3775 function wp_kses_decode_entities( $content ) { 3776 $content = preg_replace_callback( '/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $content ); 3777 $content = preg_replace_callback( '/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $content ); 3778 3779 return $content; 3780 } 3781 3782 /** 3783 * Regex callback for `wp_kses_decode_entities()`. 3784 * 3785 * @since 2.9.0 3786 * @access private 3787 * @ignore 3788 * 3789 * @param array $matches preg match 3790 * @return string 3791 */ 3792 function _wp_kses_decode_entities_chr( $matches ) { 3793 return chr( $matches[1] ); 3794 } 3795 3796 /** 3797 * Regex callback for `wp_kses_decode_entities()`. 3798 * 3799 * @since 2.9.0 3800 * @access private 3801 * @ignore 3802 * 3803 * @param array $matches preg match 3804 * @return string 3805 */ 3806 function _wp_kses_decode_entities_chr_hexdec( $matches ) { 3807 return chr( hexdec( $matches[1] ) ); 3808 } 3809 3810 /** 3811 * Sanitize content with allowed HTML KSES rules. 3812 * 3813 * This function expects slashed data. 3814 * 3815 * @since 1.0.0 3816 * 3817 * @param string $data Content to filter, expected to be escaped with slashes. 3818 * @return string Filtered content. 3819 */ 3820 function wp_filter_kses( $data ) { 3821 return addslashes( wp_kses( stripslashes( $data ), current_filter() ) ); 3822 } 3823 3824 /** 3825 * Sanitize content with allowed HTML KSES rules. 3826 * 3827 * This function expects unslashed data. 3828 * 3829 * @since 2.9.0 3830 * 3831 * @param string $data Content to filter, expected to not be escaped. 3832 * @return string Filtered content. 3833 */ 3834 function wp_kses_data( $data ) { 3835 return wp_kses( $data, current_filter() ); 3836 } 3837 3838 /** 3839 * Sanitizes content for allowed HTML tags for post content. 3840 * 3841 * Post content refers to the page contents of the 'post' type and not `$_POST` 3842 * data from forms. 3843 * 3844 * This function expects slashed data. 3845 * 3846 * @since 2.0.0 3847 * 3848 * @param string $data Post content to filter, expected to be escaped with slashes. 3849 * @return string Filtered post content with allowed HTML tags and attributes intact. 3850 */ 3851 function wp_filter_post_kses( $data ) { 3852 return addslashes( wp_kses( stripslashes( $data ), 'post' ) ); 3853 } 3854 3855 /** 3856 * Sanitizes global styles user content removing unsafe rules. 3857 * 3858 * @since 5.9.0 3859 * 3860 * @param string $data Post content to filter. 3861 * @return string Filtered post content with unsafe rules removed. 3862 */ 3863 function wp_filter_global_styles_post( $data ) { 3864 $decoded_data = json_decode( wp_unslash( $data ), true ); 3865 $json_decoding_error = json_last_error(); 3866 if ( 3867 JSON_ERROR_NONE === $json_decoding_error && 3868 is_array( $decoded_data ) && 3869 isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) && 3870 $decoded_data['isGlobalStylesUserThemeJSON'] 3871 ) { 3872 unset( $decoded_data['isGlobalStylesUserThemeJSON'] ); 3873 3874 $data_to_encode = WP_Theme_JSON::remove_insecure_properties( $decoded_data, 'custom' ); 3875 3876 $data_to_encode['isGlobalStylesUserThemeJSON'] = true; 3877 /** 3878 * JSON encode the data stored in post content. 3879 * Escape characters that are likely to be mangled by HTML filters: "<>&". 3880 * 3881 * This matches the escaping in {@see WP_REST_Global_Styles_Controller::prepare_item_for_database()}. 3882 */ 3883 return wp_slash( wp_json_encode( $data_to_encode, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) ); 3884 } 3885 return $data; 3886 } 3887 3888 /** 3889 * Sanitizes content for allowed HTML tags for post content. 3890 * 3891 * Post content refers to the page contents of the 'post' type and not `$_POST` 3892 * data from forms. 3893 * 3894 * This function expects unslashed data. 3895 * 3896 * @since 2.9.0 3897 * 3898 * @param string $data Post content to filter. 3899 * @return string Filtered post content with allowed HTML tags and attributes intact. 3900 */ 3901 function wp_kses_post( $data ) { 3902 return wp_kses( $data, 'post' ); 3903 } 3904 3905 /** 3906 * Navigates through an array, object, or scalar, and sanitizes content for 3907 * allowed HTML tags for post content. 3908 * 3909 * @since 4.4.2 3910 * 3911 * @see map_deep() 3912 * 3913 * @param mixed $data The array, object, or scalar value to inspect. 3914 * @return mixed The filtered content. 3915 */ 3916 function wp_kses_post_deep( $data ) { 3917 return map_deep( $data, 'wp_kses_post' ); 3918 } 3919 3920 /** 3921 * Strips all HTML from a text string. 3922 * 3923 * This function expects slashed data. 3924 * 3925 * @since 2.1.0 3926 * 3927 * @param string $data Content to strip all HTML from. 3928 * @return string Filtered content without any HTML. 3929 */ 3930 function wp_filter_nohtml_kses( $data ) { 3931 return addslashes( wp_kses( stripslashes( $data ), 'strip' ) ); 3932 } 3933 3934 /** 3935 * Adds all KSES input form content filters. 3936 * 3937 * All hooks have default priority. The `wp_filter_kses()` function is added to 3938 * the 'pre_comment_content' and 'title_save_pre' hooks. 3939 * 3940 * The `wp_filter_post_kses()` function is added to the 'content_save_pre', 3941 * 'excerpt_save_pre', and 'content_filtered_save_pre' hooks. 3942 * 3943 * @since 2.0.0 3944 */ 3945 function kses_init_filters() { 3946 // Normal filtering. 3947 add_filter( 'title_save_pre', 'wp_filter_kses' ); 3948 3949 // Comment filtering. 3950 if ( current_user_can( 'unfiltered_html' ) ) { 3951 add_filter( 'pre_comment_content', 'wp_filter_post_kses' ); 3952 } else { 3953 add_filter( 'pre_comment_content', 'wp_filter_kses' ); 3954 } 3955 3956 // Global Styles filtering: Global Styles filters should be executed before normal post_kses HTML filters. 3957 add_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 ); 3958 add_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 ); 3959 3960 // Post filtering. 3961 add_filter( 'content_save_pre', 'wp_filter_post_kses' ); 3962 add_filter( 'excerpt_save_pre', 'wp_filter_post_kses' ); 3963 add_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' ); 3964 } 3965 3966 /** 3967 * Removes all KSES input form content filters. 3968 * 3969 * A quick procedural method to removing all of the filters that KSES uses for 3970 * content in WordPress Loop. 3971 * 3972 * Does not remove the `kses_init()` function from {@see 'init'} hook (priority is 3973 * default). Also does not remove `kses_init()` function from {@see 'set_current_user'} 3974 * hook (priority is also default). 3975 * 3976 * @since 2.0.6 3977 */ 3978 function kses_remove_filters() { 3979 // Normal filtering. 3980 remove_filter( 'title_save_pre', 'wp_filter_kses' ); 3981 3982 // Comment filtering. 3983 remove_filter( 'pre_comment_content', 'wp_filter_post_kses' ); 3984 remove_filter( 'pre_comment_content', 'wp_filter_kses' ); 3985 3986 // Global Styles filtering. 3987 remove_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 ); 3988 remove_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 ); 3989 3990 // Post filtering. 3991 remove_filter( 'content_save_pre', 'wp_filter_post_kses' ); 3992 remove_filter( 'excerpt_save_pre', 'wp_filter_post_kses' ); 3993 remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' ); 3994 } 3995 3996 /** 3997 * Sets up most of the KSES filters for input form content. 3998 * 3999 * First removes all of the KSES filters in case the current user does not need 4000 * to have KSES filter the content. If the user does not have `unfiltered_html` 4001 * capability, then KSES filters are added. 4002 * 4003 * @since 2.0.0 4004 */ 4005 function kses_init() { 4006 kses_remove_filters(); 4007 4008 if ( ! current_user_can( 'unfiltered_html' ) ) { 4009 kses_init_filters(); 4010 } 4011 } 4012 4013 /** 4014 * Filters an inline style attribute and removes disallowed rules. 4015 * 4016 * @since 2.8.1 4017 * @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`. 4018 * @since 4.6.0 Added support for `list-style-type`. 4019 * @since 5.0.0 Added support for `background-image`. 4020 * @since 5.1.0 Added support for `text-transform`. 4021 * @since 5.2.0 Added support for `background-position` and `grid-template-columns`. 4022 * @since 5.3.0 Added support for `grid`, `flex` and `column` layout properties. 4023 * Extended `background-*` support for individual properties. 4024 * @since 5.3.1 Added support for gradient backgrounds. 4025 * @since 5.7.1 Added support for `object-position`. 4026 * @since 5.8.0 Added support for `calc()` and `var()` values. 4027 * @since 6.1.0 Added support for `min()`, `max()`, `minmax()`, `clamp()`, 4028 * nested `var()` values, and assigning values to CSS variables. 4029 * Added support for `object-fit`, `gap`, `column-gap`, `row-gap`, and `flex-wrap`. 4030 * Extended `margin-*` and `padding-*` support for logical properties. 4031 * @since 6.2.0 Added support for `aspect-ratio`, `position`, `top`, `right`, `bottom`, `left`, 4032 * and `z-index` CSS properties. 4033 * @since 6.3.0 Extended support for `filter` to accept a URL and added support for repeat(). 4034 * Added support for `box-shadow`. 4035 * @since 6.4.0 Added support for `writing-mode`. 4036 * @since 6.5.0 Added support for `background-repeat`. 4037 * @since 6.6.0 Added support for `grid-column`, `grid-row`, and `container-type`. 4038 * @since 6.9.0 Added support for `white-space`. 4039 * @since 7.1.0 Extended gradient support to allow any single-level nested function. 4040 * Added support for transform functions, `clip-path` basic shapes, 4041 * and URLs in the SVG element reference properties. 4042 * @since 7.2.0 Added support for CSS anchor positioning properties and `text-shadow`. 4043 * Added support for `background-clip`. 4044 * 4045 * @param string $css A string of CSS rules, decoded from an HTML `style` attribute. 4046 * @param string $deprecated Not used. 4047 * @return string Filtered string of CSS rules, needing HTML escaping before sending back to a `style` attribute. 4048 * 4049 * @phpstan-param '' $deprecated 4050 */ 4051 function safecss_filter_attr( $css, $deprecated = '' ) { 4052 if ( ! empty( $deprecated ) ) { 4053 _deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented. 4054 } 4055 4056 $css = wp_kses_no_null( $css ); 4057 $css = str_replace( array( "\n", "\r", "\t" ), '', $css ); 4058 4059 $allowed_protocols = wp_allowed_protocols(); 4060 4061 /** @todo Parse enough CSS to split rules without breaking on things like quoted strings. */ 4062 $css_array = explode( ';', trim( $css ) ); 4063 4064 /** 4065 * Filters the list of allowed CSS attributes. 4066 * 4067 * @since 2.8.1 4068 * @since 7.1.0 Added support for SVG presentation attributes. 4069 * @since 7.2.0 Added support for `background-clip` and its vendor prefixed companions. 4070 * 4071 * @param string[] $attr Array of allowed CSS attributes. 4072 */ 4073 $allowed_attr = apply_filters( 4074 'safe_style_css', 4075 array( 4076 'background', 4077 'background-color', 4078 'background-image', 4079 'background-position', 4080 'background-repeat', 4081 'background-size', 4082 'background-attachment', 4083 'background-blend-mode', 4084 'background-clip', 4085 '-webkit-background-clip', 4086 '-webkit-text-fill-color', 4087 4088 'border', 4089 'border-radius', 4090 'border-width', 4091 'border-color', 4092 'border-style', 4093 'border-right', 4094 'border-right-color', 4095 'border-right-style', 4096 'border-right-width', 4097 'border-bottom', 4098 'border-bottom-color', 4099 'border-bottom-left-radius', 4100 'border-bottom-right-radius', 4101 'border-bottom-style', 4102 'border-bottom-width', 4103 'border-bottom-right-radius', 4104 'border-bottom-left-radius', 4105 'border-left', 4106 'border-left-color', 4107 'border-left-style', 4108 'border-left-width', 4109 'border-top', 4110 'border-top-color', 4111 'border-top-left-radius', 4112 'border-top-right-radius', 4113 'border-top-style', 4114 'border-top-width', 4115 'border-top-left-radius', 4116 'border-top-right-radius', 4117 4118 'border-spacing', 4119 'border-collapse', 4120 'caption-side', 4121 4122 'columns', 4123 'column-count', 4124 'column-fill', 4125 'column-gap', 4126 'column-rule', 4127 'column-span', 4128 'column-width', 4129 4130 'display', 4131 4132 'color', 4133 'filter', 4134 'font', 4135 'font-family', 4136 'font-size', 4137 'font-style', 4138 'font-variant', 4139 'font-weight', 4140 'letter-spacing', 4141 'line-height', 4142 'text-align', 4143 'text-decoration', 4144 'text-indent', 4145 'text-shadow', 4146 'text-transform', 4147 'white-space', 4148 4149 'height', 4150 'min-height', 4151 'max-height', 4152 4153 'width', 4154 'min-width', 4155 'max-width', 4156 4157 'margin', 4158 'margin-right', 4159 'margin-bottom', 4160 'margin-left', 4161 'margin-top', 4162 'margin-block-start', 4163 'margin-block-end', 4164 'margin-inline-start', 4165 'margin-inline-end', 4166 4167 'padding', 4168 'padding-right', 4169 'padding-bottom', 4170 'padding-left', 4171 'padding-top', 4172 'padding-block-start', 4173 'padding-block-end', 4174 'padding-inline-start', 4175 'padding-inline-end', 4176 4177 'flex', 4178 'flex-basis', 4179 'flex-direction', 4180 'flex-flow', 4181 'flex-grow', 4182 'flex-shrink', 4183 'flex-wrap', 4184 4185 'gap', 4186 'column-gap', 4187 'row-gap', 4188 4189 'grid-template-columns', 4190 'grid-auto-columns', 4191 'grid-column-start', 4192 'grid-column-end', 4193 'grid-column', 4194 'grid-column-gap', 4195 'grid-template-rows', 4196 'grid-auto-rows', 4197 'grid-row-start', 4198 'grid-row-end', 4199 'grid-row', 4200 'grid-row-gap', 4201 'grid-gap', 4202 4203 'justify-content', 4204 'justify-items', 4205 'justify-self', 4206 'align-content', 4207 'align-items', 4208 'align-self', 4209 4210 'clear', 4211 'cursor', 4212 'direction', 4213 'float', 4214 'list-style-type', 4215 'object-fit', 4216 'object-position', 4217 'opacity', 4218 'overflow', 4219 'vertical-align', 4220 'writing-mode', 4221 4222 'position', 4223 'top', 4224 'right', 4225 'bottom', 4226 'left', 4227 'z-index', 4228 'box-shadow', 4229 'aspect-ratio', 4230 'container-type', 4231 4232 'fill', 4233 'fill-opacity', 4234 'fill-rule', 4235 4236 'stroke', 4237 'stroke-dasharray', 4238 'stroke-dashoffset', 4239 'stroke-linecap', 4240 'stroke-linejoin', 4241 'stroke-miterlimit', 4242 'stroke-opacity', 4243 'stroke-width', 4244 4245 'color-interpolation', 4246 'color-interpolation-filters', 4247 'paint-order', 4248 'stop-color', 4249 'stop-opacity', 4250 'flood-color', 4251 'flood-opacity', 4252 'lighting-color', 4253 4254 'marker', 4255 'marker-end', 4256 'marker-mid', 4257 'marker-start', 4258 4259 'clip-path', 4260 'clip-rule', 4261 'mask', 4262 'mask-type', 4263 4264 'cx', 4265 'cy', 4266 'r', 4267 'rx', 4268 'ry', 4269 'x', 4270 'y', 4271 'd', 4272 4273 'alignment-baseline', 4274 'baseline-shift', 4275 'dominant-baseline', 4276 'glyph-orientation-horizontal', 4277 'glyph-orientation-vertical', 4278 'text-anchor', 4279 'unicode-bidi', 4280 'word-spacing', 4281 4282 'font-size-adjust', 4283 'font-stretch', 4284 4285 'color-rendering', 4286 'image-rendering', 4287 'shape-rendering', 4288 'text-rendering', 4289 'vector-effect', 4290 4291 'transform', 4292 'transform-origin', 4293 4294 'pointer-events', 4295 'visibility', 4296 4297 'anchor-name', 4298 'anchor-scope', 4299 'position-anchor', 4300 'position-area', 4301 'position-try', 4302 'position-try-fallbacks', 4303 'position-try-order', 4304 'position-visibility', 4305 4306 // Custom CSS properties. 4307 '--*', 4308 ) 4309 ); 4310 4311 /* 4312 * CSS attributes that accept URL data types. 4313 * 4314 * This is in accordance to the CSS spec and unrelated to 4315 * the sub-set of supported attributes above. 4316 * 4317 * See: https://developer.mozilla.org/en-US/docs/Web/CSS/url 4318 */ 4319 $css_url_data_types = array( 4320 'background', 4321 'background-image', 4322 4323 'cursor', 4324 'filter', 4325 4326 'list-style', 4327 'list-style-image', 4328 4329 // SVG presentation properties that accept url() references. 4330 'clip-path', 4331 'fill', 4332 'marker', 4333 'marker-end', 4334 'marker-mid', 4335 'marker-start', 4336 'mask', 4337 'stroke', 4338 ); 4339 4340 /* 4341 * CSS attributes that accept gradient data types. 4342 * 4343 */ 4344 $css_gradient_data_types = array( 4345 'background', 4346 'background-image', 4347 ); 4348 4349 if ( empty( $allowed_attr ) ) { 4350 return $css; 4351 } 4352 4353 $css = ''; 4354 foreach ( $css_array as $css_item ) { 4355 if ( '' === $css_item ) { 4356 continue; 4357 } 4358 4359 $css_item = trim( $css_item ); 4360 $css_test_string = $css_item; 4361 $found = false; 4362 $url_attr = false; 4363 $gradient_attr = false; 4364 $is_custom_var = false; 4365 4366 if ( ! str_contains( $css_item, ':' ) ) { 4367 $found = true; 4368 } else { 4369 $parts = explode( ':', $css_item, 2 ); 4370 $css_selector = trim( $parts[0] ); 4371 4372 // Allow assigning values to CSS variables. 4373 if ( in_array( '--*', $allowed_attr, true ) && preg_match( '/^--[a-zA-Z0-9-_]+$/', $css_selector ) ) { 4374 $allowed_attr[] = $css_selector; 4375 $is_custom_var = true; 4376 } 4377 4378 if ( in_array( $css_selector, $allowed_attr, true ) ) { 4379 $found = true; 4380 $url_attr = in_array( $css_selector, $css_url_data_types, true ); 4381 $gradient_attr = in_array( $css_selector, $css_gradient_data_types, true ); 4382 } 4383 4384 if ( $is_custom_var ) { 4385 $css_value = trim( $parts[1] ); 4386 $url_attr = str_starts_with( $css_value, 'url(' ); 4387 $gradient_attr = str_contains( $css_value, '-gradient(' ); 4388 } 4389 } 4390 4391 if ( $found && $url_attr ) { 4392 // Simplified: matches the sequence `url(*)`. 4393 preg_match_all( '/url\([^)]+\)/', $parts[1], $url_matches ); 4394 4395 foreach ( $url_matches[0] as $url_match ) { 4396 // Clean up the URL from each of the matches above. 4397 preg_match( '/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces ); 4398 4399 if ( empty( $url_pieces[2] ) ) { 4400 $found = false; 4401 break; 4402 } 4403 4404 $url = trim( $url_pieces[2] ); 4405 4406 if ( empty( $url ) || wp_kses_bad_protocol( $url, $allowed_protocols ) !== $url ) { 4407 $found = false; 4408 break; 4409 } else { 4410 // Remove the whole `url(*)` bit that was matched above from the CSS. 4411 $css_test_string = str_replace( $url_match, '', $css_test_string ); 4412 } 4413 } 4414 } 4415 4416 if ( $found && $gradient_attr ) { 4417 /* 4418 * Match every `*-gradient()` in the value, allowing one level of nested functions 4419 * (e.g. rgb(), hsl(), var()). Matching each occurrence, rather than requiring the 4420 * whole value to be a single gradient, lets a gradient combine with a url() image. 4421 */ 4422 preg_match_all( '/(?:repeating-)?(?:linear|radial|conic)-gradient\((?:[^()]|\([^()]*\))*\)/', $css_test_string, $gradient_matches ); 4423 4424 foreach ( $gradient_matches[0] as $gradient_match ) { 4425 // Remove each `gradient()` bit that was matched above from the CSS. 4426 $css_test_string = str_replace( $gradient_match, '', $css_test_string ); 4427 } 4428 } 4429 4430 if ( $found ) { 4431 /* 4432 * Allow CSS functions like var(), calc(), etc. by removing them from the test string. 4433 * Nested functions and parentheses are also removed, so long as the parentheses are balanced. 4434 */ 4435 $css_test_string = preg_replace( 4436 '/\b(?:' 4437 // General purpose value functions. 4438 . 'var|calc|min|max|minmax|clamp|repeat' 4439 // Transform functions. 4440 . '|matrix|matrix3d|perspective' 4441 . '|rotate|rotate3d|rotateX|rotateY|rotateZ' 4442 . '|scale|scale3d|scaleX|scaleY|scaleZ' 4443 . '|skew|skewX|skewY' 4444 . '|translate|translate3d|translateX|translateY|translateZ' 4445 // Basic shape functions, as used by `clip-path`. 4446 . '|circle|ellipse|inset|path|polygon|rect|shape|xywh' 4447 . ')(\((?:[^()]|(?1))*\))/', 4448 '', 4449 $css_test_string 4450 ); 4451 4452 // Bail if the recursive function stripping hit a PCRE error (e.g. stack/backtrack limit). 4453 if ( null === $css_test_string ) { 4454 continue; 4455 } 4456 4457 /* 4458 * Disallow CSS containing \ ( & } = or comments, except for within url(), var(), calc(), etc. 4459 * which were removed from the test string above. 4460 */ 4461 $allow_css = 0 === preg_match( '%[\\\(&=}]|/\*%', $css_test_string ); 4462 4463 /** 4464 * Filters the check for unsafe CSS in `safecss_filter_attr`. 4465 * 4466 * Enables developers to determine whether a section of CSS should be allowed or discarded. 4467 * By default, the value will be false if the part contains \ ( & } = or comments. 4468 * Return true to allow the CSS part to be included in the output. 4469 * 4470 * @since 5.5.0 4471 * 4472 * @param bool $allow_css Whether the CSS in the test string is considered safe. 4473 * @param string $css_test_string The CSS string to test. 4474 */ 4475 $allow_css = apply_filters( 'safecss_filter_attr_allow_css', $allow_css, $css_test_string ); 4476 4477 // Only add the CSS part if it passes the regex check. 4478 if ( $allow_css ) { 4479 if ( '' !== $css ) { 4480 $css .= ';'; 4481 } 4482 4483 $css .= $css_item; 4484 } 4485 } 4486 } 4487 4488 return $css; 4489 } 4490 4491 /** 4492 * Helper function to add global attributes to a tag in the allowed HTML list. 4493 * 4494 * @since 3.5.0 4495 * @since 5.0.0 Added support for `data-*` wildcard attributes. 4496 * @since 6.0.0 Added `dir`, `lang`, and `xml:lang` to global attributes. 4497 * @since 6.3.0 Added `aria-controls`, `aria-current`, and `aria-expanded` attributes. 4498 * @since 6.4.0 Added `aria-live` and `hidden` attributes. 4499 * @since 7.1.0 Added `tabindex` attribute. 4500 * 4501 * @access private 4502 * @ignore 4503 * 4504 * @param array $value An array of attributes. 4505 * @return array The array of attributes with global attributes added. 4506 */ 4507 function _wp_add_global_attributes( $value ) { 4508 $global_attributes = array( 4509 'aria-controls' => true, 4510 'aria-current' => true, 4511 'aria-describedby' => true, 4512 'aria-details' => true, 4513 'aria-expanded' => true, 4514 'aria-hidden' => true, 4515 'aria-label' => true, 4516 'aria-labelledby' => true, 4517 'aria-live' => true, 4518 'class' => true, 4519 'data-*' => true, 4520 'dir' => true, 4521 'hidden' => true, 4522 'id' => true, 4523 'lang' => true, 4524 'style' => true, 4525 'tabindex' => true, 4526 'title' => true, 4527 'role' => true, 4528 'xml:lang' => true, 4529 ); 4530 4531 if ( true === $value ) { 4532 $value = array(); 4533 } 4534 4535 if ( is_array( $value ) ) { 4536 return array_merge( $value, $global_attributes ); 4537 } 4538 4539 return $value; 4540 } 4541 4542 /** 4543 * Helper function to check if this is a safe PDF URL. 4544 * 4545 * @since 5.9.0 4546 * @access private 4547 * @ignore 4548 * 4549 * @param string $url The URL to check. 4550 * @return bool True if the URL is safe, false otherwise. 4551 */ 4552 function _wp_kses_allow_pdf_objects( $url ) { 4553 // We're not interested in URLs that contain query strings or fragments. 4554 if ( str_contains( $url, '?' ) || str_contains( $url, '#' ) ) { 4555 return false; 4556 } 4557 4558 // If it doesn't have a PDF extension, it's not safe. 4559 if ( ! str_ends_with( $url, '.pdf' ) ) { 4560 return false; 4561 } 4562 4563 // If the URL host matches the current site's media URL, it's safe. 4564 $upload_info = wp_upload_dir( null, false ); 4565 $parsed_url = wp_parse_url( $upload_info['url'] ); 4566 $upload_host = $parsed_url['host'] ?? ''; 4567 $upload_port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : ''; 4568 4569 if ( str_starts_with( $url, "http://$upload_host$upload_port/" ) 4570 || str_starts_with( $url, "https://$upload_host$upload_port/" ) 4571 ) { 4572 return true; 4573 } 4574 4575 return false; 4576 } 4577 4578 /** 4579 * Determines whether KSES restricts the value of any attribute of an element. 4580 * 4581 * An attribute rule other than `required` and `valueless` restricts the value itself, 4582 * for example `values` or `value_callback`. 4583 * 4584 * @since 7.1.4 4585 * @access private 4586 * @ignore 4587 * 4588 * @param array|bool $allowed_attributes The attributes KSES allows on the element. 4589 * @return bool Whether KSES restricts the value of any attribute of the element. 4590 */ 4591 function _wp_kses_restricts_attribute_values( $allowed_attributes ): bool { 4592 if ( ! is_array( $allowed_attributes ) ) { 4593 return false; 4594 } 4595 4596 foreach ( $allowed_attributes as $attribute_rules ) { 4597 if ( ! is_array( $attribute_rules ) ) { 4598 continue; 4599 } 4600 foreach ( array_keys( $attribute_rules ) as $rule ) { 4601 if ( ! in_array( strtolower( (string) $rule ), array( 'required', 'valueless' ), true ) ) { 4602 return true; 4603 } 4604 } 4605 } 4606 4607 return false; 4608 } 4609 4610 /** 4611 * Determines whether a directive binds an attribute whose value KSES restricts. 4612 * 4613 * This only applies to elements for which KSES restricts the value of at least one 4614 * attribute. On those elements, a `data-wp-bind` directive is reported unless it binds 4615 * an attribute which KSES allows there with any value. KSES calls this to keep such a 4616 * directive out of content saved by an author who cannot post unfiltered HTML. 4617 * 4618 * @since 7.1.4 4619 * @access private 4620 * @ignore 4621 * 4622 * @param string $directive_name The directive attribute name, in lowercase. 4623 * @param array|bool $allowed_attributes The attributes KSES allows on the element. 4624 * @return bool Whether the directive binds an attribute whose value KSES restricts. 4625 */ 4626 function _wp_kses_directive_binds_value_restricted_attribute( string $directive_name, $allowed_attributes ): bool { 4627 if ( ! str_starts_with( $directive_name, 'data-wp-bind--' ) ) { 4628 return false; 4629 } 4630 4631 if ( ! _wp_kses_restricts_attribute_values( $allowed_attributes ) ) { 4632 return false; 4633 } 4634 4635 /* 4636 * Both the whole remainder of the name and the part before a unique ID are checked, so 4637 * that the result does not depend on how the unique ID is parsed. A binding with a unique 4638 * ID is not applied at all, so removing one changes nothing. 4639 */ 4640 $bound_attribute = substr( $directive_name, strlen( 'data-wp-bind--' ) ); 4641 $bound_attributes = array( $bound_attribute ); 4642 $unique_id_index = strpos( $bound_attribute, '---' ); 4643 if ( false !== $unique_id_index ) { 4644 $bound_attributes[] = substr( $bound_attribute, 0, $unique_id_index ); 4645 } 4646 4647 foreach ( $bound_attributes as $attribute_name ) { 4648 if ( isset( $allowed_attributes[ $attribute_name ] ) ) { 4649 $rules = $allowed_attributes[ $attribute_name ]; 4650 } elseif ( 1 === preg_match( '/^data-[a-z0-9_-]+$/', $attribute_name ) && isset( $allowed_attributes['data-*'] ) ) { 4651 $rules = $allowed_attributes['data-*']; 4652 } else { 4653 return true; 4654 } 4655 4656 if ( ! $rules || is_array( $rules ) ) { 4657 return true; 4658 } 4659 } 4660 4661 return false; 4662 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated : Fri Dec 4 08:20:01 2026 | Cross-referenced by PHPXref |