1
0

HTMLPurifier.standalone.php 669 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099
  1. <?php
  2. /**
  3. * @file
  4. * This file was auto-generated by generate-includes.php and includes all of
  5. * the core files required by HTML Purifier. Use this if performance is a
  6. * primary concern and you are using an opcode cache. PLEASE DO NOT EDIT THIS
  7. * FILE, changes will be overwritten the next time the script is run.
  8. *
  9. * @version 4.8.0
  10. *
  11. * @warning
  12. * You must *not* include any other HTML Purifier files before this file,
  13. * because 'require' not 'require_once' is used.
  14. *
  15. * @warning
  16. * This file requires that the include path contains the HTML Purifier
  17. * library directory; this is not auto-set.
  18. */
  19. /*! @mainpage
  20. *
  21. * HTML Purifier is an HTML filter that will take an arbitrary snippet of
  22. * HTML and rigorously test, validate and filter it into a version that
  23. * is safe for output onto webpages. It achieves this by:
  24. *
  25. * -# Lexing (parsing into tokens) the document,
  26. * -# Executing various strategies on the tokens:
  27. * -# Removing all elements not in the whitelist,
  28. * -# Making the tokens well-formed,
  29. * -# Fixing the nesting of the nodes, and
  30. * -# Validating attributes of the nodes; and
  31. * -# Generating HTML from the purified tokens.
  32. *
  33. * However, most users will only need to interface with the HTMLPurifier
  34. * and HTMLPurifier_Config.
  35. */
  36. /*
  37. HTML Purifier 4.8.0 - Standards Compliant HTML Filtering
  38. Copyright (C) 2006-2008 Edward Z. Yang
  39. This library is free software; you can redistribute it and/or
  40. modify it under the terms of the GNU Lesser General Public
  41. License as published by the Free Software Foundation; either
  42. version 2.1 of the License, or (at your option) any later version.
  43. This library is distributed in the hope that it will be useful,
  44. but WITHOUT ANY WARRANTY; without even the implied warranty of
  45. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  46. Lesser General Public License for more details.
  47. You should have received a copy of the GNU Lesser General Public
  48. License along with this library; if not, write to the Free Software
  49. Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  50. */
  51. /**
  52. * Facade that coordinates HTML Purifier's subsystems in order to purify HTML.
  53. *
  54. * @note There are several points in which configuration can be specified
  55. * for HTML Purifier. The precedence of these (from lowest to
  56. * highest) is as follows:
  57. * -# Instance: new HTMLPurifier($config)
  58. * -# Invocation: purify($html, $config)
  59. * These configurations are entirely independent of each other and
  60. * are *not* merged (this behavior may change in the future).
  61. *
  62. * @todo We need an easier way to inject strategies using the configuration
  63. * object.
  64. */
  65. class HTMLPurifier
  66. {
  67. /**
  68. * Version of HTML Purifier.
  69. * @type string
  70. */
  71. public $version = '4.8.0';
  72. /**
  73. * Constant with version of HTML Purifier.
  74. */
  75. const VERSION = '4.8.0';
  76. /**
  77. * Global configuration object.
  78. * @type HTMLPurifier_Config
  79. */
  80. public $config;
  81. /**
  82. * Array of extra filter objects to run on HTML,
  83. * for backwards compatibility.
  84. * @type HTMLPurifier_Filter[]
  85. */
  86. private $filters = array();
  87. /**
  88. * Single instance of HTML Purifier.
  89. * @type HTMLPurifier
  90. */
  91. private static $instance;
  92. /**
  93. * @type HTMLPurifier_Strategy_Core
  94. */
  95. protected $strategy;
  96. /**
  97. * @type HTMLPurifier_Generator
  98. */
  99. protected $generator;
  100. /**
  101. * Resultant context of last run purification.
  102. * Is an array of contexts if the last called method was purifyArray().
  103. * @type HTMLPurifier_Context
  104. */
  105. public $context;
  106. /**
  107. * Initializes the purifier.
  108. *
  109. * @param HTMLPurifier_Config|mixed $config Optional HTMLPurifier_Config object
  110. * for all instances of the purifier, if omitted, a default
  111. * configuration is supplied (which can be overridden on a
  112. * per-use basis).
  113. * The parameter can also be any type that
  114. * HTMLPurifier_Config::create() supports.
  115. */
  116. public function __construct($config = null)
  117. {
  118. $this->config = HTMLPurifier_Config::create($config);
  119. $this->strategy = new HTMLPurifier_Strategy_Core();
  120. }
  121. /**
  122. * Adds a filter to process the output. First come first serve
  123. *
  124. * @param HTMLPurifier_Filter $filter HTMLPurifier_Filter object
  125. */
  126. public function addFilter($filter)
  127. {
  128. trigger_error(
  129. 'HTMLPurifier->addFilter() is deprecated, use configuration directives' .
  130. ' in the Filter namespace or Filter.Custom',
  131. E_USER_WARNING
  132. );
  133. $this->filters[] = $filter;
  134. }
  135. /**
  136. * Filters an HTML snippet/document to be XSS-free and standards-compliant.
  137. *
  138. * @param string $html String of HTML to purify
  139. * @param HTMLPurifier_Config $config Config object for this operation,
  140. * if omitted, defaults to the config object specified during this
  141. * object's construction. The parameter can also be any type
  142. * that HTMLPurifier_Config::create() supports.
  143. *
  144. * @return string Purified HTML
  145. */
  146. public function purify($html, $config = null)
  147. {
  148. // :TODO: make the config merge in, instead of replace
  149. $config = $config ? HTMLPurifier_Config::create($config) : $this->config;
  150. // implementation is partially environment dependant, partially
  151. // configuration dependant
  152. $lexer = HTMLPurifier_Lexer::create($config);
  153. $context = new HTMLPurifier_Context();
  154. // setup HTML generator
  155. $this->generator = new HTMLPurifier_Generator($config, $context);
  156. $context->register('Generator', $this->generator);
  157. // set up global context variables
  158. if ($config->get('Core.CollectErrors')) {
  159. // may get moved out if other facilities use it
  160. $language_factory = HTMLPurifier_LanguageFactory::instance();
  161. $language = $language_factory->create($config, $context);
  162. $context->register('Locale', $language);
  163. $error_collector = new HTMLPurifier_ErrorCollector($context);
  164. $context->register('ErrorCollector', $error_collector);
  165. }
  166. // setup id_accumulator context, necessary due to the fact that
  167. // AttrValidator can be called from many places
  168. $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
  169. $context->register('IDAccumulator', $id_accumulator);
  170. $html = HTMLPurifier_Encoder::convertToUTF8($html, $config, $context);
  171. // setup filters
  172. $filter_flags = $config->getBatch('Filter');
  173. $custom_filters = $filter_flags['Custom'];
  174. unset($filter_flags['Custom']);
  175. $filters = array();
  176. foreach ($filter_flags as $filter => $flag) {
  177. if (!$flag) {
  178. continue;
  179. }
  180. if (strpos($filter, '.') !== false) {
  181. continue;
  182. }
  183. $class = "HTMLPurifier_Filter_$filter";
  184. $filters[] = new $class;
  185. }
  186. foreach ($custom_filters as $filter) {
  187. // maybe "HTMLPurifier_Filter_$filter", but be consistent with AutoFormat
  188. $filters[] = $filter;
  189. }
  190. $filters = array_merge($filters, $this->filters);
  191. // maybe prepare(), but later
  192. for ($i = 0, $filter_size = count($filters); $i < $filter_size; $i++) {
  193. $html = $filters[$i]->preFilter($html, $config, $context);
  194. }
  195. // purified HTML
  196. $html =
  197. $this->generator->generateFromTokens(
  198. // list of tokens
  199. $this->strategy->execute(
  200. // list of un-purified tokens
  201. $lexer->tokenizeHTML(
  202. // un-purified HTML
  203. $html,
  204. $config,
  205. $context
  206. ),
  207. $config,
  208. $context
  209. )
  210. );
  211. for ($i = $filter_size - 1; $i >= 0; $i--) {
  212. $html = $filters[$i]->postFilter($html, $config, $context);
  213. }
  214. $html = HTMLPurifier_Encoder::convertFromUTF8($html, $config, $context);
  215. $this->context =& $context;
  216. return $html;
  217. }
  218. /**
  219. * Filters an array of HTML snippets
  220. *
  221. * @param string[] $array_of_html Array of html snippets
  222. * @param HTMLPurifier_Config $config Optional config object for this operation.
  223. * See HTMLPurifier::purify() for more details.
  224. *
  225. * @return string[] Array of purified HTML
  226. */
  227. public function purifyArray($array_of_html, $config = null)
  228. {
  229. $context_array = array();
  230. foreach ($array_of_html as $key => $html) {
  231. $array_of_html[$key] = $this->purify($html, $config);
  232. $context_array[$key] = $this->context;
  233. }
  234. $this->context = $context_array;
  235. return $array_of_html;
  236. }
  237. /**
  238. * Singleton for enforcing just one HTML Purifier in your system
  239. *
  240. * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype
  241. * HTMLPurifier instance to overload singleton with,
  242. * or HTMLPurifier_Config instance to configure the
  243. * generated version with.
  244. *
  245. * @return HTMLPurifier
  246. */
  247. public static function instance($prototype = null)
  248. {
  249. if (!self::$instance || $prototype) {
  250. if ($prototype instanceof HTMLPurifier) {
  251. self::$instance = $prototype;
  252. } elseif ($prototype) {
  253. self::$instance = new HTMLPurifier($prototype);
  254. } else {
  255. self::$instance = new HTMLPurifier();
  256. }
  257. }
  258. return self::$instance;
  259. }
  260. /**
  261. * Singleton for enforcing just one HTML Purifier in your system
  262. *
  263. * @param HTMLPurifier|HTMLPurifier_Config $prototype Optional prototype
  264. * HTMLPurifier instance to overload singleton with,
  265. * or HTMLPurifier_Config instance to configure the
  266. * generated version with.
  267. *
  268. * @return HTMLPurifier
  269. * @note Backwards compatibility, see instance()
  270. */
  271. public static function getInstance($prototype = null)
  272. {
  273. return HTMLPurifier::instance($prototype);
  274. }
  275. }
  276. /**
  277. * Converts a stream of HTMLPurifier_Token into an HTMLPurifier_Node,
  278. * and back again.
  279. *
  280. * @note This transformation is not an equivalence. We mutate the input
  281. * token stream to make it so; see all [MUT] markers in code.
  282. */
  283. class HTMLPurifier_Arborize
  284. {
  285. public static function arborize($tokens, $config, $context) {
  286. $definition = $config->getHTMLDefinition();
  287. $parent = new HTMLPurifier_Token_Start($definition->info_parent);
  288. $stack = array($parent->toNode());
  289. foreach ($tokens as $token) {
  290. $token->skip = null; // [MUT]
  291. $token->carryover = null; // [MUT]
  292. if ($token instanceof HTMLPurifier_Token_End) {
  293. $token->start = null; // [MUT]
  294. $r = array_pop($stack);
  295. assert($r->name === $token->name);
  296. assert(empty($token->attr));
  297. $r->endCol = $token->col;
  298. $r->endLine = $token->line;
  299. $r->endArmor = $token->armor;
  300. continue;
  301. }
  302. $node = $token->toNode();
  303. $stack[count($stack)-1]->children[] = $node;
  304. if ($token instanceof HTMLPurifier_Token_Start) {
  305. $stack[] = $node;
  306. }
  307. }
  308. assert(count($stack) == 1);
  309. return $stack[0];
  310. }
  311. public static function flatten($node, $config, $context) {
  312. $level = 0;
  313. $nodes = array($level => new HTMLPurifier_Queue(array($node)));
  314. $closingTokens = array();
  315. $tokens = array();
  316. do {
  317. while (!$nodes[$level]->isEmpty()) {
  318. $node = $nodes[$level]->shift(); // FIFO
  319. list($start, $end) = $node->toTokenPair();
  320. if ($level > 0) {
  321. $tokens[] = $start;
  322. }
  323. if ($end !== NULL) {
  324. $closingTokens[$level][] = $end;
  325. }
  326. if ($node instanceof HTMLPurifier_Node_Element) {
  327. $level++;
  328. $nodes[$level] = new HTMLPurifier_Queue();
  329. foreach ($node->children as $childNode) {
  330. $nodes[$level]->push($childNode);
  331. }
  332. }
  333. }
  334. $level--;
  335. if ($level && isset($closingTokens[$level])) {
  336. while ($token = array_pop($closingTokens[$level])) {
  337. $tokens[] = $token;
  338. }
  339. }
  340. } while ($level > 0);
  341. return $tokens;
  342. }
  343. }
  344. /**
  345. * Defines common attribute collections that modules reference
  346. */
  347. class HTMLPurifier_AttrCollections
  348. {
  349. /**
  350. * Associative array of attribute collections, indexed by name.
  351. * @type array
  352. */
  353. public $info = array();
  354. /**
  355. * Performs all expansions on internal data for use by other inclusions
  356. * It also collects all attribute collection extensions from
  357. * modules
  358. * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance
  359. * @param HTMLPurifier_HTMLModule[] $modules Hash array of HTMLPurifier_HTMLModule members
  360. */
  361. public function __construct($attr_types, $modules)
  362. {
  363. $this->doConstruct($attr_types, $modules);
  364. }
  365. public function doConstruct($attr_types, $modules)
  366. {
  367. // load extensions from the modules
  368. foreach ($modules as $module) {
  369. foreach ($module->attr_collections as $coll_i => $coll) {
  370. if (!isset($this->info[$coll_i])) {
  371. $this->info[$coll_i] = array();
  372. }
  373. foreach ($coll as $attr_i => $attr) {
  374. if ($attr_i === 0 && isset($this->info[$coll_i][$attr_i])) {
  375. // merge in includes
  376. $this->info[$coll_i][$attr_i] = array_merge(
  377. $this->info[$coll_i][$attr_i],
  378. $attr
  379. );
  380. continue;
  381. }
  382. $this->info[$coll_i][$attr_i] = $attr;
  383. }
  384. }
  385. }
  386. // perform internal expansions and inclusions
  387. foreach ($this->info as $name => $attr) {
  388. // merge attribute collections that include others
  389. $this->performInclusions($this->info[$name]);
  390. // replace string identifiers with actual attribute objects
  391. $this->expandIdentifiers($this->info[$name], $attr_types);
  392. }
  393. }
  394. /**
  395. * Takes a reference to an attribute associative array and performs
  396. * all inclusions specified by the zero index.
  397. * @param array &$attr Reference to attribute array
  398. */
  399. public function performInclusions(&$attr)
  400. {
  401. if (!isset($attr[0])) {
  402. return;
  403. }
  404. $merge = $attr[0];
  405. $seen = array(); // recursion guard
  406. // loop through all the inclusions
  407. for ($i = 0; isset($merge[$i]); $i++) {
  408. if (isset($seen[$merge[$i]])) {
  409. continue;
  410. }
  411. $seen[$merge[$i]] = true;
  412. // foreach attribute of the inclusion, copy it over
  413. if (!isset($this->info[$merge[$i]])) {
  414. continue;
  415. }
  416. foreach ($this->info[$merge[$i]] as $key => $value) {
  417. if (isset($attr[$key])) {
  418. continue;
  419. } // also catches more inclusions
  420. $attr[$key] = $value;
  421. }
  422. if (isset($this->info[$merge[$i]][0])) {
  423. // recursion
  424. $merge = array_merge($merge, $this->info[$merge[$i]][0]);
  425. }
  426. }
  427. unset($attr[0]);
  428. }
  429. /**
  430. * Expands all string identifiers in an attribute array by replacing
  431. * them with the appropriate values inside HTMLPurifier_AttrTypes
  432. * @param array &$attr Reference to attribute array
  433. * @param HTMLPurifier_AttrTypes $attr_types HTMLPurifier_AttrTypes instance
  434. */
  435. public function expandIdentifiers(&$attr, $attr_types)
  436. {
  437. // because foreach will process new elements we add, make sure we
  438. // skip duplicates
  439. $processed = array();
  440. foreach ($attr as $def_i => $def) {
  441. // skip inclusions
  442. if ($def_i === 0) {
  443. continue;
  444. }
  445. if (isset($processed[$def_i])) {
  446. continue;
  447. }
  448. // determine whether or not attribute is required
  449. if ($required = (strpos($def_i, '*') !== false)) {
  450. // rename the definition
  451. unset($attr[$def_i]);
  452. $def_i = trim($def_i, '*');
  453. $attr[$def_i] = $def;
  454. }
  455. $processed[$def_i] = true;
  456. // if we've already got a literal object, move on
  457. if (is_object($def)) {
  458. // preserve previous required
  459. $attr[$def_i]->required = ($required || $attr[$def_i]->required);
  460. continue;
  461. }
  462. if ($def === false) {
  463. unset($attr[$def_i]);
  464. continue;
  465. }
  466. if ($t = $attr_types->get($def)) {
  467. $attr[$def_i] = $t;
  468. $attr[$def_i]->required = $required;
  469. } else {
  470. unset($attr[$def_i]);
  471. }
  472. }
  473. }
  474. }
  475. /**
  476. * Base class for all validating attribute definitions.
  477. *
  478. * This family of classes forms the core for not only HTML attribute validation,
  479. * but also any sort of string that needs to be validated or cleaned (which
  480. * means CSS properties and composite definitions are defined here too).
  481. * Besides defining (through code) what precisely makes the string valid,
  482. * subclasses are also responsible for cleaning the code if possible.
  483. */
  484. abstract class HTMLPurifier_AttrDef
  485. {
  486. /**
  487. * Tells us whether or not an HTML attribute is minimized.
  488. * Has no meaning in other contexts.
  489. * @type bool
  490. */
  491. public $minimized = false;
  492. /**
  493. * Tells us whether or not an HTML attribute is required.
  494. * Has no meaning in other contexts
  495. * @type bool
  496. */
  497. public $required = false;
  498. /**
  499. * Validates and cleans passed string according to a definition.
  500. *
  501. * @param string $string String to be validated and cleaned.
  502. * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object.
  503. * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object.
  504. */
  505. abstract public function validate($string, $config, $context);
  506. /**
  507. * Convenience method that parses a string as if it were CDATA.
  508. *
  509. * This method process a string in the manner specified at
  510. * <http://www.w3.org/TR/html4/types.html#h-6.2> by removing
  511. * leading and trailing whitespace, ignoring line feeds, and replacing
  512. * carriage returns and tabs with spaces. While most useful for HTML
  513. * attributes specified as CDATA, it can also be applied to most CSS
  514. * values.
  515. *
  516. * @note This method is not entirely standards compliant, as trim() removes
  517. * more types of whitespace than specified in the spec. In practice,
  518. * this is rarely a problem, as those extra characters usually have
  519. * already been removed by HTMLPurifier_Encoder.
  520. *
  521. * @warning This processing is inconsistent with XML's whitespace handling
  522. * as specified by section 3.3.3 and referenced XHTML 1.0 section
  523. * 4.7. However, note that we are NOT necessarily
  524. * parsing XML, thus, this behavior may still be correct. We
  525. * assume that newlines have been normalized.
  526. */
  527. public function parseCDATA($string)
  528. {
  529. $string = trim($string);
  530. $string = str_replace(array("\n", "\t", "\r"), ' ', $string);
  531. return $string;
  532. }
  533. /**
  534. * Factory method for creating this class from a string.
  535. * @param string $string String construction info
  536. * @return HTMLPurifier_AttrDef Created AttrDef object corresponding to $string
  537. */
  538. public function make($string)
  539. {
  540. // default implementation, return a flyweight of this object.
  541. // If $string has an effect on the returned object (i.e. you
  542. // need to overload this method), it is best
  543. // to clone or instantiate new copies. (Instantiation is safer.)
  544. return $this;
  545. }
  546. /**
  547. * Removes spaces from rgb(0, 0, 0) so that shorthand CSS properties work
  548. * properly. THIS IS A HACK!
  549. * @param string $string a CSS colour definition
  550. * @return string
  551. */
  552. protected function mungeRgb($string)
  553. {
  554. return preg_replace('/rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\)/', 'rgb(\1,\2,\3)', $string);
  555. }
  556. /**
  557. * Parses a possibly escaped CSS string and returns the "pure"
  558. * version of it.
  559. */
  560. protected function expandCSSEscape($string)
  561. {
  562. // flexibly parse it
  563. $ret = '';
  564. for ($i = 0, $c = strlen($string); $i < $c; $i++) {
  565. if ($string[$i] === '\\') {
  566. $i++;
  567. if ($i >= $c) {
  568. $ret .= '\\';
  569. break;
  570. }
  571. if (ctype_xdigit($string[$i])) {
  572. $code = $string[$i];
  573. for ($a = 1, $i++; $i < $c && $a < 6; $i++, $a++) {
  574. if (!ctype_xdigit($string[$i])) {
  575. break;
  576. }
  577. $code .= $string[$i];
  578. }
  579. // We have to be extremely careful when adding
  580. // new characters, to make sure we're not breaking
  581. // the encoding.
  582. $char = HTMLPurifier_Encoder::unichr(hexdec($code));
  583. if (HTMLPurifier_Encoder::cleanUTF8($char) === '') {
  584. continue;
  585. }
  586. $ret .= $char;
  587. if ($i < $c && trim($string[$i]) !== '') {
  588. $i--;
  589. }
  590. continue;
  591. }
  592. if ($string[$i] === "\n") {
  593. continue;
  594. }
  595. }
  596. $ret .= $string[$i];
  597. }
  598. return $ret;
  599. }
  600. }
  601. /**
  602. * Processes an entire attribute array for corrections needing multiple values.
  603. *
  604. * Occasionally, a certain attribute will need to be removed and popped onto
  605. * another value. Instead of creating a complex return syntax for
  606. * HTMLPurifier_AttrDef, we just pass the whole attribute array to a
  607. * specialized object and have that do the special work. That is the
  608. * family of HTMLPurifier_AttrTransform.
  609. *
  610. * An attribute transformation can be assigned to run before or after
  611. * HTMLPurifier_AttrDef validation. See HTMLPurifier_HTMLDefinition for
  612. * more details.
  613. */
  614. abstract class HTMLPurifier_AttrTransform
  615. {
  616. /**
  617. * Abstract: makes changes to the attributes dependent on multiple values.
  618. *
  619. * @param array $attr Assoc array of attributes, usually from
  620. * HTMLPurifier_Token_Tag::$attr
  621. * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object.
  622. * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object
  623. * @return array Processed attribute array.
  624. */
  625. abstract public function transform($attr, $config, $context);
  626. /**
  627. * Prepends CSS properties to the style attribute, creating the
  628. * attribute if it doesn't exist.
  629. * @param array &$attr Attribute array to process (passed by reference)
  630. * @param string $css CSS to prepend
  631. */
  632. public function prependCSS(&$attr, $css)
  633. {
  634. $attr['style'] = isset($attr['style']) ? $attr['style'] : '';
  635. $attr['style'] = $css . $attr['style'];
  636. }
  637. /**
  638. * Retrieves and removes an attribute
  639. * @param array &$attr Attribute array to process (passed by reference)
  640. * @param mixed $key Key of attribute to confiscate
  641. * @return mixed
  642. */
  643. public function confiscateAttr(&$attr, $key)
  644. {
  645. if (!isset($attr[$key])) {
  646. return null;
  647. }
  648. $value = $attr[$key];
  649. unset($attr[$key]);
  650. return $value;
  651. }
  652. }
  653. /**
  654. * Provides lookup array of attribute types to HTMLPurifier_AttrDef objects
  655. */
  656. class HTMLPurifier_AttrTypes
  657. {
  658. /**
  659. * Lookup array of attribute string identifiers to concrete implementations.
  660. * @type HTMLPurifier_AttrDef[]
  661. */
  662. protected $info = array();
  663. /**
  664. * Constructs the info array, supplying default implementations for attribute
  665. * types.
  666. */
  667. public function __construct()
  668. {
  669. // XXX This is kind of poor, since we don't actually /clone/
  670. // instances; instead, we use the supplied make() attribute. So,
  671. // the underlying class must know how to deal with arguments.
  672. // With the old implementation of Enum, that ignored its
  673. // arguments when handling a make dispatch, the IAlign
  674. // definition wouldn't work.
  675. // pseudo-types, must be instantiated via shorthand
  676. $this->info['Enum'] = new HTMLPurifier_AttrDef_Enum();
  677. $this->info['Bool'] = new HTMLPurifier_AttrDef_HTML_Bool();
  678. $this->info['CDATA'] = new HTMLPurifier_AttrDef_Text();
  679. $this->info['ID'] = new HTMLPurifier_AttrDef_HTML_ID();
  680. $this->info['Length'] = new HTMLPurifier_AttrDef_HTML_Length();
  681. $this->info['MultiLength'] = new HTMLPurifier_AttrDef_HTML_MultiLength();
  682. $this->info['NMTOKENS'] = new HTMLPurifier_AttrDef_HTML_Nmtokens();
  683. $this->info['Pixels'] = new HTMLPurifier_AttrDef_HTML_Pixels();
  684. $this->info['Text'] = new HTMLPurifier_AttrDef_Text();
  685. $this->info['URI'] = new HTMLPurifier_AttrDef_URI();
  686. $this->info['LanguageCode'] = new HTMLPurifier_AttrDef_Lang();
  687. $this->info['Color'] = new HTMLPurifier_AttrDef_HTML_Color();
  688. $this->info['IAlign'] = self::makeEnum('top,middle,bottom,left,right');
  689. $this->info['LAlign'] = self::makeEnum('top,bottom,left,right');
  690. $this->info['FrameTarget'] = new HTMLPurifier_AttrDef_HTML_FrameTarget();
  691. // unimplemented aliases
  692. $this->info['ContentType'] = new HTMLPurifier_AttrDef_Text();
  693. $this->info['ContentTypes'] = new HTMLPurifier_AttrDef_Text();
  694. $this->info['Charsets'] = new HTMLPurifier_AttrDef_Text();
  695. $this->info['Character'] = new HTMLPurifier_AttrDef_Text();
  696. // "proprietary" types
  697. $this->info['Class'] = new HTMLPurifier_AttrDef_HTML_Class();
  698. // number is really a positive integer (one or more digits)
  699. // FIXME: ^^ not always, see start and value of list items
  700. $this->info['Number'] = new HTMLPurifier_AttrDef_Integer(false, false, true);
  701. }
  702. private static function makeEnum($in)
  703. {
  704. return new HTMLPurifier_AttrDef_Clone(new HTMLPurifier_AttrDef_Enum(explode(',', $in)));
  705. }
  706. /**
  707. * Retrieves a type
  708. * @param string $type String type name
  709. * @return HTMLPurifier_AttrDef Object AttrDef for type
  710. */
  711. public function get($type)
  712. {
  713. // determine if there is any extra info tacked on
  714. if (strpos($type, '#') !== false) {
  715. list($type, $string) = explode('#', $type, 2);
  716. } else {
  717. $string = '';
  718. }
  719. if (!isset($this->info[$type])) {
  720. trigger_error('Cannot retrieve undefined attribute type ' . $type, E_USER_ERROR);
  721. return;
  722. }
  723. return $this->info[$type]->make($string);
  724. }
  725. /**
  726. * Sets a new implementation for a type
  727. * @param string $type String type name
  728. * @param HTMLPurifier_AttrDef $impl Object AttrDef for type
  729. */
  730. public function set($type, $impl)
  731. {
  732. $this->info[$type] = $impl;
  733. }
  734. }
  735. /**
  736. * Validates the attributes of a token. Doesn't manage required attributes
  737. * very well. The only reason we factored this out was because RemoveForeignElements
  738. * also needed it besides ValidateAttributes.
  739. */
  740. class HTMLPurifier_AttrValidator
  741. {
  742. /**
  743. * Validates the attributes of a token, mutating it as necessary.
  744. * that has valid tokens
  745. * @param HTMLPurifier_Token $token Token to validate.
  746. * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config
  747. * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context
  748. */
  749. public function validateToken($token, $config, $context)
  750. {
  751. $definition = $config->getHTMLDefinition();
  752. $e =& $context->get('ErrorCollector', true);
  753. // initialize IDAccumulator if necessary
  754. $ok =& $context->get('IDAccumulator', true);
  755. if (!$ok) {
  756. $id_accumulator = HTMLPurifier_IDAccumulator::build($config, $context);
  757. $context->register('IDAccumulator', $id_accumulator);
  758. }
  759. // initialize CurrentToken if necessary
  760. $current_token =& $context->get('CurrentToken', true);
  761. if (!$current_token) {
  762. $context->register('CurrentToken', $token);
  763. }
  764. if (!$token instanceof HTMLPurifier_Token_Start &&
  765. !$token instanceof HTMLPurifier_Token_Empty
  766. ) {
  767. return;
  768. }
  769. // create alias to global definition array, see also $defs
  770. // DEFINITION CALL
  771. $d_defs = $definition->info_global_attr;
  772. // don't update token until the very end, to ensure an atomic update
  773. $attr = $token->attr;
  774. // do global transformations (pre)
  775. // nothing currently utilizes this
  776. foreach ($definition->info_attr_transform_pre as $transform) {
  777. $attr = $transform->transform($o = $attr, $config, $context);
  778. if ($e) {
  779. if ($attr != $o) {
  780. $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
  781. }
  782. }
  783. }
  784. // do local transformations only applicable to this element (pre)
  785. // ex. <p align="right"> to <p style="text-align:right;">
  786. foreach ($definition->info[$token->name]->attr_transform_pre as $transform) {
  787. $attr = $transform->transform($o = $attr, $config, $context);
  788. if ($e) {
  789. if ($attr != $o) {
  790. $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
  791. }
  792. }
  793. }
  794. // create alias to this element's attribute definition array, see
  795. // also $d_defs (global attribute definition array)
  796. // DEFINITION CALL
  797. $defs = $definition->info[$token->name]->attr;
  798. $attr_key = false;
  799. $context->register('CurrentAttr', $attr_key);
  800. // iterate through all the attribute keypairs
  801. // Watch out for name collisions: $key has previously been used
  802. foreach ($attr as $attr_key => $value) {
  803. // call the definition
  804. if (isset($defs[$attr_key])) {
  805. // there is a local definition defined
  806. if ($defs[$attr_key] === false) {
  807. // We've explicitly been told not to allow this element.
  808. // This is usually when there's a global definition
  809. // that must be overridden.
  810. // Theoretically speaking, we could have a
  811. // AttrDef_DenyAll, but this is faster!
  812. $result = false;
  813. } else {
  814. // validate according to the element's definition
  815. $result = $defs[$attr_key]->validate(
  816. $value,
  817. $config,
  818. $context
  819. );
  820. }
  821. } elseif (isset($d_defs[$attr_key])) {
  822. // there is a global definition defined, validate according
  823. // to the global definition
  824. $result = $d_defs[$attr_key]->validate(
  825. $value,
  826. $config,
  827. $context
  828. );
  829. } else {
  830. // system never heard of the attribute? DELETE!
  831. $result = false;
  832. }
  833. // put the results into effect
  834. if ($result === false || $result === null) {
  835. // this is a generic error message that should replaced
  836. // with more specific ones when possible
  837. if ($e) {
  838. $e->send(E_ERROR, 'AttrValidator: Attribute removed');
  839. }
  840. // remove the attribute
  841. unset($attr[$attr_key]);
  842. } elseif (is_string($result)) {
  843. // generally, if a substitution is happening, there
  844. // was some sort of implicit correction going on. We'll
  845. // delegate it to the attribute classes to say exactly what.
  846. // simple substitution
  847. $attr[$attr_key] = $result;
  848. } else {
  849. // nothing happens
  850. }
  851. // we'd also want slightly more complicated substitution
  852. // involving an array as the return value,
  853. // although we're not sure how colliding attributes would
  854. // resolve (certain ones would be completely overriden,
  855. // others would prepend themselves).
  856. }
  857. $context->destroy('CurrentAttr');
  858. // post transforms
  859. // global (error reporting untested)
  860. foreach ($definition->info_attr_transform_post as $transform) {
  861. $attr = $transform->transform($o = $attr, $config, $context);
  862. if ($e) {
  863. if ($attr != $o) {
  864. $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
  865. }
  866. }
  867. }
  868. // local (error reporting untested)
  869. foreach ($definition->info[$token->name]->attr_transform_post as $transform) {
  870. $attr = $transform->transform($o = $attr, $config, $context);
  871. if ($e) {
  872. if ($attr != $o) {
  873. $e->send(E_NOTICE, 'AttrValidator: Attributes transformed', $o, $attr);
  874. }
  875. }
  876. }
  877. $token->attr = $attr;
  878. // destroy CurrentToken if we made it ourselves
  879. if (!$current_token) {
  880. $context->destroy('CurrentToken');
  881. }
  882. }
  883. }
  884. // constants are slow, so we use as few as possible
  885. if (!defined('HTMLPURIFIER_PREFIX')) {
  886. define('HTMLPURIFIER_PREFIX', dirname(__FILE__) . '/standalone');
  887. set_include_path(HTMLPURIFIER_PREFIX . PATH_SEPARATOR . get_include_path());
  888. }
  889. // accomodations for versions earlier than 5.0.2
  890. // borrowed from PHP_Compat, LGPL licensed, by Aidan Lister <aidan@php.net>
  891. if (!defined('PHP_EOL')) {
  892. switch (strtoupper(substr(PHP_OS, 0, 3))) {
  893. case 'WIN':
  894. define('PHP_EOL', "\r\n");
  895. break;
  896. case 'DAR':
  897. define('PHP_EOL', "\r");
  898. break;
  899. default:
  900. define('PHP_EOL', "\n");
  901. }
  902. }
  903. /**
  904. * Bootstrap class that contains meta-functionality for HTML Purifier such as
  905. * the autoload function.
  906. *
  907. * @note
  908. * This class may be used without any other files from HTML Purifier.
  909. */
  910. class HTMLPurifier_Bootstrap
  911. {
  912. /**
  913. * Autoload function for HTML Purifier
  914. * @param string $class Class to load
  915. * @return bool
  916. */
  917. public static function autoload($class)
  918. {
  919. $file = HTMLPurifier_Bootstrap::getPath($class);
  920. if (!$file) {
  921. return false;
  922. }
  923. // Technically speaking, it should be ok and more efficient to
  924. // just do 'require', but Antonio Parraga reports that with
  925. // Zend extensions such as Zend debugger and APC, this invariant
  926. // may be broken. Since we have efficient alternatives, pay
  927. // the cost here and avoid the bug.
  928. require_once HTMLPURIFIER_PREFIX . '/' . $file;
  929. return true;
  930. }
  931. /**
  932. * Returns the path for a specific class.
  933. * @param string $class Class path to get
  934. * @return string
  935. */
  936. public static function getPath($class)
  937. {
  938. if (strncmp('HTMLPurifier', $class, 12) !== 0) {
  939. return false;
  940. }
  941. // Custom implementations
  942. if (strncmp('HTMLPurifier_Language_', $class, 22) === 0) {
  943. $code = str_replace('_', '-', substr($class, 22));
  944. $file = 'HTMLPurifier/Language/classes/' . $code . '.php';
  945. } else {
  946. $file = str_replace('_', '/', $class) . '.php';
  947. }
  948. if (!file_exists(HTMLPURIFIER_PREFIX . '/' . $file)) {
  949. return false;
  950. }
  951. return $file;
  952. }
  953. /**
  954. * "Pre-registers" our autoloader on the SPL stack.
  955. */
  956. public static function registerAutoload()
  957. {
  958. $autoload = array('HTMLPurifier_Bootstrap', 'autoload');
  959. if (($funcs = spl_autoload_functions()) === false) {
  960. spl_autoload_register($autoload);
  961. } elseif (function_exists('spl_autoload_unregister')) {
  962. if (version_compare(PHP_VERSION, '5.3.0', '>=')) {
  963. // prepend flag exists, no need for shenanigans
  964. spl_autoload_register($autoload, true, true);
  965. } else {
  966. $buggy = version_compare(PHP_VERSION, '5.2.11', '<');
  967. $compat = version_compare(PHP_VERSION, '5.1.2', '<=') &&
  968. version_compare(PHP_VERSION, '5.1.0', '>=');
  969. foreach ($funcs as $func) {
  970. if ($buggy && is_array($func)) {
  971. // :TRICKY: There are some compatibility issues and some
  972. // places where we need to error out
  973. $reflector = new ReflectionMethod($func[0], $func[1]);
  974. if (!$reflector->isStatic()) {
  975. throw new Exception(
  976. 'HTML Purifier autoloader registrar is not compatible
  977. with non-static object methods due to PHP Bug #44144;
  978. Please do not use HTMLPurifier.autoload.php (or any
  979. file that includes this file); instead, place the code:
  980. spl_autoload_register(array(\'HTMLPurifier_Bootstrap\', \'autoload\'))
  981. after your own autoloaders.'
  982. );
  983. }
  984. // Suprisingly, spl_autoload_register supports the
  985. // Class::staticMethod callback format, although call_user_func doesn't
  986. if ($compat) {
  987. $func = implode('::', $func);
  988. }
  989. }
  990. spl_autoload_unregister($func);
  991. }
  992. spl_autoload_register($autoload);
  993. foreach ($funcs as $func) {
  994. spl_autoload_register($func);
  995. }
  996. }
  997. }
  998. }
  999. }
  1000. /**
  1001. * Super-class for definition datatype objects, implements serialization
  1002. * functions for the class.
  1003. */
  1004. abstract class HTMLPurifier_Definition
  1005. {
  1006. /**
  1007. * Has setup() been called yet?
  1008. * @type bool
  1009. */
  1010. public $setup = false;
  1011. /**
  1012. * If true, write out the final definition object to the cache after
  1013. * setup. This will be true only if all invocations to get a raw
  1014. * definition object are also optimized. This does not cause file
  1015. * system thrashing because on subsequent calls the cached object
  1016. * is used and any writes to the raw definition object are short
  1017. * circuited. See enduser-customize.html for the high-level
  1018. * picture.
  1019. * @type bool
  1020. */
  1021. public $optimized = null;
  1022. /**
  1023. * What type of definition is it?
  1024. * @type string
  1025. */
  1026. public $type;
  1027. /**
  1028. * Sets up the definition object into the final form, something
  1029. * not done by the constructor
  1030. * @param HTMLPurifier_Config $config
  1031. */
  1032. abstract protected function doSetup($config);
  1033. /**
  1034. * Setup function that aborts if already setup
  1035. * @param HTMLPurifier_Config $config
  1036. */
  1037. public function setup($config)
  1038. {
  1039. if ($this->setup) {
  1040. return;
  1041. }
  1042. $this->setup = true;
  1043. $this->doSetup($config);
  1044. }
  1045. }
  1046. /**
  1047. * Defines allowed CSS attributes and what their values are.
  1048. * @see HTMLPurifier_HTMLDefinition
  1049. */
  1050. class HTMLPurifier_CSSDefinition extends HTMLPurifier_Definition
  1051. {
  1052. public $type = 'CSS';
  1053. /**
  1054. * Assoc array of attribute name to definition object.
  1055. * @type HTMLPurifier_AttrDef[]
  1056. */
  1057. public $info = array();
  1058. /**
  1059. * Constructs the info array. The meat of this class.
  1060. * @param HTMLPurifier_Config $config
  1061. */
  1062. protected function doSetup($config)
  1063. {
  1064. $this->info['text-align'] = new HTMLPurifier_AttrDef_Enum(
  1065. array('left', 'right', 'center', 'justify'),
  1066. false
  1067. );
  1068. $border_style =
  1069. $this->info['border-bottom-style'] =
  1070. $this->info['border-right-style'] =
  1071. $this->info['border-left-style'] =
  1072. $this->info['border-top-style'] = new HTMLPurifier_AttrDef_Enum(
  1073. array(
  1074. 'none',
  1075. 'hidden',
  1076. 'dotted',
  1077. 'dashed',
  1078. 'solid',
  1079. 'double',
  1080. 'groove',
  1081. 'ridge',
  1082. 'inset',
  1083. 'outset'
  1084. ),
  1085. false
  1086. );
  1087. $this->info['border-style'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_style);
  1088. $this->info['clear'] = new HTMLPurifier_AttrDef_Enum(
  1089. array('none', 'left', 'right', 'both'),
  1090. false
  1091. );
  1092. $this->info['float'] = new HTMLPurifier_AttrDef_Enum(
  1093. array('none', 'left', 'right'),
  1094. false
  1095. );
  1096. $this->info['font-style'] = new HTMLPurifier_AttrDef_Enum(
  1097. array('normal', 'italic', 'oblique'),
  1098. false
  1099. );
  1100. $this->info['font-variant'] = new HTMLPurifier_AttrDef_Enum(
  1101. array('normal', 'small-caps'),
  1102. false
  1103. );
  1104. $uri_or_none = new HTMLPurifier_AttrDef_CSS_Composite(
  1105. array(
  1106. new HTMLPurifier_AttrDef_Enum(array('none')),
  1107. new HTMLPurifier_AttrDef_CSS_URI()
  1108. )
  1109. );
  1110. $this->info['list-style-position'] = new HTMLPurifier_AttrDef_Enum(
  1111. array('inside', 'outside'),
  1112. false
  1113. );
  1114. $this->info['list-style-type'] = new HTMLPurifier_AttrDef_Enum(
  1115. array(
  1116. 'disc',
  1117. 'circle',
  1118. 'square',
  1119. 'decimal',
  1120. 'lower-roman',
  1121. 'upper-roman',
  1122. 'lower-alpha',
  1123. 'upper-alpha',
  1124. 'none'
  1125. ),
  1126. false
  1127. );
  1128. $this->info['list-style-image'] = $uri_or_none;
  1129. $this->info['list-style'] = new HTMLPurifier_AttrDef_CSS_ListStyle($config);
  1130. $this->info['text-transform'] = new HTMLPurifier_AttrDef_Enum(
  1131. array('capitalize', 'uppercase', 'lowercase', 'none'),
  1132. false
  1133. );
  1134. $this->info['color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1135. $this->info['background-image'] = $uri_or_none;
  1136. $this->info['background-repeat'] = new HTMLPurifier_AttrDef_Enum(
  1137. array('repeat', 'repeat-x', 'repeat-y', 'no-repeat')
  1138. );
  1139. $this->info['background-attachment'] = new HTMLPurifier_AttrDef_Enum(
  1140. array('scroll', 'fixed')
  1141. );
  1142. $this->info['background-position'] = new HTMLPurifier_AttrDef_CSS_BackgroundPosition();
  1143. $border_color =
  1144. $this->info['border-top-color'] =
  1145. $this->info['border-bottom-color'] =
  1146. $this->info['border-left-color'] =
  1147. $this->info['border-right-color'] =
  1148. $this->info['background-color'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1149. array(
  1150. new HTMLPurifier_AttrDef_Enum(array('transparent')),
  1151. new HTMLPurifier_AttrDef_CSS_Color()
  1152. )
  1153. );
  1154. $this->info['background'] = new HTMLPurifier_AttrDef_CSS_Background($config);
  1155. $this->info['border-color'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_color);
  1156. $border_width =
  1157. $this->info['border-top-width'] =
  1158. $this->info['border-bottom-width'] =
  1159. $this->info['border-left-width'] =
  1160. $this->info['border-right-width'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1161. array(
  1162. new HTMLPurifier_AttrDef_Enum(array('thin', 'medium', 'thick')),
  1163. new HTMLPurifier_AttrDef_CSS_Length('0') //disallow negative
  1164. )
  1165. );
  1166. $this->info['border-width'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_width);
  1167. $this->info['letter-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1168. array(
  1169. new HTMLPurifier_AttrDef_Enum(array('normal')),
  1170. new HTMLPurifier_AttrDef_CSS_Length()
  1171. )
  1172. );
  1173. $this->info['word-spacing'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1174. array(
  1175. new HTMLPurifier_AttrDef_Enum(array('normal')),
  1176. new HTMLPurifier_AttrDef_CSS_Length()
  1177. )
  1178. );
  1179. $this->info['font-size'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1180. array(
  1181. new HTMLPurifier_AttrDef_Enum(
  1182. array(
  1183. 'xx-small',
  1184. 'x-small',
  1185. 'small',
  1186. 'medium',
  1187. 'large',
  1188. 'x-large',
  1189. 'xx-large',
  1190. 'larger',
  1191. 'smaller'
  1192. )
  1193. ),
  1194. new HTMLPurifier_AttrDef_CSS_Percentage(),
  1195. new HTMLPurifier_AttrDef_CSS_Length()
  1196. )
  1197. );
  1198. $this->info['line-height'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1199. array(
  1200. new HTMLPurifier_AttrDef_Enum(array('normal')),
  1201. new HTMLPurifier_AttrDef_CSS_Number(true), // no negatives
  1202. new HTMLPurifier_AttrDef_CSS_Length('0'),
  1203. new HTMLPurifier_AttrDef_CSS_Percentage(true)
  1204. )
  1205. );
  1206. $margin =
  1207. $this->info['margin-top'] =
  1208. $this->info['margin-bottom'] =
  1209. $this->info['margin-left'] =
  1210. $this->info['margin-right'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1211. array(
  1212. new HTMLPurifier_AttrDef_CSS_Length(),
  1213. new HTMLPurifier_AttrDef_CSS_Percentage(),
  1214. new HTMLPurifier_AttrDef_Enum(array('auto'))
  1215. )
  1216. );
  1217. $this->info['margin'] = new HTMLPurifier_AttrDef_CSS_Multiple($margin);
  1218. // non-negative
  1219. $padding =
  1220. $this->info['padding-top'] =
  1221. $this->info['padding-bottom'] =
  1222. $this->info['padding-left'] =
  1223. $this->info['padding-right'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1224. array(
  1225. new HTMLPurifier_AttrDef_CSS_Length('0'),
  1226. new HTMLPurifier_AttrDef_CSS_Percentage(true)
  1227. )
  1228. );
  1229. $this->info['padding'] = new HTMLPurifier_AttrDef_CSS_Multiple($padding);
  1230. $this->info['text-indent'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1231. array(
  1232. new HTMLPurifier_AttrDef_CSS_Length(),
  1233. new HTMLPurifier_AttrDef_CSS_Percentage()
  1234. )
  1235. );
  1236. $trusted_wh = new HTMLPurifier_AttrDef_CSS_Composite(
  1237. array(
  1238. new HTMLPurifier_AttrDef_CSS_Length('0'),
  1239. new HTMLPurifier_AttrDef_CSS_Percentage(true),
  1240. new HTMLPurifier_AttrDef_Enum(array('auto'))
  1241. )
  1242. );
  1243. $max = $config->get('CSS.MaxImgLength');
  1244. $this->info['width'] =
  1245. $this->info['height'] =
  1246. $max === null ?
  1247. $trusted_wh :
  1248. new HTMLPurifier_AttrDef_Switch(
  1249. 'img',
  1250. // For img tags:
  1251. new HTMLPurifier_AttrDef_CSS_Composite(
  1252. array(
  1253. new HTMLPurifier_AttrDef_CSS_Length('0', $max),
  1254. new HTMLPurifier_AttrDef_Enum(array('auto'))
  1255. )
  1256. ),
  1257. // For everyone else:
  1258. $trusted_wh
  1259. );
  1260. $this->info['text-decoration'] = new HTMLPurifier_AttrDef_CSS_TextDecoration();
  1261. $this->info['font-family'] = new HTMLPurifier_AttrDef_CSS_FontFamily();
  1262. // this could use specialized code
  1263. $this->info['font-weight'] = new HTMLPurifier_AttrDef_Enum(
  1264. array(
  1265. 'normal',
  1266. 'bold',
  1267. 'bolder',
  1268. 'lighter',
  1269. '100',
  1270. '200',
  1271. '300',
  1272. '400',
  1273. '500',
  1274. '600',
  1275. '700',
  1276. '800',
  1277. '900'
  1278. ),
  1279. false
  1280. );
  1281. // MUST be called after other font properties, as it references
  1282. // a CSSDefinition object
  1283. $this->info['font'] = new HTMLPurifier_AttrDef_CSS_Font($config);
  1284. // same here
  1285. $this->info['border'] =
  1286. $this->info['border-bottom'] =
  1287. $this->info['border-top'] =
  1288. $this->info['border-left'] =
  1289. $this->info['border-right'] = new HTMLPurifier_AttrDef_CSS_Border($config);
  1290. $this->info['border-collapse'] = new HTMLPurifier_AttrDef_Enum(
  1291. array('collapse', 'separate')
  1292. );
  1293. $this->info['caption-side'] = new HTMLPurifier_AttrDef_Enum(
  1294. array('top', 'bottom')
  1295. );
  1296. $this->info['table-layout'] = new HTMLPurifier_AttrDef_Enum(
  1297. array('auto', 'fixed')
  1298. );
  1299. $this->info['vertical-align'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1300. array(
  1301. new HTMLPurifier_AttrDef_Enum(
  1302. array(
  1303. 'baseline',
  1304. 'sub',
  1305. 'super',
  1306. 'top',
  1307. 'text-top',
  1308. 'middle',
  1309. 'bottom',
  1310. 'text-bottom'
  1311. )
  1312. ),
  1313. new HTMLPurifier_AttrDef_CSS_Length(),
  1314. new HTMLPurifier_AttrDef_CSS_Percentage()
  1315. )
  1316. );
  1317. $this->info['border-spacing'] = new HTMLPurifier_AttrDef_CSS_Multiple(new HTMLPurifier_AttrDef_CSS_Length(), 2);
  1318. // These CSS properties don't work on many browsers, but we live
  1319. // in THE FUTURE!
  1320. $this->info['white-space'] = new HTMLPurifier_AttrDef_Enum(
  1321. array('nowrap', 'normal', 'pre', 'pre-wrap', 'pre-line')
  1322. );
  1323. if ($config->get('CSS.Proprietary')) {
  1324. $this->doSetupProprietary($config);
  1325. }
  1326. if ($config->get('CSS.AllowTricky')) {
  1327. $this->doSetupTricky($config);
  1328. }
  1329. if ($config->get('CSS.Trusted')) {
  1330. $this->doSetupTrusted($config);
  1331. }
  1332. $allow_important = $config->get('CSS.AllowImportant');
  1333. // wrap all attr-defs with decorator that handles !important
  1334. foreach ($this->info as $k => $v) {
  1335. $this->info[$k] = new HTMLPurifier_AttrDef_CSS_ImportantDecorator($v, $allow_important);
  1336. }
  1337. $this->setupConfigStuff($config);
  1338. }
  1339. /**
  1340. * @param HTMLPurifier_Config $config
  1341. */
  1342. protected function doSetupProprietary($config)
  1343. {
  1344. // Internet Explorer only scrollbar colors
  1345. $this->info['scrollbar-arrow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1346. $this->info['scrollbar-base-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1347. $this->info['scrollbar-darkshadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1348. $this->info['scrollbar-face-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1349. $this->info['scrollbar-highlight-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1350. $this->info['scrollbar-shadow-color'] = new HTMLPurifier_AttrDef_CSS_Color();
  1351. // vendor specific prefixes of opacity
  1352. $this->info['-moz-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
  1353. $this->info['-khtml-opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
  1354. // only opacity, for now
  1355. $this->info['filter'] = new HTMLPurifier_AttrDef_CSS_Filter();
  1356. // more CSS3
  1357. $this->info['page-break-after'] =
  1358. $this->info['page-break-before'] = new HTMLPurifier_AttrDef_Enum(
  1359. array(
  1360. 'auto',
  1361. 'always',
  1362. 'avoid',
  1363. 'left',
  1364. 'right'
  1365. )
  1366. );
  1367. $this->info['page-break-inside'] = new HTMLPurifier_AttrDef_Enum(array('auto', 'avoid'));
  1368. $border_radius = new HTMLPurifier_AttrDef_CSS_Composite(
  1369. array(
  1370. new HTMLPurifier_AttrDef_CSS_Percentage(true), // disallow negative
  1371. new HTMLPurifier_AttrDef_CSS_Length('0') // disallow negative
  1372. ));
  1373. $this->info['border-top-left-radius'] =
  1374. $this->info['border-top-right-radius'] =
  1375. $this->info['border-bottom-right-radius'] =
  1376. $this->info['border-bottom-left-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 2);
  1377. // TODO: support SLASH syntax
  1378. $this->info['border-radius'] = new HTMLPurifier_AttrDef_CSS_Multiple($border_radius, 4);
  1379. }
  1380. /**
  1381. * @param HTMLPurifier_Config $config
  1382. */
  1383. protected function doSetupTricky($config)
  1384. {
  1385. $this->info['display'] = new HTMLPurifier_AttrDef_Enum(
  1386. array(
  1387. 'inline',
  1388. 'block',
  1389. 'list-item',
  1390. 'run-in',
  1391. 'compact',
  1392. 'marker',
  1393. 'table',
  1394. 'inline-block',
  1395. 'inline-table',
  1396. 'table-row-group',
  1397. 'table-header-group',
  1398. 'table-footer-group',
  1399. 'table-row',
  1400. 'table-column-group',
  1401. 'table-column',
  1402. 'table-cell',
  1403. 'table-caption',
  1404. 'none'
  1405. )
  1406. );
  1407. $this->info['visibility'] = new HTMLPurifier_AttrDef_Enum(
  1408. array('visible', 'hidden', 'collapse')
  1409. );
  1410. $this->info['overflow'] = new HTMLPurifier_AttrDef_Enum(array('visible', 'hidden', 'auto', 'scroll'));
  1411. $this->info['opacity'] = new HTMLPurifier_AttrDef_CSS_AlphaValue();
  1412. }
  1413. /**
  1414. * @param HTMLPurifier_Config $config
  1415. */
  1416. protected function doSetupTrusted($config)
  1417. {
  1418. $this->info['position'] = new HTMLPurifier_AttrDef_Enum(
  1419. array('static', 'relative', 'absolute', 'fixed')
  1420. );
  1421. $this->info['top'] =
  1422. $this->info['left'] =
  1423. $this->info['right'] =
  1424. $this->info['bottom'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1425. array(
  1426. new HTMLPurifier_AttrDef_CSS_Length(),
  1427. new HTMLPurifier_AttrDef_CSS_Percentage(),
  1428. new HTMLPurifier_AttrDef_Enum(array('auto')),
  1429. )
  1430. );
  1431. $this->info['z-index'] = new HTMLPurifier_AttrDef_CSS_Composite(
  1432. array(
  1433. new HTMLPurifier_AttrDef_Integer(),
  1434. new HTMLPurifier_AttrDef_Enum(array('auto')),
  1435. )
  1436. );
  1437. }
  1438. /**
  1439. * Performs extra config-based processing. Based off of
  1440. * HTMLPurifier_HTMLDefinition.
  1441. * @param HTMLPurifier_Config $config
  1442. * @todo Refactor duplicate elements into common class (probably using
  1443. * composition, not inheritance).
  1444. */
  1445. protected function setupConfigStuff($config)
  1446. {
  1447. // setup allowed elements
  1448. $support = "(for information on implementing this, see the " .
  1449. "support forums) ";
  1450. $allowed_properties = $config->get('CSS.AllowedProperties');
  1451. if ($allowed_properties !== null) {
  1452. foreach ($this->info as $name => $d) {
  1453. if (!isset($allowed_properties[$name])) {
  1454. unset($this->info[$name]);
  1455. }
  1456. unset($allowed_properties[$name]);
  1457. }
  1458. // emit errors
  1459. foreach ($allowed_properties as $name => $d) {
  1460. // :TODO: Is this htmlspecialchars() call really necessary?
  1461. $name = htmlspecialchars($name);
  1462. trigger_error("Style attribute '$name' is not supported $support", E_USER_WARNING);
  1463. }
  1464. }
  1465. $forbidden_properties = $config->get('CSS.ForbiddenProperties');
  1466. if ($forbidden_properties !== null) {
  1467. foreach ($this->info as $name => $d) {
  1468. if (isset($forbidden_properties[$name])) {
  1469. unset($this->info[$name]);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. }
  1475. /**
  1476. * Defines allowed child nodes and validates nodes against it.
  1477. */
  1478. abstract class HTMLPurifier_ChildDef
  1479. {
  1480. /**
  1481. * Type of child definition, usually right-most part of class name lowercase.
  1482. * Used occasionally in terms of context.
  1483. * @type string
  1484. */
  1485. public $type;
  1486. /**
  1487. * Indicates whether or not an empty array of children is okay.
  1488. *
  1489. * This is necessary for redundant checking when changes affecting
  1490. * a child node may cause a parent node to now be disallowed.
  1491. * @type bool
  1492. */
  1493. public $allow_empty;
  1494. /**
  1495. * Lookup array of all elements that this definition could possibly allow.
  1496. * @type array
  1497. */
  1498. public $elements = array();
  1499. /**
  1500. * Get lookup of tag names that should not close this element automatically.
  1501. * All other elements will do so.
  1502. * @param HTMLPurifier_Config $config HTMLPurifier_Config object
  1503. * @return array
  1504. */
  1505. public function getAllowedElements($config)
  1506. {
  1507. return $this->elements;
  1508. }
  1509. /**
  1510. * Validates nodes according to definition and returns modification.
  1511. *
  1512. * @param HTMLPurifier_Node[] $children Array of HTMLPurifier_Node
  1513. * @param HTMLPurifier_Config $config HTMLPurifier_Config object
  1514. * @param HTMLPurifier_Context $context HTMLPurifier_Context object
  1515. * @return bool|array true to leave nodes as is, false to remove parent node, array of replacement children
  1516. */
  1517. abstract public function validateChildren($children, $config, $context);
  1518. }
  1519. /**
  1520. * Configuration object that triggers customizable behavior.
  1521. *
  1522. * @warning This class is strongly defined: that means that the class
  1523. * will fail if an undefined directive is retrieved or set.
  1524. *
  1525. * @note Many classes that could (although many times don't) use the
  1526. * configuration object make it a mandatory parameter. This is
  1527. * because a configuration object should always be forwarded,
  1528. * otherwise, you run the risk of missing a parameter and then
  1529. * being stumped when a configuration directive doesn't work.
  1530. *
  1531. * @todo Reconsider some of the public member variables
  1532. */
  1533. class HTMLPurifier_Config
  1534. {
  1535. /**
  1536. * HTML Purifier's version
  1537. * @type string
  1538. */
  1539. public $version = '4.8.0';
  1540. /**
  1541. * Whether or not to automatically finalize
  1542. * the object if a read operation is done.
  1543. * @type bool
  1544. */
  1545. public $autoFinalize = true;
  1546. // protected member variables
  1547. /**
  1548. * Namespace indexed array of serials for specific namespaces.
  1549. * @see getSerial() for more info.
  1550. * @type string[]
  1551. */
  1552. protected $serials = array();
  1553. /**
  1554. * Serial for entire configuration object.
  1555. * @type string
  1556. */
  1557. protected $serial;
  1558. /**
  1559. * Parser for variables.
  1560. * @type HTMLPurifier_VarParser_Flexible
  1561. */
  1562. protected $parser = null;
  1563. /**
  1564. * Reference HTMLPurifier_ConfigSchema for value checking.
  1565. * @type HTMLPurifier_ConfigSchema
  1566. * @note This is public for introspective purposes. Please don't
  1567. * abuse!
  1568. */
  1569. public $def;
  1570. /**
  1571. * Indexed array of definitions.
  1572. * @type HTMLPurifier_Definition[]
  1573. */
  1574. protected $definitions;
  1575. /**
  1576. * Whether or not config is finalized.
  1577. * @type bool
  1578. */
  1579. protected $finalized = false;
  1580. /**
  1581. * Property list containing configuration directives.
  1582. * @type array
  1583. */
  1584. protected $plist;
  1585. /**
  1586. * Whether or not a set is taking place due to an alias lookup.
  1587. * @type bool
  1588. */
  1589. private $aliasMode;
  1590. /**
  1591. * Set to false if you do not want line and file numbers in errors.
  1592. * (useful when unit testing). This will also compress some errors
  1593. * and exceptions.
  1594. * @type bool
  1595. */
  1596. public $chatty = true;
  1597. /**
  1598. * Current lock; only gets to this namespace are allowed.
  1599. * @type string
  1600. */
  1601. private $lock;
  1602. /**
  1603. * Constructor
  1604. * @param HTMLPurifier_ConfigSchema $definition ConfigSchema that defines
  1605. * what directives are allowed.
  1606. * @param HTMLPurifier_PropertyList $parent
  1607. */
  1608. public function __construct($definition, $parent = null)
  1609. {
  1610. $parent = $parent ? $parent : $definition->defaultPlist;
  1611. $this->plist = new HTMLPurifier_PropertyList($parent);
  1612. $this->def = $definition; // keep a copy around for checking
  1613. $this->parser = new HTMLPurifier_VarParser_Flexible();
  1614. }
  1615. /**
  1616. * Convenience constructor that creates a config object based on a mixed var
  1617. * @param mixed $config Variable that defines the state of the config
  1618. * object. Can be: a HTMLPurifier_Config() object,
  1619. * an array of directives based on loadArray(),
  1620. * or a string filename of an ini file.
  1621. * @param HTMLPurifier_ConfigSchema $schema Schema object
  1622. * @return HTMLPurifier_Config Configured object
  1623. */
  1624. public static function create($config, $schema = null)
  1625. {
  1626. if ($config instanceof HTMLPurifier_Config) {
  1627. // pass-through
  1628. return $config;
  1629. }
  1630. if (!$schema) {
  1631. $ret = HTMLPurifier_Config::createDefault();
  1632. } else {
  1633. $ret = new HTMLPurifier_Config($schema);
  1634. }
  1635. if (is_string($config)) {
  1636. $ret->loadIni($config);
  1637. } elseif (is_array($config)) $ret->loadArray($config);
  1638. return $ret;
  1639. }
  1640. /**
  1641. * Creates a new config object that inherits from a previous one.
  1642. * @param HTMLPurifier_Config $config Configuration object to inherit from.
  1643. * @return HTMLPurifier_Config object with $config as its parent.
  1644. */
  1645. public static function inherit(HTMLPurifier_Config $config)
  1646. {
  1647. return new HTMLPurifier_Config($config->def, $config->plist);
  1648. }
  1649. /**
  1650. * Convenience constructor that creates a default configuration object.
  1651. * @return HTMLPurifier_Config default object.
  1652. */
  1653. public static function createDefault()
  1654. {
  1655. $definition = HTMLPurifier_ConfigSchema::instance();
  1656. $config = new HTMLPurifier_Config($definition);
  1657. return $config;
  1658. }
  1659. /**
  1660. * Retrieves a value from the configuration.
  1661. *
  1662. * @param string $key String key
  1663. * @param mixed $a
  1664. *
  1665. * @return mixed
  1666. */
  1667. public function get($key, $a = null)
  1668. {
  1669. if ($a !== null) {
  1670. $this->triggerError(
  1671. "Using deprecated API: use \$config->get('$key.$a') instead",
  1672. E_USER_WARNING
  1673. );
  1674. $key = "$key.$a";
  1675. }
  1676. if (!$this->finalized) {
  1677. $this->autoFinalize();
  1678. }
  1679. if (!isset($this->def->info[$key])) {
  1680. // can't add % due to SimpleTest bug
  1681. $this->triggerError(
  1682. 'Cannot retrieve value of undefined directive ' . htmlspecialchars($key),
  1683. E_USER_WARNING
  1684. );
  1685. return;
  1686. }
  1687. if (isset($this->def->info[$key]->isAlias)) {
  1688. $d = $this->def->info[$key];
  1689. $this->triggerError(
  1690. 'Cannot get value from aliased directive, use real name ' . $d->key,
  1691. E_USER_ERROR
  1692. );
  1693. return;
  1694. }
  1695. if ($this->lock) {
  1696. list($ns) = explode('.', $key);
  1697. if ($ns !== $this->lock) {
  1698. $this->triggerError(
  1699. 'Cannot get value of namespace ' . $ns . ' when lock for ' .
  1700. $this->lock .
  1701. ' is active, this probably indicates a Definition setup method ' .
  1702. 'is accessing directives that are not within its namespace',
  1703. E_USER_ERROR
  1704. );
  1705. return;
  1706. }
  1707. }
  1708. return $this->plist->get($key);
  1709. }
  1710. /**
  1711. * Retrieves an array of directives to values from a given namespace
  1712. *
  1713. * @param string $namespace String namespace
  1714. *
  1715. * @return array
  1716. */
  1717. public function getBatch($namespace)
  1718. {
  1719. if (!$this->finalized) {
  1720. $this->autoFinalize();
  1721. }
  1722. $full = $this->getAll();
  1723. if (!isset($full[$namespace])) {
  1724. $this->triggerError(
  1725. 'Cannot retrieve undefined namespace ' .
  1726. htmlspecialchars($namespace),
  1727. E_USER_WARNING
  1728. );
  1729. return;
  1730. }
  1731. return $full[$namespace];
  1732. }
  1733. /**
  1734. * Returns a SHA-1 signature of a segment of the configuration object
  1735. * that uniquely identifies that particular configuration
  1736. *
  1737. * @param string $namespace Namespace to get serial for
  1738. *
  1739. * @return string
  1740. * @note Revision is handled specially and is removed from the batch
  1741. * before processing!
  1742. */
  1743. public function getBatchSerial($namespace)
  1744. {
  1745. if (empty($this->serials[$namespace])) {
  1746. $batch = $this->getBatch($namespace);
  1747. unset($batch['DefinitionRev']);
  1748. $this->serials[$namespace] = sha1(serialize($batch));
  1749. }
  1750. return $this->serials[$namespace];
  1751. }
  1752. /**
  1753. * Returns a SHA-1 signature for the entire configuration object
  1754. * that uniquely identifies that particular configuration
  1755. *
  1756. * @return string
  1757. */
  1758. public function getSerial()
  1759. {
  1760. if (empty($this->serial)) {
  1761. $this->serial = sha1(serialize($this->getAll()));
  1762. }
  1763. return $this->serial;
  1764. }
  1765. /**
  1766. * Retrieves all directives, organized by namespace
  1767. *
  1768. * @warning This is a pretty inefficient function, avoid if you can
  1769. */
  1770. public function getAll()
  1771. {
  1772. if (!$this->finalized) {
  1773. $this->autoFinalize();
  1774. }
  1775. $ret = array();
  1776. foreach ($this->plist->squash() as $name => $value) {
  1777. list($ns, $key) = explode('.', $name, 2);
  1778. $ret[$ns][$key] = $value;
  1779. }
  1780. return $ret;
  1781. }
  1782. /**
  1783. * Sets a value to configuration.
  1784. *
  1785. * @param string $key key
  1786. * @param mixed $value value
  1787. * @param mixed $a
  1788. */
  1789. public function set($key, $value, $a = null)
  1790. {
  1791. if (strpos($key, '.') === false) {
  1792. $namespace = $key;
  1793. $directive = $value;
  1794. $value = $a;
  1795. $key = "$key.$directive";
  1796. $this->triggerError("Using deprecated API: use \$config->set('$key', ...) instead", E_USER_NOTICE);
  1797. } else {
  1798. list($namespace) = explode('.', $key);
  1799. }
  1800. if ($this->isFinalized('Cannot set directive after finalization')) {
  1801. return;
  1802. }
  1803. if (!isset($this->def->info[$key])) {
  1804. $this->triggerError(
  1805. 'Cannot set undefined directive ' . htmlspecialchars($key) . ' to value',
  1806. E_USER_WARNING
  1807. );
  1808. return;
  1809. }
  1810. $def = $this->def->info[$key];
  1811. if (isset($def->isAlias)) {
  1812. if ($this->aliasMode) {
  1813. $this->triggerError(
  1814. 'Double-aliases not allowed, please fix '.
  1815. 'ConfigSchema bug with' . $key,
  1816. E_USER_ERROR
  1817. );
  1818. return;
  1819. }
  1820. $this->aliasMode = true;
  1821. $this->set($def->key, $value);
  1822. $this->aliasMode = false;
  1823. $this->triggerError("$key is an alias, preferred directive name is {$def->key}", E_USER_NOTICE);
  1824. return;
  1825. }
  1826. // Raw type might be negative when using the fully optimized form
  1827. // of stdclass, which indicates allow_null == true
  1828. $rtype = is_int($def) ? $def : $def->type;
  1829. if ($rtype < 0) {
  1830. $type = -$rtype;
  1831. $allow_null = true;
  1832. } else {
  1833. $type = $rtype;
  1834. $allow_null = isset($def->allow_null);
  1835. }
  1836. try {
  1837. $value = $this->parser->parse($value, $type, $allow_null);
  1838. } catch (HTMLPurifier_VarParserException $e) {
  1839. $this->triggerError(
  1840. 'Value for ' . $key . ' is of invalid type, should be ' .
  1841. HTMLPurifier_VarParser::getTypeName($type),
  1842. E_USER_WARNING
  1843. );
  1844. return;
  1845. }
  1846. if (is_string($value) && is_object($def)) {
  1847. // resolve value alias if defined
  1848. if (isset($def->aliases[$value])) {
  1849. $value = $def->aliases[$value];
  1850. }
  1851. // check to see if the value is allowed
  1852. if (isset($def->allowed) && !isset($def->allowed[$value])) {
  1853. $this->triggerError(
  1854. 'Value not supported, valid values are: ' .
  1855. $this->_listify($def->allowed),
  1856. E_USER_WARNING
  1857. );
  1858. return;
  1859. }
  1860. }
  1861. $this->plist->set($key, $value);
  1862. // reset definitions if the directives they depend on changed
  1863. // this is a very costly process, so it's discouraged
  1864. // with finalization
  1865. if ($namespace == 'HTML' || $namespace == 'CSS' || $namespace == 'URI') {
  1866. $this->definitions[$namespace] = null;
  1867. }
  1868. $this->serials[$namespace] = false;
  1869. }
  1870. /**
  1871. * Convenience function for error reporting
  1872. *
  1873. * @param array $lookup
  1874. *
  1875. * @return string
  1876. */
  1877. private function _listify($lookup)
  1878. {
  1879. $list = array();
  1880. foreach ($lookup as $name => $b) {
  1881. $list[] = $name;
  1882. }
  1883. return implode(', ', $list);
  1884. }
  1885. /**
  1886. * Retrieves object reference to the HTML definition.
  1887. *
  1888. * @param bool $raw Return a copy that has not been setup yet. Must be
  1889. * called before it's been setup, otherwise won't work.
  1890. * @param bool $optimized If true, this method may return null, to
  1891. * indicate that a cached version of the modified
  1892. * definition object is available and no further edits
  1893. * are necessary. Consider using
  1894. * maybeGetRawHTMLDefinition, which is more explicitly
  1895. * named, instead.
  1896. *
  1897. * @return HTMLPurifier_HTMLDefinition
  1898. */
  1899. public function getHTMLDefinition($raw = false, $optimized = false)
  1900. {
  1901. return $this->getDefinition('HTML', $raw, $optimized);
  1902. }
  1903. /**
  1904. * Retrieves object reference to the CSS definition
  1905. *
  1906. * @param bool $raw Return a copy that has not been setup yet. Must be
  1907. * called before it's been setup, otherwise won't work.
  1908. * @param bool $optimized If true, this method may return null, to
  1909. * indicate that a cached version of the modified
  1910. * definition object is available and no further edits
  1911. * are necessary. Consider using
  1912. * maybeGetRawCSSDefinition, which is more explicitly
  1913. * named, instead.
  1914. *
  1915. * @return HTMLPurifier_CSSDefinition
  1916. */
  1917. public function getCSSDefinition($raw = false, $optimized = false)
  1918. {
  1919. return $this->getDefinition('CSS', $raw, $optimized);
  1920. }
  1921. /**
  1922. * Retrieves object reference to the URI definition
  1923. *
  1924. * @param bool $raw Return a copy that has not been setup yet. Must be
  1925. * called before it's been setup, otherwise won't work.
  1926. * @param bool $optimized If true, this method may return null, to
  1927. * indicate that a cached version of the modified
  1928. * definition object is available and no further edits
  1929. * are necessary. Consider using
  1930. * maybeGetRawURIDefinition, which is more explicitly
  1931. * named, instead.
  1932. *
  1933. * @return HTMLPurifier_URIDefinition
  1934. */
  1935. public function getURIDefinition($raw = false, $optimized = false)
  1936. {
  1937. return $this->getDefinition('URI', $raw, $optimized);
  1938. }
  1939. /**
  1940. * Retrieves a definition
  1941. *
  1942. * @param string $type Type of definition: HTML, CSS, etc
  1943. * @param bool $raw Whether or not definition should be returned raw
  1944. * @param bool $optimized Only has an effect when $raw is true. Whether
  1945. * or not to return null if the result is already present in
  1946. * the cache. This is off by default for backwards
  1947. * compatibility reasons, but you need to do things this
  1948. * way in order to ensure that caching is done properly.
  1949. * Check out enduser-customize.html for more details.
  1950. * We probably won't ever change this default, as much as the
  1951. * maybe semantics is the "right thing to do."
  1952. *
  1953. * @throws HTMLPurifier_Exception
  1954. * @return HTMLPurifier_Definition
  1955. */
  1956. public function getDefinition($type, $raw = false, $optimized = false)
  1957. {
  1958. if ($optimized && !$raw) {
  1959. throw new HTMLPurifier_Exception("Cannot set optimized = true when raw = false");
  1960. }
  1961. if (!$this->finalized) {
  1962. $this->autoFinalize();
  1963. }
  1964. // temporarily suspend locks, so we can handle recursive definition calls
  1965. $lock = $this->lock;
  1966. $this->lock = null;
  1967. $factory = HTMLPurifier_DefinitionCacheFactory::instance();
  1968. $cache = $factory->create($type, $this);
  1969. $this->lock = $lock;
  1970. if (!$raw) {
  1971. // full definition
  1972. // ---------------
  1973. // check if definition is in memory
  1974. if (!empty($this->definitions[$type])) {
  1975. $def = $this->definitions[$type];
  1976. // check if the definition is setup
  1977. if ($def->setup) {
  1978. return $def;
  1979. } else {
  1980. $def->setup($this);
  1981. if ($def->optimized) {
  1982. $cache->add($def, $this);
  1983. }
  1984. return $def;
  1985. }
  1986. }
  1987. // check if definition is in cache
  1988. $def = $cache->get($this);
  1989. if ($def) {
  1990. // definition in cache, save to memory and return it
  1991. $this->definitions[$type] = $def;
  1992. return $def;
  1993. }
  1994. // initialize it
  1995. $def = $this->initDefinition($type);
  1996. // set it up
  1997. $this->lock = $type;
  1998. $def->setup($this);
  1999. $this->lock = null;
  2000. // save in cache
  2001. $cache->add($def, $this);
  2002. // return it
  2003. return $def;
  2004. } else {
  2005. // raw definition
  2006. // --------------
  2007. // check preconditions
  2008. $def = null;
  2009. if ($optimized) {
  2010. if (is_null($this->get($type . '.DefinitionID'))) {
  2011. // fatally error out if definition ID not set
  2012. throw new HTMLPurifier_Exception(
  2013. "Cannot retrieve raw version without specifying %$type.DefinitionID"
  2014. );
  2015. }
  2016. }
  2017. if (!empty($this->definitions[$type])) {
  2018. $def = $this->definitions[$type];
  2019. if ($def->setup && !$optimized) {
  2020. $extra = $this->chatty ?
  2021. " (try moving this code block earlier in your initialization)" :
  2022. "";
  2023. throw new HTMLPurifier_Exception(
  2024. "Cannot retrieve raw definition after it has already been setup" .
  2025. $extra
  2026. );
  2027. }
  2028. if ($def->optimized === null) {
  2029. $extra = $this->chatty ? " (try flushing your cache)" : "";
  2030. throw new HTMLPurifier_Exception(
  2031. "Optimization status of definition is unknown" . $extra
  2032. );
  2033. }
  2034. if ($def->optimized !== $optimized) {
  2035. $msg = $optimized ? "optimized" : "unoptimized";
  2036. $extra = $this->chatty ?
  2037. " (this backtrace is for the first inconsistent call, which was for a $msg raw definition)"
  2038. : "";
  2039. throw new HTMLPurifier_Exception(
  2040. "Inconsistent use of optimized and unoptimized raw definition retrievals" . $extra
  2041. );
  2042. }
  2043. }
  2044. // check if definition was in memory
  2045. if ($def) {
  2046. if ($def->setup) {
  2047. // invariant: $optimized === true (checked above)
  2048. return null;
  2049. } else {
  2050. return $def;
  2051. }
  2052. }
  2053. // if optimized, check if definition was in cache
  2054. // (because we do the memory check first, this formulation
  2055. // is prone to cache slamming, but I think
  2056. // guaranteeing that either /all/ of the raw
  2057. // setup code or /none/ of it is run is more important.)
  2058. if ($optimized) {
  2059. // This code path only gets run once; once we put
  2060. // something in $definitions (which is guaranteed by the
  2061. // trailing code), we always short-circuit above.
  2062. $def = $cache->get($this);
  2063. if ($def) {
  2064. // save the full definition for later, but don't
  2065. // return it yet
  2066. $this->definitions[$type] = $def;
  2067. return null;
  2068. }
  2069. }
  2070. // check invariants for creation
  2071. if (!$optimized) {
  2072. if (!is_null($this->get($type . '.DefinitionID'))) {
  2073. if ($this->chatty) {
  2074. $this->triggerError(
  2075. 'Due to a documentation error in previous version of HTML Purifier, your ' .
  2076. 'definitions are not being cached. If this is OK, you can remove the ' .
  2077. '%$type.DefinitionRev and %$type.DefinitionID declaration. Otherwise, ' .
  2078. 'modify your code to use maybeGetRawDefinition, and test if the returned ' .
  2079. 'value is null before making any edits (if it is null, that means that a ' .
  2080. 'cached version is available, and no raw operations are necessary). See ' .
  2081. '<a href="http://htmlpurifier.org/docs/enduser-customize.html#optimized">' .
  2082. 'Customize</a> for more details',
  2083. E_USER_WARNING
  2084. );
  2085. } else {
  2086. $this->triggerError(
  2087. "Useless DefinitionID declaration",
  2088. E_USER_WARNING
  2089. );
  2090. }
  2091. }
  2092. }
  2093. // initialize it
  2094. $def = $this->initDefinition($type);
  2095. $def->optimized = $optimized;
  2096. return $def;
  2097. }
  2098. throw new HTMLPurifier_Exception("The impossible happened!");
  2099. }
  2100. /**
  2101. * Initialise definition
  2102. *
  2103. * @param string $type What type of definition to create
  2104. *
  2105. * @return HTMLPurifier_CSSDefinition|HTMLPurifier_HTMLDefinition|HTMLPurifier_URIDefinition
  2106. * @throws HTMLPurifier_Exception
  2107. */
  2108. private function initDefinition($type)
  2109. {
  2110. // quick checks failed, let's create the object
  2111. if ($type == 'HTML') {
  2112. $def = new HTMLPurifier_HTMLDefinition();
  2113. } elseif ($type == 'CSS') {
  2114. $def = new HTMLPurifier_CSSDefinition();
  2115. } elseif ($type == 'URI') {
  2116. $def = new HTMLPurifier_URIDefinition();
  2117. } else {
  2118. throw new HTMLPurifier_Exception(
  2119. "Definition of $type type not supported"
  2120. );
  2121. }
  2122. $this->definitions[$type] = $def;
  2123. return $def;
  2124. }
  2125. public function maybeGetRawDefinition($name)
  2126. {
  2127. return $this->getDefinition($name, true, true);
  2128. }
  2129. /**
  2130. * @return HTMLPurifier_HTMLDefinition
  2131. */
  2132. public function maybeGetRawHTMLDefinition()
  2133. {
  2134. return $this->getDefinition('HTML', true, true);
  2135. }
  2136. /**
  2137. * @return HTMLPurifier_CSSDefinition
  2138. */
  2139. public function maybeGetRawCSSDefinition()
  2140. {
  2141. return $this->getDefinition('CSS', true, true);
  2142. }
  2143. /**
  2144. * @return HTMLPurifier_URIDefinition
  2145. */
  2146. public function maybeGetRawURIDefinition()
  2147. {
  2148. return $this->getDefinition('URI', true, true);
  2149. }
  2150. /**
  2151. * Loads configuration values from an array with the following structure:
  2152. * Namespace.Directive => Value
  2153. *
  2154. * @param array $config_array Configuration associative array
  2155. */
  2156. public function loadArray($config_array)
  2157. {
  2158. if ($this->isFinalized('Cannot load directives after finalization')) {
  2159. return;
  2160. }
  2161. foreach ($config_array as $key => $value) {
  2162. $key = str_replace('_', '.', $key);
  2163. if (strpos($key, '.') !== false) {
  2164. $this->set($key, $value);
  2165. } else {
  2166. $namespace = $key;
  2167. $namespace_values = $value;
  2168. foreach ($namespace_values as $directive => $value2) {
  2169. $this->set($namespace .'.'. $directive, $value2);
  2170. }
  2171. }
  2172. }
  2173. }
  2174. /**
  2175. * Returns a list of array(namespace, directive) for all directives
  2176. * that are allowed in a web-form context as per an allowed
  2177. * namespaces/directives list.
  2178. *
  2179. * @param array $allowed List of allowed namespaces/directives
  2180. * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
  2181. *
  2182. * @return array
  2183. */
  2184. public static function getAllowedDirectivesForForm($allowed, $schema = null)
  2185. {
  2186. if (!$schema) {
  2187. $schema = HTMLPurifier_ConfigSchema::instance();
  2188. }
  2189. if ($allowed !== true) {
  2190. if (is_string($allowed)) {
  2191. $allowed = array($allowed);
  2192. }
  2193. $allowed_ns = array();
  2194. $allowed_directives = array();
  2195. $blacklisted_directives = array();
  2196. foreach ($allowed as $ns_or_directive) {
  2197. if (strpos($ns_or_directive, '.') !== false) {
  2198. // directive
  2199. if ($ns_or_directive[0] == '-') {
  2200. $blacklisted_directives[substr($ns_or_directive, 1)] = true;
  2201. } else {
  2202. $allowed_directives[$ns_or_directive] = true;
  2203. }
  2204. } else {
  2205. // namespace
  2206. $allowed_ns[$ns_or_directive] = true;
  2207. }
  2208. }
  2209. }
  2210. $ret = array();
  2211. foreach ($schema->info as $key => $def) {
  2212. list($ns, $directive) = explode('.', $key, 2);
  2213. if ($allowed !== true) {
  2214. if (isset($blacklisted_directives["$ns.$directive"])) {
  2215. continue;
  2216. }
  2217. if (!isset($allowed_directives["$ns.$directive"]) && !isset($allowed_ns[$ns])) {
  2218. continue;
  2219. }
  2220. }
  2221. if (isset($def->isAlias)) {
  2222. continue;
  2223. }
  2224. if ($directive == 'DefinitionID' || $directive == 'DefinitionRev') {
  2225. continue;
  2226. }
  2227. $ret[] = array($ns, $directive);
  2228. }
  2229. return $ret;
  2230. }
  2231. /**
  2232. * Loads configuration values from $_GET/$_POST that were posted
  2233. * via ConfigForm
  2234. *
  2235. * @param array $array $_GET or $_POST array to import
  2236. * @param string|bool $index Index/name that the config variables are in
  2237. * @param array|bool $allowed List of allowed namespaces/directives
  2238. * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
  2239. * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
  2240. *
  2241. * @return mixed
  2242. */
  2243. public static function loadArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)
  2244. {
  2245. $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $schema);
  2246. $config = HTMLPurifier_Config::create($ret, $schema);
  2247. return $config;
  2248. }
  2249. /**
  2250. * Merges in configuration values from $_GET/$_POST to object. NOT STATIC.
  2251. *
  2252. * @param array $array $_GET or $_POST array to import
  2253. * @param string|bool $index Index/name that the config variables are in
  2254. * @param array|bool $allowed List of allowed namespaces/directives
  2255. * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
  2256. */
  2257. public function mergeArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true)
  2258. {
  2259. $ret = HTMLPurifier_Config::prepareArrayFromForm($array, $index, $allowed, $mq_fix, $this->def);
  2260. $this->loadArray($ret);
  2261. }
  2262. /**
  2263. * Prepares an array from a form into something usable for the more
  2264. * strict parts of HTMLPurifier_Config
  2265. *
  2266. * @param array $array $_GET or $_POST array to import
  2267. * @param string|bool $index Index/name that the config variables are in
  2268. * @param array|bool $allowed List of allowed namespaces/directives
  2269. * @param bool $mq_fix Boolean whether or not to enable magic quotes fix
  2270. * @param HTMLPurifier_ConfigSchema $schema Schema to use, if not global copy
  2271. *
  2272. * @return array
  2273. */
  2274. public static function prepareArrayFromForm($array, $index = false, $allowed = true, $mq_fix = true, $schema = null)
  2275. {
  2276. if ($index !== false) {
  2277. $array = (isset($array[$index]) && is_array($array[$index])) ? $array[$index] : array();
  2278. }
  2279. $mq = $mq_fix && function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc();
  2280. $allowed = HTMLPurifier_Config::getAllowedDirectivesForForm($allowed, $schema);
  2281. $ret = array();
  2282. foreach ($allowed as $key) {
  2283. list($ns, $directive) = $key;
  2284. $skey = "$ns.$directive";
  2285. if (!empty($array["Null_$skey"])) {
  2286. $ret[$ns][$directive] = null;
  2287. continue;
  2288. }
  2289. if (!isset($array[$skey])) {
  2290. continue;
  2291. }
  2292. $value = $mq ? stripslashes($array[$skey]) : $array[$skey];
  2293. $ret[$ns][$directive] = $value;
  2294. }
  2295. return $ret;
  2296. }
  2297. /**
  2298. * Loads configuration values from an ini file
  2299. *
  2300. * @param string $filename Name of ini file
  2301. */
  2302. public function loadIni($filename)
  2303. {
  2304. if ($this->isFinalized('Cannot load directives after finalization')) {
  2305. return;
  2306. }
  2307. $array = parse_ini_file($filename, true);
  2308. $this->loadArray($array);
  2309. }
  2310. /**
  2311. * Checks whether or not the configuration object is finalized.
  2312. *
  2313. * @param string|bool $error String error message, or false for no error
  2314. *
  2315. * @return bool
  2316. */
  2317. public function isFinalized($error = false)
  2318. {
  2319. if ($this->finalized && $error) {
  2320. $this->triggerError($error, E_USER_ERROR);
  2321. }
  2322. return $this->finalized;
  2323. }
  2324. /**
  2325. * Finalizes configuration only if auto finalize is on and not
  2326. * already finalized
  2327. */
  2328. public function autoFinalize()
  2329. {
  2330. if ($this->autoFinalize) {
  2331. $this->finalize();
  2332. } else {
  2333. $this->plist->squash(true);
  2334. }
  2335. }
  2336. /**
  2337. * Finalizes a configuration object, prohibiting further change
  2338. */
  2339. public function finalize()
  2340. {
  2341. $this->finalized = true;
  2342. $this->parser = null;
  2343. }
  2344. /**
  2345. * Produces a nicely formatted error message by supplying the
  2346. * stack frame information OUTSIDE of HTMLPurifier_Config.
  2347. *
  2348. * @param string $msg An error message
  2349. * @param int $no An error number
  2350. */
  2351. protected function triggerError($msg, $no)
  2352. {
  2353. // determine previous stack frame
  2354. $extra = '';
  2355. if ($this->chatty) {
  2356. $trace = debug_backtrace();
  2357. // zip(tail(trace), trace) -- but PHP is not Haskell har har
  2358. for ($i = 0, $c = count($trace); $i < $c - 1; $i++) {
  2359. // XXX this is not correct on some versions of HTML Purifier
  2360. if ($trace[$i + 1]['class'] === 'HTMLPurifier_Config') {
  2361. continue;
  2362. }
  2363. $frame = $trace[$i];
  2364. $extra = " invoked on line {$frame['line']} in file {$frame['file']}";
  2365. break;
  2366. }
  2367. }
  2368. trigger_error($msg . $extra, $no);
  2369. }
  2370. /**
  2371. * Returns a serialized form of the configuration object that can
  2372. * be reconstituted.
  2373. *
  2374. * @return string
  2375. */
  2376. public function serialize()
  2377. {
  2378. $this->getDefinition('HTML');
  2379. $this->getDefinition('CSS');
  2380. $this->getDefinition('URI');
  2381. return serialize($this);
  2382. }
  2383. }
  2384. /**
  2385. * Configuration definition, defines directives and their defaults.
  2386. */
  2387. class HTMLPurifier_ConfigSchema
  2388. {
  2389. /**
  2390. * Defaults of the directives and namespaces.
  2391. * @type array
  2392. * @note This shares the exact same structure as HTMLPurifier_Config::$conf
  2393. */
  2394. public $defaults = array();
  2395. /**
  2396. * The default property list. Do not edit this property list.
  2397. * @type array
  2398. */
  2399. public $defaultPlist;
  2400. /**
  2401. * Definition of the directives.
  2402. * The structure of this is:
  2403. *
  2404. * array(
  2405. * 'Namespace' => array(
  2406. * 'Directive' => new stdclass(),
  2407. * )
  2408. * )
  2409. *
  2410. * The stdclass may have the following properties:
  2411. *
  2412. * - If isAlias isn't set:
  2413. * - type: Integer type of directive, see HTMLPurifier_VarParser for definitions
  2414. * - allow_null: If set, this directive allows null values
  2415. * - aliases: If set, an associative array of value aliases to real values
  2416. * - allowed: If set, a lookup array of allowed (string) values
  2417. * - If isAlias is set:
  2418. * - namespace: Namespace this directive aliases to
  2419. * - name: Directive name this directive aliases to
  2420. *
  2421. * In certain degenerate cases, stdclass will actually be an integer. In
  2422. * that case, the value is equivalent to an stdclass with the type
  2423. * property set to the integer. If the integer is negative, type is
  2424. * equal to the absolute value of integer, and allow_null is true.
  2425. *
  2426. * This class is friendly with HTMLPurifier_Config. If you need introspection
  2427. * about the schema, you're better of using the ConfigSchema_Interchange,
  2428. * which uses more memory but has much richer information.
  2429. * @type array
  2430. */
  2431. public $info = array();
  2432. /**
  2433. * Application-wide singleton
  2434. * @type HTMLPurifier_ConfigSchema
  2435. */
  2436. protected static $singleton;
  2437. public function __construct()
  2438. {
  2439. $this->defaultPlist = new HTMLPurifier_PropertyList();
  2440. }
  2441. /**
  2442. * Unserializes the default ConfigSchema.
  2443. * @return HTMLPurifier_ConfigSchema
  2444. */
  2445. public static function makeFromSerial()
  2446. {
  2447. $contents = file_get_contents(HTMLPURIFIER_PREFIX . '/HTMLPurifier/ConfigSchema/schema.ser');
  2448. $r = unserialize($contents);
  2449. if (!$r) {
  2450. $hash = sha1($contents);
  2451. trigger_error("Unserialization of configuration schema failed, sha1 of file was $hash", E_USER_ERROR);
  2452. }
  2453. return $r;
  2454. }
  2455. /**
  2456. * Retrieves an instance of the application-wide configuration definition.
  2457. * @param HTMLPurifier_ConfigSchema $prototype
  2458. * @return HTMLPurifier_ConfigSchema
  2459. */
  2460. public static function instance($prototype = null)
  2461. {
  2462. if ($prototype !== null) {
  2463. HTMLPurifier_ConfigSchema::$singleton = $prototype;
  2464. } elseif (HTMLPurifier_ConfigSchema::$singleton === null || $prototype === true) {
  2465. HTMLPurifier_ConfigSchema::$singleton = HTMLPurifier_ConfigSchema::makeFromSerial();
  2466. }
  2467. return HTMLPurifier_ConfigSchema::$singleton;
  2468. }
  2469. /**
  2470. * Defines a directive for configuration
  2471. * @warning Will fail of directive's namespace is defined.
  2472. * @warning This method's signature is slightly different from the legacy
  2473. * define() static method! Beware!
  2474. * @param string $key Name of directive
  2475. * @param mixed $default Default value of directive
  2476. * @param string $type Allowed type of the directive. See
  2477. * HTMLPurifier_DirectiveDef::$type for allowed values
  2478. * @param bool $allow_null Whether or not to allow null values
  2479. */
  2480. public function add($key, $default, $type, $allow_null)
  2481. {
  2482. $obj = new stdclass();
  2483. $obj->type = is_int($type) ? $type : HTMLPurifier_VarParser::$types[$type];
  2484. if ($allow_null) {
  2485. $obj->allow_null = true;
  2486. }
  2487. $this->info[$key] = $obj;
  2488. $this->defaults[$key] = $default;
  2489. $this->defaultPlist->set($key, $default);
  2490. }
  2491. /**
  2492. * Defines a directive value alias.
  2493. *
  2494. * Directive value aliases are convenient for developers because it lets
  2495. * them set a directive to several values and get the same result.
  2496. * @param string $key Name of Directive
  2497. * @param array $aliases Hash of aliased values to the real alias
  2498. */
  2499. public function addValueAliases($key, $aliases)
  2500. {
  2501. if (!isset($this->info[$key]->aliases)) {
  2502. $this->info[$key]->aliases = array();
  2503. }
  2504. foreach ($aliases as $alias => $real) {
  2505. $this->info[$key]->aliases[$alias] = $real;
  2506. }
  2507. }
  2508. /**
  2509. * Defines a set of allowed values for a directive.
  2510. * @warning This is slightly different from the corresponding static
  2511. * method definition.
  2512. * @param string $key Name of directive
  2513. * @param array $allowed Lookup array of allowed values
  2514. */
  2515. public function addAllowedValues($key, $allowed)
  2516. {
  2517. $this->info[$key]->allowed = $allowed;
  2518. }
  2519. /**
  2520. * Defines a directive alias for backwards compatibility
  2521. * @param string $key Directive that will be aliased
  2522. * @param string $new_key Directive that the alias will be to
  2523. */
  2524. public function addAlias($key, $new_key)
  2525. {
  2526. $obj = new stdclass;
  2527. $obj->key = $new_key;
  2528. $obj->isAlias = true;
  2529. $this->info[$key] = $obj;
  2530. }
  2531. /**
  2532. * Replaces any stdclass that only has the type property with type integer.
  2533. */
  2534. public function postProcess()
  2535. {
  2536. foreach ($this->info as $key => $v) {
  2537. if (count((array) $v) == 1) {
  2538. $this->info[$key] = $v->type;
  2539. } elseif (count((array) $v) == 2 && isset($v->allow_null)) {
  2540. $this->info[$key] = -$v->type;
  2541. }
  2542. }
  2543. }
  2544. }
  2545. /**
  2546. * @todo Unit test
  2547. */
  2548. class HTMLPurifier_ContentSets
  2549. {
  2550. /**
  2551. * List of content set strings (pipe separators) indexed by name.
  2552. * @type array
  2553. */
  2554. public $info = array();
  2555. /**
  2556. * List of content set lookups (element => true) indexed by name.
  2557. * @type array
  2558. * @note This is in HTMLPurifier_HTMLDefinition->info_content_sets
  2559. */
  2560. public $lookup = array();
  2561. /**
  2562. * Synchronized list of defined content sets (keys of info).
  2563. * @type array
  2564. */
  2565. protected $keys = array();
  2566. /**
  2567. * Synchronized list of defined content values (values of info).
  2568. * @type array
  2569. */
  2570. protected $values = array();
  2571. /**
  2572. * Merges in module's content sets, expands identifiers in the content
  2573. * sets and populates the keys, values and lookup member variables.
  2574. * @param HTMLPurifier_HTMLModule[] $modules List of HTMLPurifier_HTMLModule
  2575. */
  2576. public function __construct($modules)
  2577. {
  2578. if (!is_array($modules)) {
  2579. $modules = array($modules);
  2580. }
  2581. // populate content_sets based on module hints
  2582. // sorry, no way of overloading
  2583. foreach ($modules as $module) {
  2584. foreach ($module->content_sets as $key => $value) {
  2585. $temp = $this->convertToLookup($value);
  2586. if (isset($this->lookup[$key])) {
  2587. // add it into the existing content set
  2588. $this->lookup[$key] = array_merge($this->lookup[$key], $temp);
  2589. } else {
  2590. $this->lookup[$key] = $temp;
  2591. }
  2592. }
  2593. }
  2594. $old_lookup = false;
  2595. while ($old_lookup !== $this->lookup) {
  2596. $old_lookup = $this->lookup;
  2597. foreach ($this->lookup as $i => $set) {
  2598. $add = array();
  2599. foreach ($set as $element => $x) {
  2600. if (isset($this->lookup[$element])) {
  2601. $add += $this->lookup[$element];
  2602. unset($this->lookup[$i][$element]);
  2603. }
  2604. }
  2605. $this->lookup[$i] += $add;
  2606. }
  2607. }
  2608. foreach ($this->lookup as $key => $lookup) {
  2609. $this->info[$key] = implode(' | ', array_keys($lookup));
  2610. }
  2611. $this->keys = array_keys($this->info);
  2612. $this->values = array_values($this->info);
  2613. }
  2614. /**
  2615. * Accepts a definition; generates and assigns a ChildDef for it
  2616. * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef reference
  2617. * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef
  2618. */
  2619. public function generateChildDef(&$def, $module)
  2620. {
  2621. if (!empty($def->child)) { // already done!
  2622. return;
  2623. }
  2624. $content_model = $def->content_model;
  2625. if (is_string($content_model)) {
  2626. // Assume that $this->keys is alphanumeric
  2627. $def->content_model = preg_replace_callback(
  2628. '/\b(' . implode('|', $this->keys) . ')\b/',
  2629. array($this, 'generateChildDefCallback'),
  2630. $content_model
  2631. );
  2632. //$def->content_model = str_replace(
  2633. // $this->keys, $this->values, $content_model);
  2634. }
  2635. $def->child = $this->getChildDef($def, $module);
  2636. }
  2637. public function generateChildDefCallback($matches)
  2638. {
  2639. return $this->info[$matches[0]];
  2640. }
  2641. /**
  2642. * Instantiates a ChildDef based on content_model and content_model_type
  2643. * member variables in HTMLPurifier_ElementDef
  2644. * @note This will also defer to modules for custom HTMLPurifier_ChildDef
  2645. * subclasses that need content set expansion
  2646. * @param HTMLPurifier_ElementDef $def HTMLPurifier_ElementDef to have ChildDef extracted
  2647. * @param HTMLPurifier_HTMLModule $module Module that defined the ElementDef
  2648. * @return HTMLPurifier_ChildDef corresponding to ElementDef
  2649. */
  2650. public function getChildDef($def, $module)
  2651. {
  2652. $value = $def->content_model;
  2653. if (is_object($value)) {
  2654. trigger_error(
  2655. 'Literal object child definitions should be stored in '.
  2656. 'ElementDef->child not ElementDef->content_model',
  2657. E_USER_NOTICE
  2658. );
  2659. return $value;
  2660. }
  2661. switch ($def->content_model_type) {
  2662. case 'required':
  2663. return new HTMLPurifier_ChildDef_Required($value);
  2664. case 'optional':
  2665. return new HTMLPurifier_ChildDef_Optional($value);
  2666. case 'empty':
  2667. return new HTMLPurifier_ChildDef_Empty();
  2668. case 'custom':
  2669. return new HTMLPurifier_ChildDef_Custom($value);
  2670. }
  2671. // defer to its module
  2672. $return = false;
  2673. if ($module->defines_child_def) { // save a func call
  2674. $return = $module->getChildDef($def);
  2675. }
  2676. if ($return !== false) {
  2677. return $return;
  2678. }
  2679. // error-out
  2680. trigger_error(
  2681. 'Could not determine which ChildDef class to instantiate',
  2682. E_USER_ERROR
  2683. );
  2684. return false;
  2685. }
  2686. /**
  2687. * Converts a string list of elements separated by pipes into
  2688. * a lookup array.
  2689. * @param string $string List of elements
  2690. * @return array Lookup array of elements
  2691. */
  2692. protected function convertToLookup($string)
  2693. {
  2694. $array = explode('|', str_replace(' ', '', $string));
  2695. $ret = array();
  2696. foreach ($array as $k) {
  2697. $ret[$k] = true;
  2698. }
  2699. return $ret;
  2700. }
  2701. }
  2702. /**
  2703. * Registry object that contains information about the current context.
  2704. * @warning Is a bit buggy when variables are set to null: it thinks
  2705. * they don't exist! So use false instead, please.
  2706. * @note Since the variables Context deals with may not be objects,
  2707. * references are very important here! Do not remove!
  2708. */
  2709. class HTMLPurifier_Context
  2710. {
  2711. /**
  2712. * Private array that stores the references.
  2713. * @type array
  2714. */
  2715. private $_storage = array();
  2716. /**
  2717. * Registers a variable into the context.
  2718. * @param string $name String name
  2719. * @param mixed $ref Reference to variable to be registered
  2720. */
  2721. public function register($name, &$ref)
  2722. {
  2723. if (array_key_exists($name, $this->_storage)) {
  2724. trigger_error(
  2725. "Name $name produces collision, cannot re-register",
  2726. E_USER_ERROR
  2727. );
  2728. return;
  2729. }
  2730. $this->_storage[$name] =& $ref;
  2731. }
  2732. /**
  2733. * Retrieves a variable reference from the context.
  2734. * @param string $name String name
  2735. * @param bool $ignore_error Boolean whether or not to ignore error
  2736. * @return mixed
  2737. */
  2738. public function &get($name, $ignore_error = false)
  2739. {
  2740. if (!array_key_exists($name, $this->_storage)) {
  2741. if (!$ignore_error) {
  2742. trigger_error(
  2743. "Attempted to retrieve non-existent variable $name",
  2744. E_USER_ERROR
  2745. );
  2746. }
  2747. $var = null; // so we can return by reference
  2748. return $var;
  2749. }
  2750. return $this->_storage[$name];
  2751. }
  2752. /**
  2753. * Destroys a variable in the context.
  2754. * @param string $name String name
  2755. */
  2756. public function destroy($name)
  2757. {
  2758. if (!array_key_exists($name, $this->_storage)) {
  2759. trigger_error(
  2760. "Attempted to destroy non-existent variable $name",
  2761. E_USER_ERROR
  2762. );
  2763. return;
  2764. }
  2765. unset($this->_storage[$name]);
  2766. }
  2767. /**
  2768. * Checks whether or not the variable exists.
  2769. * @param string $name String name
  2770. * @return bool
  2771. */
  2772. public function exists($name)
  2773. {
  2774. return array_key_exists($name, $this->_storage);
  2775. }
  2776. /**
  2777. * Loads a series of variables from an associative array
  2778. * @param array $context_array Assoc array of variables to load
  2779. */
  2780. public function loadArray($context_array)
  2781. {
  2782. foreach ($context_array as $key => $discard) {
  2783. $this->register($key, $context_array[$key]);
  2784. }
  2785. }
  2786. }
  2787. /**
  2788. * Abstract class representing Definition cache managers that implements
  2789. * useful common methods and is a factory.
  2790. * @todo Create a separate maintenance file advanced users can use to
  2791. * cache their custom HTMLDefinition, which can be loaded
  2792. * via a configuration directive
  2793. * @todo Implement memcached
  2794. */
  2795. abstract class HTMLPurifier_DefinitionCache
  2796. {
  2797. /**
  2798. * @type string
  2799. */
  2800. public $type;
  2801. /**
  2802. * @param string $type Type of definition objects this instance of the
  2803. * cache will handle.
  2804. */
  2805. public function __construct($type)
  2806. {
  2807. $this->type = $type;
  2808. }
  2809. /**
  2810. * Generates a unique identifier for a particular configuration
  2811. * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config
  2812. * @return string
  2813. */
  2814. public function generateKey($config)
  2815. {
  2816. return $config->version . ',' . // possibly replace with function calls
  2817. $config->getBatchSerial($this->type) . ',' .
  2818. $config->get($this->type . '.DefinitionRev');
  2819. }
  2820. /**
  2821. * Tests whether or not a key is old with respect to the configuration's
  2822. * version and revision number.
  2823. * @param string $key Key to test
  2824. * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config to test against
  2825. * @return bool
  2826. */
  2827. public function isOld($key, $config)
  2828. {
  2829. if (substr_count($key, ',') < 2) {
  2830. return true;
  2831. }
  2832. list($version, $hash, $revision) = explode(',', $key, 3);
  2833. $compare = version_compare($version, $config->version);
  2834. // version mismatch, is always old
  2835. if ($compare != 0) {
  2836. return true;
  2837. }
  2838. // versions match, ids match, check revision number
  2839. if ($hash == $config->getBatchSerial($this->type) &&
  2840. $revision < $config->get($this->type . '.DefinitionRev')) {
  2841. return true;
  2842. }
  2843. return false;
  2844. }
  2845. /**
  2846. * Checks if a definition's type jives with the cache's type
  2847. * @note Throws an error on failure
  2848. * @param HTMLPurifier_Definition $def Definition object to check
  2849. * @return bool true if good, false if not
  2850. */
  2851. public function checkDefType($def)
  2852. {
  2853. if ($def->type !== $this->type) {
  2854. trigger_error("Cannot use definition of type {$def->type} in cache for {$this->type}");
  2855. return false;
  2856. }
  2857. return true;
  2858. }
  2859. /**
  2860. * Adds a definition object to the cache
  2861. * @param HTMLPurifier_Definition $def
  2862. * @param HTMLPurifier_Config $config
  2863. */
  2864. abstract public function add($def, $config);
  2865. /**
  2866. * Unconditionally saves a definition object to the cache
  2867. * @param HTMLPurifier_Definition $def
  2868. * @param HTMLPurifier_Config $config
  2869. */
  2870. abstract public function set($def, $config);
  2871. /**
  2872. * Replace an object in the cache
  2873. * @param HTMLPurifier_Definition $def
  2874. * @param HTMLPurifier_Config $config
  2875. */
  2876. abstract public function replace($def, $config);
  2877. /**
  2878. * Retrieves a definition object from the cache
  2879. * @param HTMLPurifier_Config $config
  2880. */
  2881. abstract public function get($config);
  2882. /**
  2883. * Removes a definition object to the cache
  2884. * @param HTMLPurifier_Config $config
  2885. */
  2886. abstract public function remove($config);
  2887. /**
  2888. * Clears all objects from cache
  2889. * @param HTMLPurifier_Config $config
  2890. */
  2891. abstract public function flush($config);
  2892. /**
  2893. * Clears all expired (older version or revision) objects from cache
  2894. * @note Be careful implementing this method as flush. Flush must
  2895. * not interfere with other Definition types, and cleanup()
  2896. * should not be repeatedly called by userland code.
  2897. * @param HTMLPurifier_Config $config
  2898. */
  2899. abstract public function cleanup($config);
  2900. }
  2901. /**
  2902. * Responsible for creating definition caches.
  2903. */
  2904. class HTMLPurifier_DefinitionCacheFactory
  2905. {
  2906. /**
  2907. * @type array
  2908. */
  2909. protected $caches = array('Serializer' => array());
  2910. /**
  2911. * @type array
  2912. */
  2913. protected $implementations = array();
  2914. /**
  2915. * @type HTMLPurifier_DefinitionCache_Decorator[]
  2916. */
  2917. protected $decorators = array();
  2918. /**
  2919. * Initialize default decorators
  2920. */
  2921. public function setup()
  2922. {
  2923. $this->addDecorator('Cleanup');
  2924. }
  2925. /**
  2926. * Retrieves an instance of global definition cache factory.
  2927. * @param HTMLPurifier_DefinitionCacheFactory $prototype
  2928. * @return HTMLPurifier_DefinitionCacheFactory
  2929. */
  2930. public static function instance($prototype = null)
  2931. {
  2932. static $instance;
  2933. if ($prototype !== null) {
  2934. $instance = $prototype;
  2935. } elseif ($instance === null || $prototype === true) {
  2936. $instance = new HTMLPurifier_DefinitionCacheFactory();
  2937. $instance->setup();
  2938. }
  2939. return $instance;
  2940. }
  2941. /**
  2942. * Registers a new definition cache object
  2943. * @param string $short Short name of cache object, for reference
  2944. * @param string $long Full class name of cache object, for construction
  2945. */
  2946. public function register($short, $long)
  2947. {
  2948. $this->implementations[$short] = $long;
  2949. }
  2950. /**
  2951. * Factory method that creates a cache object based on configuration
  2952. * @param string $type Name of definitions handled by cache
  2953. * @param HTMLPurifier_Config $config Config instance
  2954. * @return mixed
  2955. */
  2956. public function create($type, $config)
  2957. {
  2958. $method = $config->get('Cache.DefinitionImpl');
  2959. if ($method === null) {
  2960. return new HTMLPurifier_DefinitionCache_Null($type);
  2961. }
  2962. if (!empty($this->caches[$method][$type])) {
  2963. return $this->caches[$method][$type];
  2964. }
  2965. if (isset($this->implementations[$method]) &&
  2966. class_exists($class = $this->implementations[$method], false)) {
  2967. $cache = new $class($type);
  2968. } else {
  2969. if ($method != 'Serializer') {
  2970. trigger_error("Unrecognized DefinitionCache $method, using Serializer instead", E_USER_WARNING);
  2971. }
  2972. $cache = new HTMLPurifier_DefinitionCache_Serializer($type);
  2973. }
  2974. foreach ($this->decorators as $decorator) {
  2975. $new_cache = $decorator->decorate($cache);
  2976. // prevent infinite recursion in PHP 4
  2977. unset($cache);
  2978. $cache = $new_cache;
  2979. }
  2980. $this->caches[$method][$type] = $cache;
  2981. return $this->caches[$method][$type];
  2982. }
  2983. /**
  2984. * Registers a decorator to add to all new cache objects
  2985. * @param HTMLPurifier_DefinitionCache_Decorator|string $decorator An instance or the name of a decorator
  2986. */
  2987. public function addDecorator($decorator)
  2988. {
  2989. if (is_string($decorator)) {
  2990. $class = "HTMLPurifier_DefinitionCache_Decorator_$decorator";
  2991. $decorator = new $class;
  2992. }
  2993. $this->decorators[$decorator->name] = $decorator;
  2994. }
  2995. }
  2996. /**
  2997. * Represents a document type, contains information on which modules
  2998. * need to be loaded.
  2999. * @note This class is inspected by Printer_HTMLDefinition->renderDoctype.
  3000. * If structure changes, please update that function.
  3001. */
  3002. class HTMLPurifier_Doctype
  3003. {
  3004. /**
  3005. * Full name of doctype
  3006. * @type string
  3007. */
  3008. public $name;
  3009. /**
  3010. * List of standard modules (string identifiers or literal objects)
  3011. * that this doctype uses
  3012. * @type array
  3013. */
  3014. public $modules = array();
  3015. /**
  3016. * List of modules to use for tidying up code
  3017. * @type array
  3018. */
  3019. public $tidyModules = array();
  3020. /**
  3021. * Is the language derived from XML (i.e. XHTML)?
  3022. * @type bool
  3023. */
  3024. public $xml = true;
  3025. /**
  3026. * List of aliases for this doctype
  3027. * @type array
  3028. */
  3029. public $aliases = array();
  3030. /**
  3031. * Public DTD identifier
  3032. * @type string
  3033. */
  3034. public $dtdPublic;
  3035. /**
  3036. * System DTD identifier
  3037. * @type string
  3038. */
  3039. public $dtdSystem;
  3040. public function __construct(
  3041. $name = null,
  3042. $xml = true,
  3043. $modules = array(),
  3044. $tidyModules = array(),
  3045. $aliases = array(),
  3046. $dtd_public = null,
  3047. $dtd_system = null
  3048. ) {
  3049. $this->name = $name;
  3050. $this->xml = $xml;
  3051. $this->modules = $modules;
  3052. $this->tidyModules = $tidyModules;
  3053. $this->aliases = $aliases;
  3054. $this->dtdPublic = $dtd_public;
  3055. $this->dtdSystem = $dtd_system;
  3056. }
  3057. }
  3058. class HTMLPurifier_DoctypeRegistry
  3059. {
  3060. /**
  3061. * Hash of doctype names to doctype objects.
  3062. * @type array
  3063. */
  3064. protected $doctypes;
  3065. /**
  3066. * Lookup table of aliases to real doctype names.
  3067. * @type array
  3068. */
  3069. protected $aliases;
  3070. /**
  3071. * Registers a doctype to the registry
  3072. * @note Accepts a fully-formed doctype object, or the
  3073. * parameters for constructing a doctype object
  3074. * @param string $doctype Name of doctype or literal doctype object
  3075. * @param bool $xml
  3076. * @param array $modules Modules doctype will load
  3077. * @param array $tidy_modules Modules doctype will load for certain modes
  3078. * @param array $aliases Alias names for doctype
  3079. * @param string $dtd_public
  3080. * @param string $dtd_system
  3081. * @return HTMLPurifier_Doctype Editable registered doctype
  3082. */
  3083. public function register(
  3084. $doctype,
  3085. $xml = true,
  3086. $modules = array(),
  3087. $tidy_modules = array(),
  3088. $aliases = array(),
  3089. $dtd_public = null,
  3090. $dtd_system = null
  3091. ) {
  3092. if (!is_array($modules)) {
  3093. $modules = array($modules);
  3094. }
  3095. if (!is_array($tidy_modules)) {
  3096. $tidy_modules = array($tidy_modules);
  3097. }
  3098. if (!is_array($aliases)) {
  3099. $aliases = array($aliases);
  3100. }
  3101. if (!is_object($doctype)) {
  3102. $doctype = new HTMLPurifier_Doctype(
  3103. $doctype,
  3104. $xml,
  3105. $modules,
  3106. $tidy_modules,
  3107. $aliases,
  3108. $dtd_public,
  3109. $dtd_system
  3110. );
  3111. }
  3112. $this->doctypes[$doctype->name] = $doctype;
  3113. $name = $doctype->name;
  3114. // hookup aliases
  3115. foreach ($doctype->aliases as $alias) {
  3116. if (isset($this->doctypes[$alias])) {
  3117. continue;
  3118. }
  3119. $this->aliases[$alias] = $name;
  3120. }
  3121. // remove old aliases
  3122. if (isset($this->aliases[$name])) {
  3123. unset($this->aliases[$name]);
  3124. }
  3125. return $doctype;
  3126. }
  3127. /**
  3128. * Retrieves reference to a doctype of a certain name
  3129. * @note This function resolves aliases
  3130. * @note When possible, use the more fully-featured make()
  3131. * @param string $doctype Name of doctype
  3132. * @return HTMLPurifier_Doctype Editable doctype object
  3133. */
  3134. public function get($doctype)
  3135. {
  3136. if (isset($this->aliases[$doctype])) {
  3137. $doctype = $this->aliases[$doctype];
  3138. }
  3139. if (!isset($this->doctypes[$doctype])) {
  3140. trigger_error('Doctype ' . htmlspecialchars($doctype) . ' does not exist', E_USER_ERROR);
  3141. $anon = new HTMLPurifier_Doctype($doctype);
  3142. return $anon;
  3143. }
  3144. return $this->doctypes[$doctype];
  3145. }
  3146. /**
  3147. * Creates a doctype based on a configuration object,
  3148. * will perform initialization on the doctype
  3149. * @note Use this function to get a copy of doctype that config
  3150. * can hold on to (this is necessary in order to tell
  3151. * Generator whether or not the current document is XML
  3152. * based or not).
  3153. * @param HTMLPurifier_Config $config
  3154. * @return HTMLPurifier_Doctype
  3155. */
  3156. public function make($config)
  3157. {
  3158. return clone $this->get($this->getDoctypeFromConfig($config));
  3159. }
  3160. /**
  3161. * Retrieves the doctype from the configuration object
  3162. * @param HTMLPurifier_Config $config
  3163. * @return string
  3164. */
  3165. public function getDoctypeFromConfig($config)
  3166. {
  3167. // recommended test
  3168. $doctype = $config->get('HTML.Doctype');
  3169. if (!empty($doctype)) {
  3170. return $doctype;
  3171. }
  3172. $doctype = $config->get('HTML.CustomDoctype');
  3173. if (!empty($doctype)) {
  3174. return $doctype;
  3175. }
  3176. // backwards-compatibility
  3177. if ($config->get('HTML.XHTML')) {
  3178. $doctype = 'XHTML 1.0';
  3179. } else {
  3180. $doctype = 'HTML 4.01';
  3181. }
  3182. if ($config->get('HTML.Strict')) {
  3183. $doctype .= ' Strict';
  3184. } else {
  3185. $doctype .= ' Transitional';
  3186. }
  3187. return $doctype;
  3188. }
  3189. }
  3190. /**
  3191. * Structure that stores an HTML element definition. Used by
  3192. * HTMLPurifier_HTMLDefinition and HTMLPurifier_HTMLModule.
  3193. * @note This class is inspected by HTMLPurifier_Printer_HTMLDefinition.
  3194. * Please update that class too.
  3195. * @warning If you add new properties to this class, you MUST update
  3196. * the mergeIn() method.
  3197. */
  3198. class HTMLPurifier_ElementDef
  3199. {
  3200. /**
  3201. * Does the definition work by itself, or is it created solely
  3202. * for the purpose of merging into another definition?
  3203. * @type bool
  3204. */
  3205. public $standalone = true;
  3206. /**
  3207. * Associative array of attribute name to HTMLPurifier_AttrDef.
  3208. * @type array
  3209. * @note Before being processed by HTMLPurifier_AttrCollections
  3210. * when modules are finalized during
  3211. * HTMLPurifier_HTMLDefinition->setup(), this array may also
  3212. * contain an array at index 0 that indicates which attribute
  3213. * collections to load into the full array. It may also
  3214. * contain string indentifiers in lieu of HTMLPurifier_AttrDef,
  3215. * see HTMLPurifier_AttrTypes on how they are expanded during
  3216. * HTMLPurifier_HTMLDefinition->setup() processing.
  3217. */
  3218. public $attr = array();
  3219. // XXX: Design note: currently, it's not possible to override
  3220. // previously defined AttrTransforms without messing around with
  3221. // the final generated config. This is by design; a previous version
  3222. // used an associated list of attr_transform, but it was extremely
  3223. // easy to accidentally override other attribute transforms by
  3224. // forgetting to specify an index (and just using 0.) While we
  3225. // could check this by checking the index number and complaining,
  3226. // there is a second problem which is that it is not at all easy to
  3227. // tell when something is getting overridden. Combine this with a
  3228. // codebase where this isn't really being used, and it's perfect for
  3229. // nuking.
  3230. /**
  3231. * List of tags HTMLPurifier_AttrTransform to be done before validation.
  3232. * @type array
  3233. */
  3234. public $attr_transform_pre = array();
  3235. /**
  3236. * List of tags HTMLPurifier_AttrTransform to be done after validation.
  3237. * @type array
  3238. */
  3239. public $attr_transform_post = array();
  3240. /**
  3241. * HTMLPurifier_ChildDef of this tag.
  3242. * @type HTMLPurifier_ChildDef
  3243. */
  3244. public $child;
  3245. /**
  3246. * Abstract string representation of internal ChildDef rules.
  3247. * @see HTMLPurifier_ContentSets for how this is parsed and then transformed
  3248. * into an HTMLPurifier_ChildDef.
  3249. * @warning This is a temporary variable that is not available after
  3250. * being processed by HTMLDefinition
  3251. * @type string
  3252. */
  3253. public $content_model;
  3254. /**
  3255. * Value of $child->type, used to determine which ChildDef to use,
  3256. * used in combination with $content_model.
  3257. * @warning This must be lowercase
  3258. * @warning This is a temporary variable that is not available after
  3259. * being processed by HTMLDefinition
  3260. * @type string
  3261. */
  3262. public $content_model_type;
  3263. /**
  3264. * Does the element have a content model (#PCDATA | Inline)*? This
  3265. * is important for chameleon ins and del processing in
  3266. * HTMLPurifier_ChildDef_Chameleon. Dynamically set: modules don't
  3267. * have to worry about this one.
  3268. * @type bool
  3269. */
  3270. public $descendants_are_inline = false;
  3271. /**
  3272. * List of the names of required attributes this element has.
  3273. * Dynamically populated by HTMLPurifier_HTMLDefinition::getElement()
  3274. * @type array
  3275. */
  3276. public $required_attr = array();
  3277. /**
  3278. * Lookup table of tags excluded from all descendants of this tag.
  3279. * @type array
  3280. * @note SGML permits exclusions for all descendants, but this is
  3281. * not possible with DTDs or XML Schemas. W3C has elected to
  3282. * use complicated compositions of content_models to simulate
  3283. * exclusion for children, but we go the simpler, SGML-style
  3284. * route of flat-out exclusions, which correctly apply to
  3285. * all descendants and not just children. Note that the XHTML
  3286. * Modularization Abstract Modules are blithely unaware of such
  3287. * distinctions.
  3288. */
  3289. public $excludes = array();
  3290. /**
  3291. * This tag is explicitly auto-closed by the following tags.
  3292. * @type array
  3293. */
  3294. public $autoclose = array();
  3295. /**
  3296. * If a foreign element is found in this element, test if it is
  3297. * allowed by this sub-element; if it is, instead of closing the
  3298. * current element, place it inside this element.
  3299. * @type string
  3300. */
  3301. public $wrap;
  3302. /**
  3303. * Whether or not this is a formatting element affected by the
  3304. * "Active Formatting Elements" algorithm.
  3305. * @type bool
  3306. */
  3307. public $formatting;
  3308. /**
  3309. * Low-level factory constructor for creating new standalone element defs
  3310. */
  3311. public static function create($content_model, $content_model_type, $attr)
  3312. {
  3313. $def = new HTMLPurifier_ElementDef();
  3314. $def->content_model = $content_model;
  3315. $def->content_model_type = $content_model_type;
  3316. $def->attr = $attr;
  3317. return $def;
  3318. }
  3319. /**
  3320. * Merges the values of another element definition into this one.
  3321. * Values from the new element def take precedence if a value is
  3322. * not mergeable.
  3323. * @param HTMLPurifier_ElementDef $def
  3324. */
  3325. public function mergeIn($def)
  3326. {
  3327. // later keys takes precedence
  3328. foreach ($def->attr as $k => $v) {
  3329. if ($k === 0) {
  3330. // merge in the includes
  3331. // sorry, no way to override an include
  3332. foreach ($v as $v2) {
  3333. $this->attr[0][] = $v2;
  3334. }
  3335. continue;
  3336. }
  3337. if ($v === false) {
  3338. if (isset($this->attr[$k])) {
  3339. unset($this->attr[$k]);
  3340. }
  3341. continue;
  3342. }
  3343. $this->attr[$k] = $v;
  3344. }
  3345. $this->_mergeAssocArray($this->excludes, $def->excludes);
  3346. $this->attr_transform_pre = array_merge($this->attr_transform_pre, $def->attr_transform_pre);
  3347. $this->attr_transform_post = array_merge($this->attr_transform_post, $def->attr_transform_post);
  3348. if (!empty($def->content_model)) {
  3349. $this->content_model =
  3350. str_replace("#SUPER", $this->content_model, $def->content_model);
  3351. $this->child = false;
  3352. }
  3353. if (!empty($def->content_model_type)) {
  3354. $this->content_model_type = $def->content_model_type;
  3355. $this->child = false;
  3356. }
  3357. if (!is_null($def->child)) {
  3358. $this->child = $def->child;
  3359. }
  3360. if (!is_null($def->formatting)) {
  3361. $this->formatting = $def->formatting;
  3362. }
  3363. if ($def->descendants_are_inline) {
  3364. $this->descendants_are_inline = $def->descendants_are_inline;
  3365. }
  3366. }
  3367. /**
  3368. * Merges one array into another, removes values which equal false
  3369. * @param $a1 Array by reference that is merged into
  3370. * @param $a2 Array that merges into $a1
  3371. */
  3372. private function _mergeAssocArray(&$a1, $a2)
  3373. {
  3374. foreach ($a2 as $k => $v) {
  3375. if ($v === false) {
  3376. if (isset($a1[$k])) {
  3377. unset($a1[$k]);
  3378. }
  3379. continue;
  3380. }
  3381. $a1[$k] = $v;
  3382. }
  3383. }
  3384. }
  3385. /**
  3386. * A UTF-8 specific character encoder that handles cleaning and transforming.
  3387. * @note All functions in this class should be static.
  3388. */
  3389. class HTMLPurifier_Encoder
  3390. {
  3391. /**
  3392. * Constructor throws fatal error if you attempt to instantiate class
  3393. */
  3394. private function __construct()
  3395. {
  3396. trigger_error('Cannot instantiate encoder, call methods statically', E_USER_ERROR);
  3397. }
  3398. /**
  3399. * Error-handler that mutes errors, alternative to shut-up operator.
  3400. */
  3401. public static function muteErrorHandler()
  3402. {
  3403. }
  3404. /**
  3405. * iconv wrapper which mutes errors, but doesn't work around bugs.
  3406. * @param string $in Input encoding
  3407. * @param string $out Output encoding
  3408. * @param string $text The text to convert
  3409. * @return string
  3410. */
  3411. public static function unsafeIconv($in, $out, $text)
  3412. {
  3413. set_error_handler(array('HTMLPurifier_Encoder', 'muteErrorHandler'));
  3414. $r = iconv($in, $out, $text);
  3415. restore_error_handler();
  3416. return $r;
  3417. }
  3418. /**
  3419. * iconv wrapper which mutes errors and works around bugs.
  3420. * @param string $in Input encoding
  3421. * @param string $out Output encoding
  3422. * @param string $text The text to convert
  3423. * @param int $max_chunk_size
  3424. * @return string
  3425. */
  3426. public static function iconv($in, $out, $text, $max_chunk_size = 8000)
  3427. {
  3428. $code = self::testIconvTruncateBug();
  3429. if ($code == self::ICONV_OK) {
  3430. return self::unsafeIconv($in, $out, $text);
  3431. } elseif ($code == self::ICONV_TRUNCATES) {
  3432. // we can only work around this if the input character set
  3433. // is utf-8
  3434. if ($in == 'utf-8') {
  3435. if ($max_chunk_size < 4) {
  3436. trigger_error('max_chunk_size is too small', E_USER_WARNING);
  3437. return false;
  3438. }
  3439. // split into 8000 byte chunks, but be careful to handle
  3440. // multibyte boundaries properly
  3441. if (($c = strlen($text)) <= $max_chunk_size) {
  3442. return self::unsafeIconv($in, $out, $text);
  3443. }
  3444. $r = '';
  3445. $i = 0;
  3446. while (true) {
  3447. if ($i + $max_chunk_size >= $c) {
  3448. $r .= self::unsafeIconv($in, $out, substr($text, $i));
  3449. break;
  3450. }
  3451. // wibble the boundary
  3452. if (0x80 != (0xC0 & ord($text[$i + $max_chunk_size]))) {
  3453. $chunk_size = $max_chunk_size;
  3454. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 1]))) {
  3455. $chunk_size = $max_chunk_size - 1;
  3456. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 2]))) {
  3457. $chunk_size = $max_chunk_size - 2;
  3458. } elseif (0x80 != (0xC0 & ord($text[$i + $max_chunk_size - 3]))) {
  3459. $chunk_size = $max_chunk_size - 3;
  3460. } else {
  3461. return false; // rather confusing UTF-8...
  3462. }
  3463. $chunk = substr($text, $i, $chunk_size); // substr doesn't mind overlong lengths
  3464. $r .= self::unsafeIconv($in, $out, $chunk);
  3465. $i += $chunk_size;
  3466. }
  3467. return $r;
  3468. } else {
  3469. return false;
  3470. }
  3471. } else {
  3472. return false;
  3473. }
  3474. }
  3475. /**
  3476. * Cleans a UTF-8 string for well-formedness and SGML validity
  3477. *
  3478. * It will parse according to UTF-8 and return a valid UTF8 string, with
  3479. * non-SGML codepoints excluded.
  3480. *
  3481. * @param string $str The string to clean
  3482. * @param bool $force_php
  3483. * @return string
  3484. *
  3485. * @note Just for reference, the non-SGML code points are 0 to 31 and
  3486. * 127 to 159, inclusive. However, we allow code points 9, 10
  3487. * and 13, which are the tab, line feed and carriage return
  3488. * respectively. 128 and above the code points map to multibyte
  3489. * UTF-8 representations.
  3490. *
  3491. * @note Fallback code adapted from utf8ToUnicode by Henri Sivonen and
  3492. * hsivonen@iki.fi at <http://iki.fi/hsivonen/php-utf8/> under the
  3493. * LGPL license. Notes on what changed are inside, but in general,
  3494. * the original code transformed UTF-8 text into an array of integer
  3495. * Unicode codepoints. Understandably, transforming that back to
  3496. * a string would be somewhat expensive, so the function was modded to
  3497. * directly operate on the string. However, this discourages code
  3498. * reuse, and the logic enumerated here would be useful for any
  3499. * function that needs to be able to understand UTF-8 characters.
  3500. * As of right now, only smart lossless character encoding converters
  3501. * would need that, and I'm probably not going to implement them.
  3502. * Once again, PHP 6 should solve all our problems.
  3503. */
  3504. public static function cleanUTF8($str, $force_php = false)
  3505. {
  3506. // UTF-8 validity is checked since PHP 4.3.5
  3507. // This is an optimization: if the string is already valid UTF-8, no
  3508. // need to do PHP stuff. 99% of the time, this will be the case.
  3509. // The regexp matches the XML char production, as well as well as excluding
  3510. // non-SGML codepoints U+007F to U+009F
  3511. if (preg_match(
  3512. '/^[\x{9}\x{A}\x{D}\x{20}-\x{7E}\x{A0}-\x{D7FF}\x{E000}-\x{FFFD}\x{10000}-\x{10FFFF}]*$/Du',
  3513. $str
  3514. )) {
  3515. return $str;
  3516. }
  3517. $mState = 0; // cached expected number of octets after the current octet
  3518. // until the beginning of the next UTF8 character sequence
  3519. $mUcs4 = 0; // cached Unicode character
  3520. $mBytes = 1; // cached expected number of octets in the current sequence
  3521. // original code involved an $out that was an array of Unicode
  3522. // codepoints. Instead of having to convert back into UTF-8, we've
  3523. // decided to directly append valid UTF-8 characters onto a string
  3524. // $out once they're done. $char accumulates raw bytes, while $mUcs4
  3525. // turns into the Unicode code point, so there's some redundancy.
  3526. $out = '';
  3527. $char = '';
  3528. $len = strlen($str);
  3529. for ($i = 0; $i < $len; $i++) {
  3530. $in = ord($str{$i});
  3531. $char .= $str[$i]; // append byte to char
  3532. if (0 == $mState) {
  3533. // When mState is zero we expect either a US-ASCII character
  3534. // or a multi-octet sequence.
  3535. if (0 == (0x80 & ($in))) {
  3536. // US-ASCII, pass straight through.
  3537. if (($in <= 31 || $in == 127) &&
  3538. !($in == 9 || $in == 13 || $in == 10) // save \r\t\n
  3539. ) {
  3540. // control characters, remove
  3541. } else {
  3542. $out .= $char;
  3543. }
  3544. // reset
  3545. $char = '';
  3546. $mBytes = 1;
  3547. } elseif (0xC0 == (0xE0 & ($in))) {
  3548. // First octet of 2 octet sequence
  3549. $mUcs4 = ($in);
  3550. $mUcs4 = ($mUcs4 & 0x1F) << 6;
  3551. $mState = 1;
  3552. $mBytes = 2;
  3553. } elseif (0xE0 == (0xF0 & ($in))) {
  3554. // First octet of 3 octet sequence
  3555. $mUcs4 = ($in);
  3556. $mUcs4 = ($mUcs4 & 0x0F) << 12;
  3557. $mState = 2;
  3558. $mBytes = 3;
  3559. } elseif (0xF0 == (0xF8 & ($in))) {
  3560. // First octet of 4 octet sequence
  3561. $mUcs4 = ($in);
  3562. $mUcs4 = ($mUcs4 & 0x07) << 18;
  3563. $mState = 3;
  3564. $mBytes = 4;
  3565. } elseif (0xF8 == (0xFC & ($in))) {
  3566. // First octet of 5 octet sequence.
  3567. //
  3568. // This is illegal because the encoded codepoint must be
  3569. // either:
  3570. // (a) not the shortest form or
  3571. // (b) outside the Unicode range of 0-0x10FFFF.
  3572. // Rather than trying to resynchronize, we will carry on
  3573. // until the end of the sequence and let the later error
  3574. // handling code catch it.
  3575. $mUcs4 = ($in);
  3576. $mUcs4 = ($mUcs4 & 0x03) << 24;
  3577. $mState = 4;
  3578. $mBytes = 5;
  3579. } elseif (0xFC == (0xFE & ($in))) {
  3580. // First octet of 6 octet sequence, see comments for 5
  3581. // octet sequence.
  3582. $mUcs4 = ($in);
  3583. $mUcs4 = ($mUcs4 & 1) << 30;
  3584. $mState = 5;
  3585. $mBytes = 6;
  3586. } else {
  3587. // Current octet is neither in the US-ASCII range nor a
  3588. // legal first octet of a multi-octet sequence.
  3589. $mState = 0;
  3590. $mUcs4 = 0;
  3591. $mBytes = 1;
  3592. $char = '';
  3593. }
  3594. } else {
  3595. // When mState is non-zero, we expect a continuation of the
  3596. // multi-octet sequence
  3597. if (0x80 == (0xC0 & ($in))) {
  3598. // Legal continuation.
  3599. $shift = ($mState - 1) * 6;
  3600. $tmp = $in;
  3601. $tmp = ($tmp & 0x0000003F) << $shift;
  3602. $mUcs4 |= $tmp;
  3603. if (0 == --$mState) {
  3604. // End of the multi-octet sequence. mUcs4 now contains
  3605. // the final Unicode codepoint to be output
  3606. // Check for illegal sequences and codepoints.
  3607. // From Unicode 3.1, non-shortest form is illegal
  3608. if (((2 == $mBytes) && ($mUcs4 < 0x0080)) ||
  3609. ((3 == $mBytes) && ($mUcs4 < 0x0800)) ||
  3610. ((4 == $mBytes) && ($mUcs4 < 0x10000)) ||
  3611. (4 < $mBytes) ||
  3612. // From Unicode 3.2, surrogate characters = illegal
  3613. (($mUcs4 & 0xFFFFF800) == 0xD800) ||
  3614. // Codepoints outside the Unicode range are illegal
  3615. ($mUcs4 > 0x10FFFF)
  3616. ) {
  3617. } elseif (0xFEFF != $mUcs4 && // omit BOM
  3618. // check for valid Char unicode codepoints
  3619. (
  3620. 0x9 == $mUcs4 ||
  3621. 0xA == $mUcs4 ||
  3622. 0xD == $mUcs4 ||
  3623. (0x20 <= $mUcs4 && 0x7E >= $mUcs4) ||
  3624. // 7F-9F is not strictly prohibited by XML,
  3625. // but it is non-SGML, and thus we don't allow it
  3626. (0xA0 <= $mUcs4 && 0xD7FF >= $mUcs4) ||
  3627. (0x10000 <= $mUcs4 && 0x10FFFF >= $mUcs4)
  3628. )
  3629. ) {
  3630. $out .= $char;
  3631. }
  3632. // initialize UTF8 cache (reset)
  3633. $mState = 0;
  3634. $mUcs4 = 0;
  3635. $mBytes = 1;
  3636. $char = '';
  3637. }
  3638. } else {
  3639. // ((0xC0 & (*in) != 0x80) && (mState != 0))
  3640. // Incomplete multi-octet sequence.
  3641. // used to result in complete fail, but we'll reset
  3642. $mState = 0;
  3643. $mUcs4 = 0;
  3644. $mBytes = 1;
  3645. $char ='';
  3646. }
  3647. }
  3648. }
  3649. return $out;
  3650. }
  3651. /**
  3652. * Translates a Unicode codepoint into its corresponding UTF-8 character.
  3653. * @note Based on Feyd's function at
  3654. * <http://forums.devnetwork.net/viewtopic.php?p=191404#191404>,
  3655. * which is in public domain.
  3656. * @note While we're going to do code point parsing anyway, a good
  3657. * optimization would be to refuse to translate code points that
  3658. * are non-SGML characters. However, this could lead to duplication.
  3659. * @note This is very similar to the unichr function in
  3660. * maintenance/generate-entity-file.php (although this is superior,
  3661. * due to its sanity checks).
  3662. */
  3663. // +----------+----------+----------+----------+
  3664. // | 33222222 | 22221111 | 111111 | |
  3665. // | 10987654 | 32109876 | 54321098 | 76543210 | bit
  3666. // +----------+----------+----------+----------+
  3667. // | | | | 0xxxxxxx | 1 byte 0x00000000..0x0000007F
  3668. // | | | 110yyyyy | 10xxxxxx | 2 byte 0x00000080..0x000007FF
  3669. // | | 1110zzzz | 10yyyyyy | 10xxxxxx | 3 byte 0x00000800..0x0000FFFF
  3670. // | 11110www | 10wwzzzz | 10yyyyyy | 10xxxxxx | 4 byte 0x00010000..0x0010FFFF
  3671. // +----------+----------+----------+----------+
  3672. // | 00000000 | 00011111 | 11111111 | 11111111 | Theoretical upper limit of legal scalars: 2097151 (0x001FFFFF)
  3673. // | 00000000 | 00010000 | 11111111 | 11111111 | Defined upper limit of legal scalar codes
  3674. // +----------+----------+----------+----------+
  3675. public static function unichr($code)
  3676. {
  3677. if ($code > 1114111 or $code < 0 or
  3678. ($code >= 55296 and $code <= 57343) ) {
  3679. // bits are set outside the "valid" range as defined
  3680. // by UNICODE 4.1.0
  3681. return '';
  3682. }
  3683. $x = $y = $z = $w = 0;
  3684. if ($code < 128) {
  3685. // regular ASCII character
  3686. $x = $code;
  3687. } else {
  3688. // set up bits for UTF-8
  3689. $x = ($code & 63) | 128;
  3690. if ($code < 2048) {
  3691. $y = (($code & 2047) >> 6) | 192;
  3692. } else {
  3693. $y = (($code & 4032) >> 6) | 128;
  3694. if ($code < 65536) {
  3695. $z = (($code >> 12) & 15) | 224;
  3696. } else {
  3697. $z = (($code >> 12) & 63) | 128;
  3698. $w = (($code >> 18) & 7) | 240;
  3699. }
  3700. }
  3701. }
  3702. // set up the actual character
  3703. $ret = '';
  3704. if ($w) {
  3705. $ret .= chr($w);
  3706. }
  3707. if ($z) {
  3708. $ret .= chr($z);
  3709. }
  3710. if ($y) {
  3711. $ret .= chr($y);
  3712. }
  3713. $ret .= chr($x);
  3714. return $ret;
  3715. }
  3716. /**
  3717. * @return bool
  3718. */
  3719. public static function iconvAvailable()
  3720. {
  3721. static $iconv = null;
  3722. if ($iconv === null) {
  3723. $iconv = function_exists('iconv') && self::testIconvTruncateBug() != self::ICONV_UNUSABLE;
  3724. }
  3725. return $iconv;
  3726. }
  3727. /**
  3728. * Convert a string to UTF-8 based on configuration.
  3729. * @param string $str The string to convert
  3730. * @param HTMLPurifier_Config $config
  3731. * @param HTMLPurifier_Context $context
  3732. * @return string
  3733. */
  3734. public static function convertToUTF8($str, $config, $context)
  3735. {
  3736. $encoding = $config->get('Core.Encoding');
  3737. if ($encoding === 'utf-8') {
  3738. return $str;
  3739. }
  3740. static $iconv = null;
  3741. if ($iconv === null) {
  3742. $iconv = self::iconvAvailable();
  3743. }
  3744. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  3745. // unaffected by bugs, since UTF-8 support all characters
  3746. $str = self::unsafeIconv($encoding, 'utf-8//IGNORE', $str);
  3747. if ($str === false) {
  3748. // $encoding is not a valid encoding
  3749. trigger_error('Invalid encoding ' . $encoding, E_USER_ERROR);
  3750. return '';
  3751. }
  3752. // If the string is bjorked by Shift_JIS or a similar encoding
  3753. // that doesn't support all of ASCII, convert the naughty
  3754. // characters to their true byte-wise ASCII/UTF-8 equivalents.
  3755. $str = strtr($str, self::testEncodingSupportsASCII($encoding));
  3756. return $str;
  3757. } elseif ($encoding === 'iso-8859-1') {
  3758. $str = utf8_encode($str);
  3759. return $str;
  3760. }
  3761. $bug = HTMLPurifier_Encoder::testIconvTruncateBug();
  3762. if ($bug == self::ICONV_OK) {
  3763. trigger_error('Encoding not supported, please install iconv', E_USER_ERROR);
  3764. } else {
  3765. trigger_error(
  3766. 'You have a buggy version of iconv, see https://bugs.php.net/bug.php?id=48147 ' .
  3767. 'and http://sourceware.org/bugzilla/show_bug.cgi?id=13541',
  3768. E_USER_ERROR
  3769. );
  3770. }
  3771. }
  3772. /**
  3773. * Converts a string from UTF-8 based on configuration.
  3774. * @param string $str The string to convert
  3775. * @param HTMLPurifier_Config $config
  3776. * @param HTMLPurifier_Context $context
  3777. * @return string
  3778. * @note Currently, this is a lossy conversion, with unexpressable
  3779. * characters being omitted.
  3780. */
  3781. public static function convertFromUTF8($str, $config, $context)
  3782. {
  3783. $encoding = $config->get('Core.Encoding');
  3784. if ($escape = $config->get('Core.EscapeNonASCIICharacters')) {
  3785. $str = self::convertToASCIIDumbLossless($str);
  3786. }
  3787. if ($encoding === 'utf-8') {
  3788. return $str;
  3789. }
  3790. static $iconv = null;
  3791. if ($iconv === null) {
  3792. $iconv = self::iconvAvailable();
  3793. }
  3794. if ($iconv && !$config->get('Test.ForceNoIconv')) {
  3795. // Undo our previous fix in convertToUTF8, otherwise iconv will barf
  3796. $ascii_fix = self::testEncodingSupportsASCII($encoding);
  3797. if (!$escape && !empty($ascii_fix)) {
  3798. $clear_fix = array();
  3799. foreach ($ascii_fix as $utf8 => $native) {
  3800. $clear_fix[$utf8] = '';
  3801. }
  3802. $str = strtr($str, $clear_fix);
  3803. }
  3804. $str = strtr($str, array_flip($ascii_fix));
  3805. // Normal stuff
  3806. $str = self::iconv('utf-8', $encoding . '//IGNORE', $str);
  3807. return $str;
  3808. } elseif ($encoding === 'iso-8859-1') {
  3809. $str = utf8_decode($str);
  3810. return $str;
  3811. }
  3812. trigger_error('Encoding not supported', E_USER_ERROR);
  3813. // You might be tempted to assume that the ASCII representation
  3814. // might be OK, however, this is *not* universally true over all
  3815. // encodings. So we take the conservative route here, rather
  3816. // than forcibly turn on %Core.EscapeNonASCIICharacters
  3817. }
  3818. /**
  3819. * Lossless (character-wise) conversion of HTML to ASCII
  3820. * @param string $str UTF-8 string to be converted to ASCII
  3821. * @return string ASCII encoded string with non-ASCII character entity-ized
  3822. * @warning Adapted from MediaWiki, claiming fair use: this is a common
  3823. * algorithm. If you disagree with this license fudgery,
  3824. * implement it yourself.
  3825. * @note Uses decimal numeric entities since they are best supported.
  3826. * @note This is a DUMB function: it has no concept of keeping
  3827. * character entities that the projected character encoding
  3828. * can allow. We could possibly implement a smart version
  3829. * but that would require it to also know which Unicode
  3830. * codepoints the charset supported (not an easy task).
  3831. * @note Sort of with cleanUTF8() but it assumes that $str is
  3832. * well-formed UTF-8
  3833. */
  3834. public static function convertToASCIIDumbLossless($str)
  3835. {
  3836. $bytesleft = 0;
  3837. $result = '';
  3838. $working = 0;
  3839. $len = strlen($str);
  3840. for ($i = 0; $i < $len; $i++) {
  3841. $bytevalue = ord($str[$i]);
  3842. if ($bytevalue <= 0x7F) { //0xxx xxxx
  3843. $result .= chr($bytevalue);
  3844. $bytesleft = 0;
  3845. } elseif ($bytevalue <= 0xBF) { //10xx xxxx
  3846. $working = $working << 6;
  3847. $working += ($bytevalue & 0x3F);
  3848. $bytesleft--;
  3849. if ($bytesleft <= 0) {
  3850. $result .= "&#" . $working . ";";
  3851. }
  3852. } elseif ($bytevalue <= 0xDF) { //110x xxxx
  3853. $working = $bytevalue & 0x1F;
  3854. $bytesleft = 1;
  3855. } elseif ($bytevalue <= 0xEF) { //1110 xxxx
  3856. $working = $bytevalue & 0x0F;
  3857. $bytesleft = 2;
  3858. } else { //1111 0xxx
  3859. $working = $bytevalue & 0x07;
  3860. $bytesleft = 3;
  3861. }
  3862. }
  3863. return $result;
  3864. }
  3865. /** No bugs detected in iconv. */
  3866. const ICONV_OK = 0;
  3867. /** Iconv truncates output if converting from UTF-8 to another
  3868. * character set with //IGNORE, and a non-encodable character is found */
  3869. const ICONV_TRUNCATES = 1;
  3870. /** Iconv does not support //IGNORE, making it unusable for
  3871. * transcoding purposes */
  3872. const ICONV_UNUSABLE = 2;
  3873. /**
  3874. * glibc iconv has a known bug where it doesn't handle the magic
  3875. * //IGNORE stanza correctly. In particular, rather than ignore
  3876. * characters, it will return an EILSEQ after consuming some number
  3877. * of characters, and expect you to restart iconv as if it were
  3878. * an E2BIG. Old versions of PHP did not respect the errno, and
  3879. * returned the fragment, so as a result you would see iconv
  3880. * mysteriously truncating output. We can work around this by
  3881. * manually chopping our input into segments of about 8000
  3882. * characters, as long as PHP ignores the error code. If PHP starts
  3883. * paying attention to the error code, iconv becomes unusable.
  3884. *
  3885. * @return int Error code indicating severity of bug.
  3886. */
  3887. public static function testIconvTruncateBug()
  3888. {
  3889. static $code = null;
  3890. if ($code === null) {
  3891. // better not use iconv, otherwise infinite loop!
  3892. $r = self::unsafeIconv('utf-8', 'ascii//IGNORE', "\xCE\xB1" . str_repeat('a', 9000));
  3893. if ($r === false) {
  3894. $code = self::ICONV_UNUSABLE;
  3895. } elseif (($c = strlen($r)) < 9000) {
  3896. $code = self::ICONV_TRUNCATES;
  3897. } elseif ($c > 9000) {
  3898. trigger_error(
  3899. 'Your copy of iconv is extremely buggy. Please notify HTML Purifier maintainers: ' .
  3900. 'include your iconv version as per phpversion()',
  3901. E_USER_ERROR
  3902. );
  3903. } else {
  3904. $code = self::ICONV_OK;
  3905. }
  3906. }
  3907. return $code;
  3908. }
  3909. /**
  3910. * This expensive function tests whether or not a given character
  3911. * encoding supports ASCII. 7/8-bit encodings like Shift_JIS will
  3912. * fail this test, and require special processing. Variable width
  3913. * encodings shouldn't ever fail.
  3914. *
  3915. * @param string $encoding Encoding name to test, as per iconv format
  3916. * @param bool $bypass Whether or not to bypass the precompiled arrays.
  3917. * @return Array of UTF-8 characters to their corresponding ASCII,
  3918. * which can be used to "undo" any overzealous iconv action.
  3919. */
  3920. public static function testEncodingSupportsASCII($encoding, $bypass = false)
  3921. {
  3922. // All calls to iconv here are unsafe, proof by case analysis:
  3923. // If ICONV_OK, no difference.
  3924. // If ICONV_TRUNCATE, all calls involve one character inputs,
  3925. // so bug is not triggered.
  3926. // If ICONV_UNUSABLE, this call is irrelevant
  3927. static $encodings = array();
  3928. if (!$bypass) {
  3929. if (isset($encodings[$encoding])) {
  3930. return $encodings[$encoding];
  3931. }
  3932. $lenc = strtolower($encoding);
  3933. switch ($lenc) {
  3934. case 'shift_jis':
  3935. return array("\xC2\xA5" => '\\', "\xE2\x80\xBE" => '~');
  3936. case 'johab':
  3937. return array("\xE2\x82\xA9" => '\\');
  3938. }
  3939. if (strpos($lenc, 'iso-8859-') === 0) {
  3940. return array();
  3941. }
  3942. }
  3943. $ret = array();
  3944. if (self::unsafeIconv('UTF-8', $encoding, 'a') === false) {
  3945. return false;
  3946. }
  3947. for ($i = 0x20; $i <= 0x7E; $i++) { // all printable ASCII chars
  3948. $c = chr($i); // UTF-8 char
  3949. $r = self::unsafeIconv('UTF-8', "$encoding//IGNORE", $c); // initial conversion
  3950. if ($r === '' ||
  3951. // This line is needed for iconv implementations that do not
  3952. // omit characters that do not exist in the target character set
  3953. ($r === $c && self::unsafeIconv($encoding, 'UTF-8//IGNORE', $r) !== $c)
  3954. ) {
  3955. // Reverse engineer: what's the UTF-8 equiv of this byte
  3956. // sequence? This assumes that there's no variable width
  3957. // encoding that doesn't support ASCII.
  3958. $ret[self::unsafeIconv($encoding, 'UTF-8//IGNORE', $c)] = $c;
  3959. }
  3960. }
  3961. $encodings[$encoding] = $ret;
  3962. return $ret;
  3963. }
  3964. }
  3965. /**
  3966. * Object that provides entity lookup table from entity name to character
  3967. */
  3968. class HTMLPurifier_EntityLookup
  3969. {
  3970. /**
  3971. * Assoc array of entity name to character represented.
  3972. * @type array
  3973. */
  3974. public $table;
  3975. /**
  3976. * Sets up the entity lookup table from the serialized file contents.
  3977. * @param bool $file
  3978. * @note The serialized contents are versioned, but were generated
  3979. * using the maintenance script generate_entity_file.php
  3980. * @warning This is not in constructor to help enforce the Singleton
  3981. */
  3982. public function setup($file = false)
  3983. {
  3984. if (!$file) {
  3985. $file = HTMLPURIFIER_PREFIX . '/HTMLPurifier/EntityLookup/entities.ser';
  3986. }
  3987. $this->table = unserialize(file_get_contents($file));
  3988. }
  3989. /**
  3990. * Retrieves sole instance of the object.
  3991. * @param bool|HTMLPurifier_EntityLookup $prototype Optional prototype of custom lookup table to overload with.
  3992. * @return HTMLPurifier_EntityLookup
  3993. */
  3994. public static function instance($prototype = false)
  3995. {
  3996. // no references, since PHP doesn't copy unless modified
  3997. static $instance = null;
  3998. if ($prototype) {
  3999. $instance = $prototype;
  4000. } elseif (!$instance) {
  4001. $instance = new HTMLPurifier_EntityLookup();
  4002. $instance->setup();
  4003. }
  4004. return $instance;
  4005. }
  4006. }
  4007. // if want to implement error collecting here, we'll need to use some sort
  4008. // of global data (probably trigger_error) because it's impossible to pass
  4009. // $config or $context to the callback functions.
  4010. /**
  4011. * Handles referencing and derefencing character entities
  4012. */
  4013. class HTMLPurifier_EntityParser
  4014. {
  4015. /**
  4016. * Reference to entity lookup table.
  4017. * @type HTMLPurifier_EntityLookup
  4018. */
  4019. protected $_entity_lookup;
  4020. /**
  4021. * Callback regex string for parsing entities.
  4022. * @type string
  4023. */
  4024. protected $_substituteEntitiesRegex =
  4025. '/&(?:[#]x([a-fA-F0-9]+)|[#]0*(\d+)|([A-Za-z_:][A-Za-z0-9.\-_:]*));?/';
  4026. // 1. hex 2. dec 3. string (XML style)
  4027. /**
  4028. * Decimal to parsed string conversion table for special entities.
  4029. * @type array
  4030. */
  4031. protected $_special_dec2str =
  4032. array(
  4033. 34 => '"',
  4034. 38 => '&',
  4035. 39 => "'",
  4036. 60 => '<',
  4037. 62 => '>'
  4038. );
  4039. /**
  4040. * Stripped entity names to decimal conversion table for special entities.
  4041. * @type array
  4042. */
  4043. protected $_special_ent2dec =
  4044. array(
  4045. 'quot' => 34,
  4046. 'amp' => 38,
  4047. 'lt' => 60,
  4048. 'gt' => 62
  4049. );
  4050. /**
  4051. * Substitutes non-special entities with their parsed equivalents. Since
  4052. * running this whenever you have parsed character is t3h 5uck, we run
  4053. * it before everything else.
  4054. *
  4055. * @param string $string String to have non-special entities parsed.
  4056. * @return string Parsed string.
  4057. */
  4058. public function substituteNonSpecialEntities($string)
  4059. {
  4060. // it will try to detect missing semicolons, but don't rely on it
  4061. return preg_replace_callback(
  4062. $this->_substituteEntitiesRegex,
  4063. array($this, 'nonSpecialEntityCallback'),
  4064. $string
  4065. );
  4066. }
  4067. /**
  4068. * Callback function for substituteNonSpecialEntities() that does the work.
  4069. *
  4070. * @param array $matches PCRE matches array, with 0 the entire match, and
  4071. * either index 1, 2 or 3 set with a hex value, dec value,
  4072. * or string (respectively).
  4073. * @return string Replacement string.
  4074. */
  4075. protected function nonSpecialEntityCallback($matches)
  4076. {
  4077. // replaces all but big five
  4078. $entity = $matches[0];
  4079. $is_num = (@$matches[0][1] === '#');
  4080. if ($is_num) {
  4081. $is_hex = (@$entity[2] === 'x');
  4082. $code = $is_hex ? hexdec($matches[1]) : (int) $matches[2];
  4083. // abort for special characters
  4084. if (isset($this->_special_dec2str[$code])) {
  4085. return $entity;
  4086. }
  4087. return HTMLPurifier_Encoder::unichr($code);
  4088. } else {
  4089. if (isset($this->_special_ent2dec[$matches[3]])) {
  4090. return $entity;
  4091. }
  4092. if (!$this->_entity_lookup) {
  4093. $this->_entity_lookup = HTMLPurifier_EntityLookup::instance();
  4094. }
  4095. if (isset($this->_entity_lookup->table[$matches[3]])) {
  4096. return $this->_entity_lookup->table[$matches[3]];
  4097. } else {
  4098. return $entity;
  4099. }
  4100. }
  4101. }
  4102. /**
  4103. * Substitutes only special entities with their parsed equivalents.
  4104. *
  4105. * @notice We try to avoid calling this function because otherwise, it
  4106. * would have to be called a lot (for every parsed section).
  4107. *
  4108. * @param string $string String to have non-special entities parsed.
  4109. * @return string Parsed string.
  4110. */
  4111. public function substituteSpecialEntities($string)
  4112. {
  4113. return preg_replace_callback(
  4114. $this->_substituteEntitiesRegex,
  4115. array($this, 'specialEntityCallback'),
  4116. $string
  4117. );
  4118. }
  4119. /**
  4120. * Callback function for substituteSpecialEntities() that does the work.
  4121. *
  4122. * This callback has same syntax as nonSpecialEntityCallback().
  4123. *
  4124. * @param array $matches PCRE-style matches array, with 0 the entire match, and
  4125. * either index 1, 2 or 3 set with a hex value, dec value,
  4126. * or string (respectively).
  4127. * @return string Replacement string.
  4128. */
  4129. protected function specialEntityCallback($matches)
  4130. {
  4131. $entity = $matches[0];
  4132. $is_num = (@$matches[0][1] === '#');
  4133. if ($is_num) {
  4134. $is_hex = (@$entity[2] === 'x');
  4135. $int = $is_hex ? hexdec($matches[1]) : (int) $matches[2];
  4136. return isset($this->_special_dec2str[$int]) ?
  4137. $this->_special_dec2str[$int] :
  4138. $entity;
  4139. } else {
  4140. return isset($this->_special_ent2dec[$matches[3]]) ?
  4141. $this->_special_ent2dec[$matches[3]] :
  4142. $entity;
  4143. }
  4144. }
  4145. }
  4146. /**
  4147. * Error collection class that enables HTML Purifier to report HTML
  4148. * problems back to the user
  4149. */
  4150. class HTMLPurifier_ErrorCollector
  4151. {
  4152. /**
  4153. * Identifiers for the returned error array. These are purposely numeric
  4154. * so list() can be used.
  4155. */
  4156. const LINENO = 0;
  4157. const SEVERITY = 1;
  4158. const MESSAGE = 2;
  4159. const CHILDREN = 3;
  4160. /**
  4161. * @type array
  4162. */
  4163. protected $errors;
  4164. /**
  4165. * @type array
  4166. */
  4167. protected $_current;
  4168. /**
  4169. * @type array
  4170. */
  4171. protected $_stacks = array(array());
  4172. /**
  4173. * @type HTMLPurifier_Language
  4174. */
  4175. protected $locale;
  4176. /**
  4177. * @type HTMLPurifier_Generator
  4178. */
  4179. protected $generator;
  4180. /**
  4181. * @type HTMLPurifier_Context
  4182. */
  4183. protected $context;
  4184. /**
  4185. * @type array
  4186. */
  4187. protected $lines = array();
  4188. /**
  4189. * @param HTMLPurifier_Context $context
  4190. */
  4191. public function __construct($context)
  4192. {
  4193. $this->locale =& $context->get('Locale');
  4194. $this->context = $context;
  4195. $this->_current =& $this->_stacks[0];
  4196. $this->errors =& $this->_stacks[0];
  4197. }
  4198. /**
  4199. * Sends an error message to the collector for later use
  4200. * @param int $severity Error severity, PHP error style (don't use E_USER_)
  4201. * @param string $msg Error message text
  4202. */
  4203. public function send($severity, $msg)
  4204. {
  4205. $args = array();
  4206. if (func_num_args() > 2) {
  4207. $args = func_get_args();
  4208. array_shift($args);
  4209. unset($args[0]);
  4210. }
  4211. $token = $this->context->get('CurrentToken', true);
  4212. $line = $token ? $token->line : $this->context->get('CurrentLine', true);
  4213. $col = $token ? $token->col : $this->context->get('CurrentCol', true);
  4214. $attr = $this->context->get('CurrentAttr', true);
  4215. // perform special substitutions, also add custom parameters
  4216. $subst = array();
  4217. if (!is_null($token)) {
  4218. $args['CurrentToken'] = $token;
  4219. }
  4220. if (!is_null($attr)) {
  4221. $subst['$CurrentAttr.Name'] = $attr;
  4222. if (isset($token->attr[$attr])) {
  4223. $subst['$CurrentAttr.Value'] = $token->attr[$attr];
  4224. }
  4225. }
  4226. if (empty($args)) {
  4227. $msg = $this->locale->getMessage($msg);
  4228. } else {
  4229. $msg = $this->locale->formatMessage($msg, $args);
  4230. }
  4231. if (!empty($subst)) {
  4232. $msg = strtr($msg, $subst);
  4233. }
  4234. // (numerically indexed)
  4235. $error = array(
  4236. self::LINENO => $line,
  4237. self::SEVERITY => $severity,
  4238. self::MESSAGE => $msg,
  4239. self::CHILDREN => array()
  4240. );
  4241. $this->_current[] = $error;
  4242. // NEW CODE BELOW ...
  4243. // Top-level errors are either:
  4244. // TOKEN type, if $value is set appropriately, or
  4245. // "syntax" type, if $value is null
  4246. $new_struct = new HTMLPurifier_ErrorStruct();
  4247. $new_struct->type = HTMLPurifier_ErrorStruct::TOKEN;
  4248. if ($token) {
  4249. $new_struct->value = clone $token;
  4250. }
  4251. if (is_int($line) && is_int($col)) {
  4252. if (isset($this->lines[$line][$col])) {
  4253. $struct = $this->lines[$line][$col];
  4254. } else {
  4255. $struct = $this->lines[$line][$col] = $new_struct;
  4256. }
  4257. // These ksorts may present a performance problem
  4258. ksort($this->lines[$line], SORT_NUMERIC);
  4259. } else {
  4260. if (isset($this->lines[-1])) {
  4261. $struct = $this->lines[-1];
  4262. } else {
  4263. $struct = $this->lines[-1] = $new_struct;
  4264. }
  4265. }
  4266. ksort($this->lines, SORT_NUMERIC);
  4267. // Now, check if we need to operate on a lower structure
  4268. if (!empty($attr)) {
  4269. $struct = $struct->getChild(HTMLPurifier_ErrorStruct::ATTR, $attr);
  4270. if (!$struct->value) {
  4271. $struct->value = array($attr, 'PUT VALUE HERE');
  4272. }
  4273. }
  4274. if (!empty($cssprop)) {
  4275. $struct = $struct->getChild(HTMLPurifier_ErrorStruct::CSSPROP, $cssprop);
  4276. if (!$struct->value) {
  4277. // if we tokenize CSS this might be a little more difficult to do
  4278. $struct->value = array($cssprop, 'PUT VALUE HERE');
  4279. }
  4280. }
  4281. // Ok, structs are all setup, now time to register the error
  4282. $struct->addError($severity, $msg);
  4283. }
  4284. /**
  4285. * Retrieves raw error data for custom formatter to use
  4286. */
  4287. public function getRaw()
  4288. {
  4289. return $this->errors;
  4290. }
  4291. /**
  4292. * Default HTML formatting implementation for error messages
  4293. * @param HTMLPurifier_Config $config Configuration, vital for HTML output nature
  4294. * @param array $errors Errors array to display; used for recursion.
  4295. * @return string
  4296. */
  4297. public function getHTMLFormatted($config, $errors = null)
  4298. {
  4299. $ret = array();
  4300. $this->generator = new HTMLPurifier_Generator($config, $this->context);
  4301. if ($errors === null) {
  4302. $errors = $this->errors;
  4303. }
  4304. // 'At line' message needs to be removed
  4305. // generation code for new structure goes here. It needs to be recursive.
  4306. foreach ($this->lines as $line => $col_array) {
  4307. if ($line == -1) {
  4308. continue;
  4309. }
  4310. foreach ($col_array as $col => $struct) {
  4311. $this->_renderStruct($ret, $struct, $line, $col);
  4312. }
  4313. }
  4314. if (isset($this->lines[-1])) {
  4315. $this->_renderStruct($ret, $this->lines[-1]);
  4316. }
  4317. if (empty($errors)) {
  4318. return '<p>' . $this->locale->getMessage('ErrorCollector: No errors') . '</p>';
  4319. } else {
  4320. return '<ul><li>' . implode('</li><li>', $ret) . '</li></ul>';
  4321. }
  4322. }
  4323. private function _renderStruct(&$ret, $struct, $line = null, $col = null)
  4324. {
  4325. $stack = array($struct);
  4326. $context_stack = array(array());
  4327. while ($current = array_pop($stack)) {
  4328. $context = array_pop($context_stack);
  4329. foreach ($current->errors as $error) {
  4330. list($severity, $msg) = $error;
  4331. $string = '';
  4332. $string .= '<div>';
  4333. // W3C uses an icon to indicate the severity of the error.
  4334. $error = $this->locale->getErrorName($severity);
  4335. $string .= "<span class=\"error e$severity\"><strong>$error</strong></span> ";
  4336. if (!is_null($line) && !is_null($col)) {
  4337. $string .= "<em class=\"location\">Line $line, Column $col: </em> ";
  4338. } else {
  4339. $string .= '<em class="location">End of Document: </em> ';
  4340. }
  4341. $string .= '<strong class="description">' . $this->generator->escape($msg) . '</strong> ';
  4342. $string .= '</div>';
  4343. // Here, have a marker for the character on the column appropriate.
  4344. // Be sure to clip extremely long lines.
  4345. //$string .= '<pre>';
  4346. //$string .= '';
  4347. //$string .= '</pre>';
  4348. $ret[] = $string;
  4349. }
  4350. foreach ($current->children as $array) {
  4351. $context[] = $current;
  4352. $stack = array_merge($stack, array_reverse($array, true));
  4353. for ($i = count($array); $i > 0; $i--) {
  4354. $context_stack[] = $context;
  4355. }
  4356. }
  4357. }
  4358. }
  4359. }
  4360. /**
  4361. * Records errors for particular segments of an HTML document such as tokens,
  4362. * attributes or CSS properties. They can contain error structs (which apply
  4363. * to components of what they represent), but their main purpose is to hold
  4364. * errors applying to whatever struct is being used.
  4365. */
  4366. class HTMLPurifier_ErrorStruct
  4367. {
  4368. /**
  4369. * Possible values for $children first-key. Note that top-level structures
  4370. * are automatically token-level.
  4371. */
  4372. const TOKEN = 0;
  4373. const ATTR = 1;
  4374. const CSSPROP = 2;
  4375. /**
  4376. * Type of this struct.
  4377. * @type string
  4378. */
  4379. public $type;
  4380. /**
  4381. * Value of the struct we are recording errors for. There are various
  4382. * values for this:
  4383. * - TOKEN: Instance of HTMLPurifier_Token
  4384. * - ATTR: array('attr-name', 'value')
  4385. * - CSSPROP: array('prop-name', 'value')
  4386. * @type mixed
  4387. */
  4388. public $value;
  4389. /**
  4390. * Errors registered for this structure.
  4391. * @type array
  4392. */
  4393. public $errors = array();
  4394. /**
  4395. * Child ErrorStructs that are from this structure. For example, a TOKEN
  4396. * ErrorStruct would contain ATTR ErrorStructs. This is a multi-dimensional
  4397. * array in structure: [TYPE]['identifier']
  4398. * @type array
  4399. */
  4400. public $children = array();
  4401. /**
  4402. * @param string $type
  4403. * @param string $id
  4404. * @return mixed
  4405. */
  4406. public function getChild($type, $id)
  4407. {
  4408. if (!isset($this->children[$type][$id])) {
  4409. $this->children[$type][$id] = new HTMLPurifier_ErrorStruct();
  4410. $this->children[$type][$id]->type = $type;
  4411. }
  4412. return $this->children[$type][$id];
  4413. }
  4414. /**
  4415. * @param int $severity
  4416. * @param string $message
  4417. */
  4418. public function addError($severity, $message)
  4419. {
  4420. $this->errors[] = array($severity, $message);
  4421. }
  4422. }
  4423. /**
  4424. * Global exception class for HTML Purifier; any exceptions we throw
  4425. * are from here.
  4426. */
  4427. class HTMLPurifier_Exception extends Exception
  4428. {
  4429. }
  4430. /**
  4431. * Represents a pre or post processing filter on HTML Purifier's output
  4432. *
  4433. * Sometimes, a little ad-hoc fixing of HTML has to be done before
  4434. * it gets sent through HTML Purifier: you can use filters to acheive
  4435. * this effect. For instance, YouTube videos can be preserved using
  4436. * this manner. You could have used a decorator for this task, but
  4437. * PHP's support for them is not terribly robust, so we're going
  4438. * to just loop through the filters.
  4439. *
  4440. * Filters should be exited first in, last out. If there are three filters,
  4441. * named 1, 2 and 3, the order of execution should go 1->preFilter,
  4442. * 2->preFilter, 3->preFilter, purify, 3->postFilter, 2->postFilter,
  4443. * 1->postFilter.
  4444. *
  4445. * @note Methods are not declared abstract as it is perfectly legitimate
  4446. * for an implementation not to want anything to happen on a step
  4447. */
  4448. class HTMLPurifier_Filter
  4449. {
  4450. /**
  4451. * Name of the filter for identification purposes.
  4452. * @type string
  4453. */
  4454. public $name;
  4455. /**
  4456. * Pre-processor function, handles HTML before HTML Purifier
  4457. * @param string $html
  4458. * @param HTMLPurifier_Config $config
  4459. * @param HTMLPurifier_Context $context
  4460. * @return string
  4461. */
  4462. public function preFilter($html, $config, $context)
  4463. {
  4464. return $html;
  4465. }
  4466. /**
  4467. * Post-processor function, handles HTML after HTML Purifier
  4468. * @param string $html
  4469. * @param HTMLPurifier_Config $config
  4470. * @param HTMLPurifier_Context $context
  4471. * @return string
  4472. */
  4473. public function postFilter($html, $config, $context)
  4474. {
  4475. return $html;
  4476. }
  4477. }
  4478. /**
  4479. * Generates HTML from tokens.
  4480. * @todo Refactor interface so that configuration/context is determined
  4481. * upon instantiation, no need for messy generateFromTokens() calls
  4482. * @todo Make some of the more internal functions protected, and have
  4483. * unit tests work around that
  4484. */
  4485. class HTMLPurifier_Generator
  4486. {
  4487. /**
  4488. * Whether or not generator should produce XML output.
  4489. * @type bool
  4490. */
  4491. private $_xhtml = true;
  4492. /**
  4493. * :HACK: Whether or not generator should comment the insides of <script> tags.
  4494. * @type bool
  4495. */
  4496. private $_scriptFix = false;
  4497. /**
  4498. * Cache of HTMLDefinition during HTML output to determine whether or
  4499. * not attributes should be minimized.
  4500. * @type HTMLPurifier_HTMLDefinition
  4501. */
  4502. private $_def;
  4503. /**
  4504. * Cache of %Output.SortAttr.
  4505. * @type bool
  4506. */
  4507. private $_sortAttr;
  4508. /**
  4509. * Cache of %Output.FlashCompat.
  4510. * @type bool
  4511. */
  4512. private $_flashCompat;
  4513. /**
  4514. * Cache of %Output.FixInnerHTML.
  4515. * @type bool
  4516. */
  4517. private $_innerHTMLFix;
  4518. /**
  4519. * Stack for keeping track of object information when outputting IE
  4520. * compatibility code.
  4521. * @type array
  4522. */
  4523. private $_flashStack = array();
  4524. /**
  4525. * Configuration for the generator
  4526. * @type HTMLPurifier_Config
  4527. */
  4528. protected $config;
  4529. /**
  4530. * @param HTMLPurifier_Config $config
  4531. * @param HTMLPurifier_Context $context
  4532. */
  4533. public function __construct($config, $context)
  4534. {
  4535. $this->config = $config;
  4536. $this->_scriptFix = $config->get('Output.CommentScriptContents');
  4537. $this->_innerHTMLFix = $config->get('Output.FixInnerHTML');
  4538. $this->_sortAttr = $config->get('Output.SortAttr');
  4539. $this->_flashCompat = $config->get('Output.FlashCompat');
  4540. $this->_def = $config->getHTMLDefinition();
  4541. $this->_xhtml = $this->_def->doctype->xml;
  4542. }
  4543. /**
  4544. * Generates HTML from an array of tokens.
  4545. * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token
  4546. * @return string Generated HTML
  4547. */
  4548. public function generateFromTokens($tokens)
  4549. {
  4550. if (!$tokens) {
  4551. return '';
  4552. }
  4553. // Basic algorithm
  4554. $html = '';
  4555. for ($i = 0, $size = count($tokens); $i < $size; $i++) {
  4556. if ($this->_scriptFix && $tokens[$i]->name === 'script'
  4557. && $i + 2 < $size && $tokens[$i+2] instanceof HTMLPurifier_Token_End) {
  4558. // script special case
  4559. // the contents of the script block must be ONE token
  4560. // for this to work.
  4561. $html .= $this->generateFromToken($tokens[$i++]);
  4562. $html .= $this->generateScriptFromToken($tokens[$i++]);
  4563. }
  4564. $html .= $this->generateFromToken($tokens[$i]);
  4565. }
  4566. // Tidy cleanup
  4567. if (extension_loaded('tidy') && $this->config->get('Output.TidyFormat')) {
  4568. $tidy = new Tidy;
  4569. $tidy->parseString(
  4570. $html,
  4571. array(
  4572. 'indent'=> true,
  4573. 'output-xhtml' => $this->_xhtml,
  4574. 'show-body-only' => true,
  4575. 'indent-spaces' => 2,
  4576. 'wrap' => 68,
  4577. ),
  4578. 'utf8'
  4579. );
  4580. $tidy->cleanRepair();
  4581. $html = (string) $tidy; // explicit cast necessary
  4582. }
  4583. // Normalize newlines to system defined value
  4584. if ($this->config->get('Core.NormalizeNewlines')) {
  4585. $nl = $this->config->get('Output.Newline');
  4586. if ($nl === null) {
  4587. $nl = PHP_EOL;
  4588. }
  4589. if ($nl !== "\n") {
  4590. $html = str_replace("\n", $nl, $html);
  4591. }
  4592. }
  4593. return $html;
  4594. }
  4595. /**
  4596. * Generates HTML from a single token.
  4597. * @param HTMLPurifier_Token $token HTMLPurifier_Token object.
  4598. * @return string Generated HTML
  4599. */
  4600. public function generateFromToken($token)
  4601. {
  4602. if (!$token instanceof HTMLPurifier_Token) {
  4603. trigger_error('Cannot generate HTML from non-HTMLPurifier_Token object', E_USER_WARNING);
  4604. return '';
  4605. } elseif ($token instanceof HTMLPurifier_Token_Start) {
  4606. $attr = $this->generateAttributes($token->attr, $token->name);
  4607. if ($this->_flashCompat) {
  4608. if ($token->name == "object") {
  4609. $flash = new stdclass();
  4610. $flash->attr = $token->attr;
  4611. $flash->param = array();
  4612. $this->_flashStack[] = $flash;
  4613. }
  4614. }
  4615. return '<' . $token->name . ($attr ? ' ' : '') . $attr . '>';
  4616. } elseif ($token instanceof HTMLPurifier_Token_End) {
  4617. $_extra = '';
  4618. if ($this->_flashCompat) {
  4619. if ($token->name == "object" && !empty($this->_flashStack)) {
  4620. // doesn't do anything for now
  4621. }
  4622. }
  4623. return $_extra . '</' . $token->name . '>';
  4624. } elseif ($token instanceof HTMLPurifier_Token_Empty) {
  4625. if ($this->_flashCompat && $token->name == "param" && !empty($this->_flashStack)) {
  4626. $this->_flashStack[count($this->_flashStack)-1]->param[$token->attr['name']] = $token->attr['value'];
  4627. }
  4628. $attr = $this->generateAttributes($token->attr, $token->name);
  4629. return '<' . $token->name . ($attr ? ' ' : '') . $attr .
  4630. ( $this->_xhtml ? ' /': '' ) // <br /> v. <br>
  4631. . '>';
  4632. } elseif ($token instanceof HTMLPurifier_Token_Text) {
  4633. return $this->escape($token->data, ENT_NOQUOTES);
  4634. } elseif ($token instanceof HTMLPurifier_Token_Comment) {
  4635. return '<!--' . $token->data . '-->';
  4636. } else {
  4637. return '';
  4638. }
  4639. }
  4640. /**
  4641. * Special case processor for the contents of script tags
  4642. * @param HTMLPurifier_Token $token HTMLPurifier_Token object.
  4643. * @return string
  4644. * @warning This runs into problems if there's already a literal
  4645. * --> somewhere inside the script contents.
  4646. */
  4647. public function generateScriptFromToken($token)
  4648. {
  4649. if (!$token instanceof HTMLPurifier_Token_Text) {
  4650. return $this->generateFromToken($token);
  4651. }
  4652. // Thanks <http://lachy.id.au/log/2005/05/script-comments>
  4653. $data = preg_replace('#//\s*$#', '', $token->data);
  4654. return '<!--//--><![CDATA[//><!--' . "\n" . trim($data) . "\n" . '//--><!]]>';
  4655. }
  4656. /**
  4657. * Generates attribute declarations from attribute array.
  4658. * @note This does not include the leading or trailing space.
  4659. * @param array $assoc_array_of_attributes Attribute array
  4660. * @param string $element Name of element attributes are for, used to check
  4661. * attribute minimization.
  4662. * @return string Generated HTML fragment for insertion.
  4663. */
  4664. public function generateAttributes($assoc_array_of_attributes, $element = '')
  4665. {
  4666. $html = '';
  4667. if ($this->_sortAttr) {
  4668. ksort($assoc_array_of_attributes);
  4669. }
  4670. foreach ($assoc_array_of_attributes as $key => $value) {
  4671. if (!$this->_xhtml) {
  4672. // Remove namespaced attributes
  4673. if (strpos($key, ':') !== false) {
  4674. continue;
  4675. }
  4676. // Check if we should minimize the attribute: val="val" -> val
  4677. if ($element && !empty($this->_def->info[$element]->attr[$key]->minimized)) {
  4678. $html .= $key . ' ';
  4679. continue;
  4680. }
  4681. }
  4682. // Workaround for Internet Explorer innerHTML bug.
  4683. // Essentially, Internet Explorer, when calculating
  4684. // innerHTML, omits quotes if there are no instances of
  4685. // angled brackets, quotes or spaces. However, when parsing
  4686. // HTML (for example, when you assign to innerHTML), it
  4687. // treats backticks as quotes. Thus,
  4688. // <img alt="``" />
  4689. // becomes
  4690. // <img alt=`` />
  4691. // becomes
  4692. // <img alt='' />
  4693. // Fortunately, all we need to do is trigger an appropriate
  4694. // quoting style, which we do by adding an extra space.
  4695. // This also is consistent with the W3C spec, which states
  4696. // that user agents may ignore leading or trailing
  4697. // whitespace (in fact, most don't, at least for attributes
  4698. // like alt, but an extra space at the end is barely
  4699. // noticeable). Still, we have a configuration knob for
  4700. // this, since this transformation is not necesary if you
  4701. // don't process user input with innerHTML or you don't plan
  4702. // on supporting Internet Explorer.
  4703. if ($this->_innerHTMLFix) {
  4704. if (strpos($value, '`') !== false) {
  4705. // check if correct quoting style would not already be
  4706. // triggered
  4707. if (strcspn($value, '"\' <>') === strlen($value)) {
  4708. // protect!
  4709. $value .= ' ';
  4710. }
  4711. }
  4712. }
  4713. $html .= $key.'="'.$this->escape($value).'" ';
  4714. }
  4715. return rtrim($html);
  4716. }
  4717. /**
  4718. * Escapes raw text data.
  4719. * @todo This really ought to be protected, but until we have a facility
  4720. * for properly generating HTML here w/o using tokens, it stays
  4721. * public.
  4722. * @param string $string String data to escape for HTML.
  4723. * @param int $quote Quoting style, like htmlspecialchars. ENT_NOQUOTES is
  4724. * permissible for non-attribute output.
  4725. * @return string escaped data.
  4726. */
  4727. public function escape($string, $quote = null)
  4728. {
  4729. // Workaround for APC bug on Mac Leopard reported by sidepodcast
  4730. // http://htmlpurifier.org/phorum/read.php?3,4823,4846
  4731. if ($quote === null) {
  4732. $quote = ENT_COMPAT;
  4733. }
  4734. return htmlspecialchars($string, $quote, 'UTF-8');
  4735. }
  4736. }
  4737. /**
  4738. * Definition of the purified HTML that describes allowed children,
  4739. * attributes, and many other things.
  4740. *
  4741. * Conventions:
  4742. *
  4743. * All member variables that are prefixed with info
  4744. * (including the main $info array) are used by HTML Purifier internals
  4745. * and should not be directly edited when customizing the HTMLDefinition.
  4746. * They can usually be set via configuration directives or custom
  4747. * modules.
  4748. *
  4749. * On the other hand, member variables without the info prefix are used
  4750. * internally by the HTMLDefinition and MUST NOT be used by other HTML
  4751. * Purifier internals. Many of them, however, are public, and may be
  4752. * edited by userspace code to tweak the behavior of HTMLDefinition.
  4753. *
  4754. * @note This class is inspected by Printer_HTMLDefinition; please
  4755. * update that class if things here change.
  4756. *
  4757. * @warning Directives that change this object's structure must be in
  4758. * the HTML or Attr namespace!
  4759. */
  4760. class HTMLPurifier_HTMLDefinition extends HTMLPurifier_Definition
  4761. {
  4762. // FULLY-PUBLIC VARIABLES ---------------------------------------------
  4763. /**
  4764. * Associative array of element names to HTMLPurifier_ElementDef.
  4765. * @type HTMLPurifier_ElementDef[]
  4766. */
  4767. public $info = array();
  4768. /**
  4769. * Associative array of global attribute name to attribute definition.
  4770. * @type array
  4771. */
  4772. public $info_global_attr = array();
  4773. /**
  4774. * String name of parent element HTML will be going into.
  4775. * @type string
  4776. */
  4777. public $info_parent = 'div';
  4778. /**
  4779. * Definition for parent element, allows parent element to be a
  4780. * tag that's not allowed inside the HTML fragment.
  4781. * @type HTMLPurifier_ElementDef
  4782. */
  4783. public $info_parent_def;
  4784. /**
  4785. * String name of element used to wrap inline elements in block context.
  4786. * @type string
  4787. * @note This is rarely used except for BLOCKQUOTEs in strict mode
  4788. */
  4789. public $info_block_wrapper = 'p';
  4790. /**
  4791. * Associative array of deprecated tag name to HTMLPurifier_TagTransform.
  4792. * @type array
  4793. */
  4794. public $info_tag_transform = array();
  4795. /**
  4796. * Indexed list of HTMLPurifier_AttrTransform to be performed before validation.
  4797. * @type HTMLPurifier_AttrTransform[]
  4798. */
  4799. public $info_attr_transform_pre = array();
  4800. /**
  4801. * Indexed list of HTMLPurifier_AttrTransform to be performed after validation.
  4802. * @type HTMLPurifier_AttrTransform[]
  4803. */
  4804. public $info_attr_transform_post = array();
  4805. /**
  4806. * Nested lookup array of content set name (Block, Inline) to
  4807. * element name to whether or not it belongs in that content set.
  4808. * @type array
  4809. */
  4810. public $info_content_sets = array();
  4811. /**
  4812. * Indexed list of HTMLPurifier_Injector to be used.
  4813. * @type HTMLPurifier_Injector[]
  4814. */
  4815. public $info_injector = array();
  4816. /**
  4817. * Doctype object
  4818. * @type HTMLPurifier_Doctype
  4819. */
  4820. public $doctype;
  4821. // RAW CUSTOMIZATION STUFF --------------------------------------------
  4822. /**
  4823. * Adds a custom attribute to a pre-existing element
  4824. * @note This is strictly convenience, and does not have a corresponding
  4825. * method in HTMLPurifier_HTMLModule
  4826. * @param string $element_name Element name to add attribute to
  4827. * @param string $attr_name Name of attribute
  4828. * @param mixed $def Attribute definition, can be string or object, see
  4829. * HTMLPurifier_AttrTypes for details
  4830. */
  4831. public function addAttribute($element_name, $attr_name, $def)
  4832. {
  4833. $module = $this->getAnonymousModule();
  4834. if (!isset($module->info[$element_name])) {
  4835. $element = $module->addBlankElement($element_name);
  4836. } else {
  4837. $element = $module->info[$element_name];
  4838. }
  4839. $element->attr[$attr_name] = $def;
  4840. }
  4841. /**
  4842. * Adds a custom element to your HTML definition
  4843. * @see HTMLPurifier_HTMLModule::addElement() for detailed
  4844. * parameter and return value descriptions.
  4845. */
  4846. public function addElement($element_name, $type, $contents, $attr_collections, $attributes = array())
  4847. {
  4848. $module = $this->getAnonymousModule();
  4849. // assume that if the user is calling this, the element
  4850. // is safe. This may not be a good idea
  4851. $element = $module->addElement($element_name, $type, $contents, $attr_collections, $attributes);
  4852. return $element;
  4853. }
  4854. /**
  4855. * Adds a blank element to your HTML definition, for overriding
  4856. * existing behavior
  4857. * @param string $element_name
  4858. * @return HTMLPurifier_ElementDef
  4859. * @see HTMLPurifier_HTMLModule::addBlankElement() for detailed
  4860. * parameter and return value descriptions.
  4861. */
  4862. public function addBlankElement($element_name)
  4863. {
  4864. $module = $this->getAnonymousModule();
  4865. $element = $module->addBlankElement($element_name);
  4866. return $element;
  4867. }
  4868. /**
  4869. * Retrieves a reference to the anonymous module, so you can
  4870. * bust out advanced features without having to make your own
  4871. * module.
  4872. * @return HTMLPurifier_HTMLModule
  4873. */
  4874. public function getAnonymousModule()
  4875. {
  4876. if (!$this->_anonModule) {
  4877. $this->_anonModule = new HTMLPurifier_HTMLModule();
  4878. $this->_anonModule->name = 'Anonymous';
  4879. }
  4880. return $this->_anonModule;
  4881. }
  4882. private $_anonModule = null;
  4883. // PUBLIC BUT INTERNAL VARIABLES --------------------------------------
  4884. /**
  4885. * @type string
  4886. */
  4887. public $type = 'HTML';
  4888. /**
  4889. * @type HTMLPurifier_HTMLModuleManager
  4890. */
  4891. public $manager;
  4892. /**
  4893. * Performs low-cost, preliminary initialization.
  4894. */
  4895. public function __construct()
  4896. {
  4897. $this->manager = new HTMLPurifier_HTMLModuleManager();
  4898. }
  4899. /**
  4900. * @param HTMLPurifier_Config $config
  4901. */
  4902. protected function doSetup($config)
  4903. {
  4904. $this->processModules($config);
  4905. $this->setupConfigStuff($config);
  4906. unset($this->manager);
  4907. // cleanup some of the element definitions
  4908. foreach ($this->info as $k => $v) {
  4909. unset($this->info[$k]->content_model);
  4910. unset($this->info[$k]->content_model_type);
  4911. }
  4912. }
  4913. /**
  4914. * Extract out the information from the manager
  4915. * @param HTMLPurifier_Config $config
  4916. */
  4917. protected function processModules($config)
  4918. {
  4919. if ($this->_anonModule) {
  4920. // for user specific changes
  4921. // this is late-loaded so we don't have to deal with PHP4
  4922. // reference wonky-ness
  4923. $this->manager->addModule($this->_anonModule);
  4924. unset($this->_anonModule);
  4925. }
  4926. $this->manager->setup($config);
  4927. $this->doctype = $this->manager->doctype;
  4928. foreach ($this->manager->modules as $module) {
  4929. foreach ($module->info_tag_transform as $k => $v) {
  4930. if ($v === false) {
  4931. unset($this->info_tag_transform[$k]);
  4932. } else {
  4933. $this->info_tag_transform[$k] = $v;
  4934. }
  4935. }
  4936. foreach ($module->info_attr_transform_pre as $k => $v) {
  4937. if ($v === false) {
  4938. unset($this->info_attr_transform_pre[$k]);
  4939. } else {
  4940. $this->info_attr_transform_pre[$k] = $v;
  4941. }
  4942. }
  4943. foreach ($module->info_attr_transform_post as $k => $v) {
  4944. if ($v === false) {
  4945. unset($this->info_attr_transform_post[$k]);
  4946. } else {
  4947. $this->info_attr_transform_post[$k] = $v;
  4948. }
  4949. }
  4950. foreach ($module->info_injector as $k => $v) {
  4951. if ($v === false) {
  4952. unset($this->info_injector[$k]);
  4953. } else {
  4954. $this->info_injector[$k] = $v;
  4955. }
  4956. }
  4957. }
  4958. $this->info = $this->manager->getElements();
  4959. $this->info_content_sets = $this->manager->contentSets->lookup;
  4960. }
  4961. /**
  4962. * Sets up stuff based on config. We need a better way of doing this.
  4963. * @param HTMLPurifier_Config $config
  4964. */
  4965. protected function setupConfigStuff($config)
  4966. {
  4967. $block_wrapper = $config->get('HTML.BlockWrapper');
  4968. if (isset($this->info_content_sets['Block'][$block_wrapper])) {
  4969. $this->info_block_wrapper = $block_wrapper;
  4970. } else {
  4971. trigger_error(
  4972. 'Cannot use non-block element as block wrapper',
  4973. E_USER_ERROR
  4974. );
  4975. }
  4976. $parent = $config->get('HTML.Parent');
  4977. $def = $this->manager->getElement($parent, true);
  4978. if ($def) {
  4979. $this->info_parent = $parent;
  4980. $this->info_parent_def = $def;
  4981. } else {
  4982. trigger_error(
  4983. 'Cannot use unrecognized element as parent',
  4984. E_USER_ERROR
  4985. );
  4986. $this->info_parent_def = $this->manager->getElement($this->info_parent, true);
  4987. }
  4988. // support template text
  4989. $support = "(for information on implementing this, see the support forums) ";
  4990. // setup allowed elements -----------------------------------------
  4991. $allowed_elements = $config->get('HTML.AllowedElements');
  4992. $allowed_attributes = $config->get('HTML.AllowedAttributes'); // retrieve early
  4993. if (!is_array($allowed_elements) && !is_array($allowed_attributes)) {
  4994. $allowed = $config->get('HTML.Allowed');
  4995. if (is_string($allowed)) {
  4996. list($allowed_elements, $allowed_attributes) = $this->parseTinyMCEAllowedList($allowed);
  4997. }
  4998. }
  4999. if (is_array($allowed_elements)) {
  5000. foreach ($this->info as $name => $d) {
  5001. if (!isset($allowed_elements[$name])) {
  5002. unset($this->info[$name]);
  5003. }
  5004. unset($allowed_elements[$name]);
  5005. }
  5006. // emit errors
  5007. foreach ($allowed_elements as $element => $d) {
  5008. $element = htmlspecialchars($element); // PHP doesn't escape errors, be careful!
  5009. trigger_error("Element '$element' is not supported $support", E_USER_WARNING);
  5010. }
  5011. }
  5012. // setup allowed attributes ---------------------------------------
  5013. $allowed_attributes_mutable = $allowed_attributes; // by copy!
  5014. if (is_array($allowed_attributes)) {
  5015. // This actually doesn't do anything, since we went away from
  5016. // global attributes. It's possible that userland code uses
  5017. // it, but HTMLModuleManager doesn't!
  5018. foreach ($this->info_global_attr as $attr => $x) {
  5019. $keys = array($attr, "*@$attr", "*.$attr");
  5020. $delete = true;
  5021. foreach ($keys as $key) {
  5022. if ($delete && isset($allowed_attributes[$key])) {
  5023. $delete = false;
  5024. }
  5025. if (isset($allowed_attributes_mutable[$key])) {
  5026. unset($allowed_attributes_mutable[$key]);
  5027. }
  5028. }
  5029. if ($delete) {
  5030. unset($this->info_global_attr[$attr]);
  5031. }
  5032. }
  5033. foreach ($this->info as $tag => $info) {
  5034. foreach ($info->attr as $attr => $x) {
  5035. $keys = array("$tag@$attr", $attr, "*@$attr", "$tag.$attr", "*.$attr");
  5036. $delete = true;
  5037. foreach ($keys as $key) {
  5038. if ($delete && isset($allowed_attributes[$key])) {
  5039. $delete = false;
  5040. }
  5041. if (isset($allowed_attributes_mutable[$key])) {
  5042. unset($allowed_attributes_mutable[$key]);
  5043. }
  5044. }
  5045. if ($delete) {
  5046. if ($this->info[$tag]->attr[$attr]->required) {
  5047. trigger_error(
  5048. "Required attribute '$attr' in element '$tag' " .
  5049. "was not allowed, which means '$tag' will not be allowed either",
  5050. E_USER_WARNING
  5051. );
  5052. }
  5053. unset($this->info[$tag]->attr[$attr]);
  5054. }
  5055. }
  5056. }
  5057. // emit errors
  5058. foreach ($allowed_attributes_mutable as $elattr => $d) {
  5059. $bits = preg_split('/[.@]/', $elattr, 2);
  5060. $c = count($bits);
  5061. switch ($c) {
  5062. case 2:
  5063. if ($bits[0] !== '*') {
  5064. $element = htmlspecialchars($bits[0]);
  5065. $attribute = htmlspecialchars($bits[1]);
  5066. if (!isset($this->info[$element])) {
  5067. trigger_error(
  5068. "Cannot allow attribute '$attribute' if element " .
  5069. "'$element' is not allowed/supported $support"
  5070. );
  5071. } else {
  5072. trigger_error(
  5073. "Attribute '$attribute' in element '$element' not supported $support",
  5074. E_USER_WARNING
  5075. );
  5076. }
  5077. break;
  5078. }
  5079. // otherwise fall through
  5080. case 1:
  5081. $attribute = htmlspecialchars($bits[0]);
  5082. trigger_error(
  5083. "Global attribute '$attribute' is not ".
  5084. "supported in any elements $support",
  5085. E_USER_WARNING
  5086. );
  5087. break;
  5088. }
  5089. }
  5090. }
  5091. // setup forbidden elements ---------------------------------------
  5092. $forbidden_elements = $config->get('HTML.ForbiddenElements');
  5093. $forbidden_attributes = $config->get('HTML.ForbiddenAttributes');
  5094. foreach ($this->info as $tag => $info) {
  5095. if (isset($forbidden_elements[$tag])) {
  5096. unset($this->info[$tag]);
  5097. continue;
  5098. }
  5099. foreach ($info->attr as $attr => $x) {
  5100. if (isset($forbidden_attributes["$tag@$attr"]) ||
  5101. isset($forbidden_attributes["*@$attr"]) ||
  5102. isset($forbidden_attributes[$attr])
  5103. ) {
  5104. unset($this->info[$tag]->attr[$attr]);
  5105. continue;
  5106. } elseif (isset($forbidden_attributes["$tag.$attr"])) { // this segment might get removed eventually
  5107. // $tag.$attr are not user supplied, so no worries!
  5108. trigger_error(
  5109. "Error with $tag.$attr: tag.attr syntax not supported for " .
  5110. "HTML.ForbiddenAttributes; use tag@attr instead",
  5111. E_USER_WARNING
  5112. );
  5113. }
  5114. }
  5115. }
  5116. foreach ($forbidden_attributes as $key => $v) {
  5117. if (strlen($key) < 2) {
  5118. continue;
  5119. }
  5120. if ($key[0] != '*') {
  5121. continue;
  5122. }
  5123. if ($key[1] == '.') {
  5124. trigger_error(
  5125. "Error with $key: *.attr syntax not supported for HTML.ForbiddenAttributes; use attr instead",
  5126. E_USER_WARNING
  5127. );
  5128. }
  5129. }
  5130. // setup injectors -----------------------------------------------------
  5131. foreach ($this->info_injector as $i => $injector) {
  5132. if ($injector->checkNeeded($config) !== false) {
  5133. // remove injector that does not have it's required
  5134. // elements/attributes present, and is thus not needed.
  5135. unset($this->info_injector[$i]);
  5136. }
  5137. }
  5138. }
  5139. /**
  5140. * Parses a TinyMCE-flavored Allowed Elements and Attributes list into
  5141. * separate lists for processing. Format is element[attr1|attr2],element2...
  5142. * @warning Although it's largely drawn from TinyMCE's implementation,
  5143. * it is different, and you'll probably have to modify your lists
  5144. * @param array $list String list to parse
  5145. * @return array
  5146. * @todo Give this its own class, probably static interface
  5147. */
  5148. public function parseTinyMCEAllowedList($list)
  5149. {
  5150. $list = str_replace(array(' ', "\t"), '', $list);
  5151. $elements = array();
  5152. $attributes = array();
  5153. $chunks = preg_split('/(,|[\n\r]+)/', $list);
  5154. foreach ($chunks as $chunk) {
  5155. if (empty($chunk)) {
  5156. continue;
  5157. }
  5158. // remove TinyMCE element control characters
  5159. if (!strpos($chunk, '[')) {
  5160. $element = $chunk;
  5161. $attr = false;
  5162. } else {
  5163. list($element, $attr) = explode('[', $chunk);
  5164. }
  5165. if ($element !== '*') {
  5166. $elements[$element] = true;
  5167. }
  5168. if (!$attr) {
  5169. continue;
  5170. }
  5171. $attr = substr($attr, 0, strlen($attr) - 1); // remove trailing ]
  5172. $attr = explode('|', $attr);
  5173. foreach ($attr as $key) {
  5174. $attributes["$element.$key"] = true;
  5175. }
  5176. }
  5177. return array($elements, $attributes);
  5178. }
  5179. }
  5180. /**
  5181. * Represents an XHTML 1.1 module, with information on elements, tags
  5182. * and attributes.
  5183. * @note Even though this is technically XHTML 1.1, it is also used for
  5184. * regular HTML parsing. We are using modulization as a convenient
  5185. * way to represent the internals of HTMLDefinition, and our
  5186. * implementation is by no means conforming and does not directly
  5187. * use the normative DTDs or XML schemas.
  5188. * @note The public variables in a module should almost directly
  5189. * correspond to the variables in HTMLPurifier_HTMLDefinition.
  5190. * However, the prefix info carries no special meaning in these
  5191. * objects (include it anyway if that's the correspondence though).
  5192. * @todo Consider making some member functions protected
  5193. */
  5194. class HTMLPurifier_HTMLModule
  5195. {
  5196. // -- Overloadable ----------------------------------------------------
  5197. /**
  5198. * Short unique string identifier of the module.
  5199. * @type string
  5200. */
  5201. public $name;
  5202. /**
  5203. * Informally, a list of elements this module changes.
  5204. * Not used in any significant way.
  5205. * @type array
  5206. */
  5207. public $elements = array();
  5208. /**
  5209. * Associative array of element names to element definitions.
  5210. * Some definitions may be incomplete, to be merged in later
  5211. * with the full definition.
  5212. * @type array
  5213. */
  5214. public $info = array();
  5215. /**
  5216. * Associative array of content set names to content set additions.
  5217. * This is commonly used to, say, add an A element to the Inline
  5218. * content set. This corresponds to an internal variable $content_sets
  5219. * and NOT info_content_sets member variable of HTMLDefinition.
  5220. * @type array
  5221. */
  5222. public $content_sets = array();
  5223. /**
  5224. * Associative array of attribute collection names to attribute
  5225. * collection additions. More rarely used for adding attributes to
  5226. * the global collections. Example is the StyleAttribute module adding
  5227. * the style attribute to the Core. Corresponds to HTMLDefinition's
  5228. * attr_collections->info, since the object's data is only info,
  5229. * with extra behavior associated with it.
  5230. * @type array
  5231. */
  5232. public $attr_collections = array();
  5233. /**
  5234. * Associative array of deprecated tag name to HTMLPurifier_TagTransform.
  5235. * @type array
  5236. */
  5237. public $info_tag_transform = array();
  5238. /**
  5239. * List of HTMLPurifier_AttrTransform to be performed before validation.
  5240. * @type array
  5241. */
  5242. public $info_attr_transform_pre = array();
  5243. /**
  5244. * List of HTMLPurifier_AttrTransform to be performed after validation.
  5245. * @type array
  5246. */
  5247. public $info_attr_transform_post = array();
  5248. /**
  5249. * List of HTMLPurifier_Injector to be performed during well-formedness fixing.
  5250. * An injector will only be invoked if all of it's pre-requisites are met;
  5251. * if an injector fails setup, there will be no error; it will simply be
  5252. * silently disabled.
  5253. * @type array
  5254. */
  5255. public $info_injector = array();
  5256. /**
  5257. * Boolean flag that indicates whether or not getChildDef is implemented.
  5258. * For optimization reasons: may save a call to a function. Be sure
  5259. * to set it if you do implement getChildDef(), otherwise it will have
  5260. * no effect!
  5261. * @type bool
  5262. */
  5263. public $defines_child_def = false;
  5264. /**
  5265. * Boolean flag whether or not this module is safe. If it is not safe, all
  5266. * of its members are unsafe. Modules are safe by default (this might be
  5267. * slightly dangerous, but it doesn't make much sense to force HTML Purifier,
  5268. * which is based off of safe HTML, to explicitly say, "This is safe," even
  5269. * though there are modules which are "unsafe")
  5270. *
  5271. * @type bool
  5272. * @note Previously, safety could be applied at an element level granularity.
  5273. * We've removed this ability, so in order to add "unsafe" elements
  5274. * or attributes, a dedicated module with this property set to false
  5275. * must be used.
  5276. */
  5277. public $safe = true;
  5278. /**
  5279. * Retrieves a proper HTMLPurifier_ChildDef subclass based on
  5280. * content_model and content_model_type member variables of
  5281. * the HTMLPurifier_ElementDef class. There is a similar function
  5282. * in HTMLPurifier_HTMLDefinition.
  5283. * @param HTMLPurifier_ElementDef $def
  5284. * @return HTMLPurifier_ChildDef subclass
  5285. */
  5286. public function getChildDef($def)
  5287. {
  5288. return false;
  5289. }
  5290. // -- Convenience -----------------------------------------------------
  5291. /**
  5292. * Convenience function that sets up a new element
  5293. * @param string $element Name of element to add
  5294. * @param string|bool $type What content set should element be registered to?
  5295. * Set as false to skip this step.
  5296. * @param string $contents Allowed children in form of:
  5297. * "$content_model_type: $content_model"
  5298. * @param array $attr_includes What attribute collections to register to
  5299. * element?
  5300. * @param array $attr What unique attributes does the element define?
  5301. * @see HTMLPurifier_ElementDef:: for in-depth descriptions of these parameters.
  5302. * @return HTMLPurifier_ElementDef Created element definition object, so you
  5303. * can set advanced parameters
  5304. */
  5305. public function addElement($element, $type, $contents, $attr_includes = array(), $attr = array())
  5306. {
  5307. $this->elements[] = $element;
  5308. // parse content_model
  5309. list($content_model_type, $content_model) = $this->parseContents($contents);
  5310. // merge in attribute inclusions
  5311. $this->mergeInAttrIncludes($attr, $attr_includes);
  5312. // add element to content sets
  5313. if ($type) {
  5314. $this->addElementToContentSet($element, $type);
  5315. }
  5316. // create element
  5317. $this->info[$element] = HTMLPurifier_ElementDef::create(
  5318. $content_model,
  5319. $content_model_type,
  5320. $attr
  5321. );
  5322. // literal object $contents means direct child manipulation
  5323. if (!is_string($contents)) {
  5324. $this->info[$element]->child = $contents;
  5325. }
  5326. return $this->info[$element];
  5327. }
  5328. /**
  5329. * Convenience function that creates a totally blank, non-standalone
  5330. * element.
  5331. * @param string $element Name of element to create
  5332. * @return HTMLPurifier_ElementDef Created element
  5333. */
  5334. public function addBlankElement($element)
  5335. {
  5336. if (!isset($this->info[$element])) {
  5337. $this->elements[] = $element;
  5338. $this->info[$element] = new HTMLPurifier_ElementDef();
  5339. $this->info[$element]->standalone = false;
  5340. } else {
  5341. trigger_error("Definition for $element already exists in module, cannot redefine");
  5342. }
  5343. return $this->info[$element];
  5344. }
  5345. /**
  5346. * Convenience function that registers an element to a content set
  5347. * @param string $element Element to register
  5348. * @param string $type Name content set (warning: case sensitive, usually upper-case
  5349. * first letter)
  5350. */
  5351. public function addElementToContentSet($element, $type)
  5352. {
  5353. if (!isset($this->content_sets[$type])) {
  5354. $this->content_sets[$type] = '';
  5355. } else {
  5356. $this->content_sets[$type] .= ' | ';
  5357. }
  5358. $this->content_sets[$type] .= $element;
  5359. }
  5360. /**
  5361. * Convenience function that transforms single-string contents
  5362. * into separate content model and content model type
  5363. * @param string $contents Allowed children in form of:
  5364. * "$content_model_type: $content_model"
  5365. * @return array
  5366. * @note If contents is an object, an array of two nulls will be
  5367. * returned, and the callee needs to take the original $contents
  5368. * and use it directly.
  5369. */
  5370. public function parseContents($contents)
  5371. {
  5372. if (!is_string($contents)) {
  5373. return array(null, null);
  5374. } // defer
  5375. switch ($contents) {
  5376. // check for shorthand content model forms
  5377. case 'Empty':
  5378. return array('empty', '');
  5379. case 'Inline':
  5380. return array('optional', 'Inline | #PCDATA');
  5381. case 'Flow':
  5382. return array('optional', 'Flow | #PCDATA');
  5383. }
  5384. list($content_model_type, $content_model) = explode(':', $contents);
  5385. $content_model_type = strtolower(trim($content_model_type));
  5386. $content_model = trim($content_model);
  5387. return array($content_model_type, $content_model);
  5388. }
  5389. /**
  5390. * Convenience function that merges a list of attribute includes into
  5391. * an attribute array.
  5392. * @param array $attr Reference to attr array to modify
  5393. * @param array $attr_includes Array of includes / string include to merge in
  5394. */
  5395. public function mergeInAttrIncludes(&$attr, $attr_includes)
  5396. {
  5397. if (!is_array($attr_includes)) {
  5398. if (empty($attr_includes)) {
  5399. $attr_includes = array();
  5400. } else {
  5401. $attr_includes = array($attr_includes);
  5402. }
  5403. }
  5404. $attr[0] = $attr_includes;
  5405. }
  5406. /**
  5407. * Convenience function that generates a lookup table with boolean
  5408. * true as value.
  5409. * @param string $list List of values to turn into a lookup
  5410. * @note You can also pass an arbitrary number of arguments in
  5411. * place of the regular argument
  5412. * @return array array equivalent of list
  5413. */
  5414. public function makeLookup($list)
  5415. {
  5416. if (is_string($list)) {
  5417. $list = func_get_args();
  5418. }
  5419. $ret = array();
  5420. foreach ($list as $value) {
  5421. if (is_null($value)) {
  5422. continue;
  5423. }
  5424. $ret[$value] = true;
  5425. }
  5426. return $ret;
  5427. }
  5428. /**
  5429. * Lazy load construction of the module after determining whether
  5430. * or not it's needed, and also when a finalized configuration object
  5431. * is available.
  5432. * @param HTMLPurifier_Config $config
  5433. */
  5434. public function setup($config)
  5435. {
  5436. }
  5437. }
  5438. class HTMLPurifier_HTMLModuleManager
  5439. {
  5440. /**
  5441. * @type HTMLPurifier_DoctypeRegistry
  5442. */
  5443. public $doctypes;
  5444. /**
  5445. * Instance of current doctype.
  5446. * @type string
  5447. */
  5448. public $doctype;
  5449. /**
  5450. * @type HTMLPurifier_AttrTypes
  5451. */
  5452. public $attrTypes;
  5453. /**
  5454. * Active instances of modules for the specified doctype are
  5455. * indexed, by name, in this array.
  5456. * @type HTMLPurifier_HTMLModule[]
  5457. */
  5458. public $modules = array();
  5459. /**
  5460. * Array of recognized HTMLPurifier_HTMLModule instances,
  5461. * indexed by module's class name. This array is usually lazy loaded, but a
  5462. * user can overload a module by pre-emptively registering it.
  5463. * @type HTMLPurifier_HTMLModule[]
  5464. */
  5465. public $registeredModules = array();
  5466. /**
  5467. * List of extra modules that were added by the user
  5468. * using addModule(). These get unconditionally merged into the current doctype, whatever
  5469. * it may be.
  5470. * @type HTMLPurifier_HTMLModule[]
  5471. */
  5472. public $userModules = array();
  5473. /**
  5474. * Associative array of element name to list of modules that have
  5475. * definitions for the element; this array is dynamically filled.
  5476. * @type array
  5477. */
  5478. public $elementLookup = array();
  5479. /**
  5480. * List of prefixes we should use for registering small names.
  5481. * @type array
  5482. */
  5483. public $prefixes = array('HTMLPurifier_HTMLModule_');
  5484. /**
  5485. * @type HTMLPurifier_ContentSets
  5486. */
  5487. public $contentSets;
  5488. /**
  5489. * @type HTMLPurifier_AttrCollections
  5490. */
  5491. public $attrCollections;
  5492. /**
  5493. * If set to true, unsafe elements and attributes will be allowed.
  5494. * @type bool
  5495. */
  5496. public $trusted = false;
  5497. public function __construct()
  5498. {
  5499. // editable internal objects
  5500. $this->attrTypes = new HTMLPurifier_AttrTypes();
  5501. $this->doctypes = new HTMLPurifier_DoctypeRegistry();
  5502. // setup basic modules
  5503. $common = array(
  5504. 'CommonAttributes', 'Text', 'Hypertext', 'List',
  5505. 'Presentation', 'Edit', 'Bdo', 'Tables', 'Image',
  5506. 'StyleAttribute',
  5507. // Unsafe:
  5508. 'Scripting', 'Object', 'Forms',
  5509. // Sorta legacy, but present in strict:
  5510. 'Name',
  5511. );
  5512. $transitional = array('Legacy', 'Target', 'Iframe');
  5513. $xml = array('XMLCommonAttributes');
  5514. $non_xml = array('NonXMLCommonAttributes');
  5515. // setup basic doctypes
  5516. $this->doctypes->register(
  5517. 'HTML 4.01 Transitional',
  5518. false,
  5519. array_merge($common, $transitional, $non_xml),
  5520. array('Tidy_Transitional', 'Tidy_Proprietary'),
  5521. array(),
  5522. '-//W3C//DTD HTML 4.01 Transitional//EN',
  5523. 'http://www.w3.org/TR/html4/loose.dtd'
  5524. );
  5525. $this->doctypes->register(
  5526. 'HTML 4.01 Strict',
  5527. false,
  5528. array_merge($common, $non_xml),
  5529. array('Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
  5530. array(),
  5531. '-//W3C//DTD HTML 4.01//EN',
  5532. 'http://www.w3.org/TR/html4/strict.dtd'
  5533. );
  5534. $this->doctypes->register(
  5535. 'XHTML 1.0 Transitional',
  5536. true,
  5537. array_merge($common, $transitional, $xml, $non_xml),
  5538. array('Tidy_Transitional', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Name'),
  5539. array(),
  5540. '-//W3C//DTD XHTML 1.0 Transitional//EN',
  5541. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'
  5542. );
  5543. $this->doctypes->register(
  5544. 'XHTML 1.0 Strict',
  5545. true,
  5546. array_merge($common, $xml, $non_xml),
  5547. array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Strict', 'Tidy_Proprietary', 'Tidy_Name'),
  5548. array(),
  5549. '-//W3C//DTD XHTML 1.0 Strict//EN',
  5550. 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd'
  5551. );
  5552. $this->doctypes->register(
  5553. 'XHTML 1.1',
  5554. true,
  5555. // Iframe is a real XHTML 1.1 module, despite being
  5556. // "transitional"!
  5557. array_merge($common, $xml, array('Ruby', 'Iframe')),
  5558. array('Tidy_Strict', 'Tidy_XHTML', 'Tidy_Proprietary', 'Tidy_Strict', 'Tidy_Name'), // Tidy_XHTML1_1
  5559. array(),
  5560. '-//W3C//DTD XHTML 1.1//EN',
  5561. 'http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd'
  5562. );
  5563. }
  5564. /**
  5565. * Registers a module to the recognized module list, useful for
  5566. * overloading pre-existing modules.
  5567. * @param $module Mixed: string module name, with or without
  5568. * HTMLPurifier_HTMLModule prefix, or instance of
  5569. * subclass of HTMLPurifier_HTMLModule.
  5570. * @param $overload Boolean whether or not to overload previous modules.
  5571. * If this is not set, and you do overload a module,
  5572. * HTML Purifier will complain with a warning.
  5573. * @note This function will not call autoload, you must instantiate
  5574. * (and thus invoke) autoload outside the method.
  5575. * @note If a string is passed as a module name, different variants
  5576. * will be tested in this order:
  5577. * - Check for HTMLPurifier_HTMLModule_$name
  5578. * - Check all prefixes with $name in order they were added
  5579. * - Check for literal object name
  5580. * - Throw fatal error
  5581. * If your object name collides with an internal class, specify
  5582. * your module manually. All modules must have been included
  5583. * externally: registerModule will not perform inclusions for you!
  5584. */
  5585. public function registerModule($module, $overload = false)
  5586. {
  5587. if (is_string($module)) {
  5588. // attempt to load the module
  5589. $original_module = $module;
  5590. $ok = false;
  5591. foreach ($this->prefixes as $prefix) {
  5592. $module = $prefix . $original_module;
  5593. if (class_exists($module)) {
  5594. $ok = true;
  5595. break;
  5596. }
  5597. }
  5598. if (!$ok) {
  5599. $module = $original_module;
  5600. if (!class_exists($module)) {
  5601. trigger_error(
  5602. $original_module . ' module does not exist',
  5603. E_USER_ERROR
  5604. );
  5605. return;
  5606. }
  5607. }
  5608. $module = new $module();
  5609. }
  5610. if (empty($module->name)) {
  5611. trigger_error('Module instance of ' . get_class($module) . ' must have name');
  5612. return;
  5613. }
  5614. if (!$overload && isset($this->registeredModules[$module->name])) {
  5615. trigger_error('Overloading ' . $module->name . ' without explicit overload parameter', E_USER_WARNING);
  5616. }
  5617. $this->registeredModules[$module->name] = $module;
  5618. }
  5619. /**
  5620. * Adds a module to the current doctype by first registering it,
  5621. * and then tacking it on to the active doctype
  5622. */
  5623. public function addModule($module)
  5624. {
  5625. $this->registerModule($module);
  5626. if (is_object($module)) {
  5627. $module = $module->name;
  5628. }
  5629. $this->userModules[] = $module;
  5630. }
  5631. /**
  5632. * Adds a class prefix that registerModule() will use to resolve a
  5633. * string name to a concrete class
  5634. */
  5635. public function addPrefix($prefix)
  5636. {
  5637. $this->prefixes[] = $prefix;
  5638. }
  5639. /**
  5640. * Performs processing on modules, after being called you may
  5641. * use getElement() and getElements()
  5642. * @param HTMLPurifier_Config $config
  5643. */
  5644. public function setup($config)
  5645. {
  5646. $this->trusted = $config->get('HTML.Trusted');
  5647. // generate
  5648. $this->doctype = $this->doctypes->make($config);
  5649. $modules = $this->doctype->modules;
  5650. // take out the default modules that aren't allowed
  5651. $lookup = $config->get('HTML.AllowedModules');
  5652. $special_cases = $config->get('HTML.CoreModules');
  5653. if (is_array($lookup)) {
  5654. foreach ($modules as $k => $m) {
  5655. if (isset($special_cases[$m])) {
  5656. continue;
  5657. }
  5658. if (!isset($lookup[$m])) {
  5659. unset($modules[$k]);
  5660. }
  5661. }
  5662. }
  5663. // custom modules
  5664. if ($config->get('HTML.Proprietary')) {
  5665. $modules[] = 'Proprietary';
  5666. }
  5667. if ($config->get('HTML.SafeObject')) {
  5668. $modules[] = 'SafeObject';
  5669. }
  5670. if ($config->get('HTML.SafeEmbed')) {
  5671. $modules[] = 'SafeEmbed';
  5672. }
  5673. if ($config->get('HTML.SafeScripting') !== array()) {
  5674. $modules[] = 'SafeScripting';
  5675. }
  5676. if ($config->get('HTML.Nofollow')) {
  5677. $modules[] = 'Nofollow';
  5678. }
  5679. if ($config->get('HTML.TargetBlank')) {
  5680. $modules[] = 'TargetBlank';
  5681. }
  5682. // NB: HTML.TargetNoreferrer must be AFTER HTML.TargetBlank
  5683. // so that its post-attr-transform gets run afterwards.
  5684. if ($config->get('HTML.TargetNoreferrer')) {
  5685. $modules[] = 'TargetNoreferrer';
  5686. }
  5687. // merge in custom modules
  5688. $modules = array_merge($modules, $this->userModules);
  5689. foreach ($modules as $module) {
  5690. $this->processModule($module);
  5691. $this->modules[$module]->setup($config);
  5692. }
  5693. foreach ($this->doctype->tidyModules as $module) {
  5694. $this->processModule($module);
  5695. $this->modules[$module]->setup($config);
  5696. }
  5697. // prepare any injectors
  5698. foreach ($this->modules as $module) {
  5699. $n = array();
  5700. foreach ($module->info_injector as $injector) {
  5701. if (!is_object($injector)) {
  5702. $class = "HTMLPurifier_Injector_$injector";
  5703. $injector = new $class;
  5704. }
  5705. $n[$injector->name] = $injector;
  5706. }
  5707. $module->info_injector = $n;
  5708. }
  5709. // setup lookup table based on all valid modules
  5710. foreach ($this->modules as $module) {
  5711. foreach ($module->info as $name => $def) {
  5712. if (!isset($this->elementLookup[$name])) {
  5713. $this->elementLookup[$name] = array();
  5714. }
  5715. $this->elementLookup[$name][] = $module->name;
  5716. }
  5717. }
  5718. // note the different choice
  5719. $this->contentSets = new HTMLPurifier_ContentSets(
  5720. // content set assembly deals with all possible modules,
  5721. // not just ones deemed to be "safe"
  5722. $this->modules
  5723. );
  5724. $this->attrCollections = new HTMLPurifier_AttrCollections(
  5725. $this->attrTypes,
  5726. // there is no way to directly disable a global attribute,
  5727. // but using AllowedAttributes or simply not including
  5728. // the module in your custom doctype should be sufficient
  5729. $this->modules
  5730. );
  5731. }
  5732. /**
  5733. * Takes a module and adds it to the active module collection,
  5734. * registering it if necessary.
  5735. */
  5736. public function processModule($module)
  5737. {
  5738. if (!isset($this->registeredModules[$module]) || is_object($module)) {
  5739. $this->registerModule($module);
  5740. }
  5741. $this->modules[$module] = $this->registeredModules[$module];
  5742. }
  5743. /**
  5744. * Retrieves merged element definitions.
  5745. * @return Array of HTMLPurifier_ElementDef
  5746. */
  5747. public function getElements()
  5748. {
  5749. $elements = array();
  5750. foreach ($this->modules as $module) {
  5751. if (!$this->trusted && !$module->safe) {
  5752. continue;
  5753. }
  5754. foreach ($module->info as $name => $v) {
  5755. if (isset($elements[$name])) {
  5756. continue;
  5757. }
  5758. $elements[$name] = $this->getElement($name);
  5759. }
  5760. }
  5761. // remove dud elements, this happens when an element that
  5762. // appeared to be safe actually wasn't
  5763. foreach ($elements as $n => $v) {
  5764. if ($v === false) {
  5765. unset($elements[$n]);
  5766. }
  5767. }
  5768. return $elements;
  5769. }
  5770. /**
  5771. * Retrieves a single merged element definition
  5772. * @param string $name Name of element
  5773. * @param bool $trusted Boolean trusted overriding parameter: set to true
  5774. * if you want the full version of an element
  5775. * @return HTMLPurifier_ElementDef Merged HTMLPurifier_ElementDef
  5776. * @note You may notice that modules are getting iterated over twice (once
  5777. * in getElements() and once here). This
  5778. * is because
  5779. */
  5780. public function getElement($name, $trusted = null)
  5781. {
  5782. if (!isset($this->elementLookup[$name])) {
  5783. return false;
  5784. }
  5785. // setup global state variables
  5786. $def = false;
  5787. if ($trusted === null) {
  5788. $trusted = $this->trusted;
  5789. }
  5790. // iterate through each module that has registered itself to this
  5791. // element
  5792. foreach ($this->elementLookup[$name] as $module_name) {
  5793. $module = $this->modules[$module_name];
  5794. // refuse to create/merge from a module that is deemed unsafe--
  5795. // pretend the module doesn't exist--when trusted mode is not on.
  5796. if (!$trusted && !$module->safe) {
  5797. continue;
  5798. }
  5799. // clone is used because, ideally speaking, the original
  5800. // definition should not be modified. Usually, this will
  5801. // make no difference, but for consistency's sake
  5802. $new_def = clone $module->info[$name];
  5803. if (!$def && $new_def->standalone) {
  5804. $def = $new_def;
  5805. } elseif ($def) {
  5806. // This will occur even if $new_def is standalone. In practice,
  5807. // this will usually result in a full replacement.
  5808. $def->mergeIn($new_def);
  5809. } else {
  5810. // :TODO:
  5811. // non-standalone definitions that don't have a standalone
  5812. // to merge into could be deferred to the end
  5813. // HOWEVER, it is perfectly valid for a non-standalone
  5814. // definition to lack a standalone definition, even
  5815. // after all processing: this allows us to safely
  5816. // specify extra attributes for elements that may not be
  5817. // enabled all in one place. In particular, this might
  5818. // be the case for trusted elements. WARNING: care must
  5819. // be taken that the /extra/ definitions are all safe.
  5820. continue;
  5821. }
  5822. // attribute value expansions
  5823. $this->attrCollections->performInclusions($def->attr);
  5824. $this->attrCollections->expandIdentifiers($def->attr, $this->attrTypes);
  5825. // descendants_are_inline, for ChildDef_Chameleon
  5826. if (is_string($def->content_model) &&
  5827. strpos($def->content_model, 'Inline') !== false) {
  5828. if ($name != 'del' && $name != 'ins') {
  5829. // this is for you, ins/del
  5830. $def->descendants_are_inline = true;
  5831. }
  5832. }
  5833. $this->contentSets->generateChildDef($def, $module);
  5834. }
  5835. // This can occur if there is a blank definition, but no base to
  5836. // mix it in with
  5837. if (!$def) {
  5838. return false;
  5839. }
  5840. // add information on required attributes
  5841. foreach ($def->attr as $attr_name => $attr_def) {
  5842. if ($attr_def->required) {
  5843. $def->required_attr[] = $attr_name;
  5844. }
  5845. }
  5846. return $def;
  5847. }
  5848. }
  5849. /**
  5850. * Component of HTMLPurifier_AttrContext that accumulates IDs to prevent dupes
  5851. * @note In Slashdot-speak, dupe means duplicate.
  5852. * @note The default constructor does not accept $config or $context objects:
  5853. * use must use the static build() factory method to perform initialization.
  5854. */
  5855. class HTMLPurifier_IDAccumulator
  5856. {
  5857. /**
  5858. * Lookup table of IDs we've accumulated.
  5859. * @public
  5860. */
  5861. public $ids = array();
  5862. /**
  5863. * Builds an IDAccumulator, also initializing the default blacklist
  5864. * @param HTMLPurifier_Config $config Instance of HTMLPurifier_Config
  5865. * @param HTMLPurifier_Context $context Instance of HTMLPurifier_Context
  5866. * @return HTMLPurifier_IDAccumulator Fully initialized HTMLPurifier_IDAccumulator
  5867. */
  5868. public static function build($config, $context)
  5869. {
  5870. $id_accumulator = new HTMLPurifier_IDAccumulator();
  5871. $id_accumulator->load($config->get('Attr.IDBlacklist'));
  5872. return $id_accumulator;
  5873. }
  5874. /**
  5875. * Add an ID to the lookup table.
  5876. * @param string $id ID to be added.
  5877. * @return bool status, true if success, false if there's a dupe
  5878. */
  5879. public function add($id)
  5880. {
  5881. if (isset($this->ids[$id])) {
  5882. return false;
  5883. }
  5884. return $this->ids[$id] = true;
  5885. }
  5886. /**
  5887. * Load a list of IDs into the lookup table
  5888. * @param $array_of_ids Array of IDs to load
  5889. * @note This function doesn't care about duplicates
  5890. */
  5891. public function load($array_of_ids)
  5892. {
  5893. foreach ($array_of_ids as $id) {
  5894. $this->ids[$id] = true;
  5895. }
  5896. }
  5897. }
  5898. /**
  5899. * Injects tokens into the document while parsing for well-formedness.
  5900. * This enables "formatter-like" functionality such as auto-paragraphing,
  5901. * smiley-ification and linkification to take place.
  5902. *
  5903. * A note on how handlers create changes; this is done by assigning a new
  5904. * value to the $token reference. These values can take a variety of forms and
  5905. * are best described HTMLPurifier_Strategy_MakeWellFormed->processToken()
  5906. * documentation.
  5907. *
  5908. * @todo Allow injectors to request a re-run on their output. This
  5909. * would help if an operation is recursive.
  5910. */
  5911. abstract class HTMLPurifier_Injector
  5912. {
  5913. /**
  5914. * Advisory name of injector, this is for friendly error messages.
  5915. * @type string
  5916. */
  5917. public $name;
  5918. /**
  5919. * @type HTMLPurifier_HTMLDefinition
  5920. */
  5921. protected $htmlDefinition;
  5922. /**
  5923. * Reference to CurrentNesting variable in Context. This is an array
  5924. * list of tokens that we are currently "inside"
  5925. * @type array
  5926. */
  5927. protected $currentNesting;
  5928. /**
  5929. * Reference to current token.
  5930. * @type HTMLPurifier_Token
  5931. */
  5932. protected $currentToken;
  5933. /**
  5934. * Reference to InputZipper variable in Context.
  5935. * @type HTMLPurifier_Zipper
  5936. */
  5937. protected $inputZipper;
  5938. /**
  5939. * Array of elements and attributes this injector creates and therefore
  5940. * need to be allowed by the definition. Takes form of
  5941. * array('element' => array('attr', 'attr2'), 'element2')
  5942. * @type array
  5943. */
  5944. public $needed = array();
  5945. /**
  5946. * Number of elements to rewind backwards (relative).
  5947. * @type bool|int
  5948. */
  5949. protected $rewindOffset = false;
  5950. /**
  5951. * Rewind to a spot to re-perform processing. This is useful if you
  5952. * deleted a node, and now need to see if this change affected any
  5953. * earlier nodes. Rewinding does not affect other injectors, and can
  5954. * result in infinite loops if not used carefully.
  5955. * @param bool|int $offset
  5956. * @warning HTML Purifier will prevent you from fast-forwarding with this
  5957. * function.
  5958. */
  5959. public function rewindOffset($offset)
  5960. {
  5961. $this->rewindOffset = $offset;
  5962. }
  5963. /**
  5964. * Retrieves rewind offset, and then unsets it.
  5965. * @return bool|int
  5966. */
  5967. public function getRewindOffset()
  5968. {
  5969. $r = $this->rewindOffset;
  5970. $this->rewindOffset = false;
  5971. return $r;
  5972. }
  5973. /**
  5974. * Prepares the injector by giving it the config and context objects:
  5975. * this allows references to important variables to be made within
  5976. * the injector. This function also checks if the HTML environment
  5977. * will work with the Injector (see checkNeeded()).
  5978. * @param HTMLPurifier_Config $config
  5979. * @param HTMLPurifier_Context $context
  5980. * @return bool|string Boolean false if success, string of missing needed element/attribute if failure
  5981. */
  5982. public function prepare($config, $context)
  5983. {
  5984. $this->htmlDefinition = $config->getHTMLDefinition();
  5985. // Even though this might fail, some unit tests ignore this and
  5986. // still test checkNeeded, so be careful. Maybe get rid of that
  5987. // dependency.
  5988. $result = $this->checkNeeded($config);
  5989. if ($result !== false) {
  5990. return $result;
  5991. }
  5992. $this->currentNesting =& $context->get('CurrentNesting');
  5993. $this->currentToken =& $context->get('CurrentToken');
  5994. $this->inputZipper =& $context->get('InputZipper');
  5995. return false;
  5996. }
  5997. /**
  5998. * This function checks if the HTML environment
  5999. * will work with the Injector: if p tags are not allowed, the
  6000. * Auto-Paragraphing injector should not be enabled.
  6001. * @param HTMLPurifier_Config $config
  6002. * @return bool|string Boolean false if success, string of missing needed element/attribute if failure
  6003. */
  6004. public function checkNeeded($config)
  6005. {
  6006. $def = $config->getHTMLDefinition();
  6007. foreach ($this->needed as $element => $attributes) {
  6008. if (is_int($element)) {
  6009. $element = $attributes;
  6010. }
  6011. if (!isset($def->info[$element])) {
  6012. return $element;
  6013. }
  6014. if (!is_array($attributes)) {
  6015. continue;
  6016. }
  6017. foreach ($attributes as $name) {
  6018. if (!isset($def->info[$element]->attr[$name])) {
  6019. return "$element.$name";
  6020. }
  6021. }
  6022. }
  6023. return false;
  6024. }
  6025. /**
  6026. * Tests if the context node allows a certain element
  6027. * @param string $name Name of element to test for
  6028. * @return bool True if element is allowed, false if it is not
  6029. */
  6030. public function allowsElement($name)
  6031. {
  6032. if (!empty($this->currentNesting)) {
  6033. $parent_token = array_pop($this->currentNesting);
  6034. $this->currentNesting[] = $parent_token;
  6035. $parent = $this->htmlDefinition->info[$parent_token->name];
  6036. } else {
  6037. $parent = $this->htmlDefinition->info_parent_def;
  6038. }
  6039. if (!isset($parent->child->elements[$name]) || isset($parent->excludes[$name])) {
  6040. return false;
  6041. }
  6042. // check for exclusion
  6043. for ($i = count($this->currentNesting) - 2; $i >= 0; $i--) {
  6044. $node = $this->currentNesting[$i];
  6045. $def = $this->htmlDefinition->info[$node->name];
  6046. if (isset($def->excludes[$name])) {
  6047. return false;
  6048. }
  6049. }
  6050. return true;
  6051. }
  6052. /**
  6053. * Iterator function, which starts with the next token and continues until
  6054. * you reach the end of the input tokens.
  6055. * @warning Please prevent previous references from interfering with this
  6056. * functions by setting $i = null beforehand!
  6057. * @param int $i Current integer index variable for inputTokens
  6058. * @param HTMLPurifier_Token $current Current token variable.
  6059. * Do NOT use $token, as that variable is also a reference
  6060. * @return bool
  6061. */
  6062. protected function forward(&$i, &$current)
  6063. {
  6064. if ($i === null) {
  6065. $i = count($this->inputZipper->back) - 1;
  6066. } else {
  6067. $i--;
  6068. }
  6069. if ($i < 0) {
  6070. return false;
  6071. }
  6072. $current = $this->inputZipper->back[$i];
  6073. return true;
  6074. }
  6075. /**
  6076. * Similar to _forward, but accepts a third parameter $nesting (which
  6077. * should be initialized at 0) and stops when we hit the end tag
  6078. * for the node $this->inputIndex starts in.
  6079. * @param int $i Current integer index variable for inputTokens
  6080. * @param HTMLPurifier_Token $current Current token variable.
  6081. * Do NOT use $token, as that variable is also a reference
  6082. * @param int $nesting
  6083. * @return bool
  6084. */
  6085. protected function forwardUntilEndToken(&$i, &$current, &$nesting)
  6086. {
  6087. $result = $this->forward($i, $current);
  6088. if (!$result) {
  6089. return false;
  6090. }
  6091. if ($nesting === null) {
  6092. $nesting = 0;
  6093. }
  6094. if ($current instanceof HTMLPurifier_Token_Start) {
  6095. $nesting++;
  6096. } elseif ($current instanceof HTMLPurifier_Token_End) {
  6097. if ($nesting <= 0) {
  6098. return false;
  6099. }
  6100. $nesting--;
  6101. }
  6102. return true;
  6103. }
  6104. /**
  6105. * Iterator function, starts with the previous token and continues until
  6106. * you reach the beginning of input tokens.
  6107. * @warning Please prevent previous references from interfering with this
  6108. * functions by setting $i = null beforehand!
  6109. * @param int $i Current integer index variable for inputTokens
  6110. * @param HTMLPurifier_Token $current Current token variable.
  6111. * Do NOT use $token, as that variable is also a reference
  6112. * @return bool
  6113. */
  6114. protected function backward(&$i, &$current)
  6115. {
  6116. if ($i === null) {
  6117. $i = count($this->inputZipper->front) - 1;
  6118. } else {
  6119. $i--;
  6120. }
  6121. if ($i < 0) {
  6122. return false;
  6123. }
  6124. $current = $this->inputZipper->front[$i];
  6125. return true;
  6126. }
  6127. /**
  6128. * Handler that is called when a text token is processed
  6129. */
  6130. public function handleText(&$token)
  6131. {
  6132. }
  6133. /**
  6134. * Handler that is called when a start or empty token is processed
  6135. */
  6136. public function handleElement(&$token)
  6137. {
  6138. }
  6139. /**
  6140. * Handler that is called when an end token is processed
  6141. */
  6142. public function handleEnd(&$token)
  6143. {
  6144. $this->notifyEnd($token);
  6145. }
  6146. /**
  6147. * Notifier that is called when an end token is processed
  6148. * @param HTMLPurifier_Token $token Current token variable.
  6149. * @note This differs from handlers in that the token is read-only
  6150. * @deprecated
  6151. */
  6152. public function notifyEnd($token)
  6153. {
  6154. }
  6155. }
  6156. /**
  6157. * Represents a language and defines localizable string formatting and
  6158. * other functions, as well as the localized messages for HTML Purifier.
  6159. */
  6160. class HTMLPurifier_Language
  6161. {
  6162. /**
  6163. * ISO 639 language code of language. Prefers shortest possible version.
  6164. * @type string
  6165. */
  6166. public $code = 'en';
  6167. /**
  6168. * Fallback language code.
  6169. * @type bool|string
  6170. */
  6171. public $fallback = false;
  6172. /**
  6173. * Array of localizable messages.
  6174. * @type array
  6175. */
  6176. public $messages = array();
  6177. /**
  6178. * Array of localizable error codes.
  6179. * @type array
  6180. */
  6181. public $errorNames = array();
  6182. /**
  6183. * True if no message file was found for this language, so English
  6184. * is being used instead. Check this if you'd like to notify the
  6185. * user that they've used a non-supported language.
  6186. * @type bool
  6187. */
  6188. public $error = false;
  6189. /**
  6190. * Has the language object been loaded yet?
  6191. * @type bool
  6192. * @todo Make it private, fix usage in HTMLPurifier_LanguageTest
  6193. */
  6194. public $_loaded = false;
  6195. /**
  6196. * @type HTMLPurifier_Config
  6197. */
  6198. protected $config;
  6199. /**
  6200. * @type HTMLPurifier_Context
  6201. */
  6202. protected $context;
  6203. /**
  6204. * @param HTMLPurifier_Config $config
  6205. * @param HTMLPurifier_Context $context
  6206. */
  6207. public function __construct($config, $context)
  6208. {
  6209. $this->config = $config;
  6210. $this->context = $context;
  6211. }
  6212. /**
  6213. * Loads language object with necessary info from factory cache
  6214. * @note This is a lazy loader
  6215. */
  6216. public function load()
  6217. {
  6218. if ($this->_loaded) {
  6219. return;
  6220. }
  6221. $factory = HTMLPurifier_LanguageFactory::instance();
  6222. $factory->loadLanguage($this->code);
  6223. foreach ($factory->keys as $key) {
  6224. $this->$key = $factory->cache[$this->code][$key];
  6225. }
  6226. $this->_loaded = true;
  6227. }
  6228. /**
  6229. * Retrieves a localised message.
  6230. * @param string $key string identifier of message
  6231. * @return string localised message
  6232. */
  6233. public function getMessage($key)
  6234. {
  6235. if (!$this->_loaded) {
  6236. $this->load();
  6237. }
  6238. if (!isset($this->messages[$key])) {
  6239. return "[$key]";
  6240. }
  6241. return $this->messages[$key];
  6242. }
  6243. /**
  6244. * Retrieves a localised error name.
  6245. * @param int $int error number, corresponding to PHP's error reporting
  6246. * @return string localised message
  6247. */
  6248. public function getErrorName($int)
  6249. {
  6250. if (!$this->_loaded) {
  6251. $this->load();
  6252. }
  6253. if (!isset($this->errorNames[$int])) {
  6254. return "[Error: $int]";
  6255. }
  6256. return $this->errorNames[$int];
  6257. }
  6258. /**
  6259. * Converts an array list into a string readable representation
  6260. * @param array $array
  6261. * @return string
  6262. */
  6263. public function listify($array)
  6264. {
  6265. $sep = $this->getMessage('Item separator');
  6266. $sep_last = $this->getMessage('Item separator last');
  6267. $ret = '';
  6268. for ($i = 0, $c = count($array); $i < $c; $i++) {
  6269. if ($i == 0) {
  6270. } elseif ($i + 1 < $c) {
  6271. $ret .= $sep;
  6272. } else {
  6273. $ret .= $sep_last;
  6274. }
  6275. $ret .= $array[$i];
  6276. }
  6277. return $ret;
  6278. }
  6279. /**
  6280. * Formats a localised message with passed parameters
  6281. * @param string $key string identifier of message
  6282. * @param array $args Parameters to substitute in
  6283. * @return string localised message
  6284. * @todo Implement conditionals? Right now, some messages make
  6285. * reference to line numbers, but those aren't always available
  6286. */
  6287. public function formatMessage($key, $args = array())
  6288. {
  6289. if (!$this->_loaded) {
  6290. $this->load();
  6291. }
  6292. if (!isset($this->messages[$key])) {
  6293. return "[$key]";
  6294. }
  6295. $raw = $this->messages[$key];
  6296. $subst = array();
  6297. $generator = false;
  6298. foreach ($args as $i => $value) {
  6299. if (is_object($value)) {
  6300. if ($value instanceof HTMLPurifier_Token) {
  6301. // factor this out some time
  6302. if (!$generator) {
  6303. $generator = $this->context->get('Generator');
  6304. }
  6305. if (isset($value->name)) {
  6306. $subst['$'.$i.'.Name'] = $value->name;
  6307. }
  6308. if (isset($value->data)) {
  6309. $subst['$'.$i.'.Data'] = $value->data;
  6310. }
  6311. $subst['$'.$i.'.Compact'] =
  6312. $subst['$'.$i.'.Serialized'] = $generator->generateFromToken($value);
  6313. // a more complex algorithm for compact representation
  6314. // could be introduced for all types of tokens. This
  6315. // may need to be factored out into a dedicated class
  6316. if (!empty($value->attr)) {
  6317. $stripped_token = clone $value;
  6318. $stripped_token->attr = array();
  6319. $subst['$'.$i.'.Compact'] = $generator->generateFromToken($stripped_token);
  6320. }
  6321. $subst['$'.$i.'.Line'] = $value->line ? $value->line : 'unknown';
  6322. }
  6323. continue;
  6324. } elseif (is_array($value)) {
  6325. $keys = array_keys($value);
  6326. if (array_keys($keys) === $keys) {
  6327. // list
  6328. $subst['$'.$i] = $this->listify($value);
  6329. } else {
  6330. // associative array
  6331. // no $i implementation yet, sorry
  6332. $subst['$'.$i.'.Keys'] = $this->listify($keys);
  6333. $subst['$'.$i.'.Values'] = $this->listify(array_values($value));
  6334. }
  6335. continue;
  6336. }
  6337. $subst['$' . $i] = $value;
  6338. }
  6339. return strtr($raw, $subst);
  6340. }
  6341. }
  6342. /**
  6343. * Class responsible for generating HTMLPurifier_Language objects, managing
  6344. * caching and fallbacks.
  6345. * @note Thanks to MediaWiki for the general logic, although this version
  6346. * has been entirely rewritten
  6347. * @todo Serialized cache for languages
  6348. */
  6349. class HTMLPurifier_LanguageFactory
  6350. {
  6351. /**
  6352. * Cache of language code information used to load HTMLPurifier_Language objects.
  6353. * Structure is: $factory->cache[$language_code][$key] = $value
  6354. * @type array
  6355. */
  6356. public $cache;
  6357. /**
  6358. * Valid keys in the HTMLPurifier_Language object. Designates which
  6359. * variables to slurp out of a message file.
  6360. * @type array
  6361. */
  6362. public $keys = array('fallback', 'messages', 'errorNames');
  6363. /**
  6364. * Instance to validate language codes.
  6365. * @type HTMLPurifier_AttrDef_Lang
  6366. *
  6367. */
  6368. protected $validator;
  6369. /**
  6370. * Cached copy of dirname(__FILE__), directory of current file without
  6371. * trailing slash.
  6372. * @type string
  6373. */
  6374. protected $dir;
  6375. /**
  6376. * Keys whose contents are a hash map and can be merged.
  6377. * @type array
  6378. */
  6379. protected $mergeable_keys_map = array('messages' => true, 'errorNames' => true);
  6380. /**
  6381. * Keys whose contents are a list and can be merged.
  6382. * @value array lookup
  6383. */
  6384. protected $mergeable_keys_list = array();
  6385. /**
  6386. * Retrieve sole instance of the factory.
  6387. * @param HTMLPurifier_LanguageFactory $prototype Optional prototype to overload sole instance with,
  6388. * or bool true to reset to default factory.
  6389. * @return HTMLPurifier_LanguageFactory
  6390. */
  6391. public static function instance($prototype = null)
  6392. {
  6393. static $instance = null;
  6394. if ($prototype !== null) {
  6395. $instance = $prototype;
  6396. } elseif ($instance === null || $prototype == true) {
  6397. $instance = new HTMLPurifier_LanguageFactory();
  6398. $instance->setup();
  6399. }
  6400. return $instance;
  6401. }
  6402. /**
  6403. * Sets up the singleton, much like a constructor
  6404. * @note Prevents people from getting this outside of the singleton
  6405. */
  6406. public function setup()
  6407. {
  6408. $this->validator = new HTMLPurifier_AttrDef_Lang();
  6409. $this->dir = HTMLPURIFIER_PREFIX . '/HTMLPurifier';
  6410. }
  6411. /**
  6412. * Creates a language object, handles class fallbacks
  6413. * @param HTMLPurifier_Config $config
  6414. * @param HTMLPurifier_Context $context
  6415. * @param bool|string $code Code to override configuration with. Private parameter.
  6416. * @return HTMLPurifier_Language
  6417. */
  6418. public function create($config, $context, $code = false)
  6419. {
  6420. // validate language code
  6421. if ($code === false) {
  6422. $code = $this->validator->validate(
  6423. $config->get('Core.Language'),
  6424. $config,
  6425. $context
  6426. );
  6427. } else {
  6428. $code = $this->validator->validate($code, $config, $context);
  6429. }
  6430. if ($code === false) {
  6431. $code = 'en'; // malformed code becomes English
  6432. }
  6433. $pcode = str_replace('-', '_', $code); // make valid PHP classname
  6434. static $depth = 0; // recursion protection
  6435. if ($code == 'en') {
  6436. $lang = new HTMLPurifier_Language($config, $context);
  6437. } else {
  6438. $class = 'HTMLPurifier_Language_' . $pcode;
  6439. $file = $this->dir . '/Language/classes/' . $code . '.php';
  6440. if (file_exists($file) || class_exists($class, false)) {
  6441. $lang = new $class($config, $context);
  6442. } else {
  6443. // Go fallback
  6444. $raw_fallback = $this->getFallbackFor($code);
  6445. $fallback = $raw_fallback ? $raw_fallback : 'en';
  6446. $depth++;
  6447. $lang = $this->create($config, $context, $fallback);
  6448. if (!$raw_fallback) {
  6449. $lang->error = true;
  6450. }
  6451. $depth--;
  6452. }
  6453. }
  6454. $lang->code = $code;
  6455. return $lang;
  6456. }
  6457. /**
  6458. * Returns the fallback language for language
  6459. * @note Loads the original language into cache
  6460. * @param string $code language code
  6461. * @return string|bool
  6462. */
  6463. public function getFallbackFor($code)
  6464. {
  6465. $this->loadLanguage($code);
  6466. return $this->cache[$code]['fallback'];
  6467. }
  6468. /**
  6469. * Loads language into the cache, handles message file and fallbacks
  6470. * @param string $code language code
  6471. */
  6472. public function loadLanguage($code)
  6473. {
  6474. static $languages_seen = array(); // recursion guard
  6475. // abort if we've already loaded it
  6476. if (isset($this->cache[$code])) {
  6477. return;
  6478. }
  6479. // generate filename
  6480. $filename = $this->dir . '/Language/messages/' . $code . '.php';
  6481. // default fallback : may be overwritten by the ensuing include
  6482. $fallback = ($code != 'en') ? 'en' : false;
  6483. // load primary localisation
  6484. if (!file_exists($filename)) {
  6485. // skip the include: will rely solely on fallback
  6486. $filename = $this->dir . '/Language/messages/en.php';
  6487. $cache = array();
  6488. } else {
  6489. include $filename;
  6490. $cache = compact($this->keys);
  6491. }
  6492. // load fallback localisation
  6493. if (!empty($fallback)) {
  6494. // infinite recursion guard
  6495. if (isset($languages_seen[$code])) {
  6496. trigger_error(
  6497. 'Circular fallback reference in language ' .
  6498. $code,
  6499. E_USER_ERROR
  6500. );
  6501. $fallback = 'en';
  6502. }
  6503. $language_seen[$code] = true;
  6504. // load the fallback recursively
  6505. $this->loadLanguage($fallback);
  6506. $fallback_cache = $this->cache[$fallback];
  6507. // merge fallback with current language
  6508. foreach ($this->keys as $key) {
  6509. if (isset($cache[$key]) && isset($fallback_cache[$key])) {
  6510. if (isset($this->mergeable_keys_map[$key])) {
  6511. $cache[$key] = $cache[$key] + $fallback_cache[$key];
  6512. } elseif (isset($this->mergeable_keys_list[$key])) {
  6513. $cache[$key] = array_merge($fallback_cache[$key], $cache[$key]);
  6514. }
  6515. } else {
  6516. $cache[$key] = $fallback_cache[$key];
  6517. }
  6518. }
  6519. }
  6520. // save to cache for later retrieval
  6521. $this->cache[$code] = $cache;
  6522. return;
  6523. }
  6524. }
  6525. /**
  6526. * Represents a measurable length, with a string numeric magnitude
  6527. * and a unit. This object is immutable.
  6528. */
  6529. class HTMLPurifier_Length
  6530. {
  6531. /**
  6532. * String numeric magnitude.
  6533. * @type string
  6534. */
  6535. protected $n;
  6536. /**
  6537. * String unit. False is permitted if $n = 0.
  6538. * @type string|bool
  6539. */
  6540. protected $unit;
  6541. /**
  6542. * Whether or not this length is valid. Null if not calculated yet.
  6543. * @type bool
  6544. */
  6545. protected $isValid;
  6546. /**
  6547. * Array Lookup array of units recognized by CSS 2.1
  6548. * @type array
  6549. */
  6550. protected static $allowedUnits = array(
  6551. 'em' => true, 'ex' => true, 'px' => true, 'in' => true,
  6552. 'cm' => true, 'mm' => true, 'pt' => true, 'pc' => true
  6553. );
  6554. /**
  6555. * @param string $n Magnitude
  6556. * @param bool|string $u Unit
  6557. */
  6558. public function __construct($n = '0', $u = false)
  6559. {
  6560. $this->n = (string) $n;
  6561. $this->unit = $u !== false ? (string) $u : false;
  6562. }
  6563. /**
  6564. * @param string $s Unit string, like '2em' or '3.4in'
  6565. * @return HTMLPurifier_Length
  6566. * @warning Does not perform validation.
  6567. */
  6568. public static function make($s)
  6569. {
  6570. if ($s instanceof HTMLPurifier_Length) {
  6571. return $s;
  6572. }
  6573. $n_length = strspn($s, '1234567890.+-');
  6574. $n = substr($s, 0, $n_length);
  6575. $unit = substr($s, $n_length);
  6576. if ($unit === '') {
  6577. $unit = false;
  6578. }
  6579. return new HTMLPurifier_Length($n, $unit);
  6580. }
  6581. /**
  6582. * Validates the number and unit.
  6583. * @return bool
  6584. */
  6585. protected function validate()
  6586. {
  6587. // Special case:
  6588. if ($this->n === '+0' || $this->n === '-0') {
  6589. $this->n = '0';
  6590. }
  6591. if ($this->n === '0' && $this->unit === false) {
  6592. return true;
  6593. }
  6594. if (!ctype_lower($this->unit)) {
  6595. $this->unit = strtolower($this->unit);
  6596. }
  6597. if (!isset(HTMLPurifier_Length::$allowedUnits[$this->unit])) {
  6598. return false;
  6599. }
  6600. // Hack:
  6601. $def = new HTMLPurifier_AttrDef_CSS_Number();
  6602. $result = $def->validate($this->n, false, false);
  6603. if ($result === false) {
  6604. return false;
  6605. }
  6606. $this->n = $result;
  6607. return true;
  6608. }
  6609. /**
  6610. * Returns string representation of number.
  6611. * @return string
  6612. */
  6613. public function toString()
  6614. {
  6615. if (!$this->isValid()) {
  6616. return false;
  6617. }
  6618. return $this->n . $this->unit;
  6619. }
  6620. /**
  6621. * Retrieves string numeric magnitude.
  6622. * @return string
  6623. */
  6624. public function getN()
  6625. {
  6626. return $this->n;
  6627. }
  6628. /**
  6629. * Retrieves string unit.
  6630. * @return string
  6631. */
  6632. public function getUnit()
  6633. {
  6634. return $this->unit;
  6635. }
  6636. /**
  6637. * Returns true if this length unit is valid.
  6638. * @return bool
  6639. */
  6640. public function isValid()
  6641. {
  6642. if ($this->isValid === null) {
  6643. $this->isValid = $this->validate();
  6644. }
  6645. return $this->isValid;
  6646. }
  6647. /**
  6648. * Compares two lengths, and returns 1 if greater, -1 if less and 0 if equal.
  6649. * @param HTMLPurifier_Length $l
  6650. * @return int
  6651. * @warning If both values are too large or small, this calculation will
  6652. * not work properly
  6653. */
  6654. public function compareTo($l)
  6655. {
  6656. if ($l === false) {
  6657. return false;
  6658. }
  6659. if ($l->unit !== $this->unit) {
  6660. $converter = new HTMLPurifier_UnitConverter();
  6661. $l = $converter->convert($l, $this->unit);
  6662. if ($l === false) {
  6663. return false;
  6664. }
  6665. }
  6666. return $this->n - $l->n;
  6667. }
  6668. }
  6669. /**
  6670. * Forgivingly lexes HTML (SGML-style) markup into tokens.
  6671. *
  6672. * A lexer parses a string of SGML-style markup and converts them into
  6673. * corresponding tokens. It doesn't check for well-formedness, although its
  6674. * internal mechanism may make this automatic (such as the case of
  6675. * HTMLPurifier_Lexer_DOMLex). There are several implementations to choose
  6676. * from.
  6677. *
  6678. * A lexer is HTML-oriented: it might work with XML, but it's not
  6679. * recommended, as we adhere to a subset of the specification for optimization
  6680. * reasons. This might change in the future. Also, most tokenizers are not
  6681. * expected to handle DTDs or PIs.
  6682. *
  6683. * This class should not be directly instantiated, but you may use create() to
  6684. * retrieve a default copy of the lexer. Being a supertype, this class
  6685. * does not actually define any implementation, but offers commonly used
  6686. * convenience functions for subclasses.
  6687. *
  6688. * @note The unit tests will instantiate this class for testing purposes, as
  6689. * many of the utility functions require a class to be instantiated.
  6690. * This means that, even though this class is not runnable, it will
  6691. * not be declared abstract.
  6692. *
  6693. * @par
  6694. *
  6695. * @note
  6696. * We use tokens rather than create a DOM representation because DOM would:
  6697. *
  6698. * @par
  6699. * -# Require more processing and memory to create,
  6700. * -# Is not streamable, and
  6701. * -# Has the entire document structure (html and body not needed).
  6702. *
  6703. * @par
  6704. * However, DOM is helpful in that it makes it easy to move around nodes
  6705. * without a lot of lookaheads to see when a tag is closed. This is a
  6706. * limitation of the token system and some workarounds would be nice.
  6707. */
  6708. class HTMLPurifier_Lexer
  6709. {
  6710. /**
  6711. * Whether or not this lexer implements line-number/column-number tracking.
  6712. * If it does, set to true.
  6713. */
  6714. public $tracksLineNumbers = false;
  6715. // -- STATIC ----------------------------------------------------------
  6716. /**
  6717. * Retrieves or sets the default Lexer as a Prototype Factory.
  6718. *
  6719. * By default HTMLPurifier_Lexer_DOMLex will be returned. There are
  6720. * a few exceptions involving special features that only DirectLex
  6721. * implements.
  6722. *
  6723. * @note The behavior of this class has changed, rather than accepting
  6724. * a prototype object, it now accepts a configuration object.
  6725. * To specify your own prototype, set %Core.LexerImpl to it.
  6726. * This change in behavior de-singletonizes the lexer object.
  6727. *
  6728. * @param HTMLPurifier_Config $config
  6729. * @return HTMLPurifier_Lexer
  6730. * @throws HTMLPurifier_Exception
  6731. */
  6732. public static function create($config)
  6733. {
  6734. if (!($config instanceof HTMLPurifier_Config)) {
  6735. $lexer = $config;
  6736. trigger_error(
  6737. "Passing a prototype to
  6738. HTMLPurifier_Lexer::create() is deprecated, please instead
  6739. use %Core.LexerImpl",
  6740. E_USER_WARNING
  6741. );
  6742. } else {
  6743. $lexer = $config->get('Core.LexerImpl');
  6744. }
  6745. $needs_tracking =
  6746. $config->get('Core.MaintainLineNumbers') ||
  6747. $config->get('Core.CollectErrors');
  6748. $inst = null;
  6749. if (is_object($lexer)) {
  6750. $inst = $lexer;
  6751. } else {
  6752. if (is_null($lexer)) {
  6753. do {
  6754. // auto-detection algorithm
  6755. if ($needs_tracking) {
  6756. $lexer = 'DirectLex';
  6757. break;
  6758. }
  6759. if (class_exists('DOMDocument') &&
  6760. method_exists('DOMDocument', 'loadHTML') &&
  6761. !extension_loaded('domxml')
  6762. ) {
  6763. // check for DOM support, because while it's part of the
  6764. // core, it can be disabled compile time. Also, the PECL
  6765. // domxml extension overrides the default DOM, and is evil
  6766. // and nasty and we shan't bother to support it
  6767. $lexer = 'DOMLex';
  6768. } else {
  6769. $lexer = 'DirectLex';
  6770. }
  6771. } while (0);
  6772. } // do..while so we can break
  6773. // instantiate recognized string names
  6774. switch ($lexer) {
  6775. case 'DOMLex':
  6776. $inst = new HTMLPurifier_Lexer_DOMLex();
  6777. break;
  6778. case 'DirectLex':
  6779. $inst = new HTMLPurifier_Lexer_DirectLex();
  6780. break;
  6781. case 'PH5P':
  6782. $inst = new HTMLPurifier_Lexer_PH5P();
  6783. break;
  6784. default:
  6785. throw new HTMLPurifier_Exception(
  6786. "Cannot instantiate unrecognized Lexer type " .
  6787. htmlspecialchars($lexer)
  6788. );
  6789. }
  6790. }
  6791. if (!$inst) {
  6792. throw new HTMLPurifier_Exception('No lexer was instantiated');
  6793. }
  6794. // once PHP DOM implements native line numbers, or we
  6795. // hack out something using XSLT, remove this stipulation
  6796. if ($needs_tracking && !$inst->tracksLineNumbers) {
  6797. throw new HTMLPurifier_Exception(
  6798. 'Cannot use lexer that does not support line numbers with ' .
  6799. 'Core.MaintainLineNumbers or Core.CollectErrors (use DirectLex instead)'
  6800. );
  6801. }
  6802. return $inst;
  6803. }
  6804. // -- CONVENIENCE MEMBERS ---------------------------------------------
  6805. public function __construct()
  6806. {
  6807. $this->_entity_parser = new HTMLPurifier_EntityParser();
  6808. }
  6809. /**
  6810. * Most common entity to raw value conversion table for special entities.
  6811. * @type array
  6812. */
  6813. protected $_special_entity2str =
  6814. array(
  6815. '&quot;' => '"',
  6816. '&amp;' => '&',
  6817. '&lt;' => '<',
  6818. '&gt;' => '>',
  6819. '&#39;' => "'",
  6820. '&#039;' => "'",
  6821. '&#x27;' => "'"
  6822. );
  6823. /**
  6824. * Parses special entities into the proper characters.
  6825. *
  6826. * This string will translate escaped versions of the special characters
  6827. * into the correct ones.
  6828. *
  6829. * @warning
  6830. * You should be able to treat the output of this function as
  6831. * completely parsed, but that's only because all other entities should
  6832. * have been handled previously in substituteNonSpecialEntities()
  6833. *
  6834. * @param string $string String character data to be parsed.
  6835. * @return string Parsed character data.
  6836. */
  6837. public function parseData($string)
  6838. {
  6839. // following functions require at least one character
  6840. if ($string === '') {
  6841. return '';
  6842. }
  6843. // subtracts amps that cannot possibly be escaped
  6844. $num_amp = substr_count($string, '&') - substr_count($string, '& ') -
  6845. ($string[strlen($string) - 1] === '&' ? 1 : 0);
  6846. if (!$num_amp) {
  6847. return $string;
  6848. } // abort if no entities
  6849. $num_esc_amp = substr_count($string, '&amp;');
  6850. $string = strtr($string, $this->_special_entity2str);
  6851. // code duplication for sake of optimization, see above
  6852. $num_amp_2 = substr_count($string, '&') - substr_count($string, '& ') -
  6853. ($string[strlen($string) - 1] === '&' ? 1 : 0);
  6854. if ($num_amp_2 <= $num_esc_amp) {
  6855. return $string;
  6856. }
  6857. // hmm... now we have some uncommon entities. Use the callback.
  6858. $string = $this->_entity_parser->substituteSpecialEntities($string);
  6859. return $string;
  6860. }
  6861. /**
  6862. * Lexes an HTML string into tokens.
  6863. * @param $string String HTML.
  6864. * @param HTMLPurifier_Config $config
  6865. * @param HTMLPurifier_Context $context
  6866. * @return HTMLPurifier_Token[] array representation of HTML.
  6867. */
  6868. public function tokenizeHTML($string, $config, $context)
  6869. {
  6870. trigger_error('Call to abstract class', E_USER_ERROR);
  6871. }
  6872. /**
  6873. * Translates CDATA sections into regular sections (through escaping).
  6874. * @param string $string HTML string to process.
  6875. * @return string HTML with CDATA sections escaped.
  6876. */
  6877. protected static function escapeCDATA($string)
  6878. {
  6879. return preg_replace_callback(
  6880. '/<!\[CDATA\[(.+?)\]\]>/s',
  6881. array('HTMLPurifier_Lexer', 'CDATACallback'),
  6882. $string
  6883. );
  6884. }
  6885. /**
  6886. * Special CDATA case that is especially convoluted for <script>
  6887. * @param string $string HTML string to process.
  6888. * @return string HTML with CDATA sections escaped.
  6889. */
  6890. protected static function escapeCommentedCDATA($string)
  6891. {
  6892. return preg_replace_callback(
  6893. '#<!--//--><!\[CDATA\[//><!--(.+?)//--><!\]\]>#s',
  6894. array('HTMLPurifier_Lexer', 'CDATACallback'),
  6895. $string
  6896. );
  6897. }
  6898. /**
  6899. * Special Internet Explorer conditional comments should be removed.
  6900. * @param string $string HTML string to process.
  6901. * @return string HTML with conditional comments removed.
  6902. */
  6903. protected static function removeIEConditional($string)
  6904. {
  6905. return preg_replace(
  6906. '#<!--\[if [^>]+\]>.*?<!\[endif\]-->#si', // probably should generalize for all strings
  6907. '',
  6908. $string
  6909. );
  6910. }
  6911. /**
  6912. * Callback function for escapeCDATA() that does the work.
  6913. *
  6914. * @warning Though this is public in order to let the callback happen,
  6915. * calling it directly is not recommended.
  6916. * @param array $matches PCRE matches array, with index 0 the entire match
  6917. * and 1 the inside of the CDATA section.
  6918. * @return string Escaped internals of the CDATA section.
  6919. */
  6920. protected static function CDATACallback($matches)
  6921. {
  6922. // not exactly sure why the character set is needed, but whatever
  6923. return htmlspecialchars($matches[1], ENT_COMPAT, 'UTF-8');
  6924. }
  6925. /**
  6926. * Takes a piece of HTML and normalizes it by converting entities, fixing
  6927. * encoding, extracting bits, and other good stuff.
  6928. * @param string $html HTML.
  6929. * @param HTMLPurifier_Config $config
  6930. * @param HTMLPurifier_Context $context
  6931. * @return string
  6932. * @todo Consider making protected
  6933. */
  6934. public function normalize($html, $config, $context)
  6935. {
  6936. // normalize newlines to \n
  6937. if ($config->get('Core.NormalizeNewlines')) {
  6938. $html = str_replace("\r\n", "\n", $html);
  6939. $html = str_replace("\r", "\n", $html);
  6940. }
  6941. if ($config->get('HTML.Trusted')) {
  6942. // escape convoluted CDATA
  6943. $html = $this->escapeCommentedCDATA($html);
  6944. }
  6945. // escape CDATA
  6946. $html = $this->escapeCDATA($html);
  6947. $html = $this->removeIEConditional($html);
  6948. // extract body from document if applicable
  6949. if ($config->get('Core.ConvertDocumentToFragment')) {
  6950. $e = false;
  6951. if ($config->get('Core.CollectErrors')) {
  6952. $e =& $context->get('ErrorCollector');
  6953. }
  6954. $new_html = $this->extractBody($html);
  6955. if ($e && $new_html != $html) {
  6956. $e->send(E_WARNING, 'Lexer: Extracted body');
  6957. }
  6958. $html = $new_html;
  6959. }
  6960. // expand entities that aren't the big five
  6961. $html = $this->_entity_parser->substituteNonSpecialEntities($html);
  6962. // clean into wellformed UTF-8 string for an SGML context: this has
  6963. // to be done after entity expansion because the entities sometimes
  6964. // represent non-SGML characters (horror, horror!)
  6965. $html = HTMLPurifier_Encoder::cleanUTF8($html);
  6966. // if processing instructions are to removed, remove them now
  6967. if ($config->get('Core.RemoveProcessingInstructions')) {
  6968. $html = preg_replace('#<\?.+?\?>#s', '', $html);
  6969. }
  6970. return $html;
  6971. }
  6972. /**
  6973. * Takes a string of HTML (fragment or document) and returns the content
  6974. * @todo Consider making protected
  6975. */
  6976. public function extractBody($html)
  6977. {
  6978. $matches = array();
  6979. $result = preg_match('|(.*?)<body[^>]*>(.*)</body>|is', $html, $matches);
  6980. if ($result) {
  6981. // Make sure it's not in a comment
  6982. $comment_start = strrpos($matches[1], '<!--');
  6983. $comment_end = strrpos($matches[1], '-->');
  6984. if ($comment_start === false ||
  6985. ($comment_end !== false && $comment_end > $comment_start)) {
  6986. return $matches[2];
  6987. }
  6988. }
  6989. return $html;
  6990. }
  6991. }
  6992. /**
  6993. * Abstract base node class that all others inherit from.
  6994. *
  6995. * Why do we not use the DOM extension? (1) It is not always available,
  6996. * (2) it has funny constraints on the data it can represent,
  6997. * whereas we want a maximally flexible representation, and (3) its
  6998. * interface is a bit cumbersome.
  6999. */
  7000. abstract class HTMLPurifier_Node
  7001. {
  7002. /**
  7003. * Line number of the start token in the source document
  7004. * @type int
  7005. */
  7006. public $line;
  7007. /**
  7008. * Column number of the start token in the source document. Null if unknown.
  7009. * @type int
  7010. */
  7011. public $col;
  7012. /**
  7013. * Lookup array of processing that this token is exempt from.
  7014. * Currently, valid values are "ValidateAttributes".
  7015. * @type array
  7016. */
  7017. public $armor = array();
  7018. /**
  7019. * When true, this node should be ignored as non-existent.
  7020. *
  7021. * Who is responsible for ignoring dead nodes? FixNesting is
  7022. * responsible for removing them before passing on to child
  7023. * validators.
  7024. */
  7025. public $dead = false;
  7026. /**
  7027. * Returns a pair of start and end tokens, where the end token
  7028. * is null if it is not necessary. Does not include children.
  7029. * @type array
  7030. */
  7031. abstract public function toTokenPair();
  7032. }
  7033. /**
  7034. * Class that handles operations involving percent-encoding in URIs.
  7035. *
  7036. * @warning
  7037. * Be careful when reusing instances of PercentEncoder. The object
  7038. * you use for normalize() SHOULD NOT be used for encode(), or
  7039. * vice-versa.
  7040. */
  7041. class HTMLPurifier_PercentEncoder
  7042. {
  7043. /**
  7044. * Reserved characters to preserve when using encode().
  7045. * @type array
  7046. */
  7047. protected $preserve = array();
  7048. /**
  7049. * String of characters that should be preserved while using encode().
  7050. * @param bool $preserve
  7051. */
  7052. public function __construct($preserve = false)
  7053. {
  7054. // unreserved letters, ought to const-ify
  7055. for ($i = 48; $i <= 57; $i++) { // digits
  7056. $this->preserve[$i] = true;
  7057. }
  7058. for ($i = 65; $i <= 90; $i++) { // upper-case
  7059. $this->preserve[$i] = true;
  7060. }
  7061. for ($i = 97; $i <= 122; $i++) { // lower-case
  7062. $this->preserve[$i] = true;
  7063. }
  7064. $this->preserve[45] = true; // Dash -
  7065. $this->preserve[46] = true; // Period .
  7066. $this->preserve[95] = true; // Underscore _
  7067. $this->preserve[126]= true; // Tilde ~
  7068. // extra letters not to escape
  7069. if ($preserve !== false) {
  7070. for ($i = 0, $c = strlen($preserve); $i < $c; $i++) {
  7071. $this->preserve[ord($preserve[$i])] = true;
  7072. }
  7073. }
  7074. }
  7075. /**
  7076. * Our replacement for urlencode, it encodes all non-reserved characters,
  7077. * as well as any extra characters that were instructed to be preserved.
  7078. * @note
  7079. * Assumes that the string has already been normalized, making any
  7080. * and all percent escape sequences valid. Percents will not be
  7081. * re-escaped, regardless of their status in $preserve
  7082. * @param string $string String to be encoded
  7083. * @return string Encoded string.
  7084. */
  7085. public function encode($string)
  7086. {
  7087. $ret = '';
  7088. for ($i = 0, $c = strlen($string); $i < $c; $i++) {
  7089. if ($string[$i] !== '%' && !isset($this->preserve[$int = ord($string[$i])])) {
  7090. $ret .= '%' . sprintf('%02X', $int);
  7091. } else {
  7092. $ret .= $string[$i];
  7093. }
  7094. }
  7095. return $ret;
  7096. }
  7097. /**
  7098. * Fix up percent-encoding by decoding unreserved characters and normalizing.
  7099. * @warning This function is affected by $preserve, even though the
  7100. * usual desired behavior is for this not to preserve those
  7101. * characters. Be careful when reusing instances of PercentEncoder!
  7102. * @param string $string String to normalize
  7103. * @return string
  7104. */
  7105. public function normalize($string)
  7106. {
  7107. if ($string == '') {
  7108. return '';
  7109. }
  7110. $parts = explode('%', $string);
  7111. $ret = array_shift($parts);
  7112. foreach ($parts as $part) {
  7113. $length = strlen($part);
  7114. if ($length < 2) {
  7115. $ret .= '%25' . $part;
  7116. continue;
  7117. }
  7118. $encoding = substr($part, 0, 2);
  7119. $text = substr($part, 2);
  7120. if (!ctype_xdigit($encoding)) {
  7121. $ret .= '%25' . $part;
  7122. continue;
  7123. }
  7124. $int = hexdec($encoding);
  7125. if (isset($this->preserve[$int])) {
  7126. $ret .= chr($int) . $text;
  7127. continue;
  7128. }
  7129. $encoding = strtoupper($encoding);
  7130. $ret .= '%' . $encoding . $text;
  7131. }
  7132. return $ret;
  7133. }
  7134. }
  7135. /**
  7136. * Generic property list implementation
  7137. */
  7138. class HTMLPurifier_PropertyList
  7139. {
  7140. /**
  7141. * Internal data-structure for properties.
  7142. * @type array
  7143. */
  7144. protected $data = array();
  7145. /**
  7146. * Parent plist.
  7147. * @type HTMLPurifier_PropertyList
  7148. */
  7149. protected $parent;
  7150. /**
  7151. * Cache.
  7152. * @type array
  7153. */
  7154. protected $cache;
  7155. /**
  7156. * @param HTMLPurifier_PropertyList $parent Parent plist
  7157. */
  7158. public function __construct($parent = null)
  7159. {
  7160. $this->parent = $parent;
  7161. }
  7162. /**
  7163. * Recursively retrieves the value for a key
  7164. * @param string $name
  7165. * @throws HTMLPurifier_Exception
  7166. */
  7167. public function get($name)
  7168. {
  7169. if ($this->has($name)) {
  7170. return $this->data[$name];
  7171. }
  7172. // possible performance bottleneck, convert to iterative if necessary
  7173. if ($this->parent) {
  7174. return $this->parent->get($name);
  7175. }
  7176. throw new HTMLPurifier_Exception("Key '$name' not found");
  7177. }
  7178. /**
  7179. * Sets the value of a key, for this plist
  7180. * @param string $name
  7181. * @param mixed $value
  7182. */
  7183. public function set($name, $value)
  7184. {
  7185. $this->data[$name] = $value;
  7186. }
  7187. /**
  7188. * Returns true if a given key exists
  7189. * @param string $name
  7190. * @return bool
  7191. */
  7192. public function has($name)
  7193. {
  7194. return array_key_exists($name, $this->data);
  7195. }
  7196. /**
  7197. * Resets a value to the value of it's parent, usually the default. If
  7198. * no value is specified, the entire plist is reset.
  7199. * @param string $name
  7200. */
  7201. public function reset($name = null)
  7202. {
  7203. if ($name == null) {
  7204. $this->data = array();
  7205. } else {
  7206. unset($this->data[$name]);
  7207. }
  7208. }
  7209. /**
  7210. * Squashes this property list and all of its property lists into a single
  7211. * array, and returns the array. This value is cached by default.
  7212. * @param bool $force If true, ignores the cache and regenerates the array.
  7213. * @return array
  7214. */
  7215. public function squash($force = false)
  7216. {
  7217. if ($this->cache !== null && !$force) {
  7218. return $this->cache;
  7219. }
  7220. if ($this->parent) {
  7221. return $this->cache = array_merge($this->parent->squash($force), $this->data);
  7222. } else {
  7223. return $this->cache = $this->data;
  7224. }
  7225. }
  7226. /**
  7227. * Returns the parent plist.
  7228. * @return HTMLPurifier_PropertyList
  7229. */
  7230. public function getParent()
  7231. {
  7232. return $this->parent;
  7233. }
  7234. /**
  7235. * Sets the parent plist.
  7236. * @param HTMLPurifier_PropertyList $plist Parent plist
  7237. */
  7238. public function setParent($plist)
  7239. {
  7240. $this->parent = $plist;
  7241. }
  7242. }
  7243. /**
  7244. * Property list iterator. Do not instantiate this class directly.
  7245. */
  7246. class HTMLPurifier_PropertyListIterator extends FilterIterator
  7247. {
  7248. /**
  7249. * @type int
  7250. */
  7251. protected $l;
  7252. /**
  7253. * @type string
  7254. */
  7255. protected $filter;
  7256. /**
  7257. * @param Iterator $iterator Array of data to iterate over
  7258. * @param string $filter Optional prefix to only allow values of
  7259. */
  7260. public function __construct(Iterator $iterator, $filter = null)
  7261. {
  7262. parent::__construct($iterator);
  7263. $this->l = strlen($filter);
  7264. $this->filter = $filter;
  7265. }
  7266. /**
  7267. * @return bool
  7268. */
  7269. public function accept()
  7270. {
  7271. $key = $this->getInnerIterator()->key();
  7272. if (strncmp($key, $this->filter, $this->l) !== 0) {
  7273. return false;
  7274. }
  7275. return true;
  7276. }
  7277. }
  7278. /**
  7279. * A simple array-backed queue, based off of the classic Okasaki
  7280. * persistent amortized queue. The basic idea is to maintain two
  7281. * stacks: an input stack and an output stack. When the output
  7282. * stack runs out, reverse the input stack and use it as the output
  7283. * stack.
  7284. *
  7285. * We don't use the SPL implementation because it's only supported
  7286. * on PHP 5.3 and later.
  7287. *
  7288. * Exercise: Prove that push/pop on this queue take amortized O(1) time.
  7289. *
  7290. * Exercise: Extend this queue to be a deque, while preserving amortized
  7291. * O(1) time. Some care must be taken on rebalancing to avoid quadratic
  7292. * behaviour caused by repeatedly shuffling data from the input stack
  7293. * to the output stack and back.
  7294. */
  7295. class HTMLPurifier_Queue {
  7296. private $input;
  7297. private $output;
  7298. public function __construct($input = array()) {
  7299. $this->input = $input;
  7300. $this->output = array();
  7301. }
  7302. /**
  7303. * Shifts an element off the front of the queue.
  7304. */
  7305. public function shift() {
  7306. if (empty($this->output)) {
  7307. $this->output = array_reverse($this->input);
  7308. $this->input = array();
  7309. }
  7310. if (empty($this->output)) {
  7311. return NULL;
  7312. }
  7313. return array_pop($this->output);
  7314. }
  7315. /**
  7316. * Pushes an element onto the front of the queue.
  7317. */
  7318. public function push($x) {
  7319. array_push($this->input, $x);
  7320. }
  7321. /**
  7322. * Checks if it's empty.
  7323. */
  7324. public function isEmpty() {
  7325. return empty($this->input) && empty($this->output);
  7326. }
  7327. }
  7328. /**
  7329. * Supertype for classes that define a strategy for modifying/purifying tokens.
  7330. *
  7331. * While HTMLPurifier's core purpose is fixing HTML into something proper,
  7332. * strategies provide plug points for extra configuration or even extra
  7333. * features, such as custom tags, custom parsing of text, etc.
  7334. */
  7335. abstract class HTMLPurifier_Strategy
  7336. {
  7337. /**
  7338. * Executes the strategy on the tokens.
  7339. *
  7340. * @param HTMLPurifier_Token[] $tokens Array of HTMLPurifier_Token objects to be operated on.
  7341. * @param HTMLPurifier_Config $config
  7342. * @param HTMLPurifier_Context $context
  7343. * @return HTMLPurifier_Token[] Processed array of token objects.
  7344. */
  7345. abstract public function execute($tokens, $config, $context);
  7346. }
  7347. /**
  7348. * This is in almost every respect equivalent to an array except
  7349. * that it keeps track of which keys were accessed.
  7350. *
  7351. * @warning For the sake of backwards compatibility with early versions
  7352. * of PHP 5, you must not use the $hash[$key] syntax; if you do
  7353. * our version of offsetGet is never called.
  7354. */
  7355. class HTMLPurifier_StringHash extends ArrayObject
  7356. {
  7357. /**
  7358. * @type array
  7359. */
  7360. protected $accessed = array();
  7361. /**
  7362. * Retrieves a value, and logs the access.
  7363. * @param mixed $index
  7364. * @return mixed
  7365. */
  7366. public function offsetGet($index)
  7367. {
  7368. $this->accessed[$index] = true;
  7369. return parent::offsetGet($index);
  7370. }
  7371. /**
  7372. * Returns a lookup array of all array indexes that have been accessed.
  7373. * @return array in form array($index => true).
  7374. */
  7375. public function getAccessed()
  7376. {
  7377. return $this->accessed;
  7378. }
  7379. /**
  7380. * Resets the access array.
  7381. */
  7382. public function resetAccessed()
  7383. {
  7384. $this->accessed = array();
  7385. }
  7386. }
  7387. /**
  7388. * Parses string hash files. File format is as such:
  7389. *
  7390. * DefaultKeyValue
  7391. * KEY: Value
  7392. * KEY2: Value2
  7393. * --MULTILINE-KEY--
  7394. * Multiline
  7395. * value.
  7396. *
  7397. * Which would output something similar to:
  7398. *
  7399. * array(
  7400. * 'ID' => 'DefaultKeyValue',
  7401. * 'KEY' => 'Value',
  7402. * 'KEY2' => 'Value2',
  7403. * 'MULTILINE-KEY' => "Multiline\nvalue.\n",
  7404. * )
  7405. *
  7406. * We use this as an easy to use file-format for configuration schema
  7407. * files, but the class itself is usage agnostic.
  7408. *
  7409. * You can use ---- to forcibly terminate parsing of a single string-hash;
  7410. * this marker is used in multi string-hashes to delimit boundaries.
  7411. */
  7412. class HTMLPurifier_StringHashParser
  7413. {
  7414. /**
  7415. * @type string
  7416. */
  7417. public $default = 'ID';
  7418. /**
  7419. * Parses a file that contains a single string-hash.
  7420. * @param string $file
  7421. * @return array
  7422. */
  7423. public function parseFile($file)
  7424. {
  7425. if (!file_exists($file)) {
  7426. return false;
  7427. }
  7428. $fh = fopen($file, 'r');
  7429. if (!$fh) {
  7430. return false;
  7431. }
  7432. $ret = $this->parseHandle($fh);
  7433. fclose($fh);
  7434. return $ret;
  7435. }
  7436. /**
  7437. * Parses a file that contains multiple string-hashes delimited by '----'
  7438. * @param string $file
  7439. * @return array
  7440. */
  7441. public function parseMultiFile($file)
  7442. {
  7443. if (!file_exists($file)) {
  7444. return false;
  7445. }
  7446. $ret = array();
  7447. $fh = fopen($file, 'r');
  7448. if (!$fh) {
  7449. return false;
  7450. }
  7451. while (!feof($fh)) {
  7452. $ret[] = $this->parseHandle($fh);
  7453. }
  7454. fclose($fh);
  7455. return $ret;
  7456. }
  7457. /**
  7458. * Internal parser that acepts a file handle.
  7459. * @note While it's possible to simulate in-memory parsing by using
  7460. * custom stream wrappers, if such a use-case arises we should
  7461. * factor out the file handle into its own class.
  7462. * @param resource $fh File handle with pointer at start of valid string-hash
  7463. * block.
  7464. * @return array
  7465. */
  7466. protected function parseHandle($fh)
  7467. {
  7468. $state = false;
  7469. $single = false;
  7470. $ret = array();
  7471. do {
  7472. $line = fgets($fh);
  7473. if ($line === false) {
  7474. break;
  7475. }
  7476. $line = rtrim($line, "\n\r");
  7477. if (!$state && $line === '') {
  7478. continue;
  7479. }
  7480. if ($line === '----') {
  7481. break;
  7482. }
  7483. if (strncmp('--#', $line, 3) === 0) {
  7484. // Comment
  7485. continue;
  7486. } elseif (strncmp('--', $line, 2) === 0) {
  7487. // Multiline declaration
  7488. $state = trim($line, '- ');
  7489. if (!isset($ret[$state])) {
  7490. $ret[$state] = '';
  7491. }
  7492. continue;
  7493. } elseif (!$state) {
  7494. $single = true;
  7495. if (strpos($line, ':') !== false) {
  7496. // Single-line declaration
  7497. list($state, $line) = explode(':', $line, 2);
  7498. $line = trim($line);
  7499. } else {
  7500. // Use default declaration
  7501. $state = $this->default;
  7502. }
  7503. }
  7504. if ($single) {
  7505. $ret[$state] = $line;
  7506. $single = false;
  7507. $state = false;
  7508. } else {
  7509. $ret[$state] .= "$line\n";
  7510. }
  7511. } while (!feof($fh));
  7512. return $ret;
  7513. }
  7514. }
  7515. /**
  7516. * Defines a mutation of an obsolete tag into a valid tag.
  7517. */
  7518. abstract class HTMLPurifier_TagTransform
  7519. {
  7520. /**
  7521. * Tag name to transform the tag to.
  7522. * @type string
  7523. */
  7524. public $transform_to;
  7525. /**
  7526. * Transforms the obsolete tag into the valid tag.
  7527. * @param HTMLPurifier_Token_Tag $tag Tag to be transformed.
  7528. * @param HTMLPurifier_Config $config Mandatory HTMLPurifier_Config object
  7529. * @param HTMLPurifier_Context $context Mandatory HTMLPurifier_Context object
  7530. */
  7531. abstract public function transform($tag, $config, $context);
  7532. /**
  7533. * Prepends CSS properties to the style attribute, creating the
  7534. * attribute if it doesn't exist.
  7535. * @warning Copied over from AttrTransform, be sure to keep in sync
  7536. * @param array $attr Attribute array to process (passed by reference)
  7537. * @param string $css CSS to prepend
  7538. */
  7539. protected function prependCSS(&$attr, $css)
  7540. {
  7541. $attr['style'] = isset($attr['style']) ? $attr['style'] : '';
  7542. $attr['style'] = $css . $attr['style'];
  7543. }
  7544. }
  7545. /**
  7546. * Abstract base token class that all others inherit from.
  7547. */
  7548. abstract class HTMLPurifier_Token
  7549. {
  7550. /**
  7551. * Line number node was on in source document. Null if unknown.
  7552. * @type int
  7553. */
  7554. public $line;
  7555. /**
  7556. * Column of line node was on in source document. Null if unknown.
  7557. * @type int
  7558. */
  7559. public $col;
  7560. /**
  7561. * Lookup array of processing that this token is exempt from.
  7562. * Currently, valid values are "ValidateAttributes" and
  7563. * "MakeWellFormed_TagClosedError"
  7564. * @type array
  7565. */
  7566. public $armor = array();
  7567. /**
  7568. * Used during MakeWellFormed.
  7569. * @type
  7570. */
  7571. public $skip;
  7572. /**
  7573. * @type
  7574. */
  7575. public $rewind;
  7576. /**
  7577. * @type
  7578. */
  7579. public $carryover;
  7580. /**
  7581. * @param string $n
  7582. * @return null|string
  7583. */
  7584. public function __get($n)
  7585. {
  7586. if ($n === 'type') {
  7587. trigger_error('Deprecated type property called; use instanceof', E_USER_NOTICE);
  7588. switch (get_class($this)) {
  7589. case 'HTMLPurifier_Token_Start':
  7590. return 'start';
  7591. case 'HTMLPurifier_Token_Empty':
  7592. return 'empty';
  7593. case 'HTMLPurifier_Token_End':
  7594. return 'end';
  7595. case 'HTMLPurifier_Token_Text':
  7596. return 'text';
  7597. case 'HTMLPurifier_Token_Comment':
  7598. return 'comment';
  7599. default:
  7600. return null;
  7601. }
  7602. }
  7603. }
  7604. /**
  7605. * Sets the position of the token in the source document.
  7606. * @param int $l
  7607. * @param int $c
  7608. */
  7609. public function position($l = null, $c = null)
  7610. {
  7611. $this->line = $l;
  7612. $this->col = $c;
  7613. }
  7614. /**
  7615. * Convenience function for DirectLex settings line/col position.
  7616. * @param int $l
  7617. * @param int $c
  7618. */
  7619. public function rawPosition($l, $c)
  7620. {
  7621. if ($c === -1) {
  7622. $l++;
  7623. }
  7624. $this->line = $l;
  7625. $this->col = $c;
  7626. }
  7627. /**
  7628. * Converts a token into its corresponding node.
  7629. */
  7630. abstract public function toNode();
  7631. }
  7632. /**
  7633. * Factory for token generation.
  7634. *
  7635. * @note Doing some benchmarking indicates that the new operator is much
  7636. * slower than the clone operator (even discounting the cost of the
  7637. * constructor). This class is for that optimization.
  7638. * Other then that, there's not much point as we don't
  7639. * maintain parallel HTMLPurifier_Token hierarchies (the main reason why
  7640. * you'd want to use an abstract factory).
  7641. * @todo Port DirectLex to use this
  7642. */
  7643. class HTMLPurifier_TokenFactory
  7644. {
  7645. // p stands for prototype
  7646. /**
  7647. * @type HTMLPurifier_Token_Start
  7648. */
  7649. private $p_start;
  7650. /**
  7651. * @type HTMLPurifier_Token_End
  7652. */
  7653. private $p_end;
  7654. /**
  7655. * @type HTMLPurifier_Token_Empty
  7656. */
  7657. private $p_empty;
  7658. /**
  7659. * @type HTMLPurifier_Token_Text
  7660. */
  7661. private $p_text;
  7662. /**
  7663. * @type HTMLPurifier_Token_Comment
  7664. */
  7665. private $p_comment;
  7666. /**
  7667. * Generates blank prototypes for cloning.
  7668. */
  7669. public function __construct()
  7670. {
  7671. $this->p_start = new HTMLPurifier_Token_Start('', array());
  7672. $this->p_end = new HTMLPurifier_Token_End('');
  7673. $this->p_empty = new HTMLPurifier_Token_Empty('', array());
  7674. $this->p_text = new HTMLPurifier_Token_Text('');
  7675. $this->p_comment = new HTMLPurifier_Token_Comment('');
  7676. }
  7677. /**
  7678. * Creates a HTMLPurifier_Token_Start.
  7679. * @param string $name Tag name
  7680. * @param array $attr Associative array of attributes
  7681. * @return HTMLPurifier_Token_Start Generated HTMLPurifier_Token_Start
  7682. */
  7683. public function createStart($name, $attr = array())
  7684. {
  7685. $p = clone $this->p_start;
  7686. $p->__construct($name, $attr);
  7687. return $p;
  7688. }
  7689. /**
  7690. * Creates a HTMLPurifier_Token_End.
  7691. * @param string $name Tag name
  7692. * @return HTMLPurifier_Token_End Generated HTMLPurifier_Token_End
  7693. */
  7694. public function createEnd($name)
  7695. {
  7696. $p = clone $this->p_end;
  7697. $p->__construct($name);
  7698. return $p;
  7699. }
  7700. /**
  7701. * Creates a HTMLPurifier_Token_Empty.
  7702. * @param string $name Tag name
  7703. * @param array $attr Associative array of attributes
  7704. * @return HTMLPurifier_Token_Empty Generated HTMLPurifier_Token_Empty
  7705. */
  7706. public function createEmpty($name, $attr = array())
  7707. {
  7708. $p = clone $this->p_empty;
  7709. $p->__construct($name, $attr);
  7710. return $p;
  7711. }
  7712. /**
  7713. * Creates a HTMLPurifier_Token_Text.
  7714. * @param string $data Data of text token
  7715. * @return HTMLPurifier_Token_Text Generated HTMLPurifier_Token_Text
  7716. */
  7717. public function createText($data)
  7718. {
  7719. $p = clone $this->p_text;
  7720. $p->__construct($data);
  7721. return $p;
  7722. }
  7723. /**
  7724. * Creates a HTMLPurifier_Token_Comment.
  7725. * @param string $data Data of comment token
  7726. * @return HTMLPurifier_Token_Comment Generated HTMLPurifier_Token_Comment
  7727. */
  7728. public function createComment($data)
  7729. {
  7730. $p = clone $this->p_comment;
  7731. $p->__construct($data);
  7732. return $p;
  7733. }
  7734. }
  7735. /**
  7736. * HTML Purifier's internal representation of a URI.
  7737. * @note
  7738. * Internal data-structures are completely escaped. If the data needs
  7739. * to be used in a non-URI context (which is very unlikely), be sure
  7740. * to decode it first. The URI may not necessarily be well-formed until
  7741. * validate() is called.
  7742. */
  7743. class HTMLPurifier_URI
  7744. {
  7745. /**
  7746. * @type string
  7747. */
  7748. public $scheme;
  7749. /**
  7750. * @type string
  7751. */
  7752. public $userinfo;
  7753. /**
  7754. * @type string
  7755. */
  7756. public $host;
  7757. /**
  7758. * @type int
  7759. */
  7760. public $port;
  7761. /**
  7762. * @type string
  7763. */
  7764. public $path;
  7765. /**
  7766. * @type string
  7767. */
  7768. public $query;
  7769. /**
  7770. * @type string
  7771. */
  7772. public $fragment;
  7773. /**
  7774. * @param string $scheme
  7775. * @param string $userinfo
  7776. * @param string $host
  7777. * @param int $port
  7778. * @param string $path
  7779. * @param string $query
  7780. * @param string $fragment
  7781. * @note Automatically normalizes scheme and port
  7782. */
  7783. public function __construct($scheme, $userinfo, $host, $port, $path, $query, $fragment)
  7784. {
  7785. $this->scheme = is_null($scheme) || ctype_lower($scheme) ? $scheme : strtolower($scheme);
  7786. $this->userinfo = $userinfo;
  7787. $this->host = $host;
  7788. $this->port = is_null($port) ? $port : (int)$port;
  7789. $this->path = $path;
  7790. $this->query = $query;
  7791. $this->fragment = $fragment;
  7792. }
  7793. /**
  7794. * Retrieves a scheme object corresponding to the URI's scheme/default
  7795. * @param HTMLPurifier_Config $config
  7796. * @param HTMLPurifier_Context $context
  7797. * @return HTMLPurifier_URIScheme Scheme object appropriate for validating this URI
  7798. */
  7799. public function getSchemeObj($config, $context)
  7800. {
  7801. $registry = HTMLPurifier_URISchemeRegistry::instance();
  7802. if ($this->scheme !== null) {
  7803. $scheme_obj = $registry->getScheme($this->scheme, $config, $context);
  7804. if (!$scheme_obj) {
  7805. return false;
  7806. } // invalid scheme, clean it out
  7807. } else {
  7808. // no scheme: retrieve the default one
  7809. $def = $config->getDefinition('URI');
  7810. $scheme_obj = $def->getDefaultScheme($config, $context);
  7811. if (!$scheme_obj) {
  7812. // something funky happened to the default scheme object
  7813. trigger_error(
  7814. 'Default scheme object "' . $def->defaultScheme . '" was not readable',
  7815. E_USER_WARNING
  7816. );
  7817. return false;
  7818. }
  7819. }
  7820. return $scheme_obj;
  7821. }
  7822. /**
  7823. * Generic validation method applicable for all schemes. May modify
  7824. * this URI in order to get it into a compliant form.
  7825. * @param HTMLPurifier_Config $config
  7826. * @param HTMLPurifier_Context $context
  7827. * @return bool True if validation/filtering succeeds, false if failure
  7828. */
  7829. public function validate($config, $context)
  7830. {
  7831. // ABNF definitions from RFC 3986
  7832. $chars_sub_delims = '!$&\'()*+,;=';
  7833. $chars_gen_delims = ':/?#[]@';
  7834. $chars_pchar = $chars_sub_delims . ':@';
  7835. // validate host
  7836. if (!is_null($this->host)) {
  7837. $host_def = new HTMLPurifier_AttrDef_URI_Host();
  7838. $this->host = $host_def->validate($this->host, $config, $context);
  7839. if ($this->host === false) {
  7840. $this->host = null;
  7841. }
  7842. }
  7843. // validate scheme
  7844. // NOTE: It's not appropriate to check whether or not this
  7845. // scheme is in our registry, since a URIFilter may convert a
  7846. // URI that we don't allow into one we do. So instead, we just
  7847. // check if the scheme can be dropped because there is no host
  7848. // and it is our default scheme.
  7849. if (!is_null($this->scheme) && is_null($this->host) || $this->host === '') {
  7850. // support for relative paths is pretty abysmal when the
  7851. // scheme is present, so axe it when possible
  7852. $def = $config->getDefinition('URI');
  7853. if ($def->defaultScheme === $this->scheme) {
  7854. $this->scheme = null;
  7855. }
  7856. }
  7857. // validate username
  7858. if (!is_null($this->userinfo)) {
  7859. $encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . ':');
  7860. $this->userinfo = $encoder->encode($this->userinfo);
  7861. }
  7862. // validate port
  7863. if (!is_null($this->port)) {
  7864. if ($this->port < 1 || $this->port > 65535) {
  7865. $this->port = null;
  7866. }
  7867. }
  7868. // validate path
  7869. $segments_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/');
  7870. if (!is_null($this->host)) { // this catches $this->host === ''
  7871. // path-abempty (hier and relative)
  7872. // http://www.example.com/my/path
  7873. // //www.example.com/my/path (looks odd, but works, and
  7874. // recognized by most browsers)
  7875. // (this set is valid or invalid on a scheme by scheme
  7876. // basis, so we'll deal with it later)
  7877. // file:///my/path
  7878. // ///my/path
  7879. $this->path = $segments_encoder->encode($this->path);
  7880. } elseif ($this->path !== '') {
  7881. if ($this->path[0] === '/') {
  7882. // path-absolute (hier and relative)
  7883. // http:/my/path
  7884. // /my/path
  7885. if (strlen($this->path) >= 2 && $this->path[1] === '/') {
  7886. // This could happen if both the host gets stripped
  7887. // out
  7888. // http://my/path
  7889. // //my/path
  7890. $this->path = '';
  7891. } else {
  7892. $this->path = $segments_encoder->encode($this->path);
  7893. }
  7894. } elseif (!is_null($this->scheme)) {
  7895. // path-rootless (hier)
  7896. // http:my/path
  7897. // Short circuit evaluation means we don't need to check nz
  7898. $this->path = $segments_encoder->encode($this->path);
  7899. } else {
  7900. // path-noscheme (relative)
  7901. // my/path
  7902. // (once again, not checking nz)
  7903. $segment_nc_encoder = new HTMLPurifier_PercentEncoder($chars_sub_delims . '@');
  7904. $c = strpos($this->path, '/');
  7905. if ($c !== false) {
  7906. $this->path =
  7907. $segment_nc_encoder->encode(substr($this->path, 0, $c)) .
  7908. $segments_encoder->encode(substr($this->path, $c));
  7909. } else {
  7910. $this->path = $segment_nc_encoder->encode($this->path);
  7911. }
  7912. }
  7913. } else {
  7914. // path-empty (hier and relative)
  7915. $this->path = ''; // just to be safe
  7916. }
  7917. // qf = query and fragment
  7918. $qf_encoder = new HTMLPurifier_PercentEncoder($chars_pchar . '/?');
  7919. if (!is_null($this->query)) {
  7920. $this->query = $qf_encoder->encode($this->query);
  7921. }
  7922. if (!is_null($this->fragment)) {
  7923. $this->fragment = $qf_encoder->encode($this->fragment);
  7924. }
  7925. return true;
  7926. }
  7927. /**
  7928. * Convert URI back to string
  7929. * @return string URI appropriate for output
  7930. */
  7931. public function toString()
  7932. {
  7933. // reconstruct authority
  7934. $authority = null;
  7935. // there is a rendering difference between a null authority
  7936. // (http:foo-bar) and an empty string authority
  7937. // (http:///foo-bar).
  7938. if (!is_null($this->host)) {
  7939. $authority = '';
  7940. if (!is_null($this->userinfo)) {
  7941. $authority .= $this->userinfo . '@';
  7942. }
  7943. $authority .= $this->host;
  7944. if (!is_null($this->port)) {
  7945. $authority .= ':' . $this->port;
  7946. }
  7947. }
  7948. // Reconstruct the result
  7949. // One might wonder about parsing quirks from browsers after
  7950. // this reconstruction. Unfortunately, parsing behavior depends
  7951. // on what *scheme* was employed (file:///foo is handled *very*
  7952. // differently than http:///foo), so unfortunately we have to
  7953. // defer to the schemes to do the right thing.
  7954. $result = '';
  7955. if (!is_null($this->scheme)) {
  7956. $result .= $this->scheme . ':';
  7957. }
  7958. if (!is_null($authority)) {
  7959. $result .= '//' . $authority;
  7960. }
  7961. $result .= $this->path;
  7962. if (!is_null($this->query)) {
  7963. $result .= '?' . $this->query;
  7964. }
  7965. if (!is_null($this->fragment)) {
  7966. $result .= '#' . $this->fragment;
  7967. }
  7968. return $result;
  7969. }
  7970. /**
  7971. * Returns true if this URL might be considered a 'local' URL given
  7972. * the current context. This is true when the host is null, or
  7973. * when it matches the host supplied to the configuration.
  7974. *
  7975. * Note that this does not do any scheme checking, so it is mostly
  7976. * only appropriate for metadata that doesn't care about protocol
  7977. * security. isBenign is probably what you actually want.
  7978. * @param HTMLPurifier_Config $config
  7979. * @param HTMLPurifier_Context $context
  7980. * @return bool
  7981. */
  7982. public function isLocal($config, $context)
  7983. {
  7984. if ($this->host === null) {
  7985. return true;
  7986. }
  7987. $uri_def = $config->getDefinition('URI');
  7988. if ($uri_def->host === $this->host) {
  7989. return true;
  7990. }
  7991. return false;
  7992. }
  7993. /**
  7994. * Returns true if this URL should be considered a 'benign' URL,
  7995. * that is:
  7996. *
  7997. * - It is a local URL (isLocal), and
  7998. * - It has a equal or better level of security
  7999. * @param HTMLPurifier_Config $config
  8000. * @param HTMLPurifier_Context $context
  8001. * @return bool
  8002. */
  8003. public function isBenign($config, $context)
  8004. {
  8005. if (!$this->isLocal($config, $context)) {
  8006. return false;
  8007. }
  8008. $scheme_obj = $this->getSchemeObj($config, $context);
  8009. if (!$scheme_obj) {
  8010. return false;
  8011. } // conservative approach
  8012. $current_scheme_obj = $config->getDefinition('URI')->getDefaultScheme($config, $context);
  8013. if ($current_scheme_obj->secure) {
  8014. if (!$scheme_obj->secure) {
  8015. return false;
  8016. }
  8017. }
  8018. return true;
  8019. }
  8020. }
  8021. class HTMLPurifier_URIDefinition extends HTMLPurifier_Definition
  8022. {
  8023. public $type = 'URI';
  8024. protected $filters = array();
  8025. protected $postFilters = array();
  8026. protected $registeredFilters = array();
  8027. /**
  8028. * HTMLPurifier_URI object of the base specified at %URI.Base
  8029. */
  8030. public $base;
  8031. /**
  8032. * String host to consider "home" base, derived off of $base
  8033. */
  8034. public $host;
  8035. /**
  8036. * Name of default scheme based on %URI.DefaultScheme and %URI.Base
  8037. */
  8038. public $defaultScheme;
  8039. public function __construct()
  8040. {
  8041. $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternal());
  8042. $this->registerFilter(new HTMLPurifier_URIFilter_DisableExternalResources());
  8043. $this->registerFilter(new HTMLPurifier_URIFilter_DisableResources());
  8044. $this->registerFilter(new HTMLPurifier_URIFilter_HostBlacklist());
  8045. $this->registerFilter(new HTMLPurifier_URIFilter_SafeIframe());
  8046. $this->registerFilter(new HTMLPurifier_URIFilter_MakeAbsolute());
  8047. $this->registerFilter(new HTMLPurifier_URIFilter_Munge());
  8048. }
  8049. public function registerFilter($filter)
  8050. {
  8051. $this->registeredFilters[$filter->name] = $filter;
  8052. }
  8053. public function addFilter($filter, $config)
  8054. {
  8055. $r = $filter->prepare($config);
  8056. if ($r === false) return; // null is ok, for backwards compat
  8057. if ($filter->post) {
  8058. $this->postFilters[$filter->name] = $filter;
  8059. } else {
  8060. $this->filters[$filter->name] = $filter;
  8061. }
  8062. }
  8063. protected function doSetup($config)
  8064. {
  8065. $this->setupMemberVariables($config);
  8066. $this->setupFilters($config);
  8067. }
  8068. protected function setupFilters($config)
  8069. {
  8070. foreach ($this->registeredFilters as $name => $filter) {
  8071. if ($filter->always_load) {
  8072. $this->addFilter($filter, $config);
  8073. } else {
  8074. $conf = $config->get('URI.' . $name);
  8075. if ($conf !== false && $conf !== null) {
  8076. $this->addFilter($filter, $config);
  8077. }
  8078. }
  8079. }
  8080. unset($this->registeredFilters);
  8081. }
  8082. protected function setupMemberVariables($config)
  8083. {
  8084. $this->host = $config->get('URI.Host');
  8085. $base_uri = $config->get('URI.Base');
  8086. if (!is_null($base_uri)) {
  8087. $parser = new HTMLPurifier_URIParser();
  8088. $this->base = $parser->parse($base_uri);
  8089. $this->defaultScheme = $this->base->scheme;
  8090. if (is_null($this->host)) $this->host = $this->base->host;
  8091. }
  8092. if (is_null($this->defaultScheme)) $this->defaultScheme = $config->get('URI.DefaultScheme');
  8093. }
  8094. public function getDefaultScheme($config, $context)
  8095. {
  8096. return HTMLPurifier_URISchemeRegistry::instance()->getScheme($this->defaultScheme, $config, $context);
  8097. }
  8098. public function filter(&$uri, $config, $context)
  8099. {
  8100. foreach ($this->filters as $name => $f) {
  8101. $result = $f->filter($uri, $config, $context);
  8102. if (!$result) return false;
  8103. }
  8104. return true;
  8105. }
  8106. public function postFilter(&$uri, $config, $context)
  8107. {
  8108. foreach ($this->postFilters as $name => $f) {
  8109. $result = $f->filter($uri, $config, $context);
  8110. if (!$result) return false;
  8111. }
  8112. return true;
  8113. }
  8114. }
  8115. /**
  8116. * Chainable filters for custom URI processing.
  8117. *
  8118. * These filters can perform custom actions on a URI filter object,
  8119. * including transformation or blacklisting. A filter named Foo
  8120. * must have a corresponding configuration directive %URI.Foo,
  8121. * unless always_load is specified to be true.
  8122. *
  8123. * The following contexts may be available while URIFilters are being
  8124. * processed:
  8125. *
  8126. * - EmbeddedURI: true if URI is an embedded resource that will
  8127. * be loaded automatically on page load
  8128. * - CurrentToken: a reference to the token that is currently
  8129. * being processed
  8130. * - CurrentAttr: the name of the attribute that is currently being
  8131. * processed
  8132. * - CurrentCSSProperty: the name of the CSS property that is
  8133. * currently being processed (if applicable)
  8134. *
  8135. * @warning This filter is called before scheme object validation occurs.
  8136. * Make sure, if you require a specific scheme object, you
  8137. * you check that it exists. This allows filters to convert
  8138. * proprietary URI schemes into regular ones.
  8139. */
  8140. abstract class HTMLPurifier_URIFilter
  8141. {
  8142. /**
  8143. * Unique identifier of filter.
  8144. * @type string
  8145. */
  8146. public $name;
  8147. /**
  8148. * True if this filter should be run after scheme validation.
  8149. * @type bool
  8150. */
  8151. public $post = false;
  8152. /**
  8153. * True if this filter should always be loaded.
  8154. * This permits a filter to be named Foo without the corresponding
  8155. * %URI.Foo directive existing.
  8156. * @type bool
  8157. */
  8158. public $always_load = false;
  8159. /**
  8160. * Performs initialization for the filter. If the filter returns
  8161. * false, this means that it shouldn't be considered active.
  8162. * @param HTMLPurifier_Config $config
  8163. * @return bool
  8164. */
  8165. public function prepare($config)
  8166. {
  8167. return true;
  8168. }
  8169. /**
  8170. * Filter a URI object
  8171. * @param HTMLPurifier_URI $uri Reference to URI object variable
  8172. * @param HTMLPurifier_Config $config
  8173. * @param HTMLPurifier_Context $context
  8174. * @return bool Whether or not to continue processing: false indicates
  8175. * URL is no good, true indicates continue processing. Note that
  8176. * all changes are committed directly on the URI object
  8177. */
  8178. abstract public function filter(&$uri, $config, $context);
  8179. }
  8180. /**
  8181. * Parses a URI into the components and fragment identifier as specified
  8182. * by RFC 3986.
  8183. */
  8184. class HTMLPurifier_URIParser
  8185. {
  8186. /**
  8187. * Instance of HTMLPurifier_PercentEncoder to do normalization with.
  8188. */
  8189. protected $percentEncoder;
  8190. public function __construct()
  8191. {
  8192. $this->percentEncoder = new HTMLPurifier_PercentEncoder();
  8193. }
  8194. /**
  8195. * Parses a URI.
  8196. * @param $uri string URI to parse
  8197. * @return HTMLPurifier_URI representation of URI. This representation has
  8198. * not been validated yet and may not conform to RFC.
  8199. */
  8200. public function parse($uri)
  8201. {
  8202. $uri = $this->percentEncoder->normalize($uri);
  8203. // Regexp is as per Appendix B.
  8204. // Note that ["<>] are an addition to the RFC's recommended
  8205. // characters, because they represent external delimeters.
  8206. $r_URI = '!'.
  8207. '(([a-zA-Z0-9\.\+\-]+):)?'. // 2. Scheme
  8208. '(//([^/?#"<>]*))?'. // 4. Authority
  8209. '([^?#"<>]*)'. // 5. Path
  8210. '(\?([^#"<>]*))?'. // 7. Query
  8211. '(#([^"<>]*))?'. // 8. Fragment
  8212. '!';
  8213. $matches = array();
  8214. $result = preg_match($r_URI, $uri, $matches);
  8215. if (!$result) return false; // *really* invalid URI
  8216. // seperate out parts
  8217. $scheme = !empty($matches[1]) ? $matches[2] : null;
  8218. $authority = !empty($matches[3]) ? $matches[4] : null;
  8219. $path = $matches[5]; // always present, can be empty
  8220. $query = !empty($matches[6]) ? $matches[7] : null;
  8221. $fragment = !empty($matches[8]) ? $matches[9] : null;
  8222. // further parse authority
  8223. if ($authority !== null) {
  8224. $r_authority = "/^((.+?)@)?(\[[^\]]+\]|[^:]*)(:(\d*))?/";
  8225. $matches = array();
  8226. preg_match($r_authority, $authority, $matches);
  8227. $userinfo = !empty($matches[1]) ? $matches[2] : null;
  8228. $host = !empty($matches[3]) ? $matches[3] : '';
  8229. $port = !empty($matches[4]) ? (int) $matches[5] : null;
  8230. } else {
  8231. $port = $host = $userinfo = null;
  8232. }
  8233. return new HTMLPurifier_URI(
  8234. $scheme, $userinfo, $host, $port, $path, $query, $fragment);
  8235. }
  8236. }
  8237. /**
  8238. * Validator for the components of a URI for a specific scheme
  8239. */
  8240. abstract class HTMLPurifier_URIScheme
  8241. {
  8242. /**
  8243. * Scheme's default port (integer). If an explicit port number is
  8244. * specified that coincides with the default port, it will be
  8245. * elided.
  8246. * @type int
  8247. */
  8248. public $default_port = null;
  8249. /**
  8250. * Whether or not URIs of this scheme are locatable by a browser
  8251. * http and ftp are accessible, while mailto and news are not.
  8252. * @type bool
  8253. */
  8254. public $browsable = false;
  8255. /**
  8256. * Whether or not data transmitted over this scheme is encrypted.
  8257. * https is secure, http is not.
  8258. * @type bool
  8259. */
  8260. public $secure = false;
  8261. /**
  8262. * Whether or not the URI always uses <hier_part>, resolves edge cases
  8263. * with making relative URIs absolute
  8264. * @type bool
  8265. */
  8266. public $hierarchical = false;
  8267. /**
  8268. * Whether or not the URI may omit a hostname when the scheme is
  8269. * explicitly specified, ala file:///path/to/file. As of writing,
  8270. * 'file' is the only scheme that browsers support his properly.
  8271. * @type bool
  8272. */
  8273. public $may_omit_host = false;
  8274. /**
  8275. * Validates the components of a URI for a specific scheme.
  8276. * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object
  8277. * @param HTMLPurifier_Config $config
  8278. * @param HTMLPurifier_Context $context
  8279. * @return bool success or failure
  8280. */
  8281. abstract public function doValidate(&$uri, $config, $context);
  8282. /**
  8283. * Public interface for validating components of a URI. Performs a
  8284. * bunch of default actions. Don't overload this method.
  8285. * @param HTMLPurifier_URI $uri Reference to a HTMLPurifier_URI object
  8286. * @param HTMLPurifier_Config $config
  8287. * @param HTMLPurifier_Context $context
  8288. * @return bool success or failure
  8289. */
  8290. public function validate(&$uri, $config, $context)
  8291. {
  8292. if ($this->default_port == $uri->port) {
  8293. $uri->port = null;
  8294. }
  8295. // kludge: browsers do funny things when the scheme but not the
  8296. // authority is set
  8297. if (!$this->may_omit_host &&
  8298. // if the scheme is present, a missing host is always in error
  8299. (!is_null($uri->scheme) && ($uri->host === '' || is_null($uri->host))) ||
  8300. // if the scheme is not present, a *blank* host is in error,
  8301. // since this translates into '///path' which most browsers
  8302. // interpret as being 'http://path'.
  8303. (is_null($uri->scheme) && $uri->host === '')
  8304. ) {
  8305. do {
  8306. if (is_null($uri->scheme)) {
  8307. if (substr($uri->path, 0, 2) != '//') {
  8308. $uri->host = null;
  8309. break;
  8310. }
  8311. // URI is '////path', so we cannot nullify the
  8312. // host to preserve semantics. Try expanding the
  8313. // hostname instead (fall through)
  8314. }
  8315. // first see if we can manually insert a hostname
  8316. $host = $config->get('URI.Host');
  8317. if (!is_null($host)) {
  8318. $uri->host = $host;
  8319. } else {
  8320. // we can't do anything sensible, reject the URL.
  8321. return false;
  8322. }
  8323. } while (false);
  8324. }
  8325. return $this->doValidate($uri, $config, $context);
  8326. }
  8327. }
  8328. /**
  8329. * Registry for retrieving specific URI scheme validator objects.
  8330. */
  8331. class HTMLPurifier_URISchemeRegistry
  8332. {
  8333. /**
  8334. * Retrieve sole instance of the registry.
  8335. * @param HTMLPurifier_URISchemeRegistry $prototype Optional prototype to overload sole instance with,
  8336. * or bool true to reset to default registry.
  8337. * @return HTMLPurifier_URISchemeRegistry
  8338. * @note Pass a registry object $prototype with a compatible interface and
  8339. * the function will copy it and return it all further times.
  8340. */
  8341. public static function instance($prototype = null)
  8342. {
  8343. static $instance = null;
  8344. if ($prototype !== null) {
  8345. $instance = $prototype;
  8346. } elseif ($instance === null || $prototype == true) {
  8347. $instance = new HTMLPurifier_URISchemeRegistry();
  8348. }
  8349. return $instance;
  8350. }
  8351. /**
  8352. * Cache of retrieved schemes.
  8353. * @type HTMLPurifier_URIScheme[]
  8354. */
  8355. protected $schemes = array();
  8356. /**
  8357. * Retrieves a scheme validator object
  8358. * @param string $scheme String scheme name like http or mailto
  8359. * @param HTMLPurifier_Config $config
  8360. * @param HTMLPurifier_Context $context
  8361. * @return HTMLPurifier_URIScheme
  8362. */
  8363. public function getScheme($scheme, $config, $context)
  8364. {
  8365. if (!$config) {
  8366. $config = HTMLPurifier_Config::createDefault();
  8367. }
  8368. // important, otherwise attacker could include arbitrary file
  8369. $allowed_schemes = $config->get('URI.AllowedSchemes');
  8370. if (!$config->get('URI.OverrideAllowedSchemes') &&
  8371. !isset($allowed_schemes[$scheme])
  8372. ) {
  8373. return;
  8374. }
  8375. if (isset($this->schemes[$scheme])) {
  8376. return $this->schemes[$scheme];
  8377. }
  8378. if (!isset($allowed_schemes[$scheme])) {
  8379. return;
  8380. }
  8381. $class = 'HTMLPurifier_URIScheme_' . $scheme;
  8382. if (!class_exists($class)) {
  8383. return;
  8384. }
  8385. $this->schemes[$scheme] = new $class();
  8386. return $this->schemes[$scheme];
  8387. }
  8388. /**
  8389. * Registers a custom scheme to the cache, bypassing reflection.
  8390. * @param string $scheme Scheme name
  8391. * @param HTMLPurifier_URIScheme $scheme_obj
  8392. */
  8393. public function register($scheme, $scheme_obj)
  8394. {
  8395. $this->schemes[$scheme] = $scheme_obj;
  8396. }
  8397. }
  8398. /**
  8399. * Class for converting between different unit-lengths as specified by
  8400. * CSS.
  8401. */
  8402. class HTMLPurifier_UnitConverter
  8403. {
  8404. const ENGLISH = 1;
  8405. const METRIC = 2;
  8406. const DIGITAL = 3;
  8407. /**
  8408. * Units information array. Units are grouped into measuring systems
  8409. * (English, Metric), and are assigned an integer representing
  8410. * the conversion factor between that unit and the smallest unit in
  8411. * the system. Numeric indexes are actually magical constants that
  8412. * encode conversion data from one system to the next, with a O(n^2)
  8413. * constraint on memory (this is generally not a problem, since
  8414. * the number of measuring systems is small.)
  8415. */
  8416. protected static $units = array(
  8417. self::ENGLISH => array(
  8418. 'px' => 3, // This is as per CSS 2.1 and Firefox. Your mileage may vary
  8419. 'pt' => 4,
  8420. 'pc' => 48,
  8421. 'in' => 288,
  8422. self::METRIC => array('pt', '0.352777778', 'mm'),
  8423. ),
  8424. self::METRIC => array(
  8425. 'mm' => 1,
  8426. 'cm' => 10,
  8427. self::ENGLISH => array('mm', '2.83464567', 'pt'),
  8428. ),
  8429. );
  8430. /**
  8431. * Minimum bcmath precision for output.
  8432. * @type int
  8433. */
  8434. protected $outputPrecision;
  8435. /**
  8436. * Bcmath precision for internal calculations.
  8437. * @type int
  8438. */
  8439. protected $internalPrecision;
  8440. /**
  8441. * Whether or not BCMath is available.
  8442. * @type bool
  8443. */
  8444. private $bcmath;
  8445. public function __construct($output_precision = 4, $internal_precision = 10, $force_no_bcmath = false)
  8446. {
  8447. $this->outputPrecision = $output_precision;
  8448. $this->internalPrecision = $internal_precision;
  8449. $this->bcmath = !$force_no_bcmath && function_exists('bcmul');
  8450. }
  8451. /**
  8452. * Converts a length object of one unit into another unit.
  8453. * @param HTMLPurifier_Length $length
  8454. * Instance of HTMLPurifier_Length to convert. You must validate()
  8455. * it before passing it here!
  8456. * @param string $to_unit
  8457. * Unit to convert to.
  8458. * @return HTMLPurifier_Length|bool
  8459. * @note
  8460. * About precision: This conversion function pays very special
  8461. * attention to the incoming precision of values and attempts
  8462. * to maintain a number of significant figure. Results are
  8463. * fairly accurate up to nine digits. Some caveats:
  8464. * - If a number is zero-padded as a result of this significant
  8465. * figure tracking, the zeroes will be eliminated.
  8466. * - If a number contains less than four sigfigs ($outputPrecision)
  8467. * and this causes some decimals to be excluded, those
  8468. * decimals will be added on.
  8469. */
  8470. public function convert($length, $to_unit)
  8471. {
  8472. if (!$length->isValid()) {
  8473. return false;
  8474. }
  8475. $n = $length->getN();
  8476. $unit = $length->getUnit();
  8477. if ($n === '0' || $unit === false) {
  8478. return new HTMLPurifier_Length('0', false);
  8479. }
  8480. $state = $dest_state = false;
  8481. foreach (self::$units as $k => $x) {
  8482. if (isset($x[$unit])) {
  8483. $state = $k;
  8484. }
  8485. if (isset($x[$to_unit])) {
  8486. $dest_state = $k;
  8487. }
  8488. }
  8489. if (!$state || !$dest_state) {
  8490. return false;
  8491. }
  8492. // Some calculations about the initial precision of the number;
  8493. // this will be useful when we need to do final rounding.
  8494. $sigfigs = $this->getSigFigs($n);
  8495. if ($sigfigs < $this->outputPrecision) {
  8496. $sigfigs = $this->outputPrecision;
  8497. }
  8498. // BCMath's internal precision deals only with decimals. Use
  8499. // our default if the initial number has no decimals, or increase
  8500. // it by how ever many decimals, thus, the number of guard digits
  8501. // will always be greater than or equal to internalPrecision.
  8502. $log = (int)floor(log(abs($n), 10));
  8503. $cp = ($log < 0) ? $this->internalPrecision - $log : $this->internalPrecision; // internal precision
  8504. for ($i = 0; $i < 2; $i++) {
  8505. // Determine what unit IN THIS SYSTEM we need to convert to
  8506. if ($dest_state === $state) {
  8507. // Simple conversion
  8508. $dest_unit = $to_unit;
  8509. } else {
  8510. // Convert to the smallest unit, pending a system shift
  8511. $dest_unit = self::$units[$state][$dest_state][0];
  8512. }
  8513. // Do the conversion if necessary
  8514. if ($dest_unit !== $unit) {
  8515. $factor = $this->div(self::$units[$state][$unit], self::$units[$state][$dest_unit], $cp);
  8516. $n = $this->mul($n, $factor, $cp);
  8517. $unit = $dest_unit;
  8518. }
  8519. // Output was zero, so bail out early. Shouldn't ever happen.
  8520. if ($n === '') {
  8521. $n = '0';
  8522. $unit = $to_unit;
  8523. break;
  8524. }
  8525. // It was a simple conversion, so bail out
  8526. if ($dest_state === $state) {
  8527. break;
  8528. }
  8529. if ($i !== 0) {
  8530. // Conversion failed! Apparently, the system we forwarded
  8531. // to didn't have this unit. This should never happen!
  8532. return false;
  8533. }
  8534. // Pre-condition: $i == 0
  8535. // Perform conversion to next system of units
  8536. $n = $this->mul($n, self::$units[$state][$dest_state][1], $cp);
  8537. $unit = self::$units[$state][$dest_state][2];
  8538. $state = $dest_state;
  8539. // One more loop around to convert the unit in the new system.
  8540. }
  8541. // Post-condition: $unit == $to_unit
  8542. if ($unit !== $to_unit) {
  8543. return false;
  8544. }
  8545. // Useful for debugging:
  8546. //echo "<pre>n";
  8547. //echo "$n\nsigfigs = $sigfigs\nnew_log = $new_log\nlog = $log\nrp = $rp\n</pre>\n";
  8548. $n = $this->round($n, $sigfigs);
  8549. if (strpos($n, '.') !== false) {
  8550. $n = rtrim($n, '0');
  8551. }
  8552. $n = rtrim($n, '.');
  8553. return new HTMLPurifier_Length($n, $unit);
  8554. }
  8555. /**
  8556. * Returns the number of significant figures in a string number.
  8557. * @param string $n Decimal number
  8558. * @return int number of sigfigs
  8559. */
  8560. public function getSigFigs($n)
  8561. {
  8562. $n = ltrim($n, '0+-');
  8563. $dp = strpos($n, '.'); // decimal position
  8564. if ($dp === false) {
  8565. $sigfigs = strlen(rtrim($n, '0'));
  8566. } else {
  8567. $sigfigs = strlen(ltrim($n, '0.')); // eliminate extra decimal character
  8568. if ($dp !== 0) {
  8569. $sigfigs--;
  8570. }
  8571. }
  8572. return $sigfigs;
  8573. }
  8574. /**
  8575. * Adds two numbers, using arbitrary precision when available.
  8576. * @param string $s1
  8577. * @param string $s2
  8578. * @param int $scale
  8579. * @return string
  8580. */
  8581. private function add($s1, $s2, $scale)
  8582. {
  8583. if ($this->bcmath) {
  8584. return bcadd($s1, $s2, $scale);
  8585. } else {
  8586. return $this->scale((float)$s1 + (float)$s2, $scale);
  8587. }
  8588. }
  8589. /**
  8590. * Multiples two numbers, using arbitrary precision when available.
  8591. * @param string $s1
  8592. * @param string $s2
  8593. * @param int $scale
  8594. * @return string
  8595. */
  8596. private function mul($s1, $s2, $scale)
  8597. {
  8598. if ($this->bcmath) {
  8599. return bcmul($s1, $s2, $scale);
  8600. } else {
  8601. return $this->scale((float)$s1 * (float)$s2, $scale);
  8602. }
  8603. }
  8604. /**
  8605. * Divides two numbers, using arbitrary precision when available.
  8606. * @param string $s1
  8607. * @param string $s2
  8608. * @param int $scale
  8609. * @return string
  8610. */
  8611. private function div($s1, $s2, $scale)
  8612. {
  8613. if ($this->bcmath) {
  8614. return bcdiv($s1, $s2, $scale);
  8615. } else {
  8616. return $this->scale((float)$s1 / (float)$s2, $scale);
  8617. }
  8618. }
  8619. /**
  8620. * Rounds a number according to the number of sigfigs it should have,
  8621. * using arbitrary precision when available.
  8622. * @param float $n
  8623. * @param int $sigfigs
  8624. * @return string
  8625. */
  8626. private function round($n, $sigfigs)
  8627. {
  8628. $new_log = (int)floor(log(abs($n), 10)); // Number of digits left of decimal - 1
  8629. $rp = $sigfigs - $new_log - 1; // Number of decimal places needed
  8630. $neg = $n < 0 ? '-' : ''; // Negative sign
  8631. if ($this->bcmath) {
  8632. if ($rp >= 0) {
  8633. $n = bcadd($n, $neg . '0.' . str_repeat('0', $rp) . '5', $rp + 1);
  8634. $n = bcdiv($n, '1', $rp);
  8635. } else {
  8636. // This algorithm partially depends on the standardized
  8637. // form of numbers that comes out of bcmath.
  8638. $n = bcadd($n, $neg . '5' . str_repeat('0', $new_log - $sigfigs), 0);
  8639. $n = substr($n, 0, $sigfigs + strlen($neg)) . str_repeat('0', $new_log - $sigfigs + 1);
  8640. }
  8641. return $n;
  8642. } else {
  8643. return $this->scale(round($n, $sigfigs - $new_log - 1), $rp + 1);
  8644. }
  8645. }
  8646. /**
  8647. * Scales a float to $scale digits right of decimal point, like BCMath.
  8648. * @param float $r
  8649. * @param int $scale
  8650. * @return string
  8651. */
  8652. private function scale($r, $scale)
  8653. {
  8654. if ($scale < 0) {
  8655. // The f sprintf type doesn't support negative numbers, so we
  8656. // need to cludge things manually. First get the string.
  8657. $r = sprintf('%.0f', (float)$r);
  8658. // Due to floating point precision loss, $r will more than likely
  8659. // look something like 4652999999999.9234. We grab one more digit
  8660. // than we need to precise from $r and then use that to round
  8661. // appropriately.
  8662. $precise = (string)round(substr($r, 0, strlen($r) + $scale), -1);
  8663. // Now we return it, truncating the zero that was rounded off.
  8664. return substr($precise, 0, -1) . str_repeat('0', -$scale + 1);
  8665. }
  8666. return sprintf('%.' . $scale . 'f', (float)$r);
  8667. }
  8668. }
  8669. /**
  8670. * Parses string representations into their corresponding native PHP
  8671. * variable type. The base implementation does a simple type-check.
  8672. */
  8673. class HTMLPurifier_VarParser
  8674. {
  8675. const STRING = 1;
  8676. const ISTRING = 2;
  8677. const TEXT = 3;
  8678. const ITEXT = 4;
  8679. const INT = 5;
  8680. const FLOAT = 6;
  8681. const BOOL = 7;
  8682. const LOOKUP = 8;
  8683. const ALIST = 9;
  8684. const HASH = 10;
  8685. const MIXED = 11;
  8686. /**
  8687. * Lookup table of allowed types. Mainly for backwards compatibility, but
  8688. * also convenient for transforming string type names to the integer constants.
  8689. */
  8690. public static $types = array(
  8691. 'string' => self::STRING,
  8692. 'istring' => self::ISTRING,
  8693. 'text' => self::TEXT,
  8694. 'itext' => self::ITEXT,
  8695. 'int' => self::INT,
  8696. 'float' => self::FLOAT,
  8697. 'bool' => self::BOOL,
  8698. 'lookup' => self::LOOKUP,
  8699. 'list' => self::ALIST,
  8700. 'hash' => self::HASH,
  8701. 'mixed' => self::MIXED
  8702. );
  8703. /**
  8704. * Lookup table of types that are string, and can have aliases or
  8705. * allowed value lists.
  8706. */
  8707. public static $stringTypes = array(
  8708. self::STRING => true,
  8709. self::ISTRING => true,
  8710. self::TEXT => true,
  8711. self::ITEXT => true,
  8712. );
  8713. /**
  8714. * Validate a variable according to type.
  8715. * It may return NULL as a valid type if $allow_null is true.
  8716. *
  8717. * @param mixed $var Variable to validate
  8718. * @param int $type Type of variable, see HTMLPurifier_VarParser->types
  8719. * @param bool $allow_null Whether or not to permit null as a value
  8720. * @return string Validated and type-coerced variable
  8721. * @throws HTMLPurifier_VarParserException
  8722. */
  8723. final public function parse($var, $type, $allow_null = false)
  8724. {
  8725. if (is_string($type)) {
  8726. if (!isset(HTMLPurifier_VarParser::$types[$type])) {
  8727. throw new HTMLPurifier_VarParserException("Invalid type '$type'");
  8728. } else {
  8729. $type = HTMLPurifier_VarParser::$types[$type];
  8730. }
  8731. }
  8732. $var = $this->parseImplementation($var, $type, $allow_null);
  8733. if ($allow_null && $var === null) {
  8734. return null;
  8735. }
  8736. // These are basic checks, to make sure nothing horribly wrong
  8737. // happened in our implementations.
  8738. switch ($type) {
  8739. case (self::STRING):
  8740. case (self::ISTRING):
  8741. case (self::TEXT):
  8742. case (self::ITEXT):
  8743. if (!is_string($var)) {
  8744. break;
  8745. }
  8746. if ($type == self::ISTRING || $type == self::ITEXT) {
  8747. $var = strtolower($var);
  8748. }
  8749. return $var;
  8750. case (self::INT):
  8751. if (!is_int($var)) {
  8752. break;
  8753. }
  8754. return $var;
  8755. case (self::FLOAT):
  8756. if (!is_float($var)) {
  8757. break;
  8758. }
  8759. return $var;
  8760. case (self::BOOL):
  8761. if (!is_bool($var)) {
  8762. break;
  8763. }
  8764. return $var;
  8765. case (self::LOOKUP):
  8766. case (self::ALIST):
  8767. case (self::HASH):
  8768. if (!is_array($var)) {
  8769. break;
  8770. }
  8771. if ($type === self::LOOKUP) {
  8772. foreach ($var as $k) {
  8773. if ($k !== true) {
  8774. $this->error('Lookup table contains value other than true');
  8775. }
  8776. }
  8777. } elseif ($type === self::ALIST) {
  8778. $keys = array_keys($var);
  8779. if (array_keys($keys) !== $keys) {
  8780. $this->error('Indices for list are not uniform');
  8781. }
  8782. }
  8783. return $var;
  8784. case (self::MIXED):
  8785. return $var;
  8786. default:
  8787. $this->errorInconsistent(get_class($this), $type);
  8788. }
  8789. $this->errorGeneric($var, $type);
  8790. }
  8791. /**
  8792. * Actually implements the parsing. Base implementation does not
  8793. * do anything to $var. Subclasses should overload this!
  8794. * @param mixed $var
  8795. * @param int $type
  8796. * @param bool $allow_null
  8797. * @return string
  8798. */
  8799. protected function parseImplementation($var, $type, $allow_null)
  8800. {
  8801. return $var;
  8802. }
  8803. /**
  8804. * Throws an exception.
  8805. * @throws HTMLPurifier_VarParserException
  8806. */
  8807. protected function error($msg)
  8808. {
  8809. throw new HTMLPurifier_VarParserException($msg);
  8810. }
  8811. /**
  8812. * Throws an inconsistency exception.
  8813. * @note This should not ever be called. It would be called if we
  8814. * extend the allowed values of HTMLPurifier_VarParser without
  8815. * updating subclasses.
  8816. * @param string $class
  8817. * @param int $type
  8818. * @throws HTMLPurifier_Exception
  8819. */
  8820. protected function errorInconsistent($class, $type)
  8821. {
  8822. throw new HTMLPurifier_Exception(
  8823. "Inconsistency in $class: " . HTMLPurifier_VarParser::getTypeName($type) .
  8824. " not implemented"
  8825. );
  8826. }
  8827. /**
  8828. * Generic error for if a type didn't work.
  8829. * @param mixed $var
  8830. * @param int $type
  8831. */
  8832. protected function errorGeneric($var, $type)
  8833. {
  8834. $vtype = gettype($var);
  8835. $this->error("Expected type " . HTMLPurifier_VarParser::getTypeName($type) . ", got $vtype");
  8836. }
  8837. /**
  8838. * @param int $type
  8839. * @return string
  8840. */
  8841. public static function getTypeName($type)
  8842. {
  8843. static $lookup;
  8844. if (!$lookup) {
  8845. // Lazy load the alternative lookup table
  8846. $lookup = array_flip(HTMLPurifier_VarParser::$types);
  8847. }
  8848. if (!isset($lookup[$type])) {
  8849. return 'unknown';
  8850. }
  8851. return $lookup[$type];
  8852. }
  8853. }
  8854. /**
  8855. * Exception type for HTMLPurifier_VarParser
  8856. */
  8857. class HTMLPurifier_VarParserException extends HTMLPurifier_Exception
  8858. {
  8859. }
  8860. /**
  8861. * A zipper is a purely-functional data structure which contains
  8862. * a focus that can be efficiently manipulated. It is known as
  8863. * a "one-hole context". This mutable variant implements a zipper
  8864. * for a list as a pair of two arrays, laid out as follows:
  8865. *
  8866. * Base list: 1 2 3 4 [ ] 6 7 8 9
  8867. * Front list: 1 2 3 4
  8868. * Back list: 9 8 7 6
  8869. *
  8870. * User is expected to keep track of the "current element" and properly
  8871. * fill it back in as necessary. (ToDo: Maybe it's more user friendly
  8872. * to implicitly track the current element?)
  8873. *
  8874. * Nota bene: the current class gets confused if you try to store NULLs
  8875. * in the list.
  8876. */
  8877. class HTMLPurifier_Zipper
  8878. {
  8879. public $front, $back;
  8880. public function __construct($front, $back) {
  8881. $this->front = $front;
  8882. $this->back = $back;
  8883. }
  8884. /**
  8885. * Creates a zipper from an array, with a hole in the
  8886. * 0-index position.
  8887. * @param Array to zipper-ify.
  8888. * @return Tuple of zipper and element of first position.
  8889. */
  8890. static public function fromArray($array) {
  8891. $z = new self(array(), array_reverse($array));
  8892. $t = $z->delete(); // delete the "dummy hole"
  8893. return array($z, $t);
  8894. }
  8895. /**
  8896. * Convert zipper back into a normal array, optionally filling in
  8897. * the hole with a value. (Usually you should supply a $t, unless you
  8898. * are at the end of the array.)
  8899. */
  8900. public function toArray($t = NULL) {
  8901. $a = $this->front;
  8902. if ($t !== NULL) $a[] = $t;
  8903. for ($i = count($this->back)-1; $i >= 0; $i--) {
  8904. $a[] = $this->back[$i];
  8905. }
  8906. return $a;
  8907. }
  8908. /**
  8909. * Move hole to the next element.
  8910. * @param $t Element to fill hole with
  8911. * @return Original contents of new hole.
  8912. */
  8913. public function next($t) {
  8914. if ($t !== NULL) array_push($this->front, $t);
  8915. return empty($this->back) ? NULL : array_pop($this->back);
  8916. }
  8917. /**
  8918. * Iterated hole advancement.
  8919. * @param $t Element to fill hole with
  8920. * @param $i How many forward to advance hole
  8921. * @return Original contents of new hole, i away
  8922. */
  8923. public function advance($t, $n) {
  8924. for ($i = 0; $i < $n; $i++) {
  8925. $t = $this->next($t);
  8926. }
  8927. return $t;
  8928. }
  8929. /**
  8930. * Move hole to the previous element
  8931. * @param $t Element to fill hole with
  8932. * @return Original contents of new hole.
  8933. */
  8934. public function prev($t) {
  8935. if ($t !== NULL) array_push($this->back, $t);
  8936. return empty($this->front) ? NULL : array_pop($this->front);
  8937. }
  8938. /**
  8939. * Delete contents of current hole, shifting hole to
  8940. * next element.
  8941. * @return Original contents of new hole.
  8942. */
  8943. public function delete() {
  8944. return empty($this->back) ? NULL : array_pop($this->back);
  8945. }
  8946. /**
  8947. * Returns true if we are at the end of the list.
  8948. * @return bool
  8949. */
  8950. public function done() {
  8951. return empty($this->back);
  8952. }
  8953. /**
  8954. * Insert element before hole.
  8955. * @param Element to insert
  8956. */
  8957. public function insertBefore($t) {
  8958. if ($t !== NULL) array_push($this->front, $t);
  8959. }
  8960. /**
  8961. * Insert element after hole.
  8962. * @param Element to insert
  8963. */
  8964. public function insertAfter($t) {
  8965. if ($t !== NULL) array_push($this->back, $t);
  8966. }
  8967. /**
  8968. * Splice in multiple elements at hole. Functional specification
  8969. * in terms of array_splice:
  8970. *
  8971. * $arr1 = $arr;
  8972. * $old1 = array_splice($arr1, $i, $delete, $replacement);
  8973. *
  8974. * list($z, $t) = HTMLPurifier_Zipper::fromArray($arr);
  8975. * $t = $z->advance($t, $i);
  8976. * list($old2, $t) = $z->splice($t, $delete, $replacement);
  8977. * $arr2 = $z->toArray($t);
  8978. *
  8979. * assert($old1 === $old2);
  8980. * assert($arr1 === $arr2);
  8981. *
  8982. * NB: the absolute index location after this operation is
  8983. * *unchanged!*
  8984. *
  8985. * @param Current contents of hole.
  8986. */
  8987. public function splice($t, $delete, $replacement) {
  8988. // delete
  8989. $old = array();
  8990. $r = $t;
  8991. for ($i = $delete; $i > 0; $i--) {
  8992. $old[] = $r;
  8993. $r = $this->delete();
  8994. }
  8995. // insert
  8996. for ($i = count($replacement)-1; $i >= 0; $i--) {
  8997. $this->insertAfter($r);
  8998. $r = $replacement[$i];
  8999. }
  9000. return array($old, $r);
  9001. }
  9002. }
  9003. /**
  9004. * Validates the HTML attribute style, otherwise known as CSS.
  9005. * @note We don't implement the whole CSS specification, so it might be
  9006. * difficult to reuse this component in the context of validating
  9007. * actual stylesheet declarations.
  9008. * @note If we were really serious about validating the CSS, we would
  9009. * tokenize the styles and then parse the tokens. Obviously, we
  9010. * are not doing that. Doing that could seriously harm performance,
  9011. * but would make these components a lot more viable for a CSS
  9012. * filtering solution.
  9013. */
  9014. class HTMLPurifier_AttrDef_CSS extends HTMLPurifier_AttrDef
  9015. {
  9016. /**
  9017. * @param string $css
  9018. * @param HTMLPurifier_Config $config
  9019. * @param HTMLPurifier_Context $context
  9020. * @return bool|string
  9021. */
  9022. public function validate($css, $config, $context)
  9023. {
  9024. $css = $this->parseCDATA($css);
  9025. $definition = $config->getCSSDefinition();
  9026. $allow_duplicates = $config->get("CSS.AllowDuplicates");
  9027. // we're going to break the spec and explode by semicolons.
  9028. // This is because semicolon rarely appears in escaped form
  9029. // Doing this is generally flaky but fast
  9030. // IT MIGHT APPEAR IN URIs, see HTMLPurifier_AttrDef_CSSURI
  9031. // for details
  9032. $declarations = explode(';', $css);
  9033. $propvalues = array();
  9034. $new_declarations = '';
  9035. /**
  9036. * Name of the current CSS property being validated.
  9037. */
  9038. $property = false;
  9039. $context->register('CurrentCSSProperty', $property);
  9040. foreach ($declarations as $declaration) {
  9041. if (!$declaration) {
  9042. continue;
  9043. }
  9044. if (!strpos($declaration, ':')) {
  9045. continue;
  9046. }
  9047. list($property, $value) = explode(':', $declaration, 2);
  9048. $property = trim($property);
  9049. $value = trim($value);
  9050. $ok = false;
  9051. do {
  9052. if (isset($definition->info[$property])) {
  9053. $ok = true;
  9054. break;
  9055. }
  9056. if (ctype_lower($property)) {
  9057. break;
  9058. }
  9059. $property = strtolower($property);
  9060. if (isset($definition->info[$property])) {
  9061. $ok = true;
  9062. break;
  9063. }
  9064. } while (0);
  9065. if (!$ok) {
  9066. continue;
  9067. }
  9068. // inefficient call, since the validator will do this again
  9069. if (strtolower(trim($value)) !== 'inherit') {
  9070. // inherit works for everything (but only on the base property)
  9071. $result = $definition->info[$property]->validate(
  9072. $value,
  9073. $config,
  9074. $context
  9075. );
  9076. } else {
  9077. $result = 'inherit';
  9078. }
  9079. if ($result === false) {
  9080. continue;
  9081. }
  9082. if ($allow_duplicates) {
  9083. $new_declarations .= "$property:$result;";
  9084. } else {
  9085. $propvalues[$property] = $result;
  9086. }
  9087. }
  9088. $context->destroy('CurrentCSSProperty');
  9089. // procedure does not write the new CSS simultaneously, so it's
  9090. // slightly inefficient, but it's the only way of getting rid of
  9091. // duplicates. Perhaps config to optimize it, but not now.
  9092. foreach ($propvalues as $prop => $value) {
  9093. $new_declarations .= "$prop:$value;";
  9094. }
  9095. return $new_declarations ? $new_declarations : false;
  9096. }
  9097. }
  9098. /**
  9099. * Dummy AttrDef that mimics another AttrDef, BUT it generates clones
  9100. * with make.
  9101. */
  9102. class HTMLPurifier_AttrDef_Clone extends HTMLPurifier_AttrDef
  9103. {
  9104. /**
  9105. * What we're cloning.
  9106. * @type HTMLPurifier_AttrDef
  9107. */
  9108. protected $clone;
  9109. /**
  9110. * @param HTMLPurifier_AttrDef $clone
  9111. */
  9112. public function __construct($clone)
  9113. {
  9114. $this->clone = $clone;
  9115. }
  9116. /**
  9117. * @param string $v
  9118. * @param HTMLPurifier_Config $config
  9119. * @param HTMLPurifier_Context $context
  9120. * @return bool|string
  9121. */
  9122. public function validate($v, $config, $context)
  9123. {
  9124. return $this->clone->validate($v, $config, $context);
  9125. }
  9126. /**
  9127. * @param string $string
  9128. * @return HTMLPurifier_AttrDef
  9129. */
  9130. public function make($string)
  9131. {
  9132. return clone $this->clone;
  9133. }
  9134. }
  9135. // Enum = Enumerated
  9136. /**
  9137. * Validates a keyword against a list of valid values.
  9138. * @warning The case-insensitive compare of this function uses PHP's
  9139. * built-in strtolower and ctype_lower functions, which may
  9140. * cause problems with international comparisons
  9141. */
  9142. class HTMLPurifier_AttrDef_Enum extends HTMLPurifier_AttrDef
  9143. {
  9144. /**
  9145. * Lookup table of valid values.
  9146. * @type array
  9147. * @todo Make protected
  9148. */
  9149. public $valid_values = array();
  9150. /**
  9151. * Bool indicating whether or not enumeration is case sensitive.
  9152. * @note In general this is always case insensitive.
  9153. */
  9154. protected $case_sensitive = false; // values according to W3C spec
  9155. /**
  9156. * @param array $valid_values List of valid values
  9157. * @param bool $case_sensitive Whether or not case sensitive
  9158. */
  9159. public function __construct($valid_values = array(), $case_sensitive = false)
  9160. {
  9161. $this->valid_values = array_flip($valid_values);
  9162. $this->case_sensitive = $case_sensitive;
  9163. }
  9164. /**
  9165. * @param string $string
  9166. * @param HTMLPurifier_Config $config
  9167. * @param HTMLPurifier_Context $context
  9168. * @return bool|string
  9169. */
  9170. public function validate($string, $config, $context)
  9171. {
  9172. $string = trim($string);
  9173. if (!$this->case_sensitive) {
  9174. // we may want to do full case-insensitive libraries
  9175. $string = ctype_lower($string) ? $string : strtolower($string);
  9176. }
  9177. $result = isset($this->valid_values[$string]);
  9178. return $result ? $string : false;
  9179. }
  9180. /**
  9181. * @param string $string In form of comma-delimited list of case-insensitive
  9182. * valid values. Example: "foo,bar,baz". Prepend "s:" to make
  9183. * case sensitive
  9184. * @return HTMLPurifier_AttrDef_Enum
  9185. */
  9186. public function make($string)
  9187. {
  9188. if (strlen($string) > 2 && $string[0] == 's' && $string[1] == ':') {
  9189. $string = substr($string, 2);
  9190. $sensitive = true;
  9191. } else {
  9192. $sensitive = false;
  9193. }
  9194. $values = explode(',', $string);
  9195. return new HTMLPurifier_AttrDef_Enum($values, $sensitive);
  9196. }
  9197. }
  9198. /**
  9199. * Validates an integer.
  9200. * @note While this class was modeled off the CSS definition, no currently
  9201. * allowed CSS uses this type. The properties that do are: widows,
  9202. * orphans, z-index, counter-increment, counter-reset. Some of the
  9203. * HTML attributes, however, find use for a non-negative version of this.
  9204. */
  9205. class HTMLPurifier_AttrDef_Integer extends HTMLPurifier_AttrDef
  9206. {
  9207. /**
  9208. * Whether or not negative values are allowed.
  9209. * @type bool
  9210. */
  9211. protected $negative = true;
  9212. /**
  9213. * Whether or not zero is allowed.
  9214. * @type bool
  9215. */
  9216. protected $zero = true;
  9217. /**
  9218. * Whether or not positive values are allowed.
  9219. * @type bool
  9220. */
  9221. protected $positive = true;
  9222. /**
  9223. * @param $negative Bool indicating whether or not negative values are allowed
  9224. * @param $zero Bool indicating whether or not zero is allowed
  9225. * @param $positive Bool indicating whether or not positive values are allowed
  9226. */
  9227. public function __construct($negative = true, $zero = true, $positive = true)
  9228. {
  9229. $this->negative = $negative;
  9230. $this->zero = $zero;
  9231. $this->positive = $positive;
  9232. }
  9233. /**
  9234. * @param string $integer
  9235. * @param HTMLPurifier_Config $config
  9236. * @param HTMLPurifier_Context $context
  9237. * @return bool|string
  9238. */
  9239. public function validate($integer, $config, $context)
  9240. {
  9241. $integer = $this->parseCDATA($integer);
  9242. if ($integer === '') {
  9243. return false;
  9244. }
  9245. // we could possibly simply typecast it to integer, but there are
  9246. // certain fringe cases that must not return an integer.
  9247. // clip leading sign
  9248. if ($this->negative && $integer[0] === '-') {
  9249. $digits = substr($integer, 1);
  9250. if ($digits === '0') {
  9251. $integer = '0';
  9252. } // rm minus sign for zero
  9253. } elseif ($this->positive && $integer[0] === '+') {
  9254. $digits = $integer = substr($integer, 1); // rm unnecessary plus
  9255. } else {
  9256. $digits = $integer;
  9257. }
  9258. // test if it's numeric
  9259. if (!ctype_digit($digits)) {
  9260. return false;
  9261. }
  9262. // perform scope tests
  9263. if (!$this->zero && $integer == 0) {
  9264. return false;
  9265. }
  9266. if (!$this->positive && $integer > 0) {
  9267. return false;
  9268. }
  9269. if (!$this->negative && $integer < 0) {
  9270. return false;
  9271. }
  9272. return $integer;
  9273. }
  9274. }
  9275. /**
  9276. * Validates the HTML attribute lang, effectively a language code.
  9277. * @note Built according to RFC 3066, which obsoleted RFC 1766
  9278. */
  9279. class HTMLPurifier_AttrDef_Lang extends HTMLPurifier_AttrDef
  9280. {
  9281. /**
  9282. * @param string $string
  9283. * @param HTMLPurifier_Config $config
  9284. * @param HTMLPurifier_Context $context
  9285. * @return bool|string
  9286. */
  9287. public function validate($string, $config, $context)
  9288. {
  9289. $string = trim($string);
  9290. if (!$string) {
  9291. return false;
  9292. }
  9293. $subtags = explode('-', $string);
  9294. $num_subtags = count($subtags);
  9295. if ($num_subtags == 0) { // sanity check
  9296. return false;
  9297. }
  9298. // process primary subtag : $subtags[0]
  9299. $length = strlen($subtags[0]);
  9300. switch ($length) {
  9301. case 0:
  9302. return false;
  9303. case 1:
  9304. if (!($subtags[0] == 'x' || $subtags[0] == 'i')) {
  9305. return false;
  9306. }
  9307. break;
  9308. case 2:
  9309. case 3:
  9310. if (!ctype_alpha($subtags[0])) {
  9311. return false;
  9312. } elseif (!ctype_lower($subtags[0])) {
  9313. $subtags[0] = strtolower($subtags[0]);
  9314. }
  9315. break;
  9316. default:
  9317. return false;
  9318. }
  9319. $new_string = $subtags[0];
  9320. if ($num_subtags == 1) {
  9321. return $new_string;
  9322. }
  9323. // process second subtag : $subtags[1]
  9324. $length = strlen($subtags[1]);
  9325. if ($length == 0 || ($length == 1 && $subtags[1] != 'x') || $length > 8 || !ctype_alnum($subtags[1])) {
  9326. return $new_string;
  9327. }
  9328. if (!ctype_lower($subtags[1])) {
  9329. $subtags[1] = strtolower($subtags[1]);
  9330. }
  9331. $new_string .= '-' . $subtags[1];
  9332. if ($num_subtags == 2) {
  9333. return $new_string;
  9334. }
  9335. // process all other subtags, index 2 and up
  9336. for ($i = 2; $i < $num_subtags; $i++) {
  9337. $length = strlen($subtags[$i]);
  9338. if ($length == 0 || $length > 8 || !ctype_alnum($subtags[$i])) {
  9339. return $new_string;
  9340. }
  9341. if (!ctype_lower($subtags[$i])) {
  9342. $subtags[$i] = strtolower($subtags[$i]);
  9343. }
  9344. $new_string .= '-' . $subtags[$i];
  9345. }
  9346. return $new_string;
  9347. }
  9348. }
  9349. /**
  9350. * Decorator that, depending on a token, switches between two definitions.
  9351. */
  9352. class HTMLPurifier_AttrDef_Switch
  9353. {
  9354. /**
  9355. * @type string
  9356. */
  9357. protected $tag;
  9358. /**
  9359. * @type HTMLPurifier_AttrDef
  9360. */
  9361. protected $withTag;
  9362. /**
  9363. * @type HTMLPurifier_AttrDef
  9364. */
  9365. protected $withoutTag;
  9366. /**
  9367. * @param string $tag Tag name to switch upon
  9368. * @param HTMLPurifier_AttrDef $with_tag Call if token matches tag
  9369. * @param HTMLPurifier_AttrDef $without_tag Call if token doesn't match, or there is no token
  9370. */
  9371. public function __construct($tag, $with_tag, $without_tag)
  9372. {
  9373. $this->tag = $tag;
  9374. $this->withTag = $with_tag;
  9375. $this->withoutTag = $without_tag;
  9376. }
  9377. /**
  9378. * @param string $string
  9379. * @param HTMLPurifier_Config $config
  9380. * @param HTMLPurifier_Context $context
  9381. * @return bool|string
  9382. */
  9383. public function validate($string, $config, $context)
  9384. {
  9385. $token = $context->get('CurrentToken', true);
  9386. if (!$token || $token->name !== $this->tag) {
  9387. return $this->withoutTag->validate($string, $config, $context);
  9388. } else {
  9389. return $this->withTag->validate($string, $config, $context);
  9390. }
  9391. }
  9392. }
  9393. /**
  9394. * Validates arbitrary text according to the HTML spec.
  9395. */
  9396. class HTMLPurifier_AttrDef_Text extends HTMLPurifier_AttrDef
  9397. {
  9398. /**
  9399. * @param string $string
  9400. * @param HTMLPurifier_Config $config
  9401. * @param HTMLPurifier_Context $context
  9402. * @return bool|string
  9403. */
  9404. public function validate($string, $config, $context)
  9405. {
  9406. return $this->parseCDATA($string);
  9407. }
  9408. }
  9409. /**
  9410. * Validates a URI as defined by RFC 3986.
  9411. * @note Scheme-specific mechanics deferred to HTMLPurifier_URIScheme
  9412. */
  9413. class HTMLPurifier_AttrDef_URI extends HTMLPurifier_AttrDef
  9414. {
  9415. /**
  9416. * @type HTMLPurifier_URIParser
  9417. */
  9418. protected $parser;
  9419. /**
  9420. * @type bool
  9421. */
  9422. protected $embedsResource;
  9423. /**
  9424. * @param bool $embeds_resource Does the URI here result in an extra HTTP request?
  9425. */
  9426. public function __construct($embeds_resource = false)
  9427. {
  9428. $this->parser = new HTMLPurifier_URIParser();
  9429. $this->embedsResource = (bool)$embeds_resource;
  9430. }
  9431. /**
  9432. * @param string $string
  9433. * @return HTMLPurifier_AttrDef_URI
  9434. */
  9435. public function make($string)
  9436. {
  9437. $embeds = ($string === 'embedded');
  9438. return new HTMLPurifier_AttrDef_URI($embeds);
  9439. }
  9440. /**
  9441. * @param string $uri
  9442. * @param HTMLPurifier_Config $config
  9443. * @param HTMLPurifier_Context $context
  9444. * @return bool|string
  9445. */
  9446. public function validate($uri, $config, $context)
  9447. {
  9448. if ($config->get('URI.Disable')) {
  9449. return false;
  9450. }
  9451. $uri = $this->parseCDATA($uri);
  9452. // parse the URI
  9453. $uri = $this->parser->parse($uri);
  9454. if ($uri === false) {
  9455. return false;
  9456. }
  9457. // add embedded flag to context for validators
  9458. $context->register('EmbeddedURI', $this->embedsResource);
  9459. $ok = false;
  9460. do {
  9461. // generic validation
  9462. $result = $uri->validate($config, $context);
  9463. if (!$result) {
  9464. break;
  9465. }
  9466. // chained filtering
  9467. $uri_def = $config->getDefinition('URI');
  9468. $result = $uri_def->filter($uri, $config, $context);
  9469. if (!$result) {
  9470. break;
  9471. }
  9472. // scheme-specific validation
  9473. $scheme_obj = $uri->getSchemeObj($config, $context);
  9474. if (!$scheme_obj) {
  9475. break;
  9476. }
  9477. if ($this->embedsResource && !$scheme_obj->browsable) {
  9478. break;
  9479. }
  9480. $result = $scheme_obj->validate($uri, $config, $context);
  9481. if (!$result) {
  9482. break;
  9483. }
  9484. // Post chained filtering
  9485. $result = $uri_def->postFilter($uri, $config, $context);
  9486. if (!$result) {
  9487. break;
  9488. }
  9489. // survived gauntlet
  9490. $ok = true;
  9491. } while (false);
  9492. $context->destroy('EmbeddedURI');
  9493. if (!$ok) {
  9494. return false;
  9495. }
  9496. // back to string
  9497. return $uri->toString();
  9498. }
  9499. }
  9500. /**
  9501. * Validates a number as defined by the CSS spec.
  9502. */
  9503. class HTMLPurifier_AttrDef_CSS_Number extends HTMLPurifier_AttrDef
  9504. {
  9505. /**
  9506. * Indicates whether or not only positive values are allowed.
  9507. * @type bool
  9508. */
  9509. protected $non_negative = false;
  9510. /**
  9511. * @param bool $non_negative indicates whether negatives are forbidden
  9512. */
  9513. public function __construct($non_negative = false)
  9514. {
  9515. $this->non_negative = $non_negative;
  9516. }
  9517. /**
  9518. * @param string $number
  9519. * @param HTMLPurifier_Config $config
  9520. * @param HTMLPurifier_Context $context
  9521. * @return string|bool
  9522. * @warning Some contexts do not pass $config, $context. These
  9523. * variables should not be used without checking HTMLPurifier_Length
  9524. */
  9525. public function validate($number, $config, $context)
  9526. {
  9527. $number = $this->parseCDATA($number);
  9528. if ($number === '') {
  9529. return false;
  9530. }
  9531. if ($number === '0') {
  9532. return '0';
  9533. }
  9534. $sign = '';
  9535. switch ($number[0]) {
  9536. case '-':
  9537. if ($this->non_negative) {
  9538. return false;
  9539. }
  9540. $sign = '-';
  9541. case '+':
  9542. $number = substr($number, 1);
  9543. }
  9544. if (ctype_digit($number)) {
  9545. $number = ltrim($number, '0');
  9546. return $number ? $sign . $number : '0';
  9547. }
  9548. // Period is the only non-numeric character allowed
  9549. if (strpos($number, '.') === false) {
  9550. return false;
  9551. }
  9552. list($left, $right) = explode('.', $number, 2);
  9553. if ($left === '' && $right === '') {
  9554. return false;
  9555. }
  9556. if ($left !== '' && !ctype_digit($left)) {
  9557. return false;
  9558. }
  9559. $left = ltrim($left, '0');
  9560. $right = rtrim($right, '0');
  9561. if ($right === '') {
  9562. return $left ? $sign . $left : '0';
  9563. } elseif (!ctype_digit($right)) {
  9564. return false;
  9565. }
  9566. return $sign . $left . '.' . $right;
  9567. }
  9568. }
  9569. class HTMLPurifier_AttrDef_CSS_AlphaValue extends HTMLPurifier_AttrDef_CSS_Number
  9570. {
  9571. public function __construct()
  9572. {
  9573. parent::__construct(false); // opacity is non-negative, but we will clamp it
  9574. }
  9575. /**
  9576. * @param string $number
  9577. * @param HTMLPurifier_Config $config
  9578. * @param HTMLPurifier_Context $context
  9579. * @return string
  9580. */
  9581. public function validate($number, $config, $context)
  9582. {
  9583. $result = parent::validate($number, $config, $context);
  9584. if ($result === false) {
  9585. return $result;
  9586. }
  9587. $float = (float)$result;
  9588. if ($float < 0.0) {
  9589. $result = '0';
  9590. }
  9591. if ($float > 1.0) {
  9592. $result = '1';
  9593. }
  9594. return $result;
  9595. }
  9596. }
  9597. /**
  9598. * Validates shorthand CSS property background.
  9599. * @warning Does not support url tokens that have internal spaces.
  9600. */
  9601. class HTMLPurifier_AttrDef_CSS_Background extends HTMLPurifier_AttrDef
  9602. {
  9603. /**
  9604. * Local copy of component validators.
  9605. * @type HTMLPurifier_AttrDef[]
  9606. * @note See HTMLPurifier_AttrDef_Font::$info for a similar impl.
  9607. */
  9608. protected $info;
  9609. /**
  9610. * @param HTMLPurifier_Config $config
  9611. */
  9612. public function __construct($config)
  9613. {
  9614. $def = $config->getCSSDefinition();
  9615. $this->info['background-color'] = $def->info['background-color'];
  9616. $this->info['background-image'] = $def->info['background-image'];
  9617. $this->info['background-repeat'] = $def->info['background-repeat'];
  9618. $this->info['background-attachment'] = $def->info['background-attachment'];
  9619. $this->info['background-position'] = $def->info['background-position'];
  9620. }
  9621. /**
  9622. * @param string $string
  9623. * @param HTMLPurifier_Config $config
  9624. * @param HTMLPurifier_Context $context
  9625. * @return bool|string
  9626. */
  9627. public function validate($string, $config, $context)
  9628. {
  9629. // regular pre-processing
  9630. $string = $this->parseCDATA($string);
  9631. if ($string === '') {
  9632. return false;
  9633. }
  9634. // munge rgb() decl if necessary
  9635. $string = $this->mungeRgb($string);
  9636. // assumes URI doesn't have spaces in it
  9637. $bits = explode(' ', $string); // bits to process
  9638. $caught = array();
  9639. $caught['color'] = false;
  9640. $caught['image'] = false;
  9641. $caught['repeat'] = false;
  9642. $caught['attachment'] = false;
  9643. $caught['position'] = false;
  9644. $i = 0; // number of catches
  9645. foreach ($bits as $bit) {
  9646. if ($bit === '') {
  9647. continue;
  9648. }
  9649. foreach ($caught as $key => $status) {
  9650. if ($key != 'position') {
  9651. if ($status !== false) {
  9652. continue;
  9653. }
  9654. $r = $this->info['background-' . $key]->validate($bit, $config, $context);
  9655. } else {
  9656. $r = $bit;
  9657. }
  9658. if ($r === false) {
  9659. continue;
  9660. }
  9661. if ($key == 'position') {
  9662. if ($caught[$key] === false) {
  9663. $caught[$key] = '';
  9664. }
  9665. $caught[$key] .= $r . ' ';
  9666. } else {
  9667. $caught[$key] = $r;
  9668. }
  9669. $i++;
  9670. break;
  9671. }
  9672. }
  9673. if (!$i) {
  9674. return false;
  9675. }
  9676. if ($caught['position'] !== false) {
  9677. $caught['position'] = $this->info['background-position']->
  9678. validate($caught['position'], $config, $context);
  9679. }
  9680. $ret = array();
  9681. foreach ($caught as $value) {
  9682. if ($value === false) {
  9683. continue;
  9684. }
  9685. $ret[] = $value;
  9686. }
  9687. if (empty($ret)) {
  9688. return false;
  9689. }
  9690. return implode(' ', $ret);
  9691. }
  9692. }
  9693. /* W3C says:
  9694. [ // adjective and number must be in correct order, even if
  9695. // you could switch them without introducing ambiguity.
  9696. // some browsers support that syntax
  9697. [
  9698. <percentage> | <length> | left | center | right
  9699. ]
  9700. [
  9701. <percentage> | <length> | top | center | bottom
  9702. ]?
  9703. ] |
  9704. [ // this signifies that the vertical and horizontal adjectives
  9705. // can be arbitrarily ordered, however, there can only be two,
  9706. // one of each, or none at all
  9707. [
  9708. left | center | right
  9709. ] ||
  9710. [
  9711. top | center | bottom
  9712. ]
  9713. ]
  9714. top, left = 0%
  9715. center, (none) = 50%
  9716. bottom, right = 100%
  9717. */
  9718. /* QuirksMode says:
  9719. keyword + length/percentage must be ordered correctly, as per W3C
  9720. Internet Explorer and Opera, however, support arbitrary ordering. We
  9721. should fix it up.
  9722. Minor issue though, not strictly necessary.
  9723. */
  9724. // control freaks may appreciate the ability to convert these to
  9725. // percentages or something, but it's not necessary
  9726. /**
  9727. * Validates the value of background-position.
  9728. */
  9729. class HTMLPurifier_AttrDef_CSS_BackgroundPosition extends HTMLPurifier_AttrDef
  9730. {
  9731. /**
  9732. * @type HTMLPurifier_AttrDef_CSS_Length
  9733. */
  9734. protected $length;
  9735. /**
  9736. * @type HTMLPurifier_AttrDef_CSS_Percentage
  9737. */
  9738. protected $percentage;
  9739. public function __construct()
  9740. {
  9741. $this->length = new HTMLPurifier_AttrDef_CSS_Length();
  9742. $this->percentage = new HTMLPurifier_AttrDef_CSS_Percentage();
  9743. }
  9744. /**
  9745. * @param string $string
  9746. * @param HTMLPurifier_Config $config
  9747. * @param HTMLPurifier_Context $context
  9748. * @return bool|string
  9749. */
  9750. public function validate($string, $config, $context)
  9751. {
  9752. $string = $this->parseCDATA($string);
  9753. $bits = explode(' ', $string);
  9754. $keywords = array();
  9755. $keywords['h'] = false; // left, right
  9756. $keywords['v'] = false; // top, bottom
  9757. $keywords['ch'] = false; // center (first word)
  9758. $keywords['cv'] = false; // center (second word)
  9759. $measures = array();
  9760. $i = 0;
  9761. $lookup = array(
  9762. 'top' => 'v',
  9763. 'bottom' => 'v',
  9764. 'left' => 'h',
  9765. 'right' => 'h',
  9766. 'center' => 'c'
  9767. );
  9768. foreach ($bits as $bit) {
  9769. if ($bit === '') {
  9770. continue;
  9771. }
  9772. // test for keyword
  9773. $lbit = ctype_lower($bit) ? $bit : strtolower($bit);
  9774. if (isset($lookup[$lbit])) {
  9775. $status = $lookup[$lbit];
  9776. if ($status == 'c') {
  9777. if ($i == 0) {
  9778. $status = 'ch';
  9779. } else {
  9780. $status = 'cv';
  9781. }
  9782. }
  9783. $keywords[$status] = $lbit;
  9784. $i++;
  9785. }
  9786. // test for length
  9787. $r = $this->length->validate($bit, $config, $context);
  9788. if ($r !== false) {
  9789. $measures[] = $r;
  9790. $i++;
  9791. }
  9792. // test for percentage
  9793. $r = $this->percentage->validate($bit, $config, $context);
  9794. if ($r !== false) {
  9795. $measures[] = $r;
  9796. $i++;
  9797. }
  9798. }
  9799. if (!$i) {
  9800. return false;
  9801. } // no valid values were caught
  9802. $ret = array();
  9803. // first keyword
  9804. if ($keywords['h']) {
  9805. $ret[] = $keywords['h'];
  9806. } elseif ($keywords['ch']) {
  9807. $ret[] = $keywords['ch'];
  9808. $keywords['cv'] = false; // prevent re-use: center = center center
  9809. } elseif (count($measures)) {
  9810. $ret[] = array_shift($measures);
  9811. }
  9812. if ($keywords['v']) {
  9813. $ret[] = $keywords['v'];
  9814. } elseif ($keywords['cv']) {
  9815. $ret[] = $keywords['cv'];
  9816. } elseif (count($measures)) {
  9817. $ret[] = array_shift($measures);
  9818. }
  9819. if (empty($ret)) {
  9820. return false;
  9821. }
  9822. return implode(' ', $ret);
  9823. }
  9824. }
  9825. /**
  9826. * Validates the border property as defined by CSS.
  9827. */
  9828. class HTMLPurifier_AttrDef_CSS_Border extends HTMLPurifier_AttrDef
  9829. {
  9830. /**
  9831. * Local copy of properties this property is shorthand for.
  9832. * @type HTMLPurifier_AttrDef[]
  9833. */
  9834. protected $info = array();
  9835. /**
  9836. * @param HTMLPurifier_Config $config
  9837. */
  9838. public function __construct($config)
  9839. {
  9840. $def = $config->getCSSDefinition();
  9841. $this->info['border-width'] = $def->info['border-width'];
  9842. $this->info['border-style'] = $def->info['border-style'];
  9843. $this->info['border-top-color'] = $def->info['border-top-color'];
  9844. }
  9845. /**
  9846. * @param string $string
  9847. * @param HTMLPurifier_Config $config
  9848. * @param HTMLPurifier_Context $context
  9849. * @return bool|string
  9850. */
  9851. public function validate($string, $config, $context)
  9852. {
  9853. $string = $this->parseCDATA($string);
  9854. $string = $this->mungeRgb($string);
  9855. $bits = explode(' ', $string);
  9856. $done = array(); // segments we've finished
  9857. $ret = ''; // return value
  9858. foreach ($bits as $bit) {
  9859. foreach ($this->info as $propname => $validator) {
  9860. if (isset($done[$propname])) {
  9861. continue;
  9862. }
  9863. $r = $validator->validate($bit, $config, $context);
  9864. if ($r !== false) {
  9865. $ret .= $r . ' ';
  9866. $done[$propname] = true;
  9867. break;
  9868. }
  9869. }
  9870. }
  9871. return rtrim($ret);
  9872. }
  9873. }
  9874. /**
  9875. * Validates Color as defined by CSS.
  9876. */
  9877. class HTMLPurifier_AttrDef_CSS_Color extends HTMLPurifier_AttrDef
  9878. {
  9879. /**
  9880. * @param string $color
  9881. * @param HTMLPurifier_Config $config
  9882. * @param HTMLPurifier_Context $context
  9883. * @return bool|string
  9884. */
  9885. public function validate($color, $config, $context)
  9886. {
  9887. static $colors = null;
  9888. if ($colors === null) {
  9889. $colors = $config->get('Core.ColorKeywords');
  9890. }
  9891. $color = trim($color);
  9892. if ($color === '') {
  9893. return false;
  9894. }
  9895. $lower = strtolower($color);
  9896. if (isset($colors[$lower])) {
  9897. return $colors[$lower];
  9898. }
  9899. if (strpos($color, 'rgb(') !== false) {
  9900. // rgb literal handling
  9901. $length = strlen($color);
  9902. if (strpos($color, ')') !== $length - 1) {
  9903. return false;
  9904. }
  9905. $triad = substr($color, 4, $length - 4 - 1);
  9906. $parts = explode(',', $triad);
  9907. if (count($parts) !== 3) {
  9908. return false;
  9909. }
  9910. $type = false; // to ensure that they're all the same type
  9911. $new_parts = array();
  9912. foreach ($parts as $part) {
  9913. $part = trim($part);
  9914. if ($part === '') {
  9915. return false;
  9916. }
  9917. $length = strlen($part);
  9918. if ($part[$length - 1] === '%') {
  9919. // handle percents
  9920. if (!$type) {
  9921. $type = 'percentage';
  9922. } elseif ($type !== 'percentage') {
  9923. return false;
  9924. }
  9925. $num = (float)substr($part, 0, $length - 1);
  9926. if ($num < 0) {
  9927. $num = 0;
  9928. }
  9929. if ($num > 100) {
  9930. $num = 100;
  9931. }
  9932. $new_parts[] = "$num%";
  9933. } else {
  9934. // handle integers
  9935. if (!$type) {
  9936. $type = 'integer';
  9937. } elseif ($type !== 'integer') {
  9938. return false;
  9939. }
  9940. $num = (int)$part;
  9941. if ($num < 0) {
  9942. $num = 0;
  9943. }
  9944. if ($num > 255) {
  9945. $num = 255;
  9946. }
  9947. $new_parts[] = (string)$num;
  9948. }
  9949. }
  9950. $new_triad = implode(',', $new_parts);
  9951. $color = "rgb($new_triad)";
  9952. } else {
  9953. // hexadecimal handling
  9954. if ($color[0] === '#') {
  9955. $hex = substr($color, 1);
  9956. } else {
  9957. $hex = $color;
  9958. $color = '#' . $color;
  9959. }
  9960. $length = strlen($hex);
  9961. if ($length !== 3 && $length !== 6) {
  9962. return false;
  9963. }
  9964. if (!ctype_xdigit($hex)) {
  9965. return false;
  9966. }
  9967. }
  9968. return $color;
  9969. }
  9970. }
  9971. /**
  9972. * Allows multiple validators to attempt to validate attribute.
  9973. *
  9974. * Composite is just what it sounds like: a composite of many validators.
  9975. * This means that multiple HTMLPurifier_AttrDef objects will have a whack
  9976. * at the string. If one of them passes, that's what is returned. This is
  9977. * especially useful for CSS values, which often are a choice between
  9978. * an enumerated set of predefined values or a flexible data type.
  9979. */
  9980. class HTMLPurifier_AttrDef_CSS_Composite extends HTMLPurifier_AttrDef
  9981. {
  9982. /**
  9983. * List of objects that may process strings.
  9984. * @type HTMLPurifier_AttrDef[]
  9985. * @todo Make protected
  9986. */
  9987. public $defs;
  9988. /**
  9989. * @param HTMLPurifier_AttrDef[] $defs List of HTMLPurifier_AttrDef objects
  9990. */
  9991. public function __construct($defs)
  9992. {
  9993. $this->defs = $defs;
  9994. }
  9995. /**
  9996. * @param string $string
  9997. * @param HTMLPurifier_Config $config
  9998. * @param HTMLPurifier_Context $context
  9999. * @return bool|string
  10000. */
  10001. public function validate($string, $config, $context)
  10002. {
  10003. foreach ($this->defs as $i => $def) {
  10004. $result = $this->defs[$i]->validate($string, $config, $context);
  10005. if ($result !== false) {
  10006. return $result;
  10007. }
  10008. }
  10009. return false;
  10010. }
  10011. }
  10012. /**
  10013. * Decorator which enables CSS properties to be disabled for specific elements.
  10014. */
  10015. class HTMLPurifier_AttrDef_CSS_DenyElementDecorator extends HTMLPurifier_AttrDef
  10016. {
  10017. /**
  10018. * @type HTMLPurifier_AttrDef
  10019. */
  10020. public $def;
  10021. /**
  10022. * @type string
  10023. */
  10024. public $element;
  10025. /**
  10026. * @param HTMLPurifier_AttrDef $def Definition to wrap
  10027. * @param string $element Element to deny
  10028. */
  10029. public function __construct($def, $element)
  10030. {
  10031. $this->def = $def;
  10032. $this->element = $element;
  10033. }
  10034. /**
  10035. * Checks if CurrentToken is set and equal to $this->element
  10036. * @param string $string
  10037. * @param HTMLPurifier_Config $config
  10038. * @param HTMLPurifier_Context $context
  10039. * @return bool|string
  10040. */
  10041. public function validate($string, $config, $context)
  10042. {
  10043. $token = $context->get('CurrentToken', true);
  10044. if ($token && $token->name == $this->element) {
  10045. return false;
  10046. }
  10047. return $this->def->validate($string, $config, $context);
  10048. }
  10049. }
  10050. /**
  10051. * Microsoft's proprietary filter: CSS property
  10052. * @note Currently supports the alpha filter. In the future, this will
  10053. * probably need an extensible framework
  10054. */
  10055. class HTMLPurifier_AttrDef_CSS_Filter extends HTMLPurifier_AttrDef
  10056. {
  10057. /**
  10058. * @type HTMLPurifier_AttrDef_Integer
  10059. */
  10060. protected $intValidator;
  10061. public function __construct()
  10062. {
  10063. $this->intValidator = new HTMLPurifier_AttrDef_Integer();
  10064. }
  10065. /**
  10066. * @param string $value
  10067. * @param HTMLPurifier_Config $config
  10068. * @param HTMLPurifier_Context $context
  10069. * @return bool|string
  10070. */
  10071. public function validate($value, $config, $context)
  10072. {
  10073. $value = $this->parseCDATA($value);
  10074. if ($value === 'none') {
  10075. return $value;
  10076. }
  10077. // if we looped this we could support multiple filters
  10078. $function_length = strcspn($value, '(');
  10079. $function = trim(substr($value, 0, $function_length));
  10080. if ($function !== 'alpha' &&
  10081. $function !== 'Alpha' &&
  10082. $function !== 'progid:DXImageTransform.Microsoft.Alpha'
  10083. ) {
  10084. return false;
  10085. }
  10086. $cursor = $function_length + 1;
  10087. $parameters_length = strcspn($value, ')', $cursor);
  10088. $parameters = substr($value, $cursor, $parameters_length);
  10089. $params = explode(',', $parameters);
  10090. $ret_params = array();
  10091. $lookup = array();
  10092. foreach ($params as $param) {
  10093. list($key, $value) = explode('=', $param);
  10094. $key = trim($key);
  10095. $value = trim($value);
  10096. if (isset($lookup[$key])) {
  10097. continue;
  10098. }
  10099. if ($key !== 'opacity') {
  10100. continue;
  10101. }
  10102. $value = $this->intValidator->validate($value, $config, $context);
  10103. if ($value === false) {
  10104. continue;
  10105. }
  10106. $int = (int)$value;
  10107. if ($int > 100) {
  10108. $value = '100';
  10109. }
  10110. if ($int < 0) {
  10111. $value = '0';
  10112. }
  10113. $ret_params[] = "$key=$value";
  10114. $lookup[$key] = true;
  10115. }
  10116. $ret_parameters = implode(',', $ret_params);
  10117. $ret_function = "$function($ret_parameters)";
  10118. return $ret_function;
  10119. }
  10120. }
  10121. /**
  10122. * Validates shorthand CSS property font.
  10123. */
  10124. class HTMLPurifier_AttrDef_CSS_Font extends HTMLPurifier_AttrDef
  10125. {
  10126. /**
  10127. * Local copy of validators
  10128. * @type HTMLPurifier_AttrDef[]
  10129. * @note If we moved specific CSS property definitions to their own
  10130. * classes instead of having them be assembled at run time by
  10131. * CSSDefinition, this wouldn't be necessary. We'd instantiate
  10132. * our own copies.
  10133. */
  10134. protected $info = array();
  10135. /**
  10136. * @param HTMLPurifier_Config $config
  10137. */
  10138. public function __construct($config)
  10139. {
  10140. $def = $config->getCSSDefinition();
  10141. $this->info['font-style'] = $def->info['font-style'];
  10142. $this->info['font-variant'] = $def->info['font-variant'];
  10143. $this->info['font-weight'] = $def->info['font-weight'];
  10144. $this->info['font-size'] = $def->info['font-size'];
  10145. $this->info['line-height'] = $def->info['line-height'];
  10146. $this->info['font-family'] = $def->info['font-family'];
  10147. }
  10148. /**
  10149. * @param string $string
  10150. * @param HTMLPurifier_Config $config
  10151. * @param HTMLPurifier_Context $context
  10152. * @return bool|string
  10153. */
  10154. public function validate($string, $config, $context)
  10155. {
  10156. static $system_fonts = array(
  10157. 'caption' => true,
  10158. 'icon' => true,
  10159. 'menu' => true,
  10160. 'message-box' => true,
  10161. 'small-caption' => true,
  10162. 'status-bar' => true
  10163. );
  10164. // regular pre-processing
  10165. $string = $this->parseCDATA($string);
  10166. if ($string === '') {
  10167. return false;
  10168. }
  10169. // check if it's one of the keywords
  10170. $lowercase_string = strtolower($string);
  10171. if (isset($system_fonts[$lowercase_string])) {
  10172. return $lowercase_string;
  10173. }
  10174. $bits = explode(' ', $string); // bits to process
  10175. $stage = 0; // this indicates what we're looking for
  10176. $caught = array(); // which stage 0 properties have we caught?
  10177. $stage_1 = array('font-style', 'font-variant', 'font-weight');
  10178. $final = ''; // output
  10179. for ($i = 0, $size = count($bits); $i < $size; $i++) {
  10180. if ($bits[$i] === '') {
  10181. continue;
  10182. }
  10183. switch ($stage) {
  10184. case 0: // attempting to catch font-style, font-variant or font-weight
  10185. foreach ($stage_1 as $validator_name) {
  10186. if (isset($caught[$validator_name])) {
  10187. continue;
  10188. }
  10189. $r = $this->info[$validator_name]->validate(
  10190. $bits[$i],
  10191. $config,
  10192. $context
  10193. );
  10194. if ($r !== false) {
  10195. $final .= $r . ' ';
  10196. $caught[$validator_name] = true;
  10197. break;
  10198. }
  10199. }
  10200. // all three caught, continue on
  10201. if (count($caught) >= 3) {
  10202. $stage = 1;
  10203. }
  10204. if ($r !== false) {
  10205. break;
  10206. }
  10207. case 1: // attempting to catch font-size and perhaps line-height
  10208. $found_slash = false;
  10209. if (strpos($bits[$i], '/') !== false) {
  10210. list($font_size, $line_height) =
  10211. explode('/', $bits[$i]);
  10212. if ($line_height === '') {
  10213. // ooh, there's a space after the slash!
  10214. $line_height = false;
  10215. $found_slash = true;
  10216. }
  10217. } else {
  10218. $font_size = $bits[$i];
  10219. $line_height = false;
  10220. }
  10221. $r = $this->info['font-size']->validate(
  10222. $font_size,
  10223. $config,
  10224. $context
  10225. );
  10226. if ($r !== false) {
  10227. $final .= $r;
  10228. // attempt to catch line-height
  10229. if ($line_height === false) {
  10230. // we need to scroll forward
  10231. for ($j = $i + 1; $j < $size; $j++) {
  10232. if ($bits[$j] === '') {
  10233. continue;
  10234. }
  10235. if ($bits[$j] === '/') {
  10236. if ($found_slash) {
  10237. return false;
  10238. } else {
  10239. $found_slash = true;
  10240. continue;
  10241. }
  10242. }
  10243. $line_height = $bits[$j];
  10244. break;
  10245. }
  10246. } else {
  10247. // slash already found
  10248. $found_slash = true;
  10249. $j = $i;
  10250. }
  10251. if ($found_slash) {
  10252. $i = $j;
  10253. $r = $this->info['line-height']->validate(
  10254. $line_height,
  10255. $config,
  10256. $context
  10257. );
  10258. if ($r !== false) {
  10259. $final .= '/' . $r;
  10260. }
  10261. }
  10262. $final .= ' ';
  10263. $stage = 2;
  10264. break;
  10265. }
  10266. return false;
  10267. case 2: // attempting to catch font-family
  10268. $font_family =
  10269. implode(' ', array_slice($bits, $i, $size - $i));
  10270. $r = $this->info['font-family']->validate(
  10271. $font_family,
  10272. $config,
  10273. $context
  10274. );
  10275. if ($r !== false) {
  10276. $final .= $r . ' ';
  10277. // processing completed successfully
  10278. return rtrim($final);
  10279. }
  10280. return false;
  10281. }
  10282. }
  10283. return false;
  10284. }
  10285. }
  10286. /**
  10287. * Validates a font family list according to CSS spec
  10288. */
  10289. class HTMLPurifier_AttrDef_CSS_FontFamily extends HTMLPurifier_AttrDef
  10290. {
  10291. protected $mask = null;
  10292. public function __construct()
  10293. {
  10294. $this->mask = '_- ';
  10295. for ($c = 'a'; $c <= 'z'; $c++) {
  10296. $this->mask .= $c;
  10297. }
  10298. for ($c = 'A'; $c <= 'Z'; $c++) {
  10299. $this->mask .= $c;
  10300. }
  10301. for ($c = '0'; $c <= '9'; $c++) {
  10302. $this->mask .= $c;
  10303. } // cast-y, but should be fine
  10304. // special bytes used by UTF-8
  10305. for ($i = 0x80; $i <= 0xFF; $i++) {
  10306. // We don't bother excluding invalid bytes in this range,
  10307. // because the our restriction of well-formed UTF-8 will
  10308. // prevent these from ever occurring.
  10309. $this->mask .= chr($i);
  10310. }
  10311. /*
  10312. PHP's internal strcspn implementation is
  10313. O(length of string * length of mask), making it inefficient
  10314. for large masks. However, it's still faster than
  10315. preg_match 8)
  10316. for (p = s1;;) {
  10317. spanp = s2;
  10318. do {
  10319. if (*spanp == c || p == s1_end) {
  10320. return p - s1;
  10321. }
  10322. } while (spanp++ < (s2_end - 1));
  10323. c = *++p;
  10324. }
  10325. */
  10326. // possible optimization: invert the mask.
  10327. }
  10328. /**
  10329. * @param string $string
  10330. * @param HTMLPurifier_Config $config
  10331. * @param HTMLPurifier_Context $context
  10332. * @return bool|string
  10333. */
  10334. public function validate($string, $config, $context)
  10335. {
  10336. static $generic_names = array(
  10337. 'serif' => true,
  10338. 'sans-serif' => true,
  10339. 'monospace' => true,
  10340. 'fantasy' => true,
  10341. 'cursive' => true
  10342. );
  10343. $allowed_fonts = $config->get('CSS.AllowedFonts');
  10344. // assume that no font names contain commas in them
  10345. $fonts = explode(',', $string);
  10346. $final = '';
  10347. foreach ($fonts as $font) {
  10348. $font = trim($font);
  10349. if ($font === '') {
  10350. continue;
  10351. }
  10352. // match a generic name
  10353. if (isset($generic_names[$font])) {
  10354. if ($allowed_fonts === null || isset($allowed_fonts[$font])) {
  10355. $final .= $font . ', ';
  10356. }
  10357. continue;
  10358. }
  10359. // match a quoted name
  10360. if ($font[0] === '"' || $font[0] === "'") {
  10361. $length = strlen($font);
  10362. if ($length <= 2) {
  10363. continue;
  10364. }
  10365. $quote = $font[0];
  10366. if ($font[$length - 1] !== $quote) {
  10367. continue;
  10368. }
  10369. $font = substr($font, 1, $length - 2);
  10370. }
  10371. $font = $this->expandCSSEscape($font);
  10372. // $font is a pure representation of the font name
  10373. if ($allowed_fonts !== null && !isset($allowed_fonts[$font])) {
  10374. continue;
  10375. }
  10376. if (ctype_alnum($font) && $font !== '') {
  10377. // very simple font, allow it in unharmed
  10378. $final .= $font . ', ';
  10379. continue;
  10380. }
  10381. // bugger out on whitespace. form feed (0C) really
  10382. // shouldn't show up regardless
  10383. $font = str_replace(array("\n", "\t", "\r", "\x0C"), ' ', $font);
  10384. // Here, there are various classes of characters which need
  10385. // to be treated differently:
  10386. // - Alphanumeric characters are essentially safe. We
  10387. // handled these above.
  10388. // - Spaces require quoting, though most parsers will do
  10389. // the right thing if there aren't any characters that
  10390. // can be misinterpreted
  10391. // - Dashes rarely occur, but they fairly unproblematic
  10392. // for parsing/rendering purposes.
  10393. // The above characters cover the majority of Western font
  10394. // names.
  10395. // - Arbitrary Unicode characters not in ASCII. Because
  10396. // most parsers give little thought to Unicode, treatment
  10397. // of these codepoints is basically uniform, even for
  10398. // punctuation-like codepoints. These characters can
  10399. // show up in non-Western pages and are supported by most
  10400. // major browsers, for example: "MS 明朝" is a
  10401. // legitimate font-name
  10402. // <http://ja.wikipedia.org/wiki/MS_明朝>. See
  10403. // the CSS3 spec for more examples:
  10404. // <http://www.w3.org/TR/2011/WD-css3-fonts-20110324/localizedfamilynames.png>
  10405. // You can see live samples of these on the Internet:
  10406. // <http://www.google.co.jp/search?q=font-family+MS+明朝|ゴシック>
  10407. // However, most of these fonts have ASCII equivalents:
  10408. // for example, 'MS Mincho', and it's considered
  10409. // professional to use ASCII font names instead of
  10410. // Unicode font names. Thanks Takeshi Terada for
  10411. // providing this information.
  10412. // The following characters, to my knowledge, have not been
  10413. // used to name font names.
  10414. // - Single quote. While theoretically you might find a
  10415. // font name that has a single quote in its name (serving
  10416. // as an apostrophe, e.g. Dave's Scribble), I haven't
  10417. // been able to find any actual examples of this.
  10418. // Internet Explorer's cssText translation (which I
  10419. // believe is invoked by innerHTML) normalizes any
  10420. // quoting to single quotes, and fails to escape single
  10421. // quotes. (Note that this is not IE's behavior for all
  10422. // CSS properties, just some sort of special casing for
  10423. // font-family). So a single quote *cannot* be used
  10424. // safely in the font-family context if there will be an
  10425. // innerHTML/cssText translation. Note that Firefox 3.x
  10426. // does this too.
  10427. // - Double quote. In IE, these get normalized to
  10428. // single-quotes, no matter what the encoding. (Fun
  10429. // fact, in IE8, the 'content' CSS property gained
  10430. // support, where they special cased to preserve encoded
  10431. // double quotes, but still translate unadorned double
  10432. // quotes into single quotes.) So, because their
  10433. // fixpoint behavior is identical to single quotes, they
  10434. // cannot be allowed either. Firefox 3.x displays
  10435. // single-quote style behavior.
  10436. // - Backslashes are reduced by one (so \\ -> \) every
  10437. // iteration, so they cannot be used safely. This shows
  10438. // up in IE7, IE8 and FF3
  10439. // - Semicolons, commas and backticks are handled properly.
  10440. // - The rest of the ASCII punctuation is handled properly.
  10441. // We haven't checked what browsers do to unadorned
  10442. // versions, but this is not important as long as the
  10443. // browser doesn't /remove/ surrounding quotes (as IE does
  10444. // for HTML).
  10445. //
  10446. // With these results in hand, we conclude that there are
  10447. // various levels of safety:
  10448. // - Paranoid: alphanumeric, spaces and dashes(?)
  10449. // - International: Paranoid + non-ASCII Unicode
  10450. // - Edgy: Everything except quotes, backslashes
  10451. // - NoJS: Standards compliance, e.g. sod IE. Note that
  10452. // with some judicious character escaping (since certain
  10453. // types of escaping doesn't work) this is theoretically
  10454. // OK as long as innerHTML/cssText is not called.
  10455. // We believe that international is a reasonable default
  10456. // (that we will implement now), and once we do more
  10457. // extensive research, we may feel comfortable with dropping
  10458. // it down to edgy.
  10459. // Edgy: alphanumeric, spaces, dashes, underscores and Unicode. Use of
  10460. // str(c)spn assumes that the string was already well formed
  10461. // Unicode (which of course it is).
  10462. if (strspn($font, $this->mask) !== strlen($font)) {
  10463. continue;
  10464. }
  10465. // Historical:
  10466. // In the absence of innerHTML/cssText, these ugly
  10467. // transforms don't pose a security risk (as \\ and \"
  10468. // might--these escapes are not supported by most browsers).
  10469. // We could try to be clever and use single-quote wrapping
  10470. // when there is a double quote present, but I have choosen
  10471. // not to implement that. (NOTE: you can reduce the amount
  10472. // of escapes by one depending on what quoting style you use)
  10473. // $font = str_replace('\\', '\\5C ', $font);
  10474. // $font = str_replace('"', '\\22 ', $font);
  10475. // $font = str_replace("'", '\\27 ', $font);
  10476. // font possibly with spaces, requires quoting
  10477. $final .= "'$font', ";
  10478. }
  10479. $final = rtrim($final, ', ');
  10480. if ($final === '') {
  10481. return false;
  10482. }
  10483. return $final;
  10484. }
  10485. }
  10486. /**
  10487. * Validates based on {ident} CSS grammar production
  10488. */
  10489. class HTMLPurifier_AttrDef_CSS_Ident extends HTMLPurifier_AttrDef
  10490. {
  10491. /**
  10492. * @param string $string
  10493. * @param HTMLPurifier_Config $config
  10494. * @param HTMLPurifier_Context $context
  10495. * @return bool|string
  10496. */
  10497. public function validate($string, $config, $context)
  10498. {
  10499. $string = trim($string);
  10500. // early abort: '' and '0' (strings that convert to false) are invalid
  10501. if (!$string) {
  10502. return false;
  10503. }
  10504. $pattern = '/^(-?[A-Za-z_][A-Za-z_\-0-9]*)$/';
  10505. if (!preg_match($pattern, $string)) {
  10506. return false;
  10507. }
  10508. return $string;
  10509. }
  10510. }
  10511. /**
  10512. * Decorator which enables !important to be used in CSS values.
  10513. */
  10514. class HTMLPurifier_AttrDef_CSS_ImportantDecorator extends HTMLPurifier_AttrDef
  10515. {
  10516. /**
  10517. * @type HTMLPurifier_AttrDef
  10518. */
  10519. public $def;
  10520. /**
  10521. * @type bool
  10522. */
  10523. public $allow;
  10524. /**
  10525. * @param HTMLPurifier_AttrDef $def Definition to wrap
  10526. * @param bool $allow Whether or not to allow !important
  10527. */
  10528. public function __construct($def, $allow = false)
  10529. {
  10530. $this->def = $def;
  10531. $this->allow = $allow;
  10532. }
  10533. /**
  10534. * Intercepts and removes !important if necessary
  10535. * @param string $string
  10536. * @param HTMLPurifier_Config $config
  10537. * @param HTMLPurifier_Context $context
  10538. * @return bool|string
  10539. */
  10540. public function validate($string, $config, $context)
  10541. {
  10542. // test for ! and important tokens
  10543. $string = trim($string);
  10544. $is_important = false;
  10545. // :TODO: optimization: test directly for !important and ! important
  10546. if (strlen($string) >= 9 && substr($string, -9) === 'important') {
  10547. $temp = rtrim(substr($string, 0, -9));
  10548. // use a temp, because we might want to restore important
  10549. if (strlen($temp) >= 1 && substr($temp, -1) === '!') {
  10550. $string = rtrim(substr($temp, 0, -1));
  10551. $is_important = true;
  10552. }
  10553. }
  10554. $string = $this->def->validate($string, $config, $context);
  10555. if ($this->allow && $is_important) {
  10556. $string .= ' !important';
  10557. }
  10558. return $string;
  10559. }
  10560. }
  10561. /**
  10562. * Represents a Length as defined by CSS.
  10563. */
  10564. class HTMLPurifier_AttrDef_CSS_Length extends HTMLPurifier_AttrDef
  10565. {
  10566. /**
  10567. * @type HTMLPurifier_Length|string
  10568. */
  10569. protected $min;
  10570. /**
  10571. * @type HTMLPurifier_Length|string
  10572. */
  10573. protected $max;
  10574. /**
  10575. * @param HTMLPurifier_Length|string $min Minimum length, or null for no bound. String is also acceptable.
  10576. * @param HTMLPurifier_Length|string $max Maximum length, or null for no bound. String is also acceptable.
  10577. */
  10578. public function __construct($min = null, $max = null)
  10579. {
  10580. $this->min = $min !== null ? HTMLPurifier_Length::make($min) : null;
  10581. $this->max = $max !== null ? HTMLPurifier_Length::make($max) : null;
  10582. }
  10583. /**
  10584. * @param string $string
  10585. * @param HTMLPurifier_Config $config
  10586. * @param HTMLPurifier_Context $context
  10587. * @return bool|string
  10588. */
  10589. public function validate($string, $config, $context)
  10590. {
  10591. $string = $this->parseCDATA($string);
  10592. // Optimizations
  10593. if ($string === '') {
  10594. return false;
  10595. }
  10596. if ($string === '0') {
  10597. return '0';
  10598. }
  10599. if (strlen($string) === 1) {
  10600. return false;
  10601. }
  10602. $length = HTMLPurifier_Length::make($string);
  10603. if (!$length->isValid()) {
  10604. return false;
  10605. }
  10606. if ($this->min) {
  10607. $c = $length->compareTo($this->min);
  10608. if ($c === false) {
  10609. return false;
  10610. }
  10611. if ($c < 0) {
  10612. return false;
  10613. }
  10614. }
  10615. if ($this->max) {
  10616. $c = $length->compareTo($this->max);
  10617. if ($c === false) {
  10618. return false;
  10619. }
  10620. if ($c > 0) {
  10621. return false;
  10622. }
  10623. }
  10624. return $length->toString();
  10625. }
  10626. }
  10627. /**
  10628. * Validates shorthand CSS property list-style.
  10629. * @warning Does not support url tokens that have internal spaces.
  10630. */
  10631. class HTMLPurifier_AttrDef_CSS_ListStyle extends HTMLPurifier_AttrDef
  10632. {
  10633. /**
  10634. * Local copy of validators.
  10635. * @type HTMLPurifier_AttrDef[]
  10636. * @note See HTMLPurifier_AttrDef_CSS_Font::$info for a similar impl.
  10637. */
  10638. protected $info;
  10639. /**
  10640. * @param HTMLPurifier_Config $config
  10641. */
  10642. public function __construct($config)
  10643. {
  10644. $def = $config->getCSSDefinition();
  10645. $this->info['list-style-type'] = $def->info['list-style-type'];
  10646. $this->info['list-style-position'] = $def->info['list-style-position'];
  10647. $this->info['list-style-image'] = $def->info['list-style-image'];
  10648. }
  10649. /**
  10650. * @param string $string
  10651. * @param HTMLPurifier_Config $config
  10652. * @param HTMLPurifier_Context $context
  10653. * @return bool|string
  10654. */
  10655. public function validate($string, $config, $context)
  10656. {
  10657. // regular pre-processing
  10658. $string = $this->parseCDATA($string);
  10659. if ($string === '') {
  10660. return false;
  10661. }
  10662. // assumes URI doesn't have spaces in it
  10663. $bits = explode(' ', strtolower($string)); // bits to process
  10664. $caught = array();
  10665. $caught['type'] = false;
  10666. $caught['position'] = false;
  10667. $caught['image'] = false;
  10668. $i = 0; // number of catches
  10669. $none = false;
  10670. foreach ($bits as $bit) {
  10671. if ($i >= 3) {
  10672. return;
  10673. } // optimization bit
  10674. if ($bit === '') {
  10675. continue;
  10676. }
  10677. foreach ($caught as $key => $status) {
  10678. if ($status !== false) {
  10679. continue;
  10680. }
  10681. $r = $this->info['list-style-' . $key]->validate($bit, $config, $context);
  10682. if ($r === false) {
  10683. continue;
  10684. }
  10685. if ($r === 'none') {
  10686. if ($none) {
  10687. continue;
  10688. } else {
  10689. $none = true;
  10690. }
  10691. if ($key == 'image') {
  10692. continue;
  10693. }
  10694. }
  10695. $caught[$key] = $r;
  10696. $i++;
  10697. break;
  10698. }
  10699. }
  10700. if (!$i) {
  10701. return false;
  10702. }
  10703. $ret = array();
  10704. // construct type
  10705. if ($caught['type']) {
  10706. $ret[] = $caught['type'];
  10707. }
  10708. // construct image
  10709. if ($caught['image']) {
  10710. $ret[] = $caught['image'];
  10711. }
  10712. // construct position
  10713. if ($caught['position']) {
  10714. $ret[] = $caught['position'];
  10715. }
  10716. if (empty($ret)) {
  10717. return false;
  10718. }
  10719. return implode(' ', $ret);
  10720. }
  10721. }
  10722. /**
  10723. * Framework class for strings that involve multiple values.
  10724. *
  10725. * Certain CSS properties such as border-width and margin allow multiple
  10726. * lengths to be specified. This class can take a vanilla border-width
  10727. * definition and multiply it, usually into a max of four.
  10728. *
  10729. * @note Even though the CSS specification isn't clear about it, inherit
  10730. * can only be used alone: it will never manifest as part of a multi
  10731. * shorthand declaration. Thus, this class does not allow inherit.
  10732. */
  10733. class HTMLPurifier_AttrDef_CSS_Multiple extends HTMLPurifier_AttrDef
  10734. {
  10735. /**
  10736. * Instance of component definition to defer validation to.
  10737. * @type HTMLPurifier_AttrDef
  10738. * @todo Make protected
  10739. */
  10740. public $single;
  10741. /**
  10742. * Max number of values allowed.
  10743. * @todo Make protected
  10744. */
  10745. public $max;
  10746. /**
  10747. * @param HTMLPurifier_AttrDef $single HTMLPurifier_AttrDef to multiply
  10748. * @param int $max Max number of values allowed (usually four)
  10749. */
  10750. public function __construct($single, $max = 4)
  10751. {
  10752. $this->single = $single;
  10753. $this->max = $max;
  10754. }
  10755. /**
  10756. * @param string $string
  10757. * @param HTMLPurifier_Config $config
  10758. * @param HTMLPurifier_Context $context
  10759. * @return bool|string
  10760. */
  10761. public function validate($string, $config, $context)
  10762. {
  10763. $string = $this->mungeRgb($this->parseCDATA($string));
  10764. if ($string === '') {
  10765. return false;
  10766. }
  10767. $parts = explode(' ', $string); // parseCDATA replaced \r, \t and \n
  10768. $length = count($parts);
  10769. $final = '';
  10770. for ($i = 0, $num = 0; $i < $length && $num < $this->max; $i++) {
  10771. if (ctype_space($parts[$i])) {
  10772. continue;
  10773. }
  10774. $result = $this->single->validate($parts[$i], $config, $context);
  10775. if ($result !== false) {
  10776. $final .= $result . ' ';
  10777. $num++;
  10778. }
  10779. }
  10780. if ($final === '') {
  10781. return false;
  10782. }
  10783. return rtrim($final);
  10784. }
  10785. }
  10786. /**
  10787. * Validates a Percentage as defined by the CSS spec.
  10788. */
  10789. class HTMLPurifier_AttrDef_CSS_Percentage extends HTMLPurifier_AttrDef
  10790. {
  10791. /**
  10792. * Instance to defer number validation to.
  10793. * @type HTMLPurifier_AttrDef_CSS_Number
  10794. */
  10795. protected $number_def;
  10796. /**
  10797. * @param bool $non_negative Whether to forbid negative values
  10798. */
  10799. public function __construct($non_negative = false)
  10800. {
  10801. $this->number_def = new HTMLPurifier_AttrDef_CSS_Number($non_negative);
  10802. }
  10803. /**
  10804. * @param string $string
  10805. * @param HTMLPurifier_Config $config
  10806. * @param HTMLPurifier_Context $context
  10807. * @return bool|string
  10808. */
  10809. public function validate($string, $config, $context)
  10810. {
  10811. $string = $this->parseCDATA($string);
  10812. if ($string === '') {
  10813. return false;
  10814. }
  10815. $length = strlen($string);
  10816. if ($length === 1) {
  10817. return false;
  10818. }
  10819. if ($string[$length - 1] !== '%') {
  10820. return false;
  10821. }
  10822. $number = substr($string, 0, $length - 1);
  10823. $number = $this->number_def->validate($number, $config, $context);
  10824. if ($number === false) {
  10825. return false;
  10826. }
  10827. return "$number%";
  10828. }
  10829. }
  10830. /**
  10831. * Validates the value for the CSS property text-decoration
  10832. * @note This class could be generalized into a version that acts sort of
  10833. * like Enum except you can compound the allowed values.
  10834. */
  10835. class HTMLPurifier_AttrDef_CSS_TextDecoration extends HTMLPurifier_AttrDef
  10836. {
  10837. /**
  10838. * @param string $string
  10839. * @param HTMLPurifier_Config $config
  10840. * @param HTMLPurifier_Context $context
  10841. * @return bool|string
  10842. */
  10843. public function validate($string, $config, $context)
  10844. {
  10845. static $allowed_values = array(
  10846. 'line-through' => true,
  10847. 'overline' => true,
  10848. 'underline' => true,
  10849. );
  10850. $string = strtolower($this->parseCDATA($string));
  10851. if ($string === 'none') {
  10852. return $string;
  10853. }
  10854. $parts = explode(' ', $string);
  10855. $final = '';
  10856. foreach ($parts as $part) {
  10857. if (isset($allowed_values[$part])) {
  10858. $final .= $part . ' ';
  10859. }
  10860. }
  10861. $final = rtrim($final);
  10862. if ($final === '') {
  10863. return false;
  10864. }
  10865. return $final;
  10866. }
  10867. }
  10868. /**
  10869. * Validates a URI in CSS syntax, which uses url('http://example.com')
  10870. * @note While theoretically speaking a URI in a CSS document could
  10871. * be non-embedded, as of CSS2 there is no such usage so we're
  10872. * generalizing it. This may need to be changed in the future.
  10873. * @warning Since HTMLPurifier_AttrDef_CSS blindly uses semicolons as
  10874. * the separator, you cannot put a literal semicolon in
  10875. * in the URI. Try percent encoding it, in that case.
  10876. */
  10877. class HTMLPurifier_AttrDef_CSS_URI extends HTMLPurifier_AttrDef_URI
  10878. {
  10879. public function __construct()
  10880. {
  10881. parent::__construct(true); // always embedded
  10882. }
  10883. /**
  10884. * @param string $uri_string
  10885. * @param HTMLPurifier_Config $config
  10886. * @param HTMLPurifier_Context $context
  10887. * @return bool|string
  10888. */
  10889. public function validate($uri_string, $config, $context)
  10890. {
  10891. // parse the URI out of the string and then pass it onto
  10892. // the parent object
  10893. $uri_string = $this->parseCDATA($uri_string);
  10894. if (strpos($uri_string, 'url(') !== 0) {
  10895. return false;
  10896. }
  10897. $uri_string = substr($uri_string, 4);
  10898. if (strlen($uri_string) == 0) {
  10899. return false;
  10900. }
  10901. $new_length = strlen($uri_string) - 1;
  10902. if ($uri_string[$new_length] != ')') {
  10903. return false;
  10904. }
  10905. $uri = trim(substr($uri_string, 0, $new_length));
  10906. if (!empty($uri) && ($uri[0] == "'" || $uri[0] == '"')) {
  10907. $quote = $uri[0];
  10908. $new_length = strlen($uri) - 1;
  10909. if ($uri[$new_length] !== $quote) {
  10910. return false;
  10911. }
  10912. $uri = substr($uri, 1, $new_length - 1);
  10913. }
  10914. $uri = $this->expandCSSEscape($uri);
  10915. $result = parent::validate($uri, $config, $context);
  10916. if ($result === false) {
  10917. return false;
  10918. }
  10919. // extra sanity check; should have been done by URI
  10920. $result = str_replace(array('"', "\\", "\n", "\x0c", "\r"), "", $result);
  10921. // suspicious characters are ()'; we're going to percent encode
  10922. // them for safety.
  10923. $result = str_replace(array('(', ')', "'"), array('%28', '%29', '%27'), $result);
  10924. // there's an extra bug where ampersands lose their escaping on
  10925. // an innerHTML cycle, so a very unlucky query parameter could
  10926. // then change the meaning of the URL. Unfortunately, there's
  10927. // not much we can do about that...
  10928. return "url(\"$result\")";
  10929. }
  10930. }
  10931. /**
  10932. * Validates a boolean attribute
  10933. */
  10934. class HTMLPurifier_AttrDef_HTML_Bool extends HTMLPurifier_AttrDef
  10935. {
  10936. /**
  10937. * @type bool
  10938. */
  10939. protected $name;
  10940. /**
  10941. * @type bool
  10942. */
  10943. public $minimized = true;
  10944. /**
  10945. * @param bool $name
  10946. */
  10947. public function __construct($name = false)
  10948. {
  10949. $this->name = $name;
  10950. }
  10951. /**
  10952. * @param string $string
  10953. * @param HTMLPurifier_Config $config
  10954. * @param HTMLPurifier_Context $context
  10955. * @return bool|string
  10956. */
  10957. public function validate($string, $config, $context)
  10958. {
  10959. return $this->name;
  10960. }
  10961. /**
  10962. * @param string $string Name of attribute
  10963. * @return HTMLPurifier_AttrDef_HTML_Bool
  10964. */
  10965. public function make($string)
  10966. {
  10967. return new HTMLPurifier_AttrDef_HTML_Bool($string);
  10968. }
  10969. }
  10970. /**
  10971. * Validates contents based on NMTOKENS attribute type.
  10972. */
  10973. class HTMLPurifier_AttrDef_HTML_Nmtokens extends HTMLPurifier_AttrDef
  10974. {
  10975. /**
  10976. * @param string $string
  10977. * @param HTMLPurifier_Config $config
  10978. * @param HTMLPurifier_Context $context
  10979. * @return bool|string
  10980. */
  10981. public function validate($string, $config, $context)
  10982. {
  10983. $string = trim($string);
  10984. // early abort: '' and '0' (strings that convert to false) are invalid
  10985. if (!$string) {
  10986. return false;
  10987. }
  10988. $tokens = $this->split($string, $config, $context);
  10989. $tokens = $this->filter($tokens, $config, $context);
  10990. if (empty($tokens)) {
  10991. return false;
  10992. }
  10993. return implode(' ', $tokens);
  10994. }
  10995. /**
  10996. * Splits a space separated list of tokens into its constituent parts.
  10997. * @param string $string
  10998. * @param HTMLPurifier_Config $config
  10999. * @param HTMLPurifier_Context $context
  11000. * @return array
  11001. */
  11002. protected function split($string, $config, $context)
  11003. {
  11004. // OPTIMIZABLE!
  11005. // do the preg_match, capture all subpatterns for reformulation
  11006. // we don't support U+00A1 and up codepoints or
  11007. // escaping because I don't know how to do that with regexps
  11008. // and plus it would complicate optimization efforts (you never
  11009. // see that anyway).
  11010. $pattern = '/(?:(?<=\s)|\A)' . // look behind for space or string start
  11011. '((?:--|-?[A-Za-z_])[A-Za-z_\-0-9]*)' .
  11012. '(?:(?=\s)|\z)/'; // look ahead for space or string end
  11013. preg_match_all($pattern, $string, $matches);
  11014. return $matches[1];
  11015. }
  11016. /**
  11017. * Template method for removing certain tokens based on arbitrary criteria.
  11018. * @note If we wanted to be really functional, we'd do an array_filter
  11019. * with a callback. But... we're not.
  11020. * @param array $tokens
  11021. * @param HTMLPurifier_Config $config
  11022. * @param HTMLPurifier_Context $context
  11023. * @return array
  11024. */
  11025. protected function filter($tokens, $config, $context)
  11026. {
  11027. return $tokens;
  11028. }
  11029. }
  11030. /**
  11031. * Implements special behavior for class attribute (normally NMTOKENS)
  11032. */
  11033. class HTMLPurifier_AttrDef_HTML_Class extends HTMLPurifier_AttrDef_HTML_Nmtokens
  11034. {
  11035. /**
  11036. * @param string $string
  11037. * @param HTMLPurifier_Config $config
  11038. * @param HTMLPurifier_Context $context
  11039. * @return bool|string
  11040. */
  11041. protected function split($string, $config, $context)
  11042. {
  11043. // really, this twiddle should be lazy loaded
  11044. $name = $config->getDefinition('HTML')->doctype->name;
  11045. if ($name == "XHTML 1.1" || $name == "XHTML 2.0") {
  11046. return parent::split($string, $config, $context);
  11047. } else {
  11048. return preg_split('/\s+/', $string);
  11049. }
  11050. }
  11051. /**
  11052. * @param array $tokens
  11053. * @param HTMLPurifier_Config $config
  11054. * @param HTMLPurifier_Context $context
  11055. * @return array
  11056. */
  11057. protected function filter($tokens, $config, $context)
  11058. {
  11059. $allowed = $config->get('Attr.AllowedClasses');
  11060. $forbidden = $config->get('Attr.ForbiddenClasses');
  11061. $ret = array();
  11062. foreach ($tokens as $token) {
  11063. if (($allowed === null || isset($allowed[$token])) &&
  11064. !isset($forbidden[$token]) &&
  11065. // We need this O(n) check because of PHP's array
  11066. // implementation that casts -0 to 0.
  11067. !in_array($token, $ret, true)
  11068. ) {
  11069. $ret[] = $token;
  11070. }
  11071. }
  11072. return $ret;
  11073. }
  11074. }
  11075. /**
  11076. * Validates a color according to the HTML spec.
  11077. */
  11078. class HTMLPurifier_AttrDef_HTML_Color extends HTMLPurifier_AttrDef
  11079. {
  11080. /**
  11081. * @param string $string
  11082. * @param HTMLPurifier_Config $config
  11083. * @param HTMLPurifier_Context $context
  11084. * @return bool|string
  11085. */
  11086. public function validate($string, $config, $context)
  11087. {
  11088. static $colors = null;
  11089. if ($colors === null) {
  11090. $colors = $config->get('Core.ColorKeywords');
  11091. }
  11092. $string = trim($string);
  11093. if (empty($string)) {
  11094. return false;
  11095. }
  11096. $lower = strtolower($string);
  11097. if (isset($colors[$lower])) {
  11098. return $colors[$lower];
  11099. }
  11100. if ($string[0] === '#') {
  11101. $hex = substr($string, 1);
  11102. } else {
  11103. $hex = $string;
  11104. }
  11105. $length = strlen($hex);
  11106. if ($length !== 3 && $length !== 6) {
  11107. return false;
  11108. }
  11109. if (!ctype_xdigit($hex)) {
  11110. return false;
  11111. }
  11112. if ($length === 3) {
  11113. $hex = $hex[0] . $hex[0] . $hex[1] . $hex[1] . $hex[2] . $hex[2];
  11114. }
  11115. return "#$hex";
  11116. }
  11117. }
  11118. /**
  11119. * Special-case enum attribute definition that lazy loads allowed frame targets
  11120. */
  11121. class HTMLPurifier_AttrDef_HTML_FrameTarget extends HTMLPurifier_AttrDef_Enum
  11122. {
  11123. /**
  11124. * @type array
  11125. */
  11126. public $valid_values = false; // uninitialized value
  11127. /**
  11128. * @type bool
  11129. */
  11130. protected $case_sensitive = false;
  11131. public function __construct()
  11132. {
  11133. }
  11134. /**
  11135. * @param string $string
  11136. * @param HTMLPurifier_Config $config
  11137. * @param HTMLPurifier_Context $context
  11138. * @return bool|string
  11139. */
  11140. public function validate($string, $config, $context)
  11141. {
  11142. if ($this->valid_values === false) {
  11143. $this->valid_values = $config->get('Attr.AllowedFrameTargets');
  11144. }
  11145. return parent::validate($string, $config, $context);
  11146. }
  11147. }
  11148. /**
  11149. * Validates the HTML attribute ID.
  11150. * @warning Even though this is the id processor, it
  11151. * will ignore the directive Attr:IDBlacklist, since it will only
  11152. * go according to the ID accumulator. Since the accumulator is
  11153. * automatically generated, it will have already absorbed the
  11154. * blacklist. If you're hacking around, make sure you use load()!
  11155. */
  11156. class HTMLPurifier_AttrDef_HTML_ID extends HTMLPurifier_AttrDef
  11157. {
  11158. // selector is NOT a valid thing to use for IDREFs, because IDREFs
  11159. // *must* target IDs that exist, whereas selector #ids do not.
  11160. /**
  11161. * Determines whether or not we're validating an ID in a CSS
  11162. * selector context.
  11163. * @type bool
  11164. */
  11165. protected $selector;
  11166. /**
  11167. * @param bool $selector
  11168. */
  11169. public function __construct($selector = false)
  11170. {
  11171. $this->selector = $selector;
  11172. }
  11173. /**
  11174. * @param string $id
  11175. * @param HTMLPurifier_Config $config
  11176. * @param HTMLPurifier_Context $context
  11177. * @return bool|string
  11178. */
  11179. public function validate($id, $config, $context)
  11180. {
  11181. if (!$this->selector && !$config->get('Attr.EnableID')) {
  11182. return false;
  11183. }
  11184. $id = trim($id); // trim it first
  11185. if ($id === '') {
  11186. return false;
  11187. }
  11188. $prefix = $config->get('Attr.IDPrefix');
  11189. if ($prefix !== '') {
  11190. $prefix .= $config->get('Attr.IDPrefixLocal');
  11191. // prevent re-appending the prefix
  11192. if (strpos($id, $prefix) !== 0) {
  11193. $id = $prefix . $id;
  11194. }
  11195. } elseif ($config->get('Attr.IDPrefixLocal') !== '') {
  11196. trigger_error(
  11197. '%Attr.IDPrefixLocal cannot be used unless ' .
  11198. '%Attr.IDPrefix is set',
  11199. E_USER_WARNING
  11200. );
  11201. }
  11202. if (!$this->selector) {
  11203. $id_accumulator =& $context->get('IDAccumulator');
  11204. if (isset($id_accumulator->ids[$id])) {
  11205. return false;
  11206. }
  11207. }
  11208. // we purposely avoid using regex, hopefully this is faster
  11209. if ($config->get('Attr.ID.HTML5') === true) {
  11210. if (preg_match('/[\t\n\x0b\x0c ]/', $id)) {
  11211. return false;
  11212. }
  11213. } else {
  11214. if (ctype_alpha($id)) {
  11215. // OK
  11216. } else {
  11217. if (!ctype_alpha(@$id[0])) {
  11218. return false;
  11219. }
  11220. // primitive style of regexps, I suppose
  11221. $trim = trim(
  11222. $id,
  11223. 'A..Za..z0..9:-._'
  11224. );
  11225. if ($trim !== '') {
  11226. return false;
  11227. }
  11228. }
  11229. }
  11230. $regexp = $config->get('Attr.IDBlacklistRegexp');
  11231. if ($regexp && preg_match($regexp, $id)) {
  11232. return false;
  11233. }
  11234. if (!$this->selector) {
  11235. $id_accumulator->add($id);
  11236. }
  11237. // if no change was made to the ID, return the result
  11238. // else, return the new id if stripping whitespace made it
  11239. // valid, or return false.
  11240. return $id;
  11241. }
  11242. }
  11243. /**
  11244. * Validates an integer representation of pixels according to the HTML spec.
  11245. */
  11246. class HTMLPurifier_AttrDef_HTML_Pixels extends HTMLPurifier_AttrDef
  11247. {
  11248. /**
  11249. * @type int
  11250. */
  11251. protected $max;
  11252. /**
  11253. * @param int $max
  11254. */
  11255. public function __construct($max = null)
  11256. {
  11257. $this->max = $max;
  11258. }
  11259. /**
  11260. * @param string $string
  11261. * @param HTMLPurifier_Config $config
  11262. * @param HTMLPurifier_Context $context
  11263. * @return bool|string
  11264. */
  11265. public function validate($string, $config, $context)
  11266. {
  11267. $string = trim($string);
  11268. if ($string === '0') {
  11269. return $string;
  11270. }
  11271. if ($string === '') {
  11272. return false;
  11273. }
  11274. $length = strlen($string);
  11275. if (substr($string, $length - 2) == 'px') {
  11276. $string = substr($string, 0, $length - 2);
  11277. }
  11278. if (!is_numeric($string)) {
  11279. return false;
  11280. }
  11281. $int = (int)$string;
  11282. if ($int < 0) {
  11283. return '0';
  11284. }
  11285. // upper-bound value, extremely high values can
  11286. // crash operating systems, see <http://ha.ckers.org/imagecrash.html>
  11287. // WARNING, above link WILL crash you if you're using Windows
  11288. if ($this->max !== null && $int > $this->max) {
  11289. return (string)$this->max;
  11290. }
  11291. return (string)$int;
  11292. }
  11293. /**
  11294. * @param string $string
  11295. * @return HTMLPurifier_AttrDef
  11296. */
  11297. public function make($string)
  11298. {
  11299. if ($string === '') {
  11300. $max = null;
  11301. } else {
  11302. $max = (int)$string;
  11303. }
  11304. $class = get_class($this);
  11305. return new $class($max);
  11306. }
  11307. }
  11308. /**
  11309. * Validates the HTML type length (not to be confused with CSS's length).
  11310. *
  11311. * This accepts integer pixels or percentages as lengths for certain
  11312. * HTML attributes.
  11313. */
  11314. class HTMLPurifier_AttrDef_HTML_Length extends HTMLPurifier_AttrDef_HTML_Pixels
  11315. {
  11316. /**
  11317. * @param string $string
  11318. * @param HTMLPurifier_Config $config
  11319. * @param HTMLPurifier_Context $context
  11320. * @return bool|string
  11321. */
  11322. public function validate($string, $config, $context)
  11323. {
  11324. $string = trim($string);
  11325. if ($string === '') {
  11326. return false;
  11327. }
  11328. $parent_result = parent::validate($string, $config, $context);
  11329. if ($parent_result !== false) {
  11330. return $parent_result;
  11331. }
  11332. $length = strlen($string);
  11333. $last_char = $string[$length - 1];
  11334. if ($last_char !== '%') {
  11335. return false;
  11336. }
  11337. $points = substr($string, 0, $length - 1);
  11338. if (!is_numeric($points)) {
  11339. return false;
  11340. }
  11341. $points = (int)$points;
  11342. if ($points < 0) {
  11343. return '0%';
  11344. }
  11345. if ($points > 100) {
  11346. return '100%';
  11347. }
  11348. return ((string)$points) . '%';
  11349. }
  11350. }
  11351. /**
  11352. * Validates a rel/rev link attribute against a directive of allowed values
  11353. * @note We cannot use Enum because link types allow multiple
  11354. * values.
  11355. * @note Assumes link types are ASCII text
  11356. */
  11357. class HTMLPurifier_AttrDef_HTML_LinkTypes extends HTMLPurifier_AttrDef
  11358. {
  11359. /**
  11360. * Name config attribute to pull.
  11361. * @type string
  11362. */
  11363. protected $name;
  11364. /**
  11365. * @param string $name
  11366. */
  11367. public function __construct($name)
  11368. {
  11369. $configLookup = array(
  11370. 'rel' => 'AllowedRel',
  11371. 'rev' => 'AllowedRev'
  11372. );
  11373. if (!isset($configLookup[$name])) {
  11374. trigger_error(
  11375. 'Unrecognized attribute name for link ' .
  11376. 'relationship.',
  11377. E_USER_ERROR
  11378. );
  11379. return;
  11380. }
  11381. $this->name = $configLookup[$name];
  11382. }
  11383. /**
  11384. * @param string $string
  11385. * @param HTMLPurifier_Config $config
  11386. * @param HTMLPurifier_Context $context
  11387. * @return bool|string
  11388. */
  11389. public function validate($string, $config, $context)
  11390. {
  11391. $allowed = $config->get('Attr.' . $this->name);
  11392. if (empty($allowed)) {
  11393. return false;
  11394. }
  11395. $string = $this->parseCDATA($string);
  11396. $parts = explode(' ', $string);
  11397. // lookup to prevent duplicates
  11398. $ret_lookup = array();
  11399. foreach ($parts as $part) {
  11400. $part = strtolower(trim($part));
  11401. if (!isset($allowed[$part])) {
  11402. continue;
  11403. }
  11404. $ret_lookup[$part] = true;
  11405. }
  11406. if (empty($ret_lookup)) {
  11407. return false;
  11408. }
  11409. $string = implode(' ', array_keys($ret_lookup));
  11410. return $string;
  11411. }
  11412. }
  11413. /**
  11414. * Validates a MultiLength as defined by the HTML spec.
  11415. *
  11416. * A multilength is either a integer (pixel count), a percentage, or
  11417. * a relative number.
  11418. */
  11419. class HTMLPurifier_AttrDef_HTML_MultiLength extends HTMLPurifier_AttrDef_HTML_Length
  11420. {
  11421. /**
  11422. * @param string $string
  11423. * @param HTMLPurifier_Config $config
  11424. * @param HTMLPurifier_Context $context
  11425. * @return bool|string
  11426. */
  11427. public function validate($string, $config, $context)
  11428. {
  11429. $string = trim($string);
  11430. if ($string === '') {
  11431. return false;
  11432. }
  11433. $parent_result = parent::validate($string, $config, $context);
  11434. if ($parent_result !== false) {
  11435. return $parent_result;
  11436. }
  11437. $length = strlen($string);
  11438. $last_char = $string[$length - 1];
  11439. if ($last_char !== '*') {
  11440. return false;
  11441. }
  11442. $int = substr($string, 0, $length - 1);
  11443. if ($int == '') {
  11444. return '*';
  11445. }
  11446. if (!is_numeric($int)) {
  11447. return false;
  11448. }
  11449. $int = (int)$int;
  11450. if ($int < 0) {
  11451. return false;
  11452. }
  11453. if ($int == 0) {
  11454. return '0';
  11455. }
  11456. if ($int == 1) {
  11457. return '*';
  11458. }
  11459. return ((string)$int) . '*';
  11460. }
  11461. }
  11462. abstract class HTMLPurifier_AttrDef_URI_Email extends HTMLPurifier_AttrDef
  11463. {
  11464. /**
  11465. * Unpacks a mailbox into its display-name and address
  11466. * @param string $string
  11467. * @return mixed
  11468. */
  11469. public function unpack($string)
  11470. {
  11471. // needs to be implemented
  11472. }
  11473. }
  11474. // sub-implementations
  11475. /**
  11476. * Validates a host according to the IPv4, IPv6 and DNS (future) specifications.
  11477. */
  11478. class HTMLPurifier_AttrDef_URI_Host extends HTMLPurifier_AttrDef
  11479. {
  11480. /**
  11481. * IPv4 sub-validator.
  11482. * @type HTMLPurifier_AttrDef_URI_IPv4
  11483. */
  11484. protected $ipv4;
  11485. /**
  11486. * IPv6 sub-validator.
  11487. * @type HTMLPurifier_AttrDef_URI_IPv6
  11488. */
  11489. protected $ipv6;
  11490. public function __construct()
  11491. {
  11492. $this->ipv4 = new HTMLPurifier_AttrDef_URI_IPv4();
  11493. $this->ipv6 = new HTMLPurifier_AttrDef_URI_IPv6();
  11494. }
  11495. /**
  11496. * @param string $string
  11497. * @param HTMLPurifier_Config $config
  11498. * @param HTMLPurifier_Context $context
  11499. * @return bool|string
  11500. */
  11501. public function validate($string, $config, $context)
  11502. {
  11503. $length = strlen($string);
  11504. // empty hostname is OK; it's usually semantically equivalent:
  11505. // the default host as defined by a URI scheme is used:
  11506. //
  11507. // If the URI scheme defines a default for host, then that
  11508. // default applies when the host subcomponent is undefined
  11509. // or when the registered name is empty (zero length).
  11510. if ($string === '') {
  11511. return '';
  11512. }
  11513. if ($length > 1 && $string[0] === '[' && $string[$length - 1] === ']') {
  11514. //IPv6
  11515. $ip = substr($string, 1, $length - 2);
  11516. $valid = $this->ipv6->validate($ip, $config, $context);
  11517. if ($valid === false) {
  11518. return false;
  11519. }
  11520. return '[' . $valid . ']';
  11521. }
  11522. // need to do checks on unusual encodings too
  11523. $ipv4 = $this->ipv4->validate($string, $config, $context);
  11524. if ($ipv4 !== false) {
  11525. return $ipv4;
  11526. }
  11527. // A regular domain name.
  11528. // This doesn't match I18N domain names, but we don't have proper IRI support,
  11529. // so force users to insert Punycode.
  11530. // There is not a good sense in which underscores should be
  11531. // allowed, since it's technically not! (And if you go as
  11532. // far to allow everything as specified by the DNS spec...
  11533. // well, that's literally everything, modulo some space limits
  11534. // for the components and the overall name (which, by the way,
  11535. // we are NOT checking!). So we (arbitrarily) decide this:
  11536. // let's allow underscores wherever we would have allowed
  11537. // hyphens, if they are enabled. This is a pretty good match
  11538. // for browser behavior, for example, a large number of browsers
  11539. // cannot handle foo_.example.com, but foo_bar.example.com is
  11540. // fairly well supported.
  11541. $underscore = $config->get('Core.AllowHostnameUnderscore') ? '_' : '';
  11542. // Based off of RFC 1738, but amended so that
  11543. // as per RFC 3696, the top label need only not be all numeric.
  11544. // The productions describing this are:
  11545. $a = '[a-z]'; // alpha
  11546. $an = '[a-z0-9]'; // alphanum
  11547. $and = "[a-z0-9-$underscore]"; // alphanum | "-"
  11548. // domainlabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  11549. $domainlabel = "$an(?:$and*$an)?";
  11550. // AMENDED as per RFC 3696
  11551. // toplabel = alphanum | alphanum *( alphanum | "-" ) alphanum
  11552. // side condition: not all numeric
  11553. $toplabel = "$an(?:$and*$an)?";
  11554. // hostname = *( domainlabel "." ) toplabel [ "." ]
  11555. if (preg_match("/^(?:$domainlabel\.)*($toplabel)\.?$/i", $string, $matches)) {
  11556. if (!ctype_digit($matches[1])) {
  11557. return $string;
  11558. }
  11559. }
  11560. // PHP 5.3 and later support this functionality natively
  11561. if (function_exists('idn_to_ascii')) {
  11562. return idn_to_ascii($string);
  11563. // If we have Net_IDNA2 support, we can support IRIs by
  11564. // punycoding them. (This is the most portable thing to do,
  11565. // since otherwise we have to assume browsers support
  11566. } elseif ($config->get('Core.EnableIDNA')) {
  11567. $idna = new Net_IDNA2(array('encoding' => 'utf8', 'overlong' => false, 'strict' => true));
  11568. // we need to encode each period separately
  11569. $parts = explode('.', $string);
  11570. try {
  11571. $new_parts = array();
  11572. foreach ($parts as $part) {
  11573. $encodable = false;
  11574. for ($i = 0, $c = strlen($part); $i < $c; $i++) {
  11575. if (ord($part[$i]) > 0x7a) {
  11576. $encodable = true;
  11577. break;
  11578. }
  11579. }
  11580. if (!$encodable) {
  11581. $new_parts[] = $part;
  11582. } else {
  11583. $new_parts[] = $idna->encode($part);
  11584. }
  11585. }
  11586. $string = implode('.', $new_parts);
  11587. if (preg_match("/^($domainlabel\.)*$toplabel\.?$/i", $string)) {
  11588. return $string;
  11589. }
  11590. } catch (Exception $e) {
  11591. // XXX error reporting
  11592. }
  11593. }
  11594. return false;
  11595. }
  11596. }
  11597. /**
  11598. * Validates an IPv4 address
  11599. * @author Feyd @ forums.devnetwork.net (public domain)
  11600. */
  11601. class HTMLPurifier_AttrDef_URI_IPv4 extends HTMLPurifier_AttrDef
  11602. {
  11603. /**
  11604. * IPv4 regex, protected so that IPv6 can reuse it.
  11605. * @type string
  11606. */
  11607. protected $ip4;
  11608. /**
  11609. * @param string $aIP
  11610. * @param HTMLPurifier_Config $config
  11611. * @param HTMLPurifier_Context $context
  11612. * @return bool|string
  11613. */
  11614. public function validate($aIP, $config, $context)
  11615. {
  11616. if (!$this->ip4) {
  11617. $this->_loadRegex();
  11618. }
  11619. if (preg_match('#^' . $this->ip4 . '$#s', $aIP)) {
  11620. return $aIP;
  11621. }
  11622. return false;
  11623. }
  11624. /**
  11625. * Lazy load function to prevent regex from being stuffed in
  11626. * cache.
  11627. */
  11628. protected function _loadRegex()
  11629. {
  11630. $oct = '(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])'; // 0-255
  11631. $this->ip4 = "(?:{$oct}\\.{$oct}\\.{$oct}\\.{$oct})";
  11632. }
  11633. }
  11634. /**
  11635. * Validates an IPv6 address.
  11636. * @author Feyd @ forums.devnetwork.net (public domain)
  11637. * @note This function requires brackets to have been removed from address
  11638. * in URI.
  11639. */
  11640. class HTMLPurifier_AttrDef_URI_IPv6 extends HTMLPurifier_AttrDef_URI_IPv4
  11641. {
  11642. /**
  11643. * @param string $aIP
  11644. * @param HTMLPurifier_Config $config
  11645. * @param HTMLPurifier_Context $context
  11646. * @return bool|string
  11647. */
  11648. public function validate($aIP, $config, $context)
  11649. {
  11650. if (!$this->ip4) {
  11651. $this->_loadRegex();
  11652. }
  11653. $original = $aIP;
  11654. $hex = '[0-9a-fA-F]';
  11655. $blk = '(?:' . $hex . '{1,4})';
  11656. $pre = '(?:/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))'; // /0 - /128
  11657. // prefix check
  11658. if (strpos($aIP, '/') !== false) {
  11659. if (preg_match('#' . $pre . '$#s', $aIP, $find)) {
  11660. $aIP = substr($aIP, 0, 0 - strlen($find[0]));
  11661. unset($find);
  11662. } else {
  11663. return false;
  11664. }
  11665. }
  11666. // IPv4-compatiblity check
  11667. if (preg_match('#(?<=:' . ')' . $this->ip4 . '$#s', $aIP, $find)) {
  11668. $aIP = substr($aIP, 0, 0 - strlen($find[0]));
  11669. $ip = explode('.', $find[0]);
  11670. $ip = array_map('dechex', $ip);
  11671. $aIP .= $ip[0] . $ip[1] . ':' . $ip[2] . $ip[3];
  11672. unset($find, $ip);
  11673. }
  11674. // compression check
  11675. $aIP = explode('::', $aIP);
  11676. $c = count($aIP);
  11677. if ($c > 2) {
  11678. return false;
  11679. } elseif ($c == 2) {
  11680. list($first, $second) = $aIP;
  11681. $first = explode(':', $first);
  11682. $second = explode(':', $second);
  11683. if (count($first) + count($second) > 8) {
  11684. return false;
  11685. }
  11686. while (count($first) < 8) {
  11687. array_push($first, '0');
  11688. }
  11689. array_splice($first, 8 - count($second), 8, $second);
  11690. $aIP = $first;
  11691. unset($first, $second);
  11692. } else {
  11693. $aIP = explode(':', $aIP[0]);
  11694. }
  11695. $c = count($aIP);
  11696. if ($c != 8) {
  11697. return false;
  11698. }
  11699. // All the pieces should be 16-bit hex strings. Are they?
  11700. foreach ($aIP as $piece) {
  11701. if (!preg_match('#^[0-9a-fA-F]{4}$#s', sprintf('%04s', $piece))) {
  11702. return false;
  11703. }
  11704. }
  11705. return $original;
  11706. }
  11707. }
  11708. /**
  11709. * Primitive email validation class based on the regexp found at
  11710. * http://www.regular-expressions.info/email.html
  11711. */
  11712. class HTMLPurifier_AttrDef_URI_Email_SimpleCheck extends HTMLPurifier_AttrDef_URI_Email
  11713. {
  11714. /**
  11715. * @param string $string
  11716. * @param HTMLPurifier_Config $config
  11717. * @param HTMLPurifier_Context $context
  11718. * @return bool|string
  11719. */
  11720. public function validate($string, $config, $context)
  11721. {
  11722. // no support for named mailboxes i.e. "Bob <bob@example.com>"
  11723. // that needs more percent encoding to be done
  11724. if ($string == '') {
  11725. return false;
  11726. }
  11727. $string = trim($string);
  11728. $result = preg_match('/^[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i', $string);
  11729. return $result ? $string : false;
  11730. }
  11731. }
  11732. /**
  11733. * Pre-transform that changes proprietary background attribute to CSS.
  11734. */
  11735. class HTMLPurifier_AttrTransform_Background extends HTMLPurifier_AttrTransform
  11736. {
  11737. /**
  11738. * @param array $attr
  11739. * @param HTMLPurifier_Config $config
  11740. * @param HTMLPurifier_Context $context
  11741. * @return array
  11742. */
  11743. public function transform($attr, $config, $context)
  11744. {
  11745. if (!isset($attr['background'])) {
  11746. return $attr;
  11747. }
  11748. $background = $this->confiscateAttr($attr, 'background');
  11749. // some validation should happen here
  11750. $this->prependCSS($attr, "background-image:url($background);");
  11751. return $attr;
  11752. }
  11753. }
  11754. // this MUST be placed in post, as it assumes that any value in dir is valid
  11755. /**
  11756. * Post-trasnform that ensures that bdo tags have the dir attribute set.
  11757. */
  11758. class HTMLPurifier_AttrTransform_BdoDir extends HTMLPurifier_AttrTransform
  11759. {
  11760. /**
  11761. * @param array $attr
  11762. * @param HTMLPurifier_Config $config
  11763. * @param HTMLPurifier_Context $context
  11764. * @return array
  11765. */
  11766. public function transform($attr, $config, $context)
  11767. {
  11768. if (isset($attr['dir'])) {
  11769. return $attr;
  11770. }
  11771. $attr['dir'] = $config->get('Attr.DefaultTextDir');
  11772. return $attr;
  11773. }
  11774. }
  11775. /**
  11776. * Pre-transform that changes deprecated bgcolor attribute to CSS.
  11777. */
  11778. class HTMLPurifier_AttrTransform_BgColor extends HTMLPurifier_AttrTransform
  11779. {
  11780. /**
  11781. * @param array $attr
  11782. * @param HTMLPurifier_Config $config
  11783. * @param HTMLPurifier_Context $context
  11784. * @return array
  11785. */
  11786. public function transform($attr, $config, $context)
  11787. {
  11788. if (!isset($attr['bgcolor'])) {
  11789. return $attr;
  11790. }
  11791. $bgcolor = $this->confiscateAttr($attr, 'bgcolor');
  11792. // some validation should happen here
  11793. $this->prependCSS($attr, "background-color:$bgcolor;");
  11794. return $attr;
  11795. }
  11796. }
  11797. /**
  11798. * Pre-transform that changes converts a boolean attribute to fixed CSS
  11799. */
  11800. class HTMLPurifier_AttrTransform_BoolToCSS extends HTMLPurifier_AttrTransform
  11801. {
  11802. /**
  11803. * Name of boolean attribute that is trigger.
  11804. * @type string
  11805. */
  11806. protected $attr;
  11807. /**
  11808. * CSS declarations to add to style, needs trailing semicolon.
  11809. * @type string
  11810. */
  11811. protected $css;
  11812. /**
  11813. * @param string $attr attribute name to convert from
  11814. * @param string $css CSS declarations to add to style (needs semicolon)
  11815. */
  11816. public function __construct($attr, $css)
  11817. {
  11818. $this->attr = $attr;
  11819. $this->css = $css;
  11820. }
  11821. /**
  11822. * @param array $attr
  11823. * @param HTMLPurifier_Config $config
  11824. * @param HTMLPurifier_Context $context
  11825. * @return array
  11826. */
  11827. public function transform($attr, $config, $context)
  11828. {
  11829. if (!isset($attr[$this->attr])) {
  11830. return $attr;
  11831. }
  11832. unset($attr[$this->attr]);
  11833. $this->prependCSS($attr, $this->css);
  11834. return $attr;
  11835. }
  11836. }
  11837. /**
  11838. * Pre-transform that changes deprecated border attribute to CSS.
  11839. */
  11840. class HTMLPurifier_AttrTransform_Border extends HTMLPurifier_AttrTransform
  11841. {
  11842. /**
  11843. * @param array $attr
  11844. * @param HTMLPurifier_Config $config
  11845. * @param HTMLPurifier_Context $context
  11846. * @return array
  11847. */
  11848. public function transform($attr, $config, $context)
  11849. {
  11850. if (!isset($attr['border'])) {
  11851. return $attr;
  11852. }
  11853. $border_width = $this->confiscateAttr($attr, 'border');
  11854. // some validation should happen here
  11855. $this->prependCSS($attr, "border:{$border_width}px solid;");
  11856. return $attr;
  11857. }
  11858. }
  11859. /**
  11860. * Generic pre-transform that converts an attribute with a fixed number of
  11861. * values (enumerated) to CSS.
  11862. */
  11863. class HTMLPurifier_AttrTransform_EnumToCSS extends HTMLPurifier_AttrTransform
  11864. {
  11865. /**
  11866. * Name of attribute to transform from.
  11867. * @type string
  11868. */
  11869. protected $attr;
  11870. /**
  11871. * Lookup array of attribute values to CSS.
  11872. * @type array
  11873. */
  11874. protected $enumToCSS = array();
  11875. /**
  11876. * Case sensitivity of the matching.
  11877. * @type bool
  11878. * @warning Currently can only be guaranteed to work with ASCII
  11879. * values.
  11880. */
  11881. protected $caseSensitive = false;
  11882. /**
  11883. * @param string $attr Attribute name to transform from
  11884. * @param array $enum_to_css Lookup array of attribute values to CSS
  11885. * @param bool $case_sensitive Case sensitivity indicator, default false
  11886. */
  11887. public function __construct($attr, $enum_to_css, $case_sensitive = false)
  11888. {
  11889. $this->attr = $attr;
  11890. $this->enumToCSS = $enum_to_css;
  11891. $this->caseSensitive = (bool)$case_sensitive;
  11892. }
  11893. /**
  11894. * @param array $attr
  11895. * @param HTMLPurifier_Config $config
  11896. * @param HTMLPurifier_Context $context
  11897. * @return array
  11898. */
  11899. public function transform($attr, $config, $context)
  11900. {
  11901. if (!isset($attr[$this->attr])) {
  11902. return $attr;
  11903. }
  11904. $value = trim($attr[$this->attr]);
  11905. unset($attr[$this->attr]);
  11906. if (!$this->caseSensitive) {
  11907. $value = strtolower($value);
  11908. }
  11909. if (!isset($this->enumToCSS[$value])) {
  11910. return $attr;
  11911. }
  11912. $this->prependCSS($attr, $this->enumToCSS[$value]);
  11913. return $attr;
  11914. }
  11915. }
  11916. // must be called POST validation
  11917. /**
  11918. * Transform that supplies default values for the src and alt attributes
  11919. * in img tags, as well as prevents the img tag from being removed
  11920. * because of a missing alt tag. This needs to be registered as both
  11921. * a pre and post attribute transform.
  11922. */
  11923. class HTMLPurifier_AttrTransform_ImgRequired extends HTMLPurifier_AttrTransform
  11924. {
  11925. /**
  11926. * @param array $attr
  11927. * @param HTMLPurifier_Config $config
  11928. * @param HTMLPurifier_Context $context
  11929. * @return array
  11930. */
  11931. public function transform($attr, $config, $context)
  11932. {
  11933. $src = true;
  11934. if (!isset($attr['src'])) {
  11935. if ($config->get('Core.RemoveInvalidImg')) {
  11936. return $attr;
  11937. }
  11938. $attr['src'] = $config->get('Attr.DefaultInvalidImage');
  11939. $src = false;
  11940. }
  11941. if (!isset($attr['alt'])) {
  11942. if ($src) {
  11943. $alt = $config->get('Attr.DefaultImageAlt');
  11944. if ($alt === null) {
  11945. $attr['alt'] = basename($attr['src']);
  11946. } else {
  11947. $attr['alt'] = $alt;
  11948. }
  11949. } else {
  11950. $attr['alt'] = $config->get('Attr.DefaultInvalidImageAlt');
  11951. }
  11952. }
  11953. return $attr;
  11954. }
  11955. }
  11956. /**
  11957. * Pre-transform that changes deprecated hspace and vspace attributes to CSS
  11958. */
  11959. class HTMLPurifier_AttrTransform_ImgSpace extends HTMLPurifier_AttrTransform
  11960. {
  11961. /**
  11962. * @type string
  11963. */
  11964. protected $attr;
  11965. /**
  11966. * @type array
  11967. */
  11968. protected $css = array(
  11969. 'hspace' => array('left', 'right'),
  11970. 'vspace' => array('top', 'bottom')
  11971. );
  11972. /**
  11973. * @param string $attr
  11974. */
  11975. public function __construct($attr)
  11976. {
  11977. $this->attr = $attr;
  11978. if (!isset($this->css[$attr])) {
  11979. trigger_error(htmlspecialchars($attr) . ' is not valid space attribute');
  11980. }
  11981. }
  11982. /**
  11983. * @param array $attr
  11984. * @param HTMLPurifier_Config $config
  11985. * @param HTMLPurifier_Context $context
  11986. * @return array
  11987. */
  11988. public function transform($attr, $config, $context)
  11989. {
  11990. if (!isset($attr[$this->attr])) {
  11991. return $attr;
  11992. }
  11993. $width = $this->confiscateAttr($attr, $this->attr);
  11994. // some validation could happen here
  11995. if (!isset($this->css[$this->attr])) {
  11996. return $attr;
  11997. }
  11998. $style = '';
  11999. foreach ($this->css[$this->attr] as $suffix) {
  12000. $property = "margin-$suffix";
  12001. $style .= "$property:{$width}px;";
  12002. }
  12003. $this->prependCSS($attr, $style);
  12004. return $attr;
  12005. }
  12006. }
  12007. /**
  12008. * Performs miscellaneous cross attribute validation and filtering for
  12009. * input elements. This is meant to be a post-transform.
  12010. */
  12011. class HTMLPurifier_AttrTransform_Input extends HTMLPurifier_AttrTransform
  12012. {
  12013. /**
  12014. * @type HTMLPurifier_AttrDef_HTML_Pixels
  12015. */
  12016. protected $pixels;
  12017. public function __construct()
  12018. {
  12019. $this->pixels = new HTMLPurifier_AttrDef_HTML_Pixels();
  12020. }
  12021. /**
  12022. * @param array $attr
  12023. * @param HTMLPurifier_Config $config
  12024. * @param HTMLPurifier_Context $context
  12025. * @return array
  12026. */
  12027. public function transform($attr, $config, $context)
  12028. {
  12029. if (!isset($attr['type'])) {
  12030. $t = 'text';
  12031. } else {
  12032. $t = strtolower($attr['type']);
  12033. }
  12034. if (isset($attr['checked']) && $t !== 'radio' && $t !== 'checkbox') {
  12035. unset($attr['checked']);
  12036. }
  12037. if (isset($attr['maxlength']) && $t !== 'text' && $t !== 'password') {
  12038. unset($attr['maxlength']);
  12039. }
  12040. if (isset($attr['size']) && $t !== 'text' && $t !== 'password') {
  12041. $result = $this->pixels->validate($attr['size'], $config, $context);
  12042. if ($result === false) {
  12043. unset($attr['size']);
  12044. } else {
  12045. $attr['size'] = $result;
  12046. }
  12047. }
  12048. if (isset($attr['src']) && $t !== 'image') {
  12049. unset($attr['src']);
  12050. }
  12051. if (!isset($attr['value']) && ($t === 'radio' || $t === 'checkbox')) {
  12052. $attr['value'] = '';
  12053. }
  12054. return $attr;
  12055. }
  12056. }
  12057. /**
  12058. * Post-transform that copies lang's value to xml:lang (and vice-versa)
  12059. * @note Theoretically speaking, this could be a pre-transform, but putting
  12060. * post is more efficient.
  12061. */
  12062. class HTMLPurifier_AttrTransform_Lang extends HTMLPurifier_AttrTransform
  12063. {
  12064. /**
  12065. * @param array $attr
  12066. * @param HTMLPurifier_Config $config
  12067. * @param HTMLPurifier_Context $context
  12068. * @return array
  12069. */
  12070. public function transform($attr, $config, $context)
  12071. {
  12072. $lang = isset($attr['lang']) ? $attr['lang'] : false;
  12073. $xml_lang = isset($attr['xml:lang']) ? $attr['xml:lang'] : false;
  12074. if ($lang !== false && $xml_lang === false) {
  12075. $attr['xml:lang'] = $lang;
  12076. } elseif ($xml_lang !== false) {
  12077. $attr['lang'] = $xml_lang;
  12078. }
  12079. return $attr;
  12080. }
  12081. }
  12082. /**
  12083. * Class for handling width/height length attribute transformations to CSS
  12084. */
  12085. class HTMLPurifier_AttrTransform_Length extends HTMLPurifier_AttrTransform
  12086. {
  12087. /**
  12088. * @type string
  12089. */
  12090. protected $name;
  12091. /**
  12092. * @type string
  12093. */
  12094. protected $cssName;
  12095. public function __construct($name, $css_name = null)
  12096. {
  12097. $this->name = $name;
  12098. $this->cssName = $css_name ? $css_name : $name;
  12099. }
  12100. /**
  12101. * @param array $attr
  12102. * @param HTMLPurifier_Config $config
  12103. * @param HTMLPurifier_Context $context
  12104. * @return array
  12105. */
  12106. public function transform($attr, $config, $context)
  12107. {
  12108. if (!isset($attr[$this->name])) {
  12109. return $attr;
  12110. }
  12111. $length = $this->confiscateAttr($attr, $this->name);
  12112. if (ctype_digit($length)) {
  12113. $length .= 'px';
  12114. }
  12115. $this->prependCSS($attr, $this->cssName . ":$length;");
  12116. return $attr;
  12117. }
  12118. }
  12119. /**
  12120. * Pre-transform that changes deprecated name attribute to ID if necessary
  12121. */
  12122. class HTMLPurifier_AttrTransform_Name extends HTMLPurifier_AttrTransform
  12123. {
  12124. /**
  12125. * @param array $attr
  12126. * @param HTMLPurifier_Config $config
  12127. * @param HTMLPurifier_Context $context
  12128. * @return array
  12129. */
  12130. public function transform($attr, $config, $context)
  12131. {
  12132. // Abort early if we're using relaxed definition of name
  12133. if ($config->get('HTML.Attr.Name.UseCDATA')) {
  12134. return $attr;
  12135. }
  12136. if (!isset($attr['name'])) {
  12137. return $attr;
  12138. }
  12139. $id = $this->confiscateAttr($attr, 'name');
  12140. if (isset($attr['id'])) {
  12141. return $attr;
  12142. }
  12143. $attr['id'] = $id;
  12144. return $attr;
  12145. }
  12146. }
  12147. /**
  12148. * Post-transform that performs validation to the name attribute; if
  12149. * it is present with an equivalent id attribute, it is passed through;
  12150. * otherwise validation is performed.
  12151. */
  12152. class HTMLPurifier_AttrTransform_NameSync extends HTMLPurifier_AttrTransform
  12153. {
  12154. public function __construct()
  12155. {
  12156. $this->idDef = new HTMLPurifier_AttrDef_HTML_ID();
  12157. }
  12158. /**
  12159. * @param array $attr
  12160. * @param HTMLPurifier_Config $config
  12161. * @param HTMLPurifier_Context $context
  12162. * @return array
  12163. */
  12164. public function transform($attr, $config, $context)
  12165. {
  12166. if (!isset($attr['name'])) {
  12167. return $attr;
  12168. }
  12169. $name = $attr['name'];
  12170. if (isset($attr['id']) && $attr['id'] === $name) {
  12171. return $attr;
  12172. }
  12173. $result = $this->idDef->validate($name, $config, $context);
  12174. if ($result === false) {
  12175. unset($attr['name']);
  12176. } else {
  12177. $attr['name'] = $result;
  12178. }
  12179. return $attr;
  12180. }
  12181. }
  12182. // must be called POST validation
  12183. /**
  12184. * Adds rel="nofollow" to all outbound links. This transform is
  12185. * only attached if Attr.Nofollow is TRUE.
  12186. */
  12187. class HTMLPurifier_AttrTransform_Nofollow extends HTMLPurifier_AttrTransform
  12188. {
  12189. /**
  12190. * @type HTMLPurifier_URIParser
  12191. */
  12192. private $parser;
  12193. public function __construct()
  12194. {
  12195. $this->parser = new HTMLPurifier_URIParser();
  12196. }
  12197. /**
  12198. * @param array $attr
  12199. * @param HTMLPurifier_Config $config
  12200. * @param HTMLPurifier_Context $context
  12201. * @return array
  12202. */
  12203. public function transform($attr, $config, $context)
  12204. {
  12205. if (!isset($attr['href'])) {
  12206. return $attr;
  12207. }
  12208. // XXX Kind of inefficient
  12209. $url = $this->parser->parse($attr['href']);
  12210. $scheme = $url->getSchemeObj($config, $context);
  12211. if ($scheme->browsable && !$url->isLocal($config, $context)) {
  12212. if (isset($attr['rel'])) {
  12213. $rels = explode(' ', $attr['rel']);
  12214. if (!in_array('nofollow', $rels)) {
  12215. $rels[] = 'nofollow';
  12216. }
  12217. $attr['rel'] = implode(' ', $rels);
  12218. } else {
  12219. $attr['rel'] = 'nofollow';
  12220. }
  12221. }
  12222. return $attr;
  12223. }
  12224. }
  12225. class HTMLPurifier_AttrTransform_SafeEmbed extends HTMLPurifier_AttrTransform
  12226. {
  12227. /**
  12228. * @type string
  12229. */
  12230. public $name = "SafeEmbed";
  12231. /**
  12232. * @param array $attr
  12233. * @param HTMLPurifier_Config $config
  12234. * @param HTMLPurifier_Context $context
  12235. * @return array
  12236. */
  12237. public function transform($attr, $config, $context)
  12238. {
  12239. $attr['allowscriptaccess'] = 'never';
  12240. $attr['allownetworking'] = 'internal';
  12241. $attr['type'] = 'application/x-shockwave-flash';
  12242. return $attr;
  12243. }
  12244. }
  12245. /**
  12246. * Writes default type for all objects. Currently only supports flash.
  12247. */
  12248. class HTMLPurifier_AttrTransform_SafeObject extends HTMLPurifier_AttrTransform
  12249. {
  12250. /**
  12251. * @type string
  12252. */
  12253. public $name = "SafeObject";
  12254. /**
  12255. * @param array $attr
  12256. * @param HTMLPurifier_Config $config
  12257. * @param HTMLPurifier_Context $context
  12258. * @return array
  12259. */
  12260. public function transform($attr, $config, $context)
  12261. {
  12262. if (!isset($attr['type'])) {
  12263. $attr['type'] = 'application/x-shockwave-flash';
  12264. }
  12265. return $attr;
  12266. }
  12267. }
  12268. /**
  12269. * Validates name/value pairs in param tags to be used in safe objects. This
  12270. * will only allow name values it recognizes, and pre-fill certain attributes
  12271. * with required values.
  12272. *
  12273. * @note
  12274. * This class only supports Flash. In the future, Quicktime support
  12275. * may be added.
  12276. *
  12277. * @warning
  12278. * This class expects an injector to add the necessary parameters tags.
  12279. */
  12280. class HTMLPurifier_AttrTransform_SafeParam extends HTMLPurifier_AttrTransform
  12281. {
  12282. /**
  12283. * @type string
  12284. */
  12285. public $name = "SafeParam";
  12286. /**
  12287. * @type HTMLPurifier_AttrDef_URI
  12288. */
  12289. private $uri;
  12290. public function __construct()
  12291. {
  12292. $this->uri = new HTMLPurifier_AttrDef_URI(true); // embedded
  12293. $this->wmode = new HTMLPurifier_AttrDef_Enum(array('window', 'opaque', 'transparent'));
  12294. }
  12295. /**
  12296. * @param array $attr
  12297. * @param HTMLPurifier_Config $config
  12298. * @param HTMLPurifier_Context $context
  12299. * @return array
  12300. */
  12301. public function transform($attr, $config, $context)
  12302. {
  12303. // If we add support for other objects, we'll need to alter the
  12304. // transforms.
  12305. switch ($attr['name']) {
  12306. // application/x-shockwave-flash
  12307. // Keep this synchronized with Injector/SafeObject.php
  12308. case 'allowScriptAccess':
  12309. $attr['value'] = 'never';
  12310. break;
  12311. case 'allowNetworking':
  12312. $attr['value'] = 'internal';
  12313. break;
  12314. case 'allowFullScreen':
  12315. if ($config->get('HTML.FlashAllowFullScreen')) {
  12316. $attr['value'] = ($attr['value'] == 'true') ? 'true' : 'false';
  12317. } else {
  12318. $attr['value'] = 'false';
  12319. }
  12320. break;
  12321. case 'wmode':
  12322. $attr['value'] = $this->wmode->validate($attr['value'], $config, $context);
  12323. break;
  12324. case 'movie':
  12325. case 'src':
  12326. $attr['name'] = "movie";
  12327. $attr['value'] = $this->uri->validate($attr['value'], $config, $context);
  12328. break;
  12329. case 'flashvars':
  12330. // we're going to allow arbitrary inputs to the SWF, on
  12331. // the reasoning that it could only hack the SWF, not us.
  12332. break;
  12333. // add other cases to support other param name/value pairs
  12334. default:
  12335. $attr['name'] = $attr['value'] = null;
  12336. }
  12337. return $attr;
  12338. }
  12339. }
  12340. /**
  12341. * Implements required attribute stipulation for <script>
  12342. */
  12343. class HTMLPurifier_AttrTransform_ScriptRequired extends HTMLPurifier_AttrTransform
  12344. {
  12345. /**
  12346. * @param array $attr
  12347. * @param HTMLPurifier_Config $config
  12348. * @param HTMLPurifier_Context $context
  12349. * @return array
  12350. */
  12351. public function transform($attr, $config, $context)
  12352. {
  12353. if (!isset($attr['type'])) {
  12354. $attr['type'] = 'text/javascript';
  12355. }
  12356. return $attr;
  12357. }
  12358. }
  12359. // must be called POST validation
  12360. /**
  12361. * Adds target="blank" to all outbound links. This transform is
  12362. * only attached if Attr.TargetBlank is TRUE. This works regardless
  12363. * of whether or not Attr.AllowedFrameTargets
  12364. */
  12365. class HTMLPurifier_AttrTransform_TargetBlank extends HTMLPurifier_AttrTransform
  12366. {
  12367. /**
  12368. * @type HTMLPurifier_URIParser
  12369. */
  12370. private $parser;
  12371. public function __construct()
  12372. {
  12373. $this->parser = new HTMLPurifier_URIParser();
  12374. }
  12375. /**
  12376. * @param array $attr
  12377. * @param HTMLPurifier_Config $config
  12378. * @param HTMLPurifier_Context $context
  12379. * @return array
  12380. */
  12381. public function transform($attr, $config, $context)
  12382. {
  12383. if (!isset($attr['href'])) {
  12384. return $attr;
  12385. }
  12386. // XXX Kind of inefficient
  12387. $url = $this->parser->parse($attr['href']);
  12388. $scheme = $url->getSchemeObj($config, $context);
  12389. if ($scheme->browsable && !$url->isBenign($config, $context)) {
  12390. $attr['target'] = '_blank';
  12391. }
  12392. return $attr;
  12393. }
  12394. }
  12395. // must be called POST validation
  12396. /**
  12397. * Adds rel="noreferrer" to any links which target a different window
  12398. * than the current one. This is used to prevent malicious websites
  12399. * from silently replacing the original window, which could be used
  12400. * to do phishing.
  12401. * This transform is controlled by %HTML.TargetNoreferrer.
  12402. */
  12403. class HTMLPurifier_AttrTransform_TargetNoreferrer extends HTMLPurifier_AttrTransform
  12404. {
  12405. /**
  12406. * @param array $attr
  12407. * @param HTMLPurifier_Config $config
  12408. * @param HTMLPurifier_Context $context
  12409. * @return array
  12410. */
  12411. public function transform($attr, $config, $context)
  12412. {
  12413. if (isset($attr['rel'])) {
  12414. $rels = explode(' ', $attr['rel']);
  12415. } else {
  12416. $rels = array();
  12417. }
  12418. if (isset($attr['target']) && !in_array('noreferrer', $rels)) {
  12419. $rels[] = 'noreferrer';
  12420. }
  12421. if (!empty($rels) || isset($attr['rel'])) {
  12422. $attr['rel'] = implode(' ', $rels);
  12423. }
  12424. return $attr;
  12425. }
  12426. }
  12427. /**
  12428. * Sets height/width defaults for <textarea>
  12429. */
  12430. class HTMLPurifier_AttrTransform_Textarea extends HTMLPurifier_AttrTransform
  12431. {
  12432. /**
  12433. * @param array $attr
  12434. * @param HTMLPurifier_Config $config
  12435. * @param HTMLPurifier_Context $context
  12436. * @return array
  12437. */
  12438. public function transform($attr, $config, $context)
  12439. {
  12440. // Calculated from Firefox
  12441. if (!isset($attr['cols'])) {
  12442. $attr['cols'] = '22';
  12443. }
  12444. if (!isset($attr['rows'])) {
  12445. $attr['rows'] = '3';
  12446. }
  12447. return $attr;
  12448. }
  12449. }
  12450. /**
  12451. * Definition that uses different definitions depending on context.
  12452. *
  12453. * The del and ins tags are notable because they allow different types of
  12454. * elements depending on whether or not they're in a block or inline context.
  12455. * Chameleon allows this behavior to happen by using two different
  12456. * definitions depending on context. While this somewhat generalized,
  12457. * it is specifically intended for those two tags.
  12458. */
  12459. class HTMLPurifier_ChildDef_Chameleon extends HTMLPurifier_ChildDef
  12460. {
  12461. /**
  12462. * Instance of the definition object to use when inline. Usually stricter.
  12463. * @type HTMLPurifier_ChildDef_Optional
  12464. */
  12465. public $inline;
  12466. /**
  12467. * Instance of the definition object to use when block.
  12468. * @type HTMLPurifier_ChildDef_Optional
  12469. */
  12470. public $block;
  12471. /**
  12472. * @type string
  12473. */
  12474. public $type = 'chameleon';
  12475. /**
  12476. * @param array $inline List of elements to allow when inline.
  12477. * @param array $block List of elements to allow when block.
  12478. */
  12479. public function __construct($inline, $block)
  12480. {
  12481. $this->inline = new HTMLPurifier_ChildDef_Optional($inline);
  12482. $this->block = new HTMLPurifier_ChildDef_Optional($block);
  12483. $this->elements = $this->block->elements;
  12484. }
  12485. /**
  12486. * @param HTMLPurifier_Node[] $children
  12487. * @param HTMLPurifier_Config $config
  12488. * @param HTMLPurifier_Context $context
  12489. * @return bool
  12490. */
  12491. public function validateChildren($children, $config, $context)
  12492. {
  12493. if ($context->get('IsInline') === false) {
  12494. return $this->block->validateChildren(
  12495. $children,
  12496. $config,
  12497. $context
  12498. );
  12499. } else {
  12500. return $this->inline->validateChildren(
  12501. $children,
  12502. $config,
  12503. $context
  12504. );
  12505. }
  12506. }
  12507. }
  12508. /**
  12509. * Custom validation class, accepts DTD child definitions
  12510. *
  12511. * @warning Currently this class is an all or nothing proposition, that is,
  12512. * it will only give a bool return value.
  12513. */
  12514. class HTMLPurifier_ChildDef_Custom extends HTMLPurifier_ChildDef
  12515. {
  12516. /**
  12517. * @type string
  12518. */
  12519. public $type = 'custom';
  12520. /**
  12521. * @type bool
  12522. */
  12523. public $allow_empty = false;
  12524. /**
  12525. * Allowed child pattern as defined by the DTD.
  12526. * @type string
  12527. */
  12528. public $dtd_regex;
  12529. /**
  12530. * PCRE regex derived from $dtd_regex.
  12531. * @type string
  12532. */
  12533. private $_pcre_regex;
  12534. /**
  12535. * @param $dtd_regex Allowed child pattern from the DTD
  12536. */
  12537. public function __construct($dtd_regex)
  12538. {
  12539. $this->dtd_regex = $dtd_regex;
  12540. $this->_compileRegex();
  12541. }
  12542. /**
  12543. * Compiles the PCRE regex from a DTD regex ($dtd_regex to $_pcre_regex)
  12544. */
  12545. protected function _compileRegex()
  12546. {
  12547. $raw = str_replace(' ', '', $this->dtd_regex);
  12548. if ($raw{0} != '(') {
  12549. $raw = "($raw)";
  12550. }
  12551. $el = '[#a-zA-Z0-9_.-]+';
  12552. $reg = $raw;
  12553. // COMPLICATED! AND MIGHT BE BUGGY! I HAVE NO CLUE WHAT I'M
  12554. // DOING! Seriously: if there's problems, please report them.
  12555. // collect all elements into the $elements array
  12556. preg_match_all("/$el/", $reg, $matches);
  12557. foreach ($matches[0] as $match) {
  12558. $this->elements[$match] = true;
  12559. }
  12560. // setup all elements as parentheticals with leading commas
  12561. $reg = preg_replace("/$el/", '(,\\0)', $reg);
  12562. // remove commas when they were not solicited
  12563. $reg = preg_replace("/([^,(|]\(+),/", '\\1', $reg);
  12564. // remove all non-paranthetical commas: they are handled by first regex
  12565. $reg = preg_replace("/,\(/", '(', $reg);
  12566. $this->_pcre_regex = $reg;
  12567. }
  12568. /**
  12569. * @param HTMLPurifier_Node[] $children
  12570. * @param HTMLPurifier_Config $config
  12571. * @param HTMLPurifier_Context $context
  12572. * @return bool
  12573. */
  12574. public function validateChildren($children, $config, $context)
  12575. {
  12576. $list_of_children = '';
  12577. $nesting = 0; // depth into the nest
  12578. foreach ($children as $node) {
  12579. if (!empty($node->is_whitespace)) {
  12580. continue;
  12581. }
  12582. $list_of_children .= $node->name . ',';
  12583. }
  12584. // add leading comma to deal with stray comma declarations
  12585. $list_of_children = ',' . rtrim($list_of_children, ',');
  12586. $okay =
  12587. preg_match(
  12588. '/^,?' . $this->_pcre_regex . '$/',
  12589. $list_of_children
  12590. );
  12591. return (bool)$okay;
  12592. }
  12593. }
  12594. /**
  12595. * Definition that disallows all elements.
  12596. * @warning validateChildren() in this class is actually never called, because
  12597. * empty elements are corrected in HTMLPurifier_Strategy_MakeWellFormed
  12598. * before child definitions are parsed in earnest by
  12599. * HTMLPurifier_Strategy_FixNesting.
  12600. */
  12601. class HTMLPurifier_ChildDef_Empty extends HTMLPurifier_ChildDef
  12602. {
  12603. /**
  12604. * @type bool
  12605. */
  12606. public $allow_empty = true;
  12607. /**
  12608. * @type string
  12609. */
  12610. public $type = 'empty';
  12611. public function __construct()
  12612. {
  12613. }
  12614. /**
  12615. * @param HTMLPurifier_Node[] $children
  12616. * @param HTMLPurifier_Config $config
  12617. * @param HTMLPurifier_Context $context
  12618. * @return array
  12619. */
  12620. public function validateChildren($children, $config, $context)
  12621. {
  12622. return array();
  12623. }
  12624. }
  12625. /**
  12626. * Definition for list containers ul and ol.
  12627. *
  12628. * What does this do? The big thing is to handle ol/ul at the top
  12629. * level of list nodes, which should be handled specially by /folding/
  12630. * them into the previous list node. We generally shouldn't ever
  12631. * see other disallowed elements, because the autoclose behavior
  12632. * in MakeWellFormed handles it.
  12633. */
  12634. class HTMLPurifier_ChildDef_List extends HTMLPurifier_ChildDef
  12635. {
  12636. /**
  12637. * @type string
  12638. */
  12639. public $type = 'list';
  12640. /**
  12641. * @type array
  12642. */
  12643. // lying a little bit, so that we can handle ul and ol ourselves
  12644. // XXX: This whole business with 'wrap' is all a bit unsatisfactory
  12645. public $elements = array('li' => true, 'ul' => true, 'ol' => true);
  12646. /**
  12647. * @param array $children
  12648. * @param HTMLPurifier_Config $config
  12649. * @param HTMLPurifier_Context $context
  12650. * @return array
  12651. */
  12652. public function validateChildren($children, $config, $context)
  12653. {
  12654. // Flag for subclasses
  12655. $this->whitespace = false;
  12656. // if there are no tokens, delete parent node
  12657. if (empty($children)) {
  12658. return false;
  12659. }
  12660. // if li is not allowed, delete parent node
  12661. if (!isset($config->getHTMLDefinition()->info['li'])) {
  12662. trigger_error("Cannot allow ul/ol without allowing li", E_USER_WARNING);
  12663. return false;
  12664. }
  12665. // the new set of children
  12666. $result = array();
  12667. // a little sanity check to make sure it's not ALL whitespace
  12668. $all_whitespace = true;
  12669. $current_li = false;
  12670. foreach ($children as $node) {
  12671. if (!empty($node->is_whitespace)) {
  12672. $result[] = $node;
  12673. continue;
  12674. }
  12675. $all_whitespace = false; // phew, we're not talking about whitespace
  12676. if ($node->name === 'li') {
  12677. // good
  12678. $current_li = $node;
  12679. $result[] = $node;
  12680. } else {
  12681. // we want to tuck this into the previous li
  12682. // Invariant: we expect the node to be ol/ul
  12683. // ToDo: Make this more robust in the case of not ol/ul
  12684. // by distinguishing between existing li and li created
  12685. // to handle non-list elements; non-list elements should
  12686. // not be appended to an existing li; only li created
  12687. // for non-list. This distinction is not currently made.
  12688. if ($current_li === false) {
  12689. $current_li = new HTMLPurifier_Node_Element('li');
  12690. $result[] = $current_li;
  12691. }
  12692. $current_li->children[] = $node;
  12693. $current_li->empty = false; // XXX fascinating! Check for this error elsewhere ToDo
  12694. }
  12695. }
  12696. if (empty($result)) {
  12697. return false;
  12698. }
  12699. if ($all_whitespace) {
  12700. return false;
  12701. }
  12702. return $result;
  12703. }
  12704. }
  12705. /**
  12706. * Definition that allows a set of elements, but disallows empty children.
  12707. */
  12708. class HTMLPurifier_ChildDef_Required extends HTMLPurifier_ChildDef
  12709. {
  12710. /**
  12711. * Lookup table of allowed elements.
  12712. * @type array
  12713. */
  12714. public $elements = array();
  12715. /**
  12716. * Whether or not the last passed node was all whitespace.
  12717. * @type bool
  12718. */
  12719. protected $whitespace = false;
  12720. /**
  12721. * @param array|string $elements List of allowed element names (lowercase).
  12722. */
  12723. public function __construct($elements)
  12724. {
  12725. if (is_string($elements)) {
  12726. $elements = str_replace(' ', '', $elements);
  12727. $elements = explode('|', $elements);
  12728. }
  12729. $keys = array_keys($elements);
  12730. if ($keys == array_keys($keys)) {
  12731. $elements = array_flip($elements);
  12732. foreach ($elements as $i => $x) {
  12733. $elements[$i] = true;
  12734. if (empty($i)) {
  12735. unset($elements[$i]);
  12736. } // remove blank
  12737. }
  12738. }
  12739. $this->elements = $elements;
  12740. }
  12741. /**
  12742. * @type bool
  12743. */
  12744. public $allow_empty = false;
  12745. /**
  12746. * @type string
  12747. */
  12748. public $type = 'required';
  12749. /**
  12750. * @param array $children
  12751. * @param HTMLPurifier_Config $config
  12752. * @param HTMLPurifier_Context $context
  12753. * @return array
  12754. */
  12755. public function validateChildren($children, $config, $context)
  12756. {
  12757. // Flag for subclasses
  12758. $this->whitespace = false;
  12759. // if there are no tokens, delete parent node
  12760. if (empty($children)) {
  12761. return false;
  12762. }
  12763. // the new set of children
  12764. $result = array();
  12765. // whether or not parsed character data is allowed
  12766. // this controls whether or not we silently drop a tag
  12767. // or generate escaped HTML from it
  12768. $pcdata_allowed = isset($this->elements['#PCDATA']);
  12769. // a little sanity check to make sure it's not ALL whitespace
  12770. $all_whitespace = true;
  12771. $stack = array_reverse($children);
  12772. while (!empty($stack)) {
  12773. $node = array_pop($stack);
  12774. if (!empty($node->is_whitespace)) {
  12775. $result[] = $node;
  12776. continue;
  12777. }
  12778. $all_whitespace = false; // phew, we're not talking about whitespace
  12779. if (!isset($this->elements[$node->name])) {
  12780. // special case text
  12781. // XXX One of these ought to be redundant or something
  12782. if ($pcdata_allowed && $node instanceof HTMLPurifier_Node_Text) {
  12783. $result[] = $node;
  12784. continue;
  12785. }
  12786. // spill the child contents in
  12787. // ToDo: Make configurable
  12788. if ($node instanceof HTMLPurifier_Node_Element) {
  12789. for ($i = count($node->children) - 1; $i >= 0; $i--) {
  12790. $stack[] = $node->children[$i];
  12791. }
  12792. continue;
  12793. }
  12794. continue;
  12795. }
  12796. $result[] = $node;
  12797. }
  12798. if (empty($result)) {
  12799. return false;
  12800. }
  12801. if ($all_whitespace) {
  12802. $this->whitespace = true;
  12803. return false;
  12804. }
  12805. return $result;
  12806. }
  12807. }
  12808. /**
  12809. * Definition that allows a set of elements, and allows no children.
  12810. * @note This is a hack to reuse code from HTMLPurifier_ChildDef_Required,
  12811. * really, one shouldn't inherit from the other. Only altered behavior
  12812. * is to overload a returned false with an array. Thus, it will never
  12813. * return false.
  12814. */
  12815. class HTMLPurifier_ChildDef_Optional extends HTMLPurifier_ChildDef_Required
  12816. {
  12817. /**
  12818. * @type bool
  12819. */
  12820. public $allow_empty = true;
  12821. /**
  12822. * @type string
  12823. */
  12824. public $type = 'optional';
  12825. /**
  12826. * @param array $children
  12827. * @param HTMLPurifier_Config $config
  12828. * @param HTMLPurifier_Context $context
  12829. * @return array
  12830. */
  12831. public function validateChildren($children, $config, $context)
  12832. {
  12833. $result = parent::validateChildren($children, $config, $context);
  12834. // we assume that $children is not modified
  12835. if ($result === false) {
  12836. if (empty($children)) {
  12837. return true;
  12838. } elseif ($this->whitespace) {
  12839. return $children;
  12840. } else {
  12841. return array();
  12842. }
  12843. }
  12844. return $result;
  12845. }
  12846. }
  12847. /**
  12848. * Takes the contents of blockquote when in strict and reformats for validation.
  12849. */
  12850. class HTMLPurifier_ChildDef_StrictBlockquote extends HTMLPurifier_ChildDef_Required
  12851. {
  12852. /**
  12853. * @type array
  12854. */
  12855. protected $real_elements;
  12856. /**
  12857. * @type array
  12858. */
  12859. protected $fake_elements;
  12860. /**
  12861. * @type bool
  12862. */
  12863. public $allow_empty = true;
  12864. /**
  12865. * @type string
  12866. */
  12867. public $type = 'strictblockquote';
  12868. /**
  12869. * @type bool
  12870. */
  12871. protected $init = false;
  12872. /**
  12873. * @param HTMLPurifier_Config $config
  12874. * @return array
  12875. * @note We don't want MakeWellFormed to auto-close inline elements since
  12876. * they might be allowed.
  12877. */
  12878. public function getAllowedElements($config)
  12879. {
  12880. $this->init($config);
  12881. return $this->fake_elements;
  12882. }
  12883. /**
  12884. * @param array $children
  12885. * @param HTMLPurifier_Config $config
  12886. * @param HTMLPurifier_Context $context
  12887. * @return array
  12888. */
  12889. public function validateChildren($children, $config, $context)
  12890. {
  12891. $this->init($config);
  12892. // trick the parent class into thinking it allows more
  12893. $this->elements = $this->fake_elements;
  12894. $result = parent::validateChildren($children, $config, $context);
  12895. $this->elements = $this->real_elements;
  12896. if ($result === false) {
  12897. return array();
  12898. }
  12899. if ($result === true) {
  12900. $result = $children;
  12901. }
  12902. $def = $config->getHTMLDefinition();
  12903. $block_wrap_name = $def->info_block_wrapper;
  12904. $block_wrap = false;
  12905. $ret = array();
  12906. foreach ($result as $node) {
  12907. if ($block_wrap === false) {
  12908. if (($node instanceof HTMLPurifier_Node_Text && !$node->is_whitespace) ||
  12909. ($node instanceof HTMLPurifier_Node_Element && !isset($this->elements[$node->name]))) {
  12910. $block_wrap = new HTMLPurifier_Node_Element($def->info_block_wrapper);
  12911. $ret[] = $block_wrap;
  12912. }
  12913. } else {
  12914. if ($node instanceof HTMLPurifier_Node_Element && isset($this->elements[$node->name])) {
  12915. $block_wrap = false;
  12916. }
  12917. }
  12918. if ($block_wrap) {
  12919. $block_wrap->children[] = $node;
  12920. } else {
  12921. $ret[] = $node;
  12922. }
  12923. }
  12924. return $ret;
  12925. }
  12926. /**
  12927. * @param HTMLPurifier_Config $config
  12928. */
  12929. private function init($config)
  12930. {
  12931. if (!$this->init) {
  12932. $def = $config->getHTMLDefinition();
  12933. // allow all inline elements
  12934. $this->real_elements = $this->elements;
  12935. $this->fake_elements = $def->info_content_sets['Flow'];
  12936. $this->fake_elements['#PCDATA'] = true;
  12937. $this->init = true;
  12938. }
  12939. }
  12940. }
  12941. /**
  12942. * Definition for tables. The general idea is to extract out all of the
  12943. * essential bits, and then reconstruct it later.
  12944. *
  12945. * This is a bit confusing, because the DTDs and the W3C
  12946. * validators seem to disagree on the appropriate definition. The
  12947. * DTD claims:
  12948. *
  12949. * (CAPTION?, (COL*|COLGROUP*), THEAD?, TFOOT?, TBODY+)
  12950. *
  12951. * But actually, the HTML4 spec then has this to say:
  12952. *
  12953. * The TBODY start tag is always required except when the table
  12954. * contains only one table body and no table head or foot sections.
  12955. * The TBODY end tag may always be safely omitted.
  12956. *
  12957. * So the DTD is kind of wrong. The validator is, unfortunately, kind
  12958. * of on crack.
  12959. *
  12960. * The definition changed again in XHTML1.1; and in my opinion, this
  12961. * formulation makes the most sense.
  12962. *
  12963. * caption?, ( col* | colgroup* ), (( thead?, tfoot?, tbody+ ) | ( tr+ ))
  12964. *
  12965. * Essentially, we have two modes: thead/tfoot/tbody mode, and tr mode.
  12966. * If we encounter a thead, tfoot or tbody, we are placed in the former
  12967. * mode, and we *must* wrap any stray tr segments with a tbody. But if
  12968. * we don't run into any of them, just have tr tags is OK.
  12969. */
  12970. class HTMLPurifier_ChildDef_Table extends HTMLPurifier_ChildDef
  12971. {
  12972. /**
  12973. * @type bool
  12974. */
  12975. public $allow_empty = false;
  12976. /**
  12977. * @type string
  12978. */
  12979. public $type = 'table';
  12980. /**
  12981. * @type array
  12982. */
  12983. public $elements = array(
  12984. 'tr' => true,
  12985. 'tbody' => true,
  12986. 'thead' => true,
  12987. 'tfoot' => true,
  12988. 'caption' => true,
  12989. 'colgroup' => true,
  12990. 'col' => true
  12991. );
  12992. public function __construct()
  12993. {
  12994. }
  12995. /**
  12996. * @param array $children
  12997. * @param HTMLPurifier_Config $config
  12998. * @param HTMLPurifier_Context $context
  12999. * @return array
  13000. */
  13001. public function validateChildren($children, $config, $context)
  13002. {
  13003. if (empty($children)) {
  13004. return false;
  13005. }
  13006. // only one of these elements is allowed in a table
  13007. $caption = false;
  13008. $thead = false;
  13009. $tfoot = false;
  13010. // whitespace
  13011. $initial_ws = array();
  13012. $after_caption_ws = array();
  13013. $after_thead_ws = array();
  13014. $after_tfoot_ws = array();
  13015. // as many of these as you want
  13016. $cols = array();
  13017. $content = array();
  13018. $tbody_mode = false; // if true, then we need to wrap any stray
  13019. // <tr>s with a <tbody>.
  13020. $ws_accum =& $initial_ws;
  13021. foreach ($children as $node) {
  13022. if ($node instanceof HTMLPurifier_Node_Comment) {
  13023. $ws_accum[] = $node;
  13024. continue;
  13025. }
  13026. switch ($node->name) {
  13027. case 'tbody':
  13028. $tbody_mode = true;
  13029. // fall through
  13030. case 'tr':
  13031. $content[] = $node;
  13032. $ws_accum =& $content;
  13033. break;
  13034. case 'caption':
  13035. // there can only be one caption!
  13036. if ($caption !== false) break;
  13037. $caption = $node;
  13038. $ws_accum =& $after_caption_ws;
  13039. break;
  13040. case 'thead':
  13041. $tbody_mode = true;
  13042. // XXX This breaks rendering properties with
  13043. // Firefox, which never floats a <thead> to
  13044. // the top. Ever. (Our scheme will float the
  13045. // first <thead> to the top.) So maybe
  13046. // <thead>s that are not first should be
  13047. // turned into <tbody>? Very tricky, indeed.
  13048. if ($thead === false) {
  13049. $thead = $node;
  13050. $ws_accum =& $after_thead_ws;
  13051. } else {
  13052. // Oops, there's a second one! What
  13053. // should we do? Current behavior is to
  13054. // transmutate the first and last entries into
  13055. // tbody tags, and then put into content.
  13056. // Maybe a better idea is to *attach
  13057. // it* to the existing thead or tfoot?
  13058. // We don't do this, because Firefox
  13059. // doesn't float an extra tfoot to the
  13060. // bottom like it does for the first one.
  13061. $node->name = 'tbody';
  13062. $content[] = $node;
  13063. $ws_accum =& $content;
  13064. }
  13065. break;
  13066. case 'tfoot':
  13067. // see above for some aveats
  13068. $tbody_mode = true;
  13069. if ($tfoot === false) {
  13070. $tfoot = $node;
  13071. $ws_accum =& $after_tfoot_ws;
  13072. } else {
  13073. $node->name = 'tbody';
  13074. $content[] = $node;
  13075. $ws_accum =& $content;
  13076. }
  13077. break;
  13078. case 'colgroup':
  13079. case 'col':
  13080. $cols[] = $node;
  13081. $ws_accum =& $cols;
  13082. break;
  13083. case '#PCDATA':
  13084. // How is whitespace handled? We treat is as sticky to
  13085. // the *end* of the previous element. So all of the
  13086. // nonsense we have worked on is to keep things
  13087. // together.
  13088. if (!empty($node->is_whitespace)) {
  13089. $ws_accum[] = $node;
  13090. }
  13091. break;
  13092. }
  13093. }
  13094. if (empty($content)) {
  13095. return false;
  13096. }
  13097. $ret = $initial_ws;
  13098. if ($caption !== false) {
  13099. $ret[] = $caption;
  13100. $ret = array_merge($ret, $after_caption_ws);
  13101. }
  13102. if ($cols !== false) {
  13103. $ret = array_merge($ret, $cols);
  13104. }
  13105. if ($thead !== false) {
  13106. $ret[] = $thead;
  13107. $ret = array_merge($ret, $after_thead_ws);
  13108. }
  13109. if ($tfoot !== false) {
  13110. $ret[] = $tfoot;
  13111. $ret = array_merge($ret, $after_tfoot_ws);
  13112. }
  13113. if ($tbody_mode) {
  13114. // we have to shuffle tr into tbody
  13115. $current_tr_tbody = null;
  13116. foreach($content as $node) {
  13117. switch ($node->name) {
  13118. case 'tbody':
  13119. $current_tr_tbody = null;
  13120. $ret[] = $node;
  13121. break;
  13122. case 'tr':
  13123. if ($current_tr_tbody === null) {
  13124. $current_tr_tbody = new HTMLPurifier_Node_Element('tbody');
  13125. $ret[] = $current_tr_tbody;
  13126. }
  13127. $current_tr_tbody->children[] = $node;
  13128. break;
  13129. case '#PCDATA':
  13130. assert($node->is_whitespace);
  13131. if ($current_tr_tbody === null) {
  13132. $ret[] = $node;
  13133. } else {
  13134. $current_tr_tbody->children[] = $node;
  13135. }
  13136. break;
  13137. }
  13138. }
  13139. } else {
  13140. $ret = array_merge($ret, $content);
  13141. }
  13142. return $ret;
  13143. }
  13144. }
  13145. class HTMLPurifier_DefinitionCache_Decorator extends HTMLPurifier_DefinitionCache
  13146. {
  13147. /**
  13148. * Cache object we are decorating
  13149. * @type HTMLPurifier_DefinitionCache
  13150. */
  13151. public $cache;
  13152. /**
  13153. * The name of the decorator
  13154. * @var string
  13155. */
  13156. public $name;
  13157. public function __construct()
  13158. {
  13159. }
  13160. /**
  13161. * Lazy decorator function
  13162. * @param HTMLPurifier_DefinitionCache $cache Reference to cache object to decorate
  13163. * @return HTMLPurifier_DefinitionCache_Decorator
  13164. */
  13165. public function decorate(&$cache)
  13166. {
  13167. $decorator = $this->copy();
  13168. // reference is necessary for mocks in PHP 4
  13169. $decorator->cache =& $cache;
  13170. $decorator->type = $cache->type;
  13171. return $decorator;
  13172. }
  13173. /**
  13174. * Cross-compatible clone substitute
  13175. * @return HTMLPurifier_DefinitionCache_Decorator
  13176. */
  13177. public function copy()
  13178. {
  13179. return new HTMLPurifier_DefinitionCache_Decorator();
  13180. }
  13181. /**
  13182. * @param HTMLPurifier_Definition $def
  13183. * @param HTMLPurifier_Config $config
  13184. * @return mixed
  13185. */
  13186. public function add($def, $config)
  13187. {
  13188. return $this->cache->add($def, $config);
  13189. }
  13190. /**
  13191. * @param HTMLPurifier_Definition $def
  13192. * @param HTMLPurifier_Config $config
  13193. * @return mixed
  13194. */
  13195. public function set($def, $config)
  13196. {
  13197. return $this->cache->set($def, $config);
  13198. }
  13199. /**
  13200. * @param HTMLPurifier_Definition $def
  13201. * @param HTMLPurifier_Config $config
  13202. * @return mixed
  13203. */
  13204. public function replace($def, $config)
  13205. {
  13206. return $this->cache->replace($def, $config);
  13207. }
  13208. /**
  13209. * @param HTMLPurifier_Config $config
  13210. * @return mixed
  13211. */
  13212. public function get($config)
  13213. {
  13214. return $this->cache->get($config);
  13215. }
  13216. /**
  13217. * @param HTMLPurifier_Config $config
  13218. * @return mixed
  13219. */
  13220. public function remove($config)
  13221. {
  13222. return $this->cache->remove($config);
  13223. }
  13224. /**
  13225. * @param HTMLPurifier_Config $config
  13226. * @return mixed
  13227. */
  13228. public function flush($config)
  13229. {
  13230. return $this->cache->flush($config);
  13231. }
  13232. /**
  13233. * @param HTMLPurifier_Config $config
  13234. * @return mixed
  13235. */
  13236. public function cleanup($config)
  13237. {
  13238. return $this->cache->cleanup($config);
  13239. }
  13240. }
  13241. /**
  13242. * Null cache object to use when no caching is on.
  13243. */
  13244. class HTMLPurifier_DefinitionCache_Null extends HTMLPurifier_DefinitionCache
  13245. {
  13246. /**
  13247. * @param HTMLPurifier_Definition $def
  13248. * @param HTMLPurifier_Config $config
  13249. * @return bool
  13250. */
  13251. public function add($def, $config)
  13252. {
  13253. return false;
  13254. }
  13255. /**
  13256. * @param HTMLPurifier_Definition $def
  13257. * @param HTMLPurifier_Config $config
  13258. * @return bool
  13259. */
  13260. public function set($def, $config)
  13261. {
  13262. return false;
  13263. }
  13264. /**
  13265. * @param HTMLPurifier_Definition $def
  13266. * @param HTMLPurifier_Config $config
  13267. * @return bool
  13268. */
  13269. public function replace($def, $config)
  13270. {
  13271. return false;
  13272. }
  13273. /**
  13274. * @param HTMLPurifier_Config $config
  13275. * @return bool
  13276. */
  13277. public function remove($config)
  13278. {
  13279. return false;
  13280. }
  13281. /**
  13282. * @param HTMLPurifier_Config $config
  13283. * @return bool
  13284. */
  13285. public function get($config)
  13286. {
  13287. return false;
  13288. }
  13289. /**
  13290. * @param HTMLPurifier_Config $config
  13291. * @return bool
  13292. */
  13293. public function flush($config)
  13294. {
  13295. return false;
  13296. }
  13297. /**
  13298. * @param HTMLPurifier_Config $config
  13299. * @return bool
  13300. */
  13301. public function cleanup($config)
  13302. {
  13303. return false;
  13304. }
  13305. }
  13306. class HTMLPurifier_DefinitionCache_Serializer extends HTMLPurifier_DefinitionCache
  13307. {
  13308. /**
  13309. * @param HTMLPurifier_Definition $def
  13310. * @param HTMLPurifier_Config $config
  13311. * @return int|bool
  13312. */
  13313. public function add($def, $config)
  13314. {
  13315. if (!$this->checkDefType($def)) {
  13316. return;
  13317. }
  13318. $file = $this->generateFilePath($config);
  13319. if (file_exists($file)) {
  13320. return false;
  13321. }
  13322. if (!$this->_prepareDir($config)) {
  13323. return false;
  13324. }
  13325. return $this->_write($file, serialize($def), $config);
  13326. }
  13327. /**
  13328. * @param HTMLPurifier_Definition $def
  13329. * @param HTMLPurifier_Config $config
  13330. * @return int|bool
  13331. */
  13332. public function set($def, $config)
  13333. {
  13334. if (!$this->checkDefType($def)) {
  13335. return;
  13336. }
  13337. $file = $this->generateFilePath($config);
  13338. if (!$this->_prepareDir($config)) {
  13339. return false;
  13340. }
  13341. return $this->_write($file, serialize($def), $config);
  13342. }
  13343. /**
  13344. * @param HTMLPurifier_Definition $def
  13345. * @param HTMLPurifier_Config $config
  13346. * @return int|bool
  13347. */
  13348. public function replace($def, $config)
  13349. {
  13350. if (!$this->checkDefType($def)) {
  13351. return;
  13352. }
  13353. $file = $this->generateFilePath($config);
  13354. if (!file_exists($file)) {
  13355. return false;
  13356. }
  13357. if (!$this->_prepareDir($config)) {
  13358. return false;
  13359. }
  13360. return $this->_write($file, serialize($def), $config);
  13361. }
  13362. /**
  13363. * @param HTMLPurifier_Config $config
  13364. * @return bool|HTMLPurifier_Config
  13365. */
  13366. public function get($config)
  13367. {
  13368. $file = $this->generateFilePath($config);
  13369. if (!file_exists($file)) {
  13370. return false;
  13371. }
  13372. return unserialize(file_get_contents($file));
  13373. }
  13374. /**
  13375. * @param HTMLPurifier_Config $config
  13376. * @return bool
  13377. */
  13378. public function remove($config)
  13379. {
  13380. $file = $this->generateFilePath($config);
  13381. if (!file_exists($file)) {
  13382. return false;
  13383. }
  13384. return unlink($file);
  13385. }
  13386. /**
  13387. * @param HTMLPurifier_Config $config
  13388. * @return bool
  13389. */
  13390. public function flush($config)
  13391. {
  13392. if (!$this->_prepareDir($config)) {
  13393. return false;
  13394. }
  13395. $dir = $this->generateDirectoryPath($config);
  13396. $dh = opendir($dir);
  13397. // Apparently, on some versions of PHP, readdir will return
  13398. // an empty string if you pass an invalid argument to readdir.
  13399. // So you need this test. See #49.
  13400. if (false === $dh) {
  13401. return false;
  13402. }
  13403. while (false !== ($filename = readdir($dh))) {
  13404. if (empty($filename)) {
  13405. continue;
  13406. }
  13407. if ($filename[0] === '.') {
  13408. continue;
  13409. }
  13410. unlink($dir . '/' . $filename);
  13411. }
  13412. return true;
  13413. }
  13414. /**
  13415. * @param HTMLPurifier_Config $config
  13416. * @return bool
  13417. */
  13418. public function cleanup($config)
  13419. {
  13420. if (!$this->_prepareDir($config)) {
  13421. return false;
  13422. }
  13423. $dir = $this->generateDirectoryPath($config);
  13424. $dh = opendir($dir);
  13425. // See #49 (and above).
  13426. if (false === $dh) {
  13427. return false;
  13428. }
  13429. while (false !== ($filename = readdir($dh))) {
  13430. if (empty($filename)) {
  13431. continue;
  13432. }
  13433. if ($filename[0] === '.') {
  13434. continue;
  13435. }
  13436. $key = substr($filename, 0, strlen($filename) - 4);
  13437. if ($this->isOld($key, $config)) {
  13438. unlink($dir . '/' . $filename);
  13439. }
  13440. }
  13441. return true;
  13442. }
  13443. /**
  13444. * Generates the file path to the serial file corresponding to
  13445. * the configuration and definition name
  13446. * @param HTMLPurifier_Config $config
  13447. * @return string
  13448. * @todo Make protected
  13449. */
  13450. public function generateFilePath($config)
  13451. {
  13452. $key = $this->generateKey($config);
  13453. return $this->generateDirectoryPath($config) . '/' . $key . '.ser';
  13454. }
  13455. /**
  13456. * Generates the path to the directory contain this cache's serial files
  13457. * @param HTMLPurifier_Config $config
  13458. * @return string
  13459. * @note No trailing slash
  13460. * @todo Make protected
  13461. */
  13462. public function generateDirectoryPath($config)
  13463. {
  13464. $base = $this->generateBaseDirectoryPath($config);
  13465. return $base . '/' . $this->type;
  13466. }
  13467. /**
  13468. * Generates path to base directory that contains all definition type
  13469. * serials
  13470. * @param HTMLPurifier_Config $config
  13471. * @return mixed|string
  13472. * @todo Make protected
  13473. */
  13474. public function generateBaseDirectoryPath($config)
  13475. {
  13476. $base = $config->get('Cache.SerializerPath');
  13477. $base = is_null($base) ? HTMLPURIFIER_PREFIX . '/HTMLPurifier/DefinitionCache/Serializer' : $base;
  13478. return $base;
  13479. }
  13480. /**
  13481. * Convenience wrapper function for file_put_contents
  13482. * @param string $file File name to write to
  13483. * @param string $data Data to write into file
  13484. * @param HTMLPurifier_Config $config
  13485. * @return int|bool Number of bytes written if success, or false if failure.
  13486. */
  13487. private function _write($file, $data, $config)
  13488. {
  13489. $result = file_put_contents($file, $data);
  13490. if ($result !== false) {
  13491. // set permissions of the new file (no execute)
  13492. $chmod = $config->get('Cache.SerializerPermissions');
  13493. if ($chmod === null) {
  13494. // don't do anything
  13495. } else {
  13496. $chmod = $chmod & 0666;
  13497. chmod($file, $chmod);
  13498. }
  13499. }
  13500. return $result;
  13501. }
  13502. /**
  13503. * Prepares the directory that this type stores the serials in
  13504. * @param HTMLPurifier_Config $config
  13505. * @return bool True if successful
  13506. */
  13507. private function _prepareDir($config)
  13508. {
  13509. $directory = $this->generateDirectoryPath($config);
  13510. $chmod = $config->get('Cache.SerializerPermissions');
  13511. if (!is_dir($directory)) {
  13512. $base = $this->generateBaseDirectoryPath($config);
  13513. if (!is_dir($base)) {
  13514. trigger_error(
  13515. 'Base directory ' . $base . ' does not exist,
  13516. please create or change using %Cache.SerializerPath',
  13517. E_USER_WARNING
  13518. );
  13519. return false;
  13520. } elseif (!$this->_testPermissions($base, $chmod)) {
  13521. return false;
  13522. }
  13523. if ($chmod === null) {
  13524. trigger_error(
  13525. 'Base directory ' . $base . ' does not exist,
  13526. please create or change using %Cache.SerializerPath',
  13527. E_USER_WARNING
  13528. );
  13529. return false;
  13530. }
  13531. if ($chmod !== null) {
  13532. mkdir($directory, $chmod);
  13533. } else {
  13534. mkdir($directory);
  13535. }
  13536. if (!$this->_testPermissions($directory, $chmod)) {
  13537. trigger_error(
  13538. 'Base directory ' . $base . ' does not exist,
  13539. please create or change using %Cache.SerializerPath',
  13540. E_USER_WARNING
  13541. );
  13542. return false;
  13543. }
  13544. } elseif (!$this->_testPermissions($directory, $chmod)) {
  13545. return false;
  13546. }
  13547. return true;
  13548. }
  13549. /**
  13550. * Tests permissions on a directory and throws out friendly
  13551. * error messages and attempts to chmod it itself if possible
  13552. * @param string $dir Directory path
  13553. * @param int $chmod Permissions
  13554. * @return bool True if directory is writable
  13555. */
  13556. private function _testPermissions($dir, $chmod)
  13557. {
  13558. // early abort, if it is writable, everything is hunky-dory
  13559. if (is_writable($dir)) {
  13560. return true;
  13561. }
  13562. if (!is_dir($dir)) {
  13563. // generally, you'll want to handle this beforehand
  13564. // so a more specific error message can be given
  13565. trigger_error(
  13566. 'Directory ' . $dir . ' does not exist',
  13567. E_USER_WARNING
  13568. );
  13569. return false;
  13570. }
  13571. if (function_exists('posix_getuid') && $chmod !== null) {
  13572. // POSIX system, we can give more specific advice
  13573. if (fileowner($dir) === posix_getuid()) {
  13574. // we can chmod it ourselves
  13575. $chmod = $chmod | 0700;
  13576. if (chmod($dir, $chmod)) {
  13577. return true;
  13578. }
  13579. } elseif (filegroup($dir) === posix_getgid()) {
  13580. $chmod = $chmod | 0070;
  13581. } else {
  13582. // PHP's probably running as nobody, so we'll
  13583. // need to give global permissions
  13584. $chmod = $chmod | 0777;
  13585. }
  13586. trigger_error(
  13587. 'Directory ' . $dir . ' not writable, ' .
  13588. 'please chmod to ' . decoct($chmod),
  13589. E_USER_WARNING
  13590. );
  13591. } else {
  13592. // generic error message
  13593. trigger_error(
  13594. 'Directory ' . $dir . ' not writable, ' .
  13595. 'please alter file permissions',
  13596. E_USER_WARNING
  13597. );
  13598. }
  13599. return false;
  13600. }
  13601. }
  13602. /**
  13603. * Definition cache decorator class that cleans up the cache
  13604. * whenever there is a cache miss.
  13605. */
  13606. class HTMLPurifier_DefinitionCache_Decorator_Cleanup extends HTMLPurifier_DefinitionCache_Decorator
  13607. {
  13608. /**
  13609. * @type string
  13610. */
  13611. public $name = 'Cleanup';
  13612. /**
  13613. * @return HTMLPurifier_DefinitionCache_Decorator_Cleanup
  13614. */
  13615. public function copy()
  13616. {
  13617. return new HTMLPurifier_DefinitionCache_Decorator_Cleanup();
  13618. }
  13619. /**
  13620. * @param HTMLPurifier_Definition $def
  13621. * @param HTMLPurifier_Config $config
  13622. * @return mixed
  13623. */
  13624. public function add($def, $config)
  13625. {
  13626. $status = parent::add($def, $config);
  13627. if (!$status) {
  13628. parent::cleanup($config);
  13629. }
  13630. return $status;
  13631. }
  13632. /**
  13633. * @param HTMLPurifier_Definition $def
  13634. * @param HTMLPurifier_Config $config
  13635. * @return mixed
  13636. */
  13637. public function set($def, $config)
  13638. {
  13639. $status = parent::set($def, $config);
  13640. if (!$status) {
  13641. parent::cleanup($config);
  13642. }
  13643. return $status;
  13644. }
  13645. /**
  13646. * @param HTMLPurifier_Definition $def
  13647. * @param HTMLPurifier_Config $config
  13648. * @return mixed
  13649. */
  13650. public function replace($def, $config)
  13651. {
  13652. $status = parent::replace($def, $config);
  13653. if (!$status) {
  13654. parent::cleanup($config);
  13655. }
  13656. return $status;
  13657. }
  13658. /**
  13659. * @param HTMLPurifier_Config $config
  13660. * @return mixed
  13661. */
  13662. public function get($config)
  13663. {
  13664. $ret = parent::get($config);
  13665. if (!$ret) {
  13666. parent::cleanup($config);
  13667. }
  13668. return $ret;
  13669. }
  13670. }
  13671. /**
  13672. * Definition cache decorator class that saves all cache retrievals
  13673. * to PHP's memory; good for unit tests or circumstances where
  13674. * there are lots of configuration objects floating around.
  13675. */
  13676. class HTMLPurifier_DefinitionCache_Decorator_Memory extends HTMLPurifier_DefinitionCache_Decorator
  13677. {
  13678. /**
  13679. * @type array
  13680. */
  13681. protected $definitions;
  13682. /**
  13683. * @type string
  13684. */
  13685. public $name = 'Memory';
  13686. /**
  13687. * @return HTMLPurifier_DefinitionCache_Decorator_Memory
  13688. */
  13689. public function copy()
  13690. {
  13691. return new HTMLPurifier_DefinitionCache_Decorator_Memory();
  13692. }
  13693. /**
  13694. * @param HTMLPurifier_Definition $def
  13695. * @param HTMLPurifier_Config $config
  13696. * @return mixed
  13697. */
  13698. public function add($def, $config)
  13699. {
  13700. $status = parent::add($def, $config);
  13701. if ($status) {
  13702. $this->definitions[$this->generateKey($config)] = $def;
  13703. }
  13704. return $status;
  13705. }
  13706. /**
  13707. * @param HTMLPurifier_Definition $def
  13708. * @param HTMLPurifier_Config $config
  13709. * @return mixed
  13710. */
  13711. public function set($def, $config)
  13712. {
  13713. $status = parent::set($def, $config);
  13714. if ($status) {
  13715. $this->definitions[$this->generateKey($config)] = $def;
  13716. }
  13717. return $status;
  13718. }
  13719. /**
  13720. * @param HTMLPurifier_Definition $def
  13721. * @param HTMLPurifier_Config $config
  13722. * @return mixed
  13723. */
  13724. public function replace($def, $config)
  13725. {
  13726. $status = parent::replace($def, $config);
  13727. if ($status) {
  13728. $this->definitions[$this->generateKey($config)] = $def;
  13729. }
  13730. return $status;
  13731. }
  13732. /**
  13733. * @param HTMLPurifier_Config $config
  13734. * @return mixed
  13735. */
  13736. public function get($config)
  13737. {
  13738. $key = $this->generateKey($config);
  13739. if (isset($this->definitions[$key])) {
  13740. return $this->definitions[$key];
  13741. }
  13742. $this->definitions[$key] = parent::get($config);
  13743. return $this->definitions[$key];
  13744. }
  13745. }
  13746. /**
  13747. * XHTML 1.1 Bi-directional Text Module, defines elements that
  13748. * declare directionality of content. Text Extension Module.
  13749. */
  13750. class HTMLPurifier_HTMLModule_Bdo extends HTMLPurifier_HTMLModule
  13751. {
  13752. /**
  13753. * @type string
  13754. */
  13755. public $name = 'Bdo';
  13756. /**
  13757. * @type array
  13758. */
  13759. public $attr_collections = array(
  13760. 'I18N' => array('dir' => false)
  13761. );
  13762. /**
  13763. * @param HTMLPurifier_Config $config
  13764. */
  13765. public function setup($config)
  13766. {
  13767. $bdo = $this->addElement(
  13768. 'bdo',
  13769. 'Inline',
  13770. 'Inline',
  13771. array('Core', 'Lang'),
  13772. array(
  13773. 'dir' => 'Enum#ltr,rtl', // required
  13774. // The Abstract Module specification has the attribute
  13775. // inclusions wrong for bdo: bdo allows Lang
  13776. )
  13777. );
  13778. $bdo->attr_transform_post[] = new HTMLPurifier_AttrTransform_BdoDir();
  13779. $this->attr_collections['I18N']['dir'] = 'Enum#ltr,rtl';
  13780. }
  13781. }
  13782. class HTMLPurifier_HTMLModule_CommonAttributes extends HTMLPurifier_HTMLModule
  13783. {
  13784. /**
  13785. * @type string
  13786. */
  13787. public $name = 'CommonAttributes';
  13788. /**
  13789. * @type array
  13790. */
  13791. public $attr_collections = array(
  13792. 'Core' => array(
  13793. 0 => array('Style'),
  13794. // 'xml:space' => false,
  13795. 'class' => 'Class',
  13796. 'id' => 'ID',
  13797. 'title' => 'CDATA',
  13798. ),
  13799. 'Lang' => array(),
  13800. 'I18N' => array(
  13801. 0 => array('Lang'), // proprietary, for xml:lang/lang
  13802. ),
  13803. 'Common' => array(
  13804. 0 => array('Core', 'I18N')
  13805. )
  13806. );
  13807. }
  13808. /**
  13809. * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension
  13810. * Module.
  13811. */
  13812. class HTMLPurifier_HTMLModule_Edit extends HTMLPurifier_HTMLModule
  13813. {
  13814. /**
  13815. * @type string
  13816. */
  13817. public $name = 'Edit';
  13818. /**
  13819. * @param HTMLPurifier_Config $config
  13820. */
  13821. public function setup($config)
  13822. {
  13823. $contents = 'Chameleon: #PCDATA | Inline ! #PCDATA | Flow';
  13824. $attr = array(
  13825. 'cite' => 'URI',
  13826. // 'datetime' => 'Datetime', // not implemented
  13827. );
  13828. $this->addElement('del', 'Inline', $contents, 'Common', $attr);
  13829. $this->addElement('ins', 'Inline', $contents, 'Common', $attr);
  13830. }
  13831. // HTML 4.01 specifies that ins/del must not contain block
  13832. // elements when used in an inline context, chameleon is
  13833. // a complicated workaround to acheive this effect
  13834. // Inline context ! Block context (exclamation mark is
  13835. // separator, see getChildDef for parsing)
  13836. /**
  13837. * @type bool
  13838. */
  13839. public $defines_child_def = true;
  13840. /**
  13841. * @param HTMLPurifier_ElementDef $def
  13842. * @return HTMLPurifier_ChildDef_Chameleon
  13843. */
  13844. public function getChildDef($def)
  13845. {
  13846. if ($def->content_model_type != 'chameleon') {
  13847. return false;
  13848. }
  13849. $value = explode('!', $def->content_model);
  13850. return new HTMLPurifier_ChildDef_Chameleon($value[0], $value[1]);
  13851. }
  13852. }
  13853. /**
  13854. * XHTML 1.1 Forms module, defines all form-related elements found in HTML 4.
  13855. */
  13856. class HTMLPurifier_HTMLModule_Forms extends HTMLPurifier_HTMLModule
  13857. {
  13858. /**
  13859. * @type string
  13860. */
  13861. public $name = 'Forms';
  13862. /**
  13863. * @type bool
  13864. */
  13865. public $safe = false;
  13866. /**
  13867. * @type array
  13868. */
  13869. public $content_sets = array(
  13870. 'Block' => 'Form',
  13871. 'Inline' => 'Formctrl',
  13872. );
  13873. /**
  13874. * @param HTMLPurifier_Config $config
  13875. */
  13876. public function setup($config)
  13877. {
  13878. $form = $this->addElement(
  13879. 'form',
  13880. 'Form',
  13881. 'Required: Heading | List | Block | fieldset',
  13882. 'Common',
  13883. array(
  13884. 'accept' => 'ContentTypes',
  13885. 'accept-charset' => 'Charsets',
  13886. 'action*' => 'URI',
  13887. 'method' => 'Enum#get,post',
  13888. // really ContentType, but these two are the only ones used today
  13889. 'enctype' => 'Enum#application/x-www-form-urlencoded,multipart/form-data',
  13890. )
  13891. );
  13892. $form->excludes = array('form' => true);
  13893. $input = $this->addElement(
  13894. 'input',
  13895. 'Formctrl',
  13896. 'Empty',
  13897. 'Common',
  13898. array(
  13899. 'accept' => 'ContentTypes',
  13900. 'accesskey' => 'Character',
  13901. 'alt' => 'Text',
  13902. 'checked' => 'Bool#checked',
  13903. 'disabled' => 'Bool#disabled',
  13904. 'maxlength' => 'Number',
  13905. 'name' => 'CDATA',
  13906. 'readonly' => 'Bool#readonly',
  13907. 'size' => 'Number',
  13908. 'src' => 'URI#embedded',
  13909. 'tabindex' => 'Number',
  13910. 'type' => 'Enum#text,password,checkbox,button,radio,submit,reset,file,hidden,image',
  13911. 'value' => 'CDATA',
  13912. )
  13913. );
  13914. $input->attr_transform_post[] = new HTMLPurifier_AttrTransform_Input();
  13915. $this->addElement(
  13916. 'select',
  13917. 'Formctrl',
  13918. 'Required: optgroup | option',
  13919. 'Common',
  13920. array(
  13921. 'disabled' => 'Bool#disabled',
  13922. 'multiple' => 'Bool#multiple',
  13923. 'name' => 'CDATA',
  13924. 'size' => 'Number',
  13925. 'tabindex' => 'Number',
  13926. )
  13927. );
  13928. $this->addElement(
  13929. 'option',
  13930. false,
  13931. 'Optional: #PCDATA',
  13932. 'Common',
  13933. array(
  13934. 'disabled' => 'Bool#disabled',
  13935. 'label' => 'Text',
  13936. 'selected' => 'Bool#selected',
  13937. 'value' => 'CDATA',
  13938. )
  13939. );
  13940. // It's illegal for there to be more than one selected, but not
  13941. // be multiple. Also, no selected means undefined behavior. This might
  13942. // be difficult to implement; perhaps an injector, or a context variable.
  13943. $textarea = $this->addElement(
  13944. 'textarea',
  13945. 'Formctrl',
  13946. 'Optional: #PCDATA',
  13947. 'Common',
  13948. array(
  13949. 'accesskey' => 'Character',
  13950. 'cols*' => 'Number',
  13951. 'disabled' => 'Bool#disabled',
  13952. 'name' => 'CDATA',
  13953. 'readonly' => 'Bool#readonly',
  13954. 'rows*' => 'Number',
  13955. 'tabindex' => 'Number',
  13956. )
  13957. );
  13958. $textarea->attr_transform_pre[] = new HTMLPurifier_AttrTransform_Textarea();
  13959. $button = $this->addElement(
  13960. 'button',
  13961. 'Formctrl',
  13962. 'Optional: #PCDATA | Heading | List | Block | Inline',
  13963. 'Common',
  13964. array(
  13965. 'accesskey' => 'Character',
  13966. 'disabled' => 'Bool#disabled',
  13967. 'name' => 'CDATA',
  13968. 'tabindex' => 'Number',
  13969. 'type' => 'Enum#button,submit,reset',
  13970. 'value' => 'CDATA',
  13971. )
  13972. );
  13973. // For exclusions, ideally we'd specify content sets, not literal elements
  13974. $button->excludes = $this->makeLookup(
  13975. 'form',
  13976. 'fieldset', // Form
  13977. 'input',
  13978. 'select',
  13979. 'textarea',
  13980. 'label',
  13981. 'button', // Formctrl
  13982. 'a', // as per HTML 4.01 spec, this is omitted by modularization
  13983. 'isindex',
  13984. 'iframe' // legacy items
  13985. );
  13986. // Extra exclusion: img usemap="" is not permitted within this element.
  13987. // We'll omit this for now, since we don't have any good way of
  13988. // indicating it yet.
  13989. // This is HIGHLY user-unfriendly; we need a custom child-def for this
  13990. $this->addElement('fieldset', 'Form', 'Custom: (#WS?,legend,(Flow|#PCDATA)*)', 'Common');
  13991. $label = $this->addElement(
  13992. 'label',
  13993. 'Formctrl',
  13994. 'Optional: #PCDATA | Inline',
  13995. 'Common',
  13996. array(
  13997. 'accesskey' => 'Character',
  13998. // 'for' => 'IDREF', // IDREF not implemented, cannot allow
  13999. )
  14000. );
  14001. $label->excludes = array('label' => true);
  14002. $this->addElement(
  14003. 'legend',
  14004. false,
  14005. 'Optional: #PCDATA | Inline',
  14006. 'Common',
  14007. array(
  14008. 'accesskey' => 'Character',
  14009. )
  14010. );
  14011. $this->addElement(
  14012. 'optgroup',
  14013. false,
  14014. 'Required: option',
  14015. 'Common',
  14016. array(
  14017. 'disabled' => 'Bool#disabled',
  14018. 'label*' => 'Text',
  14019. )
  14020. );
  14021. // Don't forget an injector for <isindex>. This one's a little complex
  14022. // because it maps to multiple elements.
  14023. }
  14024. }
  14025. /**
  14026. * XHTML 1.1 Hypertext Module, defines hypertext links. Core Module.
  14027. */
  14028. class HTMLPurifier_HTMLModule_Hypertext extends HTMLPurifier_HTMLModule
  14029. {
  14030. /**
  14031. * @type string
  14032. */
  14033. public $name = 'Hypertext';
  14034. /**
  14035. * @param HTMLPurifier_Config $config
  14036. */
  14037. public function setup($config)
  14038. {
  14039. $a = $this->addElement(
  14040. 'a',
  14041. 'Inline',
  14042. 'Inline',
  14043. 'Common',
  14044. array(
  14045. // 'accesskey' => 'Character',
  14046. // 'charset' => 'Charset',
  14047. 'href' => 'URI',
  14048. // 'hreflang' => 'LanguageCode',
  14049. 'rel' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rel'),
  14050. 'rev' => new HTMLPurifier_AttrDef_HTML_LinkTypes('rev'),
  14051. // 'tabindex' => 'Number',
  14052. // 'type' => 'ContentType',
  14053. )
  14054. );
  14055. $a->formatting = true;
  14056. $a->excludes = array('a' => true);
  14057. }
  14058. }
  14059. /**
  14060. * XHTML 1.1 Iframe Module provides inline frames.
  14061. *
  14062. * @note This module is not considered safe unless an Iframe
  14063. * whitelisting mechanism is specified. Currently, the only
  14064. * such mechanism is %URL.SafeIframeRegexp
  14065. */
  14066. class HTMLPurifier_HTMLModule_Iframe extends HTMLPurifier_HTMLModule
  14067. {
  14068. /**
  14069. * @type string
  14070. */
  14071. public $name = 'Iframe';
  14072. /**
  14073. * @type bool
  14074. */
  14075. public $safe = false;
  14076. /**
  14077. * @param HTMLPurifier_Config $config
  14078. */
  14079. public function setup($config)
  14080. {
  14081. if ($config->get('HTML.SafeIframe')) {
  14082. $this->safe = true;
  14083. }
  14084. $this->addElement(
  14085. 'iframe',
  14086. 'Inline',
  14087. 'Flow',
  14088. 'Common',
  14089. array(
  14090. 'src' => 'URI#embedded',
  14091. 'width' => 'Length',
  14092. 'height' => 'Length',
  14093. 'name' => 'ID',
  14094. 'scrolling' => 'Enum#yes,no,auto',
  14095. 'frameborder' => 'Enum#0,1',
  14096. 'longdesc' => 'URI',
  14097. 'marginheight' => 'Pixels',
  14098. 'marginwidth' => 'Pixels',
  14099. )
  14100. );
  14101. }
  14102. }
  14103. /**
  14104. * XHTML 1.1 Image Module provides basic image embedding.
  14105. * @note There is specialized code for removing empty images in
  14106. * HTMLPurifier_Strategy_RemoveForeignElements
  14107. */
  14108. class HTMLPurifier_HTMLModule_Image extends HTMLPurifier_HTMLModule
  14109. {
  14110. /**
  14111. * @type string
  14112. */
  14113. public $name = 'Image';
  14114. /**
  14115. * @param HTMLPurifier_Config $config
  14116. */
  14117. public function setup($config)
  14118. {
  14119. $max = $config->get('HTML.MaxImgLength');
  14120. $img = $this->addElement(
  14121. 'img',
  14122. 'Inline',
  14123. 'Empty',
  14124. 'Common',
  14125. array(
  14126. 'alt*' => 'Text',
  14127. // According to the spec, it's Length, but percents can
  14128. // be abused, so we allow only Pixels.
  14129. 'height' => 'Pixels#' . $max,
  14130. 'width' => 'Pixels#' . $max,
  14131. 'longdesc' => 'URI',
  14132. 'src*' => new HTMLPurifier_AttrDef_URI(true), // embedded
  14133. )
  14134. );
  14135. if ($max === null || $config->get('HTML.Trusted')) {
  14136. $img->attr['height'] =
  14137. $img->attr['width'] = 'Length';
  14138. }
  14139. // kind of strange, but splitting things up would be inefficient
  14140. $img->attr_transform_pre[] =
  14141. $img->attr_transform_post[] =
  14142. new HTMLPurifier_AttrTransform_ImgRequired();
  14143. }
  14144. }
  14145. /**
  14146. * XHTML 1.1 Legacy module defines elements that were previously
  14147. * deprecated.
  14148. *
  14149. * @note Not all legacy elements have been implemented yet, which
  14150. * is a bit of a reverse problem as compared to browsers! In
  14151. * addition, this legacy module may implement a bit more than
  14152. * mandated by XHTML 1.1.
  14153. *
  14154. * This module can be used in combination with TransformToStrict in order
  14155. * to transform as many deprecated elements as possible, but retain
  14156. * questionably deprecated elements that do not have good alternatives
  14157. * as well as transform elements that don't have an implementation.
  14158. * See docs/ref-strictness.txt for more details.
  14159. */
  14160. class HTMLPurifier_HTMLModule_Legacy extends HTMLPurifier_HTMLModule
  14161. {
  14162. /**
  14163. * @type string
  14164. */
  14165. public $name = 'Legacy';
  14166. /**
  14167. * @param HTMLPurifier_Config $config
  14168. */
  14169. public function setup($config)
  14170. {
  14171. $this->addElement(
  14172. 'basefont',
  14173. 'Inline',
  14174. 'Empty',
  14175. null,
  14176. array(
  14177. 'color' => 'Color',
  14178. 'face' => 'Text', // extremely broad, we should
  14179. 'size' => 'Text', // tighten it
  14180. 'id' => 'ID'
  14181. )
  14182. );
  14183. $this->addElement('center', 'Block', 'Flow', 'Common');
  14184. $this->addElement(
  14185. 'dir',
  14186. 'Block',
  14187. 'Required: li',
  14188. 'Common',
  14189. array(
  14190. 'compact' => 'Bool#compact'
  14191. )
  14192. );
  14193. $this->addElement(
  14194. 'font',
  14195. 'Inline',
  14196. 'Inline',
  14197. array('Core', 'I18N'),
  14198. array(
  14199. 'color' => 'Color',
  14200. 'face' => 'Text', // extremely broad, we should
  14201. 'size' => 'Text', // tighten it
  14202. )
  14203. );
  14204. $this->addElement(
  14205. 'menu',
  14206. 'Block',
  14207. 'Required: li',
  14208. 'Common',
  14209. array(
  14210. 'compact' => 'Bool#compact'
  14211. )
  14212. );
  14213. $s = $this->addElement('s', 'Inline', 'Inline', 'Common');
  14214. $s->formatting = true;
  14215. $strike = $this->addElement('strike', 'Inline', 'Inline', 'Common');
  14216. $strike->formatting = true;
  14217. $u = $this->addElement('u', 'Inline', 'Inline', 'Common');
  14218. $u->formatting = true;
  14219. // setup modifications to old elements
  14220. $align = 'Enum#left,right,center,justify';
  14221. $address = $this->addBlankElement('address');
  14222. $address->content_model = 'Inline | #PCDATA | p';
  14223. $address->content_model_type = 'optional';
  14224. $address->child = false;
  14225. $blockquote = $this->addBlankElement('blockquote');
  14226. $blockquote->content_model = 'Flow | #PCDATA';
  14227. $blockquote->content_model_type = 'optional';
  14228. $blockquote->child = false;
  14229. $br = $this->addBlankElement('br');
  14230. $br->attr['clear'] = 'Enum#left,all,right,none';
  14231. $caption = $this->addBlankElement('caption');
  14232. $caption->attr['align'] = 'Enum#top,bottom,left,right';
  14233. $div = $this->addBlankElement('div');
  14234. $div->attr['align'] = $align;
  14235. $dl = $this->addBlankElement('dl');
  14236. $dl->attr['compact'] = 'Bool#compact';
  14237. for ($i = 1; $i <= 6; $i++) {
  14238. $h = $this->addBlankElement("h$i");
  14239. $h->attr['align'] = $align;
  14240. }
  14241. $hr = $this->addBlankElement('hr');
  14242. $hr->attr['align'] = $align;
  14243. $hr->attr['noshade'] = 'Bool#noshade';
  14244. $hr->attr['size'] = 'Pixels';
  14245. $hr->attr['width'] = 'Length';
  14246. $img = $this->addBlankElement('img');
  14247. $img->attr['align'] = 'IAlign';
  14248. $img->attr['border'] = 'Pixels';
  14249. $img->attr['hspace'] = 'Pixels';
  14250. $img->attr['vspace'] = 'Pixels';
  14251. // figure out this integer business
  14252. $li = $this->addBlankElement('li');
  14253. $li->attr['value'] = new HTMLPurifier_AttrDef_Integer();
  14254. $li->attr['type'] = 'Enum#s:1,i,I,a,A,disc,square,circle';
  14255. $ol = $this->addBlankElement('ol');
  14256. $ol->attr['compact'] = 'Bool#compact';
  14257. $ol->attr['start'] = new HTMLPurifier_AttrDef_Integer();
  14258. $ol->attr['type'] = 'Enum#s:1,i,I,a,A';
  14259. $p = $this->addBlankElement('p');
  14260. $p->attr['align'] = $align;
  14261. $pre = $this->addBlankElement('pre');
  14262. $pre->attr['width'] = 'Number';
  14263. // script omitted
  14264. $table = $this->addBlankElement('table');
  14265. $table->attr['align'] = 'Enum#left,center,right';
  14266. $table->attr['bgcolor'] = 'Color';
  14267. $tr = $this->addBlankElement('tr');
  14268. $tr->attr['bgcolor'] = 'Color';
  14269. $th = $this->addBlankElement('th');
  14270. $th->attr['bgcolor'] = 'Color';
  14271. $th->attr['height'] = 'Length';
  14272. $th->attr['nowrap'] = 'Bool#nowrap';
  14273. $th->attr['width'] = 'Length';
  14274. $td = $this->addBlankElement('td');
  14275. $td->attr['bgcolor'] = 'Color';
  14276. $td->attr['height'] = 'Length';
  14277. $td->attr['nowrap'] = 'Bool#nowrap';
  14278. $td->attr['width'] = 'Length';
  14279. $ul = $this->addBlankElement('ul');
  14280. $ul->attr['compact'] = 'Bool#compact';
  14281. $ul->attr['type'] = 'Enum#square,disc,circle';
  14282. // "safe" modifications to "unsafe" elements
  14283. // WARNING: If you want to add support for an unsafe, legacy
  14284. // attribute, make a new TrustedLegacy module with the trusted
  14285. // bit set appropriately
  14286. $form = $this->addBlankElement('form');
  14287. $form->content_model = 'Flow | #PCDATA';
  14288. $form->content_model_type = 'optional';
  14289. $form->attr['target'] = 'FrameTarget';
  14290. $input = $this->addBlankElement('input');
  14291. $input->attr['align'] = 'IAlign';
  14292. $legend = $this->addBlankElement('legend');
  14293. $legend->attr['align'] = 'LAlign';
  14294. }
  14295. }
  14296. /**
  14297. * XHTML 1.1 List Module, defines list-oriented elements. Core Module.
  14298. */
  14299. class HTMLPurifier_HTMLModule_List extends HTMLPurifier_HTMLModule
  14300. {
  14301. /**
  14302. * @type string
  14303. */
  14304. public $name = 'List';
  14305. // According to the abstract schema, the List content set is a fully formed
  14306. // one or more expr, but it invariably occurs in an optional declaration
  14307. // so we're not going to do that subtlety. It might cause trouble
  14308. // if a user defines "List" and expects that multiple lists are
  14309. // allowed to be specified, but then again, that's not very intuitive.
  14310. // Furthermore, the actual XML Schema may disagree. Regardless,
  14311. // we don't have support for such nested expressions without using
  14312. // the incredibly inefficient and draconic Custom ChildDef.
  14313. /**
  14314. * @type array
  14315. */
  14316. public $content_sets = array('Flow' => 'List');
  14317. /**
  14318. * @param HTMLPurifier_Config $config
  14319. */
  14320. public function setup($config)
  14321. {
  14322. $ol = $this->addElement('ol', 'List', new HTMLPurifier_ChildDef_List(), 'Common');
  14323. $ul = $this->addElement('ul', 'List', new HTMLPurifier_ChildDef_List(), 'Common');
  14324. // XXX The wrap attribute is handled by MakeWellFormed. This is all
  14325. // quite unsatisfactory, because we generated this
  14326. // *specifically* for lists, and now a big chunk of the handling
  14327. // is done properly by the List ChildDef. So actually, we just
  14328. // want enough information to make autoclosing work properly,
  14329. // and then hand off the tricky stuff to the ChildDef.
  14330. $ol->wrap = 'li';
  14331. $ul->wrap = 'li';
  14332. $this->addElement('dl', 'List', 'Required: dt | dd', 'Common');
  14333. $this->addElement('li', false, 'Flow', 'Common');
  14334. $this->addElement('dd', false, 'Flow', 'Common');
  14335. $this->addElement('dt', false, 'Inline', 'Common');
  14336. }
  14337. }
  14338. class HTMLPurifier_HTMLModule_Name extends HTMLPurifier_HTMLModule
  14339. {
  14340. /**
  14341. * @type string
  14342. */
  14343. public $name = 'Name';
  14344. /**
  14345. * @param HTMLPurifier_Config $config
  14346. */
  14347. public function setup($config)
  14348. {
  14349. $elements = array('a', 'applet', 'form', 'frame', 'iframe', 'img', 'map');
  14350. foreach ($elements as $name) {
  14351. $element = $this->addBlankElement($name);
  14352. $element->attr['name'] = 'CDATA';
  14353. if (!$config->get('HTML.Attr.Name.UseCDATA')) {
  14354. $element->attr_transform_post[] = new HTMLPurifier_AttrTransform_NameSync();
  14355. }
  14356. }
  14357. }
  14358. }
  14359. /**
  14360. * Module adds the nofollow attribute transformation to a tags. It
  14361. * is enabled by HTML.Nofollow
  14362. */
  14363. class HTMLPurifier_HTMLModule_Nofollow extends HTMLPurifier_HTMLModule
  14364. {
  14365. /**
  14366. * @type string
  14367. */
  14368. public $name = 'Nofollow';
  14369. /**
  14370. * @param HTMLPurifier_Config $config
  14371. */
  14372. public function setup($config)
  14373. {
  14374. $a = $this->addBlankElement('a');
  14375. $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_Nofollow();
  14376. }
  14377. }
  14378. class HTMLPurifier_HTMLModule_NonXMLCommonAttributes extends HTMLPurifier_HTMLModule
  14379. {
  14380. /**
  14381. * @type string
  14382. */
  14383. public $name = 'NonXMLCommonAttributes';
  14384. /**
  14385. * @type array
  14386. */
  14387. public $attr_collections = array(
  14388. 'Lang' => array(
  14389. 'lang' => 'LanguageCode',
  14390. )
  14391. );
  14392. }
  14393. /**
  14394. * XHTML 1.1 Object Module, defines elements for generic object inclusion
  14395. * @warning Users will commonly use <embed> to cater to legacy browsers: this
  14396. * module does not allow this sort of behavior
  14397. */
  14398. class HTMLPurifier_HTMLModule_Object extends HTMLPurifier_HTMLModule
  14399. {
  14400. /**
  14401. * @type string
  14402. */
  14403. public $name = 'Object';
  14404. /**
  14405. * @type bool
  14406. */
  14407. public $safe = false;
  14408. /**
  14409. * @param HTMLPurifier_Config $config
  14410. */
  14411. public function setup($config)
  14412. {
  14413. $this->addElement(
  14414. 'object',
  14415. 'Inline',
  14416. 'Optional: #PCDATA | Flow | param',
  14417. 'Common',
  14418. array(
  14419. 'archive' => 'URI',
  14420. 'classid' => 'URI',
  14421. 'codebase' => 'URI',
  14422. 'codetype' => 'Text',
  14423. 'data' => 'URI',
  14424. 'declare' => 'Bool#declare',
  14425. 'height' => 'Length',
  14426. 'name' => 'CDATA',
  14427. 'standby' => 'Text',
  14428. 'tabindex' => 'Number',
  14429. 'type' => 'ContentType',
  14430. 'width' => 'Length'
  14431. )
  14432. );
  14433. $this->addElement(
  14434. 'param',
  14435. false,
  14436. 'Empty',
  14437. null,
  14438. array(
  14439. 'id' => 'ID',
  14440. 'name*' => 'Text',
  14441. 'type' => 'Text',
  14442. 'value' => 'Text',
  14443. 'valuetype' => 'Enum#data,ref,object'
  14444. )
  14445. );
  14446. }
  14447. }
  14448. /**
  14449. * XHTML 1.1 Presentation Module, defines simple presentation-related
  14450. * markup. Text Extension Module.
  14451. * @note The official XML Schema and DTD specs further divide this into
  14452. * two modules:
  14453. * - Block Presentation (hr)
  14454. * - Inline Presentation (b, big, i, small, sub, sup, tt)
  14455. * We have chosen not to heed this distinction, as content_sets
  14456. * provides satisfactory disambiguation.
  14457. */
  14458. class HTMLPurifier_HTMLModule_Presentation extends HTMLPurifier_HTMLModule
  14459. {
  14460. /**
  14461. * @type string
  14462. */
  14463. public $name = 'Presentation';
  14464. /**
  14465. * @param HTMLPurifier_Config $config
  14466. */
  14467. public function setup($config)
  14468. {
  14469. $this->addElement('hr', 'Block', 'Empty', 'Common');
  14470. $this->addElement('sub', 'Inline', 'Inline', 'Common');
  14471. $this->addElement('sup', 'Inline', 'Inline', 'Common');
  14472. $b = $this->addElement('b', 'Inline', 'Inline', 'Common');
  14473. $b->formatting = true;
  14474. $big = $this->addElement('big', 'Inline', 'Inline', 'Common');
  14475. $big->formatting = true;
  14476. $i = $this->addElement('i', 'Inline', 'Inline', 'Common');
  14477. $i->formatting = true;
  14478. $small = $this->addElement('small', 'Inline', 'Inline', 'Common');
  14479. $small->formatting = true;
  14480. $tt = $this->addElement('tt', 'Inline', 'Inline', 'Common');
  14481. $tt->formatting = true;
  14482. }
  14483. }
  14484. /**
  14485. * Module defines proprietary tags and attributes in HTML.
  14486. * @warning If this module is enabled, standards-compliance is off!
  14487. */
  14488. class HTMLPurifier_HTMLModule_Proprietary extends HTMLPurifier_HTMLModule
  14489. {
  14490. /**
  14491. * @type string
  14492. */
  14493. public $name = 'Proprietary';
  14494. /**
  14495. * @param HTMLPurifier_Config $config
  14496. */
  14497. public function setup($config)
  14498. {
  14499. $this->addElement(
  14500. 'marquee',
  14501. 'Inline',
  14502. 'Flow',
  14503. 'Common',
  14504. array(
  14505. 'direction' => 'Enum#left,right,up,down',
  14506. 'behavior' => 'Enum#alternate',
  14507. 'width' => 'Length',
  14508. 'height' => 'Length',
  14509. 'scrolldelay' => 'Number',
  14510. 'scrollamount' => 'Number',
  14511. 'loop' => 'Number',
  14512. 'bgcolor' => 'Color',
  14513. 'hspace' => 'Pixels',
  14514. 'vspace' => 'Pixels',
  14515. )
  14516. );
  14517. }
  14518. }
  14519. /**
  14520. * XHTML 1.1 Ruby Annotation Module, defines elements that indicate
  14521. * short runs of text alongside base text for annotation or pronounciation.
  14522. */
  14523. class HTMLPurifier_HTMLModule_Ruby extends HTMLPurifier_HTMLModule
  14524. {
  14525. /**
  14526. * @type string
  14527. */
  14528. public $name = 'Ruby';
  14529. /**
  14530. * @param HTMLPurifier_Config $config
  14531. */
  14532. public function setup($config)
  14533. {
  14534. $this->addElement(
  14535. 'ruby',
  14536. 'Inline',
  14537. 'Custom: ((rb, (rt | (rp, rt, rp))) | (rbc, rtc, rtc?))',
  14538. 'Common'
  14539. );
  14540. $this->addElement('rbc', false, 'Required: rb', 'Common');
  14541. $this->addElement('rtc', false, 'Required: rt', 'Common');
  14542. $rb = $this->addElement('rb', false, 'Inline', 'Common');
  14543. $rb->excludes = array('ruby' => true);
  14544. $rt = $this->addElement('rt', false, 'Inline', 'Common', array('rbspan' => 'Number'));
  14545. $rt->excludes = array('ruby' => true);
  14546. $this->addElement('rp', false, 'Optional: #PCDATA', 'Common');
  14547. }
  14548. }
  14549. /**
  14550. * A "safe" embed module. See SafeObject. This is a proprietary element.
  14551. */
  14552. class HTMLPurifier_HTMLModule_SafeEmbed extends HTMLPurifier_HTMLModule
  14553. {
  14554. /**
  14555. * @type string
  14556. */
  14557. public $name = 'SafeEmbed';
  14558. /**
  14559. * @param HTMLPurifier_Config $config
  14560. */
  14561. public function setup($config)
  14562. {
  14563. $max = $config->get('HTML.MaxImgLength');
  14564. $embed = $this->addElement(
  14565. 'embed',
  14566. 'Inline',
  14567. 'Empty',
  14568. 'Common',
  14569. array(
  14570. 'src*' => 'URI#embedded',
  14571. 'type' => 'Enum#application/x-shockwave-flash',
  14572. 'width' => 'Pixels#' . $max,
  14573. 'height' => 'Pixels#' . $max,
  14574. 'allowscriptaccess' => 'Enum#never',
  14575. 'allownetworking' => 'Enum#internal',
  14576. 'flashvars' => 'Text',
  14577. 'wmode' => 'Enum#window,transparent,opaque',
  14578. 'name' => 'ID',
  14579. )
  14580. );
  14581. $embed->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeEmbed();
  14582. }
  14583. }
  14584. /**
  14585. * A "safe" object module. In theory, objects permitted by this module will
  14586. * be safe, and untrusted users can be allowed to embed arbitrary flash objects
  14587. * (maybe other types too, but only Flash is supported as of right now).
  14588. * Highly experimental.
  14589. */
  14590. class HTMLPurifier_HTMLModule_SafeObject extends HTMLPurifier_HTMLModule
  14591. {
  14592. /**
  14593. * @type string
  14594. */
  14595. public $name = 'SafeObject';
  14596. /**
  14597. * @param HTMLPurifier_Config $config
  14598. */
  14599. public function setup($config)
  14600. {
  14601. // These definitions are not intrinsically safe: the attribute transforms
  14602. // are a vital part of ensuring safety.
  14603. $max = $config->get('HTML.MaxImgLength');
  14604. $object = $this->addElement(
  14605. 'object',
  14606. 'Inline',
  14607. 'Optional: param | Flow | #PCDATA',
  14608. 'Common',
  14609. array(
  14610. // While technically not required by the spec, we're forcing
  14611. // it to this value.
  14612. 'type' => 'Enum#application/x-shockwave-flash',
  14613. 'width' => 'Pixels#' . $max,
  14614. 'height' => 'Pixels#' . $max,
  14615. 'data' => 'URI#embedded',
  14616. 'codebase' => new HTMLPurifier_AttrDef_Enum(
  14617. array(
  14618. 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0'
  14619. )
  14620. ),
  14621. )
  14622. );
  14623. $object->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeObject();
  14624. $param = $this->addElement(
  14625. 'param',
  14626. false,
  14627. 'Empty',
  14628. false,
  14629. array(
  14630. 'id' => 'ID',
  14631. 'name*' => 'Text',
  14632. 'value' => 'Text'
  14633. )
  14634. );
  14635. $param->attr_transform_post[] = new HTMLPurifier_AttrTransform_SafeParam();
  14636. $this->info_injector[] = 'SafeObject';
  14637. }
  14638. }
  14639. /**
  14640. * A "safe" script module. No inline JS is allowed, and pointed to JS
  14641. * files must match whitelist.
  14642. */
  14643. class HTMLPurifier_HTMLModule_SafeScripting extends HTMLPurifier_HTMLModule
  14644. {
  14645. /**
  14646. * @type string
  14647. */
  14648. public $name = 'SafeScripting';
  14649. /**
  14650. * @param HTMLPurifier_Config $config
  14651. */
  14652. public function setup($config)
  14653. {
  14654. // These definitions are not intrinsically safe: the attribute transforms
  14655. // are a vital part of ensuring safety.
  14656. $allowed = $config->get('HTML.SafeScripting');
  14657. $script = $this->addElement(
  14658. 'script',
  14659. 'Inline',
  14660. 'Empty',
  14661. null,
  14662. array(
  14663. // While technically not required by the spec, we're forcing
  14664. // it to this value.
  14665. 'type' => 'Enum#text/javascript',
  14666. 'src*' => new HTMLPurifier_AttrDef_Enum(array_keys($allowed))
  14667. )
  14668. );
  14669. $script->attr_transform_pre[] =
  14670. $script->attr_transform_post[] = new HTMLPurifier_AttrTransform_ScriptRequired();
  14671. }
  14672. }
  14673. /*
  14674. WARNING: THIS MODULE IS EXTREMELY DANGEROUS AS IT ENABLES INLINE SCRIPTING
  14675. INSIDE HTML PURIFIER DOCUMENTS. USE ONLY WITH TRUSTED USER INPUT!!!
  14676. */
  14677. /**
  14678. * XHTML 1.1 Scripting module, defines elements that are used to contain
  14679. * information pertaining to executable scripts or the lack of support
  14680. * for executable scripts.
  14681. * @note This module does not contain inline scripting elements
  14682. */
  14683. class HTMLPurifier_HTMLModule_Scripting extends HTMLPurifier_HTMLModule
  14684. {
  14685. /**
  14686. * @type string
  14687. */
  14688. public $name = 'Scripting';
  14689. /**
  14690. * @type array
  14691. */
  14692. public $elements = array('script', 'noscript');
  14693. /**
  14694. * @type array
  14695. */
  14696. public $content_sets = array('Block' => 'script | noscript', 'Inline' => 'script | noscript');
  14697. /**
  14698. * @type bool
  14699. */
  14700. public $safe = false;
  14701. /**
  14702. * @param HTMLPurifier_Config $config
  14703. */
  14704. public function setup($config)
  14705. {
  14706. // TODO: create custom child-definition for noscript that
  14707. // auto-wraps stray #PCDATA in a similar manner to
  14708. // blockquote's custom definition (we would use it but
  14709. // blockquote's contents are optional while noscript's contents
  14710. // are required)
  14711. // TODO: convert this to new syntax, main problem is getting
  14712. // both content sets working
  14713. // In theory, this could be safe, but I don't see any reason to
  14714. // allow it.
  14715. $this->info['noscript'] = new HTMLPurifier_ElementDef();
  14716. $this->info['noscript']->attr = array(0 => array('Common'));
  14717. $this->info['noscript']->content_model = 'Heading | List | Block';
  14718. $this->info['noscript']->content_model_type = 'required';
  14719. $this->info['script'] = new HTMLPurifier_ElementDef();
  14720. $this->info['script']->attr = array(
  14721. 'defer' => new HTMLPurifier_AttrDef_Enum(array('defer')),
  14722. 'src' => new HTMLPurifier_AttrDef_URI(true),
  14723. 'type' => new HTMLPurifier_AttrDef_Enum(array('text/javascript'))
  14724. );
  14725. $this->info['script']->content_model = '#PCDATA';
  14726. $this->info['script']->content_model_type = 'optional';
  14727. $this->info['script']->attr_transform_pre[] =
  14728. $this->info['script']->attr_transform_post[] =
  14729. new HTMLPurifier_AttrTransform_ScriptRequired();
  14730. }
  14731. }
  14732. /**
  14733. * XHTML 1.1 Edit Module, defines editing-related elements. Text Extension
  14734. * Module.
  14735. */
  14736. class HTMLPurifier_HTMLModule_StyleAttribute extends HTMLPurifier_HTMLModule
  14737. {
  14738. /**
  14739. * @type string
  14740. */
  14741. public $name = 'StyleAttribute';
  14742. /**
  14743. * @type array
  14744. */
  14745. public $attr_collections = array(
  14746. // The inclusion routine differs from the Abstract Modules but
  14747. // is in line with the DTD and XML Schemas.
  14748. 'Style' => array('style' => false), // see constructor
  14749. 'Core' => array(0 => array('Style'))
  14750. );
  14751. /**
  14752. * @param HTMLPurifier_Config $config
  14753. */
  14754. public function setup($config)
  14755. {
  14756. $this->attr_collections['Style']['style'] = new HTMLPurifier_AttrDef_CSS();
  14757. }
  14758. }
  14759. /**
  14760. * XHTML 1.1 Tables Module, fully defines accessible table elements.
  14761. */
  14762. class HTMLPurifier_HTMLModule_Tables extends HTMLPurifier_HTMLModule
  14763. {
  14764. /**
  14765. * @type string
  14766. */
  14767. public $name = 'Tables';
  14768. /**
  14769. * @param HTMLPurifier_Config $config
  14770. */
  14771. public function setup($config)
  14772. {
  14773. $this->addElement('caption', false, 'Inline', 'Common');
  14774. $this->addElement(
  14775. 'table',
  14776. 'Block',
  14777. new HTMLPurifier_ChildDef_Table(),
  14778. 'Common',
  14779. array(
  14780. 'border' => 'Pixels',
  14781. 'cellpadding' => 'Length',
  14782. 'cellspacing' => 'Length',
  14783. 'frame' => 'Enum#void,above,below,hsides,lhs,rhs,vsides,box,border',
  14784. 'rules' => 'Enum#none,groups,rows,cols,all',
  14785. 'summary' => 'Text',
  14786. 'width' => 'Length'
  14787. )
  14788. );
  14789. // common attributes
  14790. $cell_align = array(
  14791. 'align' => 'Enum#left,center,right,justify,char',
  14792. 'charoff' => 'Length',
  14793. 'valign' => 'Enum#top,middle,bottom,baseline',
  14794. );
  14795. $cell_t = array_merge(
  14796. array(
  14797. 'abbr' => 'Text',
  14798. 'colspan' => 'Number',
  14799. 'rowspan' => 'Number',
  14800. // Apparently, as of HTML5 this attribute only applies
  14801. // to 'th' elements.
  14802. 'scope' => 'Enum#row,col,rowgroup,colgroup',
  14803. ),
  14804. $cell_align
  14805. );
  14806. $this->addElement('td', false, 'Flow', 'Common', $cell_t);
  14807. $this->addElement('th', false, 'Flow', 'Common', $cell_t);
  14808. $this->addElement('tr', false, 'Required: td | th', 'Common', $cell_align);
  14809. $cell_col = array_merge(
  14810. array(
  14811. 'span' => 'Number',
  14812. 'width' => 'MultiLength',
  14813. ),
  14814. $cell_align
  14815. );
  14816. $this->addElement('col', false, 'Empty', 'Common', $cell_col);
  14817. $this->addElement('colgroup', false, 'Optional: col', 'Common', $cell_col);
  14818. $this->addElement('tbody', false, 'Required: tr', 'Common', $cell_align);
  14819. $this->addElement('thead', false, 'Required: tr', 'Common', $cell_align);
  14820. $this->addElement('tfoot', false, 'Required: tr', 'Common', $cell_align);
  14821. }
  14822. }
  14823. /**
  14824. * XHTML 1.1 Target Module, defines target attribute in link elements.
  14825. */
  14826. class HTMLPurifier_HTMLModule_Target extends HTMLPurifier_HTMLModule
  14827. {
  14828. /**
  14829. * @type string
  14830. */
  14831. public $name = 'Target';
  14832. /**
  14833. * @param HTMLPurifier_Config $config
  14834. */
  14835. public function setup($config)
  14836. {
  14837. $elements = array('a');
  14838. foreach ($elements as $name) {
  14839. $e = $this->addBlankElement($name);
  14840. $e->attr = array(
  14841. 'target' => new HTMLPurifier_AttrDef_HTML_FrameTarget()
  14842. );
  14843. }
  14844. }
  14845. }
  14846. /**
  14847. * Module adds the target=blank attribute transformation to a tags. It
  14848. * is enabled by HTML.TargetBlank
  14849. */
  14850. class HTMLPurifier_HTMLModule_TargetBlank extends HTMLPurifier_HTMLModule
  14851. {
  14852. /**
  14853. * @type string
  14854. */
  14855. public $name = 'TargetBlank';
  14856. /**
  14857. * @param HTMLPurifier_Config $config
  14858. */
  14859. public function setup($config)
  14860. {
  14861. $a = $this->addBlankElement('a');
  14862. $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetBlank();
  14863. }
  14864. }
  14865. /**
  14866. * Module adds the target-based noreferrer attribute transformation to a tags. It
  14867. * is enabled by HTML.TargetNoreferrer
  14868. */
  14869. class HTMLPurifier_HTMLModule_TargetNoreferrer extends HTMLPurifier_HTMLModule
  14870. {
  14871. /**
  14872. * @type string
  14873. */
  14874. public $name = 'TargetNoreferrer';
  14875. /**
  14876. * @param HTMLPurifier_Config $config
  14877. */
  14878. public function setup($config) {
  14879. $a = $this->addBlankElement('a');
  14880. $a->attr_transform_post[] = new HTMLPurifier_AttrTransform_TargetNoreferrer();
  14881. }
  14882. }
  14883. /**
  14884. * XHTML 1.1 Text Module, defines basic text containers. Core Module.
  14885. * @note In the normative XML Schema specification, this module
  14886. * is further abstracted into the following modules:
  14887. * - Block Phrasal (address, blockquote, pre, h1, h2, h3, h4, h5, h6)
  14888. * - Block Structural (div, p)
  14889. * - Inline Phrasal (abbr, acronym, cite, code, dfn, em, kbd, q, samp, strong, var)
  14890. * - Inline Structural (br, span)
  14891. * This module, functionally, does not distinguish between these
  14892. * sub-modules, but the code is internally structured to reflect
  14893. * these distinctions.
  14894. */
  14895. class HTMLPurifier_HTMLModule_Text extends HTMLPurifier_HTMLModule
  14896. {
  14897. /**
  14898. * @type string
  14899. */
  14900. public $name = 'Text';
  14901. /**
  14902. * @type array
  14903. */
  14904. public $content_sets = array(
  14905. 'Flow' => 'Heading | Block | Inline'
  14906. );
  14907. /**
  14908. * @param HTMLPurifier_Config $config
  14909. */
  14910. public function setup($config)
  14911. {
  14912. // Inline Phrasal -------------------------------------------------
  14913. $this->addElement('abbr', 'Inline', 'Inline', 'Common');
  14914. $this->addElement('acronym', 'Inline', 'Inline', 'Common');
  14915. $this->addElement('cite', 'Inline', 'Inline', 'Common');
  14916. $this->addElement('dfn', 'Inline', 'Inline', 'Common');
  14917. $this->addElement('kbd', 'Inline', 'Inline', 'Common');
  14918. $this->addElement('q', 'Inline', 'Inline', 'Common', array('cite' => 'URI'));
  14919. $this->addElement('samp', 'Inline', 'Inline', 'Common');
  14920. $this->addElement('var', 'Inline', 'Inline', 'Common');
  14921. $em = $this->addElement('em', 'Inline', 'Inline', 'Common');
  14922. $em->formatting = true;
  14923. $strong = $this->addElement('strong', 'Inline', 'Inline', 'Common');
  14924. $strong->formatting = true;
  14925. $code = $this->addElement('code', 'Inline', 'Inline', 'Common');
  14926. $code->formatting = true;
  14927. // Inline Structural ----------------------------------------------
  14928. $this->addElement('span', 'Inline', 'Inline', 'Common');
  14929. $this->addElement('br', 'Inline', 'Empty', 'Core');
  14930. // Block Phrasal --------------------------------------------------
  14931. $this->addElement('address', 'Block', 'Inline', 'Common');
  14932. $this->addElement('blockquote', 'Block', 'Optional: Heading | Block | List', 'Common', array('cite' => 'URI'));
  14933. $pre = $this->addElement('pre', 'Block', 'Inline', 'Common');
  14934. $pre->excludes = $this->makeLookup(
  14935. 'img',
  14936. 'big',
  14937. 'small',
  14938. 'object',
  14939. 'applet',
  14940. 'font',
  14941. 'basefont'
  14942. );
  14943. $this->addElement('h1', 'Heading', 'Inline', 'Common');
  14944. $this->addElement('h2', 'Heading', 'Inline', 'Common');
  14945. $this->addElement('h3', 'Heading', 'Inline', 'Common');
  14946. $this->addElement('h4', 'Heading', 'Inline', 'Common');
  14947. $this->addElement('h5', 'Heading', 'Inline', 'Common');
  14948. $this->addElement('h6', 'Heading', 'Inline', 'Common');
  14949. // Block Structural -----------------------------------------------
  14950. $p = $this->addElement('p', 'Block', 'Inline', 'Common');
  14951. $p->autoclose = array_flip(
  14952. array("address", "blockquote", "center", "dir", "div", "dl", "fieldset", "ol", "p", "ul")
  14953. );
  14954. $this->addElement('div', 'Block', 'Flow', 'Common');
  14955. }
  14956. }
  14957. /**
  14958. * Abstract class for a set of proprietary modules that clean up (tidy)
  14959. * poorly written HTML.
  14960. * @todo Figure out how to protect some of these methods/properties
  14961. */
  14962. class HTMLPurifier_HTMLModule_Tidy extends HTMLPurifier_HTMLModule
  14963. {
  14964. /**
  14965. * List of supported levels.
  14966. * Index zero is a special case "no fixes" level.
  14967. * @type array
  14968. */
  14969. public $levels = array(0 => 'none', 'light', 'medium', 'heavy');
  14970. /**
  14971. * Default level to place all fixes in.
  14972. * Disabled by default.
  14973. * @type string
  14974. */
  14975. public $defaultLevel = null;
  14976. /**
  14977. * Lists of fixes used by getFixesForLevel().
  14978. * Format is:
  14979. * HTMLModule_Tidy->fixesForLevel[$level] = array('fix-1', 'fix-2');
  14980. * @type array
  14981. */
  14982. public $fixesForLevel = array(
  14983. 'light' => array(),
  14984. 'medium' => array(),
  14985. 'heavy' => array()
  14986. );
  14987. /**
  14988. * Lazy load constructs the module by determining the necessary
  14989. * fixes to create and then delegating to the populate() function.
  14990. * @param HTMLPurifier_Config $config
  14991. * @todo Wildcard matching and error reporting when an added or
  14992. * subtracted fix has no effect.
  14993. */
  14994. public function setup($config)
  14995. {
  14996. // create fixes, initialize fixesForLevel
  14997. $fixes = $this->makeFixes();
  14998. $this->makeFixesForLevel($fixes);
  14999. // figure out which fixes to use
  15000. $level = $config->get('HTML.TidyLevel');
  15001. $fixes_lookup = $this->getFixesForLevel($level);
  15002. // get custom fix declarations: these need namespace processing
  15003. $add_fixes = $config->get('HTML.TidyAdd');
  15004. $remove_fixes = $config->get('HTML.TidyRemove');
  15005. foreach ($fixes as $name => $fix) {
  15006. // needs to be refactored a little to implement globbing
  15007. if (isset($remove_fixes[$name]) ||
  15008. (!isset($add_fixes[$name]) && !isset($fixes_lookup[$name]))) {
  15009. unset($fixes[$name]);
  15010. }
  15011. }
  15012. // populate this module with necessary fixes
  15013. $this->populate($fixes);
  15014. }
  15015. /**
  15016. * Retrieves all fixes per a level, returning fixes for that specific
  15017. * level as well as all levels below it.
  15018. * @param string $level level identifier, see $levels for valid values
  15019. * @return array Lookup up table of fixes
  15020. */
  15021. public function getFixesForLevel($level)
  15022. {
  15023. if ($level == $this->levels[0]) {
  15024. return array();
  15025. }
  15026. $activated_levels = array();
  15027. for ($i = 1, $c = count($this->levels); $i < $c; $i++) {
  15028. $activated_levels[] = $this->levels[$i];
  15029. if ($this->levels[$i] == $level) {
  15030. break;
  15031. }
  15032. }
  15033. if ($i == $c) {
  15034. trigger_error(
  15035. 'Tidy level ' . htmlspecialchars($level) . ' not recognized',
  15036. E_USER_WARNING
  15037. );
  15038. return array();
  15039. }
  15040. $ret = array();
  15041. foreach ($activated_levels as $level) {
  15042. foreach ($this->fixesForLevel[$level] as $fix) {
  15043. $ret[$fix] = true;
  15044. }
  15045. }
  15046. return $ret;
  15047. }
  15048. /**
  15049. * Dynamically populates the $fixesForLevel member variable using
  15050. * the fixes array. It may be custom overloaded, used in conjunction
  15051. * with $defaultLevel, or not used at all.
  15052. * @param array $fixes
  15053. */
  15054. public function makeFixesForLevel($fixes)
  15055. {
  15056. if (!isset($this->defaultLevel)) {
  15057. return;
  15058. }
  15059. if (!isset($this->fixesForLevel[$this->defaultLevel])) {
  15060. trigger_error(
  15061. 'Default level ' . $this->defaultLevel . ' does not exist',
  15062. E_USER_ERROR
  15063. );
  15064. return;
  15065. }
  15066. $this->fixesForLevel[$this->defaultLevel] = array_keys($fixes);
  15067. }
  15068. /**
  15069. * Populates the module with transforms and other special-case code
  15070. * based on a list of fixes passed to it
  15071. * @param array $fixes Lookup table of fixes to activate
  15072. */
  15073. public function populate($fixes)
  15074. {
  15075. foreach ($fixes as $name => $fix) {
  15076. // determine what the fix is for
  15077. list($type, $params) = $this->getFixType($name);
  15078. switch ($type) {
  15079. case 'attr_transform_pre':
  15080. case 'attr_transform_post':
  15081. $attr = $params['attr'];
  15082. if (isset($params['element'])) {
  15083. $element = $params['element'];
  15084. if (empty($this->info[$element])) {
  15085. $e = $this->addBlankElement($element);
  15086. } else {
  15087. $e = $this->info[$element];
  15088. }
  15089. } else {
  15090. $type = "info_$type";
  15091. $e = $this;
  15092. }
  15093. // PHP does some weird parsing when I do
  15094. // $e->$type[$attr], so I have to assign a ref.
  15095. $f =& $e->$type;
  15096. $f[$attr] = $fix;
  15097. break;
  15098. case 'tag_transform':
  15099. $this->info_tag_transform[$params['element']] = $fix;
  15100. break;
  15101. case 'child':
  15102. case 'content_model_type':
  15103. $element = $params['element'];
  15104. if (empty($this->info[$element])) {
  15105. $e = $this->addBlankElement($element);
  15106. } else {
  15107. $e = $this->info[$element];
  15108. }
  15109. $e->$type = $fix;
  15110. break;
  15111. default:
  15112. trigger_error("Fix type $type not supported", E_USER_ERROR);
  15113. break;
  15114. }
  15115. }
  15116. }
  15117. /**
  15118. * Parses a fix name and determines what kind of fix it is, as well
  15119. * as other information defined by the fix
  15120. * @param $name String name of fix
  15121. * @return array(string $fix_type, array $fix_parameters)
  15122. * @note $fix_parameters is type dependant, see populate() for usage
  15123. * of these parameters
  15124. */
  15125. public function getFixType($name)
  15126. {
  15127. // parse it
  15128. $property = $attr = null;
  15129. if (strpos($name, '#') !== false) {
  15130. list($name, $property) = explode('#', $name);
  15131. }
  15132. if (strpos($name, '@') !== false) {
  15133. list($name, $attr) = explode('@', $name);
  15134. }
  15135. // figure out the parameters
  15136. $params = array();
  15137. if ($name !== '') {
  15138. $params['element'] = $name;
  15139. }
  15140. if (!is_null($attr)) {
  15141. $params['attr'] = $attr;
  15142. }
  15143. // special case: attribute transform
  15144. if (!is_null($attr)) {
  15145. if (is_null($property)) {
  15146. $property = 'pre';
  15147. }
  15148. $type = 'attr_transform_' . $property;
  15149. return array($type, $params);
  15150. }
  15151. // special case: tag transform
  15152. if (is_null($property)) {
  15153. return array('tag_transform', $params);
  15154. }
  15155. return array($property, $params);
  15156. }
  15157. /**
  15158. * Defines all fixes the module will perform in a compact
  15159. * associative array of fix name to fix implementation.
  15160. * @return array
  15161. */
  15162. public function makeFixes()
  15163. {
  15164. }
  15165. }
  15166. class HTMLPurifier_HTMLModule_XMLCommonAttributes extends HTMLPurifier_HTMLModule
  15167. {
  15168. /**
  15169. * @type string
  15170. */
  15171. public $name = 'XMLCommonAttributes';
  15172. /**
  15173. * @type array
  15174. */
  15175. public $attr_collections = array(
  15176. 'Lang' => array(
  15177. 'xml:lang' => 'LanguageCode',
  15178. )
  15179. );
  15180. }
  15181. /**
  15182. * Name is deprecated, but allowed in strict doctypes, so onl
  15183. */
  15184. class HTMLPurifier_HTMLModule_Tidy_Name extends HTMLPurifier_HTMLModule_Tidy
  15185. {
  15186. /**
  15187. * @type string
  15188. */
  15189. public $name = 'Tidy_Name';
  15190. /**
  15191. * @type string
  15192. */
  15193. public $defaultLevel = 'heavy';
  15194. /**
  15195. * @return array
  15196. */
  15197. public function makeFixes()
  15198. {
  15199. $r = array();
  15200. // @name for img, a -----------------------------------------------
  15201. // Technically, it's allowed even on strict, so we allow authors to use
  15202. // it. However, it's deprecated in future versions of XHTML.
  15203. $r['img@name'] =
  15204. $r['a@name'] = new HTMLPurifier_AttrTransform_Name();
  15205. return $r;
  15206. }
  15207. }
  15208. class HTMLPurifier_HTMLModule_Tidy_Proprietary extends HTMLPurifier_HTMLModule_Tidy
  15209. {
  15210. /**
  15211. * @type string
  15212. */
  15213. public $name = 'Tidy_Proprietary';
  15214. /**
  15215. * @type string
  15216. */
  15217. public $defaultLevel = 'light';
  15218. /**
  15219. * @return array
  15220. */
  15221. public function makeFixes()
  15222. {
  15223. $r = array();
  15224. $r['table@background'] = new HTMLPurifier_AttrTransform_Background();
  15225. $r['td@background'] = new HTMLPurifier_AttrTransform_Background();
  15226. $r['th@background'] = new HTMLPurifier_AttrTransform_Background();
  15227. $r['tr@background'] = new HTMLPurifier_AttrTransform_Background();
  15228. $r['thead@background'] = new HTMLPurifier_AttrTransform_Background();
  15229. $r['tfoot@background'] = new HTMLPurifier_AttrTransform_Background();
  15230. $r['tbody@background'] = new HTMLPurifier_AttrTransform_Background();
  15231. $r['table@height'] = new HTMLPurifier_AttrTransform_Length('height');
  15232. return $r;
  15233. }
  15234. }
  15235. class HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4 extends HTMLPurifier_HTMLModule_Tidy
  15236. {
  15237. /**
  15238. * @return array
  15239. */
  15240. public function makeFixes()
  15241. {
  15242. $r = array();
  15243. // == deprecated tag transforms ===================================
  15244. $r['font'] = new HTMLPurifier_TagTransform_Font();
  15245. $r['menu'] = new HTMLPurifier_TagTransform_Simple('ul');
  15246. $r['dir'] = new HTMLPurifier_TagTransform_Simple('ul');
  15247. $r['center'] = new HTMLPurifier_TagTransform_Simple('div', 'text-align:center;');
  15248. $r['u'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:underline;');
  15249. $r['s'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
  15250. $r['strike'] = new HTMLPurifier_TagTransform_Simple('span', 'text-decoration:line-through;');
  15251. // == deprecated attribute transforms =============================
  15252. $r['caption@align'] =
  15253. new HTMLPurifier_AttrTransform_EnumToCSS(
  15254. 'align',
  15255. array(
  15256. // we're following IE's behavior, not Firefox's, due
  15257. // to the fact that no one supports caption-side:right,
  15258. // W3C included (with CSS 2.1). This is a slightly
  15259. // unreasonable attribute!
  15260. 'left' => 'text-align:left;',
  15261. 'right' => 'text-align:right;',
  15262. 'top' => 'caption-side:top;',
  15263. 'bottom' => 'caption-side:bottom;' // not supported by IE
  15264. )
  15265. );
  15266. // @align for img -------------------------------------------------
  15267. $r['img@align'] =
  15268. new HTMLPurifier_AttrTransform_EnumToCSS(
  15269. 'align',
  15270. array(
  15271. 'left' => 'float:left;',
  15272. 'right' => 'float:right;',
  15273. 'top' => 'vertical-align:top;',
  15274. 'middle' => 'vertical-align:middle;',
  15275. 'bottom' => 'vertical-align:baseline;',
  15276. )
  15277. );
  15278. // @align for table -----------------------------------------------
  15279. $r['table@align'] =
  15280. new HTMLPurifier_AttrTransform_EnumToCSS(
  15281. 'align',
  15282. array(
  15283. 'left' => 'float:left;',
  15284. 'center' => 'margin-left:auto;margin-right:auto;',
  15285. 'right' => 'float:right;'
  15286. )
  15287. );
  15288. // @align for hr -----------------------------------------------
  15289. $r['hr@align'] =
  15290. new HTMLPurifier_AttrTransform_EnumToCSS(
  15291. 'align',
  15292. array(
  15293. // we use both text-align and margin because these work
  15294. // for different browsers (IE and Firefox, respectively)
  15295. // and the melange makes for a pretty cross-compatible
  15296. // solution
  15297. 'left' => 'margin-left:0;margin-right:auto;text-align:left;',
  15298. 'center' => 'margin-left:auto;margin-right:auto;text-align:center;',
  15299. 'right' => 'margin-left:auto;margin-right:0;text-align:right;'
  15300. )
  15301. );
  15302. // @align for h1, h2, h3, h4, h5, h6, p, div ----------------------
  15303. // {{{
  15304. $align_lookup = array();
  15305. $align_values = array('left', 'right', 'center', 'justify');
  15306. foreach ($align_values as $v) {
  15307. $align_lookup[$v] = "text-align:$v;";
  15308. }
  15309. // }}}
  15310. $r['h1@align'] =
  15311. $r['h2@align'] =
  15312. $r['h3@align'] =
  15313. $r['h4@align'] =
  15314. $r['h5@align'] =
  15315. $r['h6@align'] =
  15316. $r['p@align'] =
  15317. $r['div@align'] =
  15318. new HTMLPurifier_AttrTransform_EnumToCSS('align', $align_lookup);
  15319. // @bgcolor for table, tr, td, th ---------------------------------
  15320. $r['table@bgcolor'] =
  15321. $r['td@bgcolor'] =
  15322. $r['th@bgcolor'] =
  15323. new HTMLPurifier_AttrTransform_BgColor();
  15324. // @border for img ------------------------------------------------
  15325. $r['img@border'] = new HTMLPurifier_AttrTransform_Border();
  15326. // @clear for br --------------------------------------------------
  15327. $r['br@clear'] =
  15328. new HTMLPurifier_AttrTransform_EnumToCSS(
  15329. 'clear',
  15330. array(
  15331. 'left' => 'clear:left;',
  15332. 'right' => 'clear:right;',
  15333. 'all' => 'clear:both;',
  15334. 'none' => 'clear:none;',
  15335. )
  15336. );
  15337. // @height for td, th ---------------------------------------------
  15338. $r['td@height'] =
  15339. $r['th@height'] =
  15340. new HTMLPurifier_AttrTransform_Length('height');
  15341. // @hspace for img ------------------------------------------------
  15342. $r['img@hspace'] = new HTMLPurifier_AttrTransform_ImgSpace('hspace');
  15343. // @noshade for hr ------------------------------------------------
  15344. // this transformation is not precise but often good enough.
  15345. // different browsers use different styles to designate noshade
  15346. $r['hr@noshade'] =
  15347. new HTMLPurifier_AttrTransform_BoolToCSS(
  15348. 'noshade',
  15349. 'color:#808080;background-color:#808080;border:0;'
  15350. );
  15351. // @nowrap for td, th ---------------------------------------------
  15352. $r['td@nowrap'] =
  15353. $r['th@nowrap'] =
  15354. new HTMLPurifier_AttrTransform_BoolToCSS(
  15355. 'nowrap',
  15356. 'white-space:nowrap;'
  15357. );
  15358. // @size for hr --------------------------------------------------
  15359. $r['hr@size'] = new HTMLPurifier_AttrTransform_Length('size', 'height');
  15360. // @type for li, ol, ul -------------------------------------------
  15361. // {{{
  15362. $ul_types = array(
  15363. 'disc' => 'list-style-type:disc;',
  15364. 'square' => 'list-style-type:square;',
  15365. 'circle' => 'list-style-type:circle;'
  15366. );
  15367. $ol_types = array(
  15368. '1' => 'list-style-type:decimal;',
  15369. 'i' => 'list-style-type:lower-roman;',
  15370. 'I' => 'list-style-type:upper-roman;',
  15371. 'a' => 'list-style-type:lower-alpha;',
  15372. 'A' => 'list-style-type:upper-alpha;'
  15373. );
  15374. $li_types = $ul_types + $ol_types;
  15375. // }}}
  15376. $r['ul@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ul_types);
  15377. $r['ol@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $ol_types, true);
  15378. $r['li@type'] = new HTMLPurifier_AttrTransform_EnumToCSS('type', $li_types, true);
  15379. // @vspace for img ------------------------------------------------
  15380. $r['img@vspace'] = new HTMLPurifier_AttrTransform_ImgSpace('vspace');
  15381. // @width for hr, td, th ------------------------------------------
  15382. $r['td@width'] =
  15383. $r['th@width'] =
  15384. $r['hr@width'] = new HTMLPurifier_AttrTransform_Length('width');
  15385. return $r;
  15386. }
  15387. }
  15388. class HTMLPurifier_HTMLModule_Tidy_Strict extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4
  15389. {
  15390. /**
  15391. * @type string
  15392. */
  15393. public $name = 'Tidy_Strict';
  15394. /**
  15395. * @type string
  15396. */
  15397. public $defaultLevel = 'light';
  15398. /**
  15399. * @return array
  15400. */
  15401. public function makeFixes()
  15402. {
  15403. $r = parent::makeFixes();
  15404. $r['blockquote#content_model_type'] = 'strictblockquote';
  15405. return $r;
  15406. }
  15407. /**
  15408. * @type bool
  15409. */
  15410. public $defines_child_def = true;
  15411. /**
  15412. * @param HTMLPurifier_ElementDef $def
  15413. * @return HTMLPurifier_ChildDef_StrictBlockquote
  15414. */
  15415. public function getChildDef($def)
  15416. {
  15417. if ($def->content_model_type != 'strictblockquote') {
  15418. return parent::getChildDef($def);
  15419. }
  15420. return new HTMLPurifier_ChildDef_StrictBlockquote($def->content_model);
  15421. }
  15422. }
  15423. class HTMLPurifier_HTMLModule_Tidy_Transitional extends HTMLPurifier_HTMLModule_Tidy_XHTMLAndHTML4
  15424. {
  15425. /**
  15426. * @type string
  15427. */
  15428. public $name = 'Tidy_Transitional';
  15429. /**
  15430. * @type string
  15431. */
  15432. public $defaultLevel = 'heavy';
  15433. }
  15434. class HTMLPurifier_HTMLModule_Tidy_XHTML extends HTMLPurifier_HTMLModule_Tidy
  15435. {
  15436. /**
  15437. * @type string
  15438. */
  15439. public $name = 'Tidy_XHTML';
  15440. /**
  15441. * @type string
  15442. */
  15443. public $defaultLevel = 'medium';
  15444. /**
  15445. * @return array
  15446. */
  15447. public function makeFixes()
  15448. {
  15449. $r = array();
  15450. $r['@lang'] = new HTMLPurifier_AttrTransform_Lang();
  15451. return $r;
  15452. }
  15453. }
  15454. /**
  15455. * Injector that auto paragraphs text in the root node based on
  15456. * double-spacing.
  15457. * @todo Ensure all states are unit tested, including variations as well.
  15458. * @todo Make a graph of the flow control for this Injector.
  15459. */
  15460. class HTMLPurifier_Injector_AutoParagraph extends HTMLPurifier_Injector
  15461. {
  15462. /**
  15463. * @type string
  15464. */
  15465. public $name = 'AutoParagraph';
  15466. /**
  15467. * @type array
  15468. */
  15469. public $needed = array('p');
  15470. /**
  15471. * @return HTMLPurifier_Token_Start
  15472. */
  15473. private function _pStart()
  15474. {
  15475. $par = new HTMLPurifier_Token_Start('p');
  15476. $par->armor['MakeWellFormed_TagClosedError'] = true;
  15477. return $par;
  15478. }
  15479. /**
  15480. * @param HTMLPurifier_Token_Text $token
  15481. */
  15482. public function handleText(&$token)
  15483. {
  15484. $text = $token->data;
  15485. // Does the current parent allow <p> tags?
  15486. if ($this->allowsElement('p')) {
  15487. if (empty($this->currentNesting) || strpos($text, "\n\n") !== false) {
  15488. // Note that we have differing behavior when dealing with text
  15489. // in the anonymous root node, or a node inside the document.
  15490. // If the text as a double-newline, the treatment is the same;
  15491. // if it doesn't, see the next if-block if you're in the document.
  15492. $i = $nesting = null;
  15493. if (!$this->forwardUntilEndToken($i, $current, $nesting) && $token->is_whitespace) {
  15494. // State 1.1: ... ^ (whitespace, then document end)
  15495. // ----
  15496. // This is a degenerate case
  15497. } else {
  15498. if (!$token->is_whitespace || $this->_isInline($current)) {
  15499. // State 1.2: PAR1
  15500. // ----
  15501. // State 1.3: PAR1\n\nPAR2
  15502. // ------------
  15503. // State 1.4: <div>PAR1\n\nPAR2 (see State 2)
  15504. // ------------
  15505. $token = array($this->_pStart());
  15506. $this->_splitText($text, $token);
  15507. } else {
  15508. // State 1.5: \n<hr />
  15509. // --
  15510. }
  15511. }
  15512. } else {
  15513. // State 2: <div>PAR1... (similar to 1.4)
  15514. // ----
  15515. // We're in an element that allows paragraph tags, but we're not
  15516. // sure if we're going to need them.
  15517. if ($this->_pLookAhead()) {
  15518. // State 2.1: <div>PAR1<b>PAR1\n\nPAR2
  15519. // ----
  15520. // Note: This will always be the first child, since any
  15521. // previous inline element would have triggered this very
  15522. // same routine, and found the double newline. One possible
  15523. // exception would be a comment.
  15524. $token = array($this->_pStart(), $token);
  15525. } else {
  15526. // State 2.2.1: <div>PAR1<div>
  15527. // ----
  15528. // State 2.2.2: <div>PAR1<b>PAR1</b></div>
  15529. // ----
  15530. }
  15531. }
  15532. // Is the current parent a <p> tag?
  15533. } elseif (!empty($this->currentNesting) &&
  15534. $this->currentNesting[count($this->currentNesting) - 1]->name == 'p') {
  15535. // State 3.1: ...<p>PAR1
  15536. // ----
  15537. // State 3.2: ...<p>PAR1\n\nPAR2
  15538. // ------------
  15539. $token = array();
  15540. $this->_splitText($text, $token);
  15541. // Abort!
  15542. } else {
  15543. // State 4.1: ...<b>PAR1
  15544. // ----
  15545. // State 4.2: ...<b>PAR1\n\nPAR2
  15546. // ------------
  15547. }
  15548. }
  15549. /**
  15550. * @param HTMLPurifier_Token $token
  15551. */
  15552. public function handleElement(&$token)
  15553. {
  15554. // We don't have to check if we're already in a <p> tag for block
  15555. // tokens, because the tag would have been autoclosed by MakeWellFormed.
  15556. if ($this->allowsElement('p')) {
  15557. if (!empty($this->currentNesting)) {
  15558. if ($this->_isInline($token)) {
  15559. // State 1: <div>...<b>
  15560. // ---
  15561. // Check if this token is adjacent to the parent token
  15562. // (seek backwards until token isn't whitespace)
  15563. $i = null;
  15564. $this->backward($i, $prev);
  15565. if (!$prev instanceof HTMLPurifier_Token_Start) {
  15566. // Token wasn't adjacent
  15567. if ($prev instanceof HTMLPurifier_Token_Text &&
  15568. substr($prev->data, -2) === "\n\n"
  15569. ) {
  15570. // State 1.1.4: <div><p>PAR1</p>\n\n<b>
  15571. // ---
  15572. // Quite frankly, this should be handled by splitText
  15573. $token = array($this->_pStart(), $token);
  15574. } else {
  15575. // State 1.1.1: <div><p>PAR1</p><b>
  15576. // ---
  15577. // State 1.1.2: <div><br /><b>
  15578. // ---
  15579. // State 1.1.3: <div>PAR<b>
  15580. // ---
  15581. }
  15582. } else {
  15583. // State 1.2.1: <div><b>
  15584. // ---
  15585. // Lookahead to see if <p> is needed.
  15586. if ($this->_pLookAhead()) {
  15587. // State 1.3.1: <div><b>PAR1\n\nPAR2
  15588. // ---
  15589. $token = array($this->_pStart(), $token);
  15590. } else {
  15591. // State 1.3.2: <div><b>PAR1</b></div>
  15592. // ---
  15593. // State 1.3.3: <div><b>PAR1</b><div></div>\n\n</div>
  15594. // ---
  15595. }
  15596. }
  15597. } else {
  15598. // State 2.3: ...<div>
  15599. // -----
  15600. }
  15601. } else {
  15602. if ($this->_isInline($token)) {
  15603. // State 3.1: <b>
  15604. // ---
  15605. // This is where the {p} tag is inserted, not reflected in
  15606. // inputTokens yet, however.
  15607. $token = array($this->_pStart(), $token);
  15608. } else {
  15609. // State 3.2: <div>
  15610. // -----
  15611. }
  15612. $i = null;
  15613. if ($this->backward($i, $prev)) {
  15614. if (!$prev instanceof HTMLPurifier_Token_Text) {
  15615. // State 3.1.1: ...</p>{p}<b>
  15616. // ---
  15617. // State 3.2.1: ...</p><div>
  15618. // -----
  15619. if (!is_array($token)) {
  15620. $token = array($token);
  15621. }
  15622. array_unshift($token, new HTMLPurifier_Token_Text("\n\n"));
  15623. } else {
  15624. // State 3.1.2: ...</p>\n\n{p}<b>
  15625. // ---
  15626. // State 3.2.2: ...</p>\n\n<div>
  15627. // -----
  15628. // Note: PAR<ELEM> cannot occur because PAR would have been
  15629. // wrapped in <p> tags.
  15630. }
  15631. }
  15632. }
  15633. } else {
  15634. // State 2.2: <ul><li>
  15635. // ----
  15636. // State 2.4: <p><b>
  15637. // ---
  15638. }
  15639. }
  15640. /**
  15641. * Splits up a text in paragraph tokens and appends them
  15642. * to the result stream that will replace the original
  15643. * @param string $data String text data that will be processed
  15644. * into paragraphs
  15645. * @param HTMLPurifier_Token[] $result Reference to array of tokens that the
  15646. * tags will be appended onto
  15647. */
  15648. private function _splitText($data, &$result)
  15649. {
  15650. $raw_paragraphs = explode("\n\n", $data);
  15651. $paragraphs = array(); // without empty paragraphs
  15652. $needs_start = false;
  15653. $needs_end = false;
  15654. $c = count($raw_paragraphs);
  15655. if ($c == 1) {
  15656. // There were no double-newlines, abort quickly. In theory this
  15657. // should never happen.
  15658. $result[] = new HTMLPurifier_Token_Text($data);
  15659. return;
  15660. }
  15661. for ($i = 0; $i < $c; $i++) {
  15662. $par = $raw_paragraphs[$i];
  15663. if (trim($par) !== '') {
  15664. $paragraphs[] = $par;
  15665. } else {
  15666. if ($i == 0) {
  15667. // Double newline at the front
  15668. if (empty($result)) {
  15669. // The empty result indicates that the AutoParagraph
  15670. // injector did not add any start paragraph tokens.
  15671. // This means that we have been in a paragraph for
  15672. // a while, and the newline means we should start a new one.
  15673. $result[] = new HTMLPurifier_Token_End('p');
  15674. $result[] = new HTMLPurifier_Token_Text("\n\n");
  15675. // However, the start token should only be added if
  15676. // there is more processing to be done (i.e. there are
  15677. // real paragraphs in here). If there are none, the
  15678. // next start paragraph tag will be handled by the
  15679. // next call to the injector
  15680. $needs_start = true;
  15681. } else {
  15682. // We just started a new paragraph!
  15683. // Reinstate a double-newline for presentation's sake, since
  15684. // it was in the source code.
  15685. array_unshift($result, new HTMLPurifier_Token_Text("\n\n"));
  15686. }
  15687. } elseif ($i + 1 == $c) {
  15688. // Double newline at the end
  15689. // There should be a trailing </p> when we're finally done.
  15690. $needs_end = true;
  15691. }
  15692. }
  15693. }
  15694. // Check if this was just a giant blob of whitespace. Move this earlier,
  15695. // perhaps?
  15696. if (empty($paragraphs)) {
  15697. return;
  15698. }
  15699. // Add the start tag indicated by \n\n at the beginning of $data
  15700. if ($needs_start) {
  15701. $result[] = $this->_pStart();
  15702. }
  15703. // Append the paragraphs onto the result
  15704. foreach ($paragraphs as $par) {
  15705. $result[] = new HTMLPurifier_Token_Text($par);
  15706. $result[] = new HTMLPurifier_Token_End('p');
  15707. $result[] = new HTMLPurifier_Token_Text("\n\n");
  15708. $result[] = $this->_pStart();
  15709. }
  15710. // Remove trailing start token; Injector will handle this later if
  15711. // it was indeed needed. This prevents from needing to do a lookahead,
  15712. // at the cost of a lookbehind later.
  15713. array_pop($result);
  15714. // If there is no need for an end tag, remove all of it and let
  15715. // MakeWellFormed close it later.
  15716. if (!$needs_end) {
  15717. array_pop($result); // removes \n\n
  15718. array_pop($result); // removes </p>
  15719. }
  15720. }
  15721. /**
  15722. * Returns true if passed token is inline (and, ergo, allowed in
  15723. * paragraph tags)
  15724. * @param HTMLPurifier_Token $token
  15725. * @return bool
  15726. */
  15727. private function _isInline($token)
  15728. {
  15729. return isset($this->htmlDefinition->info['p']->child->elements[$token->name]);
  15730. }
  15731. /**
  15732. * Looks ahead in the token list and determines whether or not we need
  15733. * to insert a <p> tag.
  15734. * @return bool
  15735. */
  15736. private function _pLookAhead()
  15737. {
  15738. if ($this->currentToken instanceof HTMLPurifier_Token_Start) {
  15739. $nesting = 1;
  15740. } else {
  15741. $nesting = 0;
  15742. }
  15743. $ok = false;
  15744. $i = null;
  15745. while ($this->forwardUntilEndToken($i, $current, $nesting)) {
  15746. $result = $this->_checkNeedsP($current);
  15747. if ($result !== null) {
  15748. $ok = $result;
  15749. break;
  15750. }
  15751. }
  15752. return $ok;
  15753. }
  15754. /**
  15755. * Determines if a particular token requires an earlier inline token
  15756. * to get a paragraph. This should be used with _forwardUntilEndToken
  15757. * @param HTMLPurifier_Token $current
  15758. * @return bool
  15759. */
  15760. private function _checkNeedsP($current)
  15761. {
  15762. if ($current instanceof HTMLPurifier_Token_Start) {
  15763. if (!$this->_isInline($current)) {
  15764. // <div>PAR1<div>
  15765. // ----
  15766. // Terminate early, since we hit a block element
  15767. return false;
  15768. }
  15769. } elseif ($current instanceof HTMLPurifier_Token_Text) {
  15770. if (strpos($current->data, "\n\n") !== false) {
  15771. // <div>PAR1<b>PAR1\n\nPAR2
  15772. // ----
  15773. return true;
  15774. } else {
  15775. // <div>PAR1<b>PAR1...
  15776. // ----
  15777. }
  15778. }
  15779. return null;
  15780. }
  15781. }
  15782. /**
  15783. * Injector that displays the URL of an anchor instead of linking to it, in addition to showing the text of the link.
  15784. */
  15785. class HTMLPurifier_Injector_DisplayLinkURI extends HTMLPurifier_Injector
  15786. {
  15787. /**
  15788. * @type string
  15789. */
  15790. public $name = 'DisplayLinkURI';
  15791. /**
  15792. * @type array
  15793. */
  15794. public $needed = array('a');
  15795. /**
  15796. * @param $token
  15797. */
  15798. public function handleElement(&$token)
  15799. {
  15800. }
  15801. /**
  15802. * @param HTMLPurifier_Token $token
  15803. */
  15804. public function handleEnd(&$token)
  15805. {
  15806. if (isset($token->start->attr['href'])) {
  15807. $url = $token->start->attr['href'];
  15808. unset($token->start->attr['href']);
  15809. $token = array($token, new HTMLPurifier_Token_Text(" ($url)"));
  15810. } else {
  15811. // nothing to display
  15812. }
  15813. }
  15814. }
  15815. /**
  15816. * Injector that converts http, https and ftp text URLs to actual links.
  15817. */
  15818. class HTMLPurifier_Injector_Linkify extends HTMLPurifier_Injector
  15819. {
  15820. /**
  15821. * @type string
  15822. */
  15823. public $name = 'Linkify';
  15824. /**
  15825. * @type array
  15826. */
  15827. public $needed = array('a' => array('href'));
  15828. /**
  15829. * @param HTMLPurifier_Token $token
  15830. */
  15831. public function handleText(&$token)
  15832. {
  15833. if (!$this->allowsElement('a')) {
  15834. return;
  15835. }
  15836. if (strpos($token->data, '://') === false) {
  15837. // our really quick heuristic failed, abort
  15838. // this may not work so well if we want to match things like
  15839. // "google.com", but then again, most people don't
  15840. return;
  15841. }
  15842. // there is/are URL(s). Let's split the string.
  15843. // We use this regex:
  15844. // https://gist.github.com/gruber/249502
  15845. // but with @cscott's backtracking fix and also
  15846. // the Unicode characters un-Unicodified.
  15847. $bits = preg_split(
  15848. '/\\b((?:[a-z][\\w\\-]+:(?:\\/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}\\/)(?:[^\\s()<>]|\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\))+(?:\\((?:[^\\s()<>]|(?:\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:\'".,<>?\x{00ab}\x{00bb}\x{201c}\x{201d}\x{2018}\x{2019}]))/iu',
  15849. $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  15850. $token = array();
  15851. // $i = index
  15852. // $c = count
  15853. // $l = is link
  15854. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  15855. if (!$l) {
  15856. if ($bits[$i] === '') {
  15857. continue;
  15858. }
  15859. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  15860. } else {
  15861. $token[] = new HTMLPurifier_Token_Start('a', array('href' => $bits[$i]));
  15862. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  15863. $token[] = new HTMLPurifier_Token_End('a');
  15864. }
  15865. }
  15866. }
  15867. }
  15868. /**
  15869. * Injector that converts configuration directive syntax %Namespace.Directive
  15870. * to links
  15871. */
  15872. class HTMLPurifier_Injector_PurifierLinkify extends HTMLPurifier_Injector
  15873. {
  15874. /**
  15875. * @type string
  15876. */
  15877. public $name = 'PurifierLinkify';
  15878. /**
  15879. * @type string
  15880. */
  15881. public $docURL;
  15882. /**
  15883. * @type array
  15884. */
  15885. public $needed = array('a' => array('href'));
  15886. /**
  15887. * @param HTMLPurifier_Config $config
  15888. * @param HTMLPurifier_Context $context
  15889. * @return string
  15890. */
  15891. public function prepare($config, $context)
  15892. {
  15893. $this->docURL = $config->get('AutoFormat.PurifierLinkify.DocURL');
  15894. return parent::prepare($config, $context);
  15895. }
  15896. /**
  15897. * @param HTMLPurifier_Token $token
  15898. */
  15899. public function handleText(&$token)
  15900. {
  15901. if (!$this->allowsElement('a')) {
  15902. return;
  15903. }
  15904. if (strpos($token->data, '%') === false) {
  15905. return;
  15906. }
  15907. $bits = preg_split('#%([a-z0-9]+\.[a-z0-9]+)#Si', $token->data, -1, PREG_SPLIT_DELIM_CAPTURE);
  15908. $token = array();
  15909. // $i = index
  15910. // $c = count
  15911. // $l = is link
  15912. for ($i = 0, $c = count($bits), $l = false; $i < $c; $i++, $l = !$l) {
  15913. if (!$l) {
  15914. if ($bits[$i] === '') {
  15915. continue;
  15916. }
  15917. $token[] = new HTMLPurifier_Token_Text($bits[$i]);
  15918. } else {
  15919. $token[] = new HTMLPurifier_Token_Start(
  15920. 'a',
  15921. array('href' => str_replace('%s', $bits[$i], $this->docURL))
  15922. );
  15923. $token[] = new HTMLPurifier_Token_Text('%' . $bits[$i]);
  15924. $token[] = new HTMLPurifier_Token_End('a');
  15925. }
  15926. }
  15927. }
  15928. }
  15929. class HTMLPurifier_Injector_RemoveEmpty extends HTMLPurifier_Injector
  15930. {
  15931. /**
  15932. * @type HTMLPurifier_Context
  15933. */
  15934. private $context;
  15935. /**
  15936. * @type HTMLPurifier_Config
  15937. */
  15938. private $config;
  15939. /**
  15940. * @type HTMLPurifier_AttrValidator
  15941. */
  15942. private $attrValidator;
  15943. /**
  15944. * @type bool
  15945. */
  15946. private $removeNbsp;
  15947. /**
  15948. * @type bool
  15949. */
  15950. private $removeNbspExceptions;
  15951. /**
  15952. * Cached contents of %AutoFormat.RemoveEmpty.Predicate
  15953. * @type array
  15954. */
  15955. private $exclude;
  15956. /**
  15957. * @param HTMLPurifier_Config $config
  15958. * @param HTMLPurifier_Context $context
  15959. * @return void
  15960. */
  15961. public function prepare($config, $context)
  15962. {
  15963. parent::prepare($config, $context);
  15964. $this->config = $config;
  15965. $this->context = $context;
  15966. $this->removeNbsp = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp');
  15967. $this->removeNbspExceptions = $config->get('AutoFormat.RemoveEmpty.RemoveNbsp.Exceptions');
  15968. $this->exclude = $config->get('AutoFormat.RemoveEmpty.Predicate');
  15969. foreach ($this->exclude as $key => $attrs) {
  15970. if (!is_array($attrs)) {
  15971. // HACK, see HTMLPurifier/Printer/ConfigForm.php
  15972. $this->exclude[$key] = explode(';', $attrs);
  15973. }
  15974. }
  15975. $this->attrValidator = new HTMLPurifier_AttrValidator();
  15976. }
  15977. /**
  15978. * @param HTMLPurifier_Token $token
  15979. */
  15980. public function handleElement(&$token)
  15981. {
  15982. if (!$token instanceof HTMLPurifier_Token_Start) {
  15983. return;
  15984. }
  15985. $next = false;
  15986. $deleted = 1; // the current tag
  15987. for ($i = count($this->inputZipper->back) - 1; $i >= 0; $i--, $deleted++) {
  15988. $next = $this->inputZipper->back[$i];
  15989. if ($next instanceof HTMLPurifier_Token_Text) {
  15990. if ($next->is_whitespace) {
  15991. continue;
  15992. }
  15993. if ($this->removeNbsp && !isset($this->removeNbspExceptions[$token->name])) {
  15994. $plain = str_replace("\xC2\xA0", "", $next->data);
  15995. $isWsOrNbsp = $plain === '' || ctype_space($plain);
  15996. if ($isWsOrNbsp) {
  15997. continue;
  15998. }
  15999. }
  16000. }
  16001. break;
  16002. }
  16003. if (!$next || ($next instanceof HTMLPurifier_Token_End && $next->name == $token->name)) {
  16004. $this->attrValidator->validateToken($token, $this->config, $this->context);
  16005. $token->armor['ValidateAttributes'] = true;
  16006. if (isset($this->exclude[$token->name])) {
  16007. $r = true;
  16008. foreach ($this->exclude[$token->name] as $elem) {
  16009. if (!isset($token->attr[$elem])) $r = false;
  16010. }
  16011. if ($r) return;
  16012. }
  16013. if (isset($token->attr['id']) || isset($token->attr['name'])) {
  16014. return;
  16015. }
  16016. $token = $deleted + 1;
  16017. for ($b = 0, $c = count($this->inputZipper->front); $b < $c; $b++) {
  16018. $prev = $this->inputZipper->front[$b];
  16019. if ($prev instanceof HTMLPurifier_Token_Text && $prev->is_whitespace) {
  16020. continue;
  16021. }
  16022. break;
  16023. }
  16024. // This is safe because we removed the token that triggered this.
  16025. $this->rewindOffset($b+$deleted);
  16026. return;
  16027. }
  16028. }
  16029. }
  16030. /**
  16031. * Injector that removes spans with no attributes
  16032. */
  16033. class HTMLPurifier_Injector_RemoveSpansWithoutAttributes extends HTMLPurifier_Injector
  16034. {
  16035. /**
  16036. * @type string
  16037. */
  16038. public $name = 'RemoveSpansWithoutAttributes';
  16039. /**
  16040. * @type array
  16041. */
  16042. public $needed = array('span');
  16043. /**
  16044. * @type HTMLPurifier_AttrValidator
  16045. */
  16046. private $attrValidator;
  16047. /**
  16048. * Used by AttrValidator.
  16049. * @type HTMLPurifier_Config
  16050. */
  16051. private $config;
  16052. /**
  16053. * @type HTMLPurifier_Context
  16054. */
  16055. private $context;
  16056. public function prepare($config, $context)
  16057. {
  16058. $this->attrValidator = new HTMLPurifier_AttrValidator();
  16059. $this->config = $config;
  16060. $this->context = $context;
  16061. return parent::prepare($config, $context);
  16062. }
  16063. /**
  16064. * @param HTMLPurifier_Token $token
  16065. */
  16066. public function handleElement(&$token)
  16067. {
  16068. if ($token->name !== 'span' || !$token instanceof HTMLPurifier_Token_Start) {
  16069. return;
  16070. }
  16071. // We need to validate the attributes now since this doesn't normally
  16072. // happen until after MakeWellFormed. If all the attributes are removed
  16073. // the span needs to be removed too.
  16074. $this->attrValidator->validateToken($token, $this->config, $this->context);
  16075. $token->armor['ValidateAttributes'] = true;
  16076. if (!empty($token->attr)) {
  16077. return;
  16078. }
  16079. $nesting = 0;
  16080. while ($this->forwardUntilEndToken($i, $current, $nesting)) {
  16081. }
  16082. if ($current instanceof HTMLPurifier_Token_End && $current->name === 'span') {
  16083. // Mark closing span tag for deletion
  16084. $current->markForDeletion = true;
  16085. // Delete open span tag
  16086. $token = false;
  16087. }
  16088. }
  16089. /**
  16090. * @param HTMLPurifier_Token $token
  16091. */
  16092. public function handleEnd(&$token)
  16093. {
  16094. if ($token->markForDeletion) {
  16095. $token = false;
  16096. }
  16097. }
  16098. }
  16099. /**
  16100. * Adds important param elements to inside of object in order to make
  16101. * things safe.
  16102. */
  16103. class HTMLPurifier_Injector_SafeObject extends HTMLPurifier_Injector
  16104. {
  16105. /**
  16106. * @type string
  16107. */
  16108. public $name = 'SafeObject';
  16109. /**
  16110. * @type array
  16111. */
  16112. public $needed = array('object', 'param');
  16113. /**
  16114. * @type array
  16115. */
  16116. protected $objectStack = array();
  16117. /**
  16118. * @type array
  16119. */
  16120. protected $paramStack = array();
  16121. /**
  16122. * Keep this synchronized with AttrTransform/SafeParam.php.
  16123. * @type array
  16124. */
  16125. protected $addParam = array(
  16126. 'allowScriptAccess' => 'never',
  16127. 'allowNetworking' => 'internal',
  16128. );
  16129. /**
  16130. * These are all lower-case keys.
  16131. * @type array
  16132. */
  16133. protected $allowedParam = array(
  16134. 'wmode' => true,
  16135. 'movie' => true,
  16136. 'flashvars' => true,
  16137. 'src' => true,
  16138. 'allowfullscreen' => true, // if omitted, assume to be 'false'
  16139. );
  16140. /**
  16141. * @param HTMLPurifier_Config $config
  16142. * @param HTMLPurifier_Context $context
  16143. * @return void
  16144. */
  16145. public function prepare($config, $context)
  16146. {
  16147. parent::prepare($config, $context);
  16148. }
  16149. /**
  16150. * @param HTMLPurifier_Token $token
  16151. */
  16152. public function handleElement(&$token)
  16153. {
  16154. if ($token->name == 'object') {
  16155. $this->objectStack[] = $token;
  16156. $this->paramStack[] = array();
  16157. $new = array($token);
  16158. foreach ($this->addParam as $name => $value) {
  16159. $new[] = new HTMLPurifier_Token_Empty('param', array('name' => $name, 'value' => $value));
  16160. }
  16161. $token = $new;
  16162. } elseif ($token->name == 'param') {
  16163. $nest = count($this->currentNesting) - 1;
  16164. if ($nest >= 0 && $this->currentNesting[$nest]->name === 'object') {
  16165. $i = count($this->objectStack) - 1;
  16166. if (!isset($token->attr['name'])) {
  16167. $token = false;
  16168. return;
  16169. }
  16170. $n = $token->attr['name'];
  16171. // We need this fix because YouTube doesn't supply a data
  16172. // attribute, which we need if a type is specified. This is
  16173. // *very* Flash specific.
  16174. if (!isset($this->objectStack[$i]->attr['data']) &&
  16175. ($token->attr['name'] == 'movie' || $token->attr['name'] == 'src')
  16176. ) {
  16177. $this->objectStack[$i]->attr['data'] = $token->attr['value'];
  16178. }
  16179. // Check if the parameter is the correct value but has not
  16180. // already been added
  16181. if (!isset($this->paramStack[$i][$n]) &&
  16182. isset($this->addParam[$n]) &&
  16183. $token->attr['name'] === $this->addParam[$n]) {
  16184. // keep token, and add to param stack
  16185. $this->paramStack[$i][$n] = true;
  16186. } elseif (isset($this->allowedParam[strtolower($n)])) {
  16187. // keep token, don't do anything to it
  16188. // (could possibly check for duplicates here)
  16189. // Note: In principle, parameters should be case sensitive.
  16190. // But it seems they are not really; so accept any case.
  16191. } else {
  16192. $token = false;
  16193. }
  16194. } else {
  16195. // not directly inside an object, DENY!
  16196. $token = false;
  16197. }
  16198. }
  16199. }
  16200. public function handleEnd(&$token)
  16201. {
  16202. // This is the WRONG way of handling the object and param stacks;
  16203. // we should be inserting them directly on the relevant object tokens
  16204. // so that the global stack handling handles it.
  16205. if ($token->name == 'object') {
  16206. array_pop($this->objectStack);
  16207. array_pop($this->paramStack);
  16208. }
  16209. }
  16210. }
  16211. /**
  16212. * Parser that uses PHP 5's DOM extension (part of the core).
  16213. *
  16214. * In PHP 5, the DOM XML extension was revamped into DOM and added to the core.
  16215. * It gives us a forgiving HTML parser, which we use to transform the HTML
  16216. * into a DOM, and then into the tokens. It is blazingly fast (for large
  16217. * documents, it performs twenty times faster than
  16218. * HTMLPurifier_Lexer_DirectLex,and is the default choice for PHP 5.
  16219. *
  16220. * @note Any empty elements will have empty tokens associated with them, even if
  16221. * this is prohibited by the spec. This is cannot be fixed until the spec
  16222. * comes into play.
  16223. *
  16224. * @note PHP's DOM extension does not actually parse any entities, we use
  16225. * our own function to do that.
  16226. *
  16227. * @warning DOM tends to drop whitespace, which may wreak havoc on indenting.
  16228. * If this is a huge problem, due to the fact that HTML is hand
  16229. * edited and you are unable to get a parser cache that caches the
  16230. * the output of HTML Purifier while keeping the original HTML lying
  16231. * around, you may want to run Tidy on the resulting output or use
  16232. * HTMLPurifier_DirectLex
  16233. */
  16234. class HTMLPurifier_Lexer_DOMLex extends HTMLPurifier_Lexer
  16235. {
  16236. /**
  16237. * @type HTMLPurifier_TokenFactory
  16238. */
  16239. private $factory;
  16240. public function __construct()
  16241. {
  16242. // setup the factory
  16243. parent::__construct();
  16244. $this->factory = new HTMLPurifier_TokenFactory();
  16245. }
  16246. /**
  16247. * @param string $html
  16248. * @param HTMLPurifier_Config $config
  16249. * @param HTMLPurifier_Context $context
  16250. * @return HTMLPurifier_Token[]
  16251. */
  16252. public function tokenizeHTML($html, $config, $context)
  16253. {
  16254. $html = $this->normalize($html, $config, $context);
  16255. // attempt to armor stray angled brackets that cannot possibly
  16256. // form tags and thus are probably being used as emoticons
  16257. if ($config->get('Core.AggressivelyFixLt')) {
  16258. $char = '[^a-z!\/]';
  16259. $comment = "/<!--(.*?)(-->|\z)/is";
  16260. $html = preg_replace_callback($comment, array($this, 'callbackArmorCommentEntities'), $html);
  16261. do {
  16262. $old = $html;
  16263. $html = preg_replace("/<($char)/i", '&lt;\\1', $html);
  16264. } while ($html !== $old);
  16265. $html = preg_replace_callback($comment, array($this, 'callbackUndoCommentSubst'), $html); // fix comments
  16266. }
  16267. // preprocess html, essential for UTF-8
  16268. $html = $this->wrapHTML($html, $config, $context);
  16269. $doc = new DOMDocument();
  16270. $doc->encoding = 'UTF-8'; // theoretically, the above has this covered
  16271. set_error_handler(array($this, 'muteErrorHandler'));
  16272. $doc->loadHTML($html);
  16273. restore_error_handler();
  16274. $tokens = array();
  16275. $this->tokenizeDOM(
  16276. $doc->getElementsByTagName('html')->item(0)-> // <html>
  16277. getElementsByTagName('body')->item(0), // <body>
  16278. $tokens
  16279. );
  16280. return $tokens;
  16281. }
  16282. /**
  16283. * Iterative function that tokenizes a node, putting it into an accumulator.
  16284. * To iterate is human, to recurse divine - L. Peter Deutsch
  16285. * @param DOMNode $node DOMNode to be tokenized.
  16286. * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens.
  16287. * @return HTMLPurifier_Token of node appended to previously passed tokens.
  16288. */
  16289. protected function tokenizeDOM($node, &$tokens)
  16290. {
  16291. $level = 0;
  16292. $nodes = array($level => new HTMLPurifier_Queue(array($node)));
  16293. $closingNodes = array();
  16294. do {
  16295. while (!$nodes[$level]->isEmpty()) {
  16296. $node = $nodes[$level]->shift(); // FIFO
  16297. $collect = $level > 0 ? true : false;
  16298. $needEndingTag = $this->createStartNode($node, $tokens, $collect);
  16299. if ($needEndingTag) {
  16300. $closingNodes[$level][] = $node;
  16301. }
  16302. if ($node->childNodes && $node->childNodes->length) {
  16303. $level++;
  16304. $nodes[$level] = new HTMLPurifier_Queue();
  16305. foreach ($node->childNodes as $childNode) {
  16306. $nodes[$level]->push($childNode);
  16307. }
  16308. }
  16309. }
  16310. $level--;
  16311. if ($level && isset($closingNodes[$level])) {
  16312. while ($node = array_pop($closingNodes[$level])) {
  16313. $this->createEndNode($node, $tokens);
  16314. }
  16315. }
  16316. } while ($level > 0);
  16317. }
  16318. /**
  16319. * @param DOMNode $node DOMNode to be tokenized.
  16320. * @param HTMLPurifier_Token[] $tokens Array-list of already tokenized tokens.
  16321. * @param bool $collect Says whether or start and close are collected, set to
  16322. * false at first recursion because it's the implicit DIV
  16323. * tag you're dealing with.
  16324. * @return bool if the token needs an endtoken
  16325. * @todo data and tagName properties don't seem to exist in DOMNode?
  16326. */
  16327. protected function createStartNode($node, &$tokens, $collect)
  16328. {
  16329. // intercept non element nodes. WE MUST catch all of them,
  16330. // but we're not getting the character reference nodes because
  16331. // those should have been preprocessed
  16332. if ($node->nodeType === XML_TEXT_NODE) {
  16333. $tokens[] = $this->factory->createText($node->data);
  16334. return false;
  16335. } elseif ($node->nodeType === XML_CDATA_SECTION_NODE) {
  16336. // undo libxml's special treatment of <script> and <style> tags
  16337. $last = end($tokens);
  16338. $data = $node->data;
  16339. // (note $node->tagname is already normalized)
  16340. if ($last instanceof HTMLPurifier_Token_Start && ($last->name == 'script' || $last->name == 'style')) {
  16341. $new_data = trim($data);
  16342. if (substr($new_data, 0, 4) === '<!--') {
  16343. $data = substr($new_data, 4);
  16344. if (substr($data, -3) === '-->') {
  16345. $data = substr($data, 0, -3);
  16346. } else {
  16347. // Highly suspicious! Not sure what to do...
  16348. }
  16349. }
  16350. }
  16351. $tokens[] = $this->factory->createText($this->parseData($data));
  16352. return false;
  16353. } elseif ($node->nodeType === XML_COMMENT_NODE) {
  16354. // this is code is only invoked for comments in script/style in versions
  16355. // of libxml pre-2.6.28 (regular comments, of course, are still
  16356. // handled regularly)
  16357. $tokens[] = $this->factory->createComment($node->data);
  16358. return false;
  16359. } elseif ($node->nodeType !== XML_ELEMENT_NODE) {
  16360. // not-well tested: there may be other nodes we have to grab
  16361. return false;
  16362. }
  16363. $attr = $node->hasAttributes() ? $this->transformAttrToAssoc($node->attributes) : array();
  16364. // We still have to make sure that the element actually IS empty
  16365. if (!$node->childNodes->length) {
  16366. if ($collect) {
  16367. $tokens[] = $this->factory->createEmpty($node->tagName, $attr);
  16368. }
  16369. return false;
  16370. } else {
  16371. if ($collect) {
  16372. $tokens[] = $this->factory->createStart(
  16373. $tag_name = $node->tagName, // somehow, it get's dropped
  16374. $attr
  16375. );
  16376. }
  16377. return true;
  16378. }
  16379. }
  16380. /**
  16381. * @param DOMNode $node
  16382. * @param HTMLPurifier_Token[] $tokens
  16383. */
  16384. protected function createEndNode($node, &$tokens)
  16385. {
  16386. $tokens[] = $this->factory->createEnd($node->tagName);
  16387. }
  16388. /**
  16389. * Converts a DOMNamedNodeMap of DOMAttr objects into an assoc array.
  16390. *
  16391. * @param DOMNamedNodeMap $node_map DOMNamedNodeMap of DOMAttr objects.
  16392. * @return array Associative array of attributes.
  16393. */
  16394. protected function transformAttrToAssoc($node_map)
  16395. {
  16396. // NamedNodeMap is documented very well, so we're using undocumented
  16397. // features, namely, the fact that it implements Iterator and
  16398. // has a ->length attribute
  16399. if ($node_map->length === 0) {
  16400. return array();
  16401. }
  16402. $array = array();
  16403. foreach ($node_map as $attr) {
  16404. $array[$attr->name] = $attr->value;
  16405. }
  16406. return $array;
  16407. }
  16408. /**
  16409. * An error handler that mutes all errors
  16410. * @param int $errno
  16411. * @param string $errstr
  16412. */
  16413. public function muteErrorHandler($errno, $errstr)
  16414. {
  16415. }
  16416. /**
  16417. * Callback function for undoing escaping of stray angled brackets
  16418. * in comments
  16419. * @param array $matches
  16420. * @return string
  16421. */
  16422. public function callbackUndoCommentSubst($matches)
  16423. {
  16424. return '<!--' . strtr($matches[1], array('&amp;' => '&', '&lt;' => '<')) . $matches[2];
  16425. }
  16426. /**
  16427. * Callback function that entity-izes ampersands in comments so that
  16428. * callbackUndoCommentSubst doesn't clobber them
  16429. * @param array $matches
  16430. * @return string
  16431. */
  16432. public function callbackArmorCommentEntities($matches)
  16433. {
  16434. return '<!--' . str_replace('&', '&amp;', $matches[1]) . $matches[2];
  16435. }
  16436. /**
  16437. * Wraps an HTML fragment in the necessary HTML
  16438. * @param string $html
  16439. * @param HTMLPurifier_Config $config
  16440. * @param HTMLPurifier_Context $context
  16441. * @return string
  16442. */
  16443. protected function wrapHTML($html, $config, $context)
  16444. {
  16445. $def = $config->getDefinition('HTML');
  16446. $ret = '';
  16447. if (!empty($def->doctype->dtdPublic) || !empty($def->doctype->dtdSystem)) {
  16448. $ret .= '<!DOCTYPE html ';
  16449. if (!empty($def->doctype->dtdPublic)) {
  16450. $ret .= 'PUBLIC "' . $def->doctype->dtdPublic . '" ';
  16451. }
  16452. if (!empty($def->doctype->dtdSystem)) {
  16453. $ret .= '"' . $def->doctype->dtdSystem . '" ';
  16454. }
  16455. $ret .= '>';
  16456. }
  16457. $ret .= '<html><head>';
  16458. $ret .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
  16459. // No protection if $html contains a stray </div>!
  16460. $ret .= '</head><body>' . $html . '</body></html>';
  16461. return $ret;
  16462. }
  16463. }
  16464. /**
  16465. * Our in-house implementation of a parser.
  16466. *
  16467. * A pure PHP parser, DirectLex has absolutely no dependencies, making
  16468. * it a reasonably good default for PHP4. Written with efficiency in mind,
  16469. * it can be four times faster than HTMLPurifier_Lexer_PEARSax3, although it
  16470. * pales in comparison to HTMLPurifier_Lexer_DOMLex.
  16471. *
  16472. * @todo Reread XML spec and document differences.
  16473. */
  16474. class HTMLPurifier_Lexer_DirectLex extends HTMLPurifier_Lexer
  16475. {
  16476. /**
  16477. * @type bool
  16478. */
  16479. public $tracksLineNumbers = true;
  16480. /**
  16481. * Whitespace characters for str(c)spn.
  16482. * @type string
  16483. */
  16484. protected $_whitespace = "\x20\x09\x0D\x0A";
  16485. /**
  16486. * Callback function for script CDATA fudge
  16487. * @param array $matches, in form of array(opening tag, contents, closing tag)
  16488. * @return string
  16489. */
  16490. protected function scriptCallback($matches)
  16491. {
  16492. return $matches[1] . htmlspecialchars($matches[2], ENT_COMPAT, 'UTF-8') . $matches[3];
  16493. }
  16494. /**
  16495. * @param String $html
  16496. * @param HTMLPurifier_Config $config
  16497. * @param HTMLPurifier_Context $context
  16498. * @return array|HTMLPurifier_Token[]
  16499. */
  16500. public function tokenizeHTML($html, $config, $context)
  16501. {
  16502. // special normalization for script tags without any armor
  16503. // our "armor" heurstic is a < sign any number of whitespaces after
  16504. // the first script tag
  16505. if ($config->get('HTML.Trusted')) {
  16506. $html = preg_replace_callback(
  16507. '#(<script[^>]*>)(\s*[^<].+?)(</script>)#si',
  16508. array($this, 'scriptCallback'),
  16509. $html
  16510. );
  16511. }
  16512. $html = $this->normalize($html, $config, $context);
  16513. $cursor = 0; // our location in the text
  16514. $inside_tag = false; // whether or not we're parsing the inside of a tag
  16515. $array = array(); // result array
  16516. // This is also treated to mean maintain *column* numbers too
  16517. $maintain_line_numbers = $config->get('Core.MaintainLineNumbers');
  16518. if ($maintain_line_numbers === null) {
  16519. // automatically determine line numbering by checking
  16520. // if error collection is on
  16521. $maintain_line_numbers = $config->get('Core.CollectErrors');
  16522. }
  16523. if ($maintain_line_numbers) {
  16524. $current_line = 1;
  16525. $current_col = 0;
  16526. $length = strlen($html);
  16527. } else {
  16528. $current_line = false;
  16529. $current_col = false;
  16530. $length = false;
  16531. }
  16532. $context->register('CurrentLine', $current_line);
  16533. $context->register('CurrentCol', $current_col);
  16534. $nl = "\n";
  16535. // how often to manually recalculate. This will ALWAYS be right,
  16536. // but it's pretty wasteful. Set to 0 to turn off
  16537. $synchronize_interval = $config->get('Core.DirectLexLineNumberSyncInterval');
  16538. $e = false;
  16539. if ($config->get('Core.CollectErrors')) {
  16540. $e =& $context->get('ErrorCollector');
  16541. }
  16542. // for testing synchronization
  16543. $loops = 0;
  16544. while (++$loops) {
  16545. // $cursor is either at the start of a token, or inside of
  16546. // a tag (i.e. there was a < immediately before it), as indicated
  16547. // by $inside_tag
  16548. if ($maintain_line_numbers) {
  16549. // $rcursor, however, is always at the start of a token.
  16550. $rcursor = $cursor - (int)$inside_tag;
  16551. // Column number is cheap, so we calculate it every round.
  16552. // We're interested at the *end* of the newline string, so
  16553. // we need to add strlen($nl) == 1 to $nl_pos before subtracting it
  16554. // from our "rcursor" position.
  16555. $nl_pos = strrpos($html, $nl, $rcursor - $length);
  16556. $current_col = $rcursor - (is_bool($nl_pos) ? 0 : $nl_pos + 1);
  16557. // recalculate lines
  16558. if ($synchronize_interval && // synchronization is on
  16559. $cursor > 0 && // cursor is further than zero
  16560. $loops % $synchronize_interval === 0) { // time to synchronize!
  16561. $current_line = 1 + $this->substrCount($html, $nl, 0, $cursor);
  16562. }
  16563. }
  16564. $position_next_lt = strpos($html, '<', $cursor);
  16565. $position_next_gt = strpos($html, '>', $cursor);
  16566. // triggers on "<b>asdf</b>" but not "asdf <b></b>"
  16567. // special case to set up context
  16568. if ($position_next_lt === $cursor) {
  16569. $inside_tag = true;
  16570. $cursor++;
  16571. }
  16572. if (!$inside_tag && $position_next_lt !== false) {
  16573. // We are not inside tag and there still is another tag to parse
  16574. $token = new
  16575. HTMLPurifier_Token_Text(
  16576. $this->parseData(
  16577. substr(
  16578. $html,
  16579. $cursor,
  16580. $position_next_lt - $cursor
  16581. )
  16582. )
  16583. );
  16584. if ($maintain_line_numbers) {
  16585. $token->rawPosition($current_line, $current_col);
  16586. $current_line += $this->substrCount($html, $nl, $cursor, $position_next_lt - $cursor);
  16587. }
  16588. $array[] = $token;
  16589. $cursor = $position_next_lt + 1;
  16590. $inside_tag = true;
  16591. continue;
  16592. } elseif (!$inside_tag) {
  16593. // We are not inside tag but there are no more tags
  16594. // If we're already at the end, break
  16595. if ($cursor === strlen($html)) {
  16596. break;
  16597. }
  16598. // Create Text of rest of string
  16599. $token = new
  16600. HTMLPurifier_Token_Text(
  16601. $this->parseData(
  16602. substr(
  16603. $html,
  16604. $cursor
  16605. )
  16606. )
  16607. );
  16608. if ($maintain_line_numbers) {
  16609. $token->rawPosition($current_line, $current_col);
  16610. }
  16611. $array[] = $token;
  16612. break;
  16613. } elseif ($inside_tag && $position_next_gt !== false) {
  16614. // We are in tag and it is well formed
  16615. // Grab the internals of the tag
  16616. $strlen_segment = $position_next_gt - $cursor;
  16617. if ($strlen_segment < 1) {
  16618. // there's nothing to process!
  16619. $token = new HTMLPurifier_Token_Text('<');
  16620. $cursor++;
  16621. continue;
  16622. }
  16623. $segment = substr($html, $cursor, $strlen_segment);
  16624. if ($segment === false) {
  16625. // somehow, we attempted to access beyond the end of
  16626. // the string, defense-in-depth, reported by Nate Abele
  16627. break;
  16628. }
  16629. // Check if it's a comment
  16630. if (substr($segment, 0, 3) === '!--') {
  16631. // re-determine segment length, looking for -->
  16632. $position_comment_end = strpos($html, '-->', $cursor);
  16633. if ($position_comment_end === false) {
  16634. // uh oh, we have a comment that extends to
  16635. // infinity. Can't be helped: set comment
  16636. // end position to end of string
  16637. if ($e) {
  16638. $e->send(E_WARNING, 'Lexer: Unclosed comment');
  16639. }
  16640. $position_comment_end = strlen($html);
  16641. $end = true;
  16642. } else {
  16643. $end = false;
  16644. }
  16645. $strlen_segment = $position_comment_end - $cursor;
  16646. $segment = substr($html, $cursor, $strlen_segment);
  16647. $token = new
  16648. HTMLPurifier_Token_Comment(
  16649. substr(
  16650. $segment,
  16651. 3,
  16652. $strlen_segment - 3
  16653. )
  16654. );
  16655. if ($maintain_line_numbers) {
  16656. $token->rawPosition($current_line, $current_col);
  16657. $current_line += $this->substrCount($html, $nl, $cursor, $strlen_segment);
  16658. }
  16659. $array[] = $token;
  16660. $cursor = $end ? $position_comment_end : $position_comment_end + 3;
  16661. $inside_tag = false;
  16662. continue;
  16663. }
  16664. // Check if it's an end tag
  16665. $is_end_tag = (strpos($segment, '/') === 0);
  16666. if ($is_end_tag) {
  16667. $type = substr($segment, 1);
  16668. $token = new HTMLPurifier_Token_End($type);
  16669. if ($maintain_line_numbers) {
  16670. $token->rawPosition($current_line, $current_col);
  16671. $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
  16672. }
  16673. $array[] = $token;
  16674. $inside_tag = false;
  16675. $cursor = $position_next_gt + 1;
  16676. continue;
  16677. }
  16678. // Check leading character is alnum, if not, we may
  16679. // have accidently grabbed an emoticon. Translate into
  16680. // text and go our merry way
  16681. if (!ctype_alpha($segment[0])) {
  16682. // XML: $segment[0] !== '_' && $segment[0] !== ':'
  16683. if ($e) {
  16684. $e->send(E_NOTICE, 'Lexer: Unescaped lt');
  16685. }
  16686. $token = new HTMLPurifier_Token_Text('<');
  16687. if ($maintain_line_numbers) {
  16688. $token->rawPosition($current_line, $current_col);
  16689. $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
  16690. }
  16691. $array[] = $token;
  16692. $inside_tag = false;
  16693. continue;
  16694. }
  16695. // Check if it is explicitly self closing, if so, remove
  16696. // trailing slash. Remember, we could have a tag like <br>, so
  16697. // any later token processing scripts must convert improperly
  16698. // classified EmptyTags from StartTags.
  16699. $is_self_closing = (strrpos($segment, '/') === $strlen_segment - 1);
  16700. if ($is_self_closing) {
  16701. $strlen_segment--;
  16702. $segment = substr($segment, 0, $strlen_segment);
  16703. }
  16704. // Check if there are any attributes
  16705. $position_first_space = strcspn($segment, $this->_whitespace);
  16706. if ($position_first_space >= $strlen_segment) {
  16707. if ($is_self_closing) {
  16708. $token = new HTMLPurifier_Token_Empty($segment);
  16709. } else {
  16710. $token = new HTMLPurifier_Token_Start($segment);
  16711. }
  16712. if ($maintain_line_numbers) {
  16713. $token->rawPosition($current_line, $current_col);
  16714. $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
  16715. }
  16716. $array[] = $token;
  16717. $inside_tag = false;
  16718. $cursor = $position_next_gt + 1;
  16719. continue;
  16720. }
  16721. // Grab out all the data
  16722. $type = substr($segment, 0, $position_first_space);
  16723. $attribute_string =
  16724. trim(
  16725. substr(
  16726. $segment,
  16727. $position_first_space
  16728. )
  16729. );
  16730. if ($attribute_string) {
  16731. $attr = $this->parseAttributeString(
  16732. $attribute_string,
  16733. $config,
  16734. $context
  16735. );
  16736. } else {
  16737. $attr = array();
  16738. }
  16739. if ($is_self_closing) {
  16740. $token = new HTMLPurifier_Token_Empty($type, $attr);
  16741. } else {
  16742. $token = new HTMLPurifier_Token_Start($type, $attr);
  16743. }
  16744. if ($maintain_line_numbers) {
  16745. $token->rawPosition($current_line, $current_col);
  16746. $current_line += $this->substrCount($html, $nl, $cursor, $position_next_gt - $cursor);
  16747. }
  16748. $array[] = $token;
  16749. $cursor = $position_next_gt + 1;
  16750. $inside_tag = false;
  16751. continue;
  16752. } else {
  16753. // inside tag, but there's no ending > sign
  16754. if ($e) {
  16755. $e->send(E_WARNING, 'Lexer: Missing gt');
  16756. }
  16757. $token = new
  16758. HTMLPurifier_Token_Text(
  16759. '<' .
  16760. $this->parseData(
  16761. substr($html, $cursor)
  16762. )
  16763. );
  16764. if ($maintain_line_numbers) {
  16765. $token->rawPosition($current_line, $current_col);
  16766. }
  16767. // no cursor scroll? Hmm...
  16768. $array[] = $token;
  16769. break;
  16770. }
  16771. break;
  16772. }
  16773. $context->destroy('CurrentLine');
  16774. $context->destroy('CurrentCol');
  16775. return $array;
  16776. }
  16777. /**
  16778. * PHP 5.0.x compatible substr_count that implements offset and length
  16779. * @param string $haystack
  16780. * @param string $needle
  16781. * @param int $offset
  16782. * @param int $length
  16783. * @return int
  16784. */
  16785. protected function substrCount($haystack, $needle, $offset, $length)
  16786. {
  16787. static $oldVersion;
  16788. if ($oldVersion === null) {
  16789. $oldVersion = version_compare(PHP_VERSION, '5.1', '<');
  16790. }
  16791. if ($oldVersion) {
  16792. $haystack = substr($haystack, $offset, $length);
  16793. return substr_count($haystack, $needle);
  16794. } else {
  16795. return substr_count($haystack, $needle, $offset, $length);
  16796. }
  16797. }
  16798. /**
  16799. * Takes the inside of an HTML tag and makes an assoc array of attributes.
  16800. *
  16801. * @param string $string Inside of tag excluding name.
  16802. * @param HTMLPurifier_Config $config
  16803. * @param HTMLPurifier_Context $context
  16804. * @return array Assoc array of attributes.
  16805. */
  16806. public function parseAttributeString($string, $config, $context)
  16807. {
  16808. $string = (string)$string; // quick typecast
  16809. if ($string == '') {
  16810. return array();
  16811. } // no attributes
  16812. $e = false;
  16813. if ($config->get('Core.CollectErrors')) {
  16814. $e =& $context->get('ErrorCollector');
  16815. }
  16816. // let's see if we can abort as quickly as possible
  16817. // one equal sign, no spaces => one attribute
  16818. $num_equal = substr_count($string, '=');
  16819. $has_space = strpos($string, ' ');
  16820. if ($num_equal === 0 && !$has_space) {
  16821. // bool attribute
  16822. return array($string => $string);
  16823. } elseif ($num_equal === 1 && !$has_space) {
  16824. // only one attribute
  16825. list($key, $quoted_value) = explode('=', $string);
  16826. $quoted_value = trim($quoted_value);
  16827. if (!$key) {
  16828. if ($e) {
  16829. $e->send(E_ERROR, 'Lexer: Missing attribute key');
  16830. }
  16831. return array();
  16832. }
  16833. if (!$quoted_value) {
  16834. return array($key => '');
  16835. }
  16836. $first_char = @$quoted_value[0];
  16837. $last_char = @$quoted_value[strlen($quoted_value) - 1];
  16838. $same_quote = ($first_char == $last_char);
  16839. $open_quote = ($first_char == '"' || $first_char == "'");
  16840. if ($same_quote && $open_quote) {
  16841. // well behaved
  16842. $value = substr($quoted_value, 1, strlen($quoted_value) - 2);
  16843. } else {
  16844. // not well behaved
  16845. if ($open_quote) {
  16846. if ($e) {
  16847. $e->send(E_ERROR, 'Lexer: Missing end quote');
  16848. }
  16849. $value = substr($quoted_value, 1);
  16850. } else {
  16851. $value = $quoted_value;
  16852. }
  16853. }
  16854. if ($value === false) {
  16855. $value = '';
  16856. }
  16857. return array($key => $this->parseData($value));
  16858. }
  16859. // setup loop environment
  16860. $array = array(); // return assoc array of attributes
  16861. $cursor = 0; // current position in string (moves forward)
  16862. $size = strlen($string); // size of the string (stays the same)
  16863. // if we have unquoted attributes, the parser expects a terminating
  16864. // space, so let's guarantee that there's always a terminating space.
  16865. $string .= ' ';
  16866. $old_cursor = -1;
  16867. while ($cursor < $size) {
  16868. if ($old_cursor >= $cursor) {
  16869. throw new Exception("Infinite loop detected");
  16870. }
  16871. $old_cursor = $cursor;
  16872. $cursor += ($value = strspn($string, $this->_whitespace, $cursor));
  16873. // grab the key
  16874. $key_begin = $cursor; //we're currently at the start of the key
  16875. // scroll past all characters that are the key (not whitespace or =)
  16876. $cursor += strcspn($string, $this->_whitespace . '=', $cursor);
  16877. $key_end = $cursor; // now at the end of the key
  16878. $key = substr($string, $key_begin, $key_end - $key_begin);
  16879. if (!$key) {
  16880. if ($e) {
  16881. $e->send(E_ERROR, 'Lexer: Missing attribute key');
  16882. }
  16883. $cursor += 1 + strcspn($string, $this->_whitespace, $cursor + 1); // prevent infinite loop
  16884. continue; // empty key
  16885. }
  16886. // scroll past all whitespace
  16887. $cursor += strspn($string, $this->_whitespace, $cursor);
  16888. if ($cursor >= $size) {
  16889. $array[$key] = $key;
  16890. break;
  16891. }
  16892. // if the next character is an equal sign, we've got a regular
  16893. // pair, otherwise, it's a bool attribute
  16894. $first_char = @$string[$cursor];
  16895. if ($first_char == '=') {
  16896. // key="value"
  16897. $cursor++;
  16898. $cursor += strspn($string, $this->_whitespace, $cursor);
  16899. if ($cursor === false) {
  16900. $array[$key] = '';
  16901. break;
  16902. }
  16903. // we might be in front of a quote right now
  16904. $char = @$string[$cursor];
  16905. if ($char == '"' || $char == "'") {
  16906. // it's quoted, end bound is $char
  16907. $cursor++;
  16908. $value_begin = $cursor;
  16909. $cursor = strpos($string, $char, $cursor);
  16910. $value_end = $cursor;
  16911. } else {
  16912. // it's not quoted, end bound is whitespace
  16913. $value_begin = $cursor;
  16914. $cursor += strcspn($string, $this->_whitespace, $cursor);
  16915. $value_end = $cursor;
  16916. }
  16917. // we reached a premature end
  16918. if ($cursor === false) {
  16919. $cursor = $size;
  16920. $value_end = $cursor;
  16921. }
  16922. $value = substr($string, $value_begin, $value_end - $value_begin);
  16923. if ($value === false) {
  16924. $value = '';
  16925. }
  16926. $array[$key] = $this->parseData($value);
  16927. $cursor++;
  16928. } else {
  16929. // boolattr
  16930. if ($key !== '') {
  16931. $array[$key] = $key;
  16932. } else {
  16933. // purely theoretical
  16934. if ($e) {
  16935. $e->send(E_ERROR, 'Lexer: Missing attribute key');
  16936. }
  16937. }
  16938. }
  16939. }
  16940. return $array;
  16941. }
  16942. }
  16943. /**
  16944. * Concrete comment node class.
  16945. */
  16946. class HTMLPurifier_Node_Comment extends HTMLPurifier_Node
  16947. {
  16948. /**
  16949. * Character data within comment.
  16950. * @type string
  16951. */
  16952. public $data;
  16953. /**
  16954. * @type bool
  16955. */
  16956. public $is_whitespace = true;
  16957. /**
  16958. * Transparent constructor.
  16959. *
  16960. * @param string $data String comment data.
  16961. * @param int $line
  16962. * @param int $col
  16963. */
  16964. public function __construct($data, $line = null, $col = null)
  16965. {
  16966. $this->data = $data;
  16967. $this->line = $line;
  16968. $this->col = $col;
  16969. }
  16970. public function toTokenPair() {
  16971. return array(new HTMLPurifier_Token_Comment($this->data, $this->line, $this->col), null);
  16972. }
  16973. }
  16974. /**
  16975. * Concrete element node class.
  16976. */
  16977. class HTMLPurifier_Node_Element extends HTMLPurifier_Node
  16978. {
  16979. /**
  16980. * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.
  16981. *
  16982. * @note Strictly speaking, XML tags are case sensitive, so we shouldn't
  16983. * be lower-casing them, but these tokens cater to HTML tags, which are
  16984. * insensitive.
  16985. * @type string
  16986. */
  16987. public $name;
  16988. /**
  16989. * Associative array of the node's attributes.
  16990. * @type array
  16991. */
  16992. public $attr = array();
  16993. /**
  16994. * List of child elements.
  16995. * @type array
  16996. */
  16997. public $children = array();
  16998. /**
  16999. * Does this use the <a></a> form or the </a> form, i.e.
  17000. * is it a pair of start/end tokens or an empty token.
  17001. * @bool
  17002. */
  17003. public $empty = false;
  17004. public $endCol = null, $endLine = null, $endArmor = array();
  17005. public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array()) {
  17006. $this->name = $name;
  17007. $this->attr = $attr;
  17008. $this->line = $line;
  17009. $this->col = $col;
  17010. $this->armor = $armor;
  17011. }
  17012. public function toTokenPair() {
  17013. // XXX inefficiency here, normalization is not necessary
  17014. if ($this->empty) {
  17015. return array(new HTMLPurifier_Token_Empty($this->name, $this->attr, $this->line, $this->col, $this->armor), null);
  17016. } else {
  17017. $start = new HTMLPurifier_Token_Start($this->name, $this->attr, $this->line, $this->col, $this->armor);
  17018. $end = new HTMLPurifier_Token_End($this->name, array(), $this->endLine, $this->endCol, $this->endArmor);
  17019. //$end->start = $start;
  17020. return array($start, $end);
  17021. }
  17022. }
  17023. }
  17024. /**
  17025. * Concrete text token class.
  17026. *
  17027. * Text tokens comprise of regular parsed character data (PCDATA) and raw
  17028. * character data (from the CDATA sections). Internally, their
  17029. * data is parsed with all entities expanded. Surprisingly, the text token
  17030. * does have a "tag name" called #PCDATA, which is how the DTD represents it
  17031. * in permissible child nodes.
  17032. */
  17033. class HTMLPurifier_Node_Text extends HTMLPurifier_Node
  17034. {
  17035. /**
  17036. * PCDATA tag name compatible with DTD, see
  17037. * HTMLPurifier_ChildDef_Custom for details.
  17038. * @type string
  17039. */
  17040. public $name = '#PCDATA';
  17041. /**
  17042. * @type string
  17043. */
  17044. public $data;
  17045. /**< Parsed character data of text. */
  17046. /**
  17047. * @type bool
  17048. */
  17049. public $is_whitespace;
  17050. /**< Bool indicating if node is whitespace. */
  17051. /**
  17052. * Constructor, accepts data and determines if it is whitespace.
  17053. * @param string $data String parsed character data.
  17054. * @param int $line
  17055. * @param int $col
  17056. */
  17057. public function __construct($data, $is_whitespace, $line = null, $col = null)
  17058. {
  17059. $this->data = $data;
  17060. $this->is_whitespace = $is_whitespace;
  17061. $this->line = $line;
  17062. $this->col = $col;
  17063. }
  17064. public function toTokenPair() {
  17065. return array(new HTMLPurifier_Token_Text($this->data, $this->line, $this->col), null);
  17066. }
  17067. }
  17068. /**
  17069. * Composite strategy that runs multiple strategies on tokens.
  17070. */
  17071. abstract class HTMLPurifier_Strategy_Composite extends HTMLPurifier_Strategy
  17072. {
  17073. /**
  17074. * List of strategies to run tokens through.
  17075. * @type HTMLPurifier_Strategy[]
  17076. */
  17077. protected $strategies = array();
  17078. /**
  17079. * @param HTMLPurifier_Token[] $tokens
  17080. * @param HTMLPurifier_Config $config
  17081. * @param HTMLPurifier_Context $context
  17082. * @return HTMLPurifier_Token[]
  17083. */
  17084. public function execute($tokens, $config, $context)
  17085. {
  17086. foreach ($this->strategies as $strategy) {
  17087. $tokens = $strategy->execute($tokens, $config, $context);
  17088. }
  17089. return $tokens;
  17090. }
  17091. }
  17092. /**
  17093. * Core strategy composed of the big four strategies.
  17094. */
  17095. class HTMLPurifier_Strategy_Core extends HTMLPurifier_Strategy_Composite
  17096. {
  17097. public function __construct()
  17098. {
  17099. $this->strategies[] = new HTMLPurifier_Strategy_RemoveForeignElements();
  17100. $this->strategies[] = new HTMLPurifier_Strategy_MakeWellFormed();
  17101. $this->strategies[] = new HTMLPurifier_Strategy_FixNesting();
  17102. $this->strategies[] = new HTMLPurifier_Strategy_ValidateAttributes();
  17103. }
  17104. }
  17105. /**
  17106. * Takes a well formed list of tokens and fixes their nesting.
  17107. *
  17108. * HTML elements dictate which elements are allowed to be their children,
  17109. * for example, you can't have a p tag in a span tag. Other elements have
  17110. * much more rigorous definitions: tables, for instance, require a specific
  17111. * order for their elements. There are also constraints not expressible by
  17112. * document type definitions, such as the chameleon nature of ins/del
  17113. * tags and global child exclusions.
  17114. *
  17115. * The first major objective of this strategy is to iterate through all
  17116. * the nodes and determine whether or not their children conform to the
  17117. * element's definition. If they do not, the child definition may
  17118. * optionally supply an amended list of elements that is valid or
  17119. * require that the entire node be deleted (and the previous node
  17120. * rescanned).
  17121. *
  17122. * The second objective is to ensure that explicitly excluded elements of
  17123. * an element do not appear in its children. Code that accomplishes this
  17124. * task is pervasive through the strategy, though the two are distinct tasks
  17125. * and could, theoretically, be seperated (although it's not recommended).
  17126. *
  17127. * @note Whether or not unrecognized children are silently dropped or
  17128. * translated into text depends on the child definitions.
  17129. *
  17130. * @todo Enable nodes to be bubbled out of the structure. This is
  17131. * easier with our new algorithm.
  17132. */
  17133. class HTMLPurifier_Strategy_FixNesting extends HTMLPurifier_Strategy
  17134. {
  17135. /**
  17136. * @param HTMLPurifier_Token[] $tokens
  17137. * @param HTMLPurifier_Config $config
  17138. * @param HTMLPurifier_Context $context
  17139. * @return array|HTMLPurifier_Token[]
  17140. */
  17141. public function execute($tokens, $config, $context)
  17142. {
  17143. //####################################################################//
  17144. // Pre-processing
  17145. // O(n) pass to convert to a tree, so that we can efficiently
  17146. // refer to substrings
  17147. $top_node = HTMLPurifier_Arborize::arborize($tokens, $config, $context);
  17148. // get a copy of the HTML definition
  17149. $definition = $config->getHTMLDefinition();
  17150. $excludes_enabled = !$config->get('Core.DisableExcludes');
  17151. // setup the context variable 'IsInline', for chameleon processing
  17152. // is 'false' when we are not inline, 'true' when it must always
  17153. // be inline, and an integer when it is inline for a certain
  17154. // branch of the document tree
  17155. $is_inline = $definition->info_parent_def->descendants_are_inline;
  17156. $context->register('IsInline', $is_inline);
  17157. // setup error collector
  17158. $e =& $context->get('ErrorCollector', true);
  17159. //####################################################################//
  17160. // Loop initialization
  17161. // stack that contains all elements that are excluded
  17162. // it is organized by parent elements, similar to $stack,
  17163. // but it is only populated when an element with exclusions is
  17164. // processed, i.e. there won't be empty exclusions.
  17165. $exclude_stack = array($definition->info_parent_def->excludes);
  17166. // variable that contains the start token while we are processing
  17167. // nodes. This enables error reporting to do its job
  17168. $node = $top_node;
  17169. // dummy token
  17170. list($token, $d) = $node->toTokenPair();
  17171. $context->register('CurrentNode', $node);
  17172. $context->register('CurrentToken', $token);
  17173. //####################################################################//
  17174. // Loop
  17175. // We need to implement a post-order traversal iteratively, to
  17176. // avoid running into stack space limits. This is pretty tricky
  17177. // to reason about, so we just manually stack-ify the recursive
  17178. // variant:
  17179. //
  17180. // function f($node) {
  17181. // foreach ($node->children as $child) {
  17182. // f($child);
  17183. // }
  17184. // validate($node);
  17185. // }
  17186. //
  17187. // Thus, we will represent a stack frame as array($node,
  17188. // $is_inline, stack of children)
  17189. // e.g. array_reverse($node->children) - already processed
  17190. // children.
  17191. $parent_def = $definition->info_parent_def;
  17192. $stack = array(
  17193. array($top_node,
  17194. $parent_def->descendants_are_inline,
  17195. $parent_def->excludes, // exclusions
  17196. 0)
  17197. );
  17198. while (!empty($stack)) {
  17199. list($node, $is_inline, $excludes, $ix) = array_pop($stack);
  17200. // recursive call
  17201. $go = false;
  17202. $def = empty($stack) ? $definition->info_parent_def : $definition->info[$node->name];
  17203. while (isset($node->children[$ix])) {
  17204. $child = $node->children[$ix++];
  17205. if ($child instanceof HTMLPurifier_Node_Element) {
  17206. $go = true;
  17207. $stack[] = array($node, $is_inline, $excludes, $ix);
  17208. $stack[] = array($child,
  17209. // ToDo: I don't think it matters if it's def or
  17210. // child_def, but double check this...
  17211. $is_inline || $def->descendants_are_inline,
  17212. empty($def->excludes) ? $excludes
  17213. : array_merge($excludes, $def->excludes),
  17214. 0);
  17215. break;
  17216. }
  17217. };
  17218. if ($go) continue;
  17219. list($token, $d) = $node->toTokenPair();
  17220. // base case
  17221. if ($excludes_enabled && isset($excludes[$node->name])) {
  17222. $node->dead = true;
  17223. if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node excluded');
  17224. } else {
  17225. // XXX I suppose it would be slightly more efficient to
  17226. // avoid the allocation here and have children
  17227. // strategies handle it
  17228. $children = array();
  17229. foreach ($node->children as $child) {
  17230. if (!$child->dead) $children[] = $child;
  17231. }
  17232. $result = $def->child->validateChildren($children, $config, $context);
  17233. if ($result === true) {
  17234. // nop
  17235. $node->children = $children;
  17236. } elseif ($result === false) {
  17237. $node->dead = true;
  17238. if ($e) $e->send(E_ERROR, 'Strategy_FixNesting: Node removed');
  17239. } else {
  17240. $node->children = $result;
  17241. if ($e) {
  17242. // XXX This will miss mutations of internal nodes. Perhaps defer to the child validators
  17243. if (empty($result) && !empty($children)) {
  17244. $e->send(E_ERROR, 'Strategy_FixNesting: Node contents removed');
  17245. } else if ($result != $children) {
  17246. $e->send(E_WARNING, 'Strategy_FixNesting: Node reorganized');
  17247. }
  17248. }
  17249. }
  17250. }
  17251. }
  17252. //####################################################################//
  17253. // Post-processing
  17254. // remove context variables
  17255. $context->destroy('IsInline');
  17256. $context->destroy('CurrentNode');
  17257. $context->destroy('CurrentToken');
  17258. //####################################################################//
  17259. // Return
  17260. return HTMLPurifier_Arborize::flatten($node, $config, $context);
  17261. }
  17262. }
  17263. /**
  17264. * Takes tokens makes them well-formed (balance end tags, etc.)
  17265. *
  17266. * Specification of the armor attributes this strategy uses:
  17267. *
  17268. * - MakeWellFormed_TagClosedError: This armor field is used to
  17269. * suppress tag closed errors for certain tokens [TagClosedSuppress],
  17270. * in particular, if a tag was generated automatically by HTML
  17271. * Purifier, we may rely on our infrastructure to close it for us
  17272. * and shouldn't report an error to the user [TagClosedAuto].
  17273. */
  17274. class HTMLPurifier_Strategy_MakeWellFormed extends HTMLPurifier_Strategy
  17275. {
  17276. /**
  17277. * Array stream of tokens being processed.
  17278. * @type HTMLPurifier_Token[]
  17279. */
  17280. protected $tokens;
  17281. /**
  17282. * Current token.
  17283. * @type HTMLPurifier_Token
  17284. */
  17285. protected $token;
  17286. /**
  17287. * Zipper managing the true state.
  17288. * @type HTMLPurifier_Zipper
  17289. */
  17290. protected $zipper;
  17291. /**
  17292. * Current nesting of elements.
  17293. * @type array
  17294. */
  17295. protected $stack;
  17296. /**
  17297. * Injectors active in this stream processing.
  17298. * @type HTMLPurifier_Injector[]
  17299. */
  17300. protected $injectors;
  17301. /**
  17302. * Current instance of HTMLPurifier_Config.
  17303. * @type HTMLPurifier_Config
  17304. */
  17305. protected $config;
  17306. /**
  17307. * Current instance of HTMLPurifier_Context.
  17308. * @type HTMLPurifier_Context
  17309. */
  17310. protected $context;
  17311. /**
  17312. * @param HTMLPurifier_Token[] $tokens
  17313. * @param HTMLPurifier_Config $config
  17314. * @param HTMLPurifier_Context $context
  17315. * @return HTMLPurifier_Token[]
  17316. * @throws HTMLPurifier_Exception
  17317. */
  17318. public function execute($tokens, $config, $context)
  17319. {
  17320. $definition = $config->getHTMLDefinition();
  17321. // local variables
  17322. $generator = new HTMLPurifier_Generator($config, $context);
  17323. $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
  17324. // used for autoclose early abortion
  17325. $global_parent_allowed_elements = $definition->info_parent_def->child->getAllowedElements($config);
  17326. $e = $context->get('ErrorCollector', true);
  17327. $i = false; // injector index
  17328. list($zipper, $token) = HTMLPurifier_Zipper::fromArray($tokens);
  17329. if ($token === NULL) {
  17330. return array();
  17331. }
  17332. $reprocess = false; // whether or not to reprocess the same token
  17333. $stack = array();
  17334. // member variables
  17335. $this->stack =& $stack;
  17336. $this->tokens =& $tokens;
  17337. $this->token =& $token;
  17338. $this->zipper =& $zipper;
  17339. $this->config = $config;
  17340. $this->context = $context;
  17341. // context variables
  17342. $context->register('CurrentNesting', $stack);
  17343. $context->register('InputZipper', $zipper);
  17344. $context->register('CurrentToken', $token);
  17345. // -- begin INJECTOR --
  17346. $this->injectors = array();
  17347. $injectors = $config->getBatch('AutoFormat');
  17348. $def_injectors = $definition->info_injector;
  17349. $custom_injectors = $injectors['Custom'];
  17350. unset($injectors['Custom']); // special case
  17351. foreach ($injectors as $injector => $b) {
  17352. // XXX: Fix with a legitimate lookup table of enabled filters
  17353. if (strpos($injector, '.') !== false) {
  17354. continue;
  17355. }
  17356. $injector = "HTMLPurifier_Injector_$injector";
  17357. if (!$b) {
  17358. continue;
  17359. }
  17360. $this->injectors[] = new $injector;
  17361. }
  17362. foreach ($def_injectors as $injector) {
  17363. // assumed to be objects
  17364. $this->injectors[] = $injector;
  17365. }
  17366. foreach ($custom_injectors as $injector) {
  17367. if (!$injector) {
  17368. continue;
  17369. }
  17370. if (is_string($injector)) {
  17371. $injector = "HTMLPurifier_Injector_$injector";
  17372. $injector = new $injector;
  17373. }
  17374. $this->injectors[] = $injector;
  17375. }
  17376. // give the injectors references to the definition and context
  17377. // variables for performance reasons
  17378. foreach ($this->injectors as $ix => $injector) {
  17379. $error = $injector->prepare($config, $context);
  17380. if (!$error) {
  17381. continue;
  17382. }
  17383. array_splice($this->injectors, $ix, 1); // rm the injector
  17384. trigger_error("Cannot enable {$injector->name} injector because $error is not allowed", E_USER_WARNING);
  17385. }
  17386. // -- end INJECTOR --
  17387. // a note on reprocessing:
  17388. // In order to reduce code duplication, whenever some code needs
  17389. // to make HTML changes in order to make things "correct", the
  17390. // new HTML gets sent through the purifier, regardless of its
  17391. // status. This means that if we add a start token, because it
  17392. // was totally necessary, we don't have to update nesting; we just
  17393. // punt ($reprocess = true; continue;) and it does that for us.
  17394. // isset is in loop because $tokens size changes during loop exec
  17395. for (;;
  17396. // only increment if we don't need to reprocess
  17397. $reprocess ? $reprocess = false : $token = $zipper->next($token)) {
  17398. // check for a rewind
  17399. if (is_int($i)) {
  17400. // possibility: disable rewinding if the current token has a
  17401. // rewind set on it already. This would offer protection from
  17402. // infinite loop, but might hinder some advanced rewinding.
  17403. $rewind_offset = $this->injectors[$i]->getRewindOffset();
  17404. if (is_int($rewind_offset)) {
  17405. for ($j = 0; $j < $rewind_offset; $j++) {
  17406. if (empty($zipper->front)) break;
  17407. $token = $zipper->prev($token);
  17408. // indicate that other injectors should not process this token,
  17409. // but we need to reprocess it
  17410. unset($token->skip[$i]);
  17411. $token->rewind = $i;
  17412. if ($token instanceof HTMLPurifier_Token_Start) {
  17413. array_pop($this->stack);
  17414. } elseif ($token instanceof HTMLPurifier_Token_End) {
  17415. $this->stack[] = $token->start;
  17416. }
  17417. }
  17418. }
  17419. $i = false;
  17420. }
  17421. // handle case of document end
  17422. if ($token === NULL) {
  17423. // kill processing if stack is empty
  17424. if (empty($this->stack)) {
  17425. break;
  17426. }
  17427. // peek
  17428. $top_nesting = array_pop($this->stack);
  17429. $this->stack[] = $top_nesting;
  17430. // send error [TagClosedSuppress]
  17431. if ($e && !isset($top_nesting->armor['MakeWellFormed_TagClosedError'])) {
  17432. $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by document end', $top_nesting);
  17433. }
  17434. // append, don't splice, since this is the end
  17435. $token = new HTMLPurifier_Token_End($top_nesting->name);
  17436. // punt!
  17437. $reprocess = true;
  17438. continue;
  17439. }
  17440. //echo '<br>'; printZipper($zipper, $token);//printTokens($this->stack);
  17441. //flush();
  17442. // quick-check: if it's not a tag, no need to process
  17443. if (empty($token->is_tag)) {
  17444. if ($token instanceof HTMLPurifier_Token_Text) {
  17445. foreach ($this->injectors as $i => $injector) {
  17446. if (isset($token->skip[$i])) {
  17447. continue;
  17448. }
  17449. if ($token->rewind !== null && $token->rewind !== $i) {
  17450. continue;
  17451. }
  17452. // XXX fuckup
  17453. $r = $token;
  17454. $injector->handleText($r);
  17455. $token = $this->processToken($r, $i);
  17456. $reprocess = true;
  17457. break;
  17458. }
  17459. }
  17460. // another possibility is a comment
  17461. continue;
  17462. }
  17463. if (isset($definition->info[$token->name])) {
  17464. $type = $definition->info[$token->name]->child->type;
  17465. } else {
  17466. $type = false; // Type is unknown, treat accordingly
  17467. }
  17468. // quick tag checks: anything that's *not* an end tag
  17469. $ok = false;
  17470. if ($type === 'empty' && $token instanceof HTMLPurifier_Token_Start) {
  17471. // claims to be a start tag but is empty
  17472. $token = new HTMLPurifier_Token_Empty(
  17473. $token->name,
  17474. $token->attr,
  17475. $token->line,
  17476. $token->col,
  17477. $token->armor
  17478. );
  17479. $ok = true;
  17480. } elseif ($type && $type !== 'empty' && $token instanceof HTMLPurifier_Token_Empty) {
  17481. // claims to be empty but really is a start tag
  17482. // NB: this assignment is required
  17483. $old_token = $token;
  17484. $token = new HTMLPurifier_Token_End($token->name);
  17485. $token = $this->insertBefore(
  17486. new HTMLPurifier_Token_Start($old_token->name, $old_token->attr, $old_token->line, $old_token->col, $old_token->armor)
  17487. );
  17488. // punt (since we had to modify the input stream in a non-trivial way)
  17489. $reprocess = true;
  17490. continue;
  17491. } elseif ($token instanceof HTMLPurifier_Token_Empty) {
  17492. // real empty token
  17493. $ok = true;
  17494. } elseif ($token instanceof HTMLPurifier_Token_Start) {
  17495. // start tag
  17496. // ...unless they also have to close their parent
  17497. if (!empty($this->stack)) {
  17498. // Performance note: you might think that it's rather
  17499. // inefficient, recalculating the autoclose information
  17500. // for every tag that a token closes (since when we
  17501. // do an autoclose, we push a new token into the
  17502. // stream and then /process/ that, before
  17503. // re-processing this token.) But this is
  17504. // necessary, because an injector can make an
  17505. // arbitrary transformations to the autoclosing
  17506. // tokens we introduce, so things may have changed
  17507. // in the meantime. Also, doing the inefficient thing is
  17508. // "easy" to reason about (for certain perverse definitions
  17509. // of "easy")
  17510. $parent = array_pop($this->stack);
  17511. $this->stack[] = $parent;
  17512. $parent_def = null;
  17513. $parent_elements = null;
  17514. $autoclose = false;
  17515. if (isset($definition->info[$parent->name])) {
  17516. $parent_def = $definition->info[$parent->name];
  17517. $parent_elements = $parent_def->child->getAllowedElements($config);
  17518. $autoclose = !isset($parent_elements[$token->name]);
  17519. }
  17520. if ($autoclose && $definition->info[$token->name]->wrap) {
  17521. // Check if an element can be wrapped by another
  17522. // element to make it valid in a context (for
  17523. // example, <ul><ul> needs a <li> in between)
  17524. $wrapname = $definition->info[$token->name]->wrap;
  17525. $wrapdef = $definition->info[$wrapname];
  17526. $elements = $wrapdef->child->getAllowedElements($config);
  17527. if (isset($elements[$token->name]) && isset($parent_elements[$wrapname])) {
  17528. $newtoken = new HTMLPurifier_Token_Start($wrapname);
  17529. $token = $this->insertBefore($newtoken);
  17530. $reprocess = true;
  17531. continue;
  17532. }
  17533. }
  17534. $carryover = false;
  17535. if ($autoclose && $parent_def->formatting) {
  17536. $carryover = true;
  17537. }
  17538. if ($autoclose) {
  17539. // check if this autoclose is doomed to fail
  17540. // (this rechecks $parent, which his harmless)
  17541. $autoclose_ok = isset($global_parent_allowed_elements[$token->name]);
  17542. if (!$autoclose_ok) {
  17543. foreach ($this->stack as $ancestor) {
  17544. $elements = $definition->info[$ancestor->name]->child->getAllowedElements($config);
  17545. if (isset($elements[$token->name])) {
  17546. $autoclose_ok = true;
  17547. break;
  17548. }
  17549. if ($definition->info[$token->name]->wrap) {
  17550. $wrapname = $definition->info[$token->name]->wrap;
  17551. $wrapdef = $definition->info[$wrapname];
  17552. $wrap_elements = $wrapdef->child->getAllowedElements($config);
  17553. if (isset($wrap_elements[$token->name]) && isset($elements[$wrapname])) {
  17554. $autoclose_ok = true;
  17555. break;
  17556. }
  17557. }
  17558. }
  17559. }
  17560. if ($autoclose_ok) {
  17561. // errors need to be updated
  17562. $new_token = new HTMLPurifier_Token_End($parent->name);
  17563. $new_token->start = $parent;
  17564. // [TagClosedSuppress]
  17565. if ($e && !isset($parent->armor['MakeWellFormed_TagClosedError'])) {
  17566. if (!$carryover) {
  17567. $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag auto closed', $parent);
  17568. } else {
  17569. $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag carryover', $parent);
  17570. }
  17571. }
  17572. if ($carryover) {
  17573. $element = clone $parent;
  17574. // [TagClosedAuto]
  17575. $element->armor['MakeWellFormed_TagClosedError'] = true;
  17576. $element->carryover = true;
  17577. $token = $this->processToken(array($new_token, $token, $element));
  17578. } else {
  17579. $token = $this->insertBefore($new_token);
  17580. }
  17581. } else {
  17582. $token = $this->remove();
  17583. }
  17584. $reprocess = true;
  17585. continue;
  17586. }
  17587. }
  17588. $ok = true;
  17589. }
  17590. if ($ok) {
  17591. foreach ($this->injectors as $i => $injector) {
  17592. if (isset($token->skip[$i])) {
  17593. continue;
  17594. }
  17595. if ($token->rewind !== null && $token->rewind !== $i) {
  17596. continue;
  17597. }
  17598. $r = $token;
  17599. $injector->handleElement($r);
  17600. $token = $this->processToken($r, $i);
  17601. $reprocess = true;
  17602. break;
  17603. }
  17604. if (!$reprocess) {
  17605. // ah, nothing interesting happened; do normal processing
  17606. if ($token instanceof HTMLPurifier_Token_Start) {
  17607. $this->stack[] = $token;
  17608. } elseif ($token instanceof HTMLPurifier_Token_End) {
  17609. throw new HTMLPurifier_Exception(
  17610. 'Improper handling of end tag in start code; possible error in MakeWellFormed'
  17611. );
  17612. }
  17613. }
  17614. continue;
  17615. }
  17616. // sanity check: we should be dealing with a closing tag
  17617. if (!$token instanceof HTMLPurifier_Token_End) {
  17618. throw new HTMLPurifier_Exception('Unaccounted for tag token in input stream, bug in HTML Purifier');
  17619. }
  17620. // make sure that we have something open
  17621. if (empty($this->stack)) {
  17622. if ($escape_invalid_tags) {
  17623. if ($e) {
  17624. $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag to text');
  17625. }
  17626. $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
  17627. } else {
  17628. if ($e) {
  17629. $e->send(E_WARNING, 'Strategy_MakeWellFormed: Unnecessary end tag removed');
  17630. }
  17631. $token = $this->remove();
  17632. }
  17633. $reprocess = true;
  17634. continue;
  17635. }
  17636. // first, check for the simplest case: everything closes neatly.
  17637. // Eventually, everything passes through here; if there are problems
  17638. // we modify the input stream accordingly and then punt, so that
  17639. // the tokens get processed again.
  17640. $current_parent = array_pop($this->stack);
  17641. if ($current_parent->name == $token->name) {
  17642. $token->start = $current_parent;
  17643. foreach ($this->injectors as $i => $injector) {
  17644. if (isset($token->skip[$i])) {
  17645. continue;
  17646. }
  17647. if ($token->rewind !== null && $token->rewind !== $i) {
  17648. continue;
  17649. }
  17650. $r = $token;
  17651. $injector->handleEnd($r);
  17652. $token = $this->processToken($r, $i);
  17653. $this->stack[] = $current_parent;
  17654. $reprocess = true;
  17655. break;
  17656. }
  17657. continue;
  17658. }
  17659. // okay, so we're trying to close the wrong tag
  17660. // undo the pop previous pop
  17661. $this->stack[] = $current_parent;
  17662. // scroll back the entire nest, trying to find our tag.
  17663. // (feature could be to specify how far you'd like to go)
  17664. $size = count($this->stack);
  17665. // -2 because -1 is the last element, but we already checked that
  17666. $skipped_tags = false;
  17667. for ($j = $size - 2; $j >= 0; $j--) {
  17668. if ($this->stack[$j]->name == $token->name) {
  17669. $skipped_tags = array_slice($this->stack, $j);
  17670. break;
  17671. }
  17672. }
  17673. // we didn't find the tag, so remove
  17674. if ($skipped_tags === false) {
  17675. if ($escape_invalid_tags) {
  17676. if ($e) {
  17677. $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag to text');
  17678. }
  17679. $token = new HTMLPurifier_Token_Text($generator->generateFromToken($token));
  17680. } else {
  17681. if ($e) {
  17682. $e->send(E_WARNING, 'Strategy_MakeWellFormed: Stray end tag removed');
  17683. }
  17684. $token = $this->remove();
  17685. }
  17686. $reprocess = true;
  17687. continue;
  17688. }
  17689. // do errors, in REVERSE $j order: a,b,c with </a></b></c>
  17690. $c = count($skipped_tags);
  17691. if ($e) {
  17692. for ($j = $c - 1; $j > 0; $j--) {
  17693. // notice we exclude $j == 0, i.e. the current ending tag, from
  17694. // the errors... [TagClosedSuppress]
  17695. if (!isset($skipped_tags[$j]->armor['MakeWellFormed_TagClosedError'])) {
  17696. $e->send(E_NOTICE, 'Strategy_MakeWellFormed: Tag closed by element end', $skipped_tags[$j]);
  17697. }
  17698. }
  17699. }
  17700. // insert tags, in FORWARD $j order: c,b,a with </a></b></c>
  17701. $replace = array($token);
  17702. for ($j = 1; $j < $c; $j++) {
  17703. // ...as well as from the insertions
  17704. $new_token = new HTMLPurifier_Token_End($skipped_tags[$j]->name);
  17705. $new_token->start = $skipped_tags[$j];
  17706. array_unshift($replace, $new_token);
  17707. if (isset($definition->info[$new_token->name]) && $definition->info[$new_token->name]->formatting) {
  17708. // [TagClosedAuto]
  17709. $element = clone $skipped_tags[$j];
  17710. $element->carryover = true;
  17711. $element->armor['MakeWellFormed_TagClosedError'] = true;
  17712. $replace[] = $element;
  17713. }
  17714. }
  17715. $token = $this->processToken($replace);
  17716. $reprocess = true;
  17717. continue;
  17718. }
  17719. $context->destroy('CurrentToken');
  17720. $context->destroy('CurrentNesting');
  17721. $context->destroy('InputZipper');
  17722. unset($this->injectors, $this->stack, $this->tokens);
  17723. return $zipper->toArray($token);
  17724. }
  17725. /**
  17726. * Processes arbitrary token values for complicated substitution patterns.
  17727. * In general:
  17728. *
  17729. * If $token is an array, it is a list of tokens to substitute for the
  17730. * current token. These tokens then get individually processed. If there
  17731. * is a leading integer in the list, that integer determines how many
  17732. * tokens from the stream should be removed.
  17733. *
  17734. * If $token is a regular token, it is swapped with the current token.
  17735. *
  17736. * If $token is false, the current token is deleted.
  17737. *
  17738. * If $token is an integer, that number of tokens (with the first token
  17739. * being the current one) will be deleted.
  17740. *
  17741. * @param HTMLPurifier_Token|array|int|bool $token Token substitution value
  17742. * @param HTMLPurifier_Injector|int $injector Injector that performed the substitution; default is if
  17743. * this is not an injector related operation.
  17744. * @throws HTMLPurifier_Exception
  17745. */
  17746. protected function processToken($token, $injector = -1)
  17747. {
  17748. // normalize forms of token
  17749. if (is_object($token)) {
  17750. $token = array(1, $token);
  17751. }
  17752. if (is_int($token)) {
  17753. $token = array($token);
  17754. }
  17755. if ($token === false) {
  17756. $token = array(1);
  17757. }
  17758. if (!is_array($token)) {
  17759. throw new HTMLPurifier_Exception('Invalid token type from injector');
  17760. }
  17761. if (!is_int($token[0])) {
  17762. array_unshift($token, 1);
  17763. }
  17764. if ($token[0] === 0) {
  17765. throw new HTMLPurifier_Exception('Deleting zero tokens is not valid');
  17766. }
  17767. // $token is now an array with the following form:
  17768. // array(number nodes to delete, new node 1, new node 2, ...)
  17769. $delete = array_shift($token);
  17770. list($old, $r) = $this->zipper->splice($this->token, $delete, $token);
  17771. if ($injector > -1) {
  17772. // determine appropriate skips
  17773. $oldskip = isset($old[0]) ? $old[0]->skip : array();
  17774. foreach ($token as $object) {
  17775. $object->skip = $oldskip;
  17776. $object->skip[$injector] = true;
  17777. }
  17778. }
  17779. return $r;
  17780. }
  17781. /**
  17782. * Inserts a token before the current token. Cursor now points to
  17783. * this token. You must reprocess after this.
  17784. * @param HTMLPurifier_Token $token
  17785. */
  17786. private function insertBefore($token)
  17787. {
  17788. // NB not $this->zipper->insertBefore(), due to positioning
  17789. // differences
  17790. $splice = $this->zipper->splice($this->token, 0, array($token));
  17791. return $splice[1];
  17792. }
  17793. /**
  17794. * Removes current token. Cursor now points to new token occupying previously
  17795. * occupied space. You must reprocess after this.
  17796. */
  17797. private function remove()
  17798. {
  17799. return $this->zipper->delete();
  17800. }
  17801. }
  17802. /**
  17803. * Removes all unrecognized tags from the list of tokens.
  17804. *
  17805. * This strategy iterates through all the tokens and removes unrecognized
  17806. * tokens. If a token is not recognized but a TagTransform is defined for
  17807. * that element, the element will be transformed accordingly.
  17808. */
  17809. class HTMLPurifier_Strategy_RemoveForeignElements extends HTMLPurifier_Strategy
  17810. {
  17811. /**
  17812. * @param HTMLPurifier_Token[] $tokens
  17813. * @param HTMLPurifier_Config $config
  17814. * @param HTMLPurifier_Context $context
  17815. * @return array|HTMLPurifier_Token[]
  17816. */
  17817. public function execute($tokens, $config, $context)
  17818. {
  17819. $definition = $config->getHTMLDefinition();
  17820. $generator = new HTMLPurifier_Generator($config, $context);
  17821. $result = array();
  17822. $escape_invalid_tags = $config->get('Core.EscapeInvalidTags');
  17823. $remove_invalid_img = $config->get('Core.RemoveInvalidImg');
  17824. // currently only used to determine if comments should be kept
  17825. $trusted = $config->get('HTML.Trusted');
  17826. $comment_lookup = $config->get('HTML.AllowedComments');
  17827. $comment_regexp = $config->get('HTML.AllowedCommentsRegexp');
  17828. $check_comments = $comment_lookup !== array() || $comment_regexp !== null;
  17829. $remove_script_contents = $config->get('Core.RemoveScriptContents');
  17830. $hidden_elements = $config->get('Core.HiddenElements');
  17831. // remove script contents compatibility
  17832. if ($remove_script_contents === true) {
  17833. $hidden_elements['script'] = true;
  17834. } elseif ($remove_script_contents === false && isset($hidden_elements['script'])) {
  17835. unset($hidden_elements['script']);
  17836. }
  17837. $attr_validator = new HTMLPurifier_AttrValidator();
  17838. // removes tokens until it reaches a closing tag with its value
  17839. $remove_until = false;
  17840. // converts comments into text tokens when this is equal to a tag name
  17841. $textify_comments = false;
  17842. $token = false;
  17843. $context->register('CurrentToken', $token);
  17844. $e = false;
  17845. if ($config->get('Core.CollectErrors')) {
  17846. $e =& $context->get('ErrorCollector');
  17847. }
  17848. foreach ($tokens as $token) {
  17849. if ($remove_until) {
  17850. if (empty($token->is_tag) || $token->name !== $remove_until) {
  17851. continue;
  17852. }
  17853. }
  17854. if (!empty($token->is_tag)) {
  17855. // DEFINITION CALL
  17856. // before any processing, try to transform the element
  17857. if (isset($definition->info_tag_transform[$token->name])) {
  17858. $original_name = $token->name;
  17859. // there is a transformation for this tag
  17860. // DEFINITION CALL
  17861. $token = $definition->
  17862. info_tag_transform[$token->name]->transform($token, $config, $context);
  17863. if ($e) {
  17864. $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Tag transform', $original_name);
  17865. }
  17866. }
  17867. if (isset($definition->info[$token->name])) {
  17868. // mostly everything's good, but
  17869. // we need to make sure required attributes are in order
  17870. if (($token instanceof HTMLPurifier_Token_Start || $token instanceof HTMLPurifier_Token_Empty) &&
  17871. $definition->info[$token->name]->required_attr &&
  17872. ($token->name != 'img' || $remove_invalid_img) // ensure config option still works
  17873. ) {
  17874. $attr_validator->validateToken($token, $config, $context);
  17875. $ok = true;
  17876. foreach ($definition->info[$token->name]->required_attr as $name) {
  17877. if (!isset($token->attr[$name])) {
  17878. $ok = false;
  17879. break;
  17880. }
  17881. }
  17882. if (!$ok) {
  17883. if ($e) {
  17884. $e->send(
  17885. E_ERROR,
  17886. 'Strategy_RemoveForeignElements: Missing required attribute',
  17887. $name
  17888. );
  17889. }
  17890. continue;
  17891. }
  17892. $token->armor['ValidateAttributes'] = true;
  17893. }
  17894. if (isset($hidden_elements[$token->name]) && $token instanceof HTMLPurifier_Token_Start) {
  17895. $textify_comments = $token->name;
  17896. } elseif ($token->name === $textify_comments && $token instanceof HTMLPurifier_Token_End) {
  17897. $textify_comments = false;
  17898. }
  17899. } elseif ($escape_invalid_tags) {
  17900. // invalid tag, generate HTML representation and insert in
  17901. if ($e) {
  17902. $e->send(E_WARNING, 'Strategy_RemoveForeignElements: Foreign element to text');
  17903. }
  17904. $token = new HTMLPurifier_Token_Text(
  17905. $generator->generateFromToken($token)
  17906. );
  17907. } else {
  17908. // check if we need to destroy all of the tag's children
  17909. // CAN BE GENERICIZED
  17910. if (isset($hidden_elements[$token->name])) {
  17911. if ($token instanceof HTMLPurifier_Token_Start) {
  17912. $remove_until = $token->name;
  17913. } elseif ($token instanceof HTMLPurifier_Token_Empty) {
  17914. // do nothing: we're still looking
  17915. } else {
  17916. $remove_until = false;
  17917. }
  17918. if ($e) {
  17919. $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign meta element removed');
  17920. }
  17921. } else {
  17922. if ($e) {
  17923. $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Foreign element removed');
  17924. }
  17925. }
  17926. continue;
  17927. }
  17928. } elseif ($token instanceof HTMLPurifier_Token_Comment) {
  17929. // textify comments in script tags when they are allowed
  17930. if ($textify_comments !== false) {
  17931. $data = $token->data;
  17932. $token = new HTMLPurifier_Token_Text($data);
  17933. } elseif ($trusted || $check_comments) {
  17934. // always cleanup comments
  17935. $trailing_hyphen = false;
  17936. if ($e) {
  17937. // perform check whether or not there's a trailing hyphen
  17938. if (substr($token->data, -1) == '-') {
  17939. $trailing_hyphen = true;
  17940. }
  17941. }
  17942. $token->data = rtrim($token->data, '-');
  17943. $found_double_hyphen = false;
  17944. while (strpos($token->data, '--') !== false) {
  17945. $found_double_hyphen = true;
  17946. $token->data = str_replace('--', '-', $token->data);
  17947. }
  17948. if ($trusted || !empty($comment_lookup[trim($token->data)]) ||
  17949. ($comment_regexp !== null && preg_match($comment_regexp, trim($token->data)))) {
  17950. // OK good
  17951. if ($e) {
  17952. if ($trailing_hyphen) {
  17953. $e->send(
  17954. E_NOTICE,
  17955. 'Strategy_RemoveForeignElements: Trailing hyphen in comment removed'
  17956. );
  17957. }
  17958. if ($found_double_hyphen) {
  17959. $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Hyphens in comment collapsed');
  17960. }
  17961. }
  17962. } else {
  17963. if ($e) {
  17964. $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
  17965. }
  17966. continue;
  17967. }
  17968. } else {
  17969. // strip comments
  17970. if ($e) {
  17971. $e->send(E_NOTICE, 'Strategy_RemoveForeignElements: Comment removed');
  17972. }
  17973. continue;
  17974. }
  17975. } elseif ($token instanceof HTMLPurifier_Token_Text) {
  17976. } else {
  17977. continue;
  17978. }
  17979. $result[] = $token;
  17980. }
  17981. if ($remove_until && $e) {
  17982. // we removed tokens until the end, throw error
  17983. $e->send(E_ERROR, 'Strategy_RemoveForeignElements: Token removed to end', $remove_until);
  17984. }
  17985. $context->destroy('CurrentToken');
  17986. return $result;
  17987. }
  17988. }
  17989. /**
  17990. * Validate all attributes in the tokens.
  17991. */
  17992. class HTMLPurifier_Strategy_ValidateAttributes extends HTMLPurifier_Strategy
  17993. {
  17994. /**
  17995. * @param HTMLPurifier_Token[] $tokens
  17996. * @param HTMLPurifier_Config $config
  17997. * @param HTMLPurifier_Context $context
  17998. * @return HTMLPurifier_Token[]
  17999. */
  18000. public function execute($tokens, $config, $context)
  18001. {
  18002. // setup validator
  18003. $validator = new HTMLPurifier_AttrValidator();
  18004. $token = false;
  18005. $context->register('CurrentToken', $token);
  18006. foreach ($tokens as $key => $token) {
  18007. // only process tokens that have attributes,
  18008. // namely start and empty tags
  18009. if (!$token instanceof HTMLPurifier_Token_Start && !$token instanceof HTMLPurifier_Token_Empty) {
  18010. continue;
  18011. }
  18012. // skip tokens that are armored
  18013. if (!empty($token->armor['ValidateAttributes'])) {
  18014. continue;
  18015. }
  18016. // note that we have no facilities here for removing tokens
  18017. $validator->validateToken($token, $config, $context);
  18018. }
  18019. $context->destroy('CurrentToken');
  18020. return $tokens;
  18021. }
  18022. }
  18023. /**
  18024. * Transforms FONT tags to the proper form (SPAN with CSS styling)
  18025. *
  18026. * This transformation takes the three proprietary attributes of FONT and
  18027. * transforms them into their corresponding CSS attributes. These are color,
  18028. * face, and size.
  18029. *
  18030. * @note Size is an interesting case because it doesn't map cleanly to CSS.
  18031. * Thanks to
  18032. * http://style.cleverchimp.com/font_size_intervals/altintervals.html
  18033. * for reasonable mappings.
  18034. * @warning This doesn't work completely correctly; specifically, this
  18035. * TagTransform operates before well-formedness is enforced, so
  18036. * the "active formatting elements" algorithm doesn't get applied.
  18037. */
  18038. class HTMLPurifier_TagTransform_Font extends HTMLPurifier_TagTransform
  18039. {
  18040. /**
  18041. * @type string
  18042. */
  18043. public $transform_to = 'span';
  18044. /**
  18045. * @type array
  18046. */
  18047. protected $_size_lookup = array(
  18048. '0' => 'xx-small',
  18049. '1' => 'xx-small',
  18050. '2' => 'small',
  18051. '3' => 'medium',
  18052. '4' => 'large',
  18053. '5' => 'x-large',
  18054. '6' => 'xx-large',
  18055. '7' => '300%',
  18056. '-1' => 'smaller',
  18057. '-2' => '60%',
  18058. '+1' => 'larger',
  18059. '+2' => '150%',
  18060. '+3' => '200%',
  18061. '+4' => '300%'
  18062. );
  18063. /**
  18064. * @param HTMLPurifier_Token_Tag $tag
  18065. * @param HTMLPurifier_Config $config
  18066. * @param HTMLPurifier_Context $context
  18067. * @return HTMLPurifier_Token_End|string
  18068. */
  18069. public function transform($tag, $config, $context)
  18070. {
  18071. if ($tag instanceof HTMLPurifier_Token_End) {
  18072. $new_tag = clone $tag;
  18073. $new_tag->name = $this->transform_to;
  18074. return $new_tag;
  18075. }
  18076. $attr = $tag->attr;
  18077. $prepend_style = '';
  18078. // handle color transform
  18079. if (isset($attr['color'])) {
  18080. $prepend_style .= 'color:' . $attr['color'] . ';';
  18081. unset($attr['color']);
  18082. }
  18083. // handle face transform
  18084. if (isset($attr['face'])) {
  18085. $prepend_style .= 'font-family:' . $attr['face'] . ';';
  18086. unset($attr['face']);
  18087. }
  18088. // handle size transform
  18089. if (isset($attr['size'])) {
  18090. // normalize large numbers
  18091. if ($attr['size'] !== '') {
  18092. if ($attr['size']{0} == '+' || $attr['size']{0} == '-') {
  18093. $size = (int)$attr['size'];
  18094. if ($size < -2) {
  18095. $attr['size'] = '-2';
  18096. }
  18097. if ($size > 4) {
  18098. $attr['size'] = '+4';
  18099. }
  18100. } else {
  18101. $size = (int)$attr['size'];
  18102. if ($size > 7) {
  18103. $attr['size'] = '7';
  18104. }
  18105. }
  18106. }
  18107. if (isset($this->_size_lookup[$attr['size']])) {
  18108. $prepend_style .= 'font-size:' .
  18109. $this->_size_lookup[$attr['size']] . ';';
  18110. }
  18111. unset($attr['size']);
  18112. }
  18113. if ($prepend_style) {
  18114. $attr['style'] = isset($attr['style']) ?
  18115. $prepend_style . $attr['style'] :
  18116. $prepend_style;
  18117. }
  18118. $new_tag = clone $tag;
  18119. $new_tag->name = $this->transform_to;
  18120. $new_tag->attr = $attr;
  18121. return $new_tag;
  18122. }
  18123. }
  18124. /**
  18125. * Simple transformation, just change tag name to something else,
  18126. * and possibly add some styling. This will cover most of the deprecated
  18127. * tag cases.
  18128. */
  18129. class HTMLPurifier_TagTransform_Simple extends HTMLPurifier_TagTransform
  18130. {
  18131. /**
  18132. * @type string
  18133. */
  18134. protected $style;
  18135. /**
  18136. * @param string $transform_to Tag name to transform to.
  18137. * @param string $style CSS style to add to the tag
  18138. */
  18139. public function __construct($transform_to, $style = null)
  18140. {
  18141. $this->transform_to = $transform_to;
  18142. $this->style = $style;
  18143. }
  18144. /**
  18145. * @param HTMLPurifier_Token_Tag $tag
  18146. * @param HTMLPurifier_Config $config
  18147. * @param HTMLPurifier_Context $context
  18148. * @return string
  18149. */
  18150. public function transform($tag, $config, $context)
  18151. {
  18152. $new_tag = clone $tag;
  18153. $new_tag->name = $this->transform_to;
  18154. if (!is_null($this->style) &&
  18155. ($new_tag instanceof HTMLPurifier_Token_Start || $new_tag instanceof HTMLPurifier_Token_Empty)
  18156. ) {
  18157. $this->prependCSS($new_tag->attr, $this->style);
  18158. }
  18159. return $new_tag;
  18160. }
  18161. }
  18162. /**
  18163. * Concrete comment token class. Generally will be ignored.
  18164. */
  18165. class HTMLPurifier_Token_Comment extends HTMLPurifier_Token
  18166. {
  18167. /**
  18168. * Character data within comment.
  18169. * @type string
  18170. */
  18171. public $data;
  18172. /**
  18173. * @type bool
  18174. */
  18175. public $is_whitespace = true;
  18176. /**
  18177. * Transparent constructor.
  18178. *
  18179. * @param string $data String comment data.
  18180. * @param int $line
  18181. * @param int $col
  18182. */
  18183. public function __construct($data, $line = null, $col = null)
  18184. {
  18185. $this->data = $data;
  18186. $this->line = $line;
  18187. $this->col = $col;
  18188. }
  18189. public function toNode() {
  18190. return new HTMLPurifier_Node_Comment($this->data, $this->line, $this->col);
  18191. }
  18192. }
  18193. /**
  18194. * Abstract class of a tag token (start, end or empty), and its behavior.
  18195. */
  18196. abstract class HTMLPurifier_Token_Tag extends HTMLPurifier_Token
  18197. {
  18198. /**
  18199. * Static bool marker that indicates the class is a tag.
  18200. *
  18201. * This allows us to check objects with <tt>!empty($obj->is_tag)</tt>
  18202. * without having to use a function call <tt>is_a()</tt>.
  18203. * @type bool
  18204. */
  18205. public $is_tag = true;
  18206. /**
  18207. * The lower-case name of the tag, like 'a', 'b' or 'blockquote'.
  18208. *
  18209. * @note Strictly speaking, XML tags are case sensitive, so we shouldn't
  18210. * be lower-casing them, but these tokens cater to HTML tags, which are
  18211. * insensitive.
  18212. * @type string
  18213. */
  18214. public $name;
  18215. /**
  18216. * Associative array of the tag's attributes.
  18217. * @type array
  18218. */
  18219. public $attr = array();
  18220. /**
  18221. * Non-overloaded constructor, which lower-cases passed tag name.
  18222. *
  18223. * @param string $name String name.
  18224. * @param array $attr Associative array of attributes.
  18225. * @param int $line
  18226. * @param int $col
  18227. * @param array $armor
  18228. */
  18229. public function __construct($name, $attr = array(), $line = null, $col = null, $armor = array())
  18230. {
  18231. $this->name = ctype_lower($name) ? $name : strtolower($name);
  18232. foreach ($attr as $key => $value) {
  18233. // normalization only necessary when key is not lowercase
  18234. if (!ctype_lower($key)) {
  18235. $new_key = strtolower($key);
  18236. if (!isset($attr[$new_key])) {
  18237. $attr[$new_key] = $attr[$key];
  18238. }
  18239. if ($new_key !== $key) {
  18240. unset($attr[$key]);
  18241. }
  18242. }
  18243. }
  18244. $this->attr = $attr;
  18245. $this->line = $line;
  18246. $this->col = $col;
  18247. $this->armor = $armor;
  18248. }
  18249. public function toNode() {
  18250. return new HTMLPurifier_Node_Element($this->name, $this->attr, $this->line, $this->col, $this->armor);
  18251. }
  18252. }
  18253. /**
  18254. * Concrete empty token class.
  18255. */
  18256. class HTMLPurifier_Token_Empty extends HTMLPurifier_Token_Tag
  18257. {
  18258. public function toNode() {
  18259. $n = parent::toNode();
  18260. $n->empty = true;
  18261. return $n;
  18262. }
  18263. }
  18264. /**
  18265. * Concrete end token class.
  18266. *
  18267. * @warning This class accepts attributes even though end tags cannot. This
  18268. * is for optimization reasons, as under normal circumstances, the Lexers
  18269. * do not pass attributes.
  18270. */
  18271. class HTMLPurifier_Token_End extends HTMLPurifier_Token_Tag
  18272. {
  18273. /**
  18274. * Token that started this node.
  18275. * Added by MakeWellFormed. Please do not edit this!
  18276. * @type HTMLPurifier_Token
  18277. */
  18278. public $start;
  18279. public function toNode() {
  18280. throw new Exception("HTMLPurifier_Token_End->toNode not supported!");
  18281. }
  18282. }
  18283. /**
  18284. * Concrete start token class.
  18285. */
  18286. class HTMLPurifier_Token_Start extends HTMLPurifier_Token_Tag
  18287. {
  18288. }
  18289. /**
  18290. * Concrete text token class.
  18291. *
  18292. * Text tokens comprise of regular parsed character data (PCDATA) and raw
  18293. * character data (from the CDATA sections). Internally, their
  18294. * data is parsed with all entities expanded. Surprisingly, the text token
  18295. * does have a "tag name" called #PCDATA, which is how the DTD represents it
  18296. * in permissible child nodes.
  18297. */
  18298. class HTMLPurifier_Token_Text extends HTMLPurifier_Token
  18299. {
  18300. /**
  18301. * @type string
  18302. */
  18303. public $name = '#PCDATA';
  18304. /**< PCDATA tag name compatible with DTD. */
  18305. /**
  18306. * @type string
  18307. */
  18308. public $data;
  18309. /**< Parsed character data of text. */
  18310. /**
  18311. * @type bool
  18312. */
  18313. public $is_whitespace;
  18314. /**< Bool indicating if node is whitespace. */
  18315. /**
  18316. * Constructor, accepts data and determines if it is whitespace.
  18317. * @param string $data String parsed character data.
  18318. * @param int $line
  18319. * @param int $col
  18320. */
  18321. public function __construct($data, $line = null, $col = null)
  18322. {
  18323. $this->data = $data;
  18324. $this->is_whitespace = ctype_space($data);
  18325. $this->line = $line;
  18326. $this->col = $col;
  18327. }
  18328. public function toNode() {
  18329. return new HTMLPurifier_Node_Text($this->data, $this->is_whitespace, $this->line, $this->col);
  18330. }
  18331. }
  18332. class HTMLPurifier_URIFilter_DisableExternal extends HTMLPurifier_URIFilter
  18333. {
  18334. /**
  18335. * @type string
  18336. */
  18337. public $name = 'DisableExternal';
  18338. /**
  18339. * @type array
  18340. */
  18341. protected $ourHostParts = false;
  18342. /**
  18343. * @param HTMLPurifier_Config $config
  18344. * @return void
  18345. */
  18346. public function prepare($config)
  18347. {
  18348. $our_host = $config->getDefinition('URI')->host;
  18349. if ($our_host !== null) {
  18350. $this->ourHostParts = array_reverse(explode('.', $our_host));
  18351. }
  18352. }
  18353. /**
  18354. * @param HTMLPurifier_URI $uri Reference
  18355. * @param HTMLPurifier_Config $config
  18356. * @param HTMLPurifier_Context $context
  18357. * @return bool
  18358. */
  18359. public function filter(&$uri, $config, $context)
  18360. {
  18361. if (is_null($uri->host)) {
  18362. return true;
  18363. }
  18364. if ($this->ourHostParts === false) {
  18365. return false;
  18366. }
  18367. $host_parts = array_reverse(explode('.', $uri->host));
  18368. foreach ($this->ourHostParts as $i => $x) {
  18369. if (!isset($host_parts[$i])) {
  18370. return false;
  18371. }
  18372. if ($host_parts[$i] != $this->ourHostParts[$i]) {
  18373. return false;
  18374. }
  18375. }
  18376. return true;
  18377. }
  18378. }
  18379. class HTMLPurifier_URIFilter_DisableExternalResources extends HTMLPurifier_URIFilter_DisableExternal
  18380. {
  18381. /**
  18382. * @type string
  18383. */
  18384. public $name = 'DisableExternalResources';
  18385. /**
  18386. * @param HTMLPurifier_URI $uri
  18387. * @param HTMLPurifier_Config $config
  18388. * @param HTMLPurifier_Context $context
  18389. * @return bool
  18390. */
  18391. public function filter(&$uri, $config, $context)
  18392. {
  18393. if (!$context->get('EmbeddedURI', true)) {
  18394. return true;
  18395. }
  18396. return parent::filter($uri, $config, $context);
  18397. }
  18398. }
  18399. class HTMLPurifier_URIFilter_DisableResources extends HTMLPurifier_URIFilter
  18400. {
  18401. /**
  18402. * @type string
  18403. */
  18404. public $name = 'DisableResources';
  18405. /**
  18406. * @param HTMLPurifier_URI $uri
  18407. * @param HTMLPurifier_Config $config
  18408. * @param HTMLPurifier_Context $context
  18409. * @return bool
  18410. */
  18411. public function filter(&$uri, $config, $context)
  18412. {
  18413. return !$context->get('EmbeddedURI', true);
  18414. }
  18415. }
  18416. // It's not clear to me whether or not Punycode means that hostnames
  18417. // do not have canonical forms anymore. As far as I can tell, it's
  18418. // not a problem (punycoding should be identity when no Unicode
  18419. // points are involved), but I'm not 100% sure
  18420. class HTMLPurifier_URIFilter_HostBlacklist extends HTMLPurifier_URIFilter
  18421. {
  18422. /**
  18423. * @type string
  18424. */
  18425. public $name = 'HostBlacklist';
  18426. /**
  18427. * @type array
  18428. */
  18429. protected $blacklist = array();
  18430. /**
  18431. * @param HTMLPurifier_Config $config
  18432. * @return bool
  18433. */
  18434. public function prepare($config)
  18435. {
  18436. $this->blacklist = $config->get('URI.HostBlacklist');
  18437. return true;
  18438. }
  18439. /**
  18440. * @param HTMLPurifier_URI $uri
  18441. * @param HTMLPurifier_Config $config
  18442. * @param HTMLPurifier_Context $context
  18443. * @return bool
  18444. */
  18445. public function filter(&$uri, $config, $context)
  18446. {
  18447. foreach ($this->blacklist as $blacklisted_host_fragment) {
  18448. if (strpos($uri->host, $blacklisted_host_fragment) !== false) {
  18449. return false;
  18450. }
  18451. }
  18452. return true;
  18453. }
  18454. }
  18455. // does not support network paths
  18456. class HTMLPurifier_URIFilter_MakeAbsolute extends HTMLPurifier_URIFilter
  18457. {
  18458. /**
  18459. * @type string
  18460. */
  18461. public $name = 'MakeAbsolute';
  18462. /**
  18463. * @type
  18464. */
  18465. protected $base;
  18466. /**
  18467. * @type array
  18468. */
  18469. protected $basePathStack = array();
  18470. /**
  18471. * @param HTMLPurifier_Config $config
  18472. * @return bool
  18473. */
  18474. public function prepare($config)
  18475. {
  18476. $def = $config->getDefinition('URI');
  18477. $this->base = $def->base;
  18478. if (is_null($this->base)) {
  18479. trigger_error(
  18480. 'URI.MakeAbsolute is being ignored due to lack of ' .
  18481. 'value for URI.Base configuration',
  18482. E_USER_WARNING
  18483. );
  18484. return false;
  18485. }
  18486. $this->base->fragment = null; // fragment is invalid for base URI
  18487. $stack = explode('/', $this->base->path);
  18488. array_pop($stack); // discard last segment
  18489. $stack = $this->_collapseStack($stack); // do pre-parsing
  18490. $this->basePathStack = $stack;
  18491. return true;
  18492. }
  18493. /**
  18494. * @param HTMLPurifier_URI $uri
  18495. * @param HTMLPurifier_Config $config
  18496. * @param HTMLPurifier_Context $context
  18497. * @return bool
  18498. */
  18499. public function filter(&$uri, $config, $context)
  18500. {
  18501. if (is_null($this->base)) {
  18502. return true;
  18503. } // abort early
  18504. if ($uri->path === '' && is_null($uri->scheme) &&
  18505. is_null($uri->host) && is_null($uri->query) && is_null($uri->fragment)) {
  18506. // reference to current document
  18507. $uri = clone $this->base;
  18508. return true;
  18509. }
  18510. if (!is_null($uri->scheme)) {
  18511. // absolute URI already: don't change
  18512. if (!is_null($uri->host)) {
  18513. return true;
  18514. }
  18515. $scheme_obj = $uri->getSchemeObj($config, $context);
  18516. if (!$scheme_obj) {
  18517. // scheme not recognized
  18518. return false;
  18519. }
  18520. if (!$scheme_obj->hierarchical) {
  18521. // non-hierarchal URI with explicit scheme, don't change
  18522. return true;
  18523. }
  18524. // special case: had a scheme but always is hierarchical and had no authority
  18525. }
  18526. if (!is_null($uri->host)) {
  18527. // network path, don't bother
  18528. return true;
  18529. }
  18530. if ($uri->path === '') {
  18531. $uri->path = $this->base->path;
  18532. } elseif ($uri->path[0] !== '/') {
  18533. // relative path, needs more complicated processing
  18534. $stack = explode('/', $uri->path);
  18535. $new_stack = array_merge($this->basePathStack, $stack);
  18536. if ($new_stack[0] !== '' && !is_null($this->base->host)) {
  18537. array_unshift($new_stack, '');
  18538. }
  18539. $new_stack = $this->_collapseStack($new_stack);
  18540. $uri->path = implode('/', $new_stack);
  18541. } else {
  18542. // absolute path, but still we should collapse
  18543. $uri->path = implode('/', $this->_collapseStack(explode('/', $uri->path)));
  18544. }
  18545. // re-combine
  18546. $uri->scheme = $this->base->scheme;
  18547. if (is_null($uri->userinfo)) {
  18548. $uri->userinfo = $this->base->userinfo;
  18549. }
  18550. if (is_null($uri->host)) {
  18551. $uri->host = $this->base->host;
  18552. }
  18553. if (is_null($uri->port)) {
  18554. $uri->port = $this->base->port;
  18555. }
  18556. return true;
  18557. }
  18558. /**
  18559. * Resolve dots and double-dots in a path stack
  18560. * @param array $stack
  18561. * @return array
  18562. */
  18563. private function _collapseStack($stack)
  18564. {
  18565. $result = array();
  18566. $is_folder = false;
  18567. for ($i = 0; isset($stack[$i]); $i++) {
  18568. $is_folder = false;
  18569. // absorb an internally duplicated slash
  18570. if ($stack[$i] == '' && $i && isset($stack[$i + 1])) {
  18571. continue;
  18572. }
  18573. if ($stack[$i] == '..') {
  18574. if (!empty($result)) {
  18575. $segment = array_pop($result);
  18576. if ($segment === '' && empty($result)) {
  18577. // error case: attempted to back out too far:
  18578. // restore the leading slash
  18579. $result[] = '';
  18580. } elseif ($segment === '..') {
  18581. $result[] = '..'; // cannot remove .. with ..
  18582. }
  18583. } else {
  18584. // relative path, preserve the double-dots
  18585. $result[] = '..';
  18586. }
  18587. $is_folder = true;
  18588. continue;
  18589. }
  18590. if ($stack[$i] == '.') {
  18591. // silently absorb
  18592. $is_folder = true;
  18593. continue;
  18594. }
  18595. $result[] = $stack[$i];
  18596. }
  18597. if ($is_folder) {
  18598. $result[] = '';
  18599. }
  18600. return $result;
  18601. }
  18602. }
  18603. class HTMLPurifier_URIFilter_Munge extends HTMLPurifier_URIFilter
  18604. {
  18605. /**
  18606. * @type string
  18607. */
  18608. public $name = 'Munge';
  18609. /**
  18610. * @type bool
  18611. */
  18612. public $post = true;
  18613. /**
  18614. * @type string
  18615. */
  18616. private $target;
  18617. /**
  18618. * @type HTMLPurifier_URIParser
  18619. */
  18620. private $parser;
  18621. /**
  18622. * @type bool
  18623. */
  18624. private $doEmbed;
  18625. /**
  18626. * @type string
  18627. */
  18628. private $secretKey;
  18629. /**
  18630. * @type array
  18631. */
  18632. protected $replace = array();
  18633. /**
  18634. * @param HTMLPurifier_Config $config
  18635. * @return bool
  18636. */
  18637. public function prepare($config)
  18638. {
  18639. $this->target = $config->get('URI.' . $this->name);
  18640. $this->parser = new HTMLPurifier_URIParser();
  18641. $this->doEmbed = $config->get('URI.MungeResources');
  18642. $this->secretKey = $config->get('URI.MungeSecretKey');
  18643. if ($this->secretKey && !function_exists('hash_hmac')) {
  18644. throw new Exception("Cannot use %URI.MungeSecretKey without hash_hmac support.");
  18645. }
  18646. return true;
  18647. }
  18648. /**
  18649. * @param HTMLPurifier_URI $uri
  18650. * @param HTMLPurifier_Config $config
  18651. * @param HTMLPurifier_Context $context
  18652. * @return bool
  18653. */
  18654. public function filter(&$uri, $config, $context)
  18655. {
  18656. if ($context->get('EmbeddedURI', true) && !$this->doEmbed) {
  18657. return true;
  18658. }
  18659. $scheme_obj = $uri->getSchemeObj($config, $context);
  18660. if (!$scheme_obj) {
  18661. return true;
  18662. } // ignore unknown schemes, maybe another postfilter did it
  18663. if (!$scheme_obj->browsable) {
  18664. return true;
  18665. } // ignore non-browseable schemes, since we can't munge those in a reasonable way
  18666. if ($uri->isBenign($config, $context)) {
  18667. return true;
  18668. } // don't redirect if a benign URL
  18669. $this->makeReplace($uri, $config, $context);
  18670. $this->replace = array_map('rawurlencode', $this->replace);
  18671. $new_uri = strtr($this->target, $this->replace);
  18672. $new_uri = $this->parser->parse($new_uri);
  18673. // don't redirect if the target host is the same as the
  18674. // starting host
  18675. if ($uri->host === $new_uri->host) {
  18676. return true;
  18677. }
  18678. $uri = $new_uri; // overwrite
  18679. return true;
  18680. }
  18681. /**
  18682. * @param HTMLPurifier_URI $uri
  18683. * @param HTMLPurifier_Config $config
  18684. * @param HTMLPurifier_Context $context
  18685. */
  18686. protected function makeReplace($uri, $config, $context)
  18687. {
  18688. $string = $uri->toString();
  18689. // always available
  18690. $this->replace['%s'] = $string;
  18691. $this->replace['%r'] = $context->get('EmbeddedURI', true);
  18692. $token = $context->get('CurrentToken', true);
  18693. $this->replace['%n'] = $token ? $token->name : null;
  18694. $this->replace['%m'] = $context->get('CurrentAttr', true);
  18695. $this->replace['%p'] = $context->get('CurrentCSSProperty', true);
  18696. // not always available
  18697. if ($this->secretKey) {
  18698. $this->replace['%t'] = hash_hmac("sha256", $string, $this->secretKey);
  18699. }
  18700. }
  18701. }
  18702. /**
  18703. * Implements safety checks for safe iframes.
  18704. *
  18705. * @warning This filter is *critical* for ensuring that %HTML.SafeIframe
  18706. * works safely.
  18707. */
  18708. class HTMLPurifier_URIFilter_SafeIframe extends HTMLPurifier_URIFilter
  18709. {
  18710. /**
  18711. * @type string
  18712. */
  18713. public $name = 'SafeIframe';
  18714. /**
  18715. * @type bool
  18716. */
  18717. public $always_load = true;
  18718. /**
  18719. * @type string
  18720. */
  18721. protected $regexp = null;
  18722. // XXX: The not so good bit about how this is all set up now is we
  18723. // can't check HTML.SafeIframe in the 'prepare' step: we have to
  18724. // defer till the actual filtering.
  18725. /**
  18726. * @param HTMLPurifier_Config $config
  18727. * @return bool
  18728. */
  18729. public function prepare($config)
  18730. {
  18731. $this->regexp = $config->get('URI.SafeIframeRegexp');
  18732. return true;
  18733. }
  18734. /**
  18735. * @param HTMLPurifier_URI $uri
  18736. * @param HTMLPurifier_Config $config
  18737. * @param HTMLPurifier_Context $context
  18738. * @return bool
  18739. */
  18740. public function filter(&$uri, $config, $context)
  18741. {
  18742. // check if filter not applicable
  18743. if (!$config->get('HTML.SafeIframe')) {
  18744. return true;
  18745. }
  18746. // check if the filter should actually trigger
  18747. if (!$context->get('EmbeddedURI', true)) {
  18748. return true;
  18749. }
  18750. $token = $context->get('CurrentToken', true);
  18751. if (!($token && $token->name == 'iframe')) {
  18752. return true;
  18753. }
  18754. // check if we actually have some whitelists enabled
  18755. if ($this->regexp === null) {
  18756. return false;
  18757. }
  18758. // actually check the whitelists
  18759. return preg_match($this->regexp, $uri->toString());
  18760. }
  18761. }
  18762. /**
  18763. * Implements data: URI for base64 encoded images supported by GD.
  18764. */
  18765. class HTMLPurifier_URIScheme_data extends HTMLPurifier_URIScheme
  18766. {
  18767. /**
  18768. * @type bool
  18769. */
  18770. public $browsable = true;
  18771. /**
  18772. * @type array
  18773. */
  18774. public $allowed_types = array(
  18775. // you better write validation code for other types if you
  18776. // decide to allow them
  18777. 'image/jpeg' => true,
  18778. 'image/gif' => true,
  18779. 'image/png' => true,
  18780. );
  18781. // this is actually irrelevant since we only write out the path
  18782. // component
  18783. /**
  18784. * @type bool
  18785. */
  18786. public $may_omit_host = true;
  18787. /**
  18788. * @param HTMLPurifier_URI $uri
  18789. * @param HTMLPurifier_Config $config
  18790. * @param HTMLPurifier_Context $context
  18791. * @return bool
  18792. */
  18793. public function doValidate(&$uri, $config, $context)
  18794. {
  18795. $result = explode(',', $uri->path, 2);
  18796. $is_base64 = false;
  18797. $charset = null;
  18798. $content_type = null;
  18799. if (count($result) == 2) {
  18800. list($metadata, $data) = $result;
  18801. // do some legwork on the metadata
  18802. $metas = explode(';', $metadata);
  18803. while (!empty($metas)) {
  18804. $cur = array_shift($metas);
  18805. if ($cur == 'base64') {
  18806. $is_base64 = true;
  18807. break;
  18808. }
  18809. if (substr($cur, 0, 8) == 'charset=') {
  18810. // doesn't match if there are arbitrary spaces, but
  18811. // whatever dude
  18812. if ($charset !== null) {
  18813. continue;
  18814. } // garbage
  18815. $charset = substr($cur, 8); // not used
  18816. } else {
  18817. if ($content_type !== null) {
  18818. continue;
  18819. } // garbage
  18820. $content_type = $cur;
  18821. }
  18822. }
  18823. } else {
  18824. $data = $result[0];
  18825. }
  18826. if ($content_type !== null && empty($this->allowed_types[$content_type])) {
  18827. return false;
  18828. }
  18829. if ($charset !== null) {
  18830. // error; we don't allow plaintext stuff
  18831. $charset = null;
  18832. }
  18833. $data = rawurldecode($data);
  18834. if ($is_base64) {
  18835. $raw_data = base64_decode($data);
  18836. } else {
  18837. $raw_data = $data;
  18838. }
  18839. if ( strlen($raw_data) < 12 ) {
  18840. // error; exif_imagetype throws exception with small files,
  18841. // and this likely indicates a corrupt URI/failed parse anyway
  18842. return false;
  18843. }
  18844. // XXX probably want to refactor this into a general mechanism
  18845. // for filtering arbitrary content types
  18846. if (function_exists('sys_get_temp_dir')) {
  18847. $file = tempnam(sys_get_temp_dir(), "");
  18848. } else {
  18849. $file = tempnam("/tmp", "");
  18850. }
  18851. file_put_contents($file, $raw_data);
  18852. if (function_exists('exif_imagetype')) {
  18853. $image_code = exif_imagetype($file);
  18854. unlink($file);
  18855. } elseif (function_exists('getimagesize')) {
  18856. set_error_handler(array($this, 'muteErrorHandler'));
  18857. $info = getimagesize($file);
  18858. restore_error_handler();
  18859. unlink($file);
  18860. if ($info == false) {
  18861. return false;
  18862. }
  18863. $image_code = $info[2];
  18864. } else {
  18865. trigger_error("could not find exif_imagetype or getimagesize functions", E_USER_ERROR);
  18866. }
  18867. $real_content_type = image_type_to_mime_type($image_code);
  18868. if ($real_content_type != $content_type) {
  18869. // we're nice guys; if the content type is something else we
  18870. // support, change it over
  18871. if (empty($this->allowed_types[$real_content_type])) {
  18872. return false;
  18873. }
  18874. $content_type = $real_content_type;
  18875. }
  18876. // ok, it's kosher, rewrite what we need
  18877. $uri->userinfo = null;
  18878. $uri->host = null;
  18879. $uri->port = null;
  18880. $uri->fragment = null;
  18881. $uri->query = null;
  18882. $uri->path = "$content_type;base64," . base64_encode($raw_data);
  18883. return true;
  18884. }
  18885. /**
  18886. * @param int $errno
  18887. * @param string $errstr
  18888. */
  18889. public function muteErrorHandler($errno, $errstr)
  18890. {
  18891. }
  18892. }
  18893. /**
  18894. * Validates file as defined by RFC 1630 and RFC 1738.
  18895. */
  18896. class HTMLPurifier_URIScheme_file extends HTMLPurifier_URIScheme
  18897. {
  18898. /**
  18899. * Generally file:// URLs are not accessible from most
  18900. * machines, so placing them as an img src is incorrect.
  18901. * @type bool
  18902. */
  18903. public $browsable = false;
  18904. /**
  18905. * Basically the *only* URI scheme for which this is true, since
  18906. * accessing files on the local machine is very common. In fact,
  18907. * browsers on some operating systems don't understand the
  18908. * authority, though I hear it is used on Windows to refer to
  18909. * network shares.
  18910. * @type bool
  18911. */
  18912. public $may_omit_host = true;
  18913. /**
  18914. * @param HTMLPurifier_URI $uri
  18915. * @param HTMLPurifier_Config $config
  18916. * @param HTMLPurifier_Context $context
  18917. * @return bool
  18918. */
  18919. public function doValidate(&$uri, $config, $context)
  18920. {
  18921. // Authentication method is not supported
  18922. $uri->userinfo = null;
  18923. // file:// makes no provisions for accessing the resource
  18924. $uri->port = null;
  18925. // While it seems to work on Firefox, the querystring has
  18926. // no possible effect and is thus stripped.
  18927. $uri->query = null;
  18928. return true;
  18929. }
  18930. }
  18931. /**
  18932. * Validates ftp (File Transfer Protocol) URIs as defined by generic RFC 1738.
  18933. */
  18934. class HTMLPurifier_URIScheme_ftp extends HTMLPurifier_URIScheme
  18935. {
  18936. /**
  18937. * @type int
  18938. */
  18939. public $default_port = 21;
  18940. /**
  18941. * @type bool
  18942. */
  18943. public $browsable = true; // usually
  18944. /**
  18945. * @type bool
  18946. */
  18947. public $hierarchical = true;
  18948. /**
  18949. * @param HTMLPurifier_URI $uri
  18950. * @param HTMLPurifier_Config $config
  18951. * @param HTMLPurifier_Context $context
  18952. * @return bool
  18953. */
  18954. public function doValidate(&$uri, $config, $context)
  18955. {
  18956. $uri->query = null;
  18957. // typecode check
  18958. $semicolon_pos = strrpos($uri->path, ';'); // reverse
  18959. if ($semicolon_pos !== false) {
  18960. $type = substr($uri->path, $semicolon_pos + 1); // no semicolon
  18961. $uri->path = substr($uri->path, 0, $semicolon_pos);
  18962. $type_ret = '';
  18963. if (strpos($type, '=') !== false) {
  18964. // figure out whether or not the declaration is correct
  18965. list($key, $typecode) = explode('=', $type, 2);
  18966. if ($key !== 'type') {
  18967. // invalid key, tack it back on encoded
  18968. $uri->path .= '%3B' . $type;
  18969. } elseif ($typecode === 'a' || $typecode === 'i' || $typecode === 'd') {
  18970. $type_ret = ";type=$typecode";
  18971. }
  18972. } else {
  18973. $uri->path .= '%3B' . $type;
  18974. }
  18975. $uri->path = str_replace(';', '%3B', $uri->path);
  18976. $uri->path .= $type_ret;
  18977. }
  18978. return true;
  18979. }
  18980. }
  18981. /**
  18982. * Validates http (HyperText Transfer Protocol) as defined by RFC 2616
  18983. */
  18984. class HTMLPurifier_URIScheme_http extends HTMLPurifier_URIScheme
  18985. {
  18986. /**
  18987. * @type int
  18988. */
  18989. public $default_port = 80;
  18990. /**
  18991. * @type bool
  18992. */
  18993. public $browsable = true;
  18994. /**
  18995. * @type bool
  18996. */
  18997. public $hierarchical = true;
  18998. /**
  18999. * @param HTMLPurifier_URI $uri
  19000. * @param HTMLPurifier_Config $config
  19001. * @param HTMLPurifier_Context $context
  19002. * @return bool
  19003. */
  19004. public function doValidate(&$uri, $config, $context)
  19005. {
  19006. $uri->userinfo = null;
  19007. return true;
  19008. }
  19009. }
  19010. /**
  19011. * Validates https (Secure HTTP) according to http scheme.
  19012. */
  19013. class HTMLPurifier_URIScheme_https extends HTMLPurifier_URIScheme_http
  19014. {
  19015. /**
  19016. * @type int
  19017. */
  19018. public $default_port = 443;
  19019. /**
  19020. * @type bool
  19021. */
  19022. public $secure = true;
  19023. }
  19024. // VERY RELAXED! Shouldn't cause problems, not even Firefox checks if the
  19025. // email is valid, but be careful!
  19026. /**
  19027. * Validates mailto (for E-mail) according to RFC 2368
  19028. * @todo Validate the email address
  19029. * @todo Filter allowed query parameters
  19030. */
  19031. class HTMLPurifier_URIScheme_mailto extends HTMLPurifier_URIScheme
  19032. {
  19033. /**
  19034. * @type bool
  19035. */
  19036. public $browsable = false;
  19037. /**
  19038. * @type bool
  19039. */
  19040. public $may_omit_host = true;
  19041. /**
  19042. * @param HTMLPurifier_URI $uri
  19043. * @param HTMLPurifier_Config $config
  19044. * @param HTMLPurifier_Context $context
  19045. * @return bool
  19046. */
  19047. public function doValidate(&$uri, $config, $context)
  19048. {
  19049. $uri->userinfo = null;
  19050. $uri->host = null;
  19051. $uri->port = null;
  19052. // we need to validate path against RFC 2368's addr-spec
  19053. return true;
  19054. }
  19055. }
  19056. /**
  19057. * Validates news (Usenet) as defined by generic RFC 1738
  19058. */
  19059. class HTMLPurifier_URIScheme_news extends HTMLPurifier_URIScheme
  19060. {
  19061. /**
  19062. * @type bool
  19063. */
  19064. public $browsable = false;
  19065. /**
  19066. * @type bool
  19067. */
  19068. public $may_omit_host = true;
  19069. /**
  19070. * @param HTMLPurifier_URI $uri
  19071. * @param HTMLPurifier_Config $config
  19072. * @param HTMLPurifier_Context $context
  19073. * @return bool
  19074. */
  19075. public function doValidate(&$uri, $config, $context)
  19076. {
  19077. $uri->userinfo = null;
  19078. $uri->host = null;
  19079. $uri->port = null;
  19080. $uri->query = null;
  19081. // typecode check needed on path
  19082. return true;
  19083. }
  19084. }
  19085. /**
  19086. * Validates nntp (Network News Transfer Protocol) as defined by generic RFC 1738
  19087. */
  19088. class HTMLPurifier_URIScheme_nntp extends HTMLPurifier_URIScheme
  19089. {
  19090. /**
  19091. * @type int
  19092. */
  19093. public $default_port = 119;
  19094. /**
  19095. * @type bool
  19096. */
  19097. public $browsable = false;
  19098. /**
  19099. * @param HTMLPurifier_URI $uri
  19100. * @param HTMLPurifier_Config $config
  19101. * @param HTMLPurifier_Context $context
  19102. * @return bool
  19103. */
  19104. public function doValidate(&$uri, $config, $context)
  19105. {
  19106. $uri->userinfo = null;
  19107. $uri->query = null;
  19108. return true;
  19109. }
  19110. }
  19111. /**
  19112. * Validates tel (for phone numbers).
  19113. *
  19114. * The relevant specifications for this protocol are RFC 3966 and RFC 5341,
  19115. * but this class takes a much simpler approach: we normalize phone
  19116. * numbers so that they only include (possibly) a leading plus,
  19117. * and then any number of digits and x'es.
  19118. */
  19119. class HTMLPurifier_URIScheme_tel extends HTMLPurifier_URIScheme
  19120. {
  19121. /**
  19122. * @type bool
  19123. */
  19124. public $browsable = false;
  19125. /**
  19126. * @type bool
  19127. */
  19128. public $may_omit_host = true;
  19129. /**
  19130. * @param HTMLPurifier_URI $uri
  19131. * @param HTMLPurifier_Config $config
  19132. * @param HTMLPurifier_Context $context
  19133. * @return bool
  19134. */
  19135. public function doValidate(&$uri, $config, $context)
  19136. {
  19137. $uri->userinfo = null;
  19138. $uri->host = null;
  19139. $uri->port = null;
  19140. // Delete all non-numeric characters, non-x characters
  19141. // from phone number, EXCEPT for a leading plus sign.
  19142. $uri->path = preg_replace('/(?!^\+)[^\dx]/', '',
  19143. // Normalize e(x)tension to lower-case
  19144. str_replace('X', 'x', $uri->path));
  19145. return true;
  19146. }
  19147. }
  19148. /**
  19149. * Performs safe variable parsing based on types which can be used by
  19150. * users. This may not be able to represent all possible data inputs,
  19151. * however.
  19152. */
  19153. class HTMLPurifier_VarParser_Flexible extends HTMLPurifier_VarParser
  19154. {
  19155. /**
  19156. * @param mixed $var
  19157. * @param int $type
  19158. * @param bool $allow_null
  19159. * @return array|bool|float|int|mixed|null|string
  19160. * @throws HTMLPurifier_VarParserException
  19161. */
  19162. protected function parseImplementation($var, $type, $allow_null)
  19163. {
  19164. if ($allow_null && $var === null) {
  19165. return null;
  19166. }
  19167. switch ($type) {
  19168. // Note: if code "breaks" from the switch, it triggers a generic
  19169. // exception to be thrown. Specific errors can be specifically
  19170. // done here.
  19171. case self::MIXED:
  19172. case self::ISTRING:
  19173. case self::STRING:
  19174. case self::TEXT:
  19175. case self::ITEXT:
  19176. return $var;
  19177. case self::INT:
  19178. if (is_string($var) && ctype_digit($var)) {
  19179. $var = (int)$var;
  19180. }
  19181. return $var;
  19182. case self::FLOAT:
  19183. if ((is_string($var) && is_numeric($var)) || is_int($var)) {
  19184. $var = (float)$var;
  19185. }
  19186. return $var;
  19187. case self::BOOL:
  19188. if (is_int($var) && ($var === 0 || $var === 1)) {
  19189. $var = (bool)$var;
  19190. } elseif (is_string($var)) {
  19191. if ($var == 'on' || $var == 'true' || $var == '1') {
  19192. $var = true;
  19193. } elseif ($var == 'off' || $var == 'false' || $var == '0') {
  19194. $var = false;
  19195. } else {
  19196. throw new HTMLPurifier_VarParserException("Unrecognized value '$var' for $type");
  19197. }
  19198. }
  19199. return $var;
  19200. case self::ALIST:
  19201. case self::HASH:
  19202. case self::LOOKUP:
  19203. if (is_string($var)) {
  19204. // special case: technically, this is an array with
  19205. // a single empty string item, but having an empty
  19206. // array is more intuitive
  19207. if ($var == '') {
  19208. return array();
  19209. }
  19210. if (strpos($var, "\n") === false && strpos($var, "\r") === false) {
  19211. // simplistic string to array method that only works
  19212. // for simple lists of tag names or alphanumeric characters
  19213. $var = explode(',', $var);
  19214. } else {
  19215. $var = preg_split('/(,|[\n\r]+)/', $var);
  19216. }
  19217. // remove spaces
  19218. foreach ($var as $i => $j) {
  19219. $var[$i] = trim($j);
  19220. }
  19221. if ($type === self::HASH) {
  19222. // key:value,key2:value2
  19223. $nvar = array();
  19224. foreach ($var as $keypair) {
  19225. $c = explode(':', $keypair, 2);
  19226. if (!isset($c[1])) {
  19227. continue;
  19228. }
  19229. $nvar[trim($c[0])] = trim($c[1]);
  19230. }
  19231. $var = $nvar;
  19232. }
  19233. }
  19234. if (!is_array($var)) {
  19235. break;
  19236. }
  19237. $keys = array_keys($var);
  19238. if ($keys === array_keys($keys)) {
  19239. if ($type == self::ALIST) {
  19240. return $var;
  19241. } elseif ($type == self::LOOKUP) {
  19242. $new = array();
  19243. foreach ($var as $key) {
  19244. $new[$key] = true;
  19245. }
  19246. return $new;
  19247. } else {
  19248. break;
  19249. }
  19250. }
  19251. if ($type === self::ALIST) {
  19252. trigger_error("Array list did not have consecutive integer indexes", E_USER_WARNING);
  19253. return array_values($var);
  19254. }
  19255. if ($type === self::LOOKUP) {
  19256. foreach ($var as $key => $value) {
  19257. if ($value !== true) {
  19258. trigger_error(
  19259. "Lookup array has non-true value at key '$key'; " .
  19260. "maybe your input array was not indexed numerically",
  19261. E_USER_WARNING
  19262. );
  19263. }
  19264. $var[$key] = true;
  19265. }
  19266. }
  19267. return $var;
  19268. default:
  19269. $this->errorInconsistent(__CLASS__, $type);
  19270. }
  19271. $this->errorGeneric($var, $type);
  19272. }
  19273. }
  19274. /**
  19275. * This variable parser uses PHP's internal code engine. Because it does
  19276. * this, it can represent all inputs; however, it is dangerous and cannot
  19277. * be used by users.
  19278. */
  19279. class HTMLPurifier_VarParser_Native extends HTMLPurifier_VarParser
  19280. {
  19281. /**
  19282. * @param mixed $var
  19283. * @param int $type
  19284. * @param bool $allow_null
  19285. * @return null|string
  19286. */
  19287. protected function parseImplementation($var, $type, $allow_null)
  19288. {
  19289. return $this->evalExpression($var);
  19290. }
  19291. /**
  19292. * @param string $expr
  19293. * @return mixed
  19294. * @throws HTMLPurifier_VarParserException
  19295. */
  19296. protected function evalExpression($expr)
  19297. {
  19298. $var = null;
  19299. $result = eval("\$var = $expr;");
  19300. if ($result === false) {
  19301. throw new HTMLPurifier_VarParserException("Fatal error in evaluated code");
  19302. }
  19303. return $var;
  19304. }
  19305. }