- md5
- 7a2695779b7a23e3163b07b2c21fc491
- sha1
- 3fcabd3e45c3d53597344eaae79064d3214ee160
- sha256
- 20d4874714616d7ef74a3bc491502889172d53a83354bfbee1069d48a801426f
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342
<?php
/**
* kses 0.2.2 - HTML/XHTML filter that only allows some elements and attributes
* Copyright (C) 2002, 2003, 2005 Ulf Harnhammar
*
* This program is free software and open source software; you can redistribute
* it and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
* http://www.gnu.org/licenses/gpl.html
*
* [kses strips evil scripts!]
*
* Added wp_ prefix to avoid conflicts with existing kses users
*
* @version 0.2.2
* @copyright (C) 2002, 2003, 2005
* @author Ulf Harnhammar <http://advogato.org/person/metaur/>
*
* @package External
* @subpackage KSES
*/
/**
* Specifies the default allowable HTML tags.
*
* Using `CUSTOM_TAGS` is not recommended and should be considered deprecated. The
* {@see 'wp_kses_allowed_html'} filter is more powerful and supplies context.
*
* When using this constant, make sure to set all of these globals to arrays:
*
* - `$allowedposttags`
* - `$allowedtags`
* - `$allowedentitynames`
* - `$allowedxmlentitynames`
*
* @see wp_kses_allowed_html()
* @since 1.2.0
*
* @var array[]|false Array of default allowable HTML tags, or false to use the defaults.
*/
if ( ! defined( 'CUSTOM_TAGS' ) ) {
define( 'CUSTOM_TAGS', false );
}
// Ensure that these variables are added to the global namespace
// (e.g. if using namespaces / autoload in the current PHP environment).
global $allowedposttags, $allowedtags, $allowedentitynames, $allowedxmlentitynames;
/**
* Indicates which implementation of {@see \wp_kses()} is running.
*
* Nominally `legacy` unless temporarily-switched for {@see \wp_sanitize_html_kses()}.
* It’s safe to latch this into `legacy`.
*
* @global 'legacy'|'html-api' $wp_kses_operating_mode
*
* @since 7.2.0
*/
global $wp_kses_operating_mode;
$wp_kses_operating_mode = 'legacy';
if ( ! CUSTOM_TAGS ) {
/**
* KSES global for default allowable HTML tags.
*
* Can be overridden with the `CUSTOM_TAGS` constant.
*
* @var array[] $allowedposttags Array of default allowable HTML tags.
* @since 2.0.0
*/
$allowedposttags = array(
'address' => array(),
'a' => array(
'href' => true,
'rel' => true,
'rev' => true,
'name' => true,
'target' => true,
'download' => array(
'valueless' => 'y',
),
),
'abbr' => array(),
'acronym' => array(),
'area' => array(
'alt' => true,
'coords' => true,
'href' => true,
'nohref' => true,
'shape' => true,
'target' => true,
),
'article' => array(
'align' => true,
),
'aside' => array(
'align' => true,
),
'audio' => array(
'autoplay' => true,
'controls' => true,
'loop' => true,
'muted' => true,
'preload' => true,
'src' => true,
),
'b' => array(),
'bdo' => array(),
'big' => array(),
'blockquote' => array(
'cite' => true,
),
'br' => array(),
'button' => array(
'command' => true,
'commandfor' => true,
'disabled' => true,
'name' => true,
'type' => true,
'value' => true,
'popovertarget' => true,
'popovertargetaction' => true,
'aria-haspopup' => true,
),
'caption' => array(
'align' => true,
),
'cite' => array(),
'code' => array(),
'col' => array(
'align' => true,
'char' => true,
'charoff' => true,
'span' => true,
'valign' => true,
'width' => true,
),
'colgroup' => array(
'align' => true,
'char' => true,
'charoff' => true,
'span' => true,
'valign' => true,
'width' => true,
),
'data' => array(
'value' => true,
),
'del' => array(
'datetime' => true,
),
'dd' => array(),
'dfn' => array(),
'details' => array(
'align' => true,
'open' => true,
'name' => true,
),
'div' => array(
'align' => true,
'popover' => true,
),
'dialog' => array(
'closedby' => true,
'open' => true,
'popover' => true,
'autofocus' => true,
),
'dl' => array(),
'dt' => array(),
'em' => array(),
'fieldset' => array(),
'figure' => array(
'align' => true,
),
'figcaption' => array(
'align' => true,
),
'font' => array(
'color' => true,
'face' => true,
'size' => true,
),
'footer' => array(
'align' => true,
),
'h1' => array(
'align' => true,
),
'h2' => array(
'align' => true,
),
'h3' => array(
'align' => true,
),
'h4' => array(
'align' => true,
),
'h5' => array(
'align' => true,
),
'h6' => array(
'align' => true,
),
'header' => array(
'align' => true,
),
'hgroup' => array(
'align' => true,
),
'hr' => array(
'align' => true,
'noshade' => true,
'size' => true,
'width' => true,
),
'i' => array(),
'img' => array(
'alt' => true,
'align' => true,
'border' => true,
'height' => true,
'hspace' => true,
'loading' => true,
'longdesc' => true,
'vspace' => true,
'src' => true,
'usemap' => true,
'width' => true,
),
'ins' => array(
'datetime' => true,
'cite' => true,
),
'kbd' => array(),
'label' => array(
'for' => true,
),
'legend' => array(
'align' => true,
),
'li' => array(
'align' => true,
'value' => true,
),
'main' => array(
'align' => true,
),
'map' => array(
'name' => true,
),
'mark' => array(),
'menu' => array(
'type' => true,
),
'meter' => array(
'high' => true,
'low' => true,
'max' => true,
'min' => true,
'optimum' => true,
'value' => true,
),
'nav' => array(
'align' => true,
),
'object' => array(
'data' => array(
'required' => true,
'value_callback' => '_wp_kses_allow_pdf_objects',
),
'type' => array(
'required' => true,
'values' => array( 'application/pdf' ),
),
),
'p' => array(
'align' => true,
),
'pre' => array(
'width' => true,
),
'progress' => array(
'max' => true,
'value' => true,
),
'q' => array(
'cite' => true,
),
'rb' => array(),
'rp' => array(),
'rt' => array(),
'rtc' => array(),
'ruby' => array(),
's' => array(),
'samp' => array(),
'search' => array(),
'span' => array(
'align' => true,
),
'section' => array(
'align' => true,
),
'small' => array(),
'strike' => array(),
'strong' => array(),
'sub' => array(),
'summary' => array(
'align' => true,
),
'sup' => array(),
'table' => array(
'align' => true,
'bgcolor' => true,
'border' => true,
'cellpadding' => true,
'cellspacing' => true,
'rules' => true,
'summary' => true,
'width' => true,
),
'tbody' => array(
'align' => true,
'char' => true,
'charoff' => true,
'valign' => true,
),
'td' => array(
'abbr' => true,
'align' => true,
'axis' => true,
'bgcolor' => true,
'char' => true,
'charoff' => true,
'colspan' => true,
'headers' => true,
'height' => true,
'nowrap' => true,
'rowspan' => true,
'scope' => true,
'valign' => true,
'width' => true,
),
'textarea' => array(
'cols' => true,
'rows' => true,
'disabled' => true,
'name' => true,
'readonly' => true,
),
'tfoot' => array(
'align' => true,
'char' => true,
'charoff' => true,
'valign' => true,
),
'th' => array(
'abbr' => true,
'align' => true,
'axis' => true,
'bgcolor' => true,
'char' => true,
'charoff' => true,
'colspan' => true,
'headers' => true,
'height' => true,
'nowrap' => true,
'rowspan' => true,
'scope' => true,
'valign' => true,
'width' => true,
),
'thead' => array(
'align' => true,
'char' => true,
'charoff' => true,
'valign' => true,
),
'time' => array(
'datetime' => true,
),
'title' => array(),
'tr' => array(
'align' => true,
'bgcolor' => true,
'char' => true,
'charoff' => true,
'valign' => true,
),
'track' => array(
'default' => true,
'kind' => true,
'label' => true,
'src' => true,
'srclang' => true,
),
'tt' => array(),
'u' => array(),
'ul' => array(
'type' => true,
'popover' => true,
'role' => true,
),
'ol' => array(
'start' => true,
'type' => true,
'reversed' => true,
),
'var' => array(),
'video' => array(
'autoplay' => true,
'controls' => true,
'height' => true,
'loop' => true,
'muted' => true,
'playsinline' => true,
'poster' => true,
'preload' => true,
'src' => true,
'width' => true,
),
'wbr' => array(),
);
// https://www.w3.org/TR/mathml-core/#global-attributes
// Except common attributes added by _wp_add_global_attributes.
$math_global_attributes = array(
'displaystyle' => true,
'scriptlevel' => true,
'mathbackground' => true,
'mathcolor' => true,
'mathsize' => true,
// Common attributes also defined by _wp_add_global_attributes.
// We do not want to add all those global attributes though.
'class' => true,
'data-*' => true,
'dir' => true,
'id' => true,
'style' => true,
);
$math_overunder_attributes = array(
'accentunder' => true,
'accent' => true,
);
$allowedposttags = array_merge(
$allowedposttags,
array(
// https://www.w3.org/TR/mathml-core/#the-top-level-math-element
'math' => array_merge(
$math_global_attributes,
array(
'display' => true,
)
),
// https://www.w3.org/TR/mathml-core/#token-elements
// https://www.w3.org/TR/mathml-core/#text-mtext
'mtext' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#the-mi-element
'mi' => array_merge(
$math_global_attributes,
array(
'mathvariant' => true,
)
),
// https://www.w3.org/TR/mathml-core/#number-mn
'mn' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#operator-fence-separator-or-accent-mo
'mo' => array_merge(
$math_global_attributes,
array(
'form' => true,
'fence' => true,
'separator' => true,
'lspace' => true,
'rspace' => true,
'stretchy' => true,
'symmetric' => true,
'maxsize' => true,
'minsize' => true,
'largeop' => true,
'movablelimits' => true,
)
),
// https://www.w3.org/TR/mathml-core/#space-mspace
'mspace' => array_merge(
$math_global_attributes,
array(
'width' => true,
'height' => true,
'depth' => true,
)
),
// https://www.w3.org/TR/mathml-core/#string-literal-ms
'ms' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#general-layout-schemata
// https://www.w3.org/TR/mathml-core/#horizontally-group-sub-expressions-mrow
'mrow' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#fractions-mfrac
'mfrac' => array_merge(
$math_global_attributes,
array(
'linethickness' => true,
)
),
// https://www.w3.org/TR/mathml-core/#radicals-msqrt-mroot
'msqrt' => $math_global_attributes,
'mroot' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#style-change-mstyle
'mstyle' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#error-message-merror
'merror' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#adjust-space-around-content-mpadded
'mpadded' => array_merge(
$math_global_attributes,
array(
'width' => true,
'height' => true,
'depth' => true,
'lspace' => true,
'voffset' => true,
)
),
// https://www.w3.org/TR/mathml-core/#making-sub-expressions-invisible-mphantom
'mphantom' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#script-and-limit-schemata
// https://www.w3.org/TR/mathml-core/#subscripts-and-superscripts-msub-msup-msubsup
'msub' => $math_global_attributes,
'msup' => $math_global_attributes,
'msubsup' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#underscripts-and-overscripts-munder-mover-munderover
'munder' => array_merge( $math_global_attributes, $math_overunder_attributes ),
'mover' => array_merge( $math_global_attributes, $math_overunder_attributes ),
'munderover' => array_merge( $math_global_attributes, $math_overunder_attributes ),
// https://www.w3.org/TR/mathml-core/#prescripts-and-tensor-indices-mmultiscripts
'mmultiscripts' => $math_global_attributes,
'mprescripts' => $math_global_attributes,
// https://www.w3.org/TR/mathml-core/#tabular-math
// https://www.w3.org/TR/mathml-core/#table-or-matrix-mtable
'mtable' => array_merge(
$math_global_attributes,
array(
// Non-standard, used by temml/katex.
// https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtable
'columnalign' => true,
'rowspacing' => true,
'columnspacing' => true,
'align' => true,
'rowalign' => true,
'columnlines' => true,
'rowlines' => true,
'frame' => true,
'framespacing' => true,
'width' => true,
)
),
// https://www.w3.org/TR/mathml-core/#row-in-table-or-matrix-mtr
'mtr' => array_merge(
$math_global_attributes,
array(
// Non-standard, used by temml/katex.
// https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtr
'columnalign' => true,
'rowalign' => true,
)
),
// https://www.w3.org/TR/mathml-core/#entry-in-table-or-matrix-mtd
'mtd' => array_merge(
$math_global_attributes,
array(
'columnspan' => true,
'rowspan' => true,
// Non-standard, used by temml/katex.
// https://developer.mozilla.org/en-US/docs/Web/MathML/Reference/Element/mtd
'columnalign' => true,
'rowalign' => true,
)
),
// https://www.w3.org/TR/mathml-core/#semantics-and-presentation
'semantics' => $math_global_attributes,
'annotation' => array_merge(
$math_global_attributes,
array(
'encoding' => true,
)
),
// Non-standard but widely supported, used by temml/katex.
'menclose' => array_merge(
$math_global_attributes,
array(
'notation' => true,
)
),
)
);
/**
* @var array[] $allowedtags Array of KSES allowed HTML elements.
* @since 1.0.0
*/
$allowedtags = array(
'a' => array(
'href' => true,
'title' => true,
),
'abbr' => array(
'title' => true,
),
'acronym' => array(
'title' => true,
),
'b' => array(),
'blockquote' => array(
'cite' => true,
),
'cite' => array(),
'code' => array(),
'del' => array(
'datetime' => true,
),
'em' => array(),
'i' => array(),
'q' => array(
'cite' => true,
),
's' => array(),
'strike' => array(),
'strong' => array(),
);
/**
* @var string[] $allowedentitynames Array of KSES allowed HTML entity names.
* @since 1.0.0
*/
$allowedentitynames = array(
'nbsp',
'iexcl',
'cent',
'pound',
'curren',
'yen',
'brvbar',
'sect',
'uml',
'copy',
'ordf',
'laquo',
'not',
'shy',
'reg',
'macr',
'deg',
'plusmn',
'acute',
'micro',
'para',
'middot',
'cedil',
'ordm',
'raquo',
'iquest',
'Agrave',
'Aacute',
'Acirc',
'Atilde',
'Auml',
'Aring',
'AElig',
'Ccedil',
'Egrave',
'Eacute',
'Ecirc',
'Euml',
'Igrave',
'Iacute',
'Icirc',
'Iuml',
'ETH',
'Ntilde',
'Ograve',
'Oacute',
'Ocirc',
'Otilde',
'Ouml',
'times',
'Oslash',
'Ugrave',
'Uacute',
'Ucirc',
'Uuml',
'Yacute',
'THORN',
'szlig',
'agrave',
'aacute',
'acirc',
'atilde',
'auml',
'aring',
'aelig',
'ccedil',
'egrave',
'eacute',
'ecirc',
'euml',
'igrave',
'iacute',
'icirc',
'iuml',
'eth',
'ntilde',
'ograve',
'oacute',
'ocirc',
'otilde',
'ouml',
'divide',
'oslash',
'ugrave',
'uacute',
'ucirc',
'uuml',
'yacute',
'thorn',
'yuml',
'quot',
'amp',
'lt',
'gt',
'apos',
'OElig',
'oelig',
'Scaron',
'scaron',
'Yuml',
'circ',
'tilde',
'ensp',
'emsp',
'thinsp',
'zwnj',
'zwj',
'lrm',
'rlm',
'ndash',
'mdash',
'lsquo',
'rsquo',
'sbquo',
'ldquo',
'rdquo',
'bdquo',
'dagger',
'Dagger',
'permil',
'lsaquo',
'rsaquo',
'euro',
'fnof',
'Alpha',
'Beta',
'Gamma',
'Delta',
'Epsilon',
'Zeta',
'Eta',
'Theta',
'Iota',
'Kappa',
'Lambda',
'Mu',
'Nu',
'Xi',
'Omicron',
'Pi',
'Rho',
'Sigma',
'Tau',
'Upsilon',
'Phi',
'Chi',
'Psi',
'Omega',
'alpha',
'beta',
'gamma',
'delta',
'epsilon',
'zeta',
'eta',
'theta',
'iota',
'kappa',
'lambda',
'mu',
'nu',
'xi',
'omicron',
'pi',
'rho',
'sigmaf',
'sigma',
'tau',
'upsilon',
'phi',
'chi',
'psi',
'omega',
'thetasym',
'upsih',
'piv',
'bull',
'hellip',
'prime',
'Prime',
'oline',
'frasl',
'weierp',
'image',
'real',
'trade',
'alefsym',
'larr',
'uarr',
'rarr',
'darr',
'harr',
'crarr',
'lArr',
'uArr',
'rArr',
'dArr',
'hArr',
'forall',
'part',
'exist',
'empty',
'nabla',
'isin',
'notin',
'ni',
'prod',
'sum',
'minus',
'lowast',
'radic',
'prop',
'infin',
'ang',
'and',
'or',
'cap',
'cup',
'int',
'sim',
'cong',
'asymp',
'ne',
'equiv',
'le',
'ge',
'sub',
'sup',
'nsub',
'sube',
'supe',
'oplus',
'otimes',
'perp',
'sdot',
'lceil',
'rceil',
'lfloor',
'rfloor',
'lang',
'rang',
'loz',
'spades',
'clubs',
'hearts',
'diams',
'sup1',
'sup2',
'sup3',
'frac14',
'frac12',
'frac34',
'there4',
);
/**
* @var string[] $allowedxmlentitynames Array of KSES allowed XML entity names.
* @since 5.5.0
*/
$allowedxmlentitynames = array(
'amp',
'lt',
'gt',
'apos',
'quot',
);
$allowedposttags = array_map( '_wp_add_global_attributes', $allowedposttags );
} else {
$required_kses_globals = array(
'allowedposttags',
'allowedtags',
'allowedentitynames',
'allowedxmlentitynames',
);
$missing_kses_globals = array();
foreach ( $required_kses_globals as $global_name ) {
if ( ! isset( $GLOBALS[ $global_name ] ) || ! is_array( $GLOBALS[ $global_name ] ) ) {
$missing_kses_globals[] = '<code>$' . $global_name . '</code>';
}
}
if ( $missing_kses_globals ) {
_doing_it_wrong(
'wp_kses_allowed_html',
sprintf(
/* translators: 1: CUSTOM_TAGS, 2: Global variable names. */
__( 'When using the %1$s constant, make sure to set these globals to an array: %2$s.' ),
'<code>CUSTOM_TAGS</code>',
implode( ', ', $missing_kses_globals )
),
'6.2.0'
);
}
$allowedtags = wp_kses_array_lc( $allowedtags );
$allowedposttags = wp_kses_array_lc( $allowedposttags );
}
/**
* Filters text content and strips out disallowed HTML.
*
* This function makes sure that only the allowed HTML element names, attribute
* names, attribute values, and HTML entities will occur in the given text string.
*
* This function expects unslashed data.
*
* @see wp_kses_post() for specifically filtering post content and fields.
* @see wp_allowed_protocols() for the default allowed protocols in link URLs.
*
* @see 'wp_kses_force_legacy_parser' to opt-out of the new HTML-API-based implementation.
*
* @since 1.0.0
* @since 7.2.0 Rewritten with the HTML API for more reliable parsing.
*
* @global string $wp_kses_operating_mode
*
* @param string $content Text content to filter.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. {@see wp_kses_allowed_html()}
* for the list of accepted context names.
* @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
* Defaults to the result of wp_allowed_protocols().
* @return string Filtered content containing only the allowed HTML.
*/
function wp_kses( $content, $allowed_html, $allowed_protocols = array() ) {
global $wp_kses_operating_mode;
/**
* Filters whether to rely on the legacy parsing inside `wp_kses()`.
*
* @since 7.2.0
*
* @param bool $force_legacy_parser Whether to force using the legacy parser
* instead of relying on the HTML API.
*/
if ( ! apply_filters( 'wp_kses_force_legacy_parser', true ) ) {
return wp_sanitize_html_kses( (string) $content, $allowed_html, $allowed_protocols );
}
if ( empty( $allowed_protocols ) ) {
$allowed_protocols = wp_allowed_protocols();
}
$content = wp_kses_no_null( $content, array( 'slash_zero' => 'keep' ) );
$content = wp_kses_normalize_entities( $content );
// Ensure that the legacy pre-kses filters run by setting the operating mode appropriately.
try {
$previous_kses_mode = $wp_kses_operating_mode;
$wp_kses_operating_mode = 'legacy';
$content = wp_kses_hook( $content, $allowed_html, $allowed_protocols );
} finally {
$wp_kses_operating_mode = $previous_kses_mode;
}
return wp_kses_split( $content, $allowed_html, $allowed_protocols );
}
/**
* Filters HTML content, sanitizing according to given policies.
*
* Modern implementation of {@see wp_kses()} built with the HTML API.
*
* @since 7.2.0
*
* @global string $wp_kses_operating_mode
*
* @access private This function should not be called directly, as it serves a transitionary
* role while replacing the implementation of {@see \wp_kses()}.
*
* @param string $content Text content to filter.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Optional. Array of allowed URL protocols.
* Defaults to the result of wp_allowed_protocols().
* @return string Filtered content containing only the allowed HTML.
*/
function wp_sanitize_html_kses( $content, $allowed_html, $allowed_protocols = array() ) {
global $wp_kses_operating_mode;
$specified_allowed_html = $allowed_html;
$allowed_protocols = empty( $allowed_protocols )
? wp_allowed_protocols()
: $allowed_protocols;
// Preserve legacy behavior of stripping unwanted C0 control characters.
$content = preg_replace( '/[\x01-\x08\x0B\x0C\x0E-\x1F]/', '', $content );
/*
* Call legacy pre-kses filters that might have been added by plugins.
*
* Also set the operating mode to bypass the pre-filters from the legacy
* implementation of `wp_kses()`, as these filters are now run in-band
* during the processing of the input document.
*/
try {
$previous_kses_mode = $wp_kses_operating_mode;
$wp_kses_operating_mode = 'html-api';
$content = wp_kses_hook( $content, $specified_allowed_html, $allowed_protocols );
} finally {
$wp_kses_operating_mode = $previous_kses_mode;
}
$allowed_html = is_array( $allowed_html )
? $allowed_html
: wp_kses_allowed_html( $allowed_html );
/*
* The explanation for this call is that “the quoting from `preg_replace(//e)`
* requires” it, but this version of `wp_kses()` doesn’t rely on PCRE functions
* to parse HTML. Given that this corrupts text, it will be skipped.
*/
//$content = wp_kses_stripslashes( $content );
$processor = new class( $content, $specified_allowed_html, $allowed_html, $allowed_protocols, wp_kses_uri_attributes() ) extends WP_HTML_Tag_Processor {
/**
* An array of allowed HTML elements and attributes, or a context name such as 'post'.
*
* It’s important to store this alongside the resolved allowable HTML because some
* filters in some plugins look for the string values, e.g. for “post” instead of
* the resolved array, and apply logic based on that context.
*
* @see wp_kses_allowed_html() for the list of accepted context names.
* @see self::$allowed_html for the resolved array of allowable HTML elements and attributes.
*
* @since 7.2.0
*
* @var array[]|string
*/
private $specified_allowed_html;
/**
* An array of allowed HTML elements and attributes.
*
* This array of allowable HTML elements and attributes is resolved from the value provided
* to the sanitizer function. It’s resolved at the start to avoid repeatedly calling the
* filter stack and array-merging computations. However, it’s still necessary to carry along
* the provided context so that filters expecting the array-or-string version continue to
* operate properly.
*
* @see self::$specified_allowed_html
*
* @since 7.2.0
*
* @var array[]
*/
private $allowed_html;
/**
* Array of allowed URL protocols.
*
* @see \wp_allowed_protocols()
*
* @since 7.2.0
*
* @var string[]
*/
private $allowed_protocols;
/**
* List of attributes whose values are expected to be considered URLs.
*
* @see \wp_kses_uri_attributes()
*
* @since 7.2.0
*
* @var string[]
*/
private $uri_attributes;
/**
* Tracks balanced tags when inside foreign content.
*
* @since 7.2.0
*
* @var string[]
*/
private $foreign_content_stack = array();
/**
* Tracks how deeply into a MathML ANNOTATION-XML element the current token is;
* an optimization to avoid checking up the open-element stack on every token.
*
* @since 7.2.0
*
* @var int
*/
private $math_annotation_xml_depth = 0;
/**
* Constructor function, used internally.
*
* @since 7.2.0
* @access private
*
* @param string $html Content to filter.
* @param array[]|string $specified_allowed_html Context passed into sanitizer.
* @param array[] $allowed_html Resolved allowable HTML.
* @param string[] $allowed_protocols Resolved allowable protocols.
* @param string[] $uri_attributes Resolved URI attributes.
*/
public function __construct( $html, $specified_allowed_html, $allowed_html, $allowed_protocols, $uri_attributes ) {
parent::__construct( $html );
$this->specified_allowed_html = $specified_allowed_html;
$this->allowed_html = $allowed_html;
$this->allowed_protocols = $allowed_protocols;
$this->uri_attributes = $uri_attributes;
}
/**
* Returns the raw byte-span of the currently-matched token,
* assuming that the parser is matched on a token.
*
* @since 7.2.0
* @access private
*
* @return WP_HTML_Span|null
*/
private function get_span() {
$this->set_bookmark( 'here' );
if ( ! isset( $this->bookmarks['here'] ) ) {
return null;
}
return $this->bookmarks['here'];
}
/**
* Sets the value of a given HTML attribute, adjusting URL attributes
* to ensure compatibility with legacy {@see wp_kses()} behavior.
*
* @since 7.2.0
* @access private
*
* @param string $name Name of HTML attribute to set.
* @param string|true $value Value to set; `true` for boolean attribute.
* @return bool Whether the attribute was set.
*/
public function set_attribute( $name, $value ): bool {
$lower_name = strtolower( $name );
$is_url_ish = in_array( $lower_name, $this->uri_attributes, true );
if ( ! $is_url_ish || ! is_string( $value ) ) {
return parent::set_attribute( $name, $value );
}
$escaped = strtr(
$value,
array(
'<' => '<',
'>' => '>',
'&' => '&',
'"' => '"',
"'" => ''',
)
);
// Set a benign placeholder to replace below.
if ( ! parent::set_attribute( $name, true ) ) {
return false;
}
$this->lexical_updates[ $lower_name ]->text = " {$lower_name}=\"{$escaped}\"";
return true;
}
/**
* Indicates if the currently-matched token, given the parsed context, would require more
* complicated parsing rules to proceed without risking escape from foreign content.
*
* @since 7.2.0
* @access private
*
* @param bool $is_inside_mathml_text_integration_point Whether the token is inside a MathML text integration point.
* @param bool $is_inside_svg_html_integration_point Whether the token is inside an SVG HTML integration point.
* @return bool Whether the current token risks escaping foreign content.
*/
private function could_escape_foreign_content( bool $is_inside_mathml_text_integration_point, bool $is_inside_svg_html_integration_point ): bool {
$token_name = $this->get_token_name();
$is_closer = $this->is_tag_closer();
$namespace = $this->get_namespace();
$self_closing = ! $is_closer && $this->has_self_closing_flag();
if ( ! $is_closer && $is_inside_svg_html_integration_point ) {
return true;
}
/*
* These two elements are excepted in HTML from the normal processing
* rules because they function in similar ways to character data.
*
* > The mglyph element is used to represent non-standard characters or
* > symbols by images; the malignmark element establishes an alignment
* > point for use within table constructs, and is otherwise invisible.
*
* They must contain no elements, so only allow self-closing tags.
*/
if ( ! $is_closer && $is_inside_mathml_text_integration_point ) {
return ! ( $self_closing && ( 'MGLYPH' === $token_name || 'MALIGNMARK' === $token_name ) );
}
if (
! $is_closer &&
'FONT' === $token_name &&
(
null !== $this->get_attribute( 'color' ) ||
null !== $this->get_attribute( 'face' ) ||
null !== $this->get_attribute( 'size' )
)
) {
return true;
}
if (
! $is_closer &&
in_array(
$token_name,
array(
'B',
'BIG',
'BLOCKQUOTE',
'BODY',
'BR',
'CENTER',
'CODE',
'DD',
'DIV',
'DL',
'DT',
'EM',
'EMBED',
'H1',
'H2',
'H3',
'H4',
'H5',
'H6',
'HEAD',
'HR',
'I',
'IMG',
'LI',
'LISTING',
'MENU',
'META',
'NOBR',
'OL',
'P',
'PRE',
'RUBY',
'S',
'SMALL',
'SPAN',
'STRONG',
'STRIKE',
'SUB',
'SUP',
'TABLE',
'TT',
'U',
'UL',
'VAR',
),
true
) ||
(
$is_closer &&
in_array(
$token_name,
array(
'BR',
'P',
),
true
)
)
) {
return true;
}
if ( 'math' === $namespace && ! $is_closer && ! $self_closing ) {
$encoding = $this->get_attribute( 'encoding' );
if (
'ANNOTATION-XML' === $token_name &&
is_string( $encoding ) &&
(
0 === strcasecmp( $encoding, 'text/html' ) ||
0 === strcasecmp( $encoding, 'application/xhtml+xml' )
)
) {
return true;
}
/*
* When SVG becomes a direct descendant of a MathML ANNOTATION-XML,
* the namespace remains `math` but there could be an SVG element
* with an HTML integration point. Conservatively reject any child
* SVG element inside a MathML ANNOTATION-XML to prevent this.
*/
if ( 'SVG' === $token_name && $this->math_annotation_xml_depth > 0 ) {
return true;
}
}
return false;
}
/**
* Indicates if a given string contains text that would parse as a block delimiter.
*
* @since 7.2.0
* @access private
*
* @param string $text Text to check for a block comment delimiter.
* @return bool Whether a block comment delimiter of any kind was found in the given string.
*/
private static function contains_a_block_delimiter( string $text ): bool {
if ( '' === $text ) {
return false;
}
$processor = new WP_Block_Processor( $text );
return $processor->next_delimiter();
}
/**
* Returns a sanitized copy of the input HTML.
*
* @since 7.2.0
* @access private
*
* @return string Sanitized copy of given input HTML.
*/
public function sanitize() {
$template_depth = 0;
$output = '';
$special_newline_at = PHP_INT_MIN;
$foreign_content_starts_at = PHP_INT_MAX;
$open_blocks = array();
$open_blocks_at = array();
$foreign_closed_blocks = array();
$is_in_mathml_text_integration_point = false;
$is_in_svg_html_integration_point = false;
/**
* These are treated as void elements inside the HTML API
* due to the special handling of their inner text content.
*/
$special_atomic_elements = array(
'IFRAME',
'NOEMBED',
'NOFRAMES',
'SCRIPT',
'STYLE',
'TEXTAREA',
'TITLE',
'XMP',
);
while ( $this->next_token() ) {
$token_name = $this->get_token_name();
$token_type = $this->get_token_type();
$namespace = $this->get_namespace();
$is_closer = $this->is_tag_closer();
$here = $this->get_span();
/*
* Prevent allowing NOSCRIPT elements whose parsing rules change
* based on whether the scripting flag is enabled in a browser.
* Rely on trusted inputs for producing the appropriate NOSCRIPT
* content, and prevent untrusted inputs from generating it.
*/
if ( 'NOSCRIPT' === $token_name && ! $is_closer ) {
break;
}
/*
* PLAINTEXT is unique in that it changes the tokenization. Everything in
* a document following the PLAINTEXT opening tag is interpreted as character
* data, meaning there are no more tags, comments, or anything. Because of
* this, it is the only element without a closing tag.
*
* Because of its unique role, it’s risky to leave in place because very few
* parsers are going to recognize the tag and properly switch modes for the
* rest of the document. Instead, the PLAINTEXT tag is removed and its content
* is re-written as an escaped text node.
*
* This changes the structure of the document, because no PLAINTEXT element
* will appear, and it won’t be possible to style its contents, but the element
* is discouraged anyway and should not be allowed from untrusted inputs.
*/
if ( 'PLAINTEXT' === $token_name && 'html' === $namespace && ! $is_closer ) {
if ( $template_depth > 0 && ! isset( $this->allowed_html['template'] ) ) {
break;
}
$text = substr( $this->html, $here->start + $here->length );
$needs_special_newline = (
strlen( $output ) === $special_newline_at &&
1 === strspn( $text, "\n\r", 0, 1 )
);
if ( $needs_special_newline ) {
$output .= "\n";
}
$output .= strtr(
$text,
array(
"\x00" => "\u{FFFD}",
"\r\n" => "\n",
"\r" => "\n",
'<' => '<',
'&' => '&',
'>' => '>',
)
);
break;
}
$is_in_text_integration_point = (
$is_in_mathml_text_integration_point ||
( ! $is_closer && $is_in_svg_html_integration_point )
);
/*
* While content inside integration points is generally not allowed here,
* character data inside the MathML text elements _is_ allowed. This is
* because the rules only change slightly: NULL bytes are removed instead
* of being replaced with the Unicode replacement character U+FFFD; and
* active formats are reconstructed. The format reconstruction doesn’t
* occur here but a browser will still do so; this sanitizer is generally
* unaware of nesting structure.
*/
if ( $is_in_text_integration_point && '#text' === $token_type ) {
$this->change_parsing_namespace( 'html' );
$text = $this->get_modifiable_text();
$this->change_parsing_namespace( $namespace );
} else {
$text = $this->get_modifiable_text();
}
/*
* Enter the foreign content and change the parsing namespace
* so that the parser recognizes real self-closing elements.
*/
$is_svg_or_math = 'MATH' === $token_name || 'SVG' === $token_name;
$has_self_closing_flag = ! $is_closer && $this->has_self_closing_flag();
if ( $is_svg_or_math && ! $is_closer && 'html' === $namespace ) {
$this->change_parsing_namespace( strtolower( $token_name ) );
$namespace = $this->get_namespace();
}
if ( 'html' !== $namespace && '#tag' === $token_type ) {
/*
* Ensure that only well-formed foreign content is allowed.
* Since un-balanced closing tags might implicitly close the
* open foreign-content element, these must be rejected.
*/
if ( $is_closer ) {
$open_element = array_pop( $this->foreign_content_stack );
if ( null === $open_element || $token_name !== $open_element ) {
break;
}
if ( 'math' === $namespace && 'ANNOTATION-XML' === $open_element ) {
--$this->math_annotation_xml_depth;
}
/*
* Reset the foreign content tracker so it doesn’t truncate
* unintentionally after foreign content has properly closed.
*/
if ( empty( $this->foreign_content_stack ) ) {
$foreign_content_starts_at = PHP_INT_MAX;
}
} else {
/*
* Track the opening of the last transition into foreign
* content so that it can be discarded when encountering
* tags that would require more substantial parsing.
*/
if ( empty( $this->foreign_content_stack ) ) {
$foreign_content_starts_at = strlen( $output );
}
$this->foreign_content_stack[] = $token_name;
if ( 'math' === $namespace && 'ANNOTATION-XML' === $token_name ) {
++$this->math_annotation_xml_depth;
}
}
}
if ( 'TEMPLATE' === $token_name && 'html' === $namespace && ! $is_closer ) {
++$template_depth;
}
$skip_token = (
(
$template_depth > 0 &&
! isset( $this->allowed_html['template'] )
) ||
(
! empty( $this->foreign_content_stack ) &&
! isset( $this->allowed_html[ strtolower( $this->foreign_content_stack[0] ) ] )
)
);
switch ( $token_type ) {
case '#text':
if ( $skip_token ) {
break;
}
$needs_special_newline = (
strlen( $output ) === $special_newline_at &&
1 === strspn( $text, "\n\r", 0, 1 )
);
$text = strtr(
$text,
array(
"\r" => '
',
'<' => '<',
'&' => '&',
'>' => '>',
)
);
if ( $needs_special_newline ) {
$output .= "\n{$text}";
} else {
$output .= $text;
}
break;
/*
* Untrusted sources should not be creating these kinds of tokens,
* so remove them entirely from the output.
*/
case '#doctype':
case '#presumptuous-tag':
case '#processing-instruction':
break;
/*
* It’s questionable whether these should be allowed through, but
* the legacy behavior supports it. Therefore, allow them as long
* as they don’t contain potentially confusing syntax characters.
*/
case '#funky-comment':
if ( ! $skip_token && ! str_contains( $text, '<' ) ) {
$output .= substr( $this->html, $here->start, $here->length );
}
break;
/*
* `wp_kses()` runs iteratively on the content inside of these tokens,
* but the content is benign in a browser.
*/
case '#comment':
if ( $skip_token ) {
break;
}
/*
* There are several kinds of malformed HTML which are handled by interpreting
* them as HTML comments. For example, `<?>` is called a “bogus comment” by the
* HTML specification, but when loaded by a browser is equivalent to `<!--?-->`.
* In this way, interacting with the DOM via JavaScript differs from handling
* the textual representation of a page in PHP.
*
* Ignore these non-normative comment forms to protect downstream parsers which
* might not be expecting their kinds of syntax. This prevents mis-parses for
* code which over-simplifies HTML parsing.
*/
if ( WP_HTML_Tag_Processor::COMMENT_AS_HTML_COMMENT !== $this->get_comment_type() ) {
break;
}
// Apply special filtering for block comment delimiters with JSON attributes.
$comment = substr( $this->html, $here->start, $here->length );
/*
* A comment like `<!-- notes --!>` still appears as a normative HTML comment,
* but as an incorrectly-closed comment. Ignore these as well, as part of only
* allowing normative comment contents.
*/
$was_incorrectly_closed = '!' === $comment[ strlen( $comment ) - 2 ];
if ( $was_incorrectly_closed ) {
break;
}
$block_processor = new WP_Block_Processor( $comment );
if ( $block_processor->next_token() && ! $block_processor->is_html() ) {
$block_type = $block_processor->get_block_type();
$implicit_block_type = str_starts_with( $block_type, 'core/' )
? substr( $block_type, /* 'core/' */ 5 )
: $block_type;
switch ( $block_processor->get_delimiter_type() ) {
// Track when blocks open and when they don’t self-close.
case WP_Block_Processor::OPENER:
$open_blocks[] = $implicit_block_type;
$open_blocks_at[] = strlen( $output );
break;
// Track when blocks close.
case WP_Block_Processor::CLOSER:
if ( empty( $open_blocks ) ) {
break 2;
}
/*
* The default parser closes any open block, even when
* the names don’t match. Preserve this behavior here
* to avoid differences in sanitization and parsing.
*/
$closed_block = array_pop( $open_blocks );
$closed_block_at = array_pop( $open_blocks_at );
if ( 'html' !== $namespace && $closed_block_at < $foreign_content_starts_at ) {
$foreign_closed_blocks[] = $closed_block;
}
}
// Filter block attributes for opening delimiters.
$attributes = $block_processor->allocate_and_return_parsed_attributes();
$voider = WP_Block_Processor::VOID === $block_processor->get_delimiter_type() ? '/' : '';
if ( $block_processor->opens_block() ) {
if ( isset( $attributes ) ) {
$attributes = filter_block_kses_value(
$attributes,
$this->specified_allowed_html,
$this->allowed_protocols,
array( 'blockName' => $block_type )
);
}
}
// Fully normalize all block delimiters: name, whitespace, attributes, flags.
if ( WP_Block_Processor::CLOSER === $block_processor->get_delimiter_type() ) {
$text = " /wp:{$implicit_block_type} ";
} elseif ( ! empty( $attributes ) ) {
$serialized_attributes = serialize_block_attributes( $attributes );
$text = " wp:{$implicit_block_type} {$serialized_attributes} {$voider}";
} else {
$text = " wp:{$implicit_block_type} {$voider}";
}
}
/*
* Legacy `wp_kses()` recursively calls itself on the contents of comments.
* Since comment content is not escaped, this changes the meaning of those
* comments when parsed. Still, code often expects to find tag-like syntax
* only when they are real tags. This legacy defect is preserved to avoid
* presenting content that downstream parsers might misinterpret as markup.
*/
$text = strtr( $text, array( '<' => '<' ) );
$output .= "<!--{$text}-->";
break;
/*
* True CDATA sections only exist within embedded SVG and MathML content,
* where they represent text data without any escaping. However, because
* parsers tend to vary on how to parse these, for untrusted inputs,
* rewrite all CDATA sections as normal escaped text.
*/
case '#cdata-section':
if ( ! $skip_token ) {
$output .= strtr(
$text,
array(
"\x00" => "\u{FFFD}",
'<' => '<',
'&' => '&',
'>' => '>',
)
);
}
break;
case '#tag':
/*
* Any failures inside foreign content should return the part of
* the post processed up until the entrance of the foreign content.
* This is necessary because it’s only inside foreign content that
* the self-closing flag indicates a self-closing element.
*
* While the HTML Processor can enter into SVG and MATH and track
* when they close, it’s substantially more complicated and requires
* considerable accounting. To avoid all of that, and to accept the
* kind of content that is nominal and safe, track only when the
* next tag _could_ lead to implicit changing of the parsing namespace
* or insertion mode.
*/
if (
'html' !== $namespace &&
$this->could_escape_foreign_content(
$is_in_mathml_text_integration_point,
$is_in_svg_html_integration_point
)
) {
break 2;
}
if ( $skip_token ) {
break;
}
$tag_name = strtolower( $token_name );
// Skip unallowed elements by tag name
if ( ! isset( $this->allowed_html[ $tag_name ] ) ) {
break;
}
if ( $is_closer ) {
$output .= "</{$tag_name}>";
break;
}
$is_special_atomic_element = (
'html' === $namespace &&
in_array( $token_name, $special_atomic_elements, true )
);
$expects_closer = ! (
'html' === $namespace
? ( WP_HTML_Processor::is_void( $token_name ) || $is_special_atomic_element )
: $has_self_closing_flag
);
$self_closer = ( 'html' !== $namespace && $has_self_closing_flag ) ? ' /' : '';
$closing_tag = $is_special_atomic_element ? "</{$tag_name}>" : '';
$attribute_names = $this->get_attribute_names_with_prefix( '' );
$element_attributes = $this->allowed_html[ $tag_name ];
// Check for required attributes.
$required_attributes = array();
if ( is_array( $element_attributes ) ) {
foreach ( $element_attributes as $name => $spec ) {
if ( true === ( $spec['required'] ?? false ) ) {
$required_attributes[ $name ] = true;
}
}
}
/*
* Allow `data-*` attributes.
*
* When specifying `$allowed_html`, the attribute name should be set as
* `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
* https://www.w3.org/TR/html40/struct/objects.html#adef-data).
*
* Note: the attribute name should only contain `A-Za-z0-9_-` chars.
*/
if ( ! empty( $element_attributes['data-*'] ) ) {
if ( is_array( $attribute_names ) ) {
foreach ( $attribute_names as $name ) {
if (
1 === preg_match( '/^data-[a-z0-9_-]+$/', $name ) &&
(
! isset( $element_attributes[ $name ] ) ||
'' === $element_attributes[ $name ]
)
) {
$element_attributes[ $name ] = $element_attributes['data-*'];
}
}
}
unset( $element_attributes['data-*'] );
}
$tag_maker = new self(
"<{$tag_name}{$self_closer}>{$closing_tag}",
$this->specified_allowed_html,
$this->allowed_html,
$this->allowed_protocols,
$this->uri_attributes
);
$tag_maker->change_parsing_namespace( $namespace );
$tag_maker->next_token();
if ( is_array( $attribute_names ) ) {
foreach ( $attribute_names as $name ) {
$spec = $element_attributes[ $name ] ?? null;
// This attribute is not specified, thus not allowed. Skip it.
if ( null === $spec || '' === $spec ) {
continue;
}
/*
* An Interactivity API binding replaces an attribute value when the content
* is rendered, after KSES has checked it. Where KSES restricts attribute values
* on an element, only bindings of attributes it allows there with any value
* are kept.
*/
if (
str_starts_with( $name, 'data-wp-bind--' ) &&
_wp_kses_directive_binds_value_restricted_attribute( $name, $this->allowed_html[ $tag_name ] )
) {
continue;
}
$raw_value = $this->get_attribute( $name );
$value = is_string( $raw_value ) ? $raw_value : '';
// Process the style attribute through CSS sanitization.
if ( 'style' === $name ) {
if ( ! is_string( $raw_value ) ) {
continue;
}
$value = safecss_filter_attr( $value );
if ( '' === trim( $value ) ) {
continue;
}
}
$is_url_ish = in_array( strtolower( $name ), $this->uri_attributes, true );
if ( $is_url_ish ) {
$value = wp_kses_bad_protocol( $value, $this->allowed_protocols );
}
/*
* Process the remaining attributes according to their policies.
*
* Non-array values for the attribute specification are assumed
* to be `true`, thus permitting the attribute.
*/
if ( is_array( $spec ) ) {
foreach ( $spec as $property => $constraint ) {
$vless = true === $raw_value ? 'y' : 'n';
if ( ! wp_kses_check_attr_val( $value, $vless, $property, $constraint ) ) {
continue 2;
}
}
}
$did_set = ( true === $raw_value && '' === $value )
? $tag_maker->set_attribute( $name, true )
: $tag_maker->set_attribute( $name, $value );
if ( $did_set ) {
unset( $required_attributes[ $name ] );
}
}
}
$needs_special_newline = 'html' === $namespace && ( 'PRE' === $token_name || 'LISTING' === $token_name );
if ( ! empty( $required_attributes ) ) {
if ( ! $expects_closer ) {
break;
}
/*
* Since this processor cannot track nesting of HTML elements
* generally, leave opening tags when required attributes are
* missing, but strip them of their attributes.
*/
$output .= "<{$tag_name}>";
if ( $needs_special_newline ) {
$special_newline_at = strlen( $output );
}
break;
}
if ( $is_special_atomic_element ) {
if ( 'TITLE' === $token_name || 'TEXTAREA' === $token_name ) {
/*
* RCDATA nodes can be safely escaped, but this must be
* done after enqueuing the update to avoid double-escaping.
*/
$tag_maker->set_modifiable_text( $text );
$tag_maker->lexical_updates['modifiable text']->text = strtr(
$tag_maker->lexical_updates['modifiable text']->text,
array(
"\x00" => "\u{FFFD}",
"\r" => '
',
)
);
} elseif ( ! self::contains_a_block_delimiter( $text ) ) {
// Other nodes not containing a block delimiter are safe.
$tag_maker->set_modifiable_text( $text );
} else {
/*
* But RAWTEXT and SCRIPT cannot be generally escaped, so reject
* updates which would include something that could be misparsed
* as a block comment delimiter.
*/
$tag_maker->set_modifiable_text( '' );
}
}
$output .= $tag_maker->get_updated_html();
if ( $needs_special_newline ) {
$special_newline_at = strlen( $output );
}
break;
}
// Re-enter the HTML namespace.
if ( 'html' !== $namespace ) {
if ( $has_self_closing_flag ) {
array_pop( $this->foreign_content_stack );
if ( 'math' === $namespace && 'ANNOTATION-XML' === $token_name ) {
--$this->math_annotation_xml_depth;
}
}
if ( empty( $this->foreign_content_stack ) ) {
$is_in_mathml_text_integration_point = false;
$is_in_svg_html_integration_point = false;
$this->change_parsing_namespace( 'html' );
$foreign_content_starts_at = PHP_INT_MAX;
$foreign_closed_blocks = array();
} elseif ( '#tag' === $token_type && ! $has_self_closing_flag ) {
switch ( $token_name ) {
case 'MI':
case 'MN':
case 'MO':
case 'MS':
case 'MTEXT':
$is_in_mathml_text_integration_point = ! $is_closer && 'math' === $namespace;
break;
case 'DESC':
case 'FOREIGNOBJECT':
case 'TITLE':
$is_in_svg_html_integration_point = ! $is_closer && 'svg' === $namespace;
break;
}
}
}
if ( 'TEMPLATE' === $token_name && $template_depth > 0 && $is_closer && 'html' === $namespace ) {
--$template_depth;
}
}
/*
* While there might have been an incomplete token in the output stream,
* there is no need to render it to the output. They would disappear on
* their own in a browser if they ended the document, but here they do
* not end the document; instead, they are likely being inserted into an
* existing document, where the incomplete token might mess with the rest
* of the page’s HTML structure.
*/
$sanitized = substr( $output, 0, $foreign_content_starts_at );
// Templates should be contained within blocks, so close them first.
if ( $template_depth > 0 && isset( $this->allowed_html['template'] ) ) {
$sanitized .= str_repeat( '</template>', $template_depth );
}
// Close any remaining-open blocks ensure isolation of block content.
foreach ( $foreign_closed_blocks as $block_name ) {
$sanitized .= "<!-- /wp:{$block_name} -->";
}
for ( $i = count( $open_blocks ) - 1; $i >= 0; $i-- ) {
// Skip blocks that were opened when inside truncated foreign content.
if ( $open_blocks_at[ $i ] >= $foreign_content_starts_at ) {
continue;
}
$block_name = $open_blocks[ $i ];
$sanitized .= "<!-- /wp:{$block_name} -->";
}
return $sanitized;
}
};
return $processor->sanitize();
}
/**
* Filters one HTML attribute and ensures its value is allowed.
*
* This function can escape data in some situations where `wp_kses()` must strip the whole attribute.
*
* @since 4.2.3
*
* @param string $attr The 'whole' attribute, including name and value.
* @param string $element The HTML element name to which the attribute belongs.
* @return string Filtered attribute.
*/
function wp_kses_one_attr( $attr, $element ) {
$uris = wp_kses_uri_attributes();
$allowed_html = wp_kses_allowed_html( 'post' );
$allowed_protocols = wp_allowed_protocols();
$attr = wp_kses_no_null( $attr, array( 'slash_zero' => 'keep' ) );
// Preserve leading and trailing whitespace.
$matches = array();
preg_match( '/^\s*/', $attr, $matches );
$lead = $matches[0];
preg_match( '/\s*$/', $attr, $matches );
$trail = $matches[0];
if ( empty( $trail ) ) {
$attr = substr( $attr, strlen( $lead ) );
} else {
$attr = substr( $attr, strlen( $lead ), -strlen( $trail ) );
}
// Parse attribute name and value from input.
$split = preg_split( '/\s*=\s*/', $attr, 2 );
$name = $split[0];
if ( count( $split ) === 2 ) {
$value = $split[1];
/*
* Remove quotes surrounding $value.
* Also guarantee correct quoting in $attr for this one attribute.
*/
if ( '' === $value ) {
$quote = '';
} else {
$quote = $value[0];
}
if ( '"' === $quote || "'" === $quote ) {
if ( ! str_ends_with( $value, $quote ) ) {
return '';
}
$value = substr( $value, 1, -1 );
} else {
$quote = '"';
}
// Sanitize quotes, angle braces, and entities.
$value = esc_attr( $value );
// Sanitize URI values.
if ( in_array( strtolower( $name ), $uris, true ) ) {
$value = wp_kses_bad_protocol( $value, $allowed_protocols );
}
$attr = "$name=$quote$value$quote";
$vless = 'n';
} else {
$value = '';
$vless = 'y';
}
// Sanitize attribute by name.
wp_kses_attr_check( $name, $value, $attr, $vless, $element, $allowed_html );
// Restore whitespace.
return $lead . $attr . $trail;
}
/**
* Returns an array of allowed HTML tags and attributes for a given context.
*
* @since 3.5.0
* @since 5.0.1 `form` removed as allowable HTML tag.
*
* @global array $allowedposttags
* @global array $allowedtags
* @global array $allowedentitynames
*
* @param string|array $context The context for which to retrieve tags. Allowed values are 'post',
* 'strip', 'data', 'entities', or the name of a field filter such as
* 'pre_user_description', or an array of allowed HTML elements and attributes.
* @return array Array of allowed HTML tags and their allowed attributes.
*/
function wp_kses_allowed_html( $context = '' ) {
global $allowedposttags, $allowedtags, $allowedentitynames;
if ( is_array( $context ) ) {
// When `$context` is an array it's actually an array of allowed HTML elements and attributes.
$html = $context;
$context = 'explicit';
/**
* Filters the HTML tags that are allowed for a given context.
*
* HTML tags and attribute names are case-insensitive in HTML but must be
* added to the KSES allow list in lowercase. An item added to the allow list
* in upper or mixed case will not recognized as permitted by KSES.
*
* @since 3.5.0
*
* @param array[] $html Allowed HTML tags.
* @param string $context Context name.
*/
return apply_filters( 'wp_kses_allowed_html', $html, $context );
}
switch ( $context ) {
case 'post':
/** This filter is documented in wp-includes/kses.php */
$tags = apply_filters( 'wp_kses_allowed_html', $allowedposttags, $context );
// 5.0.1 removed the `<form>` tag, allow it if a filter is allowing it's sub-elements `<input>` or `<select>`.
if ( ! CUSTOM_TAGS && ! isset( $tags['form'] ) && ( isset( $tags['input'] ) || isset( $tags['select'] ) ) ) {
$tags = $allowedposttags;
$tags['form'] = array(
'action' => true,
'accept' => true,
'accept-charset' => true,
'enctype' => true,
'method' => true,
'name' => true,
'target' => true,
);
/** This filter is documented in wp-includes/kses.php */
$tags = apply_filters( 'wp_kses_allowed_html', $tags, $context );
}
return $tags;
case 'user_description':
case 'pre_term_description':
case 'pre_user_description':
$tags = $allowedtags;
$tags['a']['rel'] = true;
$tags['a']['target'] = true;
/** This filter is documented in wp-includes/kses.php */
return apply_filters( 'wp_kses_allowed_html', $tags, $context );
case 'strip':
/** This filter is documented in wp-includes/kses.php */
return apply_filters( 'wp_kses_allowed_html', array(), $context );
case 'entities':
/** This filter is documented in wp-includes/kses.php */
return apply_filters( 'wp_kses_allowed_html', $allowedentitynames, $context );
case 'data':
default:
/** This filter is documented in wp-includes/kses.php */
return apply_filters( 'wp_kses_allowed_html', $allowedtags, $context );
}
}
/**
* Allows the note mention chip markup in comment content.
*
* The notes `@` mention completer stores a mention as a chip carrying the
* mentioned user's ID in a class token:
* `<span class="wp-note-mention user-N">@Name</span>`. The default comment
* allowlist does not allow `span` at all, so for users without
* `unfiltered_html` the mention would be stripped on save.
*
* The allowance is deliberately narrow and always on: `span` is a
* semantics-free element and _wp_kses_sanitize_note_mention_classes()
* reduces its `class` to the two mention tokens right after kses runs, so
* regular (including anonymous) commenters gain nothing beyond the inert
* mention markup itself.
*
* @since 7.1.0
* @access private
*
* @param array<string, array<string, bool>> $allowed The allowed tags structure for the context.
* @param string $context The kses context.
* @return array<string, array<string, bool>> Modified allowed tags structure.
*/
function _wp_kses_allow_note_mention_span( $allowed, $context ): array {
if ( ! is_array( $allowed ) ) {
$allowed = array();
}
if ( 'pre_comment_content' !== $context ) {
return $allowed;
}
if ( ! isset( $allowed['span'] ) || ! is_array( $allowed['span'] ) ) {
$allowed['span'] = array();
}
$allowed['span']['class'] = true;
return $allowed;
}
/**
* Reduces `span` classes in comment content to the note mention tokens.
*
* _wp_kses_allow_note_mention_span() lets `class` through kses on `span` so
* the mention chip survives, but `class` is an open-ended styling and
* scripting hook, so this companion pass - running right after
* `wp_filter_kses` at priority 10 - strips every class token except the two
* the mention markup uses: `wp-note-mention` and `user-N`. `span` is the only
* comment tag allowed to carry `class` at all, so walking `span` tags covers
* the entire allowance.
*
* The pass only applies while the restrictive comment allowlist is active:
* users with `unfiltered_html` are filtered through `wp_filter_post_kses`
* (or not at all), where arbitrary classes are already permitted, and
* narrowing their markup here would restrict what core allows them to post.
*
* @since 7.1.0
* @access private
*
* @param string $content Slashed comment content, already filtered by kses.
* @return string Slashed comment content with span classes reduced.
*/
function _wp_kses_sanitize_note_mention_classes( $content ): string {
if ( ! is_string( $content ) ) {
$content = '';
}
if ( false === has_filter( 'pre_comment_content', 'wp_filter_kses' ) ) {
return $content;
}
$processor = new WP_HTML_Tag_Processor( wp_unslash( $content ) );
while ( $processor->next_tag( 'SPAN' ) ) {
foreach ( $processor->class_list() as $token ) {
if ( 'wp-note-mention' !== $token && ! preg_match( '/^user-[1-9][0-9]*$/', $token ) ) {
// Removing the last class also removes the attribute itself.
$processor->remove_class( $token );
}
}
}
return wp_slash( $processor->get_updated_html() );
}
/**
* You add any KSES hooks here.
*
* There is currently only one KSES WordPress hook, {@see 'pre_kses'}, and it is called here.
* All parameters are passed to the hooks and expected to receive a string.
*
* @since 1.0.0
*
* @param string $content Content to filter through KSES.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Filtered content through {@see 'pre_kses'} hook.
*/
function wp_kses_hook( $content, $allowed_html, $allowed_protocols ) {
/**
* Filters content to be run through KSES.
*
* @since 2.3.0
*
* @param string $content Content to filter through KSES.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Array of allowed URL protocols.
*/
return apply_filters( 'pre_kses', $content, $allowed_html, $allowed_protocols );
}
/**
* Returns the version number of KSES.
*
* @since 1.0.0
*
* @return string KSES version number.
*/
function wp_kses_version() {
return '0.2.2';
}
/**
* Searches for HTML tags, no matter how malformed.
*
* It also matches stray `>` characters.
*
* @since 1.0.0
* @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments.
*
* @global array[]|string $pass_allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'.
* @global string[] $pass_allowed_protocols Array of allowed URL protocols.
*
* @param string $content Content to filter.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Content with fixed HTML tags
*/
function wp_kses_split( $content, $allowed_html, $allowed_protocols ) {
global $pass_allowed_html, $pass_allowed_protocols;
$pass_allowed_html = $allowed_html;
$pass_allowed_protocols = $allowed_protocols;
$token_pattern = <<<REGEX
~
( # Detect comments of various flavors before attempting to find tags.
(<!--.*?(-->|$)) # - Normative HTML comments.
|
</[^a-zA-Z][^>]*> # - Closing tags with invalid tag names.
|
<![^>]*> # - Invalid markup declaration nodes. Not all invalid nodes
# are matched so as to avoid breaking legacy behaviors.
)
|
(<[^>]*(>|$)|>) # Tag-like spans of text.
~x
REGEX;
return preg_replace_callback( $token_pattern, '_wp_kses_split_callback', $content );
}
/**
* Returns an array of HTML attribute names whose value contains a URL.
*
* This function returns a list of all HTML attributes that must contain
* a URL according to the HTML specification.
*
* This list includes URI attributes both allowed and disallowed by KSES.
*
* @link https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes
*
* @since 5.0.1
*
* @return string[] HTML attribute names whose value contains a URL.
*/
function wp_kses_uri_attributes() {
$uri_attributes = array(
'action',
'archive',
'background',
'cite',
'classid',
'codebase',
'data',
'formaction',
'href',
'icon',
'longdesc',
'manifest',
'poster',
'profile',
'src',
'usemap',
'xmlns',
);
/**
* Filters the list of attributes that are required to contain a URL.
*
* Use this filter to add any `data-` attributes that are required to be
* validated as a URL.
*
* @since 5.0.1
*
* @param string[] $uri_attributes HTML attribute names whose value contains a URL.
*/
$uri_attributes = apply_filters( 'wp_kses_uri_attributes', $uri_attributes );
return $uri_attributes;
}
/**
* Callback for `wp_kses_split()`.
*
* @since 3.1.0
* @access private
* @ignore
*
* @global array[]|string $pass_allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'.
* @global string[] $pass_allowed_protocols Array of allowed URL protocols.
*
* @param array $matches preg_replace regexp matches
* @return string
*/
function _wp_kses_split_callback( $matches ) {
global $pass_allowed_html, $pass_allowed_protocols;
return wp_kses_split2( $matches[0], $pass_allowed_html, $pass_allowed_protocols );
}
/**
* Callback for `wp_kses_split()` for fixing malformed HTML tags.
*
* This function does a lot of work. It rejects some very malformed things like
* `<:::>`. It returns an empty string, if the element isn't allowed (look ma, no
* `strip_tags()`!). Otherwise it splits the tag into an element and an attribute
* list.
*
* After the tag is split into an element and an attribute list, it is run
* through another filter which will remove illegal attributes and once that is
* completed, will be returned.
*
* @access private
* @ignore
* @since 1.0.0
* @since 6.6.0 Recognize additional forms of invalid HTML which convert into comments.
*
* @param string $content Content to filter.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Fixed HTML element
*/
function wp_kses_split2( $content, $allowed_html, $allowed_protocols ) {
$content = wp_kses_stripslashes( $content );
/*
* The regex pattern used to split HTML into chunks attempts
* to split on HTML token boundaries. This function should
* thus receive chunks that _either_ start with meaningful
* syntax tokens, like a tag `<div>` or a comment `<!-- ... -->`.
*
* If the first character of the `$content` chunk _isn't_ one
* of these syntax elements, which always starts with `<`, then
* the match had to be for the final alternation of `>`. In such
* case, it's probably standing on its own and could be encoded
* with a character reference to remove ambiguity.
*
* In other words, if this chunk isn't from a match of a syntax
* token, it's just a plaintext greater-than (`>`) sign.
*/
if ( ! str_starts_with( $content, '<' ) ) {
return '>';
}
/*
* When certain invalid syntax constructs appear, the HTML parser
* shifts into what's called the "bogus comment state." This is a
* plaintext state that consumes everything until the nearest `>`
* and then transforms the entire span into an HTML comment.
*
* Preserve these comments and do not treat them like tags.
*
* @link https://html.spec.whatwg.org/#bogus-comment-state
*/
if ( 1 === preg_match( '~^(?:</[^a-zA-Z][^>]*>|<![a-z][^>]*>)$~', $content ) ) {
/**
* Since the pattern matches `</…>` and also `<!…>`, this will
* preserve the type of the cleaned-up token in the output.
*/
$opener = $content[1];
$content = substr( $content, 2, -1 );
do {
$prev = $content;
$content = wp_kses( $content, $allowed_html, $allowed_protocols );
} while ( $prev !== $content );
// Recombine the modified inner content with the original token structure.
return "<{$opener}{$content}>";
}
/*
* Normative HTML comments should be handled separately as their
* parsing rules differ from those for tags and text nodes.
*/
if ( str_starts_with( $content, '<!--' ) ) {
$content = str_replace( array( '<!--', '-->' ), '', $content );
while ( ( $newstring = wp_kses( $content, $allowed_html, $allowed_protocols ) ) !== $content ) {
$content = $newstring;
}
if ( '' === $content ) {
return '';
}
// Prevent multiple dashes in comments.
$content = preg_replace( '/--+/', '-', $content );
// Prevent three dashes closing a comment.
$content = preg_replace( '/-$/', '', $content );
return "<!--{$content}-->";
}
// It's seriously malformed.
if ( ! preg_match( '%^<\s*(/\s*)?([a-zA-Z0-9-]+)([^>]*)>?$%', $content, $matches ) ) {
return '';
}
$slash = trim( $matches[1] );
$elem = $matches[2];
$attrlist = $matches[3];
if ( ! is_array( $allowed_html ) ) {
$allowed_html = wp_kses_allowed_html( $allowed_html );
}
// They are using a not allowed HTML element.
if ( ! isset( $allowed_html[ strtolower( $elem ) ] ) ) {
return '';
}
// No attributes are allowed for closing elements.
if ( '' !== $slash ) {
return "</$elem>";
}
return wp_kses_attr( $elem, $attrlist, $allowed_html, $allowed_protocols );
}
/**
* Removes all attributes, if none are allowed for this element.
*
* If some are allowed it calls `wp_kses_hair()` to split them further, and then
* it builds up new HTML code from the data that `wp_kses_hair()` returns. It also
* removes `<` and `>` characters, if there are any left. One more thing it does
* is to check if the tag has a closing XHTML slash, and if it does, it puts one
* in the returned code as well.
*
* An array of allowed values can be defined for attributes. If the attribute value
* doesn't fall into the list, the attribute will be removed from the tag.
*
* Attributes can be marked as required. If a required attribute is not present,
* KSES will remove all attributes from the tag. As KSES doesn't match opening and
* closing tags, it's not possible to safely remove the tag itself, the safest
* fallback is to strip all attributes from the tag, instead.
*
* @since 1.0.0
* @since 5.9.0 Added support for an array of allowed values for attributes.
* Added support for required attributes.
*
* @param string $element HTML element/tag.
* @param string $attr HTML attributes from HTML element to closing HTML element tag.
* @param array[]|string $allowed_html An array of allowed HTML elements and attributes,
* or a context name such as 'post'. See wp_kses_allowed_html()
* for the list of accepted context names.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Sanitized HTML element.
*/
function wp_kses_attr( $element, $attr, $allowed_html, $allowed_protocols ) {
if ( ! is_array( $allowed_html ) ) {
$allowed_html = wp_kses_allowed_html( $allowed_html );
}
// Is there a closing XHTML slash at the end of the attributes?
$xhtml_slash = '';
if ( preg_match( '%\s*/\s*$%', $attr ) ) {
$xhtml_slash = ' /';
}
// Are any attributes allowed at all for this element?
$element_low = strtolower( $element );
if ( empty( $allowed_html[ $element_low ] ) || true === $allowed_html[ $element_low ] ) {
return "<$element$xhtml_slash>";
}
// Split it.
$attrarr = wp_kses_hair( $attr, $allowed_protocols );
// Check if there are attributes that are required.
$required_attrs = array_filter(
$allowed_html[ $element_low ],
static function ( $required_attr_limits ) {
return isset( $required_attr_limits['required'] ) && true === $required_attr_limits['required'];
}
);
/*
* If a required attribute check fails, we can return nothing for a self-closing tag,
* but for a non-self-closing tag the best option is to return the element with attributes,
* as KSES doesn't handle matching the relevant closing tag.
*/
$stripped_tag = '';
if ( empty( $xhtml_slash ) ) {
$stripped_tag = "<$element>";
}
// Go through $attrarr, and save the allowed attributes for this element in $attr2.
$attr2 = '';
foreach ( $attrarr as $arreach ) {
// Check if this attribute is required.
$required = isset( $required_attrs[ strtolower( $arreach['name'] ) ] );
if ( wp_kses_attr_check( $arreach['name'], $arreach['value'], $arreach['whole'], $arreach['vless'], $element, $allowed_html ) ) {
$attr2 .= ' ' . $arreach['whole'];
// If this was a required attribute, we can mark it as found.
if ( $required ) {
unset( $required_attrs[ strtolower( $arreach['name'] ) ] );
}
} elseif ( $required ) {
// This attribute was required, but didn't pass the check. The entire tag is not allowed.
return $stripped_tag;
}
}
// If some required attributes weren't set, the entire tag is not allowed.
if ( ! empty( $required_attrs ) ) {
return $stripped_tag;
}
// Remove any "<" or ">" characters.
$attr2 = preg_replace( '/[<>]/', '', $attr2 );
return "<$element$attr2$xhtml_slash>";
}
/**
* Determines whether an attribute is allowed.
*
* @since 4.2.3
* @since 5.0.0 Added support for `data-*` wildcard attributes.
*
* @param string $name The attribute name. Passed by reference. Returns empty string when not allowed.
* @param string $value The attribute value. Passed by reference. Returns a filtered value.
* @param string $whole The `name=value` input. Passed by reference. Returns filtered input.
* @param string $vless Whether the attribute is valueless. Use 'y' or 'n'.
* @param string $element The name of the element to which this attribute belongs.
* @param array $allowed_html The full list of allowed elements and attributes.
* @return bool Whether or not the attribute is allowed.
*/
function wp_kses_attr_check( &$name, &$value, &$whole, $vless, $element, $allowed_html ) {
$name_low = strtolower( $name );
$element_low = strtolower( $element );
if ( ! isset( $allowed_html[ $element_low ] ) ) {
$name = '';
$value = '';
$whole = '';
return false;
}
$allowed_attr = $allowed_html[ $element_low ];
if ( ! isset( $allowed_attr[ $name_low ] ) || '' === $allowed_attr[ $name_low ] ) {
/*
* Allow `data-*` attributes.
*
* When specifying `$allowed_html`, the attribute name should be set as
* `data-*` (not to be mixed with the HTML 4.0 `data` attribute, see
* https://www.w3.org/TR/html40/struct/objects.html#adef-data).
*
* Note: the attribute name should only contain `A-Za-z0-9_-` chars.
*/
if ( str_starts_with( $name_low, 'data-' ) && ! empty( $allowed_attr['data-*'] )
&& preg_match( '/^data-[a-z0-9_-]+$/', $name_low, $match )
) {
/*
* Add the whole attribute name to the allowed attributes and set any restrictions
* for the `data-*` attribute values for the current element.
*/
$allowed_attr[ $match[0] ] = $allowed_attr['data-*'];
} else {
$name = '';
$value = '';
$whole = '';
return false;
}
}
/*
* An Interactivity API binding replaces an attribute value when the content is rendered,
* after KSES has checked it. Where KSES restricts attribute values on an element, only
* bindings of attributes it allows there with any value are kept.
*/
if (
str_starts_with( $name_low, 'data-wp-bind--' ) &&
_wp_kses_directive_binds_value_restricted_attribute( $name_low, $allowed_attr )
) {
$name = '';
$value = '';
$whole = '';
return false;
}
if ( 'style' === $name_low ) {
$decoded_value = WP_HTML_Decoder::decode_attribute( $value );
$new_value = safecss_filter_attr( $decoded_value );
if ( empty( $new_value ) ) {
$name = '';
$value = '';
$whole = '';
return false;
}
if ( $new_value !== $decoded_value ) {
$encoded_value = esc_attr( $new_value );
$whole = str_replace( $value, $encoded_value, $whole );
$value = $encoded_value;
}
}
if ( is_array( $allowed_attr[ $name_low ] ) ) {
// There are some checks.
foreach ( $allowed_attr[ $name_low ] as $currkey => $currval ) {
if ( ! wp_kses_check_attr_val( $value, $vless, $currkey, $currval ) ) {
$name = '';
$value = '';
$whole = '';
return false;
}
}
}
return true;
}
/**
* Given a string of HTML attributes and values, parse into a structured attribute list.
*
* This function performs a number of transformations while parsing attribute strings:
* - It normalizes attribute values and surrounds them with double quotes.
* - It normalizes HTML character references inside attribute values.
* - It removes “bad” URL protocols from attribute values.
*
* Otherwise this reads the attributes as if they were part of an HTML tag. It performs
* these transformations to lower the risk of mis-parsing down the line and to perform
* URL sanitization in line with the rest of the `kses` subsystem. Importantly, it does
* not decode the attribute values, meaning that special HTML syntax characters will
* be left with character references in the `value` property.
*
* Example:
*
* $attrs = wp_kses_hair( 'class="is-wide" inert data-lazy=\'<img>\' =/🐮=/' );
* $attrs === array(
* 'class' => array( 'name' => 'class', 'value' => 'is-wide', 'whole' => 'class="is-wide"', 'vless' => 'n' ),
* 'inert' => array( 'name' => 'inert', 'value' => '', 'whole' => 'inert', 'vless' => 'y' ),
* 'data-lazy' => array( 'name' => 'data-lazy', 'value' => '<img>', 'whole' => 'data-lazy="<img>"', 'vless' => 'n' ),
* '=' => array( 'name' => '=', 'value' => '', 'whole' => '=', 'vless' => 'y' ),
* '🐮' => array( 'name' => '🐮', 'value' => '/', 'whole' => '🐮="/"', 'vless' => 'n' ),
* );
*
* @since 1.0.0
* @since 7.0.0 Reliably parses HTML via the HTML API.
*
* @param string $attr Attribute list from HTML element to closing HTML element tag.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return array<string, array{name: string, value: string, whole: string, vless: 'y'|'n'}> Array of attribute information after parsing.
*/
function wp_kses_hair( $attr, $allowed_protocols ) {
$attributes = array();
$uris = wp_kses_uri_attributes();
$processor = new WP_HTML_Tag_Processor( "<wp {$attr}>" );
$processor->next_token();
$attribute_names = $processor->get_attribute_names_with_prefix( '' );
if ( null === $attribute_names || 0 === count( $attribute_names ) ) {
return $attributes;
}
$syntax_characters = array(
'&' => '&',
'<' => '<',
'>' => '>',
"'" => ''',
'"' => '"',
);
foreach ( $attribute_names as $name ) {
$value = $processor->get_attribute( $name );
$is_bool = true === $value;
if ( is_string( $value ) && in_array( $name, $uris, true ) ) {
$value = wp_kses_bad_protocol( $value, $allowed_protocols );
}
// Reconstruct and normalize the attribute value.
$recoded = $is_bool ? '' : strtr( $value, $syntax_characters );
$whole = $is_bool ? $name : "{$name}=\"{$recoded}\"";
$attributes[ $name ] = array(
'name' => $name,
'value' => $recoded,
'whole' => $whole,
'vless' => $is_bool ? 'y' : 'n',
);
}
return $attributes;
}
/**
* Finds all attributes of an HTML element.
*
* Does not modify input. May return "evil" output.
*
* Based on `wp_kses_split2()` and `wp_kses_attr()`.
*
* @since 4.2.3
*
* @param string $element HTML element.
* @return array|false List of attributes found in the element. Returns false on failure.
*/
function wp_kses_attr_parse( $element ) {
$valid = preg_match( '%^(<\s*)(/\s*)?([a-zA-Z0-9]+\s*)([^>]*)(>?)$%', $element, $matches );
if ( 1 !== $valid ) {
return false;
}
$begin = $matches[1];
$slash = $matches[2];
$elname = $matches[3];
$attr = $matches[4];
$end = $matches[5];
if ( '' !== $slash ) {
// Closing elements do not get parsed.
return false;
}
// Is there a closing XHTML slash at the end of the attributes?
if ( 1 === preg_match( '%\s*/\s*$%', $attr, $matches ) ) {
$xhtml_slash = $matches[0];
$attr = substr( $attr, 0, -strlen( $xhtml_slash ) );
} else {
$xhtml_slash = '';
}
// Split it.
$attrarr = wp_kses_hair_parse( $attr );
if ( false === $attrarr ) {
return false;
}
// Make sure all input is returned by adding front and back matter.
array_unshift( $attrarr, $begin . $slash . $elname );
array_push( $attrarr, $xhtml_slash . $end );
return $attrarr;
}
/**
* Builds an attribute list from string containing attributes.
*
* Does not modify input. May return "evil" output.
* In case of unexpected input, returns false instead of stripping things.
*
* Based on `wp_kses_hair()` but does not return a multi-dimensional array.
*
* @since 4.2.3
*
* @param string $attr Attribute list from HTML element to closing HTML element tag.
* @return array|false List of attributes found in $attr. Returns false on failure.
*/
function wp_kses_hair_parse( $attr ) {
if ( '' === $attr ) {
return array();
}
$regex =
'(?:
[_a-zA-Z][-_a-zA-Z0-9:.]* # Attribute name.
|
\[\[?[^\[\]]+\]\]? # Shortcode in the name position implies unfiltered_html.
)
(?: # Attribute value.
\s*=\s* # All values begin with "=".
(?:
"[^"]*" # Double-quoted.
|
\'[^\']*\' # Single-quoted.
|
[^\s"\']+ # Non-quoted.
(?:\s|$) # Must have a space.
)
|
(?:\s|$) # If attribute has no value, space is required.
)
\s* # Trailing space is optional except as mentioned above.
';
/*
* Although it is possible to reduce this procedure to a single regexp,
* we must run that regexp twice to get exactly the expected result.
*
* Note: do NOT remove the `x` modifiers as they are essential for the above regex!
*/
$validation = "/^($regex)+$/x";
$extraction = "/$regex/x";
if ( 1 === preg_match( $validation, $attr ) ) {
preg_match_all( $extraction, $attr, $attrarr );
return $attrarr[0];
} else {
return false;
}
}
/**
* Performs different checks for attribute values.
*
* The currently implemented checks are "maxlen", "minlen", "maxval", "minval",
* and "valueless".
*
* @since 1.0.0
*
* @param string $value Attribute value.
* @param string $vless Whether the attribute is valueless. Use 'y' or 'n'.
* @param string $checkname What $checkvalue is checking for.
* @param mixed $checkvalue What constraint the value should pass.
* @return bool Whether check passes.
*/
function wp_kses_check_attr_val( $value, $vless, $checkname, $checkvalue ) {
$ok = true;
switch ( strtolower( $checkname ) ) {
case 'maxlen':
/*
* The maxlen check makes sure that the attribute value has a length not
* greater than the given value. This can be used to avoid Buffer Overflows
* in WWW clients and various Internet servers.
*/
if ( strlen( $value ) > $checkvalue ) {
$ok = false;
}
break;
case 'minlen':
/*
* The minlen check makes sure that the attribute value has a length not
* smaller than the given value.
*/
if ( strlen( $value ) < $checkvalue ) {
$ok = false;
}
break;
case 'maxval':
/*
* The maxval check does two things: it checks that the attribute value is
* an integer from 0 and up, without an excessive amount of zeroes or
* whitespace (to avoid Buffer Overflows). It also checks that the attribute
* value is not greater than the given value.
* This check can be used to avoid Denial of Service attacks.
*/
if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
$ok = false;
}
if ( $value > $checkvalue ) {
$ok = false;
}
break;
case 'minval':
/*
* The minval check makes sure that the attribute value is a positive integer,
* and that it is not smaller than the given value.
*/
if ( ! preg_match( '/^\s{0,6}[0-9]{1,6}\s{0,6}$/', $value ) ) {
$ok = false;
}
if ( $value < $checkvalue ) {
$ok = false;
}
break;
case 'valueless':
/*
* The valueless check makes sure if the attribute has a value
* (like `<a href="blah">`) or not (`<option selected>`). If the given value
* is a "y" or a "Y", the attribute must not have a value.
* If the given value is an "n" or an "N", the attribute must have a value.
*/
if ( strtolower( $checkvalue ) !== $vless ) {
$ok = false;
}
break;
case 'values':
/*
* The values check is used when you want to make sure that the attribute
* has one of the given values.
*/
if ( ! in_array( strtolower( $value ), $checkvalue, true ) ) {
$ok = false;
}
break;
case 'value_callback':
/*
* The value_callback check is used when you want to make sure that the attribute
* value is accepted by the callback function.
*/
if ( ! call_user_func( $checkvalue, $value ) ) {
$ok = false;
}
break;
} // End switch.
return $ok;
}
/**
* Sanitizes a string and removed disallowed URL protocols.
*
* This function removes all non-allowed protocols from the beginning of the
* string. It ignores whitespace and the case of the letters, and it does
* understand HTML entities. It does its work recursively, so it won't be
* fooled by a string like `javascript:javascript:alert(57)`.
*
* @since 1.0.0
*
* @param string $content Content to filter bad protocols from.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Filtered content.
*/
function wp_kses_bad_protocol( $content, $allowed_protocols ) {
$content = wp_kses_no_null( $content );
// Short-circuit if the string starts with `https://` or `http://`. Most common cases.
if (
( str_starts_with( $content, 'https://' ) && in_array( 'https', $allowed_protocols, true ) ) ||
( str_starts_with( $content, 'http://' ) && in_array( 'http', $allowed_protocols, true ) )
) {
return $content;
}
$iterations = 0;
do {
$original_content = $content;
$content = wp_kses_bad_protocol_once( $content, $allowed_protocols );
} while ( $original_content !== $content && ++$iterations < 6 );
if ( $original_content !== $content ) {
return '';
}
return $content;
}
/**
* Removes any invalid control characters in a text string.
*
* Also removes any instance of the `\0` string.
*
* @since 1.0.0
*
* @param string $content Content to filter null characters from.
* @param array $options Set 'slash_zero' => 'keep' when '\0' is allowed. Default is 'remove'.
* @return string Filtered content.
*/
function wp_kses_no_null( $content, $options = null ) {
if ( ! isset( $options['slash_zero'] ) ) {
$options = array( 'slash_zero' => 'remove' );
}
$content = preg_replace( '/[\x00-\x08\x0B\x0C\x0E-\x1F]/', '', $content );
if ( 'remove' === $options['slash_zero'] ) {
$content = preg_replace( '/\\\\+0+/', '', $content );
}
return $content;
}
/**
* Strips slashes from in front of quotes.
*
* This function changes the character sequence `\"` to just `"`. It leaves all other
* slashes alone. The quoting from `preg_replace(//e)` requires this.
*
* @since 1.0.0
*
* @param string $content String to strip slashes from.
* @return string Fixed string with quoted slashes.
*/
function wp_kses_stripslashes( $content ) {
return preg_replace( '%\\\\"%', '"', $content );
}
/**
* Converts the keys of an array to lowercase.
*
* @since 1.0.0
*
* @param array $inarray Unfiltered array.
* @return array Fixed array with all lowercase keys.
*/
function wp_kses_array_lc( $inarray ) {
$outarray = array();
foreach ( (array) $inarray as $inkey => $inval ) {
$outkey = strtolower( $inkey );
$outarray[ $outkey ] = array();
foreach ( (array) $inval as $inkey2 => $inval2 ) {
$outkey2 = strtolower( $inkey2 );
$outarray[ $outkey ][ $outkey2 ] = $inval2;
}
}
return $outarray;
}
/**
* Sanitizes content from bad protocols and other characters.
*
* This function searches for URL protocols at the beginning of the string, while
* handling whitespace and HTML entities.
*
* @since 1.0.0
*
* @param string $content Content to check for bad protocols.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @param int $count Depth of call recursion to this function.
* @return string Sanitized content.
*/
function wp_kses_bad_protocol_once( $content, $allowed_protocols, $count = 1 ) {
$content = preg_replace( '/(�*58(?![;0-9])|�*3a(?![;a-f0-9]))/i', '$1;', $content );
$content2 = preg_split( '/:|�*58;|�*3a;|:/i', $content, 2 );
if ( isset( $content2[1] ) && ! preg_match( '%/\?%', $content2[0] ) ) {
$content = trim( $content2[1] );
$protocol = wp_kses_bad_protocol_once2( $content2[0], $allowed_protocols );
if ( 'feed:' === $protocol ) {
if ( $count > 2 ) {
return '';
}
$content = wp_kses_bad_protocol_once( $content, $allowed_protocols, ++$count );
if ( empty( $content ) ) {
return $content;
}
}
$content = $protocol . $content;
}
return $content;
}
/**
* Callback for `wp_kses_bad_protocol_once()` regular expression.
*
* This function processes URL protocols, checks to see if they're in the
* list of allowed protocols or not, and returns different data depending
* on the answer.
*
* @access private
* @ignore
* @since 1.0.0
*
* @param string $scheme URI scheme to check against the list of allowed protocols.
* @param string[] $allowed_protocols Array of allowed URL protocols.
* @return string Sanitized content.
*/
function wp_kses_bad_protocol_once2( $scheme, $allowed_protocols ) {
$scheme = wp_kses_decode_entities( $scheme );
$scheme = preg_replace( '/\s/', '', $scheme );
$scheme = wp_kses_no_null( $scheme );
$scheme = strtolower( $scheme );
$allowed = array_any( (array) $allowed_protocols, fn( $protocol ) => strtolower( $protocol ) === $scheme );
if ( $allowed ) {
return "$scheme:";
} else {
return '';
}
}
/**
* Converts and fixes HTML entities.
*
* This function normalizes HTML entities. It will convert `AT&T` to the correct
* `AT&T`, `:` to `:`, `&#XYZZY;` to `&#XYZZY;` and so on.
*
* When `$context` is set to 'xml', HTML entities are converted to their code points. For
* example, `AT&T…&#XYZZY;` is converted to `AT&T…&#XYZZY;`.
*
* @since 1.0.0
* @since 5.5.0 Added `$context` parameter.
*
* @param string $content Content to normalize entities.
* @param string $context Context for normalization. Can be either 'html' or 'xml'.
* Default 'html'.
* @return string Content with normalized entities.
*/
function wp_kses_normalize_entities( $content, $context = 'html' ) {
// Disarm all entities by converting & to &
$content = str_replace( '&', '&', $content );
/*
* Decode any character references that are now double-encoded.
*
* It's important that the following normalizations happen in the correct order.
*
* At this point, all `&` have been transformed to `&`. Double-encoded named character
* references like `&amp;` will be decoded back to their single-encoded form `&`.
*
* First, numeric (decimal and hexadecimal) character references must be handled so that
* `&#09;` becomes `	`. If the named character references were handled first, there
* would be no way to know whether the double-encoded character reference had been produced
* in this function or was the original input.
*
* Consider the two examples, first with named entity decoding followed by numeric
* entity decoding. We'll use U+002E FULL STOP (.) in our example, this table follows the
* string processing from left to right:
*
* | Input | &-encoded | Named ref double-decoded | Numeric ref double-decoded |
* | ------------ | ---------------- | ------------------------- | -------------------------- |
* | `.` | `&#x2E;` | `&#x2E;` | `.` |
* | `&#x2E;` | `&amp;#x2E;` | `&#x2E;` | `.` |
*
* Notice in the example above that different inputs result in the same result. The second case
* was not normalized and produced HTML that is semantically different from the input.
*
* | Input | &-encoded | Numeric ref double-decoded | Named ref double-decoded |
* | ------------ | ---------------- | --------------------------- | ------------------------ |
* | `.` | `&#x2E;` | `.` | `.` |
* | `&#x2E;` | `&amp;#x2E;` | `&amp;#x2E;` | `&#x2E;` |
*
* Here, each input is normalized to an appropriate output.
*/
$content = preg_replace_callback( '/&#(0*[1-9][0-9]{0,6});/', 'wp_kses_normalize_entities2', $content );
$content = preg_replace_callback( '/&#[Xx](0*[1-9A-Fa-f][0-9A-Fa-f]{0,5});/', 'wp_kses_normalize_entities3', $content );
if ( 'xml' === $context ) {
$content = preg_replace_callback( '/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_xml_named_entities', $content );
} else {
$content = preg_replace_callback( '/&([A-Za-z]{2,8}[0-9]{0,2});/', 'wp_kses_named_entities', $content );
}
return $content;
}
/**
* Callback for `wp_kses_normalize_entities()` regular expression.
*
* This function only accepts valid named entity references, which are finite,
* case-sensitive, and highly scrutinized by HTML and XML validators.
*
* @since 3.0.0
*
* @global array $allowedentitynames
*
* @param array $matches preg_replace_callback() matches array.
* @return string Correctly encoded entity.
*/
function wp_kses_named_entities( $matches ) {
global $allowedentitynames;
if ( empty( $matches[1] ) ) {
return '';
}
$i = $matches[1];
return ( ! in_array( $i, $allowedentitynames, true ) ) ? "&$i;" : "&$i;";
}
/**
* Callback for `wp_kses_normalize_entities()` regular expression.
*
* This function only accepts valid named entity references, which are finite,
* case-sensitive, and highly scrutinized by XML validators. HTML named entity
* references are converted to their code points.
*
* @since 5.5.0
*
* @global array $allowedentitynames
* @global array $allowedxmlentitynames
*
* @param array $matches preg_replace_callback() matches array.
* @return string Correctly encoded entity.
*/
function wp_kses_xml_named_entities( $matches ) {
global $allowedentitynames, $allowedxmlentitynames;
if ( empty( $matches[1] ) ) {
return '';
}
$i = $matches[1];
if ( in_array( $i, $allowedxmlentitynames, true ) ) {
return "&$i;";
} elseif ( in_array( $i, $allowedentitynames, true ) ) {
return html_entity_decode( "&$i;", ENT_HTML5 );
}
return "&$i;";
}
/**
* Callback for `wp_kses_normalize_entities()` regular expression.
*
* This function helps `wp_kses_normalize_entities()` to only accept 16-bit
* values and nothing more for `&#number;` entities.
*
* @access private
* @ignore
* @since 1.0.0
*
* @param array $matches `preg_replace_callback()` matches array.
* @return string Correctly encoded entity.
*/
function wp_kses_normalize_entities2( $matches ) {
if ( empty( $matches[1] ) ) {
return '';
}
$i = $matches[1];
if ( valid_unicode( $i ) ) {
$i = str_pad( ltrim( $i, '0' ), 3, '0', STR_PAD_LEFT );
$i = "&#$i;";
} else {
$i = "&#$i;";
}
return $i;
}
/**
* Callback for `wp_kses_normalize_entities()` for regular expression.
*
* This function helps `wp_kses_normalize_entities()` to only accept valid Unicode
* numeric entities in hex form.
*
* @since 2.7.0
* @access private
* @ignore
*
* @param array $matches `preg_replace_callback()` matches array.
* @return string Correctly encoded entity.
*/
function wp_kses_normalize_entities3( $matches ) {
if ( empty( $matches[1] ) ) {
return '';
}
$hexchars = $matches[1];
return ( ! valid_unicode( hexdec( $hexchars ) ) ) ? "&#x$hexchars;" : '&#x' . ltrim( $hexchars, '0' ) . ';';
}
/**
* Determines if a Unicode codepoint is valid.
*
* The definition of a valid Unicode codepoint is taken from the XML definition:
*
* > Characters
* >
* > …
* > Legal characters are tab, carriage return, line feed, and the legal characters of
* > Unicode and ISO/IEC 10646.
* > …
* > Char ::= #x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
*
* @since 2.7.0
*
* @link https://www.w3.org/TR/xml/#charsets
*
* @param int $i Unicode codepoint.
* @return bool Whether or not the codepoint is a valid Unicode codepoint.
*/
function valid_unicode( $i ) {
$i = (int) $i;
return (
0x9 === $i || // U+0009 HORIZONTAL TABULATION (HT)
0xA === $i || // U+000A LINE FEED (LF)
0xD === $i || // U+000D CARRIAGE RETURN (CR)
/*
* The valid Unicode characters according to the XML specification:
*
* > any Unicode character, excluding the surrogate blocks, FFFE, and FFFF.
*/
( 0x20 <= $i && $i <= 0xD7FF ) ||
( 0xE000 <= $i && $i <= 0xFFFD ) ||
( 0x10000 <= $i && $i <= 0x10FFFF )
);
}
/**
* Converts all numeric HTML entities to their named counterparts.
*
* This function decodes numeric HTML entities (`A` and `A`).
* It doesn't do anything with named entities like `ä`, but we don't
* need them in the allowed URL protocols system anyway.
*
* @since 1.0.0
*
* @param string $content Content to change entities.
* @return string Content after decoded entities.
*/
function wp_kses_decode_entities( $content ) {
$content = preg_replace_callback( '/&#([0-9]+);/', '_wp_kses_decode_entities_chr', $content );
$content = preg_replace_callback( '/&#[Xx]([0-9A-Fa-f]+);/', '_wp_kses_decode_entities_chr_hexdec', $content );
return $content;
}
/**
* Regex callback for `wp_kses_decode_entities()`.
*
* @since 2.9.0
* @access private
* @ignore
*
* @param array $matches preg match
* @return string
*/
function _wp_kses_decode_entities_chr( $matches ) {
return chr( $matches[1] );
}
/**
* Regex callback for `wp_kses_decode_entities()`.
*
* @since 2.9.0
* @access private
* @ignore
*
* @param array $matches preg match
* @return string
*/
function _wp_kses_decode_entities_chr_hexdec( $matches ) {
return chr( hexdec( $matches[1] ) );
}
/**
* Sanitize content with allowed HTML KSES rules.
*
* This function expects slashed data.
*
* @since 1.0.0
*
* @param string $data Content to filter, expected to be escaped with slashes.
* @return string Filtered content.
*/
function wp_filter_kses( $data ) {
return addslashes( wp_kses( stripslashes( $data ), current_filter() ) );
}
/**
* Sanitize content with allowed HTML KSES rules.
*
* This function expects unslashed data.
*
* @since 2.9.0
*
* @param string $data Content to filter, expected to not be escaped.
* @return string Filtered content.
*/
function wp_kses_data( $data ) {
return wp_kses( $data, current_filter() );
}
/**
* Sanitizes content for allowed HTML tags for post content.
*
* Post content refers to the page contents of the 'post' type and not `$_POST`
* data from forms.
*
* This function expects slashed data.
*
* @since 2.0.0
*
* @param string $data Post content to filter, expected to be escaped with slashes.
* @return string Filtered post content with allowed HTML tags and attributes intact.
*/
function wp_filter_post_kses( $data ) {
return addslashes( wp_kses( stripslashes( $data ), 'post' ) );
}
/**
* Sanitizes global styles user content removing unsafe rules.
*
* @since 5.9.0
*
* @param string $data Post content to filter.
* @return string Filtered post content with unsafe rules removed.
*/
function wp_filter_global_styles_post( $data ) {
$decoded_data = json_decode( wp_unslash( $data ), true );
$json_decoding_error = json_last_error();
if (
JSON_ERROR_NONE === $json_decoding_error &&
is_array( $decoded_data ) &&
isset( $decoded_data['isGlobalStylesUserThemeJSON'] ) &&
$decoded_data['isGlobalStylesUserThemeJSON']
) {
unset( $decoded_data['isGlobalStylesUserThemeJSON'] );
$data_to_encode = WP_Theme_JSON::remove_insecure_properties( $decoded_data, 'custom' );
$data_to_encode['isGlobalStylesUserThemeJSON'] = true;
/**
* JSON encode the data stored in post content.
* Escape characters that are likely to be mangled by HTML filters: "<>&".
*
* This matches the escaping in {@see WP_REST_Global_Styles_Controller::prepare_item_for_database()}.
*/
return wp_slash( wp_json_encode( $data_to_encode, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) );
}
return $data;
}
/**
* Sanitizes content for allowed HTML tags for post content.
*
* Post content refers to the page contents of the 'post' type and not `$_POST`
* data from forms.
*
* This function expects unslashed data.
*
* @since 2.9.0
*
* @param string $data Post content to filter.
* @return string Filtered post content with allowed HTML tags and attributes intact.
*/
function wp_kses_post( $data ) {
return wp_kses( $data, 'post' );
}
/**
* Navigates through an array, object, or scalar, and sanitizes content for
* allowed HTML tags for post content.
*
* @since 4.4.2
*
* @see map_deep()
*
* @param mixed $data The array, object, or scalar value to inspect.
* @return mixed The filtered content.
*/
function wp_kses_post_deep( $data ) {
return map_deep( $data, 'wp_kses_post' );
}
/**
* Strips all HTML from a text string.
*
* This function expects slashed data.
*
* @since 2.1.0
*
* @param string $data Content to strip all HTML from.
* @return string Filtered content without any HTML.
*/
function wp_filter_nohtml_kses( $data ) {
return addslashes( wp_kses( stripslashes( $data ), 'strip' ) );
}
/**
* Adds all KSES input form content filters.
*
* All hooks have default priority. The `wp_filter_kses()` function is added to
* the 'pre_comment_content' and 'title_save_pre' hooks.
*
* The `wp_filter_post_kses()` function is added to the 'content_save_pre',
* 'excerpt_save_pre', and 'content_filtered_save_pre' hooks.
*
* @since 2.0.0
*/
function kses_init_filters() {
// Normal filtering.
add_filter( 'title_save_pre', 'wp_filter_kses' );
// Comment filtering.
if ( current_user_can( 'unfiltered_html' ) ) {
add_filter( 'pre_comment_content', 'wp_filter_post_kses' );
} else {
add_filter( 'pre_comment_content', 'wp_filter_kses' );
}
// Global Styles filtering: Global Styles filters should be executed before normal post_kses HTML filters.
add_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
add_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
// Post filtering.
add_filter( 'content_save_pre', 'wp_filter_post_kses' );
add_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
add_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
}
/**
* Removes all KSES input form content filters.
*
* A quick procedural method to removing all of the filters that KSES uses for
* content in WordPress Loop.
*
* Does not remove the `kses_init()` function from {@see 'init'} hook (priority is
* default). Also does not remove `kses_init()` function from {@see 'set_current_user'}
* hook (priority is also default).
*
* @since 2.0.6
*/
function kses_remove_filters() {
// Normal filtering.
remove_filter( 'title_save_pre', 'wp_filter_kses' );
// Comment filtering.
remove_filter( 'pre_comment_content', 'wp_filter_post_kses' );
remove_filter( 'pre_comment_content', 'wp_filter_kses' );
// Global Styles filtering.
remove_filter( 'content_save_pre', 'wp_filter_global_styles_post', 9 );
remove_filter( 'content_filtered_save_pre', 'wp_filter_global_styles_post', 9 );
// Post filtering.
remove_filter( 'content_save_pre', 'wp_filter_post_kses' );
remove_filter( 'excerpt_save_pre', 'wp_filter_post_kses' );
remove_filter( 'content_filtered_save_pre', 'wp_filter_post_kses' );
}
/**
* Sets up most of the KSES filters for input form content.
*
* First removes all of the KSES filters in case the current user does not need
* to have KSES filter the content. If the user does not have `unfiltered_html`
* capability, then KSES filters are added.
*
* @since 2.0.0
*/
function kses_init() {
kses_remove_filters();
if ( ! current_user_can( 'unfiltered_html' ) ) {
kses_init_filters();
}
}
/**
* Filters an inline style attribute and removes disallowed rules.
*
* @since 2.8.1
* @since 4.4.0 Added support for `min-height`, `max-height`, `min-width`, and `max-width`.
* @since 4.6.0 Added support for `list-style-type`.
* @since 5.0.0 Added support for `background-image`.
* @since 5.1.0 Added support for `text-transform`.
* @since 5.2.0 Added support for `background-position` and `grid-template-columns`.
* @since 5.3.0 Added support for `grid`, `flex` and `column` layout properties.
* Extended `background-*` support for individual properties.
* @since 5.3.1 Added support for gradient backgrounds.
* @since 5.7.1 Added support for `object-position`.
* @since 5.8.0 Added support for `calc()` and `var()` values.
* @since 6.1.0 Added support for `min()`, `max()`, `minmax()`, `clamp()`,
* nested `var()` values, and assigning values to CSS variables.
* Added support for `object-fit`, `gap`, `column-gap`, `row-gap`, and `flex-wrap`.
* Extended `margin-*` and `padding-*` support for logical properties.
* @since 6.2.0 Added support for `aspect-ratio`, `position`, `top`, `right`, `bottom`, `left`,
* and `z-index` CSS properties.
* @since 6.3.0 Extended support for `filter` to accept a URL and added support for repeat().
* Added support for `box-shadow`.
* @since 6.4.0 Added support for `writing-mode`.
* @since 6.5.0 Added support for `background-repeat`.
* @since 6.6.0 Added support for `grid-column`, `grid-row`, and `container-type`.
* @since 6.9.0 Added support for `white-space`.
* @since 7.1.0 Extended gradient support to allow any single-level nested function.
* Added support for transform functions, `clip-path` basic shapes,
* and URLs in the SVG element reference properties.
* @since 7.2.0 Added support for CSS anchor positioning properties and `text-shadow`.
* Added support for `background-clip`.
*
* @param string $css A string of CSS rules, decoded from an HTML `style` attribute.
* @param string $deprecated Not used.
* @return string Filtered string of CSS rules, needing HTML escaping before sending back to a `style` attribute.
*
* @phpstan-param '' $deprecated
*/
function safecss_filter_attr( $css, $deprecated = '' ) {
if ( ! empty( $deprecated ) ) {
_deprecated_argument( __FUNCTION__, '2.8.1' ); // Never implemented.
}
$css = wp_kses_no_null( $css );
$css = str_replace( array( "\n", "\r", "\t" ), '', $css );
$allowed_protocols = wp_allowed_protocols();
/** @todo Parse enough CSS to split rules without breaking on things like quoted strings. */
$css_array = explode( ';', trim( $css ) );
/**
* Filters the list of allowed CSS attributes.
*
* @since 2.8.1
* @since 7.1.0 Added support for SVG presentation attributes.
* @since 7.2.0 Added support for `background-clip` and its vendor prefixed companions.
*
* @param string[] $attr Array of allowed CSS attributes.
*/
$allowed_attr = apply_filters(
'safe_style_css',
array(
'background',
'background-color',
'background-image',
'background-position',
'background-repeat',
'background-size',
'background-attachment',
'background-blend-mode',
'background-clip',
'-webkit-background-clip',
'-webkit-text-fill-color',
'border',
'border-radius',
'border-width',
'border-color',
'border-style',
'border-right',
'border-right-color',
'border-right-style',
'border-right-width',
'border-bottom',
'border-bottom-color',
'border-bottom-left-radius',
'border-bottom-right-radius',
'border-bottom-style',
'border-bottom-width',
'border-bottom-right-radius',
'border-bottom-left-radius',
'border-left',
'border-left-color',
'border-left-style',
'border-left-width',
'border-top',
'border-top-color',
'border-top-left-radius',
'border-top-right-radius',
'border-top-style',
'border-top-width',
'border-top-left-radius',
'border-top-right-radius',
'border-spacing',
'border-collapse',
'caption-side',
'columns',
'column-count',
'column-fill',
'column-gap',
'column-rule',
'column-span',
'column-width',
'display',
'color',
'filter',
'font',
'font-family',
'font-size',
'font-style',
'font-variant',
'font-weight',
'letter-spacing',
'line-height',
'text-align',
'text-decoration',
'text-indent',
'text-shadow',
'text-transform',
'white-space',
'height',
'min-height',
'max-height',
'width',
'min-width',
'max-width',
'margin',
'margin-right',
'margin-bottom',
'margin-left',
'margin-top',
'margin-block-start',
'margin-block-end',
'margin-inline-start',
'margin-inline-end',
'padding',
'padding-right',
'padding-bottom',
'padding-left',
'padding-top',
'padding-block-start',
'padding-block-end',
'padding-inline-start',
'padding-inline-end',
'flex',
'flex-basis',
'flex-direction',
'flex-flow',
'flex-grow',
'flex-shrink',
'flex-wrap',
'gap',
'column-gap',
'row-gap',
'grid-template-columns',
'grid-auto-columns',
'grid-column-start',
'grid-column-end',
'grid-column',
'grid-column-gap',
'grid-template-rows',
'grid-auto-rows',
'grid-row-start',
'grid-row-end',
'grid-row',
'grid-row-gap',
'grid-gap',
'justify-content',
'justify-items',
'justify-self',
'align-content',
'align-items',
'align-self',
'clear',
'cursor',
'direction',
'float',
'list-style-type',
'object-fit',
'object-position',
'opacity',
'overflow',
'vertical-align',
'writing-mode',
'position',
'top',
'right',
'bottom',
'left',
'z-index',
'box-shadow',
'aspect-ratio',
'container-type',
'fill',
'fill-opacity',
'fill-rule',
'stroke',
'stroke-dasharray',
'stroke-dashoffset',
'stroke-linecap',
'stroke-linejoin',
'stroke-miterlimit',
'stroke-opacity',
'stroke-width',
'color-interpolation',
'color-interpolation-filters',
'paint-order',
'stop-color',
'stop-opacity',
'flood-color',
'flood-opacity',
'lighting-color',
'marker',
'marker-end',
'marker-mid',
'marker-start',
'clip-path',
'clip-rule',
'mask',
'mask-type',
'cx',
'cy',
'r',
'rx',
'ry',
'x',
'y',
'd',
'alignment-baseline',
'baseline-shift',
'dominant-baseline',
'glyph-orientation-horizontal',
'glyph-orientation-vertical',
'text-anchor',
'unicode-bidi',
'word-spacing',
'font-size-adjust',
'font-stretch',
'color-rendering',
'image-rendering',
'shape-rendering',
'text-rendering',
'vector-effect',
'transform',
'transform-origin',
'pointer-events',
'visibility',
'anchor-name',
'anchor-scope',
'position-anchor',
'position-area',
'position-try',
'position-try-fallbacks',
'position-try-order',
'position-visibility',
// Custom CSS properties.
'--*',
)
);
/*
* CSS attributes that accept URL data types.
*
* This is in accordance to the CSS spec and unrelated to
* the sub-set of supported attributes above.
*
* See: https://developer.mozilla.org/en-US/docs/Web/CSS/url
*/
$css_url_data_types = array(
'background',
'background-image',
'cursor',
'filter',
'list-style',
'list-style-image',
// SVG presentation properties that accept url() references.
'clip-path',
'fill',
'marker',
'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke',
);
/*
* CSS attributes that accept gradient data types.
*
*/
$css_gradient_data_types = array(
'background',
'background-image',
);
if ( empty( $allowed_attr ) ) {
return $css;
}
$css = '';
foreach ( $css_array as $css_item ) {
if ( '' === $css_item ) {
continue;
}
$css_item = trim( $css_item );
$css_test_string = $css_item;
$found = false;
$url_attr = false;
$gradient_attr = false;
$is_custom_var = false;
if ( ! str_contains( $css_item, ':' ) ) {
$found = true;
} else {
$parts = explode( ':', $css_item, 2 );
$css_selector = trim( $parts[0] );
// Allow assigning values to CSS variables.
if ( in_array( '--*', $allowed_attr, true ) && preg_match( '/^--[a-zA-Z0-9-_]+$/', $css_selector ) ) {
$allowed_attr[] = $css_selector;
$is_custom_var = true;
}
if ( in_array( $css_selector, $allowed_attr, true ) ) {
$found = true;
$url_attr = in_array( $css_selector, $css_url_data_types, true );
$gradient_attr = in_array( $css_selector, $css_gradient_data_types, true );
}
if ( $is_custom_var ) {
$css_value = trim( $parts[1] );
$url_attr = str_starts_with( $css_value, 'url(' );
$gradient_attr = str_contains( $css_value, '-gradient(' );
}
}
if ( $found && $url_attr ) {
// Simplified: matches the sequence `url(*)`.
preg_match_all( '/url\([^)]+\)/', $parts[1], $url_matches );
foreach ( $url_matches[0] as $url_match ) {
// Clean up the URL from each of the matches above.
preg_match( '/^url\(\s*([\'\"]?)(.*)(\g1)\s*\)$/', $url_match, $url_pieces );
if ( empty( $url_pieces[2] ) ) {
$found = false;
break;
}
$url = trim( $url_pieces[2] );
if ( empty( $url ) || wp_kses_bad_protocol( $url, $allowed_protocols ) !== $url ) {
$found = false;
break;
} else {
// Remove the whole `url(*)` bit that was matched above from the CSS.
$css_test_string = str_replace( $url_match, '', $css_test_string );
}
}
}
if ( $found && $gradient_attr ) {
/*
* Match every `*-gradient()` in the value, allowing one level of nested functions
* (e.g. rgb(), hsl(), var()). Matching each occurrence, rather than requiring the
* whole value to be a single gradient, lets a gradient combine with a url() image.
*/
preg_match_all( '/(?:repeating-)?(?:linear|radial|conic)-gradient\((?:[^()]|\([^()]*\))*\)/', $css_test_string, $gradient_matches );
foreach ( $gradient_matches[0] as $gradient_match ) {
// Remove each `gradient()` bit that was matched above from the CSS.
$css_test_string = str_replace( $gradient_match, '', $css_test_string );
}
}
if ( $found ) {
/*
* Allow CSS functions like var(), calc(), etc. by removing them from the test string.
* Nested functions and parentheses are also removed, so long as the parentheses are balanced.
*/
$css_test_string = preg_replace(
'/\b(?:'
// General purpose value functions.
. 'var|calc|min|max|minmax|clamp|repeat'
// Transform functions.
. '|matrix|matrix3d|perspective'
. '|rotate|rotate3d|rotateX|rotateY|rotateZ'
. '|scale|scale3d|scaleX|scaleY|scaleZ'
. '|skew|skewX|skewY'
. '|translate|translate3d|translateX|translateY|translateZ'
// Basic shape functions, as used by `clip-path`.
. '|circle|ellipse|inset|path|polygon|rect|shape|xywh'
. ')(\((?:[^()]|(?1))*\))/',
'',
$css_test_string
);
// Bail if the recursive function stripping hit a PCRE error (e.g. stack/backtrack limit).
if ( null === $css_test_string ) {
continue;
}
/*
* Disallow CSS containing \ ( & } = or comments, except for within url(), var(), calc(), etc.
* which were removed from the test string above.
*/
$allow_css = 0 === preg_match( '%[\\\(&=}]|/\*%', $css_test_string );
/**
* Filters the check for unsafe CSS in `safecss_filter_attr`.
*
* Enables developers to determine whether a section of CSS should be allowed or discarded.
* By default, the value will be false if the part contains \ ( & } = or comments.
* Return true to allow the CSS part to be included in the output.
*
* @since 5.5.0
*
* @param bool $allow_css Whether the CSS in the test string is considered safe.
* @param string $css_test_string The CSS string to test.
*/
$allow_css = apply_filters( 'safecss_filter_attr_allow_css', $allow_css, $css_test_string );
// Only add the CSS part if it passes the regex check.
if ( $allow_css ) {
if ( '' !== $css ) {
$css .= ';';
}
$css .= $css_item;
}
}
}
return $css;
}
/**
* Helper function to add global attributes to a tag in the allowed HTML list.
*
* @since 3.5.0
* @since 5.0.0 Added support for `data-*` wildcard attributes.
* @since 6.0.0 Added `dir`, `lang`, and `xml:lang` to global attributes.
* @since 6.3.0 Added `aria-controls`, `aria-current`, and `aria-expanded` attributes.
* @since 6.4.0 Added `aria-live` and `hidden` attributes.
* @since 7.1.0 Added `tabindex` attribute.
*
* @access private
* @ignore
*
* @param array $value An array of attributes.
* @return array The array of attributes with global attributes added.
*/
function _wp_add_global_attributes( $value ) {
$global_attributes = array(
'aria-controls' => true,
'aria-current' => true,
'aria-describedby' => true,
'aria-details' => true,
'aria-expanded' => true,
'aria-hidden' => true,
'aria-label' => true,
'aria-labelledby' => true,
'aria-live' => true,
'class' => true,
'data-*' => true,
'dir' => true,
'hidden' => true,
'id' => true,
'lang' => true,
'style' => true,
'tabindex' => true,
'title' => true,
'role' => true,
'xml:lang' => true,
);
if ( true === $value ) {
$value = array();
}
if ( is_array( $value ) ) {
return array_merge( $value, $global_attributes );
}
return $value;
}
/**
* Helper function to check if this is a safe PDF URL.
*
* @since 5.9.0
* @access private
* @ignore
*
* @param string $url The URL to check.
* @return bool True if the URL is safe, false otherwise.
*/
function _wp_kses_allow_pdf_objects( $url ) {
// We're not interested in URLs that contain query strings or fragments.
if ( str_contains( $url, '?' ) || str_contains( $url, '#' ) ) {
return false;
}
// If it doesn't have a PDF extension, it's not safe.
if ( ! str_ends_with( $url, '.pdf' ) ) {
return false;
}
// If the URL host matches the current site's media URL, it's safe.
$upload_info = wp_upload_dir( null, false );
$parsed_url = wp_parse_url( $upload_info['url'] );
$upload_host = $parsed_url['host'] ?? '';
$upload_port = isset( $parsed_url['port'] ) ? ':' . $parsed_url['port'] : '';
if ( str_starts_with( $url, "http://$upload_host$upload_port/" )
|| str_starts_with( $url, "https://$upload_host$upload_port/" )
) {
return true;
}
return false;
}
/**
* Determines whether KSES restricts the value of any attribute of an element.
*
* An attribute rule other than `required` and `valueless` restricts the value itself,
* for example `values` or `value_callback`.
*
* @since 7.1.4
* @access private
* @ignore
*
* @param array|bool $allowed_attributes The attributes KSES allows on the element.
* @return bool Whether KSES restricts the value of any attribute of the element.
*/
function _wp_kses_restricts_attribute_values( $allowed_attributes ): bool {
if ( ! is_array( $allowed_attributes ) ) {
return false;
}
foreach ( $allowed_attributes as $attribute_rules ) {
if ( ! is_array( $attribute_rules ) ) {
continue;
}
foreach ( array_keys( $attribute_rules ) as $rule ) {
if ( ! in_array( strtolower( (string) $rule ), array( 'required', 'valueless' ), true ) ) {
return true;
}
}
}
return false;
}
/**
* Determines whether a directive binds an attribute whose value KSES restricts.
*
* This only applies to elements for which KSES restricts the value of at least one
* attribute. On those elements, a `data-wp-bind` directive is reported unless it binds
* an attribute which KSES allows there with any value. KSES calls this to keep such a
* directive out of content saved by an author who cannot post unfiltered HTML.
*
* @since 7.1.4
* @access private
* @ignore
*
* @param string $directive_name The directive attribute name, in lowercase.
* @param array|bool $allowed_attributes The attributes KSES allows on the element.
* @return bool Whether the directive binds an attribute whose value KSES restricts.
*/
function _wp_kses_directive_binds_value_restricted_attribute( string $directive_name, $allowed_attributes ): bool {
if ( ! str_starts_with( $directive_name, 'data-wp-bind--' ) ) {
return false;
}
if ( ! _wp_kses_restricts_attribute_values( $allowed_attributes ) ) {
return false;
}
/*
* Both the whole remainder of the name and the part before a unique ID are checked, so
* that the result does not depend on how the unique ID is parsed. A binding with a unique
* ID is not applied at all, so removing one changes nothing.
*/
$bound_attribute = substr( $directive_name, strlen( 'data-wp-bind--' ) );
$bound_attributes = array( $bound_attribute );
$unique_id_index = strpos( $bound_attribute, '---' );
if ( false !== $unique_id_index ) {
$bound_attributes[] = substr( $bound_attribute, 0, $unique_id_index );
}
foreach ( $bound_attributes as $attribute_name ) {
if ( isset( $allowed_attributes[ $attribute_name ] ) ) {
$rules = $allowed_attributes[ $attribute_name ];
} elseif ( 1 === preg_match( '/^data-[a-z0-9_-]+$/', $attribute_name ) && isset( $allowed_attributes['data-*'] ) ) {
$rules = $allowed_attributes['data-*'];
} else {
return true;
}
if ( ! $rules || is_array( $rules ) ) {
return true;
}
}
return false;
}
The same content is in 2 releases, WordPress 7.2-beta3 to 7.2-beta4. See them all, or every version of this file.