classes.php 227KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787
  1. <?php
  2. namespace Symfony\Bundle\FrameworkBundle\EventListener
  3. {
  4. use Symfony\Component\DependencyInjection\ContainerInterface;
  5. use Symfony\Component\HttpKernel\HttpKernelInterface;
  6. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  7. class SessionListener
  8. {
  9. private $container;
  10. private $autoStart;
  11. public function __construct(ContainerInterface $container, $autoStart = false)
  12. {
  13. $this->container = $container;
  14. $this->autoStart = $autoStart;
  15. }
  16. public function onKernelRequest(GetResponseEvent $event)
  17. {
  18. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  19. return;
  20. }
  21. if (!$this->container->has('session')) {
  22. return;
  23. }
  24. $request = $event->getRequest();
  25. if ($request->hasSession()) {
  26. return;
  27. }
  28. $request->setSession($session = $this->container->get('session'));
  29. if ($this->autoStart || $request->hasPreviousSession()) {
  30. $session->start();
  31. }
  32. }
  33. }
  34. }
  35. namespace Symfony\Component\HttpFoundation\SessionStorage
  36. {
  37. interface SessionStorageInterface
  38. {
  39. function start();
  40. function getId();
  41. function read($key);
  42. function remove($key);
  43. function write($key, $data);
  44. function regenerate($destroy = false);
  45. }
  46. }
  47. namespace Symfony\Component\HttpFoundation
  48. {
  49. use Symfony\Component\HttpFoundation\SessionStorage\SessionStorageInterface;
  50. class Session implements \Serializable
  51. {
  52. protected $storage;
  53. protected $started;
  54. protected $attributes;
  55. protected $flashes;
  56. protected $oldFlashes;
  57. protected $locale;
  58. protected $defaultLocale;
  59. protected $saved;
  60. public function __construct(SessionStorageInterface $storage, $defaultLocale = 'en')
  61. {
  62. $this->storage = $storage;
  63. $this->defaultLocale = $defaultLocale;
  64. $this->locale = $defaultLocale;
  65. $this->flashes = array();
  66. $this->oldFlashes = array();
  67. $this->attributes = array();
  68. $this->setPhpDefaultLocale($this->defaultLocale);
  69. $this->started = false;
  70. $this->saved = false;
  71. }
  72. public function start()
  73. {
  74. if (true === $this->started) {
  75. return;
  76. }
  77. $this->storage->start();
  78. $attributes = $this->storage->read('_symfony2');
  79. if (isset($attributes['attributes'])) {
  80. $this->attributes = $attributes['attributes'];
  81. $this->flashes = $attributes['flashes'];
  82. $this->locale = $attributes['locale'];
  83. $this->setPhpDefaultLocale($this->locale);
  84. $this->oldFlashes = $this->flashes;
  85. }
  86. $this->started = true;
  87. }
  88. public function has($name)
  89. {
  90. return array_key_exists($name, $this->attributes);
  91. }
  92. public function get($name, $default = null)
  93. {
  94. return array_key_exists($name, $this->attributes) ? $this->attributes[$name] : $default;
  95. }
  96. public function set($name, $value)
  97. {
  98. if (false === $this->started) {
  99. $this->start();
  100. }
  101. $this->attributes[$name] = $value;
  102. }
  103. public function all()
  104. {
  105. return $this->attributes;
  106. }
  107. public function replace(array $attributes)
  108. {
  109. if (false === $this->started) {
  110. $this->start();
  111. }
  112. $this->attributes = $attributes;
  113. }
  114. public function remove($name)
  115. {
  116. if (false === $this->started) {
  117. $this->start();
  118. }
  119. if (array_key_exists($name, $this->attributes)) {
  120. unset($this->attributes[$name]);
  121. }
  122. }
  123. public function clear()
  124. {
  125. if (false === $this->started) {
  126. $this->start();
  127. }
  128. $this->attributes = array();
  129. $this->flashes = array();
  130. $this->setPhpDefaultLocale($this->locale = $this->defaultLocale);
  131. }
  132. public function invalidate()
  133. {
  134. $this->clear();
  135. $this->storage->regenerate();
  136. }
  137. public function migrate()
  138. {
  139. $this->storage->regenerate();
  140. }
  141. public function getId()
  142. {
  143. if (false === $this->started) {
  144. $this->start();
  145. }
  146. return $this->storage->getId();
  147. }
  148. public function getLocale()
  149. {
  150. return $this->locale;
  151. }
  152. public function setLocale($locale)
  153. {
  154. if (false === $this->started) {
  155. $this->start();
  156. }
  157. $this->setPhpDefaultLocale($this->locale = $locale);
  158. }
  159. public function getFlashes()
  160. {
  161. return $this->flashes;
  162. }
  163. public function setFlashes($values)
  164. {
  165. if (false === $this->started) {
  166. $this->start();
  167. }
  168. $this->flashes = $values;
  169. $this->oldFlashes = array();
  170. }
  171. public function getFlash($name, $default = null)
  172. {
  173. return array_key_exists($name, $this->flashes) ? $this->flashes[$name] : $default;
  174. }
  175. public function setFlash($name, $value)
  176. {
  177. if (false === $this->started) {
  178. $this->start();
  179. }
  180. $this->flashes[$name] = $value;
  181. unset($this->oldFlashes[$name]);
  182. }
  183. public function hasFlash($name)
  184. {
  185. if (false === $this->started) {
  186. $this->start();
  187. }
  188. return array_key_exists($name, $this->flashes);
  189. }
  190. public function removeFlash($name)
  191. {
  192. if (false === $this->started) {
  193. $this->start();
  194. }
  195. unset($this->flashes[$name]);
  196. }
  197. public function clearFlashes()
  198. {
  199. if (false === $this->started) {
  200. $this->start();
  201. }
  202. $this->flashes = array();
  203. $this->oldFlashes = array();
  204. }
  205. public function save()
  206. {
  207. if (false === $this->started) {
  208. $this->start();
  209. }
  210. $this->flashes = array_diff_key($this->flashes, $this->oldFlashes);
  211. $this->storage->write('_symfony2', array(
  212. 'attributes' => $this->attributes,
  213. 'flashes' => $this->flashes,
  214. 'locale' => $this->locale,
  215. ));
  216. $this->saved = true;
  217. }
  218. public function __destruct()
  219. {
  220. if (true === $this->started && !$this->saved) {
  221. $this->save();
  222. }
  223. }
  224. public function serialize()
  225. {
  226. return serialize(array($this->storage, $this->defaultLocale));
  227. }
  228. public function unserialize($serialized)
  229. {
  230. list($this->storage, $this->defaultLocale) = unserialize($serialized);
  231. $this->attributes = array();
  232. $this->started = false;
  233. }
  234. private function setPhpDefaultLocale($locale)
  235. {
  236. try {
  237. if (class_exists('Locale', false)) {
  238. \Locale::setDefault($locale);
  239. }
  240. } catch (\Exception $e) {
  241. }
  242. }
  243. }
  244. }
  245. namespace Symfony\Component\HttpFoundation\SessionStorage
  246. {
  247. class NativeSessionStorage implements SessionStorageInterface
  248. {
  249. static protected $sessionIdRegenerated = false;
  250. static protected $sessionStarted = false;
  251. protected $options;
  252. public function __construct(array $options = array())
  253. {
  254. $cookieDefaults = session_get_cookie_params();
  255. $this->options = array_merge(array(
  256. 'lifetime' => $cookieDefaults['lifetime'],
  257. 'path' => $cookieDefaults['path'],
  258. 'domain' => $cookieDefaults['domain'],
  259. 'secure' => $cookieDefaults['secure'],
  260. 'httponly' => isset($cookieDefaults['httponly']) ? $cookieDefaults['httponly'] : false,
  261. ), $options);
  262. if (isset($this->options['name'])) {
  263. session_name($this->options['name']);
  264. }
  265. }
  266. public function start()
  267. {
  268. if (self::$sessionStarted) {
  269. return;
  270. }
  271. session_set_cookie_params(
  272. $this->options['lifetime'],
  273. $this->options['path'],
  274. $this->options['domain'],
  275. $this->options['secure'],
  276. $this->options['httponly']
  277. );
  278. session_cache_limiter(false);
  279. if (!ini_get('session.use_cookies') && isset($this->options['id']) && $this->options['id'] && $this->options['id'] != session_id()) {
  280. session_id($this->options['id']);
  281. }
  282. session_start();
  283. self::$sessionStarted = true;
  284. }
  285. public function getId()
  286. {
  287. if (!self::$sessionStarted) {
  288. throw new \RuntimeException('The session must be started before reading its ID');
  289. }
  290. return session_id();
  291. }
  292. public function read($key, $default = null)
  293. {
  294. return array_key_exists($key, $_SESSION) ? $_SESSION[$key] : $default;
  295. }
  296. public function remove($key)
  297. {
  298. $retval = null;
  299. if (isset($_SESSION[$key])) {
  300. $retval = $_SESSION[$key];
  301. unset($_SESSION[$key]);
  302. }
  303. return $retval;
  304. }
  305. public function write($key, $data)
  306. {
  307. $_SESSION[$key] = $data;
  308. }
  309. public function regenerate($destroy = false)
  310. {
  311. if (self::$sessionIdRegenerated) {
  312. return;
  313. }
  314. session_regenerate_id($destroy);
  315. self::$sessionIdRegenerated = true;
  316. }
  317. }
  318. }
  319. namespace Symfony\Component\Routing\Matcher
  320. {
  321. use Symfony\Component\Routing\RequestContextAwareInterface;
  322. interface UrlMatcherInterface extends RequestContextAwareInterface
  323. {
  324. function match($pathinfo);
  325. }
  326. }
  327. namespace Symfony\Component\Routing\Generator
  328. {
  329. use Symfony\Component\Routing\RequestContextAwareInterface;
  330. interface UrlGeneratorInterface extends RequestContextAwareInterface
  331. {
  332. function generate($name, $parameters = array(), $absolute = false);
  333. }
  334. }
  335. namespace Symfony\Component\Routing
  336. {
  337. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  338. use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
  339. interface RouterInterface extends UrlMatcherInterface, UrlGeneratorInterface
  340. {
  341. }
  342. }
  343. namespace Symfony\Component\Routing\Matcher
  344. {
  345. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  346. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  347. use Symfony\Component\Routing\Route;
  348. use Symfony\Component\Routing\RouteCollection;
  349. use Symfony\Component\Routing\RequestContext;
  350. class UrlMatcher implements UrlMatcherInterface
  351. {
  352. protected $context;
  353. private $routes;
  354. public function __construct(RouteCollection $routes, RequestContext $context)
  355. {
  356. $this->routes = $routes;
  357. $this->context = $context;
  358. }
  359. public function setContext(RequestContext $context)
  360. {
  361. $this->context = $context;
  362. }
  363. public function getContext()
  364. {
  365. return $this->context;
  366. }
  367. public function match($pathinfo)
  368. {
  369. $this->allow = array();
  370. if ($ret = $this->matchCollection($pathinfo, $this->routes)) {
  371. return $ret;
  372. }
  373. throw 0 < count($this->allow)
  374. ? new MethodNotAllowedException(array_unique(array_map('strtoupper', $this->allow)))
  375. : new ResourceNotFoundException();
  376. }
  377. protected function matchCollection($pathinfo, RouteCollection $routes)
  378. {
  379. $pathinfo = urldecode($pathinfo);
  380. foreach ($routes as $name => $route) {
  381. if ($route instanceof RouteCollection) {
  382. if (false === strpos($route->getPrefix(), '{') && $route->getPrefix() !== substr($pathinfo, 0, strlen($route->getPrefix()))) {
  383. continue;
  384. }
  385. if (!$ret = $this->matchCollection($pathinfo, $route)) {
  386. continue;
  387. }
  388. return $ret;
  389. }
  390. $compiledRoute = $route->compile();
  391. if ('' !== $compiledRoute->getStaticPrefix() && 0 !== strpos($pathinfo, $compiledRoute->getStaticPrefix())) {
  392. continue;
  393. }
  394. if (!preg_match($compiledRoute->getRegex(), $pathinfo, $matches)) {
  395. continue;
  396. }
  397. if ($req = $route->getRequirement('_method')) {
  398. if ('HEAD' === $method = $this->context->getMethod()) {
  399. $method = 'GET';
  400. }
  401. if (!in_array($method, $req = explode('|', strtoupper($req)))) {
  402. $this->allow = array_merge($this->allow, $req);
  403. continue;
  404. }
  405. }
  406. return array_merge($this->mergeDefaults($matches, $route->getDefaults()), array('_route' => $name));
  407. }
  408. }
  409. protected function mergeDefaults($params, $defaults)
  410. {
  411. $parameters = $defaults;
  412. foreach ($params as $key => $value) {
  413. if (!is_int($key)) {
  414. $parameters[$key] = rawurldecode($value);
  415. }
  416. }
  417. return $parameters;
  418. }
  419. }
  420. }
  421. namespace Symfony\Component\Routing\Generator
  422. {
  423. use Symfony\Component\Routing\Route;
  424. use Symfony\Component\Routing\RouteCollection;
  425. use Symfony\Component\Routing\RequestContext;
  426. use Symfony\Component\Routing\Exception\InvalidParameterException;
  427. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  428. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  429. class UrlGenerator implements UrlGeneratorInterface
  430. {
  431. protected $context;
  432. protected $decodedChars = array(
  433. '%2F' => '/',
  434. );
  435. protected $routes;
  436. protected $cache;
  437. public function __construct(RouteCollection $routes, RequestContext $context)
  438. {
  439. $this->routes = $routes;
  440. $this->context = $context;
  441. $this->cache = array();
  442. }
  443. public function setContext(RequestContext $context)
  444. {
  445. $this->context = $context;
  446. }
  447. public function getContext()
  448. {
  449. return $this->context;
  450. }
  451. public function generate($name, $parameters = array(), $absolute = false)
  452. {
  453. if (null === $route = $this->routes->get($name)) {
  454. throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
  455. }
  456. if (!isset($this->cache[$name])) {
  457. $this->cache[$name] = $route->compile();
  458. }
  459. return $this->doGenerate($this->cache[$name]->getVariables(), $route->getDefaults(), $route->getRequirements(), $this->cache[$name]->getTokens(), $parameters, $name, $absolute);
  460. }
  461. protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $absolute)
  462. {
  463. $variables = array_flip($variables);
  464. $originParameters = $parameters;
  465. $parameters = array_replace($this->context->getParameters(), $parameters);
  466. $tparams = array_replace($defaults, $parameters);
  467. if ($diff = array_diff_key($variables, $tparams)) {
  468. throw new MissingMandatoryParametersException(sprintf('The "%s" route has some missing mandatory parameters ("%s").', $name, implode('", "', array_keys($diff))));
  469. }
  470. $url = '';
  471. $optional = true;
  472. foreach ($tokens as $token) {
  473. if ('variable' === $token[0]) {
  474. if (false === $optional || !array_key_exists($token[3], $defaults) || (isset($parameters[$token[3]]) && (string) $parameters[$token[3]] != (string) $defaults[$token[3]])) {
  475. if (!$isEmpty = in_array($tparams[$token[3]], array(null, '', false), true)) {
  476. if ($tparams[$token[3]] && !preg_match('#^'.$token[2].'$#', $tparams[$token[3]])) {
  477. throw new InvalidParameterException(sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given).', $token[3], $name, $token[2], $tparams[$token[3]]));
  478. }
  479. }
  480. if (!$isEmpty || !$optional) {
  481. $url = $token[1].strtr(rawurlencode($tparams[$token[3]]), $this->decodedChars).$url;
  482. }
  483. $optional = false;
  484. }
  485. } elseif ('text' === $token[0]) {
  486. $url = $token[1].$url;
  487. $optional = false;
  488. }
  489. }
  490. if (!$url) {
  491. $url = '/';
  492. }
  493. $extra = array_diff_key($originParameters, $variables, $defaults);
  494. if ($extra && $query = http_build_query($extra)) {
  495. $url .= '?'.$query;
  496. }
  497. $url = $this->context->getBaseUrl().$url;
  498. if ($this->context->getHost()) {
  499. $scheme = $this->context->getScheme();
  500. if (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme != $req) {
  501. $absolute = true;
  502. $scheme = $req;
  503. }
  504. if ($absolute) {
  505. $port = '';
  506. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  507. $port = ':'.$this->context->getHttpPort();
  508. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  509. $port = ':'.$this->context->getHttpsPort();
  510. }
  511. $url = $scheme.'://'.$this->context->getHost().$port.$url;
  512. }
  513. }
  514. return $url;
  515. }
  516. }
  517. }
  518. namespace Symfony\Component\Routing\Matcher
  519. {
  520. interface RedirectableUrlMatcherInterface
  521. {
  522. function redirect($path, $route, $scheme = null);
  523. }
  524. }
  525. namespace Symfony\Component\Routing
  526. {
  527. interface RequestContextAwareInterface
  528. {
  529. function setContext(RequestContext $context);
  530. }
  531. }
  532. namespace Symfony\Component\Routing
  533. {
  534. class RequestContext
  535. {
  536. private $baseUrl;
  537. private $method;
  538. private $host;
  539. private $scheme;
  540. private $httpPort;
  541. private $httpsPort;
  542. private $parameters;
  543. public function __construct($baseUrl = '', $method = 'GET', $host = 'localhost', $scheme = 'http', $httpPort = 80, $httpsPort = 443)
  544. {
  545. $this->baseUrl = $baseUrl;
  546. $this->method = strtoupper($method);
  547. $this->host = $host;
  548. $this->scheme = strtolower($scheme);
  549. $this->httpPort = $httpPort;
  550. $this->httpsPort = $httpsPort;
  551. $this->parameters = array();
  552. }
  553. public function getBaseUrl()
  554. {
  555. return $this->baseUrl;
  556. }
  557. public function setBaseUrl($baseUrl)
  558. {
  559. $this->baseUrl = $baseUrl;
  560. }
  561. public function getMethod()
  562. {
  563. return $this->method;
  564. }
  565. public function setMethod($method)
  566. {
  567. $this->method = strtoupper($method);
  568. }
  569. public function getHost()
  570. {
  571. return $this->host;
  572. }
  573. public function setHost($host)
  574. {
  575. $this->host = $host;
  576. }
  577. public function getScheme()
  578. {
  579. return $this->scheme;
  580. }
  581. public function setScheme($scheme)
  582. {
  583. $this->scheme = strtolower($scheme);
  584. }
  585. public function getHttpPort()
  586. {
  587. return $this->httpPort;
  588. }
  589. public function setHttpPort($httpPort)
  590. {
  591. $this->httpPort = $httpPort;
  592. }
  593. public function getHttpsPort()
  594. {
  595. return $this->httpsPort;
  596. }
  597. public function setHttpsPort($httpsPort)
  598. {
  599. $this->httpsPort = $httpsPort;
  600. }
  601. public function getParameters()
  602. {
  603. return $this->parameters;
  604. }
  605. public function setParameters(array $parameters)
  606. {
  607. $this->parameters = $parameters;
  608. return $this;
  609. }
  610. public function getParameter($name)
  611. {
  612. return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
  613. }
  614. public function hasParameter($name)
  615. {
  616. return array_key_exists($name, $this->parameters);
  617. }
  618. public function setParameter($name, $parameter)
  619. {
  620. $this->parameters[$name] = $parameter;
  621. }
  622. }
  623. }
  624. namespace Symfony\Component\Routing
  625. {
  626. use Symfony\Component\Config\Loader\LoaderInterface;
  627. use Symfony\Component\Config\ConfigCache;
  628. class Router implements RouterInterface
  629. {
  630. protected $matcher;
  631. protected $generator;
  632. protected $defaults;
  633. protected $context;
  634. protected $loader;
  635. protected $collection;
  636. protected $resource;
  637. protected $options;
  638. public function __construct(LoaderInterface $loader, $resource, array $options = array(), RequestContext $context = null, array $defaults = array())
  639. {
  640. $this->loader = $loader;
  641. $this->resource = $resource;
  642. $this->context = null === $context ? new RequestContext() : $context;
  643. $this->defaults = $defaults;
  644. $this->setOptions($options);
  645. }
  646. public function setOptions(array $options)
  647. {
  648. $this->options = array(
  649. 'cache_dir' => null,
  650. 'debug' => false,
  651. 'generator_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
  652. 'generator_base_class' => 'Symfony\\Component\\Routing\\Generator\\UrlGenerator',
  653. 'generator_dumper_class' => 'Symfony\\Component\\Routing\\Generator\\Dumper\\PhpGeneratorDumper',
  654. 'generator_cache_class' => 'ProjectUrlGenerator',
  655. 'matcher_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  656. 'matcher_base_class' => 'Symfony\\Component\\Routing\\Matcher\\UrlMatcher',
  657. 'matcher_dumper_class' => 'Symfony\\Component\\Routing\\Matcher\\Dumper\\PhpMatcherDumper',
  658. 'matcher_cache_class' => 'ProjectUrlMatcher',
  659. 'resource_type' => null,
  660. );
  661. $invalid = array();
  662. $isInvalid = false;
  663. foreach ($options as $key => $value) {
  664. if (array_key_exists($key, $this->options)) {
  665. $this->options[$key] = $value;
  666. } else {
  667. $isInvalid = true;
  668. $invalid[] = $key;
  669. }
  670. }
  671. if ($isInvalid) {
  672. throw new \InvalidArgumentException(sprintf('The Router does not support the following options: "%s".', implode('\', \'', $invalid)));
  673. }
  674. }
  675. public function setOption($key, $value)
  676. {
  677. if (!array_key_exists($key, $this->options)) {
  678. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  679. }
  680. $this->options[$key] = $value;
  681. }
  682. public function getOption($key)
  683. {
  684. if (!array_key_exists($key, $this->options)) {
  685. throw new \InvalidArgumentException(sprintf('The Router does not support the "%s" option.', $key));
  686. }
  687. return $this->options[$key];
  688. }
  689. public function getRouteCollection()
  690. {
  691. if (null === $this->collection) {
  692. $this->collection = $this->loader->load($this->resource, $this->options['resource_type']);
  693. }
  694. return $this->collection;
  695. }
  696. public function setContext(RequestContext $context)
  697. {
  698. $this->context = $context;
  699. $this->getMatcher()->setContext($context);
  700. $this->getGenerator()->setContext($context);
  701. }
  702. public function getContext()
  703. {
  704. return $this->context;
  705. }
  706. public function generate($name, $parameters = array(), $absolute = false)
  707. {
  708. return $this->getGenerator()->generate($name, $parameters, $absolute);
  709. }
  710. public function match($url)
  711. {
  712. return $this->getMatcher()->match($url);
  713. }
  714. public function getMatcher()
  715. {
  716. if (null !== $this->matcher) {
  717. return $this->matcher;
  718. }
  719. if (null === $this->options['cache_dir'] || null === $this->options['matcher_cache_class']) {
  720. return $this->matcher = new $this->options['matcher_class']($this->getRouteCollection(), $this->context, $this->defaults);
  721. }
  722. $class = $this->options['matcher_cache_class'];
  723. $cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
  724. if (!$cache->isFresh($class)) {
  725. $dumper = new $this->options['matcher_dumper_class']($this->getRouteCollection());
  726. $options = array(
  727. 'class' => $class,
  728. 'base_class' => $this->options['matcher_base_class'],
  729. );
  730. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  731. }
  732. require_once $cache;
  733. return $this->matcher = new $class($this->context, $this->defaults);
  734. }
  735. public function getGenerator()
  736. {
  737. if (null !== $this->generator) {
  738. return $this->generator;
  739. }
  740. if (null === $this->options['cache_dir'] || null === $this->options['generator_cache_class']) {
  741. return $this->generator = new $this->options['generator_class']($this->getRouteCollection(), $this->context, $this->defaults);
  742. }
  743. $class = $this->options['generator_cache_class'];
  744. $cache = new ConfigCache($this->options['cache_dir'].'/'.$class.'.php', $this->options['debug']);
  745. if (!$cache->isFresh($class)) {
  746. $dumper = new $this->options['generator_dumper_class']($this->getRouteCollection());
  747. $options = array(
  748. 'class' => $class,
  749. 'base_class' => $this->options['generator_base_class'],
  750. );
  751. $cache->write($dumper->dump($options), $this->getRouteCollection()->getResources());
  752. }
  753. require_once $cache;
  754. return $this->generator = new $class($this->context, $this->defaults);
  755. }
  756. }
  757. }
  758. namespace Symfony\Bundle\FrameworkBundle\Routing
  759. {
  760. use Symfony\Component\Routing\Matcher\UrlMatcher;
  761. use Symfony\Component\Routing\Matcher\RedirectableUrlMatcherInterface;
  762. class RedirectableUrlMatcher extends UrlMatcher implements RedirectableUrlMatcherInterface
  763. {
  764. public function redirect($path, $route, $scheme = null)
  765. {
  766. return array(
  767. '_controller' => 'Symfony\\Bundle\\FrameworkBundle\\Controller\\RedirectController::urlRedirectAction',
  768. 'path' => $path,
  769. 'permanent' => true,
  770. 'scheme' => $scheme,
  771. 'httpPort' => $this->context->getHttpPort(),
  772. 'httpsPort' => $this->context->getHttpsPort(),
  773. '_route' => $route,
  774. );
  775. }
  776. }
  777. }
  778. namespace Symfony\Bundle\FrameworkBundle\Routing
  779. {
  780. use Symfony\Component\Routing\Router as BaseRouter;
  781. use Symfony\Component\Routing\RequestContext;
  782. use Symfony\Component\DependencyInjection\ContainerInterface;
  783. class Router extends BaseRouter
  784. {
  785. private $container;
  786. public function __construct(ContainerInterface $container, $resource, array $options = array(), RequestContext $context = null, array $defaults = array())
  787. {
  788. $this->container = $container;
  789. $this->resource = $resource;
  790. $this->context = null === $context ? new RequestContext() : $context;
  791. $this->defaults = $defaults;
  792. $this->setOptions($options);
  793. }
  794. public function getRouteCollection()
  795. {
  796. if (null === $this->collection) {
  797. $this->collection = $this->container->get('routing.loader')->load($this->resource, $this->options['resource_type']);
  798. }
  799. return $this->collection;
  800. }
  801. }
  802. }
  803. namespace Symfony\Bundle\FrameworkBundle\Templating
  804. {
  805. use Symfony\Component\DependencyInjection\ContainerInterface;
  806. class GlobalVariables
  807. {
  808. protected $container;
  809. public function __construct(ContainerInterface $container)
  810. {
  811. $this->container = $container;
  812. }
  813. public function getSecurity()
  814. {
  815. if ($this->container->has('security.context')) {
  816. return $this->container->get('security.context');
  817. }
  818. }
  819. public function getUser()
  820. {
  821. if (!$security = $this->getSecurity()) {
  822. return;
  823. }
  824. if (!$token = $security->getToken()) {
  825. return;
  826. }
  827. $user = $token->getUser();
  828. if (!is_object($user)) {
  829. return;
  830. }
  831. return $user;
  832. }
  833. public function getRequest()
  834. {
  835. if ($this->container->has('request') && $request = $this->container->get('request')) {
  836. return $request;
  837. }
  838. }
  839. public function getSession()
  840. {
  841. if ($request = $this->getRequest()) {
  842. return $request->getSession();
  843. }
  844. }
  845. public function getEnvironment()
  846. {
  847. return $this->container->getParameter('kernel.environment');
  848. }
  849. public function getDebug()
  850. {
  851. return (Boolean) $this->container->getParameter('kernel.debug');
  852. }
  853. }
  854. }
  855. namespace Symfony\Bundle\FrameworkBundle\Templating
  856. {
  857. use Symfony\Component\Templating\EngineInterface as BaseEngineInterface;
  858. use Symfony\Component\HttpFoundation\Response;
  859. interface EngineInterface extends BaseEngineInterface
  860. {
  861. function renderResponse($view, array $parameters = array(), Response $response = null);
  862. }
  863. }
  864. namespace Symfony\Component\Templating
  865. {
  866. interface TemplateNameParserInterface
  867. {
  868. function parse($name);
  869. }
  870. }
  871. namespace Symfony\Component\Templating
  872. {
  873. use Symfony\Component\Templating\TemplateReferenceInterface;
  874. use Symfony\Component\Templating\TemplateReference;
  875. class TemplateNameParser implements TemplateNameParserInterface
  876. {
  877. public function parse($name)
  878. {
  879. if ($name instanceof TemplateReferenceInterface) {
  880. return $name;
  881. }
  882. $engine = null;
  883. if (false !== $pos = strrpos($name, '.')) {
  884. $engine = substr($name, $pos + 1);
  885. }
  886. return new TemplateReference($name, $engine);
  887. }
  888. }
  889. }
  890. namespace Symfony\Component\Templating
  891. {
  892. interface EngineInterface
  893. {
  894. function render($name, array $parameters = array());
  895. function exists($name);
  896. function supports($name);
  897. }
  898. }
  899. namespace Symfony\Component\Config
  900. {
  901. interface FileLocatorInterface
  902. {
  903. function locate($name, $currentPath = null, $first = true);
  904. }
  905. }
  906. namespace Symfony\Component\Templating
  907. {
  908. interface TemplateReferenceInterface
  909. {
  910. function all();
  911. function set($name, $value);
  912. function get($name);
  913. function getPath();
  914. function getLogicalName();
  915. }
  916. }
  917. namespace Symfony\Component\Templating
  918. {
  919. class TemplateReference implements TemplateReferenceInterface
  920. {
  921. protected $parameters;
  922. public function __construct($name = null, $engine = null)
  923. {
  924. $this->parameters = array(
  925. 'name' => $name,
  926. 'engine' => $engine,
  927. );
  928. }
  929. public function __toString()
  930. {
  931. return $this->getLogicalName();
  932. }
  933. public function set($name, $value)
  934. {
  935. if (array_key_exists($name, $this->parameters)) {
  936. $this->parameters[$name] = $value;
  937. } else {
  938. throw new \InvalidArgumentException(sprintf('The template does not support the "%s" parameter.', $name));
  939. }
  940. return $this;
  941. }
  942. public function get($name)
  943. {
  944. if (array_key_exists($name, $this->parameters)) {
  945. return $this->parameters[$name];
  946. }
  947. throw new \InvalidArgumentException(sprintf('The template does not support the "%s" parameter.', $name));
  948. }
  949. public function all()
  950. {
  951. return $this->parameters;
  952. }
  953. public function getPath()
  954. {
  955. return $this->parameters['name'];
  956. }
  957. public function getLogicalName()
  958. {
  959. return $this->parameters['name'];
  960. }
  961. }
  962. }
  963. namespace Symfony\Bundle\FrameworkBundle\Templating
  964. {
  965. use Symfony\Component\Templating\TemplateReference as BaseTemplateReference;
  966. class TemplateReference extends BaseTemplateReference
  967. {
  968. public function __construct($bundle = null, $controller = null, $name = null, $format = null, $engine = null)
  969. {
  970. $this->parameters = array(
  971. 'bundle' => $bundle,
  972. 'controller' => $controller,
  973. 'name' => $name,
  974. 'format' => $format,
  975. 'engine' => $engine,
  976. );
  977. }
  978. public function getPath()
  979. {
  980. $controller = str_replace('\\', '/', $this->get('controller'));
  981. $path = (empty($controller) ? '' : $controller.'/').$this->get('name').'.'.$this->get('format').'.'.$this->get('engine');
  982. return empty($this->parameters['bundle']) ? 'views/'.$path : '@'.$this->get('bundle').'/Resources/views/'.$path;
  983. }
  984. public function getLogicalName()
  985. {
  986. return sprintf('%s:%s:%s.%s.%s', $this->parameters['bundle'], $this->parameters['controller'], $this->parameters['name'], $this->parameters['format'], $this->parameters['engine']);
  987. }
  988. }
  989. }
  990. namespace Symfony\Bundle\FrameworkBundle\Templating
  991. {
  992. use Symfony\Component\Templating\TemplateNameParser as BaseTemplateNameParser;
  993. use Symfony\Component\Templating\TemplateReferenceInterface;
  994. use Symfony\Component\HttpKernel\KernelInterface;
  995. class TemplateNameParser extends BaseTemplateNameParser
  996. {
  997. protected $kernel;
  998. protected $cache;
  999. public function __construct(KernelInterface $kernel)
  1000. {
  1001. $this->kernel = $kernel;
  1002. $this->cache = array();
  1003. }
  1004. public function parse($name)
  1005. {
  1006. if ($name instanceof TemplateReferenceInterface) {
  1007. return $name;
  1008. } else if (isset($this->cache[$name])) {
  1009. return $this->cache[$name];
  1010. }
  1011. $name = str_replace(':/', ':', preg_replace('#/{2,}#', '/', strtr($name, '\\', '/')));
  1012. if (false !== strpos($name, '..')) {
  1013. throw new \RuntimeException(sprintf('Template name "%s" contains invalid characters.', $name));
  1014. }
  1015. $parts = explode(':', $name);
  1016. if (3 !== count($parts)) {
  1017. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid (format is "bundle:section:template.format.engine").', $name));
  1018. }
  1019. $elements = explode('.', $parts[2]);
  1020. if (3 > count($elements)) {
  1021. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid (format is "bundle:section:template.format.engine").', $name));
  1022. }
  1023. $engine = array_pop($elements);
  1024. $format = array_pop($elements);
  1025. $template = new TemplateReference($parts[0], $parts[1], implode('.', $elements), $format, $engine);
  1026. if ($template->get('bundle')) {
  1027. try {
  1028. $this->kernel->getBundle($template->get('bundle'));
  1029. } catch (\Exception $e) {
  1030. throw new \InvalidArgumentException(sprintf('Template name "%s" is not valid.', $name), 0, $e);
  1031. }
  1032. }
  1033. return $this->cache[$name] = $template;
  1034. }
  1035. public function parseFromFilename($file)
  1036. {
  1037. $parts = explode('/', strtr($file, '\\', '/'));
  1038. $elements = explode('.', array_pop($parts));
  1039. if (3 > count($elements)) {
  1040. return false;
  1041. }
  1042. $engine = array_pop($elements);
  1043. $format = array_pop($elements);
  1044. return new TemplateReference('', implode('/', $parts), implode('.', $elements), $format, $engine);
  1045. }
  1046. }
  1047. }
  1048. namespace Symfony\Bundle\FrameworkBundle\Templating\Loader
  1049. {
  1050. use Symfony\Component\Config\FileLocatorInterface;
  1051. use Symfony\Component\Templating\TemplateReferenceInterface;
  1052. class TemplateLocator implements FileLocatorInterface
  1053. {
  1054. protected $locator;
  1055. protected $path;
  1056. protected $cache;
  1057. public function __construct(FileLocatorInterface $locator, $cacheDir = null)
  1058. {
  1059. if (null !== $cacheDir && file_exists($cache = $cacheDir.'/templates.php')) {
  1060. $this->cache = require $cache;
  1061. }
  1062. $this->locator = $locator;
  1063. }
  1064. public function locate($template, $currentPath = null, $first = true)
  1065. {
  1066. if (!$template instanceof TemplateReferenceInterface) {
  1067. throw new \InvalidArgumentException("The template must be an instance of TemplateReferenceInterface.");
  1068. }
  1069. $key = $template->getLogicalName();
  1070. if (isset($this->cache[$key])) {
  1071. return $this->cache[$key];
  1072. }
  1073. try {
  1074. return $this->cache[$key] = $this->locator->locate($template->getPath(), $currentPath);
  1075. } catch (\InvalidArgumentException $e) {
  1076. throw new \InvalidArgumentException(sprintf('Unable to find template "%s" in "%s".', $template, $this->path), 0, $e);
  1077. }
  1078. }
  1079. }
  1080. }
  1081. namespace Symfony\Component\HttpFoundation
  1082. {
  1083. class ParameterBag
  1084. {
  1085. protected $parameters;
  1086. public function __construct(array $parameters = array())
  1087. {
  1088. $this->parameters = $parameters;
  1089. }
  1090. public function all()
  1091. {
  1092. return $this->parameters;
  1093. }
  1094. public function keys()
  1095. {
  1096. return array_keys($this->parameters);
  1097. }
  1098. public function replace(array $parameters = array())
  1099. {
  1100. $this->parameters = $parameters;
  1101. }
  1102. public function add(array $parameters = array())
  1103. {
  1104. $this->parameters = array_replace($this->parameters, $parameters);
  1105. }
  1106. public function get($path, $default = null, $deep = false)
  1107. {
  1108. if (!$deep || false === $pos = strpos($path, '[')) {
  1109. return array_key_exists($path, $this->parameters) ? $this->parameters[$path] : $default;
  1110. }
  1111. $root = substr($path, 0, $pos);
  1112. if (!array_key_exists($root, $this->parameters)) {
  1113. return $default;
  1114. }
  1115. $value = $this->parameters[$root];
  1116. $currentKey = null;
  1117. for ($i=$pos,$c=strlen($path); $i<$c; $i++) {
  1118. $char = $path[$i];
  1119. if ('[' === $char) {
  1120. if (null !== $currentKey) {
  1121. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "[" at position %d.', $i));
  1122. }
  1123. $currentKey = '';
  1124. } else if (']' === $char) {
  1125. if (null === $currentKey) {
  1126. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "]" at position %d.', $i));
  1127. }
  1128. if (!is_array($value) || !array_key_exists($currentKey, $value)) {
  1129. return $default;
  1130. }
  1131. $value = $value[$currentKey];
  1132. $currentKey = null;
  1133. } else {
  1134. if (null === $currentKey) {
  1135. throw new \InvalidArgumentException(sprintf('Malformed path. Unexpected "%s" at position %d.', $char, $i));
  1136. }
  1137. $currentKey .= $char;
  1138. }
  1139. }
  1140. if (null !== $currentKey) {
  1141. throw new \InvalidArgumentException(sprintf('Malformed path. Path must end with "]".'));
  1142. }
  1143. return $value;
  1144. }
  1145. public function set($key, $value)
  1146. {
  1147. $this->parameters[$key] = $value;
  1148. }
  1149. public function has($key)
  1150. {
  1151. return array_key_exists($key, $this->parameters);
  1152. }
  1153. public function remove($key)
  1154. {
  1155. unset($this->parameters[$key]);
  1156. }
  1157. public function getAlpha($key, $default = '', $deep = false)
  1158. {
  1159. return preg_replace('/[^[:alpha:]]/', '', $this->get($key, $default, $deep));
  1160. }
  1161. public function getAlnum($key, $default = '', $deep = false)
  1162. {
  1163. return preg_replace('/[^[:alnum:]]/', '', $this->get($key, $default, $deep));
  1164. }
  1165. public function getDigits($key, $default = '', $deep = false)
  1166. {
  1167. return preg_replace('/[^[:digit:]]/', '', $this->get($key, $default, $deep));
  1168. }
  1169. public function getInt($key, $default = 0, $deep = false)
  1170. {
  1171. return (int) $this->get($key, $default, $deep);
  1172. }
  1173. }
  1174. }
  1175. namespace Symfony\Component\HttpFoundation
  1176. {
  1177. class HeaderBag
  1178. {
  1179. protected $headers;
  1180. protected $cacheControl;
  1181. public function __construct(array $headers = array())
  1182. {
  1183. $this->cacheControl = array();
  1184. $this->headers = array();
  1185. foreach ($headers as $key => $values) {
  1186. $this->set($key, $values);
  1187. }
  1188. }
  1189. public function __toString()
  1190. {
  1191. if (!$this->headers) {
  1192. return '';
  1193. }
  1194. $beautifier = function ($name) {
  1195. return preg_replace_callback('/\-(.)/', function ($match) { return '-'.strtoupper($match[1]); }, ucfirst($name));
  1196. };
  1197. $max = max(array_map('strlen', array_keys($this->headers))) + 1;
  1198. $content = '';
  1199. ksort($this->headers);
  1200. foreach ($this->headers as $name => $values) {
  1201. foreach ($values as $value) {
  1202. $content .= sprintf("%-{$max}s %s\r\n", $beautifier($name).':', $value);
  1203. }
  1204. }
  1205. return $content;
  1206. }
  1207. public function all()
  1208. {
  1209. return $this->headers;
  1210. }
  1211. public function keys()
  1212. {
  1213. return array_keys($this->headers);
  1214. }
  1215. public function replace(array $headers = array())
  1216. {
  1217. $this->headers = array();
  1218. $this->add($headers);
  1219. }
  1220. public function add(array $headers)
  1221. {
  1222. foreach ($headers as $key => $values) {
  1223. $this->set($key, $values);
  1224. }
  1225. }
  1226. public function get($key, $default = null, $first = true)
  1227. {
  1228. $key = strtr(strtolower($key), '_', '-');
  1229. if (!array_key_exists($key, $this->headers)) {
  1230. if (null === $default) {
  1231. return $first ? null : array();
  1232. }
  1233. return $first ? $default : array($default);
  1234. }
  1235. if ($first) {
  1236. return count($this->headers[$key]) ? $this->headers[$key][0] : $default;
  1237. }
  1238. return $this->headers[$key];
  1239. }
  1240. public function set($key, $values, $replace = true)
  1241. {
  1242. $key = strtr(strtolower($key), '_', '-');
  1243. $values = (array) $values;
  1244. if (true === $replace || !isset($this->headers[$key])) {
  1245. $this->headers[$key] = $values;
  1246. } else {
  1247. $this->headers[$key] = array_merge($this->headers[$key], $values);
  1248. }
  1249. if ('cache-control' === $key) {
  1250. $this->cacheControl = $this->parseCacheControl($values[0]);
  1251. }
  1252. }
  1253. public function has($key)
  1254. {
  1255. return array_key_exists(strtr(strtolower($key), '_', '-'), $this->headers);
  1256. }
  1257. public function contains($key, $value)
  1258. {
  1259. return in_array($value, $this->get($key, null, false));
  1260. }
  1261. public function remove($key)
  1262. {
  1263. $key = strtr(strtolower($key), '_', '-');
  1264. unset($this->headers[$key]);
  1265. if ('cache-control' === $key) {
  1266. $this->cacheControl = array();
  1267. }
  1268. }
  1269. public function getDate($key, \DateTime $default = null)
  1270. {
  1271. if (null === $value = $this->get($key)) {
  1272. return $default;
  1273. }
  1274. if (false === $date = \DateTime::createFromFormat(DATE_RFC2822, $value)) {
  1275. throw new \RuntimeException(sprintf('The %s HTTP header is not parseable (%s).', $key, $value));
  1276. }
  1277. return $date;
  1278. }
  1279. public function addCacheControlDirective($key, $value = true)
  1280. {
  1281. $this->cacheControl[$key] = $value;
  1282. $this->set('Cache-Control', $this->getCacheControlHeader());
  1283. }
  1284. public function hasCacheControlDirective($key)
  1285. {
  1286. return array_key_exists($key, $this->cacheControl);
  1287. }
  1288. public function getCacheControlDirective($key)
  1289. {
  1290. return array_key_exists($key, $this->cacheControl) ? $this->cacheControl[$key] : null;
  1291. }
  1292. public function removeCacheControlDirective($key)
  1293. {
  1294. unset($this->cacheControl[$key]);
  1295. $this->set('Cache-Control', $this->getCacheControlHeader());
  1296. }
  1297. protected function getCacheControlHeader()
  1298. {
  1299. $parts = array();
  1300. ksort($this->cacheControl);
  1301. foreach ($this->cacheControl as $key => $value) {
  1302. if (true === $value) {
  1303. $parts[] = $key;
  1304. } else {
  1305. if (preg_match('#[^a-zA-Z0-9._-]#', $value)) {
  1306. $value = '"'.$value.'"';
  1307. }
  1308. $parts[] = "$key=$value";
  1309. }
  1310. }
  1311. return implode(', ', $parts);
  1312. }
  1313. protected function parseCacheControl($header)
  1314. {
  1315. $cacheControl = array();
  1316. preg_match_all('#([a-zA-Z][a-zA-Z_-]*)\s*(?:=(?:"([^"]*)"|([^ \t",;]*)))?#', $header, $matches, PREG_SET_ORDER);
  1317. foreach ($matches as $match) {
  1318. $cacheControl[strtolower($match[1])] = isset($match[2]) && $match[2] ? $match[2] : (isset($match[3]) ? $match[3] : true);
  1319. }
  1320. return $cacheControl;
  1321. }
  1322. }
  1323. }
  1324. namespace Symfony\Component\HttpFoundation
  1325. {
  1326. use Symfony\Component\HttpFoundation\File\UploadedFile;
  1327. class FileBag extends ParameterBag
  1328. {
  1329. static private $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  1330. public function __construct(array $parameters = array())
  1331. {
  1332. $this->replace($parameters);
  1333. }
  1334. public function replace(array $files = array())
  1335. {
  1336. $this->parameters = array();
  1337. $this->add($files);
  1338. }
  1339. public function set($key, $value)
  1340. {
  1341. if (is_array($value) || $value instanceof UploadedFile) {
  1342. parent::set($key, $this->convertFileInformation($value));
  1343. } else {
  1344. throw new \InvalidArgumentException('An uploaded file must be an array or an instance of UploadedFile.');
  1345. }
  1346. }
  1347. public function add(array $files = array())
  1348. {
  1349. foreach ($files as $key => $file) {
  1350. $this->set($key, $file);
  1351. }
  1352. }
  1353. protected function convertFileInformation($file)
  1354. {
  1355. if ($file instanceof UploadedFile) {
  1356. return $file;
  1357. }
  1358. $file = $this->fixPhpFilesArray($file);
  1359. if (is_array($file)) {
  1360. $keys = array_keys($file);
  1361. sort($keys);
  1362. if ($keys == self::$fileKeys) {
  1363. if (UPLOAD_ERR_NO_FILE == $file['error']) {
  1364. $file = null;
  1365. } else {
  1366. $file = new UploadedFile($file['tmp_name'], $file['name'], $file['type'], $file['size'], $file['error']);
  1367. }
  1368. } else {
  1369. $file = array_map(array($this, 'convertFileInformation'), $file);
  1370. }
  1371. }
  1372. return $file;
  1373. }
  1374. protected function fixPhpFilesArray($data)
  1375. {
  1376. if (!is_array($data)) {
  1377. return $data;
  1378. }
  1379. $keys = array_keys($data);
  1380. sort($keys);
  1381. if (self::$fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
  1382. return $data;
  1383. }
  1384. $files = $data;
  1385. foreach (self::$fileKeys as $k) {
  1386. unset($files[$k]);
  1387. }
  1388. foreach (array_keys($data['name']) as $key) {
  1389. $files[$key] = $this->fixPhpFilesArray(array(
  1390. 'error' => $data['error'][$key],
  1391. 'name' => $data['name'][$key],
  1392. 'type' => $data['type'][$key],
  1393. 'tmp_name' => $data['tmp_name'][$key],
  1394. 'size' => $data['size'][$key]
  1395. ));
  1396. }
  1397. return $files;
  1398. }
  1399. }
  1400. }
  1401. namespace Symfony\Component\HttpFoundation
  1402. {
  1403. class ServerBag extends ParameterBag
  1404. {
  1405. public function getHeaders()
  1406. {
  1407. $headers = array();
  1408. foreach ($this->parameters as $key => $value) {
  1409. if ('HTTP_' === substr($key, 0, 5)) {
  1410. $headers[substr($key, 5)] = $value;
  1411. }
  1412. elseif (in_array($key, array('CONTENT_LENGTH', 'CONTENT_MD5', 'CONTENT_TYPE'))) {
  1413. $headers[$key] = $this->parameters[$key];
  1414. }
  1415. }
  1416. if (isset($this->parameters['PHP_AUTH_USER'])) {
  1417. $pass = isset($this->parameters['PHP_AUTH_PW']) ? $this->parameters['PHP_AUTH_PW'] : '';
  1418. $headers['AUTHORIZATION'] = 'Basic '.base64_encode($this->parameters['PHP_AUTH_USER'].':'.$pass);
  1419. }
  1420. return $headers;
  1421. }
  1422. }
  1423. }
  1424. namespace Symfony\Component\HttpFoundation
  1425. {
  1426. use Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage;
  1427. class Request
  1428. {
  1429. static protected $trustProxy = false;
  1430. public $attributes;
  1431. public $request;
  1432. public $query;
  1433. public $server;
  1434. public $files;
  1435. public $cookies;
  1436. public $headers;
  1437. protected $content;
  1438. protected $languages;
  1439. protected $charsets;
  1440. protected $acceptableContentTypes;
  1441. protected $pathInfo;
  1442. protected $requestUri;
  1443. protected $baseUrl;
  1444. protected $basePath;
  1445. protected $method;
  1446. protected $format;
  1447. protected $session;
  1448. static protected $formats;
  1449. public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1450. {
  1451. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  1452. }
  1453. public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  1454. {
  1455. $this->request = new ParameterBag($request);
  1456. $this->query = new ParameterBag($query);
  1457. $this->attributes = new ParameterBag($attributes);
  1458. $this->cookies = new ParameterBag($cookies);
  1459. $this->files = new FileBag($files);
  1460. $this->server = new ServerBag($server);
  1461. $this->headers = new HeaderBag($this->server->getHeaders());
  1462. $this->content = $content;
  1463. $this->languages = null;
  1464. $this->charsets = null;
  1465. $this->acceptableContentTypes = null;
  1466. $this->pathInfo = null;
  1467. $this->requestUri = null;
  1468. $this->baseUrl = null;
  1469. $this->basePath = null;
  1470. $this->method = null;
  1471. $this->format = null;
  1472. }
  1473. static public function createFromGlobals()
  1474. {
  1475. $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
  1476. if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
  1477. && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE'))
  1478. ) {
  1479. parse_str($request->getContent(), $data);
  1480. $request->request = new ParameterBag($data);
  1481. }
  1482. return $request;
  1483. }
  1484. static public function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  1485. {
  1486. $defaults = array(
  1487. 'SERVER_NAME' => 'localhost',
  1488. 'SERVER_PORT' => 80,
  1489. 'HTTP_HOST' => 'localhost',
  1490. 'HTTP_USER_AGENT' => 'Symfony/2.X',
  1491. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  1492. 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  1493. 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  1494. 'REMOTE_ADDR' => '127.0.0.1',
  1495. 'SCRIPT_NAME' => '',
  1496. 'SCRIPT_FILENAME' => '',
  1497. 'SERVER_PROTOCOL' => 'HTTP/1.1',
  1498. 'REQUEST_TIME' => time(),
  1499. );
  1500. $components = parse_url($uri);
  1501. if (isset($components['host'])) {
  1502. $defaults['SERVER_NAME'] = $components['host'];
  1503. $defaults['HTTP_HOST'] = $components['host'];
  1504. }
  1505. if (isset($components['scheme'])) {
  1506. if ('https' === $components['scheme']) {
  1507. $defaults['HTTPS'] = 'on';
  1508. $defaults['SERVER_PORT'] = 443;
  1509. }
  1510. }
  1511. if (isset($components['port'])) {
  1512. $defaults['SERVER_PORT'] = $components['port'];
  1513. $defaults['HTTP_HOST'] = $defaults['HTTP_HOST'].':'.$components['port'];
  1514. }
  1515. if (!isset($components['path'])) {
  1516. $components['path'] = '';
  1517. }
  1518. if (in_array(strtoupper($method), array('POST', 'PUT', 'DELETE'))) {
  1519. $request = $parameters;
  1520. $query = array();
  1521. $defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  1522. } else {
  1523. $request = array();
  1524. $query = $parameters;
  1525. if (false !== $pos = strpos($uri, '?')) {
  1526. $qs = substr($uri, $pos + 1);
  1527. parse_str($qs, $params);
  1528. $query = array_merge($params, $query);
  1529. }
  1530. }
  1531. $queryString = isset($components['query']) ? html_entity_decode($components['query']) : '';
  1532. parse_str($queryString, $qs);
  1533. if (is_array($qs)) {
  1534. $query = array_replace($qs, $query);
  1535. }
  1536. $uri = $components['path'].($queryString ? '?'.$queryString : '');
  1537. $server = array_replace($defaults, $server, array(
  1538. 'REQUEST_METHOD' => strtoupper($method),
  1539. 'PATH_INFO' => '',
  1540. 'REQUEST_URI' => $uri,
  1541. 'QUERY_STRING' => $queryString,
  1542. ));
  1543. return new static($query, $request, array(), $cookies, $files, $server, $content);
  1544. }
  1545. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
  1546. {
  1547. $dup = clone $this;
  1548. if ($query !== null) {
  1549. $dup->query = new ParameterBag($query);
  1550. }
  1551. if ($request !== null) {
  1552. $dup->request = new ParameterBag($request);
  1553. }
  1554. if ($attributes !== null) {
  1555. $dup->attributes = new ParameterBag($attributes);
  1556. }
  1557. if ($cookies !== null) {
  1558. $dup->cookies = new ParameterBag($cookies);
  1559. }
  1560. if ($files !== null) {
  1561. $dup->files = new FileBag($files);
  1562. }
  1563. if ($server !== null) {
  1564. $dup->server = new ServerBag($server);
  1565. $dup->headers = new HeaderBag($dup->server->getHeaders());
  1566. }
  1567. $this->languages = null;
  1568. $this->charsets = null;
  1569. $this->acceptableContentTypes = null;
  1570. $this->pathInfo = null;
  1571. $this->requestUri = null;
  1572. $this->baseUrl = null;
  1573. $this->basePath = null;
  1574. $this->method = null;
  1575. $this->format = null;
  1576. return $dup;
  1577. }
  1578. public function __clone()
  1579. {
  1580. $this->query = clone $this->query;
  1581. $this->request = clone $this->request;
  1582. $this->attributes = clone $this->attributes;
  1583. $this->cookies = clone $this->cookies;
  1584. $this->files = clone $this->files;
  1585. $this->server = clone $this->server;
  1586. $this->headers = clone $this->headers;
  1587. }
  1588. public function __toString()
  1589. {
  1590. return
  1591. sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  1592. $this->headers."\r\n".
  1593. $this->getContent();
  1594. }
  1595. public function overrideGlobals()
  1596. {
  1597. $_GET = $this->query->all();
  1598. $_POST = $this->request->all();
  1599. $_SERVER = $this->server->all();
  1600. $_COOKIE = $this->cookies->all();
  1601. foreach ($this->headers->all() as $key => $value) {
  1602. $key = strtoupper(str_replace('-', '_', $key));
  1603. if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
  1604. $_SERVER[$key] = implode(', ', $value);
  1605. } else {
  1606. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  1607. }
  1608. }
  1609. $_REQUEST = array_merge($_GET, $_POST);
  1610. }
  1611. static public function trustProxyData()
  1612. {
  1613. self::$trustProxy = true;
  1614. }
  1615. public function get($key, $default = null, $deep = false)
  1616. {
  1617. return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default, $deep), $deep), $deep);
  1618. }
  1619. public function getSession()
  1620. {
  1621. return $this->session;
  1622. }
  1623. public function hasPreviousSession()
  1624. {
  1625. return $this->cookies->has(session_name()) && null !== $this->session;
  1626. }
  1627. public function hasSession()
  1628. {
  1629. return null !== $this->session;
  1630. }
  1631. public function setSession(Session $session)
  1632. {
  1633. $this->session = $session;
  1634. }
  1635. public function getClientIp($proxy = false)
  1636. {
  1637. if ($proxy) {
  1638. if ($this->server->has('HTTP_CLIENT_IP')) {
  1639. return $this->server->get('HTTP_CLIENT_IP');
  1640. } elseif (self::$trustProxy && $this->server->has('HTTP_X_FORWARDED_FOR')) {
  1641. return $this->server->get('HTTP_X_FORWARDED_FOR');
  1642. }
  1643. }
  1644. return $this->server->get('REMOTE_ADDR');
  1645. }
  1646. public function getScriptName()
  1647. {
  1648. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
  1649. }
  1650. public function getPathInfo()
  1651. {
  1652. if (null === $this->pathInfo) {
  1653. $this->pathInfo = $this->preparePathInfo();
  1654. }
  1655. return $this->pathInfo;
  1656. }
  1657. public function getBasePath()
  1658. {
  1659. if (null === $this->basePath) {
  1660. $this->basePath = $this->prepareBasePath();
  1661. }
  1662. return $this->basePath;
  1663. }
  1664. public function getBaseUrl()
  1665. {
  1666. if (null === $this->baseUrl) {
  1667. $this->baseUrl = $this->prepareBaseUrl();
  1668. }
  1669. return $this->baseUrl;
  1670. }
  1671. public function getScheme()
  1672. {
  1673. return $this->isSecure() ? 'https' : 'http';
  1674. }
  1675. public function getPort()
  1676. {
  1677. return $this->headers->get('X-Forwarded-Port') ?: $this->server->get('SERVER_PORT');
  1678. }
  1679. public function getHttpHost()
  1680. {
  1681. $scheme = $this->getScheme();
  1682. $port = $this->getPort();
  1683. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  1684. return $this->getHost();
  1685. }
  1686. return $this->getHost().':'.$port;
  1687. }
  1688. public function getRequestUri()
  1689. {
  1690. if (null === $this->requestUri) {
  1691. $this->requestUri = $this->prepareRequestUri();
  1692. }
  1693. return $this->requestUri;
  1694. }
  1695. public function getUri()
  1696. {
  1697. $qs = $this->getQueryString();
  1698. if (null !== $qs) {
  1699. $qs = '?'.$qs;
  1700. }
  1701. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  1702. }
  1703. public function getUriForPath($path)
  1704. {
  1705. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$path;
  1706. }
  1707. public function getQueryString()
  1708. {
  1709. if (!$qs = $this->server->get('QUERY_STRING')) {
  1710. return null;
  1711. }
  1712. $parts = array();
  1713. $order = array();
  1714. foreach (explode('&', $qs) as $segment) {
  1715. if (false === strpos($segment, '=')) {
  1716. $parts[] = $segment;
  1717. $order[] = $segment;
  1718. } else {
  1719. $tmp = explode('=', rawurldecode($segment), 2);
  1720. $parts[] = rawurlencode($tmp[0]).'='.rawurlencode($tmp[1]);
  1721. $order[] = $tmp[0];
  1722. }
  1723. }
  1724. array_multisort($order, SORT_ASC, $parts);
  1725. return implode('&', $parts);
  1726. }
  1727. public function isSecure()
  1728. {
  1729. return (
  1730. (strtolower($this->server->get('HTTPS')) == 'on' || $this->server->get('HTTPS') == 1)
  1731. ||
  1732. (self::$trustProxy && strtolower($this->headers->get('SSL_HTTPS')) == 'on' || $this->headers->get('SSL_HTTPS') == 1)
  1733. ||
  1734. (self::$trustProxy && strtolower($this->headers->get('X_FORWARDED_PROTO')) == 'https')
  1735. );
  1736. }
  1737. public function getHost()
  1738. {
  1739. if (self::$trustProxy && $host = $this->headers->get('X_FORWARDED_HOST')) {
  1740. $elements = explode(',', $host);
  1741. $host = trim($elements[count($elements) - 1]);
  1742. } else {
  1743. if (!$host = $this->headers->get('HOST')) {
  1744. if (!$host = $this->server->get('SERVER_NAME')) {
  1745. $host = $this->server->get('SERVER_ADDR', '');
  1746. }
  1747. }
  1748. }
  1749. $host = preg_replace('/:\d+$/', '', $host);
  1750. return trim($host);
  1751. }
  1752. public function setMethod($method)
  1753. {
  1754. $this->method = null;
  1755. $this->server->set('REQUEST_METHOD', $method);
  1756. }
  1757. public function getMethod()
  1758. {
  1759. if (null === $this->method) {
  1760. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  1761. if ('POST' === $this->method) {
  1762. $this->method = strtoupper($this->headers->get('X-HTTP-METHOD-OVERRIDE', $this->request->get('_method', 'POST')));
  1763. }
  1764. }
  1765. return $this->method;
  1766. }
  1767. public function getMimeType($format)
  1768. {
  1769. if (null === static::$formats) {
  1770. static::initializeFormats();
  1771. }
  1772. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  1773. }
  1774. public function getFormat($mimeType)
  1775. {
  1776. if (false !== $pos = strpos($mimeType, ';')) {
  1777. $mimeType = substr($mimeType, 0, $pos);
  1778. }
  1779. if (null === static::$formats) {
  1780. static::initializeFormats();
  1781. }
  1782. foreach (static::$formats as $format => $mimeTypes) {
  1783. if (in_array($mimeType, (array) $mimeTypes)) {
  1784. return $format;
  1785. }
  1786. }
  1787. return null;
  1788. }
  1789. public function setFormat($format, $mimeTypes)
  1790. {
  1791. if (null === static::$formats) {
  1792. static::initializeFormats();
  1793. }
  1794. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  1795. }
  1796. public function getRequestFormat($default = 'html')
  1797. {
  1798. if (null === $this->format) {
  1799. $this->format = $this->get('_format', $default);
  1800. }
  1801. return $this->format;
  1802. }
  1803. public function setRequestFormat($format)
  1804. {
  1805. $this->format = $format;
  1806. }
  1807. public function isMethodSafe()
  1808. {
  1809. return in_array($this->getMethod(), array('GET', 'HEAD'));
  1810. }
  1811. public function getContent($asResource = false)
  1812. {
  1813. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  1814. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  1815. }
  1816. if (true === $asResource) {
  1817. $this->content = false;
  1818. return fopen('php://input', 'rb');
  1819. }
  1820. if (null === $this->content) {
  1821. $this->content = file_get_contents('php://input');
  1822. }
  1823. return $this->content;
  1824. }
  1825. public function getETags()
  1826. {
  1827. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  1828. }
  1829. public function isNoCache()
  1830. {
  1831. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  1832. }
  1833. public function getPreferredLanguage(array $locales = null)
  1834. {
  1835. $preferredLanguages = $this->getLanguages();
  1836. if (null === $locales) {
  1837. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  1838. }
  1839. if (!$preferredLanguages) {
  1840. return $locales[0];
  1841. }
  1842. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  1843. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  1844. }
  1845. public function getLanguages()
  1846. {
  1847. if (null !== $this->languages) {
  1848. return $this->languages;
  1849. }
  1850. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  1851. $this->languages = array();
  1852. foreach ($languages as $lang => $q) {
  1853. if (strstr($lang, '-')) {
  1854. $codes = explode('-', $lang);
  1855. if ($codes[0] == 'i') {
  1856. if (count($codes) > 1) {
  1857. $lang = $codes[1];
  1858. }
  1859. } else {
  1860. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  1861. if ($i == 0) {
  1862. $lang = strtolower($codes[0]);
  1863. } else {
  1864. $lang .= '_'.strtoupper($codes[$i]);
  1865. }
  1866. }
  1867. }
  1868. }
  1869. $this->languages[] = $lang;
  1870. }
  1871. return $this->languages;
  1872. }
  1873. public function getCharsets()
  1874. {
  1875. if (null !== $this->charsets) {
  1876. return $this->charsets;
  1877. }
  1878. return $this->charsets = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept-Charset')));
  1879. }
  1880. public function getAcceptableContentTypes()
  1881. {
  1882. if (null !== $this->acceptableContentTypes) {
  1883. return $this->acceptableContentTypes;
  1884. }
  1885. return $this->acceptableContentTypes = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept')));
  1886. }
  1887. public function isXmlHttpRequest()
  1888. {
  1889. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1890. }
  1891. public function splitHttpAcceptHeader($header)
  1892. {
  1893. if (!$header) {
  1894. return array();
  1895. }
  1896. $values = array();
  1897. foreach (array_filter(explode(',', $header)) as $value) {
  1898. if ($pos = strpos($value, ';')) {
  1899. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  1900. $value = trim(substr($value, 0, $pos));
  1901. } else {
  1902. $q = 1;
  1903. }
  1904. if (0 < $q) {
  1905. $values[trim($value)] = $q;
  1906. }
  1907. }
  1908. arsort($values);
  1909. reset($values);
  1910. return $values;
  1911. }
  1912. protected function prepareRequestUri()
  1913. {
  1914. $requestUri = '';
  1915. if ($this->headers->has('X_REWRITE_URL')) {
  1916. $requestUri = $this->headers->get('X_REWRITE_URL');
  1917. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  1918. $requestUri = $this->server->get('UNENCODED_URL');
  1919. } elseif ($this->server->has('REQUEST_URI')) {
  1920. $requestUri = $this->server->get('REQUEST_URI');
  1921. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  1922. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  1923. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  1924. }
  1925. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1926. $requestUri = $this->server->get('ORIG_PATH_INFO');
  1927. if ($this->server->get('QUERY_STRING')) {
  1928. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1929. }
  1930. }
  1931. return $requestUri;
  1932. }
  1933. protected function prepareBaseUrl()
  1934. {
  1935. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1936. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  1937. $baseUrl = $this->server->get('SCRIPT_NAME');
  1938. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  1939. $baseUrl = $this->server->get('PHP_SELF');
  1940. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  1941. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); } else {
  1942. $path = $this->server->get('PHP_SELF', '');
  1943. $file = $this->server->get('SCRIPT_FILENAME', '');
  1944. $segs = explode('/', trim($file, '/'));
  1945. $segs = array_reverse($segs);
  1946. $index = 0;
  1947. $last = count($segs);
  1948. $baseUrl = '';
  1949. do {
  1950. $seg = $segs[$index];
  1951. $baseUrl = '/'.$seg.$baseUrl;
  1952. ++$index;
  1953. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  1954. }
  1955. $requestUri = $this->getRequestUri();
  1956. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  1957. return $baseUrl;
  1958. }
  1959. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  1960. return rtrim(dirname($baseUrl), '/');
  1961. }
  1962. $truncatedRequestUri = $requestUri;
  1963. if (($pos = strpos($requestUri, '?')) !== false) {
  1964. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1965. }
  1966. $basename = basename($baseUrl);
  1967. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  1968. return '';
  1969. }
  1970. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  1971. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1972. }
  1973. return rtrim($baseUrl, '/');
  1974. }
  1975. protected function prepareBasePath()
  1976. {
  1977. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1978. $baseUrl = $this->getBaseUrl();
  1979. if (empty($baseUrl)) {
  1980. return '';
  1981. }
  1982. if (basename($baseUrl) === $filename) {
  1983. $basePath = dirname($baseUrl);
  1984. } else {
  1985. $basePath = $baseUrl;
  1986. }
  1987. if ('\\' === DIRECTORY_SEPARATOR) {
  1988. $basePath = str_replace('\\', '/', $basePath);
  1989. }
  1990. return rtrim($basePath, '/');
  1991. }
  1992. protected function preparePathInfo()
  1993. {
  1994. $baseUrl = $this->getBaseUrl();
  1995. if (null === ($requestUri = $this->getRequestUri())) {
  1996. return '/';
  1997. }
  1998. $pathInfo = '/';
  1999. if ($pos = strpos($requestUri, '?')) {
  2000. $requestUri = substr($requestUri, 0, $pos);
  2001. }
  2002. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  2003. return '/';
  2004. } elseif (null === $baseUrl) {
  2005. return $requestUri;
  2006. }
  2007. return (string) $pathInfo;
  2008. }
  2009. static protected function initializeFormats()
  2010. {
  2011. static::$formats = array(
  2012. 'html' => array('text/html', 'application/xhtml+xml'),
  2013. 'txt' => array('text/plain'),
  2014. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  2015. 'css' => array('text/css'),
  2016. 'json' => array('application/json', 'application/x-json'),
  2017. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  2018. 'rdf' => array('application/rdf+xml'),
  2019. 'atom' => array('application/atom+xml'),
  2020. );
  2021. }
  2022. }
  2023. }
  2024. namespace Symfony\Component\HttpFoundation
  2025. {
  2026. class Response
  2027. {
  2028. public $headers;
  2029. protected $content;
  2030. protected $version;
  2031. protected $statusCode;
  2032. protected $statusText;
  2033. protected $charset;
  2034. static public $statusTexts = array(
  2035. 100 => 'Continue',
  2036. 101 => 'Switching Protocols',
  2037. 200 => 'OK',
  2038. 201 => 'Created',
  2039. 202 => 'Accepted',
  2040. 203 => 'Non-Authoritative Information',
  2041. 204 => 'No Content',
  2042. 205 => 'Reset Content',
  2043. 206 => 'Partial Content',
  2044. 300 => 'Multiple Choices',
  2045. 301 => 'Moved Permanently',
  2046. 302 => 'Found',
  2047. 303 => 'See Other',
  2048. 304 => 'Not Modified',
  2049. 305 => 'Use Proxy',
  2050. 307 => 'Temporary Redirect',
  2051. 400 => 'Bad Request',
  2052. 401 => 'Unauthorized',
  2053. 402 => 'Payment Required',
  2054. 403 => 'Forbidden',
  2055. 404 => 'Not Found',
  2056. 405 => 'Method Not Allowed',
  2057. 406 => 'Not Acceptable',
  2058. 407 => 'Proxy Authentication Required',
  2059. 408 => 'Request Timeout',
  2060. 409 => 'Conflict',
  2061. 410 => 'Gone',
  2062. 411 => 'Length Required',
  2063. 412 => 'Precondition Failed',
  2064. 413 => 'Request Entity Too Large',
  2065. 414 => 'Request-URI Too Long',
  2066. 415 => 'Unsupported Media Type',
  2067. 416 => 'Requested Range Not Satisfiable',
  2068. 417 => 'Expectation Failed',
  2069. 418 => 'I\'m a teapot',
  2070. 500 => 'Internal Server Error',
  2071. 501 => 'Not Implemented',
  2072. 502 => 'Bad Gateway',
  2073. 503 => 'Service Unavailable',
  2074. 504 => 'Gateway Timeout',
  2075. 505 => 'HTTP Version Not Supported',
  2076. );
  2077. public function __construct($content = '', $status = 200, $headers = array())
  2078. {
  2079. $this->headers = new ResponseHeaderBag($headers);
  2080. $this->setContent($content);
  2081. $this->setStatusCode($status);
  2082. $this->setProtocolVersion('1.0');
  2083. if (!$this->headers->has('Date')) {
  2084. $this->setDate(new \DateTime(null, new \DateTimeZone('UTC')));
  2085. }
  2086. }
  2087. public function __toString()
  2088. {
  2089. $this->prepare();
  2090. return
  2091. sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText)."\r\n".
  2092. $this->headers."\r\n".
  2093. $this->getContent();
  2094. }
  2095. public function __clone()
  2096. {
  2097. $this->headers = clone $this->headers;
  2098. }
  2099. public function prepare()
  2100. {
  2101. if ($this->isInformational() || in_array($this->statusCode, array(204, 304))) {
  2102. $this->setContent('');
  2103. }
  2104. $charset = $this->charset ?: 'UTF-8';
  2105. if (!$this->headers->has('Content-Type')) {
  2106. $this->headers->set('Content-Type', 'text/html; charset='.$charset);
  2107. } elseif ('text/' === substr($this->headers->get('Content-Type'), 0, 5) && false === strpos($this->headers->get('Content-Type'), 'charset')) {
  2108. $this->headers->set('Content-Type', $this->headers->get('Content-Type').'; charset='.$charset);
  2109. }
  2110. if ($this->headers->has('Transfer-Encoding')) {
  2111. $this->headers->remove('Content-Length');
  2112. }
  2113. }
  2114. public function sendHeaders()
  2115. {
  2116. if (headers_sent()) {
  2117. return;
  2118. }
  2119. $this->prepare();
  2120. header(sprintf('HTTP/%s %s %s', $this->version, $this->statusCode, $this->statusText));
  2121. foreach ($this->headers->all() as $name => $values) {
  2122. foreach ($values as $value) {
  2123. header($name.': '.$value, false);
  2124. }
  2125. }
  2126. foreach ($this->headers->getCookies() as $cookie) {
  2127. setcookie($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
  2128. }
  2129. }
  2130. public function sendContent()
  2131. {
  2132. echo $this->content;
  2133. }
  2134. public function send()
  2135. {
  2136. $this->sendHeaders();
  2137. $this->sendContent();
  2138. if (function_exists('fastcgi_finish_request')) {
  2139. fastcgi_finish_request();
  2140. }
  2141. }
  2142. public function setContent($content)
  2143. {
  2144. if (null !== $content && !is_string($content) && !is_numeric($content) && !is_callable(array($content, '__toString'))) {
  2145. throw new \UnexpectedValueException('The Response content must be a string or object implementing __toString(), "'.gettype($content).'" given.');
  2146. }
  2147. $this->content = (string) $content;
  2148. }
  2149. public function getContent()
  2150. {
  2151. return $this->content;
  2152. }
  2153. public function setProtocolVersion($version)
  2154. {
  2155. $this->version = $version;
  2156. }
  2157. public function getProtocolVersion()
  2158. {
  2159. return $this->version;
  2160. }
  2161. public function setStatusCode($code, $text = null)
  2162. {
  2163. $this->statusCode = (int) $code;
  2164. if ($this->isInvalid()) {
  2165. throw new \InvalidArgumentException(sprintf('The HTTP status code "%s" is not valid.', $code));
  2166. }
  2167. $this->statusText = false === $text ? '' : (null === $text ? self::$statusTexts[$this->statusCode] : $text);
  2168. }
  2169. public function getStatusCode()
  2170. {
  2171. return $this->statusCode;
  2172. }
  2173. public function setCharset($charset)
  2174. {
  2175. $this->charset = $charset;
  2176. }
  2177. public function getCharset()
  2178. {
  2179. return $this->charset;
  2180. }
  2181. public function isCacheable()
  2182. {
  2183. if (!in_array($this->statusCode, array(200, 203, 300, 301, 302, 404, 410))) {
  2184. return false;
  2185. }
  2186. if ($this->headers->hasCacheControlDirective('no-store') || $this->headers->getCacheControlDirective('private')) {
  2187. return false;
  2188. }
  2189. return $this->isValidateable() || $this->isFresh();
  2190. }
  2191. public function isFresh()
  2192. {
  2193. return $this->getTtl() > 0;
  2194. }
  2195. public function isValidateable()
  2196. {
  2197. return $this->headers->has('Last-Modified') || $this->headers->has('ETag');
  2198. }
  2199. public function setPrivate()
  2200. {
  2201. $this->headers->removeCacheControlDirective('public');
  2202. $this->headers->addCacheControlDirective('private');
  2203. }
  2204. public function setPublic()
  2205. {
  2206. $this->headers->addCacheControlDirective('public');
  2207. $this->headers->removeCacheControlDirective('private');
  2208. }
  2209. public function mustRevalidate()
  2210. {
  2211. return $this->headers->hasCacheControlDirective('must-revalidate') || $this->headers->has('must-proxy-revalidate');
  2212. }
  2213. public function getDate()
  2214. {
  2215. return $this->headers->getDate('Date');
  2216. }
  2217. public function setDate(\DateTime $date)
  2218. {
  2219. $date->setTimezone(new \DateTimeZone('UTC'));
  2220. $this->headers->set('Date', $date->format('D, d M Y H:i:s').' GMT');
  2221. }
  2222. public function getAge()
  2223. {
  2224. if ($age = $this->headers->get('Age')) {
  2225. return $age;
  2226. }
  2227. return max(time() - $this->getDate()->format('U'), 0);
  2228. }
  2229. public function expire()
  2230. {
  2231. if ($this->isFresh()) {
  2232. $this->headers->set('Age', $this->getMaxAge());
  2233. }
  2234. }
  2235. public function getExpires()
  2236. {
  2237. return $this->headers->getDate('Expires');
  2238. }
  2239. public function setExpires(\DateTime $date = null)
  2240. {
  2241. if (null === $date) {
  2242. $this->headers->remove('Expires');
  2243. } else {
  2244. $date = clone $date;
  2245. $date->setTimezone(new \DateTimeZone('UTC'));
  2246. $this->headers->set('Expires', $date->format('D, d M Y H:i:s').' GMT');
  2247. }
  2248. }
  2249. public function getMaxAge()
  2250. {
  2251. if ($age = $this->headers->getCacheControlDirective('s-maxage')) {
  2252. return $age;
  2253. }
  2254. if ($age = $this->headers->getCacheControlDirective('max-age')) {
  2255. return $age;
  2256. }
  2257. if (null !== $this->getExpires()) {
  2258. return $this->getExpires()->format('U') - $this->getDate()->format('U');
  2259. }
  2260. return null;
  2261. }
  2262. public function setMaxAge($value)
  2263. {
  2264. $this->headers->addCacheControlDirective('max-age', $value);
  2265. }
  2266. public function setSharedMaxAge($value)
  2267. {
  2268. $this->setPublic();
  2269. $this->headers->addCacheControlDirective('s-maxage', $value);
  2270. }
  2271. public function getTtl()
  2272. {
  2273. if ($maxAge = $this->getMaxAge()) {
  2274. return $maxAge - $this->getAge();
  2275. }
  2276. return null;
  2277. }
  2278. public function setTtl($seconds)
  2279. {
  2280. $this->setSharedMaxAge($this->getAge() + $seconds);
  2281. }
  2282. public function setClientTtl($seconds)
  2283. {
  2284. $this->setMaxAge($this->getAge() + $seconds);
  2285. }
  2286. public function getLastModified()
  2287. {
  2288. return $this->headers->getDate('Last-Modified');
  2289. }
  2290. public function setLastModified(\DateTime $date = null)
  2291. {
  2292. if (null === $date) {
  2293. $this->headers->remove('Last-Modified');
  2294. } else {
  2295. $date = clone $date;
  2296. $date->setTimezone(new \DateTimeZone('UTC'));
  2297. $this->headers->set('Last-Modified', $date->format('D, d M Y H:i:s').' GMT');
  2298. }
  2299. }
  2300. public function getEtag()
  2301. {
  2302. return $this->headers->get('ETag');
  2303. }
  2304. public function setEtag($etag = null, $weak = false)
  2305. {
  2306. if (null === $etag) {
  2307. $this->headers->remove('Etag');
  2308. } else {
  2309. if (0 !== strpos($etag, '"')) {
  2310. $etag = '"'.$etag.'"';
  2311. }
  2312. $this->headers->set('ETag', (true === $weak ? 'W/' : '').$etag);
  2313. }
  2314. }
  2315. public function setCache(array $options)
  2316. {
  2317. if ($diff = array_diff(array_keys($options), array('etag', 'last_modified', 'max_age', 's_maxage', 'private', 'public'))) {
  2318. throw new \InvalidArgumentException(sprintf('Response does not support the following options: "%s".', implode('", "', array_keys($diff))));
  2319. }
  2320. if (isset($options['etag'])) {
  2321. $this->setEtag($options['etag']);
  2322. }
  2323. if (isset($options['last_modified'])) {
  2324. $this->setLastModified($options['last_modified']);
  2325. }
  2326. if (isset($options['max_age'])) {
  2327. $this->setMaxAge($options['max_age']);
  2328. }
  2329. if (isset($options['s_maxage'])) {
  2330. $this->setSharedMaxAge($options['s_maxage']);
  2331. }
  2332. if (isset($options['public'])) {
  2333. if ($options['public']) {
  2334. $this->setPublic();
  2335. } else {
  2336. $this->setPrivate();
  2337. }
  2338. }
  2339. if (isset($options['private'])) {
  2340. if ($options['private']) {
  2341. $this->setPrivate();
  2342. } else {
  2343. $this->setPublic();
  2344. }
  2345. }
  2346. }
  2347. public function setNotModified()
  2348. {
  2349. $this->setStatusCode(304);
  2350. $this->setContent(null);
  2351. foreach (array('Allow', 'Content-Encoding', 'Content-Language', 'Content-Length', 'Content-MD5', 'Content-Type', 'Last-Modified') as $header) {
  2352. $this->headers->remove($header);
  2353. }
  2354. }
  2355. public function hasVary()
  2356. {
  2357. return (Boolean) $this->headers->get('Vary');
  2358. }
  2359. public function getVary()
  2360. {
  2361. if (!$vary = $this->headers->get('Vary')) {
  2362. return array();
  2363. }
  2364. return is_array($vary) ? $vary : preg_split('/[\s,]+/', $vary);
  2365. }
  2366. public function setVary($headers, $replace = true)
  2367. {
  2368. $this->headers->set('Vary', $headers, $replace);
  2369. }
  2370. public function isNotModified(Request $request)
  2371. {
  2372. $lastModified = $request->headers->get('If-Modified-Since');
  2373. $notModified = false;
  2374. if ($etags = $request->getEtags()) {
  2375. $notModified = (in_array($this->getEtag(), $etags) || in_array('*', $etags)) && (!$lastModified || $this->headers->get('Last-Modified') == $lastModified);
  2376. } elseif ($lastModified) {
  2377. $notModified = $lastModified == $this->headers->get('Last-Modified');
  2378. }
  2379. if ($notModified) {
  2380. $this->setNotModified();
  2381. }
  2382. return $notModified;
  2383. }
  2384. public function isInvalid()
  2385. {
  2386. return $this->statusCode < 100 || $this->statusCode >= 600;
  2387. }
  2388. public function isInformational()
  2389. {
  2390. return $this->statusCode >= 100 && $this->statusCode < 200;
  2391. }
  2392. public function isSuccessful()
  2393. {
  2394. return $this->statusCode >= 200 && $this->statusCode < 300;
  2395. }
  2396. public function isRedirection()
  2397. {
  2398. return $this->statusCode >= 300 && $this->statusCode < 400;
  2399. }
  2400. public function isClientError()
  2401. {
  2402. return $this->statusCode >= 400 && $this->statusCode < 500;
  2403. }
  2404. public function isServerError()
  2405. {
  2406. return $this->statusCode >= 500 && $this->statusCode < 600;
  2407. }
  2408. public function isOk()
  2409. {
  2410. return 200 === $this->statusCode;
  2411. }
  2412. public function isForbidden()
  2413. {
  2414. return 403 === $this->statusCode;
  2415. }
  2416. public function isNotFound()
  2417. {
  2418. return 404 === $this->statusCode;
  2419. }
  2420. public function isRedirect($location = null)
  2421. {
  2422. return in_array($this->statusCode, array(201, 301, 302, 303, 307)) && (null === $location ?: $location == $this->headers->get('Location'));
  2423. }
  2424. public function isEmpty()
  2425. {
  2426. return in_array($this->statusCode, array(201, 204, 304));
  2427. }
  2428. }
  2429. }
  2430. namespace Symfony\Component\HttpFoundation
  2431. {
  2432. class ResponseHeaderBag extends HeaderBag
  2433. {
  2434. const COOKIES_FLAT = 'flat';
  2435. const COOKIES_ARRAY = 'array';
  2436. protected $computedCacheControl = array();
  2437. protected $cookies = array();
  2438. public function __construct(array $headers = array())
  2439. {
  2440. parent::__construct($headers);
  2441. if (!isset($this->headers['cache-control'])) {
  2442. $this->set('cache-control', '');
  2443. }
  2444. }
  2445. public function __toString()
  2446. {
  2447. $cookies = '';
  2448. foreach ($this->getCookies() as $cookie) {
  2449. $cookies .= 'Set-Cookie: '.$cookie."\r\n";
  2450. }
  2451. return parent::__toString().$cookies;
  2452. }
  2453. public function replace(array $headers = array())
  2454. {
  2455. parent::replace($headers);
  2456. if (!isset($this->headers['cache-control'])) {
  2457. $this->set('cache-control', '');
  2458. }
  2459. }
  2460. public function set($key, $values, $replace = true)
  2461. {
  2462. parent::set($key, $values, $replace);
  2463. if (in_array(strtr(strtolower($key), '_', '-'), array('cache-control', 'etag', 'last-modified', 'expires'))) {
  2464. $computed = $this->computeCacheControlValue();
  2465. $this->headers['cache-control'] = array($computed);
  2466. $this->computedCacheControl = $this->parseCacheControl($computed);
  2467. }
  2468. }
  2469. public function remove($key)
  2470. {
  2471. parent::remove($key);
  2472. if ('cache-control' === strtr(strtolower($key), '_', '-')) {
  2473. $this->computedCacheControl = array();
  2474. }
  2475. }
  2476. public function hasCacheControlDirective($key)
  2477. {
  2478. return array_key_exists($key, $this->computedCacheControl);
  2479. }
  2480. public function getCacheControlDirective($key)
  2481. {
  2482. return array_key_exists($key, $this->computedCacheControl) ? $this->computedCacheControl[$key] : null;
  2483. }
  2484. public function setCookie(Cookie $cookie)
  2485. {
  2486. $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;
  2487. }
  2488. public function removeCookie($name, $path = null, $domain = null)
  2489. {
  2490. unset($this->cookies[$domain][$path][$name]);
  2491. if (empty($this->cookies[$domain][$path])) {
  2492. unset($this->cookies[$domain][$path]);
  2493. if (empty($this->cookies[$domain])) {
  2494. unset($this->cookies[$domain]);
  2495. }
  2496. }
  2497. }
  2498. public function getCookies($format = self::COOKIES_FLAT)
  2499. {
  2500. if (!in_array($format, array(self::COOKIES_FLAT, self::COOKIES_ARRAY))) {
  2501. throw new \InvalidArgumentException(sprintf('Format "%s" invalid (%s).', $format, implode(', ', array(self::COOKIES_FLAT, self::COOKIES_ARRAY))));
  2502. }
  2503. if (self::COOKIES_ARRAY === $format) {
  2504. return $this->cookies;
  2505. }
  2506. $flattenedCookies = array();
  2507. foreach ($this->cookies as $path) {
  2508. foreach ($path as $cookies) {
  2509. foreach ($cookies as $cookie) {
  2510. $flattenedCookies[] = $cookie;
  2511. }
  2512. }
  2513. }
  2514. return $flattenedCookies;
  2515. }
  2516. public function clearCookie($name, $path = null, $domain = null)
  2517. {
  2518. $this->setCookie(new Cookie($name, null, 1, $path, $domain));
  2519. }
  2520. protected function computeCacheControlValue()
  2521. {
  2522. if (!$this->cacheControl && !$this->has('ETag') && !$this->has('Last-Modified') && !$this->has('Expires')) {
  2523. return 'no-cache';
  2524. }
  2525. if (!$this->cacheControl) {
  2526. return 'private, must-revalidate';
  2527. }
  2528. $header = $this->getCacheControlHeader();
  2529. if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
  2530. return $header;
  2531. }
  2532. if (!isset($this->cacheControl['s-maxage'])) {
  2533. return $header.', private';
  2534. }
  2535. return $header;
  2536. }
  2537. }
  2538. }
  2539. namespace Symfony\Component\Config
  2540. {
  2541. class FileLocator implements FileLocatorInterface
  2542. {
  2543. protected $paths;
  2544. public function __construct($paths = array())
  2545. {
  2546. $this->paths = (array) $paths;
  2547. }
  2548. public function locate($name, $currentPath = null, $first = true)
  2549. {
  2550. if ($this->isAbsolutePath($name)) {
  2551. if (!file_exists($name)) {
  2552. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist.', $name));
  2553. }
  2554. return $name;
  2555. }
  2556. $filepaths = array();
  2557. if (null !== $currentPath && file_exists($file = $currentPath.DIRECTORY_SEPARATOR.$name)) {
  2558. if (true === $first) {
  2559. return $file;
  2560. }
  2561. $filepaths[] = $file;
  2562. }
  2563. foreach ($this->paths as $path) {
  2564. if (file_exists($file = $path.DIRECTORY_SEPARATOR.$name)) {
  2565. if (true === $first) {
  2566. return $file;
  2567. }
  2568. $filepaths[] = $file;
  2569. }
  2570. }
  2571. if (!$filepaths) {
  2572. throw new \InvalidArgumentException(sprintf('The file "%s" does not exist (in: %s%s).', $name, null !== $currentPath ? $currentPath.', ' : '', implode(', ', $this->paths)));
  2573. }
  2574. return array_values(array_unique($filepaths));
  2575. }
  2576. private function isAbsolutePath($file)
  2577. {
  2578. if ($file[0] == '/' || $file[0] == '\\'
  2579. || (strlen($file) > 3 && ctype_alpha($file[0])
  2580. && $file[1] == ':'
  2581. && ($file[2] == '\\' || $file[2] == '/')
  2582. )
  2583. ) {
  2584. return true;
  2585. }
  2586. return false;
  2587. }
  2588. }
  2589. }
  2590. namespace Symfony\Component\EventDispatcher
  2591. {
  2592. interface EventDispatcherInterface
  2593. {
  2594. function dispatch($eventName, Event $event = null);
  2595. function addListener($eventName, $listener, $priority = 0);
  2596. function addSubscriber(EventSubscriberInterface $subscriber);
  2597. function removeListener($eventName, $listener);
  2598. function removeSubscriber(EventSubscriberInterface $subscriber);
  2599. function getListeners($eventName = null);
  2600. function hasListeners($eventName = null);
  2601. }
  2602. }
  2603. namespace Symfony\Component\EventDispatcher
  2604. {
  2605. class EventDispatcher implements EventDispatcherInterface
  2606. {
  2607. private $listeners = array();
  2608. private $sorted = array();
  2609. public function dispatch($eventName, Event $event = null)
  2610. {
  2611. if (!isset($this->listeners[$eventName])) {
  2612. return;
  2613. }
  2614. if (null === $event) {
  2615. $event = new Event();
  2616. }
  2617. $this->doDispatch($this->getListeners($eventName), $eventName, $event);
  2618. }
  2619. public function getListeners($eventName = null)
  2620. {
  2621. if (null !== $eventName) {
  2622. if (!isset($this->sorted[$eventName])) {
  2623. $this->sortListeners($eventName);
  2624. }
  2625. return $this->sorted[$eventName];
  2626. }
  2627. foreach (array_keys($this->listeners) as $eventName) {
  2628. if (!isset($this->sorted[$eventName])) {
  2629. $this->sortListeners($eventName);
  2630. }
  2631. }
  2632. return $this->sorted;
  2633. }
  2634. public function hasListeners($eventName = null)
  2635. {
  2636. return (Boolean) count($this->getListeners($eventName));
  2637. }
  2638. public function addListener($eventName, $listener, $priority = 0)
  2639. {
  2640. $this->listeners[$eventName][$priority][] = $listener;
  2641. unset($this->sorted[$eventName]);
  2642. }
  2643. public function removeListener($eventName, $listener)
  2644. {
  2645. if (!isset($this->listeners[$eventName])) {
  2646. return;
  2647. }
  2648. foreach ($this->listeners[$eventName] as $priority => $listeners) {
  2649. if (false !== ($key = array_search($listener, $listeners))) {
  2650. unset($this->listeners[$eventName][$priority][$key], $this->sorted[$eventName]);
  2651. }
  2652. }
  2653. }
  2654. public function addSubscriber(EventSubscriberInterface $subscriber)
  2655. {
  2656. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  2657. if (is_string($params)) {
  2658. $this->addListener($eventName, array($subscriber, $params));
  2659. } else {
  2660. $this->addListener($eventName, array($subscriber, $params[0]), $params[1]);
  2661. }
  2662. }
  2663. }
  2664. public function removeSubscriber(EventSubscriberInterface $subscriber)
  2665. {
  2666. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  2667. $this->removeListener($eventName, array($subscriber, is_string($params) ? $params : $params[0]));
  2668. }
  2669. }
  2670. protected function doDispatch($listeners, $eventName, Event $event)
  2671. {
  2672. foreach ($listeners as $listener) {
  2673. call_user_func($listener, $event);
  2674. if ($event->isPropagationStopped()) {
  2675. break;
  2676. }
  2677. }
  2678. }
  2679. private function sortListeners($eventName)
  2680. {
  2681. $this->sorted[$eventName] = array();
  2682. if (isset($this->listeners[$eventName])) {
  2683. krsort($this->listeners[$eventName]);
  2684. $this->sorted[$eventName] = call_user_func_array('array_merge', $this->listeners[$eventName]);
  2685. }
  2686. }
  2687. }
  2688. }
  2689. namespace Symfony\Component\EventDispatcher
  2690. {
  2691. class Event
  2692. {
  2693. private $propagationStopped = false;
  2694. public function isPropagationStopped()
  2695. {
  2696. return $this->propagationStopped;
  2697. }
  2698. public function stopPropagation()
  2699. {
  2700. $this->propagationStopped = true;
  2701. }
  2702. }
  2703. }
  2704. namespace Symfony\Component\EventDispatcher
  2705. {
  2706. interface EventSubscriberInterface
  2707. {
  2708. static function getSubscribedEvents();
  2709. }
  2710. }
  2711. namespace Symfony\Component\HttpKernel
  2712. {
  2713. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  2714. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  2715. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  2716. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  2717. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  2718. use Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent;
  2719. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  2720. use Symfony\Component\HttpFoundation\Request;
  2721. use Symfony\Component\HttpFoundation\Response;
  2722. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  2723. class HttpKernel implements HttpKernelInterface
  2724. {
  2725. private $dispatcher;
  2726. private $resolver;
  2727. public function __construct(EventDispatcherInterface $dispatcher, ControllerResolverInterface $resolver)
  2728. {
  2729. $this->dispatcher = $dispatcher;
  2730. $this->resolver = $resolver;
  2731. }
  2732. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  2733. {
  2734. try {
  2735. return $this->handleRaw($request, $type);
  2736. } catch (\Exception $e) {
  2737. if (false === $catch) {
  2738. throw $e;
  2739. }
  2740. return $this->handleException($e, $request, $type);
  2741. }
  2742. }
  2743. private function handleRaw(Request $request, $type = self::MASTER_REQUEST)
  2744. {
  2745. $event = new GetResponseEvent($this, $request, $type);
  2746. $this->dispatcher->dispatch(KernelEvents::REQUEST, $event);
  2747. if ($event->hasResponse()) {
  2748. return $this->filterResponse($event->getResponse(), $request, $type);
  2749. }
  2750. if (false === $controller = $this->resolver->getController($request)) {
  2751. throw new NotFoundHttpException(sprintf('Unable to find the controller for path "%s". Maybe you forgot to add the matching route in your routing configuration?', $request->getPathInfo()));
  2752. }
  2753. $event = new FilterControllerEvent($this, $controller, $request, $type);
  2754. $this->dispatcher->dispatch(KernelEvents::CONTROLLER, $event);
  2755. $controller = $event->getController();
  2756. $arguments = $this->resolver->getArguments($request, $controller);
  2757. $response = call_user_func_array($controller, $arguments);
  2758. if (!$response instanceof Response) {
  2759. $event = new GetResponseForControllerResultEvent($this, $request, $type, $response);
  2760. $this->dispatcher->dispatch(KernelEvents::VIEW, $event);
  2761. if ($event->hasResponse()) {
  2762. $response = $event->getResponse();
  2763. }
  2764. if (!$response instanceof Response) {
  2765. $msg = sprintf('The controller must return a response (%s given).', $this->varToString($response));
  2766. if (null === $response) {
  2767. $msg .= ' Did you forget to add a return statement somewhere in your controller?';
  2768. }
  2769. throw new \LogicException($msg);
  2770. }
  2771. }
  2772. return $this->filterResponse($response, $request, $type);
  2773. }
  2774. private function filterResponse(Response $response, Request $request, $type)
  2775. {
  2776. $event = new FilterResponseEvent($this, $request, $type, $response);
  2777. $this->dispatcher->dispatch(KernelEvents::RESPONSE, $event);
  2778. return $event->getResponse();
  2779. }
  2780. private function handleException(\Exception $e, $request, $type)
  2781. {
  2782. $event = new GetResponseForExceptionEvent($this, $request, $type, $e);
  2783. $this->dispatcher->dispatch(KernelEvents::EXCEPTION, $event);
  2784. if (!$event->hasResponse()) {
  2785. throw $e;
  2786. }
  2787. try {
  2788. return $this->filterResponse($event->getResponse(), $request, $type);
  2789. } catch (\Exception $e) {
  2790. return $event->getResponse();
  2791. }
  2792. }
  2793. private function varToString($var)
  2794. {
  2795. if (is_object($var)) {
  2796. return sprintf('Object(%s)', get_class($var));
  2797. }
  2798. if (is_array($var)) {
  2799. $a = array();
  2800. foreach ($var as $k => $v) {
  2801. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  2802. }
  2803. return sprintf("Array(%s)", implode(', ', $a));
  2804. }
  2805. if (is_resource($var)) {
  2806. return sprintf('Resource(%s)', get_resource_type($var));
  2807. }
  2808. if (null === $var) {
  2809. return 'null';
  2810. }
  2811. if (false === $var) {
  2812. return 'false';
  2813. }
  2814. if (true === $var) {
  2815. return 'true';
  2816. }
  2817. return (string) $var;
  2818. }
  2819. }
  2820. }
  2821. namespace Symfony\Component\HttpKernel\EventListener
  2822. {
  2823. use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
  2824. use Symfony\Component\HttpFoundation\Response;
  2825. use Symfony\Component\HttpKernel\HttpKernelInterface;
  2826. class ResponseListener
  2827. {
  2828. private $charset;
  2829. public function __construct($charset)
  2830. {
  2831. $this->charset = $charset;
  2832. }
  2833. public function onKernelResponse(FilterResponseEvent $event)
  2834. {
  2835. $request = $event->getRequest();
  2836. $response = $event->getResponse();
  2837. if ('HEAD' === $request->getMethod()) {
  2838. $length = $response->headers->get('Content-Length');
  2839. $response->setContent('');
  2840. if ($length) {
  2841. $response->headers->set('Content-Length', $length);
  2842. }
  2843. }
  2844. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  2845. return;
  2846. }
  2847. if (null === $response->getCharset()) {
  2848. $response->setCharset($this->charset);
  2849. }
  2850. if ($response->headers->has('Content-Type')) {
  2851. return;
  2852. }
  2853. $format = $request->getRequestFormat();
  2854. if ((null !== $format) && $mimeType = $request->getMimeType($format)) {
  2855. $response->headers->set('Content-Type', $mimeType);
  2856. }
  2857. }
  2858. }
  2859. }
  2860. namespace Symfony\Component\HttpKernel\Controller
  2861. {
  2862. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  2863. use Symfony\Component\HttpFoundation\Request;
  2864. class ControllerResolver implements ControllerResolverInterface
  2865. {
  2866. private $logger;
  2867. public function __construct(LoggerInterface $logger = null)
  2868. {
  2869. $this->logger = $logger;
  2870. }
  2871. public function getController(Request $request)
  2872. {
  2873. if (!$controller = $request->attributes->get('_controller')) {
  2874. if (null !== $this->logger) {
  2875. $this->logger->warn('Unable to look for the controller as the "_controller" parameter is missing');
  2876. }
  2877. return false;
  2878. }
  2879. if (is_array($controller) || (is_object($controller) && method_exists($controller, '__invoke'))) {
  2880. return $controller;
  2881. }
  2882. if (false === strpos($controller, ':') && method_exists($controller, '__invoke')) {
  2883. return new $controller;
  2884. }
  2885. list($controller, $method) = $this->createController($controller);
  2886. if (!method_exists($controller, $method)) {
  2887. throw new \InvalidArgumentException(sprintf('Method "%s::%s" does not exist.', get_class($controller), $method));
  2888. }
  2889. return array($controller, $method);
  2890. }
  2891. public function getArguments(Request $request, $controller)
  2892. {
  2893. if (is_array($controller)) {
  2894. $r = new \ReflectionMethod($controller[0], $controller[1]);
  2895. } elseif (is_object($controller)) {
  2896. $r = new \ReflectionObject($controller);
  2897. $r = $r->getMethod('__invoke');
  2898. } else {
  2899. $r = new \ReflectionFunction($controller);
  2900. }
  2901. return $this->doGetArguments($request, $controller, $r->getParameters());
  2902. }
  2903. protected function doGetArguments(Request $request, $controller, array $parameters)
  2904. {
  2905. $attributes = $request->attributes->all();
  2906. $arguments = array();
  2907. foreach ($parameters as $param) {
  2908. if (array_key_exists($param->getName(), $attributes)) {
  2909. $arguments[] = $attributes[$param->getName()];
  2910. } elseif ($param->getClass() && $param->getClass()->isInstance($request)) {
  2911. $arguments[] = $request;
  2912. } elseif ($param->isDefaultValueAvailable()) {
  2913. $arguments[] = $param->getDefaultValue();
  2914. } else {
  2915. if (is_array($controller)) {
  2916. $repr = sprintf('%s::%s()', get_class($controller[0]), $controller[1]);
  2917. } elseif (is_object($controller)) {
  2918. $repr = get_class($controller);
  2919. } else {
  2920. $repr = $controller;
  2921. }
  2922. throw new \RuntimeException(sprintf('Controller "%s" requires that you provide a value for the "$%s" argument (because there is no default value or because there is a non optional argument after this one).', $repr, $param->getName()));
  2923. }
  2924. }
  2925. return $arguments;
  2926. }
  2927. protected function createController($controller)
  2928. {
  2929. if (false === strpos($controller, '::')) {
  2930. throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
  2931. }
  2932. list($class, $method) = explode('::', $controller);
  2933. if (!class_exists($class)) {
  2934. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  2935. }
  2936. return array(new $class(), $method);
  2937. }
  2938. }
  2939. }
  2940. namespace Symfony\Component\HttpKernel\Controller
  2941. {
  2942. use Symfony\Component\HttpFoundation\Request;
  2943. interface ControllerResolverInterface
  2944. {
  2945. function getController(Request $request);
  2946. function getArguments(Request $request, $controller);
  2947. }
  2948. }
  2949. namespace Symfony\Component\HttpKernel\Event
  2950. {
  2951. use Symfony\Component\HttpKernel\HttpKernelInterface;
  2952. use Symfony\Component\HttpFoundation\Request;
  2953. use Symfony\Component\EventDispatcher\Event;
  2954. class KernelEvent extends Event
  2955. {
  2956. private $kernel;
  2957. private $request;
  2958. private $requestType;
  2959. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType)
  2960. {
  2961. $this->kernel = $kernel;
  2962. $this->request = $request;
  2963. $this->requestType = $requestType;
  2964. }
  2965. public function getKernel()
  2966. {
  2967. return $this->kernel;
  2968. }
  2969. public function getRequest()
  2970. {
  2971. return $this->request;
  2972. }
  2973. public function getRequestType()
  2974. {
  2975. return $this->requestType;
  2976. }
  2977. }
  2978. }
  2979. namespace Symfony\Component\HttpKernel\Event
  2980. {
  2981. use Symfony\Component\HttpKernel\HttpKernelInterface;
  2982. use Symfony\Component\HttpFoundation\Request;
  2983. class FilterControllerEvent extends KernelEvent
  2984. {
  2985. private $controller;
  2986. public function __construct(HttpKernelInterface $kernel, $controller, Request $request, $requestType)
  2987. {
  2988. parent::__construct($kernel, $request, $requestType);
  2989. $this->setController($controller);
  2990. }
  2991. public function getController()
  2992. {
  2993. return $this->controller;
  2994. }
  2995. public function setController($controller)
  2996. {
  2997. if (!is_callable($controller)) {
  2998. throw new \LogicException(sprintf('The controller must be a callable (%s given).', $this->varToString($controller)));
  2999. }
  3000. $this->controller = $controller;
  3001. }
  3002. private function varToString($var)
  3003. {
  3004. if (is_object($var)) {
  3005. return sprintf('Object(%s)', get_class($var));
  3006. }
  3007. if (is_array($var)) {
  3008. $a = array();
  3009. foreach ($var as $k => $v) {
  3010. $a[] = sprintf('%s => %s', $k, $this->varToString($v));
  3011. }
  3012. return sprintf("Array(%s)", implode(', ', $a));
  3013. }
  3014. if (is_resource($var)) {
  3015. return sprintf('Resource(%s)', get_resource_type($var));
  3016. }
  3017. if (null === $var) {
  3018. return 'null';
  3019. }
  3020. if (false === $var) {
  3021. return 'false';
  3022. }
  3023. if (true === $var) {
  3024. return 'true';
  3025. }
  3026. return (string) $var;
  3027. }
  3028. }
  3029. }
  3030. namespace Symfony\Component\HttpKernel\Event
  3031. {
  3032. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3033. use Symfony\Component\HttpFoundation\Request;
  3034. use Symfony\Component\HttpFoundation\Response;
  3035. class FilterResponseEvent extends KernelEvent
  3036. {
  3037. private $response;
  3038. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, Response $response)
  3039. {
  3040. parent::__construct($kernel, $request, $requestType);
  3041. $this->setResponse($response);
  3042. }
  3043. public function getResponse()
  3044. {
  3045. return $this->response;
  3046. }
  3047. public function setResponse(Response $response)
  3048. {
  3049. $this->response = $response;
  3050. }
  3051. }
  3052. }
  3053. namespace Symfony\Component\HttpKernel\Event
  3054. {
  3055. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3056. use Symfony\Component\HttpFoundation\Request;
  3057. use Symfony\Component\HttpFoundation\Response;
  3058. class GetResponseEvent extends KernelEvent
  3059. {
  3060. private $response;
  3061. public function getResponse()
  3062. {
  3063. return $this->response;
  3064. }
  3065. public function setResponse(Response $response)
  3066. {
  3067. $this->response = $response;
  3068. $this->stopPropagation();
  3069. }
  3070. public function hasResponse()
  3071. {
  3072. return null !== $this->response;
  3073. }
  3074. }
  3075. }
  3076. namespace Symfony\Component\HttpKernel\Event
  3077. {
  3078. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3079. use Symfony\Component\HttpFoundation\Request;
  3080. class GetResponseForControllerResultEvent extends GetResponseEvent
  3081. {
  3082. private $controllerResult;
  3083. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, $controllerResult)
  3084. {
  3085. parent::__construct($kernel, $request, $requestType);
  3086. $this->controllerResult = $controllerResult;
  3087. }
  3088. public function getControllerResult()
  3089. {
  3090. return $this->controllerResult;
  3091. }
  3092. }
  3093. }
  3094. namespace Symfony\Component\HttpKernel\Event
  3095. {
  3096. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3097. use Symfony\Component\HttpFoundation\Request;
  3098. class GetResponseForExceptionEvent extends GetResponseEvent
  3099. {
  3100. private $exception;
  3101. public function __construct(HttpKernelInterface $kernel, Request $request, $requestType, \Exception $e)
  3102. {
  3103. parent::__construct($kernel, $request, $requestType);
  3104. $this->setException($e);
  3105. }
  3106. public function getException()
  3107. {
  3108. return $this->exception;
  3109. }
  3110. public function setException(\Exception $exception)
  3111. {
  3112. $this->exception = $exception;
  3113. }
  3114. }
  3115. }
  3116. namespace Symfony\Component\HttpKernel
  3117. {
  3118. final class KernelEvents
  3119. {
  3120. const REQUEST = 'kernel.request';
  3121. const EXCEPTION = 'kernel.exception';
  3122. const VIEW = 'kernel.view';
  3123. const CONTROLLER = 'kernel.controller';
  3124. const RESPONSE = 'kernel.response';
  3125. }
  3126. }
  3127. namespace Symfony\Component\HttpKernel\Config
  3128. {
  3129. use Symfony\Component\Config\FileLocator as BaseFileLocator;
  3130. use Symfony\Component\HttpKernel\KernelInterface;
  3131. class FileLocator extends BaseFileLocator
  3132. {
  3133. private $kernel;
  3134. private $path;
  3135. public function __construct(KernelInterface $kernel, $path = null, array $paths = array())
  3136. {
  3137. $this->kernel = $kernel;
  3138. $this->path = $path;
  3139. $paths[] = $path;
  3140. parent::__construct($paths);
  3141. }
  3142. public function locate($file, $currentPath = null, $first = true)
  3143. {
  3144. if ('@' === $file[0]) {
  3145. return $this->kernel->locateResource($file, $this->path, $first);
  3146. }
  3147. return parent::locate($file, $currentPath, $first);
  3148. }
  3149. }
  3150. }
  3151. namespace Symfony\Bundle\FrameworkBundle\EventListener
  3152. {
  3153. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  3154. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3155. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  3156. use Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException;
  3157. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  3158. use Symfony\Component\HttpFoundation\Request;
  3159. use Symfony\Component\Routing\Exception\MethodNotAllowedException;
  3160. use Symfony\Component\Routing\Exception\ResourceNotFoundException;
  3161. use Symfony\Component\Routing\RouterInterface;
  3162. use Symfony\Component\Routing\RequestContext;
  3163. class RouterListener
  3164. {
  3165. private $router;
  3166. private $logger;
  3167. private $httpPort;
  3168. private $httpsPort;
  3169. public function __construct(RouterInterface $router, $httpPort = 80, $httpsPort = 443, LoggerInterface $logger = null)
  3170. {
  3171. $this->router = $router;
  3172. $this->httpPort = $httpPort;
  3173. $this->httpsPort = $httpsPort;
  3174. $this->logger = $logger;
  3175. }
  3176. public function onEarlyKernelRequest(GetResponseEvent $event)
  3177. {
  3178. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  3179. return;
  3180. }
  3181. $request = $event->getRequest();
  3182. $context = $this->router->getContext();
  3183. $context->setBaseUrl($request->getBaseUrl());
  3184. $context->setMethod($request->getMethod());
  3185. $context->setHost($request->getHost());
  3186. $context->setScheme($request->getScheme());
  3187. $context->setHttpPort($request->isSecure() ? $this->httpPort : $request->getPort());
  3188. $context->setHttpsPort($request->isSecure() ? $request->getPort() : $this->httpsPort);
  3189. }
  3190. public function onKernelRequest(GetResponseEvent $event)
  3191. {
  3192. $request = $event->getRequest();
  3193. if ($request->attributes->has('_controller')) {
  3194. return;
  3195. }
  3196. try {
  3197. $parameters = $this->router->match($request->getPathInfo());
  3198. if (null !== $this->logger) {
  3199. $this->logger->info(sprintf('Matched route "%s" (parameters: %s)', $parameters['_route'], $this->parametersToString($parameters)));
  3200. }
  3201. $request->attributes->add($parameters);
  3202. } catch (ResourceNotFoundException $e) {
  3203. $message = sprintf('No route found for "%s %s"', $request->getMethod(), $request->getPathInfo());
  3204. throw new NotFoundHttpException($message, $e);
  3205. } catch (MethodNotAllowedException $e) {
  3206. $message = sprintf('No route found for "%s %s": Method Not Allowed (Allow: %s)', $request->getMethod(), $request->getPathInfo(), strtoupper(implode(', ', $e->getAllowedMethods())));
  3207. throw new MethodNotAllowedHttpException($e->getAllowedMethods(), $message, $e);
  3208. }
  3209. if (HttpKernelInterface::MASTER_REQUEST === $event->getRequestType()) {
  3210. $context = $this->router->getContext();
  3211. $session = $request->getSession();
  3212. if ($locale = $request->attributes->get('_locale')) {
  3213. if ($session) {
  3214. $session->setLocale($locale);
  3215. }
  3216. $context->setParameter('_locale', $locale);
  3217. } elseif ($session) {
  3218. $context->setParameter('_locale', $session->getLocale());
  3219. }
  3220. }
  3221. }
  3222. private function parametersToString(array $parameters)
  3223. {
  3224. $pieces = array();
  3225. foreach ($parameters as $key => $val) {
  3226. $pieces[] = sprintf('"%s": "%s"', $key, (is_string($val) ? $val : json_encode($val)));
  3227. }
  3228. return implode(', ', $pieces);
  3229. }
  3230. }
  3231. }
  3232. namespace Symfony\Bundle\FrameworkBundle\Controller
  3233. {
  3234. use Symfony\Component\HttpKernel\KernelInterface;
  3235. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  3236. class ControllerNameParser
  3237. {
  3238. protected $kernel;
  3239. public function __construct(KernelInterface $kernel)
  3240. {
  3241. $this->kernel = $kernel;
  3242. }
  3243. public function parse($controller)
  3244. {
  3245. if (3 != count($parts = explode(':', $controller))) {
  3246. throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid a:b:c controller string.', $controller));
  3247. }
  3248. list($bundle, $controller, $action) = $parts;
  3249. $class = null;
  3250. $logs = array();
  3251. foreach ($this->kernel->getBundle($bundle, false) as $b) {
  3252. $try = $b->getNamespace().'\\Controller\\'.$controller.'Controller';
  3253. if (!class_exists($try)) {
  3254. $logs[] = sprintf('Unable to find controller "%s:%s" - class "%s" does not exist.', $bundle, $controller, $try);
  3255. } else {
  3256. $class = $try;
  3257. break;
  3258. }
  3259. }
  3260. if (null === $class) {
  3261. $this->handleControllerNotFoundException($bundle, $controller, $logs);
  3262. }
  3263. return $class.'::'.$action.'Action';
  3264. }
  3265. private function handleControllerNotFoundException($bundle, $controller, array $logs)
  3266. {
  3267. if (1 == count($logs)) {
  3268. throw new \InvalidArgumentException($logs[0]);
  3269. }
  3270. $names = array();
  3271. foreach ($this->kernel->getBundle($bundle, false) as $b) {
  3272. $names[] = $b->getName();
  3273. }
  3274. $msg = sprintf('Unable to find controller "%s:%s" in bundles %s.', $bundle, $controller, implode(', ', $names));
  3275. throw new \InvalidArgumentException($msg);
  3276. }
  3277. }
  3278. }
  3279. namespace Symfony\Bundle\FrameworkBundle\Controller
  3280. {
  3281. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  3282. use Symfony\Component\HttpKernel\Controller\ControllerResolver as BaseControllerResolver;
  3283. use Symfony\Component\DependencyInjection\ContainerInterface;
  3284. use Symfony\Bundle\FrameworkBundle\Controller\ControllerNameParser;
  3285. use Symfony\Component\DependencyInjection\ContainerAwareInterface;
  3286. class ControllerResolver extends BaseControllerResolver
  3287. {
  3288. protected $container;
  3289. protected $parser;
  3290. public function __construct(ContainerInterface $container, ControllerNameParser $parser, LoggerInterface $logger = null)
  3291. {
  3292. $this->container = $container;
  3293. $this->parser = $parser;
  3294. parent::__construct($logger);
  3295. }
  3296. protected function createController($controller)
  3297. {
  3298. if (false === strpos($controller, '::')) {
  3299. $count = substr_count($controller, ':');
  3300. if (2 == $count) {
  3301. $controller = $this->parser->parse($controller);
  3302. } elseif (1 == $count) {
  3303. list($service, $method) = explode(':', $controller);
  3304. return array($this->container->get($service), $method);
  3305. } else {
  3306. throw new \LogicException(sprintf('Unable to parse the controller name "%s".', $controller));
  3307. }
  3308. }
  3309. list($class, $method) = explode('::', $controller);
  3310. if (!class_exists($class)) {
  3311. throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
  3312. }
  3313. $controller = new $class();
  3314. if ($controller instanceof ContainerAwareInterface) {
  3315. $controller->setContainer($this->container);
  3316. }
  3317. return array($controller, $method);
  3318. }
  3319. }
  3320. }
  3321. namespace Symfony\Bundle\FrameworkBundle
  3322. {
  3323. use Symfony\Component\DependencyInjection\ContainerInterface;
  3324. use Symfony\Component\EventDispatcher\EventDispatcher;
  3325. use Symfony\Component\EventDispatcher\Event;
  3326. class ContainerAwareEventDispatcher extends EventDispatcher
  3327. {
  3328. private $container;
  3329. private $listenerIds = array();
  3330. private $listeners = array();
  3331. public function __construct(ContainerInterface $container)
  3332. {
  3333. $this->container = $container;
  3334. }
  3335. public function addListenerService($eventName, $callback, $priority = 0)
  3336. {
  3337. if (!is_array($callback) || 2 !== count($callback)) {
  3338. throw new \InvalidArgumentException('Expected an array("service", "method") argument');
  3339. }
  3340. $this->listenerIds[$eventName][] = array($callback[0], $callback[1], $priority);
  3341. }
  3342. public function dispatch($eventName, Event $event = null)
  3343. {
  3344. if (isset($this->listenerIds[$eventName])) {
  3345. foreach ($this->listenerIds[$eventName] as $args) {
  3346. list($serviceId, $method, $priority) = $args;
  3347. $listener = $this->container->get($serviceId);
  3348. $key = $serviceId.'.'.$method;
  3349. if (!isset($this->listeners[$eventName][$key])) {
  3350. $this->addListener($eventName, array($listener, $method), $priority);
  3351. } elseif ($listener !== $this->listeners[$eventName][$key]) {
  3352. $this->removeListener($eventName, array($this->listeners[$eventName][$key], $method));
  3353. $this->addListener($eventName, array($listener, $method), $priority);
  3354. }
  3355. $this->listeners[$eventName][$key] = $listener;
  3356. }
  3357. }
  3358. parent::dispatch($eventName, $event);
  3359. }
  3360. }
  3361. }
  3362. namespace Symfony\Bundle\FrameworkBundle
  3363. {
  3364. use Symfony\Component\HttpFoundation\Request;
  3365. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3366. use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
  3367. use Symfony\Component\DependencyInjection\ContainerInterface;
  3368. use Symfony\Component\HttpKernel\HttpKernel as BaseHttpKernel;
  3369. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  3370. class HttpKernel extends BaseHttpKernel
  3371. {
  3372. private $container;
  3373. private $esiSupport;
  3374. public function __construct(EventDispatcherInterface $dispatcher, ContainerInterface $container, ControllerResolverInterface $controllerResolver)
  3375. {
  3376. parent::__construct($dispatcher, $controllerResolver);
  3377. $this->container = $container;
  3378. }
  3379. public function handle(Request $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
  3380. {
  3381. $this->container->enterScope('request');
  3382. $this->container->set('request', $request, 'request');
  3383. try {
  3384. $response = parent::handle($request, $type, $catch);
  3385. } catch (\Exception $e) {
  3386. $this->container->leaveScope('request');
  3387. throw $e;
  3388. }
  3389. $this->container->leaveScope('request');
  3390. return $response;
  3391. }
  3392. public function forward($controller, array $attributes = array(), array $query = array())
  3393. {
  3394. $attributes['_controller'] = $controller;
  3395. $subRequest = $this->container->get('request')->duplicate($query, null, $attributes);
  3396. return $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  3397. }
  3398. public function render($controller, array $options = array())
  3399. {
  3400. $options = array_merge(array(
  3401. 'attributes' => array(),
  3402. 'query' => array(),
  3403. 'ignore_errors' => !$this->container->getParameter('kernel.debug'),
  3404. 'alt' => array(),
  3405. 'standalone' => false,
  3406. 'comment' => '',
  3407. ), $options);
  3408. if (!is_array($options['alt'])) {
  3409. $options['alt'] = array($options['alt']);
  3410. }
  3411. if (null === $this->esiSupport) {
  3412. $this->esiSupport = $this->container->has('esi') && $this->container->get('esi')->hasSurrogateEsiCapability($this->container->get('request'));
  3413. }
  3414. if ($this->esiSupport && $options['standalone']) {
  3415. $uri = $this->generateInternalUri($controller, $options['attributes'], $options['query']);
  3416. $alt = '';
  3417. if ($options['alt']) {
  3418. $alt = $this->generateInternalUri($options['alt'][0], isset($options['alt'][1]) ? $options['alt'][1] : array(), isset($options['alt'][2]) ? $options['alt'][2] : array());
  3419. }
  3420. return $this->container->get('esi')->renderIncludeTag($uri, $alt, $options['ignore_errors'], $options['comment']);
  3421. }
  3422. $request = $this->container->get('request');
  3423. if (0 === strpos($controller, '/')) {
  3424. $subRequest = Request::create($controller, 'get', array(), $request->cookies->all(), array(), $request->server->all());
  3425. $subRequest->setSession($request->getSession());
  3426. } else {
  3427. $options['attributes']['_controller'] = $controller;
  3428. $options['attributes']['_format'] = $request->getRequestFormat();
  3429. $options['attributes']['_route'] = '_internal';
  3430. $subRequest = $request->duplicate($options['query'], null, $options['attributes']);
  3431. }
  3432. try {
  3433. $response = $this->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);
  3434. if (!$response->isSuccessful()) {
  3435. throw new \RuntimeException(sprintf('Error when rendering "%s" (Status code is %s).', $request->getUri(), $response->getStatusCode()));
  3436. }
  3437. return $response->getContent();
  3438. } catch (\Exception $e) {
  3439. if ($options['alt']) {
  3440. $alt = $options['alt'];
  3441. unset($options['alt']);
  3442. $options['attributes'] = isset($alt[1]) ? $alt[1] : array();
  3443. $options['query'] = isset($alt[2]) ? $alt[2] : array();
  3444. return $this->render($alt[0], $options);
  3445. }
  3446. if (!$options['ignore_errors']) {
  3447. throw $e;
  3448. }
  3449. }
  3450. }
  3451. public function generateInternalUri($controller, array $attributes = array(), array $query = array())
  3452. {
  3453. if (0 === strpos($controller, '/')) {
  3454. return $controller;
  3455. }
  3456. $path = http_build_query($attributes);
  3457. $uri = $this->container->get('router')->generate('_internal', array(
  3458. 'controller' => $controller,
  3459. 'path' => $path ?: 'none',
  3460. '_format' => $this->container->get('request')->getRequestFormat(),
  3461. ));
  3462. if ($queryString = http_build_query($query)) {
  3463. $uri .= '?'.$queryString;
  3464. }
  3465. return $uri;
  3466. }
  3467. }
  3468. }
  3469. namespace Symfony\Component\Security\Http
  3470. {
  3471. use Symfony\Component\HttpKernel\HttpKernelInterface;
  3472. use Symfony\Component\HttpKernel\Event\GetResponseEvent;
  3473. use Symfony\Component\HttpFoundation\Request;
  3474. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  3475. class Firewall
  3476. {
  3477. private $map;
  3478. private $dispatcher;
  3479. public function __construct(FirewallMapInterface $map, EventDispatcherInterface $dispatcher)
  3480. {
  3481. $this->map = $map;
  3482. $this->dispatcher = $dispatcher;
  3483. }
  3484. public function onKernelRequest(GetResponseEvent $event)
  3485. {
  3486. if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
  3487. return;
  3488. }
  3489. list($listeners, $exception) = $this->map->getListeners($event->getRequest());
  3490. if (null !== $exception) {
  3491. $exception->register($this->dispatcher);
  3492. }
  3493. foreach ($listeners as $listener) {
  3494. $response = $listener->handle($event);
  3495. if ($event->hasResponse()) {
  3496. break;
  3497. }
  3498. }
  3499. }
  3500. }
  3501. }
  3502. namespace Symfony\Component\Security\Http
  3503. {
  3504. use Symfony\Component\HttpFoundation\Request;
  3505. interface FirewallMapInterface
  3506. {
  3507. function getListeners(Request $request);
  3508. }
  3509. }
  3510. namespace Symfony\Component\Security\Core
  3511. {
  3512. use Symfony\Component\Security\Core\User\UserInterface;
  3513. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  3514. use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
  3515. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  3516. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3517. use Symfony\Component\Security\Acl\Voter\FieldVote;
  3518. class SecurityContext implements SecurityContextInterface
  3519. {
  3520. private $token;
  3521. private $accessDecisionManager;
  3522. private $authenticationManager;
  3523. private $alwaysAuthenticate;
  3524. public function __construct(AuthenticationManagerInterface $authenticationManager, AccessDecisionManagerInterface $accessDecisionManager, $alwaysAuthenticate = false)
  3525. {
  3526. $this->authenticationManager = $authenticationManager;
  3527. $this->accessDecisionManager = $accessDecisionManager;
  3528. $this->alwaysAuthenticate = $alwaysAuthenticate;
  3529. }
  3530. public final function isGranted($attributes, $object = null)
  3531. {
  3532. if (null === $this->token) {
  3533. throw new AuthenticationCredentialsNotFoundException('The security context contains no authentication token. One possible reason may be that there is no firewall configured for this URL.');
  3534. }
  3535. if ($this->alwaysAuthenticate || !$this->token->isAuthenticated()) {
  3536. $this->token = $this->authenticationManager->authenticate($this->token);
  3537. }
  3538. return $this->accessDecisionManager->decide($this->token, (array) $attributes, $object);
  3539. }
  3540. public function getToken()
  3541. {
  3542. return $this->token;
  3543. }
  3544. public function setToken(TokenInterface $token = null)
  3545. {
  3546. $this->token = $token;
  3547. }
  3548. }
  3549. }
  3550. namespace Symfony\Component\Security\Core
  3551. {
  3552. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3553. interface SecurityContextInterface
  3554. {
  3555. const ACCESS_DENIED_ERROR = '_security.403_error';
  3556. const AUTHENTICATION_ERROR = '_security.last_error';
  3557. const LAST_USERNAME = '_security.last_username';
  3558. function getToken();
  3559. function setToken(TokenInterface $token = null);
  3560. function isGranted($attributes, $object = null);
  3561. }
  3562. }
  3563. namespace Symfony\Component\Security\Core\User
  3564. {
  3565. interface UserProviderInterface
  3566. {
  3567. function loadUserByUsername($username);
  3568. function refreshUser(UserInterface $user);
  3569. function supportsClass($class);
  3570. }
  3571. }
  3572. namespace Symfony\Component\Security\Core\Authentication
  3573. {
  3574. use Symfony\Component\Security\Core\Exception\AccountStatusException;
  3575. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  3576. use Symfony\Component\Security\Core\Exception\ProviderNotFoundException;
  3577. use Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface;
  3578. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3579. class AuthenticationProviderManager implements AuthenticationManagerInterface
  3580. {
  3581. private $providers;
  3582. private $eraseCredentials;
  3583. public function __construct(array $providers, $eraseCredentials = true)
  3584. {
  3585. if (!$providers) {
  3586. throw new \InvalidArgumentException('You must at least add one authentication provider.');
  3587. }
  3588. $this->providers = $providers;
  3589. $this->eraseCredentials = (Boolean) $eraseCredentials;
  3590. }
  3591. public function authenticate(TokenInterface $token)
  3592. {
  3593. $lastException = null;
  3594. $result = null;
  3595. foreach ($this->providers as $provider) {
  3596. if (!$provider->supports($token)) {
  3597. continue;
  3598. }
  3599. try {
  3600. $result = $provider->authenticate($token);
  3601. if (null !== $result) {
  3602. break;
  3603. }
  3604. } catch (AccountStatusException $e) {
  3605. $e->setExtraInformation($token);
  3606. throw $e;
  3607. } catch (AuthenticationException $e) {
  3608. $lastException = $e;
  3609. }
  3610. }
  3611. if (null !== $result) {
  3612. if (true === $this->eraseCredentials) {
  3613. $result->eraseCredentials();
  3614. }
  3615. return $result;
  3616. }
  3617. if (null === $lastException) {
  3618. $lastException = new ProviderNotFoundException(sprintf('No Authentication Provider found for token of class "%s".', get_class($token)));
  3619. }
  3620. $lastException->setExtraInformation($token);
  3621. throw $lastException;
  3622. }
  3623. }
  3624. }
  3625. namespace Symfony\Component\Security\Core\Authentication
  3626. {
  3627. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3628. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  3629. interface AuthenticationManagerInterface
  3630. {
  3631. function authenticate(TokenInterface $token);
  3632. }
  3633. }
  3634. namespace Symfony\Component\Security\Core\Authorization
  3635. {
  3636. use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
  3637. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3638. class AccessDecisionManager implements AccessDecisionManagerInterface
  3639. {
  3640. private $voters;
  3641. private $strategy;
  3642. private $allowIfAllAbstainDecisions;
  3643. private $allowIfEqualGrantedDeniedDecisions;
  3644. public function __construct(array $voters, $strategy = 'affirmative', $allowIfAllAbstainDecisions = false, $allowIfEqualGrantedDeniedDecisions = true)
  3645. {
  3646. if (!$voters) {
  3647. throw new \InvalidArgumentException('You must at least add one voter.');
  3648. }
  3649. $this->voters = $voters;
  3650. $this->strategy = 'decide'.ucfirst($strategy);
  3651. $this->allowIfAllAbstainDecisions = (Boolean) $allowIfAllAbstainDecisions;
  3652. $this->allowIfEqualGrantedDeniedDecisions = (Boolean) $allowIfEqualGrantedDeniedDecisions;
  3653. }
  3654. public function decide(TokenInterface $token, array $attributes, $object = null)
  3655. {
  3656. return $this->{$this->strategy}($token, $attributes, $object);
  3657. }
  3658. public function supportsAttribute($attribute)
  3659. {
  3660. foreach ($this->voters as $voter) {
  3661. if ($voter->supportsAttribute($attribute)) {
  3662. return true;
  3663. }
  3664. }
  3665. return false;
  3666. }
  3667. public function supportsClass($class)
  3668. {
  3669. foreach ($this->voters as $voter) {
  3670. if ($voter->supportsClass($class)) {
  3671. return true;
  3672. }
  3673. }
  3674. return false;
  3675. }
  3676. private function decideAffirmative(TokenInterface $token, array $attributes, $object = null)
  3677. {
  3678. $deny = 0;
  3679. foreach ($this->voters as $voter) {
  3680. $result = $voter->vote($token, $object, $attributes);
  3681. switch ($result) {
  3682. case VoterInterface::ACCESS_GRANTED:
  3683. return true;
  3684. case VoterInterface::ACCESS_DENIED:
  3685. ++$deny;
  3686. break;
  3687. default:
  3688. break;
  3689. }
  3690. }
  3691. if ($deny > 0) {
  3692. return false;
  3693. }
  3694. return $this->allowIfAllAbstainDecisions;
  3695. }
  3696. private function decideConsensus(TokenInterface $token, array $attributes, $object = null)
  3697. {
  3698. $grant = 0;
  3699. $deny = 0;
  3700. $abstain = 0;
  3701. foreach ($this->voters as $voter) {
  3702. $result = $voter->vote($token, $object, $attributes);
  3703. switch ($result) {
  3704. case VoterInterface::ACCESS_GRANTED:
  3705. ++$grant;
  3706. break;
  3707. case VoterInterface::ACCESS_DENIED:
  3708. ++$deny;
  3709. break;
  3710. default:
  3711. ++$abstain;
  3712. break;
  3713. }
  3714. }
  3715. if ($grant > $deny) {
  3716. return true;
  3717. }
  3718. if ($deny > $grant) {
  3719. return false;
  3720. }
  3721. if ($grant == $deny && $grant != 0) {
  3722. return $this->allowIfEqualGrantedDeniedDecisions;
  3723. }
  3724. return $this->allowIfAllAbstainDecisions;
  3725. }
  3726. private function decideUnanimous(TokenInterface $token, array $attributes, $object = null)
  3727. {
  3728. $grant = 0;
  3729. foreach ($attributes as $attribute) {
  3730. foreach ($this->voters as $voter) {
  3731. $result = $voter->vote($token, $object, array($attribute));
  3732. switch ($result) {
  3733. case VoterInterface::ACCESS_GRANTED:
  3734. ++$grant;
  3735. break;
  3736. case VoterInterface::ACCESS_DENIED:
  3737. return false;
  3738. default:
  3739. break;
  3740. }
  3741. }
  3742. }
  3743. if ($grant > 0) {
  3744. return true;
  3745. }
  3746. return $this->allowIfAllAbstainDecisions;
  3747. }
  3748. }
  3749. }
  3750. namespace Symfony\Component\Security\Core\Authorization
  3751. {
  3752. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3753. interface AccessDecisionManagerInterface
  3754. {
  3755. function decide(TokenInterface $token, array $attributes, $object = null);
  3756. function supportsAttribute($attribute);
  3757. function supportsClass($class);
  3758. }
  3759. }
  3760. namespace Symfony\Component\Security\Core\Authorization\Voter
  3761. {
  3762. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  3763. interface VoterInterface
  3764. {
  3765. const ACCESS_GRANTED = 1;
  3766. const ACCESS_ABSTAIN = 0;
  3767. const ACCESS_DENIED = -1;
  3768. function supportsAttribute($attribute);
  3769. function supportsClass($class);
  3770. function vote(TokenInterface $token, $object, array $attributes);
  3771. }
  3772. }
  3773. namespace Symfony\Bundle\SecurityBundle\Security
  3774. {
  3775. use Symfony\Component\Security\Http\FirewallMapInterface;
  3776. use Symfony\Component\HttpFoundation\Request;
  3777. use Symfony\Component\DependencyInjection\ContainerInterface;
  3778. class FirewallMap implements FirewallMapInterface
  3779. {
  3780. protected $container;
  3781. protected $map;
  3782. public function __construct(ContainerInterface $container, array $map)
  3783. {
  3784. $this->container = $container;
  3785. $this->map = $map;
  3786. }
  3787. public function getListeners(Request $request)
  3788. {
  3789. foreach ($this->map as $contextId => $requestMatcher) {
  3790. if (null === $requestMatcher || $requestMatcher->matches($request)) {
  3791. return $this->container->get($contextId)->getContext();
  3792. }
  3793. }
  3794. return array(array(), null);
  3795. }
  3796. }
  3797. }
  3798. namespace Symfony\Bundle\SecurityBundle\Security
  3799. {
  3800. use Symfony\Component\Security\Http\Firewall\ExceptionListener;
  3801. class FirewallContext
  3802. {
  3803. private $listeners;
  3804. private $exceptionListener;
  3805. public function __construct(array $listeners, ExceptionListener $exceptionListener = null)
  3806. {
  3807. $this->listeners = $listeners;
  3808. $this->exceptionListener = $exceptionListener;
  3809. }
  3810. public function getContext()
  3811. {
  3812. return array($this->listeners, $this->exceptionListener);
  3813. }
  3814. }
  3815. }
  3816. namespace Symfony\Component\HttpFoundation
  3817. {
  3818. class RequestMatcher implements RequestMatcherInterface
  3819. {
  3820. private $path;
  3821. private $host;
  3822. private $methods;
  3823. private $ip;
  3824. private $attributes;
  3825. public function __construct($path = null, $host = null, $methods = null, $ip = null, array $attributes = array())
  3826. {
  3827. $this->path = $path;
  3828. $this->host = $host;
  3829. $this->methods = $methods;
  3830. $this->ip = $ip;
  3831. $this->attributes = $attributes;
  3832. }
  3833. public function matchHost($regexp)
  3834. {
  3835. $this->host = $regexp;
  3836. }
  3837. public function matchPath($regexp)
  3838. {
  3839. $this->path = $regexp;
  3840. }
  3841. public function matchIp($ip)
  3842. {
  3843. $this->ip = $ip;
  3844. }
  3845. public function matchMethod($method)
  3846. {
  3847. $this->methods = array_map('strtoupper', is_array($method) ? $method : array($method));
  3848. }
  3849. public function matchAttribute($key, $regexp)
  3850. {
  3851. $this->attributes[$key] = $regexp;
  3852. }
  3853. public function matches(Request $request)
  3854. {
  3855. if (null !== $this->methods && !in_array($request->getMethod(), $this->methods)) {
  3856. return false;
  3857. }
  3858. foreach ($this->attributes as $key => $pattern) {
  3859. if (!preg_match('#'.str_replace('#', '\\#', $pattern).'#', $request->attributes->get($key))) {
  3860. return false;
  3861. }
  3862. }
  3863. if (null !== $this->path) {
  3864. $path = str_replace('#', '\\#', $this->path);
  3865. if (!preg_match('#'.$path.'#', $request->getPathInfo())) {
  3866. return false;
  3867. }
  3868. }
  3869. if (null !== $this->host && !preg_match('#'.str_replace('#', '\\#', $this->host).'#', $request->getHost())) {
  3870. return false;
  3871. }
  3872. if (null !== $this->ip && !$this->checkIp($request->getClientIp(), $this->ip)) {
  3873. return false;
  3874. }
  3875. return true;
  3876. }
  3877. protected function checkIp($requestIp, $ip)
  3878. {
  3879. if (false !== strpos($requestIp, ':')) {
  3880. return $this->checkIp6($requestIp, $ip);
  3881. } else {
  3882. return $this->checkIp4($requestIp, $ip);
  3883. }
  3884. }
  3885. protected function checkIp4($requestIp, $ip)
  3886. {
  3887. if (false !== strpos($ip, '/')) {
  3888. list($address, $netmask) = explode('/', $ip);
  3889. if ($netmask < 1 || $netmask > 32) {
  3890. return false;
  3891. }
  3892. } else {
  3893. $address = $ip;
  3894. $netmask = 32;
  3895. }
  3896. return 0 === substr_compare(sprintf('%032b', ip2long($requestIp)), sprintf('%032b', ip2long($address)), 0, $netmask);
  3897. }
  3898. protected function checkIp6($requestIp, $ip)
  3899. {
  3900. if (!defined('AF_INET6')) {
  3901. throw new \RuntimeException('Unable to check Ipv6. Check that PHP was not compiled with option "disable-ipv6".');
  3902. }
  3903. list($address, $netmask) = explode('/', $ip);
  3904. $bytes_addr = unpack("n*", inet_pton($address));
  3905. $bytes_test = unpack("n*", inet_pton($requestIp));
  3906. for ($i = 1, $ceil = ceil($netmask / 16); $i <= $ceil; $i++) {
  3907. $left = $netmask - 16 * ($i-1);
  3908. $left = ($left <= 16) ?: 16;
  3909. $mask = ~(0xffff >> $left) & 0xffff;
  3910. if (($bytes_addr[$i] & $mask) != ($bytes_test[$i] & $mask)) {
  3911. return false;
  3912. }
  3913. }
  3914. return true;
  3915. }
  3916. }
  3917. }
  3918. namespace Symfony\Component\HttpFoundation
  3919. {
  3920. interface RequestMatcherInterface
  3921. {
  3922. function matches(Request $request);
  3923. }
  3924. }
  3925. namespace
  3926. {
  3927. /*
  3928. * This file is part of Twig.
  3929. *
  3930. * (c) 2009 Fabien Potencier
  3931. *
  3932. * For the full copyright and license information, please view the LICENSE
  3933. * file that was distributed with this source code.
  3934. */
  3935. /**
  3936. * Stores the Twig configuration.
  3937. *
  3938. * @package twig
  3939. * @author Fabien Potencier <fabien@symfony.com>
  3940. */
  3941. class Twig_Environment
  3942. {
  3943. const VERSION = '1.1.2';
  3944. protected $charset;
  3945. protected $loader;
  3946. protected $debug;
  3947. protected $autoReload;
  3948. protected $cache;
  3949. protected $lexer;
  3950. protected $parser;
  3951. protected $compiler;
  3952. protected $baseTemplateClass;
  3953. protected $extensions;
  3954. protected $parsers;
  3955. protected $visitors;
  3956. protected $filters;
  3957. protected $tests;
  3958. protected $functions;
  3959. protected $globals;
  3960. protected $runtimeInitialized;
  3961. protected $loadedTemplates;
  3962. protected $strictVariables;
  3963. protected $unaryOperators;
  3964. protected $binaryOperators;
  3965. protected $templateClassPrefix = '__TwigTemplate_';
  3966. protected $functionCallbacks;
  3967. protected $filterCallbacks;
  3968. /**
  3969. * Constructor.
  3970. *
  3971. * Available options:
  3972. *
  3973. * * debug: When set to `true`, the generated templates have a __toString()
  3974. * method that you can use to display the generated nodes (default to
  3975. * false).
  3976. *
  3977. * * charset: The charset used by the templates (default to utf-8).
  3978. *
  3979. * * base_template_class: The base template class to use for generated
  3980. * templates (default to Twig_Template).
  3981. *
  3982. * * cache: An absolute path where to store the compiled templates, or
  3983. * false to disable compilation cache (default)
  3984. *
  3985. * * auto_reload: Whether to reload the template is the original source changed.
  3986. * If you don't provide the auto_reload option, it will be
  3987. * determined automatically base on the debug value.
  3988. *
  3989. * * strict_variables: Whether to ignore invalid variables in templates
  3990. * (default to false).
  3991. *
  3992. * * autoescape: Whether to enable auto-escaping (default to true);
  3993. *
  3994. * * optimizations: A flag that indicates which optimizations to apply
  3995. * (default to -1 which means that all optimizations are enabled;
  3996. * set it to 0 to disable)
  3997. *
  3998. * @param Twig_LoaderInterface $loader A Twig_LoaderInterface instance
  3999. * @param array $options An array of options
  4000. */
  4001. public function __construct(Twig_LoaderInterface $loader = null, $options = array())
  4002. {
  4003. if (null !== $loader) {
  4004. $this->setLoader($loader);
  4005. }
  4006. $options = array_merge(array(
  4007. 'debug' => false,
  4008. 'charset' => 'UTF-8',
  4009. 'base_template_class' => 'Twig_Template',
  4010. 'strict_variables' => false,
  4011. 'autoescape' => true,
  4012. 'cache' => false,
  4013. 'auto_reload' => null,
  4014. 'optimizations' => -1,
  4015. ), $options);
  4016. $this->debug = (bool) $options['debug'];
  4017. $this->charset = $options['charset'];
  4018. $this->baseTemplateClass = $options['base_template_class'];
  4019. $this->autoReload = null === $options['auto_reload'] ? $this->debug : (bool) $options['auto_reload'];
  4020. $this->extensions = array(
  4021. 'core' => new Twig_Extension_Core(),
  4022. 'escaper' => new Twig_Extension_Escaper((bool) $options['autoescape']),
  4023. 'optimizer' => new Twig_Extension_Optimizer($options['optimizations']),
  4024. );
  4025. $this->strictVariables = (bool) $options['strict_variables'];
  4026. $this->runtimeInitialized = false;
  4027. $this->setCache($options['cache']);
  4028. $this->functionCallbacks = array();
  4029. $this->filterCallbacks = array();
  4030. }
  4031. /**
  4032. * Gets the base template class for compiled templates.
  4033. *
  4034. * @return string The base template class name
  4035. */
  4036. public function getBaseTemplateClass()
  4037. {
  4038. return $this->baseTemplateClass;
  4039. }
  4040. /**
  4041. * Sets the base template class for compiled templates.
  4042. *
  4043. * @param string $class The base template class name
  4044. */
  4045. public function setBaseTemplateClass($class)
  4046. {
  4047. $this->baseTemplateClass = $class;
  4048. }
  4049. /**
  4050. * Enables debugging mode.
  4051. */
  4052. public function enableDebug()
  4053. {
  4054. $this->debug = true;
  4055. }
  4056. /**
  4057. * Disables debugging mode.
  4058. */
  4059. public function disableDebug()
  4060. {
  4061. $this->debug = false;
  4062. }
  4063. /**
  4064. * Checks if debug mode is enabled.
  4065. *
  4066. * @return Boolean true if debug mode is enabled, false otherwise
  4067. */
  4068. public function isDebug()
  4069. {
  4070. return $this->debug;
  4071. }
  4072. /**
  4073. * Enables the auto_reload option.
  4074. */
  4075. public function enableAutoReload()
  4076. {
  4077. $this->autoReload = true;
  4078. }
  4079. /**
  4080. * Disables the auto_reload option.
  4081. */
  4082. public function disableAutoReload()
  4083. {
  4084. $this->autoReload = false;
  4085. }
  4086. /**
  4087. * Checks if the auto_reload option is enabled.
  4088. *
  4089. * @return Boolean true if auto_reload is enabled, false otherwise
  4090. */
  4091. public function isAutoReload()
  4092. {
  4093. return $this->autoReload;
  4094. }
  4095. /**
  4096. * Enables the strict_variables option.
  4097. */
  4098. public function enableStrictVariables()
  4099. {
  4100. $this->strictVariables = true;
  4101. }
  4102. /**
  4103. * Disables the strict_variables option.
  4104. */
  4105. public function disableStrictVariables()
  4106. {
  4107. $this->strictVariables = false;
  4108. }
  4109. /**
  4110. * Checks if the strict_variables option is enabled.
  4111. *
  4112. * @return Boolean true if strict_variables is enabled, false otherwise
  4113. */
  4114. public function isStrictVariables()
  4115. {
  4116. return $this->strictVariables;
  4117. }
  4118. /**
  4119. * Gets the cache directory or false if cache is disabled.
  4120. *
  4121. * @return string|false
  4122. */
  4123. public function getCache()
  4124. {
  4125. return $this->cache;
  4126. }
  4127. /**
  4128. * Sets the cache directory or false if cache is disabled.
  4129. *
  4130. * @param string|false $cache The absolute path to the compiled templates,
  4131. * or false to disable cache
  4132. */
  4133. public function setCache($cache)
  4134. {
  4135. $this->cache = $cache ? $cache : false;
  4136. }
  4137. /**
  4138. * Gets the cache filename for a given template.
  4139. *
  4140. * @param string $name The template name
  4141. *
  4142. * @return string The cache file name
  4143. */
  4144. public function getCacheFilename($name)
  4145. {
  4146. if (false === $this->cache) {
  4147. return false;
  4148. }
  4149. $class = substr($this->getTemplateClass($name), strlen($this->templateClassPrefix));
  4150. return $this->getCache().'/'.substr($class, 0, 2).'/'.substr($class, 2, 2).'/'.substr($class, 4).'.php';
  4151. }
  4152. /**
  4153. * Gets the template class associated with the given string.
  4154. *
  4155. * @param string $name The name for which to calculate the template class name
  4156. *
  4157. * @return string The template class name
  4158. */
  4159. public function getTemplateClass($name)
  4160. {
  4161. return $this->templateClassPrefix.md5($this->loader->getCacheKey($name));
  4162. }
  4163. /**
  4164. * Gets the template class prefix.
  4165. *
  4166. * @return string The template class prefix
  4167. */
  4168. public function getTemplateClassPrefix()
  4169. {
  4170. return $this->templateClassPrefix;
  4171. }
  4172. /**
  4173. * Renders a template.
  4174. *
  4175. * @param string $name The template name
  4176. * @param array $context An array of parameters to pass to the template
  4177. *
  4178. * @return string The rendered template
  4179. */
  4180. public function render($name, array $context = array())
  4181. {
  4182. return $this->loadTemplate($name)->render($context);
  4183. }
  4184. /**
  4185. * Loads a template by name.
  4186. *
  4187. * @param string $name The template name
  4188. *
  4189. * @return Twig_TemplateInterface A template instance representing the given template name
  4190. */
  4191. public function loadTemplate($name)
  4192. {
  4193. $cls = $this->getTemplateClass($name);
  4194. if (isset($this->loadedTemplates[$cls])) {
  4195. return $this->loadedTemplates[$cls];
  4196. }
  4197. if (!class_exists($cls, false)) {
  4198. if (false === $cache = $this->getCacheFilename($name)) {
  4199. eval('?>'.$this->compileSource($this->loader->getSource($name), $name));
  4200. } else {
  4201. if (!file_exists($cache) || ($this->isAutoReload() && !$this->loader->isFresh($name, filemtime($cache)))) {
  4202. $this->writeCacheFile($cache, $this->compileSource($this->loader->getSource($name), $name));
  4203. }
  4204. require_once $cache;
  4205. }
  4206. }
  4207. if (!$this->runtimeInitialized) {
  4208. $this->initRuntime();
  4209. }
  4210. return $this->loadedTemplates[$cls] = new $cls($this);
  4211. }
  4212. /**
  4213. * Clears the internal template cache.
  4214. */
  4215. public function clearTemplateCache()
  4216. {
  4217. $this->loadedTemplates = array();
  4218. }
  4219. /**
  4220. * Clears the template cache files on the filesystem.
  4221. */
  4222. public function clearCacheFiles()
  4223. {
  4224. if (false === $this->cache) {
  4225. return;
  4226. }
  4227. foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->cache), RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
  4228. if ($file->isFile()) {
  4229. @unlink($file->getPathname());
  4230. }
  4231. }
  4232. }
  4233. /**
  4234. * Gets the Lexer instance.
  4235. *
  4236. * @return Twig_LexerInterface A Twig_LexerInterface instance
  4237. */
  4238. public function getLexer()
  4239. {
  4240. if (null === $this->lexer) {
  4241. $this->lexer = new Twig_Lexer($this);
  4242. }
  4243. return $this->lexer;
  4244. }
  4245. /**
  4246. * Sets the Lexer instance.
  4247. *
  4248. * @param Twig_LexerInterface A Twig_LexerInterface instance
  4249. */
  4250. public function setLexer(Twig_LexerInterface $lexer)
  4251. {
  4252. $this->lexer = $lexer;
  4253. }
  4254. /**
  4255. * Tokenizes a source code.
  4256. *
  4257. * @param string $source The template source code
  4258. * @param string $name The template name
  4259. *
  4260. * @return Twig_TokenStream A Twig_TokenStream instance
  4261. */
  4262. public function tokenize($source, $name = null)
  4263. {
  4264. return $this->getLexer()->tokenize($source, $name);
  4265. }
  4266. /**
  4267. * Gets the Parser instance.
  4268. *
  4269. * @return Twig_ParserInterface A Twig_ParserInterface instance
  4270. */
  4271. public function getParser()
  4272. {
  4273. if (null === $this->parser) {
  4274. $this->parser = new Twig_Parser($this);
  4275. }
  4276. return $this->parser;
  4277. }
  4278. /**
  4279. * Sets the Parser instance.
  4280. *
  4281. * @param Twig_ParserInterface A Twig_ParserInterface instance
  4282. */
  4283. public function setParser(Twig_ParserInterface $parser)
  4284. {
  4285. $this->parser = $parser;
  4286. }
  4287. /**
  4288. * Parses a token stream.
  4289. *
  4290. * @param Twig_TokenStream $tokens A Twig_TokenStream instance
  4291. *
  4292. * @return Twig_Node_Module A Node tree
  4293. */
  4294. public function parse(Twig_TokenStream $tokens)
  4295. {
  4296. return $this->getParser()->parse($tokens);
  4297. }
  4298. /**
  4299. * Gets the Compiler instance.
  4300. *
  4301. * @return Twig_CompilerInterface A Twig_CompilerInterface instance
  4302. */
  4303. public function getCompiler()
  4304. {
  4305. if (null === $this->compiler) {
  4306. $this->compiler = new Twig_Compiler($this);
  4307. }
  4308. return $this->compiler;
  4309. }
  4310. /**
  4311. * Sets the Compiler instance.
  4312. *
  4313. * @param Twig_CompilerInterface $compiler A Twig_CompilerInterface instance
  4314. */
  4315. public function setCompiler(Twig_CompilerInterface $compiler)
  4316. {
  4317. $this->compiler = $compiler;
  4318. }
  4319. /**
  4320. * Compiles a Node.
  4321. *
  4322. * @param Twig_NodeInterface $node A Twig_NodeInterface instance
  4323. *
  4324. * @return string The compiled PHP source code
  4325. */
  4326. public function compile(Twig_NodeInterface $node)
  4327. {
  4328. return $this->getCompiler()->compile($node)->getSource();
  4329. }
  4330. /**
  4331. * Compiles a template source code.
  4332. *
  4333. * @param string $source The template source code
  4334. * @param string $name The template name
  4335. *
  4336. * @return string The compiled PHP source code
  4337. */
  4338. public function compileSource($source, $name = null)
  4339. {
  4340. try {
  4341. return $this->compile($this->parse($this->tokenize($source, $name)));
  4342. } catch (Twig_Error $e) {
  4343. $e->setTemplateFile($name);
  4344. throw $e;
  4345. } catch (Exception $e) {
  4346. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the compilation of a template ("%s").', $e->getMessage()), -1, $name, $e);
  4347. }
  4348. }
  4349. /**
  4350. * Sets the Loader instance.
  4351. *
  4352. * @param Twig_LoaderInterface $loader A Twig_LoaderInterface instance
  4353. */
  4354. public function setLoader(Twig_LoaderInterface $loader)
  4355. {
  4356. $this->loader = $loader;
  4357. }
  4358. /**
  4359. * Gets the Loader instance.
  4360. *
  4361. * @return Twig_LoaderInterface A Twig_LoaderInterface instance
  4362. */
  4363. public function getLoader()
  4364. {
  4365. return $this->loader;
  4366. }
  4367. /**
  4368. * Sets the default template charset.
  4369. *
  4370. * @param string $charset The default charset
  4371. */
  4372. public function setCharset($charset)
  4373. {
  4374. $this->charset = $charset;
  4375. }
  4376. /**
  4377. * Gets the default template charset.
  4378. *
  4379. * @return string The default charset
  4380. */
  4381. public function getCharset()
  4382. {
  4383. return $this->charset;
  4384. }
  4385. /**
  4386. * Initializes the runtime environment.
  4387. */
  4388. public function initRuntime()
  4389. {
  4390. $this->runtimeInitialized = true;
  4391. foreach ($this->getExtensions() as $extension) {
  4392. $extension->initRuntime($this);
  4393. }
  4394. }
  4395. /**
  4396. * Returns true if the given extension is registered.
  4397. *
  4398. * @param string $name The extension name
  4399. *
  4400. * @return Boolean Whether the extension is registered or not
  4401. */
  4402. public function hasExtension($name)
  4403. {
  4404. return isset($this->extensions[$name]);
  4405. }
  4406. /**
  4407. * Gets an extension by name.
  4408. *
  4409. * @param string $name The extension name
  4410. *
  4411. * @return Twig_ExtensionInterface A Twig_ExtensionInterface instance
  4412. */
  4413. public function getExtension($name)
  4414. {
  4415. if (!isset($this->extensions[$name])) {
  4416. throw new Twig_Error_Runtime(sprintf('The "%s" extension is not enabled.', $name));
  4417. }
  4418. return $this->extensions[$name];
  4419. }
  4420. /**
  4421. * Registers an extension.
  4422. *
  4423. * @param Twig_ExtensionInterface $extension A Twig_ExtensionInterface instance
  4424. */
  4425. public function addExtension(Twig_ExtensionInterface $extension)
  4426. {
  4427. $this->extensions[$extension->getName()] = $extension;
  4428. }
  4429. /**
  4430. * Removes an extension by name.
  4431. *
  4432. * @param string $name The extension name
  4433. */
  4434. public function removeExtension($name)
  4435. {
  4436. unset($this->extensions[$name]);
  4437. }
  4438. /**
  4439. * Registers an array of extensions.
  4440. *
  4441. * @param array $extensions An array of extensions
  4442. */
  4443. public function setExtensions(array $extensions)
  4444. {
  4445. foreach ($extensions as $extension) {
  4446. $this->addExtension($extension);
  4447. }
  4448. }
  4449. /**
  4450. * Returns all registered extensions.
  4451. *
  4452. * @return array An array of extensions
  4453. */
  4454. public function getExtensions()
  4455. {
  4456. return $this->extensions;
  4457. }
  4458. /**
  4459. * Registers a Token Parser.
  4460. *
  4461. * @param Twig_TokenParserInterface $parser A Twig_TokenParserInterface instance
  4462. */
  4463. public function addTokenParser(Twig_TokenParserInterface $parser)
  4464. {
  4465. if (null === $this->parsers) {
  4466. $this->getTokenParsers();
  4467. }
  4468. $this->parsers->addTokenParser($parser);
  4469. }
  4470. /**
  4471. * Gets the registered Token Parsers.
  4472. *
  4473. * @return Twig_TokenParserInterface[] An array of Twig_TokenParserInterface instances
  4474. */
  4475. public function getTokenParsers()
  4476. {
  4477. if (null === $this->parsers) {
  4478. $this->parsers = new Twig_TokenParserBroker;
  4479. foreach ($this->getExtensions() as $extension) {
  4480. $parsers = $extension->getTokenParsers();
  4481. foreach($parsers as $parser) {
  4482. if ($parser instanceof Twig_TokenParserInterface) {
  4483. $this->parsers->addTokenParser($parser);
  4484. } else if ($parser instanceof Twig_TokenParserBrokerInterface) {
  4485. $this->parsers->addTokenParserBroker($parser);
  4486. } else {
  4487. throw new Twig_Error_Runtime('getTokenParsers() must return an array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances');
  4488. }
  4489. }
  4490. }
  4491. }
  4492. return $this->parsers;
  4493. }
  4494. /**
  4495. * Registers a Node Visitor.
  4496. *
  4497. * @param Twig_NodeVisitorInterface $visitor A Twig_NodeVisitorInterface instance
  4498. */
  4499. public function addNodeVisitor(Twig_NodeVisitorInterface $visitor)
  4500. {
  4501. if (null === $this->visitors) {
  4502. $this->getNodeVisitors();
  4503. }
  4504. $this->visitors[] = $visitor;
  4505. }
  4506. /**
  4507. * Gets the registered Node Visitors.
  4508. *
  4509. * @return Twig_NodeVisitorInterface[] An array of Twig_NodeVisitorInterface instances
  4510. */
  4511. public function getNodeVisitors()
  4512. {
  4513. if (null === $this->visitors) {
  4514. $this->visitors = array();
  4515. foreach ($this->getExtensions() as $extension) {
  4516. $this->visitors = array_merge($this->visitors, $extension->getNodeVisitors());
  4517. }
  4518. }
  4519. return $this->visitors;
  4520. }
  4521. /**
  4522. * Registers a Filter.
  4523. *
  4524. * @param string $name The filter name
  4525. * @param Twig_FilterInterface $visitor A Twig_FilterInterface instance
  4526. */
  4527. public function addFilter($name, Twig_FilterInterface $filter)
  4528. {
  4529. if (null === $this->filters) {
  4530. $this->loadFilters();
  4531. }
  4532. $this->filters[$name] = $filter;
  4533. }
  4534. /**
  4535. * Get a filter by name.
  4536. *
  4537. * Subclasses may override this method and load filters differently;
  4538. * so no list of filters is available.
  4539. *
  4540. * @param string $name The filter name
  4541. *
  4542. * @return Twig_Filter|false A Twig_Filter instance or false if the filter does not exists
  4543. */
  4544. public function getFilter($name)
  4545. {
  4546. if (null === $this->filters) {
  4547. $this->loadFilters();
  4548. }
  4549. if (isset($this->filters[$name])) {
  4550. return $this->filters[$name];
  4551. }
  4552. foreach ($this->filterCallbacks as $callback) {
  4553. if (false !== $filter = call_user_func($callback, $name)) {
  4554. return $filter;
  4555. }
  4556. }
  4557. return false;
  4558. }
  4559. public function registerUndefinedFilterCallback($callable)
  4560. {
  4561. $this->filterCallbacks[] = $callable;
  4562. }
  4563. /**
  4564. * Gets the registered Filters.
  4565. *
  4566. * @return Twig_FilterInterface[] An array of Twig_FilterInterface instances
  4567. */
  4568. protected function loadFilters()
  4569. {
  4570. $this->filters = array();
  4571. foreach ($this->getExtensions() as $extension) {
  4572. $this->filters = array_merge($this->filters, $extension->getFilters());
  4573. }
  4574. }
  4575. /**
  4576. * Registers a Test.
  4577. *
  4578. * @param string $name The test name
  4579. * @param Twig_TestInterface $visitor A Twig_TestInterface instance
  4580. */
  4581. public function addTest($name, Twig_TestInterface $test)
  4582. {
  4583. if (null === $this->tests) {
  4584. $this->getTests();
  4585. }
  4586. $this->tests[$name] = $test;
  4587. }
  4588. /**
  4589. * Gets the registered Tests.
  4590. *
  4591. * @return Twig_TestInterface[] An array of Twig_TestInterface instances
  4592. */
  4593. public function getTests()
  4594. {
  4595. if (null === $this->tests) {
  4596. $this->tests = array();
  4597. foreach ($this->getExtensions() as $extension) {
  4598. $this->tests = array_merge($this->tests, $extension->getTests());
  4599. }
  4600. }
  4601. return $this->tests;
  4602. }
  4603. /**
  4604. * Registers a Function.
  4605. *
  4606. * @param string $name The function name
  4607. * @param Twig_FunctionInterface $function A Twig_FunctionInterface instance
  4608. */
  4609. public function addFunction($name, Twig_FunctionInterface $function)
  4610. {
  4611. if (null === $this->functions) {
  4612. $this->loadFunctions();
  4613. }
  4614. $this->functions[$name] = $function;
  4615. }
  4616. /**
  4617. * Get a function by name.
  4618. *
  4619. * Subclasses may override this method and load functions differently;
  4620. * so no list of functions is available.
  4621. *
  4622. * @param string $name function name
  4623. *
  4624. * @return Twig_Function|false A Twig_Function instance or false if the function does not exists
  4625. */
  4626. public function getFunction($name)
  4627. {
  4628. if (null === $this->functions) {
  4629. $this->loadFunctions();
  4630. }
  4631. if (isset($this->functions[$name])) {
  4632. return $this->functions[$name];
  4633. }
  4634. foreach ($this->functionCallbacks as $callback) {
  4635. if (false !== $function = call_user_func($callback, $name)) {
  4636. return $function;
  4637. }
  4638. }
  4639. return false;
  4640. }
  4641. public function registerUndefinedFunctionCallback($callable)
  4642. {
  4643. $this->functionCallbacks[] = $callable;
  4644. }
  4645. protected function loadFunctions()
  4646. {
  4647. $this->functions = array();
  4648. foreach ($this->getExtensions() as $extension) {
  4649. $this->functions = array_merge($this->functions, $extension->getFunctions());
  4650. }
  4651. }
  4652. /**
  4653. * Registers a Global.
  4654. *
  4655. * @param string $name The global name
  4656. * @param mixed $value The global value
  4657. */
  4658. public function addGlobal($name, $value)
  4659. {
  4660. if (null === $this->globals) {
  4661. $this->getGlobals();
  4662. }
  4663. $this->globals[$name] = $value;
  4664. }
  4665. /**
  4666. * Gets the registered Globals.
  4667. *
  4668. * @return array An array of globals
  4669. */
  4670. public function getGlobals()
  4671. {
  4672. if (null === $this->globals) {
  4673. $this->globals = array();
  4674. foreach ($this->getExtensions() as $extension) {
  4675. $this->globals = array_merge($this->globals, $extension->getGlobals());
  4676. }
  4677. }
  4678. return $this->globals;
  4679. }
  4680. /**
  4681. * Gets the registered unary Operators.
  4682. *
  4683. * @return array An array of unary operators
  4684. */
  4685. public function getUnaryOperators()
  4686. {
  4687. if (null === $this->unaryOperators) {
  4688. $this->initOperators();
  4689. }
  4690. return $this->unaryOperators;
  4691. }
  4692. /**
  4693. * Gets the registered binary Operators.
  4694. *
  4695. * @return array An array of binary operators
  4696. */
  4697. public function getBinaryOperators()
  4698. {
  4699. if (null === $this->binaryOperators) {
  4700. $this->initOperators();
  4701. }
  4702. return $this->binaryOperators;
  4703. }
  4704. protected function initOperators()
  4705. {
  4706. $this->unaryOperators = array();
  4707. $this->binaryOperators = array();
  4708. foreach ($this->getExtensions() as $extension) {
  4709. $operators = $extension->getOperators();
  4710. if (!$operators) {
  4711. continue;
  4712. }
  4713. if (2 !== count($operators)) {
  4714. throw new InvalidArgumentException(sprintf('"%s::getOperators()" does not return a valid operators array.', get_class($extension)));
  4715. }
  4716. $this->unaryOperators = array_merge($this->unaryOperators, $operators[0]);
  4717. $this->binaryOperators = array_merge($this->binaryOperators, $operators[1]);
  4718. }
  4719. }
  4720. protected function writeCacheFile($file, $content)
  4721. {
  4722. if (!is_dir(dirname($file))) {
  4723. mkdir(dirname($file), 0777, true);
  4724. }
  4725. $tmpFile = tempnam(dirname($file), basename($file));
  4726. if (false !== @file_put_contents($tmpFile, $content)) {
  4727. // rename does not work on Win32 before 5.2.6
  4728. if (@rename($tmpFile, $file) || (@copy($tmpFile, $file) && unlink($tmpFile))) {
  4729. chmod($file, 0644);
  4730. return;
  4731. }
  4732. }
  4733. throw new Twig_Error_Runtime(sprintf('Failed to write cache file "%s".', $file));
  4734. }
  4735. }
  4736. }
  4737. namespace
  4738. {
  4739. /*
  4740. * This file is part of Twig.
  4741. *
  4742. * (c) 2009 Fabien Potencier
  4743. *
  4744. * For the full copyright and license information, please view the LICENSE
  4745. * file that was distributed with this source code.
  4746. */
  4747. /**
  4748. * Interface implemented by extension classes.
  4749. *
  4750. * @package twig
  4751. * @author Fabien Potencier <fabien@symfony.com>
  4752. */
  4753. interface Twig_ExtensionInterface
  4754. {
  4755. /**
  4756. * Initializes the runtime environment.
  4757. *
  4758. * This is where you can load some file that contains filter functions for instance.
  4759. *
  4760. * @param Twig_Environment $environment The current Twig_Environment instance
  4761. */
  4762. function initRuntime(Twig_Environment $environment);
  4763. /**
  4764. * Returns the token parser instances to add to the existing list.
  4765. *
  4766. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  4767. */
  4768. function getTokenParsers();
  4769. /**
  4770. * Returns the node visitor instances to add to the existing list.
  4771. *
  4772. * @return array An array of Twig_NodeVisitorInterface instances
  4773. */
  4774. function getNodeVisitors();
  4775. /**
  4776. * Returns a list of filters to add to the existing list.
  4777. *
  4778. * @return array An array of filters
  4779. */
  4780. function getFilters();
  4781. /**
  4782. * Returns a list of tests to add to the existing list.
  4783. *
  4784. * @return array An array of tests
  4785. */
  4786. function getTests();
  4787. /**
  4788. * Returns a list of functions to add to the existing list.
  4789. *
  4790. * @return array An array of functions
  4791. */
  4792. function getFunctions();
  4793. /**
  4794. * Returns a list of operators to add to the existing list.
  4795. *
  4796. * @return array An array of operators
  4797. */
  4798. function getOperators();
  4799. /**
  4800. * Returns a list of global functions to add to the existing list.
  4801. *
  4802. * @return array An array of global functions
  4803. */
  4804. function getGlobals();
  4805. /**
  4806. * Returns the name of the extension.
  4807. *
  4808. * @return string The extension name
  4809. */
  4810. function getName();
  4811. }
  4812. }
  4813. namespace
  4814. {
  4815. /*
  4816. * This file is part of Twig.
  4817. *
  4818. * (c) 2009 Fabien Potencier
  4819. *
  4820. * For the full copyright and license information, please view the LICENSE
  4821. * file that was distributed with this source code.
  4822. */
  4823. abstract class Twig_Extension implements Twig_ExtensionInterface
  4824. {
  4825. /**
  4826. * Initializes the runtime environment.
  4827. *
  4828. * This is where you can load some file that contains filter functions for instance.
  4829. *
  4830. * @param Twig_Environment $environment The current Twig_Environment instance
  4831. */
  4832. public function initRuntime(Twig_Environment $environment)
  4833. {
  4834. }
  4835. /**
  4836. * Returns the token parser instances to add to the existing list.
  4837. *
  4838. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  4839. */
  4840. public function getTokenParsers()
  4841. {
  4842. return array();
  4843. }
  4844. /**
  4845. * Returns the node visitor instances to add to the existing list.
  4846. *
  4847. * @return array An array of Twig_NodeVisitorInterface instances
  4848. */
  4849. public function getNodeVisitors()
  4850. {
  4851. return array();
  4852. }
  4853. /**
  4854. * Returns a list of filters to add to the existing list.
  4855. *
  4856. * @return array An array of filters
  4857. */
  4858. public function getFilters()
  4859. {
  4860. return array();
  4861. }
  4862. /**
  4863. * Returns a list of tests to add to the existing list.
  4864. *
  4865. * @return array An array of tests
  4866. */
  4867. public function getTests()
  4868. {
  4869. return array();
  4870. }
  4871. /**
  4872. * Returns a list of functions to add to the existing list.
  4873. *
  4874. * @return array An array of functions
  4875. */
  4876. public function getFunctions()
  4877. {
  4878. return array();
  4879. }
  4880. /**
  4881. * Returns a list of operators to add to the existing list.
  4882. *
  4883. * @return array An array of operators
  4884. */
  4885. public function getOperators()
  4886. {
  4887. return array();
  4888. }
  4889. /**
  4890. * Returns a list of global functions to add to the existing list.
  4891. *
  4892. * @return array An array of global functions
  4893. */
  4894. public function getGlobals()
  4895. {
  4896. return array();
  4897. }
  4898. }
  4899. }
  4900. namespace
  4901. {
  4902. /*
  4903. * This file is part of Twig.
  4904. *
  4905. * (c) 2009 Fabien Potencier
  4906. *
  4907. * For the full copyright and license information, please view the LICENSE
  4908. * file that was distributed with this source code.
  4909. */
  4910. class Twig_Extension_Core extends Twig_Extension
  4911. {
  4912. /**
  4913. * Returns the token parser instance to add to the existing list.
  4914. *
  4915. * @return array An array of Twig_TokenParser instances
  4916. */
  4917. public function getTokenParsers()
  4918. {
  4919. return array(
  4920. new Twig_TokenParser_For(),
  4921. new Twig_TokenParser_If(),
  4922. new Twig_TokenParser_Extends(),
  4923. new Twig_TokenParser_Include(),
  4924. new Twig_TokenParser_Block(),
  4925. new Twig_TokenParser_Use(),
  4926. new Twig_TokenParser_Filter(),
  4927. new Twig_TokenParser_Macro(),
  4928. new Twig_TokenParser_Import(),
  4929. new Twig_TokenParser_From(),
  4930. new Twig_TokenParser_Set(),
  4931. new Twig_TokenParser_Spaceless(),
  4932. );
  4933. }
  4934. /**
  4935. * Returns a list of filters to add to the existing list.
  4936. *
  4937. * @return array An array of filters
  4938. */
  4939. public function getFilters()
  4940. {
  4941. $filters = array(
  4942. // formatting filters
  4943. 'date' => new Twig_Filter_Function('twig_date_format_filter'),
  4944. 'format' => new Twig_Filter_Function('sprintf'),
  4945. 'replace' => new Twig_Filter_Function('twig_strtr'),
  4946. // encoding
  4947. 'url_encode' => new Twig_Filter_Function('twig_urlencode_filter'),
  4948. 'json_encode' => new Twig_Filter_Function('twig_jsonencode_filter'),
  4949. // string filters
  4950. 'title' => new Twig_Filter_Function('twig_title_string_filter', array('needs_environment' => true)),
  4951. 'capitalize' => new Twig_Filter_Function('twig_capitalize_string_filter', array('needs_environment' => true)),
  4952. 'upper' => new Twig_Filter_Function('strtoupper'),
  4953. 'lower' => new Twig_Filter_Function('strtolower'),
  4954. 'striptags' => new Twig_Filter_Function('strip_tags'),
  4955. // array helpers
  4956. 'join' => new Twig_Filter_Function('twig_join_filter'),
  4957. 'reverse' => new Twig_Filter_Function('twig_reverse_filter'),
  4958. 'length' => new Twig_Filter_Function('twig_length_filter', array('needs_environment' => true)),
  4959. 'sort' => new Twig_Filter_Function('twig_sort_filter'),
  4960. 'merge' => new Twig_Filter_Function('twig_array_merge'),
  4961. // iteration and runtime
  4962. 'default' => new Twig_Filter_Function('twig_default_filter'),
  4963. 'keys' => new Twig_Filter_Function('twig_get_array_keys_filter'),
  4964. // escaping
  4965. 'escape' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')),
  4966. 'e' => new Twig_Filter_Function('twig_escape_filter', array('needs_environment' => true, 'is_safe_callback' => 'twig_escape_filter_is_safe')),
  4967. );
  4968. if (function_exists('mb_get_info')) {
  4969. $filters['upper'] = new Twig_Filter_Function('twig_upper_filter', array('needs_environment' => true));
  4970. $filters['lower'] = new Twig_Filter_Function('twig_lower_filter', array('needs_environment' => true));
  4971. }
  4972. return $filters;
  4973. }
  4974. /**
  4975. * Returns a list of global functions to add to the existing list.
  4976. *
  4977. * @return array An array of global functions
  4978. */
  4979. public function getFunctions()
  4980. {
  4981. return array(
  4982. 'range' => new Twig_Function_Function('range'),
  4983. 'constant' => new Twig_Function_Function('constant'),
  4984. 'cycle' => new Twig_Function_Function('twig_cycle'),
  4985. );
  4986. }
  4987. /**
  4988. * Returns a list of filters to add to the existing list.
  4989. *
  4990. * @return array An array of filters
  4991. */
  4992. public function getTests()
  4993. {
  4994. return array(
  4995. 'even' => new Twig_Test_Function('twig_test_even'),
  4996. 'odd' => new Twig_Test_Function('twig_test_odd'),
  4997. 'defined' => new Twig_Test_Function('twig_test_defined'),
  4998. 'sameas' => new Twig_Test_Function('twig_test_sameas'),
  4999. 'none' => new Twig_Test_Function('twig_test_none'),
  5000. 'null' => new Twig_Test_Function('twig_test_none'),
  5001. 'divisibleby' => new Twig_Test_Function('twig_test_divisibleby'),
  5002. 'constant' => new Twig_Test_Function('twig_test_constant'),
  5003. 'empty' => new Twig_Test_Function('twig_test_empty'),
  5004. );
  5005. }
  5006. /**
  5007. * Returns a list of operators to add to the existing list.
  5008. *
  5009. * @return array An array of operators
  5010. */
  5011. public function getOperators()
  5012. {
  5013. return array(
  5014. array(
  5015. 'not' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Not'),
  5016. '-' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Neg'),
  5017. '+' => array('precedence' => 50, 'class' => 'Twig_Node_Expression_Unary_Pos'),
  5018. ),
  5019. array(
  5020. 'or' => array('precedence' => 10, 'class' => 'Twig_Node_Expression_Binary_Or', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5021. 'and' => array('precedence' => 15, 'class' => 'Twig_Node_Expression_Binary_And', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5022. '==' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Equal', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5023. '!=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5024. '<' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Less', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5025. '>' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_Greater', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5026. '>=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_GreaterEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5027. '<=' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_LessEqual', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5028. 'not in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_NotIn', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5029. 'in' => array('precedence' => 20, 'class' => 'Twig_Node_Expression_Binary_In', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5030. '+' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Add', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5031. '-' => array('precedence' => 30, 'class' => 'Twig_Node_Expression_Binary_Sub', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5032. '~' => array('precedence' => 40, 'class' => 'Twig_Node_Expression_Binary_Concat', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5033. '*' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mul', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5034. '/' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Div', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5035. '//' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_FloorDiv', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5036. '%' => array('precedence' => 60, 'class' => 'Twig_Node_Expression_Binary_Mod', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5037. 'is' => array('precedence' => 100, 'callable' => array($this, 'parseTestExpression'), 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5038. 'is not' => array('precedence' => 100, 'callable' => array($this, 'parseNotTestExpression'), 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5039. '..' => array('precedence' => 110, 'class' => 'Twig_Node_Expression_Binary_Range', 'associativity' => Twig_ExpressionParser::OPERATOR_LEFT),
  5040. '**' => array('precedence' => 200, 'class' => 'Twig_Node_Expression_Binary_Power', 'associativity' => Twig_ExpressionParser::OPERATOR_RIGHT),
  5041. ),
  5042. );
  5043. }
  5044. public function parseNotTestExpression(Twig_Parser $parser, $node)
  5045. {
  5046. return new Twig_Node_Expression_Unary_Not($this->parseTestExpression($parser, $node), $parser->getCurrentToken()->getLine());
  5047. }
  5048. public function parseTestExpression(Twig_Parser $parser, $node)
  5049. {
  5050. $stream = $parser->getStream();
  5051. $name = $stream->expect(Twig_Token::NAME_TYPE);
  5052. $arguments = null;
  5053. if ($stream->test(Twig_Token::PUNCTUATION_TYPE, '(')) {
  5054. $arguments = $parser->getExpressionParser()->parseArguments();
  5055. }
  5056. return new Twig_Node_Expression_Test($node, $name->getValue(), $arguments, $parser->getCurrentToken()->getLine());
  5057. }
  5058. /**
  5059. * Returns the name of the extension.
  5060. *
  5061. * @return string The extension name
  5062. */
  5063. public function getName()
  5064. {
  5065. return 'core';
  5066. }
  5067. }
  5068. /**
  5069. * Cycles over a value.
  5070. *
  5071. * @param ArrayAccess|array $values An array or an ArrayAccess instance
  5072. * @param integer $i The cycle value
  5073. *
  5074. * @return string The next value in the cycle
  5075. */
  5076. function twig_cycle($values, $i)
  5077. {
  5078. if (!is_array($values) && !$values instanceof ArrayAccess) {
  5079. return $values;
  5080. }
  5081. return $values[$i % count($values)];
  5082. }
  5083. /**
  5084. * Converts a date to the given format.
  5085. *
  5086. * <pre>
  5087. * {{ post.published_at|date("m/d/Y") }}
  5088. * </pre>
  5089. *
  5090. * @param DateTime|string $date A date
  5091. * @param string $format A format
  5092. * @param DateTimeZone|string $timezone A timezone
  5093. *
  5094. * @return string The formatter date
  5095. */
  5096. function twig_date_format_filter($date, $format = 'F j, Y H:i', $timezone = null)
  5097. {
  5098. if (!$date instanceof DateTime) {
  5099. if (ctype_digit((string) $date)) {
  5100. $date = new DateTime('@'.$date);
  5101. $date->setTimezone(new DateTimeZone(date_default_timezone_get()));
  5102. } else {
  5103. $date = new DateTime($date);
  5104. }
  5105. }
  5106. if (null !== $timezone) {
  5107. if (!$timezone instanceof DateTimeZone) {
  5108. $timezone = new DateTimeZone($timezone);
  5109. }
  5110. $date->setTimezone($timezone);
  5111. }
  5112. return $date->format($format);
  5113. }
  5114. /**
  5115. * URL encodes a string.
  5116. *
  5117. * @param string $url A URL
  5118. * @param bool $raw true to use rawurlencode() instead of urlencode
  5119. *
  5120. * @return string The URL encoded value
  5121. */
  5122. function twig_urlencode_filter($url, $raw = false)
  5123. {
  5124. if ($raw) {
  5125. return rawurlencode($url);
  5126. }
  5127. return urlencode($url);
  5128. }
  5129. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  5130. /**
  5131. * JSON encodes a PHP variable.
  5132. *
  5133. * @param mixed $value The value to encode.
  5134. * @param integer $options Not used on PHP 5.2.x
  5135. *
  5136. * @return mixed The JSON encoded value
  5137. */
  5138. function twig_jsonencode_filter($value, $options = 0)
  5139. {
  5140. if ($value instanceof Twig_Markup) {
  5141. $value = (string) $value;
  5142. } elseif (is_array($value)) {
  5143. array_walk_recursive($value, '_twig_markup2string');
  5144. }
  5145. return json_encode($value);
  5146. }
  5147. } else {
  5148. /**
  5149. * JSON encodes a PHP variable.
  5150. *
  5151. * @param mixed $value The value to encode.
  5152. * @param integer $options Bitmask consisting of JSON_HEX_QUOT, JSON_HEX_TAG, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
  5153. *
  5154. * @return mixed The JSON encoded value
  5155. */
  5156. function twig_jsonencode_filter($value, $options = 0)
  5157. {
  5158. if ($value instanceof Twig_Markup) {
  5159. $value = (string) $value;
  5160. } elseif (is_array($value)) {
  5161. array_walk_recursive($value, '_twig_markup2string');
  5162. }
  5163. return json_encode($value, $options);
  5164. }
  5165. }
  5166. function _twig_markup2string(&$value)
  5167. {
  5168. if ($value instanceof Twig_Markup) {
  5169. $value = (string) $value;
  5170. }
  5171. }
  5172. /**
  5173. * Merges an array with another one.
  5174. *
  5175. * <pre>
  5176. * {% set items = { 'apple': 'fruit', 'orange': 'fruit' } %}
  5177. *
  5178. * {% set items = items|merge({ 'peugeot': 'car' }) %}
  5179. *
  5180. * {# items now contains { 'apple': 'fruit', 'orange': 'fruit', 'peugeot': 'car' } #}
  5181. * </pre>
  5182. *
  5183. * @param array $arr1 An array
  5184. * @param array $arr2 An array
  5185. *
  5186. * @return array The merged array
  5187. */
  5188. function twig_array_merge($arr1, $arr2)
  5189. {
  5190. if (!is_array($arr1) || !is_array($arr2)) {
  5191. throw new Twig_Error_Runtime('The merge filter only work with arrays or hashes.');
  5192. }
  5193. return array_merge($arr1, $arr2);
  5194. }
  5195. /**
  5196. * Joins the values to a string.
  5197. *
  5198. * The separator between elements is an empty string per default, you can define it with the optional parameter.
  5199. *
  5200. * <pre>
  5201. * {{ [1, 2, 3]|join('|') }}
  5202. * {# returns 1|2|3 #}
  5203. *
  5204. * {{ [1, 2, 3]|join }}
  5205. * {# returns 123 #}
  5206. * </pre>
  5207. *
  5208. * @param array $value An array
  5209. * @param string $glue The separator
  5210. *
  5211. * @return string The concatenated string
  5212. */
  5213. function twig_join_filter($value, $glue = '')
  5214. {
  5215. return implode($glue, (array) $value);
  5216. }
  5217. /**
  5218. * Returns the value or the default value when it is undefined or empty.
  5219. *
  5220. * <pre>
  5221. *
  5222. * {{ var.foo|default('foo item on var is not defined') }}
  5223. *
  5224. * </pre>
  5225. *
  5226. * @param mixed $value A value
  5227. * @param mixed $default The default value
  5228. *
  5229. * @param mixed The value or the default value;
  5230. */
  5231. function twig_default_filter($value, $default = '')
  5232. {
  5233. if (twig_test_empty($value)) {
  5234. return $default;
  5235. } else {
  5236. return $value;
  5237. }
  5238. }
  5239. /**
  5240. * Returns the keys for the given array.
  5241. *
  5242. * It is useful when you want to iterate over the keys of an array:
  5243. *
  5244. * <pre>
  5245. * {% for key in array|keys %}
  5246. * {# ... #}
  5247. * {% endfor %}
  5248. * </pre>
  5249. *
  5250. * @param array $array An array
  5251. *
  5252. * @return array The keys
  5253. */
  5254. function twig_get_array_keys_filter($array)
  5255. {
  5256. if (is_object($array) && $array instanceof Traversable) {
  5257. return array_keys(iterator_to_array($array));
  5258. }
  5259. if (!is_array($array)) {
  5260. return array();
  5261. }
  5262. return array_keys($array);
  5263. }
  5264. /**
  5265. * Reverses an array.
  5266. *
  5267. * @param array|Traversable $array An array or a Traversable instance
  5268. *
  5269. * return array The array reversed
  5270. */
  5271. function twig_reverse_filter($array)
  5272. {
  5273. if (is_object($array) && $array instanceof Traversable) {
  5274. return array_reverse(iterator_to_array($array));
  5275. }
  5276. if (!is_array($array)) {
  5277. return array();
  5278. }
  5279. return array_reverse($array);
  5280. }
  5281. /**
  5282. * Sorts an array.
  5283. *
  5284. * @param array $array An array
  5285. */
  5286. function twig_sort_filter($array)
  5287. {
  5288. asort($array);
  5289. return $array;
  5290. }
  5291. /* used internally */
  5292. function twig_in_filter($value, $compare)
  5293. {
  5294. if (is_array($compare)) {
  5295. return in_array($value, $compare);
  5296. } elseif (is_string($compare)) {
  5297. return false !== strpos($compare, (string) $value);
  5298. } elseif (is_object($compare) && $compare instanceof Traversable) {
  5299. return in_array($value, iterator_to_array($compare, false));
  5300. }
  5301. return false;
  5302. }
  5303. /**
  5304. * Replaces placeholders in a string.
  5305. *
  5306. * <pre>
  5307. * {{ "I like %this% and %that%."|replace({'%this%': foo, '%that%': "bar"}) }}
  5308. * </pre>
  5309. *
  5310. * @param string $pattern A string
  5311. * @param string $replacements The values for the placeholders
  5312. *
  5313. * @return string The string where the placeholders have been replaced
  5314. */
  5315. function twig_strtr($pattern, $replacements)
  5316. {
  5317. return str_replace(array_keys($replacements), array_values($replacements), $pattern);
  5318. }
  5319. /**
  5320. * Escapes a string.
  5321. *
  5322. * @param Twig_Environment $env A Twig_Environment instance
  5323. * @param string $string The value to be escaped
  5324. * @param string $type The escaping strategy
  5325. * @param string $charset The charset
  5326. */
  5327. function twig_escape_filter(Twig_Environment $env, $string, $type = 'html', $charset = null)
  5328. {
  5329. if (is_object($string) && $string instanceof Twig_Markup) {
  5330. return $string;
  5331. }
  5332. if (!is_string($string) && !(is_object($string) && method_exists($string, '__toString'))) {
  5333. return $string;
  5334. }
  5335. if (null === $charset) {
  5336. $charset = $env->getCharset();
  5337. }
  5338. switch ($type) {
  5339. case 'js':
  5340. // escape all non-alphanumeric characters
  5341. // into their \xHH or \uHHHH representations
  5342. if ('UTF-8' != $charset) {
  5343. $string = _twig_convert_encoding($string, 'UTF-8', $charset);
  5344. }
  5345. if (null === $string = preg_replace_callback('#[^\p{L}\p{N} ]#u', '_twig_escape_js_callback', $string)) {
  5346. throw new Twig_Error_Runtime('The string to escape is not a valid UTF-8 string.');
  5347. }
  5348. if ('UTF-8' != $charset) {
  5349. $string = _twig_convert_encoding($string, $charset, 'UTF-8');
  5350. }
  5351. return $string;
  5352. case 'html':
  5353. return htmlspecialchars($string, ENT_QUOTES, $charset);
  5354. default:
  5355. throw new Twig_Error_Runtime(sprintf('Invalid escape type "%s".', $type));
  5356. }
  5357. }
  5358. /* used internally */
  5359. function twig_escape_filter_is_safe(Twig_Node $filterArgs)
  5360. {
  5361. foreach ($filterArgs as $arg) {
  5362. if ($arg instanceof Twig_Node_Expression_Constant) {
  5363. return array($arg->getAttribute('value'));
  5364. } else {
  5365. return array();
  5366. }
  5367. break;
  5368. }
  5369. return array('html');
  5370. }
  5371. if (function_exists('iconv')) {
  5372. function _twig_convert_encoding($string, $to, $from)
  5373. {
  5374. return iconv($from, $to, $string);
  5375. }
  5376. } elseif (function_exists('mb_convert_encoding')) {
  5377. function _twig_convert_encoding($string, $to, $from)
  5378. {
  5379. return mb_convert_encoding($string, $to, $from);
  5380. }
  5381. } else {
  5382. function _twig_convert_encoding($string, $to, $from)
  5383. {
  5384. throw new Twig_Error_Runtime('No suitable convert encoding function (use UTF-8 as your encoding or install the iconv or mbstring extension).');
  5385. }
  5386. }
  5387. function _twig_escape_js_callback($matches)
  5388. {
  5389. $char = $matches[0];
  5390. // \xHH
  5391. if (!isset($char[1])) {
  5392. return '\\x'.substr('00'.bin2hex($char), -2);
  5393. }
  5394. // \uHHHH
  5395. $char = _twig_convert_encoding($char, 'UTF-16BE', 'UTF-8');
  5396. return '\\u'.substr('0000'.bin2hex($char), -4);
  5397. }
  5398. // add multibyte extensions if possible
  5399. if (function_exists('mb_get_info')) {
  5400. /**
  5401. * Returns the length of a PHP variable.
  5402. *
  5403. * @param Twig_Environment $env A Twig_Environment instance
  5404. * @param mixed $thing A PHP variable
  5405. *
  5406. * @return integer The length of the value
  5407. */
  5408. function twig_length_filter(Twig_Environment $env, $thing)
  5409. {
  5410. return is_scalar($thing) ? mb_strlen($thing, $env->getCharset()) : count($thing);
  5411. }
  5412. /**
  5413. * Converts a string to uppercase.
  5414. *
  5415. * @param Twig_Environment $env A Twig_Environment instance
  5416. * @param string $string A string
  5417. *
  5418. * @return string The uppercased string
  5419. */
  5420. function twig_upper_filter(Twig_Environment $env, $string)
  5421. {
  5422. if (null !== ($charset = $env->getCharset())) {
  5423. return mb_strtoupper($string, $charset);
  5424. }
  5425. return strtoupper($string);
  5426. }
  5427. /**
  5428. * Converts a string to lowercase.
  5429. *
  5430. * @param Twig_Environment $env A Twig_Environment instance
  5431. * @param string $string A string
  5432. *
  5433. * @return string The lowercased string
  5434. */
  5435. function twig_lower_filter(Twig_Environment $env, $string)
  5436. {
  5437. if (null !== ($charset = $env->getCharset())) {
  5438. return mb_strtolower($string, $charset);
  5439. }
  5440. return strtolower($string);
  5441. }
  5442. /**
  5443. * Returns a titlecased string.
  5444. *
  5445. * @param Twig_Environment $env A Twig_Environment instance
  5446. * @param string $string A string
  5447. *
  5448. * @return string The titlecased string
  5449. */
  5450. function twig_title_string_filter(Twig_Environment $env, $string)
  5451. {
  5452. if (null !== ($charset = $env->getCharset())) {
  5453. return mb_convert_case($string, MB_CASE_TITLE, $charset);
  5454. }
  5455. return ucwords(strtolower($string));
  5456. }
  5457. /**
  5458. * Returns a capitalized string.
  5459. *
  5460. * @param Twig_Environment $env A Twig_Environment instance
  5461. * @param string $string A string
  5462. *
  5463. * @return string The capitalized string
  5464. */
  5465. function twig_capitalize_string_filter(Twig_Environment $env, $string)
  5466. {
  5467. if (null !== ($charset = $env->getCharset())) {
  5468. return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset).
  5469. mb_strtolower(mb_substr($string, 1, mb_strlen($string, $charset), $charset), $charset);
  5470. }
  5471. return ucfirst(strtolower($string));
  5472. }
  5473. }
  5474. // and byte fallback
  5475. else
  5476. {
  5477. /**
  5478. * Returns the length of a PHP variable.
  5479. *
  5480. * @param Twig_Environment $env A Twig_Environment instance
  5481. * @param mixed $thing A PHP variable
  5482. *
  5483. * @return integer The length of the value
  5484. */
  5485. function twig_length_filter(Twig_Environment $env, $thing)
  5486. {
  5487. return is_scalar($thing) ? strlen($thing) : count($thing);
  5488. }
  5489. /**
  5490. * Returns a titlecased string.
  5491. *
  5492. * @param Twig_Environment $env A Twig_Environment instance
  5493. * @param string $string A string
  5494. *
  5495. * @return string The titlecased string
  5496. */
  5497. function twig_title_string_filter(Twig_Environment $env, $string)
  5498. {
  5499. return ucwords(strtolower($string));
  5500. }
  5501. /**
  5502. * Returns a capitalized string.
  5503. *
  5504. * @param Twig_Environment $env A Twig_Environment instance
  5505. * @param string $string A string
  5506. *
  5507. * @return string The capitalized string
  5508. */
  5509. function twig_capitalize_string_filter(Twig_Environment $env, $string)
  5510. {
  5511. return ucfirst(strtolower($string));
  5512. }
  5513. }
  5514. /* used internally */
  5515. function twig_ensure_traversable($seq)
  5516. {
  5517. if (is_array($seq) || (is_object($seq) && $seq instanceof Traversable)) {
  5518. return $seq;
  5519. } else {
  5520. return array();
  5521. }
  5522. }
  5523. /**
  5524. * Checks that a variable points to the same memory address than another one.
  5525. *
  5526. * <pre>
  5527. * {% if foo.attribute is sameas(false) %}
  5528. * the foo attribute really is the ``false`` PHP value
  5529. * {% endif %}
  5530. * </pre>
  5531. *
  5532. * @param mixed $value A PHP variable
  5533. * @param mixed $test The PHP variable to test against
  5534. *
  5535. * @return Boolean true if the values are the same, false otherwise
  5536. */
  5537. function twig_test_sameas($value, $test)
  5538. {
  5539. return $value === $test;
  5540. }
  5541. /**
  5542. * Checks that a variable is null.
  5543. *
  5544. * <pre>
  5545. * {{ var is none }}
  5546. * </pre>
  5547. *
  5548. * @param mixed $value a PHP variable.
  5549. *
  5550. * @return Boolean true if the value is null, false otherwise
  5551. */
  5552. function twig_test_none($value)
  5553. {
  5554. return null === $value;
  5555. }
  5556. /**
  5557. * Checks if a variable is divisible by a number.
  5558. *
  5559. * <pre>
  5560. * {% if loop.index is divisibleby(3) %}
  5561. * </pre>
  5562. *
  5563. * @param integer $value A PHP value
  5564. * @param integer $num A number
  5565. *
  5566. * @return Boolean true if the value is divisible by the number, false otherwise
  5567. */
  5568. function twig_test_divisibleby($value, $num)
  5569. {
  5570. return 0 == $value % $num;
  5571. }
  5572. /**
  5573. * Checks if a number is even.
  5574. *
  5575. * <pre>
  5576. * {{ var is even }}
  5577. * </pre>
  5578. *
  5579. * @param integer $value An integer
  5580. *
  5581. * @return Boolean true if the value is even, false otherwise
  5582. */
  5583. function twig_test_even($value)
  5584. {
  5585. return $value % 2 == 0;
  5586. }
  5587. /**
  5588. * Checks if a number is odd.
  5589. *
  5590. * <pre>
  5591. * {{ var is odd }}
  5592. * </pre>
  5593. *
  5594. * @param integer $value An integer
  5595. *
  5596. * @return Boolean true if the value is odd, false otherwise
  5597. */
  5598. function twig_test_odd($value)
  5599. {
  5600. return $value % 2 == 1;
  5601. }
  5602. /**
  5603. * Checks if a variable is the exact same value as a constant.
  5604. *
  5605. * <pre>
  5606. * {% if post.status is constant('Post::PUBLISHED') %}
  5607. * the status attribute is exactly the same as Post::PUBLISHED
  5608. * {% endif %}
  5609. * </pre>
  5610. *
  5611. * @param mixed $value A PHP value
  5612. * @param mixed $constant The constant to test against
  5613. *
  5614. * @return Boolean true if the value is the same as the constant, false otherwise
  5615. */
  5616. function twig_test_constant($value, $constant)
  5617. {
  5618. return constant($constant) === $value;
  5619. }
  5620. /**
  5621. * Checks if a variable is defined in the current context.
  5622. *
  5623. * <pre>
  5624. * {# defined works with variable names #}
  5625. * {% if foo is defined %}
  5626. * {# ... #}
  5627. * {% endif %}
  5628. * </pre>
  5629. *
  5630. * @param mixed $name A PHP variable
  5631. * @param array $context The current context
  5632. *
  5633. * @return Boolean true if the value is defined, false otherwise
  5634. */
  5635. function twig_test_defined($name, $context)
  5636. {
  5637. return array_key_exists($name, $context);
  5638. }
  5639. /**
  5640. * Checks if a variable is empty.
  5641. *
  5642. * <pre>
  5643. * {# evaluates to true if the foo variable is null, false, or the empty string #}
  5644. * {% if foo is empty %}
  5645. * {# ... #}
  5646. * {% endif %}
  5647. * </pre>
  5648. *
  5649. * @param mixed $value A PHP variable
  5650. *
  5651. * @return Boolean true if the value is empty, false otherwise
  5652. */
  5653. function twig_test_empty($value)
  5654. {
  5655. return false === $value || (empty($value) && '0' != $value);
  5656. }
  5657. }
  5658. namespace
  5659. {
  5660. /*
  5661. * This file is part of Twig.
  5662. *
  5663. * (c) 2009 Fabien Potencier
  5664. *
  5665. * For the full copyright and license information, please view the LICENSE
  5666. * file that was distributed with this source code.
  5667. */
  5668. class Twig_Extension_Escaper extends Twig_Extension
  5669. {
  5670. protected $autoescape;
  5671. public function __construct($autoescape = true)
  5672. {
  5673. $this->autoescape = $autoescape;
  5674. }
  5675. /**
  5676. * Returns the token parser instances to add to the existing list.
  5677. *
  5678. * @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
  5679. */
  5680. public function getTokenParsers()
  5681. {
  5682. return array(new Twig_TokenParser_AutoEscape());
  5683. }
  5684. /**
  5685. * Returns the node visitor instances to add to the existing list.
  5686. *
  5687. * @return array An array of Twig_NodeVisitorInterface instances
  5688. */
  5689. public function getNodeVisitors()
  5690. {
  5691. return array(new Twig_NodeVisitor_Escaper());
  5692. }
  5693. /**
  5694. * Returns a list of filters to add to the existing list.
  5695. *
  5696. * @return array An array of filters
  5697. */
  5698. public function getFilters()
  5699. {
  5700. return array(
  5701. 'raw' => new Twig_Filter_Function('twig_raw_filter', array('is_safe' => array('all'))),
  5702. );
  5703. }
  5704. public function isGlobal()
  5705. {
  5706. return $this->autoescape;
  5707. }
  5708. /**
  5709. * Returns the name of the extension.
  5710. *
  5711. * @return string The extension name
  5712. */
  5713. public function getName()
  5714. {
  5715. return 'escaper';
  5716. }
  5717. }
  5718. /**
  5719. * Marks a variable as being safe.
  5720. *
  5721. * @param string $string A PHP variable
  5722. */
  5723. function twig_raw_filter($string)
  5724. {
  5725. return $string;
  5726. }
  5727. }
  5728. namespace
  5729. {
  5730. /*
  5731. * This file is part of Twig.
  5732. *
  5733. * (c) 2010 Fabien Potencier
  5734. *
  5735. * For the full copyright and license information, please view the LICENSE
  5736. * file that was distributed with this source code.
  5737. */
  5738. class Twig_Extension_Optimizer extends Twig_Extension
  5739. {
  5740. protected $optimizers;
  5741. public function __construct($optimizers = -1)
  5742. {
  5743. $this->optimizers = $optimizers;
  5744. }
  5745. /**
  5746. * {@inheritdoc}
  5747. */
  5748. public function getNodeVisitors()
  5749. {
  5750. return array(new Twig_NodeVisitor_Optimizer($this->optimizers));
  5751. }
  5752. /**
  5753. * {@inheritdoc}
  5754. */
  5755. public function getName()
  5756. {
  5757. return 'optimizer';
  5758. }
  5759. }
  5760. }
  5761. namespace
  5762. {
  5763. /*
  5764. * This file is part of Twig.
  5765. *
  5766. * (c) 2009 Fabien Potencier
  5767. *
  5768. * For the full copyright and license information, please view the LICENSE
  5769. * file that was distributed with this source code.
  5770. */
  5771. /**
  5772. * Interface all loaders must implement.
  5773. *
  5774. * @package twig
  5775. * @author Fabien Potencier <fabien@symfony.com>
  5776. */
  5777. interface Twig_LoaderInterface
  5778. {
  5779. /**
  5780. * Gets the source code of a template, given its name.
  5781. *
  5782. * @param string $name The name of the template to load
  5783. *
  5784. * @return string The template source code
  5785. */
  5786. function getSource($name);
  5787. /**
  5788. * Gets the cache key to use for the cache for a given template name.
  5789. *
  5790. * @param string $name The name of the template to load
  5791. *
  5792. * @return string The cache key
  5793. */
  5794. function getCacheKey($name);
  5795. /**
  5796. * Returns true if the template is still fresh.
  5797. *
  5798. * @param string $name The template name
  5799. * @param timestamp $time The last modification time of the cached template
  5800. */
  5801. function isFresh($name, $time);
  5802. }
  5803. }
  5804. namespace
  5805. {
  5806. /*
  5807. * This file is part of Twig.
  5808. *
  5809. * (c) 2010 Fabien Potencier
  5810. *
  5811. * For the full copyright and license information, please view the LICENSE
  5812. * file that was distributed with this source code.
  5813. */
  5814. /**
  5815. * Marks a content as safe.
  5816. *
  5817. * @package twig
  5818. * @author Fabien Potencier <fabien@symfony.com>
  5819. */
  5820. class Twig_Markup
  5821. {
  5822. protected $content;
  5823. public function __construct($content)
  5824. {
  5825. $this->content = (string) $content;
  5826. }
  5827. public function __toString()
  5828. {
  5829. return $this->content;
  5830. }
  5831. }
  5832. }
  5833. namespace
  5834. {
  5835. /*
  5836. * This file is part of Twig.
  5837. *
  5838. * (c) 2009 Fabien Potencier
  5839. *
  5840. * For the full copyright and license information, please view the LICENSE
  5841. * file that was distributed with this source code.
  5842. */
  5843. /**
  5844. * Interface implemented by all compiled templates.
  5845. *
  5846. * @package twig
  5847. * @author Fabien Potencier <fabien@symfony.com>
  5848. */
  5849. interface Twig_TemplateInterface
  5850. {
  5851. const ANY_CALL = 'any';
  5852. const ARRAY_CALL = 'array';
  5853. const METHOD_CALL = 'method';
  5854. /**
  5855. * Renders the template with the given context and returns it as string.
  5856. *
  5857. * @param array $context An array of parameters to pass to the template
  5858. *
  5859. * @return string The rendered template
  5860. */
  5861. function render(array $context);
  5862. /**
  5863. * Displays the template with the given context.
  5864. *
  5865. * @param array $context An array of parameters to pass to the template
  5866. * @param array $blocks An array of blocks to pass to the template
  5867. */
  5868. function display(array $context, array $blocks = array());
  5869. /**
  5870. * Returns the bound environment for this template.
  5871. *
  5872. * @return Twig_Environment The current environment
  5873. */
  5874. function getEnvironment();
  5875. }
  5876. }
  5877. namespace
  5878. {
  5879. /*
  5880. * This file is part of Twig.
  5881. *
  5882. * (c) 2009 Fabien Potencier
  5883. * (c) 2009 Armin Ronacher
  5884. *
  5885. * For the full copyright and license information, please view the LICENSE
  5886. * file that was distributed with this source code.
  5887. */
  5888. /**
  5889. * Default base class for compiled templates.
  5890. *
  5891. * @package twig
  5892. * @author Fabien Potencier <fabien@symfony.com>
  5893. */
  5894. abstract class Twig_Template implements Twig_TemplateInterface
  5895. {
  5896. static protected $cache = array();
  5897. protected $env;
  5898. protected $blocks;
  5899. /**
  5900. * Constructor.
  5901. *
  5902. * @param Twig_Environment $env A Twig_Environment instance
  5903. */
  5904. public function __construct(Twig_Environment $env)
  5905. {
  5906. $this->env = $env;
  5907. $this->blocks = array();
  5908. }
  5909. /**
  5910. * Returns the template name.
  5911. *
  5912. * @return string The template name
  5913. */
  5914. public function getTemplateName()
  5915. {
  5916. return null;
  5917. }
  5918. /**
  5919. * Returns the Twig environment.
  5920. *
  5921. * @return Twig_Environment The Twig environment
  5922. */
  5923. public function getEnvironment()
  5924. {
  5925. return $this->env;
  5926. }
  5927. /**
  5928. * Returns the parent template.
  5929. *
  5930. * @return Twig_TemplateInterface|false The parent template or false if there is no parent
  5931. */
  5932. public function getParent(array $context)
  5933. {
  5934. return false;
  5935. }
  5936. /**
  5937. * Displays a parent block.
  5938. *
  5939. * @param string $name The block name to display from the parent
  5940. * @param array $context The context
  5941. * @param array $blocks The current set of blocks
  5942. */
  5943. public function displayParentBlock($name, array $context, array $blocks = array())
  5944. {
  5945. if (false !== $parent = $this->getParent($context)) {
  5946. $parent->displayBlock($name, $context, $blocks);
  5947. } else {
  5948. throw new Twig_Error_Runtime('This template has no parent', -1, $this->getTemplateName());
  5949. }
  5950. }
  5951. /**
  5952. * Displays a block.
  5953. *
  5954. * @param string $name The block name to display
  5955. * @param array $context The context
  5956. * @param array $blocks The current set of blocks
  5957. */
  5958. public function displayBlock($name, array $context, array $blocks = array())
  5959. {
  5960. if (isset($blocks[$name])) {
  5961. $b = $blocks;
  5962. unset($b[$name]);
  5963. call_user_func($blocks[$name], $context, $b);
  5964. } elseif (isset($this->blocks[$name])) {
  5965. call_user_func($this->blocks[$name], $context, $blocks);
  5966. } elseif (false !== $parent = $this->getParent($context)) {
  5967. $parent->displayBlock($name, $context, array_merge($this->blocks, $blocks));
  5968. }
  5969. }
  5970. /**
  5971. * Renders a parent block.
  5972. *
  5973. * @param string $name The block name to render from the parent
  5974. * @param array $context The context
  5975. * @param array $blocks The current set of blocks
  5976. *
  5977. * @return string The rendered block
  5978. */
  5979. public function renderParentBlock($name, array $context, array $blocks = array())
  5980. {
  5981. ob_start();
  5982. $this->displayParentBlock($name, $context, $blocks);
  5983. return ob_get_clean();
  5984. }
  5985. /**
  5986. * Renders a block.
  5987. *
  5988. * @param string $name The block name to render
  5989. * @param array $context The context
  5990. * @param array $blocks The current set of blocks
  5991. *
  5992. * @return string The rendered block
  5993. */
  5994. public function renderBlock($name, array $context, array $blocks = array())
  5995. {
  5996. ob_start();
  5997. $this->displayBlock($name, $context, $blocks);
  5998. return ob_get_clean();
  5999. }
  6000. /**
  6001. * Returns whether a block exists or not.
  6002. *
  6003. * @param string $name The block name
  6004. *
  6005. * @return Boolean true if the block exists, false otherwise
  6006. */
  6007. public function hasBlock($name)
  6008. {
  6009. return isset($this->blocks[$name]);
  6010. }
  6011. /**
  6012. * Returns all block names.
  6013. *
  6014. * @return array An array of block names
  6015. */
  6016. public function getBlockNames()
  6017. {
  6018. return array_keys($this->blocks);
  6019. }
  6020. /**
  6021. * Returns all blocks.
  6022. *
  6023. * @return array An array of blocks
  6024. */
  6025. public function getBlocks()
  6026. {
  6027. return $this->blocks;
  6028. }
  6029. /**
  6030. * Displays the template with the given context.
  6031. *
  6032. * @param array $context An array of parameters to pass to the template
  6033. * @param array $blocks An array of blocks to pass to the template
  6034. */
  6035. public function display(array $context, array $blocks = array())
  6036. {
  6037. try {
  6038. $this->doDisplay($context, $blocks);
  6039. } catch (Twig_Error $e) {
  6040. throw $e;
  6041. } catch (Exception $e) {
  6042. throw new Twig_Error_Runtime(sprintf('An exception has been thrown during the rendering of a template ("%s").', $e->getMessage()), -1, null, $e);
  6043. }
  6044. }
  6045. /**
  6046. * Renders the template with the given context and returns it as string.
  6047. *
  6048. * @param array $context An array of parameters to pass to the template
  6049. *
  6050. * @return string The rendered template
  6051. */
  6052. public function render(array $context)
  6053. {
  6054. $level = ob_get_level();
  6055. ob_start();
  6056. try {
  6057. $this->display($context);
  6058. } catch (Exception $e) {
  6059. while (ob_get_level() > $level) {
  6060. ob_end_clean();
  6061. }
  6062. throw $e;
  6063. }
  6064. return ob_get_clean();
  6065. }
  6066. /**
  6067. * Auto-generated method to display the template with the given context.
  6068. *
  6069. * @param array $context An array of parameters to pass to the template
  6070. * @param array $blocks An array of blocks to pass to the template
  6071. */
  6072. abstract protected function doDisplay(array $context, array $blocks = array());
  6073. /**
  6074. * Returns a variable from the context.
  6075. *
  6076. * @param array $context The context
  6077. * @param string $item The variable to return from the context
  6078. *
  6079. * @return The content of the context variable
  6080. *
  6081. * @throws Twig_Error_Runtime if the variable does not exist and Twig is running in strict mode
  6082. */
  6083. protected function getContext($context, $item)
  6084. {
  6085. if (!array_key_exists($item, $context)) {
  6086. if (!$this->env->isStrictVariables()) {
  6087. return null;
  6088. }
  6089. throw new Twig_Error_Runtime(sprintf('Variable "%s" does not exist', $item));
  6090. }
  6091. return $context[$item];
  6092. }
  6093. /**
  6094. * Returns the attribute value for a given array/object.
  6095. *
  6096. * @param mixed $object The object or array from where to get the item
  6097. * @param mixed $item The item to get from the array or object
  6098. * @param array $arguments An array of arguments to pass if the item is an object method
  6099. * @param string $type The type of attribute (@see Twig_TemplateInterface)
  6100. * @param Boolean $isDefinedTest Whether this is only a defined check
  6101. */
  6102. protected function getAttribute($object, $item, array $arguments = array(), $type = Twig_TemplateInterface::ANY_CALL, $isDefinedTest = false)
  6103. {
  6104. // array
  6105. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  6106. if ((is_array($object) && array_key_exists($item, $object))
  6107. || ($object instanceof ArrayAccess && isset($object[$item]))
  6108. ) {
  6109. if ($isDefinedTest) {
  6110. return true;
  6111. }
  6112. return $object[$item];
  6113. }
  6114. if (Twig_TemplateInterface::ARRAY_CALL === $type) {
  6115. if ($isDefinedTest) {
  6116. return false;
  6117. }
  6118. if (!$this->env->isStrictVariables()) {
  6119. return null;
  6120. }
  6121. if (is_object($object)) {
  6122. throw new Twig_Error_Runtime(sprintf('Key "%s" in object (with ArrayAccess) of type "%s" does not exist', $item, get_class($object)));
  6123. // array
  6124. } else {
  6125. throw new Twig_Error_Runtime(sprintf('Key "%s" for array with keys "%s" does not exist', $item, implode(', ', array_keys($object))));
  6126. }
  6127. }
  6128. }
  6129. if (!is_object($object)) {
  6130. if ($isDefinedTest) {
  6131. return false;
  6132. }
  6133. if (!$this->env->isStrictVariables()) {
  6134. return null;
  6135. }
  6136. throw new Twig_Error_Runtime(sprintf('Item "%s" for "%s" does not exist', $item, $object));
  6137. }
  6138. // get some information about the object
  6139. $class = get_class($object);
  6140. if (!isset(self::$cache[$class])) {
  6141. $r = new ReflectionClass($class);
  6142. self::$cache[$class] = array('methods' => array(), 'properties' => array());
  6143. foreach ($r->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
  6144. self::$cache[$class]['methods'][strtolower($method->getName())] = true;
  6145. }
  6146. foreach ($r->getProperties(ReflectionProperty::IS_PUBLIC) as $property) {
  6147. self::$cache[$class]['properties'][$property->getName()] = true;
  6148. }
  6149. }
  6150. // object property
  6151. if (Twig_TemplateInterface::METHOD_CALL !== $type) {
  6152. if (isset(self::$cache[$class]['properties'][$item])
  6153. || isset($object->$item) || array_key_exists($item, $object)
  6154. ) {
  6155. if ($isDefinedTest) {
  6156. return true;
  6157. }
  6158. if ($this->env->hasExtension('sandbox')) {
  6159. $this->env->getExtension('sandbox')->checkPropertyAllowed($object, $item);
  6160. }
  6161. return $object->$item;
  6162. }
  6163. }
  6164. // object method
  6165. $lcItem = strtolower($item);
  6166. if (isset(self::$cache[$class]['methods'][$lcItem])) {
  6167. $method = $item;
  6168. } elseif (isset(self::$cache[$class]['methods']['get'.$lcItem])) {
  6169. $method = 'get'.$item;
  6170. } elseif (isset(self::$cache[$class]['methods']['is'.$lcItem])) {
  6171. $method = 'is'.$item;
  6172. } elseif (isset(self::$cache[$class]['methods']['__call'])) {
  6173. $method = $item;
  6174. } else {
  6175. if ($isDefinedTest) {
  6176. return false;
  6177. }
  6178. if (!$this->env->isStrictVariables()) {
  6179. return null;
  6180. }
  6181. throw new Twig_Error_Runtime(sprintf('Method "%s" for object "%s" does not exist', $item, get_class($object)));
  6182. }
  6183. if ($isDefinedTest) {
  6184. return true;
  6185. }
  6186. if ($this->env->hasExtension('sandbox')) {
  6187. $this->env->getExtension('sandbox')->checkMethodAllowed($object, $method);
  6188. }
  6189. $ret = call_user_func_array(array($object, $method), $arguments);
  6190. if ($object instanceof Twig_TemplateInterface) {
  6191. return new Twig_Markup($ret);
  6192. }
  6193. return $ret;
  6194. }
  6195. }
  6196. }
  6197. namespace Monolog\Formatter
  6198. {
  6199. interface FormatterInterface
  6200. {
  6201. function format(array $record);
  6202. function formatBatch(array $records);
  6203. }
  6204. }
  6205. namespace Monolog\Formatter
  6206. {
  6207. use Monolog\Logger;
  6208. class LineFormatter implements FormatterInterface
  6209. {
  6210. const SIMPLE_FORMAT = "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n";
  6211. const SIMPLE_DATE = "Y-m-d H:i:s";
  6212. protected $format;
  6213. protected $dateFormat;
  6214. public function __construct($format = null, $dateFormat = null)
  6215. {
  6216. $this->format = $format ?: static::SIMPLE_FORMAT;
  6217. $this->dateFormat = $dateFormat ?: static::SIMPLE_DATE;
  6218. }
  6219. public function format(array $record)
  6220. {
  6221. $vars = $record;
  6222. $vars['datetime'] = $vars['datetime']->format($this->dateFormat);
  6223. $output = $this->format;
  6224. foreach ($vars['extra'] as $var => $val) {
  6225. if (false !== strpos($output, '%extra.'.$var.'%')) {
  6226. $output = str_replace('%extra.'.$var.'%', $this->convertToString($val), $output);
  6227. unset($vars['extra'][$var]);
  6228. }
  6229. }
  6230. foreach ($vars as $var => $val) {
  6231. $output = str_replace('%'.$var.'%', $this->convertToString($val), $output);
  6232. }
  6233. return $output;
  6234. }
  6235. public function formatBatch(array $records)
  6236. {
  6237. $message = '';
  6238. foreach ($records as $record) {
  6239. $message .= $this->format($record);
  6240. }
  6241. return $message;
  6242. }
  6243. protected function convertToString($data)
  6244. {
  6245. if (null === $data || is_scalar($data)) {
  6246. return (string) $data;
  6247. }
  6248. return stripslashes(json_encode($this->normalize($data)));
  6249. }
  6250. protected function normalize($data)
  6251. {
  6252. if (null === $data || is_scalar($data)) {
  6253. return $data;
  6254. }
  6255. if (is_array($data) || $data instanceof \Traversable) {
  6256. $normalized = array();
  6257. foreach ($data as $key => $value) {
  6258. $normalized[$key] = $this->normalize($value);
  6259. }
  6260. return $normalized;
  6261. }
  6262. if (is_resource($data)) {
  6263. return '[resource]';
  6264. }
  6265. return sprintf("[object] (%s: %s)", get_class($data), json_encode($data));
  6266. }
  6267. }
  6268. }
  6269. namespace Monolog\Handler
  6270. {
  6271. use Monolog\Formatter\FormatterInterface;
  6272. interface HandlerInterface
  6273. {
  6274. function isHandling(array $record);
  6275. function handle(array $record);
  6276. function handleBatch(array $records);
  6277. function pushProcessor($callback);
  6278. function popProcessor();
  6279. function setFormatter(FormatterInterface $formatter);
  6280. function getFormatter();
  6281. }
  6282. }
  6283. namespace Monolog\Handler
  6284. {
  6285. use Monolog\Logger;
  6286. use Monolog\Formatter\FormatterInterface;
  6287. use Monolog\Formatter\LineFormatter;
  6288. abstract class AbstractHandler implements HandlerInterface
  6289. {
  6290. protected $level = Logger::DEBUG;
  6291. protected $bubble = false;
  6292. protected $formatter;
  6293. protected $processors = array();
  6294. public function __construct($level = Logger::DEBUG, $bubble = true)
  6295. {
  6296. $this->level = $level;
  6297. $this->bubble = $bubble;
  6298. }
  6299. public function isHandling(array $record)
  6300. {
  6301. return $record['level'] >= $this->level;
  6302. }
  6303. public function handleBatch(array $records)
  6304. {
  6305. foreach ($records as $record) {
  6306. $this->handle($record);
  6307. }
  6308. }
  6309. public function close()
  6310. {
  6311. }
  6312. public function pushProcessor($callback)
  6313. {
  6314. if (!is_callable($callback)) {
  6315. throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
  6316. }
  6317. array_unshift($this->processors, $callback);
  6318. }
  6319. public function popProcessor()
  6320. {
  6321. if (!$this->processors) {
  6322. throw new \LogicException('You tried to pop from an empty processor stack.');
  6323. }
  6324. return array_shift($this->processors);
  6325. }
  6326. public function setFormatter(FormatterInterface $formatter)
  6327. {
  6328. $this->formatter = $formatter;
  6329. }
  6330. public function getFormatter()
  6331. {
  6332. if (!$this->formatter) {
  6333. $this->formatter = $this->getDefaultFormatter();
  6334. }
  6335. return $this->formatter;
  6336. }
  6337. public function setLevel($level)
  6338. {
  6339. $this->level = $level;
  6340. }
  6341. public function getLevel()
  6342. {
  6343. return $this->level;
  6344. }
  6345. public function setBubble($bubble)
  6346. {
  6347. $this->bubble = $bubble;
  6348. }
  6349. public function getBubble()
  6350. {
  6351. return $this->bubble;
  6352. }
  6353. public function __destruct()
  6354. {
  6355. $this->close();
  6356. }
  6357. protected function getDefaultFormatter()
  6358. {
  6359. return new LineFormatter();
  6360. }
  6361. }
  6362. }
  6363. namespace Monolog\Handler
  6364. {
  6365. use Monolog\Logger;
  6366. use Monolog\Formatter\FormatterInterface;
  6367. use Monolog\Formatter\LineFormatter;
  6368. abstract class AbstractProcessingHandler extends AbstractHandler
  6369. {
  6370. public function handle(array $record)
  6371. {
  6372. if ($record['level'] < $this->level) {
  6373. return false;
  6374. }
  6375. $record = $this->processRecord($record);
  6376. $record['formatted'] = $this->getFormatter()->format($record);
  6377. $this->write($record);
  6378. return false === $this->bubble;
  6379. }
  6380. abstract protected function write(array $record);
  6381. protected function processRecord(array $record)
  6382. {
  6383. if ($this->processors) {
  6384. foreach ($this->processors as $processor) {
  6385. $record = call_user_func($processor, $record);
  6386. }
  6387. }
  6388. return $record;
  6389. }
  6390. }
  6391. }
  6392. namespace Monolog\Handler
  6393. {
  6394. use Monolog\Formatter\SimpleFormatter;
  6395. use Monolog\Logger;
  6396. class StreamHandler extends AbstractProcessingHandler
  6397. {
  6398. protected $stream;
  6399. protected $url;
  6400. public function __construct($stream, $level = Logger::DEBUG, $bubble = true)
  6401. {
  6402. parent::__construct($level, $bubble);
  6403. if (is_resource($stream)) {
  6404. $this->stream = $stream;
  6405. } else {
  6406. $this->url = $stream;
  6407. }
  6408. }
  6409. public function close()
  6410. {
  6411. if (is_resource($this->stream)) {
  6412. fclose($this->stream);
  6413. }
  6414. $this->stream = null;
  6415. }
  6416. protected function write(array $record)
  6417. {
  6418. if (null === $this->stream) {
  6419. if (!$this->url) {
  6420. throw new \LogicException('Missing stream url, the stream can not be opened. This may be caused by a premature call to close().');
  6421. }
  6422. $this->stream = @fopen($this->url, 'a');
  6423. if (!is_resource($this->stream)) {
  6424. $this->stream = null;
  6425. throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened; it may be invalid or not writable.', $this->url));
  6426. }
  6427. }
  6428. fwrite($this->stream, (string) $record['formatted']);
  6429. }
  6430. }
  6431. }
  6432. namespace Monolog\Handler
  6433. {
  6434. use Monolog\Logger;
  6435. class FingersCrossedHandler extends AbstractHandler
  6436. {
  6437. protected $handler;
  6438. protected $actionLevel;
  6439. protected $buffering = true;
  6440. protected $bufferSize;
  6441. protected $buffer = array();
  6442. protected $stopBuffering;
  6443. public function __construct($handler, $actionLevel = Logger::WARNING, $bufferSize = 0, $bubble = true, $stopBuffering = true)
  6444. {
  6445. $this->handler = $handler;
  6446. $this->actionLevel = $actionLevel;
  6447. $this->bufferSize = $bufferSize;
  6448. $this->bubble = $bubble;
  6449. $this->stopBuffering = $stopBuffering;
  6450. }
  6451. public function isHandling(array $record)
  6452. {
  6453. return true;
  6454. }
  6455. public function handle(array $record)
  6456. {
  6457. if ($this->buffering) {
  6458. $this->buffer[] = $record;
  6459. if ($this->bufferSize > 0 && count($this->buffer) > $this->bufferSize) {
  6460. array_shift($this->buffer);
  6461. }
  6462. if ($record['level'] >= $this->actionLevel) {
  6463. if ($this->stopBuffering) {
  6464. $this->buffering = false;
  6465. }
  6466. if (!$this->handler instanceof HandlerInterface) {
  6467. $this->handler = call_user_func($this->handler, $record, $this);
  6468. }
  6469. if (!$this->handler instanceof HandlerInterface) {
  6470. throw new \RuntimeException("The factory callback should return a HandlerInterface");
  6471. }
  6472. $this->handler->handleBatch($this->buffer);
  6473. $this->buffer = array();
  6474. }
  6475. } else {
  6476. $this->handler->handle($record);
  6477. }
  6478. return false === $this->bubble;
  6479. }
  6480. public function reset()
  6481. {
  6482. $this->buffering = true;
  6483. }
  6484. }
  6485. }
  6486. namespace Monolog
  6487. {
  6488. use Monolog\Handler\HandlerInterface;
  6489. use Monolog\Handler\StreamHandler;
  6490. class Logger
  6491. {
  6492. const DEBUG = 100;
  6493. const INFO = 200;
  6494. const WARNING = 300;
  6495. const ERROR = 400;
  6496. const CRITICAL = 500;
  6497. const ALERT = 550;
  6498. protected static $levels = array(
  6499. 100 => 'DEBUG',
  6500. 200 => 'INFO',
  6501. 300 => 'WARNING',
  6502. 400 => 'ERROR',
  6503. 500 => 'CRITICAL',
  6504. 550 => 'ALERT',
  6505. );
  6506. protected $name;
  6507. protected $handlers = array();
  6508. protected $processors = array();
  6509. public function __construct($name)
  6510. {
  6511. $this->name = $name;
  6512. }
  6513. public function getName() {
  6514. return $this->name;
  6515. }
  6516. public function pushHandler(HandlerInterface $handler)
  6517. {
  6518. array_unshift($this->handlers, $handler);
  6519. }
  6520. public function popHandler()
  6521. {
  6522. if (!$this->handlers) {
  6523. throw new \LogicException('You tried to pop from an empty handler stack.');
  6524. }
  6525. return array_shift($this->handlers);
  6526. }
  6527. public function pushProcessor($callback)
  6528. {
  6529. if (!is_callable($callback)) {
  6530. throw new \InvalidArgumentException('Processors must be valid callables (callback or object with an __invoke method), '.var_export($callback, true).' given');
  6531. }
  6532. array_unshift($this->processors, $callback);
  6533. }
  6534. public function popProcessor()
  6535. {
  6536. if (!$this->processors) {
  6537. throw new \LogicException('You tried to pop from an empty processor stack.');
  6538. }
  6539. return array_shift($this->processors);
  6540. }
  6541. public function addRecord($level, $message, array $context = array())
  6542. {
  6543. if (!$this->handlers) {
  6544. $this->pushHandler(new StreamHandler('php://stderr', self::DEBUG));
  6545. }
  6546. $record = array(
  6547. 'message' => (string) $message,
  6548. 'context' => $context,
  6549. 'level' => $level,
  6550. 'level_name' => self::getLevelName($level),
  6551. 'channel' => $this->name,
  6552. 'datetime' => new \DateTime(),
  6553. 'extra' => array(),
  6554. );
  6555. $handlerKey = null;
  6556. foreach ($this->handlers as $key => $handler) {
  6557. if ($handler->isHandling($record)) {
  6558. $handlerKey = $key;
  6559. break;
  6560. }
  6561. }
  6562. if (null === $handlerKey) {
  6563. return false;
  6564. }
  6565. foreach ($this->processors as $processor) {
  6566. $record = call_user_func($processor, $record);
  6567. }
  6568. while (isset($this->handlers[$handlerKey]) &&
  6569. false === $this->handlers[$handlerKey]->handle($record)) {
  6570. $handlerKey++;
  6571. }
  6572. return true;
  6573. }
  6574. public function addDebug($message, array $context = array())
  6575. {
  6576. return $this->addRecord(self::DEBUG, $message, $context);
  6577. }
  6578. public function addInfo($message, array $context = array())
  6579. {
  6580. return $this->addRecord(self::INFO, $message, $context);
  6581. }
  6582. public function addWarning($message, array $context = array())
  6583. {
  6584. return $this->addRecord(self::WARNING, $message, $context);
  6585. }
  6586. public function addError($message, array $context = array())
  6587. {
  6588. return $this->addRecord(self::ERROR, $message, $context);
  6589. }
  6590. public function addCritical($message, array $context = array())
  6591. {
  6592. return $this->addRecord(self::CRITICAL, $message, $context);
  6593. }
  6594. public function addAlert($message, array $context = array())
  6595. {
  6596. return $this->addRecord(self::ALERT, $message, $context);
  6597. }
  6598. public static function getLevelName($level)
  6599. {
  6600. return self::$levels[$level];
  6601. }
  6602. public function debug($message, array $context = array())
  6603. {
  6604. return $this->addRecord(self::DEBUG, $message, $context);
  6605. }
  6606. public function info($message, array $context = array())
  6607. {
  6608. return $this->addRecord(self::INFO, $message, $context);
  6609. }
  6610. public function notice($message, array $context = array())
  6611. {
  6612. return $this->addRecord(self::INFO, $message, $context);
  6613. }
  6614. public function warn($message, array $context = array())
  6615. {
  6616. return $this->addRecord(self::WARNING, $message, $context);
  6617. }
  6618. public function err($message, array $context = array())
  6619. {
  6620. return $this->addRecord(self::ERROR, $message, $context);
  6621. }
  6622. public function crit($message, array $context = array())
  6623. {
  6624. return $this->addRecord(self::CRITICAL, $message, $context);
  6625. }
  6626. public function alert($message, array $context = array())
  6627. {
  6628. return $this->addRecord(self::ALERT, $message, $context);
  6629. }
  6630. public function emerg($message, array $context = array())
  6631. {
  6632. return $this->addRecord(self::ALERT, $message, $context);
  6633. }
  6634. }
  6635. }
  6636. namespace Symfony\Bridge\Monolog
  6637. {
  6638. use Monolog\Logger as BaseLogger;
  6639. use Symfony\Component\HttpKernel\Log\LoggerInterface;
  6640. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  6641. class Logger extends BaseLogger implements LoggerInterface, DebugLoggerInterface
  6642. {
  6643. public function getLogs()
  6644. {
  6645. if ($logger = $this->getDebugLogger()) {
  6646. return $logger->getLogs();
  6647. }
  6648. }
  6649. public function countErrors()
  6650. {
  6651. if ($logger = $this->getDebugLogger()) {
  6652. return $logger->countErrors();
  6653. }
  6654. }
  6655. private function getDebugLogger()
  6656. {
  6657. foreach ($this->handlers as $handler) {
  6658. if ($handler instanceof DebugLoggerInterface) {
  6659. return $handler;
  6660. }
  6661. }
  6662. }
  6663. }
  6664. }
  6665. namespace Symfony\Bridge\Monolog\Handler
  6666. {
  6667. use Monolog\Logger;
  6668. use Monolog\Handler\TestHandler;
  6669. use Symfony\Component\HttpKernel\Log\DebugLoggerInterface;
  6670. class DebugHandler extends TestHandler implements DebugLoggerInterface
  6671. {
  6672. public function getLogs()
  6673. {
  6674. $records = array();
  6675. foreach ($this->records as $record) {
  6676. $records[] = array(
  6677. 'timestamp' => $record['datetime']->getTimestamp(),
  6678. 'message' => $record['message'],
  6679. 'priority' => $record['level'],
  6680. 'priorityName' => $record['level_name'],
  6681. 'context' => $record['context'],
  6682. );
  6683. }
  6684. return $records;
  6685. }
  6686. public function countErrors()
  6687. {
  6688. $cnt = 0;
  6689. foreach (array(Logger::ERROR, Logger::CRITICAL, Logger::ALERT) as $level) {
  6690. if (isset($this->recordsByLevel[$level])) {
  6691. $cnt += count($this->recordsByLevel[$level]);
  6692. }
  6693. }
  6694. return $cnt;
  6695. }
  6696. }
  6697. }
  6698. namespace JMS\SecurityExtraBundle\Controller
  6699. {
  6700. use Doctrine\Common\Annotations\Reader;
  6701. use Symfony\Component\DependencyInjection\ContainerInterface;
  6702. use JMS\SecurityExtraBundle\Metadata\Driver\AnnotationConverter;
  6703. use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
  6704. use JMS\SecurityExtraBundle\Security\Authorization\Interception\MethodInvocation;
  6705. use JMS\SecurityExtraBundle\Annotation\Secure;
  6706. use JMS\SecurityExtraBundle\Metadata\Driver\AnnotationReader;
  6707. use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
  6708. class ControllerListener
  6709. {
  6710. private $reader;
  6711. private $converter;
  6712. private $container;
  6713. public function __construct(ContainerInterface $container, Reader $reader)
  6714. {
  6715. $this->container = $container;
  6716. $this->reader = $reader;
  6717. $this->converter = new AnnotationConverter();
  6718. }
  6719. public function onCoreController(FilterControllerEvent $event)
  6720. {
  6721. if (!is_array($controller = $event->getController())) {
  6722. return;
  6723. }
  6724. $method = new MethodInvocation($controller[0], $controller[1], $controller[0]);
  6725. if (!$annotations = $this->reader->getMethodAnnotations($method)) {
  6726. return;
  6727. }
  6728. if (null === $metadata = $this->converter->convertMethodAnnotations($method, $annotations)) {
  6729. return;
  6730. }
  6731. $jmsSecurityExtra__metadata = $metadata->getAsArray();
  6732. $closureCode = 'return function(';
  6733. $params = $paramNames = array();
  6734. foreach ($method->getParameters() as $param) {
  6735. $name = $param->getName();
  6736. $paramNames[] = '$'.$name;
  6737. $parameter = '';
  6738. if (null !== $class = $param->getClass()) {
  6739. $parameter .= '\\'.$class->getName().' ';
  6740. } else if ($param->isArray()) {
  6741. $parameter .= 'array ';
  6742. }
  6743. $parameter .= '$'.$name;
  6744. if ($param->isDefaultValueAvailable()) {
  6745. $parameter .= ' = '.var_export($param->getDefaultValue(), true);
  6746. }
  6747. $params[] = $parameter;
  6748. }
  6749. $params = implode(', ', $params);
  6750. $closureCode .= $params.') ';
  6751. $jmsSecurityExtra__interceptor = $this->container->get('security.access.method_interceptor');
  6752. $jmsSecurityExtra__method = $method;
  6753. $closureCode .= 'use ($jmsSecurityExtra__metadata, $jmsSecurityExtra__interceptor, $jmsSecurityExtra__method) {';
  6754. $closureCode .= '$jmsSecurityExtra__method->setArguments(array('.implode(', ', $paramNames).'));';
  6755. $closureCode .= 'return $jmsSecurityExtra__interceptor->invoke($jmsSecurityExtra__method, $jmsSecurityExtra__metadata);';
  6756. $closureCode .= '};';
  6757. $event->setController(eval($closureCode));
  6758. }
  6759. }
  6760. }
  6761. namespace JMS\SecurityExtraBundle\Metadata\Driver
  6762. {
  6763. use JMS\SecurityExtraBundle\Annotation\RunAs;
  6764. use JMS\SecurityExtraBundle\Annotation\SatisfiesParentSecurityPolicy;
  6765. use JMS\SecurityExtraBundle\Annotation\SecureReturn;
  6766. use JMS\SecurityExtraBundle\Annotation\SecureParam;
  6767. use JMS\SecurityExtraBundle\Annotation\Secure;
  6768. use JMS\SecurityExtraBundle\Metadata\MethodMetadata;
  6769. class AnnotationConverter
  6770. {
  6771. public function convertMethodAnnotations(\ReflectionMethod $method, array $annotations)
  6772. {
  6773. $parameters = array();
  6774. foreach ($method->getParameters() as $index => $parameter) {
  6775. $parameters[$parameter->getName()] = $index;
  6776. }
  6777. $methodMetadata = new MethodMetadata($method->getDeclaringClass()->getName(), $method->getName());
  6778. $hasSecurityMetadata = false;
  6779. foreach ($annotations as $annotation) {
  6780. if ($annotation instanceof Secure) {
  6781. $methodMetadata->roles = $annotation->roles;
  6782. $hasSecurityMetadata = true;
  6783. } else if ($annotation instanceof SecureParam) {
  6784. if (!isset($parameters[$annotation->name])) {
  6785. throw new \InvalidArgumentException(sprintf('The parameter "%s" does not exist for method "%s".', $annotation->name, $method->getName()));
  6786. }
  6787. $methodMetadata->addParamPermissions($parameters[$annotation->name], $annotation->permissions);
  6788. $hasSecurityMetadata = true;
  6789. } else if ($annotation instanceof SecureReturn) {
  6790. $methodMetadata->returnPermissions = $annotation->permissions;
  6791. $hasSecurityMetadata = true;
  6792. } else if ($annotation instanceof SatisfiesParentSecurityPolicy) {
  6793. $methodMetadata->satisfiesParentSecurityPolicy = true;
  6794. $hasSecurityMetadata = true;
  6795. } else if ($annotation instanceof RunAs) {
  6796. $methodMetadata->runAsRoles = $annotation->roles;
  6797. $hasSecurityMetadata = true;
  6798. }
  6799. }
  6800. return $hasSecurityMetadata ? $methodMetadata : null;
  6801. }
  6802. }}
  6803. namespace JMS\SecurityExtraBundle\Security\Authorization\Interception
  6804. {
  6805. class MethodInvocation extends \ReflectionMethod
  6806. {
  6807. private $arguments;
  6808. private $object;
  6809. public function __construct($class, $name, $object, array $arguments = array())
  6810. {
  6811. parent::__construct($class, $name);
  6812. if (!is_object($object)) {
  6813. throw new \InvalidArgumentException('$object must be an object.');
  6814. }
  6815. $this->arguments = $arguments;
  6816. $this->object = $object;
  6817. }
  6818. public function setArguments(array $arguments)
  6819. {
  6820. $this->arguments = $arguments;
  6821. }
  6822. public function getArguments()
  6823. {
  6824. return $this->arguments;
  6825. }
  6826. public function getThis()
  6827. {
  6828. return $this->object;
  6829. }
  6830. }}