1
0

Less.php 255 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510
  1. <?php
  2. require_once( dirname(__FILE__).'/Cache.php');
  3. /**
  4. * Class for parsing and compiling less files into css
  5. *
  6. * @package Less
  7. * @subpackage parser
  8. *
  9. */
  10. class Less_Parser{
  11. /**
  12. * Default parser options
  13. */
  14. public static $default_options = array(
  15. 'compress' => false, // option - whether to compress
  16. 'strictUnits' => false, // whether units need to evaluate correctly
  17. 'strictMath' => false, // whether math has to be within parenthesis
  18. 'relativeUrls' => true, // option - whether to adjust URL's to be relative
  19. 'urlArgs' => array(), // whether to add args into url tokens
  20. 'numPrecision' => 8,
  21. 'import_dirs' => array(),
  22. 'import_callback' => null,
  23. 'cache_dir' => null,
  24. 'cache_method' => 'php', // false, 'serialize', 'php', 'var_export', 'callback';
  25. 'cache_callback_get' => null,
  26. 'cache_callback_set' => null,
  27. 'sourceMap' => false, // whether to output a source map
  28. 'sourceMapBasepath' => null,
  29. 'sourceMapWriteTo' => null,
  30. 'sourceMapURL' => null,
  31. 'plugins' => array(),
  32. );
  33. public static $options = array();
  34. private $input; // Less input string
  35. private $input_len; // input string length
  36. private $pos; // current index in `input`
  37. private $saveStack = array(); // holds state for backtracking
  38. private $furthest;
  39. private $mb_internal_encoding = ''; // for remember exists value of mbstring.internal_encoding
  40. /**
  41. * @var Less_Environment
  42. */
  43. private $env;
  44. protected $rules = array();
  45. private static $imports = array();
  46. public static $has_extends = false;
  47. public static $next_id = 0;
  48. /**
  49. * Filename to contents of all parsed the files
  50. *
  51. * @var array
  52. */
  53. public static $contentsMap = array();
  54. /**
  55. * @param Less_Environment|array|null $env
  56. */
  57. public function __construct( $env = null ){
  58. // Top parser on an import tree must be sure there is one "env"
  59. // which will then be passed around by reference.
  60. if( $env instanceof Less_Environment ){
  61. $this->env = $env;
  62. }else{
  63. $this->SetOptions(Less_Parser::$default_options);
  64. $this->Reset( $env );
  65. }
  66. // mbstring.func_overload > 1 bugfix
  67. // The encoding value must be set for each source file,
  68. // therefore, to conserve resources and improve the speed of this design is taken here
  69. if (ini_get('mbstring.func_overload')) {
  70. $this->mb_internal_encoding = ini_get('mbstring.internal_encoding');
  71. @ini_set('mbstring.internal_encoding', 'ascii');
  72. }
  73. }
  74. /**
  75. * Reset the parser state completely
  76. *
  77. */
  78. public function Reset( $options = null ){
  79. $this->rules = array();
  80. self::$imports = array();
  81. self::$has_extends = false;
  82. self::$imports = array();
  83. self::$contentsMap = array();
  84. $this->env = new Less_Environment($options);
  85. $this->env->Init();
  86. //set new options
  87. if( is_array($options) ){
  88. $this->SetOptions(Less_Parser::$default_options);
  89. $this->SetOptions($options);
  90. }
  91. }
  92. /**
  93. * Set one or more compiler options
  94. * options: import_dirs, cache_dir, cache_method
  95. *
  96. */
  97. public function SetOptions( $options ){
  98. foreach($options as $option => $value){
  99. $this->SetOption($option,$value);
  100. }
  101. }
  102. /**
  103. * Set one compiler option
  104. *
  105. */
  106. public function SetOption($option,$value){
  107. switch($option){
  108. case 'import_dirs':
  109. $this->SetImportDirs($value);
  110. return;
  111. case 'cache_dir':
  112. if( is_string($value) ){
  113. Less_Cache::SetCacheDir($value);
  114. Less_Cache::CheckCacheDir();
  115. }
  116. return;
  117. }
  118. Less_Parser::$options[$option] = $value;
  119. }
  120. /**
  121. * Registers a new custom function
  122. *
  123. * @param string $name function name
  124. * @param callable $callback callback
  125. */
  126. public function registerFunction($name, $callback) {
  127. $this->env->functions[$name] = $callback;
  128. }
  129. /**
  130. * Removed an already registered function
  131. *
  132. * @param string $name function name
  133. */
  134. public function unregisterFunction($name) {
  135. if( isset($this->env->functions[$name]) )
  136. unset($this->env->functions[$name]);
  137. }
  138. /**
  139. * Get the current css buffer
  140. *
  141. * @return string
  142. */
  143. public function getCss(){
  144. $precision = ini_get('precision');
  145. @ini_set('precision',16);
  146. $locale = setlocale(LC_NUMERIC, 0);
  147. setlocale(LC_NUMERIC, "C");
  148. try {
  149. $root = new Less_Tree_Ruleset(array(), $this->rules );
  150. $root->root = true;
  151. $root->firstRoot = true;
  152. $this->PreVisitors($root);
  153. self::$has_extends = false;
  154. $evaldRoot = $root->compile($this->env);
  155. $this->PostVisitors($evaldRoot);
  156. if( Less_Parser::$options['sourceMap'] ){
  157. $generator = new Less_SourceMap_Generator($evaldRoot, Less_Parser::$contentsMap, Less_Parser::$options );
  158. // will also save file
  159. // FIXME: should happen somewhere else?
  160. $css = $generator->generateCSS();
  161. }else{
  162. $css = $evaldRoot->toCSS();
  163. }
  164. if( Less_Parser::$options['compress'] ){
  165. $css = preg_replace('/(^(\s)+)|((\s)+$)/', '', $css);
  166. }
  167. } catch (Exception $exc) {
  168. // Intentional fall-through so we can reset environment
  169. }
  170. //reset php settings
  171. @ini_set('precision',$precision);
  172. setlocale(LC_NUMERIC, $locale);
  173. // If you previously defined $this->mb_internal_encoding
  174. // is required to return the encoding as it was before
  175. if ($this->mb_internal_encoding != '') {
  176. @ini_set("mbstring.internal_encoding", $this->mb_internal_encoding);
  177. $this->mb_internal_encoding = '';
  178. }
  179. // Rethrow exception after we handled resetting the environment
  180. if (!empty($exc)) {
  181. throw $exc;
  182. }
  183. return $css;
  184. }
  185. /**
  186. * Run pre-compile visitors
  187. *
  188. */
  189. private function PreVisitors($root){
  190. if( Less_Parser::$options['plugins'] ){
  191. foreach(Less_Parser::$options['plugins'] as $plugin){
  192. if( !empty($plugin->isPreEvalVisitor) ){
  193. $plugin->run($root);
  194. }
  195. }
  196. }
  197. }
  198. /**
  199. * Run post-compile visitors
  200. *
  201. */
  202. private function PostVisitors($evaldRoot){
  203. $visitors = array();
  204. $visitors[] = new Less_Visitor_joinSelector();
  205. if( self::$has_extends ){
  206. $visitors[] = new Less_Visitor_processExtends();
  207. }
  208. $visitors[] = new Less_Visitor_toCSS();
  209. if( Less_Parser::$options['plugins'] ){
  210. foreach(Less_Parser::$options['plugins'] as $plugin){
  211. if( property_exists($plugin,'isPreEvalVisitor') && $plugin->isPreEvalVisitor ){
  212. continue;
  213. }
  214. if( property_exists($plugin,'isPreVisitor') && $plugin->isPreVisitor ){
  215. array_unshift( $visitors, $plugin);
  216. }else{
  217. $visitors[] = $plugin;
  218. }
  219. }
  220. }
  221. for($i = 0; $i < count($visitors); $i++ ){
  222. $visitors[$i]->run($evaldRoot);
  223. }
  224. }
  225. /**
  226. * Parse a Less string into css
  227. *
  228. * @param string $str The string to convert
  229. * @param string $uri_root The url of the file
  230. * @return Less_Tree_Ruleset|Less_Parser
  231. */
  232. public function parse( $str, $file_uri = null ){
  233. if( !$file_uri ){
  234. $uri_root = '';
  235. $filename = 'anonymous-file-'.Less_Parser::$next_id++.'.less';
  236. }else{
  237. $file_uri = self::WinPath($file_uri);
  238. $filename = $file_uri;
  239. $uri_root = dirname($file_uri);
  240. }
  241. $previousFileInfo = $this->env->currentFileInfo;
  242. $uri_root = self::WinPath($uri_root);
  243. $this->SetFileInfo($filename, $uri_root);
  244. $this->input = $str;
  245. $this->_parse();
  246. if( $previousFileInfo ){
  247. $this->env->currentFileInfo = $previousFileInfo;
  248. }
  249. return $this;
  250. }
  251. /**
  252. * Parse a Less string from a given file
  253. *
  254. * @throws Less_Exception_Parser
  255. * @param string $filename The file to parse
  256. * @param string $uri_root The url of the file
  257. * @param bool $returnRoot Indicates whether the return value should be a css string a root node
  258. * @return Less_Tree_Ruleset|Less_Parser
  259. */
  260. public function parseFile( $filename, $uri_root = '', $returnRoot = false){
  261. if( !file_exists($filename) ){
  262. $this->Error(sprintf('File `%s` not found.', $filename));
  263. }
  264. // fix uri_root?
  265. // Instead of The mixture of file path for the first argument and directory path for the second argument has bee
  266. if( !$returnRoot && !empty($uri_root) && basename($uri_root) == basename($filename) ){
  267. $uri_root = dirname($uri_root);
  268. }
  269. $previousFileInfo = $this->env->currentFileInfo;
  270. if( $filename ){
  271. $filename = self::WinPath(realpath($filename));
  272. }
  273. $uri_root = self::WinPath($uri_root);
  274. $this->SetFileInfo($filename, $uri_root);
  275. self::AddParsedFile($filename);
  276. if( $returnRoot ){
  277. $rules = $this->GetRules( $filename );
  278. $return = new Less_Tree_Ruleset(array(), $rules );
  279. }else{
  280. $this->_parse( $filename );
  281. $return = $this;
  282. }
  283. if( $previousFileInfo ){
  284. $this->env->currentFileInfo = $previousFileInfo;
  285. }
  286. return $return;
  287. }
  288. /**
  289. * Allows a user to set variables values
  290. * @param array $vars
  291. * @return Less_Parser
  292. */
  293. public function ModifyVars( $vars ){
  294. $this->input = Less_Parser::serializeVars( $vars );
  295. $this->_parse();
  296. return $this;
  297. }
  298. /**
  299. * @param string $filename
  300. */
  301. public function SetFileInfo( $filename, $uri_root = ''){
  302. $filename = Less_Environment::normalizePath($filename);
  303. $dirname = preg_replace('/[^\/\\\\]*$/','',$filename);
  304. if( !empty($uri_root) ){
  305. $uri_root = rtrim($uri_root,'/').'/';
  306. }
  307. $currentFileInfo = array();
  308. //entry info
  309. if( isset($this->env->currentFileInfo) ){
  310. $currentFileInfo['entryPath'] = $this->env->currentFileInfo['entryPath'];
  311. $currentFileInfo['entryUri'] = $this->env->currentFileInfo['entryUri'];
  312. $currentFileInfo['rootpath'] = $this->env->currentFileInfo['rootpath'];
  313. }else{
  314. $currentFileInfo['entryPath'] = $dirname;
  315. $currentFileInfo['entryUri'] = $uri_root;
  316. $currentFileInfo['rootpath'] = $dirname;
  317. }
  318. $currentFileInfo['currentDirectory'] = $dirname;
  319. $currentFileInfo['currentUri'] = $uri_root.basename($filename);
  320. $currentFileInfo['filename'] = $filename;
  321. $currentFileInfo['uri_root'] = $uri_root;
  322. //inherit reference
  323. if( isset($this->env->currentFileInfo['reference']) && $this->env->currentFileInfo['reference'] ){
  324. $currentFileInfo['reference'] = true;
  325. }
  326. $this->env->currentFileInfo = $currentFileInfo;
  327. }
  328. /**
  329. * @deprecated 1.5.1.2
  330. *
  331. */
  332. public function SetCacheDir( $dir ){
  333. if( !file_exists($dir) ){
  334. if( mkdir($dir) ){
  335. return true;
  336. }
  337. throw new Less_Exception_Parser('Less.php cache directory couldn\'t be created: '.$dir);
  338. }elseif( !is_dir($dir) ){
  339. throw new Less_Exception_Parser('Less.php cache directory doesn\'t exist: '.$dir);
  340. }elseif( !is_writable($dir) ){
  341. throw new Less_Exception_Parser('Less.php cache directory isn\'t writable: '.$dir);
  342. }else{
  343. $dir = self::WinPath($dir);
  344. Less_Cache::$cache_dir = rtrim($dir,'/').'/';
  345. return true;
  346. }
  347. }
  348. /**
  349. * Set a list of directories or callbacks the parser should use for determining import paths
  350. *
  351. * @param array $dirs
  352. */
  353. public function SetImportDirs( $dirs ){
  354. Less_Parser::$options['import_dirs'] = array();
  355. foreach($dirs as $path => $uri_root){
  356. $path = self::WinPath($path);
  357. if( !empty($path) ){
  358. $path = rtrim($path,'/').'/';
  359. }
  360. if ( !is_callable($uri_root) ){
  361. $uri_root = self::WinPath($uri_root);
  362. if( !empty($uri_root) ){
  363. $uri_root = rtrim($uri_root,'/').'/';
  364. }
  365. }
  366. Less_Parser::$options['import_dirs'][$path] = $uri_root;
  367. }
  368. }
  369. /**
  370. * @param string $file_path
  371. */
  372. private function _parse( $file_path = null ){
  373. $this->rules = array_merge($this->rules, $this->GetRules( $file_path ));
  374. }
  375. /**
  376. * Return the results of parsePrimary for $file_path
  377. * Use cache and save cached results if possible
  378. *
  379. * @param string|null $file_path
  380. */
  381. private function GetRules( $file_path ){
  382. $this->SetInput($file_path);
  383. $cache_file = $this->CacheFile( $file_path );
  384. if( $cache_file ){
  385. if( Less_Parser::$options['cache_method'] == 'callback' ){
  386. if( is_callable(Less_Parser::$options['cache_callback_get']) ){
  387. $cache = call_user_func_array(
  388. Less_Parser::$options['cache_callback_get'],
  389. array($this, $file_path, $cache_file)
  390. );
  391. if( $cache ){
  392. $this->UnsetInput();
  393. return $cache;
  394. }
  395. }
  396. }elseif( file_exists($cache_file) ){
  397. switch(Less_Parser::$options['cache_method']){
  398. // Using serialize
  399. // Faster but uses more memory
  400. case 'serialize':
  401. $cache = unserialize(file_get_contents($cache_file));
  402. if( $cache ){
  403. touch($cache_file);
  404. $this->UnsetInput();
  405. return $cache;
  406. }
  407. break;
  408. // Using generated php code
  409. case 'var_export':
  410. case 'php':
  411. $this->UnsetInput();
  412. return include($cache_file);
  413. }
  414. }
  415. }
  416. $rules = $this->parsePrimary();
  417. if( $this->pos < $this->input_len ){
  418. throw new Less_Exception_Chunk($this->input, null, $this->furthest, $this->env->currentFileInfo);
  419. }
  420. $this->UnsetInput();
  421. //save the cache
  422. if( $cache_file ){
  423. if( Less_Parser::$options['cache_method'] == 'callback' ){
  424. if( is_callable(Less_Parser::$options['cache_callback_set']) ){
  425. call_user_func_array(
  426. Less_Parser::$options['cache_callback_set'],
  427. array($this, $file_path, $cache_file, $rules)
  428. );
  429. }
  430. }else{
  431. //msg('write cache file');
  432. switch(Less_Parser::$options['cache_method']){
  433. case 'serialize':
  434. file_put_contents( $cache_file, serialize($rules) );
  435. break;
  436. case 'php':
  437. file_put_contents( $cache_file, '<?php return '.self::ArgString($rules).'; ?>' );
  438. break;
  439. case 'var_export':
  440. //Requires __set_state()
  441. file_put_contents( $cache_file, '<?php return '.var_export($rules,true).'; ?>' );
  442. break;
  443. }
  444. Less_Cache::CleanCache();
  445. }
  446. }
  447. return $rules;
  448. }
  449. /**
  450. * Set up the input buffer
  451. *
  452. */
  453. public function SetInput( $file_path ){
  454. if( $file_path ){
  455. $this->input = file_get_contents( $file_path );
  456. }
  457. $this->pos = $this->furthest = 0;
  458. // Remove potential UTF Byte Order Mark
  459. $this->input = preg_replace('/\\G\xEF\xBB\xBF/', '', $this->input);
  460. $this->input_len = strlen($this->input);
  461. if( Less_Parser::$options['sourceMap'] && $this->env->currentFileInfo ){
  462. $uri = $this->env->currentFileInfo['currentUri'];
  463. Less_Parser::$contentsMap[$uri] = $this->input;
  464. }
  465. }
  466. /**
  467. * Free up some memory
  468. *
  469. */
  470. public function UnsetInput(){
  471. unset($this->input, $this->pos, $this->input_len, $this->furthest);
  472. $this->saveStack = array();
  473. }
  474. public function CacheFile( $file_path ){
  475. if( $file_path && $this->CacheEnabled() ){
  476. $env = get_object_vars($this->env);
  477. unset($env['frames']);
  478. $parts = array();
  479. $parts[] = $file_path;
  480. $parts[] = filesize( $file_path );
  481. $parts[] = filemtime( $file_path );
  482. $parts[] = $env;
  483. $parts[] = Less_Version::cache_version;
  484. $parts[] = Less_Parser::$options['cache_method'];
  485. return Less_Cache::$cache_dir . Less_Cache::$prefix . base_convert( sha1(json_encode($parts) ), 16, 36) . '.lesscache';
  486. }
  487. }
  488. static function AddParsedFile($file){
  489. self::$imports[] = $file;
  490. }
  491. static function AllParsedFiles(){
  492. return self::$imports;
  493. }
  494. /**
  495. * @param string $file
  496. */
  497. static function FileParsed($file){
  498. return in_array($file,self::$imports);
  499. }
  500. function save() {
  501. $this->saveStack[] = $this->pos;
  502. }
  503. private function restore() {
  504. $this->pos = array_pop($this->saveStack);
  505. }
  506. private function forget(){
  507. array_pop($this->saveStack);
  508. }
  509. private function isWhitespace($offset = 0) {
  510. return preg_match('/\s/',$this->input[ $this->pos + $offset]);
  511. }
  512. /**
  513. * Parse from a token, regexp or string, and move forward if match
  514. *
  515. * @param array $toks
  516. * @return array
  517. */
  518. private function match($toks){
  519. // The match is confirmed, add the match length to `this::pos`,
  520. // and consume any extra white-space characters (' ' || '\n')
  521. // which come after that. The reason for this is that LeSS's
  522. // grammar is mostly white-space insensitive.
  523. //
  524. foreach($toks as $tok){
  525. $char = $tok[0];
  526. if( $char === '/' ){
  527. $match = $this->MatchReg($tok);
  528. if( $match ){
  529. return count($match) === 1 ? $match[0] : $match;
  530. }
  531. }elseif( $char === '#' ){
  532. $match = $this->MatchChar($tok[1]);
  533. }else{
  534. // Non-terminal, match using a function call
  535. $match = $this->$tok();
  536. }
  537. if( $match ){
  538. return $match;
  539. }
  540. }
  541. }
  542. /**
  543. * @param string[] $toks
  544. *
  545. * @return string
  546. */
  547. private function MatchFuncs($toks){
  548. if( $this->pos < $this->input_len ){
  549. foreach($toks as $tok){
  550. $match = $this->$tok();
  551. if( $match ){
  552. return $match;
  553. }
  554. }
  555. }
  556. }
  557. // Match a single character in the input,
  558. private function MatchChar($tok){
  559. if( ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok) ){
  560. $this->skipWhitespace(1);
  561. return $tok;
  562. }
  563. }
  564. // Match a regexp from the current start point
  565. private function MatchReg($tok){
  566. if( preg_match($tok, $this->input, $match, 0, $this->pos) ){
  567. $this->skipWhitespace(strlen($match[0]));
  568. return $match;
  569. }
  570. }
  571. /**
  572. * Same as match(), but don't change the state of the parser,
  573. * just return the match.
  574. *
  575. * @param string $tok
  576. * @return integer
  577. */
  578. public function PeekReg($tok){
  579. return preg_match($tok, $this->input, $match, 0, $this->pos);
  580. }
  581. /**
  582. * @param string $tok
  583. */
  584. public function PeekChar($tok){
  585. //return ($this->input[$this->pos] === $tok );
  586. return ($this->pos < $this->input_len) && ($this->input[$this->pos] === $tok );
  587. }
  588. /**
  589. * @param integer $length
  590. */
  591. public function skipWhitespace($length){
  592. $this->pos += $length;
  593. for(; $this->pos < $this->input_len; $this->pos++ ){
  594. $c = $this->input[$this->pos];
  595. if( ($c !== "\n") && ($c !== "\r") && ($c !== "\t") && ($c !== ' ') ){
  596. break;
  597. }
  598. }
  599. }
  600. /**
  601. * @param string $tok
  602. * @param string|null $msg
  603. */
  604. public function expect($tok, $msg = NULL) {
  605. $result = $this->match( array($tok) );
  606. if (!$result) {
  607. $this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
  608. } else {
  609. return $result;
  610. }
  611. }
  612. /**
  613. * @param string $tok
  614. */
  615. public function expectChar($tok, $msg = null ){
  616. $result = $this->MatchChar($tok);
  617. if( !$result ){
  618. $this->Error( $msg ? "Expected '" . $tok . "' got '" . $this->input[$this->pos] . "'" : $msg );
  619. }else{
  620. return $result;
  621. }
  622. }
  623. //
  624. // Here in, the parsing rules/functions
  625. //
  626. // The basic structure of the syntax tree generated is as follows:
  627. //
  628. // Ruleset -> Rule -> Value -> Expression -> Entity
  629. //
  630. // Here's some LESS code:
  631. //
  632. // .class {
  633. // color: #fff;
  634. // border: 1px solid #000;
  635. // width: @w + 4px;
  636. // > .child {...}
  637. // }
  638. //
  639. // And here's what the parse tree might look like:
  640. //
  641. // Ruleset (Selector '.class', [
  642. // Rule ("color", Value ([Expression [Color #fff]]))
  643. // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
  644. // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
  645. // Ruleset (Selector [Element '>', '.child'], [...])
  646. // ])
  647. //
  648. // In general, most rules will try to parse a token with the `$()` function, and if the return
  649. // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
  650. // first, before parsing, that's when we use `peek()`.
  651. //
  652. //
  653. // The `primary` rule is the *entry* and *exit* point of the parser.
  654. // The rules here can appear at any level of the parse tree.
  655. //
  656. // The recursive nature of the grammar is an interplay between the `block`
  657. // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
  658. // as represented by this simplified grammar:
  659. //
  660. // primary → (ruleset | rule)+
  661. // ruleset → selector+ block
  662. // block → '{' primary '}'
  663. //
  664. // Only at one point is the primary rule not called from the
  665. // block rule: at the root level.
  666. //
  667. private function parsePrimary(){
  668. $root = array();
  669. while( true ){
  670. if( $this->pos >= $this->input_len ){
  671. break;
  672. }
  673. $node = $this->parseExtend(true);
  674. if( $node ){
  675. $root = array_merge($root,$node);
  676. continue;
  677. }
  678. //$node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseDirective'));
  679. $node = $this->MatchFuncs( array( 'parseMixinDefinition', 'parseNameValue', 'parseRule', 'parseRuleset', 'parseMixinCall', 'parseComment', 'parseRulesetCall', 'parseDirective'));
  680. if( $node ){
  681. $root[] = $node;
  682. }elseif( !$this->MatchReg('/\\G[\s\n;]+/') ){
  683. break;
  684. }
  685. if( $this->PeekChar('}') ){
  686. break;
  687. }
  688. }
  689. return $root;
  690. }
  691. // We create a Comment node for CSS comments `/* */`,
  692. // but keep the LeSS comments `//` silent, by just skipping
  693. // over them.
  694. private function parseComment(){
  695. if( $this->input[$this->pos] !== '/' ){
  696. return;
  697. }
  698. if( $this->input[$this->pos+1] === '/' ){
  699. $match = $this->MatchReg('/\\G\/\/.*/');
  700. return $this->NewObj4('Less_Tree_Comment',array($match[0], true, $this->pos, $this->env->currentFileInfo));
  701. }
  702. //$comment = $this->MatchReg('/\\G\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/');
  703. $comment = $this->MatchReg('/\\G\/\*(?s).*?\*+\/\n?/');//not the same as less.js to prevent fatal errors
  704. if( $comment ){
  705. return $this->NewObj4('Less_Tree_Comment',array($comment[0], false, $this->pos, $this->env->currentFileInfo));
  706. }
  707. }
  708. private function parseComments(){
  709. $comments = array();
  710. while( $this->pos < $this->input_len ){
  711. $comment = $this->parseComment();
  712. if( !$comment ){
  713. break;
  714. }
  715. $comments[] = $comment;
  716. }
  717. return $comments;
  718. }
  719. //
  720. // A string, which supports escaping " and '
  721. //
  722. // "milky way" 'he\'s the one!'
  723. //
  724. private function parseEntitiesQuoted() {
  725. $j = $this->pos;
  726. $e = false;
  727. $index = $this->pos;
  728. if( $this->input[$this->pos] === '~' ){
  729. $j++;
  730. $e = true; // Escaped strings
  731. }
  732. if( $this->input[$j] != '"' && $this->input[$j] !== "'" ){
  733. return;
  734. }
  735. if ($e) {
  736. $this->MatchChar('~');
  737. }
  738. // Fix for #124: match escaped newlines
  739. //$str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.)*)"|\'((?:[^\'\\\\\r\n]|\\\\.)*)\'/');
  740. $str = $this->MatchReg('/\\G"((?:[^"\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)"|\'((?:[^\'\\\\\r\n]|\\\\.|\\\\\r\n|\\\\[\n\r\f])*)\'/');
  741. if( $str ){
  742. $result = $str[0][0] == '"' ? $str[1] : $str[2];
  743. return $this->NewObj5('Less_Tree_Quoted',array($str[0], $result, $e, $index, $this->env->currentFileInfo) );
  744. }
  745. return;
  746. }
  747. //
  748. // A catch-all word, such as:
  749. //
  750. // black border-collapse
  751. //
  752. private function parseEntitiesKeyword(){
  753. //$k = $this->MatchReg('/\\G[_A-Za-z-][_A-Za-z0-9-]*/');
  754. $k = $this->MatchReg('/\\G%|\\G[_A-Za-z-][_A-Za-z0-9-]*/');
  755. if( $k ){
  756. $k = $k[0];
  757. $color = $this->fromKeyword($k);
  758. if( $color ){
  759. return $color;
  760. }
  761. return $this->NewObj1('Less_Tree_Keyword',$k);
  762. }
  763. }
  764. // duplicate of Less_Tree_Color::FromKeyword
  765. private function FromKeyword( $keyword ){
  766. $keyword = strtolower($keyword);
  767. if( Less_Colors::hasOwnProperty($keyword) ){
  768. // detect named color
  769. return $this->NewObj1('Less_Tree_Color',substr(Less_Colors::color($keyword), 1));
  770. }
  771. if( $keyword === 'transparent' ){
  772. return $this->NewObj3('Less_Tree_Color', array( array(0, 0, 0), 0, true));
  773. }
  774. }
  775. //
  776. // A function call
  777. //
  778. // rgb(255, 0, 255)
  779. //
  780. // We also try to catch IE's `alpha()`, but let the `alpha` parser
  781. // deal with the details.
  782. //
  783. // The arguments are parsed with the `entities.arguments` parser.
  784. //
  785. private function parseEntitiesCall(){
  786. $index = $this->pos;
  787. if( !preg_match('/\\G([\w-]+|%|progid:[\w\.]+)\(/', $this->input, $name,0,$this->pos) ){
  788. return;
  789. }
  790. $name = $name[1];
  791. $nameLC = strtolower($name);
  792. if ($nameLC === 'url') {
  793. return null;
  794. }
  795. $this->pos += strlen($name);
  796. if( $nameLC === 'alpha' ){
  797. $alpha_ret = $this->parseAlpha();
  798. if( $alpha_ret ){
  799. return $alpha_ret;
  800. }
  801. }
  802. $this->MatchChar('('); // Parse the '(' and consume whitespace.
  803. $args = $this->parseEntitiesArguments();
  804. if( !$this->MatchChar(')') ){
  805. return;
  806. }
  807. if ($name) {
  808. return $this->NewObj4('Less_Tree_Call',array($name, $args, $index, $this->env->currentFileInfo) );
  809. }
  810. }
  811. /**
  812. * Parse a list of arguments
  813. *
  814. * @return array
  815. */
  816. private function parseEntitiesArguments(){
  817. $args = array();
  818. while( true ){
  819. $arg = $this->MatchFuncs( array('parseEntitiesAssignment','parseExpression') );
  820. if( !$arg ){
  821. break;
  822. }
  823. $args[] = $arg;
  824. if( !$this->MatchChar(',') ){
  825. break;
  826. }
  827. }
  828. return $args;
  829. }
  830. private function parseEntitiesLiteral(){
  831. return $this->MatchFuncs( array('parseEntitiesDimension','parseEntitiesColor','parseEntitiesQuoted','parseUnicodeDescriptor') );
  832. }
  833. // Assignments are argument entities for calls.
  834. // They are present in ie filter properties as shown below.
  835. //
  836. // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
  837. //
  838. private function parseEntitiesAssignment() {
  839. $key = $this->MatchReg('/\\G\w+(?=\s?=)/');
  840. if( !$key ){
  841. return;
  842. }
  843. if( !$this->MatchChar('=') ){
  844. return;
  845. }
  846. $value = $this->parseEntity();
  847. if( $value ){
  848. return $this->NewObj2('Less_Tree_Assignment',array($key[0], $value));
  849. }
  850. }
  851. //
  852. // Parse url() tokens
  853. //
  854. // We use a specific rule for urls, because they don't really behave like
  855. // standard function calls. The difference is that the argument doesn't have
  856. // to be enclosed within a string, so it can't be parsed as an Expression.
  857. //
  858. private function parseEntitiesUrl(){
  859. if( $this->input[$this->pos] !== 'u' || !$this->matchReg('/\\Gurl\(/') ){
  860. return;
  861. }
  862. $value = $this->match( array('parseEntitiesQuoted','parseEntitiesVariable','/\\Gdata\:.*?[^\)]+/','/\\G(?:(?:\\\\[\(\)\'"])|[^\(\)\'"])+/') );
  863. if( !$value ){
  864. $value = '';
  865. }
  866. $this->expectChar(')');
  867. if( isset($value->value) || $value instanceof Less_Tree_Variable ){
  868. return $this->NewObj2('Less_Tree_Url',array($value, $this->env->currentFileInfo));
  869. }
  870. return $this->NewObj2('Less_Tree_Url', array( $this->NewObj1('Less_Tree_Anonymous',$value), $this->env->currentFileInfo) );
  871. }
  872. //
  873. // A Variable entity, such as `@fink`, in
  874. //
  875. // width: @fink + 2px
  876. //
  877. // We use a different parser for variable definitions,
  878. // see `parsers.variable`.
  879. //
  880. private function parseEntitiesVariable(){
  881. $index = $this->pos;
  882. if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G@@?[\w-]+/'))) {
  883. return $this->NewObj3('Less_Tree_Variable', array( $name[0], $index, $this->env->currentFileInfo));
  884. }
  885. }
  886. // A variable entity useing the protective {} e.g. @{var}
  887. private function parseEntitiesVariableCurly() {
  888. $index = $this->pos;
  889. if( $this->input_len > ($this->pos+1) && $this->input[$this->pos] === '@' && ($curly = $this->MatchReg('/\\G@\{([\w-]+)\}/')) ){
  890. return $this->NewObj3('Less_Tree_Variable',array('@'.$curly[1], $index, $this->env->currentFileInfo));
  891. }
  892. }
  893. //
  894. // A Hexadecimal color
  895. //
  896. // #4F3C2F
  897. //
  898. // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
  899. //
  900. private function parseEntitiesColor(){
  901. if ($this->PeekChar('#') && ($rgb = $this->MatchReg('/\\G#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/'))) {
  902. return $this->NewObj1('Less_Tree_Color',$rgb[1]);
  903. }
  904. }
  905. //
  906. // A Dimension, that is, a number and a unit
  907. //
  908. // 0.5em 95%
  909. //
  910. private function parseEntitiesDimension(){
  911. $c = @ord($this->input[$this->pos]);
  912. //Is the first char of the dimension 0-9, '.', '+' or '-'
  913. if (($c > 57 || $c < 43) || $c === 47 || $c == 44){
  914. return;
  915. }
  916. $value = $this->MatchReg('/\\G([+-]?\d*\.?\d+)(%|[a-z]+)?/');
  917. if( $value ){
  918. if( isset($value[2]) ){
  919. return $this->NewObj2('Less_Tree_Dimension', array($value[1],$value[2]));
  920. }
  921. return $this->NewObj1('Less_Tree_Dimension',$value[1]);
  922. }
  923. }
  924. //
  925. // A unicode descriptor, as is used in unicode-range
  926. //
  927. // U+0?? or U+00A1-00A9
  928. //
  929. function parseUnicodeDescriptor() {
  930. $ud = $this->MatchReg('/\\G(U\+[0-9a-fA-F?]+)(\-[0-9a-fA-F?]+)?/');
  931. if( $ud ){
  932. return $this->NewObj1('Less_Tree_UnicodeDescriptor', $ud[0]);
  933. }
  934. }
  935. //
  936. // JavaScript code to be evaluated
  937. //
  938. // `window.location.href`
  939. //
  940. private function parseEntitiesJavascript(){
  941. $e = false;
  942. $j = $this->pos;
  943. if( $this->input[$j] === '~' ){
  944. $j++;
  945. $e = true;
  946. }
  947. if( $this->input[$j] !== '`' ){
  948. return;
  949. }
  950. if( $e ){
  951. $this->MatchChar('~');
  952. }
  953. $str = $this->MatchReg('/\\G`([^`]*)`/');
  954. if( $str ){
  955. return $this->NewObj3('Less_Tree_Javascript', array($str[1], $this->pos, $e));
  956. }
  957. }
  958. //
  959. // The variable part of a variable definition. Used in the `rule` parser
  960. //
  961. // @fink:
  962. //
  963. private function parseVariable(){
  964. if ($this->PeekChar('@') && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*:/'))) {
  965. return $name[1];
  966. }
  967. }
  968. //
  969. // The variable part of a variable definition. Used in the `rule` parser
  970. //
  971. // @fink();
  972. //
  973. private function parseRulesetCall(){
  974. if( $this->input[$this->pos] === '@' && ($name = $this->MatchReg('/\\G(@[\w-]+)\s*\(\s*\)\s*;/')) ){
  975. return $this->NewObj1('Less_Tree_RulesetCall', $name[1] );
  976. }
  977. }
  978. //
  979. // extend syntax - used to extend selectors
  980. //
  981. function parseExtend($isRule = false){
  982. $index = $this->pos;
  983. $extendList = array();
  984. if( !$this->MatchReg( $isRule ? '/\\G&:extend\(/' : '/\\G:extend\(/' ) ){ return; }
  985. do{
  986. $option = null;
  987. $elements = array();
  988. while( true ){
  989. $option = $this->MatchReg('/\\G(all)(?=\s*(\)|,))/');
  990. if( $option ){ break; }
  991. $e = $this->parseElement();
  992. if( !$e ){ break; }
  993. $elements[] = $e;
  994. }
  995. if( $option ){
  996. $option = $option[1];
  997. }
  998. $extendList[] = $this->NewObj3('Less_Tree_Extend', array( $this->NewObj1('Less_Tree_Selector',$elements), $option, $index ));
  999. }while( $this->MatchChar(",") );
  1000. $this->expect('/\\G\)/');
  1001. if( $isRule ){
  1002. $this->expect('/\\G;/');
  1003. }
  1004. return $extendList;
  1005. }
  1006. //
  1007. // A Mixin call, with an optional argument list
  1008. //
  1009. // #mixins > .square(#fff);
  1010. // .rounded(4px, black);
  1011. // .button;
  1012. //
  1013. // The `while` loop is there because mixins can be
  1014. // namespaced, but we only support the child and descendant
  1015. // selector for now.
  1016. //
  1017. private function parseMixinCall(){
  1018. $char = $this->input[$this->pos];
  1019. if( $char !== '.' && $char !== '#' ){
  1020. return;
  1021. }
  1022. $index = $this->pos;
  1023. $this->save(); // stop us absorbing part of an invalid selector
  1024. $elements = $this->parseMixinCallElements();
  1025. if( $elements ){
  1026. if( $this->MatchChar('(') ){
  1027. $returned = $this->parseMixinArgs(true);
  1028. $args = $returned['args'];
  1029. $this->expectChar(')');
  1030. }else{
  1031. $args = array();
  1032. }
  1033. $important = $this->parseImportant();
  1034. if( $this->parseEnd() ){
  1035. $this->forget();
  1036. return $this->NewObj5('Less_Tree_Mixin_Call', array( $elements, $args, $index, $this->env->currentFileInfo, $important));
  1037. }
  1038. }
  1039. $this->restore();
  1040. }
  1041. private function parseMixinCallElements(){
  1042. $elements = array();
  1043. $c = null;
  1044. while( true ){
  1045. $elemIndex = $this->pos;
  1046. $e = $this->MatchReg('/\\G[#.](?:[\w-]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/');
  1047. if( !$e ){
  1048. break;
  1049. }
  1050. $elements[] = $this->NewObj4('Less_Tree_Element', array($c, $e[0], $elemIndex, $this->env->currentFileInfo));
  1051. $c = $this->MatchChar('>');
  1052. }
  1053. return $elements;
  1054. }
  1055. /**
  1056. * @param boolean $isCall
  1057. */
  1058. private function parseMixinArgs( $isCall ){
  1059. $expressions = array();
  1060. $argsSemiColon = array();
  1061. $isSemiColonSeperated = null;
  1062. $argsComma = array();
  1063. $expressionContainsNamed = null;
  1064. $name = null;
  1065. $returner = array('args'=>array(), 'variadic'=> false);
  1066. $this->save();
  1067. while( true ){
  1068. if( $isCall ){
  1069. $arg = $this->MatchFuncs( array( 'parseDetachedRuleset','parseExpression' ) );
  1070. } else {
  1071. $this->parseComments();
  1072. if( $this->input[ $this->pos ] === '.' && $this->MatchReg('/\\G\.{3}/') ){
  1073. $returner['variadic'] = true;
  1074. if( $this->MatchChar(";") && !$isSemiColonSeperated ){
  1075. $isSemiColonSeperated = true;
  1076. }
  1077. if( $isSemiColonSeperated ){
  1078. $argsSemiColon[] = array('variadic'=>true);
  1079. }else{
  1080. $argsComma[] = array('variadic'=>true);
  1081. }
  1082. break;
  1083. }
  1084. $arg = $this->MatchFuncs( array('parseEntitiesVariable','parseEntitiesLiteral','parseEntitiesKeyword') );
  1085. }
  1086. if( !$arg ){
  1087. break;
  1088. }
  1089. $nameLoop = null;
  1090. if( $arg instanceof Less_Tree_Expression ){
  1091. $arg->throwAwayComments();
  1092. }
  1093. $value = $arg;
  1094. $val = null;
  1095. if( $isCall ){
  1096. // Variable
  1097. if( property_exists($arg,'value') && count($arg->value) == 1 ){
  1098. $val = $arg->value[0];
  1099. }
  1100. } else {
  1101. $val = $arg;
  1102. }
  1103. if( $val instanceof Less_Tree_Variable ){
  1104. if( $this->MatchChar(':') ){
  1105. if( $expressions ){
  1106. if( $isSemiColonSeperated ){
  1107. $this->Error('Cannot mix ; and , as delimiter types');
  1108. }
  1109. $expressionContainsNamed = true;
  1110. }
  1111. // we do not support setting a ruleset as a default variable - it doesn't make sense
  1112. // However if we do want to add it, there is nothing blocking it, just don't error
  1113. // and remove isCall dependency below
  1114. $value = null;
  1115. if( $isCall ){
  1116. $value = $this->parseDetachedRuleset();
  1117. }
  1118. if( !$value ){
  1119. $value = $this->parseExpression();
  1120. }
  1121. if( !$value ){
  1122. if( $isCall ){
  1123. $this->Error('could not understand value for named argument');
  1124. } else {
  1125. $this->restore();
  1126. $returner['args'] = array();
  1127. return $returner;
  1128. }
  1129. }
  1130. $nameLoop = ($name = $val->name);
  1131. }elseif( !$isCall && $this->MatchReg('/\\G\.{3}/') ){
  1132. $returner['variadic'] = true;
  1133. if( $this->MatchChar(";") && !$isSemiColonSeperated ){
  1134. $isSemiColonSeperated = true;
  1135. }
  1136. if( $isSemiColonSeperated ){
  1137. $argsSemiColon[] = array('name'=> $arg->name, 'variadic' => true);
  1138. }else{
  1139. $argsComma[] = array('name'=> $arg->name, 'variadic' => true);
  1140. }
  1141. break;
  1142. }elseif( !$isCall ){
  1143. $name = $nameLoop = $val->name;
  1144. $value = null;
  1145. }
  1146. }
  1147. if( $value ){
  1148. $expressions[] = $value;
  1149. }
  1150. $argsComma[] = array('name'=>$nameLoop, 'value'=>$value );
  1151. if( $this->MatchChar(',') ){
  1152. continue;
  1153. }
  1154. if( $this->MatchChar(';') || $isSemiColonSeperated ){
  1155. if( $expressionContainsNamed ){
  1156. $this->Error('Cannot mix ; and , as delimiter types');
  1157. }
  1158. $isSemiColonSeperated = true;
  1159. if( count($expressions) > 1 ){
  1160. $value = $this->NewObj1('Less_Tree_Value', $expressions);
  1161. }
  1162. $argsSemiColon[] = array('name'=>$name, 'value'=>$value );
  1163. $name = null;
  1164. $expressions = array();
  1165. $expressionContainsNamed = false;
  1166. }
  1167. }
  1168. $this->forget();
  1169. $returner['args'] = ($isSemiColonSeperated ? $argsSemiColon : $argsComma);
  1170. return $returner;
  1171. }
  1172. //
  1173. // A Mixin definition, with a list of parameters
  1174. //
  1175. // .rounded (@radius: 2px, @color) {
  1176. // ...
  1177. // }
  1178. //
  1179. // Until we have a finer grained state-machine, we have to
  1180. // do a look-ahead, to make sure we don't have a mixin call.
  1181. // See the `rule` function for more information.
  1182. //
  1183. // We start by matching `.rounded (`, and then proceed on to
  1184. // the argument list, which has optional default values.
  1185. // We store the parameters in `params`, with a `value` key,
  1186. // if there is a value, such as in the case of `@radius`.
  1187. //
  1188. // Once we've got our params list, and a closing `)`, we parse
  1189. // the `{...}` block.
  1190. //
  1191. private function parseMixinDefinition(){
  1192. $cond = null;
  1193. $char = $this->input[$this->pos];
  1194. if( ($char !== '.' && $char !== '#') || ($char === '{' && $this->PeekReg('/\\G[^{]*\}/')) ){
  1195. return;
  1196. }
  1197. $this->save();
  1198. $match = $this->MatchReg('/\\G([#.](?:[\w-]|\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/');
  1199. if( $match ){
  1200. $name = $match[1];
  1201. $argInfo = $this->parseMixinArgs( false );
  1202. $params = $argInfo['args'];
  1203. $variadic = $argInfo['variadic'];
  1204. // .mixincall("@{a}");
  1205. // looks a bit like a mixin definition..
  1206. // also
  1207. // .mixincall(@a: {rule: set;});
  1208. // so we have to be nice and restore
  1209. if( !$this->MatchChar(')') ){
  1210. $this->furthest = $this->pos;
  1211. $this->restore();
  1212. return;
  1213. }
  1214. $this->parseComments();
  1215. if ($this->MatchReg('/\\Gwhen/')) { // Guard
  1216. $cond = $this->expect('parseConditions', 'Expected conditions');
  1217. }
  1218. $ruleset = $this->parseBlock();
  1219. if( is_array($ruleset) ){
  1220. $this->forget();
  1221. return $this->NewObj5('Less_Tree_Mixin_Definition', array( $name, $params, $ruleset, $cond, $variadic));
  1222. }
  1223. $this->restore();
  1224. }else{
  1225. $this->forget();
  1226. }
  1227. }
  1228. //
  1229. // Entities are the smallest recognized token,
  1230. // and can be found inside a rule's value.
  1231. //
  1232. private function parseEntity(){
  1233. return $this->MatchFuncs( array('parseEntitiesLiteral','parseEntitiesVariable','parseEntitiesUrl','parseEntitiesCall','parseEntitiesKeyword','parseEntitiesJavascript','parseComment') );
  1234. }
  1235. //
  1236. // A Rule terminator. Note that we use `peek()` to check for '}',
  1237. // because the `block` rule will be expecting it, but we still need to make sure
  1238. // it's there, if ';' was ommitted.
  1239. //
  1240. private function parseEnd(){
  1241. return $this->MatchChar(';') || $this->PeekChar('}');
  1242. }
  1243. //
  1244. // IE's alpha function
  1245. //
  1246. // alpha(opacity=88)
  1247. //
  1248. private function parseAlpha(){
  1249. if ( ! $this->MatchReg('/\\G\(opacity=/i')) {
  1250. return;
  1251. }
  1252. $value = $this->MatchReg('/\\G[0-9]+/');
  1253. if( $value ){
  1254. $value = $value[0];
  1255. }else{
  1256. $value = $this->parseEntitiesVariable();
  1257. if( !$value ){
  1258. return;
  1259. }
  1260. }
  1261. $this->expectChar(')');
  1262. return $this->NewObj1('Less_Tree_Alpha',$value);
  1263. }
  1264. //
  1265. // A Selector Element
  1266. //
  1267. // div
  1268. // + h1
  1269. // #socks
  1270. // input[type="text"]
  1271. //
  1272. // Elements are the building blocks for Selectors,
  1273. // they are made out of a `Combinator` (see combinator rule),
  1274. // and an element name, such as a tag a class, or `*`.
  1275. //
  1276. private function parseElement(){
  1277. $c = $this->parseCombinator();
  1278. $index = $this->pos;
  1279. $e = $this->match( array('/\\G(?:\d+\.\d+|\d+)%/', '/\\G(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/',
  1280. '#*', '#&', 'parseAttribute', '/\\G\([^()@]+\)/', '/\\G[\.#](?=@)/', 'parseEntitiesVariableCurly') );
  1281. if( is_null($e) ){
  1282. $this->save();
  1283. if( $this->MatchChar('(') ){
  1284. if( ($v = $this->parseSelector()) && $this->MatchChar(')') ){
  1285. $e = $this->NewObj1('Less_Tree_Paren',$v);
  1286. $this->forget();
  1287. }else{
  1288. $this->restore();
  1289. }
  1290. }else{
  1291. $this->forget();
  1292. }
  1293. }
  1294. if( !is_null($e) ){
  1295. return $this->NewObj4('Less_Tree_Element',array( $c, $e, $index, $this->env->currentFileInfo));
  1296. }
  1297. }
  1298. //
  1299. // Combinators combine elements together, in a Selector.
  1300. //
  1301. // Because our parser isn't white-space sensitive, special care
  1302. // has to be taken, when parsing the descendant combinator, ` `,
  1303. // as it's an empty space. We have to check the previous character
  1304. // in the input, to see if it's a ` ` character.
  1305. //
  1306. private function parseCombinator(){
  1307. if( $this->pos < $this->input_len ){
  1308. $c = $this->input[$this->pos];
  1309. if ($c === '>' || $c === '+' || $c === '~' || $c === '|' || $c === '^' ){
  1310. $this->pos++;
  1311. if( $this->input[$this->pos] === '^' ){
  1312. $c = '^^';
  1313. $this->pos++;
  1314. }
  1315. $this->skipWhitespace(0);
  1316. return $c;
  1317. }
  1318. if( $this->pos > 0 && $this->isWhitespace(-1) ){
  1319. return ' ';
  1320. }
  1321. }
  1322. }
  1323. //
  1324. // A CSS selector (see selector below)
  1325. // with less extensions e.g. the ability to extend and guard
  1326. //
  1327. private function parseLessSelector(){
  1328. return $this->parseSelector(true);
  1329. }
  1330. //
  1331. // A CSS Selector
  1332. //
  1333. // .class > div + h1
  1334. // li a:hover
  1335. //
  1336. // Selectors are made out of one or more Elements, see above.
  1337. //
  1338. private function parseSelector( $isLess = false ){
  1339. $elements = array();
  1340. $extendList = array();
  1341. $condition = null;
  1342. $when = false;
  1343. $extend = false;
  1344. $e = null;
  1345. $c = null;
  1346. $index = $this->pos;
  1347. while( ($isLess && ($extend = $this->parseExtend())) || ($isLess && ($when = $this->MatchReg('/\\Gwhen/') )) || ($e = $this->parseElement()) ){
  1348. if( $when ){
  1349. $condition = $this->expect('parseConditions', 'expected condition');
  1350. }elseif( $condition ){
  1351. //error("CSS guard can only be used at the end of selector");
  1352. }elseif( $extend ){
  1353. $extendList = array_merge($extendList,$extend);
  1354. }else{
  1355. //if( count($extendList) ){
  1356. //error("Extend can only be used at the end of selector");
  1357. //}
  1358. if( $this->pos < $this->input_len ){
  1359. $c = $this->input[ $this->pos ];
  1360. }
  1361. $elements[] = $e;
  1362. $e = null;
  1363. }
  1364. if( $c === '{' || $c === '}' || $c === ';' || $c === ',' || $c === ')') { break; }
  1365. }
  1366. if( $elements ){
  1367. return $this->NewObj5('Less_Tree_Selector',array($elements, $extendList, $condition, $index, $this->env->currentFileInfo));
  1368. }
  1369. if( $extendList ) {
  1370. $this->Error('Extend must be used to extend a selector, it cannot be used on its own');
  1371. }
  1372. }
  1373. private function parseTag(){
  1374. return ( $tag = $this->MatchReg('/\\G[A-Za-z][A-Za-z-]*[0-9]?/') ) ? $tag : $this->MatchChar('*');
  1375. }
  1376. private function parseAttribute(){
  1377. $val = null;
  1378. if( !$this->MatchChar('[') ){
  1379. return;
  1380. }
  1381. $key = $this->parseEntitiesVariableCurly();
  1382. if( !$key ){
  1383. $key = $this->expect('/\\G(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\\\.)+/');
  1384. }
  1385. $op = $this->MatchReg('/\\G[|~*$^]?=/');
  1386. if( $op ){
  1387. $val = $this->match( array('parseEntitiesQuoted','/\\G[0-9]+%/','/\\G[\w-]+/','parseEntitiesVariableCurly') );
  1388. }
  1389. $this->expectChar(']');
  1390. return $this->NewObj3('Less_Tree_Attribute',array( $key, $op[0], $val));
  1391. }
  1392. //
  1393. // The `block` rule is used by `ruleset` and `mixin.definition`.
  1394. // It's a wrapper around the `primary` rule, with added `{}`.
  1395. //
  1396. private function parseBlock(){
  1397. if( $this->MatchChar('{') ){
  1398. $content = $this->parsePrimary();
  1399. if( $this->MatchChar('}') ){
  1400. return $content;
  1401. }
  1402. }
  1403. }
  1404. private function parseBlockRuleset(){
  1405. $block = $this->parseBlock();
  1406. if( $block ){
  1407. $block = $this->NewObj2('Less_Tree_Ruleset',array( null, $block));
  1408. }
  1409. return $block;
  1410. }
  1411. private function parseDetachedRuleset(){
  1412. $blockRuleset = $this->parseBlockRuleset();
  1413. if( $blockRuleset ){
  1414. return $this->NewObj1('Less_Tree_DetachedRuleset',$blockRuleset);
  1415. }
  1416. }
  1417. //
  1418. // div, .class, body > p {...}
  1419. //
  1420. private function parseRuleset(){
  1421. $selectors = array();
  1422. $this->save();
  1423. while( true ){
  1424. $s = $this->parseLessSelector();
  1425. if( !$s ){
  1426. break;
  1427. }
  1428. $selectors[] = $s;
  1429. $this->parseComments();
  1430. if( $s->condition && count($selectors) > 1 ){
  1431. $this->Error('Guards are only currently allowed on a single selector.');
  1432. }
  1433. if( !$this->MatchChar(',') ){
  1434. break;
  1435. }
  1436. if( $s->condition ){
  1437. $this->Error('Guards are only currently allowed on a single selector.');
  1438. }
  1439. $this->parseComments();
  1440. }
  1441. if( $selectors ){
  1442. $rules = $this->parseBlock();
  1443. if( is_array($rules) ){
  1444. $this->forget();
  1445. return $this->NewObj2('Less_Tree_Ruleset',array( $selectors, $rules)); //Less_Environment::$strictImports
  1446. }
  1447. }
  1448. // Backtrack
  1449. $this->furthest = $this->pos;
  1450. $this->restore();
  1451. }
  1452. /**
  1453. * Custom less.php parse function for finding simple name-value css pairs
  1454. * ex: width:100px;
  1455. *
  1456. */
  1457. private function parseNameValue(){
  1458. $index = $this->pos;
  1459. $this->save();
  1460. //$match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*((?:\'")?[a-zA-Z0-9\-% \.,!]+?(?:\'")?)\s*([;}])/');
  1461. $match = $this->MatchReg('/\\G([a-zA-Z\-]+)\s*:\s*([\'"]?[#a-zA-Z0-9\-%\.,]+?[\'"]?) *(! *important)?\s*([;}])/');
  1462. if( $match ){
  1463. if( $match[4] == '}' ){
  1464. $this->pos = $index + strlen($match[0])-1;
  1465. }
  1466. if( $match[3] ){
  1467. $match[2] .= ' !important';
  1468. }
  1469. return $this->NewObj4('Less_Tree_NameValue',array( $match[1], $match[2], $index, $this->env->currentFileInfo));
  1470. }
  1471. $this->restore();
  1472. }
  1473. private function parseRule( $tryAnonymous = null ){
  1474. $merge = false;
  1475. $startOfRule = $this->pos;
  1476. $c = $this->input[$this->pos];
  1477. if( $c === '.' || $c === '#' || $c === '&' ){
  1478. return;
  1479. }
  1480. $this->save();
  1481. $name = $this->MatchFuncs( array('parseVariable','parseRuleProperty'));
  1482. if( $name ){
  1483. $isVariable = is_string($name);
  1484. $value = null;
  1485. if( $isVariable ){
  1486. $value = $this->parseDetachedRuleset();
  1487. }
  1488. $important = null;
  1489. if( !$value ){
  1490. // prefer to try to parse first if its a variable or we are compressing
  1491. // but always fallback on the other one
  1492. //if( !$tryAnonymous && is_string($name) && $name[0] === '@' ){
  1493. if( !$tryAnonymous && (Less_Parser::$options['compress'] || $isVariable) ){
  1494. $value = $this->MatchFuncs( array('parseValue','parseAnonymousValue'));
  1495. }else{
  1496. $value = $this->MatchFuncs( array('parseAnonymousValue','parseValue'));
  1497. }
  1498. $important = $this->parseImportant();
  1499. // a name returned by this.ruleProperty() is always an array of the form:
  1500. // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"]
  1501. // where each item is a tree.Keyword or tree.Variable
  1502. if( !$isVariable && is_array($name) ){
  1503. $nm = array_pop($name);
  1504. if( $nm->value ){
  1505. $merge = $nm->value;
  1506. }
  1507. }
  1508. }
  1509. if( $value && $this->parseEnd() ){
  1510. $this->forget();
  1511. return $this->NewObj6('Less_Tree_Rule',array( $name, $value, $important, $merge, $startOfRule, $this->env->currentFileInfo));
  1512. }else{
  1513. $this->furthest = $this->pos;
  1514. $this->restore();
  1515. if( $value && !$tryAnonymous ){
  1516. return $this->parseRule(true);
  1517. }
  1518. }
  1519. }else{
  1520. $this->forget();
  1521. }
  1522. }
  1523. function parseAnonymousValue(){
  1524. if( preg_match('/\\G([^@+\/\'"*`(;{}-]*);/',$this->input, $match, 0, $this->pos) ){
  1525. $this->pos += strlen($match[1]);
  1526. return $this->NewObj1('Less_Tree_Anonymous',$match[1]);
  1527. }
  1528. }
  1529. //
  1530. // An @import directive
  1531. //
  1532. // @import "lib";
  1533. //
  1534. // Depending on our environment, importing is done differently:
  1535. // In the browser, it's an XHR request, in Node, it would be a
  1536. // file-system operation. The function used for importing is
  1537. // stored in `import`, which we pass to the Import constructor.
  1538. //
  1539. private function parseImport(){
  1540. $this->save();
  1541. $dir = $this->MatchReg('/\\G@import?\s+/');
  1542. if( $dir ){
  1543. $options = $this->parseImportOptions();
  1544. $path = $this->MatchFuncs( array('parseEntitiesQuoted','parseEntitiesUrl'));
  1545. if( $path ){
  1546. $features = $this->parseMediaFeatures();
  1547. if( $this->MatchChar(';') ){
  1548. if( $features ){
  1549. $features = $this->NewObj1('Less_Tree_Value',$features);
  1550. }
  1551. $this->forget();
  1552. return $this->NewObj5('Less_Tree_Import',array( $path, $features, $options, $this->pos, $this->env->currentFileInfo));
  1553. }
  1554. }
  1555. }
  1556. $this->restore();
  1557. }
  1558. private function parseImportOptions(){
  1559. $options = array();
  1560. // list of options, surrounded by parens
  1561. if( !$this->MatchChar('(') ){
  1562. return $options;
  1563. }
  1564. do{
  1565. $optionName = $this->parseImportOption();
  1566. if( $optionName ){
  1567. $value = true;
  1568. switch( $optionName ){
  1569. case "css":
  1570. $optionName = "less";
  1571. $value = false;
  1572. break;
  1573. case "once":
  1574. $optionName = "multiple";
  1575. $value = false;
  1576. break;
  1577. }
  1578. $options[$optionName] = $value;
  1579. if( !$this->MatchChar(',') ){ break; }
  1580. }
  1581. }while( $optionName );
  1582. $this->expectChar(')');
  1583. return $options;
  1584. }
  1585. private function parseImportOption(){
  1586. $opt = $this->MatchReg('/\\G(less|css|multiple|once|inline|reference)/');
  1587. if( $opt ){
  1588. return $opt[1];
  1589. }
  1590. }
  1591. private function parseMediaFeature() {
  1592. $nodes = array();
  1593. do{
  1594. $e = $this->MatchFuncs(array('parseEntitiesKeyword','parseEntitiesVariable'));
  1595. if( $e ){
  1596. $nodes[] = $e;
  1597. } elseif ($this->MatchChar('(')) {
  1598. $p = $this->parseProperty();
  1599. $e = $this->parseValue();
  1600. if ($this->MatchChar(')')) {
  1601. if ($p && $e) {
  1602. $r = $this->NewObj7('Less_Tree_Rule', array( $p, $e, null, null, $this->pos, $this->env->currentFileInfo, true));
  1603. $nodes[] = $this->NewObj1('Less_Tree_Paren',$r);
  1604. } elseif ($e) {
  1605. $nodes[] = $this->NewObj1('Less_Tree_Paren',$e);
  1606. } else {
  1607. return null;
  1608. }
  1609. } else
  1610. return null;
  1611. }
  1612. } while ($e);
  1613. if ($nodes) {
  1614. return $this->NewObj1('Less_Tree_Expression',$nodes);
  1615. }
  1616. }
  1617. private function parseMediaFeatures() {
  1618. $features = array();
  1619. do{
  1620. $e = $this->parseMediaFeature();
  1621. if( $e ){
  1622. $features[] = $e;
  1623. if (!$this->MatchChar(',')) break;
  1624. }else{
  1625. $e = $this->parseEntitiesVariable();
  1626. if( $e ){
  1627. $features[] = $e;
  1628. if (!$this->MatchChar(',')) break;
  1629. }
  1630. }
  1631. } while ($e);
  1632. return $features ? $features : null;
  1633. }
  1634. private function parseMedia() {
  1635. if( $this->MatchReg('/\\G@media/') ){
  1636. $features = $this->parseMediaFeatures();
  1637. $rules = $this->parseBlock();
  1638. if( is_array($rules) ){
  1639. return $this->NewObj4('Less_Tree_Media',array( $rules, $features, $this->pos, $this->env->currentFileInfo));
  1640. }
  1641. }
  1642. }
  1643. //
  1644. // A CSS Directive
  1645. //
  1646. // @charset "utf-8";
  1647. //
  1648. private function parseDirective(){
  1649. if( !$this->PeekChar('@') ){
  1650. return;
  1651. }
  1652. $rules = null;
  1653. $index = $this->pos;
  1654. $hasBlock = true;
  1655. $hasIdentifier = false;
  1656. $hasExpression = false;
  1657. $hasUnknown = false;
  1658. $value = $this->MatchFuncs(array('parseImport','parseMedia'));
  1659. if( $value ){
  1660. return $value;
  1661. }
  1662. $this->save();
  1663. $name = $this->MatchReg('/\\G@[a-z-]+/');
  1664. if( !$name ) return;
  1665. $name = $name[0];
  1666. $nonVendorSpecificName = $name;
  1667. $pos = strpos($name,'-', 2);
  1668. if( $name[1] == '-' && $pos > 0 ){
  1669. $nonVendorSpecificName = "@" . substr($name, $pos + 1);
  1670. }
  1671. switch( $nonVendorSpecificName ){
  1672. /*
  1673. case "@font-face":
  1674. case "@viewport":
  1675. case "@top-left":
  1676. case "@top-left-corner":
  1677. case "@top-center":
  1678. case "@top-right":
  1679. case "@top-right-corner":
  1680. case "@bottom-left":
  1681. case "@bottom-left-corner":
  1682. case "@bottom-center":
  1683. case "@bottom-right":
  1684. case "@bottom-right-corner":
  1685. case "@left-top":
  1686. case "@left-middle":
  1687. case "@left-bottom":
  1688. case "@right-top":
  1689. case "@right-middle":
  1690. case "@right-bottom":
  1691. hasBlock = true;
  1692. break;
  1693. */
  1694. case "@charset":
  1695. $hasIdentifier = true;
  1696. $hasBlock = false;
  1697. break;
  1698. case "@namespace":
  1699. $hasExpression = true;
  1700. $hasBlock = false;
  1701. break;
  1702. case "@keyframes":
  1703. $hasIdentifier = true;
  1704. break;
  1705. case "@host":
  1706. case "@page":
  1707. case "@document":
  1708. case "@supports":
  1709. $hasUnknown = true;
  1710. break;
  1711. }
  1712. if( $hasIdentifier ){
  1713. $value = $this->parseEntity();
  1714. if( !$value ){
  1715. $this->error("expected " . $name . " identifier");
  1716. }
  1717. } else if( $hasExpression ){
  1718. $value = $this->parseExpression();
  1719. if( !$value ){
  1720. $this->error("expected " . $name. " expression");
  1721. }
  1722. } else if ($hasUnknown) {
  1723. $value = $this->MatchReg('/\\G[^{;]+/');
  1724. if( $value ){
  1725. $value = $this->NewObj1('Less_Tree_Anonymous',trim($value[0]));
  1726. }
  1727. }
  1728. if( $hasBlock ){
  1729. $rules = $this->parseBlockRuleset();
  1730. }
  1731. if( $rules || (!$hasBlock && $value && $this->MatchChar(';'))) {
  1732. $this->forget();
  1733. return $this->NewObj5('Less_Tree_Directive',array($name, $value, $rules, $index, $this->env->currentFileInfo));
  1734. }
  1735. $this->restore();
  1736. }
  1737. //
  1738. // A Value is a comma-delimited list of Expressions
  1739. //
  1740. // font-family: Baskerville, Georgia, serif;
  1741. //
  1742. // In a Rule, a Value represents everything after the `:`,
  1743. // and before the `;`.
  1744. //
  1745. private function parseValue(){
  1746. $expressions = array();
  1747. do{
  1748. $e = $this->parseExpression();
  1749. if( $e ){
  1750. $expressions[] = $e;
  1751. if (! $this->MatchChar(',')) {
  1752. break;
  1753. }
  1754. }
  1755. }while($e);
  1756. if( $expressions ){
  1757. return $this->NewObj1('Less_Tree_Value',$expressions);
  1758. }
  1759. }
  1760. private function parseImportant (){
  1761. if( $this->PeekChar('!') && $this->MatchReg('/\\G! *important/') ){
  1762. return ' !important';
  1763. }
  1764. }
  1765. private function parseSub (){
  1766. if( $this->MatchChar('(') ){
  1767. $a = $this->parseAddition();
  1768. if( $a ){
  1769. $this->expectChar(')');
  1770. return $this->NewObj2('Less_Tree_Expression',array( array($a), true) ); //instead of $e->parens = true so the value is cached
  1771. }
  1772. }
  1773. }
  1774. /**
  1775. * Parses multiplication operation
  1776. *
  1777. * @return Less_Tree_Operation|null
  1778. */
  1779. function parseMultiplication(){
  1780. $return = $m = $this->parseOperand();
  1781. if( $return ){
  1782. while( true ){
  1783. $isSpaced = $this->isWhitespace( -1 );
  1784. if( $this->PeekReg('/\\G\/[*\/]/') ){
  1785. break;
  1786. }
  1787. $op = $this->MatchChar('/');
  1788. if( !$op ){
  1789. $op = $this->MatchChar('*');
  1790. if( !$op ){
  1791. break;
  1792. }
  1793. }
  1794. $a = $this->parseOperand();
  1795. if(!$a) { break; }
  1796. $m->parensInOp = true;
  1797. $a->parensInOp = true;
  1798. $return = $this->NewObj3('Less_Tree_Operation',array( $op, array( $return, $a ), $isSpaced) );
  1799. }
  1800. }
  1801. return $return;
  1802. }
  1803. /**
  1804. * Parses an addition operation
  1805. *
  1806. * @return Less_Tree_Operation|null
  1807. */
  1808. private function parseAddition (){
  1809. $return = $m = $this->parseMultiplication();
  1810. if( $return ){
  1811. while( true ){
  1812. $isSpaced = $this->isWhitespace( -1 );
  1813. $op = $this->MatchReg('/\\G[-+]\s+/');
  1814. if( $op ){
  1815. $op = $op[0];
  1816. }else{
  1817. if( !$isSpaced ){
  1818. $op = $this->match(array('#+','#-'));
  1819. }
  1820. if( !$op ){
  1821. break;
  1822. }
  1823. }
  1824. $a = $this->parseMultiplication();
  1825. if( !$a ){
  1826. break;
  1827. }
  1828. $m->parensInOp = true;
  1829. $a->parensInOp = true;
  1830. $return = $this->NewObj3('Less_Tree_Operation',array($op, array($return, $a), $isSpaced));
  1831. }
  1832. }
  1833. return $return;
  1834. }
  1835. /**
  1836. * Parses the conditions
  1837. *
  1838. * @return Less_Tree_Condition|null
  1839. */
  1840. private function parseConditions() {
  1841. $index = $this->pos;
  1842. $return = $a = $this->parseCondition();
  1843. if( $a ){
  1844. while( true ){
  1845. if( !$this->PeekReg('/\\G,\s*(not\s*)?\(/') || !$this->MatchChar(',') ){
  1846. break;
  1847. }
  1848. $b = $this->parseCondition();
  1849. if( !$b ){
  1850. break;
  1851. }
  1852. $return = $this->NewObj4('Less_Tree_Condition',array('or', $return, $b, $index));
  1853. }
  1854. return $return;
  1855. }
  1856. }
  1857. private function parseCondition() {
  1858. $index = $this->pos;
  1859. $negate = false;
  1860. $c = null;
  1861. if ($this->MatchReg('/\\Gnot/')) $negate = true;
  1862. $this->expectChar('(');
  1863. $a = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
  1864. if( $a ){
  1865. $op = $this->MatchReg('/\\G(?:>=|<=|=<|[<=>])/');
  1866. if( $op ){
  1867. $b = $this->MatchFuncs(array('parseAddition','parseEntitiesKeyword','parseEntitiesQuoted'));
  1868. if( $b ){
  1869. $c = $this->NewObj5('Less_Tree_Condition',array($op[0], $a, $b, $index, $negate));
  1870. } else {
  1871. $this->Error('Unexpected expression');
  1872. }
  1873. } else {
  1874. $k = $this->NewObj1('Less_Tree_Keyword','true');
  1875. $c = $this->NewObj5('Less_Tree_Condition',array('=', $a, $k, $index, $negate));
  1876. }
  1877. $this->expectChar(')');
  1878. return $this->MatchReg('/\\Gand/') ? $this->NewObj3('Less_Tree_Condition',array('and', $c, $this->parseCondition())) : $c;
  1879. }
  1880. }
  1881. /**
  1882. * An operand is anything that can be part of an operation,
  1883. * such as a Color, or a Variable
  1884. *
  1885. */
  1886. private function parseOperand (){
  1887. $negate = false;
  1888. $offset = $this->pos+1;
  1889. if( $offset >= $this->input_len ){
  1890. return;
  1891. }
  1892. $char = $this->input[$offset];
  1893. if( $char === '@' || $char === '(' ){
  1894. $negate = $this->MatchChar('-');
  1895. }
  1896. $o = $this->MatchFuncs(array('parseSub','parseEntitiesDimension','parseEntitiesColor','parseEntitiesVariable','parseEntitiesCall'));
  1897. if( $negate ){
  1898. $o->parensInOp = true;
  1899. $o = $this->NewObj1('Less_Tree_Negative',$o);
  1900. }
  1901. return $o;
  1902. }
  1903. /**
  1904. * Expressions either represent mathematical operations,
  1905. * or white-space delimited Entities.
  1906. *
  1907. * 1px solid black
  1908. * @var * 2
  1909. *
  1910. * @return Less_Tree_Expression|null
  1911. */
  1912. private function parseExpression (){
  1913. $entities = array();
  1914. do{
  1915. $e = $this->MatchFuncs(array('parseAddition','parseEntity'));
  1916. if( $e ){
  1917. $entities[] = $e;
  1918. // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
  1919. if( !$this->PeekReg('/\\G\/[\/*]/') ){
  1920. $delim = $this->MatchChar('/');
  1921. if( $delim ){
  1922. $entities[] = $this->NewObj1('Less_Tree_Anonymous',$delim);
  1923. }
  1924. }
  1925. }
  1926. }while($e);
  1927. if( $entities ){
  1928. return $this->NewObj1('Less_Tree_Expression',$entities);
  1929. }
  1930. }
  1931. /**
  1932. * Parse a property
  1933. * eg: 'min-width', 'orientation', etc
  1934. *
  1935. * @return string
  1936. */
  1937. private function parseProperty (){
  1938. $name = $this->MatchReg('/\\G(\*?-?[_a-zA-Z0-9-]+)\s*:/');
  1939. if( $name ){
  1940. return $name[1];
  1941. }
  1942. }
  1943. /**
  1944. * Parse a rule property
  1945. * eg: 'color', 'width', 'height', etc
  1946. *
  1947. * @return string
  1948. */
  1949. private function parseRuleProperty(){
  1950. $offset = $this->pos;
  1951. $name = array();
  1952. $index = array();
  1953. $length = 0;
  1954. $this->rulePropertyMatch('/\\G(\*?)/', $offset, $length, $index, $name );
  1955. while( $this->rulePropertyMatch('/\\G((?:[\w-]+)|(?:@\{[\w-]+\}))/', $offset, $length, $index, $name )); // !
  1956. if( (count($name) > 1) && $this->rulePropertyMatch('/\\G\s*((?:\+_|\+)?)\s*:/', $offset, $length, $index, $name) ){
  1957. // at last, we have the complete match now. move forward,
  1958. // convert name particles to tree objects and return:
  1959. $this->skipWhitespace($length);
  1960. if( $name[0] === '' ){
  1961. array_shift($name);
  1962. array_shift($index);
  1963. }
  1964. foreach($name as $k => $s ){
  1965. if( !$s || $s[0] !== '@' ){
  1966. $name[$k] = $this->NewObj1('Less_Tree_Keyword',$s);
  1967. }else{
  1968. $name[$k] = $this->NewObj3('Less_Tree_Variable',array('@' . substr($s,2,-1), $index[$k], $this->env->currentFileInfo));
  1969. }
  1970. }
  1971. return $name;
  1972. }
  1973. }
  1974. private function rulePropertyMatch( $re, &$offset, &$length, &$index, &$name ){
  1975. preg_match($re, $this->input, $a, 0, $offset);
  1976. if( $a ){
  1977. $index[] = $this->pos + $length;
  1978. $length += strlen($a[0]);
  1979. $offset += strlen($a[0]);
  1980. $name[] = $a[1];
  1981. return true;
  1982. }
  1983. }
  1984. public static function serializeVars( $vars ){
  1985. $s = '';
  1986. foreach($vars as $name => $value){
  1987. $s .= (($name[0] === '@') ? '' : '@') . $name .': '. $value . ((substr($value,-1) === ';') ? '' : ';');
  1988. }
  1989. return $s;
  1990. }
  1991. /**
  1992. * Some versions of php have trouble with method_exists($a,$b) if $a is not an object
  1993. *
  1994. * @param string $b
  1995. */
  1996. public static function is_method($a,$b){
  1997. return is_object($a) && method_exists($a,$b);
  1998. }
  1999. /**
  2000. * Round numbers similarly to javascript
  2001. * eg: 1.499999 to 1 instead of 2
  2002. *
  2003. */
  2004. public static function round($i, $precision = 0){
  2005. $precision = pow(10,$precision);
  2006. $i = $i*$precision;
  2007. $ceil = ceil($i);
  2008. $floor = floor($i);
  2009. if( ($ceil - $i) <= ($i - $floor) ){
  2010. return $ceil/$precision;
  2011. }else{
  2012. return $floor/$precision;
  2013. }
  2014. }
  2015. /**
  2016. * Create Less_Tree_* objects and optionally generate a cache string
  2017. *
  2018. * @return mixed
  2019. */
  2020. public function NewObj0($class){
  2021. $obj = new $class();
  2022. if( $this->CacheEnabled() ){
  2023. $obj->cache_string = ' new '.$class.'()';
  2024. }
  2025. return $obj;
  2026. }
  2027. public function NewObj1($class, $arg){
  2028. $obj = new $class( $arg );
  2029. if( $this->CacheEnabled() ){
  2030. $obj->cache_string = ' new '.$class.'('.Less_Parser::ArgString($arg).')';
  2031. }
  2032. return $obj;
  2033. }
  2034. public function NewObj2($class, $args){
  2035. $obj = new $class( $args[0], $args[1] );
  2036. if( $this->CacheEnabled() ){
  2037. $this->ObjCache( $obj, $class, $args);
  2038. }
  2039. return $obj;
  2040. }
  2041. public function NewObj3($class, $args){
  2042. $obj = new $class( $args[0], $args[1], $args[2] );
  2043. if( $this->CacheEnabled() ){
  2044. $this->ObjCache( $obj, $class, $args);
  2045. }
  2046. return $obj;
  2047. }
  2048. public function NewObj4($class, $args){
  2049. $obj = new $class( $args[0], $args[1], $args[2], $args[3] );
  2050. if( $this->CacheEnabled() ){
  2051. $this->ObjCache( $obj, $class, $args);
  2052. }
  2053. return $obj;
  2054. }
  2055. public function NewObj5($class, $args){
  2056. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4] );
  2057. if( $this->CacheEnabled() ){
  2058. $this->ObjCache( $obj, $class, $args);
  2059. }
  2060. return $obj;
  2061. }
  2062. public function NewObj6($class, $args){
  2063. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5] );
  2064. if( $this->CacheEnabled() ){
  2065. $this->ObjCache( $obj, $class, $args);
  2066. }
  2067. return $obj;
  2068. }
  2069. public function NewObj7($class, $args){
  2070. $obj = new $class( $args[0], $args[1], $args[2], $args[3], $args[4], $args[5], $args[6] );
  2071. if( $this->CacheEnabled() ){
  2072. $this->ObjCache( $obj, $class, $args);
  2073. }
  2074. return $obj;
  2075. }
  2076. //caching
  2077. public function ObjCache($obj, $class, $args=array()){
  2078. $obj->cache_string = ' new '.$class.'('. self::ArgCache($args).')';
  2079. }
  2080. public function ArgCache($args){
  2081. return implode(',',array_map( array('Less_Parser','ArgString'),$args));
  2082. }
  2083. /**
  2084. * Convert an argument to a string for use in the parser cache
  2085. *
  2086. * @return string
  2087. */
  2088. public static function ArgString($arg){
  2089. $type = gettype($arg);
  2090. if( $type === 'object'){
  2091. $string = $arg->cache_string;
  2092. unset($arg->cache_string);
  2093. return $string;
  2094. }elseif( $type === 'array' ){
  2095. $string = ' Array(';
  2096. foreach($arg as $k => $a){
  2097. $string .= var_export($k,true).' => '.self::ArgString($a).',';
  2098. }
  2099. return $string . ')';
  2100. }
  2101. return var_export($arg,true);
  2102. }
  2103. public function Error($msg){
  2104. throw new Less_Exception_Parser($msg, null, $this->furthest, $this->env->currentFileInfo);
  2105. }
  2106. public static function WinPath($path){
  2107. return str_replace('\\', '/', $path);
  2108. }
  2109. public function CacheEnabled(){
  2110. return (Less_Parser::$options['cache_method'] && (Less_Cache::$cache_dir || (Less_Parser::$options['cache_method'] == 'callback')));
  2111. }
  2112. }
  2113. /**
  2114. * Utility for css colors
  2115. *
  2116. * @package Less
  2117. * @subpackage color
  2118. */
  2119. class Less_Colors {
  2120. public static $colors = array(
  2121. 'aliceblue'=>'#f0f8ff',
  2122. 'antiquewhite'=>'#faebd7',
  2123. 'aqua'=>'#00ffff',
  2124. 'aquamarine'=>'#7fffd4',
  2125. 'azure'=>'#f0ffff',
  2126. 'beige'=>'#f5f5dc',
  2127. 'bisque'=>'#ffe4c4',
  2128. 'black'=>'#000000',
  2129. 'blanchedalmond'=>'#ffebcd',
  2130. 'blue'=>'#0000ff',
  2131. 'blueviolet'=>'#8a2be2',
  2132. 'brown'=>'#a52a2a',
  2133. 'burlywood'=>'#deb887',
  2134. 'cadetblue'=>'#5f9ea0',
  2135. 'chartreuse'=>'#7fff00',
  2136. 'chocolate'=>'#d2691e',
  2137. 'coral'=>'#ff7f50',
  2138. 'cornflowerblue'=>'#6495ed',
  2139. 'cornsilk'=>'#fff8dc',
  2140. 'crimson'=>'#dc143c',
  2141. 'cyan'=>'#00ffff',
  2142. 'darkblue'=>'#00008b',
  2143. 'darkcyan'=>'#008b8b',
  2144. 'darkgoldenrod'=>'#b8860b',
  2145. 'darkgray'=>'#a9a9a9',
  2146. 'darkgrey'=>'#a9a9a9',
  2147. 'darkgreen'=>'#006400',
  2148. 'darkkhaki'=>'#bdb76b',
  2149. 'darkmagenta'=>'#8b008b',
  2150. 'darkolivegreen'=>'#556b2f',
  2151. 'darkorange'=>'#ff8c00',
  2152. 'darkorchid'=>'#9932cc',
  2153. 'darkred'=>'#8b0000',
  2154. 'darksalmon'=>'#e9967a',
  2155. 'darkseagreen'=>'#8fbc8f',
  2156. 'darkslateblue'=>'#483d8b',
  2157. 'darkslategray'=>'#2f4f4f',
  2158. 'darkslategrey'=>'#2f4f4f',
  2159. 'darkturquoise'=>'#00ced1',
  2160. 'darkviolet'=>'#9400d3',
  2161. 'deeppink'=>'#ff1493',
  2162. 'deepskyblue'=>'#00bfff',
  2163. 'dimgray'=>'#696969',
  2164. 'dimgrey'=>'#696969',
  2165. 'dodgerblue'=>'#1e90ff',
  2166. 'firebrick'=>'#b22222',
  2167. 'floralwhite'=>'#fffaf0',
  2168. 'forestgreen'=>'#228b22',
  2169. 'fuchsia'=>'#ff00ff',
  2170. 'gainsboro'=>'#dcdcdc',
  2171. 'ghostwhite'=>'#f8f8ff',
  2172. 'gold'=>'#ffd700',
  2173. 'goldenrod'=>'#daa520',
  2174. 'gray'=>'#808080',
  2175. 'grey'=>'#808080',
  2176. 'green'=>'#008000',
  2177. 'greenyellow'=>'#adff2f',
  2178. 'honeydew'=>'#f0fff0',
  2179. 'hotpink'=>'#ff69b4',
  2180. 'indianred'=>'#cd5c5c',
  2181. 'indigo'=>'#4b0082',
  2182. 'ivory'=>'#fffff0',
  2183. 'khaki'=>'#f0e68c',
  2184. 'lavender'=>'#e6e6fa',
  2185. 'lavenderblush'=>'#fff0f5',
  2186. 'lawngreen'=>'#7cfc00',
  2187. 'lemonchiffon'=>'#fffacd',
  2188. 'lightblue'=>'#add8e6',
  2189. 'lightcoral'=>'#f08080',
  2190. 'lightcyan'=>'#e0ffff',
  2191. 'lightgoldenrodyellow'=>'#fafad2',
  2192. 'lightgray'=>'#d3d3d3',
  2193. 'lightgrey'=>'#d3d3d3',
  2194. 'lightgreen'=>'#90ee90',
  2195. 'lightpink'=>'#ffb6c1',
  2196. 'lightsalmon'=>'#ffa07a',
  2197. 'lightseagreen'=>'#20b2aa',
  2198. 'lightskyblue'=>'#87cefa',
  2199. 'lightslategray'=>'#778899',
  2200. 'lightslategrey'=>'#778899',
  2201. 'lightsteelblue'=>'#b0c4de',
  2202. 'lightyellow'=>'#ffffe0',
  2203. 'lime'=>'#00ff00',
  2204. 'limegreen'=>'#32cd32',
  2205. 'linen'=>'#faf0e6',
  2206. 'magenta'=>'#ff00ff',
  2207. 'maroon'=>'#800000',
  2208. 'mediumaquamarine'=>'#66cdaa',
  2209. 'mediumblue'=>'#0000cd',
  2210. 'mediumorchid'=>'#ba55d3',
  2211. 'mediumpurple'=>'#9370d8',
  2212. 'mediumseagreen'=>'#3cb371',
  2213. 'mediumslateblue'=>'#7b68ee',
  2214. 'mediumspringgreen'=>'#00fa9a',
  2215. 'mediumturquoise'=>'#48d1cc',
  2216. 'mediumvioletred'=>'#c71585',
  2217. 'midnightblue'=>'#191970',
  2218. 'mintcream'=>'#f5fffa',
  2219. 'mistyrose'=>'#ffe4e1',
  2220. 'moccasin'=>'#ffe4b5',
  2221. 'navajowhite'=>'#ffdead',
  2222. 'navy'=>'#000080',
  2223. 'oldlace'=>'#fdf5e6',
  2224. 'olive'=>'#808000',
  2225. 'olivedrab'=>'#6b8e23',
  2226. 'orange'=>'#ffa500',
  2227. 'orangered'=>'#ff4500',
  2228. 'orchid'=>'#da70d6',
  2229. 'palegoldenrod'=>'#eee8aa',
  2230. 'palegreen'=>'#98fb98',
  2231. 'paleturquoise'=>'#afeeee',
  2232. 'palevioletred'=>'#d87093',
  2233. 'papayawhip'=>'#ffefd5',
  2234. 'peachpuff'=>'#ffdab9',
  2235. 'peru'=>'#cd853f',
  2236. 'pink'=>'#ffc0cb',
  2237. 'plum'=>'#dda0dd',
  2238. 'powderblue'=>'#b0e0e6',
  2239. 'purple'=>'#800080',
  2240. 'red'=>'#ff0000',
  2241. 'rosybrown'=>'#bc8f8f',
  2242. 'royalblue'=>'#4169e1',
  2243. 'saddlebrown'=>'#8b4513',
  2244. 'salmon'=>'#fa8072',
  2245. 'sandybrown'=>'#f4a460',
  2246. 'seagreen'=>'#2e8b57',
  2247. 'seashell'=>'#fff5ee',
  2248. 'sienna'=>'#a0522d',
  2249. 'silver'=>'#c0c0c0',
  2250. 'skyblue'=>'#87ceeb',
  2251. 'slateblue'=>'#6a5acd',
  2252. 'slategray'=>'#708090',
  2253. 'slategrey'=>'#708090',
  2254. 'snow'=>'#fffafa',
  2255. 'springgreen'=>'#00ff7f',
  2256. 'steelblue'=>'#4682b4',
  2257. 'tan'=>'#d2b48c',
  2258. 'teal'=>'#008080',
  2259. 'thistle'=>'#d8bfd8',
  2260. 'tomato'=>'#ff6347',
  2261. 'turquoise'=>'#40e0d0',
  2262. 'violet'=>'#ee82ee',
  2263. 'wheat'=>'#f5deb3',
  2264. 'white'=>'#ffffff',
  2265. 'whitesmoke'=>'#f5f5f5',
  2266. 'yellow'=>'#ffff00',
  2267. 'yellowgreen'=>'#9acd32'
  2268. );
  2269. public static function hasOwnProperty($color) {
  2270. return isset(self::$colors[$color]);
  2271. }
  2272. public static function color($color) {
  2273. return self::$colors[$color];
  2274. }
  2275. }
  2276. /**
  2277. * Environment
  2278. *
  2279. * @package Less
  2280. * @subpackage environment
  2281. */
  2282. class Less_Environment{
  2283. //public $paths = array(); // option - unmodified - paths to search for imports on
  2284. //public static $files = array(); // list of files that have been imported, used for import-once
  2285. //public $rootpath; // option - rootpath to append to URL's
  2286. //public static $strictImports = null; // option -
  2287. //public $insecure; // option - whether to allow imports from insecure ssl hosts
  2288. //public $processImports; // option - whether to process imports. if false then imports will not be imported
  2289. //public $javascriptEnabled; // option - whether JavaScript is enabled. if undefined, defaults to true
  2290. //public $useFileCache; // browser only - whether to use the per file session cache
  2291. public $currentFileInfo; // information about the current file - for error reporting and importing and making urls relative etc.
  2292. public $importMultiple = false; // whether we are currently importing multiple copies
  2293. /**
  2294. * @var array
  2295. */
  2296. public $frames = array();
  2297. /**
  2298. * @var array
  2299. */
  2300. public $mediaBlocks = array();
  2301. /**
  2302. * @var array
  2303. */
  2304. public $mediaPath = array();
  2305. public static $parensStack = 0;
  2306. public static $tabLevel = 0;
  2307. public static $lastRule = false;
  2308. public static $_outputMap;
  2309. public static $mixin_stack = 0;
  2310. /**
  2311. * @var array
  2312. */
  2313. public $functions = array();
  2314. public function Init(){
  2315. self::$parensStack = 0;
  2316. self::$tabLevel = 0;
  2317. self::$lastRule = false;
  2318. self::$mixin_stack = 0;
  2319. if( Less_Parser::$options['compress'] ){
  2320. Less_Environment::$_outputMap = array(
  2321. ',' => ',',
  2322. ': ' => ':',
  2323. '' => '',
  2324. ' ' => ' ',
  2325. ':' => ' :',
  2326. '+' => '+',
  2327. '~' => '~',
  2328. '>' => '>',
  2329. '|' => '|',
  2330. '^' => '^',
  2331. '^^' => '^^'
  2332. );
  2333. }else{
  2334. Less_Environment::$_outputMap = array(
  2335. ',' => ', ',
  2336. ': ' => ': ',
  2337. '' => '',
  2338. ' ' => ' ',
  2339. ':' => ' :',
  2340. '+' => ' + ',
  2341. '~' => ' ~ ',
  2342. '>' => ' > ',
  2343. '|' => '|',
  2344. '^' => ' ^ ',
  2345. '^^' => ' ^^ '
  2346. );
  2347. }
  2348. }
  2349. public function copyEvalEnv($frames = array() ){
  2350. $new_env = new Less_Environment();
  2351. $new_env->frames = $frames;
  2352. return $new_env;
  2353. }
  2354. public static function isMathOn(){
  2355. return !Less_Parser::$options['strictMath'] || Less_Environment::$parensStack;
  2356. }
  2357. public static function isPathRelative($path){
  2358. return !preg_match('/^(?:[a-z-]+:|\/)/',$path);
  2359. }
  2360. /**
  2361. * Canonicalize a path by resolving references to '/./', '/../'
  2362. * Does not remove leading "../"
  2363. * @param string path or url
  2364. * @return string Canonicalized path
  2365. *
  2366. */
  2367. public static function normalizePath($path){
  2368. $segments = explode('/',$path);
  2369. $segments = array_reverse($segments);
  2370. $path = array();
  2371. $path_len = 0;
  2372. while( $segments ){
  2373. $segment = array_pop($segments);
  2374. switch( $segment ) {
  2375. case '.':
  2376. break;
  2377. case '..':
  2378. if( !$path_len || ( $path[$path_len-1] === '..') ){
  2379. $path[] = $segment;
  2380. $path_len++;
  2381. }else{
  2382. array_pop($path);
  2383. $path_len--;
  2384. }
  2385. break;
  2386. default:
  2387. $path[] = $segment;
  2388. $path_len++;
  2389. break;
  2390. }
  2391. }
  2392. return implode('/',$path);
  2393. }
  2394. public function unshiftFrame($frame){
  2395. array_unshift($this->frames, $frame);
  2396. }
  2397. public function shiftFrame(){
  2398. return array_shift($this->frames);
  2399. }
  2400. }
  2401. /**
  2402. * Builtin functions
  2403. *
  2404. * @package Less
  2405. * @subpackage function
  2406. * @see http://lesscss.org/functions/
  2407. */
  2408. class Less_Functions{
  2409. public $env;
  2410. public $currentFileInfo;
  2411. function __construct($env, $currentFileInfo = null ){
  2412. $this->env = $env;
  2413. $this->currentFileInfo = $currentFileInfo;
  2414. }
  2415. /**
  2416. * @param string $op
  2417. */
  2418. public static function operate( $op, $a, $b ){
  2419. switch ($op) {
  2420. case '+': return $a + $b;
  2421. case '-': return $a - $b;
  2422. case '*': return $a * $b;
  2423. case '/': return $a / $b;
  2424. }
  2425. }
  2426. public static function clamp($val, $max = 1){
  2427. return min( max($val, 0), $max);
  2428. }
  2429. public static function fround( $value ){
  2430. if( $value === 0 ){
  2431. return $value;
  2432. }
  2433. if( Less_Parser::$options['numPrecision'] ){
  2434. $p = pow(10, Less_Parser::$options['numPrecision']);
  2435. return round( $value * $p) / $p;
  2436. }
  2437. return $value;
  2438. }
  2439. public static function number($n){
  2440. if ($n instanceof Less_Tree_Dimension) {
  2441. return floatval( $n->unit->is('%') ? $n->value / 100 : $n->value);
  2442. } else if (is_numeric($n)) {
  2443. return $n;
  2444. } else {
  2445. throw new Less_Exception_Compiler("color functions take numbers as parameters");
  2446. }
  2447. }
  2448. public static function scaled($n, $size = 255 ){
  2449. if( $n instanceof Less_Tree_Dimension && $n->unit->is('%') ){
  2450. return (float)$n->value * $size / 100;
  2451. } else {
  2452. return Less_Functions::number($n);
  2453. }
  2454. }
  2455. public function rgb ($r = null, $g = null, $b = null){
  2456. if (is_null($r) || is_null($g) || is_null($b)) {
  2457. throw new Less_Exception_Compiler("rgb expects three parameters");
  2458. }
  2459. return $this->rgba($r, $g, $b, 1.0);
  2460. }
  2461. public function rgba($r = null, $g = null, $b = null, $a = null){
  2462. $rgb = array($r, $g, $b);
  2463. $rgb = array_map(array('Less_Functions','scaled'),$rgb);
  2464. $a = self::number($a);
  2465. return new Less_Tree_Color($rgb, $a);
  2466. }
  2467. public function hsl($h, $s, $l){
  2468. return $this->hsla($h, $s, $l, 1.0);
  2469. }
  2470. public function hsla($h, $s, $l, $a){
  2471. $h = fmod(self::number($h), 360) / 360; // Classic % operator will change float to int
  2472. $s = self::clamp(self::number($s));
  2473. $l = self::clamp(self::number($l));
  2474. $a = self::clamp(self::number($a));
  2475. $m2 = $l <= 0.5 ? $l * ($s + 1) : $l + $s - $l * $s;
  2476. $m1 = $l * 2 - $m2;
  2477. return $this->rgba( self::hsla_hue($h + 1/3, $m1, $m2) * 255,
  2478. self::hsla_hue($h, $m1, $m2) * 255,
  2479. self::hsla_hue($h - 1/3, $m1, $m2) * 255,
  2480. $a);
  2481. }
  2482. /**
  2483. * @param double $h
  2484. */
  2485. public function hsla_hue($h, $m1, $m2){
  2486. $h = $h < 0 ? $h + 1 : ($h > 1 ? $h - 1 : $h);
  2487. if ($h * 6 < 1) return $m1 + ($m2 - $m1) * $h * 6;
  2488. else if ($h * 2 < 1) return $m2;
  2489. else if ($h * 3 < 2) return $m1 + ($m2 - $m1) * (2/3 - $h) * 6;
  2490. else return $m1;
  2491. }
  2492. public function hsv($h, $s, $v) {
  2493. return $this->hsva($h, $s, $v, 1.0);
  2494. }
  2495. /**
  2496. * @param double $a
  2497. */
  2498. public function hsva($h, $s, $v, $a) {
  2499. $h = ((Less_Functions::number($h) % 360) / 360 ) * 360;
  2500. $s = Less_Functions::number($s);
  2501. $v = Less_Functions::number($v);
  2502. $a = Less_Functions::number($a);
  2503. $i = floor(($h / 60) % 6);
  2504. $f = ($h / 60) - $i;
  2505. $vs = array( $v,
  2506. $v * (1 - $s),
  2507. $v * (1 - $f * $s),
  2508. $v * (1 - (1 - $f) * $s));
  2509. $perm = array(array(0, 3, 1),
  2510. array(2, 0, 1),
  2511. array(1, 0, 3),
  2512. array(1, 2, 0),
  2513. array(3, 1, 0),
  2514. array(0, 1, 2));
  2515. return $this->rgba($vs[$perm[$i][0]] * 255,
  2516. $vs[$perm[$i][1]] * 255,
  2517. $vs[$perm[$i][2]] * 255,
  2518. $a);
  2519. }
  2520. public function hue($color = null){
  2521. if (!$color instanceof Less_Tree_Color) {
  2522. throw new Less_Exception_Compiler('The first argument to hue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2523. }
  2524. $c = $color->toHSL();
  2525. return new Less_Tree_Dimension(Less_Parser::round($c['h']));
  2526. }
  2527. public function saturation($color = null){
  2528. if (!$color instanceof Less_Tree_Color) {
  2529. throw new Less_Exception_Compiler('The first argument to saturation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2530. }
  2531. $c = $color->toHSL();
  2532. return new Less_Tree_Dimension(Less_Parser::round($c['s'] * 100), '%');
  2533. }
  2534. public function lightness($color = null){
  2535. if (!$color instanceof Less_Tree_Color) {
  2536. throw new Less_Exception_Compiler('The first argument to lightness must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2537. }
  2538. $c = $color->toHSL();
  2539. return new Less_Tree_Dimension(Less_Parser::round($c['l'] * 100), '%');
  2540. }
  2541. public function hsvhue( $color = null ){
  2542. if (!$color instanceof Less_Tree_Color) {
  2543. throw new Less_Exception_Compiler('The first argument to hsvhue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2544. }
  2545. $hsv = $color->toHSV();
  2546. return new Less_Tree_Dimension( Less_Parser::round($hsv['h']) );
  2547. }
  2548. public function hsvsaturation( $color = null ){
  2549. if (!$color instanceof Less_Tree_Color) {
  2550. throw new Less_Exception_Compiler('The first argument to hsvsaturation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2551. }
  2552. $hsv = $color->toHSV();
  2553. return new Less_Tree_Dimension( Less_Parser::round($hsv['s'] * 100), '%' );
  2554. }
  2555. public function hsvvalue( $color = null ){
  2556. if (!$color instanceof Less_Tree_Color) {
  2557. throw new Less_Exception_Compiler('The first argument to hsvvalue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2558. }
  2559. $hsv = $color->toHSV();
  2560. return new Less_Tree_Dimension( Less_Parser::round($hsv['v'] * 100), '%' );
  2561. }
  2562. public function red($color = null) {
  2563. if (!$color instanceof Less_Tree_Color) {
  2564. throw new Less_Exception_Compiler('The first argument to red must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2565. }
  2566. return new Less_Tree_Dimension( $color->rgb[0] );
  2567. }
  2568. public function green($color = null) {
  2569. if (!$color instanceof Less_Tree_Color) {
  2570. throw new Less_Exception_Compiler('The first argument to green must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2571. }
  2572. return new Less_Tree_Dimension( $color->rgb[1] );
  2573. }
  2574. public function blue($color = null) {
  2575. if (!$color instanceof Less_Tree_Color) {
  2576. throw new Less_Exception_Compiler('The first argument to blue must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2577. }
  2578. return new Less_Tree_Dimension( $color->rgb[2] );
  2579. }
  2580. public function alpha($color = null){
  2581. if (!$color instanceof Less_Tree_Color) {
  2582. throw new Less_Exception_Compiler('The first argument to alpha must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2583. }
  2584. $c = $color->toHSL();
  2585. return new Less_Tree_Dimension($c['a']);
  2586. }
  2587. public function luma ($color = null) {
  2588. if (!$color instanceof Less_Tree_Color) {
  2589. throw new Less_Exception_Compiler('The first argument to luma must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2590. }
  2591. return new Less_Tree_Dimension(Less_Parser::round( $color->luma() * $color->alpha * 100), '%');
  2592. }
  2593. public function luminance( $color = null ){
  2594. if (!$color instanceof Less_Tree_Color) {
  2595. throw new Less_Exception_Compiler('The first argument to luminance must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2596. }
  2597. $luminance =
  2598. (0.2126 * $color->rgb[0] / 255)
  2599. + (0.7152 * $color->rgb[1] / 255)
  2600. + (0.0722 * $color->rgb[2] / 255);
  2601. return new Less_Tree_Dimension(Less_Parser::round( $luminance * $color->alpha * 100), '%');
  2602. }
  2603. public function saturate($color = null, $amount = null){
  2604. // filter: saturate(3.2);
  2605. // should be kept as is, so check for color
  2606. if ($color instanceof Less_Tree_Dimension) {
  2607. return null;
  2608. }
  2609. if (!$color instanceof Less_Tree_Color) {
  2610. throw new Less_Exception_Compiler('The first argument to saturate must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2611. }
  2612. if (!$amount instanceof Less_Tree_Dimension) {
  2613. throw new Less_Exception_Compiler('The second argument to saturate must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2614. }
  2615. $hsl = $color->toHSL();
  2616. $hsl['s'] += $amount->value / 100;
  2617. $hsl['s'] = self::clamp($hsl['s']);
  2618. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2619. }
  2620. /**
  2621. * @param Less_Tree_Dimension $amount
  2622. */
  2623. public function desaturate($color = null, $amount = null){
  2624. if (!$color instanceof Less_Tree_Color) {
  2625. throw new Less_Exception_Compiler('The first argument to desaturate must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2626. }
  2627. if (!$amount instanceof Less_Tree_Dimension) {
  2628. throw new Less_Exception_Compiler('The second argument to desaturate must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2629. }
  2630. $hsl = $color->toHSL();
  2631. $hsl['s'] -= $amount->value / 100;
  2632. $hsl['s'] = self::clamp($hsl['s']);
  2633. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2634. }
  2635. public function lighten($color = null, $amount=null){
  2636. if (!$color instanceof Less_Tree_Color) {
  2637. throw new Less_Exception_Compiler('The first argument to lighten must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2638. }
  2639. if (!$amount instanceof Less_Tree_Dimension) {
  2640. throw new Less_Exception_Compiler('The second argument to lighten must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2641. }
  2642. $hsl = $color->toHSL();
  2643. $hsl['l'] += $amount->value / 100;
  2644. $hsl['l'] = self::clamp($hsl['l']);
  2645. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2646. }
  2647. public function darken($color = null, $amount = null){
  2648. if (!$color instanceof Less_Tree_Color) {
  2649. throw new Less_Exception_Compiler('The first argument to darken must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2650. }
  2651. if (!$amount instanceof Less_Tree_Dimension) {
  2652. throw new Less_Exception_Compiler('The second argument to darken must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2653. }
  2654. $hsl = $color->toHSL();
  2655. $hsl['l'] -= $amount->value / 100;
  2656. $hsl['l'] = self::clamp($hsl['l']);
  2657. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2658. }
  2659. public function fadein($color = null, $amount = null){
  2660. if (!$color instanceof Less_Tree_Color) {
  2661. throw new Less_Exception_Compiler('The first argument to fadein must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2662. }
  2663. if (!$amount instanceof Less_Tree_Dimension) {
  2664. throw new Less_Exception_Compiler('The second argument to fadein must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2665. }
  2666. $hsl = $color->toHSL();
  2667. $hsl['a'] += $amount->value / 100;
  2668. $hsl['a'] = self::clamp($hsl['a']);
  2669. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2670. }
  2671. public function fadeout($color = null, $amount = null){
  2672. if (!$color instanceof Less_Tree_Color) {
  2673. throw new Less_Exception_Compiler('The first argument to fadeout must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2674. }
  2675. if (!$amount instanceof Less_Tree_Dimension) {
  2676. throw new Less_Exception_Compiler('The second argument to fadeout must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2677. }
  2678. $hsl = $color->toHSL();
  2679. $hsl['a'] -= $amount->value / 100;
  2680. $hsl['a'] = self::clamp($hsl['a']);
  2681. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2682. }
  2683. public function fade($color = null, $amount = null){
  2684. if (!$color instanceof Less_Tree_Color) {
  2685. throw new Less_Exception_Compiler('The first argument to fade must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2686. }
  2687. if (!$amount instanceof Less_Tree_Dimension) {
  2688. throw new Less_Exception_Compiler('The second argument to fade must be a percentage' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2689. }
  2690. $hsl = $color->toHSL();
  2691. $hsl['a'] = $amount->value / 100;
  2692. $hsl['a'] = self::clamp($hsl['a']);
  2693. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2694. }
  2695. public function spin($color = null, $amount = null){
  2696. if (!$color instanceof Less_Tree_Color) {
  2697. throw new Less_Exception_Compiler('The first argument to spin must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2698. }
  2699. if (!$amount instanceof Less_Tree_Dimension) {
  2700. throw new Less_Exception_Compiler('The second argument to spin must be a number' . ($amount instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2701. }
  2702. $hsl = $color->toHSL();
  2703. $hue = fmod($hsl['h'] + $amount->value, 360);
  2704. $hsl['h'] = $hue < 0 ? 360 + $hue : $hue;
  2705. return $this->hsla($hsl['h'], $hsl['s'], $hsl['l'], $hsl['a']);
  2706. }
  2707. //
  2708. // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
  2709. // http://sass-lang.com
  2710. //
  2711. /**
  2712. * @param Less_Tree_Color $color1
  2713. */
  2714. public function mix($color1 = null, $color2 = null, $weight = null){
  2715. if (!$color1 instanceof Less_Tree_Color) {
  2716. throw new Less_Exception_Compiler('The first argument to mix must be a color' . ($color1 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2717. }
  2718. if (!$color2 instanceof Less_Tree_Color) {
  2719. throw new Less_Exception_Compiler('The second argument to mix must be a color' . ($color2 instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2720. }
  2721. if (!$weight) {
  2722. $weight = new Less_Tree_Dimension('50', '%');
  2723. }
  2724. if (!$weight instanceof Less_Tree_Dimension) {
  2725. throw new Less_Exception_Compiler('The third argument to contrast must be a percentage' . ($weight instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2726. }
  2727. $p = $weight->value / 100.0;
  2728. $w = $p * 2 - 1;
  2729. $hsl1 = $color1->toHSL();
  2730. $hsl2 = $color2->toHSL();
  2731. $a = $hsl1['a'] - $hsl2['a'];
  2732. $w1 = (((($w * $a) == -1) ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2;
  2733. $w2 = 1 - $w1;
  2734. $rgb = array($color1->rgb[0] * $w1 + $color2->rgb[0] * $w2,
  2735. $color1->rgb[1] * $w1 + $color2->rgb[1] * $w2,
  2736. $color1->rgb[2] * $w1 + $color2->rgb[2] * $w2);
  2737. $alpha = $color1->alpha * $p + $color2->alpha * (1 - $p);
  2738. return new Less_Tree_Color($rgb, $alpha);
  2739. }
  2740. public function greyscale($color){
  2741. return $this->desaturate($color, new Less_Tree_Dimension(100,'%'));
  2742. }
  2743. public function contrast( $color, $dark = null, $light = null, $threshold = null){
  2744. // filter: contrast(3.2);
  2745. // should be kept as is, so check for color
  2746. if (!$color instanceof Less_Tree_Color) {
  2747. return null;
  2748. }
  2749. if( !$light ){
  2750. $light = $this->rgba(255, 255, 255, 1.0);
  2751. }
  2752. if( !$dark ){
  2753. $dark = $this->rgba(0, 0, 0, 1.0);
  2754. }
  2755. if (!$dark instanceof Less_Tree_Color) {
  2756. throw new Less_Exception_Compiler('The second argument to contrast must be a color' . ($dark instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2757. }
  2758. if (!$light instanceof Less_Tree_Color) {
  2759. throw new Less_Exception_Compiler('The third argument to contrast must be a color' . ($light instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2760. }
  2761. //Figure out which is actually light and dark!
  2762. if( $dark->luma() > $light->luma() ){
  2763. $t = $light;
  2764. $light = $dark;
  2765. $dark = $t;
  2766. }
  2767. if( !$threshold ){
  2768. $threshold = 0.43;
  2769. } else {
  2770. $threshold = Less_Functions::number($threshold);
  2771. }
  2772. if( $color->luma() < $threshold ){
  2773. return $light;
  2774. } else {
  2775. return $dark;
  2776. }
  2777. }
  2778. public function e ($str){
  2779. if( is_string($str) ){
  2780. return new Less_Tree_Anonymous($str);
  2781. }
  2782. return new Less_Tree_Anonymous($str instanceof Less_Tree_JavaScript ? $str->expression : $str->value);
  2783. }
  2784. public function escape ($str){
  2785. $revert = array('%21'=>'!', '%2A'=>'*', '%27'=>"'",'%3F'=>'?','%26'=>'&','%2C'=>',','%2F'=>'/','%40'=>'@','%2B'=>'+','%24'=>'$');
  2786. return new Less_Tree_Anonymous(strtr(rawurlencode($str->value), $revert));
  2787. }
  2788. /**
  2789. * todo: This function will need some additional work to make it work the same as less.js
  2790. *
  2791. */
  2792. public function replace( $string, $pattern, $replacement, $flags = null ){
  2793. $result = $string->value;
  2794. $expr = '/'.str_replace('/','\\/',$pattern->value).'/';
  2795. if( $flags && $flags->value){
  2796. $expr .= self::replace_flags($flags->value);
  2797. }
  2798. $result = preg_replace($expr,$replacement->value,$result);
  2799. if( property_exists($string,'quote') ){
  2800. return new Less_Tree_Quoted( $string->quote, $result, $string->escaped);
  2801. }
  2802. return new Less_Tree_Quoted( '', $result );
  2803. }
  2804. public static function replace_flags($flags){
  2805. $flags = str_split($flags,1);
  2806. $new_flags = '';
  2807. foreach($flags as $flag){
  2808. switch($flag){
  2809. case 'e':
  2810. case 'g':
  2811. break;
  2812. default:
  2813. $new_flags .= $flag;
  2814. break;
  2815. }
  2816. }
  2817. return $new_flags;
  2818. }
  2819. public function _percent(){
  2820. $string = func_get_arg(0);
  2821. $args = func_get_args();
  2822. array_shift($args);
  2823. $result = $string->value;
  2824. foreach($args as $arg){
  2825. if( preg_match('/%[sda]/i',$result, $token) ){
  2826. $token = $token[0];
  2827. $value = stristr($token, 's') ? $arg->value : $arg->toCSS();
  2828. $value = preg_match('/[A-Z]$/', $token) ? urlencode($value) : $value;
  2829. $result = preg_replace('/%[sda]/i',$value, $result, 1);
  2830. }
  2831. }
  2832. $result = str_replace('%%', '%', $result);
  2833. return new Less_Tree_Quoted( $string->quote , $result, $string->escaped);
  2834. }
  2835. public function unit( $val, $unit = null) {
  2836. if( !($val instanceof Less_Tree_Dimension) ){
  2837. throw new Less_Exception_Compiler('The first argument to unit must be a number' . ($val instanceof Less_Tree_Operation ? '. Have you forgotten parenthesis?' : '.') );
  2838. }
  2839. if( $unit ){
  2840. if( $unit instanceof Less_Tree_Keyword ){
  2841. $unit = $unit->value;
  2842. } else {
  2843. $unit = $unit->toCSS();
  2844. }
  2845. } else {
  2846. $unit = "";
  2847. }
  2848. return new Less_Tree_Dimension($val->value, $unit );
  2849. }
  2850. public function convert($val, $unit){
  2851. return $val->convertTo($unit->value);
  2852. }
  2853. public function round($n, $f = false) {
  2854. $fraction = 0;
  2855. if( $f !== false ){
  2856. $fraction = $f->value;
  2857. }
  2858. return $this->_math('Less_Parser::round',null, $n, $fraction);
  2859. }
  2860. public function pi(){
  2861. return new Less_Tree_Dimension(M_PI);
  2862. }
  2863. public function mod($a, $b) {
  2864. return new Less_Tree_Dimension( $a->value % $b->value, $a->unit);
  2865. }
  2866. public function pow($x, $y) {
  2867. if( is_numeric($x) && is_numeric($y) ){
  2868. $x = new Less_Tree_Dimension($x);
  2869. $y = new Less_Tree_Dimension($y);
  2870. }elseif( !($x instanceof Less_Tree_Dimension) || !($y instanceof Less_Tree_Dimension) ){
  2871. throw new Less_Exception_Compiler('Arguments must be numbers');
  2872. }
  2873. return new Less_Tree_Dimension( pow($x->value, $y->value), $x->unit );
  2874. }
  2875. // var mathFunctions = [{name:"ce ...
  2876. public function ceil( $n ){ return $this->_math('ceil', null, $n); }
  2877. public function floor( $n ){ return $this->_math('floor', null, $n); }
  2878. public function sqrt( $n ){ return $this->_math('sqrt', null, $n); }
  2879. public function abs( $n ){ return $this->_math('abs', null, $n); }
  2880. public function tan( $n ){ return $this->_math('tan', '', $n); }
  2881. public function sin( $n ){ return $this->_math('sin', '', $n); }
  2882. public function cos( $n ){ return $this->_math('cos', '', $n); }
  2883. public function atan( $n ){ return $this->_math('atan', 'rad', $n); }
  2884. public function asin( $n ){ return $this->_math('asin', 'rad', $n); }
  2885. public function acos( $n ){ return $this->_math('acos', 'rad', $n); }
  2886. private function _math() {
  2887. $args = func_get_args();
  2888. $fn = array_shift($args);
  2889. $unit = array_shift($args);
  2890. if ($args[0] instanceof Less_Tree_Dimension) {
  2891. if( $unit === null ){
  2892. $unit = $args[0]->unit;
  2893. }else{
  2894. $args[0] = $args[0]->unify();
  2895. }
  2896. $args[0] = (float)$args[0]->value;
  2897. return new Less_Tree_Dimension( call_user_func_array($fn, $args), $unit);
  2898. } else if (is_numeric($args[0])) {
  2899. return call_user_func_array($fn,$args);
  2900. } else {
  2901. throw new Less_Exception_Compiler("math functions take numbers as parameters");
  2902. }
  2903. }
  2904. /**
  2905. * @param boolean $isMin
  2906. */
  2907. private function _minmax( $isMin, $args ){
  2908. $arg_count = count($args);
  2909. if( $arg_count < 1 ){
  2910. throw new Less_Exception_Compiler( 'one or more arguments required');
  2911. }
  2912. $j = null;
  2913. $unitClone = null;
  2914. $unitStatic = null;
  2915. $order = array(); // elems only contains original argument values.
  2916. $values = array(); // key is the unit.toString() for unified tree.Dimension values,
  2917. // value is the index into the order array.
  2918. for( $i = 0; $i < $arg_count; $i++ ){
  2919. $current = $args[$i];
  2920. if( !($current instanceof Less_Tree_Dimension) ){
  2921. if( is_array($args[$i]->value) ){
  2922. $args[] = $args[$i]->value;
  2923. }
  2924. continue;
  2925. }
  2926. if( $current->unit->toString() === '' && !$unitClone ){
  2927. $temp = new Less_Tree_Dimension($current->value, $unitClone);
  2928. $currentUnified = $temp->unify();
  2929. }else{
  2930. $currentUnified = $current->unify();
  2931. }
  2932. if( $currentUnified->unit->toString() === "" && !$unitStatic ){
  2933. $unit = $unitStatic;
  2934. }else{
  2935. $unit = $currentUnified->unit->toString();
  2936. }
  2937. if( $unit !== '' && !$unitStatic || $unit !== '' && $order[0]->unify()->unit->toString() === "" ){
  2938. $unitStatic = $unit;
  2939. }
  2940. if( $unit != '' && !$unitClone ){
  2941. $unitClone = $current->unit->toString();
  2942. }
  2943. if( isset($values['']) && $unit !== '' && $unit === $unitStatic ){
  2944. $j = $values[''];
  2945. }elseif( isset($values[$unit]) ){
  2946. $j = $values[$unit];
  2947. }else{
  2948. if( $unitStatic && $unit !== $unitStatic ){
  2949. throw new Less_Exception_Compiler( 'incompatible types');
  2950. }
  2951. $values[$unit] = count($order);
  2952. $order[] = $current;
  2953. continue;
  2954. }
  2955. if( $order[$j]->unit->toString() === "" && $unitClone ){
  2956. $temp = new Less_Tree_Dimension( $order[$j]->value, $unitClone);
  2957. $referenceUnified = $temp->unify();
  2958. }else{
  2959. $referenceUnified = $order[$j]->unify();
  2960. }
  2961. if( ($isMin && $currentUnified->value < $referenceUnified->value) || (!$isMin && $currentUnified->value > $referenceUnified->value) ){
  2962. $order[$j] = $current;
  2963. }
  2964. }
  2965. if( count($order) == 1 ){
  2966. return $order[0];
  2967. }
  2968. $args = array();
  2969. foreach($order as $a){
  2970. $args[] = $a->toCSS($this->env);
  2971. }
  2972. return new Less_Tree_Anonymous( ($isMin?'min(':'max(') . implode(Less_Environment::$_outputMap[','],$args).')');
  2973. }
  2974. public function min(){
  2975. $args = func_get_args();
  2976. return $this->_minmax( true, $args );
  2977. }
  2978. public function max(){
  2979. $args = func_get_args();
  2980. return $this->_minmax( false, $args );
  2981. }
  2982. public function getunit($n){
  2983. return new Less_Tree_Anonymous($n->unit);
  2984. }
  2985. public function argb($color) {
  2986. if (!$color instanceof Less_Tree_Color) {
  2987. throw new Less_Exception_Compiler('The first argument to argb must be a color' . ($dark instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  2988. }
  2989. return new Less_Tree_Anonymous($color->toARGB());
  2990. }
  2991. public function percentage($n) {
  2992. return new Less_Tree_Dimension($n->value * 100, '%');
  2993. }
  2994. public function color($n) {
  2995. if( $n instanceof Less_Tree_Quoted ){
  2996. $colorCandidate = $n->value;
  2997. $returnColor = Less_Tree_Color::fromKeyword($colorCandidate);
  2998. if( $returnColor ){
  2999. return $returnColor;
  3000. }
  3001. if( preg_match('/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/',$colorCandidate) ){
  3002. return new Less_Tree_Color(substr($colorCandidate, 1));
  3003. }
  3004. throw new Less_Exception_Compiler("argument must be a color keyword or 3/6 digit hex e.g. #FFF");
  3005. } else {
  3006. throw new Less_Exception_Compiler("argument must be a string");
  3007. }
  3008. }
  3009. public function iscolor($n) {
  3010. return $this->_isa($n, 'Less_Tree_Color');
  3011. }
  3012. public function isnumber($n) {
  3013. return $this->_isa($n, 'Less_Tree_Dimension');
  3014. }
  3015. public function isstring($n) {
  3016. return $this->_isa($n, 'Less_Tree_Quoted');
  3017. }
  3018. public function iskeyword($n) {
  3019. return $this->_isa($n, 'Less_Tree_Keyword');
  3020. }
  3021. public function isurl($n) {
  3022. return $this->_isa($n, 'Less_Tree_Url');
  3023. }
  3024. public function ispixel($n) {
  3025. return $this->isunit($n, 'px');
  3026. }
  3027. public function ispercentage($n) {
  3028. return $this->isunit($n, '%');
  3029. }
  3030. public function isem($n) {
  3031. return $this->isunit($n, 'em');
  3032. }
  3033. /**
  3034. * @param string $unit
  3035. */
  3036. public function isunit( $n, $unit ){
  3037. return ($n instanceof Less_Tree_Dimension) && $n->unit->is( ( property_exists($unit,'value') ? $unit->value : $unit) ) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  3038. }
  3039. /**
  3040. * @param string $type
  3041. */
  3042. private function _isa($n, $type) {
  3043. return is_a($n, $type) ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  3044. }
  3045. public function tint($color, $amount) {
  3046. return $this->mix( $this->rgb(255,255,255), $color, $amount);
  3047. }
  3048. public function shade($color, $amount) {
  3049. return $this->mix($this->rgb(0, 0, 0), $color, $amount);
  3050. }
  3051. public function extract($values, $index ){
  3052. $index = (int)$index->value - 1; // (1-based index)
  3053. // handle non-array values as an array of length 1
  3054. // return 'undefined' if index is invalid
  3055. if( property_exists($values,'value') && is_array($values->value) ){
  3056. if( isset($values->value[$index]) ){
  3057. return $values->value[$index];
  3058. }
  3059. return null;
  3060. }elseif( (int)$index === 0 ){
  3061. return $values;
  3062. }
  3063. return null;
  3064. }
  3065. public function length($values){
  3066. $n = (property_exists($values,'value') && is_array($values->value)) ? count($values->value) : 1;
  3067. return new Less_Tree_Dimension($n);
  3068. }
  3069. public function datauri($mimetypeNode, $filePathNode = null ) {
  3070. $filePath = ( $filePathNode ? $filePathNode->value : null );
  3071. $mimetype = $mimetypeNode->value;
  3072. $args = 2;
  3073. if( !$filePath ){
  3074. $filePath = $mimetype;
  3075. $args = 1;
  3076. }
  3077. $filePath = str_replace('\\','/',$filePath);
  3078. if( Less_Environment::isPathRelative($filePath) ){
  3079. if( Less_Parser::$options['relativeUrls'] ){
  3080. $temp = $this->currentFileInfo['currentDirectory'];
  3081. } else {
  3082. $temp = $this->currentFileInfo['entryPath'];
  3083. }
  3084. if( !empty($temp) ){
  3085. $filePath = Less_Environment::normalizePath(rtrim($temp,'/').'/'.$filePath);
  3086. }
  3087. }
  3088. // detect the mimetype if not given
  3089. if( $args < 2 ){
  3090. /* incomplete
  3091. $mime = require('mime');
  3092. mimetype = mime.lookup(path);
  3093. // use base 64 unless it's an ASCII or UTF-8 format
  3094. var charset = mime.charsets.lookup(mimetype);
  3095. useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
  3096. if (useBase64) mimetype += ';base64';
  3097. */
  3098. $mimetype = Less_Mime::lookup($filePath);
  3099. $charset = Less_Mime::charsets_lookup($mimetype);
  3100. $useBase64 = !in_array($charset,array('US-ASCII', 'UTF-8'));
  3101. if( $useBase64 ){ $mimetype .= ';base64'; }
  3102. }else{
  3103. $useBase64 = preg_match('/;base64$/',$mimetype);
  3104. }
  3105. if( file_exists($filePath) ){
  3106. $buf = @file_get_contents($filePath);
  3107. }else{
  3108. $buf = false;
  3109. }
  3110. // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded
  3111. // and the --ieCompat flag is enabled, return a normal url() instead.
  3112. $DATA_URI_MAX_KB = 32;
  3113. $fileSizeInKB = round( strlen($buf) / 1024 );
  3114. if( $fileSizeInKB >= $DATA_URI_MAX_KB ){
  3115. $url = new Less_Tree_Url( ($filePathNode ? $filePathNode : $mimetypeNode), $this->currentFileInfo);
  3116. return $url->compile($this);
  3117. }
  3118. if( $buf ){
  3119. $buf = $useBase64 ? base64_encode($buf) : rawurlencode($buf);
  3120. $filePath = '"data:' . $mimetype . ',' . $buf . '"';
  3121. }
  3122. return new Less_Tree_Url( new Less_Tree_Anonymous($filePath) );
  3123. }
  3124. //svg-gradient
  3125. public function svggradient( $direction ){
  3126. $throw_message = 'svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]';
  3127. $arguments = func_get_args();
  3128. if( count($arguments) < 3 ){
  3129. throw new Less_Exception_Compiler( $throw_message );
  3130. }
  3131. $stops = array_slice($arguments,1);
  3132. $gradientType = 'linear';
  3133. $rectangleDimension = 'x="0" y="0" width="1" height="1"';
  3134. $useBase64 = true;
  3135. $directionValue = $direction->toCSS();
  3136. switch( $directionValue ){
  3137. case "to bottom":
  3138. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
  3139. break;
  3140. case "to right":
  3141. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
  3142. break;
  3143. case "to bottom right":
  3144. $gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
  3145. break;
  3146. case "to top right":
  3147. $gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
  3148. break;
  3149. case "ellipse":
  3150. case "ellipse at center":
  3151. $gradientType = "radial";
  3152. $gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
  3153. $rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
  3154. break;
  3155. default:
  3156. throw new Less_Exception_Compiler( "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" );
  3157. }
  3158. $returner = '<?xml version="1.0" ?>' .
  3159. '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' .
  3160. '<' . $gradientType . 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' . $gradientDirectionSvg . '>';
  3161. for( $i = 0; $i < count($stops); $i++ ){
  3162. if( is_object($stops[$i]) && property_exists($stops[$i],'value') ){
  3163. $color = $stops[$i]->value[0];
  3164. $position = $stops[$i]->value[1];
  3165. }else{
  3166. $color = $stops[$i];
  3167. $position = null;
  3168. }
  3169. if( !($color instanceof Less_Tree_Color) || (!(($i === 0 || $i+1 === count($stops)) && $position === null) && !($position instanceof Less_Tree_Dimension)) ){
  3170. throw new Less_Exception_Compiler( $throw_message );
  3171. }
  3172. if( $position ){
  3173. $positionValue = $position->toCSS();
  3174. }elseif( $i === 0 ){
  3175. $positionValue = '0%';
  3176. }else{
  3177. $positionValue = '100%';
  3178. }
  3179. $alpha = $color->alpha;
  3180. $returner .= '<stop offset="' . $positionValue . '" stop-color="' . $color->toRGB() . '"' . ($alpha < 1 ? ' stop-opacity="' . $alpha . '"' : '') . '/>';
  3181. }
  3182. $returner .= '</' . $gradientType . 'Gradient><rect ' . $rectangleDimension . ' fill="url(#gradient)" /></svg>';
  3183. if( $useBase64 ){
  3184. $returner = "'data:image/svg+xml;base64,".base64_encode($returner)."'";
  3185. }else{
  3186. $returner = "'data:image/svg+xml,".$returner."'";
  3187. }
  3188. return new Less_Tree_URL( new Less_Tree_Anonymous( $returner ) );
  3189. }
  3190. /**
  3191. * Php version of javascript's `encodeURIComponent` function
  3192. *
  3193. * @param string $string The string to encode
  3194. * @return string The encoded string
  3195. */
  3196. public static function encodeURIComponent($string){
  3197. $revert = array('%21' => '!', '%2A' => '*', '%27' => "'", '%28' => '(', '%29' => ')');
  3198. return strtr(rawurlencode($string), $revert);
  3199. }
  3200. // Color Blending
  3201. // ref: http://www.w3.org/TR/compositing-1
  3202. public function colorBlend( $mode, $color1, $color2 ){
  3203. $ab = $color1->alpha; // backdrop
  3204. $as = $color2->alpha; // source
  3205. $r = array(); // result
  3206. $ar = $as + $ab * (1 - $as);
  3207. for( $i = 0; $i < 3; $i++ ){
  3208. $cb = $color1->rgb[$i] / 255;
  3209. $cs = $color2->rgb[$i] / 255;
  3210. $cr = call_user_func( $mode, $cb, $cs );
  3211. if( $ar ){
  3212. $cr = ($as * $cs + $ab * ($cb - $as * ($cb + $cs - $cr))) / $ar;
  3213. }
  3214. $r[$i] = $cr * 255;
  3215. }
  3216. return new Less_Tree_Color($r, $ar);
  3217. }
  3218. public function multiply($color1 = null, $color2 = null ){
  3219. if (!$color1 instanceof Less_Tree_Color) {
  3220. throw new Less_Exception_Compiler('The first argument to multiply must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3221. }
  3222. if (!$color2 instanceof Less_Tree_Color) {
  3223. throw new Less_Exception_Compiler('The second argument to multiply must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3224. }
  3225. return $this->colorBlend( array($this,'colorBlendMultiply'), $color1, $color2 );
  3226. }
  3227. private function colorBlendMultiply($cb, $cs){
  3228. return $cb * $cs;
  3229. }
  3230. public function screen($color1 = null, $color2 = null ){
  3231. if (!$color1 instanceof Less_Tree_Color) {
  3232. throw new Less_Exception_Compiler('The first argument to screen must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3233. }
  3234. if (!$color2 instanceof Less_Tree_Color) {
  3235. throw new Less_Exception_Compiler('The second argument to screen must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3236. }
  3237. return $this->colorBlend( array($this,'colorBlendScreen'), $color1, $color2 );
  3238. }
  3239. private function colorBlendScreen( $cb, $cs){
  3240. return $cb + $cs - $cb * $cs;
  3241. }
  3242. public function overlay($color1 = null, $color2 = null){
  3243. if (!$color1 instanceof Less_Tree_Color) {
  3244. throw new Less_Exception_Compiler('The first argument to overlay must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3245. }
  3246. if (!$color2 instanceof Less_Tree_Color) {
  3247. throw new Less_Exception_Compiler('The second argument to overlay must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3248. }
  3249. return $this->colorBlend( array($this,'colorBlendOverlay'), $color1, $color2 );
  3250. }
  3251. private function colorBlendOverlay($cb, $cs ){
  3252. $cb *= 2;
  3253. return ($cb <= 1)
  3254. ? $this->colorBlendMultiply($cb, $cs)
  3255. : $this->colorBlendScreen($cb - 1, $cs);
  3256. }
  3257. public function softlight($color1 = null, $color2 = null){
  3258. if (!$color1 instanceof Less_Tree_Color) {
  3259. throw new Less_Exception_Compiler('The first argument to softlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3260. }
  3261. if (!$color2 instanceof Less_Tree_Color) {
  3262. throw new Less_Exception_Compiler('The second argument to softlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3263. }
  3264. return $this->colorBlend( array($this,'colorBlendSoftlight'), $color1, $color2 );
  3265. }
  3266. private function colorBlendSoftlight($cb, $cs ){
  3267. $d = 1;
  3268. $e = $cb;
  3269. if( $cs > 0.5 ){
  3270. $e = 1;
  3271. $d = ($cb > 0.25) ? sqrt($cb)
  3272. : ((16 * $cb - 12) * $cb + 4) * $cb;
  3273. }
  3274. return $cb - (1 - 2 * $cs) * $e * ($d - $cb);
  3275. }
  3276. public function hardlight($color1 = null, $color2 = null){
  3277. if (!$color1 instanceof Less_Tree_Color) {
  3278. throw new Less_Exception_Compiler('The first argument to hardlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3279. }
  3280. if (!$color2 instanceof Less_Tree_Color) {
  3281. throw new Less_Exception_Compiler('The second argument to hardlight must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3282. }
  3283. return $this->colorBlend( array($this,'colorBlendHardlight'), $color1, $color2 );
  3284. }
  3285. private function colorBlendHardlight( $cb, $cs ){
  3286. return $this->colorBlendOverlay($cs, $cb);
  3287. }
  3288. public function difference($color1 = null, $color2 = null) {
  3289. if (!$color1 instanceof Less_Tree_Color) {
  3290. throw new Less_Exception_Compiler('The first argument to difference must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3291. }
  3292. if (!$color2 instanceof Less_Tree_Color) {
  3293. throw new Less_Exception_Compiler('The second argument to difference must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3294. }
  3295. return $this->colorBlend( array($this,'colorBlendDifference'), $color1, $color2 );
  3296. }
  3297. private function colorBlendDifference( $cb, $cs ){
  3298. return abs($cb - $cs);
  3299. }
  3300. public function exclusion( $color1 = null, $color2 = null ){
  3301. if (!$color1 instanceof Less_Tree_Color) {
  3302. throw new Less_Exception_Compiler('The first argument to exclusion must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3303. }
  3304. if (!$color2 instanceof Less_Tree_Color) {
  3305. throw new Less_Exception_Compiler('The second argument to exclusion must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3306. }
  3307. return $this->colorBlend( array($this,'colorBlendExclusion'), $color1, $color2 );
  3308. }
  3309. private function colorBlendExclusion( $cb, $cs ){
  3310. return $cb + $cs - 2 * $cb * $cs;
  3311. }
  3312. public function average($color1 = null, $color2 = null){
  3313. if (!$color1 instanceof Less_Tree_Color) {
  3314. throw new Less_Exception_Compiler('The first argument to average must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3315. }
  3316. if (!$color2 instanceof Less_Tree_Color) {
  3317. throw new Less_Exception_Compiler('The second argument to average must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3318. }
  3319. return $this->colorBlend( array($this,'colorBlendAverage'), $color1, $color2 );
  3320. }
  3321. // non-w3c functions:
  3322. public function colorBlendAverage($cb, $cs ){
  3323. return ($cb + $cs) / 2;
  3324. }
  3325. public function negation($color1 = null, $color2 = null ){
  3326. if (!$color1 instanceof Less_Tree_Color) {
  3327. throw new Less_Exception_Compiler('The first argument to negation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3328. }
  3329. if (!$color2 instanceof Less_Tree_Color) {
  3330. throw new Less_Exception_Compiler('The second argument to negation must be a color' . ($color instanceof Less_Tree_Expression ? ' (did you forgot commas?)' : '') );
  3331. }
  3332. return $this->colorBlend( array($this,'colorBlendNegation'), $color1, $color2 );
  3333. }
  3334. public function colorBlendNegation($cb, $cs){
  3335. return 1 - abs($cb + $cs - 1);
  3336. }
  3337. // ~ End of Color Blending
  3338. }
  3339. /**
  3340. * Mime lookup
  3341. *
  3342. * @package Less
  3343. * @subpackage node
  3344. */
  3345. class Less_Mime{
  3346. // this map is intentionally incomplete
  3347. // if you want more, install 'mime' dep
  3348. static $_types = array(
  3349. '.htm' => 'text/html',
  3350. '.html'=> 'text/html',
  3351. '.gif' => 'image/gif',
  3352. '.jpg' => 'image/jpeg',
  3353. '.jpeg'=> 'image/jpeg',
  3354. '.png' => 'image/png',
  3355. '.ttf' => 'application/x-font-ttf',
  3356. '.otf' => 'application/x-font-otf',
  3357. '.eot' => 'application/vnd.ms-fontobject',
  3358. '.woff' => 'application/x-font-woff',
  3359. '.svg' => 'image/svg+xml',
  3360. );
  3361. public static function lookup( $filepath ){
  3362. $parts = explode('.',$filepath);
  3363. $ext = '.'.strtolower(array_pop($parts));
  3364. if( !isset(self::$_types[$ext]) ){
  3365. return null;
  3366. }
  3367. return self::$_types[$ext];
  3368. }
  3369. public static function charsets_lookup( $type = null ){
  3370. // assumes all text types are UTF-8
  3371. return $type && preg_match('/^text\//',$type) ? 'UTF-8' : '';
  3372. }
  3373. }
  3374. /**
  3375. * Tree
  3376. *
  3377. * @package Less
  3378. * @subpackage tree
  3379. */
  3380. class Less_Tree{
  3381. public $cache_string;
  3382. public function toCSS(){
  3383. $output = new Less_Output();
  3384. $this->genCSS($output);
  3385. return $output->toString();
  3386. }
  3387. /**
  3388. * Generate CSS by adding it to the output object
  3389. *
  3390. * @param Less_Output $output The output
  3391. * @return void
  3392. */
  3393. public function genCSS($output){}
  3394. /**
  3395. * @param Less_Tree_Ruleset[] $rules
  3396. */
  3397. public static function outputRuleset( $output, $rules ){
  3398. $ruleCnt = count($rules);
  3399. Less_Environment::$tabLevel++;
  3400. // Compressed
  3401. if( Less_Parser::$options['compress'] ){
  3402. $output->add('{');
  3403. for( $i = 0; $i < $ruleCnt; $i++ ){
  3404. $rules[$i]->genCSS( $output );
  3405. }
  3406. $output->add( '}' );
  3407. Less_Environment::$tabLevel--;
  3408. return;
  3409. }
  3410. // Non-compressed
  3411. $tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
  3412. $tabRuleStr = $tabSetStr.' ';
  3413. $output->add( " {" );
  3414. for($i = 0; $i < $ruleCnt; $i++ ){
  3415. $output->add( $tabRuleStr );
  3416. $rules[$i]->genCSS( $output );
  3417. }
  3418. Less_Environment::$tabLevel--;
  3419. $output->add( $tabSetStr.'}' );
  3420. }
  3421. public function accept($visitor){}
  3422. public static function ReferencedArray($rules){
  3423. foreach($rules as $rule){
  3424. if( method_exists($rule, 'markReferenced') ){
  3425. $rule->markReferenced();
  3426. }
  3427. }
  3428. }
  3429. /**
  3430. * Requires php 5.3+
  3431. */
  3432. public static function __set_state($args){
  3433. $class = get_called_class();
  3434. $obj = new $class(null,null,null,null);
  3435. foreach($args as $key => $val){
  3436. $obj->$key = $val;
  3437. }
  3438. return $obj;
  3439. }
  3440. }
  3441. /**
  3442. * Parser output
  3443. *
  3444. * @package Less
  3445. * @subpackage output
  3446. */
  3447. class Less_Output{
  3448. /**
  3449. * Output holder
  3450. *
  3451. * @var string
  3452. */
  3453. protected $strs = array();
  3454. /**
  3455. * Adds a chunk to the stack
  3456. *
  3457. * @param string $chunk The chunk to output
  3458. * @param Less_FileInfo $fileInfo The file information
  3459. * @param integer $index The index
  3460. * @param mixed $mapLines
  3461. */
  3462. public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
  3463. $this->strs[] = $chunk;
  3464. }
  3465. /**
  3466. * Is the output empty?
  3467. *
  3468. * @return boolean
  3469. */
  3470. public function isEmpty(){
  3471. return count($this->strs) === 0;
  3472. }
  3473. /**
  3474. * Converts the output to string
  3475. *
  3476. * @return string
  3477. */
  3478. public function toString(){
  3479. return implode('',$this->strs);
  3480. }
  3481. }
  3482. /**
  3483. * Visitor
  3484. *
  3485. * @package Less
  3486. * @subpackage visitor
  3487. */
  3488. class Less_Visitor{
  3489. protected $methods = array();
  3490. protected $_visitFnCache = array();
  3491. public function __construct(){
  3492. $this->_visitFnCache = get_class_methods(get_class($this));
  3493. $this->_visitFnCache = array_flip($this->_visitFnCache);
  3494. }
  3495. public function visitObj( $node ){
  3496. $funcName = 'visit'.$node->type;
  3497. if( isset($this->_visitFnCache[$funcName]) ){
  3498. $visitDeeper = true;
  3499. $this->$funcName( $node, $visitDeeper );
  3500. if( $visitDeeper ){
  3501. $node->accept($this);
  3502. }
  3503. $funcName = $funcName . "Out";
  3504. if( isset($this->_visitFnCache[$funcName]) ){
  3505. $this->$funcName( $node );
  3506. }
  3507. }else{
  3508. $node->accept($this);
  3509. }
  3510. return $node;
  3511. }
  3512. public function visitArray( $nodes ){
  3513. array_map( array($this,'visitObj'), $nodes);
  3514. return $nodes;
  3515. }
  3516. }
  3517. /**
  3518. * Replacing Visitor
  3519. *
  3520. * @package Less
  3521. * @subpackage visitor
  3522. */
  3523. class Less_VisitorReplacing extends Less_Visitor{
  3524. public function visitObj( $node ){
  3525. $funcName = 'visit'.$node->type;
  3526. if( isset($this->_visitFnCache[$funcName]) ){
  3527. $visitDeeper = true;
  3528. $node = $this->$funcName( $node, $visitDeeper );
  3529. if( $node ){
  3530. if( $visitDeeper && is_object($node) ){
  3531. $node->accept($this);
  3532. }
  3533. $funcName = $funcName . "Out";
  3534. if( isset($this->_visitFnCache[$funcName]) ){
  3535. $this->$funcName( $node );
  3536. }
  3537. }
  3538. }else{
  3539. $node->accept($this);
  3540. }
  3541. return $node;
  3542. }
  3543. public function visitArray( $nodes ){
  3544. $newNodes = array();
  3545. foreach($nodes as $node){
  3546. $evald = $this->visitObj($node);
  3547. if( $evald ){
  3548. if( is_array($evald) ){
  3549. self::flatten($evald,$newNodes);
  3550. }else{
  3551. $newNodes[] = $evald;
  3552. }
  3553. }
  3554. }
  3555. return $newNodes;
  3556. }
  3557. public function flatten( $arr, &$out ){
  3558. foreach($arr as $item){
  3559. if( !is_array($item) ){
  3560. $out[] = $item;
  3561. continue;
  3562. }
  3563. foreach($item as $nestedItem){
  3564. if( is_array($nestedItem) ){
  3565. self::flatten( $nestedItem, $out);
  3566. }else{
  3567. $out[] = $nestedItem;
  3568. }
  3569. }
  3570. }
  3571. return $out;
  3572. }
  3573. }
  3574. /**
  3575. * Configurable
  3576. *
  3577. * @package Less
  3578. * @subpackage Core
  3579. */
  3580. abstract class Less_Configurable {
  3581. /**
  3582. * Array of options
  3583. *
  3584. * @var array
  3585. */
  3586. protected $options = array();
  3587. /**
  3588. * Array of default options
  3589. *
  3590. * @var array
  3591. */
  3592. protected $defaultOptions = array();
  3593. /**
  3594. * Set options
  3595. *
  3596. * If $options is an object it will be converted into an array by called
  3597. * it's toArray method.
  3598. *
  3599. * @throws Exception
  3600. * @param array|object $options
  3601. *
  3602. */
  3603. public function setOptions($options){
  3604. $options = array_intersect_key($options,$this->defaultOptions);
  3605. $this->options = array_merge($this->defaultOptions, $this->options, $options);
  3606. }
  3607. /**
  3608. * Get an option value by name
  3609. *
  3610. * If the option is empty or not set a NULL value will be returned.
  3611. *
  3612. * @param string $name
  3613. * @param mixed $default Default value if confiuration of $name is not present
  3614. * @return mixed
  3615. */
  3616. public function getOption($name, $default = null){
  3617. if(isset($this->options[$name])){
  3618. return $this->options[$name];
  3619. }
  3620. return $default;
  3621. }
  3622. /**
  3623. * Set an option
  3624. *
  3625. * @param string $name
  3626. * @param mixed $value
  3627. */
  3628. public function setOption($name, $value){
  3629. $this->options[$name] = $value;
  3630. }
  3631. }
  3632. /**
  3633. * Alpha
  3634. *
  3635. * @package Less
  3636. * @subpackage tree
  3637. */
  3638. class Less_Tree_Alpha extends Less_Tree{
  3639. public $value;
  3640. public $type = 'Alpha';
  3641. public function __construct($val){
  3642. $this->value = $val;
  3643. }
  3644. //function accept( $visitor ){
  3645. // $this->value = $visitor->visit( $this->value );
  3646. //}
  3647. public function compile($env){
  3648. if( is_object($this->value) ){
  3649. $this->value = $this->value->compile($env);
  3650. }
  3651. return $this;
  3652. }
  3653. /**
  3654. * @see Less_Tree::genCSS
  3655. */
  3656. public function genCSS( $output ){
  3657. $output->add( "alpha(opacity=" );
  3658. if( is_string($this->value) ){
  3659. $output->add( $this->value );
  3660. }else{
  3661. $this->value->genCSS( $output);
  3662. }
  3663. $output->add( ')' );
  3664. }
  3665. public function toCSS(){
  3666. return "alpha(opacity=" . (is_string($this->value) ? $this->value : $this->value->toCSS()) . ")";
  3667. }
  3668. }
  3669. /**
  3670. * Anonymous
  3671. *
  3672. * @package Less
  3673. * @subpackage tree
  3674. */
  3675. class Less_Tree_Anonymous extends Less_Tree{
  3676. public $value;
  3677. public $quote;
  3678. public $index;
  3679. public $mapLines;
  3680. public $currentFileInfo;
  3681. public $type = 'Anonymous';
  3682. /**
  3683. * @param integer $index
  3684. * @param boolean $mapLines
  3685. */
  3686. public function __construct($value, $index = null, $currentFileInfo = null, $mapLines = null ){
  3687. $this->value = $value;
  3688. $this->index = $index;
  3689. $this->mapLines = $mapLines;
  3690. $this->currentFileInfo = $currentFileInfo;
  3691. }
  3692. public function compile(){
  3693. return new Less_Tree_Anonymous($this->value, $this->index, $this->currentFileInfo, $this->mapLines);
  3694. }
  3695. public function compare($x){
  3696. if( !is_object($x) ){
  3697. return -1;
  3698. }
  3699. $left = $this->toCSS();
  3700. $right = $x->toCSS();
  3701. if( $left === $right ){
  3702. return 0;
  3703. }
  3704. return $left < $right ? -1 : 1;
  3705. }
  3706. /**
  3707. * @see Less_Tree::genCSS
  3708. */
  3709. public function genCSS( $output ){
  3710. $output->add( $this->value, $this->currentFileInfo, $this->index, $this->mapLines );
  3711. }
  3712. public function toCSS(){
  3713. return $this->value;
  3714. }
  3715. }
  3716. /**
  3717. * Assignment
  3718. *
  3719. * @package Less
  3720. * @subpackage tree
  3721. */
  3722. class Less_Tree_Assignment extends Less_Tree{
  3723. public $key;
  3724. public $value;
  3725. public $type = 'Assignment';
  3726. public function __construct($key, $val) {
  3727. $this->key = $key;
  3728. $this->value = $val;
  3729. }
  3730. public function accept( $visitor ){
  3731. $this->value = $visitor->visitObj( $this->value );
  3732. }
  3733. public function compile($env) {
  3734. return new Less_Tree_Assignment( $this->key, $this->value->compile($env));
  3735. }
  3736. /**
  3737. * @see Less_Tree::genCSS
  3738. */
  3739. public function genCSS( $output ){
  3740. $output->add( $this->key . '=' );
  3741. $this->value->genCSS( $output );
  3742. }
  3743. public function toCss(){
  3744. return $this->key . '=' . $this->value->toCSS();
  3745. }
  3746. }
  3747. /**
  3748. * Attribute
  3749. *
  3750. * @package Less
  3751. * @subpackage tree
  3752. */
  3753. class Less_Tree_Attribute extends Less_Tree{
  3754. public $key;
  3755. public $op;
  3756. public $value;
  3757. public $type = 'Attribute';
  3758. public function __construct($key, $op, $value){
  3759. $this->key = $key;
  3760. $this->op = $op;
  3761. $this->value = $value;
  3762. }
  3763. public function compile($env){
  3764. $key_obj = is_object($this->key);
  3765. $val_obj = is_object($this->value);
  3766. if( !$key_obj && !$val_obj ){
  3767. return $this;
  3768. }
  3769. return new Less_Tree_Attribute(
  3770. $key_obj ? $this->key->compile($env) : $this->key ,
  3771. $this->op,
  3772. $val_obj ? $this->value->compile($env) : $this->value);
  3773. }
  3774. /**
  3775. * @see Less_Tree::genCSS
  3776. */
  3777. public function genCSS( $output ){
  3778. $output->add( $this->toCSS() );
  3779. }
  3780. public function toCSS(){
  3781. $value = $this->key;
  3782. if( $this->op ){
  3783. $value .= $this->op;
  3784. $value .= (is_object($this->value) ? $this->value->toCSS() : $this->value);
  3785. }
  3786. return '[' . $value . ']';
  3787. }
  3788. }
  3789. /**
  3790. * Call
  3791. *
  3792. * @package Less
  3793. * @subpackage tree
  3794. */
  3795. class Less_Tree_Call extends Less_Tree{
  3796. public $value;
  3797. protected $name;
  3798. protected $args;
  3799. protected $index;
  3800. protected $currentFileInfo;
  3801. public $type = 'Call';
  3802. public function __construct($name, $args, $index, $currentFileInfo = null ){
  3803. $this->name = $name;
  3804. $this->args = $args;
  3805. $this->index = $index;
  3806. $this->currentFileInfo = $currentFileInfo;
  3807. }
  3808. public function accept( $visitor ){
  3809. $this->args = $visitor->visitArray( $this->args );
  3810. }
  3811. //
  3812. // When evaluating a function call,
  3813. // we either find the function in `tree.functions` [1],
  3814. // in which case we call it, passing the evaluated arguments,
  3815. // or we simply print it out as it appeared originally [2].
  3816. //
  3817. // The *functions.js* file contains the built-in functions.
  3818. //
  3819. // The reason why we evaluate the arguments, is in the case where
  3820. // we try to pass a variable to a function, like: `saturate(@color)`.
  3821. // The function should receive the value, not the variable.
  3822. //
  3823. public function compile($env=null){
  3824. $args = array();
  3825. foreach($this->args as $a){
  3826. $args[] = $a->compile($env);
  3827. }
  3828. $nameLC = strtolower($this->name);
  3829. switch($nameLC){
  3830. case '%':
  3831. $nameLC = '_percent';
  3832. break;
  3833. case 'get-unit':
  3834. $nameLC = 'getunit';
  3835. break;
  3836. case 'data-uri':
  3837. $nameLC = 'datauri';
  3838. break;
  3839. case 'svg-gradient':
  3840. $nameLC = 'svggradient';
  3841. break;
  3842. }
  3843. $result = null;
  3844. if( $nameLC === 'default' ){
  3845. $result = Less_Tree_DefaultFunc::compile();
  3846. }else{
  3847. if( method_exists('Less_Functions',$nameLC) ){ // 1.
  3848. try {
  3849. $func = new Less_Functions($env, $this->currentFileInfo);
  3850. $result = call_user_func_array( array($func,$nameLC),$args);
  3851. } catch (Exception $e) {
  3852. throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
  3853. }
  3854. } elseif( isset( $env->functions[$nameLC] ) && is_callable( $env->functions[$nameLC] ) ) {
  3855. try {
  3856. $result = call_user_func_array( $env->functions[$nameLC], $args );
  3857. } catch (Exception $e) {
  3858. throw new Less_Exception_Compiler('error evaluating function `' . $this->name . '` '.$e->getMessage().' index: '. $this->index);
  3859. }
  3860. }
  3861. }
  3862. if( $result !== null ){
  3863. return $result;
  3864. }
  3865. return new Less_Tree_Call( $this->name, $args, $this->index, $this->currentFileInfo );
  3866. }
  3867. /**
  3868. * @see Less_Tree::genCSS
  3869. */
  3870. public function genCSS( $output ){
  3871. $output->add( $this->name . '(', $this->currentFileInfo, $this->index );
  3872. $args_len = count($this->args);
  3873. for($i = 0; $i < $args_len; $i++ ){
  3874. $this->args[$i]->genCSS( $output );
  3875. if( $i + 1 < $args_len ){
  3876. $output->add( ', ' );
  3877. }
  3878. }
  3879. $output->add( ')' );
  3880. }
  3881. //public function toCSS(){
  3882. // return $this->compile()->toCSS();
  3883. //}
  3884. }
  3885. /**
  3886. * Color
  3887. *
  3888. * @package Less
  3889. * @subpackage tree
  3890. */
  3891. class Less_Tree_Color extends Less_Tree{
  3892. public $rgb;
  3893. public $alpha;
  3894. public $isTransparentKeyword;
  3895. public $type = 'Color';
  3896. public function __construct($rgb, $a = 1, $isTransparentKeyword = null ){
  3897. if( $isTransparentKeyword ){
  3898. $this->rgb = $rgb;
  3899. $this->alpha = $a;
  3900. $this->isTransparentKeyword = true;
  3901. return;
  3902. }
  3903. $this->rgb = array();
  3904. if( is_array($rgb) ){
  3905. $this->rgb = $rgb;
  3906. }else if( strlen($rgb) == 6 ){
  3907. foreach(str_split($rgb, 2) as $c){
  3908. $this->rgb[] = hexdec($c);
  3909. }
  3910. }else{
  3911. foreach(str_split($rgb, 1) as $c){
  3912. $this->rgb[] = hexdec($c.$c);
  3913. }
  3914. }
  3915. $this->alpha = is_numeric($a) ? $a : 1;
  3916. }
  3917. public function compile(){
  3918. return $this;
  3919. }
  3920. public function luma(){
  3921. $r = $this->rgb[0] / 255;
  3922. $g = $this->rgb[1] / 255;
  3923. $b = $this->rgb[2] / 255;
  3924. $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
  3925. $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
  3926. $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
  3927. return 0.2126 * $r + 0.7152 * $g + 0.0722 * $b;
  3928. }
  3929. /**
  3930. * @see Less_Tree::genCSS
  3931. */
  3932. public function genCSS( $output ){
  3933. $output->add( $this->toCSS() );
  3934. }
  3935. public function toCSS( $doNotCompress = false ){
  3936. $compress = Less_Parser::$options['compress'] && !$doNotCompress;
  3937. $alpha = Less_Functions::fround( $this->alpha );
  3938. //
  3939. // If we have some transparency, the only way to represent it
  3940. // is via `rgba`. Otherwise, we use the hex representation,
  3941. // which has better compatibility with older browsers.
  3942. // Values are capped between `0` and `255`, rounded and zero-padded.
  3943. //
  3944. if( $alpha < 1 ){
  3945. if( ( $alpha === 0 || $alpha === 0.0 ) && isset($this->isTransparentKeyword) && $this->isTransparentKeyword ){
  3946. return 'transparent';
  3947. }
  3948. $values = array();
  3949. foreach($this->rgb as $c){
  3950. $values[] = Less_Functions::clamp( round($c), 255);
  3951. }
  3952. $values[] = $alpha;
  3953. $glue = ($compress ? ',' : ', ');
  3954. return "rgba(" . implode($glue, $values) . ")";
  3955. }else{
  3956. $color = $this->toRGB();
  3957. if( $compress ){
  3958. // Convert color to short format
  3959. if( $color[1] === $color[2] && $color[3] === $color[4] && $color[5] === $color[6]) {
  3960. $color = '#'.$color[1] . $color[3] . $color[5];
  3961. }
  3962. }
  3963. return $color;
  3964. }
  3965. }
  3966. //
  3967. // Operations have to be done per-channel, if not,
  3968. // channels will spill onto each other. Once we have
  3969. // our result, in the form of an integer triplet,
  3970. // we create a new Color node to hold the result.
  3971. //
  3972. /**
  3973. * @param string $op
  3974. */
  3975. public function operate( $op, $other) {
  3976. $rgb = array();
  3977. $alpha = $this->alpha * (1 - $other->alpha) + $other->alpha;
  3978. for ($c = 0; $c < 3; $c++) {
  3979. $rgb[$c] = Less_Functions::operate( $op, $this->rgb[$c], $other->rgb[$c]);
  3980. }
  3981. return new Less_Tree_Color($rgb, $alpha);
  3982. }
  3983. public function toRGB(){
  3984. return $this->toHex($this->rgb);
  3985. }
  3986. public function toHSL(){
  3987. $r = $this->rgb[0] / 255;
  3988. $g = $this->rgb[1] / 255;
  3989. $b = $this->rgb[2] / 255;
  3990. $a = $this->alpha;
  3991. $max = max($r, $g, $b);
  3992. $min = min($r, $g, $b);
  3993. $l = ($max + $min) / 2;
  3994. $d = $max - $min;
  3995. $h = $s = 0;
  3996. if( $max !== $min ){
  3997. $s = $l > 0.5 ? $d / (2 - $max - $min) : $d / ($max + $min);
  3998. switch ($max) {
  3999. case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
  4000. case $g: $h = ($b - $r) / $d + 2; break;
  4001. case $b: $h = ($r - $g) / $d + 4; break;
  4002. }
  4003. $h /= 6;
  4004. }
  4005. return array('h' => $h * 360, 's' => $s, 'l' => $l, 'a' => $a );
  4006. }
  4007. //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
  4008. public function toHSV() {
  4009. $r = $this->rgb[0] / 255;
  4010. $g = $this->rgb[1] / 255;
  4011. $b = $this->rgb[2] / 255;
  4012. $a = $this->alpha;
  4013. $max = max($r, $g, $b);
  4014. $min = min($r, $g, $b);
  4015. $v = $max;
  4016. $d = $max - $min;
  4017. if ($max === 0) {
  4018. $s = 0;
  4019. } else {
  4020. $s = $d / $max;
  4021. }
  4022. $h = 0;
  4023. if( $max !== $min ){
  4024. switch($max){
  4025. case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break;
  4026. case $g: $h = ($b - $r) / $d + 2; break;
  4027. case $b: $h = ($r - $g) / $d + 4; break;
  4028. }
  4029. $h /= 6;
  4030. }
  4031. return array('h'=> $h * 360, 's'=> $s, 'v'=> $v, 'a' => $a );
  4032. }
  4033. public function toARGB(){
  4034. $argb = array_merge( (array) Less_Parser::round($this->alpha * 255), $this->rgb);
  4035. return $this->toHex( $argb );
  4036. }
  4037. public function compare($x){
  4038. if( !property_exists( $x, 'rgb' ) ){
  4039. return -1;
  4040. }
  4041. return ($x->rgb[0] === $this->rgb[0] &&
  4042. $x->rgb[1] === $this->rgb[1] &&
  4043. $x->rgb[2] === $this->rgb[2] &&
  4044. $x->alpha === $this->alpha) ? 0 : -1;
  4045. }
  4046. public function toHex( $v ){
  4047. $ret = '#';
  4048. foreach($v as $c){
  4049. $c = Less_Functions::clamp( Less_Parser::round($c), 255);
  4050. if( $c < 16 ){
  4051. $ret .= '0';
  4052. }
  4053. $ret .= dechex($c);
  4054. }
  4055. return $ret;
  4056. }
  4057. /**
  4058. * @param string $keyword
  4059. */
  4060. public static function fromKeyword( $keyword ){
  4061. $keyword = strtolower($keyword);
  4062. if( Less_Colors::hasOwnProperty($keyword) ){
  4063. // detect named color
  4064. return new Less_Tree_Color(substr(Less_Colors::color($keyword), 1));
  4065. }
  4066. if( $keyword === 'transparent' ){
  4067. return new Less_Tree_Color( array(0, 0, 0), 0, true);
  4068. }
  4069. }
  4070. }
  4071. /**
  4072. * Comment
  4073. *
  4074. * @package Less
  4075. * @subpackage tree
  4076. */
  4077. class Less_Tree_Comment extends Less_Tree{
  4078. public $value;
  4079. public $silent;
  4080. public $isReferenced;
  4081. public $currentFileInfo;
  4082. public $type = 'Comment';
  4083. public function __construct($value, $silent, $index = null, $currentFileInfo = null ){
  4084. $this->value = $value;
  4085. $this->silent = !! $silent;
  4086. $this->currentFileInfo = $currentFileInfo;
  4087. }
  4088. /**
  4089. * @see Less_Tree::genCSS
  4090. */
  4091. public function genCSS( $output ){
  4092. //if( $this->debugInfo ){
  4093. //$output->add( tree.debugInfo($env, $this), $this->currentFileInfo, $this->index);
  4094. //}
  4095. $output->add( trim($this->value) );//TODO shouldn't need to trim, we shouldn't grab the \n
  4096. }
  4097. public function toCSS(){
  4098. return Less_Parser::$options['compress'] ? '' : $this->value;
  4099. }
  4100. public function isSilent(){
  4101. $isReference = ($this->currentFileInfo && isset($this->currentFileInfo['reference']) && (!isset($this->isReferenced) || !$this->isReferenced) );
  4102. $isCompressed = Less_Parser::$options['compress'] && !preg_match('/^\/\*!/', $this->value);
  4103. return $this->silent || $isReference || $isCompressed;
  4104. }
  4105. public function compile(){
  4106. return $this;
  4107. }
  4108. public function markReferenced(){
  4109. $this->isReferenced = true;
  4110. }
  4111. }
  4112. /**
  4113. * Condition
  4114. *
  4115. * @package Less
  4116. * @subpackage tree
  4117. */
  4118. class Less_Tree_Condition extends Less_Tree{
  4119. public $op;
  4120. public $lvalue;
  4121. public $rvalue;
  4122. public $index;
  4123. public $negate;
  4124. public $type = 'Condition';
  4125. public function __construct($op, $l, $r, $i = 0, $negate = false) {
  4126. $this->op = trim($op);
  4127. $this->lvalue = $l;
  4128. $this->rvalue = $r;
  4129. $this->index = $i;
  4130. $this->negate = $negate;
  4131. }
  4132. public function accept($visitor){
  4133. $this->lvalue = $visitor->visitObj( $this->lvalue );
  4134. $this->rvalue = $visitor->visitObj( $this->rvalue );
  4135. }
  4136. public function compile($env) {
  4137. $a = $this->lvalue->compile($env);
  4138. $b = $this->rvalue->compile($env);
  4139. switch( $this->op ){
  4140. case 'and':
  4141. $result = $a && $b;
  4142. break;
  4143. case 'or':
  4144. $result = $a || $b;
  4145. break;
  4146. default:
  4147. if( Less_Parser::is_method($a, 'compare') ){
  4148. $result = $a->compare($b);
  4149. }elseif( Less_Parser::is_method($b, 'compare') ){
  4150. $result = $b->compare($a);
  4151. }else{
  4152. throw new Less_Exception_Compiler('Unable to perform comparison', null, $this->index);
  4153. }
  4154. switch ($result) {
  4155. case -1:
  4156. $result = $this->op === '<' || $this->op === '=<' || $this->op === '<=';
  4157. break;
  4158. case 0:
  4159. $result = $this->op === '=' || $this->op === '>=' || $this->op === '=<' || $this->op === '<=';
  4160. break;
  4161. case 1:
  4162. $result = $this->op === '>' || $this->op === '>=';
  4163. break;
  4164. }
  4165. break;
  4166. }
  4167. return $this->negate ? !$result : $result;
  4168. }
  4169. }
  4170. /**
  4171. * DefaultFunc
  4172. *
  4173. * @package Less
  4174. * @subpackage tree
  4175. */
  4176. class Less_Tree_DefaultFunc{
  4177. static $error_;
  4178. static $value_;
  4179. public static function compile(){
  4180. if( self::$error_ ){
  4181. throw new Exception(self::$error_);
  4182. }
  4183. if( self::$value_ !== null ){
  4184. return self::$value_ ? new Less_Tree_Keyword('true') : new Less_Tree_Keyword('false');
  4185. }
  4186. }
  4187. public static function value( $v ){
  4188. self::$value_ = $v;
  4189. }
  4190. public static function error( $e ){
  4191. self::$error_ = $e;
  4192. }
  4193. public static function reset(){
  4194. self::$value_ = self::$error_ = null;
  4195. }
  4196. }
  4197. /**
  4198. * DetachedRuleset
  4199. *
  4200. * @package Less
  4201. * @subpackage tree
  4202. */
  4203. class Less_Tree_DetachedRuleset extends Less_Tree{
  4204. public $ruleset;
  4205. public $frames;
  4206. public $type = 'DetachedRuleset';
  4207. public function __construct( $ruleset, $frames = null ){
  4208. $this->ruleset = $ruleset;
  4209. $this->frames = $frames;
  4210. }
  4211. public function accept($visitor) {
  4212. $this->ruleset = $visitor->visitObj($this->ruleset);
  4213. }
  4214. public function compile($env){
  4215. if( $this->frames ){
  4216. $frames = $this->frames;
  4217. }else{
  4218. $frames = $env->frames;
  4219. }
  4220. return new Less_Tree_DetachedRuleset($this->ruleset, $frames);
  4221. }
  4222. public function callEval($env) {
  4223. if( $this->frames ){
  4224. return $this->ruleset->compile( $env->copyEvalEnv( array_merge($this->frames,$env->frames) ) );
  4225. }
  4226. return $this->ruleset->compile( $env );
  4227. }
  4228. }
  4229. /**
  4230. * Dimension
  4231. *
  4232. * @package Less
  4233. * @subpackage tree
  4234. */
  4235. class Less_Tree_Dimension extends Less_Tree{
  4236. public $value;
  4237. public $unit;
  4238. public $type = 'Dimension';
  4239. public function __construct($value, $unit = null){
  4240. $this->value = floatval($value);
  4241. if( $unit && ($unit instanceof Less_Tree_Unit) ){
  4242. $this->unit = $unit;
  4243. }elseif( $unit ){
  4244. $this->unit = new Less_Tree_Unit( array($unit) );
  4245. }else{
  4246. $this->unit = new Less_Tree_Unit( );
  4247. }
  4248. }
  4249. public function accept( $visitor ){
  4250. $this->unit = $visitor->visitObj( $this->unit );
  4251. }
  4252. public function compile(){
  4253. return $this;
  4254. }
  4255. public function toColor() {
  4256. return new Less_Tree_Color(array($this->value, $this->value, $this->value));
  4257. }
  4258. /**
  4259. * @see Less_Tree::genCSS
  4260. */
  4261. public function genCSS( $output ){
  4262. if( Less_Parser::$options['strictUnits'] && !$this->unit->isSingular() ){
  4263. throw new Less_Exception_Compiler("Multiple units in dimension. Correct the units or use the unit function. Bad unit: ".$this->unit->toString());
  4264. }
  4265. $value = Less_Functions::fround( $this->value );
  4266. $strValue = (string)$value;
  4267. if( $value !== 0 && $value < 0.000001 && $value > -0.000001 ){
  4268. // would be output 1e-6 etc.
  4269. $strValue = number_format($strValue,10);
  4270. $strValue = preg_replace('/\.?0+$/','', $strValue);
  4271. }
  4272. if( Less_Parser::$options['compress'] ){
  4273. // Zero values doesn't need a unit
  4274. if( $value === 0 && $this->unit->isLength() ){
  4275. $output->add( $strValue );
  4276. return $strValue;
  4277. }
  4278. // Float values doesn't need a leading zero
  4279. if( $value > 0 && $value < 1 && $strValue[0] === '0' ){
  4280. $strValue = substr($strValue,1);
  4281. }
  4282. }
  4283. $output->add( $strValue );
  4284. $this->unit->genCSS( $output );
  4285. }
  4286. public function __toString(){
  4287. return $this->toCSS();
  4288. }
  4289. // In an operation between two Dimensions,
  4290. // we default to the first Dimension's unit,
  4291. // so `1px + 2em` will yield `3px`.
  4292. /**
  4293. * @param string $op
  4294. */
  4295. public function operate( $op, $other){
  4296. $value = Less_Functions::operate( $op, $this->value, $other->value);
  4297. $unit = clone $this->unit;
  4298. if( $op === '+' || $op === '-' ){
  4299. if( !$unit->numerator && !$unit->denominator ){
  4300. $unit->numerator = $other->unit->numerator;
  4301. $unit->denominator = $other->unit->denominator;
  4302. }elseif( !$other->unit->numerator && !$other->unit->denominator ){
  4303. // do nothing
  4304. }else{
  4305. $other = $other->convertTo( $this->unit->usedUnits());
  4306. if( Less_Parser::$options['strictUnits'] && $other->unit->toString() !== $unit->toCSS() ){
  4307. throw new Less_Exception_Compiler("Incompatible units. Change the units or use the unit function. Bad units: '".$unit->toString() . "' and ".$other->unit->toString()+"'.");
  4308. }
  4309. $value = Less_Functions::operate( $op, $this->value, $other->value);
  4310. }
  4311. }elseif( $op === '*' ){
  4312. $unit->numerator = array_merge($unit->numerator, $other->unit->numerator);
  4313. $unit->denominator = array_merge($unit->denominator, $other->unit->denominator);
  4314. sort($unit->numerator);
  4315. sort($unit->denominator);
  4316. $unit->cancel();
  4317. }elseif( $op === '/' ){
  4318. $unit->numerator = array_merge($unit->numerator, $other->unit->denominator);
  4319. $unit->denominator = array_merge($unit->denominator, $other->unit->numerator);
  4320. sort($unit->numerator);
  4321. sort($unit->denominator);
  4322. $unit->cancel();
  4323. }
  4324. return new Less_Tree_Dimension( $value, $unit);
  4325. }
  4326. public function compare($other) {
  4327. if ($other instanceof Less_Tree_Dimension) {
  4328. if( $this->unit->isEmpty() || $other->unit->isEmpty() ){
  4329. $a = $this;
  4330. $b = $other;
  4331. } else {
  4332. $a = $this->unify();
  4333. $b = $other->unify();
  4334. if( $a->unit->compare($b->unit) !== 0 ){
  4335. return -1;
  4336. }
  4337. }
  4338. $aValue = $a->value;
  4339. $bValue = $b->value;
  4340. if ($bValue > $aValue) {
  4341. return -1;
  4342. } elseif ($bValue < $aValue) {
  4343. return 1;
  4344. } else {
  4345. return 0;
  4346. }
  4347. } else {
  4348. return -1;
  4349. }
  4350. }
  4351. public function unify() {
  4352. return $this->convertTo(array('length'=> 'px', 'duration'=> 's', 'angle' => 'rad' ));
  4353. }
  4354. public function convertTo($conversions) {
  4355. $value = $this->value;
  4356. $unit = clone $this->unit;
  4357. if( is_string($conversions) ){
  4358. $derivedConversions = array();
  4359. foreach( Less_Tree_UnitConversions::$groups as $i ){
  4360. if( isset(Less_Tree_UnitConversions::${$i}[$conversions]) ){
  4361. $derivedConversions = array( $i => $conversions);
  4362. }
  4363. }
  4364. $conversions = $derivedConversions;
  4365. }
  4366. foreach($conversions as $groupName => $targetUnit){
  4367. $group = Less_Tree_UnitConversions::${$groupName};
  4368. //numerator
  4369. foreach($unit->numerator as $i => $atomicUnit){
  4370. $atomicUnit = $unit->numerator[$i];
  4371. if( !isset($group[$atomicUnit]) ){
  4372. continue;
  4373. }
  4374. $value = $value * ($group[$atomicUnit] / $group[$targetUnit]);
  4375. $unit->numerator[$i] = $targetUnit;
  4376. }
  4377. //denominator
  4378. foreach($unit->denominator as $i => $atomicUnit){
  4379. $atomicUnit = $unit->denominator[$i];
  4380. if( !isset($group[$atomicUnit]) ){
  4381. continue;
  4382. }
  4383. $value = $value / ($group[$atomicUnit] / $group[$targetUnit]);
  4384. $unit->denominator[$i] = $targetUnit;
  4385. }
  4386. }
  4387. $unit->cancel();
  4388. return new Less_Tree_Dimension( $value, $unit);
  4389. }
  4390. }
  4391. /**
  4392. * Directive
  4393. *
  4394. * @package Less
  4395. * @subpackage tree
  4396. */
  4397. class Less_Tree_Directive extends Less_Tree{
  4398. public $name;
  4399. public $value;
  4400. public $rules;
  4401. public $index;
  4402. public $isReferenced;
  4403. public $currentFileInfo;
  4404. public $debugInfo;
  4405. public $type = 'Directive';
  4406. public function __construct($name, $value = null, $rules, $index = null, $currentFileInfo = null, $debugInfo = null ){
  4407. $this->name = $name;
  4408. $this->value = $value;
  4409. if( $rules ){
  4410. $this->rules = $rules;
  4411. $this->rules->allowImports = true;
  4412. }
  4413. $this->index = $index;
  4414. $this->currentFileInfo = $currentFileInfo;
  4415. $this->debugInfo = $debugInfo;
  4416. }
  4417. public function accept( $visitor ){
  4418. if( $this->rules ){
  4419. $this->rules = $visitor->visitObj( $this->rules );
  4420. }
  4421. if( $this->value ){
  4422. $this->value = $visitor->visitObj( $this->value );
  4423. }
  4424. }
  4425. /**
  4426. * @see Less_Tree::genCSS
  4427. */
  4428. public function genCSS( $output ){
  4429. $value = $this->value;
  4430. $rules = $this->rules;
  4431. $output->add( $this->name, $this->currentFileInfo, $this->index );
  4432. if( $this->value ){
  4433. $output->add(' ');
  4434. $this->value->genCSS($output);
  4435. }
  4436. if( $this->rules ){
  4437. Less_Tree::outputRuleset( $output, array($this->rules));
  4438. } else {
  4439. $output->add(';');
  4440. }
  4441. }
  4442. public function compile($env){
  4443. $value = $this->value;
  4444. $rules = $this->rules;
  4445. if( $value ){
  4446. $value = $value->compile($env);
  4447. }
  4448. if( $rules ){
  4449. $rules = $rules->compile($env);
  4450. $rules->root = true;
  4451. }
  4452. return new Less_Tree_Directive( $this->name, $value, $rules, $this->index, $this->currentFileInfo, $this->debugInfo );
  4453. }
  4454. public function variable($name){
  4455. if( $this->rules ){
  4456. return $this->rules->variable($name);
  4457. }
  4458. }
  4459. public function find($selector){
  4460. if( $this->rules ){
  4461. return $this->rules->find($selector, $this);
  4462. }
  4463. }
  4464. //rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); },
  4465. public function markReferenced(){
  4466. $this->isReferenced = true;
  4467. if( $this->rules ){
  4468. Less_Tree::ReferencedArray($this->rules->rules);
  4469. }
  4470. }
  4471. }
  4472. /**
  4473. * Element
  4474. *
  4475. * @package Less
  4476. * @subpackage tree
  4477. */
  4478. class Less_Tree_Element extends Less_Tree{
  4479. public $combinator = '';
  4480. public $value = '';
  4481. public $index;
  4482. public $currentFileInfo;
  4483. public $type = 'Element';
  4484. public $value_is_object = false;
  4485. public function __construct($combinator, $value, $index = null, $currentFileInfo = null ){
  4486. $this->value = $value;
  4487. $this->value_is_object = is_object($value);
  4488. if( $combinator ){
  4489. $this->combinator = $combinator;
  4490. }
  4491. $this->index = $index;
  4492. $this->currentFileInfo = $currentFileInfo;
  4493. }
  4494. public function accept( $visitor ){
  4495. if( $this->value_is_object ){ //object or string
  4496. $this->value = $visitor->visitObj( $this->value );
  4497. }
  4498. }
  4499. public function compile($env){
  4500. if( Less_Environment::$mixin_stack ){
  4501. return new Less_Tree_Element($this->combinator, ($this->value_is_object ? $this->value->compile($env) : $this->value), $this->index, $this->currentFileInfo );
  4502. }
  4503. if( $this->value_is_object ){
  4504. $this->value = $this->value->compile($env);
  4505. }
  4506. return $this;
  4507. }
  4508. /**
  4509. * @see Less_Tree::genCSS
  4510. */
  4511. public function genCSS( $output ){
  4512. $output->add( $this->toCSS(), $this->currentFileInfo, $this->index );
  4513. }
  4514. public function toCSS(){
  4515. if( $this->value_is_object ){
  4516. $value = $this->value->toCSS();
  4517. }else{
  4518. $value = $this->value;
  4519. }
  4520. if( $value === '' && $this->combinator && $this->combinator === '&' ){
  4521. return '';
  4522. }
  4523. return Less_Environment::$_outputMap[$this->combinator] . $value;
  4524. }
  4525. }
  4526. /**
  4527. * Expression
  4528. *
  4529. * @package Less
  4530. * @subpackage tree
  4531. */
  4532. class Less_Tree_Expression extends Less_Tree{
  4533. public $value = array();
  4534. public $parens = false;
  4535. public $parensInOp = false;
  4536. public $type = 'Expression';
  4537. public function __construct( $value, $parens = null ){
  4538. $this->value = $value;
  4539. $this->parens = $parens;
  4540. }
  4541. public function accept( $visitor ){
  4542. $this->value = $visitor->visitArray( $this->value );
  4543. }
  4544. public function compile($env) {
  4545. $doubleParen = false;
  4546. if( $this->parens && !$this->parensInOp ){
  4547. Less_Environment::$parensStack++;
  4548. }
  4549. $returnValue = null;
  4550. if( $this->value ){
  4551. $count = count($this->value);
  4552. if( $count > 1 ){
  4553. $ret = array();
  4554. foreach($this->value as $e){
  4555. $ret[] = $e->compile($env);
  4556. }
  4557. $returnValue = new Less_Tree_Expression($ret);
  4558. }else{
  4559. if( ($this->value[0] instanceof Less_Tree_Expression) && $this->value[0]->parens && !$this->value[0]->parensInOp ){
  4560. $doubleParen = true;
  4561. }
  4562. $returnValue = $this->value[0]->compile($env);
  4563. }
  4564. } else {
  4565. $returnValue = $this;
  4566. }
  4567. if( $this->parens ){
  4568. if( !$this->parensInOp ){
  4569. Less_Environment::$parensStack--;
  4570. }elseif( !Less_Environment::isMathOn() && !$doubleParen ){
  4571. $returnValue = new Less_Tree_Paren($returnValue);
  4572. }
  4573. }
  4574. return $returnValue;
  4575. }
  4576. /**
  4577. * @see Less_Tree::genCSS
  4578. */
  4579. public function genCSS( $output ){
  4580. $val_len = count($this->value);
  4581. for( $i = 0; $i < $val_len; $i++ ){
  4582. $this->value[$i]->genCSS( $output );
  4583. if( $i + 1 < $val_len ){
  4584. $output->add( ' ' );
  4585. }
  4586. }
  4587. }
  4588. public function throwAwayComments() {
  4589. if( is_array($this->value) ){
  4590. $new_value = array();
  4591. foreach($this->value as $v){
  4592. if( $v instanceof Less_Tree_Comment ){
  4593. continue;
  4594. }
  4595. $new_value[] = $v;
  4596. }
  4597. $this->value = $new_value;
  4598. }
  4599. }
  4600. }
  4601. /**
  4602. * Extend
  4603. *
  4604. * @package Less
  4605. * @subpackage tree
  4606. */
  4607. class Less_Tree_Extend extends Less_Tree{
  4608. public $selector;
  4609. public $option;
  4610. public $index;
  4611. public $selfSelectors = array();
  4612. public $allowBefore;
  4613. public $allowAfter;
  4614. public $firstExtendOnThisSelectorPath;
  4615. public $type = 'Extend';
  4616. public $ruleset;
  4617. public $object_id;
  4618. public $parent_ids = array();
  4619. /**
  4620. * @param integer $index
  4621. */
  4622. public function __construct($selector, $option, $index){
  4623. static $i = 0;
  4624. $this->selector = $selector;
  4625. $this->option = $option;
  4626. $this->index = $index;
  4627. switch($option){
  4628. case "all":
  4629. $this->allowBefore = true;
  4630. $this->allowAfter = true;
  4631. break;
  4632. default:
  4633. $this->allowBefore = false;
  4634. $this->allowAfter = false;
  4635. break;
  4636. }
  4637. $this->object_id = $i++;
  4638. $this->parent_ids = array($this->object_id);
  4639. }
  4640. public function accept( $visitor ){
  4641. $this->selector = $visitor->visitObj( $this->selector );
  4642. }
  4643. public function compile( $env ){
  4644. Less_Parser::$has_extends = true;
  4645. $this->selector = $this->selector->compile($env);
  4646. return $this;
  4647. //return new Less_Tree_Extend( $this->selector->compile($env), $this->option, $this->index);
  4648. }
  4649. public function findSelfSelectors( $selectors ){
  4650. $selfElements = array();
  4651. for( $i = 0, $selectors_len = count($selectors); $i < $selectors_len; $i++ ){
  4652. $selectorElements = $selectors[$i]->elements;
  4653. // duplicate the logic in genCSS function inside the selector node.
  4654. // future TODO - move both logics into the selector joiner visitor
  4655. if( $i && $selectorElements && $selectorElements[0]->combinator === "") {
  4656. $selectorElements[0]->combinator = ' ';
  4657. }
  4658. $selfElements = array_merge( $selfElements, $selectors[$i]->elements );
  4659. }
  4660. $this->selfSelectors = array(new Less_Tree_Selector($selfElements));
  4661. }
  4662. }
  4663. /**
  4664. * CSS @import node
  4665. *
  4666. * The general strategy here is that we don't want to wait
  4667. * for the parsing to be completed, before we start importing
  4668. * the file. That's because in the context of a browser,
  4669. * most of the time will be spent waiting for the server to respond.
  4670. *
  4671. * On creation, we push the import path to our import queue, though
  4672. * `import,push`, we also pass it a callback, which it'll call once
  4673. * the file has been fetched, and parsed.
  4674. *
  4675. * @package Less
  4676. * @subpackage tree
  4677. */
  4678. class Less_Tree_Import extends Less_Tree{
  4679. public $options;
  4680. public $index;
  4681. public $path;
  4682. public $features;
  4683. public $currentFileInfo;
  4684. public $css;
  4685. public $skip;
  4686. public $root;
  4687. public $type = 'Import';
  4688. public function __construct($path, $features, $options, $index, $currentFileInfo = null ){
  4689. $this->options = $options;
  4690. $this->index = $index;
  4691. $this->path = $path;
  4692. $this->features = $features;
  4693. $this->currentFileInfo = $currentFileInfo;
  4694. if( is_array($options) ){
  4695. $this->options += array('inline'=>false);
  4696. if( isset($this->options['less']) || $this->options['inline'] ){
  4697. $this->css = !isset($this->options['less']) || !$this->options['less'] || $this->options['inline'];
  4698. } else {
  4699. $pathValue = $this->getPath();
  4700. if( $pathValue && preg_match('/css([\?;].*)?$/',$pathValue) ){
  4701. $this->css = true;
  4702. }
  4703. }
  4704. }
  4705. }
  4706. //
  4707. // The actual import node doesn't return anything, when converted to CSS.
  4708. // The reason is that it's used at the evaluation stage, so that the rules
  4709. // it imports can be treated like any other rules.
  4710. //
  4711. // In `eval`, we make sure all Import nodes get evaluated, recursively, so
  4712. // we end up with a flat structure, which can easily be imported in the parent
  4713. // ruleset.
  4714. //
  4715. public function accept($visitor){
  4716. if( $this->features ){
  4717. $this->features = $visitor->visitObj($this->features);
  4718. }
  4719. $this->path = $visitor->visitObj($this->path);
  4720. if( !$this->options['inline'] && $this->root ){
  4721. $this->root = $visitor->visit($this->root);
  4722. }
  4723. }
  4724. /**
  4725. * @see Less_Tree::genCSS
  4726. */
  4727. public function genCSS( $output ){
  4728. if( $this->css ){
  4729. $output->add( '@import ', $this->currentFileInfo, $this->index );
  4730. $this->path->genCSS( $output );
  4731. if( $this->features ){
  4732. $output->add( ' ' );
  4733. $this->features->genCSS( $output );
  4734. }
  4735. $output->add( ';' );
  4736. }
  4737. }
  4738. public function toCSS(){
  4739. $features = $this->features ? ' ' . $this->features->toCSS() : '';
  4740. if ($this->css) {
  4741. return "@import " . $this->path->toCSS() . $features . ";\n";
  4742. } else {
  4743. return "";
  4744. }
  4745. }
  4746. /**
  4747. * @return string
  4748. */
  4749. public function getPath(){
  4750. if ($this->path instanceof Less_Tree_Quoted) {
  4751. $path = $this->path->value;
  4752. $path = ( isset($this->css) || preg_match('/(\.[a-z]*$)|([\?;].*)$/',$path)) ? $path : $path . '.less';
  4753. } else if ($this->path instanceof Less_Tree_URL) {
  4754. $path = $this->path->value->value;
  4755. }else{
  4756. return null;
  4757. }
  4758. //remove query string and fragment
  4759. return preg_replace('/[\?#][^\?]*$/','',$path);
  4760. }
  4761. public function compileForImport( $env ){
  4762. return new Less_Tree_Import( $this->path->compile($env), $this->features, $this->options, $this->index, $this->currentFileInfo);
  4763. }
  4764. public function compilePath($env) {
  4765. $path = $this->path->compile($env);
  4766. $rootpath = '';
  4767. if( $this->currentFileInfo && $this->currentFileInfo['rootpath'] ){
  4768. $rootpath = $this->currentFileInfo['rootpath'];
  4769. }
  4770. if( !($path instanceof Less_Tree_URL) ){
  4771. if( $rootpath ){
  4772. $pathValue = $path->value;
  4773. // Add the base path if the import is relative
  4774. if( $pathValue && Less_Environment::isPathRelative($pathValue) ){
  4775. $path->value = $this->currentFileInfo['uri_root'].$pathValue;
  4776. }
  4777. }
  4778. $path->value = Less_Environment::normalizePath($path->value);
  4779. }
  4780. return $path;
  4781. }
  4782. public function compile( $env ){
  4783. $evald = $this->compileForImport($env);
  4784. //get path & uri
  4785. $path_and_uri = null;
  4786. if( is_callable(Less_Parser::$options['import_callback']) ){
  4787. $path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$evald);
  4788. }
  4789. if( !$path_and_uri ){
  4790. $path_and_uri = $evald->PathAndUri();
  4791. }
  4792. if( $path_and_uri ){
  4793. list($full_path, $uri) = $path_and_uri;
  4794. }else{
  4795. $full_path = $uri = $evald->getPath();
  4796. }
  4797. //import once
  4798. if( $evald->skip( $full_path, $env) ){
  4799. return array();
  4800. }
  4801. if( $this->options['inline'] ){
  4802. //todo needs to reference css file not import
  4803. //$contents = new Less_Tree_Anonymous($this->root, 0, array('filename'=>$this->importedFilename), true );
  4804. Less_Parser::AddParsedFile($full_path);
  4805. $contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
  4806. if( $this->features ){
  4807. return new Less_Tree_Media( array($contents), $this->features->value );
  4808. }
  4809. return array( $contents );
  4810. }
  4811. // css ?
  4812. if( $evald->css ){
  4813. $features = ( $evald->features ? $evald->features->compile($env) : null );
  4814. return new Less_Tree_Import( $this->compilePath( $env), $features, $this->options, $this->index);
  4815. }
  4816. return $this->ParseImport( $full_path, $uri, $env );
  4817. }
  4818. /**
  4819. * Using the import directories, get the full absolute path and uri of the import
  4820. *
  4821. * @param Less_Tree_Import $evald
  4822. */
  4823. public function PathAndUri(){
  4824. $evald_path = $this->getPath();
  4825. if( $evald_path ){
  4826. $import_dirs = array();
  4827. if( Less_Environment::isPathRelative($evald_path) ){
  4828. //if the path is relative, the file should be in the current directory
  4829. $import_dirs[ $this->currentFileInfo['currentDirectory'] ] = $this->currentFileInfo['uri_root'];
  4830. }else{
  4831. //otherwise, the file should be relative to the server root
  4832. $import_dirs[ $this->currentFileInfo['entryPath'] ] = $this->currentFileInfo['entryUri'];
  4833. //if the user supplied entryPath isn't the actual root
  4834. $import_dirs[ $_SERVER['DOCUMENT_ROOT'] ] = '';
  4835. }
  4836. // always look in user supplied import directories
  4837. $import_dirs = array_merge( $import_dirs, Less_Parser::$options['import_dirs'] );
  4838. foreach( $import_dirs as $rootpath => $rooturi){
  4839. if( is_callable($rooturi) ){
  4840. list($path, $uri) = call_user_func($rooturi, $evald_path);
  4841. if( is_string($path) ){
  4842. $full_path = $path;
  4843. return array( $full_path, $uri );
  4844. }
  4845. }elseif( !empty($rootpath) ){
  4846. if( $rooturi ){
  4847. if( strpos($evald_path,$rooturi) === 0 ){
  4848. $evald_path = substr( $evald_path, strlen($rooturi) );
  4849. }
  4850. }
  4851. $path = rtrim($rootpath,'/\\').'/'.ltrim($evald_path,'/\\');
  4852. if( file_exists($path) ){
  4853. $full_path = Less_Environment::normalizePath($path);
  4854. $uri = Less_Environment::normalizePath(dirname($rooturi.$evald_path));
  4855. return array( $full_path, $uri );
  4856. } elseif( file_exists($path.'.less') ){
  4857. $full_path = Less_Environment::normalizePath($path.'.less');
  4858. $uri = Less_Environment::normalizePath(dirname($rooturi.$evald_path.'.less'));
  4859. return array( $full_path, $uri );
  4860. }
  4861. }
  4862. }
  4863. }
  4864. }
  4865. /**
  4866. * Parse the import url and return the rules
  4867. *
  4868. * @return Less_Tree_Media|array
  4869. */
  4870. public function ParseImport( $full_path, $uri, $env ){
  4871. $import_env = clone $env;
  4872. if( (isset($this->options['reference']) && $this->options['reference']) || isset($this->currentFileInfo['reference']) ){
  4873. $import_env->currentFileInfo['reference'] = true;
  4874. }
  4875. if( (isset($this->options['multiple']) && $this->options['multiple']) ){
  4876. $import_env->importMultiple = true;
  4877. }
  4878. $parser = new Less_Parser($import_env);
  4879. $root = $parser->parseFile($full_path, $uri, true);
  4880. $ruleset = new Less_Tree_Ruleset(array(), $root->rules );
  4881. $ruleset->evalImports($import_env);
  4882. return $this->features ? new Less_Tree_Media($ruleset->rules, $this->features->value) : $ruleset->rules;
  4883. }
  4884. /**
  4885. * Should the import be skipped?
  4886. *
  4887. * @return boolean|null
  4888. */
  4889. private function Skip($path, $env){
  4890. $path = Less_Parser::winPath(realpath($path));
  4891. if( $path && Less_Parser::FileParsed($path) ){
  4892. if( isset($this->currentFileInfo['reference']) ){
  4893. return true;
  4894. }
  4895. return !isset($this->options['multiple']) && !$env->importMultiple;
  4896. }
  4897. }
  4898. }
  4899. /**
  4900. * Javascript
  4901. *
  4902. * @package Less
  4903. * @subpackage tree
  4904. */
  4905. class Less_Tree_Javascript extends Less_Tree{
  4906. public $type = 'Javascript';
  4907. public $escaped;
  4908. public $expression;
  4909. public $index;
  4910. /**
  4911. * @param boolean $index
  4912. * @param boolean $escaped
  4913. */
  4914. public function __construct($string, $index, $escaped){
  4915. $this->escaped = $escaped;
  4916. $this->expression = $string;
  4917. $this->index = $index;
  4918. }
  4919. public function compile(){
  4920. return new Less_Tree_Anonymous('/* Sorry, can not do JavaScript evaluation in PHP... :( */');
  4921. }
  4922. }
  4923. /**
  4924. * Keyword
  4925. *
  4926. * @package Less
  4927. * @subpackage tree
  4928. */
  4929. class Less_Tree_Keyword extends Less_Tree{
  4930. public $value;
  4931. public $type = 'Keyword';
  4932. /**
  4933. * @param string $value
  4934. */
  4935. public function __construct($value){
  4936. $this->value = $value;
  4937. }
  4938. public function compile(){
  4939. return $this;
  4940. }
  4941. /**
  4942. * @see Less_Tree::genCSS
  4943. */
  4944. public function genCSS( $output ){
  4945. if( $this->value === '%') {
  4946. throw new Less_Exception_Compiler("Invalid % without number");
  4947. }
  4948. $output->add( $this->value );
  4949. }
  4950. public function compare($other) {
  4951. if ($other instanceof Less_Tree_Keyword) {
  4952. return $other->value === $this->value ? 0 : 1;
  4953. } else {
  4954. return -1;
  4955. }
  4956. }
  4957. }
  4958. /**
  4959. * Media
  4960. *
  4961. * @package Less
  4962. * @subpackage tree
  4963. */
  4964. class Less_Tree_Media extends Less_Tree{
  4965. public $features;
  4966. public $rules;
  4967. public $index;
  4968. public $currentFileInfo;
  4969. public $isReferenced;
  4970. public $type = 'Media';
  4971. public function __construct($value = array(), $features = array(), $index = null, $currentFileInfo = null ){
  4972. $this->index = $index;
  4973. $this->currentFileInfo = $currentFileInfo;
  4974. $selectors = $this->emptySelectors();
  4975. $this->features = new Less_Tree_Value($features);
  4976. $this->rules = array(new Less_Tree_Ruleset($selectors, $value));
  4977. $this->rules[0]->allowImports = true;
  4978. }
  4979. public function accept( $visitor ){
  4980. $this->features = $visitor->visitObj($this->features);
  4981. $this->rules = $visitor->visitArray($this->rules);
  4982. }
  4983. /**
  4984. * @see Less_Tree::genCSS
  4985. */
  4986. public function genCSS( $output ){
  4987. $output->add( '@media ', $this->currentFileInfo, $this->index );
  4988. $this->features->genCSS( $output );
  4989. Less_Tree::outputRuleset( $output, $this->rules);
  4990. }
  4991. public function compile($env) {
  4992. $media = new Less_Tree_Media(array(), array(), $this->index, $this->currentFileInfo );
  4993. $strictMathBypass = false;
  4994. if( Less_Parser::$options['strictMath'] === false) {
  4995. $strictMathBypass = true;
  4996. Less_Parser::$options['strictMath'] = true;
  4997. }
  4998. $media->features = $this->features->compile($env);
  4999. if( $strictMathBypass ){
  5000. Less_Parser::$options['strictMath'] = false;
  5001. }
  5002. $env->mediaPath[] = $media;
  5003. $env->mediaBlocks[] = $media;
  5004. array_unshift($env->frames, $this->rules[0]);
  5005. $media->rules = array($this->rules[0]->compile($env));
  5006. array_shift($env->frames);
  5007. array_pop($env->mediaPath);
  5008. return !$env->mediaPath ? $media->compileTop($env) : $media->compileNested($env);
  5009. }
  5010. public function variable($name) {
  5011. return $this->rules[0]->variable($name);
  5012. }
  5013. public function find($selector) {
  5014. return $this->rules[0]->find($selector, $this);
  5015. }
  5016. public function emptySelectors(){
  5017. $el = new Less_Tree_Element('','&', $this->index, $this->currentFileInfo );
  5018. $sels = array( new Less_Tree_Selector(array($el), array(), null, $this->index, $this->currentFileInfo) );
  5019. $sels[0]->mediaEmpty = true;
  5020. return $sels;
  5021. }
  5022. public function markReferenced(){
  5023. $this->rules[0]->markReferenced();
  5024. $this->isReferenced = true;
  5025. Less_Tree::ReferencedArray($this->rules[0]->rules);
  5026. }
  5027. // evaltop
  5028. public function compileTop($env) {
  5029. $result = $this;
  5030. if (count($env->mediaBlocks) > 1) {
  5031. $selectors = $this->emptySelectors();
  5032. $result = new Less_Tree_Ruleset($selectors, $env->mediaBlocks);
  5033. $result->multiMedia = true;
  5034. }
  5035. $env->mediaBlocks = array();
  5036. $env->mediaPath = array();
  5037. return $result;
  5038. }
  5039. public function compileNested($env) {
  5040. $path = array_merge($env->mediaPath, array($this));
  5041. // Extract the media-query conditions separated with `,` (OR).
  5042. foreach ($path as $key => $p) {
  5043. $value = $p->features instanceof Less_Tree_Value ? $p->features->value : $p->features;
  5044. $path[$key] = is_array($value) ? $value : array($value);
  5045. }
  5046. // Trace all permutations to generate the resulting media-query.
  5047. //
  5048. // (a, b and c) with nested (d, e) ->
  5049. // a and d
  5050. // a and e
  5051. // b and c and d
  5052. // b and c and e
  5053. $permuted = $this->permute($path);
  5054. $expressions = array();
  5055. foreach($permuted as $path){
  5056. for( $i=0, $len=count($path); $i < $len; $i++){
  5057. $path[$i] = Less_Parser::is_method($path[$i], 'toCSS') ? $path[$i] : new Less_Tree_Anonymous($path[$i]);
  5058. }
  5059. for( $i = count($path) - 1; $i > 0; $i-- ){
  5060. array_splice($path, $i, 0, array(new Less_Tree_Anonymous('and')));
  5061. }
  5062. $expressions[] = new Less_Tree_Expression($path);
  5063. }
  5064. $this->features = new Less_Tree_Value($expressions);
  5065. // Fake a tree-node that doesn't output anything.
  5066. return new Less_Tree_Ruleset(array(), array());
  5067. }
  5068. public function permute($arr) {
  5069. if (!$arr)
  5070. return array();
  5071. if (count($arr) == 1)
  5072. return $arr[0];
  5073. $result = array();
  5074. $rest = $this->permute(array_slice($arr, 1));
  5075. foreach ($rest as $r) {
  5076. foreach ($arr[0] as $a) {
  5077. $result[] = array_merge(
  5078. is_array($a) ? $a : array($a),
  5079. is_array($r) ? $r : array($r)
  5080. );
  5081. }
  5082. }
  5083. return $result;
  5084. }
  5085. public function bubbleSelectors($selectors) {
  5086. if( !$selectors) return;
  5087. $this->rules = array(new Less_Tree_Ruleset( $selectors, array($this->rules[0])));
  5088. }
  5089. }
  5090. /**
  5091. * A simple css name-value pair
  5092. * ex: width:100px;
  5093. *
  5094. * In bootstrap, there are about 600-1,000 simple name-value pairs (depending on how forgiving the match is) -vs- 6,020 dynamic rules (Less_Tree_Rule)
  5095. * Using the name-value object can speed up bootstrap compilation slightly, but it breaks color keyword interpretation: color:red -> color:#FF0000;
  5096. *
  5097. * @package Less
  5098. * @subpackage tree
  5099. */
  5100. class Less_Tree_NameValue extends Less_Tree{
  5101. public $name;
  5102. public $value;
  5103. public $index;
  5104. public $currentFileInfo;
  5105. public $type = 'NameValue';
  5106. public function __construct($name, $value = null, $index = null, $currentFileInfo = null ){
  5107. $this->name = $name;
  5108. $this->value = $value;
  5109. $this->index = $index;
  5110. $this->currentFileInfo = $currentFileInfo;
  5111. }
  5112. public function genCSS( $output ){
  5113. $output->add(
  5114. $this->name
  5115. . Less_Environment::$_outputMap[': ']
  5116. . $this->value
  5117. . (((Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";")
  5118. , $this->currentFileInfo, $this->index);
  5119. }
  5120. public function compile ($env){
  5121. return $this;
  5122. }
  5123. }
  5124. /**
  5125. * Negative
  5126. *
  5127. * @package Less
  5128. * @subpackage tree
  5129. */
  5130. class Less_Tree_Negative extends Less_Tree{
  5131. public $value;
  5132. public $type = 'Negative';
  5133. public function __construct($node){
  5134. $this->value = $node;
  5135. }
  5136. //function accept($visitor) {
  5137. // $this->value = $visitor->visit($this->value);
  5138. //}
  5139. /**
  5140. * @see Less_Tree::genCSS
  5141. */
  5142. public function genCSS( $output ){
  5143. $output->add( '-' );
  5144. $this->value->genCSS( $output );
  5145. }
  5146. public function compile($env) {
  5147. if( Less_Environment::isMathOn() ){
  5148. $ret = new Less_Tree_Operation('*', array( new Less_Tree_Dimension(-1), $this->value ) );
  5149. return $ret->compile($env);
  5150. }
  5151. return new Less_Tree_Negative( $this->value->compile($env) );
  5152. }
  5153. }
  5154. /**
  5155. * Operation
  5156. *
  5157. * @package Less
  5158. * @subpackage tree
  5159. */
  5160. class Less_Tree_Operation extends Less_Tree{
  5161. public $op;
  5162. public $operands;
  5163. public $isSpaced;
  5164. public $type = 'Operation';
  5165. /**
  5166. * @param string $op
  5167. */
  5168. public function __construct($op, $operands, $isSpaced = false){
  5169. $this->op = trim($op);
  5170. $this->operands = $operands;
  5171. $this->isSpaced = $isSpaced;
  5172. }
  5173. public function accept($visitor) {
  5174. $this->operands = $visitor->visitArray($this->operands);
  5175. }
  5176. public function compile($env){
  5177. $a = $this->operands[0]->compile($env);
  5178. $b = $this->operands[1]->compile($env);
  5179. if( Less_Environment::isMathOn() ){
  5180. if( $a instanceof Less_Tree_Dimension && $b instanceof Less_Tree_Color ){
  5181. $a = $a->toColor();
  5182. }elseif( $b instanceof Less_Tree_Dimension && $a instanceof Less_Tree_Color ){
  5183. $b = $b->toColor();
  5184. }
  5185. if( !method_exists($a,'operate') ){
  5186. throw new Less_Exception_Compiler("Operation on an invalid type");
  5187. }
  5188. return $a->operate( $this->op, $b);
  5189. }
  5190. return new Less_Tree_Operation($this->op, array($a, $b), $this->isSpaced );
  5191. }
  5192. /**
  5193. * @see Less_Tree::genCSS
  5194. */
  5195. public function genCSS( $output ){
  5196. $this->operands[0]->genCSS( $output );
  5197. if( $this->isSpaced ){
  5198. $output->add( " " );
  5199. }
  5200. $output->add( $this->op );
  5201. if( $this->isSpaced ){
  5202. $output->add( ' ' );
  5203. }
  5204. $this->operands[1]->genCSS( $output );
  5205. }
  5206. }
  5207. /**
  5208. * Paren
  5209. *
  5210. * @package Less
  5211. * @subpackage tree
  5212. */
  5213. class Less_Tree_Paren extends Less_Tree{
  5214. public $value;
  5215. public $type = 'Paren';
  5216. public function __construct($value) {
  5217. $this->value = $value;
  5218. }
  5219. public function accept($visitor){
  5220. $this->value = $visitor->visitObj($this->value);
  5221. }
  5222. /**
  5223. * @see Less_Tree::genCSS
  5224. */
  5225. public function genCSS( $output ){
  5226. $output->add( '(' );
  5227. $this->value->genCSS( $output );
  5228. $output->add( ')' );
  5229. }
  5230. public function compile($env) {
  5231. return new Less_Tree_Paren($this->value->compile($env));
  5232. }
  5233. }
  5234. /**
  5235. * Quoted
  5236. *
  5237. * @package Less
  5238. * @subpackage tree
  5239. */
  5240. class Less_Tree_Quoted extends Less_Tree{
  5241. public $escaped;
  5242. public $value;
  5243. public $quote;
  5244. public $index;
  5245. public $currentFileInfo;
  5246. public $type = 'Quoted';
  5247. /**
  5248. * @param string $str
  5249. */
  5250. public function __construct($str, $content = '', $escaped = false, $index = false, $currentFileInfo = null ){
  5251. $this->escaped = $escaped;
  5252. $this->value = $content;
  5253. if( $str ){
  5254. $this->quote = $str[0];
  5255. }
  5256. $this->index = $index;
  5257. $this->currentFileInfo = $currentFileInfo;
  5258. }
  5259. /**
  5260. * @see Less_Tree::genCSS
  5261. */
  5262. public function genCSS( $output ){
  5263. if( !$this->escaped ){
  5264. $output->add( $this->quote, $this->currentFileInfo, $this->index );
  5265. }
  5266. $output->add( $this->value );
  5267. if( !$this->escaped ){
  5268. $output->add( $this->quote );
  5269. }
  5270. }
  5271. public function compile($env){
  5272. $value = $this->value;
  5273. if( preg_match_all('/`([^`]+)`/', $this->value, $matches) ){
  5274. foreach($matches as $i => $match){
  5275. $js = new Less_Tree_JavaScript($matches[1], $this->index, true);
  5276. $js = $js->compile()->value;
  5277. $value = str_replace($matches[0][$i], $js, $value);
  5278. }
  5279. }
  5280. if( preg_match_all('/@\{([\w-]+)\}/',$value,$matches) ){
  5281. foreach($matches[1] as $i => $match){
  5282. $v = new Less_Tree_Variable('@' . $match, $this->index, $this->currentFileInfo );
  5283. $v = $v->compile($env);
  5284. $v = ($v instanceof Less_Tree_Quoted) ? $v->value : $v->toCSS();
  5285. $value = str_replace($matches[0][$i], $v, $value);
  5286. }
  5287. }
  5288. return new Less_Tree_Quoted($this->quote . $value . $this->quote, $value, $this->escaped, $this->index, $this->currentFileInfo);
  5289. }
  5290. public function compare($x) {
  5291. if( !Less_Parser::is_method($x, 'toCSS') ){
  5292. return -1;
  5293. }
  5294. $left = $this->toCSS();
  5295. $right = $x->toCSS();
  5296. if ($left === $right) {
  5297. return 0;
  5298. }
  5299. return $left < $right ? -1 : 1;
  5300. }
  5301. }
  5302. /**
  5303. * Rule
  5304. *
  5305. * @package Less
  5306. * @subpackage tree
  5307. */
  5308. class Less_Tree_Rule extends Less_Tree{
  5309. public $name;
  5310. public $value;
  5311. public $important;
  5312. public $merge;
  5313. public $index;
  5314. public $inline;
  5315. public $variable;
  5316. public $currentFileInfo;
  5317. public $type = 'Rule';
  5318. /**
  5319. * @param string $important
  5320. */
  5321. public function __construct($name, $value = null, $important = null, $merge = null, $index = null, $currentFileInfo = null, $inline = false){
  5322. $this->name = $name;
  5323. $this->value = ($value instanceof Less_Tree_Value || $value instanceof Less_Tree_Ruleset) ? $value : new Less_Tree_Value(array($value));
  5324. $this->important = $important ? ' ' . trim($important) : '';
  5325. $this->merge = $merge;
  5326. $this->index = $index;
  5327. $this->currentFileInfo = $currentFileInfo;
  5328. $this->inline = $inline;
  5329. $this->variable = ( is_string($name) && $name[0] === '@');
  5330. }
  5331. public function accept($visitor) {
  5332. $this->value = $visitor->visitObj( $this->value );
  5333. }
  5334. /**
  5335. * @see Less_Tree::genCSS
  5336. */
  5337. public function genCSS( $output ){
  5338. $output->add( $this->name . Less_Environment::$_outputMap[': '], $this->currentFileInfo, $this->index);
  5339. try{
  5340. $this->value->genCSS( $output);
  5341. }catch( Less_Exception_Parser $e ){
  5342. $e->index = $this->index;
  5343. $e->currentFile = $this->currentFileInfo;
  5344. throw $e;
  5345. }
  5346. $output->add( $this->important . (($this->inline || (Less_Environment::$lastRule && Less_Parser::$options['compress'])) ? "" : ";"), $this->currentFileInfo, $this->index);
  5347. }
  5348. public function compile ($env){
  5349. $name = $this->name;
  5350. if( is_array($name) ){
  5351. // expand 'primitive' name directly to get
  5352. // things faster (~10% for benchmark.less):
  5353. if( count($name) === 1 && $name[0] instanceof Less_Tree_Keyword ){
  5354. $name = $name[0]->value;
  5355. }else{
  5356. $name = $this->CompileName($env,$name);
  5357. }
  5358. }
  5359. $strictMathBypass = Less_Parser::$options['strictMath'];
  5360. if( $name === "font" && !Less_Parser::$options['strictMath'] ){
  5361. Less_Parser::$options['strictMath'] = true;
  5362. }
  5363. try {
  5364. $evaldValue = $this->value->compile($env);
  5365. if( !$this->variable && $evaldValue->type === "DetachedRuleset") {
  5366. throw new Less_Exception_Compiler("Rulesets cannot be evaluated on a property.", null, $this->index, $this->currentFileInfo);
  5367. }
  5368. if( Less_Environment::$mixin_stack ){
  5369. $return = new Less_Tree_Rule($name, $evaldValue, $this->important, $this->merge, $this->index, $this->currentFileInfo, $this->inline);
  5370. }else{
  5371. $this->name = $name;
  5372. $this->value = $evaldValue;
  5373. $return = $this;
  5374. }
  5375. }catch( Less_Exception_Parser $e ){
  5376. if( !is_numeric($e->index) ){
  5377. $e->index = $this->index;
  5378. $e->currentFile = $this->currentFileInfo;
  5379. }
  5380. throw $e;
  5381. }
  5382. Less_Parser::$options['strictMath'] = $strictMathBypass;
  5383. return $return;
  5384. }
  5385. public function CompileName( $env, $name ){
  5386. $output = new Less_Output();
  5387. foreach($name as $n){
  5388. $n->compile($env)->genCSS($output);
  5389. }
  5390. return $output->toString();
  5391. }
  5392. public function makeImportant(){
  5393. return new Less_Tree_Rule($this->name, $this->value, '!important', $this->merge, $this->index, $this->currentFileInfo, $this->inline);
  5394. }
  5395. }
  5396. /**
  5397. * Ruleset
  5398. *
  5399. * @package Less
  5400. * @subpackage tree
  5401. */
  5402. class Less_Tree_Ruleset extends Less_Tree{
  5403. protected $lookups;
  5404. public $_variables;
  5405. public $_rulesets;
  5406. public $strictImports;
  5407. public $selectors;
  5408. public $rules;
  5409. public $root;
  5410. public $allowImports;
  5411. public $paths;
  5412. public $firstRoot;
  5413. public $type = 'Ruleset';
  5414. public $multiMedia;
  5415. public $allExtends;
  5416. public $ruleset_id;
  5417. public $originalRuleset;
  5418. public $first_oelements;
  5419. public function SetRulesetIndex(){
  5420. $this->ruleset_id = Less_Parser::$next_id++;
  5421. $this->originalRuleset = $this->ruleset_id;
  5422. if( $this->selectors ){
  5423. foreach($this->selectors as $sel){
  5424. if( $sel->_oelements ){
  5425. $this->first_oelements[$sel->_oelements[0]] = true;
  5426. }
  5427. }
  5428. }
  5429. }
  5430. public function __construct($selectors, $rules, $strictImports = null){
  5431. $this->selectors = $selectors;
  5432. $this->rules = $rules;
  5433. $this->lookups = array();
  5434. $this->strictImports = $strictImports;
  5435. $this->SetRulesetIndex();
  5436. }
  5437. public function accept( $visitor ){
  5438. if( $this->paths ){
  5439. $paths_len = count($this->paths);
  5440. for($i = 0,$paths_len; $i < $paths_len; $i++ ){
  5441. $this->paths[$i] = $visitor->visitArray($this->paths[$i]);
  5442. }
  5443. }elseif( $this->selectors ){
  5444. $this->selectors = $visitor->visitArray($this->selectors);
  5445. }
  5446. if( $this->rules ){
  5447. $this->rules = $visitor->visitArray($this->rules);
  5448. }
  5449. }
  5450. public function compile($env){
  5451. $ruleset = $this->PrepareRuleset($env);
  5452. // Store the frames around mixin definitions,
  5453. // so they can be evaluated like closures when the time comes.
  5454. $rsRuleCnt = count($ruleset->rules);
  5455. for( $i = 0; $i < $rsRuleCnt; $i++ ){
  5456. if( $ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset ){
  5457. $ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
  5458. }
  5459. }
  5460. $mediaBlockCount = 0;
  5461. if( $env instanceof Less_Environment ){
  5462. $mediaBlockCount = count($env->mediaBlocks);
  5463. }
  5464. // Evaluate mixin calls.
  5465. $this->EvalMixinCalls( $ruleset, $env, $rsRuleCnt );
  5466. // Evaluate everything else
  5467. for( $i=0; $i<$rsRuleCnt; $i++ ){
  5468. if(! ($ruleset->rules[$i] instanceof Less_Tree_Mixin_Definition || $ruleset->rules[$i] instanceof Less_Tree_DetachedRuleset) ){
  5469. $ruleset->rules[$i] = $ruleset->rules[$i]->compile($env);
  5470. }
  5471. }
  5472. // Evaluate everything else
  5473. for( $i=0; $i<$rsRuleCnt; $i++ ){
  5474. $rule = $ruleset->rules[$i];
  5475. // for rulesets, check if it is a css guard and can be removed
  5476. if( $rule instanceof Less_Tree_Ruleset && $rule->selectors && count($rule->selectors) === 1 ){
  5477. // check if it can be folded in (e.g. & where)
  5478. if( $rule->selectors[0]->isJustParentSelector() ){
  5479. array_splice($ruleset->rules,$i--,1);
  5480. $rsRuleCnt--;
  5481. for($j = 0; $j < count($rule->rules); $j++ ){
  5482. $subRule = $rule->rules[$j];
  5483. if( !($subRule instanceof Less_Tree_Rule) || !$subRule->variable ){
  5484. array_splice($ruleset->rules, ++$i, 0, array($subRule));
  5485. $rsRuleCnt++;
  5486. }
  5487. }
  5488. }
  5489. }
  5490. }
  5491. // Pop the stack
  5492. $env->shiftFrame();
  5493. if ($mediaBlockCount) {
  5494. $len = count($env->mediaBlocks);
  5495. for($i = $mediaBlockCount; $i < $len; $i++ ){
  5496. $env->mediaBlocks[$i]->bubbleSelectors($ruleset->selectors);
  5497. }
  5498. }
  5499. return $ruleset;
  5500. }
  5501. /**
  5502. * Compile Less_Tree_Mixin_Call objects
  5503. *
  5504. * @param Less_Tree_Ruleset $ruleset
  5505. * @param integer $rsRuleCnt
  5506. */
  5507. private function EvalMixinCalls( $ruleset, $env, &$rsRuleCnt ){
  5508. for($i=0; $i < $rsRuleCnt; $i++){
  5509. $rule = $ruleset->rules[$i];
  5510. if( $rule instanceof Less_Tree_Mixin_Call ){
  5511. $rule = $rule->compile($env);
  5512. $temp = array();
  5513. foreach($rule as $r){
  5514. if( ($r instanceof Less_Tree_Rule) && $r->variable ){
  5515. // do not pollute the scope if the variable is
  5516. // already there. consider returning false here
  5517. // but we need a way to "return" variable from mixins
  5518. if( !$ruleset->variable($r->name) ){
  5519. $temp[] = $r;
  5520. }
  5521. }else{
  5522. $temp[] = $r;
  5523. }
  5524. }
  5525. $temp_count = count($temp)-1;
  5526. array_splice($ruleset->rules, $i, 1, $temp);
  5527. $rsRuleCnt += $temp_count;
  5528. $i += $temp_count;
  5529. $ruleset->resetCache();
  5530. }elseif( $rule instanceof Less_Tree_RulesetCall ){
  5531. $rule = $rule->compile($env);
  5532. $rules = array();
  5533. foreach($rule->rules as $r){
  5534. if( ($r instanceof Less_Tree_Rule) && $r->variable ){
  5535. continue;
  5536. }
  5537. $rules[] = $r;
  5538. }
  5539. array_splice($ruleset->rules, $i, 1, $rules);
  5540. $temp_count = count($rules);
  5541. $rsRuleCnt += $temp_count - 1;
  5542. $i += $temp_count-1;
  5543. $ruleset->resetCache();
  5544. }
  5545. }
  5546. }
  5547. /**
  5548. * Compile the selectors and create a new ruleset object for the compile() method
  5549. *
  5550. */
  5551. private function PrepareRuleset($env){
  5552. $hasOnePassingSelector = false;
  5553. $selectors = array();
  5554. if( $this->selectors ){
  5555. Less_Tree_DefaultFunc::error("it is currently only allowed in parametric mixin guards,");
  5556. foreach($this->selectors as $s){
  5557. $selector = $s->compile($env);
  5558. $selectors[] = $selector;
  5559. if( $selector->evaldCondition ){
  5560. $hasOnePassingSelector = true;
  5561. }
  5562. }
  5563. Less_Tree_DefaultFunc::reset();
  5564. } else {
  5565. $hasOnePassingSelector = true;
  5566. }
  5567. if( $this->rules && $hasOnePassingSelector ){
  5568. $rules = $this->rules;
  5569. }else{
  5570. $rules = array();
  5571. }
  5572. $ruleset = new Less_Tree_Ruleset($selectors, $rules, $this->strictImports);
  5573. $ruleset->originalRuleset = $this->ruleset_id;
  5574. $ruleset->root = $this->root;
  5575. $ruleset->firstRoot = $this->firstRoot;
  5576. $ruleset->allowImports = $this->allowImports;
  5577. // push the current ruleset to the frames stack
  5578. $env->unshiftFrame($ruleset);
  5579. // Evaluate imports
  5580. if( $ruleset->root || $ruleset->allowImports || !$ruleset->strictImports ){
  5581. $ruleset->evalImports($env);
  5582. }
  5583. return $ruleset;
  5584. }
  5585. function evalImports($env) {
  5586. $rules_len = count($this->rules);
  5587. for($i=0; $i < $rules_len; $i++){
  5588. $rule = $this->rules[$i];
  5589. if( $rule instanceof Less_Tree_Import ){
  5590. $rules = $rule->compile($env);
  5591. if( is_array($rules) ){
  5592. array_splice($this->rules, $i, 1, $rules);
  5593. $temp_count = count($rules)-1;
  5594. $i += $temp_count;
  5595. $rules_len += $temp_count;
  5596. }else{
  5597. array_splice($this->rules, $i, 1, array($rules));
  5598. }
  5599. $this->resetCache();
  5600. }
  5601. }
  5602. }
  5603. function makeImportant(){
  5604. $important_rules = array();
  5605. foreach($this->rules as $rule){
  5606. if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_Ruleset ){
  5607. $important_rules[] = $rule->makeImportant();
  5608. }else{
  5609. $important_rules[] = $rule;
  5610. }
  5611. }
  5612. return new Less_Tree_Ruleset($this->selectors, $important_rules, $this->strictImports );
  5613. }
  5614. public function matchArgs($args){
  5615. return !$args;
  5616. }
  5617. // lets you call a css selector with a guard
  5618. public function matchCondition( $args, $env ){
  5619. $lastSelector = end($this->selectors);
  5620. if( !$lastSelector->evaldCondition ){
  5621. return false;
  5622. }
  5623. if( $lastSelector->condition && !$lastSelector->condition->compile( $env->copyEvalEnv( $env->frames ) ) ){
  5624. return false;
  5625. }
  5626. return true;
  5627. }
  5628. function resetCache(){
  5629. $this->_rulesets = null;
  5630. $this->_variables = null;
  5631. $this->lookups = array();
  5632. }
  5633. public function variables(){
  5634. $this->_variables = array();
  5635. foreach( $this->rules as $r){
  5636. if ($r instanceof Less_Tree_Rule && $r->variable === true) {
  5637. $this->_variables[$r->name] = $r;
  5638. }
  5639. }
  5640. }
  5641. public function variable($name){
  5642. if( is_null($this->_variables) ){
  5643. $this->variables();
  5644. }
  5645. return isset($this->_variables[$name]) ? $this->_variables[$name] : null;
  5646. }
  5647. public function find( $selector, $self = null ){
  5648. $key = implode(' ',$selector->_oelements);
  5649. if( !isset($this->lookups[$key]) ){
  5650. if( !$self ){
  5651. $self = $this->ruleset_id;
  5652. }
  5653. $this->lookups[$key] = array();
  5654. $first_oelement = $selector->_oelements[0];
  5655. foreach($this->rules as $rule){
  5656. if( $rule instanceof Less_Tree_Ruleset && $rule->ruleset_id != $self ){
  5657. if( isset($rule->first_oelements[$first_oelement]) ){
  5658. foreach( $rule->selectors as $ruleSelector ){
  5659. $match = $selector->match($ruleSelector);
  5660. if( $match ){
  5661. if( $selector->elements_len > $match ){
  5662. $this->lookups[$key] = array_merge($this->lookups[$key], $rule->find( new Less_Tree_Selector(array_slice($selector->elements, $match)), $self));
  5663. } else {
  5664. $this->lookups[$key][] = $rule;
  5665. }
  5666. break;
  5667. }
  5668. }
  5669. }
  5670. }
  5671. }
  5672. }
  5673. return $this->lookups[$key];
  5674. }
  5675. /**
  5676. * @see Less_Tree::genCSS
  5677. */
  5678. public function genCSS( $output ){
  5679. if( !$this->root ){
  5680. Less_Environment::$tabLevel++;
  5681. }
  5682. $tabRuleStr = $tabSetStr = '';
  5683. if( !Less_Parser::$options['compress'] ){
  5684. if( Less_Environment::$tabLevel ){
  5685. $tabRuleStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel );
  5686. $tabSetStr = "\n".str_repeat( ' ' , Less_Environment::$tabLevel-1 );
  5687. }else{
  5688. $tabSetStr = $tabRuleStr = "\n";
  5689. }
  5690. }
  5691. $ruleNodes = array();
  5692. $rulesetNodes = array();
  5693. foreach($this->rules as $rule){
  5694. $class = get_class($rule);
  5695. if( ($class === 'Less_Tree_Media') || ($class === 'Less_Tree_Directive') || ($this->root && $class === 'Less_Tree_Comment') || ($class === 'Less_Tree_Ruleset' && $rule->rules) ){
  5696. $rulesetNodes[] = $rule;
  5697. }else{
  5698. $ruleNodes[] = $rule;
  5699. }
  5700. }
  5701. // If this is the root node, we don't render
  5702. // a selector, or {}.
  5703. if( !$this->root ){
  5704. /*
  5705. debugInfo = tree.debugInfo(env, this, tabSetStr);
  5706. if (debugInfo) {
  5707. output.add(debugInfo);
  5708. output.add(tabSetStr);
  5709. }
  5710. */
  5711. $paths_len = count($this->paths);
  5712. for( $i = 0; $i < $paths_len; $i++ ){
  5713. $path = $this->paths[$i];
  5714. $firstSelector = true;
  5715. foreach($path as $p){
  5716. $p->genCSS( $output, $firstSelector );
  5717. $firstSelector = false;
  5718. }
  5719. if( $i + 1 < $paths_len ){
  5720. $output->add( ',' . $tabSetStr );
  5721. }
  5722. }
  5723. $output->add( (Less_Parser::$options['compress'] ? '{' : " {") . $tabRuleStr );
  5724. }
  5725. // Compile rules and rulesets
  5726. $ruleNodes_len = count($ruleNodes);
  5727. $rulesetNodes_len = count($rulesetNodes);
  5728. for( $i = 0; $i < $ruleNodes_len; $i++ ){
  5729. $rule = $ruleNodes[$i];
  5730. // @page{ directive ends up with root elements inside it, a mix of rules and rulesets
  5731. // In this instance we do not know whether it is the last property
  5732. if( $i + 1 === $ruleNodes_len && (!$this->root || $rulesetNodes_len === 0 || $this->firstRoot ) ){
  5733. Less_Environment::$lastRule = true;
  5734. }
  5735. $rule->genCSS( $output );
  5736. if( !Less_Environment::$lastRule ){
  5737. $output->add( $tabRuleStr );
  5738. }else{
  5739. Less_Environment::$lastRule = false;
  5740. }
  5741. }
  5742. if( !$this->root ){
  5743. $output->add( $tabSetStr . '}' );
  5744. Less_Environment::$tabLevel--;
  5745. }
  5746. $firstRuleset = true;
  5747. $space = ($this->root ? $tabRuleStr : $tabSetStr);
  5748. for( $i = 0; $i < $rulesetNodes_len; $i++ ){
  5749. if( $ruleNodes_len && $firstRuleset ){
  5750. $output->add( $space );
  5751. }elseif( !$firstRuleset ){
  5752. $output->add( $space );
  5753. }
  5754. $firstRuleset = false;
  5755. $rulesetNodes[$i]->genCSS( $output);
  5756. }
  5757. if( !Less_Parser::$options['compress'] && $this->firstRoot ){
  5758. $output->add( "\n" );
  5759. }
  5760. }
  5761. function markReferenced(){
  5762. if( !$this->selectors ){
  5763. return;
  5764. }
  5765. foreach($this->selectors as $selector){
  5766. $selector->markReferenced();
  5767. }
  5768. }
  5769. public function joinSelectors( $context, $selectors ){
  5770. $paths = array();
  5771. if( is_array($selectors) ){
  5772. foreach($selectors as $selector) {
  5773. $this->joinSelector( $paths, $context, $selector);
  5774. }
  5775. }
  5776. return $paths;
  5777. }
  5778. public function joinSelector( &$paths, $context, $selector){
  5779. $hasParentSelector = false;
  5780. foreach($selector->elements as $el) {
  5781. if( $el->value === '&') {
  5782. $hasParentSelector = true;
  5783. }
  5784. }
  5785. if( !$hasParentSelector ){
  5786. if( $context ){
  5787. foreach($context as $context_el){
  5788. $paths[] = array_merge($context_el, array($selector) );
  5789. }
  5790. }else {
  5791. $paths[] = array($selector);
  5792. }
  5793. return;
  5794. }
  5795. // The paths are [[Selector]]
  5796. // The first list is a list of comma seperated selectors
  5797. // The inner list is a list of inheritance seperated selectors
  5798. // e.g.
  5799. // .a, .b {
  5800. // .c {
  5801. // }
  5802. // }
  5803. // == [[.a] [.c]] [[.b] [.c]]
  5804. //
  5805. // the elements from the current selector so far
  5806. $currentElements = array();
  5807. // the current list of new selectors to add to the path.
  5808. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
  5809. // by the parents
  5810. $newSelectors = array(array());
  5811. foreach( $selector->elements as $el){
  5812. // non parent reference elements just get added
  5813. if( $el->value !== '&' ){
  5814. $currentElements[] = $el;
  5815. } else {
  5816. // the new list of selectors to add
  5817. $selectorsMultiplied = array();
  5818. // merge the current list of non parent selector elements
  5819. // on to the current list of selectors to add
  5820. if( $currentElements ){
  5821. $this->mergeElementsOnToSelectors( $currentElements, $newSelectors);
  5822. }
  5823. // loop through our current selectors
  5824. foreach($newSelectors as $sel){
  5825. // if we don't have any parent paths, the & might be in a mixin so that it can be used
  5826. // whether there are parents or not
  5827. if( !$context ){
  5828. // the combinator used on el should now be applied to the next element instead so that
  5829. // it is not lost
  5830. if( $sel ){
  5831. $sel[0]->elements = array_slice($sel[0]->elements,0);
  5832. $sel[0]->elements[] = new Less_Tree_Element($el->combinator, '', $el->index, $el->currentFileInfo );
  5833. }
  5834. $selectorsMultiplied[] = $sel;
  5835. }else {
  5836. // and the parent selectors
  5837. foreach($context as $parentSel){
  5838. // We need to put the current selectors
  5839. // then join the last selector's elements on to the parents selectors
  5840. // our new selector path
  5841. $newSelectorPath = array();
  5842. // selectors from the parent after the join
  5843. $afterParentJoin = array();
  5844. $newJoinedSelectorEmpty = true;
  5845. //construct the joined selector - if & is the first thing this will be empty,
  5846. // if not newJoinedSelector will be the last set of elements in the selector
  5847. if( $sel ){
  5848. $newSelectorPath = $sel;
  5849. $lastSelector = array_pop($newSelectorPath);
  5850. $newJoinedSelector = $selector->createDerived( array_slice($lastSelector->elements,0) );
  5851. $newJoinedSelectorEmpty = false;
  5852. }
  5853. else {
  5854. $newJoinedSelector = $selector->createDerived(array());
  5855. }
  5856. //put together the parent selectors after the join
  5857. if ( count($parentSel) > 1) {
  5858. $afterParentJoin = array_merge($afterParentJoin, array_slice($parentSel,1) );
  5859. }
  5860. if ( $parentSel ){
  5861. $newJoinedSelectorEmpty = false;
  5862. // join the elements so far with the first part of the parent
  5863. $newJoinedSelector->elements[] = new Less_Tree_Element( $el->combinator, $parentSel[0]->elements[0]->value, $el->index, $el->currentFileInfo);
  5864. $newJoinedSelector->elements = array_merge( $newJoinedSelector->elements, array_slice($parentSel[0]->elements, 1) );
  5865. }
  5866. if (!$newJoinedSelectorEmpty) {
  5867. // now add the joined selector
  5868. $newSelectorPath[] = $newJoinedSelector;
  5869. }
  5870. // and the rest of the parent
  5871. $newSelectorPath = array_merge($newSelectorPath, $afterParentJoin);
  5872. // add that to our new set of selectors
  5873. $selectorsMultiplied[] = $newSelectorPath;
  5874. }
  5875. }
  5876. }
  5877. // our new selectors has been multiplied, so reset the state
  5878. $newSelectors = $selectorsMultiplied;
  5879. $currentElements = array();
  5880. }
  5881. }
  5882. // if we have any elements left over (e.g. .a& .b == .b)
  5883. // add them on to all the current selectors
  5884. if( $currentElements ){
  5885. $this->mergeElementsOnToSelectors($currentElements, $newSelectors);
  5886. }
  5887. foreach( $newSelectors as $new_sel){
  5888. if( $new_sel ){
  5889. $paths[] = $new_sel;
  5890. }
  5891. }
  5892. }
  5893. function mergeElementsOnToSelectors( $elements, &$selectors){
  5894. if( !$selectors ){
  5895. $selectors[] = array( new Less_Tree_Selector($elements) );
  5896. return;
  5897. }
  5898. foreach( $selectors as &$sel){
  5899. // if the previous thing in sel is a parent this needs to join on to it
  5900. if( $sel ){
  5901. $last = count($sel)-1;
  5902. $sel[$last] = $sel[$last]->createDerived( array_merge($sel[$last]->elements, $elements) );
  5903. }else{
  5904. $sel[] = new Less_Tree_Selector( $elements );
  5905. }
  5906. }
  5907. }
  5908. }
  5909. /**
  5910. * RulesetCall
  5911. *
  5912. * @package Less
  5913. * @subpackage tree
  5914. */
  5915. class Less_Tree_RulesetCall extends Less_Tree{
  5916. public $variable;
  5917. public $type = "RulesetCall";
  5918. public function __construct($variable){
  5919. $this->variable = $variable;
  5920. }
  5921. public function accept($visitor) {}
  5922. public function compile( $env ){
  5923. $variable = new Less_Tree_Variable($this->variable);
  5924. $detachedRuleset = $variable->compile($env);
  5925. return $detachedRuleset->callEval($env);
  5926. }
  5927. }
  5928. /**
  5929. * Selector
  5930. *
  5931. * @package Less
  5932. * @subpackage tree
  5933. */
  5934. class Less_Tree_Selector extends Less_Tree{
  5935. public $elements;
  5936. public $condition;
  5937. public $extendList = array();
  5938. public $_css;
  5939. public $index;
  5940. public $evaldCondition = false;
  5941. public $type = 'Selector';
  5942. public $currentFileInfo = array();
  5943. public $isReferenced;
  5944. public $mediaEmpty;
  5945. public $elements_len = 0;
  5946. public $_oelements;
  5947. public $_oelements_len;
  5948. public $cacheable = true;
  5949. /**
  5950. * @param boolean $isReferenced
  5951. */
  5952. public function __construct( $elements, $extendList = array() , $condition = null, $index=null, $currentFileInfo=null, $isReferenced=null ){
  5953. $this->elements = $elements;
  5954. $this->elements_len = count($elements);
  5955. $this->extendList = $extendList;
  5956. $this->condition = $condition;
  5957. if( $currentFileInfo ){
  5958. $this->currentFileInfo = $currentFileInfo;
  5959. }
  5960. $this->isReferenced = $isReferenced;
  5961. if( !$condition ){
  5962. $this->evaldCondition = true;
  5963. }
  5964. $this->CacheElements();
  5965. }
  5966. public function accept($visitor) {
  5967. $this->elements = $visitor->visitArray($this->elements);
  5968. $this->extendList = $visitor->visitArray($this->extendList);
  5969. if( $this->condition ){
  5970. $this->condition = $visitor->visitObj($this->condition);
  5971. }
  5972. if( $visitor instanceof Less_Visitor_extendFinder ){
  5973. $this->CacheElements();
  5974. }
  5975. }
  5976. public function createDerived( $elements, $extendList = null, $evaldCondition = null ){
  5977. $newSelector = new Less_Tree_Selector( $elements, ($extendList ? $extendList : $this->extendList), null, $this->index, $this->currentFileInfo, $this->isReferenced);
  5978. $newSelector->evaldCondition = $evaldCondition ? $evaldCondition : $this->evaldCondition;
  5979. return $newSelector;
  5980. }
  5981. public function match( $other ){
  5982. if( !$other->_oelements || ($this->elements_len < $other->_oelements_len) ){
  5983. return 0;
  5984. }
  5985. for( $i = 0; $i < $other->_oelements_len; $i++ ){
  5986. if( $this->elements[$i]->value !== $other->_oelements[$i]) {
  5987. return 0;
  5988. }
  5989. }
  5990. return $other->_oelements_len; // return number of matched elements
  5991. }
  5992. public function CacheElements(){
  5993. $this->_oelements = array();
  5994. $css = '';
  5995. foreach($this->elements as $v){
  5996. $css .= $v->combinator;
  5997. if( !$v->value_is_object ){
  5998. $css .= $v->value;
  5999. continue;
  6000. }
  6001. if( !property_exists($v->value,'value') || !is_string($v->value->value) ){
  6002. $this->cacheable = false;
  6003. return;
  6004. }
  6005. $css .= $v->value->value;
  6006. }
  6007. $this->_oelements_len = preg_match_all('/[,&#\.\w-](?:[\w-]|(?:\\\\.))*/', $css, $matches);
  6008. if( $this->_oelements_len ){
  6009. $this->_oelements = $matches[0];
  6010. if( $this->_oelements[0] === '&' ){
  6011. array_shift($this->_oelements);
  6012. $this->_oelements_len--;
  6013. }
  6014. }
  6015. }
  6016. public function isJustParentSelector(){
  6017. return !$this->mediaEmpty &&
  6018. count($this->elements) === 1 &&
  6019. $this->elements[0]->value === '&' &&
  6020. ($this->elements[0]->combinator === ' ' || $this->elements[0]->combinator === '');
  6021. }
  6022. public function compile($env) {
  6023. $elements = array();
  6024. foreach($this->elements as $el){
  6025. $elements[] = $el->compile($env);
  6026. }
  6027. $extendList = array();
  6028. foreach($this->extendList as $el){
  6029. $extendList[] = $el->compile($el);
  6030. }
  6031. $evaldCondition = false;
  6032. if( $this->condition ){
  6033. $evaldCondition = $this->condition->compile($env);
  6034. }
  6035. return $this->createDerived( $elements, $extendList, $evaldCondition );
  6036. }
  6037. /**
  6038. * @see Less_Tree::genCSS
  6039. */
  6040. public function genCSS( $output, $firstSelector = true ){
  6041. if( !$firstSelector && $this->elements[0]->combinator === "" ){
  6042. $output->add(' ', $this->currentFileInfo, $this->index);
  6043. }
  6044. foreach($this->elements as $element){
  6045. $element->genCSS( $output );
  6046. }
  6047. }
  6048. public function markReferenced(){
  6049. $this->isReferenced = true;
  6050. }
  6051. public function getIsReferenced(){
  6052. return !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] || $this->isReferenced;
  6053. }
  6054. public function getIsOutput(){
  6055. return $this->evaldCondition;
  6056. }
  6057. }
  6058. /**
  6059. * UnicodeDescriptor
  6060. *
  6061. * @package Less
  6062. * @subpackage tree
  6063. */
  6064. class Less_Tree_UnicodeDescriptor extends Less_Tree{
  6065. public $value;
  6066. public $type = 'UnicodeDescriptor';
  6067. public function __construct($value){
  6068. $this->value = $value;
  6069. }
  6070. /**
  6071. * @see Less_Tree::genCSS
  6072. */
  6073. public function genCSS( $output ){
  6074. $output->add( $this->value );
  6075. }
  6076. public function compile(){
  6077. return $this;
  6078. }
  6079. }
  6080. /**
  6081. * Unit
  6082. *
  6083. * @package Less
  6084. * @subpackage tree
  6085. */
  6086. class Less_Tree_Unit extends Less_Tree{
  6087. var $numerator = array();
  6088. var $denominator = array();
  6089. public $backupUnit;
  6090. public $type = 'Unit';
  6091. public function __construct($numerator = array(), $denominator = array(), $backupUnit = null ){
  6092. $this->numerator = $numerator;
  6093. $this->denominator = $denominator;
  6094. $this->backupUnit = $backupUnit;
  6095. }
  6096. public function __clone(){
  6097. }
  6098. /**
  6099. * @see Less_Tree::genCSS
  6100. */
  6101. public function genCSS( $output ){
  6102. if( $this->numerator ){
  6103. $output->add( $this->numerator[0] );
  6104. }elseif( $this->denominator ){
  6105. $output->add( $this->denominator[0] );
  6106. }elseif( !Less_Parser::$options['strictUnits'] && $this->backupUnit ){
  6107. $output->add( $this->backupUnit );
  6108. return ;
  6109. }
  6110. }
  6111. public function toString(){
  6112. $returnStr = implode('*',$this->numerator);
  6113. foreach($this->denominator as $d){
  6114. $returnStr .= '/'.$d;
  6115. }
  6116. return $returnStr;
  6117. }
  6118. public function __toString(){
  6119. return $this->toString();
  6120. }
  6121. /**
  6122. * @param Less_Tree_Unit $other
  6123. */
  6124. public function compare($other) {
  6125. return $this->is( $other->toString() ) ? 0 : -1;
  6126. }
  6127. public function is($unitString){
  6128. return $this->toString() === $unitString;
  6129. }
  6130. public function isLength(){
  6131. $css = $this->toCSS();
  6132. return !!preg_match('/px|em|%|in|cm|mm|pc|pt|ex/',$css);
  6133. }
  6134. public function isAngle() {
  6135. return isset( Less_Tree_UnitConversions::$angle[$this->toCSS()] );
  6136. }
  6137. public function isEmpty(){
  6138. return !$this->numerator && !$this->denominator;
  6139. }
  6140. public function isSingular() {
  6141. return count($this->numerator) <= 1 && !$this->denominator;
  6142. }
  6143. public function usedUnits(){
  6144. $result = array();
  6145. foreach(Less_Tree_UnitConversions::$groups as $groupName){
  6146. $group = Less_Tree_UnitConversions::${$groupName};
  6147. foreach($this->numerator as $atomicUnit){
  6148. if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
  6149. $result[$groupName] = $atomicUnit;
  6150. }
  6151. }
  6152. foreach($this->denominator as $atomicUnit){
  6153. if( isset($group[$atomicUnit]) && !isset($result[$groupName]) ){
  6154. $result[$groupName] = $atomicUnit;
  6155. }
  6156. }
  6157. }
  6158. return $result;
  6159. }
  6160. public function cancel(){
  6161. $counter = array();
  6162. $backup = null;
  6163. foreach($this->numerator as $atomicUnit){
  6164. if( !$backup ){
  6165. $backup = $atomicUnit;
  6166. }
  6167. $counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) + 1;
  6168. }
  6169. foreach($this->denominator as $atomicUnit){
  6170. if( !$backup ){
  6171. $backup = $atomicUnit;
  6172. }
  6173. $counter[$atomicUnit] = ( isset($counter[$atomicUnit]) ? $counter[$atomicUnit] : 0) - 1;
  6174. }
  6175. $this->numerator = array();
  6176. $this->denominator = array();
  6177. foreach($counter as $atomicUnit => $count){
  6178. if( $count > 0 ){
  6179. for( $i = 0; $i < $count; $i++ ){
  6180. $this->numerator[] = $atomicUnit;
  6181. }
  6182. }elseif( $count < 0 ){
  6183. for( $i = 0; $i < -$count; $i++ ){
  6184. $this->denominator[] = $atomicUnit;
  6185. }
  6186. }
  6187. }
  6188. if( !$this->numerator && !$this->denominator && $backup ){
  6189. $this->backupUnit = $backup;
  6190. }
  6191. sort($this->numerator);
  6192. sort($this->denominator);
  6193. }
  6194. }
  6195. /**
  6196. * UnitConversions
  6197. *
  6198. * @package Less
  6199. * @subpackage tree
  6200. */
  6201. class Less_Tree_UnitConversions{
  6202. public static $groups = array('length','duration','angle');
  6203. public static $length = array(
  6204. 'm'=> 1,
  6205. 'cm'=> 0.01,
  6206. 'mm'=> 0.001,
  6207. 'in'=> 0.0254,
  6208. 'px'=> 0.000264583, // 0.0254 / 96,
  6209. 'pt'=> 0.000352778, // 0.0254 / 72,
  6210. 'pc'=> 0.004233333, // 0.0254 / 72 * 12
  6211. );
  6212. public static $duration = array(
  6213. 's'=> 1,
  6214. 'ms'=> 0.001
  6215. );
  6216. public static $angle = array(
  6217. 'rad' => 0.1591549430919, // 1/(2*M_PI),
  6218. 'deg' => 0.002777778, // 1/360,
  6219. 'grad'=> 0.0025, // 1/400,
  6220. 'turn'=> 1
  6221. );
  6222. }
  6223. /**
  6224. * Url
  6225. *
  6226. * @package Less
  6227. * @subpackage tree
  6228. */
  6229. class Less_Tree_Url extends Less_Tree{
  6230. public $attrs;
  6231. public $value;
  6232. public $currentFileInfo;
  6233. public $isEvald;
  6234. public $type = 'Url';
  6235. public function __construct($value, $currentFileInfo = null, $isEvald = null){
  6236. $this->value = $value;
  6237. $this->currentFileInfo = $currentFileInfo;
  6238. $this->isEvald = $isEvald;
  6239. }
  6240. public function accept( $visitor ){
  6241. $this->value = $visitor->visitObj($this->value);
  6242. }
  6243. /**
  6244. * @see Less_Tree::genCSS
  6245. */
  6246. public function genCSS( $output ){
  6247. $output->add( 'url(' );
  6248. $this->value->genCSS( $output );
  6249. $output->add( ')' );
  6250. }
  6251. /**
  6252. * @param Less_Functions $ctx
  6253. */
  6254. public function compile($ctx){
  6255. $val = $this->value->compile($ctx);
  6256. if( !$this->isEvald ){
  6257. // Add the base path if the URL is relative
  6258. if( Less_Parser::$options['relativeUrls']
  6259. && $this->currentFileInfo
  6260. && is_string($val->value)
  6261. && Less_Environment::isPathRelative($val->value)
  6262. ){
  6263. $rootpath = $this->currentFileInfo['uri_root'];
  6264. if ( !$val->quote ){
  6265. $rootpath = preg_replace('/[\(\)\'"\s]/', '\\$1', $rootpath );
  6266. }
  6267. $val->value = $rootpath . $val->value;
  6268. }
  6269. $val->value = Less_Environment::normalizePath( $val->value);
  6270. }
  6271. // Add cache buster if enabled
  6272. if( Less_Parser::$options['urlArgs'] ){
  6273. if( !preg_match('/^\s*data:/',$val->value) ){
  6274. $delimiter = strpos($val->value,'?') === false ? '?' : '&';
  6275. $urlArgs = $delimiter . Less_Parser::$options['urlArgs'];
  6276. $hash_pos = strpos($val->value,'#');
  6277. if( $hash_pos !== false ){
  6278. $val->value = substr_replace($val->value,$urlArgs, $hash_pos, 0);
  6279. } else {
  6280. $val->value .= $urlArgs;
  6281. }
  6282. }
  6283. }
  6284. return new Less_Tree_URL($val, $this->currentFileInfo, true);
  6285. }
  6286. }
  6287. /**
  6288. * Value
  6289. *
  6290. * @package Less
  6291. * @subpackage tree
  6292. */
  6293. class Less_Tree_Value extends Less_Tree{
  6294. public $type = 'Value';
  6295. public $value;
  6296. public function __construct($value){
  6297. $this->value = $value;
  6298. }
  6299. public function accept($visitor) {
  6300. $this->value = $visitor->visitArray($this->value);
  6301. }
  6302. public function compile($env){
  6303. $ret = array();
  6304. $i = 0;
  6305. foreach($this->value as $i => $v){
  6306. $ret[] = $v->compile($env);
  6307. }
  6308. if( $i > 0 ){
  6309. return new Less_Tree_Value($ret);
  6310. }
  6311. return $ret[0];
  6312. }
  6313. /**
  6314. * @see Less_Tree::genCSS
  6315. */
  6316. function genCSS( $output ){
  6317. $len = count($this->value);
  6318. for($i = 0; $i < $len; $i++ ){
  6319. $this->value[$i]->genCSS( $output );
  6320. if( $i+1 < $len ){
  6321. $output->add( Less_Environment::$_outputMap[','] );
  6322. }
  6323. }
  6324. }
  6325. }
  6326. /**
  6327. * Variable
  6328. *
  6329. * @package Less
  6330. * @subpackage tree
  6331. */
  6332. class Less_Tree_Variable extends Less_Tree{
  6333. public $name;
  6334. public $index;
  6335. public $currentFileInfo;
  6336. public $evaluating = false;
  6337. public $type = 'Variable';
  6338. /**
  6339. * @param string $name
  6340. */
  6341. public function __construct($name, $index = null, $currentFileInfo = null) {
  6342. $this->name = $name;
  6343. $this->index = $index;
  6344. $this->currentFileInfo = $currentFileInfo;
  6345. }
  6346. public function compile($env) {
  6347. if( $this->name[1] === '@' ){
  6348. $v = new Less_Tree_Variable(substr($this->name, 1), $this->index + 1, $this->currentFileInfo);
  6349. $name = '@' . $v->compile($env)->value;
  6350. }else{
  6351. $name = $this->name;
  6352. }
  6353. if ($this->evaluating) {
  6354. throw new Less_Exception_Compiler("Recursive variable definition for " . $name, null, $this->index, $this->currentFileInfo);
  6355. }
  6356. $this->evaluating = true;
  6357. foreach($env->frames as $frame){
  6358. if( $v = $frame->variable($name) ){
  6359. $r = $v->value->compile($env);
  6360. $this->evaluating = false;
  6361. return $r;
  6362. }
  6363. }
  6364. throw new Less_Exception_Compiler("variable " . $name . " is undefined in file ".$this->currentFileInfo["filename"], null, $this->index, $this->currentFileInfo);
  6365. }
  6366. }
  6367. class Less_Tree_Mixin_Call extends Less_Tree{
  6368. public $selector;
  6369. public $arguments;
  6370. public $index;
  6371. public $currentFileInfo;
  6372. public $important;
  6373. public $type = 'MixinCall';
  6374. /**
  6375. * less.js: tree.mixin.Call
  6376. *
  6377. */
  6378. public function __construct($elements, $args, $index, $currentFileInfo, $important = false){
  6379. $this->selector = new Less_Tree_Selector($elements);
  6380. $this->arguments = $args;
  6381. $this->index = $index;
  6382. $this->currentFileInfo = $currentFileInfo;
  6383. $this->important = $important;
  6384. }
  6385. //function accept($visitor){
  6386. // $this->selector = $visitor->visit($this->selector);
  6387. // $this->arguments = $visitor->visit($this->arguments);
  6388. //}
  6389. public function compile($env){
  6390. $rules = array();
  6391. $match = false;
  6392. $isOneFound = false;
  6393. $candidates = array();
  6394. $defaultUsed = false;
  6395. $conditionResult = array();
  6396. $args = array();
  6397. foreach($this->arguments as $a){
  6398. $args[] = array('name'=> $a['name'], 'value' => $a['value']->compile($env) );
  6399. }
  6400. foreach($env->frames as $frame){
  6401. $mixins = $frame->find($this->selector);
  6402. if( !$mixins ){
  6403. continue;
  6404. }
  6405. $isOneFound = true;
  6406. $defNone = 0;
  6407. $defTrue = 1;
  6408. $defFalse = 2;
  6409. // To make `default()` function independent of definition order we have two "subpasses" here.
  6410. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`),
  6411. // and build candidate list with corresponding flags. Then, when we know all possible matches,
  6412. // we make a final decision.
  6413. $mixins_len = count($mixins);
  6414. for( $m = 0; $m < $mixins_len; $m++ ){
  6415. $mixin = $mixins[$m];
  6416. if( $this->IsRecursive( $env, $mixin ) ){
  6417. continue;
  6418. }
  6419. if( $mixin->matchArgs($args, $env) ){
  6420. $candidate = array('mixin' => $mixin, 'group' => $defNone);
  6421. if( $mixin instanceof Less_Tree_Ruleset ){
  6422. for( $f = 0; $f < 2; $f++ ){
  6423. Less_Tree_DefaultFunc::value($f);
  6424. $conditionResult[$f] = $mixin->matchCondition( $args, $env);
  6425. }
  6426. if( $conditionResult[0] || $conditionResult[1] ){
  6427. if( $conditionResult[0] != $conditionResult[1] ){
  6428. $candidate['group'] = $conditionResult[1] ? $defTrue : $defFalse;
  6429. }
  6430. $candidates[] = $candidate;
  6431. }
  6432. }else{
  6433. $candidates[] = $candidate;
  6434. }
  6435. $match = true;
  6436. }
  6437. }
  6438. Less_Tree_DefaultFunc::reset();
  6439. $count = array(0, 0, 0);
  6440. for( $m = 0; $m < count($candidates); $m++ ){
  6441. $count[ $candidates[$m]['group'] ]++;
  6442. }
  6443. if( $count[$defNone] > 0 ){
  6444. $defaultResult = $defFalse;
  6445. } else {
  6446. $defaultResult = $defTrue;
  6447. if( ($count[$defTrue] + $count[$defFalse]) > 1 ){
  6448. throw new Exception( 'Ambiguous use of `default()` found when matching for `'. $this->format($args) + '`' );
  6449. }
  6450. }
  6451. $candidates_length = count($candidates);
  6452. $length_1 = ($candidates_length == 1);
  6453. for( $m = 0; $m < $candidates_length; $m++){
  6454. $candidate = $candidates[$m]['group'];
  6455. if( ($candidate === $defNone) || ($candidate === $defaultResult) ){
  6456. try{
  6457. $mixin = $candidates[$m]['mixin'];
  6458. if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
  6459. $mixin = new Less_Tree_Mixin_Definition('', array(), $mixin->rules, null, false);
  6460. $mixin->originalRuleset = $mixins[$m]->originalRuleset;
  6461. }
  6462. $rules = array_merge($rules, $mixin->evalCall($env, $args, $this->important)->rules);
  6463. } catch (Exception $e) {
  6464. //throw new Less_Exception_Compiler($e->getMessage(), $e->index, null, $this->currentFileInfo['filename']);
  6465. throw new Less_Exception_Compiler($e->getMessage(), null, null, $this->currentFileInfo);
  6466. }
  6467. }
  6468. }
  6469. if( $match ){
  6470. if( !$this->currentFileInfo || !isset($this->currentFileInfo['reference']) || !$this->currentFileInfo['reference'] ){
  6471. Less_Tree::ReferencedArray($rules);
  6472. }
  6473. return $rules;
  6474. }
  6475. }
  6476. if( $isOneFound ){
  6477. throw new Less_Exception_Compiler('No matching definition was found for `'.$this->Format( $args ).'`', null, $this->index, $this->currentFileInfo);
  6478. }else{
  6479. throw new Less_Exception_Compiler(trim($this->selector->toCSS()) . " is undefined in ".$this->currentFileInfo['filename'], null, $this->index);
  6480. }
  6481. }
  6482. /**
  6483. * Format the args for use in exception messages
  6484. *
  6485. */
  6486. private function Format($args){
  6487. $message = array();
  6488. if( $args ){
  6489. foreach($args as $a){
  6490. $argValue = '';
  6491. if( $a['name'] ){
  6492. $argValue += $a['name']+':';
  6493. }
  6494. if( is_object($a['value']) ){
  6495. $argValue += $a['value']->toCSS();
  6496. }else{
  6497. $argValue += '???';
  6498. }
  6499. $message[] = $argValue;
  6500. }
  6501. }
  6502. return implode(', ',$message);
  6503. }
  6504. /**
  6505. * Are we in a recursive mixin call?
  6506. *
  6507. * @return bool
  6508. */
  6509. private function IsRecursive( $env, $mixin ){
  6510. foreach($env->frames as $recur_frame){
  6511. if( !($mixin instanceof Less_Tree_Mixin_Definition) ){
  6512. if( $mixin === $recur_frame ){
  6513. return true;
  6514. }
  6515. if( isset($recur_frame->originalRuleset) && $mixin->ruleset_id === $recur_frame->originalRuleset ){
  6516. return true;
  6517. }
  6518. }
  6519. }
  6520. return false;
  6521. }
  6522. }
  6523. class Less_Tree_Mixin_Definition extends Less_Tree_Ruleset{
  6524. public $name;
  6525. public $selectors;
  6526. public $params;
  6527. public $arity = 0;
  6528. public $rules;
  6529. public $lookups = array();
  6530. public $required = 0;
  6531. public $frames = array();
  6532. public $condition;
  6533. public $variadic;
  6534. public $type = 'MixinDefinition';
  6535. // less.js : /lib/less/tree/mixin.js : tree.mixin.Definition
  6536. public function __construct($name, $params, $rules, $condition, $variadic = false, $frames = array() ){
  6537. $this->name = $name;
  6538. $this->selectors = array(new Less_Tree_Selector(array( new Less_Tree_Element(null, $name))));
  6539. $this->params = $params;
  6540. $this->condition = $condition;
  6541. $this->variadic = $variadic;
  6542. $this->rules = $rules;
  6543. if( $params ){
  6544. $this->arity = count($params);
  6545. foreach( $params as $p ){
  6546. if (! isset($p['name']) || ($p['name'] && !isset($p['value']))) {
  6547. $this->required++;
  6548. }
  6549. }
  6550. }
  6551. $this->frames = $frames;
  6552. $this->SetRulesetIndex();
  6553. }
  6554. //function accept( $visitor ){
  6555. // $this->params = $visitor->visit($this->params);
  6556. // $this->rules = $visitor->visit($this->rules);
  6557. // $this->condition = $visitor->visit($this->condition);
  6558. //}
  6559. public function toCSS(){
  6560. return '';
  6561. }
  6562. // less.js : /lib/less/tree/mixin.js : tree.mixin.Definition.evalParams
  6563. public function compileParams($env, $mixinFrames, $args = array() , &$evaldArguments = array() ){
  6564. $frame = new Less_Tree_Ruleset(null, array());
  6565. $params = $this->params;
  6566. $mixinEnv = null;
  6567. $argsLength = 0;
  6568. if( $args ){
  6569. $argsLength = count($args);
  6570. for($i = 0; $i < $argsLength; $i++ ){
  6571. $arg = $args[$i];
  6572. if( $arg && $arg['name'] ){
  6573. $isNamedFound = false;
  6574. foreach($params as $j => $param){
  6575. if( !isset($evaldArguments[$j]) && $arg['name'] === $params[$j]['name']) {
  6576. $evaldArguments[$j] = $arg['value']->compile($env);
  6577. array_unshift($frame->rules, new Less_Tree_Rule( $arg['name'], $arg['value']->compile($env) ) );
  6578. $isNamedFound = true;
  6579. break;
  6580. }
  6581. }
  6582. if ($isNamedFound) {
  6583. array_splice($args, $i, 1);
  6584. $i--;
  6585. $argsLength--;
  6586. continue;
  6587. } else {
  6588. throw new Less_Exception_Compiler("Named argument for " . $this->name .' '.$args[$i]['name'] . ' not found');
  6589. }
  6590. }
  6591. }
  6592. }
  6593. $argIndex = 0;
  6594. foreach($params as $i => $param){
  6595. if ( isset($evaldArguments[$i]) ){ continue; }
  6596. $arg = null;
  6597. if( isset($args[$argIndex]) ){
  6598. $arg = $args[$argIndex];
  6599. }
  6600. if (isset($param['name']) && $param['name']) {
  6601. if( isset($param['variadic']) ){
  6602. $varargs = array();
  6603. for ($j = $argIndex; $j < $argsLength; $j++) {
  6604. $varargs[] = $args[$j]['value']->compile($env);
  6605. }
  6606. $expression = new Less_Tree_Expression($varargs);
  6607. array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $expression->compile($env)));
  6608. }else{
  6609. $val = ($arg && $arg['value']) ? $arg['value'] : false;
  6610. if ($val) {
  6611. $val = $val->compile($env);
  6612. } else if ( isset($param['value']) ) {
  6613. if( !$mixinEnv ){
  6614. $mixinEnv = new Less_Environment();
  6615. $mixinEnv->frames = array_merge( array($frame), $mixinFrames);
  6616. }
  6617. $val = $param['value']->compile($mixinEnv);
  6618. $frame->resetCache();
  6619. } else {
  6620. throw new Less_Exception_Compiler("Wrong number of arguments for " . $this->name . " (" . $argsLength . ' for ' . $this->arity . ")");
  6621. }
  6622. array_unshift($frame->rules, new Less_Tree_Rule($param['name'], $val));
  6623. $evaldArguments[$i] = $val;
  6624. }
  6625. }
  6626. if ( isset($param['variadic']) && $args) {
  6627. for ($j = $argIndex; $j < $argsLength; $j++) {
  6628. $evaldArguments[$j] = $args[$j]['value']->compile($env);
  6629. }
  6630. }
  6631. $argIndex++;
  6632. }
  6633. ksort($evaldArguments);
  6634. $evaldArguments = array_values($evaldArguments);
  6635. return $frame;
  6636. }
  6637. public function compile($env) {
  6638. if( $this->frames ){
  6639. return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $this->frames );
  6640. }
  6641. return new Less_Tree_Mixin_Definition($this->name, $this->params, $this->rules, $this->condition, $this->variadic, $env->frames );
  6642. }
  6643. public function evalCall($env, $args = NULL, $important = NULL) {
  6644. Less_Environment::$mixin_stack++;
  6645. $_arguments = array();
  6646. if( $this->frames ){
  6647. $mixinFrames = array_merge($this->frames, $env->frames);
  6648. }else{
  6649. $mixinFrames = $env->frames;
  6650. }
  6651. $frame = $this->compileParams($env, $mixinFrames, $args, $_arguments);
  6652. $ex = new Less_Tree_Expression($_arguments);
  6653. array_unshift($frame->rules, new Less_Tree_Rule('@arguments', $ex->compile($env)));
  6654. $ruleset = new Less_Tree_Ruleset(null, $this->rules);
  6655. $ruleset->originalRuleset = $this->ruleset_id;
  6656. $ruleSetEnv = new Less_Environment();
  6657. $ruleSetEnv->frames = array_merge( array($this, $frame), $mixinFrames );
  6658. $ruleset = $ruleset->compile( $ruleSetEnv );
  6659. if( $important ){
  6660. $ruleset = $ruleset->makeImportant();
  6661. }
  6662. Less_Environment::$mixin_stack--;
  6663. return $ruleset;
  6664. }
  6665. public function matchCondition($args, $env) {
  6666. if( !$this->condition ){
  6667. return true;
  6668. }
  6669. // set array to prevent error on array_merge
  6670. if(!is_array($this->frames)) {
  6671. $this->frames = array();
  6672. }
  6673. $frame = $this->compileParams($env, array_merge($this->frames,$env->frames), $args );
  6674. $compile_env = new Less_Environment();
  6675. $compile_env->frames = array_merge(
  6676. array($frame) // the parameter variables
  6677. , $this->frames // the parent namespace/mixin frames
  6678. , $env->frames // the current environment frames
  6679. );
  6680. $compile_env->functions = $env->functions;
  6681. return (bool)$this->condition->compile($compile_env);
  6682. }
  6683. public function matchArgs($args, $env = NULL){
  6684. $argsLength = count($args);
  6685. if( !$this->variadic ){
  6686. if( $argsLength < $this->required ){
  6687. return false;
  6688. }
  6689. if( $argsLength > count($this->params) ){
  6690. return false;
  6691. }
  6692. }else{
  6693. if( $argsLength < ($this->required - 1)){
  6694. return false;
  6695. }
  6696. }
  6697. $len = min($argsLength, $this->arity);
  6698. for( $i = 0; $i < $len; $i++ ){
  6699. if( !isset($this->params[$i]['name']) && !isset($this->params[$i]['variadic']) ){
  6700. if( $args[$i]['value']->compile($env)->toCSS() != $this->params[$i]['value']->compile($env)->toCSS() ){
  6701. return false;
  6702. }
  6703. }
  6704. }
  6705. return true;
  6706. }
  6707. }
  6708. /**
  6709. * Extend Finder Visitor
  6710. *
  6711. * @package Less
  6712. * @subpackage visitor
  6713. */
  6714. class Less_Visitor_extendFinder extends Less_Visitor{
  6715. public $contexts = array();
  6716. public $allExtendsStack;
  6717. public $foundExtends;
  6718. public function __construct(){
  6719. $this->contexts = array();
  6720. $this->allExtendsStack = array(array());
  6721. parent::__construct();
  6722. }
  6723. /**
  6724. * @param Less_Tree_Ruleset $root
  6725. */
  6726. public function run($root){
  6727. $root = $this->visitObj($root);
  6728. $root->allExtends =& $this->allExtendsStack[0];
  6729. return $root;
  6730. }
  6731. public function visitRule($ruleNode, &$visitDeeper ){
  6732. $visitDeeper = false;
  6733. }
  6734. public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  6735. $visitDeeper = false;
  6736. }
  6737. public function visitRuleset($rulesetNode){
  6738. if( $rulesetNode->root ){
  6739. return;
  6740. }
  6741. $allSelectorsExtendList = array();
  6742. // get &:extend(.a); rules which apply to all selectors in this ruleset
  6743. if( $rulesetNode->rules ){
  6744. foreach($rulesetNode->rules as $rule){
  6745. if( $rule instanceof Less_Tree_Extend ){
  6746. $allSelectorsExtendList[] = $rule;
  6747. $rulesetNode->extendOnEveryPath = true;
  6748. }
  6749. }
  6750. }
  6751. // now find every selector and apply the extends that apply to all extends
  6752. // and the ones which apply to an individual extend
  6753. foreach($rulesetNode->paths as $selectorPath){
  6754. $selector = end($selectorPath); //$selectorPath[ count($selectorPath)-1];
  6755. $j = 0;
  6756. foreach($selector->extendList as $extend){
  6757. $this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
  6758. }
  6759. foreach($allSelectorsExtendList as $extend){
  6760. $this->allExtendsStackPush($rulesetNode, $selectorPath, $extend, $j);
  6761. }
  6762. }
  6763. $this->contexts[] = $rulesetNode->selectors;
  6764. }
  6765. public function allExtendsStackPush($rulesetNode, $selectorPath, $extend, &$j){
  6766. $this->foundExtends = true;
  6767. $extend = clone $extend;
  6768. $extend->findSelfSelectors( $selectorPath );
  6769. $extend->ruleset = $rulesetNode;
  6770. if( $j === 0 ){
  6771. $extend->firstExtendOnThisSelectorPath = true;
  6772. }
  6773. $end_key = count($this->allExtendsStack)-1;
  6774. $this->allExtendsStack[$end_key][] = $extend;
  6775. $j++;
  6776. }
  6777. public function visitRulesetOut( $rulesetNode ){
  6778. if( !is_object($rulesetNode) || !$rulesetNode->root ){
  6779. array_pop($this->contexts);
  6780. }
  6781. }
  6782. public function visitMedia( $mediaNode ){
  6783. $mediaNode->allExtends = array();
  6784. $this->allExtendsStack[] =& $mediaNode->allExtends;
  6785. }
  6786. public function visitMediaOut(){
  6787. array_pop($this->allExtendsStack);
  6788. }
  6789. public function visitDirective( $directiveNode ){
  6790. $directiveNode->allExtends = array();
  6791. $this->allExtendsStack[] =& $directiveNode->allExtends;
  6792. }
  6793. public function visitDirectiveOut(){
  6794. array_pop($this->allExtendsStack);
  6795. }
  6796. }
  6797. /*
  6798. class Less_Visitor_import extends Less_VisitorReplacing{
  6799. public $_visitor;
  6800. public $_importer;
  6801. public $importCount;
  6802. function __construct( $evalEnv ){
  6803. $this->env = $evalEnv;
  6804. $this->importCount = 0;
  6805. parent::__construct();
  6806. }
  6807. function run( $root ){
  6808. $root = $this->visitObj($root);
  6809. $this->isFinished = true;
  6810. //if( $this->importCount === 0) {
  6811. // $this->_finish();
  6812. //}
  6813. }
  6814. function visitImport($importNode, &$visitDeeper ){
  6815. $importVisitor = $this;
  6816. $inlineCSS = $importNode->options['inline'];
  6817. if( !$importNode->css || $inlineCSS ){
  6818. $evaldImportNode = $importNode->compileForImport($this->env);
  6819. if( $evaldImportNode && (!$evaldImportNode->css || $inlineCSS) ){
  6820. $importNode = $evaldImportNode;
  6821. $this->importCount++;
  6822. $env = clone $this->env;
  6823. if( (isset($importNode->options['multiple']) && $importNode->options['multiple']) ){
  6824. $env->importMultiple = true;
  6825. }
  6826. //get path & uri
  6827. $path_and_uri = null;
  6828. if( is_callable(Less_Parser::$options['import_callback']) ){
  6829. $path_and_uri = call_user_func(Less_Parser::$options['import_callback'],$importNode);
  6830. }
  6831. if( !$path_and_uri ){
  6832. $path_and_uri = $importNode->PathAndUri();
  6833. }
  6834. if( $path_and_uri ){
  6835. list($full_path, $uri) = $path_and_uri;
  6836. }else{
  6837. $full_path = $uri = $importNode->getPath();
  6838. }
  6839. //import once
  6840. if( $importNode->skip( $full_path, $env) ){
  6841. return array();
  6842. }
  6843. if( $importNode->options['inline'] ){
  6844. //todo needs to reference css file not import
  6845. //$contents = new Less_Tree_Anonymous($importNode->root, 0, array('filename'=>$importNode->importedFilename), true );
  6846. Less_Parser::AddParsedFile($full_path);
  6847. $contents = new Less_Tree_Anonymous( file_get_contents($full_path), 0, array(), true );
  6848. if( $importNode->features ){
  6849. return new Less_Tree_Media( array($contents), $importNode->features->value );
  6850. }
  6851. return array( $contents );
  6852. }
  6853. // css ?
  6854. if( $importNode->css ){
  6855. $features = ( $importNode->features ? $importNode->features->compile($env) : null );
  6856. return new Less_Tree_Import( $importNode->compilePath( $env), $features, $importNode->options, $this->index);
  6857. }
  6858. return $importNode->ParseImport( $full_path, $uri, $env );
  6859. }
  6860. }
  6861. $visitDeeper = false;
  6862. return $importNode;
  6863. }
  6864. function visitRule( $ruleNode, &$visitDeeper ){
  6865. $visitDeeper = false;
  6866. return $ruleNode;
  6867. }
  6868. function visitDirective($directiveNode, $visitArgs){
  6869. array_unshift($this->env->frames,$directiveNode);
  6870. return $directiveNode;
  6871. }
  6872. function visitDirectiveOut($directiveNode) {
  6873. array_shift($this->env->frames);
  6874. }
  6875. function visitMixinDefinition($mixinDefinitionNode, $visitArgs) {
  6876. array_unshift($this->env->frames,$mixinDefinitionNode);
  6877. return $mixinDefinitionNode;
  6878. }
  6879. function visitMixinDefinitionOut($mixinDefinitionNode) {
  6880. array_shift($this->env->frames);
  6881. }
  6882. function visitRuleset($rulesetNode, $visitArgs) {
  6883. array_unshift($this->env->frames,$rulesetNode);
  6884. return $rulesetNode;
  6885. }
  6886. function visitRulesetOut($rulesetNode) {
  6887. array_shift($this->env->frames);
  6888. }
  6889. function visitMedia($mediaNode, $visitArgs) {
  6890. array_unshift($this->env->frames, $mediaNode->ruleset);
  6891. return $mediaNode;
  6892. }
  6893. function visitMediaOut($mediaNode) {
  6894. array_shift($this->env->frames);
  6895. }
  6896. }
  6897. */
  6898. /**
  6899. * Join Selector Visitor
  6900. *
  6901. * @package Less
  6902. * @subpackage visitor
  6903. */
  6904. class Less_Visitor_joinSelector extends Less_Visitor{
  6905. public $contexts = array( array() );
  6906. /**
  6907. * @param Less_Tree_Ruleset $root
  6908. */
  6909. public function run( $root ){
  6910. return $this->visitObj($root);
  6911. }
  6912. public function visitRule( $ruleNode, &$visitDeeper ){
  6913. $visitDeeper = false;
  6914. }
  6915. public function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  6916. $visitDeeper = false;
  6917. }
  6918. public function visitRuleset( $rulesetNode ){
  6919. $paths = array();
  6920. if( !$rulesetNode->root ){
  6921. $selectors = array();
  6922. if( $rulesetNode->selectors && $rulesetNode->selectors ){
  6923. foreach($rulesetNode->selectors as $selector){
  6924. if( $selector->getIsOutput() ){
  6925. $selectors[] = $selector;
  6926. }
  6927. }
  6928. }
  6929. if( !$selectors ){
  6930. $rulesetNode->selectors = null;
  6931. $rulesetNode->rules = null;
  6932. }else{
  6933. $context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
  6934. $paths = $rulesetNode->joinSelectors( $context, $selectors);
  6935. }
  6936. $rulesetNode->paths = $paths;
  6937. }
  6938. $this->contexts[] = $paths; //different from less.js. Placed after joinSelectors() so that $this->contexts will get correct $paths
  6939. }
  6940. public function visitRulesetOut(){
  6941. array_pop($this->contexts);
  6942. }
  6943. public function visitMedia($mediaNode) {
  6944. $context = end($this->contexts); //$context = $this->contexts[ count($this->contexts) - 1];
  6945. if( !count($context) || (is_object($context[0]) && $context[0]->multiMedia) ){
  6946. $mediaNode->rules[0]->root = true;
  6947. }
  6948. }
  6949. }
  6950. /**
  6951. * Process Extends Visitor
  6952. *
  6953. * @package Less
  6954. * @subpackage visitor
  6955. */
  6956. class Less_Visitor_processExtends extends Less_Visitor{
  6957. public $allExtendsStack;
  6958. /**
  6959. * @param Less_Tree_Ruleset $root
  6960. */
  6961. public function run( $root ){
  6962. $extendFinder = new Less_Visitor_extendFinder();
  6963. $extendFinder->run( $root );
  6964. if( !$extendFinder->foundExtends){
  6965. return $root;
  6966. }
  6967. $root->allExtends = $this->doExtendChaining( $root->allExtends, $root->allExtends);
  6968. $this->allExtendsStack = array();
  6969. $this->allExtendsStack[] = &$root->allExtends;
  6970. return $this->visitObj( $root );
  6971. }
  6972. private function doExtendChaining( $extendsList, $extendsListTarget, $iterationCount = 0){
  6973. //
  6974. // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
  6975. // the selector we would do normally, but we are also adding an extend with the same target selector
  6976. // this means this new extend can then go and alter other extends
  6977. //
  6978. // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
  6979. // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
  6980. // we look at each selector at a time, as is done in visitRuleset
  6981. $extendsToAdd = array();
  6982. //loop through comparing every extend with every target extend.
  6983. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
  6984. // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
  6985. // and the second is the target.
  6986. // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
  6987. // case when processing media queries
  6988. for( $extendIndex = 0, $extendsList_len = count($extendsList); $extendIndex < $extendsList_len; $extendIndex++ ){
  6989. for( $targetExtendIndex = 0; $targetExtendIndex < count($extendsListTarget); $targetExtendIndex++ ){
  6990. $extend = $extendsList[$extendIndex];
  6991. $targetExtend = $extendsListTarget[$targetExtendIndex];
  6992. // look for circular references
  6993. if( in_array($targetExtend->object_id, $extend->parent_ids,true) ){
  6994. continue;
  6995. }
  6996. // find a match in the target extends self selector (the bit before :extend)
  6997. $selectorPath = array( $targetExtend->selfSelectors[0] );
  6998. $matches = $this->findMatch( $extend, $selectorPath);
  6999. if( $matches ){
  7000. // we found a match, so for each self selector..
  7001. foreach($extend->selfSelectors as $selfSelector ){
  7002. // process the extend as usual
  7003. $newSelector = $this->extendSelector( $matches, $selectorPath, $selfSelector);
  7004. // but now we create a new extend from it
  7005. $newExtend = new Less_Tree_Extend( $targetExtend->selector, $targetExtend->option, 0);
  7006. $newExtend->selfSelectors = $newSelector;
  7007. // add the extend onto the list of extends for that selector
  7008. end($newSelector)->extendList = array($newExtend);
  7009. //$newSelector[ count($newSelector)-1]->extendList = array($newExtend);
  7010. // record that we need to add it.
  7011. $extendsToAdd[] = $newExtend;
  7012. $newExtend->ruleset = $targetExtend->ruleset;
  7013. //remember its parents for circular references
  7014. $newExtend->parent_ids = array_merge($newExtend->parent_ids,$targetExtend->parent_ids,$extend->parent_ids);
  7015. // only process the selector once.. if we have :extend(.a,.b) then multiple
  7016. // extends will look at the same selector path, so when extending
  7017. // we know that any others will be duplicates in terms of what is added to the css
  7018. if( $targetExtend->firstExtendOnThisSelectorPath ){
  7019. $newExtend->firstExtendOnThisSelectorPath = true;
  7020. $targetExtend->ruleset->paths[] = $newSelector;
  7021. }
  7022. }
  7023. }
  7024. }
  7025. }
  7026. if( $extendsToAdd ){
  7027. // try to detect circular references to stop a stack overflow.
  7028. // may no longer be needed. $this->extendChainCount++;
  7029. if( $iterationCount > 100) {
  7030. try{
  7031. $selectorOne = $extendsToAdd[0]->selfSelectors[0]->toCSS();
  7032. $selectorTwo = $extendsToAdd[0]->selector->toCSS();
  7033. }catch(Exception $e){
  7034. $selectorOne = "{unable to calculate}";
  7035. $selectorTwo = "{unable to calculate}";
  7036. }
  7037. throw new Less_Exception_Parser("extend circular reference detected. One of the circular extends is currently:"+$selectorOne+":extend(" + $selectorTwo+")");
  7038. }
  7039. // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
  7040. $extendsToAdd = $this->doExtendChaining( $extendsToAdd, $extendsListTarget, $iterationCount+1);
  7041. }
  7042. return array_merge($extendsList, $extendsToAdd);
  7043. }
  7044. protected function visitRule( $ruleNode, &$visitDeeper ){
  7045. $visitDeeper = false;
  7046. }
  7047. protected function visitMixinDefinition( $mixinDefinitionNode, &$visitDeeper ){
  7048. $visitDeeper = false;
  7049. }
  7050. protected function visitSelector( $selectorNode, &$visitDeeper ){
  7051. $visitDeeper = false;
  7052. }
  7053. protected function visitRuleset($rulesetNode){
  7054. if( $rulesetNode->root ){
  7055. return;
  7056. }
  7057. $allExtends = end($this->allExtendsStack);
  7058. $paths_len = count($rulesetNode->paths);
  7059. // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
  7060. foreach($allExtends as $allExtend){
  7061. for($pathIndex = 0; $pathIndex < $paths_len; $pathIndex++ ){
  7062. // extending extends happens initially, before the main pass
  7063. if( isset($rulesetNode->extendOnEveryPath) && $rulesetNode->extendOnEveryPath ){
  7064. continue;
  7065. }
  7066. $selectorPath = $rulesetNode->paths[$pathIndex];
  7067. if( end($selectorPath)->extendList ){
  7068. continue;
  7069. }
  7070. $this->ExtendMatch( $rulesetNode, $allExtend, $selectorPath);
  7071. }
  7072. }
  7073. }
  7074. private function ExtendMatch( $rulesetNode, $extend, $selectorPath ){
  7075. $matches = $this->findMatch($extend, $selectorPath);
  7076. if( $matches ){
  7077. foreach($extend->selfSelectors as $selfSelector ){
  7078. $rulesetNode->paths[] = $this->extendSelector($matches, $selectorPath, $selfSelector);
  7079. }
  7080. }
  7081. }
  7082. private function findMatch($extend, $haystackSelectorPath ){
  7083. if( !$this->HasMatches($extend, $haystackSelectorPath) ){
  7084. return false;
  7085. }
  7086. //
  7087. // look through the haystack selector path to try and find the needle - extend.selector
  7088. // returns an array of selector matches that can then be replaced
  7089. //
  7090. $needleElements = $extend->selector->elements;
  7091. $potentialMatches = array();
  7092. $potentialMatches_len = 0;
  7093. $potentialMatch = null;
  7094. $matches = array();
  7095. // loop through the haystack elements
  7096. $haystack_path_len = count($haystackSelectorPath);
  7097. for($haystackSelectorIndex = 0; $haystackSelectorIndex < $haystack_path_len; $haystackSelectorIndex++ ){
  7098. $hackstackSelector = $haystackSelectorPath[$haystackSelectorIndex];
  7099. $haystack_elements_len = count($hackstackSelector->elements);
  7100. for($hackstackElementIndex = 0; $hackstackElementIndex < $haystack_elements_len; $hackstackElementIndex++ ){
  7101. $haystackElement = $hackstackSelector->elements[$hackstackElementIndex];
  7102. // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
  7103. if( $extend->allowBefore || ($haystackSelectorIndex === 0 && $hackstackElementIndex === 0) ){
  7104. $potentialMatches[] = array('pathIndex'=> $haystackSelectorIndex, 'index'=> $hackstackElementIndex, 'matched'=> 0, 'initialCombinator'=> $haystackElement->combinator);
  7105. $potentialMatches_len++;
  7106. }
  7107. for($i = 0; $i < $potentialMatches_len; $i++ ){
  7108. $potentialMatch = &$potentialMatches[$i];
  7109. $potentialMatch = $this->PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex );
  7110. // if we are still valid and have finished, test whether we have elements after and whether these are allowed
  7111. if( $potentialMatch && $potentialMatch['matched'] === $extend->selector->elements_len ){
  7112. $potentialMatch['finished'] = true;
  7113. if( !$extend->allowAfter && ($hackstackElementIndex+1 < $haystack_elements_len || $haystackSelectorIndex+1 < $haystack_path_len) ){
  7114. $potentialMatch = null;
  7115. }
  7116. }
  7117. // if null we remove, if not, we are still valid, so either push as a valid match or continue
  7118. if( $potentialMatch ){
  7119. if( $potentialMatch['finished'] ){
  7120. $potentialMatch['length'] = $extend->selector->elements_len;
  7121. $potentialMatch['endPathIndex'] = $haystackSelectorIndex;
  7122. $potentialMatch['endPathElementIndex'] = $hackstackElementIndex + 1; // index after end of match
  7123. $potentialMatches = array(); // we don't allow matches to overlap, so start matching again
  7124. $potentialMatches_len = 0;
  7125. $matches[] = $potentialMatch;
  7126. }
  7127. continue;
  7128. }
  7129. array_splice($potentialMatches, $i, 1);
  7130. $potentialMatches_len--;
  7131. $i--;
  7132. }
  7133. }
  7134. }
  7135. return $matches;
  7136. }
  7137. // Before going through all the nested loops, lets check to see if a match is possible
  7138. // Reduces Bootstrap 3.1 compile time from ~6.5s to ~5.6s
  7139. private function HasMatches($extend, $haystackSelectorPath){
  7140. if( !$extend->selector->cacheable ){
  7141. return true;
  7142. }
  7143. $first_el = $extend->selector->_oelements[0];
  7144. foreach($haystackSelectorPath as $hackstackSelector){
  7145. if( !$hackstackSelector->cacheable ){
  7146. return true;
  7147. }
  7148. if( in_array($first_el, $hackstackSelector->_oelements) ){
  7149. return true;
  7150. }
  7151. }
  7152. return false;
  7153. }
  7154. /**
  7155. * @param integer $hackstackElementIndex
  7156. */
  7157. private function PotentialMatch( $potentialMatch, $needleElements, $haystackElement, $hackstackElementIndex ){
  7158. if( $potentialMatch['matched'] > 0 ){
  7159. // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
  7160. // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
  7161. // what the resulting combinator will be
  7162. $targetCombinator = $haystackElement->combinator;
  7163. if( $targetCombinator === '' && $hackstackElementIndex === 0 ){
  7164. $targetCombinator = ' ';
  7165. }
  7166. if( $needleElements[ $potentialMatch['matched'] ]->combinator !== $targetCombinator ){
  7167. return null;
  7168. }
  7169. }
  7170. // if we don't match, null our match to indicate failure
  7171. if( !$this->isElementValuesEqual( $needleElements[$potentialMatch['matched'] ]->value, $haystackElement->value) ){
  7172. return null;
  7173. }
  7174. $potentialMatch['finished'] = false;
  7175. $potentialMatch['matched']++;
  7176. return $potentialMatch;
  7177. }
  7178. private function isElementValuesEqual( $elementValue1, $elementValue2 ){
  7179. if( $elementValue1 === $elementValue2 ){
  7180. return true;
  7181. }
  7182. if( is_string($elementValue1) || is_string($elementValue2) ) {
  7183. return false;
  7184. }
  7185. if( $elementValue1 instanceof Less_Tree_Attribute ){
  7186. return $this->isAttributeValuesEqual( $elementValue1, $elementValue2 );
  7187. }
  7188. $elementValue1 = $elementValue1->value;
  7189. if( $elementValue1 instanceof Less_Tree_Selector ){
  7190. return $this->isSelectorValuesEqual( $elementValue1, $elementValue2 );
  7191. }
  7192. return false;
  7193. }
  7194. /**
  7195. * @param Less_Tree_Selector $elementValue1
  7196. */
  7197. private function isSelectorValuesEqual( $elementValue1, $elementValue2 ){
  7198. $elementValue2 = $elementValue2->value;
  7199. if( !($elementValue2 instanceof Less_Tree_Selector) || $elementValue1->elements_len !== $elementValue2->elements_len ){
  7200. return false;
  7201. }
  7202. for( $i = 0; $i < $elementValue1->elements_len; $i++ ){
  7203. if( $elementValue1->elements[$i]->combinator !== $elementValue2->elements[$i]->combinator ){
  7204. if( $i !== 0 || ($elementValue1->elements[$i]->combinator || ' ') !== ($elementValue2->elements[$i]->combinator || ' ') ){
  7205. return false;
  7206. }
  7207. }
  7208. if( !$this->isElementValuesEqual($elementValue1->elements[$i]->value, $elementValue2->elements[$i]->value) ){
  7209. return false;
  7210. }
  7211. }
  7212. return true;
  7213. }
  7214. /**
  7215. * @param Less_Tree_Attribute $elementValue1
  7216. */
  7217. private function isAttributeValuesEqual( $elementValue1, $elementValue2 ){
  7218. if( $elementValue1->op !== $elementValue2->op || $elementValue1->key !== $elementValue2->key ){
  7219. return false;
  7220. }
  7221. if( !$elementValue1->value || !$elementValue2->value ){
  7222. if( $elementValue1->value || $elementValue2->value ) {
  7223. return false;
  7224. }
  7225. return true;
  7226. }
  7227. $elementValue1 = ($elementValue1->value->value ? $elementValue1->value->value : $elementValue1->value );
  7228. $elementValue2 = ($elementValue2->value->value ? $elementValue2->value->value : $elementValue2->value );
  7229. return $elementValue1 === $elementValue2;
  7230. }
  7231. private function extendSelector($matches, $selectorPath, $replacementSelector){
  7232. //for a set of matches, replace each match with the replacement selector
  7233. $currentSelectorPathIndex = 0;
  7234. $currentSelectorPathElementIndex = 0;
  7235. $path = array();
  7236. $selectorPath_len = count($selectorPath);
  7237. for($matchIndex = 0, $matches_len = count($matches); $matchIndex < $matches_len; $matchIndex++ ){
  7238. $match = $matches[$matchIndex];
  7239. $selector = $selectorPath[ $match['pathIndex'] ];
  7240. $firstElement = new Less_Tree_Element(
  7241. $match['initialCombinator'],
  7242. $replacementSelector->elements[0]->value,
  7243. $replacementSelector->elements[0]->index,
  7244. $replacementSelector->elements[0]->currentFileInfo
  7245. );
  7246. if( $match['pathIndex'] > $currentSelectorPathIndex && $currentSelectorPathElementIndex > 0 ){
  7247. $last_path = end($path);
  7248. $last_path->elements = array_merge( $last_path->elements, array_slice( $selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
  7249. $currentSelectorPathElementIndex = 0;
  7250. $currentSelectorPathIndex++;
  7251. }
  7252. $newElements = array_merge(
  7253. array_slice($selector->elements, $currentSelectorPathElementIndex, ($match['index'] - $currentSelectorPathElementIndex) ) // last parameter of array_slice is different than the last parameter of javascript's slice
  7254. , array($firstElement)
  7255. , array_slice($replacementSelector->elements,1)
  7256. );
  7257. if( $currentSelectorPathIndex === $match['pathIndex'] && $matchIndex > 0 ){
  7258. $last_key = count($path)-1;
  7259. $path[$last_key]->elements = array_merge($path[$last_key]->elements,$newElements);
  7260. }else{
  7261. $path = array_merge( $path, array_slice( $selectorPath, $currentSelectorPathIndex, $match['pathIndex'] ));
  7262. $path[] = new Less_Tree_Selector( $newElements );
  7263. }
  7264. $currentSelectorPathIndex = $match['endPathIndex'];
  7265. $currentSelectorPathElementIndex = $match['endPathElementIndex'];
  7266. if( $currentSelectorPathElementIndex >= count($selectorPath[$currentSelectorPathIndex]->elements) ){
  7267. $currentSelectorPathElementIndex = 0;
  7268. $currentSelectorPathIndex++;
  7269. }
  7270. }
  7271. if( $currentSelectorPathIndex < $selectorPath_len && $currentSelectorPathElementIndex > 0 ){
  7272. $last_path = end($path);
  7273. $last_path->elements = array_merge( $last_path->elements, array_slice($selectorPath[$currentSelectorPathIndex]->elements, $currentSelectorPathElementIndex));
  7274. $currentSelectorPathIndex++;
  7275. }
  7276. $slice_len = $selectorPath_len - $currentSelectorPathIndex;
  7277. $path = array_merge($path, array_slice($selectorPath, $currentSelectorPathIndex, $slice_len));
  7278. return $path;
  7279. }
  7280. protected function visitMedia( $mediaNode ){
  7281. $newAllExtends = array_merge( $mediaNode->allExtends, end($this->allExtendsStack) );
  7282. $this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $mediaNode->allExtends);
  7283. }
  7284. protected function visitMediaOut(){
  7285. array_pop( $this->allExtendsStack );
  7286. }
  7287. protected function visitDirective( $directiveNode ){
  7288. $newAllExtends = array_merge( $directiveNode->allExtends, end($this->allExtendsStack) );
  7289. $this->allExtendsStack[] = $this->doExtendChaining($newAllExtends, $directiveNode->allExtends);
  7290. }
  7291. protected function visitDirectiveOut(){
  7292. array_pop($this->allExtendsStack);
  7293. }
  7294. }
  7295. /**
  7296. * toCSS Visitor
  7297. *
  7298. * @package Less
  7299. * @subpackage visitor
  7300. */
  7301. class Less_Visitor_toCSS extends Less_VisitorReplacing{
  7302. private $charset;
  7303. public function __construct(){
  7304. parent::__construct();
  7305. }
  7306. /**
  7307. * @param Less_Tree_Ruleset $root
  7308. */
  7309. public function run( $root ){
  7310. return $this->visitObj($root);
  7311. }
  7312. public function visitRule( $ruleNode ){
  7313. if( $ruleNode->variable ){
  7314. return array();
  7315. }
  7316. return $ruleNode;
  7317. }
  7318. public function visitMixinDefinition($mixinNode){
  7319. // mixin definitions do not get eval'd - this means they keep state
  7320. // so we have to clear that state here so it isn't used if toCSS is called twice
  7321. $mixinNode->frames = array();
  7322. return array();
  7323. }
  7324. public function visitExtend(){
  7325. return array();
  7326. }
  7327. public function visitComment( $commentNode ){
  7328. if( $commentNode->isSilent() ){
  7329. return array();
  7330. }
  7331. return $commentNode;
  7332. }
  7333. public function visitMedia( $mediaNode, &$visitDeeper ){
  7334. $mediaNode->accept($this);
  7335. $visitDeeper = false;
  7336. if( !$mediaNode->rules ){
  7337. return array();
  7338. }
  7339. return $mediaNode;
  7340. }
  7341. public function visitDirective( $directiveNode ){
  7342. if( isset($directiveNode->currentFileInfo['reference']) && (!property_exists($directiveNode,'isReferenced') || !$directiveNode->isReferenced) ){
  7343. return array();
  7344. }
  7345. if( $directiveNode->name === '@charset' ){
  7346. // Only output the debug info together with subsequent @charset definitions
  7347. // a comment (or @media statement) before the actual @charset directive would
  7348. // be considered illegal css as it has to be on the first line
  7349. if( isset($this->charset) && $this->charset ){
  7350. //if( $directiveNode->debugInfo ){
  7351. // $comment = new Less_Tree_Comment('/* ' . str_replace("\n",'',$directiveNode->toCSS())." */\n");
  7352. // $comment->debugInfo = $directiveNode->debugInfo;
  7353. // return $this->visit($comment);
  7354. //}
  7355. return array();
  7356. }
  7357. $this->charset = true;
  7358. }
  7359. return $directiveNode;
  7360. }
  7361. public function checkPropertiesInRoot( $rulesetNode ){
  7362. if( !$rulesetNode->firstRoot ){
  7363. return;
  7364. }
  7365. foreach($rulesetNode->rules as $ruleNode){
  7366. if( $ruleNode instanceof Less_Tree_Rule && !$ruleNode->variable ){
  7367. $msg = "properties must be inside selector blocks, they cannot be in the root. Index ".$ruleNode->index.($ruleNode->currentFileInfo ? (' Filename: '.$ruleNode->currentFileInfo['filename']) : null);
  7368. throw new Less_Exception_Compiler($msg);
  7369. }
  7370. }
  7371. }
  7372. public function visitRuleset( $rulesetNode, &$visitDeeper ){
  7373. $visitDeeper = false;
  7374. $this->checkPropertiesInRoot( $rulesetNode );
  7375. if( $rulesetNode->root ){
  7376. return $this->visitRulesetRoot( $rulesetNode );
  7377. }
  7378. $rulesets = array();
  7379. $rulesetNode->paths = $this->visitRulesetPaths($rulesetNode);
  7380. // Compile rules and rulesets
  7381. $nodeRuleCnt = count($rulesetNode->rules);
  7382. for( $i = 0; $i < $nodeRuleCnt; ){
  7383. $rule = $rulesetNode->rules[$i];
  7384. if( property_exists($rule,'rules') ){
  7385. // visit because we are moving them out from being a child
  7386. $rulesets[] = $this->visitObj($rule);
  7387. array_splice($rulesetNode->rules,$i,1);
  7388. $nodeRuleCnt--;
  7389. continue;
  7390. }
  7391. $i++;
  7392. }
  7393. // accept the visitor to remove rules and refactor itself
  7394. // then we can decide now whether we want it or not
  7395. if( $nodeRuleCnt > 0 ){
  7396. $rulesetNode->accept($this);
  7397. if( $rulesetNode->rules ){
  7398. if( count($rulesetNode->rules) > 1 ){
  7399. $this->_mergeRules( $rulesetNode->rules );
  7400. $this->_removeDuplicateRules( $rulesetNode->rules );
  7401. }
  7402. // now decide whether we keep the ruleset
  7403. if( $rulesetNode->paths ){
  7404. //array_unshift($rulesets, $rulesetNode);
  7405. array_splice($rulesets,0,0,array($rulesetNode));
  7406. }
  7407. }
  7408. }
  7409. if( count($rulesets) === 1 ){
  7410. return $rulesets[0];
  7411. }
  7412. return $rulesets;
  7413. }
  7414. /**
  7415. * Helper function for visitiRuleset
  7416. *
  7417. * return array|Less_Tree_Ruleset
  7418. */
  7419. private function visitRulesetRoot( $rulesetNode ){
  7420. $rulesetNode->accept( $this );
  7421. if( $rulesetNode->firstRoot || $rulesetNode->rules ){
  7422. return $rulesetNode;
  7423. }
  7424. return array();
  7425. }
  7426. /**
  7427. * Helper function for visitRuleset()
  7428. *
  7429. * @return array
  7430. */
  7431. private function visitRulesetPaths($rulesetNode){
  7432. $paths = array();
  7433. foreach($rulesetNode->paths as $p){
  7434. if( $p[0]->elements[0]->combinator === ' ' ){
  7435. $p[0]->elements[0]->combinator = '';
  7436. }
  7437. foreach($p as $pi){
  7438. if( $pi->getIsReferenced() && $pi->getIsOutput() ){
  7439. $paths[] = $p;
  7440. break;
  7441. }
  7442. }
  7443. }
  7444. return $paths;
  7445. }
  7446. protected function _removeDuplicateRules( &$rules ){
  7447. // remove duplicates
  7448. $ruleCache = array();
  7449. for( $i = count($rules)-1; $i >= 0 ; $i-- ){
  7450. $rule = $rules[$i];
  7451. if( $rule instanceof Less_Tree_Rule || $rule instanceof Less_Tree_NameValue ){
  7452. if( !isset($ruleCache[$rule->name]) ){
  7453. $ruleCache[$rule->name] = $rule;
  7454. }else{
  7455. $ruleList =& $ruleCache[$rule->name];
  7456. if( $ruleList instanceof Less_Tree_Rule || $ruleList instanceof Less_Tree_NameValue ){
  7457. $ruleList = $ruleCache[$rule->name] = array( $ruleCache[$rule->name]->toCSS() );
  7458. }
  7459. $ruleCSS = $rule->toCSS();
  7460. if( array_search($ruleCSS,$ruleList) !== false ){
  7461. array_splice($rules,$i,1);
  7462. }else{
  7463. $ruleList[] = $ruleCSS;
  7464. }
  7465. }
  7466. }
  7467. }
  7468. }
  7469. protected function _mergeRules( &$rules ){
  7470. $groups = array();
  7471. //obj($rules);
  7472. $rules_len = count($rules);
  7473. for( $i = 0; $i < $rules_len; $i++ ){
  7474. $rule = $rules[$i];
  7475. if( ($rule instanceof Less_Tree_Rule) && $rule->merge ){
  7476. $key = $rule->name;
  7477. if( $rule->important ){
  7478. $key .= ',!';
  7479. }
  7480. if( !isset($groups[$key]) ){
  7481. $groups[$key] = array();
  7482. }else{
  7483. array_splice($rules, $i--, 1);
  7484. $rules_len--;
  7485. }
  7486. $groups[$key][] = $rule;
  7487. }
  7488. }
  7489. foreach($groups as $parts){
  7490. if( count($parts) > 1 ){
  7491. $rule = $parts[0];
  7492. $spacedGroups = array();
  7493. $lastSpacedGroup = array();
  7494. $parts_mapped = array();
  7495. foreach($parts as $p){
  7496. if( $p->merge === '+' ){
  7497. if( $lastSpacedGroup ){
  7498. $spacedGroups[] = self::toExpression($lastSpacedGroup);
  7499. }
  7500. $lastSpacedGroup = array();
  7501. }
  7502. $lastSpacedGroup[] = $p;
  7503. }
  7504. $spacedGroups[] = self::toExpression($lastSpacedGroup);
  7505. $rule->value = self::toValue($spacedGroups);
  7506. }
  7507. }
  7508. }
  7509. public static function toExpression($values){
  7510. $mapped = array();
  7511. foreach($values as $p){
  7512. $mapped[] = $p->value;
  7513. }
  7514. return new Less_Tree_Expression( $mapped );
  7515. }
  7516. public static function toValue($values){
  7517. //return new Less_Tree_Value($values); ??
  7518. $mapped = array();
  7519. foreach($values as $p){
  7520. $mapped[] = $p;
  7521. }
  7522. return new Less_Tree_Value($mapped);
  7523. }
  7524. }
  7525. /**
  7526. * Parser Exception
  7527. *
  7528. * @package Less
  7529. * @subpackage exception
  7530. */
  7531. class Less_Exception_Parser extends Exception{
  7532. /**
  7533. * The current file
  7534. *
  7535. * @var Less_ImportedFile
  7536. */
  7537. public $currentFile;
  7538. /**
  7539. * The current parser index
  7540. *
  7541. * @var integer
  7542. */
  7543. public $index;
  7544. protected $input;
  7545. protected $details = array();
  7546. /**
  7547. * Constructor
  7548. *
  7549. * @param string $message
  7550. * @param Exception $previous Previous exception
  7551. * @param integer $index The current parser index
  7552. * @param Less_FileInfo|string $currentFile The file
  7553. * @param integer $code The exception code
  7554. */
  7555. public function __construct($message = null, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
  7556. if (PHP_VERSION_ID < 50300) {
  7557. $this->previous = $previous;
  7558. parent::__construct($message, $code);
  7559. } else {
  7560. parent::__construct($message, $code, $previous);
  7561. }
  7562. $this->currentFile = $currentFile;
  7563. $this->index = $index;
  7564. $this->genMessage();
  7565. }
  7566. protected function getInput(){
  7567. if( !$this->input && $this->currentFile && $this->currentFile['filename'] && file_exists($this->currentFile['filename']) ){
  7568. $this->input = file_get_contents( $this->currentFile['filename'] );
  7569. }
  7570. }
  7571. /**
  7572. * Converts the exception to string
  7573. *
  7574. * @return string
  7575. */
  7576. public function genMessage(){
  7577. if( $this->currentFile && $this->currentFile['filename'] ){
  7578. $this->message .= ' in '.basename($this->currentFile['filename']);
  7579. }
  7580. if( $this->index !== null ){
  7581. $this->getInput();
  7582. if( $this->input ){
  7583. $line = self::getLineNumber();
  7584. $this->message .= ' on line '.$line.', column '.self::getColumn();
  7585. $lines = explode("\n",$this->input);
  7586. $count = count($lines);
  7587. $start_line = max(0, $line-3);
  7588. $last_line = min($count, $start_line+6);
  7589. $num_len = strlen($last_line);
  7590. for( $i = $start_line; $i < $last_line; $i++ ){
  7591. $this->message .= "\n".str_pad($i+1,$num_len,'0',STR_PAD_LEFT).'| '.$lines[$i];
  7592. }
  7593. }
  7594. }
  7595. }
  7596. /**
  7597. * Returns the line number the error was encountered
  7598. *
  7599. * @return integer
  7600. */
  7601. public function getLineNumber(){
  7602. if( $this->index ){
  7603. // https://bugs.php.net/bug.php?id=49790
  7604. if (ini_get("mbstring.func_overload")) {
  7605. return substr_count(substr($this->input, 0, $this->index), "\n") + 1;
  7606. } else {
  7607. return substr_count($this->input, "\n", 0, $this->index) + 1;
  7608. }
  7609. }
  7610. return 1;
  7611. }
  7612. /**
  7613. * Returns the column the error was encountered
  7614. *
  7615. * @return integer
  7616. */
  7617. public function getColumn(){
  7618. $part = substr($this->input, 0, $this->index);
  7619. $pos = strrpos($part,"\n");
  7620. return $this->index - $pos;
  7621. }
  7622. }
  7623. /**
  7624. * Chunk Exception
  7625. *
  7626. * @package Less
  7627. * @subpackage exception
  7628. */
  7629. class Less_Exception_Chunk extends Less_Exception_Parser{
  7630. protected $parserCurrentIndex = 0;
  7631. protected $emitFrom = 0;
  7632. protected $input_len;
  7633. /**
  7634. * Constructor
  7635. *
  7636. * @param string $input
  7637. * @param Exception $previous Previous exception
  7638. * @param integer $index The current parser index
  7639. * @param Less_FileInfo|string $currentFile The file
  7640. * @param integer $code The exception code
  7641. */
  7642. public function __construct($input, Exception $previous = null, $index = null, $currentFile = null, $code = 0){
  7643. $this->message = 'ParseError: Unexpected input'; //default message
  7644. $this->index = $index;
  7645. $this->currentFile = $currentFile;
  7646. $this->input = $input;
  7647. $this->input_len = strlen($input);
  7648. $this->Chunks();
  7649. $this->genMessage();
  7650. }
  7651. /**
  7652. * See less.js chunks()
  7653. * We don't actually need the chunks
  7654. *
  7655. */
  7656. protected function Chunks(){
  7657. $level = 0;
  7658. $parenLevel = 0;
  7659. $lastMultiCommentEndBrace = null;
  7660. $lastOpening = null;
  7661. $lastMultiComment = null;
  7662. $lastParen = null;
  7663. for( $this->parserCurrentIndex = 0; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++ ){
  7664. $cc = $this->CharCode($this->parserCurrentIndex);
  7665. if ((($cc >= 97) && ($cc <= 122)) || ($cc < 34)) {
  7666. // a-z or whitespace
  7667. continue;
  7668. }
  7669. switch ($cc) {
  7670. // (
  7671. case 40:
  7672. $parenLevel++;
  7673. $lastParen = $this->parserCurrentIndex;
  7674. continue;
  7675. // )
  7676. case 41:
  7677. $parenLevel--;
  7678. if( $parenLevel < 0 ){
  7679. return $this->fail("missing opening `(`");
  7680. }
  7681. continue;
  7682. // ;
  7683. case 59:
  7684. //if (!$parenLevel) { $this->emitChunk(); }
  7685. continue;
  7686. // {
  7687. case 123:
  7688. $level++;
  7689. $lastOpening = $this->parserCurrentIndex;
  7690. continue;
  7691. // }
  7692. case 125:
  7693. $level--;
  7694. if( $level < 0 ){
  7695. return $this->fail("missing opening `{`");
  7696. }
  7697. //if (!$level && !$parenLevel) { $this->emitChunk(); }
  7698. continue;
  7699. // \
  7700. case 92:
  7701. if ($this->parserCurrentIndex < $this->input_len - 1) { $this->parserCurrentIndex++; continue; }
  7702. return $this->fail("unescaped `\\`");
  7703. // ", ' and `
  7704. case 34:
  7705. case 39:
  7706. case 96:
  7707. $matched = 0;
  7708. $currentChunkStartIndex = $this->parserCurrentIndex;
  7709. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 1; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
  7710. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7711. if ($cc2 > 96) { continue; }
  7712. if ($cc2 == $cc) { $matched = 1; break; }
  7713. if ($cc2 == 92) { // \
  7714. if ($this->parserCurrentIndex == $this->input_len - 1) {
  7715. return $this->fail("unescaped `\\`");
  7716. }
  7717. $this->parserCurrentIndex++;
  7718. }
  7719. }
  7720. if ($matched) { continue; }
  7721. return $this->fail("unmatched `" + chr($cc) + "`", $currentChunkStartIndex);
  7722. // /, check for comment
  7723. case 47:
  7724. if ($parenLevel || ($this->parserCurrentIndex == $this->input_len - 1)) { continue; }
  7725. $cc2 = $this->CharCode($this->parserCurrentIndex+1);
  7726. if ($cc2 == 47) {
  7727. // //, find lnfeed
  7728. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len; $this->parserCurrentIndex++) {
  7729. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7730. if (($cc2 <= 13) && (($cc2 == 10) || ($cc2 == 13))) { break; }
  7731. }
  7732. } else if ($cc2 == 42) {
  7733. // /*, find */
  7734. $lastMultiComment = $currentChunkStartIndex = $this->parserCurrentIndex;
  7735. for ($this->parserCurrentIndex = $this->parserCurrentIndex + 2; $this->parserCurrentIndex < $this->input_len - 1; $this->parserCurrentIndex++) {
  7736. $cc2 = $this->CharCode($this->parserCurrentIndex);
  7737. if ($cc2 == 125) { $lastMultiCommentEndBrace = $this->parserCurrentIndex; }
  7738. if ($cc2 != 42) { continue; }
  7739. if ($this->CharCode($this->parserCurrentIndex+1) == 47) { break; }
  7740. }
  7741. if ($this->parserCurrentIndex == $this->input_len - 1) {
  7742. return $this->fail("missing closing `*/`", $currentChunkStartIndex);
  7743. }
  7744. }
  7745. continue;
  7746. // *, check for unmatched */
  7747. case 42:
  7748. if (($this->parserCurrentIndex < $this->input_len - 1) && ($this->CharCode($this->parserCurrentIndex+1) == 47)) {
  7749. return $this->fail("unmatched `/*`");
  7750. }
  7751. continue;
  7752. }
  7753. }
  7754. if( $level !== 0 ){
  7755. if( ($lastMultiComment > $lastOpening) && ($lastMultiCommentEndBrace > $lastMultiComment) ){
  7756. return $this->fail("missing closing `}` or `*/`", $lastOpening);
  7757. } else {
  7758. return $this->fail("missing closing `}`", $lastOpening);
  7759. }
  7760. } else if ( $parenLevel !== 0 ){
  7761. return $this->fail("missing closing `)`", $lastParen);
  7762. }
  7763. //chunk didn't fail
  7764. //$this->emitChunk(true);
  7765. }
  7766. public function CharCode($pos){
  7767. return ord($this->input[$pos]);
  7768. }
  7769. public function fail( $msg, $index = null ){
  7770. if( !$index ){
  7771. $this->index = $this->parserCurrentIndex;
  7772. }else{
  7773. $this->index = $index;
  7774. }
  7775. $this->message = 'ParseError: '.$msg;
  7776. }
  7777. /*
  7778. function emitChunk( $force = false ){
  7779. $len = $this->parserCurrentIndex - $this->emitFrom;
  7780. if ((($len < 512) && !$force) || !$len) {
  7781. return;
  7782. }
  7783. $chunks[] = substr($this->input, $this->emitFrom, $this->parserCurrentIndex + 1 - $this->emitFrom );
  7784. $this->emitFrom = $this->parserCurrentIndex + 1;
  7785. }
  7786. */
  7787. }
  7788. /**
  7789. * Compiler Exception
  7790. *
  7791. * @package Less
  7792. * @subpackage exception
  7793. */
  7794. class Less_Exception_Compiler extends Less_Exception_Parser{
  7795. }
  7796. /**
  7797. * Parser output with source map
  7798. *
  7799. * @package Less
  7800. * @subpackage Output
  7801. */
  7802. class Less_Output_Mapped extends Less_Output {
  7803. /**
  7804. * The source map generator
  7805. *
  7806. * @var Less_SourceMap_Generator
  7807. */
  7808. protected $generator;
  7809. /**
  7810. * Current line
  7811. *
  7812. * @var integer
  7813. */
  7814. protected $lineNumber = 0;
  7815. /**
  7816. * Current column
  7817. *
  7818. * @var integer
  7819. */
  7820. protected $column = 0;
  7821. /**
  7822. * Array of contents map (file and its content)
  7823. *
  7824. * @var array
  7825. */
  7826. protected $contentsMap = array();
  7827. /**
  7828. * Constructor
  7829. *
  7830. * @param array $contentsMap Array of filename to contents map
  7831. * @param Less_SourceMap_Generator $generator
  7832. */
  7833. public function __construct(array $contentsMap, $generator){
  7834. $this->contentsMap = $contentsMap;
  7835. $this->generator = $generator;
  7836. }
  7837. /**
  7838. * Adds a chunk to the stack
  7839. * The $index for less.php may be different from less.js since less.php does not chunkify inputs
  7840. *
  7841. * @param string $chunk
  7842. * @param string $fileInfo
  7843. * @param integer $index
  7844. * @param mixed $mapLines
  7845. */
  7846. public function add($chunk, $fileInfo = null, $index = 0, $mapLines = null){
  7847. //ignore adding empty strings
  7848. if( $chunk === '' ){
  7849. return;
  7850. }
  7851. $sourceLines = array();
  7852. $sourceColumns = ' ';
  7853. if( $fileInfo ){
  7854. $url = $fileInfo['currentUri'];
  7855. if( isset($this->contentsMap[$url]) ){
  7856. $inputSource = substr($this->contentsMap[$url], 0, $index);
  7857. $sourceLines = explode("\n", $inputSource);
  7858. $sourceColumns = end($sourceLines);
  7859. }else{
  7860. throw new Exception('Filename '.$url.' not in contentsMap');
  7861. }
  7862. }
  7863. $lines = explode("\n", $chunk);
  7864. $columns = end($lines);
  7865. if($fileInfo){
  7866. if(!$mapLines){
  7867. $this->generator->addMapping(
  7868. $this->lineNumber + 1, // generated_line
  7869. $this->column, // generated_column
  7870. count($sourceLines), // original_line
  7871. strlen($sourceColumns), // original_column
  7872. $fileInfo
  7873. );
  7874. }else{
  7875. for($i = 0, $count = count($lines); $i < $count; $i++){
  7876. $this->generator->addMapping(
  7877. $this->lineNumber + $i + 1, // generated_line
  7878. $i === 0 ? $this->column : 0, // generated_column
  7879. count($sourceLines) + $i, // original_line
  7880. $i === 0 ? strlen($sourceColumns) : 0, // original_column
  7881. $fileInfo
  7882. );
  7883. }
  7884. }
  7885. }
  7886. if(count($lines) === 1){
  7887. $this->column += strlen($columns);
  7888. }else{
  7889. $this->lineNumber += count($lines) - 1;
  7890. $this->column = strlen($columns);
  7891. }
  7892. // add only chunk
  7893. parent::add($chunk);
  7894. }
  7895. }
  7896. /**
  7897. * Encode / Decode Base64 VLQ.
  7898. *
  7899. * @package Less
  7900. * @subpackage SourceMap
  7901. */
  7902. class Less_SourceMap_Base64VLQ {
  7903. /**
  7904. * Shift
  7905. *
  7906. * @var integer
  7907. */
  7908. private $shift = 5;
  7909. /**
  7910. * Mask
  7911. *
  7912. * @var integer
  7913. */
  7914. private $mask = 0x1F; // == (1 << shift) == 0b00011111
  7915. /**
  7916. * Continuation bit
  7917. *
  7918. * @var integer
  7919. */
  7920. private $continuationBit = 0x20; // == (mask - 1 ) == 0b00100000
  7921. /**
  7922. * Char to integer map
  7923. *
  7924. * @var array
  7925. */
  7926. private $charToIntMap = array(
  7927. 'A' => 0, 'B' => 1, 'C' => 2, 'D' => 3, 'E' => 4, 'F' => 5, 'G' => 6,
  7928. 'H' => 7,'I' => 8, 'J' => 9, 'K' => 10, 'L' => 11, 'M' => 12, 'N' => 13,
  7929. 'O' => 14, 'P' => 15, 'Q' => 16, 'R' => 17, 'S' => 18, 'T' => 19, 'U' => 20,
  7930. 'V' => 21, 'W' => 22, 'X' => 23, 'Y' => 24, 'Z' => 25, 'a' => 26, 'b' => 27,
  7931. 'c' => 28, 'd' => 29, 'e' => 30, 'f' => 31, 'g' => 32, 'h' => 33, 'i' => 34,
  7932. 'j' => 35, 'k' => 36, 'l' => 37, 'm' => 38, 'n' => 39, 'o' => 40, 'p' => 41,
  7933. 'q' => 42, 'r' => 43, 's' => 44, 't' => 45, 'u' => 46, 'v' => 47, 'w' => 48,
  7934. 'x' => 49, 'y' => 50, 'z' => 51, 0 => 52, 1 => 53, 2 => 54, 3 => 55, 4 => 56,
  7935. 5 => 57, 6 => 58, 7 => 59, 8 => 60, 9 => 61, '+' => 62, '/' => 63,
  7936. );
  7937. /**
  7938. * Integer to char map
  7939. *
  7940. * @var array
  7941. */
  7942. private $intToCharMap = array(
  7943. 0 => 'A', 1 => 'B', 2 => 'C', 3 => 'D', 4 => 'E', 5 => 'F', 6 => 'G',
  7944. 7 => 'H', 8 => 'I', 9 => 'J', 10 => 'K', 11 => 'L', 12 => 'M', 13 => 'N',
  7945. 14 => 'O', 15 => 'P', 16 => 'Q', 17 => 'R', 18 => 'S', 19 => 'T', 20 => 'U',
  7946. 21 => 'V', 22 => 'W', 23 => 'X', 24 => 'Y', 25 => 'Z', 26 => 'a', 27 => 'b',
  7947. 28 => 'c', 29 => 'd', 30 => 'e', 31 => 'f', 32 => 'g', 33 => 'h', 34 => 'i',
  7948. 35 => 'j', 36 => 'k', 37 => 'l', 38 => 'm', 39 => 'n', 40 => 'o', 41 => 'p',
  7949. 42 => 'q', 43 => 'r', 44 => 's', 45 => 't', 46 => 'u', 47 => 'v', 48 => 'w',
  7950. 49 => 'x', 50 => 'y', 51 => 'z', 52 => '0', 53 => '1', 54 => '2', 55 => '3',
  7951. 56 => '4', 57 => '5', 58 => '6', 59 => '7', 60 => '8', 61 => '9', 62 => '+',
  7952. 63 => '/',
  7953. );
  7954. /**
  7955. * Constructor
  7956. */
  7957. public function __construct(){
  7958. // I leave it here for future reference
  7959. // foreach(str_split('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/') as $i => $char)
  7960. // {
  7961. // $this->charToIntMap[$char] = $i;
  7962. // $this->intToCharMap[$i] = $char;
  7963. // }
  7964. }
  7965. /**
  7966. * Convert from a two-complement value to a value where the sign bit is
  7967. * is placed in the least significant bit. For example, as decimals:
  7968. * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
  7969. * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
  7970. * We generate the value for 32 bit machines, hence -2147483648 becomes 1, not 4294967297,
  7971. * even on a 64 bit machine.
  7972. * @param string $aValue
  7973. */
  7974. public function toVLQSigned($aValue){
  7975. return 0xffffffff & ($aValue < 0 ? ((-$aValue) << 1) + 1 : ($aValue << 1) + 0);
  7976. }
  7977. /**
  7978. * Convert to a two-complement value from a value where the sign bit is
  7979. * is placed in the least significant bit. For example, as decimals:
  7980. * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
  7981. * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
  7982. * We assume that the value was generated with a 32 bit machine in mind.
  7983. * Hence
  7984. * 1 becomes -2147483648
  7985. * even on a 64 bit machine.
  7986. * @param integer $aValue
  7987. */
  7988. public function fromVLQSigned($aValue){
  7989. return $aValue & 1 ? $this->zeroFill(~$aValue + 2, 1) | (-1 - 0x7fffffff) : $this->zeroFill($aValue, 1);
  7990. }
  7991. /**
  7992. * Return the base 64 VLQ encoded value.
  7993. *
  7994. * @param string $aValue The value to encode
  7995. * @return string The encoded value
  7996. */
  7997. public function encode($aValue){
  7998. $encoded = '';
  7999. $vlq = $this->toVLQSigned($aValue);
  8000. do
  8001. {
  8002. $digit = $vlq & $this->mask;
  8003. $vlq = $this->zeroFill($vlq, $this->shift);
  8004. if($vlq > 0){
  8005. $digit |= $this->continuationBit;
  8006. }
  8007. $encoded .= $this->base64Encode($digit);
  8008. } while($vlq > 0);
  8009. return $encoded;
  8010. }
  8011. /**
  8012. * Return the value decoded from base 64 VLQ.
  8013. *
  8014. * @param string $encoded The encoded value to decode
  8015. * @return integer The decoded value
  8016. */
  8017. public function decode($encoded){
  8018. $vlq = 0;
  8019. $i = 0;
  8020. do
  8021. {
  8022. $digit = $this->base64Decode($encoded[$i]);
  8023. $vlq |= ($digit & $this->mask) << ($i * $this->shift);
  8024. $i++;
  8025. } while($digit & $this->continuationBit);
  8026. return $this->fromVLQSigned($vlq);
  8027. }
  8028. /**
  8029. * Right shift with zero fill.
  8030. *
  8031. * @param integer $a number to shift
  8032. * @param integer $b number of bits to shift
  8033. * @return integer
  8034. */
  8035. public function zeroFill($a, $b){
  8036. return ($a >= 0) ? ($a >> $b) : ($a >> $b) & (PHP_INT_MAX >> ($b - 1));
  8037. }
  8038. /**
  8039. * Encode single 6-bit digit as base64.
  8040. *
  8041. * @param integer $number
  8042. * @return string
  8043. * @throws Exception If the number is invalid
  8044. */
  8045. public function base64Encode($number){
  8046. if($number < 0 || $number > 63){
  8047. throw new Exception(sprintf('Invalid number "%s" given. Must be between 0 and 63.', $number));
  8048. }
  8049. return $this->intToCharMap[$number];
  8050. }
  8051. /**
  8052. * Decode single 6-bit digit from base64
  8053. *
  8054. * @param string $char
  8055. * @return number
  8056. * @throws Exception If the number is invalid
  8057. */
  8058. public function base64Decode($char){
  8059. if(!array_key_exists($char, $this->charToIntMap)){
  8060. throw new Exception(sprintf('Invalid base 64 digit "%s" given.', $char));
  8061. }
  8062. return $this->charToIntMap[$char];
  8063. }
  8064. }
  8065. /**
  8066. * Source map generator
  8067. *
  8068. * @package Less
  8069. * @subpackage Output
  8070. */
  8071. class Less_SourceMap_Generator extends Less_Configurable {
  8072. /**
  8073. * What version of source map does the generator generate?
  8074. */
  8075. const VERSION = 3;
  8076. /**
  8077. * Array of default options
  8078. *
  8079. * @var array
  8080. */
  8081. protected $defaultOptions = array(
  8082. // an optional source root, useful for relocating source files
  8083. // on a server or removing repeated values in the 'sources' entry.
  8084. // This value is prepended to the individual entries in the 'source' field.
  8085. 'sourceRoot' => '',
  8086. // an optional name of the generated code that this source map is associated with.
  8087. 'sourceMapFilename' => null,
  8088. // url of the map
  8089. 'sourceMapURL' => null,
  8090. // absolute path to a file to write the map to
  8091. 'sourceMapWriteTo' => null,
  8092. // output source contents?
  8093. 'outputSourceFiles' => false,
  8094. // base path for filename normalization
  8095. 'sourceMapRootpath' => '',
  8096. // base path for filename normalization
  8097. 'sourceMapBasepath' => ''
  8098. );
  8099. /**
  8100. * The base64 VLQ encoder
  8101. *
  8102. * @var Less_SourceMap_Base64VLQ
  8103. */
  8104. protected $encoder;
  8105. /**
  8106. * Array of mappings
  8107. *
  8108. * @var array
  8109. */
  8110. protected $mappings = array();
  8111. /**
  8112. * The root node
  8113. *
  8114. * @var Less_Tree_Ruleset
  8115. */
  8116. protected $root;
  8117. /**
  8118. * Array of contents map
  8119. *
  8120. * @var array
  8121. */
  8122. protected $contentsMap = array();
  8123. /**
  8124. * File to content map
  8125. *
  8126. * @var array
  8127. */
  8128. protected $sources = array();
  8129. protected $source_keys = array();
  8130. /**
  8131. * Constructor
  8132. *
  8133. * @param Less_Tree_Ruleset $root The root node
  8134. * @param array $options Array of options
  8135. */
  8136. public function __construct(Less_Tree_Ruleset $root, $contentsMap, $options = array()){
  8137. $this->root = $root;
  8138. $this->contentsMap = $contentsMap;
  8139. $this->encoder = new Less_SourceMap_Base64VLQ();
  8140. $this->SetOptions($options);
  8141. $this->options['sourceMapRootpath'] = $this->fixWindowsPath($this->options['sourceMapRootpath'], true);
  8142. $this->options['sourceMapBasepath'] = $this->fixWindowsPath($this->options['sourceMapBasepath'], true);
  8143. }
  8144. /**
  8145. * Generates the CSS
  8146. *
  8147. * @return string
  8148. */
  8149. public function generateCSS(){
  8150. $output = new Less_Output_Mapped($this->contentsMap, $this);
  8151. // catch the output
  8152. $this->root->genCSS($output);
  8153. $sourceMapUrl = $this->getOption('sourceMapURL');
  8154. $sourceMapFilename = $this->getOption('sourceMapFilename');
  8155. $sourceMapContent = $this->generateJson();
  8156. $sourceMapWriteTo = $this->getOption('sourceMapWriteTo');
  8157. if( !$sourceMapUrl && $sourceMapFilename ){
  8158. $sourceMapUrl = $this->normalizeFilename($sourceMapFilename);
  8159. }
  8160. // write map to a file
  8161. if( $sourceMapWriteTo ){
  8162. $this->saveMap($sourceMapWriteTo, $sourceMapContent);
  8163. }
  8164. // inline the map
  8165. if( !$sourceMapUrl ){
  8166. $sourceMapUrl = sprintf('data:application/json,%s', Less_Functions::encodeURIComponent($sourceMapContent));
  8167. }
  8168. if( $sourceMapUrl ){
  8169. $output->add( sprintf('/*# sourceMappingURL=%s */', $sourceMapUrl) );
  8170. }
  8171. return $output->toString();
  8172. }
  8173. /**
  8174. * Saves the source map to a file
  8175. *
  8176. * @param string $file The absolute path to a file
  8177. * @param string $content The content to write
  8178. * @throws Exception If the file could not be saved
  8179. */
  8180. protected function saveMap($file, $content){
  8181. $dir = dirname($file);
  8182. // directory does not exist
  8183. if( !is_dir($dir) ){
  8184. // FIXME: create the dir automatically?
  8185. throw new Exception(sprintf('The directory "%s" does not exist. Cannot save the source map.', $dir));
  8186. }
  8187. // FIXME: proper saving, with dir write check!
  8188. if(file_put_contents($file, $content) === false){
  8189. throw new Exception(sprintf('Cannot save the source map to "%s"', $file));
  8190. }
  8191. return true;
  8192. }
  8193. /**
  8194. * Normalizes the filename
  8195. *
  8196. * @param string $filename
  8197. * @return string
  8198. */
  8199. protected function normalizeFilename($filename){
  8200. $filename = $this->fixWindowsPath($filename);
  8201. $rootpath = $this->getOption('sourceMapRootpath');
  8202. $basePath = $this->getOption('sourceMapBasepath');
  8203. // "Trim" the 'sourceMapBasepath' from the output filename.
  8204. if (strpos($filename, $basePath) === 0) {
  8205. $filename = substr($filename, strlen($basePath));
  8206. }
  8207. // Remove extra leading path separators.
  8208. if(strpos($filename, '\\') === 0 || strpos($filename, '/') === 0){
  8209. $filename = substr($filename, 1);
  8210. }
  8211. return $rootpath . $filename;
  8212. }
  8213. /**
  8214. * Adds a mapping
  8215. *
  8216. * @param integer $generatedLine The line number in generated file
  8217. * @param integer $generatedColumn The column number in generated file
  8218. * @param integer $originalLine The line number in original file
  8219. * @param integer $originalColumn The column number in original file
  8220. * @param string $sourceFile The original source file
  8221. */
  8222. public function addMapping($generatedLine, $generatedColumn, $originalLine, $originalColumn, $fileInfo ){
  8223. $this->mappings[] = array(
  8224. 'generated_line' => $generatedLine,
  8225. 'generated_column' => $generatedColumn,
  8226. 'original_line' => $originalLine,
  8227. 'original_column' => $originalColumn,
  8228. 'source_file' => $fileInfo['currentUri']
  8229. );
  8230. $this->sources[$fileInfo['currentUri']] = $fileInfo['filename'];
  8231. }
  8232. /**
  8233. * Generates the JSON source map
  8234. *
  8235. * @return string
  8236. * @see https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#
  8237. */
  8238. protected function generateJson(){
  8239. $sourceMap = array();
  8240. $mappings = $this->generateMappings();
  8241. // File version (always the first entry in the object) and must be a positive integer.
  8242. $sourceMap['version'] = self::VERSION;
  8243. // An optional name of the generated code that this source map is associated with.
  8244. $file = $this->getOption('sourceMapFilename');
  8245. if( $file ){
  8246. $sourceMap['file'] = $file;
  8247. }
  8248. // An optional source root, useful for relocating source files on a server or removing repeated values in the 'sources' entry. This value is prepended to the individual entries in the 'source' field.
  8249. $root = $this->getOption('sourceRoot');
  8250. if( $root ){
  8251. $sourceMap['sourceRoot'] = $root;
  8252. }
  8253. // A list of original sources used by the 'mappings' entry.
  8254. $sourceMap['sources'] = array();
  8255. foreach($this->sources as $source_uri => $source_filename){
  8256. $sourceMap['sources'][] = $this->normalizeFilename($source_filename);
  8257. }
  8258. // A list of symbol names used by the 'mappings' entry.
  8259. $sourceMap['names'] = array();
  8260. // A string with the encoded mapping data.
  8261. $sourceMap['mappings'] = $mappings;
  8262. if( $this->getOption('outputSourceFiles') ){
  8263. // An optional list of source content, useful when the 'source' can't be hosted.
  8264. // The contents are listed in the same order as the sources above.
  8265. // 'null' may be used if some original sources should be retrieved by name.
  8266. $sourceMap['sourcesContent'] = $this->getSourcesContent();
  8267. }
  8268. // less.js compat fixes
  8269. if( count($sourceMap['sources']) && empty($sourceMap['sourceRoot']) ){
  8270. unset($sourceMap['sourceRoot']);
  8271. }
  8272. return json_encode($sourceMap);
  8273. }
  8274. /**
  8275. * Returns the sources contents
  8276. *
  8277. * @return array|null
  8278. */
  8279. protected function getSourcesContent(){
  8280. if(empty($this->sources)){
  8281. return;
  8282. }
  8283. $content = array();
  8284. foreach($this->sources as $sourceFile){
  8285. $content[] = file_get_contents($sourceFile);
  8286. }
  8287. return $content;
  8288. }
  8289. /**
  8290. * Generates the mappings string
  8291. *
  8292. * @return string
  8293. */
  8294. public function generateMappings(){
  8295. if( !count($this->mappings) ){
  8296. return '';
  8297. }
  8298. $this->source_keys = array_flip(array_keys($this->sources));
  8299. // group mappings by generated line number.
  8300. $groupedMap = $groupedMapEncoded = array();
  8301. foreach($this->mappings as $m){
  8302. $groupedMap[$m['generated_line']][] = $m;
  8303. }
  8304. ksort($groupedMap);
  8305. $lastGeneratedLine = $lastOriginalIndex = $lastOriginalLine = $lastOriginalColumn = 0;
  8306. foreach($groupedMap as $lineNumber => $line_map){
  8307. while(++$lastGeneratedLine < $lineNumber){
  8308. $groupedMapEncoded[] = ';';
  8309. }
  8310. $lineMapEncoded = array();
  8311. $lastGeneratedColumn = 0;
  8312. foreach($line_map as $m){
  8313. $mapEncoded = $this->encoder->encode($m['generated_column'] - $lastGeneratedColumn);
  8314. $lastGeneratedColumn = $m['generated_column'];
  8315. // find the index
  8316. if( $m['source_file'] ){
  8317. $index = $this->findFileIndex($m['source_file']);
  8318. if( $index !== false ){
  8319. $mapEncoded .= $this->encoder->encode($index - $lastOriginalIndex);
  8320. $lastOriginalIndex = $index;
  8321. // lines are stored 0-based in SourceMap spec version 3
  8322. $mapEncoded .= $this->encoder->encode($m['original_line'] - 1 - $lastOriginalLine);
  8323. $lastOriginalLine = $m['original_line'] - 1;
  8324. $mapEncoded .= $this->encoder->encode($m['original_column'] - $lastOriginalColumn);
  8325. $lastOriginalColumn = $m['original_column'];
  8326. }
  8327. }
  8328. $lineMapEncoded[] = $mapEncoded;
  8329. }
  8330. $groupedMapEncoded[] = implode(',', $lineMapEncoded) . ';';
  8331. }
  8332. return rtrim(implode($groupedMapEncoded), ';');
  8333. }
  8334. /**
  8335. * Finds the index for the filename
  8336. *
  8337. * @param string $filename
  8338. * @return integer|false
  8339. */
  8340. protected function findFileIndex($filename){
  8341. return $this->source_keys[$filename];
  8342. }
  8343. /**
  8344. * fix windows paths
  8345. * @param string $path
  8346. * @return string
  8347. */
  8348. public function fixWindowsPath($path, $addEndSlash = false){
  8349. $slash = ($addEndSlash) ? '/' : '';
  8350. if( !empty($path) ){
  8351. $path = str_replace('\\', '/', $path);
  8352. $path = rtrim($path,'/') . $slash;
  8353. }
  8354. return $path;
  8355. }
  8356. }