composer.phar 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834
  1. #!/usr/bin/env php
  2. <?php
  3. /*
  4. * This file is part of Composer.
  5. *
  6. * (c) Nils Adermann <naderman@naderman.de>
  7. * Jordi Boggiano <j.boggiano@seld.be>
  8. *
  9. * For the full copyright and license information, please view
  10. * the license that is located at the bottom of this file.
  11. */
  12. // Avoid APC causing random fatal errors per https://github.com/composer/composer/issues/264
  13. if (extension_loaded('apc') && ini_get('apc.enable_cli') && ini_get('apc.cache_by_default')) {
  14. if (version_compare(phpversion('apc'), '3.0.12', '>=')) {
  15. ini_set('apc.cache_by_default', 0);
  16. } else {
  17. fwrite(STDERR, 'Warning: APC <= 3.0.12 may cause fatal errors when running composer commands.'.PHP_EOL);
  18. fwrite(STDERR, 'Update APC, or set apc.enable_cli or apc.cache_by_default to 0 in your php.ini.'.PHP_EOL);
  19. }
  20. }
  21. Phar::mapPhar('composer.phar');
  22. define('COMPOSER_DEV_WARNING_TIME', 1431294610);
  23. require 'phar://composer.phar/bin/composer';
  24. __HALT_COMPILER(); ?>
  25. ®x��s������ ���composer.phar�������src/bootstrap.phpÅ��’E(UÅ��¨¯2�¶������+���src/Composer/Autoload/AutoloadGenerator.phpxD��’E(UxD��´¡ &¶������+���src/Composer/Autoload/ClassMapGenerator.phpJ��’E(UJ��y¾±K¶���������src/Composer/Cache.php*��’E(U*��–užÁ¶������%���src/Composer/Command/AboutCommand.php»��’E(U»��#{ik¶������'���src/Composer/Command/ArchiveCommand.php��’E(U��¸Uöª¶������*���src/Composer/Command/ClearCacheCommand.phpZ��’E(UZ��‰ì>¶������ ���src/Composer/Command/Command.php‰��’E(U‰��µ vJ¶������&���src/Composer/Command/ConfigCommand.php4��’E(U4��r�Ó¶������-���src/Composer/Command/CreateProjectCommand.php=1��’E(U=1��ºžÑ›¶������'���src/Composer/Command/DependsCommand.php„
  26. ��’E(U„
  27. ��È! "¶������(���src/Composer/Command/DiagnoseCommand.phpg:��’E(Ug:��9ˆìæ¶������,���src/Composer/Command/DumpAutoloadCommand.phpÿ��’E(Uÿ��FZ¶������&���src/Composer/Command/GlobalCommand.php��’E(U��©¨@•¶������,���src/Composer/Command/Helper/DialogHelper.phpž��’E(Už��•‚Œ&¶������$���src/Composer/Command/HomeCommand.php+��’E(U+��^š¶������$���src/Composer/Command/InitCommand.php 7��’E(U 7��$Îñ¶������'���src/Composer/Command/InstallCommand.php#��’E(U#��=J%¶������(���src/Composer/Command/LicensesCommand.phpÏ��’E(UÏ�� î¥”¶������&���src/Composer/Command/RemoveCommand.php”��’E(U”��¹>1œ¶������'���src/Composer/Command/RequireCommand.php~��’E(U~��¡ú„¾¶������)���src/Composer/Command/RunScriptCommand.phpk ��’E(Uk ��ÃõR¶������+���src/Composer/Command/ScriptAliasCommand.php���’E(U���¢ò9J¶������&���src/Composer/Command/SearchCommand.phpl ��’E(Ul ��¶K4¶������*���src/Composer/Command/SelfUpdateCommand.php#��’E(U#��¡#ˆ)¶������$���src/Composer/Command/ShowCommand.php50��’E(U50��¹­‰„¶������&���src/Composer/Command/StatusCommand.phpo ��’E(Uo ��—²Î¶������&���src/Composer/Command/UpdateCommand.php*��’E(U*��Í
  28. #ö������(���src/Composer/Command/ValidateCommand.php ��’E(U ��yw‚¶���������src/Composer/Composer.php) ��’E(U) ��Ò�ݘ¶������-���src/Composer/Config/ConfigSourceInterface.php®��’E(U®��6J[ª¶������(���src/Composer/Config/JsonConfigSource.php} ��’E(U} ��èÇ ¶���������src/Composer/Config.phpÿ��’E(Uÿ��/ª�¶������$���src/Composer/Console/Application.php"��’E(U"��”LTܶ������,���src/Composer/Console/HtmlOutputFormatter.phpÎ��’E(UÎ��๟„¶������/���src/Composer/DependencyResolver/DebugSolver.php‰��’E(U‰��£Ò­…¶������-���src/Composer/DependencyResolver/Decisions.phpQ��’E(UQ��?˜¬$¶������1���src/Composer/DependencyResolver/DefaultPolicy.php��’E(U��‰&—¶������>���src/Composer/DependencyResolver/Operation/InstallOperation.phpC��’E(UC��´\õ*¶������I���src/Composer/DependencyResolver/Operation/MarkAliasInstalledOperation.phpÐ��’E(UÐ��xUZa¶������K���src/Composer/DependencyResolver/Operation/MarkAliasUninstalledOperation.phpÖ��’E(UÖ��_iÇ«¶������@���src/Composer/DependencyResolver/Operation/OperationInterface.phpÓ���’E(UÓ���Ùâ&ä¶������=���src/Composer/DependencyResolver/Operation/SolverOperation.phpë��’E(Uë��ħݔ¶������@���src/Composer/DependencyResolver/Operation/UninstallOperation.phpI��’E(UI��FûÂɶ������=���src/Composer/DependencyResolver/Operation/UpdateOperation.phph��’E(Uh��öSÕ]¶������3���src/Composer/DependencyResolver/PolicyInterface.php‘��’E(U‘��BŸ¶¶������(���src/Composer/DependencyResolver/Pool.php'"��’E(U'"��Ø›x¶������+���src/Composer/DependencyResolver/Problem.php��’E(U��È S�¶������+���src/Composer/DependencyResolver/Request.phpÌ��’E(UÌ��™¦òä¶������(���src/Composer/DependencyResolver/Rule.php��’E(U��Á[”¶������+���src/Composer/DependencyResolver/RuleSet.php%
  29. ��’E(U%
  30. ��9z ¶������4���src/Composer/DependencyResolver/RuleSetGenerator.php]��’E(U]��4“Ñ9¶������3���src/Composer/DependencyResolver/RuleSetIterator.php��’E(U��}õÇù¶������2���src/Composer/DependencyResolver/RuleWatchChain.phpi��’E(Ui��hïš,¶������2���src/Composer/DependencyResolver/RuleWatchGraph.phpÜ��’E(UÜ��‰8¶������1���src/Composer/DependencyResolver/RuleWatchNode.phpç��’E(Uç��—Þȶ������*���src/Composer/DependencyResolver/Solver.php 7��’E(U 7��&„°¶������6���src/Composer/DependencyResolver/SolverBugException.php˜��’E(U˜��"qN¶������;���src/Composer/DependencyResolver/SolverProblemsException.php%��’E(U%��TíP¶������/���src/Composer/DependencyResolver/Transaction.phpÔ��’E(UÔ�� 3ô¶������-���src/Composer/Downloader/ArchiveDownloader.php  ��’E(U  ��жTj¶������1���src/Composer/Downloader/ChangeReportInterface.phpÌ���’E(UÌ���¯à¨¿¶������/���src/Composer/Downloader/DownloaderInterface.phpÊ��’E(UÊ��gs!l¶������+���src/Composer/Downloader/DownloadManager.php‘��’E(U‘��'oÅb¶������*���src/Composer/Downloader/FileDownloader.php¦��’E(U¦��c‹ζ������/���src/Composer/Downloader/FilesystemException.php��’E(U��]T½ˆ¶������)���src/Composer/Downloader/GitDownloader.phpf#��’E(Uf#��”dõ̶������*���src/Composer/Downloader/GzipDownloader.phpÈ��’E(UÈ��­äßж������(���src/Composer/Downloader/HgDownloader.phpc��’E(Uc��‡‚T„¶������0���src/Composer/Downloader/PearPackageExtractor.phpa��’E(Ua��@ÔØ#¶������.���src/Composer/Downloader/PerforceDownloader.phpx��’E(Ux��<éc¶������*���src/Composer/Downloader/PharDownloader.phpå���’E(Uå���ÞÉç¶������)���src/Composer/Downloader/RarDownloader.phpß��’E(Uß��¾¼¶������)���src/Composer/Downloader/SvnDownloader.php\��’E(U\��¨Ž=¶������)���src/Composer/Downloader/TarDownloader.phpã���’E(Uã���Í’X?¶������.���src/Composer/Downloader/TransportException.php–��’E(U–��h"Br¶������)���src/Composer/Downloader/VcsDownloader.php÷��’E(U÷��«‘ßò¶������)���src/Composer/Downloader/ZipDownloader.phpC ��’E(UC ��]^+¶������&���src/Composer/EventDispatcher/Event.php ��’E(U ��±™jï¶������0���src/Composer/EventDispatcher/EventDispatcher.phpš��’E(Uš��W¶������9���src/Composer/EventDispatcher/EventSubscriberInterface.php©���’E(U©���h·0¶���������src/Composer/Factory.php�-��’E(U�-��ËpFà¶������.���src/Composer/Installer/InstallationManager.php@��’E(U@��›ö«¶������)���src/Composer/Installer/InstallerEvent.php��’E(U��lÔzi¶������*���src/Composer/Installer/InstallerEvents.phpÞ���’E(UÞ���ìŸ@G¶������-���src/Composer/Installer/InstallerInterface.phpÅ��’E(UÅ��HS“¡¶������+���src/Composer/Installer/LibraryInstaller.phpˆ��’E(Uˆ��
  31. nB†¶������/���src/Composer/Installer/MetapackageInstaller.phpœ��’E(Uœ��ÆÅ!¶������(���src/Composer/Installer/NoopInstaller.php+��’E(U+��À·M}¶������'���src/Composer/Installer/PackageEvent.php‰��’E(U‰��‘: ¶������(���src/Composer/Installer/PackageEvents.php¸��’E(U¸��dbØs¶������(���src/Composer/Installer/PearInstaller.phpV��’E(UV���zð¶������*���src/Composer/Installer/PluginInstaller.phpJ��’E(UJ��«èV¶������+���src/Composer/Installer/ProjectInstaller.php��’E(U��*0@P¶���������src/Composer/Installer.php…u��’E(U…u��$š ϶���������src/Composer/IO/BaseIO.php—��’E(U—��
  32. n¶���������src/Composer/IO/BufferIO.php��’E(U��hvá¶���������src/Composer/IO/ConsoleIO.php��’E(U��jd5í¶���������src/Composer/IO/IOInterface.php‡��’E(U‡��Ÿp‡y¶���������src/Composer/IO/NullIO.php³��’E(U³��~1Ķ���������src/Composer/Json/JsonFile.phpy��’E(Uy��¼èî¶������#���src/Composer/Json/JsonFormatter.php��’E(U��c–]Y¶������%���src/Composer/Json/JsonManipulator.php¡'��’E(U¡'��ìßæl¶������-���src/Composer/Json/JsonValidationException.php\��’E(U\��.Xóܶ������%���src/Composer/Package/AliasPackage.phpW��’E(UW��T/YÁ¶������7���src/Composer/Package/Archiver/ArchivableFilesFinder.php¿��’E(U¿��ŽcEl¶������0���src/Composer/Package/Archiver/ArchiveManager.php' ��’E(U' ��é‰ô¶������3���src/Composer/Package/Archiver/ArchiverInterface.phpï���’E(Uï���<ʸ¶������3���src/Composer/Package/Archiver/BaseExcludeFilter.php‘��’E(U‘��Mù¶������7���src/Composer/Package/Archiver/ComposerExcludeFilter.php��’E(U��‹SZ0¶������2���src/Composer/Package/Archiver/GitExcludeFilter.phpw��’E(Uw��LgU»¶������1���src/Composer/Package/Archiver/HgExcludeFilter.php��’E(U��~”¸¶������.���src/Composer/Package/Archiver/PharArchiver.php[��’E(U[��Ê5Íø¶������$���src/Composer/Package/BasePackage.phpM ��’E(UM ��· %þ¶������(���src/Composer/Package/CompletePackage.phpÿ��’E(Uÿ��o+ã ¶������1���src/Composer/Package/CompletePackageInterface.phpõ��’E(Uõ��¦Ê�ò¶������+���src/Composer/Package/Dumper/ArrayDumper.phpì ��’E(Uì ��ª–æ¶���������src/Composer/Package/Link.php*��’E(U*��_’…¶������7���src/Composer/Package/LinkConstraint/EmptyConstraint.phpê��’E(Uê���쾶������?���src/Composer/Package/LinkConstraint/LinkConstraintInterface.php��’E(U��åþ‡¢¶������7���src/Composer/Package/LinkConstraint/MultiConstraint.phpg��’E(Ug��s3¶������:���src/Composer/Package/LinkConstraint/SpecificConstraint.phpp��’E(Up��_„ˆY¶������9���src/Composer/Package/LinkConstraint/VersionConstraint.phpÉ��’E(UÉ��y?³Ø¶������+���src/Composer/Package/Loader/ArrayLoader.php��’E(U��GY Š¶������7���src/Composer/Package/Loader/InvalidPackageException.phpE��’E(UE��xb¾¶������*���src/Composer/Package/Loader/JsonLoader.phpù��’E(Uù��!~ˆ{¶������/���src/Composer/Package/Loader/LoaderInterface.php²���’E(U²���¦}úζ������1���src/Composer/Package/Loader/RootPackageLoader.phpS"��’E(US"��ð¨<¶������5���src/Composer/Package/Loader/ValidatingArrayLoader.phpÙ/��’E(UÙ/��1¯…K¶���������src/Composer/Package/Locker.phpÞ��’E(UÞ��6hж������ ���src/Composer/Package/Package.phpÄ��’E(UÄ��„ô¶������)���src/Composer/Package/PackageInterface.php_��’E(U_��戹‚¶������)���src/Composer/Package/RootAliasPackage.phpÞ��’E(UÞ��Õ>¶������$���src/Composer/Package/RootPackage.phpn��’E(Un��áACO¶������-���src/Composer/Package/RootPackageInterface.php´��’E(U´��êqKж������.���src/Composer/Package/Version/VersionParser.php .��’E(U .��/@V¶������0���src/Composer/Package/Version/VersionSelector.phpü��’E(Uü��íM¬¶������$���src/Composer/Plugin/CommandEvent.phpâ��’E(Uâ��³ÆÇW¶������$���src/Composer/Plugin/PluginEvents.php¤���’E(U¤���0ïÞX¶������'���src/Composer/Plugin/PluginInterface.phpô���’E(Uô��� 1‰%¶������%���src/Composer/Plugin/PluginManager.phpv��’E(Uv��šU�i¶������,���src/Composer/Plugin/PreFileDownloadEvent.php`��’E(U`���9-ζ������+���src/Composer/Repository/ArrayRepository.php ��’E(U ��´¯Þ/¶������.���src/Composer/Repository/ArtifactRepository.phpë
  33. ��’E(Uë
  34. ��šÏoð¶������.���src/Composer/Repository/ComposerRepository.php¤>��’E(U¤>��Þè¶������/���src/Composer/Repository/CompositeRepository.php ��’E(U ��4úE¶������0���src/Composer/Repository/FilesystemRepository.phpÀ��’E(UÀ��&xb£¶������4���src/Composer/Repository/InstalledArrayRepository.php£���’E(U£���/ö~>¶������9���src/Composer/Repository/InstalledFilesystemRepository.php£���’E(U£���V
  35. •_¶������8���src/Composer/Repository/InstalledRepositoryInterface.php‡���’E(U‡���£9p¶������6���src/Composer/Repository/InvalidRepositoryException.phpn���’E(Un���à“똶������-���src/Composer/Repository/PackageRepository.phpG��’E(UG��í:k¶������2���src/Composer/Repository/Pear/BaseChannelReader.php6��’E(U6��.fi!¶������,���src/Composer/Repository/Pear/ChannelInfo.phpÄ��’E(UÄ��:T*ɶ������.���src/Composer/Repository/Pear/ChannelReader.phpn��’E(Un��š8¶������4���src/Composer/Repository/Pear/ChannelRest10Reader.phpÁ ��’E(UÁ ��O€ë¶������4���src/Composer/Repository/Pear/ChannelRest11Reader.php& ��’E(U& ��òUb¶������5���src/Composer/Repository/Pear/DependencyConstraint.phpq��’E(Uq��9=¶������/���src/Composer/Repository/Pear/DependencyInfo.phpq��’E(Uq��fºTò¶������8���src/Composer/Repository/Pear/PackageDependencyParser.php%��’E(U%��j?“¶������,���src/Composer/Repository/Pear/PackageInfo.php°��’E(U°��Ÿ ¸ ¶������,���src/Composer/Repository/Pear/ReleaseInfo.php’��’E(U’��o“ŠÃ¶������*���src/Composer/Repository/PearRepository.php°��’E(U°��
  36. ,B·¶������.���src/Composer/Repository/PlatformRepository.php���’E(U���µáÇض������/���src/Composer/Repository/RepositoryInterface.phpÔ��’E(UÔ��ò�ŸÉ¶������-���src/Composer/Repository/RepositoryManager.php³��’E(U³��33¸ï¶������7���src/Composer/Repository/RepositorySecurityException.phpo���’E(Uo���pÕ«ª¶������2���src/Composer/Repository/Vcs/GitBitbucketDriver.phpì ��’E(Uì ��Fÿô¶������)���src/Composer/Repository/Vcs/GitDriver.php��’E(U��\îï¶������,���src/Composer/Repository/Vcs/GitHubDriver.phpr'��’E(Ur'��".j0¶������,���src/Composer/Repository/Vcs/GitLabDriver.php%��’E(U%��d¼+ò¶������1���src/Composer/Repository/Vcs/HgBitbucketDriver.phpô ��’E(Uô ��˜áWõ¶������(���src/Composer/Repository/Vcs/HgDriver.phpà��’E(Uà��ñ‘綶������.���src/Composer/Repository/Vcs/PerforceDriver.php!
  37. ��’E(U!
  38. ���€Ùk¶������)���src/Composer/Repository/Vcs/SvnDriver.php²��’E(U²��Ë W¶������)���src/Composer/Repository/Vcs/VcsDriver.phpÑ��’E(UÑ��å%R¶������2���src/Composer/Repository/Vcs/VcsDriverInterface.php‰��’E(U‰��pO㤶������)���src/Composer/Repository/VcsRepository.phpt��’E(Ut���5²Ü¶������3���src/Composer/Repository/WritableArrayRepository.php��’E(U��¾G*¶������7���src/Composer/Repository/WritableRepositoryInterface.php‰��’E(U‰��‘/sï¶������$���src/Composer/Script/CommandEvent.phpW���’E(UW���£VZt¶���������src/Composer/Script/Event.phpµ��’E(Uµ��lt¦M¶������$���src/Composer/Script/PackageEvent.phpœ���’E(Uœ���§ÿÉ ¶������$���src/Composer/Script/ScriptEvents.phpP��’E(UP���ìhQ¶������ ���src/Composer/Util/AuthHelper.phpÌ��’E(UÌ��œ¼�À¶������$���src/Composer/Util/ComposerMirror.php±��’E(U±��­½øض������%���src/Composer/Util/ConfigValidator.php2��’E(U2��ö7.¶������"���src/Composer/Util/ErrorHandler.php��’E(U��´@…æ¶������ ���src/Composer/Util/Filesystem.php4&��’E(U4&��Rl—‡¶���������src/Composer/Util/Git.php“��’E(U“���-X`¶���������src/Composer/Util/GitHub.php^��’E(U^��ŒùX¶���������src/Composer/Util/GitLab.php’��’E(U’��s«3¶������$���src/Composer/Util/NoProxyPattern.php¾��’E(U¾��Z+°m¶���������src/Composer/Util/Perforce.php3��’E(U3��‚=e.¶������%���src/Composer/Util/ProcessExecutor.phpî��’E(Uî��ÔÀ¶������&���src/Composer/Util/RemoteFilesystem.phpR*��’E(UR*��ùLf¶������+���src/Composer/Util/SpdxLicenseIdentifier.php6
  39. ��’E(U6
  40. ��Ä6»o¶������*���src/Composer/Util/StreamContextFactory.phpâ ��’E(Uâ ��Ð B¶���������src/Composer/Util/Svn.php!��’E(U!��˜¦-[¶������%���src/Composer/Autoload/ClassLoader.php”0��’E(U”0��¸Lh¦¶���������res/composer-schema.jsonÁQ��’E(UÁQ���Œ¸Ú¶���������res/spdx-identifier.jsonD��’E(UD��*Oiò¶���������src/Composer/IO/hiddeninput.exe�$��’E(U�$��•�¥v¶������@���vendor/symfony/console/Symfony/Component/Console/Application.php¶R��’E(U¶R��”.ö(¶������D���vendor/symfony/console/Symfony/Component/Console/Command/Command.phpì��’E(Uì��·ò´¶������H���vendor/symfony/console/Symfony/Component/Console/Command/HelpCommand.php1��’E(U1��ý€”¶������H���vendor/symfony/console/Symfony/Component/Console/Command/ListCommand.php³��’E(U³��VÓé¶������B���vendor/symfony/console/Symfony/Component/Console/ConsoleEvents.phpï���’E(Uï��� ÕH¸¶������V���vendor/symfony/console/Symfony/Component/Console/Descriptor/ApplicationDescription.phpù��’E(Uù��‰>O¶������J���vendor/symfony/console/Symfony/Component/Console/Descriptor/Descriptor.php\��’E(U\��WJ[í¶������S���vendor/symfony/console/Symfony/Component/Console/Descriptor/DescriptorInterface.phpü���’E(Uü���±Qµ¶������N���vendor/symfony/console/Symfony/Component/Console/Descriptor/JsonDescriptor.php2 ��’E(U2 ��†ca¶������R���vendor/symfony/console/Symfony/Component/Console/Descriptor/MarkdownDescriptor.php
  41. ��’E(U
  42. ���LÛ*¶������N���vendor/symfony/console/Symfony/Component/Console/Descriptor/TextDescriptor.php6��’E(U6��zo¡¶������M���vendor/symfony/console/Symfony/Component/Console/Descriptor/XmlDescriptor.php ��’E(U ��…{îm¶������N���vendor/symfony/console/Symfony/Component/Console/Event/ConsoleCommandEvent.php²��’E(U²��Zk‰2¶������G���vendor/symfony/console/Symfony/Component/Console/Event/ConsoleEvent.phpÅ��’E(UÅ��ÒxÛ\¶������P���vendor/symfony/console/Symfony/Component/Console/Event/ConsoleExceptionEvent.php��’E(U��á2é¶������P���vendor/symfony/console/Symfony/Component/Console/Event/ConsoleTerminateEvent.phpz��’E(Uz��³,îL¶������N���vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatter.phpˆ ��’E(Uˆ ��+ÂF5¶������W���vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterInterface.php˜��’E(U˜��3l~´¶������S���vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyle.phpÄ��’E(UÄ��Xy¶������\���vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleInterface.phpŽ��’E(UŽ��öëÄ=¶������X���vendor/symfony/console/Symfony/Component/Console/Formatter/OutputFormatterStyleStack.php��’E(U��yI'¶������P���vendor/symfony/console/Symfony/Component/Console/Helper/DebugFormatterHelper.phpm��’E(Um��ò¯s>¶������L���vendor/symfony/console/Symfony/Component/Console/Helper/DescriptorHelper.php9��’E(U9��ûùäð¶������H���vendor/symfony/console/Symfony/Component/Console/Helper/DialogHelper.phpÊ��’E(UÊ��lÕHl¶������K���vendor/symfony/console/Symfony/Component/Console/Helper/FormatterHelper.php��’E(U��žI‚�¶������B���vendor/symfony/console/Symfony/Component/Console/Helper/Helper.phpß��’E(Uß��o¾ã¶������K���vendor/symfony/console/Symfony/Component/Console/Helper/HelperInterface.phpï���’E(Uï���=e ¶������E���vendor/symfony/console/Symfony/Component/Console/Helper/HelperSet.php/��’E(U/��âw�d¶������L���vendor/symfony/console/Symfony/Component/Console/Helper/InputAwareHelper.phpc��’E(Uc��ñø�|¶������I���vendor/symfony/console/Symfony/Component/Console/Helper/ProcessHelper.phpâ��’E(Uâ��|̼¶������G���vendor/symfony/console/Symfony/Component/Console/Helper/ProgressBar.php$��’E(U$��2Œ5J¶������J���vendor/symfony/console/Symfony/Component/Console/Helper/ProgressHelper.phpƒ��’E(Uƒ��êëä¶������J���vendor/symfony/console/Symfony/Component/Console/Helper/QuestionHelper.php��’E(U��R Š¶������A���vendor/symfony/console/Symfony/Component/Console/Helper/Table.php ��’E(U ��?{êǶ������G���vendor/symfony/console/Symfony/Component/Console/Helper/TableHelper.phpØ
  43. ��’E(UØ
  44. ��,  ¶������J���vendor/symfony/console/Symfony/Component/Console/Helper/TableSeparator.php[���’E(U[���LV¡¶������F���vendor/symfony/console/Symfony/Component/Console/Helper/TableStyle.phpÕ��’E(UÕ��æ"ðù¶������D���vendor/symfony/console/Symfony/Component/Console/Input/ArgvInput.phpÙ��’E(UÙ��ËkE¶������E���vendor/symfony/console/Symfony/Component/Console/Input/ArrayInput.phpõ ��’E(Uõ ��É×�™¶������@���vendor/symfony/console/Symfony/Component/Console/Input/Input.php
  45. ��’E(U
  46. ��ÇýT¶������H���vendor/symfony/console/Symfony/Component/Console/Input/InputArgument.phpž��’E(Už��K]ìi¶������N���vendor/symfony/console/Symfony/Component/Console/Input/InputAwareInterface.phpš���’E(Uš���‡jTŸ¶������J���vendor/symfony/console/Symfony/Component/Console/Input/InputDefinition.php ��’E(U ��˜£JM¶������I���vendor/symfony/console/Symfony/Component/Console/Input/InputInterface.php ��’E(U ��9”øǶ������F���vendor/symfony/console/Symfony/Component/Console/Input/InputOption.php« ��’E(U« ��ꆮ½¶������F���vendor/symfony/console/Symfony/Component/Console/Input/StringInput.php‹��’E(U‹��†uný¶������8���vendor/symfony/console/Symfony/Component/Console/LICENSE)��’E(U)��ë&•¶������I���vendor/symfony/console/Symfony/Component/Console/Logger/ConsoleLogger.php; ��’E(U; ��#ØB~¶������J���vendor/symfony/console/Symfony/Component/Console/Output/BufferedOutput.php_��’E(U_��ûBÍ·¶������I���vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutput.php��’E(U��j嬶������R���vendor/symfony/console/Symfony/Component/Console/Output/ConsoleOutputInterface.phpå���’E(Uå���rNô�¶������F���vendor/symfony/console/Symfony/Component/Console/Output/NullOutput.php¿��’E(U¿��`5E˶������B���vendor/symfony/console/Symfony/Component/Console/Output/Output.php§��’E(U§��Ú _¶������K���vendor/symfony/console/Symfony/Component/Console/Output/OutputInterface.phpI��’E(UI��ÈâãB¶������H���vendor/symfony/console/Symfony/Component/Console/Output/StreamOutput.php¢��’E(U¢��ü0¶������L���vendor/symfony/console/Symfony/Component/Console/Question/ChoiceQuestion.phpf��’E(Uf��Ôh¶������R���vendor/symfony/console/Symfony/Component/Console/Question/ConfirmationQuestion.phpK��’E(UK��õÃTȶ������F���vendor/symfony/console/Symfony/Component/Console/Question/Question.php®��’E(U®��.e8Ö¶������:���vendor/symfony/console/Symfony/Component/Console/Shell.php.��’E(U.��þÉŽ‡¶������M���vendor/symfony/console/Symfony/Component/Console/Tester/ApplicationTester.phpÔ��’E(UÔ��¬ì¤d¶������I���vendor/symfony/console/Symfony/Component/Console/Tester/CommandTester.php���’E(U���H»â`¶������J���vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractAdapter.php¤
  47. ��’E(U¤
  48. ��¢)z9¶������N���vendor/symfony/finder/Symfony/Component/Finder/Adapter/AbstractFindAdapter.phpÛ��’E(UÛ��SõT´¶������K���vendor/symfony/finder/Symfony/Component/Finder/Adapter/AdapterInterface.php¯��’E(U¯��‹éȶ������I���vendor/symfony/finder/Symfony/Component/Finder/Adapter/BsdFindAdapter.php{��’E(U{��Q,D2¶������I���vendor/symfony/finder/Symfony/Component/Finder/Adapter/GnuFindAdapter.php^��’E(U^��ßz˜r¶������E���vendor/symfony/finder/Symfony/Component/Finder/Adapter/PhpAdapter.php+��’E(U+��&˜îÒ¶������H���vendor/symfony/finder/Symfony/Component/Finder/Comparator/Comparator.phpŒ��’E(UŒ��wþT¶������L���vendor/symfony/finder/Symfony/Component/Finder/Comparator/DateComparator.php%��’E(U%��L¿EǶ������N���vendor/symfony/finder/Symfony/Component/Finder/Comparator/NumberComparator.phpx��’E(Ux��½™5¶������R���vendor/symfony/finder/Symfony/Component/Finder/Exception/AccessDeniedException.php„���’E(U„���½¾sœ¶������T���vendor/symfony/finder/Symfony/Component/Finder/Exception/AdapterFailureException.php��’E(U��mŒ_,¶������O���vendor/symfony/finder/Symfony/Component/Finder/Exception/ExceptionInterface.php„���’E(U„���Gz-¶������Z���vendor/symfony/finder/Symfony/Component/Finder/Exception/OperationNotPermitedException.phpŠ���’E(UŠ���U88¶������Y���vendor/symfony/finder/Symfony/Component/Finder/Exception/ShellCommandFailureException.php$��’E(U$��C”sÓ¶������H���vendor/symfony/finder/Symfony/Component/Finder/Expression/Expression.php}��’E(U}��/·cð¶������B���vendor/symfony/finder/Symfony/Component/Finder/Expression/Glob.php¡��’E(U¡�� V¿¶������C���vendor/symfony/finder/Symfony/Component/Finder/Expression/Regex.php���’E(U���S7Pæ¶������L���vendor/symfony/finder/Symfony/Component/Finder/Expression/ValueInterface.php;��’E(U;�� îãÓ¶������9���vendor/symfony/finder/Symfony/Component/Finder/Finder.php6#��’E(U6#��ÕÔG¶������7���vendor/symfony/finder/Symfony/Component/Finder/Glob.php ��’E(U ��z�ø
  49. ¶������P���vendor/symfony/finder/Symfony/Component/Finder/Iterator/CustomFilterIterator.php]��’E(U]��tà±µ¶������S���vendor/symfony/finder/Symfony/Component/Finder/Iterator/DateRangeFilterIterator.phpz��’E(Uz��}¢¶������T���vendor/symfony/finder/Symfony/Component/Finder/Iterator/DepthRangeFilterIterator.phpð��’E(Uð��ß0™¶������Z���vendor/symfony/finder/Symfony/Component/Finder/Iterator/ExcludeDirectoryFilterIterator.php”��’E(U”��"ÖóÁ¶������U���vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilecontentFilterIterator.php#��’E(U#��Ú_VǶ������R���vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilenameFilterIterator.php‡��’E(U‡��F ’ ¶������M���vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilePathsIterator.php���’E(U���ýòäQ¶������R���vendor/symfony/finder/Symfony/Component/Finder/Iterator/FileTypeFilterIterator.php\��’E(U\��p‘'˜¶������J���vendor/symfony/finder/Symfony/Component/Finder/Iterator/FilterIterator.php†��’E(U†��0£¾Ô¶������V���vendor/symfony/finder/Symfony/Component/Finder/Iterator/MultiplePcreFilterIterator.phpØ��’E(UØ��Òù“¶������N���vendor/symfony/finder/Symfony/Component/Finder/Iterator/PathFilterIterator.php¸��’E(U¸��E*E¶������V���vendor/symfony/finder/Symfony/Component/Finder/Iterator/RecursiveDirectoryIterator.phpY��’E(UY��êÓÊܶ������S���vendor/symfony/finder/Symfony/Component/Finder/Iterator/SizeRangeFilterIterator.phpg��’E(Ug��!Ô—é¶������L���vendor/symfony/finder/Symfony/Component/Finder/Iterator/SortableIterator.phpÞ��’E(UÞ��ö³%¶������6���vendor/symfony/finder/Symfony/Component/Finder/LICENSE)��’E(U)��ë&•¶������@���vendor/symfony/finder/Symfony/Component/Finder/Shell/Command.php£
  50. ��’E(U£
  51. ��Ö<ÊT¶������>���vendor/symfony/finder/Symfony/Component/Finder/Shell/Shell.phpé��’E(Ué��¿ëÛ•¶������>���vendor/symfony/finder/Symfony/Component/Finder/SplFileInfo.phpû��’E(Uû��‘†6¶������Q���vendor/symfony/process/Symfony/Component/Process/Exception/ExceptionInterface.phpf���’E(Uf���]ö>T¶������W���vendor/symfony/process/Symfony/Component/Process/Exception/InvalidArgumentException.php¨���’E(U¨���ÐÀ+_¶������M���vendor/symfony/process/Symfony/Component/Process/Exception/LogicException.php”���’E(U”��� ³ãñ¶������U���vendor/symfony/process/Symfony/Component/Process/Exception/ProcessFailedException.php<��’E(U<��"wÛn¶������W���vendor/symfony/process/Symfony/Component/Process/Exception/ProcessTimedOutException.php��’E(U��. Ãá¶������O���vendor/symfony/process/Symfony/Component/Process/Exception/RuntimeException.php˜���’E(U˜���¢Ø:¶������E���vendor/symfony/process/Symfony/Component/Process/ExecutableFinder.php~��’E(U~��+…¶������8���vendor/symfony/process/Symfony/Component/Process/LICENSE)��’E(U)��ë&•¶������H���vendor/symfony/process/Symfony/Component/Process/PhpExecutableFinder.php��’E(U��ûÔM>¶������?���vendor/symfony/process/Symfony/Component/Process/PhpProcess.php��’E(U��8ZÔ·¶������H���vendor/symfony/process/Symfony/Component/Process/Pipes/AbstractPipes.php���’E(U���˜|¥¾¶������I���vendor/symfony/process/Symfony/Component/Process/Pipes/PipesInterface.phpD��’E(UD��vØ������D���vendor/symfony/process/Symfony/Component/Process/Pipes/UnixPipes.php¤ ��’E(U¤ ��øUt¶������G���vendor/symfony/process/Symfony/Component/Process/Pipes/WindowsPipes.php½��’E(U½���.X£¶������<���vendor/symfony/process/Symfony/Component/Process/Process.phpJN��’E(UJN��¹§´¶������C���vendor/symfony/process/Symfony/Component/Process/ProcessBuilder.php ��’E(U ��„8<²¶������A���vendor/symfony/process/Symfony/Component/Process/ProcessUtils.phpŒ��’E(UŒ��ÈbÝv¶������5���vendor/symfony/yaml/Symfony/Component/Yaml/Dumper.php ��’E(U ���ÿǶ������6���vendor/symfony/yaml/Symfony/Component/Yaml/Escaper.phpR��’E(UR��Ñlö6¶������F���vendor/symfony/yaml/Symfony/Component/Yaml/Exception/DumpException.phpu���’E(Uu���e*n¶������K���vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ExceptionInterface.phpe���’E(Ue���Îcº¶������G���vendor/symfony/yaml/Symfony/Component/Yaml/Exception/ParseException.phpŸ��’E(UŸ��PˆA=¶������I���vendor/symfony/yaml/Symfony/Component/Yaml/Exception/RuntimeException.php—���’E(U—���‡õ�¶������5���vendor/symfony/yaml/Symfony/Component/Yaml/Inline.phpå&��’E(Uå&��i*{f¶������2���vendor/symfony/yaml/Symfony/Component/Yaml/LICENSE)��’E(U)��ë&•¶������5���vendor/symfony/yaml/Symfony/Component/Yaml/Parser.phpk7��’E(Uk7��æ̶������8���vendor/symfony/yaml/Symfony/Component/Yaml/Unescaper.phpž��’E(Už���:ø'¶������3���vendor/symfony/yaml/Symfony/Component/Yaml/Yaml.phpË��’E(UË��äó ¶���������vendor/seld/jsonlint/LICENSE"��’E(U"��aƒsy¶������5���vendor/seld/jsonlint/src/Seld/JsonLint/JsonParser.php)1��’E(U)1��?5R3¶������0���vendor/seld/jsonlint/src/Seld/JsonLint/Lexer.php��’E(U��‰„m!¶������;���vendor/seld/jsonlint/src/Seld/JsonLint/ParsingException.php��’E(U��‰²ñ¶������4���vendor/seld/jsonlint/src/Seld/JsonLint/Undefined.php>���’E(U>���ÿqŸŸ¶������(���vendor/justinrainbow/json-schema/LICENSE÷��’E(U÷��xÞxt¶������J���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Collection.phpý��’E(Uý��Ç ;ÿ¶������J���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Constraint.php9��’E(U9��éð°#¶������S���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/ConstraintInterface.phpN��’E(UN��øÆMy¶������D���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Enum.phpè��’E(Uè��êvĶ������F���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Format.phpí ��’E(Uí ��á” ¶������F���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Number.php«��’E(U«��›çI)¶������F���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Object.php¾
  52. ��’E(U¾
  53. ��|Ò\F¶������F���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Schema.php��’E(U��]ÜÙ¶������F���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/String.phpŸ��’E(UŸ���ˆpå¶������D���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Type.phph��’E(Uh��õd϶������I���vendor/justinrainbow/json-schema/src/JsonSchema/Constraints/Undefined.phpl��’E(Ul��ƒ Ή¶������V���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidArgumentException.phpv���’E(Uv���¬ «"¶������]���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSchemaMediaTypeException.phpv���’E(Uv���ŠCÓ¶������W���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/InvalidSourceUriException.phpw���’E(Uw���N-ò[¶������S���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/JsonDecodingException.phpÞ��’E(UÞ��†¾©‘¶������W���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/ResourceNotFoundException.phpo���’E(Uo���Æ$"Ŷ������R���vendor/justinrainbow/json-schema/src/JsonSchema/Exception/UriResolverException.phpj���’E(Uj���SÓdz¶������?���vendor/justinrainbow/json-schema/src/JsonSchema/RefResolver.php|
  54. ��’E(U|
  55. ��™& i¶������T���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/AbstractRetriever.phpÜ���’E(UÜ���]j¶������G���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/Curl.phpt��’E(Ut��I·ý�¶������R���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/FileGetContents.phpÑ��’E(UÑ��懨¶������R���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/PredefinedArray.php^��’E(U^��"ß6o¶������X���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/Retrievers/UriRetrieverInterface.php©���’E(U©���CO¶������C���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriResolver.php® ��’E(U® ��àP¾¡¶������D���vendor/justinrainbow/json-schema/src/JsonSchema/Uri/UriRetriever.php–��’E(U–��ªÿ¨Ü¶������=���vendor/justinrainbow/json-schema/src/JsonSchema/Validator.phps��’E(Us��ô„=¶���������vendor/autoload.php‘���’E(U‘���ð.â¶������'���vendor/composer/autoload_namespaces.php��’E(U��T Ùö¶������!���vendor/composer/autoload_psr4.php²���’E(U²���Ô�¨Ð¶������%���vendor/composer/autoload_classmap.php#¢��’E(U#¢��°l¤è¶������!���vendor/composer/autoload_real.phpþ��’E(Uþ��”®9¶������!���vendor/composer/include_paths.phpÝ���’E(UÝ���™Ÿ³¶���������vendor/composer/ClassLoader.phpB��’E(UB��é”í¶������ ���bin/composern��’E(Un��–…W¶���������LICENSE3��’E(U3�� �2 ¶������<?php
  56. function includeIfExists($file)
  57. {
  58. return file_exists($file) ? include $file : false;
  59. }
  60. if ((!$loader = includeIfExists(__DIR__.'/../vendor/autoload.php')) && (!$loader = includeIfExists(__DIR__.'/../../../autoload.php'))) {
  61. echo 'You must set up the project dependencies, run the following commands:'.PHP_EOL.
  62. 'curl -sS https://getcomposer.org/installer | php'.PHP_EOL.
  63. 'php composer.phar install'.PHP_EOL;
  64. exit(1);
  65. }
  66. return $loader;
  67. <?php
  68. namespace Composer\Autoload;
  69. use Composer\Config;
  70. use Composer\EventDispatcher\EventDispatcher;
  71. use Composer\Installer\InstallationManager;
  72. use Composer\IO\IOInterface;
  73. use Composer\Package\AliasPackage;
  74. use Composer\Package\PackageInterface;
  75. use Composer\Repository\InstalledRepositoryInterface;
  76. use Composer\Util\Filesystem;
  77. use Composer\Script\ScriptEvents;
  78. class AutoloadGenerator
  79. {
  80. private $eventDispatcher;
  81. private $io;
  82. private $devMode = false;
  83. public function __construct(EventDispatcher $eventDispatcher, IOInterface $io = null)
  84. {
  85. $this->eventDispatcher = $eventDispatcher;
  86. $this->io = $io;
  87. }
  88. public function setDevMode($devMode = true)
  89. {
  90. $this->devMode = (boolean) $devMode;
  91. }
  92. public function dump(Config $config, InstalledRepositoryInterface $localRepo, PackageInterface $mainPackage, InstallationManager $installationManager, $targetDir, $scanPsr0Packages = false, $suffix = '')
  93. {
  94. $this->eventDispatcher->dispatchScript(ScriptEvents::PRE_AUTOLOAD_DUMP, $this->devMode, array(), array(
  95. 'optimize' => (bool) $scanPsr0Packages,
  96. ));
  97. $filesystem = new Filesystem();
  98. $filesystem->ensureDirectoryExists($config->get('vendor-dir'));
  99. $basePath = $filesystem->normalizePath(realpath(getcwd()));
  100. $vendorPath = $filesystem->normalizePath(realpath($config->get('vendor-dir')));
  101. $useGlobalIncludePath = (bool) $config->get('use-include-path');
  102. $prependAutoloader = $config->get('prepend-autoloader') === false ? 'false' : 'true';
  103. $classMapAuthoritative = $config->get('classmap-authoritative');
  104. $targetDir = $vendorPath.'/'.$targetDir;
  105. $filesystem->ensureDirectoryExists($targetDir);
  106. $vendorPathCode = $filesystem->findShortestPathCode(realpath($targetDir), $vendorPath, true);
  107. $vendorPathCode52 = str_replace('__DIR__', 'dirname(__FILE__)', $vendorPathCode);
  108. $vendorPathToTargetDirCode = $filesystem->findShortestPathCode($vendorPath, realpath($targetDir), true);
  109. $appBaseDirCode = $filesystem->findShortestPathCode($vendorPath, $basePath, true);
  110. $appBaseDirCode = str_replace('__DIR__', '$vendorDir', $appBaseDirCode);
  111. $namespacesFile = <<<EOF
  112. <?php
  113. // autoload_namespaces.php @generated by Composer
  114. \$vendorDir = $vendorPathCode52;
  115. \$baseDir = $appBaseDirCode;
  116. return array(
  117. EOF;
  118. $psr4File = <<<EOF
  119. <?php
  120. // autoload_psr4.php @generated by Composer
  121. \$vendorDir = $vendorPathCode52;
  122. \$baseDir = $appBaseDirCode;
  123. return array(
  124. EOF;
  125. $packageMap = $this->buildPackageMap($installationManager, $mainPackage, $localRepo->getCanonicalPackages());
  126. $autoloads = $this->parseAutoloads($packageMap, $mainPackage);
  127. foreach ($autoloads['psr-0'] as $namespace => $paths) {
  128. $exportedPaths = array();
  129. foreach ($paths as $path) {
  130. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  131. }
  132. $exportedPrefix = var_export($namespace, true);
  133. $namespacesFile .= " $exportedPrefix => ";
  134. $namespacesFile .= "array(".implode(', ', $exportedPaths)."),\n";
  135. }
  136. $namespacesFile .= ");\n";
  137. foreach ($autoloads['psr-4'] as $namespace => $paths) {
  138. $exportedPaths = array();
  139. foreach ($paths as $path) {
  140. $exportedPaths[] = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  141. }
  142. $exportedPrefix = var_export($namespace, true);
  143. $psr4File .= " $exportedPrefix => ";
  144. $psr4File .= "array(".implode(', ', $exportedPaths)."),\n";
  145. }
  146. $psr4File .= ");\n";
  147. $classmapFile = <<<EOF
  148. <?php
  149. // autoload_classmap.php @generated by Composer
  150. \$vendorDir = $vendorPathCode52;
  151. \$baseDir = $appBaseDirCode;
  152. return array(
  153. EOF;
  154. $targetDirLoader = null;
  155. $mainAutoload = $mainPackage->getAutoload();
  156. if ($mainPackage->getTargetDir() && !empty($mainAutoload['psr-0'])) {
  157. $levels = count(explode('/', $filesystem->normalizePath($mainPackage->getTargetDir())));
  158. $prefixes = implode(', ', array_map(function ($prefix) {
  159. return var_export($prefix, true);
  160. }, array_keys($mainAutoload['psr-0'])));
  161. $baseDirFromTargetDirCode = $filesystem->findShortestPathCode($targetDir, $basePath, true);
  162. $targetDirLoader = <<<EOF
  163. public static function autoload(\$class)
  164. {
  165. \$dir = $baseDirFromTargetDirCode . '/';
  166. \$prefixes = array($prefixes);
  167. foreach (\$prefixes as \$prefix) {
  168. if (0 !== strpos(\$class, \$prefix)) {
  169. continue;
  170. }
  171. \$path = \$dir . implode('/', array_slice(explode('\\\\', \$class), $levels)).'.php';
  172. if (!\$path = stream_resolve_include_path(\$path)) {
  173. return false;
  174. }
  175. require \$path;
  176. return true;
  177. }
  178. }
  179. EOF;
  180. }
  181. $classMap = array();
  182. if ($scanPsr0Packages) {
  183. foreach (array('psr-0', 'psr-4') as $psrType) {
  184. foreach ($autoloads[$psrType] as $namespace => $paths) {
  185. foreach ($paths as $dir) {
  186. $dir = $filesystem->normalizePath($filesystem->isAbsolutePath($dir) ? $dir : $basePath.'/'.$dir);
  187. if (!is_dir($dir)) {
  188. continue;
  189. }
  190. $whitelist = sprintf(
  191. '{%s/%s.+(?<!(?<!/)Test\.php)$}',
  192. preg_quote($dir),
  193. ($psrType === 'psr-0' && strpos($namespace, '_') === false) ? preg_quote(strtr($namespace, '\\', '/')) : ''
  194. );
  195. $namespaceFilter = $namespace === '' ? null : $namespace;
  196. foreach (ClassMapGenerator::createMap($dir, $whitelist, $this->io, $namespaceFilter) as $class => $path) {
  197. if (!isset($classMap[$class])) {
  198. $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  199. $classMap[$class] = $path.",\n";
  200. }
  201. }
  202. }
  203. }
  204. }
  205. }
  206. foreach ($autoloads['classmap'] as $dir) {
  207. foreach (ClassMapGenerator::createMap($dir, null, $this->io) as $class => $path) {
  208. $path = $this->getPathCode($filesystem, $basePath, $vendorPath, $path);
  209. $classMap[$class] = $path.",\n";
  210. }
  211. }
  212. ksort($classMap);
  213. foreach ($classMap as $class => $code) {
  214. $classmapFile .= ' '.var_export($class, true).' => '.$code;
  215. }
  216. $classmapFile .= ");\n";
  217. if (!$suffix) {
  218. $suffix = $config->get('autoloader-suffix') ?: md5(uniqid('', true));
  219. }
  220. file_put_contents($targetDir.'/autoload_namespaces.php', $namespacesFile);
  221. file_put_contents($targetDir.'/autoload_psr4.php', $psr4File);
  222. file_put_contents($targetDir.'/autoload_classmap.php', $classmapFile);
  223. if ($includePathFile = $this->getIncludePathsFile($packageMap, $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  224. file_put_contents($targetDir.'/include_paths.php', $includePathFile);
  225. }
  226. if ($includeFilesFile = $this->getIncludeFilesFile($autoloads['files'], $filesystem, $basePath, $vendorPath, $vendorPathCode52, $appBaseDirCode)) {
  227. file_put_contents($targetDir.'/autoload_files.php', $includeFilesFile);
  228. }
  229. file_put_contents($vendorPath.'/autoload.php', $this->getAutoloadFile($vendorPathToTargetDirCode, $suffix));
  230. file_put_contents($targetDir.'/autoload_real.php', $this->getAutoloadRealFile(true, (bool) $includePathFile, $targetDirLoader, (bool) $includeFilesFile, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative));
  231. $sourceLoader = fopen(__DIR__.'/ClassLoader.php', 'r');
  232. $targetLoader = fopen($targetDir.'/ClassLoader.php', 'w+');
  233. stream_copy_to_stream($sourceLoader, $targetLoader);
  234. fclose($sourceLoader);
  235. fclose($targetLoader);
  236. unset($sourceLoader, $targetLoader);
  237. $this->eventDispatcher->dispatchScript(ScriptEvents::POST_AUTOLOAD_DUMP, $this->devMode, array(), array(
  238. 'optimize' => (bool) $scanPsr0Packages,
  239. ));
  240. }
  241. public function buildPackageMap(InstallationManager $installationManager, PackageInterface $mainPackage, array $packages)
  242. {
  243. $packageMap = array(array($mainPackage, ''));
  244. foreach ($packages as $package) {
  245. if ($package instanceof AliasPackage) {
  246. continue;
  247. }
  248. $this->validatePackage($package);
  249. $packageMap[] = array(
  250. $package,
  251. $installationManager->getInstallPath($package),
  252. );
  253. }
  254. return $packageMap;
  255. }
  256. protected function validatePackage(PackageInterface $package)
  257. {
  258. $autoload = $package->getAutoload();
  259. if (!empty($autoload['psr-4']) && null !== $package->getTargetDir()) {
  260. $name = $package->getName();
  261. $package->getTargetDir();
  262. throw new \InvalidArgumentException("PSR-4 autoloading is incompatible with the target-dir property, remove the target-dir in package '$name'.");
  263. }
  264. if (!empty($autoload['psr-4'])) {
  265. foreach ($autoload['psr-4'] as $namespace => $dirs) {
  266. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  267. throw new \InvalidArgumentException("psr-4 namespaces must end with a namespace separator, '$namespace' does not, use '$namespace\\'.");
  268. }
  269. }
  270. }
  271. }
  272. public function parseAutoloads(array $packageMap, PackageInterface $mainPackage)
  273. {
  274. $mainPackageMap = array_shift($packageMap);
  275. $sortedPackageMap = $this->sortPackageMap($packageMap);
  276. $sortedPackageMap[] = $mainPackageMap;
  277. array_unshift($packageMap, $mainPackageMap);
  278. $psr0 = $this->parseAutoloadsType($packageMap, 'psr-0', $mainPackage);
  279. $psr4 = $this->parseAutoloadsType($packageMap, 'psr-4', $mainPackage);
  280. $classmap = $this->parseAutoloadsType($sortedPackageMap, 'classmap', $mainPackage);
  281. $files = $this->parseAutoloadsType($sortedPackageMap, 'files', $mainPackage);
  282. krsort($psr0);
  283. krsort($psr4);
  284. return array('psr-0' => $psr0, 'psr-4' => $psr4, 'classmap' => $classmap, 'files' => $files);
  285. }
  286. public function createLoader(array $autoloads)
  287. {
  288. $loader = new ClassLoader();
  289. if (isset($autoloads['psr-0'])) {
  290. foreach ($autoloads['psr-0'] as $namespace => $path) {
  291. $loader->add($namespace, $path);
  292. }
  293. }
  294. if (isset($autoloads['psr-4'])) {
  295. foreach ($autoloads['psr-4'] as $namespace => $path) {
  296. $loader->addPsr4($namespace, $path);
  297. }
  298. }
  299. return $loader;
  300. }
  301. protected function getIncludePathsFile(array $packageMap, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  302. {
  303. $includePaths = array();
  304. foreach ($packageMap as $item) {
  305. list($package, $installPath) = $item;
  306. if (null !== $package->getTargetDir() && strlen($package->getTargetDir()) > 0) {
  307. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  308. }
  309. foreach ($package->getIncludePaths() as $includePath) {
  310. $includePath = trim($includePath, '/');
  311. $includePaths[] = empty($installPath) ? $includePath : $installPath.'/'.$includePath;
  312. }
  313. }
  314. if (!$includePaths) {
  315. return;
  316. }
  317. $includePathsCode = '';
  318. foreach ($includePaths as $path) {
  319. $includePathsCode .= " " . $this->getPathCode($filesystem, $basePath, $vendorPath, $path) . ",\n";
  320. }
  321. return <<<EOF
  322. <?php
  323. // include_paths.php @generated by Composer
  324. \$vendorDir = $vendorPathCode;
  325. \$baseDir = $appBaseDirCode;
  326. return array(
  327. $includePathsCode);
  328. EOF;
  329. }
  330. protected function getIncludeFilesFile(array $files, Filesystem $filesystem, $basePath, $vendorPath, $vendorPathCode, $appBaseDirCode)
  331. {
  332. $filesCode = '';
  333. foreach ($files as $functionFile) {
  334. $filesCode .= ' '.$this->getPathCode($filesystem, $basePath, $vendorPath, $functionFile).",\n";
  335. }
  336. if (!$filesCode) {
  337. return false;
  338. }
  339. return <<<EOF
  340. <?php
  341. // autoload_files.php @generated by Composer
  342. \$vendorDir = $vendorPathCode;
  343. \$baseDir = $appBaseDirCode;
  344. return array(
  345. $filesCode);
  346. EOF;
  347. }
  348. protected function getPathCode(Filesystem $filesystem, $basePath, $vendorPath, $path)
  349. {
  350. if (!$filesystem->isAbsolutePath($path)) {
  351. $path = $basePath . '/' . $path;
  352. }
  353. $path = $filesystem->normalizePath($path);
  354. $baseDir = '';
  355. if (strpos($path.'/', $vendorPath.'/') === 0) {
  356. $path = substr($path, strlen($vendorPath));
  357. $baseDir = '$vendorDir';
  358. if ($path !== false) {
  359. $baseDir .= " . ";
  360. }
  361. } else {
  362. $path = $filesystem->normalizePath($filesystem->findShortestPath($basePath, $path, true));
  363. if (!$filesystem->isAbsolutePath($path)) {
  364. $baseDir = '$baseDir . ';
  365. $path = '/' . $path;
  366. }
  367. }
  368. if (preg_match('/\.phar$/', $path)) {
  369. $baseDir = "'phar://' . " . $baseDir;
  370. }
  371. return $baseDir . (($path !== false) ? var_export($path, true) : "");
  372. }
  373. protected function getAutoloadFile($vendorPathToTargetDirCode, $suffix)
  374. {
  375. return <<<AUTOLOAD
  376. <?php
  377. // autoload.php @generated by Composer
  378. require_once $vendorPathToTargetDirCode . '/autoload_real.php';
  379. return ComposerAutoloaderInit$suffix::getLoader();
  380. AUTOLOAD;
  381. }
  382. protected function getAutoloadRealFile($useClassMap, $useIncludePath, $targetDirLoader, $useIncludeFiles, $vendorPathCode, $appBaseDirCode, $suffix, $useGlobalIncludePath, $prependAutoloader, $classMapAuthoritative)
  383. {
  384. $file = <<<HEADER
  385. <?php
  386. // autoload_real.php @generated by Composer
  387. class ComposerAutoloaderInit$suffix
  388. {
  389. private static \$loader;
  390. public static function loadClassLoader(\$class)
  391. {
  392. if ('Composer\\Autoload\\ClassLoader' === \$class) {
  393. require __DIR__ . '/ClassLoader.php';
  394. }
  395. }
  396. public static function getLoader()
  397. {
  398. if (null !== self::\$loader) {
  399. return self::\$loader;
  400. }
  401. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'), true, $prependAutoloader);
  402. self::\$loader = \$loader = new \\Composer\\Autoload\\ClassLoader();
  403. spl_autoload_unregister(array('ComposerAutoloaderInit$suffix', 'loadClassLoader'));
  404. HEADER;
  405. if ($useIncludePath) {
  406. $file .= <<<'INCLUDE_PATH'
  407. $includePaths = require __DIR__ . '/include_paths.php';
  408. array_push($includePaths, get_include_path());
  409. set_include_path(join(PATH_SEPARATOR, $includePaths));
  410. INCLUDE_PATH;
  411. }
  412. $file .= <<<'PSR0'
  413. $map = require __DIR__ . '/autoload_namespaces.php';
  414. foreach ($map as $namespace => $path) {
  415. $loader->set($namespace, $path);
  416. }
  417. PSR0;
  418. $file .= <<<'PSR4'
  419. $map = require __DIR__ . '/autoload_psr4.php';
  420. foreach ($map as $namespace => $path) {
  421. $loader->setPsr4($namespace, $path);
  422. }
  423. PSR4;
  424. if ($useClassMap) {
  425. $file .= <<<'CLASSMAP'
  426. $classMap = require __DIR__ . '/autoload_classmap.php';
  427. if ($classMap) {
  428. $loader->addClassMap($classMap);
  429. }
  430. CLASSMAP;
  431. }
  432. if ($classMapAuthoritative) {
  433. $file .= <<<'CLASSMAPAUTHORITATIVE'
  434. $loader->setClassMapAuthoritative(true);
  435. CLASSMAPAUTHORITATIVE;
  436. }
  437. if ($useGlobalIncludePath) {
  438. $file .= <<<'INCLUDEPATH'
  439. $loader->setUseIncludePath(true);
  440. INCLUDEPATH;
  441. }
  442. if ($targetDirLoader) {
  443. $file .= <<<REGISTER_AUTOLOAD
  444. spl_autoload_register(array('ComposerAutoloaderInit$suffix', 'autoload'), true, true);
  445. REGISTER_AUTOLOAD;
  446. }
  447. $file .= <<<REGISTER_LOADER
  448. \$loader->register($prependAutoloader);
  449. REGISTER_LOADER;
  450. if ($useIncludeFiles) {
  451. $file .= <<<INCLUDE_FILES
  452. \$includeFiles = require __DIR__ . '/autoload_files.php';
  453. foreach (\$includeFiles as \$file) {
  454. composerRequire$suffix(\$file);
  455. }
  456. INCLUDE_FILES;
  457. }
  458. $file .= <<<METHOD_FOOTER
  459. return \$loader;
  460. }
  461. METHOD_FOOTER;
  462. $file .= $targetDirLoader;
  463. return $file . <<<FOOTER
  464. }
  465. function composerRequire$suffix(\$file)
  466. {
  467. require \$file;
  468. }
  469. FOOTER;
  470. }
  471. protected function parseAutoloadsType(array $packageMap, $type, PackageInterface $mainPackage)
  472. {
  473. $autoloads = array();
  474. foreach ($packageMap as $item) {
  475. list($package, $installPath) = $item;
  476. $autoload = $package->getAutoload();
  477. if ($this->devMode && $package === $mainPackage) {
  478. $autoload = array_merge_recursive($autoload, $package->getDevAutoload());
  479. }
  480. if (!isset($autoload[$type]) || !is_array($autoload[$type])) {
  481. continue;
  482. }
  483. if (null !== $package->getTargetDir() && $package !== $mainPackage) {
  484. $installPath = substr($installPath, 0, -strlen('/'.$package->getTargetDir()));
  485. }
  486. foreach ($autoload[$type] as $namespace => $paths) {
  487. foreach ((array) $paths as $path) {
  488. if (($type === 'files' || $type === 'classmap') && $package->getTargetDir() && !is_readable($installPath.'/'.$path)) {
  489. if ($package === $mainPackage) {
  490. $targetDir = str_replace('\\<dirsep\\>', '[\\\\/]', preg_quote(str_replace(array('/', '\\'), '<dirsep>', $package->getTargetDir())));
  491. $path = ltrim(preg_replace('{^'.$targetDir.'}', '', ltrim($path, '\\/')), '\\/');
  492. } else {
  493. $path = $package->getTargetDir() . '/' . $path;
  494. }
  495. }
  496. $relativePath = empty($installPath) ? (empty($path) ? '.' : $path) : $installPath.'/'.$path;
  497. if ($type === 'files' || $type === 'classmap') {
  498. $autoloads[] = $relativePath;
  499. continue;
  500. }
  501. $autoloads[$namespace][] = $relativePath;
  502. }
  503. }
  504. }
  505. return $autoloads;
  506. }
  507. protected function sortPackageMap(array $packageMap)
  508. {
  509. $packages = array();
  510. $paths = array();
  511. $usageList = array();
  512. foreach ($packageMap as $item) {
  513. list($package, $path) = $item;
  514. $name = $package->getName();
  515. $packages[$name] = $package;
  516. $paths[$name] = $path;
  517. foreach (array_merge($package->getRequires(), $package->getDevRequires()) as $link) {
  518. $target = $link->getTarget();
  519. $usageList[$target][] = $name;
  520. }
  521. }
  522. $computing = array();
  523. $computed = array();
  524. $computeImportance = function ($name) use (&$computeImportance, &$computing, &$computed, $usageList) {
  525. if (isset($computed[$name])) {
  526. return $computed[$name];
  527. }
  528. if (isset($computing[$name])) {
  529. return 0;
  530. }
  531. $computing[$name] = true;
  532. $weight = 0;
  533. if (isset($usageList[$name])) {
  534. foreach ($usageList[$name] as $user) {
  535. $weight -= 1 - $computeImportance($user);
  536. }
  537. }
  538. unset($computing[$name]);
  539. $computed[$name] = $weight;
  540. return $weight;
  541. };
  542. $weightList = array();
  543. foreach ($packages as $name => $package) {
  544. $weight = $computeImportance($name);
  545. $weightList[$name] = $weight;
  546. }
  547. $stable_sort = function (&$array) {
  548. static $transform, $restore;
  549. $i = 0;
  550. if (!$transform) {
  551. $transform = function (&$v, $k) use (&$i) {
  552. $v = array($v, ++$i, $k, $v);
  553. };
  554. $restore = function (&$v, $k) {
  555. $v = $v[3];
  556. };
  557. }
  558. array_walk($array, $transform);
  559. asort($array);
  560. array_walk($array, $restore);
  561. };
  562. $stable_sort($weightList);
  563. $sortedPackageMap = array();
  564. foreach (array_keys($weightList) as $name) {
  565. $sortedPackageMap[] = array($packages[$name], $paths[$name]);
  566. }
  567. return $sortedPackageMap;
  568. }
  569. }
  570. <?php
  571. namespace Composer\Autoload;
  572. use Symfony\Component\Finder\Finder;
  573. use Composer\IO\IOInterface;
  574. class ClassMapGenerator
  575. {
  576. public static function dump($dirs, $file)
  577. {
  578. $maps = array();
  579. foreach ($dirs as $dir) {
  580. $maps = array_merge($maps, static::createMap($dir));
  581. }
  582. file_put_contents($file, sprintf('<?php return %s;', var_export($maps, true)));
  583. }
  584. public static function createMap($path, $whitelist = null, IOInterface $io = null, $namespace = null)
  585. {
  586. if (is_string($path)) {
  587. if (is_file($path)) {
  588. $path = array(new \SplFileInfo($path));
  589. } elseif (is_dir($path)) {
  590. $path = Finder::create()->files()->followLinks()->name('/\.(php|inc|hh)$/')->in($path);
  591. } else {
  592. throw new \RuntimeException(
  593. 'Could not scan for classes inside "'.$path.
  594. '" which does not appear to be a file nor a folder'
  595. );
  596. }
  597. }
  598. $map = array();
  599. foreach ($path as $file) {
  600. $filePath = $file->getRealPath();
  601. if (!in_array(pathinfo($filePath, PATHINFO_EXTENSION), array('php', 'inc', 'hh'))) {
  602. continue;
  603. }
  604. if ($whitelist && !preg_match($whitelist, strtr($filePath, '\\', '/'))) {
  605. continue;
  606. }
  607. $classes = self::findClasses($filePath);
  608. foreach ($classes as $class) {
  609. if (null !== $namespace && 0 !== strpos($class, $namespace)) {
  610. continue;
  611. }
  612. if (!isset($map[$class])) {
  613. $map[$class] = $filePath;
  614. } elseif ($io && $map[$class] !== $filePath && !preg_match('{/(test|fixture|example)s?/}i', strtr($map[$class].' '.$filePath, '\\', '/'))) {
  615. $io->writeError(
  616. '<warning>Warning: Ambiguous class resolution, "'.$class.'"'.
  617. ' was found in both "'.$map[$class].'" and "'.$filePath.'", the first will be used.</warning>'
  618. );
  619. }
  620. }
  621. }
  622. return $map;
  623. }
  624. private static function findClasses($path)
  625. {
  626. $traits = version_compare(PHP_VERSION, '5.4', '<') ? '' : '|trait';
  627. try {
  628. $contents = @php_strip_whitespace($path);
  629. if (!$contents) {
  630. if (!file_exists($path)) {
  631. throw new \Exception('File does not exist');
  632. }
  633. if (!is_readable($path)) {
  634. throw new \Exception('File is not readable');
  635. }
  636. }
  637. } catch (\Exception $e) {
  638. throw new \RuntimeException('Could not scan for classes inside '.$path.": \n".$e->getMessage(), 0, $e);
  639. }
  640. if (!preg_match('{\b(?:class|interface'.$traits.')\s}i', $contents)) {
  641. return array();
  642. }
  643. $contents = preg_replace('{<<<\s*(\'?)(\w+)\\1(?:\r\n|\n|\r)(?:.*?)(?:\r\n|\n|\r)\\2(?=\r\n|\n|\r|;)}s', 'null', $contents);
  644. $contents = preg_replace('{"[^"\\\\]*(\\\\.[^"\\\\]*)*"|\'[^\'\\\\]*(\\\\.[^\'\\\\]*)*\'}s', 'null', $contents);
  645. if (substr($contents, 0, 2) !== '<?') {
  646. $contents = preg_replace('{^.+?<\?}s', '<?', $contents, 1, $replacements);
  647. if ($replacements === 0) {
  648. return array();
  649. }
  650. }
  651. $contents = preg_replace('{\?>.+<\?}s', '?><?', $contents);
  652. $pos = strrpos($contents, '?>');
  653. if (false !== $pos && false === strpos(substr($contents, $pos), '<?')) {
  654. $contents = substr($contents, 0, $pos);
  655. }
  656. preg_match_all('{
  657. (?:
  658. \b(?<![\$:>])(?P<type>class|interface'.$traits.') \s+ (?P<name>[a-zA-Z_\x7f-\xff:][a-zA-Z0-9_\x7f-\xff:\-]*)
  659. | \b(?<![\$:>])(?P<ns>namespace) (?P<nsname>\s+[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*(?:\s*\\\\\s*[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)*)? \s*[\{;]
  660. )
  661. }ix', $contents, $matches);
  662. $classes = array();
  663. $namespace = '';
  664. for ($i = 0, $len = count($matches['type']); $i < $len; $i++) {
  665. if (!empty($matches['ns'][$i])) {
  666. $namespace = str_replace(array(' ', "\t", "\r", "\n"), '', $matches['nsname'][$i]) . '\\';
  667. } else {
  668. $name = $matches['name'][$i];
  669. if ($name[0] === ':') {
  670. $name = 'xhp'.substr(str_replace(array('-', ':'), array('_', '__'), $name), 1);
  671. }
  672. $classes[] = ltrim($namespace . $name, '\\');
  673. }
  674. }
  675. return $classes;
  676. }
  677. }
  678. <?php
  679. namespace Composer;
  680. use Composer\IO\IOInterface;
  681. use Composer\Util\Filesystem;
  682. use Symfony\Component\Finder\Finder;
  683. class Cache
  684. {
  685. private static $cacheCollected = false;
  686. private $io;
  687. private $root;
  688. private $enabled = true;
  689. private $whitelist;
  690. private $filesystem;
  691. public function __construct(IOInterface $io, $cacheDir, $whitelist = 'a-z0-9.', Filesystem $filesystem = null)
  692. {
  693. $this->io = $io;
  694. $this->root = rtrim($cacheDir, '/\\') . '/';
  695. $this->whitelist = $whitelist;
  696. $this->filesystem = $filesystem ?: new Filesystem();
  697. if (!is_dir($this->root)) {
  698. if (!@mkdir($this->root, 0777, true)) {
  699. $this->enabled = false;
  700. }
  701. }
  702. }
  703. public function isEnabled()
  704. {
  705. return $this->enabled;
  706. }
  707. public function getRoot()
  708. {
  709. return $this->root;
  710. }
  711. public function read($file)
  712. {
  713. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  714. if ($this->enabled && file_exists($this->root . $file)) {
  715. if ($this->io->isDebug()) {
  716. $this->io->writeError('Reading '.$this->root . $file.' from cache');
  717. }
  718. return file_get_contents($this->root . $file);
  719. }
  720. return false;
  721. }
  722. public function write($file, $contents)
  723. {
  724. if ($this->enabled) {
  725. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  726. if ($this->io->isDebug()) {
  727. $this->io->writeError('Writing '.$this->root . $file.' into cache');
  728. }
  729. try {
  730. return file_put_contents($this->root . $file, $contents);
  731. } catch (\ErrorException $e) {
  732. if (preg_match('{^file_put_contents\(\): Only ([0-9]+) of ([0-9]+) bytes written}', $e->getMessage(), $m)) {
  733. unlink($this->root . $file);
  734. $message = sprintf(
  735. '<warning>Writing %1$s into cache failed after %2$u of %3$u bytes written, only %4$u bytes of free space available</warning>',
  736. $this->root . $file,
  737. $m[1],
  738. $m[2],
  739. @disk_free_space($this->root . dirname($file))
  740. );
  741. $this->io->writeError($message);
  742. return false;
  743. }
  744. throw $e;
  745. }
  746. }
  747. return false;
  748. }
  749. public function copyFrom($file, $source)
  750. {
  751. if ($this->enabled) {
  752. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  753. $this->filesystem->ensureDirectoryExists(dirname($this->root . $file));
  754. if ($this->io->isDebug()) {
  755. $this->io->writeError('Writing '.$this->root . $file.' into cache');
  756. }
  757. return copy($source, $this->root . $file);
  758. }
  759. return false;
  760. }
  761. public function copyTo($file, $target)
  762. {
  763. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  764. if ($this->enabled && file_exists($this->root . $file)) {
  765. touch($this->root . $file);
  766. if ($this->io->isDebug()) {
  767. $this->io->writeError('Reading '.$this->root . $file.' from cache');
  768. }
  769. return copy($this->root . $file, $target);
  770. }
  771. return false;
  772. }
  773. public function gcIsNecessary()
  774. {
  775. return (!self::$cacheCollected && !mt_rand(0, 50));
  776. }
  777. public function remove($file)
  778. {
  779. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  780. if ($this->enabled && file_exists($this->root . $file)) {
  781. return $this->filesystem->unlink($this->root . $file);
  782. }
  783. return false;
  784. }
  785. public function gc($ttl, $maxSize)
  786. {
  787. if ($this->enabled) {
  788. $expire = new \DateTime();
  789. $expire->modify('-'.$ttl.' seconds');
  790. $finder = $this->getFinder()->date('until '.$expire->format('Y-m-d H:i:s'));
  791. foreach ($finder as $file) {
  792. $this->filesystem->unlink($file->getPathname());
  793. }
  794. $totalSize = $this->filesystem->size($this->root);
  795. if ($totalSize > $maxSize) {
  796. $iterator = $this->getFinder()->sortByAccessedTime()->getIterator();
  797. while ($totalSize > $maxSize && $iterator->valid()) {
  798. $filepath = $iterator->current()->getPathname();
  799. $totalSize -= $this->filesystem->size($filepath);
  800. $this->filesystem->unlink($filepath);
  801. $iterator->next();
  802. }
  803. }
  804. self::$cacheCollected = true;
  805. return true;
  806. }
  807. return false;
  808. }
  809. public function sha1($file)
  810. {
  811. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  812. if ($this->enabled && file_exists($this->root . $file)) {
  813. return sha1_file($this->root . $file);
  814. }
  815. return false;
  816. }
  817. public function sha256($file)
  818. {
  819. $file = preg_replace('{[^'.$this->whitelist.']}i', '-', $file);
  820. if ($this->enabled && file_exists($this->root . $file)) {
  821. return hash_file('sha256', $this->root . $file);
  822. }
  823. return false;
  824. }
  825. protected function getFinder()
  826. {
  827. return Finder::create()->in($this->root)->files();
  828. }
  829. }
  830. <?php
  831. namespace Composer\Command;
  832. use Symfony\Component\Console\Input\InputInterface;
  833. use Symfony\Component\Console\Output\OutputInterface;
  834. class AboutCommand extends Command
  835. {
  836. protected function configure()
  837. {
  838. $this
  839. ->setName('about')
  840. ->setDescription('Short information about Composer')
  841. ->setHelp(<<<EOT
  842. <info>php composer.phar about</info>
  843. EOT
  844. )
  845. ;
  846. }
  847. protected function execute(InputInterface $input, OutputInterface $output)
  848. {
  849. $this->getIO()->write(<<<EOT
  850. <info>Composer - Package Management for PHP</info>
  851. <comment>Composer is a dependency manager tracking local dependencies of your projects and libraries.
  852. See http://getcomposer.org/ for more information.</comment>
  853. EOT
  854. );
  855. }
  856. }
  857. <?php
  858. namespace Composer\Command;
  859. use Composer\Factory;
  860. use Composer\IO\IOInterface;
  861. use Composer\DependencyResolver\Pool;
  862. use Composer\Repository\CompositeRepository;
  863. use Composer\Script\ScriptEvents;
  864. use Composer\Plugin\CommandEvent;
  865. use Composer\Plugin\PluginEvents;
  866. use Composer\Package\Version\VersionParser;
  867. use Symfony\Component\Console\Input\InputArgument;
  868. use Symfony\Component\Console\Input\InputInterface;
  869. use Symfony\Component\Console\Input\InputOption;
  870. use Symfony\Component\Console\Output\OutputInterface;
  871. class ArchiveCommand extends Command
  872. {
  873. protected function configure()
  874. {
  875. $this
  876. ->setName('archive')
  877. ->setDescription('Create an archive of this composer package')
  878. ->setDefinition(array(
  879. new InputArgument('package', InputArgument::OPTIONAL, 'The package to archive instead of the current project'),
  880. new InputArgument('version', InputArgument::OPTIONAL, 'A version constraint to find the package to archive'),
  881. new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the resulting archive: tar or zip', 'tar'),
  882. new InputOption('dir', false, InputOption::VALUE_REQUIRED, 'Write the archive to this directory', '.'),
  883. ))
  884. ->setHelp(<<<EOT
  885. The <info>archive</info> command creates an archive of the specified format
  886. containing the files and directories of the Composer project or the specified
  887. package in the specified version and writes it to the specified directory.
  888. <info>php composer.phar archive [--format=zip] [--dir=/foo] [package [version]]</info>
  889. EOT
  890. )
  891. ;
  892. }
  893. protected function execute(InputInterface $input, OutputInterface $output)
  894. {
  895. $composer = $this->getComposer(false);
  896. if ($composer) {
  897. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'archive', $input, $output);
  898. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  899. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_ARCHIVE_CMD);
  900. }
  901. $returnCode = $this->archive(
  902. $this->getIO(),
  903. $input->getArgument('package'),
  904. $input->getArgument('version'),
  905. $input->getOption('format'),
  906. $input->getOption('dir')
  907. );
  908. if (0 === $returnCode && $composer) {
  909. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ARCHIVE_CMD);
  910. }
  911. return $returnCode;
  912. }
  913. protected function archive(IOInterface $io, $packageName = null, $version = null, $format = 'tar', $dest = '.')
  914. {
  915. $config = Factory::createConfig();
  916. $factory = new Factory;
  917. $downloadManager = $factory->createDownloadManager($io, $config);
  918. $archiveManager = $factory->createArchiveManager($config, $downloadManager);
  919. if ($packageName) {
  920. $package = $this->selectPackage($io, $packageName, $version);
  921. if (!$package) {
  922. return 1;
  923. }
  924. } else {
  925. $package = $this->getComposer()->getPackage();
  926. }
  927. $io->writeError('<info>Creating the archive.</info>');
  928. $archiveManager->archive($package, $format, $dest);
  929. return 0;
  930. }
  931. protected function selectPackage(IOInterface $io, $packageName, $version = null)
  932. {
  933. $io->writeError('<info>Searching for the specified package.</info>');
  934. if ($composer = $this->getComposer(false)) {
  935. $localRepo = $composer->getRepositoryManager()->getLocalRepository();
  936. $repos = new CompositeRepository(array_merge(array($localRepo), $composer->getRepositoryManager()->getRepositories()));
  937. } else {
  938. $defaultRepos = Factory::createDefaultRepositories($this->getIO());
  939. $io->writeError('No composer.json found in the current directory, searching packages from ' . implode(', ', array_keys($defaultRepos)));
  940. $repos = new CompositeRepository($defaultRepos);
  941. }
  942. $pool = new Pool();
  943. $pool->addRepository($repos);
  944. $parser = new VersionParser();
  945. $constraint = ($version) ? $parser->parseConstraints($version) : null;
  946. $packages = $pool->whatProvides($packageName, $constraint, true);
  947. if (count($packages) > 1) {
  948. $package = reset($packages);
  949. $io->writeError('<info>Found multiple matches, selected '.$package->getPrettyString().'.</info>');
  950. $io->writeError('Alternatives were '.implode(', ', array_map(function ($p) { return $p->getPrettyString(); }, $packages)).'.');
  951. $io->writeError('<comment>Please use a more specific constraint to pick a different package.</comment>');
  952. } elseif ($packages) {
  953. $package = reset($packages);
  954. $io->writeError('<info>Found an exact match '.$package->getPrettyString().'.</info>');
  955. } else {
  956. $io->writeError('<error>Could not find a package matching '.$packageName.'.</error>');
  957. return false;
  958. }
  959. return $package;
  960. }
  961. }
  962. <?php
  963. namespace Composer\Command;
  964. use Composer\Cache;
  965. use Composer\Factory;
  966. use Symfony\Component\Console\Input\InputInterface;
  967. use Symfony\Component\Console\Output\OutputInterface;
  968. class ClearCacheCommand extends Command
  969. {
  970. protected function configure()
  971. {
  972. $this
  973. ->setName('clear-cache')
  974. ->setAliases(array('clearcache'))
  975. ->setDescription('Clears composer\'s internal package cache.')
  976. ->setHelp(<<<EOT
  977. The <info>clear-cache</info> deletes all cached packages from composer's
  978. cache directory.
  979. EOT
  980. )
  981. ;
  982. }
  983. protected function execute(InputInterface $input, OutputInterface $output)
  984. {
  985. $config = Factory::createConfig();
  986. $io = $this->getIO();
  987. $cachePaths = array(
  988. 'cache-dir' => $config->get('cache-dir'),
  989. 'cache-files-dir' => $config->get('cache-files-dir'),
  990. 'cache-repo-dir' => $config->get('cache-repo-dir'),
  991. 'cache-vcs-dir' => $config->get('cache-vcs-dir'),
  992. );
  993. foreach ($cachePaths as $key => $cachePath) {
  994. $cachePath = realpath($cachePath);
  995. if (!$cachePath) {
  996. $io->writeError("<info>Cache directory does not exist ($key): $cachePath</info>");
  997. continue;
  998. }
  999. $cache = new Cache($io, $cachePath);
  1000. if (!$cache->isEnabled()) {
  1001. $io->writeError("<info>Cache is not enabled ($key): $cachePath</info>");
  1002. continue;
  1003. }
  1004. $io->writeError("<info>Clearing cache ($key): $cachePath</info>");
  1005. $cache->gc(0, 0);
  1006. }
  1007. $io->writeError('<info>All caches cleared.</info>');
  1008. }
  1009. }
  1010. <?php
  1011. namespace Composer\Command;
  1012. use Composer\Composer;
  1013. use Composer\Console\Application;
  1014. use Composer\IO\IOInterface;
  1015. use Composer\IO\NullIO;
  1016. use Symfony\Component\Console\Input\InputInterface;
  1017. use Symfony\Component\Console\Output\OutputInterface;
  1018. use Symfony\Component\Console\Command\Command as BaseCommand;
  1019. abstract class Command extends BaseCommand
  1020. {
  1021. private $composer;
  1022. private $io;
  1023. public function getComposer($required = true, $disablePlugins = false)
  1024. {
  1025. if (null === $this->composer) {
  1026. $application = $this->getApplication();
  1027. if ($application instanceof Application) {
  1028. $this->composer = $application->getComposer($required, $disablePlugins);
  1029. } elseif ($required) {
  1030. throw new \RuntimeException(
  1031. 'Could not create a Composer\Composer instance, you must inject '.
  1032. 'one if this command is not used with a Composer\Console\Application instance'
  1033. );
  1034. }
  1035. }
  1036. return $this->composer;
  1037. }
  1038. public function setComposer(Composer $composer)
  1039. {
  1040. $this->composer = $composer;
  1041. }
  1042. public function resetComposer()
  1043. {
  1044. $this->composer = null;
  1045. $this->getApplication()->resetComposer();
  1046. }
  1047. public function getIO()
  1048. {
  1049. if (null === $this->io) {
  1050. $application = $this->getApplication();
  1051. if ($application instanceof Application) {
  1052. $this->io = $application->getIO();
  1053. } else {
  1054. $this->io = new NullIO();
  1055. }
  1056. }
  1057. return $this->io;
  1058. }
  1059. public function setIO(IOInterface $io)
  1060. {
  1061. $this->io = $io;
  1062. }
  1063. protected function initialize(InputInterface $input, OutputInterface $output)
  1064. {
  1065. if (true === $input->hasParameterOption(array('--no-ansi')) && $input->hasOption('no-progress')) {
  1066. $input->setOption('no-progress', true);
  1067. }
  1068. parent::initialize($input, $output);
  1069. }
  1070. }
  1071. <?php
  1072. namespace Composer\Command;
  1073. use Symfony\Component\Console\Input\InputInterface;
  1074. use Symfony\Component\Console\Input\InputArgument;
  1075. use Symfony\Component\Console\Input\InputOption;
  1076. use Symfony\Component\Console\Output\OutputInterface;
  1077. use Composer\Config;
  1078. use Composer\Config\JsonConfigSource;
  1079. use Composer\Factory;
  1080. use Composer\Json\JsonFile;
  1081. class ConfigCommand extends Command
  1082. {
  1083. protected $config;
  1084. protected $configFile;
  1085. protected $configSource;
  1086. protected $authConfigFile;
  1087. protected $authConfigSource;
  1088. protected function configure()
  1089. {
  1090. $this
  1091. ->setName('config')
  1092. ->setDescription('Set config options')
  1093. ->setDefinition(array(
  1094. new InputOption('global', 'g', InputOption::VALUE_NONE, 'Apply command to the global config file'),
  1095. new InputOption('editor', 'e', InputOption::VALUE_NONE, 'Open editor'),
  1096. new InputOption('auth', 'a', InputOption::VALUE_NONE, 'Affect auth config file (only used for --editor)'),
  1097. new InputOption('unset', null, InputOption::VALUE_NONE, 'Unset the given setting-key'),
  1098. new InputOption('list', 'l', InputOption::VALUE_NONE, 'List configuration settings'),
  1099. new InputOption('file', 'f', InputOption::VALUE_REQUIRED, 'If you want to choose a different composer.json or config.json', 'composer.json'),
  1100. new InputOption('absolute', null, InputOption::VALUE_NONE, 'Returns absolute paths when fetching *-dir config values instead of relative'),
  1101. new InputArgument('setting-key', null, 'Setting key'),
  1102. new InputArgument('setting-value', InputArgument::IS_ARRAY, 'Setting value'),
  1103. ))
  1104. ->setHelp(<<<EOT
  1105. This command allows you to edit some basic composer settings in either the
  1106. local composer.json file or the global config.json file.
  1107. To set a config setting:
  1108. <comment>%command.full_name% bin-dir bin/</comment>
  1109. To read a config setting:
  1110. <comment>%command.full_name% bin-dir</comment>
  1111. Outputs: <info>bin</info>
  1112. To edit the global config.json file:
  1113. <comment>%command.full_name% --global</comment>
  1114. To add a repository:
  1115. <comment>%command.full_name% repositories.foo vcs http://bar.com</comment>
  1116. To remove a repository (repo is a short alias for repositories):
  1117. <comment>%command.full_name% --unset repo.foo</comment>
  1118. To disable packagist:
  1119. <comment>%command.full_name% repo.packagist false</comment>
  1120. You can alter repositories in the global config.json file by passing in the
  1121. <info>--global</info> option.
  1122. To edit the file in an external editor:
  1123. <comment>%command.full_name% --editor</comment>
  1124. To choose your editor you can set the "EDITOR" env variable.
  1125. To get a list of configuration values in the file:
  1126. <comment>%command.full_name% --list</comment>
  1127. You can always pass more than one option. As an example, if you want to edit the
  1128. global config.json file.
  1129. <comment>%command.full_name% --editor --global</comment>
  1130. EOT
  1131. )
  1132. ;
  1133. }
  1134. protected function initialize(InputInterface $input, OutputInterface $output)
  1135. {
  1136. parent::initialize($input, $output);
  1137. if ($input->getOption('global') && 'composer.json' !== $input->getOption('file')) {
  1138. throw new \RuntimeException('--file and --global can not be combined');
  1139. }
  1140. $this->config = Factory::createConfig($this->getIO());
  1141. $configFile = $input->getOption('global')
  1142. ? ($this->config->get('home') . '/config.json')
  1143. : $input->getOption('file');
  1144. $this->configFile = new JsonFile($configFile);
  1145. $this->configSource = new JsonConfigSource($this->configFile);
  1146. $authConfigFile = $input->getOption('global')
  1147. ? ($this->config->get('home') . '/auth.json')
  1148. : dirname(realpath($input->getOption('file'))) . '/auth.json';
  1149. $this->authConfigFile = new JsonFile($authConfigFile);
  1150. $this->authConfigSource = new JsonConfigSource($this->authConfigFile, true);
  1151. if ($input->getOption('global') && !$this->configFile->exists()) {
  1152. touch($this->configFile->getPath());
  1153. $this->configFile->write(array('config' => new \ArrayObject));
  1154. @chmod($this->configFile->getPath(), 0600);
  1155. }
  1156. if ($input->getOption('global') && !$this->authConfigFile->exists()) {
  1157. touch($this->authConfigFile->getPath());
  1158. $this->authConfigFile->write(array('http-basic' => new \ArrayObject, 'github-oauth' => new \ArrayObject));
  1159. @chmod($this->authConfigFile->getPath(), 0600);
  1160. }
  1161. if (!$this->configFile->exists()) {
  1162. throw new \RuntimeException(sprintf('File "%s" cannot be found in the current directory', $configFile));
  1163. }
  1164. }
  1165. protected function execute(InputInterface $input, OutputInterface $output)
  1166. {
  1167. if ($input->getOption('editor')) {
  1168. $editor = escapeshellcmd(getenv('EDITOR'));
  1169. if (!$editor) {
  1170. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  1171. $editor = 'notepad';
  1172. } else {
  1173. foreach (array('vim', 'vi', 'nano', 'pico', 'ed') as $candidate) {
  1174. if (exec('which '.$candidate)) {
  1175. $editor = $candidate;
  1176. break;
  1177. }
  1178. }
  1179. }
  1180. }
  1181. $file = $input->getOption('auth') ? $this->authConfigFile->getPath() : $this->configFile->getPath();
  1182. system($editor . ' ' . $file . (defined('PHP_WINDOWS_VERSION_BUILD') ? '' : ' > `tty`'));
  1183. return 0;
  1184. }
  1185. if (!$input->getOption('global')) {
  1186. $this->config->merge($this->configFile->read());
  1187. $this->config->merge(array('config' => $this->authConfigFile->exists() ? $this->authConfigFile->read() : array()));
  1188. }
  1189. if ($input->getOption('list')) {
  1190. $this->listConfiguration($this->config->all(), $this->config->raw(), $output);
  1191. return 0;
  1192. }
  1193. $settingKey = $input->getArgument('setting-key');
  1194. if (!$settingKey) {
  1195. return 0;
  1196. }
  1197. if (array() !== $input->getArgument('setting-value') && $input->getOption('unset')) {
  1198. throw new \RuntimeException('You can not combine a setting value with --unset');
  1199. }
  1200. if (array() === $input->getArgument('setting-value') && !$input->getOption('unset')) {
  1201. $data = $this->config->all();
  1202. if (preg_match('/^repos?(?:itories)?(?:\.(.+))?/', $settingKey, $matches)) {
  1203. if (empty($matches[1])) {
  1204. $value = isset($data['repositories']) ? $data['repositories'] : array();
  1205. } else {
  1206. if (!isset($data['repositories'][$matches[1]])) {
  1207. throw new \InvalidArgumentException('There is no '.$matches[1].' repository defined');
  1208. }
  1209. $value = $data['repositories'][$matches[1]];
  1210. }
  1211. } elseif (strpos($settingKey, '.')) {
  1212. $bits = explode('.', $settingKey);
  1213. $data = $data['config'];
  1214. foreach ($bits as $bit) {
  1215. if (isset($data[$bit])) {
  1216. $data = $data[$bit];
  1217. } elseif (isset($data[implode('.', $bits)])) {
  1218. $data = $data[implode('.', $bits)];
  1219. break;
  1220. } else {
  1221. throw new \RuntimeException($settingKey.' is not defined');
  1222. }
  1223. array_shift($bits);
  1224. }
  1225. $value = $data;
  1226. } elseif (isset($data['config'][$settingKey])) {
  1227. $value = $this->config->get($settingKey, $input->getOption('absolute') ? 0 : Config::RELATIVE_PATHS);
  1228. } else {
  1229. throw new \RuntimeException($settingKey.' is not defined');
  1230. }
  1231. if (is_array($value)) {
  1232. $value = json_encode($value);
  1233. }
  1234. $this->getIO()->write($value);
  1235. return 0;
  1236. }
  1237. $values = $input->getArgument('setting-value');
  1238. $booleanValidator = function ($val) { return in_array($val, array('true', 'false', '1', '0'), true); };
  1239. $booleanNormalizer = function ($val) { return $val !== 'false' && (bool) $val; };
  1240. $uniqueConfigValues = array(
  1241. 'process-timeout' => array('is_numeric', 'intval'),
  1242. 'use-include-path' => array($booleanValidator, $booleanNormalizer),
  1243. 'preferred-install' => array(
  1244. function ($val) { return in_array($val, array('auto', 'source', 'dist'), true); },
  1245. function ($val) { return $val; }
  1246. ),
  1247. 'store-auths' => array(
  1248. function ($val) { return in_array($val, array('true', 'false', 'prompt'), true); },
  1249. function ($val) {
  1250. if ('prompt' === $val) {
  1251. return 'prompt';
  1252. }
  1253. return $val !== 'false' && (bool) $val;
  1254. }
  1255. ),
  1256. 'notify-on-install' => array($booleanValidator, $booleanNormalizer),
  1257. 'vendor-dir' => array('is_string', function ($val) { return $val; }),
  1258. 'bin-dir' => array('is_string', function ($val) { return $val; }),
  1259. 'cache-dir' => array('is_string', function ($val) { return $val; }),
  1260. 'cache-files-dir' => array('is_string', function ($val) { return $val; }),
  1261. 'cache-repo-dir' => array('is_string', function ($val) { return $val; }),
  1262. 'cache-vcs-dir' => array('is_string', function ($val) { return $val; }),
  1263. 'cache-ttl' => array('is_numeric', 'intval'),
  1264. 'cache-files-ttl' => array('is_numeric', 'intval'),
  1265. 'cache-files-maxsize' => array(
  1266. function ($val) { return preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $val) > 0; },
  1267. function ($val) { return $val; }
  1268. ),
  1269. 'discard-changes' => array(
  1270. function ($val) { return in_array($val, array('stash', 'true', 'false', '1', '0'), true); },
  1271. function ($val) {
  1272. if ('stash' === $val) {
  1273. return 'stash';
  1274. }
  1275. return $val !== 'false' && (bool) $val;
  1276. }
  1277. ),
  1278. 'autoloader-suffix' => array('is_string', function ($val) { return $val === 'null' ? null : $val; }),
  1279. 'optimize-autoloader' => array($booleanValidator, $booleanNormalizer),
  1280. 'classmap-authoritative' => array($booleanValidator, $booleanNormalizer),
  1281. 'prepend-autoloader' => array($booleanValidator, $booleanNormalizer),
  1282. 'github-expose-hostname' => array($booleanValidator, $booleanNormalizer),
  1283. );
  1284. $multiConfigValues = array(
  1285. 'github-protocols' => array(
  1286. function ($vals) {
  1287. if (!is_array($vals)) {
  1288. return 'array expected';
  1289. }
  1290. foreach ($vals as $val) {
  1291. if (!in_array($val, array('git', 'https', 'ssh'))) {
  1292. return 'valid protocols include: git, https, ssh';
  1293. }
  1294. }
  1295. return true;
  1296. },
  1297. function ($vals) {
  1298. return $vals;
  1299. }
  1300. ),
  1301. 'github-domains' => array(
  1302. function ($vals) {
  1303. if (!is_array($vals)) {
  1304. return 'array expected';
  1305. }
  1306. return true;
  1307. },
  1308. function ($vals) {
  1309. return $vals;
  1310. }
  1311. ),
  1312. );
  1313. foreach ($uniqueConfigValues as $name => $callbacks) {
  1314. if ($settingKey === $name) {
  1315. if ($input->getOption('unset')) {
  1316. return $this->configSource->removeConfigSetting($settingKey);
  1317. }
  1318. list($validator, $normalizer) = $callbacks;
  1319. if (1 !== count($values)) {
  1320. throw new \RuntimeException('You can only pass one value. Example: php composer.phar config process-timeout 300');
  1321. }
  1322. if (true !== $validation = $validator($values[0])) {
  1323. throw new \RuntimeException(sprintf(
  1324. '"%s" is an invalid value'.($validation ? ' ('.$validation.')' : ''),
  1325. $values[0]
  1326. ));
  1327. }
  1328. return $this->configSource->addConfigSetting($settingKey, $normalizer($values[0]));
  1329. }
  1330. }
  1331. foreach ($multiConfigValues as $name => $callbacks) {
  1332. if ($settingKey === $name) {
  1333. if ($input->getOption('unset')) {
  1334. return $this->configSource->removeConfigSetting($settingKey);
  1335. }
  1336. list($validator, $normalizer) = $callbacks;
  1337. if (true !== $validation = $validator($values)) {
  1338. throw new \RuntimeException(sprintf(
  1339. '%s is an invalid value'.($validation ? ' ('.$validation.')' : ''),
  1340. json_encode($values)
  1341. ));
  1342. }
  1343. return $this->configSource->addConfigSetting($settingKey, $normalizer($values));
  1344. }
  1345. }
  1346. if (preg_match('/^repos?(?:itories)?\.(.+)/', $settingKey, $matches)) {
  1347. if ($input->getOption('unset')) {
  1348. return $this->configSource->removeRepository($matches[1]);
  1349. }
  1350. if (2 === count($values)) {
  1351. return $this->configSource->addRepository($matches[1], array(
  1352. 'type' => $values[0],
  1353. 'url' => $values[1],
  1354. ));
  1355. }
  1356. if (1 === count($values)) {
  1357. $bool = strtolower($values[0]);
  1358. if (true === $booleanValidator($bool) && false === $booleanNormalizer($bool)) {
  1359. return $this->configSource->addRepository($matches[1], false);
  1360. }
  1361. }
  1362. throw new \RuntimeException('You must pass the type and a url. Example: php composer.phar config repositories.foo vcs http://bar.com');
  1363. }
  1364. if (preg_match('/^(github-oauth|http-basic)\.(.+)/', $settingKey, $matches)) {
  1365. if ($input->getOption('unset')) {
  1366. $this->authConfigSource->removeConfigSetting($matches[1].'.'.$matches[2]);
  1367. $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
  1368. return;
  1369. }
  1370. if ($matches[1] === 'github-oauth') {
  1371. if (1 !== count($values)) {
  1372. throw new \RuntimeException('Too many arguments, expected only one token');
  1373. }
  1374. $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
  1375. $this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], $values[0]);
  1376. } elseif ($matches[1] === 'http-basic') {
  1377. if (2 !== count($values)) {
  1378. throw new \RuntimeException('Expected two arguments (username, password), got '.count($values));
  1379. }
  1380. $this->configSource->removeConfigSetting($matches[1].'.'.$matches[2]);
  1381. $this->authConfigSource->addConfigSetting($matches[1].'.'.$matches[2], array('username' => $values[0], 'password' => $values[1]));
  1382. }
  1383. return;
  1384. }
  1385. throw new \InvalidArgumentException('Setting '.$settingKey.' does not exist or is not supported by this command');
  1386. }
  1387. protected function listConfiguration(array $contents, array $rawContents, OutputInterface $output, $k = null)
  1388. {
  1389. $origK = $k;
  1390. foreach ($contents as $key => $value) {
  1391. if ($k === null && !in_array($key, array('config', 'repositories'))) {
  1392. continue;
  1393. }
  1394. $rawVal = isset($rawContents[$key]) ? $rawContents[$key] : null;
  1395. if (is_array($value) && (!is_numeric(key($value)) || ($key === 'repositories' && null === $k))) {
  1396. $k .= preg_replace('{^config\.}', '', $key . '.');
  1397. $this->listConfiguration($value, $rawVal, $output, $k);
  1398. if (substr_count($k, '.') > 1) {
  1399. $k = str_split($k, strrpos($k, '.', -2));
  1400. $k = $k[0] . '.';
  1401. } else {
  1402. $k = $origK;
  1403. }
  1404. continue;
  1405. }
  1406. if (is_array($value)) {
  1407. $value = array_map(function ($val) {
  1408. return is_array($val) ? json_encode($val) : $val;
  1409. }, $value);
  1410. $value = '['.implode(', ', $value).']';
  1411. }
  1412. if (is_bool($value)) {
  1413. $value = var_export($value, true);
  1414. }
  1415. if (is_string($rawVal) && $rawVal != $value) {
  1416. $this->getIO()->write('[<comment>' . $k . $key . '</comment>] <info>' . $rawVal . ' (' . $value . ')</info>');
  1417. } else {
  1418. $this->getIO()->write('[<comment>' . $k . $key . '</comment>] <info>' . $value . '</info>');
  1419. }
  1420. }
  1421. }
  1422. }
  1423. <?php
  1424. namespace Composer\Command;
  1425. use Composer\Config;
  1426. use Composer\Factory;
  1427. use Composer\Installer;
  1428. use Composer\Installer\ProjectInstaller;
  1429. use Composer\Installer\InstallationManager;
  1430. use Composer\IO\IOInterface;
  1431. use Composer\Package\BasePackage;
  1432. use Composer\DependencyResolver\Pool;
  1433. use Composer\DependencyResolver\Operation\InstallOperation;
  1434. use Composer\Package\Version\VersionSelector;
  1435. use Composer\Repository\ComposerRepository;
  1436. use Composer\Repository\CompositeRepository;
  1437. use Composer\Repository\FilesystemRepository;
  1438. use Composer\Repository\InstalledFilesystemRepository;
  1439. use Composer\Script\ScriptEvents;
  1440. use Symfony\Component\Console\Input\InputArgument;
  1441. use Symfony\Component\Console\Input\InputInterface;
  1442. use Symfony\Component\Console\Input\InputOption;
  1443. use Symfony\Component\Console\Output\OutputInterface;
  1444. use Symfony\Component\Finder\Finder;
  1445. use Composer\Json\JsonFile;
  1446. use Composer\Config\JsonConfigSource;
  1447. use Composer\Util\Filesystem;
  1448. use Composer\Util\RemoteFilesystem;
  1449. use Composer\Package\Version\VersionParser;
  1450. class CreateProjectCommand extends Command
  1451. {
  1452. protected function configure()
  1453. {
  1454. $this
  1455. ->setName('create-project')
  1456. ->setDescription('Create new project from a package into given directory.')
  1457. ->setDefinition(array(
  1458. new InputArgument('package', InputArgument::OPTIONAL, 'Package name to be installed'),
  1459. new InputArgument('directory', InputArgument::OPTIONAL, 'Directory where the files should be created'),
  1460. new InputArgument('version', InputArgument::OPTIONAL, 'Version, will default to latest'),
  1461. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum-stability allowed (unless a version is specified).'),
  1462. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  1463. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  1464. new InputOption('repository-url', null, InputOption::VALUE_REQUIRED, 'Pick a different repository url to look for the package.'),
  1465. new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
  1466. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
  1467. new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Whether to disable plugins.'),
  1468. new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
  1469. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Whether to prevent execution of all defined scripts in the root package.'),
  1470. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  1471. new InputOption('keep-vcs', null, InputOption::VALUE_NONE, 'Whether to prevent deletion vcs folder.'),
  1472. new InputOption('no-install', null, InputOption::VALUE_NONE, 'Whether to skip installation of the package dependencies.'),
  1473. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  1474. ))
  1475. ->setHelp(<<<EOT
  1476. The <info>create-project</info> command creates a new project from a given
  1477. package into a new directory. If executed without params and in a directory
  1478. with a composer.json file it installs the packages for the current project.
  1479. You can use this command to bootstrap new projects or setup a clean
  1480. version-controlled installation for developers of your project.
  1481. <info>php composer.phar create-project vendor/project target-directory [version]</info>
  1482. You can also specify the version with the package name using = or : as separator.
  1483. To install unstable packages, either specify the version you want, or use the
  1484. --stability=dev (where dev can be one of RC, beta, alpha or dev).
  1485. To setup a developer workable version you should create the project using the source
  1486. controlled code by appending the <info>'--prefer-source'</info> flag.
  1487. To install a package from another repository than the default one you
  1488. can pass the <info>'--repository-url=http://myrepository.org'</info> flag.
  1489. EOT
  1490. )
  1491. ;
  1492. }
  1493. protected function execute(InputInterface $input, OutputInterface $output)
  1494. {
  1495. $config = Factory::createConfig();
  1496. $preferSource = false;
  1497. $preferDist = false;
  1498. $this->updatePreferredOptions($config, $input, $preferSource, $preferDist);
  1499. if ($input->getOption('no-custom-installers')) {
  1500. $this->getIO()->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
  1501. $input->setOption('no-plugins', true);
  1502. }
  1503. return $this->installProject(
  1504. $this->getIO(),
  1505. $config,
  1506. $input->getArgument('package'),
  1507. $input->getArgument('directory'),
  1508. $input->getArgument('version'),
  1509. $input->getOption('stability'),
  1510. $preferSource,
  1511. $preferDist,
  1512. !$input->getOption('no-dev'),
  1513. $input->getOption('repository-url'),
  1514. $input->getOption('no-plugins'),
  1515. $input->getOption('no-scripts'),
  1516. $input->getOption('keep-vcs'),
  1517. $input->getOption('no-progress'),
  1518. $input->getOption('no-install'),
  1519. $input->getOption('ignore-platform-reqs'),
  1520. $input
  1521. );
  1522. }
  1523. public function installProject(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false, $noInstall = false, $ignorePlatformReqs = false, InputInterface $input)
  1524. {
  1525. $oldCwd = getcwd();
  1526. $io->loadConfiguration($config);
  1527. if ($packageName !== null) {
  1528. $installedFromVcs = $this->installRootPackage($io, $config, $packageName, $directory, $packageVersion, $stability, $preferSource, $preferDist, $installDevPackages, $repositoryUrl, $disablePlugins, $noScripts, $keepVcs, $noProgress);
  1529. } else {
  1530. $installedFromVcs = false;
  1531. }
  1532. $composer = Factory::create($io, null, $disablePlugins);
  1533. $fs = new Filesystem();
  1534. if ($noScripts === false) {
  1535. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_ROOT_PACKAGE_INSTALL, $installDevPackages);
  1536. }
  1537. $rootPackageConfig = $composer->getConfig();
  1538. $this->updatePreferredOptions($rootPackageConfig, $input, $preferSource, $preferDist);
  1539. if ($noInstall === false) {
  1540. $installer = Installer::create($io, $composer);
  1541. $installer->setPreferSource($preferSource)
  1542. ->setPreferDist($preferDist)
  1543. ->setDevMode($installDevPackages)
  1544. ->setRunScripts(!$noScripts)
  1545. ->setIgnorePlatformRequirements($ignorePlatformReqs);
  1546. if ($disablePlugins) {
  1547. $installer->disablePlugins();
  1548. }
  1549. $status = $installer->run();
  1550. if (0 !== $status) {
  1551. return $status;
  1552. }
  1553. }
  1554. $hasVcs = $installedFromVcs;
  1555. if (!$keepVcs && $installedFromVcs
  1556. && (
  1557. !$io->isInteractive()
  1558. || $io->askConfirmation('<info>Do you want to remove the existing VCS (.git, .svn..) history?</info> [<comment>Y,n</comment>]? ', true)
  1559. )
  1560. ) {
  1561. $finder = new Finder();
  1562. $finder->depth(0)->directories()->in(getcwd())->ignoreVCS(false)->ignoreDotFiles(false);
  1563. foreach (array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg') as $vcsName) {
  1564. $finder->name($vcsName);
  1565. }
  1566. try {
  1567. $dirs = iterator_to_array($finder);
  1568. unset($finder);
  1569. foreach ($dirs as $dir) {
  1570. if (!$fs->removeDirectory($dir)) {
  1571. throw new \RuntimeException('Could not remove '.$dir);
  1572. }
  1573. }
  1574. } catch (\Exception $e) {
  1575. $io->writeError('<error>An error occurred while removing the VCS metadata: '.$e->getMessage().'</error>');
  1576. }
  1577. $hasVcs = false;
  1578. }
  1579. if (!$hasVcs) {
  1580. $package = $composer->getPackage();
  1581. $configSource = new JsonConfigSource(new JsonFile('composer.json'));
  1582. foreach (BasePackage::$supportedLinkTypes as $type => $meta) {
  1583. foreach ($package->{'get'.$meta['method']}() as $link) {
  1584. if ($link->getPrettyConstraint() === 'self.version') {
  1585. $configSource->addLink($type, $link->getTarget(), $package->getPrettyVersion());
  1586. }
  1587. }
  1588. }
  1589. }
  1590. if ($noScripts === false) {
  1591. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_CREATE_PROJECT_CMD, $installDevPackages);
  1592. }
  1593. chdir($oldCwd);
  1594. $vendorComposerDir = $composer->getConfig()->get('vendor-dir').'/composer';
  1595. if (is_dir($vendorComposerDir) && $fs->isDirEmpty($vendorComposerDir)) {
  1596. @rmdir($vendorComposerDir);
  1597. $vendorDir = $composer->getConfig()->get('vendor-dir');
  1598. if (is_dir($vendorDir) && $fs->isDirEmpty($vendorDir)) {
  1599. @rmdir($vendorDir);
  1600. }
  1601. }
  1602. return 0;
  1603. }
  1604. protected function installRootPackage(IOInterface $io, Config $config, $packageName, $directory = null, $packageVersion = null, $stability = 'stable', $preferSource = false, $preferDist = false, $installDevPackages = false, $repositoryUrl = null, $disablePlugins = false, $noScripts = false, $keepVcs = false, $noProgress = false)
  1605. {
  1606. if (null === $repositoryUrl) {
  1607. $sourceRepo = new CompositeRepository(Factory::createDefaultRepositories($io, $config));
  1608. } elseif ("json" === pathinfo($repositoryUrl, PATHINFO_EXTENSION) && file_exists($repositoryUrl)) {
  1609. $json = new JsonFile($repositoryUrl, new RemoteFilesystem($io, $config));
  1610. $data = $json->read();
  1611. if (!empty($data['packages']) || !empty($data['includes']) || !empty($data['provider-includes'])) {
  1612. $sourceRepo = new ComposerRepository(array('url' => 'file://' . strtr(realpath($repositoryUrl), '\\', '/')), $io, $config);
  1613. } else {
  1614. $sourceRepo = new FilesystemRepository($json);
  1615. }
  1616. } elseif (0 === strpos($repositoryUrl, 'http')) {
  1617. $sourceRepo = new ComposerRepository(array('url' => $repositoryUrl), $io, $config);
  1618. } else {
  1619. throw new \InvalidArgumentException("Invalid repository url given. Has to be a .json file or an http url.");
  1620. }
  1621. $parser = new VersionParser();
  1622. $requirements = $parser->parseNameVersionPairs(array($packageName));
  1623. $name = strtolower($requirements[0]['name']);
  1624. if (!$packageVersion && isset($requirements[0]['version'])) {
  1625. $packageVersion = $requirements[0]['version'];
  1626. }
  1627. if (null === $stability) {
  1628. if (preg_match('{^[^,\s]*?@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $packageVersion, $match)) {
  1629. $stability = $match[1];
  1630. } else {
  1631. $stability = VersionParser::parseStability($packageVersion);
  1632. }
  1633. }
  1634. $stability = VersionParser::normalizeStability($stability);
  1635. if (!isset(BasePackage::$stabilities[$stability])) {
  1636. throw new \InvalidArgumentException('Invalid stability provided ('.$stability.'), must be one of: '.implode(', ', array_keys(BasePackage::$stabilities)));
  1637. }
  1638. $pool = new Pool($stability);
  1639. $pool->addRepository($sourceRepo);
  1640. $versionSelector = new VersionSelector($pool);
  1641. $package = $versionSelector->findBestCandidate($name, $packageVersion);
  1642. if (!$package) {
  1643. throw new \InvalidArgumentException("Could not find package $name" . ($packageVersion ? " with version $packageVersion." : " with stability $stability."));
  1644. }
  1645. if (null === $directory) {
  1646. $parts = explode("/", $name, 2);
  1647. $directory = getcwd() . DIRECTORY_SEPARATOR . array_pop($parts);
  1648. }
  1649. $io->writeError('<info>Installing ' . $package->getName() . ' (' . VersionParser::formatVersion($package, false) . ')</info>');
  1650. if ($disablePlugins) {
  1651. $io->writeError('<info>Plugins have been disabled.</info>');
  1652. }
  1653. if (0 === strpos($package->getPrettyVersion(), 'dev-') && in_array($package->getSourceType(), array('git', 'hg'))) {
  1654. $package->setSourceReference(substr($package->getPrettyVersion(), 4));
  1655. }
  1656. $dm = $this->createDownloadManager($io, $config);
  1657. $dm->setPreferSource($preferSource)
  1658. ->setPreferDist($preferDist)
  1659. ->setOutputProgress(!$noProgress);
  1660. $projectInstaller = new ProjectInstaller($directory, $dm);
  1661. $im = $this->createInstallationManager();
  1662. $im->addInstaller($projectInstaller);
  1663. $im->install(new InstalledFilesystemRepository(new JsonFile('php://memory')), new InstallOperation($package));
  1664. $im->notifyInstalls();
  1665. $installedFromVcs = 'source' === $package->getInstallationSource();
  1666. $io->writeError('<info>Created project in ' . $directory . '</info>');
  1667. chdir($directory);
  1668. putenv('COMPOSER_ROOT_VERSION='.$package->getPrettyVersion());
  1669. return $installedFromVcs;
  1670. }
  1671. protected function createDownloadManager(IOInterface $io, Config $config)
  1672. {
  1673. $factory = new Factory();
  1674. return $factory->createDownloadManager($io, $config);
  1675. }
  1676. protected function createInstallationManager()
  1677. {
  1678. return new InstallationManager();
  1679. }
  1680. protected function updatePreferredOptions(Config $config, InputInterface $input, &$preferSource, &$preferDist)
  1681. {
  1682. switch ($config->get('preferred-install')) {
  1683. case 'source':
  1684. $preferSource = true;
  1685. $preferDist = false;
  1686. break;
  1687. case 'dist':
  1688. $preferSource = false;
  1689. $preferDist = true;
  1690. break;
  1691. case 'auto':
  1692. default:
  1693. break;
  1694. }
  1695. if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
  1696. $preferSource = $input->getOption('prefer-source');
  1697. $preferDist = $input->getOption('prefer-dist');
  1698. }
  1699. }
  1700. }
  1701. <?php
  1702. namespace Composer\Command;
  1703. use Composer\DependencyResolver\Pool;
  1704. use Composer\Plugin\CommandEvent;
  1705. use Composer\Plugin\PluginEvents;
  1706. use Symfony\Component\Console\Input\InputInterface;
  1707. use Symfony\Component\Console\Input\InputArgument;
  1708. use Symfony\Component\Console\Input\InputOption;
  1709. use Symfony\Component\Console\Output\OutputInterface;
  1710. class DependsCommand extends Command
  1711. {
  1712. protected $linkTypes = array(
  1713. 'require' => array('requires', 'requires'),
  1714. 'require-dev' => array('devRequires', 'requires (dev)'),
  1715. );
  1716. protected function configure()
  1717. {
  1718. $this
  1719. ->setName('depends')
  1720. ->setDescription('Shows which packages depend on the given package')
  1721. ->setDefinition(array(
  1722. new InputArgument('package', InputArgument::REQUIRED, 'Package to inspect'),
  1723. new InputOption('link-type', '', InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, 'Link types to show (require, require-dev)', array_keys($this->linkTypes)),
  1724. ))
  1725. ->setHelp(<<<EOT
  1726. Displays detailed information about where a package is referenced.
  1727. <info>php composer.phar depends composer/composer</info>
  1728. EOT
  1729. )
  1730. ;
  1731. }
  1732. protected function execute(InputInterface $input, OutputInterface $output)
  1733. {
  1734. $composer = $this->getComposer();
  1735. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'depends', $input, $output);
  1736. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  1737. $repo = $composer->getRepositoryManager()->getLocalRepository();
  1738. $needle = $input->getArgument('package');
  1739. $pool = new Pool();
  1740. $pool->addRepository($repo);
  1741. $packages = $pool->whatProvides($needle);
  1742. if (empty($packages)) {
  1743. throw new \InvalidArgumentException('Could not find package "'.$needle.'" in your project.');
  1744. }
  1745. $linkTypes = $this->linkTypes;
  1746. $types = array_map(function ($type) use ($linkTypes) {
  1747. $type = rtrim($type, 's');
  1748. if (!isset($linkTypes[$type])) {
  1749. throw new \InvalidArgumentException('Unexpected link type: '.$type.', valid types: '.implode(', ', array_keys($linkTypes)));
  1750. }
  1751. return $type;
  1752. }, $input->getOption('link-type'));
  1753. $messages = array();
  1754. $outputPackages = array();
  1755. foreach ($repo->getPackages() as $package) {
  1756. foreach ($types as $type) {
  1757. foreach ($package->{'get'.$linkTypes[$type][0]}() as $link) {
  1758. if ($link->getTarget() === $needle) {
  1759. if (!isset($outputPackages[$package->getName()])) {
  1760. $messages[] = '<info>'.$package->getPrettyName() . '</info> ' . $linkTypes[$type][1] . ' ' . $needle .' (<info>' . $link->getPrettyConstraint() . '</info>)';
  1761. $outputPackages[$package->getName()] = true;
  1762. }
  1763. }
  1764. }
  1765. }
  1766. }
  1767. if ($messages) {
  1768. sort($messages);
  1769. $this->getIO()->write($messages);
  1770. } else {
  1771. $this->getIO()->writeError('<info>There is no installed package depending on "'.$needle.'".</info>');
  1772. }
  1773. }
  1774. }
  1775. <?php
  1776. namespace Composer\Command;
  1777. use Composer\Composer;
  1778. use Composer\Factory;
  1779. use Composer\Downloader\TransportException;
  1780. use Composer\Plugin\CommandEvent;
  1781. use Composer\Plugin\PluginEvents;
  1782. use Composer\Util\ConfigValidator;
  1783. use Composer\Util\ProcessExecutor;
  1784. use Composer\Util\RemoteFilesystem;
  1785. use Composer\Util\StreamContextFactory;
  1786. use Symfony\Component\Console\Input\InputInterface;
  1787. use Symfony\Component\Console\Output\OutputInterface;
  1788. class DiagnoseCommand extends Command
  1789. {
  1790. protected $rfs;
  1791. protected $process;
  1792. protected $failures = 0;
  1793. protected function configure()
  1794. {
  1795. $this
  1796. ->setName('diagnose')
  1797. ->setDescription('Diagnoses the system to identify common errors.')
  1798. ->setHelp(<<<EOT
  1799. The <info>diagnose</info> command checks common errors to help debugging problems.
  1800. EOT
  1801. )
  1802. ;
  1803. }
  1804. protected function execute(InputInterface $input, OutputInterface $output)
  1805. {
  1806. $composer = $this->getComposer(false);
  1807. if ($composer) {
  1808. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'diagnose', $input, $output);
  1809. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  1810. $this->getIO()->write('Checking composer.json: ', false);
  1811. $this->outputResult($this->checkComposerSchema());
  1812. }
  1813. if ($composer) {
  1814. $config = $composer->getConfig();
  1815. } else {
  1816. $config = Factory::createConfig();
  1817. }
  1818. $this->rfs = new RemoteFilesystem($this->getIO(), $config);
  1819. $this->process = new ProcessExecutor($this->getIO());
  1820. $this->getIO()->write('Checking platform settings: ', false);
  1821. $this->outputResult($this->checkPlatform());
  1822. $this->getIO()->write('Checking git settings: ', false);
  1823. $this->outputResult($this->checkGit());
  1824. $this->getIO()->write('Checking http connectivity: ', false);
  1825. $this->outputResult($this->checkHttp());
  1826. $opts = stream_context_get_options(StreamContextFactory::getContext('http://example.org'));
  1827. if (!empty($opts['http']['proxy'])) {
  1828. $this->getIO()->write('Checking HTTP proxy: ', false);
  1829. $this->outputResult($this->checkHttpProxy());
  1830. $this->getIO()->write('Checking HTTP proxy support for request_fulluri: ', false);
  1831. $this->outputResult($this->checkHttpProxyFullUriRequestParam());
  1832. $this->getIO()->write('Checking HTTPS proxy support for request_fulluri: ', false);
  1833. $this->outputResult($this->checkHttpsProxyFullUriRequestParam());
  1834. }
  1835. if ($oauth = $config->get('github-oauth')) {
  1836. foreach ($oauth as $domain => $token) {
  1837. $this->getIO()->write('Checking '.$domain.' oauth access: ', false);
  1838. $this->outputResult($this->checkGithubOauth($domain, $token));
  1839. }
  1840. } else {
  1841. $this->getIO()->write('Checking github.com rate limit: ', false);
  1842. $rate = $this->getGithubRateLimit('github.com');
  1843. if (10 > $rate['remaining']) {
  1844. $this->getIO()->write('<warning>WARNING</warning>');
  1845. $this->getIO()->write(sprintf(
  1846. '<comment>Github has a rate limit on their API. '
  1847. . 'You currently have <options=bold>%u</options=bold> '
  1848. . 'out of <options=bold>%u</options=bold> requests left.' . PHP_EOL
  1849. . 'See https://developer.github.com/v3/#rate-limiting and also' . PHP_EOL
  1850. . ' https://getcomposer.org/doc/articles/troubleshooting.md#api-rate-limit-and-oauth-tokens</comment>',
  1851. $rate['remaining'],
  1852. $rate['limit']
  1853. ));
  1854. } else {
  1855. $this->getIO()->write('<info>OK</info>');
  1856. }
  1857. }
  1858. $this->getIO()->write('Checking disk free space: ', false);
  1859. $this->outputResult($this->checkDiskSpace($config));
  1860. $this->getIO()->write('Checking composer version: ', false);
  1861. $this->outputResult($this->checkVersion());
  1862. return $this->failures;
  1863. }
  1864. private function checkComposerSchema()
  1865. {
  1866. $validator = new ConfigValidator($this->getIO());
  1867. list($errors, $publishErrors, $warnings) = $validator->validate(Factory::getComposerFile());
  1868. if ($errors || $publishErrors || $warnings) {
  1869. $messages = array(
  1870. 'error' => array_merge($errors, $publishErrors),
  1871. 'warning' => $warnings,
  1872. );
  1873. $output = '';
  1874. foreach ($messages as $style => $msgs) {
  1875. foreach ($msgs as $msg) {
  1876. $output .= '<' . $style . '>' . $msg . '</' . $style . '>' . PHP_EOL;
  1877. }
  1878. }
  1879. return rtrim($output);
  1880. }
  1881. return true;
  1882. }
  1883. private function checkGit()
  1884. {
  1885. $this->process->execute('git config color.ui', $output);
  1886. if (strtolower(trim($output)) === 'always') {
  1887. return '<comment>Your git color.ui setting is set to always, this is known to create issues. Use "git config --global color.ui true" to set it correctly.</comment>';
  1888. }
  1889. return true;
  1890. }
  1891. private function checkHttp()
  1892. {
  1893. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  1894. try {
  1895. $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false);
  1896. } catch (\Exception $e) {
  1897. return $e;
  1898. }
  1899. return true;
  1900. }
  1901. private function checkHttpProxy()
  1902. {
  1903. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  1904. try {
  1905. $json = json_decode($this->rfs->getContents('packagist.org', $protocol . '://packagist.org/packages.json', false), true);
  1906. $hash = reset($json['provider-includes']);
  1907. $hash = $hash['sha256'];
  1908. $path = str_replace('%hash%', $hash, key($json['provider-includes']));
  1909. $provider = $this->rfs->getContents('packagist.org', $protocol . '://packagist.org/'.$path, false);
  1910. if (hash('sha256', $provider) !== $hash) {
  1911. return 'It seems that your proxy is modifying http traffic on the fly';
  1912. }
  1913. } catch (\Exception $e) {
  1914. return $e;
  1915. }
  1916. return true;
  1917. }
  1918. private function checkHttpProxyFullUriRequestParam()
  1919. {
  1920. $url = 'http://packagist.org/packages.json';
  1921. try {
  1922. $this->rfs->getContents('packagist.org', $url, false);
  1923. } catch (TransportException $e) {
  1924. try {
  1925. $this->rfs->getContents('packagist.org', $url, false, array('http' => array('request_fulluri' => false)));
  1926. } catch (TransportException $e) {
  1927. return 'Unable to assess the situation, maybe packagist.org is down ('.$e->getMessage().')';
  1928. }
  1929. return 'It seems there is a problem with your proxy server, try setting the "HTTP_PROXY_REQUEST_FULLURI" and "HTTPS_PROXY_REQUEST_FULLURI" environment variables to "false"';
  1930. }
  1931. return true;
  1932. }
  1933. private function checkHttpsProxyFullUriRequestParam()
  1934. {
  1935. if (!extension_loaded('openssl')) {
  1936. return 'You need the openssl extension installed for this check';
  1937. }
  1938. $url = 'https://api.github.com/repos/Seldaek/jsonlint/zipball/1.0.0';
  1939. try {
  1940. $this->rfs->getContents('github.com', $url, false);
  1941. } catch (TransportException $e) {
  1942. try {
  1943. $this->rfs->getContents('github.com', $url, false, array('http' => array('request_fulluri' => false)));
  1944. } catch (TransportException $e) {
  1945. return 'Unable to assess the situation, maybe github is down ('.$e->getMessage().')';
  1946. }
  1947. return 'It seems there is a problem with your proxy server, try setting the "HTTPS_PROXY_REQUEST_FULLURI" environment variable to "false"';
  1948. }
  1949. return true;
  1950. }
  1951. private function checkGithubOauth($domain, $token)
  1952. {
  1953. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  1954. try {
  1955. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/user/repos' : 'https://'.$domain.'/api/v3/user/repos';
  1956. return $this->rfs->getContents($domain, $url, false, array(
  1957. 'retry-auth-failure' => false
  1958. )) ? true : 'Unexpected error';
  1959. } catch (\Exception $e) {
  1960. if ($e instanceof TransportException && $e->getCode() === 401) {
  1961. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  1962. }
  1963. return $e;
  1964. }
  1965. }
  1966. private function getGithubRateLimit($domain, $token = null)
  1967. {
  1968. if ($token) {
  1969. $this->getIO()->setAuthentication($domain, $token, 'x-oauth-basic');
  1970. }
  1971. try {
  1972. $url = $domain === 'github.com' ? 'https://api.'.$domain.'/rate_limit' : 'https://'.$domain.'/api/rate_limit';
  1973. $json = $this->rfs->getContents($domain, $url, false, array('retry-auth-failure' => false));
  1974. $data = json_decode($json, true);
  1975. return $data['resources']['core'];
  1976. } catch (\Exception $e) {
  1977. if ($e instanceof TransportException && $e->getCode() === 401) {
  1978. return '<comment>The oauth token for '.$domain.' seems invalid, run "composer config --global --unset github-oauth.'.$domain.'" to remove it</comment>';
  1979. }
  1980. return $e;
  1981. }
  1982. }
  1983. private function checkDiskSpace($config)
  1984. {
  1985. $minSpaceFree = 1024*1024;
  1986. if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  1987. || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  1988. ) {
  1989. return '<error>The disk hosting '.$dir.' is full</error>';
  1990. }
  1991. return true;
  1992. }
  1993. private function checkVersion()
  1994. {
  1995. $protocol = extension_loaded('openssl') ? 'https' : 'http';
  1996. $latest = trim($this->rfs->getContents('getcomposer.org', $protocol . '://getcomposer.org/version', false));
  1997. if (Composer::VERSION !== $latest && Composer::VERSION !== '@package_version@') {
  1998. return '<comment>You are not running the latest version</comment>';
  1999. }
  2000. return true;
  2001. }
  2002. private function outputResult($result)
  2003. {
  2004. if (true === $result) {
  2005. $this->getIO()->write('<info>OK</info>');
  2006. } else {
  2007. $this->failures++;
  2008. $this->getIO()->write('<error>FAIL</error>');
  2009. if ($result instanceof \Exception) {
  2010. $this->getIO()->write('['.get_class($result).'] '.$result->getMessage());
  2011. } elseif ($result) {
  2012. $this->getIO()->write(trim($result));
  2013. }
  2014. }
  2015. }
  2016. private function checkPlatform()
  2017. {
  2018. $output = '';
  2019. $out = function ($msg, $style) use (&$output) {
  2020. $output .= '<'.$style.'>'.$msg.'</'.$style.'>'.PHP_EOL;
  2021. };
  2022. $errors = array();
  2023. $warnings = array();
  2024. $iniPath = php_ini_loaded_file();
  2025. $displayIniMessage = false;
  2026. if ($iniPath) {
  2027. $iniMessage = PHP_EOL.PHP_EOL.'The php.ini used by your command-line PHP is: ' . $iniPath;
  2028. } else {
  2029. $iniMessage = PHP_EOL.PHP_EOL.'A php.ini file does not exist. You will have to create one.';
  2030. }
  2031. $iniMessage .= PHP_EOL.'If you can not modify the ini file, you can also run `php -d option=value` to modify ini values on the fly. You can use -d multiple times.';
  2032. if (!function_exists('json_decode')) {
  2033. $errors['json'] = true;
  2034. }
  2035. if (!extension_loaded('Phar')) {
  2036. $errors['phar'] = true;
  2037. }
  2038. if (!extension_loaded('filter')) {
  2039. $errors['filter'] = true;
  2040. }
  2041. if (!extension_loaded('hash')) {
  2042. $errors['hash'] = true;
  2043. }
  2044. if (!extension_loaded('ctype')) {
  2045. $errors['ctype'] = true;
  2046. }
  2047. if (!ini_get('allow_url_fopen')) {
  2048. $errors['allow_url_fopen'] = true;
  2049. }
  2050. if (extension_loaded('ionCube Loader') && ioncube_loader_iversion() < 40009) {
  2051. $errors['ioncube'] = ioncube_loader_version();
  2052. }
  2053. if (version_compare(PHP_VERSION, '5.3.2', '<')) {
  2054. $errors['php'] = PHP_VERSION;
  2055. }
  2056. if (!isset($errors['php']) && version_compare(PHP_VERSION, '5.3.4', '<')) {
  2057. $warnings['php'] = PHP_VERSION;
  2058. }
  2059. if (!extension_loaded('openssl')) {
  2060. $errors['openssl'] = true;
  2061. }
  2062. if (!defined('HHVM_VERSION') && !extension_loaded('apcu') && ini_get('apc.enable_cli')) {
  2063. $warnings['apc_cli'] = true;
  2064. }
  2065. ob_start();
  2066. phpinfo(INFO_GENERAL);
  2067. $phpinfo = ob_get_clean();
  2068. if (preg_match('{Configure Command(?: *</td><td class="v">| *=> *)(.*?)(?:</td>|$)}m', $phpinfo, $match)) {
  2069. $configure = $match[1];
  2070. if (false !== strpos($configure, '--enable-sigchild')) {
  2071. $warnings['sigchild'] = true;
  2072. }
  2073. if (false !== strpos($configure, '--with-curlwrappers')) {
  2074. $warnings['curlwrappers'] = true;
  2075. }
  2076. }
  2077. if (ini_get('xdebug.profiler_enabled')) {
  2078. $warnings['xdebug_profile'] = true;
  2079. } elseif (extension_loaded('xdebug')) {
  2080. $warnings['xdebug_loaded'] = true;
  2081. }
  2082. if (!empty($errors)) {
  2083. foreach ($errors as $error => $current) {
  2084. switch ($error) {
  2085. case 'json':
  2086. $text = PHP_EOL."The json extension is missing.".PHP_EOL;
  2087. $text .= "Install it or recompile php without --disable-json";
  2088. break;
  2089. case 'phar':
  2090. $text = PHP_EOL."The phar extension is missing.".PHP_EOL;
  2091. $text .= "Install it or recompile php without --disable-phar";
  2092. break;
  2093. case 'filter':
  2094. $text = PHP_EOL."The filter extension is missing.".PHP_EOL;
  2095. $text .= "Install it or recompile php without --disable-filter";
  2096. break;
  2097. case 'hash':
  2098. $text = PHP_EOL."The hash extension is missing.".PHP_EOL;
  2099. $text .= "Install it or recompile php without --disable-hash";
  2100. break;
  2101. case 'ctype':
  2102. $text = PHP_EOL."The ctype extension is missing.".PHP_EOL;
  2103. $text .= "Install it or recompile php without --disable-ctype";
  2104. break;
  2105. case 'unicode':
  2106. $text = PHP_EOL."The detect_unicode setting must be disabled.".PHP_EOL;
  2107. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  2108. $text .= " detect_unicode = Off";
  2109. $displayIniMessage = true;
  2110. break;
  2111. case 'suhosin':
  2112. $text = PHP_EOL."The suhosin.executor.include.whitelist setting is incorrect.".PHP_EOL;
  2113. $text .= "Add the following to the end of your `php.ini` or suhosin.ini (Example path [for Debian]: /etc/php5/cli/conf.d/suhosin.ini):".PHP_EOL;
  2114. $text .= " suhosin.executor.include.whitelist = phar ".$current;
  2115. $displayIniMessage = true;
  2116. break;
  2117. case 'php':
  2118. $text = PHP_EOL."Your PHP ({$current}) is too old, you must upgrade to PHP 5.3.2 or higher.";
  2119. break;
  2120. case 'allow_url_fopen':
  2121. $text = PHP_EOL."The allow_url_fopen setting is incorrect.".PHP_EOL;
  2122. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  2123. $text .= " allow_url_fopen = On";
  2124. $displayIniMessage = true;
  2125. break;
  2126. case 'ioncube':
  2127. $text = PHP_EOL."Your ionCube Loader extension ($current) is incompatible with Phar files.".PHP_EOL;
  2128. $text .= "Upgrade to ionCube 4.0.9 or higher or remove this line (path may be different) from your `php.ini` to disable it:".PHP_EOL;
  2129. $text .= " zend_extension = /usr/lib/php5/20090626+lfs/ioncube_loader_lin_5.3.so";
  2130. $displayIniMessage = true;
  2131. break;
  2132. case 'openssl':
  2133. $text = PHP_EOL."The openssl extension is missing, which means that secure HTTPS transfers are impossible.".PHP_EOL;
  2134. $text .= "If possible you should enable it or recompile php with --with-openssl";
  2135. break;
  2136. }
  2137. $out($text, 'error');
  2138. }
  2139. $output .= PHP_EOL;
  2140. }
  2141. if (!empty($warnings)) {
  2142. foreach ($warnings as $warning => $current) {
  2143. switch ($warning) {
  2144. case 'apc_cli':
  2145. $text = "The apc.enable_cli setting is incorrect.".PHP_EOL;
  2146. $text .= "Add the following to the end of your `php.ini`:".PHP_EOL;
  2147. $text .= " apc.enable_cli = Off";
  2148. $displayIniMessage = true;
  2149. break;
  2150. case 'sigchild':
  2151. $text = "PHP was compiled with --enable-sigchild which can cause issues on some platforms.".PHP_EOL;
  2152. $text .= "Recompile it without this flag if possible, see also:".PHP_EOL;
  2153. $text .= " https://bugs.php.net/bug.php?id=22999";
  2154. break;
  2155. case 'curlwrappers':
  2156. $text = "PHP was compiled with --with-curlwrappers which will cause issues with HTTP authentication and GitHub.".PHP_EOL;
  2157. $text .= " Recompile it without this flag if possible";
  2158. break;
  2159. case 'php':
  2160. $text = "Your PHP ({$current}) is quite old, upgrading to PHP 5.3.4 or higher is recommended.".PHP_EOL;
  2161. $text .= " Composer works with 5.3.2+ for most people, but there might be edge case issues.";
  2162. break;
  2163. case 'xdebug_loaded':
  2164. $text = "The xdebug extension is loaded, this can slow down Composer a little.".PHP_EOL;
  2165. $text .= " Disabling it when using Composer is recommended.";
  2166. break;
  2167. case 'xdebug_profile':
  2168. $text = "The xdebug.profiler_enabled setting is enabled, this can slow down Composer a lot.".PHP_EOL;
  2169. $text .= "Add the following to the end of your `php.ini` to disable it:".PHP_EOL;
  2170. $text .= " xdebug.profiler_enabled = 0";
  2171. $displayIniMessage = true;
  2172. break;
  2173. }
  2174. $out($text, 'comment');
  2175. }
  2176. }
  2177. if ($displayIniMessage) {
  2178. $out($iniMessage, 'comment');
  2179. }
  2180. return !$warnings && !$errors ? true : $output;
  2181. }
  2182. }
  2183. <?php
  2184. namespace Composer\Command;
  2185. use Composer\Plugin\CommandEvent;
  2186. use Composer\Plugin\PluginEvents;
  2187. use Symfony\Component\Console\Input\InputInterface;
  2188. use Symfony\Component\Console\Input\InputOption;
  2189. use Symfony\Component\Console\Output\OutputInterface;
  2190. class DumpAutoloadCommand extends Command
  2191. {
  2192. protected function configure()
  2193. {
  2194. $this
  2195. ->setName('dump-autoload')
  2196. ->setAliases(array('dumpautoload'))
  2197. ->setDescription('Dumps the autoloader')
  2198. ->setDefinition(array(
  2199. new InputOption('optimize', 'o', InputOption::VALUE_NONE, 'Optimizes PSR0 and PSR4 packages to be loaded with classmaps too, good for production.'),
  2200. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables autoload-dev rules.'),
  2201. ))
  2202. ->setHelp(<<<EOT
  2203. <info>php composer.phar dump-autoload</info>
  2204. EOT
  2205. )
  2206. ;
  2207. }
  2208. protected function execute(InputInterface $input, OutputInterface $output)
  2209. {
  2210. $composer = $this->getComposer();
  2211. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'dump-autoload', $input, $output);
  2212. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  2213. $installationManager = $composer->getInstallationManager();
  2214. $localRepo = $composer->getRepositoryManager()->getLocalRepository();
  2215. $package = $composer->getPackage();
  2216. $config = $composer->getConfig();
  2217. $optimize = $input->getOption('optimize') || $config->get('optimize-autoloader') || $config->get('classmap-authoritative');
  2218. if ($optimize) {
  2219. $this->getIO()->writeError('<info>Generating optimized autoload files</info>');
  2220. } else {
  2221. $this->getIO()->writeError('<info>Generating autoload files</info>');
  2222. }
  2223. $generator = $composer->getAutoloadGenerator();
  2224. $generator->setDevMode(!$input->getOption('no-dev'));
  2225. $generator->dump($config, $localRepo, $package, $installationManager, 'composer', $optimize);
  2226. }
  2227. }
  2228. <?php
  2229. namespace Composer\Command;
  2230. use Composer\Factory;
  2231. use Symfony\Component\Console\Input\InputInterface;
  2232. use Symfony\Component\Console\Input\InputArgument;
  2233. use Symfony\Component\Console\Input\StringInput;
  2234. use Symfony\Component\Console\Output\OutputInterface;
  2235. class GlobalCommand extends Command
  2236. {
  2237. protected function configure()
  2238. {
  2239. $this
  2240. ->setName('global')
  2241. ->setDescription('Allows running commands in the global composer dir ($COMPOSER_HOME).')
  2242. ->setDefinition(array(
  2243. new InputArgument('command-name', InputArgument::REQUIRED, ''),
  2244. new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
  2245. ))
  2246. ->setHelp(<<<EOT
  2247. Use this command as a wrapper to run other Composer commands
  2248. within the global context of COMPOSER_HOME.
  2249. You can use this to install CLI utilities globally, all you need
  2250. is to add the COMPOSER_HOME/vendor/bin dir to your PATH env var.
  2251. COMPOSER_HOME is c:\Users\<user>\AppData\Roaming\Composer on Windows
  2252. and /home/<user>/.composer on unix systems.
  2253. Note: This path may vary depending on customizations to bin-dir in
  2254. composer.json or the environmental variable COMPOSER_BIN_DIR.
  2255. EOT
  2256. )
  2257. ;
  2258. }
  2259. public function run(InputInterface $input, OutputInterface $output)
  2260. {
  2261. $tokens = preg_split('{\s+}', $input->__toString());
  2262. $args = array();
  2263. foreach ($tokens as $token) {
  2264. if ($token && $token[0] !== '-') {
  2265. $args[] = $token;
  2266. if (count($args) >= 2) {
  2267. break;
  2268. }
  2269. }
  2270. }
  2271. if (count($args) < 2) {
  2272. return parent::run($input, $output);
  2273. }
  2274. $config = Factory::createConfig();
  2275. chdir($config->get('home'));
  2276. $this->getIO()->writeError('<info>Changed current directory to '.$config->get('home').'</info>');
  2277. $input = new StringInput(preg_replace('{\bg(?:l(?:o(?:b(?:a(?:l)?)?)?)?)?\b}', '', $input->__toString(), 1));
  2278. return $this->getApplication()->run($input, $output);
  2279. }
  2280. }
  2281. <?php
  2282. namespace Composer\Command\Helper;
  2283. use Symfony\Component\Console\Helper\DialogHelper as BaseDialogHelper;
  2284. class DialogHelper extends BaseDialogHelper
  2285. {
  2286. public function getQuestion($question, $default = null, $sep = ':')
  2287. {
  2288. return $default !== null ?
  2289. sprintf('<info>%s</info> [<comment>%s</comment>]%s ', $question, $default, $sep) :
  2290. sprintf('<info>%s</info>%s ', $question, $sep);
  2291. }
  2292. }
  2293. <?php
  2294. namespace Composer\Command;
  2295. use Composer\DependencyResolver\Pool;
  2296. use Composer\Factory;
  2297. use Composer\Package\CompletePackageInterface;
  2298. use Composer\Repository\CompositeRepository;
  2299. use Composer\Repository\RepositoryInterface;
  2300. use Composer\Util\ProcessExecutor;
  2301. use Symfony\Component\Console\Input\InputArgument;
  2302. use Symfony\Component\Console\Input\InputOption;
  2303. use Symfony\Component\Console\Input\InputInterface;
  2304. use Symfony\Component\Console\Output\OutputInterface;
  2305. class HomeCommand extends Command
  2306. {
  2307. protected function configure()
  2308. {
  2309. $this
  2310. ->setName('browse')
  2311. ->setAliases(array('home'))
  2312. ->setDescription('Opens the package\'s repository URL or homepage in your browser.')
  2313. ->setDefinition(array(
  2314. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'Package(s) to browse to.'),
  2315. new InputOption('homepage', 'H', InputOption::VALUE_NONE, 'Open the homepage instead of the repository URL.'),
  2316. new InputOption('show', 's', InputOption::VALUE_NONE, 'Only show the homepage or repository URL.'),
  2317. ))
  2318. ->setHelp(<<<EOT
  2319. The home command opens or shows a package's repository URL or
  2320. homepage in your default browser.
  2321. To open the homepage by default, use -H or --homepage.
  2322. To show instead of open the repository or homepage URL, use -s or --show.
  2323. EOT
  2324. );
  2325. }
  2326. protected function execute(InputInterface $input, OutputInterface $output)
  2327. {
  2328. $repos = $this->initializeRepos();
  2329. $return = 0;
  2330. foreach ($input->getArgument('packages') as $packageName) {
  2331. foreach ($repos as $repo) {
  2332. $package = $this->getPackage($repo, $packageName);
  2333. if ($package instanceof CompletePackageInterface) {
  2334. break;
  2335. }
  2336. }
  2337. $package = $this->getPackage($repo, $packageName);
  2338. if (!$package instanceof CompletePackageInterface) {
  2339. $return = 1;
  2340. $this->getIO()->writeError('<warning>Package '.$packageName.' not found</warning>');
  2341. continue;
  2342. }
  2343. $support = $package->getSupport();
  2344. $url = isset($support['source']) ? $support['source'] : $package->getSourceUrl();
  2345. if (!$url || $input->getOption('homepage')) {
  2346. $url = $package->getHomepage();
  2347. }
  2348. if (!filter_var($url, FILTER_VALIDATE_URL)) {
  2349. $return = 1;
  2350. $this->getIO()->writeError('<warning>'.($input->getOption('homepage') ? 'Invalid or missing homepage' : 'Invalid or missing repository URL').' for '.$packageName.'</warning>');
  2351. continue;
  2352. }
  2353. if ($input->getOption('show')) {
  2354. $this->getIO()->write(sprintf('<info>%s</info>', $url));
  2355. } else {
  2356. $this->openBrowser($url);
  2357. }
  2358. }
  2359. return $return;
  2360. }
  2361. protected function getPackage(RepositoryInterface $repos, $name)
  2362. {
  2363. $name = strtolower($name);
  2364. $pool = new Pool('dev');
  2365. $pool->addRepository($repos);
  2366. $matches = $pool->whatProvides($name);
  2367. foreach ($matches as $index => $package) {
  2368. if ($package->getName() !== $name) {
  2369. unset($matches[$index]);
  2370. continue;
  2371. }
  2372. return $package;
  2373. }
  2374. }
  2375. private function openBrowser($url)
  2376. {
  2377. $url = ProcessExecutor::escape($url);
  2378. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  2379. return passthru('start "web" explorer "' . $url . '"');
  2380. }
  2381. passthru('which xdg-open', $linux);
  2382. passthru('which open', $osx);
  2383. if (0 === $linux) {
  2384. passthru('xdg-open ' . $url);
  2385. } elseif (0 === $osx) {
  2386. passthru('open ' . $url);
  2387. } else {
  2388. $this->getIO()->writeError('no suitable browser opening command found, open yourself: ' . $url);
  2389. }
  2390. }
  2391. private function initializeRepos()
  2392. {
  2393. $composer = $this->getComposer(false);
  2394. if ($composer) {
  2395. return array(
  2396. $composer->getRepositoryManager()->getLocalRepository(),
  2397. new CompositeRepository($composer->getRepositoryManager()->getRepositories())
  2398. );
  2399. }
  2400. $defaultRepos = Factory::createDefaultRepositories($this->getIO());
  2401. return array(new CompositeRepository($defaultRepos));
  2402. }
  2403. }
  2404. <?php
  2405. namespace Composer\Command;
  2406. use Composer\DependencyResolver\Pool;
  2407. use Composer\Json\JsonFile;
  2408. use Composer\Factory;
  2409. use Composer\Package\BasePackage;
  2410. use Composer\Package\Version\VersionSelector;
  2411. use Composer\Repository\CompositeRepository;
  2412. use Composer\Repository\PlatformRepository;
  2413. use Composer\Package\Version\VersionParser;
  2414. use Composer\Util\ProcessExecutor;
  2415. use Symfony\Component\Console\Input\InputInterface;
  2416. use Symfony\Component\Console\Input\InputOption;
  2417. use Symfony\Component\Console\Output\OutputInterface;
  2418. use Symfony\Component\Process\Process;
  2419. use Symfony\Component\Process\ExecutableFinder;
  2420. class InitCommand extends Command
  2421. {
  2422. protected $repos;
  2423. private $gitConfig;
  2424. private $pool;
  2425. public function parseAuthorString($author)
  2426. {
  2427. if (preg_match('/^(?P<name>[- \.,\p{L}\'’]+) <(?P<email>.+?)>$/u', $author, $match)) {
  2428. if ($this->isValidEmail($match['email'])) {
  2429. return array(
  2430. 'name' => trim($match['name']),
  2431. 'email' => $match['email']
  2432. );
  2433. }
  2434. }
  2435. throw new \InvalidArgumentException(
  2436. 'Invalid author string. Must be in the format: '.
  2437. 'John Smith <john@example.com>'
  2438. );
  2439. }
  2440. protected function configure()
  2441. {
  2442. $this
  2443. ->setName('init')
  2444. ->setDescription('Creates a basic composer.json file in current directory.')
  2445. ->setDefinition(array(
  2446. new InputOption('name', null, InputOption::VALUE_REQUIRED, 'Name of the package'),
  2447. new InputOption('description', null, InputOption::VALUE_REQUIRED, 'Description of package'),
  2448. new InputOption('author', null, InputOption::VALUE_REQUIRED, 'Author name of package'),
  2449. new InputOption('homepage', null, InputOption::VALUE_REQUIRED, 'Homepage of package'),
  2450. new InputOption('require', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  2451. new InputOption('require-dev', null, InputOption::VALUE_IS_ARRAY | InputOption::VALUE_REQUIRED, 'Package to require for development with a version constraint, e.g. foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  2452. new InputOption('stability', 's', InputOption::VALUE_REQUIRED, 'Minimum stability (empty or one of: '.implode(', ', array_keys(BasePackage::$stabilities)).')'),
  2453. new InputOption('license', 'l', InputOption::VALUE_REQUIRED, 'License of package'),
  2454. ))
  2455. ->setHelp(<<<EOT
  2456. The <info>init</info> command creates a basic composer.json file
  2457. in the current directory.
  2458. <info>php composer.phar init</info>
  2459. EOT
  2460. )
  2461. ;
  2462. }
  2463. protected function execute(InputInterface $input, OutputInterface $output)
  2464. {
  2465. $dialog = $this->getHelperSet()->get('dialog');
  2466. $whitelist = array('name', 'description', 'author', 'homepage', 'require', 'require-dev', 'stability', 'license');
  2467. $options = array_filter(array_intersect_key($input->getOptions(), array_flip($whitelist)));
  2468. if (isset($options['author'])) {
  2469. $options['authors'] = $this->formatAuthors($options['author']);
  2470. unset($options['author']);
  2471. }
  2472. if (isset($options['stability'])) {
  2473. $options['minimum-stability'] = $options['stability'];
  2474. unset($options['stability']);
  2475. }
  2476. $options['require'] = isset($options['require']) ? $this->formatRequirements($options['require']) : new \stdClass;
  2477. if (array() === $options['require']) {
  2478. $options['require'] = new \stdClass;
  2479. }
  2480. if (isset($options['require-dev'])) {
  2481. $options['require-dev'] = $this->formatRequirements($options['require-dev']);
  2482. if (array() === $options['require-dev']) {
  2483. $options['require-dev'] = new \stdClass;
  2484. }
  2485. }
  2486. $file = new JsonFile('composer.json');
  2487. $json = $file->encode($options);
  2488. if ($input->isInteractive()) {
  2489. $this->getIO()->writeError(array(
  2490. '',
  2491. $json,
  2492. ''
  2493. ));
  2494. if (!$dialog->askConfirmation($output, $dialog->getQuestion('Do you confirm generation', 'yes', '?'), true)) {
  2495. $this->getIO()->writeError('<error>Command aborted</error>');
  2496. return 1;
  2497. }
  2498. }
  2499. $file->write($options);
  2500. if ($input->isInteractive() && is_dir('.git')) {
  2501. $ignoreFile = realpath('.gitignore');
  2502. if (false === $ignoreFile) {
  2503. $ignoreFile = realpath('.') . '/.gitignore';
  2504. }
  2505. if (!$this->hasVendorIgnore($ignoreFile)) {
  2506. $question = 'Would you like the <info>vendor</info> directory added to your <info>.gitignore</info> [<comment>yes</comment>]?';
  2507. if ($dialog->askConfirmation($output, $question, true)) {
  2508. $this->addVendorIgnore($ignoreFile);
  2509. }
  2510. }
  2511. }
  2512. }
  2513. protected function interact(InputInterface $input, OutputInterface $output)
  2514. {
  2515. $git = $this->getGitConfig();
  2516. $dialog = $this->getHelperSet()->get('dialog');
  2517. $formatter = $this->getHelperSet()->get('formatter');
  2518. $this->getIO()->writeError(array(
  2519. '',
  2520. $formatter->formatBlock('Welcome to the Composer config generator', 'bg=blue;fg=white', true),
  2521. ''
  2522. ));
  2523. $this->getIO()->writeError(array(
  2524. '',
  2525. 'This command will guide you through creating your composer.json config.',
  2526. '',
  2527. ));
  2528. $cwd = realpath(".");
  2529. if (!$name = $input->getOption('name')) {
  2530. $name = basename($cwd);
  2531. $name = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $name);
  2532. $name = strtolower($name);
  2533. if (isset($git['github.user'])) {
  2534. $name = $git['github.user'] . '/' . $name;
  2535. } elseif (!empty($_SERVER['USERNAME'])) {
  2536. $name = $_SERVER['USERNAME'] . '/' . $name;
  2537. } elseif (get_current_user()) {
  2538. $name = get_current_user() . '/' . $name;
  2539. } else {
  2540. $name = $name . '/' . $name;
  2541. }
  2542. } else {
  2543. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $name)) {
  2544. throw new \InvalidArgumentException(
  2545. 'The package name '.$name.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
  2546. );
  2547. }
  2548. }
  2549. $name = $dialog->askAndValidate(
  2550. $output,
  2551. $dialog->getQuestion('Package name (<vendor>/<name>)', $name),
  2552. function ($value) use ($name) {
  2553. if (null === $value) {
  2554. return $name;
  2555. }
  2556. if (!preg_match('{^[a-z0-9_.-]+/[a-z0-9_.-]+$}', $value)) {
  2557. throw new \InvalidArgumentException(
  2558. 'The package name '.$value.' is invalid, it should be lowercase and have a vendor name, a forward slash, and a package name, matching: [a-z0-9_.-]+/[a-z0-9_.-]+'
  2559. );
  2560. }
  2561. return $value;
  2562. }
  2563. );
  2564. $input->setOption('name', $name);
  2565. $description = $input->getOption('description') ?: false;
  2566. $description = $dialog->ask(
  2567. $output,
  2568. $dialog->getQuestion('Description', $description),
  2569. $description
  2570. );
  2571. $input->setOption('description', $description);
  2572. if (null === $author = $input->getOption('author')) {
  2573. if (isset($git['user.name']) && isset($git['user.email'])) {
  2574. $author = sprintf('%s <%s>', $git['user.name'], $git['user.email']);
  2575. }
  2576. }
  2577. $self = $this;
  2578. $author = $dialog->askAndValidate(
  2579. $output,
  2580. $dialog->getQuestion('Author', $author),
  2581. function ($value) use ($self, $author) {
  2582. $value = $value ?: $author;
  2583. $author = $self->parseAuthorString($value);
  2584. return sprintf('%s <%s>', $author['name'], $author['email']);
  2585. }
  2586. );
  2587. $input->setOption('author', $author);
  2588. $minimumStability = $input->getOption('stability') ?: '';
  2589. $minimumStability = $dialog->askAndValidate(
  2590. $output,
  2591. $dialog->getQuestion('Minimum Stability', $minimumStability),
  2592. function ($value) use ($self, $minimumStability) {
  2593. if (null === $value) {
  2594. return $minimumStability;
  2595. }
  2596. if (!isset(BasePackage::$stabilities[$value])) {
  2597. throw new \InvalidArgumentException(
  2598. 'Invalid minimum stability "'.$value.'". Must be empty or one of: '.
  2599. implode(', ', array_keys(BasePackage::$stabilities))
  2600. );
  2601. }
  2602. return $value;
  2603. }
  2604. );
  2605. $input->setOption('stability', $minimumStability);
  2606. $license = $input->getOption('license') ?: false;
  2607. $license = $dialog->ask(
  2608. $output,
  2609. $dialog->getQuestion('License', $license),
  2610. $license
  2611. );
  2612. $input->setOption('license', $license);
  2613. $this->getIO()->writeError(array(
  2614. '',
  2615. 'Define your dependencies.',
  2616. ''
  2617. ));
  2618. $requirements = array();
  2619. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dependencies (require) interactively', 'yes', '?'), true)) {
  2620. $requirements = $this->determineRequirements($input, $output, $input->getOption('require'));
  2621. }
  2622. $input->setOption('require', $requirements);
  2623. $devRequirements = array();
  2624. if ($dialog->askConfirmation($output, $dialog->getQuestion('Would you like to define your dev dependencies (require-dev) interactively', 'yes', '?'), true)) {
  2625. $devRequirements = $this->determineRequirements($input, $output, $input->getOption('require-dev'));
  2626. }
  2627. $input->setOption('require-dev', $devRequirements);
  2628. }
  2629. protected function findPackages($name)
  2630. {
  2631. return $this->getRepos()->search($name);
  2632. }
  2633. protected function getRepos()
  2634. {
  2635. if (!$this->repos) {
  2636. $this->repos = new CompositeRepository(array_merge(
  2637. array(new PlatformRepository),
  2638. Factory::createDefaultRepositories($this->getIO())
  2639. ));
  2640. }
  2641. return $this->repos;
  2642. }
  2643. protected function determineRequirements(InputInterface $input, OutputInterface $output, $requires = array())
  2644. {
  2645. $dialog = $this->getHelperSet()->get('dialog');
  2646. $prompt = $dialog->getQuestion('Search for a package', false, ':');
  2647. if ($requires) {
  2648. $requires = $this->normalizeRequirements($requires);
  2649. $result = array();
  2650. foreach ($requires as $requirement) {
  2651. if (!isset($requirement['version'])) {
  2652. $version = $this->findBestVersionForPackage($input, $requirement['name']);
  2653. $requirement['version'] = $version;
  2654. $this->getIO()->writeError(sprintf(
  2655. 'Using version <info>%s</info> for <info>%s</info>',
  2656. $requirement['version'],
  2657. $requirement['name']
  2658. ));
  2659. }
  2660. $result[] = $requirement['name'] . ' ' . $requirement['version'];
  2661. }
  2662. return $result;
  2663. }
  2664. while (null !== $package = $dialog->ask($output, $prompt)) {
  2665. $matches = $this->findPackages($package);
  2666. if (count($matches)) {
  2667. $exactMatch = null;
  2668. $choices = array();
  2669. foreach ($matches as $position => $foundPackage) {
  2670. $choices[] = sprintf(' <info>%5s</info> %s', "[$position]", $foundPackage['name']);
  2671. if ($foundPackage['name'] === $package) {
  2672. $exactMatch = true;
  2673. break;
  2674. }
  2675. }
  2676. if (!$exactMatch) {
  2677. $this->getIO()->writeError(array(
  2678. '',
  2679. sprintf('Found <info>%s</info> packages matching <info>%s</info>', count($matches), $package),
  2680. ''
  2681. ));
  2682. $this->getIO()->writeError($choices);
  2683. $this->getIO()->writeError('');
  2684. $validator = function ($selection) use ($matches) {
  2685. if ('' === $selection) {
  2686. return false;
  2687. }
  2688. if (!is_numeric($selection) && preg_match('{^\s*(\S+)\s+(\S.*)\s*$}', $selection, $matches)) {
  2689. return $matches[1].' '.$matches[2];
  2690. }
  2691. if (!isset($matches[(int) $selection])) {
  2692. throw new \Exception('Not a valid selection');
  2693. }
  2694. $package = $matches[(int) $selection];
  2695. return $package['name'];
  2696. };
  2697. $package = $dialog->askAndValidate($output, $dialog->getQuestion('Enter package # to add, or the complete package name if it is not listed', false, ':'), $validator, 3);
  2698. }
  2699. if (false !== $package && false === strpos($package, ' ')) {
  2700. $validator = function ($input) {
  2701. $input = trim($input);
  2702. return $input ?: false;
  2703. };
  2704. $constraint = $dialog->askAndValidate(
  2705. $output,
  2706. $dialog->getQuestion('Enter the version constraint to require (or leave blank to use the latest version)', false, ':'),
  2707. $validator,
  2708. 3)
  2709. ;
  2710. if (false === $constraint) {
  2711. $constraint = $this->findBestVersionForPackage($input, $package);
  2712. $this->getIO()->writeError(sprintf(
  2713. 'Using version <info>%s</info> for <info>%s</info>',
  2714. $constraint,
  2715. $package
  2716. ));
  2717. }
  2718. $package .= ' '.$constraint;
  2719. }
  2720. if (false !== $package) {
  2721. $requires[] = $package;
  2722. }
  2723. }
  2724. }
  2725. return $requires;
  2726. }
  2727. protected function formatAuthors($author)
  2728. {
  2729. return array($this->parseAuthorString($author));
  2730. }
  2731. protected function formatRequirements(array $requirements)
  2732. {
  2733. $requires = array();
  2734. $requirements = $this->normalizeRequirements($requirements);
  2735. foreach ($requirements as $requirement) {
  2736. $requires[$requirement['name']] = $requirement['version'];
  2737. }
  2738. return $requires;
  2739. }
  2740. protected function getGitConfig()
  2741. {
  2742. if (null !== $this->gitConfig) {
  2743. return $this->gitConfig;
  2744. }
  2745. $finder = new ExecutableFinder();
  2746. $gitBin = $finder->find('git');
  2747. $cmd = new Process(sprintf('%s config -l', ProcessExecutor::escape($gitBin)));
  2748. $cmd->run();
  2749. if ($cmd->isSuccessful()) {
  2750. $this->gitConfig = array();
  2751. preg_match_all('{^([^=]+)=(.*)$}m', $cmd->getOutput(), $matches, PREG_SET_ORDER);
  2752. foreach ($matches as $match) {
  2753. $this->gitConfig[$match[1]] = $match[2];
  2754. }
  2755. return $this->gitConfig;
  2756. }
  2757. return $this->gitConfig = array();
  2758. }
  2759. protected function hasVendorIgnore($ignoreFile, $vendor = 'vendor')
  2760. {
  2761. if (!file_exists($ignoreFile)) {
  2762. return false;
  2763. }
  2764. $pattern = sprintf('{^/?%s(/\*?)?$}', preg_quote($vendor));
  2765. $lines = file($ignoreFile, FILE_IGNORE_NEW_LINES);
  2766. foreach ($lines as $line) {
  2767. if (preg_match($pattern, $line)) {
  2768. return true;
  2769. }
  2770. }
  2771. return false;
  2772. }
  2773. protected function normalizeRequirements(array $requirements)
  2774. {
  2775. $parser = new VersionParser();
  2776. return $parser->parseNameVersionPairs($requirements);
  2777. }
  2778. protected function addVendorIgnore($ignoreFile, $vendor = '/vendor/')
  2779. {
  2780. $contents = "";
  2781. if (file_exists($ignoreFile)) {
  2782. $contents = file_get_contents($ignoreFile);
  2783. if ("\n" !== substr($contents, 0, -1)) {
  2784. $contents .= "\n";
  2785. }
  2786. }
  2787. file_put_contents($ignoreFile, $contents . $vendor. "\n");
  2788. }
  2789. protected function isValidEmail($email)
  2790. {
  2791. if (!function_exists('filter_var')) {
  2792. return true;
  2793. }
  2794. if (version_compare(PHP_VERSION, '5.3.3', '<')) {
  2795. return true;
  2796. }
  2797. return false !== filter_var($email, FILTER_VALIDATE_EMAIL);
  2798. }
  2799. private function getPool(InputInterface $input)
  2800. {
  2801. if (!$this->pool) {
  2802. $this->pool = new Pool($this->getMinimumStability($input));
  2803. $this->pool->addRepository($this->getRepos());
  2804. }
  2805. return $this->pool;
  2806. }
  2807. private function getMinimumStability(InputInterface $input)
  2808. {
  2809. if ($input->hasOption('stability')) {
  2810. return $input->getOption('stability') ?: 'stable';
  2811. }
  2812. $file = Factory::getComposerFile();
  2813. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  2814. if (!empty($composer['minimum-stability'])) {
  2815. return $composer['minimum-stability'];
  2816. }
  2817. }
  2818. return 'stable';
  2819. }
  2820. private function findBestVersionForPackage(InputInterface $input, $name)
  2821. {
  2822. $versionSelector = new VersionSelector($this->getPool($input));
  2823. $package = $versionSelector->findBestCandidate($name);
  2824. if (!$package) {
  2825. throw new \InvalidArgumentException(sprintf(
  2826. 'Could not find package %s at any version for your minimum-stability (%s). Check the package spelling or your minimum-stability',
  2827. $name,
  2828. $this->getMinimumStability($input)
  2829. ));
  2830. }
  2831. return $versionSelector->findRecommendedRequireVersion($package);
  2832. }
  2833. }
  2834. <?php
  2835. namespace Composer\Command;
  2836. use Composer\Installer;
  2837. use Composer\Plugin\CommandEvent;
  2838. use Composer\Plugin\PluginEvents;
  2839. use Symfony\Component\Console\Input\InputInterface;
  2840. use Symfony\Component\Console\Input\InputOption;
  2841. use Symfony\Component\Console\Input\InputArgument;
  2842. use Symfony\Component\Console\Output\OutputInterface;
  2843. class InstallCommand extends Command
  2844. {
  2845. protected function configure()
  2846. {
  2847. $this
  2848. ->setName('install')
  2849. ->setDescription('Installs the project dependencies from the composer.lock file if present, or falls back on the composer.json.')
  2850. ->setDefinition(array(
  2851. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  2852. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  2853. new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
  2854. new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
  2855. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
  2856. new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Disables all plugins.'),
  2857. new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
  2858. new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'),
  2859. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  2860. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  2861. new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
  2862. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump'),
  2863. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  2864. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Should not be provided, use composer require instead to add a given package to composer.json.'),
  2865. ))
  2866. ->setHelp(<<<EOT
  2867. The <info>install</info> command reads the composer.lock file from
  2868. the current directory, processes it, and downloads and installs all the
  2869. libraries and dependencies outlined in that file. If the file does not
  2870. exist it will look for composer.json and do the same.
  2871. <info>php composer.phar install</info>
  2872. EOT
  2873. )
  2874. ;
  2875. }
  2876. protected function execute(InputInterface $input, OutputInterface $output)
  2877. {
  2878. if ($args = $input->getArgument('packages')) {
  2879. $this->getIO()->writeError('<error>Invalid argument '.implode(' ', $args).'. Use "composer require '.implode(' ', $args).'" instead to add packages to your composer.json.</error>');
  2880. return 1;
  2881. }
  2882. if ($input->getOption('no-custom-installers')) {
  2883. $this->getIO()->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
  2884. $input->setOption('no-plugins', true);
  2885. }
  2886. if ($input->getOption('dev')) {
  2887. $this->getIO()->writeError('<warning>You are using the deprecated option "dev". Dev packages are installed by default now.</warning>');
  2888. }
  2889. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  2890. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  2891. $io = $this->getIO();
  2892. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'install', $input, $output);
  2893. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  2894. $install = Installer::create($io, $composer);
  2895. $preferSource = false;
  2896. $preferDist = false;
  2897. $config = $composer->getConfig();
  2898. switch ($config->get('preferred-install')) {
  2899. case 'source':
  2900. $preferSource = true;
  2901. break;
  2902. case 'dist':
  2903. $preferDist = true;
  2904. break;
  2905. case 'auto':
  2906. default:
  2907. break;
  2908. }
  2909. if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
  2910. $preferSource = $input->getOption('prefer-source');
  2911. $preferDist = $input->getOption('prefer-dist');
  2912. }
  2913. $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader') || $config->get('classmap-authoritative');
  2914. $install
  2915. ->setDryRun($input->getOption('dry-run'))
  2916. ->setVerbose($input->getOption('verbose'))
  2917. ->setPreferSource($preferSource)
  2918. ->setPreferDist($preferDist)
  2919. ->setDevMode(!$input->getOption('no-dev'))
  2920. ->setDumpAutoloader(!$input->getOption('no-autoloader'))
  2921. ->setRunScripts(!$input->getOption('no-scripts'))
  2922. ->setOptimizeAutoloader($optimize)
  2923. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  2924. ;
  2925. if ($input->getOption('no-plugins')) {
  2926. $install->disablePlugins();
  2927. }
  2928. return $install->run();
  2929. }
  2930. }
  2931. <?php
  2932. namespace Composer\Command;
  2933. use Composer\Json\JsonFile;
  2934. use Composer\Package\Version\VersionParser;
  2935. use Composer\Plugin\CommandEvent;
  2936. use Composer\Plugin\PluginEvents;
  2937. use Composer\Package\PackageInterface;
  2938. use Composer\Repository\RepositoryInterface;
  2939. use Symfony\Component\Console\Helper\Table;
  2940. use Symfony\Component\Console\Helper\TableStyle;
  2941. use Symfony\Component\Console\Input\InputInterface;
  2942. use Symfony\Component\Console\Input\InputOption;
  2943. use Symfony\Component\Console\Output\OutputInterface;
  2944. class LicensesCommand extends Command
  2945. {
  2946. protected function configure()
  2947. {
  2948. $this
  2949. ->setName('licenses')
  2950. ->setDescription('Show information about licenses of dependencies')
  2951. ->setDefinition(array(
  2952. new InputOption('format', 'f', InputOption::VALUE_REQUIRED, 'Format of the output: text or json', 'text'),
  2953. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables search in require-dev packages.'),
  2954. ))
  2955. ->setHelp(<<<EOT
  2956. The license command displays detailed information about the licenses of
  2957. the installed dependencies.
  2958. EOT
  2959. )
  2960. ;
  2961. }
  2962. protected function execute(InputInterface $input, OutputInterface $output)
  2963. {
  2964. $composer = $this->getComposer();
  2965. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'licenses', $input, $output);
  2966. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  2967. $root = $composer->getPackage();
  2968. $repo = $composer->getRepositoryManager()->getLocalRepository();
  2969. $versionParser = new VersionParser;
  2970. if ($input->getOption('no-dev')) {
  2971. $packages = $this->filterRequiredPackages($repo, $root);
  2972. } else {
  2973. $packages = $this->appendPackages($repo->getPackages(), array());
  2974. }
  2975. ksort($packages);
  2976. switch ($format = $input->getOption('format')) {
  2977. case 'text':
  2978. $this->getIO()->write('Name: <comment>'.$root->getPrettyName().'</comment>');
  2979. $this->getIO()->write('Version: <comment>'.$versionParser->formatVersion($root).'</comment>');
  2980. $this->getIO()->write('Licenses: <comment>'.(implode(', ', $root->getLicense()) ?: 'none').'</comment>');
  2981. $this->getIO()->write('Dependencies:');
  2982. $this->getIO()->write('');
  2983. $table = new Table($output);
  2984. $table->setStyle('compact');
  2985. $table->getStyle()->setVerticalBorderChar('');
  2986. $table->getStyle()->setCellRowContentFormat('%s ');
  2987. $table->setHeaders(array('Name', 'Version', 'License'));
  2988. foreach ($packages as $package) {
  2989. $table->addRow(array(
  2990. $package->getPrettyName(),
  2991. $versionParser->formatVersion($package),
  2992. implode(', ', $package->getLicense()) ?: 'none',
  2993. ));
  2994. }
  2995. $table->render();
  2996. break;
  2997. case 'json':
  2998. foreach ($packages as $package) {
  2999. $dependencies[$package->getPrettyName()] = array(
  3000. 'version' => $versionParser->formatVersion($package),
  3001. 'license' => $package->getLicense(),
  3002. );
  3003. }
  3004. $this->getIO()->write(JsonFile::encode(array(
  3005. 'name' => $root->getPrettyName(),
  3006. 'version' => $versionParser->formatVersion($root),
  3007. 'license' => $root->getLicense(),
  3008. 'dependencies' => $dependencies,
  3009. )));
  3010. break;
  3011. default:
  3012. throw new \RuntimeException(sprintf('Unsupported format "%s". See help for supported formats.', $format));
  3013. }
  3014. }
  3015. private function filterRequiredPackages(RepositoryInterface $repo, PackageInterface $package, $bucket = array())
  3016. {
  3017. $requires = array_keys($package->getRequires());
  3018. $packageListNames = array_keys($bucket);
  3019. $packages = array_filter(
  3020. $repo->getPackages(),
  3021. function ($package) use ($requires, $packageListNames) {
  3022. return in_array($package->getName(), $requires) && !in_array($package->getName(), $packageListNames);
  3023. }
  3024. );
  3025. $bucket = $this->appendPackages($packages, $bucket);
  3026. foreach ($packages as $package) {
  3027. $bucket = $this->filterRequiredPackages($repo, $package, $bucket);
  3028. }
  3029. return $bucket;
  3030. }
  3031. public function appendPackages(array $packages, array $bucket)
  3032. {
  3033. foreach ($packages as $package) {
  3034. $bucket[$package->getName()] = $package;
  3035. }
  3036. return $bucket;
  3037. }
  3038. }
  3039. <?php
  3040. namespace Composer\Command;
  3041. use Composer\Config\JsonConfigSource;
  3042. use Composer\Installer;
  3043. use Composer\Plugin\CommandEvent;
  3044. use Composer\Plugin\PluginEvents;
  3045. use Composer\Json\JsonFile;
  3046. use Composer\Factory;
  3047. use Symfony\Component\Console\Input\InputInterface;
  3048. use Symfony\Component\Console\Input\InputOption;
  3049. use Symfony\Component\Console\Input\InputArgument;
  3050. use Symfony\Component\Console\Output\OutputInterface;
  3051. class RemoveCommand extends Command
  3052. {
  3053. protected function configure()
  3054. {
  3055. $this
  3056. ->setName('remove')
  3057. ->setDescription('Removes a package from the require or require-dev')
  3058. ->setDefinition(array(
  3059. new InputArgument('packages', InputArgument::IS_ARRAY, 'Packages that should be removed.'),
  3060. new InputOption('dev', null, InputOption::VALUE_NONE, 'Removes a package from the require-dev section.'),
  3061. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  3062. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  3063. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  3064. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies.'),
  3065. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  3066. ))
  3067. ->setHelp(<<<EOT
  3068. The <info>remove</info> command removes a package from the current
  3069. list of installed packages
  3070. <info>php composer.phar remove</info>
  3071. EOT
  3072. )
  3073. ;
  3074. }
  3075. protected function execute(InputInterface $input, OutputInterface $output)
  3076. {
  3077. $packages = $input->getArgument('packages');
  3078. $file = Factory::getComposerFile();
  3079. $jsonFile = new JsonFile($file);
  3080. $composer = $jsonFile->read();
  3081. $composerBackup = file_get_contents($jsonFile->getPath());
  3082. $json = new JsonConfigSource($jsonFile);
  3083. $type = $input->getOption('dev') ? 'require-dev' : 'require';
  3084. $altType = !$input->getOption('dev') ? 'require-dev' : 'require';
  3085. foreach ($packages as $package) {
  3086. if (isset($composer[$type][$package])) {
  3087. $json->removeLink($type, $package);
  3088. } elseif (isset($composer[$altType][$package])) {
  3089. $this->getIO()->writeError('<warning>'.$package.' could not be found in '.$type.' but it is present in '.$altType.'</warning>');
  3090. $dialog = $this->getHelperSet()->get('dialog');
  3091. if ($this->getIO()->isInteractive()) {
  3092. if ($dialog->askConfirmation($output, $dialog->getQuestion('Do you want to remove it from '.$altType, 'yes', '?'), true)) {
  3093. $json->removeLink($altType, $package);
  3094. }
  3095. }
  3096. } else {
  3097. $this->getIO()->writeError('<warning>'.$package.' is not required in your composer.json and has not been removed</warning>');
  3098. }
  3099. }
  3100. if ($input->getOption('no-update')) {
  3101. return 0;
  3102. }
  3103. $composer = $this->getComposer();
  3104. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  3105. $io = $this->getIO();
  3106. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'remove', $input, $output);
  3107. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  3108. $install = Installer::create($io, $composer);
  3109. $updateDevMode = !$input->getOption('update-no-dev');
  3110. $install
  3111. ->setVerbose($input->getOption('verbose'))
  3112. ->setDevMode($updateDevMode)
  3113. ->setUpdate(true)
  3114. ->setUpdateWhitelist($packages)
  3115. ->setWhitelistDependencies($input->getOption('update-with-dependencies'))
  3116. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  3117. ;
  3118. $status = $install->run();
  3119. if ($status !== 0) {
  3120. $this->getIO()->writeError("\n".'<error>Removal failed, reverting '.$file.' to its original content.</error>');
  3121. file_put_contents($jsonFile->getPath(), $composerBackup);
  3122. }
  3123. return $status;
  3124. }
  3125. }
  3126. <?php
  3127. namespace Composer\Command;
  3128. use Symfony\Component\Console\Input\InputInterface;
  3129. use Symfony\Component\Console\Input\InputArgument;
  3130. use Symfony\Component\Console\Input\InputOption;
  3131. use Symfony\Component\Console\Output\OutputInterface;
  3132. use Composer\Factory;
  3133. use Composer\Installer;
  3134. use Composer\Json\JsonFile;
  3135. use Composer\Json\JsonManipulator;
  3136. use Composer\Package\Version\VersionParser;
  3137. use Composer\Plugin\CommandEvent;
  3138. use Composer\Plugin\PluginEvents;
  3139. use Composer\Repository\CompositeRepository;
  3140. use Composer\Repository\PlatformRepository;
  3141. class RequireCommand extends InitCommand
  3142. {
  3143. protected function configure()
  3144. {
  3145. $this
  3146. ->setName('require')
  3147. ->setDescription('Adds required packages to your composer.json and installs them')
  3148. ->setDefinition(array(
  3149. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Required package name optionally including a version constraint, e.g. foo/bar or foo/bar:1.0.0 or foo/bar=1.0.0 or "foo/bar 1.0.0"'),
  3150. new InputOption('dev', null, InputOption::VALUE_NONE, 'Add requirement to require-dev.'),
  3151. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  3152. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  3153. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  3154. new InputOption('no-update', null, InputOption::VALUE_NONE, 'Disables the automatic update of the dependencies.'),
  3155. new InputOption('update-no-dev', null, InputOption::VALUE_NONE, 'Run the dependency update with the --no-dev option.'),
  3156. new InputOption('update-with-dependencies', null, InputOption::VALUE_NONE, 'Allows inherited dependencies to be updated with explicit dependencies.'),
  3157. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  3158. new InputOption('sort-packages', null, InputOption::VALUE_NONE, 'Sorts packages when adding/updating a new dependency'),
  3159. ))
  3160. ->setHelp(<<<EOT
  3161. The require command adds required packages to your composer.json and installs them.
  3162. If you do not specify a version constraint, composer will choose a suitable one based on the available package versions.
  3163. If you do not want to install the new dependencies immediately you can call it with --no-update
  3164. EOT
  3165. )
  3166. ;
  3167. }
  3168. protected function execute(InputInterface $input, OutputInterface $output)
  3169. {
  3170. $file = Factory::getComposerFile();
  3171. $newlyCreated = !file_exists($file);
  3172. if (!file_exists($file) && !file_put_contents($file, "{\n}\n")) {
  3173. $this->getIO()->writeError('<error>'.$file.' could not be created.</error>');
  3174. return 1;
  3175. }
  3176. if (!is_readable($file)) {
  3177. $this->getIO()->writeError('<error>'.$file.' is not readable.</error>');
  3178. return 1;
  3179. }
  3180. if (!is_writable($file)) {
  3181. $this->getIO()->writeError('<error>'.$file.' is not writable.</error>');
  3182. return 1;
  3183. }
  3184. $json = new JsonFile($file);
  3185. $composerDefinition = $json->read();
  3186. $composerBackup = file_get_contents($json->getPath());
  3187. $composer = $this->getComposer();
  3188. $repos = $composer->getRepositoryManager()->getRepositories();
  3189. $this->repos = new CompositeRepository(array_merge(
  3190. array(new PlatformRepository),
  3191. $repos
  3192. ));
  3193. $requirements = $this->determineRequirements($input, $output, $input->getArgument('packages'));
  3194. $requireKey = $input->getOption('dev') ? 'require-dev' : 'require';
  3195. $removeKey = $input->getOption('dev') ? 'require' : 'require-dev';
  3196. $baseRequirements = array_key_exists($requireKey, $composerDefinition) ? $composerDefinition[$requireKey] : array();
  3197. $requirements = $this->formatRequirements($requirements);
  3198. $versionParser = new VersionParser();
  3199. foreach ($requirements as $constraint) {
  3200. $versionParser->parseConstraints($constraint);
  3201. }
  3202. $sortPackages = $input->getOption('sort-packages');
  3203. if (!$this->updateFileCleanly($json, $baseRequirements, $requirements, $requireKey, $removeKey, $sortPackages)) {
  3204. foreach ($requirements as $package => $version) {
  3205. $baseRequirements[$package] = $version;
  3206. if (isset($composerDefinition[$removeKey][$package])) {
  3207. unset($composerDefinition[$removeKey][$package]);
  3208. }
  3209. }
  3210. $composerDefinition[$requireKey] = $baseRequirements;
  3211. $json->write($composerDefinition);
  3212. }
  3213. $this->getIO()->writeError('<info>'.$file.' has been '.($newlyCreated ? 'created' : 'updated').'</info>');
  3214. if ($input->getOption('no-update')) {
  3215. return 0;
  3216. }
  3217. $updateDevMode = !$input->getOption('update-no-dev');
  3218. $this->resetComposer();
  3219. $composer = $this->getComposer();
  3220. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  3221. $io = $this->getIO();
  3222. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'require', $input, $output);
  3223. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  3224. $install = Installer::create($io, $composer);
  3225. $install
  3226. ->setVerbose($input->getOption('verbose'))
  3227. ->setPreferSource($input->getOption('prefer-source'))
  3228. ->setPreferDist($input->getOption('prefer-dist'))
  3229. ->setDevMode($updateDevMode)
  3230. ->setUpdate(true)
  3231. ->setUpdateWhitelist(array_keys($requirements))
  3232. ->setWhitelistDependencies($input->getOption('update-with-dependencies'))
  3233. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  3234. ;
  3235. $status = $install->run();
  3236. if ($status !== 0) {
  3237. if ($newlyCreated) {
  3238. $this->getIO()->writeError("\n".'<error>Installation failed, deleting '.$file.'.</error>');
  3239. unlink($json->getPath());
  3240. } else {
  3241. $this->getIO()->writeError("\n".'<error>Installation failed, reverting '.$file.' to its original content.</error>');
  3242. file_put_contents($json->getPath(), $composerBackup);
  3243. }
  3244. }
  3245. return $status;
  3246. }
  3247. private function updateFileCleanly($json, array $base, array $new, $requireKey, $removeKey, $sortPackages)
  3248. {
  3249. $contents = file_get_contents($json->getPath());
  3250. $manipulator = new JsonManipulator($contents);
  3251. foreach ($new as $package => $constraint) {
  3252. if (!$manipulator->addLink($requireKey, $package, $constraint, $sortPackages)) {
  3253. return false;
  3254. }
  3255. if (!$manipulator->removeSubNode($removeKey, $package)) {
  3256. return false;
  3257. }
  3258. }
  3259. file_put_contents($json->getPath(), $manipulator->getContents());
  3260. return true;
  3261. }
  3262. protected function interact(InputInterface $input, OutputInterface $output)
  3263. {
  3264. return;
  3265. }
  3266. }
  3267. <?php
  3268. namespace Composer\Command;
  3269. use Composer\Script\CommandEvent;
  3270. use Composer\Script\ScriptEvents;
  3271. use Symfony\Component\Console\Input\InputInterface;
  3272. use Symfony\Component\Console\Input\InputOption;
  3273. use Symfony\Component\Console\Input\InputArgument;
  3274. use Symfony\Component\Console\Output\OutputInterface;
  3275. class RunScriptCommand extends Command
  3276. {
  3277. protected $scriptEvents = array(
  3278. ScriptEvents::PRE_INSTALL_CMD,
  3279. ScriptEvents::POST_INSTALL_CMD,
  3280. ScriptEvents::PRE_UPDATE_CMD,
  3281. ScriptEvents::POST_UPDATE_CMD,
  3282. ScriptEvents::PRE_STATUS_CMD,
  3283. ScriptEvents::POST_STATUS_CMD,
  3284. ScriptEvents::POST_ROOT_PACKAGE_INSTALL,
  3285. ScriptEvents::POST_CREATE_PROJECT_CMD,
  3286. ScriptEvents::PRE_ARCHIVE_CMD,
  3287. ScriptEvents::POST_ARCHIVE_CMD,
  3288. ScriptEvents::PRE_AUTOLOAD_DUMP,
  3289. ScriptEvents::POST_AUTOLOAD_DUMP,
  3290. );
  3291. protected function configure()
  3292. {
  3293. $this
  3294. ->setName('run-script')
  3295. ->setDescription('Run the scripts defined in composer.json.')
  3296. ->setDefinition(array(
  3297. new InputArgument('script', InputArgument::OPTIONAL, 'Script name to run.'),
  3298. new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
  3299. new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'),
  3300. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'),
  3301. new InputOption('list', 'l', InputOption::VALUE_NONE, 'List scripts.'),
  3302. ))
  3303. ->setHelp(<<<EOT
  3304. The <info>run-script</info> command runs scripts defined in composer.json:
  3305. <info>php composer.phar run-script post-update-cmd</info>
  3306. EOT
  3307. )
  3308. ;
  3309. }
  3310. protected function execute(InputInterface $input, OutputInterface $output)
  3311. {
  3312. if ($input->getOption('list')) {
  3313. return $this->listScripts();
  3314. } elseif (!$input->getArgument('script')) {
  3315. throw new \RunTimeException('Missing required argument "script"');
  3316. }
  3317. $script = $input->getArgument('script');
  3318. if (!in_array($script, $this->scriptEvents)) {
  3319. if (defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
  3320. throw new \InvalidArgumentException(sprintf('Script "%s" cannot be run with this command', $script));
  3321. }
  3322. }
  3323. $composer = $this->getComposer();
  3324. $hasListeners = $composer->getEventDispatcher()->hasEventListeners(new CommandEvent($script, $composer, $this->getIO()));
  3325. if (!$hasListeners) {
  3326. throw new \InvalidArgumentException(sprintf('Script "%s" is not defined in this package', $script));
  3327. }
  3328. $binDir = $composer->getConfig()->get('bin-dir');
  3329. if (is_dir($binDir)) {
  3330. putenv('PATH='.realpath($binDir).PATH_SEPARATOR.getenv('PATH'));
  3331. }
  3332. $args = $input->getArgument('args');
  3333. return $composer->getEventDispatcher()->dispatchScript($script, $input->getOption('dev') || !$input->getOption('no-dev'), $args);
  3334. }
  3335. protected function listScripts()
  3336. {
  3337. $scripts = $this->getComposer()->getPackage()->getScripts();
  3338. if (!count($scripts)) {
  3339. return 0;
  3340. }
  3341. $this->getIO()->writeError('<info>scripts:</info>');
  3342. foreach ($scripts as $name => $script) {
  3343. $this->getIO()->write(' ' . $name);
  3344. }
  3345. return 0;
  3346. }
  3347. }
  3348. <?php
  3349. namespace Composer\Command;
  3350. use Symfony\Component\Console\Input\InputInterface;
  3351. use Symfony\Component\Console\Input\InputOption;
  3352. use Symfony\Component\Console\Input\InputArgument;
  3353. use Symfony\Component\Console\Output\OutputInterface;
  3354. class ScriptAliasCommand extends Command
  3355. {
  3356. private $script;
  3357. public function __construct($script)
  3358. {
  3359. $this->script = $script;
  3360. parent::__construct();
  3361. }
  3362. protected function configure()
  3363. {
  3364. $this
  3365. ->setName($this->script)
  3366. ->setDescription('Run the '.$this->script.' script as defined in composer.json.')
  3367. ->setDefinition(array(
  3368. new InputOption('dev', null, InputOption::VALUE_NONE, 'Sets the dev mode.'),
  3369. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables the dev mode.'),
  3370. new InputArgument('args', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, ''),
  3371. ))
  3372. ->setHelp(<<<EOT
  3373. The <info>run-script</info> command runs scripts defined in composer.json:
  3374. <info>php composer.phar run-script post-update-cmd</info>
  3375. EOT
  3376. )
  3377. ;
  3378. }
  3379. protected function execute(InputInterface $input, OutputInterface $output)
  3380. {
  3381. $composer = $this->getComposer();
  3382. $binDir = $composer->getConfig()->get('bin-dir');
  3383. if (is_dir($binDir)) {
  3384. putenv('PATH='.realpath($binDir).PATH_SEPARATOR.getenv('PATH'));
  3385. }
  3386. $args = $input->getArguments();
  3387. return $composer->getEventDispatcher()->dispatchScript($this->script, $input->getOption('dev') || !$input->getOption('no-dev'), $args['args']);
  3388. }
  3389. }
  3390. <?php
  3391. namespace Composer\Command;
  3392. use Symfony\Component\Console\Input\InputInterface;
  3393. use Symfony\Component\Console\Input\InputArgument;
  3394. use Symfony\Component\Console\Input\InputOption;
  3395. use Symfony\Component\Console\Output\OutputInterface;
  3396. use Composer\Repository\CompositeRepository;
  3397. use Composer\Repository\PlatformRepository;
  3398. use Composer\Repository\RepositoryInterface;
  3399. use Composer\Factory;
  3400. use Composer\Plugin\CommandEvent;
  3401. use Composer\Plugin\PluginEvents;
  3402. class SearchCommand extends Command
  3403. {
  3404. protected $matches;
  3405. protected $lowMatches = array();
  3406. protected $tokens;
  3407. protected $output;
  3408. protected $onlyName;
  3409. protected function configure()
  3410. {
  3411. $this
  3412. ->setName('search')
  3413. ->setDescription('Search for packages')
  3414. ->setDefinition(array(
  3415. new InputOption('only-name', 'N', InputOption::VALUE_NONE, 'Search only in name'),
  3416. new InputArgument('tokens', InputArgument::IS_ARRAY | InputArgument::REQUIRED, 'tokens to search for'),
  3417. ))
  3418. ->setHelp(<<<EOT
  3419. The search command searches for packages by its name
  3420. <info>php composer.phar search symfony composer</info>
  3421. EOT
  3422. )
  3423. ;
  3424. }
  3425. protected function execute(InputInterface $input, OutputInterface $output)
  3426. {
  3427. $platformRepo = new PlatformRepository;
  3428. if ($composer = $this->getComposer(false)) {
  3429. $localRepo = $composer->getRepositoryManager()->getLocalRepository();
  3430. $installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
  3431. $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories()));
  3432. } else {
  3433. $defaultRepos = Factory::createDefaultRepositories($this->getIO());
  3434. $this->getIO()->writeError('No composer.json found in the current directory, showing packages from ' . implode(', ', array_keys($defaultRepos)));
  3435. $installedRepo = $platformRepo;
  3436. $repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
  3437. }
  3438. if ($composer) {
  3439. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'search', $input, $output);
  3440. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  3441. }
  3442. $onlyName = $input->getOption('only-name');
  3443. $flags = $onlyName ? RepositoryInterface::SEARCH_NAME : RepositoryInterface::SEARCH_FULLTEXT;
  3444. $results = $repos->search(implode(' ', $input->getArgument('tokens')), $flags);
  3445. foreach ($results as $result) {
  3446. $this->getIO()->write($result['name'] . (isset($result['description']) ? ' '. $result['description'] : ''));
  3447. }
  3448. }
  3449. }
  3450. <?php
  3451. namespace Composer\Command;
  3452. use Composer\Composer;
  3453. use Composer\Factory;
  3454. use Composer\Util\Filesystem;
  3455. use Composer\Util\RemoteFilesystem;
  3456. use Composer\Downloader\FilesystemException;
  3457. use Symfony\Component\Console\Input\InputInterface;
  3458. use Symfony\Component\Console\Input\InputOption;
  3459. use Symfony\Component\Console\Input\InputArgument;
  3460. use Symfony\Component\Console\Output\OutputInterface;
  3461. use Symfony\Component\Finder\Finder;
  3462. class SelfUpdateCommand extends Command
  3463. {
  3464. const HOMEPAGE = 'getcomposer.org';
  3465. const OLD_INSTALL_EXT = '-old.phar';
  3466. protected function configure()
  3467. {
  3468. $this
  3469. ->setName('self-update')
  3470. ->setAliases(array('selfupdate'))
  3471. ->setDescription('Updates composer.phar to the latest version.')
  3472. ->setDefinition(array(
  3473. new InputOption('rollback', 'r', InputOption::VALUE_NONE, 'Revert to an older installation of composer'),
  3474. new InputOption('clean-backups', null, InputOption::VALUE_NONE, 'Delete old backups during an update. This makes the current version of composer the only backup available after the update'),
  3475. new InputArgument('version', InputArgument::OPTIONAL, 'The version to update to'),
  3476. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  3477. ))
  3478. ->setHelp(<<<EOT
  3479. The <info>self-update</info> command checks getcomposer.org for newer
  3480. versions of composer and if found, installs the latest.
  3481. <info>php composer.phar self-update</info>
  3482. EOT
  3483. )
  3484. ;
  3485. }
  3486. protected function execute(InputInterface $input, OutputInterface $output)
  3487. {
  3488. $baseUrl = (extension_loaded('openssl') ? 'https' : 'http') . '://' . self::HOMEPAGE;
  3489. $config = Factory::createConfig();
  3490. $remoteFilesystem = new RemoteFilesystem($this->getIO(), $config);
  3491. $cacheDir = $config->get('cache-dir');
  3492. $rollbackDir = $config->get('home');
  3493. $localFilename = realpath($_SERVER['argv'][0]) ?: $_SERVER['argv'][0];
  3494. $tmpDir = is_writable(dirname($localFilename)) ? dirname($localFilename) : $cacheDir;
  3495. if (!is_writable($tmpDir)) {
  3496. throw new FilesystemException('Composer update failed: the "'.$tmpDir.'" directory used to download the temp file could not be written');
  3497. }
  3498. if (!is_writable($localFilename)) {
  3499. throw new FilesystemException('Composer update failed: the "'.$localFilename.'" file could not be written');
  3500. }
  3501. if ($input->getOption('rollback')) {
  3502. return $this->rollback($output, $rollbackDir, $localFilename);
  3503. }
  3504. $latestVersion = trim($remoteFilesystem->getContents(self::HOMEPAGE, $baseUrl. '/version', false));
  3505. $updateVersion = $input->getArgument('version') ?: $latestVersion;
  3506. if (preg_match('{^[0-9a-f]{40}$}', $updateVersion) && $updateVersion !== $latestVersion) {
  3507. $this->getIO()->writeError('<error>You can not update to a specific SHA-1 as those phars are not available for download</error>');
  3508. return 1;
  3509. }
  3510. if (Composer::VERSION === $updateVersion) {
  3511. $this->getIO()->writeError('<info>You are already using composer version '.$updateVersion.'.</info>');
  3512. return 0;
  3513. }
  3514. $tempFilename = $tmpDir . '/' . basename($localFilename, '.phar').'-temp.phar';
  3515. $backupFile = sprintf(
  3516. '%s/%s-%s%s',
  3517. $rollbackDir,
  3518. strtr(Composer::RELEASE_DATE, ' :', '_-'),
  3519. preg_replace('{^([0-9a-f]{7})[0-9a-f]{33}$}', '$1', Composer::VERSION),
  3520. self::OLD_INSTALL_EXT
  3521. );
  3522. $this->getIO()->writeError(sprintf("Updating to version <info>%s</info>.", $updateVersion));
  3523. $remoteFilename = $baseUrl . (preg_match('{^[0-9a-f]{40}$}', $updateVersion) ? '/composer.phar' : "/download/{$updateVersion}/composer.phar");
  3524. $remoteFilesystem->copy(self::HOMEPAGE, $remoteFilename, $tempFilename, !$input->getOption('no-progress'));
  3525. if (!file_exists($tempFilename)) {
  3526. $this->getIO()->writeError('<error>The download of the new composer version failed for an unexpected reason</error>');
  3527. return 1;
  3528. }
  3529. if ($input->getOption('clean-backups')) {
  3530. $finder = $this->getOldInstallationFinder($rollbackDir);
  3531. $fs = new Filesystem;
  3532. foreach ($finder as $file) {
  3533. $file = (string) $file;
  3534. $this->getIO()->writeError('<info>Removing: '.$file.'</info>');
  3535. $fs->remove($file);
  3536. }
  3537. }
  3538. if ($err = $this->setLocalPhar($localFilename, $tempFilename, $backupFile)) {
  3539. $this->getIO()->writeError('<error>The file is corrupted ('.$err->getMessage().').</error>');
  3540. $this->getIO()->writeError('<error>Please re-run the self-update command to try again.</error>');
  3541. return 1;
  3542. }
  3543. if (file_exists($backupFile)) {
  3544. $this->getIO()->writeError('Use <info>composer self-update --rollback</info> to return to version '.Composer::VERSION);
  3545. } else {
  3546. $this->getIO()->writeError('<warning>A backup of the current version could not be written to '.$backupFile.', no rollback possible</warning>');
  3547. }
  3548. }
  3549. protected function rollback(OutputInterface $output, $rollbackDir, $localFilename)
  3550. {
  3551. $rollbackVersion = $this->getLastBackupVersion($rollbackDir);
  3552. if (!$rollbackVersion) {
  3553. throw new \UnexpectedValueException('Composer rollback failed: no installation to roll back to in "'.$rollbackDir.'"');
  3554. }
  3555. if (!is_writable($rollbackDir)) {
  3556. throw new FilesystemException('Composer rollback failed: the "'.$rollbackDir.'" dir could not be written to');
  3557. }
  3558. $old = $rollbackDir . '/' . $rollbackVersion . self::OLD_INSTALL_EXT;
  3559. if (!is_file($old)) {
  3560. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be found');
  3561. }
  3562. if (!is_readable($old)) {
  3563. throw new FilesystemException('Composer rollback failed: "'.$old.'" could not be read');
  3564. }
  3565. $oldFile = $rollbackDir . "/{$rollbackVersion}" . self::OLD_INSTALL_EXT;
  3566. $this->getIO()->writeError(sprintf("Rolling back to version <info>%s</info>.", $rollbackVersion));
  3567. if ($err = $this->setLocalPhar($localFilename, $oldFile)) {
  3568. $this->getIO()->writeError('<error>The backup file was corrupted ('.$err->getMessage().') and has been removed.</error>');
  3569. return 1;
  3570. }
  3571. return 0;
  3572. }
  3573. protected function setLocalPhar($localFilename, $newFilename, $backupTarget = null)
  3574. {
  3575. try {
  3576. @chmod($newFilename, fileperms($localFilename));
  3577. if (!ini_get('phar.readonly')) {
  3578. $phar = new \Phar($newFilename);
  3579. unset($phar);
  3580. }
  3581. if ($backupTarget && file_exists($localFilename)) {
  3582. @copy($localFilename, $backupTarget);
  3583. }
  3584. rename($newFilename, $localFilename);
  3585. } catch (\Exception $e) {
  3586. if ($backupTarget) {
  3587. @unlink($newFilename);
  3588. }
  3589. if (!$e instanceof \UnexpectedValueException && !$e instanceof \PharException) {
  3590. throw $e;
  3591. }
  3592. return $e;
  3593. }
  3594. }
  3595. protected function getLastBackupVersion($rollbackDir)
  3596. {
  3597. $finder = $this->getOldInstallationFinder($rollbackDir);
  3598. $finder->sortByName();
  3599. $files = iterator_to_array($finder);
  3600. if (count($files)) {
  3601. return basename(end($files), self::OLD_INSTALL_EXT);
  3602. }
  3603. return false;
  3604. }
  3605. protected function getOldInstallationFinder($rollbackDir)
  3606. {
  3607. $finder = Finder::create()
  3608. ->depth(0)
  3609. ->files()
  3610. ->name('*' . self::OLD_INSTALL_EXT)
  3611. ->in($rollbackDir);
  3612. return $finder;
  3613. }
  3614. }
  3615. <?php
  3616. namespace Composer\Command;
  3617. use Composer\DependencyResolver\Pool;
  3618. use Composer\DependencyResolver\DefaultPolicy;
  3619. use Composer\Factory;
  3620. use Composer\Package\CompletePackageInterface;
  3621. use Composer\Package\Version\VersionParser;
  3622. use Composer\Plugin\CommandEvent;
  3623. use Composer\Plugin\PluginEvents;
  3624. use Symfony\Component\Console\Input\InputInterface;
  3625. use Symfony\Component\Console\Input\InputArgument;
  3626. use Symfony\Component\Console\Input\InputOption;
  3627. use Symfony\Component\Console\Output\OutputInterface;
  3628. use Composer\Repository\ArrayRepository;
  3629. use Composer\Repository\CompositeRepository;
  3630. use Composer\Repository\ComposerRepository;
  3631. use Composer\Repository\PlatformRepository;
  3632. use Composer\Repository\RepositoryInterface;
  3633. class ShowCommand extends Command
  3634. {
  3635. protected $versionParser;
  3636. protected function configure()
  3637. {
  3638. $this
  3639. ->setName('show')
  3640. ->setAliases(array('info'))
  3641. ->setDescription('Show information about packages')
  3642. ->setDefinition(array(
  3643. new InputArgument('package', InputArgument::OPTIONAL, 'Package to inspect'),
  3644. new InputArgument('version', InputArgument::OPTIONAL, 'Version or version constraint to inspect'),
  3645. new InputOption('installed', 'i', InputOption::VALUE_NONE, 'List installed packages only'),
  3646. new InputOption('platform', 'p', InputOption::VALUE_NONE, 'List platform packages only'),
  3647. new InputOption('available', 'a', InputOption::VALUE_NONE, 'List available packages only'),
  3648. new InputOption('self', 's', InputOption::VALUE_NONE, 'Show the root package information'),
  3649. new InputOption('name-only', 'N', InputOption::VALUE_NONE, 'List package names only'),
  3650. new InputOption('path', 'P', InputOption::VALUE_NONE, 'Show package paths'),
  3651. ))
  3652. ->setHelp(<<<EOT
  3653. The show command displays detailed information about a package, or
  3654. lists all packages available.
  3655. EOT
  3656. )
  3657. ;
  3658. }
  3659. protected function execute(InputInterface $input, OutputInterface $output)
  3660. {
  3661. $this->versionParser = new VersionParser;
  3662. $platformRepo = new PlatformRepository;
  3663. $composer = $this->getComposer(false);
  3664. if ($input->getOption('self')) {
  3665. $package = $this->getComposer()->getPackage();
  3666. $repos = $installedRepo = new ArrayRepository(array($package));
  3667. } elseif ($input->getOption('platform')) {
  3668. $repos = $installedRepo = $platformRepo;
  3669. } elseif ($input->getOption('installed')) {
  3670. $repos = $installedRepo = $this->getComposer()->getRepositoryManager()->getLocalRepository();
  3671. } elseif ($input->getOption('available')) {
  3672. $installedRepo = $platformRepo;
  3673. if ($composer) {
  3674. $repos = new CompositeRepository($composer->getRepositoryManager()->getRepositories());
  3675. } else {
  3676. $defaultRepos = Factory::createDefaultRepositories($this->getIO());
  3677. $repos = new CompositeRepository($defaultRepos);
  3678. $this->getIO()->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
  3679. }
  3680. } elseif ($composer) {
  3681. $localRepo = $composer->getRepositoryManager()->getLocalRepository();
  3682. $installedRepo = new CompositeRepository(array($localRepo, $platformRepo));
  3683. $repos = new CompositeRepository(array_merge(array($installedRepo), $composer->getRepositoryManager()->getRepositories()));
  3684. } else {
  3685. $defaultRepos = Factory::createDefaultRepositories($this->getIO());
  3686. $this->getIO()->writeError('No composer.json found in the current directory, showing available packages from ' . implode(', ', array_keys($defaultRepos)));
  3687. $installedRepo = $platformRepo;
  3688. $repos = new CompositeRepository(array_merge(array($installedRepo), $defaultRepos));
  3689. }
  3690. if ($composer) {
  3691. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'show', $input, $output);
  3692. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  3693. }
  3694. if ($input->getArgument('package') || !empty($package)) {
  3695. $versions = array();
  3696. if (empty($package)) {
  3697. list($package, $versions) = $this->getPackage($installedRepo, $repos, $input->getArgument('package'), $input->getArgument('version'));
  3698. if (!$package) {
  3699. throw new \InvalidArgumentException('Package '.$input->getArgument('package').' not found');
  3700. }
  3701. } else {
  3702. $versions = array($package->getPrettyVersion() => $package->getVersion());
  3703. }
  3704. $this->printMeta($input, $output, $package, $versions, $installedRepo, $repos);
  3705. $this->printLinks($input, $output, $package, 'requires');
  3706. $this->printLinks($input, $output, $package, 'devRequires', 'requires (dev)');
  3707. if ($package->getSuggests()) {
  3708. $this->getIO()->write("\n<info>suggests</info>");
  3709. foreach ($package->getSuggests() as $suggested => $reason) {
  3710. $this->getIO()->write($suggested . ' <comment>' . $reason . '</comment>');
  3711. }
  3712. }
  3713. $this->printLinks($input, $output, $package, 'provides');
  3714. $this->printLinks($input, $output, $package, 'conflicts');
  3715. $this->printLinks($input, $output, $package, 'replaces');
  3716. return;
  3717. }
  3718. $packages = array();
  3719. if ($repos instanceof CompositeRepository) {
  3720. $repos = $repos->getRepositories();
  3721. } elseif (!is_array($repos)) {
  3722. $repos = array($repos);
  3723. }
  3724. foreach ($repos as $repo) {
  3725. if ($repo === $platformRepo) {
  3726. $type = '<info>platform</info>:';
  3727. } elseif (
  3728. $repo === $installedRepo
  3729. || ($installedRepo instanceof CompositeRepository && in_array($repo, $installedRepo->getRepositories(), true))
  3730. ) {
  3731. $type = '<info>installed</info>:';
  3732. } else {
  3733. $type = '<comment>available</comment>:';
  3734. }
  3735. if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
  3736. foreach ($repo->getProviderNames() as $name) {
  3737. $packages[$type][$name] = $name;
  3738. }
  3739. } else {
  3740. foreach ($repo->getPackages() as $package) {
  3741. if (!isset($packages[$type][$package->getName()])
  3742. || !is_object($packages[$type][$package->getName()])
  3743. || version_compare($packages[$type][$package->getName()]->getVersion(), $package->getVersion(), '<')
  3744. ) {
  3745. $packages[$type][$package->getName()] = $package;
  3746. }
  3747. }
  3748. }
  3749. }
  3750. $tree = !$input->getOption('platform') && !$input->getOption('installed') && !$input->getOption('available');
  3751. $indent = $tree ? ' ' : '';
  3752. foreach (array('<info>platform</info>:' => true, '<comment>available</comment>:' => false, '<info>installed</info>:' => true) as $type => $showVersion) {
  3753. if (isset($packages[$type])) {
  3754. if ($tree) {
  3755. $this->getIO()->write($type);
  3756. }
  3757. ksort($packages[$type]);
  3758. $nameLength = $versionLength = 0;
  3759. foreach ($packages[$type] as $package) {
  3760. if (is_object($package)) {
  3761. $nameLength = max($nameLength, strlen($package->getPrettyName()));
  3762. $versionLength = max($versionLength, strlen($this->versionParser->formatVersion($package)));
  3763. } else {
  3764. $nameLength = max($nameLength, $package);
  3765. }
  3766. }
  3767. list($width) = $this->getApplication()->getTerminalDimensions();
  3768. if (null === $width) {
  3769. $width = PHP_INT_MAX;
  3770. }
  3771. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  3772. $width--;
  3773. }
  3774. $writePath = !$input->getOption('name-only') && $input->getOption('path');
  3775. $writeVersion = !$input->getOption('name-only') && !$input->getOption('path') && $showVersion && ($nameLength + $versionLength + 3 <= $width);
  3776. $writeDescription = !$input->getOption('name-only') && !$input->getOption('path') && ($nameLength + ($showVersion ? $versionLength : 0) + 24 <= $width);
  3777. foreach ($packages[$type] as $package) {
  3778. if (is_object($package)) {
  3779. $output->write($indent . str_pad($package->getPrettyName(), $nameLength, ' '), false);
  3780. if ($writeVersion) {
  3781. $output->write(' ' . str_pad($this->versionParser->formatVersion($package), $versionLength, ' '), false);
  3782. }
  3783. if ($writeDescription) {
  3784. $description = strtok($package->getDescription(), "\r\n");
  3785. $remaining = $width - $nameLength - $versionLength - 4;
  3786. if (strlen($description) > $remaining) {
  3787. $description = substr($description, 0, $remaining - 3) . '...';
  3788. }
  3789. $output->write(' ' . $description);
  3790. }
  3791. if ($writePath) {
  3792. $path = strtok(realpath($composer->getInstallationManager()->getInstallPath($package)), "\r\n");
  3793. $output->write(' ' . $path);
  3794. }
  3795. } else {
  3796. $output->write($indent . $package);
  3797. }
  3798. $this->getIO()->write('');
  3799. }
  3800. if ($tree) {
  3801. $this->getIO()->write('');
  3802. }
  3803. }
  3804. }
  3805. }
  3806. protected function getPackage(RepositoryInterface $installedRepo, RepositoryInterface $repos, $name, $version = null)
  3807. {
  3808. $name = strtolower($name);
  3809. $constraint = null;
  3810. if ($version) {
  3811. $constraint = $this->versionParser->parseConstraints($version);
  3812. }
  3813. $policy = new DefaultPolicy();
  3814. $pool = new Pool('dev');
  3815. $pool->addRepository($repos);
  3816. $matchedPackage = null;
  3817. $versions = array();
  3818. $matches = $pool->whatProvides($name, $constraint);
  3819. foreach ($matches as $index => $package) {
  3820. if ($package->getName() !== $name) {
  3821. unset($matches[$index]);
  3822. continue;
  3823. }
  3824. if (null === $version && $installedRepo->hasPackage($package)) {
  3825. $matchedPackage = $package;
  3826. }
  3827. $versions[$package->getPrettyVersion()] = $package->getVersion();
  3828. $matches[$index] = $package->getId();
  3829. }
  3830. if (!$matchedPackage && $matches && $prefered = $policy->selectPreferedPackages($pool, array(), $matches)) {
  3831. $matchedPackage = $pool->literalToPackage($prefered[0]);
  3832. }
  3833. return array($matchedPackage, $versions);
  3834. }
  3835. protected function printMeta(InputInterface $input, OutputInterface $output, CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, RepositoryInterface $repos)
  3836. {
  3837. $this->getIO()->write('<info>name</info> : ' . $package->getPrettyName());
  3838. $this->getIO()->write('<info>descrip.</info> : ' . $package->getDescription());
  3839. $this->getIO()->write('<info>keywords</info> : ' . join(', ', $package->getKeywords() ?: array()));
  3840. $this->printVersions($input, $output, $package, $versions, $installedRepo, $repos);
  3841. $this->getIO()->write('<info>type</info> : ' . $package->getType());
  3842. $this->getIO()->write('<info>license</info> : ' . implode(', ', $package->getLicense()));
  3843. $this->getIO()->write('<info>source</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getSourceType(), $package->getSourceUrl(), $package->getSourceReference()));
  3844. $this->getIO()->write('<info>dist</info> : ' . sprintf('[%s] <comment>%s</comment> %s', $package->getDistType(), $package->getDistUrl(), $package->getDistReference()));
  3845. $this->getIO()->write('<info>names</info> : ' . implode(', ', $package->getNames()));
  3846. if ($package->isAbandoned()) {
  3847. $replacement = ($package->getReplacementPackage() !== null)
  3848. ? ' The author suggests using the ' . $package->getReplacementPackage(). ' package instead.'
  3849. : null;
  3850. $this->getIO()->writeError(
  3851. sprintf('<error>Attention: This package is abandoned and no longer maintained.%s</error>', $replacement)
  3852. );
  3853. }
  3854. if ($package->getSupport()) {
  3855. $this->getIO()->write("\n<info>support</info>");
  3856. foreach ($package->getSupport() as $type => $value) {
  3857. $this->getIO()->write('<comment>' . $type . '</comment> : '.$value);
  3858. }
  3859. }
  3860. if ($package->getAutoload()) {
  3861. $this->getIO()->write("\n<info>autoload</info>");
  3862. foreach ($package->getAutoload() as $type => $autoloads) {
  3863. $this->getIO()->write('<comment>' . $type . '</comment>');
  3864. if ($type === 'psr-0') {
  3865. foreach ($autoloads as $name => $path) {
  3866. $this->getIO()->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  3867. }
  3868. } elseif ($type === 'psr-4') {
  3869. foreach ($autoloads as $name => $path) {
  3870. $this->getIO()->write(($name ?: '*') . ' => ' . (is_array($path) ? implode(', ', $path) : ($path ?: '.')));
  3871. }
  3872. } elseif ($type === 'classmap') {
  3873. $this->getIO()->write(implode(', ', $autoloads));
  3874. }
  3875. }
  3876. if ($package->getIncludePaths()) {
  3877. $this->getIO()->write('<comment>include-path</comment>');
  3878. $this->getIO()->write(implode(', ', $package->getIncludePaths()));
  3879. }
  3880. }
  3881. }
  3882. protected function printVersions(InputInterface $input, OutputInterface $output, CompletePackageInterface $package, array $versions, RepositoryInterface $installedRepo, RepositoryInterface $repos)
  3883. {
  3884. uasort($versions, 'version_compare');
  3885. $versions = array_keys(array_reverse($versions));
  3886. if ($installedRepo->hasPackage($package)) {
  3887. $installedVersion = $package->getPrettyVersion();
  3888. $key = array_search($installedVersion, $versions);
  3889. if (false !== $key) {
  3890. $versions[$key] = '<info>* ' . $installedVersion . '</info>';
  3891. }
  3892. }
  3893. $versions = implode(', ', $versions);
  3894. $this->getIO()->write('<info>versions</info> : ' . $versions);
  3895. }
  3896. protected function printLinks(InputInterface $input, OutputInterface $output, CompletePackageInterface $package, $linkType, $title = null)
  3897. {
  3898. $title = $title ?: $linkType;
  3899. if ($links = $package->{'get'.ucfirst($linkType)}()) {
  3900. $this->getIO()->write("\n<info>" . $title . "</info>");
  3901. foreach ($links as $link) {
  3902. $this->getIO()->write($link->getTarget() . ' <comment>' . $link->getPrettyConstraint() . '</comment>');
  3903. }
  3904. }
  3905. }
  3906. }
  3907. <?php
  3908. namespace Composer\Command;
  3909. use Symfony\Component\Console\Input\InputInterface;
  3910. use Symfony\Component\Console\Input\InputOption;
  3911. use Symfony\Component\Console\Output\OutputInterface;
  3912. use Composer\Downloader\ChangeReportInterface;
  3913. use Composer\Plugin\CommandEvent;
  3914. use Composer\Plugin\PluginEvents;
  3915. use Composer\Script\ScriptEvents;
  3916. class StatusCommand extends Command
  3917. {
  3918. protected function configure()
  3919. {
  3920. $this
  3921. ->setName('status')
  3922. ->setDescription('Show a list of locally modified packages')
  3923. ->setDefinition(array(
  3924. new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Show modified files for each directory that contains changes.'),
  3925. ))
  3926. ->setHelp(<<<EOT
  3927. The status command displays a list of dependencies that have
  3928. been modified locally.
  3929. EOT
  3930. )
  3931. ;
  3932. }
  3933. protected function execute(InputInterface $input, OutputInterface $output)
  3934. {
  3935. $composer = $this->getComposer();
  3936. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'status', $input, $output);
  3937. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  3938. $installedRepo = $composer->getRepositoryManager()->getLocalRepository();
  3939. $dm = $composer->getDownloadManager();
  3940. $im = $composer->getInstallationManager();
  3941. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::PRE_STATUS_CMD, true);
  3942. $errors = array();
  3943. foreach ($installedRepo->getPackages() as $package) {
  3944. $downloader = $dm->getDownloaderForInstalledPackage($package);
  3945. if ($downloader instanceof ChangeReportInterface) {
  3946. $targetDir = $im->getInstallPath($package);
  3947. if ($changes = $downloader->getLocalChanges($package, $targetDir)) {
  3948. $errors[$targetDir] = $changes;
  3949. }
  3950. }
  3951. }
  3952. if (!$errors) {
  3953. $this->getIO()->writeError('<info>No local changes</info>');
  3954. } else {
  3955. $this->getIO()->writeError('<error>You have changes in the following dependencies:</error>');
  3956. }
  3957. foreach ($errors as $path => $changes) {
  3958. if ($input->getOption('verbose')) {
  3959. $indentedChanges = implode("\n", array_map(function ($line) {
  3960. return ' ' . ltrim($line);
  3961. }, explode("\n", $changes)));
  3962. $this->getIO()->write('<info>'.$path.'</info>:');
  3963. $this->getIO()->write($indentedChanges);
  3964. } else {
  3965. $this->getIO()->write($path);
  3966. }
  3967. }
  3968. if ($errors && !$input->getOption('verbose')) {
  3969. $this->getIO()->writeError('Use --verbose (-v) to see modified files');
  3970. }
  3971. $composer->getEventDispatcher()->dispatchScript(ScriptEvents::POST_STATUS_CMD, true);
  3972. return $errors ? 1 : 0;
  3973. }
  3974. }
  3975. <?php
  3976. namespace Composer\Command;
  3977. use Composer\Installer;
  3978. use Composer\Plugin\CommandEvent;
  3979. use Composer\Plugin\PluginEvents;
  3980. use Symfony\Component\Console\Input\InputInterface;
  3981. use Symfony\Component\Console\Input\InputOption;
  3982. use Symfony\Component\Console\Input\InputArgument;
  3983. use Symfony\Component\Console\Output\OutputInterface;
  3984. class UpdateCommand extends Command
  3985. {
  3986. protected function configure()
  3987. {
  3988. $this
  3989. ->setName('update')
  3990. ->setDescription('Updates your dependencies to the latest version according to composer.json, and updates the composer.lock file.')
  3991. ->setDefinition(array(
  3992. new InputArgument('packages', InputArgument::IS_ARRAY | InputArgument::OPTIONAL, 'Packages that should be updated, if not provided all packages are.'),
  3993. new InputOption('prefer-source', null, InputOption::VALUE_NONE, 'Forces installation from package sources when possible, including VCS information.'),
  3994. new InputOption('prefer-dist', null, InputOption::VALUE_NONE, 'Forces installation from package dist even for dev versions.'),
  3995. new InputOption('dry-run', null, InputOption::VALUE_NONE, 'Outputs the operations but will not execute anything (implicitly enables --verbose).'),
  3996. new InputOption('dev', null, InputOption::VALUE_NONE, 'Enables installation of require-dev packages (enabled by default, only present for BC).'),
  3997. new InputOption('no-dev', null, InputOption::VALUE_NONE, 'Disables installation of require-dev packages.'),
  3998. new InputOption('lock', null, InputOption::VALUE_NONE, 'Only updates the lock file hash to suppress warning about the lock file being out of date.'),
  3999. new InputOption('no-plugins', null, InputOption::VALUE_NONE, 'Disables all plugins.'),
  4000. new InputOption('no-custom-installers', null, InputOption::VALUE_NONE, 'DEPRECATED: Use no-plugins instead.'),
  4001. new InputOption('no-autoloader', null, InputOption::VALUE_NONE, 'Skips autoloader generation'),
  4002. new InputOption('no-scripts', null, InputOption::VALUE_NONE, 'Skips the execution of all scripts defined in composer.json file.'),
  4003. new InputOption('no-progress', null, InputOption::VALUE_NONE, 'Do not output download progress.'),
  4004. new InputOption('with-dependencies', null, InputOption::VALUE_NONE, 'Add also all dependencies of whitelisted packages to the whitelist.'),
  4005. new InputOption('verbose', 'v|vv|vvv', InputOption::VALUE_NONE, 'Shows more details including new commits pulled in when updating packages.'),
  4006. new InputOption('optimize-autoloader', 'o', InputOption::VALUE_NONE, 'Optimize autoloader during autoloader dump.'),
  4007. new InputOption('ignore-platform-reqs', null, InputOption::VALUE_NONE, 'Ignore platform requirements (php & ext- packages).'),
  4008. new InputOption('prefer-stable', null, InputOption::VALUE_NONE, 'Prefer stable versions of dependencies.'),
  4009. new InputOption('prefer-lowest', null, InputOption::VALUE_NONE, 'Prefer lowest versions of dependencies.'),
  4010. ))
  4011. ->setHelp(<<<EOT
  4012. The <info>update</info> command reads the composer.json file from the
  4013. current directory, processes it, and updates, removes or installs all the
  4014. dependencies.
  4015. <info>php composer.phar update</info>
  4016. To limit the update operation to a few packages, you can list the package(s)
  4017. you want to update as such:
  4018. <info>php composer.phar update vendor/package1 foo/mypackage [...]</info>
  4019. You may also use an asterisk (*) pattern to limit the update operation to package(s)
  4020. from a specific vendor:
  4021. <info>php composer.phar update vendor/package1 foo/* [...]</info>
  4022. EOT
  4023. )
  4024. ;
  4025. }
  4026. protected function execute(InputInterface $input, OutputInterface $output)
  4027. {
  4028. if ($input->getOption('no-custom-installers')) {
  4029. $this->getIO()->writeError('<warning>You are using the deprecated option "no-custom-installers". Use "no-plugins" instead.</warning>');
  4030. $input->setOption('no-plugins', true);
  4031. }
  4032. if ($input->getOption('dev')) {
  4033. $this->getIO()->writeError('<warning>You are using the deprecated option "dev". Dev packages are installed by default now.</warning>');
  4034. }
  4035. $composer = $this->getComposer(true, $input->getOption('no-plugins'));
  4036. $composer->getDownloadManager()->setOutputProgress(!$input->getOption('no-progress'));
  4037. $io = $this->getIO();
  4038. $commandEvent = new CommandEvent(PluginEvents::COMMAND, 'update', $input, $output);
  4039. $composer->getEventDispatcher()->dispatch($commandEvent->getName(), $commandEvent);
  4040. $install = Installer::create($io, $composer);
  4041. $preferSource = false;
  4042. $preferDist = false;
  4043. $config = $composer->getConfig();
  4044. switch ($config->get('preferred-install')) {
  4045. case 'source':
  4046. $preferSource = true;
  4047. break;
  4048. case 'dist':
  4049. $preferDist = true;
  4050. break;
  4051. case 'auto':
  4052. default:
  4053. break;
  4054. }
  4055. if ($input->getOption('prefer-source') || $input->getOption('prefer-dist')) {
  4056. $preferSource = $input->getOption('prefer-source');
  4057. $preferDist = $input->getOption('prefer-dist');
  4058. }
  4059. $optimize = $input->getOption('optimize-autoloader') || $config->get('optimize-autoloader') || $config->get('classmap-authoritative');
  4060. $install
  4061. ->setDryRun($input->getOption('dry-run'))
  4062. ->setVerbose($input->getOption('verbose'))
  4063. ->setPreferSource($preferSource)
  4064. ->setPreferDist($preferDist)
  4065. ->setDevMode(!$input->getOption('no-dev'))
  4066. ->setDumpAutoloader(!$input->getOption('no-autoloader'))
  4067. ->setRunScripts(!$input->getOption('no-scripts'))
  4068. ->setOptimizeAutoloader($optimize)
  4069. ->setUpdate(true)
  4070. ->setUpdateWhitelist($input->getOption('lock') ? array('lock') : $input->getArgument('packages'))
  4071. ->setWhitelistDependencies($input->getOption('with-dependencies'))
  4072. ->setIgnorePlatformRequirements($input->getOption('ignore-platform-reqs'))
  4073. ->setPreferStable($input->getOption('prefer-stable'))
  4074. ->setPreferLowest($input->getOption('prefer-lowest'))
  4075. ;
  4076. if ($input->getOption('no-plugins')) {
  4077. $install->disablePlugins();
  4078. }
  4079. return $install->run();
  4080. }
  4081. }
  4082. <?php
  4083. namespace Composer\Command;
  4084. use Composer\Package\Loader\ValidatingArrayLoader;
  4085. use Composer\Util\ConfigValidator;
  4086. use Symfony\Component\Console\Input\InputArgument;
  4087. use Symfony\Component\Console\Input\InputInterface;
  4088. use Symfony\Component\Console\Input\InputOption;
  4089. use Symfony\Component\Console\Output\OutputInterface;
  4090. class ValidateCommand extends Command
  4091. {
  4092. protected function configure()
  4093. {
  4094. $this
  4095. ->setName('validate')
  4096. ->setDescription('Validates a composer.json')
  4097. ->setDefinition(array(
  4098. new InputOption('no-check-all', null, InputOption::VALUE_NONE, 'Do not make a complete validation'),
  4099. new InputOption('no-check-publish', null, InputOption::VALUE_NONE, 'Do not check for publish errors'),
  4100. new InputArgument('file', InputArgument::OPTIONAL, 'path to composer.json file', './composer.json')
  4101. ))
  4102. ->setHelp(<<<EOT
  4103. The validate command validates a given composer.json
  4104. EOT
  4105. );
  4106. }
  4107. protected function execute(InputInterface $input, OutputInterface $output)
  4108. {
  4109. $file = $input->getArgument('file');
  4110. if (!file_exists($file)) {
  4111. $this->getIO()->writeError('<error>' . $file . ' not found.</error>');
  4112. return 1;
  4113. }
  4114. if (!is_readable($file)) {
  4115. $this->getIO()->writeError('<error>' . $file . ' is not readable.</error>');
  4116. return 1;
  4117. }
  4118. $validator = new ConfigValidator($this->getIO());
  4119. $checkAll = $input->getOption('no-check-all') ? 0 : ValidatingArrayLoader::CHECK_ALL;
  4120. $checkPublish = !$input->getOption('no-check-publish');
  4121. list($errors, $publishErrors, $warnings) = $validator->validate($file, $checkAll);
  4122. if (!$errors && !$publishErrors && !$warnings) {
  4123. $this->getIO()->write('<info>' . $file . ' is valid</info>');
  4124. } elseif (!$errors && !$publishErrors) {
  4125. $this->getIO()->writeError('<info>' . $file . ' is valid, but with a few warnings</info>');
  4126. $this->getIO()->writeError('<warning>See http://getcomposer.org/doc/04-schema.md for details on the schema</warning>');
  4127. } elseif (!$errors) {
  4128. $this->getIO()->writeError('<info>' . $file . ' is valid for simple usage with composer but has</info>');
  4129. $this->getIO()->writeError('<info>strict errors that make it unable to be published as a package:</info>');
  4130. $this->getIO()->writeError('<warning>See http://getcomposer.org/doc/04-schema.md for details on the schema</warning>');
  4131. } else {
  4132. $this->getIO()->writeError('<error>' . $file . ' is invalid, the following errors/warnings were found:</error>');
  4133. }
  4134. $messages = array(
  4135. 'error' => $errors,
  4136. 'warning' => $warnings,
  4137. );
  4138. if ($checkPublish) {
  4139. $messages['error'] = array_merge($messages['error'], $publishErrors);
  4140. } else {
  4141. $messages['warning'] = array_merge($messages['warning'], $publishErrors);
  4142. }
  4143. foreach ($messages as $style => $msgs) {
  4144. foreach ($msgs as $msg) {
  4145. $this->getIO()->writeError('<' . $style . '>' . $msg . '</' . $style . '>');
  4146. }
  4147. }
  4148. return $errors || ($publishErrors && $checkPublish) ? 1 : 0;
  4149. }
  4150. }
  4151. <?php
  4152. namespace Composer;
  4153. use Composer\Package\RootPackageInterface;
  4154. use Composer\Package\Locker;
  4155. use Composer\Repository\RepositoryManager;
  4156. use Composer\Installer\InstallationManager;
  4157. use Composer\Plugin\PluginManager;
  4158. use Composer\Downloader\DownloadManager;
  4159. use Composer\EventDispatcher\EventDispatcher;
  4160. use Composer\Autoload\AutoloadGenerator;
  4161. class Composer
  4162. {
  4163. const VERSION = 'f87039656850828dee6d536b4d5cdb72703e9fd3';
  4164. const BRANCH_ALIAS_VERSION = '1.0-dev';
  4165. const RELEASE_DATE = '2015-04-10 21:45:24';
  4166. private $package;
  4167. private $locker;
  4168. private $repositoryManager;
  4169. private $downloadManager;
  4170. private $installationManager;
  4171. private $pluginManager;
  4172. private $config;
  4173. private $eventDispatcher;
  4174. private $autoloadGenerator;
  4175. public function setPackage(RootPackageInterface $package)
  4176. {
  4177. $this->package = $package;
  4178. }
  4179. public function getPackage()
  4180. {
  4181. return $this->package;
  4182. }
  4183. public function setConfig(Config $config)
  4184. {
  4185. $this->config = $config;
  4186. }
  4187. public function getConfig()
  4188. {
  4189. return $this->config;
  4190. }
  4191. public function setLocker(Locker $locker)
  4192. {
  4193. $this->locker = $locker;
  4194. }
  4195. public function getLocker()
  4196. {
  4197. return $this->locker;
  4198. }
  4199. public function setRepositoryManager(RepositoryManager $manager)
  4200. {
  4201. $this->repositoryManager = $manager;
  4202. }
  4203. public function getRepositoryManager()
  4204. {
  4205. return $this->repositoryManager;
  4206. }
  4207. public function setDownloadManager(DownloadManager $manager)
  4208. {
  4209. $this->downloadManager = $manager;
  4210. }
  4211. public function getDownloadManager()
  4212. {
  4213. return $this->downloadManager;
  4214. }
  4215. public function setInstallationManager(InstallationManager $manager)
  4216. {
  4217. $this->installationManager = $manager;
  4218. }
  4219. public function getInstallationManager()
  4220. {
  4221. return $this->installationManager;
  4222. }
  4223. public function setPluginManager(PluginManager $manager)
  4224. {
  4225. $this->pluginManager = $manager;
  4226. }
  4227. public function getPluginManager()
  4228. {
  4229. return $this->pluginManager;
  4230. }
  4231. public function setEventDispatcher(EventDispatcher $eventDispatcher)
  4232. {
  4233. $this->eventDispatcher = $eventDispatcher;
  4234. }
  4235. public function getEventDispatcher()
  4236. {
  4237. return $this->eventDispatcher;
  4238. }
  4239. public function setAutoloadGenerator(AutoloadGenerator $autoloadGenerator)
  4240. {
  4241. $this->autoloadGenerator = $autoloadGenerator;
  4242. }
  4243. public function getAutoloadGenerator()
  4244. {
  4245. return $this->autoloadGenerator;
  4246. }
  4247. }
  4248. <?php
  4249. namespace Composer\Config;
  4250. interface ConfigSourceInterface
  4251. {
  4252. public function addRepository($name, $config);
  4253. public function removeRepository($name);
  4254. public function addConfigSetting($name, $value);
  4255. public function removeConfigSetting($name);
  4256. public function addLink($type, $name, $value);
  4257. public function removeLink($type, $name);
  4258. public function getName();
  4259. }
  4260. <?php
  4261. namespace Composer\Config;
  4262. use Composer\Json\JsonFile;
  4263. use Composer\Json\JsonManipulator;
  4264. class JsonConfigSource implements ConfigSourceInterface
  4265. {
  4266. private $file;
  4267. private $authConfig;
  4268. public function __construct(JsonFile $file, $authConfig = false)
  4269. {
  4270. $this->file = $file;
  4271. $this->authConfig = $authConfig;
  4272. }
  4273. public function getName()
  4274. {
  4275. return $this->file->getPath();
  4276. }
  4277. public function addRepository($name, $config)
  4278. {
  4279. $this->manipulateJson('addRepository', $name, $config, function (&$config, $repo, $repoConfig) {
  4280. $config['repositories'][$repo] = $repoConfig;
  4281. });
  4282. }
  4283. public function removeRepository($name)
  4284. {
  4285. $this->manipulateJson('removeRepository', $name, function (&$config, $repo) {
  4286. unset($config['repositories'][$repo]);
  4287. });
  4288. }
  4289. public function addConfigSetting($name, $value)
  4290. {
  4291. $this->manipulateJson('addConfigSetting', $name, $value, function (&$config, $key, $val) {
  4292. if ($key === 'github-oauth' || $key === 'http-basic') {
  4293. list($key, $host) = explode('.', $key, 2);
  4294. if ($this->authConfig) {
  4295. $config[$key][$host] = $val;
  4296. } else {
  4297. $config['config'][$key][$host] = $val;
  4298. }
  4299. } else {
  4300. $config['config'][$key] = $val;
  4301. }
  4302. });
  4303. }
  4304. public function removeConfigSetting($name)
  4305. {
  4306. $this->manipulateJson('removeConfigSetting', $name, function (&$config, $key) {
  4307. if ($key === 'github-oauth' || $key === 'http-basic') {
  4308. list($key, $host) = explode('.', $key, 2);
  4309. if ($this->authConfig) {
  4310. unset($config[$key][$host]);
  4311. } else {
  4312. unset($config['config'][$key][$host]);
  4313. }
  4314. } else {
  4315. unset($config['config'][$key]);
  4316. }
  4317. });
  4318. }
  4319. public function addLink($type, $name, $value)
  4320. {
  4321. $this->manipulateJson('addLink', $type, $name, $value, function (&$config, $type, $name, $value) {
  4322. $config[$type][$name] = $value;
  4323. });
  4324. }
  4325. public function removeLink($type, $name)
  4326. {
  4327. $this->manipulateJson('removeSubNode', $type, $name, function (&$config, $type, $name) {
  4328. unset($config[$type][$name]);
  4329. });
  4330. }
  4331. protected function manipulateJson($method, $args, $fallback)
  4332. {
  4333. $args = func_get_args();
  4334. array_shift($args);
  4335. $fallback = array_pop($args);
  4336. if ($this->file->exists()) {
  4337. $contents = file_get_contents($this->file->getPath());
  4338. } elseif ($this->authConfig) {
  4339. $contents = "{\n}\n";
  4340. } else {
  4341. $contents = "{\n \"config\": {\n }\n}\n";
  4342. }
  4343. $manipulator = new JsonManipulator($contents);
  4344. $newFile = !$this->file->exists();
  4345. if ($this->authConfig && $method === 'addConfigSetting') {
  4346. $method = 'addSubNode';
  4347. list($mainNode, $name) = explode('.', $args[0], 2);
  4348. $args = array($mainNode, $name, $args[1]);
  4349. } elseif ($this->authConfig && $method === 'removeConfigSetting') {
  4350. $method = 'removeSubNode';
  4351. list($mainNode, $name) = explode('.', $args[0], 2);
  4352. $args = array($mainNode, $name);
  4353. }
  4354. if (call_user_func_array(array($manipulator, $method), $args)) {
  4355. file_put_contents($this->file->getPath(), $manipulator->getContents());
  4356. } else {
  4357. $config = $this->file->read();
  4358. $this->arrayUnshiftRef($args, $config);
  4359. call_user_func_array($fallback, $args);
  4360. $this->file->write($config);
  4361. }
  4362. if ($newFile) {
  4363. @chmod($this->file->getPath(), 0600);
  4364. }
  4365. }
  4366. private function arrayUnshiftRef(&$array, &$value)
  4367. {
  4368. $return = array_unshift($array, '');
  4369. $array[0] = &$value;
  4370. return $return;
  4371. }
  4372. }
  4373. <?php
  4374. namespace Composer;
  4375. use Composer\Config\ConfigSourceInterface;
  4376. class Config
  4377. {
  4378. const RELATIVE_PATHS = 1;
  4379. public static $defaultConfig = array(
  4380. 'process-timeout' => 300,
  4381. 'use-include-path' => false,
  4382. 'preferred-install' => 'auto',
  4383. 'notify-on-install' => true,
  4384. 'github-protocols' => array('git', 'https', 'ssh'),
  4385. 'vendor-dir' => 'vendor',
  4386. 'bin-dir' => '{$vendor-dir}/bin',
  4387. 'cache-dir' => '{$home}/cache',
  4388. 'cache-files-dir' => '{$cache-dir}/files',
  4389. 'cache-repo-dir' => '{$cache-dir}/repo',
  4390. 'cache-vcs-dir' => '{$cache-dir}/vcs',
  4391. 'cache-ttl' => 15552000,
  4392. 'cache-files-ttl' => null,
  4393. 'cache-files-maxsize' => '300MiB',
  4394. 'discard-changes' => false,
  4395. 'autoloader-suffix' => null,
  4396. 'optimize-autoloader' => false,
  4397. 'classmap-authoritative' => false,
  4398. 'prepend-autoloader' => true,
  4399. 'github-domains' => array('github.com'),
  4400. 'github-expose-hostname' => true,
  4401. 'gitlab-domains' => array('gitlab.com'),
  4402. 'store-auths' => 'prompt',
  4403. );
  4404. public static $defaultRepositories = array(
  4405. 'packagist' => array(
  4406. 'type' => 'composer',
  4407. 'url' => 'https?://packagist.org',
  4408. 'allow_ssl_downgrade' => true,
  4409. )
  4410. );
  4411. private $config;
  4412. private $baseDir;
  4413. private $repositories;
  4414. private $configSource;
  4415. private $authConfigSource;
  4416. private $useEnvironment;
  4417. public function __construct($useEnvironment = true, $baseDir = null)
  4418. {
  4419. $this->config = static::$defaultConfig;
  4420. $this->repositories = static::$defaultRepositories;
  4421. $this->useEnvironment = (bool) $useEnvironment;
  4422. $this->baseDir = $baseDir;
  4423. }
  4424. public function setConfigSource(ConfigSourceInterface $source)
  4425. {
  4426. $this->configSource = $source;
  4427. }
  4428. public function getConfigSource()
  4429. {
  4430. return $this->configSource;
  4431. }
  4432. public function setAuthConfigSource(ConfigSourceInterface $source)
  4433. {
  4434. $this->authConfigSource = $source;
  4435. }
  4436. public function getAuthConfigSource()
  4437. {
  4438. return $this->authConfigSource;
  4439. }
  4440. public function merge($config)
  4441. {
  4442. if (!empty($config['config']) && is_array($config['config'])) {
  4443. foreach ($config['config'] as $key => $val) {
  4444. if (in_array($key, array('github-oauth', 'http-basic')) && isset($this->config[$key])) {
  4445. $this->config[$key] = array_merge($this->config[$key], $val);
  4446. } else {
  4447. $this->config[$key] = $val;
  4448. }
  4449. }
  4450. }
  4451. if (!empty($config['repositories']) && is_array($config['repositories'])) {
  4452. $this->repositories = array_reverse($this->repositories, true);
  4453. $newRepos = array_reverse($config['repositories'], true);
  4454. foreach ($newRepos as $name => $repository) {
  4455. if (false === $repository) {
  4456. unset($this->repositories[$name]);
  4457. continue;
  4458. }
  4459. if (is_array($repository) && 1 === count($repository) && false === current($repository)) {
  4460. unset($this->repositories[key($repository)]);
  4461. continue;
  4462. }
  4463. if (is_int($name)) {
  4464. $this->repositories[] = $repository;
  4465. } else {
  4466. $this->repositories[$name] = $repository;
  4467. }
  4468. }
  4469. $this->repositories = array_reverse($this->repositories, true);
  4470. }
  4471. }
  4472. public function getRepositories()
  4473. {
  4474. return $this->repositories;
  4475. }
  4476. public function get($key, $flags = 0)
  4477. {
  4478. switch ($key) {
  4479. case 'vendor-dir':
  4480. case 'bin-dir':
  4481. case 'process-timeout':
  4482. case 'cache-dir':
  4483. case 'cache-files-dir':
  4484. case 'cache-repo-dir':
  4485. case 'cache-vcs-dir':
  4486. $env = 'COMPOSER_' . strtoupper(strtr($key, '-', '_'));
  4487. $val = rtrim($this->process($this->getComposerEnv($env) ?: $this->config[$key], $flags), '/\\');
  4488. $val = preg_replace('#^(\$HOME|~)(/|$)#', rtrim(getenv('HOME') ?: getenv('USERPROFILE'), '/\\') . '/', $val);
  4489. if (substr($key, -4) !== '-dir') {
  4490. return $val;
  4491. }
  4492. return ($flags & self::RELATIVE_PATHS == 1) ? $val : $this->realpath($val);
  4493. case 'cache-ttl':
  4494. return (int) $this->config[$key];
  4495. case 'cache-files-maxsize':
  4496. if (!preg_match('/^\s*([0-9.]+)\s*(?:([kmg])(?:i?b)?)?\s*$/i', $this->config[$key], $matches)) {
  4497. throw new \RuntimeException(
  4498. "Could not parse the value of 'cache-files-maxsize': {$this->config[$key]}"
  4499. );
  4500. }
  4501. $size = $matches[1];
  4502. if (isset($matches[2])) {
  4503. switch (strtolower($matches[2])) {
  4504. case 'g':
  4505. $size *= 1024;
  4506. case 'm':
  4507. $size *= 1024;
  4508. case 'k':
  4509. $size *= 1024;
  4510. break;
  4511. }
  4512. }
  4513. return $size;
  4514. case 'cache-files-ttl':
  4515. if (isset($this->config[$key])) {
  4516. return (int) $this->config[$key];
  4517. }
  4518. return (int) $this->config['cache-ttl'];
  4519. case 'home':
  4520. return rtrim($this->process($this->config[$key], $flags), '/\\');
  4521. case 'discard-changes':
  4522. if ($env = $this->getComposerEnv('COMPOSER_DISCARD_CHANGES')) {
  4523. if (!in_array($env, array('stash', 'true', 'false', '1', '0'), true)) {
  4524. throw new \RuntimeException(
  4525. "Invalid value for COMPOSER_DISCARD_CHANGES: {$env}. Expected 1, 0, true, false or stash"
  4526. );
  4527. }
  4528. if ('stash' === $env) {
  4529. return 'stash';
  4530. }
  4531. return $env !== 'false' && (bool) $env;
  4532. }
  4533. if (!in_array($this->config[$key], array(true, false, 'stash'), true)) {
  4534. throw new \RuntimeException(
  4535. "Invalid value for 'discard-changes': {$this->config[$key]}. Expected true, false or stash"
  4536. );
  4537. }
  4538. return $this->config[$key];
  4539. case 'github-protocols':
  4540. if (reset($this->config['github-protocols']) === 'http') {
  4541. throw new \RuntimeException('The http protocol for github is not available anymore, update your config\'s github-protocols to use "https", "git" or "ssh"');
  4542. }
  4543. return $this->config[$key];
  4544. default:
  4545. if (!isset($this->config[$key])) {
  4546. return null;
  4547. }
  4548. return $this->process($this->config[$key], $flags);
  4549. }
  4550. }
  4551. public function all($flags = 0)
  4552. {
  4553. $all = array(
  4554. 'repositories' => $this->getRepositories(),
  4555. );
  4556. foreach (array_keys($this->config) as $key) {
  4557. $all['config'][$key] = $this->get($key, $flags);
  4558. }
  4559. return $all;
  4560. }
  4561. public function raw()
  4562. {
  4563. return array(
  4564. 'repositories' => $this->getRepositories(),
  4565. 'config' => $this->config,
  4566. );
  4567. }
  4568. public function has($key)
  4569. {
  4570. return array_key_exists($key, $this->config);
  4571. }
  4572. private function process($value, $flags)
  4573. {
  4574. $config = $this;
  4575. if (!is_string($value)) {
  4576. return $value;
  4577. }
  4578. return preg_replace_callback('#\{\$(.+)\}#', function ($match) use ($config, $flags) {
  4579. return $config->get($match[1], $flags);
  4580. }, $value);
  4581. }
  4582. private function realpath($path)
  4583. {
  4584. if (substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':') {
  4585. return $path;
  4586. }
  4587. return $this->baseDir . '/' . $path;
  4588. }
  4589. private function getComposerEnv($var)
  4590. {
  4591. if ($this->useEnvironment) {
  4592. return getenv($var);
  4593. }
  4594. return false;
  4595. }
  4596. }
  4597. <?php
  4598. namespace Composer\Console;
  4599. use Symfony\Component\Console\Application as BaseApplication;
  4600. use Symfony\Component\Console\Input\InputInterface;
  4601. use Symfony\Component\Console\Input\InputOption;
  4602. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  4603. use Symfony\Component\Console\Output\OutputInterface;
  4604. use Symfony\Component\Console\Output\ConsoleOutput;
  4605. use Symfony\Component\Console\Formatter\OutputFormatter;
  4606. use Composer\Command;
  4607. use Composer\Command\Helper\DialogHelper;
  4608. use Composer\Composer;
  4609. use Composer\Factory;
  4610. use Composer\IO\IOInterface;
  4611. use Composer\IO\ConsoleIO;
  4612. use Composer\Json\JsonValidationException;
  4613. use Composer\Util\ErrorHandler;
  4614. class Application extends BaseApplication
  4615. {
  4616. protected $composer;
  4617. protected $io;
  4618. private static $logo = ' ______
  4619. / ____/___ ____ ___ ____ ____ ________ _____
  4620. / / / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
  4621. / /___/ /_/ / / / / / / /_/ / /_/ (__ ) __/ /
  4622. \____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
  4623. /_/
  4624. ';
  4625. public function __construct()
  4626. {
  4627. if (function_exists('ini_set') && extension_loaded('xdebug')) {
  4628. ini_set('xdebug.show_exception_trace', false);
  4629. ini_set('xdebug.scream', false);
  4630. }
  4631. if (function_exists('date_default_timezone_set') && function_exists('date_default_timezone_get')) {
  4632. date_default_timezone_set(@date_default_timezone_get());
  4633. }
  4634. ErrorHandler::register();
  4635. parent::__construct('Composer', Composer::VERSION);
  4636. }
  4637. public function run(InputInterface $input = null, OutputInterface $output = null)
  4638. {
  4639. if (null === $output) {
  4640. $styles = Factory::createAdditionalStyles();
  4641. $formatter = new OutputFormatter(null, $styles);
  4642. $output = new ConsoleOutput(ConsoleOutput::VERBOSITY_NORMAL, null, $formatter);
  4643. }
  4644. return parent::run($input, $output);
  4645. }
  4646. public function doRun(InputInterface $input, OutputInterface $output)
  4647. {
  4648. $this->io = new ConsoleIO($input, $output, $this->getHelperSet());
  4649. if (version_compare(PHP_VERSION, '5.3.2', '<')) {
  4650. $this->getIO()->writeError('<warning>Composer only officially supports PHP 5.3.2 and above, you will most likely encounter problems with your PHP '.PHP_VERSION.', upgrading is strongly recommended.</warning>');
  4651. }
  4652. if (defined('COMPOSER_DEV_WARNING_TIME')) {
  4653. $commandName = '';
  4654. if ($name = $this->getCommandName($input)) {
  4655. try {
  4656. $commandName = $this->find($name)->getName();
  4657. } catch (\InvalidArgumentException $e) {
  4658. }
  4659. }
  4660. if ($commandName !== 'self-update' && $commandName !== 'selfupdate') {
  4661. if (time() > COMPOSER_DEV_WARNING_TIME) {
  4662. $this->getIO()->writeError(sprintf('<warning>Warning: This development build of composer is over 30 days old. It is recommended to update it by running "%s self-update" to get the latest version.</warning>', $_SERVER['PHP_SELF']));
  4663. }
  4664. }
  4665. }
  4666. if (getenv('COMPOSER_NO_INTERACTION')) {
  4667. $input->setInteractive(false);
  4668. }
  4669. if ($newWorkDir = $this->getNewWorkingDir($input)) {
  4670. $oldWorkingDir = getcwd();
  4671. chdir($newWorkDir);
  4672. if ($this->getIO()->isDebug() >= 4) {
  4673. $this->getIO()->writeError('Changed CWD to ' . getcwd());
  4674. }
  4675. }
  4676. $file = Factory::getComposerFile();
  4677. if (is_file($file) && is_readable($file) && is_array($composer = json_decode(file_get_contents($file), true))) {
  4678. if (isset($composer['scripts']) && is_array($composer['scripts'])) {
  4679. foreach ($composer['scripts'] as $script => $dummy) {
  4680. if (!defined('Composer\Script\ScriptEvents::'.str_replace('-', '_', strtoupper($script)))) {
  4681. if ($this->has($script)) {
  4682. $this->getIO()->writeError('<warning>A script named '.$script.' would override a native Composer function and has been skipped</warning>');
  4683. } else {
  4684. $this->add(new Command\ScriptAliasCommand($script));
  4685. }
  4686. }
  4687. }
  4688. }
  4689. }
  4690. if ($input->hasParameterOption('--profile')) {
  4691. $startTime = microtime(true);
  4692. $this->io->enableDebugging($startTime);
  4693. }
  4694. $result = parent::doRun($input, $output);
  4695. if (isset($oldWorkingDir)) {
  4696. chdir($oldWorkingDir);
  4697. }
  4698. if (isset($startTime)) {
  4699. $this->getIO()->writeError('<info>Memory usage: '.round(memory_get_usage() / 1024 / 1024, 2).'MB (peak: '.round(memory_get_peak_usage() / 1024 / 1024, 2).'MB), time: '.round(microtime(true) - $startTime, 2).'s');
  4700. }
  4701. return $result;
  4702. }
  4703. private function getNewWorkingDir(InputInterface $input)
  4704. {
  4705. $workingDir = $input->getParameterOption(array('--working-dir', '-d'));
  4706. if (false !== $workingDir && !is_dir($workingDir)) {
  4707. throw new \RuntimeException('Invalid working directory specified.');
  4708. }
  4709. return $workingDir;
  4710. }
  4711. public function renderException($exception, $output)
  4712. {
  4713. try {
  4714. $composer = $this->getComposer(false, true);
  4715. if ($composer) {
  4716. $config = $composer->getConfig();
  4717. $minSpaceFree = 1024*1024;
  4718. if ((($df = @disk_free_space($dir = $config->get('home'))) !== false && $df < $minSpaceFree)
  4719. || (($df = @disk_free_space($dir = $config->get('vendor-dir'))) !== false && $df < $minSpaceFree)
  4720. || (($df = @disk_free_space($dir = sys_get_temp_dir())) !== false && $df < $minSpaceFree)
  4721. ) {
  4722. $this->getIO()->writeError('<error>The disk hosting '.$dir.' is full, this may be the cause of the following exception</error>');
  4723. }
  4724. }
  4725. } catch (\Exception $e) {
  4726. }
  4727. if (defined('PHP_WINDOWS_VERSION_BUILD') && false !== strpos($exception->getMessage(), 'The system cannot find the path specified')) {
  4728. $this->getIO()->writeError('<error>The following exception may be caused by a stale entry in your cmd.exe AutoRun</error>');
  4729. $this->getIO()->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#-the-system-cannot-find-the-path-specified-windows- for details</error>');
  4730. }
  4731. if (false !== strpos($exception->getMessage(), 'fork failed - Cannot allocate memory')) {
  4732. $this->getIO()->writeError('<error>The following exception is caused by a lack of memory and not having swap configured</error>');
  4733. $this->getIO()->writeError('<error>Check https://getcomposer.org/doc/articles/troubleshooting.md#proc-open-fork-failed-errors for details</error>');
  4734. }
  4735. if ($output instanceof ConsoleOutputInterface) {
  4736. parent::renderException($exception, $output->getErrorOutput());
  4737. } else {
  4738. parent::renderException($exception, $output);
  4739. }
  4740. }
  4741. public function getComposer($required = true, $disablePlugins = false)
  4742. {
  4743. if (null === $this->composer) {
  4744. try {
  4745. $this->composer = Factory::create($this->io, null, $disablePlugins);
  4746. } catch (\InvalidArgumentException $e) {
  4747. if ($required) {
  4748. $this->io->writeError($e->getMessage());
  4749. exit(1);
  4750. }
  4751. } catch (JsonValidationException $e) {
  4752. $errors = ' - ' . implode(PHP_EOL . ' - ', $e->getErrors());
  4753. $message = $e->getMessage() . ':' . PHP_EOL . $errors;
  4754. throw new JsonValidationException($message);
  4755. }
  4756. }
  4757. return $this->composer;
  4758. }
  4759. public function resetComposer()
  4760. {
  4761. $this->composer = null;
  4762. }
  4763. public function getIO()
  4764. {
  4765. return $this->io;
  4766. }
  4767. public function getHelp()
  4768. {
  4769. return self::$logo . parent::getHelp();
  4770. }
  4771. protected function getDefaultCommands()
  4772. {
  4773. $commands = parent::getDefaultCommands();
  4774. $commands[] = new Command\AboutCommand();
  4775. $commands[] = new Command\ConfigCommand();
  4776. $commands[] = new Command\DependsCommand();
  4777. $commands[] = new Command\InitCommand();
  4778. $commands[] = new Command\InstallCommand();
  4779. $commands[] = new Command\CreateProjectCommand();
  4780. $commands[] = new Command\UpdateCommand();
  4781. $commands[] = new Command\SearchCommand();
  4782. $commands[] = new Command\ValidateCommand();
  4783. $commands[] = new Command\ShowCommand();
  4784. $commands[] = new Command\RequireCommand();
  4785. $commands[] = new Command\DumpAutoloadCommand();
  4786. $commands[] = new Command\StatusCommand();
  4787. $commands[] = new Command\ArchiveCommand();
  4788. $commands[] = new Command\DiagnoseCommand();
  4789. $commands[] = new Command\RunScriptCommand();
  4790. $commands[] = new Command\LicensesCommand();
  4791. $commands[] = new Command\GlobalCommand();
  4792. $commands[] = new Command\ClearCacheCommand();
  4793. $commands[] = new Command\RemoveCommand();
  4794. $commands[] = new Command\HomeCommand();
  4795. if ('phar:' === substr(__FILE__, 0, 5)) {
  4796. $commands[] = new Command\SelfUpdateCommand();
  4797. }
  4798. return $commands;
  4799. }
  4800. public function getLongVersion()
  4801. {
  4802. if (Composer::BRANCH_ALIAS_VERSION) {
  4803. return sprintf(
  4804. '<info>%s</info> version <comment>%s (%s)</comment> %s',
  4805. $this->getName(),
  4806. Composer::BRANCH_ALIAS_VERSION,
  4807. $this->getVersion(),
  4808. Composer::RELEASE_DATE
  4809. );
  4810. }
  4811. return parent::getLongVersion() . ' ' . Composer::RELEASE_DATE;
  4812. }
  4813. protected function getDefaultInputDefinition()
  4814. {
  4815. $definition = parent::getDefaultInputDefinition();
  4816. $definition->addOption(new InputOption('--profile', null, InputOption::VALUE_NONE, 'Display timing and memory usage information'));
  4817. $definition->addOption(new InputOption('--working-dir', '-d', InputOption::VALUE_REQUIRED, 'If specified, use the given directory as working directory.'));
  4818. return $definition;
  4819. }
  4820. protected function getDefaultHelperSet()
  4821. {
  4822. $helperSet = parent::getDefaultHelperSet();
  4823. $helperSet->set(new DialogHelper());
  4824. return $helperSet;
  4825. }
  4826. }
  4827. <?php
  4828. namespace Composer\Console;
  4829. use Symfony\Component\Console\Formatter\OutputFormatter;
  4830. class HtmlOutputFormatter extends OutputFormatter
  4831. {
  4832. private static $availableForegroundColors = array(
  4833. 30 => 'black',
  4834. 31 => 'red',
  4835. 32 => 'green',
  4836. 33 => 'yellow',
  4837. 34 => 'blue',
  4838. 35 => 'magenta',
  4839. 36 => 'cyan',
  4840. 37 => 'white'
  4841. );
  4842. private static $availableBackgroundColors = array(
  4843. 40 => 'black',
  4844. 41 => 'red',
  4845. 42 => 'green',
  4846. 43 => 'yellow',
  4847. 44 => 'blue',
  4848. 45 => 'magenta',
  4849. 46 => 'cyan',
  4850. 47 => 'white'
  4851. );
  4852. private static $availableOptions = array(
  4853. 1 => 'bold',
  4854. 4 => 'underscore',
  4855. );
  4856. public function __construct(array $styles = array())
  4857. {
  4858. parent::__construct(true, $styles);
  4859. }
  4860. public function format($message)
  4861. {
  4862. $formatted = parent::format($message);
  4863. return preg_replace_callback("{\033\[([0-9;]+)m(.*?)\033\[0m}s", array($this, 'formatHtml'), $formatted);
  4864. }
  4865. private function formatHtml($matches)
  4866. {
  4867. $out = '<span style="';
  4868. foreach (explode(';', $matches[1]) as $code) {
  4869. if (isset(self::$availableForegroundColors[$code])) {
  4870. $out .= 'color:'.self::$availableForegroundColors[$code].';';
  4871. } elseif (isset(self::$availableBackgroundColors[$code])) {
  4872. $out .= 'background-color:'.self::$availableBackgroundColors[$code].';';
  4873. } elseif (isset(self::$availableOptions[$code])) {
  4874. switch (self::$availableOptions[$code]) {
  4875. case 'bold':
  4876. $out .= 'font-weight:bold;';
  4877. break;
  4878. case 'underscore':
  4879. $out .= 'text-decoration:underline;';
  4880. break;
  4881. }
  4882. }
  4883. }
  4884. return $out.'">'.$matches[2].'</span>';
  4885. }
  4886. }
  4887. <?php
  4888. namespace Composer\DependencyResolver;
  4889. class DebugSolver extends Solver
  4890. {
  4891. protected function printDecisionMap()
  4892. {
  4893. echo "\nDecisionMap: \n";
  4894. foreach ($this->decisionMap as $packageId => $level) {
  4895. if ($packageId === 0) {
  4896. continue;
  4897. }
  4898. if ($level > 0) {
  4899. echo ' +' . $this->pool->packageById($packageId)."\n";
  4900. } elseif ($level < 0) {
  4901. echo ' -' . $this->pool->packageById($packageId)."\n";
  4902. } else {
  4903. echo ' ?' . $this->pool->packageById($packageId)."\n";
  4904. }
  4905. }
  4906. echo "\n";
  4907. }
  4908. protected function printDecisionQueue()
  4909. {
  4910. echo "DecisionQueue: \n";
  4911. foreach ($this->decisionQueue as $i => $literal) {
  4912. echo ' ' . $this->pool->literalToString($literal) . ' ' . $this->decisionQueueWhy[$i]." level ".$this->decisionMap[abs($literal)]."\n";
  4913. }
  4914. echo "\n";
  4915. }
  4916. protected function printWatches()
  4917. {
  4918. echo "\nWatches:\n";
  4919. foreach ($this->watches as $literalId => $watch) {
  4920. echo ' '.$this->literalFromId($literalId)."\n";
  4921. $queue = array(array(' ', $watch));
  4922. while (!empty($queue)) {
  4923. list($indent, $watch) = array_pop($queue);
  4924. echo $indent.$watch;
  4925. if ($watch) {
  4926. echo ' [id='.$watch->getId().',watch1='.$this->literalFromId($watch->watch1).',watch2='.$this->literalFromId($watch->watch2)."]";
  4927. }
  4928. echo "\n";
  4929. if ($watch && ($watch->next1 == $watch || $watch->next2 == $watch)) {
  4930. if ($watch->next1 == $watch) {
  4931. echo $indent." 1 *RECURSION*";
  4932. }
  4933. if ($watch->next2 == $watch) {
  4934. echo $indent." 2 *RECURSION*";
  4935. }
  4936. } elseif ($watch && ($watch->next1 || $watch->next2)) {
  4937. $indent = str_replace(array('1', '2'), ' ', $indent);
  4938. array_push($queue, array($indent.' 2 ', $watch->next2));
  4939. array_push($queue, array($indent.' 1 ', $watch->next1));
  4940. }
  4941. }
  4942. echo "\n";
  4943. }
  4944. }
  4945. }
  4946. <?php
  4947. namespace Composer\DependencyResolver;
  4948. class Decisions implements \Iterator, \Countable
  4949. {
  4950. const DECISION_LITERAL = 0;
  4951. const DECISION_REASON = 1;
  4952. protected $pool;
  4953. protected $decisionMap;
  4954. protected $decisionQueue = array();
  4955. public function __construct($pool)
  4956. {
  4957. $this->pool = $pool;
  4958. $this->decisionMap = array();
  4959. }
  4960. public function decide($literal, $level, $why)
  4961. {
  4962. $this->addDecision($literal, $level);
  4963. $this->decisionQueue[] = array(
  4964. self::DECISION_LITERAL => $literal,
  4965. self::DECISION_REASON => $why,
  4966. );
  4967. }
  4968. public function satisfy($literal)
  4969. {
  4970. $packageId = abs($literal);
  4971. return (
  4972. $literal > 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 ||
  4973. $literal < 0 && isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0
  4974. );
  4975. }
  4976. public function conflict($literal)
  4977. {
  4978. $packageId = abs($literal);
  4979. return (
  4980. (isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0 && $literal < 0) ||
  4981. (isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] < 0 && $literal > 0)
  4982. );
  4983. }
  4984. public function decided($literalOrPackageId)
  4985. {
  4986. return !empty($this->decisionMap[abs($literalOrPackageId)]);
  4987. }
  4988. public function undecided($literalOrPackageId)
  4989. {
  4990. return empty($this->decisionMap[abs($literalOrPackageId)]);
  4991. }
  4992. public function decidedInstall($literalOrPackageId)
  4993. {
  4994. $packageId = abs($literalOrPackageId);
  4995. return isset($this->decisionMap[$packageId]) && $this->decisionMap[$packageId] > 0;
  4996. }
  4997. public function decisionLevel($literalOrPackageId)
  4998. {
  4999. $packageId = abs($literalOrPackageId);
  5000. if (isset($this->decisionMap[$packageId])) {
  5001. return abs($this->decisionMap[$packageId]);
  5002. }
  5003. return 0;
  5004. }
  5005. public function decisionRule($literalOrPackageId)
  5006. {
  5007. $packageId = abs($literalOrPackageId);
  5008. foreach ($this->decisionQueue as $i => $decision) {
  5009. if ($packageId === abs($decision[self::DECISION_LITERAL])) {
  5010. return $decision[self::DECISION_REASON];
  5011. }
  5012. }
  5013. return null;
  5014. }
  5015. public function atOffset($queueOffset)
  5016. {
  5017. return $this->decisionQueue[$queueOffset];
  5018. }
  5019. public function validOffset($queueOffset)
  5020. {
  5021. return $queueOffset >= 0 && $queueOffset < count($this->decisionQueue);
  5022. }
  5023. public function lastReason()
  5024. {
  5025. return $this->decisionQueue[count($this->decisionQueue) - 1][self::DECISION_REASON];
  5026. }
  5027. public function lastLiteral()
  5028. {
  5029. return $this->decisionQueue[count($this->decisionQueue) - 1][self::DECISION_LITERAL];
  5030. }
  5031. public function reset()
  5032. {
  5033. while ($decision = array_pop($this->decisionQueue)) {
  5034. $this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0;
  5035. }
  5036. }
  5037. public function resetToOffset($offset)
  5038. {
  5039. while (count($this->decisionQueue) > $offset + 1) {
  5040. $decision = array_pop($this->decisionQueue);
  5041. $this->decisionMap[abs($decision[self::DECISION_LITERAL])] = 0;
  5042. }
  5043. }
  5044. public function revertLast()
  5045. {
  5046. $this->decisionMap[abs($this->lastLiteral())] = 0;
  5047. array_pop($this->decisionQueue);
  5048. }
  5049. public function count()
  5050. {
  5051. return count($this->decisionQueue);
  5052. }
  5053. public function rewind()
  5054. {
  5055. end($this->decisionQueue);
  5056. }
  5057. public function current()
  5058. {
  5059. return current($this->decisionQueue);
  5060. }
  5061. public function key()
  5062. {
  5063. return key($this->decisionQueue);
  5064. }
  5065. public function next()
  5066. {
  5067. return prev($this->decisionQueue);
  5068. }
  5069. public function valid()
  5070. {
  5071. return false !== current($this->decisionQueue);
  5072. }
  5073. public function isEmpty()
  5074. {
  5075. return count($this->decisionQueue) === 0;
  5076. }
  5077. protected function addDecision($literal, $level)
  5078. {
  5079. $packageId = abs($literal);
  5080. $previousDecision = isset($this->decisionMap[$packageId]) ? $this->decisionMap[$packageId] : null;
  5081. if ($previousDecision != 0) {
  5082. $literalString = $this->pool->literalToString($literal);
  5083. $package = $this->pool->literalToPackage($literal);
  5084. throw new SolverBugException(
  5085. "Trying to decide $literalString on level $level, even though $package was previously decided as ".(int) $previousDecision."."
  5086. );
  5087. }
  5088. if ($literal > 0) {
  5089. $this->decisionMap[$packageId] = $level;
  5090. } else {
  5091. $this->decisionMap[$packageId] = -$level;
  5092. }
  5093. }
  5094. }
  5095. <?php
  5096. namespace Composer\DependencyResolver;
  5097. use Composer\Package\PackageInterface;
  5098. use Composer\Package\AliasPackage;
  5099. use Composer\Package\BasePackage;
  5100. use Composer\Package\LinkConstraint\VersionConstraint;
  5101. class DefaultPolicy implements PolicyInterface
  5102. {
  5103. private $preferStable;
  5104. private $preferLowest;
  5105. public function __construct($preferStable = false, $preferLowest = false)
  5106. {
  5107. $this->preferStable = $preferStable;
  5108. $this->preferLowest = $preferLowest;
  5109. }
  5110. public function versionCompare(PackageInterface $a, PackageInterface $b, $operator)
  5111. {
  5112. if ($this->preferStable && ($stabA = $a->getStability()) !== ($stabB = $b->getStability())) {
  5113. return BasePackage::$stabilities[$stabA] < BasePackage::$stabilities[$stabB];
  5114. }
  5115. $constraint = new VersionConstraint($operator, $b->getVersion());
  5116. $version = new VersionConstraint('==', $a->getVersion());
  5117. return $constraint->matchSpecific($version, true);
  5118. }
  5119. public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package, $mustMatchName = false)
  5120. {
  5121. $packages = array();
  5122. foreach ($pool->whatProvides($package->getName(), null, $mustMatchName) as $candidate) {
  5123. if ($candidate !== $package) {
  5124. $packages[] = $candidate;
  5125. }
  5126. }
  5127. return $packages;
  5128. }
  5129. public function getPriority(Pool $pool, PackageInterface $package)
  5130. {
  5131. return $pool->getPriority($package->getRepository());
  5132. }
  5133. public function selectPreferedPackages(Pool $pool, array $installedMap, array $literals, $requiredPackage = null)
  5134. {
  5135. $packages = $this->groupLiteralsByNamePreferInstalled($pool, $installedMap, $literals);
  5136. foreach ($packages as &$literals) {
  5137. $policy = $this;
  5138. usort($literals, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) {
  5139. return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage, true);
  5140. });
  5141. }
  5142. foreach ($packages as &$literals) {
  5143. $literals = $this->pruneToBestVersion($pool, $literals);
  5144. $literals = $this->pruneToHighestPriorityOrInstalled($pool, $installedMap, $literals);
  5145. $literals = $this->pruneRemoteAliases($pool, $literals);
  5146. }
  5147. $selected = call_user_func_array('array_merge', $packages);
  5148. usort($selected, function ($a, $b) use ($policy, $pool, $installedMap, $requiredPackage) {
  5149. return $policy->compareByPriorityPreferInstalled($pool, $installedMap, $pool->literalToPackage($a), $pool->literalToPackage($b), $requiredPackage);
  5150. });
  5151. return $selected;
  5152. }
  5153. protected function groupLiteralsByNamePreferInstalled(Pool $pool, array $installedMap, $literals)
  5154. {
  5155. $packages = array();
  5156. foreach ($literals as $literal) {
  5157. $packageName = $pool->literalToPackage($literal)->getName();
  5158. if (!isset($packages[$packageName])) {
  5159. $packages[$packageName] = array();
  5160. }
  5161. if (isset($installedMap[abs($literal)])) {
  5162. array_unshift($packages[$packageName], $literal);
  5163. } else {
  5164. $packages[$packageName][] = $literal;
  5165. }
  5166. }
  5167. return $packages;
  5168. }
  5169. public function compareByPriorityPreferInstalled(Pool $pool, array $installedMap, PackageInterface $a, PackageInterface $b, $requiredPackage = null, $ignoreReplace = false)
  5170. {
  5171. if ($a->getRepository() === $b->getRepository()) {
  5172. if ($a->getName() === $b->getName()) {
  5173. $aAliased = $a instanceof AliasPackage;
  5174. $bAliased = $b instanceof AliasPackage;
  5175. if ($aAliased && !$bAliased) {
  5176. return -1;
  5177. }
  5178. if (!$aAliased && $bAliased) {
  5179. return 1;
  5180. }
  5181. }
  5182. if (!$ignoreReplace) {
  5183. if ($this->replaces($a, $b)) {
  5184. return 1;
  5185. }
  5186. if ($this->replaces($b, $a)) {
  5187. return -1;
  5188. }
  5189. if ($requiredPackage && false !== ($pos = strpos($requiredPackage, '/'))) {
  5190. $requiredVendor = substr($requiredPackage, 0, $pos);
  5191. $aIsSameVendor = substr($a->getName(), 0, $pos) === $requiredVendor;
  5192. $bIsSameVendor = substr($b->getName(), 0, $pos) === $requiredVendor;
  5193. if ($bIsSameVendor !== $aIsSameVendor) {
  5194. return $aIsSameVendor ? -1 : 1;
  5195. }
  5196. }
  5197. }
  5198. if ($a->id === $b->id) {
  5199. return 0;
  5200. }
  5201. return ($a->id < $b->id) ? -1 : 1;
  5202. }
  5203. if (isset($installedMap[$a->id])) {
  5204. return -1;
  5205. }
  5206. if (isset($installedMap[$b->id])) {
  5207. return 1;
  5208. }
  5209. return ($this->getPriority($pool, $a) > $this->getPriority($pool, $b)) ? -1 : 1;
  5210. }
  5211. protected function replaces(PackageInterface $source, PackageInterface $target)
  5212. {
  5213. foreach ($source->getReplaces() as $link) {
  5214. if ($link->getTarget() === $target->getName()
  5215. ) {
  5216. return true;
  5217. }
  5218. }
  5219. return false;
  5220. }
  5221. protected function pruneToBestVersion(Pool $pool, $literals)
  5222. {
  5223. $operator = $this->preferLowest ? '<' : '>';
  5224. $bestLiterals = array($literals[0]);
  5225. $bestPackage = $pool->literalToPackage($literals[0]);
  5226. foreach ($literals as $i => $literal) {
  5227. if (0 === $i) {
  5228. continue;
  5229. }
  5230. $package = $pool->literalToPackage($literal);
  5231. if ($this->versionCompare($package, $bestPackage, $operator)) {
  5232. $bestPackage = $package;
  5233. $bestLiterals = array($literal);
  5234. } elseif ($this->versionCompare($package, $bestPackage, '==')) {
  5235. $bestLiterals[] = $literal;
  5236. }
  5237. }
  5238. return $bestLiterals;
  5239. }
  5240. protected function pruneToHighestPriorityOrInstalled(Pool $pool, array $installedMap, array $literals)
  5241. {
  5242. $selected = array();
  5243. $priority = null;
  5244. foreach ($literals as $literal) {
  5245. $package = $pool->literalToPackage($literal);
  5246. if (isset($installedMap[$package->id])) {
  5247. $selected[] = $literal;
  5248. continue;
  5249. }
  5250. if (null === $priority) {
  5251. $priority = $this->getPriority($pool, $package);
  5252. }
  5253. if ($this->getPriority($pool, $package) != $priority) {
  5254. break;
  5255. }
  5256. $selected[] = $literal;
  5257. }
  5258. return $selected;
  5259. }
  5260. protected function pruneRemoteAliases(Pool $pool, array $literals)
  5261. {
  5262. $hasLocalAlias = false;
  5263. foreach ($literals as $literal) {
  5264. $package = $pool->literalToPackage($literal);
  5265. if ($package instanceof AliasPackage && $package->isRootPackageAlias()) {
  5266. $hasLocalAlias = true;
  5267. break;
  5268. }
  5269. }
  5270. if (!$hasLocalAlias) {
  5271. return $literals;
  5272. }
  5273. $selected = array();
  5274. foreach ($literals as $literal) {
  5275. $package = $pool->literalToPackage($literal);
  5276. if ($package instanceof AliasPackage && $package->isRootPackageAlias()) {
  5277. $selected[] = $literal;
  5278. }
  5279. }
  5280. return $selected;
  5281. }
  5282. }
  5283. <?php
  5284. namespace Composer\DependencyResolver\Operation;
  5285. use Composer\Package\PackageInterface;
  5286. class InstallOperation extends SolverOperation
  5287. {
  5288. protected $package;
  5289. public function __construct(PackageInterface $package, $reason = null)
  5290. {
  5291. parent::__construct($reason);
  5292. $this->package = $package;
  5293. }
  5294. public function getPackage()
  5295. {
  5296. return $this->package;
  5297. }
  5298. public function getJobType()
  5299. {
  5300. return 'install';
  5301. }
  5302. public function __toString()
  5303. {
  5304. return 'Installing '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).')';
  5305. }
  5306. }
  5307. <?php
  5308. namespace Composer\DependencyResolver\Operation;
  5309. use Composer\Package\AliasPackage;
  5310. class MarkAliasInstalledOperation extends SolverOperation
  5311. {
  5312. protected $package;
  5313. public function __construct(AliasPackage $package, $reason = null)
  5314. {
  5315. parent::__construct($reason);
  5316. $this->package = $package;
  5317. }
  5318. public function getPackage()
  5319. {
  5320. return $this->package;
  5321. }
  5322. public function getJobType()
  5323. {
  5324. return 'markAliasInstalled';
  5325. }
  5326. public function __toString()
  5327. {
  5328. return 'Marking '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).') as installed, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->formatVersion($this->package->getAliasOf()).')';
  5329. }
  5330. }
  5331. <?php
  5332. namespace Composer\DependencyResolver\Operation;
  5333. use Composer\Package\AliasPackage;
  5334. class MarkAliasUninstalledOperation extends SolverOperation
  5335. {
  5336. protected $package;
  5337. public function __construct(AliasPackage $package, $reason = null)
  5338. {
  5339. parent::__construct($reason);
  5340. $this->package = $package;
  5341. }
  5342. public function getPackage()
  5343. {
  5344. return $this->package;
  5345. }
  5346. public function getJobType()
  5347. {
  5348. return 'markAliasUninstalled';
  5349. }
  5350. public function __toString()
  5351. {
  5352. return 'Marking '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).') as uninstalled, alias of '.$this->package->getAliasOf()->getPrettyName().' ('.$this->formatVersion($this->package->getAliasOf()).')';
  5353. }
  5354. }
  5355. <?php
  5356. namespace Composer\DependencyResolver\Operation;
  5357. interface OperationInterface
  5358. {
  5359. public function getJobType();
  5360. public function getReason();
  5361. public function __toString();
  5362. }
  5363. <?php
  5364. namespace Composer\DependencyResolver\Operation;
  5365. use Composer\Package\Version\VersionParser;
  5366. use Composer\Package\PackageInterface;
  5367. abstract class SolverOperation implements OperationInterface
  5368. {
  5369. protected $reason;
  5370. public function __construct($reason = null)
  5371. {
  5372. $this->reason = $reason;
  5373. }
  5374. public function getReason()
  5375. {
  5376. return $this->reason;
  5377. }
  5378. protected function formatVersion(PackageInterface $package)
  5379. {
  5380. return VersionParser::formatVersion($package);
  5381. }
  5382. }
  5383. <?php
  5384. namespace Composer\DependencyResolver\Operation;
  5385. use Composer\Package\PackageInterface;
  5386. class UninstallOperation extends SolverOperation
  5387. {
  5388. protected $package;
  5389. public function __construct(PackageInterface $package, $reason = null)
  5390. {
  5391. parent::__construct($reason);
  5392. $this->package = $package;
  5393. }
  5394. public function getPackage()
  5395. {
  5396. return $this->package;
  5397. }
  5398. public function getJobType()
  5399. {
  5400. return 'uninstall';
  5401. }
  5402. public function __toString()
  5403. {
  5404. return 'Uninstalling '.$this->package->getPrettyName().' ('.$this->formatVersion($this->package).')';
  5405. }
  5406. }
  5407. <?php
  5408. namespace Composer\DependencyResolver\Operation;
  5409. use Composer\Package\PackageInterface;
  5410. class UpdateOperation extends SolverOperation
  5411. {
  5412. protected $initialPackage;
  5413. protected $targetPackage;
  5414. public function __construct(PackageInterface $initial, PackageInterface $target, $reason = null)
  5415. {
  5416. parent::__construct($reason);
  5417. $this->initialPackage = $initial;
  5418. $this->targetPackage = $target;
  5419. }
  5420. public function getInitialPackage()
  5421. {
  5422. return $this->initialPackage;
  5423. }
  5424. public function getTargetPackage()
  5425. {
  5426. return $this->targetPackage;
  5427. }
  5428. public function getJobType()
  5429. {
  5430. return 'update';
  5431. }
  5432. public function __toString()
  5433. {
  5434. return 'Updating '.$this->initialPackage->getPrettyName().' ('.$this->formatVersion($this->initialPackage).') to '.
  5435. $this->targetPackage->getPrettyName(). ' ('.$this->formatVersion($this->targetPackage).')';
  5436. }
  5437. }
  5438. <?php
  5439. namespace Composer\DependencyResolver;
  5440. use Composer\Package\PackageInterface;
  5441. interface PolicyInterface
  5442. {
  5443. public function versionCompare(PackageInterface $a, PackageInterface $b, $operator);
  5444. public function findUpdatePackages(Pool $pool, array $installedMap, PackageInterface $package);
  5445. public function selectPreferedPackages(Pool $pool, array $installedMap, array $literals);
  5446. }
  5447. <?php
  5448. namespace Composer\DependencyResolver;
  5449. use Composer\Package\BasePackage;
  5450. use Composer\Package\AliasPackage;
  5451. use Composer\Package\Version\VersionParser;
  5452. use Composer\Package\LinkConstraint\LinkConstraintInterface;
  5453. use Composer\Package\LinkConstraint\VersionConstraint;
  5454. use Composer\Package\LinkConstraint\EmptyConstraint;
  5455. use Composer\Repository\RepositoryInterface;
  5456. use Composer\Repository\CompositeRepository;
  5457. use Composer\Repository\ComposerRepository;
  5458. use Composer\Repository\InstalledRepositoryInterface;
  5459. use Composer\Repository\PlatformRepository;
  5460. use Composer\Package\PackageInterface;
  5461. class Pool
  5462. {
  5463. const MATCH_NAME = -1;
  5464. const MATCH_NONE = 0;
  5465. const MATCH = 1;
  5466. const MATCH_PROVIDE = 2;
  5467. const MATCH_REPLACE = 3;
  5468. const MATCH_FILTERED = 4;
  5469. protected $repositories = array();
  5470. protected $providerRepos = array();
  5471. protected $packages = array();
  5472. protected $packageByName = array();
  5473. protected $packageByExactName = array();
  5474. protected $acceptableStabilities;
  5475. protected $stabilityFlags;
  5476. protected $versionParser;
  5477. protected $providerCache = array();
  5478. protected $filterRequires;
  5479. protected $whitelist = null;
  5480. protected $id = 1;
  5481. public function __construct($minimumStability = 'stable', array $stabilityFlags = array(), array $filterRequires = array())
  5482. {
  5483. $stabilities = BasePackage::$stabilities;
  5484. $this->versionParser = new VersionParser;
  5485. $this->acceptableStabilities = array();
  5486. foreach (BasePackage::$stabilities as $stability => $value) {
  5487. if ($value <= BasePackage::$stabilities[$minimumStability]) {
  5488. $this->acceptableStabilities[$stability] = $value;
  5489. }
  5490. }
  5491. $this->stabilityFlags = $stabilityFlags;
  5492. $this->filterRequires = $filterRequires;
  5493. foreach ($filterRequires as $name => $constraint) {
  5494. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name)) {
  5495. unset($this->filterRequires[$name]);
  5496. }
  5497. }
  5498. }
  5499. public function setWhitelist($whitelist)
  5500. {
  5501. $this->whitelist = $whitelist;
  5502. $this->providerCache = array();
  5503. }
  5504. public function addRepository(RepositoryInterface $repo, $rootAliases = array())
  5505. {
  5506. if ($repo instanceof CompositeRepository) {
  5507. $repos = $repo->getRepositories();
  5508. } else {
  5509. $repos = array($repo);
  5510. }
  5511. foreach ($repos as $repo) {
  5512. $this->repositories[] = $repo;
  5513. $exempt = $repo instanceof PlatformRepository || $repo instanceof InstalledRepositoryInterface;
  5514. if ($repo instanceof ComposerRepository && $repo->hasProviders()) {
  5515. $this->providerRepos[] = $repo;
  5516. $repo->setRootAliases($rootAliases);
  5517. $repo->resetPackageIds();
  5518. } else {
  5519. foreach ($repo->getPackages() as $package) {
  5520. $names = $package->getNames();
  5521. $stability = $package->getStability();
  5522. if ($exempt || $this->isPackageAcceptable($names, $stability)) {
  5523. $package->setId($this->id++);
  5524. $this->packages[] = $package;
  5525. $this->packageByExactName[$package->getName()][$package->id] = $package;
  5526. foreach ($names as $provided) {
  5527. $this->packageByName[$provided][] = $package;
  5528. }
  5529. $name = $package->getName();
  5530. if (isset($rootAliases[$name][$package->getVersion()])) {
  5531. $alias = $rootAliases[$name][$package->getVersion()];
  5532. if ($package instanceof AliasPackage) {
  5533. $package = $package->getAliasOf();
  5534. }
  5535. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  5536. $aliasPackage->setRootPackageAlias(true);
  5537. $aliasPackage->setId($this->id++);
  5538. $package->getRepository()->addPackage($aliasPackage);
  5539. $this->packages[] = $aliasPackage;
  5540. $this->packageByExactName[$aliasPackage->getName()][$aliasPackage->id] = $aliasPackage;
  5541. foreach ($aliasPackage->getNames() as $name) {
  5542. $this->packageByName[$name][] = $aliasPackage;
  5543. }
  5544. }
  5545. }
  5546. }
  5547. }
  5548. }
  5549. }
  5550. public function getPriority(RepositoryInterface $repo)
  5551. {
  5552. $priority = array_search($repo, $this->repositories, true);
  5553. if (false === $priority) {
  5554. throw new \RuntimeException("Could not determine repository priority. The repository was not registered in the pool.");
  5555. }
  5556. return -$priority;
  5557. }
  5558. public function packageById($id)
  5559. {
  5560. return $this->packages[$id - 1];
  5561. }
  5562. public function whatProvides($name, LinkConstraintInterface $constraint = null, $mustMatchName = false)
  5563. {
  5564. $key = ((int) $mustMatchName).$constraint;
  5565. if (isset($this->providerCache[$name][$key])) {
  5566. return $this->providerCache[$name][$key];
  5567. }
  5568. return $this->providerCache[$name][$key] = $this->computeWhatProvides($name, $constraint, $mustMatchName);
  5569. }
  5570. private function computeWhatProvides($name, $constraint, $mustMatchName = false)
  5571. {
  5572. $candidates = array();
  5573. foreach ($this->providerRepos as $repo) {
  5574. foreach ($repo->whatProvides($this, $name) as $candidate) {
  5575. $candidates[] = $candidate;
  5576. if ($candidate->id < 1) {
  5577. $candidate->setId($this->id++);
  5578. $this->packages[$this->id - 2] = $candidate;
  5579. }
  5580. }
  5581. }
  5582. if ($mustMatchName) {
  5583. $candidates = array_filter($candidates, function ($candidate) use ($name) {
  5584. return $candidate->getName() == $name;
  5585. });
  5586. if (isset($this->packageByExactName[$name])) {
  5587. $candidates = array_merge($candidates, $this->packageByExactName[$name]);
  5588. }
  5589. } elseif (isset($this->packageByName[$name])) {
  5590. $candidates = array_merge($candidates, $this->packageByName[$name]);
  5591. }
  5592. $matches = $provideMatches = array();
  5593. $nameMatch = false;
  5594. foreach ($candidates as $candidate) {
  5595. $aliasOfCandidate = null;
  5596. if ($candidate instanceof AliasPackage) {
  5597. $aliasOfCandidate = $candidate->getAliasOf();
  5598. }
  5599. if ($this->whitelist !== null && (
  5600. (!($candidate instanceof AliasPackage) && !isset($this->whitelist[$candidate->id])) ||
  5601. ($candidate instanceof AliasPackage && !isset($this->whitelist[$aliasOfCandidate->id]))
  5602. )) {
  5603. continue;
  5604. }
  5605. switch ($this->match($candidate, $name, $constraint)) {
  5606. case self::MATCH_NONE:
  5607. break;
  5608. case self::MATCH_NAME:
  5609. $nameMatch = true;
  5610. break;
  5611. case self::MATCH:
  5612. $nameMatch = true;
  5613. $matches[] = $candidate;
  5614. break;
  5615. case self::MATCH_PROVIDE:
  5616. $provideMatches[] = $candidate;
  5617. break;
  5618. case self::MATCH_REPLACE:
  5619. $matches[] = $candidate;
  5620. break;
  5621. case self::MATCH_FILTERED:
  5622. break;
  5623. default:
  5624. throw new \UnexpectedValueException('Unexpected match type');
  5625. }
  5626. }
  5627. if ($nameMatch) {
  5628. return $matches;
  5629. }
  5630. return array_merge($matches, $provideMatches);
  5631. }
  5632. public function literalToPackage($literal)
  5633. {
  5634. $packageId = abs($literal);
  5635. return $this->packageById($packageId);
  5636. }
  5637. public function literalToString($literal)
  5638. {
  5639. return ($literal > 0 ? '+' : '-') . $this->literalToPackage($literal);
  5640. }
  5641. public function literalToPrettyString($literal, $installedMap)
  5642. {
  5643. $package = $this->literalToPackage($literal);
  5644. if (isset($installedMap[$package->id])) {
  5645. $prefix = ($literal > 0 ? 'keep' : 'remove');
  5646. } else {
  5647. $prefix = ($literal > 0 ? 'install' : 'don\'t install');
  5648. }
  5649. return $prefix.' '.$package->getPrettyString();
  5650. }
  5651. public function isPackageAcceptable($name, $stability)
  5652. {
  5653. foreach ((array) $name as $n) {
  5654. if (!isset($this->stabilityFlags[$n]) && isset($this->acceptableStabilities[$stability])) {
  5655. return true;
  5656. }
  5657. if (isset($this->stabilityFlags[$n]) && BasePackage::$stabilities[$stability] <= $this->stabilityFlags[$n]) {
  5658. return true;
  5659. }
  5660. }
  5661. return false;
  5662. }
  5663. private function match($candidate, $name, LinkConstraintInterface $constraint = null)
  5664. {
  5665. $candidateName = $candidate->getName();
  5666. $candidateVersion = $candidate->getVersion();
  5667. $isDev = $candidate->getStability() === 'dev';
  5668. $isAlias = $candidate instanceof AliasPackage;
  5669. if (!$isDev && !$isAlias && isset($this->filterRequires[$name])) {
  5670. $requireFilter = $this->filterRequires[$name];
  5671. } else {
  5672. $requireFilter = new EmptyConstraint;
  5673. }
  5674. if ($candidateName === $name) {
  5675. $pkgConstraint = new VersionConstraint('==', $candidateVersion);
  5676. if ($constraint === null || $constraint->matches($pkgConstraint)) {
  5677. return $requireFilter->matches($pkgConstraint) ? self::MATCH : self::MATCH_FILTERED;
  5678. }
  5679. return self::MATCH_NAME;
  5680. }
  5681. $provides = $candidate->getProvides();
  5682. $replaces = $candidate->getReplaces();
  5683. if (isset($replaces[0]) || isset($provides[0])) {
  5684. foreach ($provides as $link) {
  5685. if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
  5686. return $requireFilter->matches($link->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED;
  5687. }
  5688. }
  5689. foreach ($replaces as $link) {
  5690. if ($link->getTarget() === $name && ($constraint === null || $constraint->matches($link->getConstraint()))) {
  5691. return $requireFilter->matches($link->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED;
  5692. }
  5693. }
  5694. return self::MATCH_NONE;
  5695. }
  5696. if (isset($provides[$name]) && ($constraint === null || $constraint->matches($provides[$name]->getConstraint()))) {
  5697. return $requireFilter->matches($provides[$name]->getConstraint()) ? self::MATCH_PROVIDE : self::MATCH_FILTERED;
  5698. }
  5699. if (isset($replaces[$name]) && ($constraint === null || $constraint->matches($replaces[$name]->getConstraint()))) {
  5700. return $requireFilter->matches($replaces[$name]->getConstraint()) ? self::MATCH_REPLACE : self::MATCH_FILTERED;
  5701. }
  5702. return self::MATCH_NONE;
  5703. }
  5704. }
  5705. <?php
  5706. namespace Composer\DependencyResolver;
  5707. class Problem
  5708. {
  5709. protected $reasonSeen;
  5710. protected $reasons = array();
  5711. protected $section = 0;
  5712. protected $pool;
  5713. public function __construct(Pool $pool)
  5714. {
  5715. $this->pool = $pool;
  5716. }
  5717. public function addRule(Rule $rule)
  5718. {
  5719. $this->addReason($rule->getId(), array(
  5720. 'rule' => $rule,
  5721. 'job' => $rule->getJob(),
  5722. ));
  5723. }
  5724. public function getReasons()
  5725. {
  5726. return $this->reasons;
  5727. }
  5728. public function getPrettyString(array $installedMap = array())
  5729. {
  5730. $reasons = call_user_func_array('array_merge', array_reverse($this->reasons));
  5731. if (count($reasons) === 1) {
  5732. reset($reasons);
  5733. $reason = current($reasons);
  5734. $rule = $reason['rule'];
  5735. $job = $reason['job'];
  5736. if (isset($job['constraint'])) {
  5737. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  5738. } else {
  5739. $packages = array();
  5740. }
  5741. if ($job && $job['cmd'] === 'install' && empty($packages)) {
  5742. if ($job['packageName'] === 'php' || $job['packageName'] === 'php-64bit' || $job['packageName'] === 'hhvm') {
  5743. $msg = "\n - This package requires ".$job['packageName'].$this->constraintToText($job['constraint']).' but ';
  5744. if (defined('HHVM_VERSION')) {
  5745. return $msg . 'your HHVM version does not satisfy that requirement.';
  5746. } elseif ($job['packageName'] === 'hhvm') {
  5747. return $msg . 'you are running this with PHP and not HHVM.';
  5748. }
  5749. return $msg . 'your PHP version does not satisfy that requirement.';
  5750. }
  5751. if (0 === stripos($job['packageName'], 'ext-')) {
  5752. $ext = substr($job['packageName'], 4);
  5753. $error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system';
  5754. return "\n - The requested PHP extension ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error.'.';
  5755. }
  5756. if (0 === stripos($job['packageName'], 'lib-')) {
  5757. if (strtolower($job['packageName']) === 'lib-icu') {
  5758. $error = extension_loaded('intl') ? 'has the wrong version installed, try upgrading the intl extension.' : 'is missing from your system, make sure the intl extension is loaded.';
  5759. return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' '.$error;
  5760. }
  5761. return "\n - The requested linked library ".$job['packageName'].$this->constraintToText($job['constraint']).' has the wrong version installed or is missing from your system, make sure to load the extension providing it.';
  5762. }
  5763. if (!preg_match('{^[A-Za-z0-9_./-]+$}', $job['packageName'])) {
  5764. $illegalChars = preg_replace('{[A-Za-z0-9_./-]+}', '', $job['packageName']);
  5765. return "\n - The requested package ".$job['packageName'].' could not be found, it looks like its name is invalid, "'.$illegalChars.'" is not allowed in package names.';
  5766. }
  5767. if (!$this->pool->whatProvides($job['packageName'])) {
  5768. return "\n - The requested package ".$job['packageName'].' could not be found in any version, there may be a typo in the package name.';
  5769. }
  5770. return "\n - The requested package ".$job['packageName'].$this->constraintToText($job['constraint']).' could not be found.';
  5771. }
  5772. }
  5773. $messages = array();
  5774. foreach ($reasons as $reason) {
  5775. $rule = $reason['rule'];
  5776. $job = $reason['job'];
  5777. if ($job) {
  5778. $messages[] = $this->jobToText($job);
  5779. } elseif ($rule) {
  5780. if ($rule instanceof Rule) {
  5781. $messages[] = $rule->getPrettyString($this->pool, $installedMap);
  5782. }
  5783. }
  5784. }
  5785. return "\n - ".implode("\n - ", $messages);
  5786. }
  5787. protected function addReason($id, $reason)
  5788. {
  5789. if (!isset($this->reasonSeen[$id])) {
  5790. $this->reasonSeen[$id] = true;
  5791. $this->reasons[$this->section][] = $reason;
  5792. }
  5793. }
  5794. public function nextSection()
  5795. {
  5796. $this->section++;
  5797. }
  5798. protected function jobToText($job)
  5799. {
  5800. switch ($job['cmd']) {
  5801. case 'install':
  5802. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  5803. if (!$packages) {
  5804. return 'No package found to satisfy install request for '.$job['packageName'].$this->constraintToText($job['constraint']);
  5805. }
  5806. return 'Installation request for '.$job['packageName'].$this->constraintToText($job['constraint']).' -> satisfiable by '.$this->getPackageList($packages).'.';
  5807. case 'update':
  5808. return 'Update request for '.$job['packageName'].$this->constraintToText($job['constraint']).'.';
  5809. case 'remove':
  5810. return 'Removal request for '.$job['packageName'].$this->constraintToText($job['constraint']).'';
  5811. }
  5812. if (isset($job['constraint'])) {
  5813. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  5814. } else {
  5815. $packages = array();
  5816. }
  5817. return 'Job(cmd='.$job['cmd'].', target='.$job['packageName'].', packages=['.$this->getPackageList($packages).'])';
  5818. }
  5819. protected function getPackageList($packages)
  5820. {
  5821. $prepared = array();
  5822. foreach ($packages as $package) {
  5823. $prepared[$package->getName()]['name'] = $package->getPrettyName();
  5824. $prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion();
  5825. }
  5826. foreach ($prepared as $name => $package) {
  5827. $prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']';
  5828. }
  5829. return implode(', ', $prepared);
  5830. }
  5831. protected function constraintToText($constraint)
  5832. {
  5833. return ($constraint) ? ' '.$constraint->getPrettyString() : '';
  5834. }
  5835. }
  5836. <?php
  5837. namespace Composer\DependencyResolver;
  5838. use Composer\Package\LinkConstraint\LinkConstraintInterface;
  5839. class Request
  5840. {
  5841. protected $jobs;
  5842. protected $pool;
  5843. public function __construct(Pool $pool)
  5844. {
  5845. $this->pool = $pool;
  5846. $this->jobs = array();
  5847. }
  5848. public function install($packageName, LinkConstraintInterface $constraint = null)
  5849. {
  5850. $this->addJob($packageName, 'install', $constraint);
  5851. }
  5852. public function update($packageName, LinkConstraintInterface $constraint = null)
  5853. {
  5854. $this->addJob($packageName, 'update', $constraint);
  5855. }
  5856. public function remove($packageName, LinkConstraintInterface $constraint = null)
  5857. {
  5858. $this->addJob($packageName, 'remove', $constraint);
  5859. }
  5860. public function fix($packageName, LinkConstraintInterface $constraint = null)
  5861. {
  5862. $this->addJob($packageName, 'install', $constraint, true);
  5863. }
  5864. protected function addJob($packageName, $cmd, LinkConstraintInterface $constraint = null, $fixed = false)
  5865. {
  5866. $packageName = strtolower($packageName);
  5867. $this->jobs[] = array(
  5868. 'cmd' => $cmd,
  5869. 'packageName' => $packageName,
  5870. 'constraint' => $constraint,
  5871. 'fixed' => $fixed
  5872. );
  5873. }
  5874. public function updateAll()
  5875. {
  5876. $this->jobs[] = array('cmd' => 'update-all');
  5877. }
  5878. public function getJobs()
  5879. {
  5880. return $this->jobs;
  5881. }
  5882. }
  5883. <?php
  5884. namespace Composer\DependencyResolver;
  5885. class Rule
  5886. {
  5887. const RULE_INTERNAL_ALLOW_UPDATE = 1;
  5888. const RULE_JOB_INSTALL = 2;
  5889. const RULE_JOB_REMOVE = 3;
  5890. const RULE_PACKAGE_CONFLICT = 6;
  5891. const RULE_PACKAGE_REQUIRES = 7;
  5892. const RULE_PACKAGE_OBSOLETES = 8;
  5893. const RULE_INSTALLED_PACKAGE_OBSOLETES = 9;
  5894. const RULE_PACKAGE_SAME_NAME = 10;
  5895. const RULE_PACKAGE_IMPLICIT_OBSOLETES = 11;
  5896. const RULE_LEARNED = 12;
  5897. const RULE_PACKAGE_ALIAS = 13;
  5898. public $literals;
  5899. protected $disabled;
  5900. protected $type;
  5901. protected $id;
  5902. protected $reason;
  5903. protected $reasonData;
  5904. protected $job;
  5905. protected $ruleHash;
  5906. public function __construct(array $literals, $reason, $reasonData, $job = null)
  5907. {
  5908. sort($literals);
  5909. $this->literals = $literals;
  5910. $this->reason = $reason;
  5911. $this->reasonData = $reasonData;
  5912. $this->disabled = false;
  5913. $this->job = $job;
  5914. $this->type = -1;
  5915. $this->ruleHash = substr(md5(implode(',', $this->literals)), 0, 5);
  5916. }
  5917. public function getHash()
  5918. {
  5919. return $this->ruleHash;
  5920. }
  5921. public function setId($id)
  5922. {
  5923. $this->id = $id;
  5924. }
  5925. public function getId()
  5926. {
  5927. return $this->id;
  5928. }
  5929. public function getJob()
  5930. {
  5931. return $this->job;
  5932. }
  5933. public function getReason()
  5934. {
  5935. return $this->reason;
  5936. }
  5937. public function getReasonData()
  5938. {
  5939. return $this->reasonData;
  5940. }
  5941. public function getRequiredPackage()
  5942. {
  5943. if ($this->reason === self::RULE_JOB_INSTALL) {
  5944. return $this->reasonData;
  5945. }
  5946. if ($this->reason === self::RULE_PACKAGE_REQUIRES) {
  5947. return $this->reasonData->getTarget();
  5948. }
  5949. }
  5950. public function equals(Rule $rule)
  5951. {
  5952. if ($this->ruleHash !== $rule->ruleHash) {
  5953. return false;
  5954. }
  5955. if (count($this->literals) != count($rule->literals)) {
  5956. return false;
  5957. }
  5958. for ($i = 0, $n = count($this->literals); $i < $n; $i++) {
  5959. if ($this->literals[$i] !== $rule->literals[$i]) {
  5960. return false;
  5961. }
  5962. }
  5963. return true;
  5964. }
  5965. public function setType($type)
  5966. {
  5967. $this->type = $type;
  5968. }
  5969. public function getType()
  5970. {
  5971. return $this->type;
  5972. }
  5973. public function disable()
  5974. {
  5975. $this->disabled = true;
  5976. }
  5977. public function enable()
  5978. {
  5979. $this->disabled = false;
  5980. }
  5981. public function isDisabled()
  5982. {
  5983. return $this->disabled;
  5984. }
  5985. public function isEnabled()
  5986. {
  5987. return !$this->disabled;
  5988. }
  5989. public function getLiterals()
  5990. {
  5991. return $this->literals;
  5992. }
  5993. public function isAssertion()
  5994. {
  5995. return 1 === count($this->literals);
  5996. }
  5997. public function getPrettyString(Pool $pool, array $installedMap = array())
  5998. {
  5999. $ruleText = '';
  6000. foreach ($this->literals as $i => $literal) {
  6001. if ($i != 0) {
  6002. $ruleText .= '|';
  6003. }
  6004. $ruleText .= $pool->literalToPrettyString($literal, $installedMap);
  6005. }
  6006. switch ($this->reason) {
  6007. case self::RULE_INTERNAL_ALLOW_UPDATE:
  6008. return $ruleText;
  6009. case self::RULE_JOB_INSTALL:
  6010. return "Install command rule ($ruleText)";
  6011. case self::RULE_JOB_REMOVE:
  6012. return "Remove command rule ($ruleText)";
  6013. case self::RULE_PACKAGE_CONFLICT:
  6014. $package1 = $pool->literalToPackage($this->literals[0]);
  6015. $package2 = $pool->literalToPackage($this->literals[1]);
  6016. return $package1->getPrettyString().' conflicts with '.$this->formatPackagesUnique($pool, array($package2)).'.';
  6017. case self::RULE_PACKAGE_REQUIRES:
  6018. $literals = $this->literals;
  6019. $sourceLiteral = array_shift($literals);
  6020. $sourcePackage = $pool->literalToPackage($sourceLiteral);
  6021. $requires = array();
  6022. foreach ($literals as $literal) {
  6023. $requires[] = $pool->literalToPackage($literal);
  6024. }
  6025. $text = $this->reasonData->getPrettyString($sourcePackage);
  6026. if ($requires) {
  6027. $text .= ' -> satisfiable by ' . $this->formatPackagesUnique($pool, $requires) . '.';
  6028. } else {
  6029. $targetName = $this->reasonData->getTarget();
  6030. if ($targetName === 'php' || $targetName === 'php-64bit' || $targetName === 'hhvm') {
  6031. if (defined('HHVM_VERSION')) {
  6032. $text .= ' -> your HHVM version does not satisfy that requirement.';
  6033. } elseif ($targetName === 'hhvm') {
  6034. $text .= ' -> you are running this with PHP and not HHVM.';
  6035. } else {
  6036. $text .= ' -> your PHP version does not satisfy that requirement.';
  6037. }
  6038. } elseif (0 === strpos($targetName, 'ext-')) {
  6039. $ext = substr($targetName, 4);
  6040. $error = extension_loaded($ext) ? 'has the wrong version ('.(phpversion($ext) ?: '0').') installed' : 'is missing from your system';
  6041. $text .= ' -> the requested PHP extension '.$ext.' '.$error.'.';
  6042. } elseif (0 === strpos($targetName, 'lib-')) {
  6043. $lib = substr($targetName, 4);
  6044. $text .= ' -> the requested linked library '.$lib.' has the wrong version installed or is missing from your system, make sure to have the extension providing it.';
  6045. } else {
  6046. $text .= ' -> no matching package found.';
  6047. }
  6048. }
  6049. return $text;
  6050. case self::RULE_PACKAGE_OBSOLETES:
  6051. return $ruleText;
  6052. case self::RULE_INSTALLED_PACKAGE_OBSOLETES:
  6053. return $ruleText;
  6054. case self::RULE_PACKAGE_SAME_NAME:
  6055. return 'Can only install one of: ' . $this->formatPackagesUnique($pool, $this->literals) . '.';
  6056. case self::RULE_PACKAGE_IMPLICIT_OBSOLETES:
  6057. return $ruleText;
  6058. case self::RULE_LEARNED:
  6059. return 'Conclusion: '.$ruleText;
  6060. case self::RULE_PACKAGE_ALIAS:
  6061. return $ruleText;
  6062. default:
  6063. return '('.$ruleText.')';
  6064. }
  6065. }
  6066. protected function formatPackagesUnique($pool, array $packages)
  6067. {
  6068. $prepared = array();
  6069. foreach ($packages as $package) {
  6070. if (!is_object($package)) {
  6071. $package = $pool->literalToPackage($package);
  6072. }
  6073. $prepared[$package->getName()]['name'] = $package->getPrettyName();
  6074. $prepared[$package->getName()]['versions'][$package->getVersion()] = $package->getPrettyVersion();
  6075. }
  6076. foreach ($prepared as $name => $package) {
  6077. $prepared[$name] = $package['name'].'['.implode(', ', $package['versions']).']';
  6078. }
  6079. return implode(', ', $prepared);
  6080. }
  6081. public function __toString()
  6082. {
  6083. $result = ($this->isDisabled()) ? 'disabled(' : '(';
  6084. foreach ($this->literals as $i => $literal) {
  6085. if ($i != 0) {
  6086. $result .= '|';
  6087. }
  6088. $result .= $literal;
  6089. }
  6090. $result .= ')';
  6091. return $result;
  6092. }
  6093. }
  6094. <?php
  6095. namespace Composer\DependencyResolver;
  6096. class RuleSet implements \IteratorAggregate, \Countable
  6097. {
  6098. const TYPE_PACKAGE = 0;
  6099. const TYPE_JOB = 1;
  6100. const TYPE_LEARNED = 4;
  6101. public $ruleById;
  6102. protected static $types = array(
  6103. -1 => 'UNKNOWN',
  6104. self::TYPE_PACKAGE => 'PACKAGE',
  6105. self::TYPE_JOB => 'JOB',
  6106. self::TYPE_LEARNED => 'LEARNED',
  6107. );
  6108. protected $rules;
  6109. protected $nextRuleId;
  6110. protected $rulesByHash;
  6111. public function __construct()
  6112. {
  6113. $this->nextRuleId = 0;
  6114. foreach ($this->getTypes() as $type) {
  6115. $this->rules[$type] = array();
  6116. }
  6117. $this->rulesByHash = array();
  6118. }
  6119. public function add(Rule $rule, $type)
  6120. {
  6121. if (!isset(self::$types[$type])) {
  6122. throw new \OutOfBoundsException('Unknown rule type: ' . $type);
  6123. }
  6124. if (!isset($this->rules[$type])) {
  6125. $this->rules[$type] = array();
  6126. }
  6127. $this->rules[$type][] = $rule;
  6128. $this->ruleById[$this->nextRuleId] = $rule;
  6129. $rule->setType($type);
  6130. $rule->setId($this->nextRuleId);
  6131. $this->nextRuleId++;
  6132. $hash = $rule->getHash();
  6133. if (!isset($this->rulesByHash[$hash])) {
  6134. $this->rulesByHash[$hash] = array($rule);
  6135. } else {
  6136. $this->rulesByHash[$hash][] = $rule;
  6137. }
  6138. }
  6139. public function count()
  6140. {
  6141. return $this->nextRuleId;
  6142. }
  6143. public function ruleById($id)
  6144. {
  6145. return $this->ruleById[$id];
  6146. }
  6147. public function getRules()
  6148. {
  6149. return $this->rules;
  6150. }
  6151. public function getIterator()
  6152. {
  6153. return new RuleSetIterator($this->getRules());
  6154. }
  6155. public function getIteratorFor($types)
  6156. {
  6157. if (!is_array($types)) {
  6158. $types = array($types);
  6159. }
  6160. $allRules = $this->getRules();
  6161. $rules = array();
  6162. foreach ($types as $type) {
  6163. $rules[$type] = $allRules[$type];
  6164. }
  6165. return new RuleSetIterator($rules);
  6166. }
  6167. public function getIteratorWithout($types)
  6168. {
  6169. if (!is_array($types)) {
  6170. $types = array($types);
  6171. }
  6172. $rules = $this->getRules();
  6173. foreach ($types as $type) {
  6174. unset($rules[$type]);
  6175. }
  6176. return new RuleSetIterator($rules);
  6177. }
  6178. public function getTypes()
  6179. {
  6180. $types = self::$types;
  6181. unset($types[-1]);
  6182. return array_keys($types);
  6183. }
  6184. public function containsEqual($rule)
  6185. {
  6186. if (isset($this->rulesByHash[$rule->getHash()])) {
  6187. $potentialDuplicates = $this->rulesByHash[$rule->getHash()];
  6188. foreach ($potentialDuplicates as $potentialDuplicate) {
  6189. if ($rule->equals($potentialDuplicate)) {
  6190. return true;
  6191. }
  6192. }
  6193. }
  6194. return false;
  6195. }
  6196. public function getPrettyString(Pool $pool = null)
  6197. {
  6198. $string = "\n";
  6199. foreach ($this->rules as $type => $rules) {
  6200. $string .= str_pad(self::$types[$type], 8, ' ') . ": ";
  6201. foreach ($rules as $rule) {
  6202. $string .= ($pool ? $rule->getPrettyString($pool) : $rule)."\n";
  6203. }
  6204. $string .= "\n\n";
  6205. }
  6206. return $string;
  6207. }
  6208. public function __toString()
  6209. {
  6210. return $this->getPrettyString(null);
  6211. }
  6212. }
  6213. <?php
  6214. namespace Composer\DependencyResolver;
  6215. use Composer\Package\PackageInterface;
  6216. use Composer\Package\AliasPackage;
  6217. use Composer\Repository\PlatformRepository;
  6218. class RuleSetGenerator
  6219. {
  6220. protected $policy;
  6221. protected $pool;
  6222. protected $rules;
  6223. protected $jobs;
  6224. protected $installedMap;
  6225. protected $whitelistedMap;
  6226. protected $addedMap;
  6227. public function __construct(PolicyInterface $policy, Pool $pool)
  6228. {
  6229. $this->policy = $policy;
  6230. $this->pool = $pool;
  6231. }
  6232. protected function createRequireRule(PackageInterface $package, array $providers, $reason, $reasonData = null)
  6233. {
  6234. $literals = array(-$package->id);
  6235. foreach ($providers as $provider) {
  6236. if ($provider === $package) {
  6237. return null;
  6238. }
  6239. $literals[] = $provider->id;
  6240. }
  6241. return new Rule($literals, $reason, $reasonData);
  6242. }
  6243. protected function createInstallOneOfRule(array $packages, $reason, $job)
  6244. {
  6245. $literals = array();
  6246. foreach ($packages as $package) {
  6247. $literals[] = $package->id;
  6248. }
  6249. return new Rule($literals, $reason, $job['packageName'], $job);
  6250. }
  6251. protected function createRemoveRule(PackageInterface $package, $reason, $job)
  6252. {
  6253. return new Rule(array(-$package->id), $reason, $job['packageName'], $job);
  6254. }
  6255. protected function createConflictRule(PackageInterface $issuer, PackageInterface $provider, $reason, $reasonData = null)
  6256. {
  6257. if ($issuer === $provider) {
  6258. return null;
  6259. }
  6260. return new Rule(array(-$issuer->id, -$provider->id), $reason, $reasonData);
  6261. }
  6262. private function addRule($type, Rule $newRule = null)
  6263. {
  6264. if (!$newRule || $this->rules->containsEqual($newRule)) {
  6265. return;
  6266. }
  6267. $this->rules->add($newRule, $type);
  6268. }
  6269. protected function whitelistFromPackage(PackageInterface $package)
  6270. {
  6271. $workQueue = new \SplQueue;
  6272. $workQueue->enqueue($package);
  6273. while (!$workQueue->isEmpty()) {
  6274. $package = $workQueue->dequeue();
  6275. if (isset($this->whitelistedMap[$package->id])) {
  6276. continue;
  6277. }
  6278. $this->whitelistedMap[$package->id] = true;
  6279. foreach ($package->getRequires() as $link) {
  6280. $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint(), true);
  6281. foreach ($possibleRequires as $require) {
  6282. $workQueue->enqueue($require);
  6283. }
  6284. }
  6285. $obsoleteProviders = $this->pool->whatProvides($package->getName(), null, true);
  6286. foreach ($obsoleteProviders as $provider) {
  6287. if ($provider === $package) {
  6288. continue;
  6289. }
  6290. if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) {
  6291. $workQueue->enqueue($provider);
  6292. }
  6293. }
  6294. }
  6295. }
  6296. protected function addRulesForPackage(PackageInterface $package, $ignorePlatformReqs)
  6297. {
  6298. $workQueue = new \SplQueue;
  6299. $workQueue->enqueue($package);
  6300. while (!$workQueue->isEmpty()) {
  6301. $package = $workQueue->dequeue();
  6302. if (isset($this->addedMap[$package->id])) {
  6303. continue;
  6304. }
  6305. $this->addedMap[$package->id] = true;
  6306. foreach ($package->getRequires() as $link) {
  6307. if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  6308. continue;
  6309. }
  6310. $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
  6311. $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, $possibleRequires, Rule::RULE_PACKAGE_REQUIRES, $link));
  6312. foreach ($possibleRequires as $require) {
  6313. $workQueue->enqueue($require);
  6314. }
  6315. }
  6316. foreach ($package->getConflicts() as $link) {
  6317. $possibleConflicts = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
  6318. foreach ($possibleConflicts as $conflict) {
  6319. $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $conflict, Rule::RULE_PACKAGE_CONFLICT, $link));
  6320. }
  6321. }
  6322. $isInstalled = (isset($this->installedMap[$package->id]));
  6323. foreach ($package->getReplaces() as $link) {
  6324. $obsoleteProviders = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
  6325. foreach ($obsoleteProviders as $provider) {
  6326. if ($provider === $package) {
  6327. continue;
  6328. }
  6329. if (!$this->obsoleteImpossibleForAlias($package, $provider)) {
  6330. $reason = ($isInstalled) ? Rule::RULE_INSTALLED_PACKAGE_OBSOLETES : Rule::RULE_PACKAGE_OBSOLETES;
  6331. $this->addRule(RuleSet::TYPE_PACKAGE, $this->createConflictRule($package, $provider, $reason, $link));
  6332. }
  6333. }
  6334. }
  6335. $obsoleteProviders = $this->pool->whatProvides($package->getName(), null);
  6336. foreach ($obsoleteProviders as $provider) {
  6337. if ($provider === $package) {
  6338. continue;
  6339. }
  6340. if (($package instanceof AliasPackage) && $package->getAliasOf() === $provider) {
  6341. $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createRequireRule($package, array($provider), Rule::RULE_PACKAGE_ALIAS, $package));
  6342. } elseif (!$this->obsoleteImpossibleForAlias($package, $provider)) {
  6343. $reason = ($package->getName() == $provider->getName()) ? Rule::RULE_PACKAGE_SAME_NAME : Rule::RULE_PACKAGE_IMPLICIT_OBSOLETES;
  6344. $this->addRule(RuleSet::TYPE_PACKAGE, $rule = $this->createConflictRule($package, $provider, $reason, $package));
  6345. }
  6346. }
  6347. }
  6348. }
  6349. protected function obsoleteImpossibleForAlias($package, $provider)
  6350. {
  6351. $packageIsAlias = $package instanceof AliasPackage;
  6352. $providerIsAlias = $provider instanceof AliasPackage;
  6353. $impossible = (
  6354. ($packageIsAlias && $package->getAliasOf() === $provider) ||
  6355. ($providerIsAlias && $provider->getAliasOf() === $package) ||
  6356. ($packageIsAlias && $providerIsAlias && $provider->getAliasOf() === $package->getAliasOf())
  6357. );
  6358. return $impossible;
  6359. }
  6360. protected function whitelistFromJobs()
  6361. {
  6362. foreach ($this->jobs as $job) {
  6363. switch ($job['cmd']) {
  6364. case 'install':
  6365. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint'], true);
  6366. foreach ($packages as $package) {
  6367. $this->whitelistFromPackage($package);
  6368. }
  6369. break;
  6370. }
  6371. }
  6372. }
  6373. protected function addRulesForJobs($ignorePlatformReqs)
  6374. {
  6375. foreach ($this->jobs as $job) {
  6376. switch ($job['cmd']) {
  6377. case 'install':
  6378. if (!$job['fixed'] && $ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $job['packageName'])) {
  6379. continue;
  6380. }
  6381. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  6382. if ($packages) {
  6383. foreach ($packages as $package) {
  6384. if (!isset($this->installedMap[$package->id])) {
  6385. $this->addRulesForPackage($package, $ignorePlatformReqs);
  6386. }
  6387. }
  6388. $rule = $this->createInstallOneOfRule($packages, Rule::RULE_JOB_INSTALL, $job);
  6389. $this->addRule(RuleSet::TYPE_JOB, $rule);
  6390. }
  6391. break;
  6392. case 'remove':
  6393. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  6394. foreach ($packages as $package) {
  6395. $rule = $this->createRemoveRule($package, Rule::RULE_JOB_REMOVE, $job);
  6396. $this->addRule(RuleSet::TYPE_JOB, $rule);
  6397. }
  6398. break;
  6399. }
  6400. }
  6401. }
  6402. public function getRulesFor($jobs, $installedMap, $ignorePlatformReqs = false)
  6403. {
  6404. $this->jobs = $jobs;
  6405. $this->rules = new RuleSet;
  6406. $this->installedMap = $installedMap;
  6407. $this->whitelistedMap = array();
  6408. foreach ($this->installedMap as $package) {
  6409. $this->whitelistFromPackage($package);
  6410. }
  6411. $this->whitelistFromJobs();
  6412. $this->pool->setWhitelist($this->whitelistedMap);
  6413. $this->addedMap = array();
  6414. foreach ($this->installedMap as $package) {
  6415. $this->addRulesForPackage($package, $ignorePlatformReqs);
  6416. }
  6417. $this->addRulesForJobs($ignorePlatformReqs);
  6418. return $this->rules;
  6419. }
  6420. }
  6421. <?php
  6422. namespace Composer\DependencyResolver;
  6423. class RuleSetIterator implements \Iterator
  6424. {
  6425. protected $rules;
  6426. protected $types;
  6427. protected $currentOffset;
  6428. protected $currentType;
  6429. protected $currentTypeOffset;
  6430. public function __construct(array $rules)
  6431. {
  6432. $this->rules = $rules;
  6433. $this->types = array_keys($rules);
  6434. sort($this->types);
  6435. $this->rewind();
  6436. }
  6437. public function current()
  6438. {
  6439. return $this->rules[$this->currentType][$this->currentOffset];
  6440. }
  6441. public function key()
  6442. {
  6443. return $this->currentType;
  6444. }
  6445. public function next()
  6446. {
  6447. $this->currentOffset++;
  6448. if (!isset($this->rules[$this->currentType])) {
  6449. return;
  6450. }
  6451. if ($this->currentOffset >= sizeof($this->rules[$this->currentType])) {
  6452. $this->currentOffset = 0;
  6453. do {
  6454. $this->currentTypeOffset++;
  6455. if (!isset($this->types[$this->currentTypeOffset])) {
  6456. $this->currentType = -1;
  6457. break;
  6458. }
  6459. $this->currentType = $this->types[$this->currentTypeOffset];
  6460. } while (isset($this->types[$this->currentTypeOffset]) && !sizeof($this->rules[$this->currentType]));
  6461. }
  6462. }
  6463. public function rewind()
  6464. {
  6465. $this->currentOffset = 0;
  6466. $this->currentTypeOffset = -1;
  6467. $this->currentType = -1;
  6468. do {
  6469. $this->currentTypeOffset++;
  6470. if (!isset($this->types[$this->currentTypeOffset])) {
  6471. $this->currentType = -1;
  6472. break;
  6473. }
  6474. $this->currentType = $this->types[$this->currentTypeOffset];
  6475. } while (isset($this->types[$this->currentTypeOffset]) && !sizeof($this->rules[$this->currentType]));
  6476. }
  6477. public function valid()
  6478. {
  6479. return isset($this->rules[$this->currentType])
  6480. && isset($this->rules[$this->currentType][$this->currentOffset]);
  6481. }
  6482. }
  6483. <?php
  6484. namespace Composer\DependencyResolver;
  6485. class RuleWatchChain extends \SplDoublyLinkedList
  6486. {
  6487. protected $offset = 0;
  6488. public function seek($offset)
  6489. {
  6490. $this->rewind();
  6491. for ($i = 0; $i < $offset; $i++, $this->next());
  6492. }
  6493. public function remove()
  6494. {
  6495. $offset = $this->key();
  6496. $this->offsetUnset($offset);
  6497. $this->seek($offset);
  6498. }
  6499. }
  6500. <?php
  6501. namespace Composer\DependencyResolver;
  6502. class RuleWatchGraph
  6503. {
  6504. protected $watchChains = array();
  6505. public function insert(RuleWatchNode $node)
  6506. {
  6507. if ($node->getRule()->isAssertion()) {
  6508. return;
  6509. }
  6510. foreach (array($node->watch1, $node->watch2) as $literal) {
  6511. if (!isset($this->watchChains[$literal])) {
  6512. $this->watchChains[$literal] = new RuleWatchChain;
  6513. }
  6514. $this->watchChains[$literal]->unshift($node);
  6515. }
  6516. }
  6517. public function propagateLiteral($decidedLiteral, $level, $decisions)
  6518. {
  6519. $literal = -$decidedLiteral;
  6520. if (!isset($this->watchChains[$literal])) {
  6521. return null;
  6522. }
  6523. $chain = $this->watchChains[$literal];
  6524. $chain->rewind();
  6525. while ($chain->valid()) {
  6526. $node = $chain->current();
  6527. $otherWatch = $node->getOtherWatch($literal);
  6528. if (!$node->getRule()->isDisabled() && !$decisions->satisfy($otherWatch)) {
  6529. $ruleLiterals = $node->getRule()->literals;
  6530. $alternativeLiterals = array_filter($ruleLiterals, function ($ruleLiteral) use ($literal, $otherWatch, $decisions) {
  6531. return $literal !== $ruleLiteral &&
  6532. $otherWatch !== $ruleLiteral &&
  6533. !$decisions->conflict($ruleLiteral);
  6534. });
  6535. if ($alternativeLiterals) {
  6536. reset($alternativeLiterals);
  6537. $this->moveWatch($literal, current($alternativeLiterals), $node);
  6538. continue;
  6539. }
  6540. if ($decisions->conflict($otherWatch)) {
  6541. return $node->getRule();
  6542. }
  6543. $decisions->decide($otherWatch, $level, $node->getRule());
  6544. }
  6545. $chain->next();
  6546. }
  6547. return null;
  6548. }
  6549. protected function moveWatch($fromLiteral, $toLiteral, $node)
  6550. {
  6551. if (!isset($this->watchChains[$toLiteral])) {
  6552. $this->watchChains[$toLiteral] = new RuleWatchChain;
  6553. }
  6554. $node->moveWatch($fromLiteral, $toLiteral);
  6555. $this->watchChains[$fromLiteral]->remove();
  6556. $this->watchChains[$toLiteral]->unshift($node);
  6557. }
  6558. }
  6559. <?php
  6560. namespace Composer\DependencyResolver;
  6561. class RuleWatchNode
  6562. {
  6563. public $watch1;
  6564. public $watch2;
  6565. protected $rule;
  6566. public function __construct($rule)
  6567. {
  6568. $this->rule = $rule;
  6569. $literals = $rule->literals;
  6570. $this->watch1 = count($literals) > 0 ? $literals[0] : 0;
  6571. $this->watch2 = count($literals) > 1 ? $literals[1] : 0;
  6572. }
  6573. public function watch2OnHighest(Decisions $decisions)
  6574. {
  6575. $literals = $this->rule->literals;
  6576. if (count($literals) < 3) {
  6577. return;
  6578. }
  6579. $watchLevel = 0;
  6580. foreach ($literals as $literal) {
  6581. $level = $decisions->decisionLevel($literal);
  6582. if ($level > $watchLevel) {
  6583. $this->watch2 = $literal;
  6584. $watchLevel = $level;
  6585. }
  6586. }
  6587. }
  6588. public function getRule()
  6589. {
  6590. return $this->rule;
  6591. }
  6592. public function getOtherWatch($literal)
  6593. {
  6594. if ($this->watch1 == $literal) {
  6595. return $this->watch2;
  6596. } else {
  6597. return $this->watch1;
  6598. }
  6599. }
  6600. public function moveWatch($from, $to)
  6601. {
  6602. if ($this->watch1 == $from) {
  6603. $this->watch1 = $to;
  6604. } else {
  6605. $this->watch2 = $to;
  6606. }
  6607. }
  6608. }
  6609. <?php
  6610. namespace Composer\DependencyResolver;
  6611. use Composer\Repository\RepositoryInterface;
  6612. use Composer\Repository\PlatformRepository;
  6613. class Solver
  6614. {
  6615. const BRANCH_LITERALS = 0;
  6616. const BRANCH_LEVEL = 1;
  6617. protected $policy;
  6618. protected $pool;
  6619. protected $installed;
  6620. protected $rules;
  6621. protected $ruleSetGenerator;
  6622. protected $updateAll;
  6623. protected $addedMap = array();
  6624. protected $updateMap = array();
  6625. protected $watchGraph;
  6626. protected $decisions;
  6627. protected $installedMap;
  6628. protected $propagateIndex;
  6629. protected $branches = array();
  6630. protected $problems = array();
  6631. protected $learnedPool = array();
  6632. protected $learnedWhy = array();
  6633. public function __construct(PolicyInterface $policy, Pool $pool, RepositoryInterface $installed)
  6634. {
  6635. $this->policy = $policy;
  6636. $this->pool = $pool;
  6637. $this->installed = $installed;
  6638. $this->ruleSetGenerator = new RuleSetGenerator($policy, $pool);
  6639. }
  6640. private function makeAssertionRuleDecisions()
  6641. {
  6642. $decisionStart = count($this->decisions) - 1;
  6643. $rulesCount = count($this->rules);
  6644. for ($ruleIndex = 0; $ruleIndex < $rulesCount; $ruleIndex++) {
  6645. $rule = $this->rules->ruleById[$ruleIndex];
  6646. if (!$rule->isAssertion() || $rule->isDisabled()) {
  6647. continue;
  6648. }
  6649. $literals = $rule->literals;
  6650. $literal = $literals[0];
  6651. if (!$this->decisions->decided(abs($literal))) {
  6652. $this->decisions->decide($literal, 1, $rule);
  6653. continue;
  6654. }
  6655. if ($this->decisions->satisfy($literal)) {
  6656. continue;
  6657. }
  6658. if (RuleSet::TYPE_LEARNED === $rule->getType()) {
  6659. $rule->disable();
  6660. continue;
  6661. }
  6662. $conflict = $this->decisions->decisionRule($literal);
  6663. if ($conflict && RuleSet::TYPE_PACKAGE === $conflict->getType()) {
  6664. $problem = new Problem($this->pool);
  6665. $problem->addRule($rule);
  6666. $problem->addRule($conflict);
  6667. $this->disableProblem($rule);
  6668. $this->problems[] = $problem;
  6669. continue;
  6670. }
  6671. $problem = new Problem($this->pool);
  6672. $problem->addRule($rule);
  6673. $problem->addRule($conflict);
  6674. foreach ($this->rules->getIteratorFor(RuleSet::TYPE_JOB) as $assertRule) {
  6675. if ($assertRule->isDisabled() || !$assertRule->isAssertion()) {
  6676. continue;
  6677. }
  6678. $assertRuleLiterals = $assertRule->literals;
  6679. $assertRuleLiteral = $assertRuleLiterals[0];
  6680. if (abs($literal) !== abs($assertRuleLiteral)) {
  6681. continue;
  6682. }
  6683. $problem->addRule($assertRule);
  6684. $this->disableProblem($assertRule);
  6685. }
  6686. $this->problems[] = $problem;
  6687. $this->decisions->resetToOffset($decisionStart);
  6688. $ruleIndex = -1;
  6689. }
  6690. }
  6691. protected function setupInstalledMap()
  6692. {
  6693. $this->installedMap = array();
  6694. foreach ($this->installed->getPackages() as $package) {
  6695. $this->installedMap[$package->id] = $package;
  6696. }
  6697. }
  6698. protected function checkForRootRequireProblems($ignorePlatformReqs)
  6699. {
  6700. foreach ($this->jobs as $job) {
  6701. switch ($job['cmd']) {
  6702. case 'update':
  6703. $packages = $this->pool->whatProvides($job['packageName'], $job['constraint']);
  6704. foreach ($packages as $package) {
  6705. if (isset($this->installedMap[$package->id])) {
  6706. $this->updateMap[$package->id] = true;
  6707. }
  6708. }
  6709. break;
  6710. case 'update-all':
  6711. foreach ($this->installedMap as $package) {
  6712. $this->updateMap[$package->id] = true;
  6713. }
  6714. break;
  6715. case 'install':
  6716. if ($ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $job['packageName'])) {
  6717. break;
  6718. }
  6719. if (!$this->pool->whatProvides($job['packageName'], $job['constraint'])) {
  6720. $problem = new Problem($this->pool);
  6721. $problem->addRule(new Rule(array(), null, null, $job));
  6722. $this->problems[] = $problem;
  6723. }
  6724. break;
  6725. }
  6726. }
  6727. }
  6728. public function solve(Request $request, $ignorePlatformReqs = false)
  6729. {
  6730. $this->jobs = $request->getJobs();
  6731. $this->setupInstalledMap();
  6732. $this->rules = $this->ruleSetGenerator->getRulesFor($this->jobs, $this->installedMap, $ignorePlatformReqs);
  6733. $this->checkForRootRequireProblems($ignorePlatformReqs);
  6734. $this->decisions = new Decisions($this->pool);
  6735. $this->watchGraph = new RuleWatchGraph;
  6736. foreach ($this->rules as $rule) {
  6737. $this->watchGraph->insert(new RuleWatchNode($rule));
  6738. }
  6739. $this->makeAssertionRuleDecisions();
  6740. $this->runSat(true);
  6741. foreach ($this->installedMap as $packageId => $void) {
  6742. if ($this->decisions->undecided($packageId)) {
  6743. $this->decisions->decide(-$packageId, 1, null);
  6744. }
  6745. }
  6746. if ($this->problems) {
  6747. throw new SolverProblemsException($this->problems, $this->installedMap);
  6748. }
  6749. $transaction = new Transaction($this->policy, $this->pool, $this->installedMap, $this->decisions);
  6750. return $transaction->getOperations();
  6751. }
  6752. protected function literalFromId($id)
  6753. {
  6754. $package = $this->pool->packageById(abs($id));
  6755. return new Literal($package, $id > 0);
  6756. }
  6757. protected function propagate($level)
  6758. {
  6759. while ($this->decisions->validOffset($this->propagateIndex)) {
  6760. $decision = $this->decisions->atOffset($this->propagateIndex);
  6761. $conflict = $this->watchGraph->propagateLiteral(
  6762. $decision[Decisions::DECISION_LITERAL],
  6763. $level,
  6764. $this->decisions
  6765. );
  6766. $this->propagateIndex++;
  6767. if ($conflict) {
  6768. return $conflict;
  6769. }
  6770. }
  6771. return null;
  6772. }
  6773. private function revert($level)
  6774. {
  6775. while (!$this->decisions->isEmpty()) {
  6776. $literal = $this->decisions->lastLiteral();
  6777. if ($this->decisions->undecided($literal)) {
  6778. break;
  6779. }
  6780. $decisionLevel = $this->decisions->decisionLevel($literal);
  6781. if ($decisionLevel <= $level) {
  6782. break;
  6783. }
  6784. $this->decisions->revertLast();
  6785. $this->propagateIndex = count($this->decisions);
  6786. }
  6787. while (!empty($this->branches) && $this->branches[count($this->branches) - 1][self::BRANCH_LEVEL] >= $level) {
  6788. array_pop($this->branches);
  6789. }
  6790. }
  6791. private function setPropagateLearn($level, $literal, $disableRules, Rule $rule)
  6792. {
  6793. $level++;
  6794. $this->decisions->decide($literal, $level, $rule);
  6795. while (true) {
  6796. $rule = $this->propagate($level);
  6797. if (!$rule) {
  6798. break;
  6799. }
  6800. if ($level == 1) {
  6801. return $this->analyzeUnsolvable($rule, $disableRules);
  6802. }
  6803. list($learnLiteral, $newLevel, $newRule, $why) = $this->analyze($level, $rule);
  6804. if ($newLevel <= 0 || $newLevel >= $level) {
  6805. throw new SolverBugException(
  6806. "Trying to revert to invalid level ".(int) $newLevel." from level ".(int) $level."."
  6807. );
  6808. } elseif (!$newRule) {
  6809. throw new SolverBugException(
  6810. "No rule was learned from analyzing $rule at level $level."
  6811. );
  6812. }
  6813. $level = $newLevel;
  6814. $this->revert($level);
  6815. $this->rules->add($newRule, RuleSet::TYPE_LEARNED);
  6816. $this->learnedWhy[$newRule->getId()] = $why;
  6817. $ruleNode = new RuleWatchNode($newRule);
  6818. $ruleNode->watch2OnHighest($this->decisions);
  6819. $this->watchGraph->insert($ruleNode);
  6820. $this->decisions->decide($learnLiteral, $level, $newRule);
  6821. }
  6822. return $level;
  6823. }
  6824. private function selectAndInstall($level, array $decisionQueue, $disableRules, Rule $rule)
  6825. {
  6826. $literals = $this->policy->selectPreferedPackages($this->pool, $this->installedMap, $decisionQueue, $rule->getRequiredPackage());
  6827. $selectedLiteral = array_shift($literals);
  6828. if (count($literals)) {
  6829. $this->branches[] = array($literals, $level);
  6830. }
  6831. return $this->setPropagateLearn($level, $selectedLiteral, $disableRules, $rule);
  6832. }
  6833. protected function analyze($level, $rule)
  6834. {
  6835. $analyzedRule = $rule;
  6836. $ruleLevel = 1;
  6837. $num = 0;
  6838. $l1num = 0;
  6839. $seen = array();
  6840. $learnedLiterals = array(null);
  6841. $decisionId = count($this->decisions);
  6842. $this->learnedPool[] = array();
  6843. while (true) {
  6844. $this->learnedPool[count($this->learnedPool) - 1][] = $rule;
  6845. foreach ($rule->literals as $literal) {
  6846. if ($this->decisions->satisfy($literal)) {
  6847. continue;
  6848. }
  6849. if (isset($seen[abs($literal)])) {
  6850. continue;
  6851. }
  6852. $seen[abs($literal)] = true;
  6853. $l = $this->decisions->decisionLevel($literal);
  6854. if (1 === $l) {
  6855. $l1num++;
  6856. } elseif ($level === $l) {
  6857. $num++;
  6858. } else {
  6859. $learnedLiterals[] = $literal;
  6860. if ($l > $ruleLevel) {
  6861. $ruleLevel = $l;
  6862. }
  6863. }
  6864. }
  6865. $l1retry = true;
  6866. while ($l1retry) {
  6867. $l1retry = false;
  6868. if (!$num && !--$l1num) {
  6869. break 2;
  6870. }
  6871. while (true) {
  6872. if ($decisionId <= 0) {
  6873. throw new SolverBugException(
  6874. "Reached invalid decision id $decisionId while looking through $rule for a literal present in the analyzed rule $analyzedRule."
  6875. );
  6876. }
  6877. $decisionId--;
  6878. $decision = $this->decisions->atOffset($decisionId);
  6879. $literal = $decision[Decisions::DECISION_LITERAL];
  6880. if (isset($seen[abs($literal)])) {
  6881. break;
  6882. }
  6883. }
  6884. unset($seen[abs($literal)]);
  6885. if ($num && 0 === --$num) {
  6886. $learnedLiterals[0] = -abs($literal);
  6887. if (!$l1num) {
  6888. break 2;
  6889. }
  6890. foreach ($learnedLiterals as $i => $learnedLiteral) {
  6891. if ($i !== 0) {
  6892. unset($seen[abs($learnedLiteral)]);
  6893. }
  6894. }
  6895. $l1num++;
  6896. $l1retry = true;
  6897. }
  6898. }
  6899. $decision = $this->decisions->atOffset($decisionId);
  6900. $rule = $decision[Decisions::DECISION_REASON];
  6901. }
  6902. $why = count($this->learnedPool) - 1;
  6903. if (!$learnedLiterals[0]) {
  6904. throw new SolverBugException(
  6905. "Did not find a learnable literal in analyzed rule $analyzedRule."
  6906. );
  6907. }
  6908. $newRule = new Rule($learnedLiterals, Rule::RULE_LEARNED, $why);
  6909. return array($learnedLiterals[0], $ruleLevel, $newRule, $why);
  6910. }
  6911. private function analyzeUnsolvableRule($problem, $conflictRule)
  6912. {
  6913. $why = $conflictRule->getId();
  6914. if ($conflictRule->getType() == RuleSet::TYPE_LEARNED) {
  6915. $learnedWhy = $this->learnedWhy[$why];
  6916. $problemRules = $this->learnedPool[$learnedWhy];
  6917. foreach ($problemRules as $problemRule) {
  6918. $this->analyzeUnsolvableRule($problem, $problemRule);
  6919. }
  6920. return;
  6921. }
  6922. if ($conflictRule->getType() == RuleSet::TYPE_PACKAGE) {
  6923. return;
  6924. }
  6925. $problem->nextSection();
  6926. $problem->addRule($conflictRule);
  6927. }
  6928. private function analyzeUnsolvable($conflictRule, $disableRules)
  6929. {
  6930. $problem = new Problem($this->pool);
  6931. $problem->addRule($conflictRule);
  6932. $this->analyzeUnsolvableRule($problem, $conflictRule);
  6933. $this->problems[] = $problem;
  6934. $seen = array();
  6935. $literals = $conflictRule->literals;
  6936. foreach ($literals as $literal) {
  6937. if ($this->decisions->satisfy($literal)) {
  6938. continue;
  6939. }
  6940. $seen[abs($literal)] = true;
  6941. }
  6942. foreach ($this->decisions as $decision) {
  6943. $literal = $decision[Decisions::DECISION_LITERAL];
  6944. if (!isset($seen[abs($literal)])) {
  6945. continue;
  6946. }
  6947. $why = $decision[Decisions::DECISION_REASON];
  6948. $problem->addRule($why);
  6949. $this->analyzeUnsolvableRule($problem, $why);
  6950. $literals = $why->literals;
  6951. foreach ($literals as $literal) {
  6952. if ($this->decisions->satisfy($literal)) {
  6953. continue;
  6954. }
  6955. $seen[abs($literal)] = true;
  6956. }
  6957. }
  6958. if ($disableRules) {
  6959. foreach ($this->problems[count($this->problems) - 1] as $reason) {
  6960. $this->disableProblem($reason['rule']);
  6961. }
  6962. $this->resetSolver();
  6963. return 1;
  6964. }
  6965. return 0;
  6966. }
  6967. private function disableProblem($why)
  6968. {
  6969. $job = $why->getJob();
  6970. if (!$job) {
  6971. $why->disable();
  6972. return;
  6973. }
  6974. foreach ($this->rules as $rule) {
  6975. if ($job === $rule->getJob()) {
  6976. $rule->disable();
  6977. }
  6978. }
  6979. }
  6980. private function resetSolver()
  6981. {
  6982. $this->decisions->reset();
  6983. $this->propagateIndex = 0;
  6984. $this->branches = array();
  6985. $this->enableDisableLearnedRules();
  6986. $this->makeAssertionRuleDecisions();
  6987. }
  6988. private function enableDisableLearnedRules()
  6989. {
  6990. foreach ($this->rules->getIteratorFor(RuleSet::TYPE_LEARNED) as $rule) {
  6991. $why = $this->learnedWhy[$rule->getId()];
  6992. $problemRules = $this->learnedPool[$why];
  6993. $foundDisabled = false;
  6994. foreach ($problemRules as $problemRule) {
  6995. if ($problemRule->isDisabled()) {
  6996. $foundDisabled = true;
  6997. break;
  6998. }
  6999. }
  7000. if ($foundDisabled && $rule->isEnabled()) {
  7001. $rule->disable();
  7002. } elseif (!$foundDisabled && $rule->isDisabled()) {
  7003. $rule->enable();
  7004. }
  7005. }
  7006. }
  7007. private function runSat($disableRules = true)
  7008. {
  7009. $this->propagateIndex = 0;
  7010. $decisionQueue = array();
  7011. $decisionSupplementQueue = array();
  7012. $disableRules = array();
  7013. $level = 1;
  7014. $systemLevel = $level + 1;
  7015. $installedPos = 0;
  7016. while (true) {
  7017. if (1 === $level) {
  7018. $conflictRule = $this->propagate($level);
  7019. if (null !== $conflictRule) {
  7020. if ($this->analyzeUnsolvable($conflictRule, $disableRules)) {
  7021. continue;
  7022. }
  7023. return;
  7024. }
  7025. }
  7026. if ($level < $systemLevel) {
  7027. $iterator = $this->rules->getIteratorFor(RuleSet::TYPE_JOB);
  7028. foreach ($iterator as $rule) {
  7029. if ($rule->isEnabled()) {
  7030. $decisionQueue = array();
  7031. $noneSatisfied = true;
  7032. foreach ($rule->literals as $literal) {
  7033. if ($this->decisions->satisfy($literal)) {
  7034. $noneSatisfied = false;
  7035. break;
  7036. }
  7037. if ($literal > 0 && $this->decisions->undecided($literal)) {
  7038. $decisionQueue[] = $literal;
  7039. }
  7040. }
  7041. if ($noneSatisfied && count($decisionQueue)) {
  7042. if (count($this->installed) != count($this->updateMap)) {
  7043. $prunedQueue = array();
  7044. foreach ($decisionQueue as $literal) {
  7045. if (isset($this->installedMap[abs($literal)])) {
  7046. $prunedQueue[] = $literal;
  7047. if (isset($this->updateMap[abs($literal)])) {
  7048. $prunedQueue = $decisionQueue;
  7049. break;
  7050. }
  7051. }
  7052. }
  7053. $decisionQueue = $prunedQueue;
  7054. }
  7055. }
  7056. if ($noneSatisfied && count($decisionQueue)) {
  7057. $oLevel = $level;
  7058. $level = $this->selectAndInstall($level, $decisionQueue, $disableRules, $rule);
  7059. if (0 === $level) {
  7060. return;
  7061. }
  7062. if ($level <= $oLevel) {
  7063. break;
  7064. }
  7065. }
  7066. }
  7067. }
  7068. $systemLevel = $level + 1;
  7069. $iterator->next();
  7070. if ($iterator->valid()) {
  7071. continue;
  7072. }
  7073. }
  7074. if ($level < $systemLevel) {
  7075. $systemLevel = $level;
  7076. }
  7077. for ($i = 0, $n = 0; $n < count($this->rules); $i++, $n++) {
  7078. if ($i == count($this->rules)) {
  7079. $i = 0;
  7080. }
  7081. $rule = $this->rules->ruleById[$i];
  7082. $literals = $rule->literals;
  7083. if ($rule->isDisabled()) {
  7084. continue;
  7085. }
  7086. $decisionQueue = array();
  7087. foreach ($literals as $literal) {
  7088. if ($literal <= 0) {
  7089. if (!$this->decisions->decidedInstall(abs($literal))) {
  7090. continue 2;
  7091. }
  7092. } else {
  7093. if ($this->decisions->decidedInstall(abs($literal))) {
  7094. continue 2;
  7095. }
  7096. if ($this->decisions->undecided(abs($literal))) {
  7097. $decisionQueue[] = $literal;
  7098. }
  7099. }
  7100. }
  7101. if (count($decisionQueue) < 2) {
  7102. continue;
  7103. }
  7104. $oLevel = $level;
  7105. $level = $this->selectAndInstall($level, $decisionQueue, $disableRules, $rule);
  7106. if (0 === $level) {
  7107. return;
  7108. }
  7109. $n = -1;
  7110. }
  7111. if ($level < $systemLevel) {
  7112. continue;
  7113. }
  7114. if (count($this->branches)) {
  7115. $lastLiteral = null;
  7116. $lastLevel = null;
  7117. $lastBranchIndex = 0;
  7118. $lastBranchOffset = 0;
  7119. $l = 0;
  7120. for ($i = count($this->branches) - 1; $i >= 0; $i--) {
  7121. list($literals, $l) = $this->branches[$i];
  7122. foreach ($literals as $offset => $literal) {
  7123. if ($literal && $literal > 0 && $this->decisions->decisionLevel($literal) > $l + 1) {
  7124. $lastLiteral = $literal;
  7125. $lastBranchIndex = $i;
  7126. $lastBranchOffset = $offset;
  7127. $lastLevel = $l;
  7128. }
  7129. }
  7130. }
  7131. if ($lastLiteral) {
  7132. unset($this->branches[$lastBranchIndex][self::BRANCH_LITERALS][$lastBranchOffset]);
  7133. $level = $lastLevel;
  7134. $this->revert($level);
  7135. $why = $this->decisions->lastReason();
  7136. $oLevel = $level;
  7137. $level = $this->setPropagateLearn($level, $lastLiteral, $disableRules, $why);
  7138. if ($level == 0) {
  7139. return;
  7140. }
  7141. continue;
  7142. }
  7143. }
  7144. break;
  7145. }
  7146. }
  7147. }
  7148. <?php
  7149. namespace Composer\DependencyResolver;
  7150. class SolverBugException extends \RuntimeException
  7151. {
  7152. public function __construct($message)
  7153. {
  7154. parent::__construct(
  7155. $message."\nThis exception was most likely caused by a bug in Composer.\n".
  7156. "Please report the command you ran, the exact error you received, and your composer.json on https://github.com/composer/composer/issues - thank you!\n");
  7157. }
  7158. }
  7159. <?php
  7160. namespace Composer\DependencyResolver;
  7161. class SolverProblemsException extends \RuntimeException
  7162. {
  7163. protected $problems;
  7164. protected $installedMap;
  7165. public function __construct(array $problems, array $installedMap)
  7166. {
  7167. $this->problems = $problems;
  7168. $this->installedMap = $installedMap;
  7169. parent::__construct($this->createMessage(), 2);
  7170. }
  7171. protected function createMessage()
  7172. {
  7173. $text = "\n";
  7174. foreach ($this->problems as $i => $problem) {
  7175. $text .= " Problem ".($i+1).$problem->getPrettyString($this->installedMap)."\n";
  7176. }
  7177. if (strpos($text, 'could not be found') || strpos($text, 'no matching package found')) {
  7178. $text .= "\nPotential causes:\n - A typo in the package name\n - The package is not available in a stable-enough version according to your minimum-stability setting\n see <https://groups.google.com/d/topic/composer-dev/_g3ASeIFlrc/discussion> for more details.\n\nRead <http://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.";
  7179. }
  7180. return $text;
  7181. }
  7182. public function getProblems()
  7183. {
  7184. return $this->problems;
  7185. }
  7186. }
  7187. <?php
  7188. namespace Composer\DependencyResolver;
  7189. use Composer\Package\AliasPackage;
  7190. class Transaction
  7191. {
  7192. protected $policy;
  7193. protected $pool;
  7194. protected $installedMap;
  7195. protected $decisions;
  7196. protected $transaction;
  7197. public function __construct($policy, $pool, $installedMap, $decisions)
  7198. {
  7199. $this->policy = $policy;
  7200. $this->pool = $pool;
  7201. $this->installedMap = $installedMap;
  7202. $this->decisions = $decisions;
  7203. $this->transaction = array();
  7204. }
  7205. public function getOperations()
  7206. {
  7207. $installMeansUpdateMap = $this->findUpdates();
  7208. $updateMap = array();
  7209. $installMap = array();
  7210. $uninstallMap = array();
  7211. foreach ($this->decisions as $i => $decision) {
  7212. $literal = $decision[Decisions::DECISION_LITERAL];
  7213. $reason = $decision[Decisions::DECISION_REASON];
  7214. $package = $this->pool->literalToPackage($literal);
  7215. if (($literal > 0) == (isset($this->installedMap[$package->id]))) {
  7216. continue;
  7217. }
  7218. if ($literal > 0) {
  7219. if (isset($installMeansUpdateMap[abs($literal)]) && !$package instanceof AliasPackage) {
  7220. $source = $installMeansUpdateMap[abs($literal)];
  7221. $updateMap[$package->id] = array(
  7222. 'package' => $package,
  7223. 'source' => $source,
  7224. 'reason' => $reason,
  7225. );
  7226. unset($installMeansUpdateMap[abs($literal)]);
  7227. $ignoreRemove[$source->id] = true;
  7228. } else {
  7229. $installMap[$package->id] = array(
  7230. 'package' => $package,
  7231. 'reason' => $reason,
  7232. );
  7233. }
  7234. }
  7235. }
  7236. foreach ($this->decisions as $i => $decision) {
  7237. $literal = $decision[Decisions::DECISION_LITERAL];
  7238. $reason = $decision[Decisions::DECISION_REASON];
  7239. $package = $this->pool->literalToPackage($literal);
  7240. if ($literal <= 0 &&
  7241. isset($this->installedMap[$package->id]) &&
  7242. !isset($ignoreRemove[$package->id])) {
  7243. $uninstallMap[$package->id] = array(
  7244. 'package' => $package,
  7245. 'reason' => $reason,
  7246. );
  7247. }
  7248. }
  7249. $this->transactionFromMaps($installMap, $updateMap, $uninstallMap);
  7250. return $this->transaction;
  7251. }
  7252. protected function transactionFromMaps($installMap, $updateMap, $uninstallMap)
  7253. {
  7254. $queue = array_map(function ($operation) {
  7255. return $operation['package'];
  7256. },
  7257. $this->findRootPackages($installMap, $updateMap)
  7258. );
  7259. $visited = array();
  7260. while (!empty($queue)) {
  7261. $package = array_pop($queue);
  7262. $packageId = $package->id;
  7263. if (!isset($visited[$packageId])) {
  7264. array_push($queue, $package);
  7265. if ($package instanceof AliasPackage) {
  7266. array_push($queue, $package->getAliasOf());
  7267. } else {
  7268. foreach ($package->getRequires() as $link) {
  7269. $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
  7270. foreach ($possibleRequires as $require) {
  7271. array_push($queue, $require);
  7272. }
  7273. }
  7274. }
  7275. $visited[$package->id] = true;
  7276. } else {
  7277. if (isset($installMap[$packageId])) {
  7278. $this->install(
  7279. $installMap[$packageId]['package'],
  7280. $installMap[$packageId]['reason']
  7281. );
  7282. unset($installMap[$packageId]);
  7283. }
  7284. if (isset($updateMap[$packageId])) {
  7285. $this->update(
  7286. $updateMap[$packageId]['source'],
  7287. $updateMap[$packageId]['package'],
  7288. $updateMap[$packageId]['reason']
  7289. );
  7290. unset($updateMap[$packageId]);
  7291. }
  7292. }
  7293. }
  7294. foreach ($uninstallMap as $uninstall) {
  7295. $this->uninstall($uninstall['package'], $uninstall['reason']);
  7296. }
  7297. }
  7298. protected function findRootPackages($installMap, $updateMap)
  7299. {
  7300. $packages = $installMap + $updateMap;
  7301. $roots = $packages;
  7302. foreach ($packages as $packageId => $operation) {
  7303. $package = $operation['package'];
  7304. if (!isset($roots[$packageId])) {
  7305. continue;
  7306. }
  7307. foreach ($package->getRequires() as $link) {
  7308. $possibleRequires = $this->pool->whatProvides($link->getTarget(), $link->getConstraint());
  7309. foreach ($possibleRequires as $require) {
  7310. unset($roots[$require->id]);
  7311. }
  7312. }
  7313. }
  7314. return $roots;
  7315. }
  7316. protected function findUpdates()
  7317. {
  7318. $installMeansUpdateMap = array();
  7319. foreach ($this->decisions as $i => $decision) {
  7320. $literal = $decision[Decisions::DECISION_LITERAL];
  7321. $package = $this->pool->literalToPackage($literal);
  7322. if ($package instanceof AliasPackage) {
  7323. continue;
  7324. }
  7325. if ($literal <= 0 && isset($this->installedMap[$package->id])) {
  7326. $updates = $this->policy->findUpdatePackages($this->pool, $this->installedMap, $package);
  7327. $literals = array($package->id);
  7328. foreach ($updates as $update) {
  7329. $literals[] = $update->id;
  7330. }
  7331. foreach ($literals as $updateLiteral) {
  7332. if ($updateLiteral !== $literal) {
  7333. $installMeansUpdateMap[abs($updateLiteral)] = $package;
  7334. }
  7335. }
  7336. }
  7337. }
  7338. return $installMeansUpdateMap;
  7339. }
  7340. protected function install($package, $reason)
  7341. {
  7342. if ($package instanceof AliasPackage) {
  7343. return $this->markAliasInstalled($package, $reason);
  7344. }
  7345. $this->transaction[] = new Operation\InstallOperation($package, $reason);
  7346. }
  7347. protected function update($from, $to, $reason)
  7348. {
  7349. $this->transaction[] = new Operation\UpdateOperation($from, $to, $reason);
  7350. }
  7351. protected function uninstall($package, $reason)
  7352. {
  7353. if ($package instanceof AliasPackage) {
  7354. return $this->markAliasUninstalled($package, $reason);
  7355. }
  7356. $this->transaction[] = new Operation\UninstallOperation($package, $reason);
  7357. }
  7358. protected function markAliasInstalled($package, $reason)
  7359. {
  7360. $this->transaction[] = new Operation\MarkAliasInstalledOperation($package, $reason);
  7361. }
  7362. protected function markAliasUninstalled($package, $reason)
  7363. {
  7364. $this->transaction[] = new Operation\MarkAliasUninstalledOperation($package, $reason);
  7365. }
  7366. }
  7367. <?php
  7368. namespace Composer\Downloader;
  7369. use Composer\Package\PackageInterface;
  7370. use Symfony\Component\Finder\Finder;
  7371. abstract class ArchiveDownloader extends FileDownloader
  7372. {
  7373. public function download(PackageInterface $package, $path)
  7374. {
  7375. $temporaryDir = $this->config->get('vendor-dir').'/composer/'.substr(md5(uniqid('', true)), 0, 8);
  7376. $retries = 3;
  7377. while ($retries--) {
  7378. $fileName = parent::download($package, $path);
  7379. if ($this->io->isVerbose()) {
  7380. $this->io->writeError(' Extracting archive');
  7381. }
  7382. try {
  7383. $this->filesystem->ensureDirectoryExists($temporaryDir);
  7384. try {
  7385. $this->extract($fileName, $temporaryDir);
  7386. } catch (\Exception $e) {
  7387. parent::clearCache($package, $path);
  7388. throw $e;
  7389. }
  7390. $this->filesystem->unlink($fileName);
  7391. $contentDir = $this->getFolderContent($temporaryDir);
  7392. if (1 === count($contentDir) && is_dir(reset($contentDir))) {
  7393. $contentDir = $this->getFolderContent((string) reset($contentDir));
  7394. }
  7395. foreach ($contentDir as $file) {
  7396. $file = (string) $file;
  7397. $this->filesystem->rename($file, $path . '/' . basename($file));
  7398. }
  7399. $this->filesystem->removeDirectory($temporaryDir);
  7400. if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir').'/composer/')) {
  7401. $this->filesystem->removeDirectory($this->config->get('vendor-dir').'/composer/');
  7402. }
  7403. if ($this->filesystem->isDirEmpty($this->config->get('vendor-dir'))) {
  7404. $this->filesystem->removeDirectory($this->config->get('vendor-dir'));
  7405. }
  7406. } catch (\Exception $e) {
  7407. $this->filesystem->removeDirectory($path);
  7408. $this->filesystem->removeDirectory($temporaryDir);
  7409. if ($retries && $e instanceof \UnexpectedValueException && class_exists('ZipArchive') && $e->getCode() === \ZipArchive::ER_NOZIP) {
  7410. $this->io->writeError(' Invalid zip file, retrying...');
  7411. usleep(500000);
  7412. continue;
  7413. }
  7414. throw $e;
  7415. }
  7416. break;
  7417. }
  7418. $this->io->writeError('');
  7419. }
  7420. protected function getFileName(PackageInterface $package, $path)
  7421. {
  7422. return rtrim($path.'/'.md5($path.spl_object_hash($package)).'.'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_EXTENSION), '.');
  7423. }
  7424. protected function processUrl(PackageInterface $package, $url)
  7425. {
  7426. if ($package->getDistReference() && strpos($url, 'github.com')) {
  7427. if (preg_match('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/(zip|tar)ball/(.+)$}i', $url, $match)) {
  7428. $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $package->getDistReference();
  7429. } elseif ($package->getDistReference() && preg_match('{^https?://(?:www\.)?github\.com/([^/]+)/([^/]+)/archive/.+\.(zip|tar)(?:\.gz)?$}i', $url, $match)) {
  7430. $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $package->getDistReference();
  7431. } elseif ($package->getDistReference() && preg_match('{^https?://api\.github\.com/repos/([^/]+)/([^/]+)/(zip|tar)ball(?:/.+)?$}i', $url, $match)) {
  7432. $url = 'https://api.github.com/repos/' . $match[1] . '/'. $match[2] . '/' . $match[3] . 'ball/' . $package->getDistReference();
  7433. }
  7434. }
  7435. if (!extension_loaded('openssl') && (0 === strpos($url, 'https:') || 0 === strpos($url, 'http://github.com'))) {
  7436. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  7437. }
  7438. return parent::processUrl($package, $url);
  7439. }
  7440. abstract protected function extract($file, $path);
  7441. private function getFolderContent($dir)
  7442. {
  7443. $finder = Finder::create()
  7444. ->ignoreVCS(false)
  7445. ->ignoreDotFiles(false)
  7446. ->depth(0)
  7447. ->in($dir);
  7448. return iterator_to_array($finder);
  7449. }
  7450. }
  7451. <?php
  7452. namespace Composer\Downloader;
  7453. use Composer\Package\PackageInterface;
  7454. interface ChangeReportInterface
  7455. {
  7456. public function getLocalChanges(PackageInterface $package, $path);
  7457. }
  7458. <?php
  7459. namespace Composer\Downloader;
  7460. use Composer\Package\PackageInterface;
  7461. interface DownloaderInterface
  7462. {
  7463. public function getInstallationSource();
  7464. public function download(PackageInterface $package, $path);
  7465. public function update(PackageInterface $initial, PackageInterface $target, $path);
  7466. public function remove(PackageInterface $package, $path);
  7467. public function setOutputProgress($outputProgress);
  7468. }
  7469. <?php
  7470. namespace Composer\Downloader;
  7471. use Composer\Package\PackageInterface;
  7472. use Composer\IO\IOInterface;
  7473. use Composer\Util\Filesystem;
  7474. class DownloadManager
  7475. {
  7476. private $io;
  7477. private $preferDist = false;
  7478. private $preferSource = false;
  7479. private $filesystem;
  7480. private $downloaders = array();
  7481. public function __construct(IOInterface $io, $preferSource = false, Filesystem $filesystem = null)
  7482. {
  7483. $this->io = $io;
  7484. $this->preferSource = $preferSource;
  7485. $this->filesystem = $filesystem ?: new Filesystem();
  7486. }
  7487. public function setPreferSource($preferSource)
  7488. {
  7489. $this->preferSource = $preferSource;
  7490. return $this;
  7491. }
  7492. public function setPreferDist($preferDist)
  7493. {
  7494. $this->preferDist = $preferDist;
  7495. return $this;
  7496. }
  7497. public function setOutputProgress($outputProgress)
  7498. {
  7499. foreach ($this->downloaders as $downloader) {
  7500. $downloader->setOutputProgress($outputProgress);
  7501. }
  7502. return $this;
  7503. }
  7504. public function setDownloader($type, DownloaderInterface $downloader)
  7505. {
  7506. $type = strtolower($type);
  7507. $this->downloaders[$type] = $downloader;
  7508. return $this;
  7509. }
  7510. public function getDownloader($type)
  7511. {
  7512. $type = strtolower($type);
  7513. if (!isset($this->downloaders[$type])) {
  7514. throw new \InvalidArgumentException(sprintf('Unknown downloader type: %s. Available types: %s.', $type, implode(', ', array_keys($this->downloaders))));
  7515. }
  7516. return $this->downloaders[$type];
  7517. }
  7518. public function getDownloaderForInstalledPackage(PackageInterface $package)
  7519. {
  7520. $installationSource = $package->getInstallationSource();
  7521. if ('metapackage' === $package->getType()) {
  7522. return;
  7523. }
  7524. if ('dist' === $installationSource) {
  7525. $downloader = $this->getDownloader($package->getDistType());
  7526. } elseif ('source' === $installationSource) {
  7527. $downloader = $this->getDownloader($package->getSourceType());
  7528. } else {
  7529. throw new \InvalidArgumentException(
  7530. 'Package '.$package.' seems not been installed properly'
  7531. );
  7532. }
  7533. if ($installationSource !== $downloader->getInstallationSource()) {
  7534. throw new \LogicException(sprintf(
  7535. 'Downloader "%s" is a %s type downloader and can not be used to download %s',
  7536. get_class($downloader), $downloader->getInstallationSource(), $installationSource
  7537. ));
  7538. }
  7539. return $downloader;
  7540. }
  7541. public function download(PackageInterface $package, $targetDir, $preferSource = null)
  7542. {
  7543. $preferSource = null !== $preferSource ? $preferSource : $this->preferSource;
  7544. $sourceType = $package->getSourceType();
  7545. $distType = $package->getDistType();
  7546. $sources = array();
  7547. if ($sourceType) {
  7548. $sources[] = 'source';
  7549. }
  7550. if ($distType) {
  7551. $sources[] = 'dist';
  7552. }
  7553. if (empty($sources)) {
  7554. throw new \InvalidArgumentException('Package '.$package.' must have a source or dist specified');
  7555. }
  7556. if ((!$package->isDev() || $this->preferDist) && !$preferSource) {
  7557. $sources = array_reverse($sources);
  7558. }
  7559. $this->filesystem->ensureDirectoryExists($targetDir);
  7560. foreach ($sources as $i => $source) {
  7561. if (isset($e)) {
  7562. $this->io->writeError(' <warning>Now trying to download from ' . $source . '</warning>');
  7563. }
  7564. $package->setInstallationSource($source);
  7565. try {
  7566. $downloader = $this->getDownloaderForInstalledPackage($package);
  7567. if ($downloader) {
  7568. $downloader->download($package, $targetDir);
  7569. }
  7570. break;
  7571. } catch (\RuntimeException $e) {
  7572. if ($i === count($sources) - 1) {
  7573. throw $e;
  7574. }
  7575. $this->io->writeError(
  7576. ' <warning>Failed to download '.
  7577. $package->getPrettyName().
  7578. ' from ' . $source . ': '.
  7579. $e->getMessage().'</warning>'
  7580. );
  7581. }
  7582. }
  7583. }
  7584. public function update(PackageInterface $initial, PackageInterface $target, $targetDir)
  7585. {
  7586. $downloader = $this->getDownloaderForInstalledPackage($initial);
  7587. if (!$downloader) {
  7588. return;
  7589. }
  7590. $installationSource = $initial->getInstallationSource();
  7591. if ('dist' === $installationSource) {
  7592. $initialType = $initial->getDistType();
  7593. $targetType = $target->getDistType();
  7594. } else {
  7595. $initialType = $initial->getSourceType();
  7596. $targetType = $target->getSourceType();
  7597. }
  7598. if ($target->isDev() && 'dist' === $installationSource) {
  7599. $downloader->remove($initial, $targetDir);
  7600. $this->download($target, $targetDir);
  7601. return;
  7602. }
  7603. if ($initialType === $targetType) {
  7604. $target->setInstallationSource($installationSource);
  7605. $downloader->update($initial, $target, $targetDir);
  7606. } else {
  7607. $downloader->remove($initial, $targetDir);
  7608. $this->download($target, $targetDir, 'source' === $installationSource);
  7609. }
  7610. }
  7611. public function remove(PackageInterface $package, $targetDir)
  7612. {
  7613. $downloader = $this->getDownloaderForInstalledPackage($package);
  7614. if ($downloader) {
  7615. $downloader->remove($package, $targetDir);
  7616. }
  7617. }
  7618. }
  7619. <?php
  7620. namespace Composer\Downloader;
  7621. use Composer\Config;
  7622. use Composer\Cache;
  7623. use Composer\IO\IOInterface;
  7624. use Composer\Package\PackageInterface;
  7625. use Composer\Package\Version\VersionParser;
  7626. use Composer\Plugin\PluginEvents;
  7627. use Composer\Plugin\PreFileDownloadEvent;
  7628. use Composer\EventDispatcher\EventDispatcher;
  7629. use Composer\Util\Filesystem;
  7630. use Composer\Util\RemoteFilesystem;
  7631. class FileDownloader implements DownloaderInterface
  7632. {
  7633. protected $io;
  7634. protected $config;
  7635. protected $rfs;
  7636. protected $filesystem;
  7637. protected $cache;
  7638. protected $outputProgress = true;
  7639. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, RemoteFilesystem $rfs = null, Filesystem $filesystem = null)
  7640. {
  7641. $this->io = $io;
  7642. $this->config = $config;
  7643. $this->eventDispatcher = $eventDispatcher;
  7644. $this->rfs = $rfs ?: new RemoteFilesystem($io, $config);
  7645. $this->filesystem = $filesystem ?: new Filesystem();
  7646. $this->cache = $cache;
  7647. if ($this->cache && $this->cache->gcIsNecessary()) {
  7648. $this->cache->gc($config->get('cache-files-ttl'), $config->get('cache-files-maxsize'));
  7649. }
  7650. }
  7651. public function getInstallationSource()
  7652. {
  7653. return 'dist';
  7654. }
  7655. public function download(PackageInterface $package, $path)
  7656. {
  7657. if (!$package->getDistUrl()) {
  7658. throw new \InvalidArgumentException('The given package is missing url information');
  7659. }
  7660. $this->io->writeError(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
  7661. $urls = $package->getDistUrls();
  7662. while ($url = array_shift($urls)) {
  7663. try {
  7664. return $this->doDownload($package, $path, $url);
  7665. } catch (\Exception $e) {
  7666. if ($this->io->isDebug()) {
  7667. $this->io->writeError('');
  7668. $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getCode().': '.$e->getMessage());
  7669. } elseif (count($urls)) {
  7670. $this->io->writeError('');
  7671. $this->io->writeError(' Failed, trying the next URL ('.$e->getCode().': '.$e->getMessage().')');
  7672. }
  7673. if (!count($urls)) {
  7674. throw $e;
  7675. }
  7676. }
  7677. }
  7678. $this->io->writeError('');
  7679. }
  7680. protected function doDownload(PackageInterface $package, $path, $url)
  7681. {
  7682. $this->filesystem->emptyDirectory($path);
  7683. $fileName = $this->getFileName($package, $path);
  7684. $processedUrl = $this->processUrl($package, $url);
  7685. $hostname = parse_url($processedUrl, PHP_URL_HOST);
  7686. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $processedUrl);
  7687. if ($this->eventDispatcher) {
  7688. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  7689. }
  7690. $rfs = $preFileDownloadEvent->getRemoteFilesystem();
  7691. try {
  7692. $checksum = $package->getDistSha1Checksum();
  7693. $cacheKey = $this->getCacheKey($package);
  7694. if (!$this->cache || ($checksum && $checksum !== $this->cache->sha1($cacheKey)) || !$this->cache->copyTo($cacheKey, $fileName)) {
  7695. if (!$this->outputProgress) {
  7696. $this->io->writeError(' Downloading');
  7697. }
  7698. $retries = 3;
  7699. while ($retries--) {
  7700. try {
  7701. $rfs->copy($hostname, $processedUrl, $fileName, $this->outputProgress, $package->getTransportOptions());
  7702. break;
  7703. } catch (TransportException $e) {
  7704. if ((0 !== $e->getCode() && !in_array($e->getCode(),array(500, 502, 503, 504))) || !$retries) {
  7705. throw $e;
  7706. }
  7707. if ($this->io->isVerbose()) {
  7708. $this->io->writeError(' Download failed, retrying...');
  7709. }
  7710. usleep(500000);
  7711. }
  7712. }
  7713. if ($this->cache) {
  7714. $this->cache->copyFrom($cacheKey, $fileName);
  7715. }
  7716. } else {
  7717. $this->io->writeError(' Loading from cache');
  7718. }
  7719. if (!file_exists($fileName)) {
  7720. throw new \UnexpectedValueException($url.' could not be saved to '.$fileName.', make sure the'
  7721. .' directory is writable and you have internet connectivity');
  7722. }
  7723. if ($checksum && hash_file('sha1', $fileName) !== $checksum) {
  7724. throw new \UnexpectedValueException('The checksum verification of the file failed (downloaded from '.$url.')');
  7725. }
  7726. } catch (\Exception $e) {
  7727. $this->filesystem->removeDirectory($path);
  7728. $this->clearCache($package, $path);
  7729. throw $e;
  7730. }
  7731. return $fileName;
  7732. }
  7733. public function setOutputProgress($outputProgress)
  7734. {
  7735. $this->outputProgress = $outputProgress;
  7736. return $this;
  7737. }
  7738. protected function clearCache(PackageInterface $package, $path)
  7739. {
  7740. if ($this->cache) {
  7741. $fileName = $this->getFileName($package, $path);
  7742. $this->cache->remove($this->getCacheKey($package));
  7743. }
  7744. }
  7745. public function update(PackageInterface $initial, PackageInterface $target, $path)
  7746. {
  7747. $this->remove($initial, $path);
  7748. $this->download($target, $path);
  7749. }
  7750. public function remove(PackageInterface $package, $path)
  7751. {
  7752. $this->io->writeError(" - Removing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
  7753. if (!$this->filesystem->removeDirectory($path)) {
  7754. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  7755. }
  7756. }
  7757. protected function getFileName(PackageInterface $package, $path)
  7758. {
  7759. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  7760. }
  7761. protected function processUrl(PackageInterface $package, $url)
  7762. {
  7763. if (!extension_loaded('openssl') && 0 === strpos($url, 'https:')) {
  7764. throw new \RuntimeException('You must enable the openssl extension to download files via https');
  7765. }
  7766. return $url;
  7767. }
  7768. private function getCacheKey(PackageInterface $package)
  7769. {
  7770. if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) {
  7771. return $package->getName().'/'.$package->getDistReference().'.'.$package->getDistType();
  7772. }
  7773. return $package->getName().'/'.$package->getVersion().'-'.$package->getDistReference().'.'.$package->getDistType();
  7774. }
  7775. }
  7776. <?php
  7777. namespace Composer\Downloader;
  7778. class FilesystemException extends \Exception
  7779. {
  7780. public function __construct($message = null, $code = null, \Exception $previous = null)
  7781. {
  7782. parent::__construct("Filesystem exception: \n".$message, $code, $previous);
  7783. }
  7784. }
  7785. <?php
  7786. namespace Composer\Downloader;
  7787. use Composer\Package\PackageInterface;
  7788. use Composer\Util\GitHub;
  7789. use Composer\Util\Git as GitUtil;
  7790. use Composer\Util\ProcessExecutor;
  7791. use Composer\IO\IOInterface;
  7792. use Composer\Util\Filesystem;
  7793. use Composer\Config;
  7794. class GitDownloader extends VcsDownloader
  7795. {
  7796. private $hasStashedChanges = false;
  7797. private $gitUtil;
  7798. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null)
  7799. {
  7800. parent::__construct($io, $config, $process, $fs);
  7801. $this->gitUtil = new GitUtil($this->io, $this->config, $this->process, $this->filesystem);
  7802. }
  7803. public function doDownload(PackageInterface $package, $path, $url)
  7804. {
  7805. GitUtil::cleanEnv();
  7806. $path = $this->normalizePath($path);
  7807. $ref = $package->getSourceReference();
  7808. $flag = defined('PHP_WINDOWS_VERSION_MAJOR') ? '/D ' : '';
  7809. $command = 'git clone --no-checkout %s %s && cd '.$flag.'%2$s && git remote add composer %1$s && git fetch composer';
  7810. $this->io->writeError(" Cloning ".$ref);
  7811. $commandCallable = function ($url) use ($ref, $path, $command) {
  7812. return sprintf($command, ProcessExecutor::escape($url), ProcessExecutor::escape($path), ProcessExecutor::escape($ref));
  7813. };
  7814. $this->gitUtil->runCommand($commandCallable, $url, $path, true);
  7815. if ($url !== $package->getSourceUrl()) {
  7816. $url = $package->getSourceUrl();
  7817. $this->process->execute(sprintf('git remote set-url origin %s', ProcessExecutor::escape($url)), $output, $path);
  7818. }
  7819. $this->setPushUrl($path, $url);
  7820. if ($newRef = $this->updateToCommit($path, $ref, $package->getPrettyVersion(), $package->getReleaseDate())) {
  7821. if ($package->getDistReference() === $package->getSourceReference()) {
  7822. $package->setDistReference($newRef);
  7823. }
  7824. $package->setSourceReference($newRef);
  7825. }
  7826. }
  7827. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  7828. {
  7829. GitUtil::cleanEnv();
  7830. $path = $this->normalizePath($path);
  7831. if (!is_dir($path.'/.git')) {
  7832. throw new \RuntimeException('The .git directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
  7833. }
  7834. $ref = $target->getSourceReference();
  7835. $this->io->writeError(" Checking out ".$ref);
  7836. $command = 'git remote set-url composer %s && git fetch composer && git fetch --tags composer';
  7837. $commandCallable = function ($url) use ($command) {
  7838. return sprintf($command, ProcessExecutor::escape ($url));
  7839. };
  7840. $this->gitUtil->runCommand($commandCallable, $url, $path);
  7841. if ($newRef = $this->updateToCommit($path, $ref, $target->getPrettyVersion(), $target->getReleaseDate())) {
  7842. if ($target->getDistReference() === $target->getSourceReference()) {
  7843. $target->setDistReference($newRef);
  7844. }
  7845. $target->setSourceReference($newRef);
  7846. }
  7847. }
  7848. public function getLocalChanges(PackageInterface $package, $path)
  7849. {
  7850. GitUtil::cleanEnv();
  7851. $path = $this->normalizePath($path);
  7852. if (!is_dir($path.'/.git')) {
  7853. return;
  7854. }
  7855. $command = 'git status --porcelain --untracked-files=no';
  7856. if (0 !== $this->process->execute($command, $output, $path)) {
  7857. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  7858. }
  7859. return trim($output) ?: null;
  7860. }
  7861. protected function cleanChanges(PackageInterface $package, $path, $update)
  7862. {
  7863. GitUtil::cleanEnv();
  7864. $path = $this->normalizePath($path);
  7865. if (!$changes = $this->getLocalChanges($package, $path)) {
  7866. return;
  7867. }
  7868. if (!$this->io->isInteractive()) {
  7869. $discardChanges = $this->config->get('discard-changes');
  7870. if (true === $discardChanges) {
  7871. return $this->discardChanges($path);
  7872. }
  7873. if ('stash' === $discardChanges) {
  7874. if (!$update) {
  7875. return parent::cleanChanges($package, $path, $update);
  7876. }
  7877. return $this->stashChanges($path);
  7878. }
  7879. return parent::cleanChanges($package, $path, $update);
  7880. }
  7881. $changes = array_map(function ($elem) {
  7882. return ' '.$elem;
  7883. }, preg_split('{\s*\r?\n\s*}', $changes));
  7884. $this->io->writeError(' <error>The package has modified files:</error>');
  7885. $this->io->writeError(array_slice($changes, 0, 10));
  7886. if (count($changes) > 10) {
  7887. $this->io->writeError(' <info>'.count($changes) - 10 . ' more files modified, choose "v" to view the full list</info>');
  7888. }
  7889. while (true) {
  7890. switch ($this->io->ask(' <info>Discard changes [y,n,v,'.($update ? 's,' : '').'?]?</info> ', '?')) {
  7891. case 'y':
  7892. $this->discardChanges($path);
  7893. break 2;
  7894. case 's':
  7895. if (!$update) {
  7896. goto help;
  7897. }
  7898. $this->stashChanges($path);
  7899. break 2;
  7900. case 'n':
  7901. throw new \RuntimeException('Update aborted');
  7902. case 'v':
  7903. $this->io->writeError($changes);
  7904. break;
  7905. case '?':
  7906. default:
  7907. help:
  7908. $this->io->writeError(array(
  7909. ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
  7910. ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
  7911. ' v - view modified files',
  7912. ));
  7913. if ($update) {
  7914. $this->io->writeError(' s - stash changes and try to reapply them after the update');
  7915. }
  7916. $this->io->writeError(' ? - print help');
  7917. break;
  7918. }
  7919. }
  7920. }
  7921. protected function reapplyChanges($path)
  7922. {
  7923. $path = $this->normalizePath($path);
  7924. if ($this->hasStashedChanges) {
  7925. $this->hasStashedChanges = false;
  7926. $this->io->writeError(' <info>Re-applying stashed changes</info>');
  7927. if (0 !== $this->process->execute('git stash pop', $output, $path)) {
  7928. throw new \RuntimeException("Failed to apply stashed changes:\n\n".$this->process->getErrorOutput());
  7929. }
  7930. }
  7931. }
  7932. protected function updateToCommit($path, $reference, $branch, $date)
  7933. {
  7934. $template = 'git checkout %s && git reset --hard %1$s';
  7935. $branch = preg_replace('{(?:^dev-|(?:\.x)?-dev$)}i', '', $branch);
  7936. $branches = null;
  7937. if (0 === $this->process->execute('git branch -r', $output, $path)) {
  7938. $branches = $output;
  7939. }
  7940. $gitRef = $reference;
  7941. if (!preg_match('{^[a-f0-9]{40}$}', $reference)
  7942. && $branches
  7943. && preg_match('{^\s+composer/'.preg_quote($reference).'$}m', $branches)
  7944. ) {
  7945. $command = sprintf('git checkout -B %s %s && git reset --hard %2$s', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$reference));
  7946. if (0 === $this->process->execute($command, $output, $path)) {
  7947. return;
  7948. }
  7949. }
  7950. if (preg_match('{^[a-f0-9]{40}$}', $reference)) {
  7951. if (!preg_match('{^\s+composer/'.preg_quote($branch).'$}m', $branches) && preg_match('{^\s+composer/v'.preg_quote($branch).'$}m', $branches)) {
  7952. $branch = 'v' . $branch;
  7953. }
  7954. $command = sprintf('git checkout %s', ProcessExecutor::escape($branch));
  7955. $fallbackCommand = sprintf('git checkout -B %s %s', ProcessExecutor::escape($branch), ProcessExecutor::escape('composer/'.$branch));
  7956. if (0 === $this->process->execute($command, $output, $path)
  7957. || 0 === $this->process->execute($fallbackCommand, $output, $path)
  7958. ) {
  7959. $command = sprintf('git reset --hard %s', ProcessExecutor::escape($reference));
  7960. if (0 === $this->process->execute($command, $output, $path)) {
  7961. return;
  7962. }
  7963. }
  7964. }
  7965. $command = sprintf($template, ProcessExecutor::escape($gitRef));
  7966. if (0 === $this->process->execute($command, $output, $path)) {
  7967. return;
  7968. }
  7969. if (false !== strpos($this->process->getErrorOutput(), $reference)) {
  7970. $this->io->writeError(' <warning>'.$reference.' is gone (history was rewritten?)</warning>');
  7971. }
  7972. throw new \RuntimeException('Failed to execute ' . GitUtil::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput());
  7973. }
  7974. protected function setPushUrl($path, $url)
  7975. {
  7976. if (preg_match('{^(?:https?|git)://'.GitUtil::getGitHubDomainsRegex($this->config).'/([^/]+)/([^/]+?)(?:\.git)?$}', $url, $match)) {
  7977. $protocols = $this->config->get('github-protocols');
  7978. $pushUrl = 'git@'.$match[1].':'.$match[2].'/'.$match[3].'.git';
  7979. if ($protocols[0] !== 'git') {
  7980. $pushUrl = 'https://' . $match[1] . '/'.$match[2].'/'.$match[3].'.git';
  7981. }
  7982. $cmd = sprintf('git remote set-url --push origin %s', ProcessExecutor::escape($pushUrl));
  7983. $this->process->execute($cmd, $ignoredOutput, $path);
  7984. }
  7985. }
  7986. protected function getCommitLogs($fromReference, $toReference, $path)
  7987. {
  7988. $path = $this->normalizePath($path);
  7989. $command = sprintf('git log %s..%s --pretty=format:"%%h - %%an: %%s"', $fromReference, $toReference);
  7990. if (0 !== $this->process->execute($command, $output, $path)) {
  7991. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  7992. }
  7993. return $output;
  7994. }
  7995. protected function discardChanges($path)
  7996. {
  7997. $path = $this->normalizePath($path);
  7998. if (0 !== $this->process->execute('git reset --hard', $output, $path)) {
  7999. throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
  8000. }
  8001. }
  8002. protected function stashChanges($path)
  8003. {
  8004. $path = $this->normalizePath($path);
  8005. if (0 !== $this->process->execute('git stash', $output, $path)) {
  8006. throw new \RuntimeException("Could not stash changes\n\n:".$this->process->getErrorOutput());
  8007. }
  8008. $this->hasStashedChanges = true;
  8009. }
  8010. protected function normalizePath($path)
  8011. {
  8012. if (defined('PHP_WINDOWS_VERSION_MAJOR') && strlen($path) > 0) {
  8013. $basePath = $path;
  8014. $removed = array();
  8015. while (!is_dir($basePath) && $basePath !== '\\') {
  8016. array_unshift($removed, basename($basePath));
  8017. $basePath = dirname($basePath);
  8018. }
  8019. if ($basePath === '\\') {
  8020. return $path;
  8021. }
  8022. $path = rtrim(realpath($basePath) . '/' . implode('/', $removed), '/');
  8023. }
  8024. return $path;
  8025. }
  8026. }
  8027. <?php
  8028. namespace Composer\Downloader;
  8029. use Composer\Config;
  8030. use Composer\Cache;
  8031. use Composer\EventDispatcher\EventDispatcher;
  8032. use Composer\Package\PackageInterface;
  8033. use Composer\Util\ProcessExecutor;
  8034. use Composer\IO\IOInterface;
  8035. class GzipDownloader extends ArchiveDownloader
  8036. {
  8037. protected $process;
  8038. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
  8039. {
  8040. $this->process = $process ?: new ProcessExecutor($io);
  8041. parent::__construct($io, $config, $eventDispatcher, $cache);
  8042. }
  8043. protected function extract($file, $path)
  8044. {
  8045. $targetFilepath = $path . DIRECTORY_SEPARATOR . basename(substr($file, 0, -3));
  8046. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  8047. $command = 'gzip -cd ' . ProcessExecutor::escape($file) . ' > ' . ProcessExecutor::escape($targetFilepath);
  8048. if (0 === $this->process->execute($command, $ignoredOutput)) {
  8049. return;
  8050. }
  8051. $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
  8052. throw new \RuntimeException($processError);
  8053. }
  8054. $archiveFile = gzopen($file, 'rb');
  8055. $targetFile = fopen($targetFilepath, 'wb');
  8056. while ($string = gzread($archiveFile, 4096)) {
  8057. fwrite($targetFile, $string, strlen($string));
  8058. }
  8059. gzclose($archiveFile);
  8060. fclose($targetFile);
  8061. }
  8062. protected function getFileName(PackageInterface $package, $path)
  8063. {
  8064. return $path.'/'.pathinfo(parse_url($package->getDistUrl(), PHP_URL_PATH), PATHINFO_BASENAME);
  8065. }
  8066. }
  8067. <?php
  8068. namespace Composer\Downloader;
  8069. use Composer\Package\PackageInterface;
  8070. use Composer\Util\ProcessExecutor;
  8071. class HgDownloader extends VcsDownloader
  8072. {
  8073. public function doDownload(PackageInterface $package, $path, $url)
  8074. {
  8075. $url = ProcessExecutor::escape($url);
  8076. $ref = ProcessExecutor::escape($package->getSourceReference());
  8077. $this->io->writeError(" Cloning ".$package->getSourceReference());
  8078. $command = sprintf('hg clone %s %s', $url, ProcessExecutor::escape($path));
  8079. if (0 !== $this->process->execute($command, $ignoredOutput)) {
  8080. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  8081. }
  8082. $command = sprintf('hg up %s', $ref);
  8083. if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) {
  8084. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  8085. }
  8086. }
  8087. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  8088. {
  8089. $url = ProcessExecutor::escape($url);
  8090. $ref = ProcessExecutor::escape($target->getSourceReference());
  8091. $this->io->writeError(" Updating to ".$target->getSourceReference());
  8092. if (!is_dir($path.'/.hg')) {
  8093. throw new \RuntimeException('The .hg directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
  8094. }
  8095. $command = sprintf('hg pull %s && hg up %s', $url, $ref);
  8096. if (0 !== $this->process->execute($command, $ignoredOutput, realpath($path))) {
  8097. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  8098. }
  8099. }
  8100. public function getLocalChanges(PackageInterface $package, $path)
  8101. {
  8102. if (!is_dir($path.'/.hg')) {
  8103. return;
  8104. }
  8105. $this->process->execute('hg st', $output, realpath($path));
  8106. return trim($output) ?: null;
  8107. }
  8108. protected function getCommitLogs($fromReference, $toReference, $path)
  8109. {
  8110. $command = sprintf('hg log -r %s:%s --style compact', $fromReference, $toReference);
  8111. if (0 !== $this->process->execute($command, $output, realpath($path))) {
  8112. throw new \RuntimeException('Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput());
  8113. }
  8114. return $output;
  8115. }
  8116. }
  8117. <?php
  8118. namespace Composer\Downloader;
  8119. use Composer\Util\Filesystem;
  8120. class PearPackageExtractor
  8121. {
  8122. private static $rolesWithoutPackageNamePrefix = array('php', 'script', 'www');
  8123. private $filesystem;
  8124. private $file;
  8125. public function __construct($file)
  8126. {
  8127. if (!is_file($file)) {
  8128. throw new \UnexpectedValueException('PEAR package file is not found at '.$file);
  8129. }
  8130. $this->filesystem = new Filesystem();
  8131. $this->file = $file;
  8132. }
  8133. public function extractTo($target, array $roles = array('php' => '/', 'script' => '/bin'), $vars = array())
  8134. {
  8135. $extractionPath = $target.'/tarball';
  8136. try {
  8137. $archive = new \PharData($this->file);
  8138. $archive->extractTo($extractionPath, null, true);
  8139. if (!is_file($this->combine($extractionPath, '/package.xml'))) {
  8140. throw new \RuntimeException('Invalid PEAR package. It must contain package.xml file.');
  8141. }
  8142. $fileCopyActions = $this->buildCopyActions($extractionPath, $roles, $vars);
  8143. $this->copyFiles($fileCopyActions, $extractionPath, $target, $roles, $vars);
  8144. $this->filesystem->removeDirectory($extractionPath);
  8145. } catch (\Exception $exception) {
  8146. throw new \UnexpectedValueException(sprintf('Failed to extract PEAR package %s to %s. Reason: %s', $this->file, $target, $exception->getMessage()), 0, $exception);
  8147. }
  8148. }
  8149. private function copyFiles($files, $source, $target, $roles, $vars)
  8150. {
  8151. foreach ($files as $file) {
  8152. $from = $this->combine($source, $file['from']);
  8153. $to = $this->combine($target, $roles[$file['role']]);
  8154. $to = $this->combine($to, $file['to']);
  8155. $tasks = $file['tasks'];
  8156. $this->copyFile($from, $to, $tasks, $vars);
  8157. }
  8158. }
  8159. private function copyFile($from, $to, $tasks, $vars)
  8160. {
  8161. if (!is_file($from)) {
  8162. throw new \RuntimeException('Invalid PEAR package. package.xml defines file that is not located inside tarball.');
  8163. }
  8164. $this->filesystem->ensureDirectoryExists(dirname($to));
  8165. if (0 == count($tasks)) {
  8166. $copied = copy($from, $to);
  8167. } else {
  8168. $content = file_get_contents($from);
  8169. $replacements = array();
  8170. foreach ($tasks as $task) {
  8171. $pattern = $task['from'];
  8172. $varName = $task['to'];
  8173. if (isset($vars[$varName])) {
  8174. if ($varName === 'php_bin' && false === strpos($to, '.bat')) {
  8175. $replacements[$pattern] = preg_replace('{\.bat$}', '', $vars[$varName]);
  8176. } else {
  8177. $replacements[$pattern] = $vars[$varName];
  8178. }
  8179. }
  8180. }
  8181. $content = strtr($content, $replacements);
  8182. $copied = file_put_contents($to, $content);
  8183. }
  8184. if (false === $copied) {
  8185. throw new \RuntimeException(sprintf('Failed to copy %s to %s', $from, $to));
  8186. }
  8187. }
  8188. private function buildCopyActions($source, array $roles, $vars)
  8189. {
  8190. $package = simplexml_load_file($this->combine($source, 'package.xml'));
  8191. if (false === $package) {
  8192. throw new \RuntimeException('Package definition file is not valid.');
  8193. }
  8194. $packageSchemaVersion = $package['version'];
  8195. if ('1.0' == $packageSchemaVersion) {
  8196. $children = $package->release->filelist->children();
  8197. $packageName = (string) $package->name;
  8198. $packageVersion = (string) $package->release->version;
  8199. $sourceDir = $packageName . '-' . $packageVersion;
  8200. $result = $this->buildSourceList10($children, $roles, $sourceDir, '', null, $packageName);
  8201. } elseif ('2.0' == $packageSchemaVersion || '2.1' == $packageSchemaVersion) {
  8202. $children = $package->contents->children();
  8203. $packageName = (string) $package->name;
  8204. $packageVersion = (string) $package->version->release;
  8205. $sourceDir = $packageName . '-' . $packageVersion;
  8206. $result = $this->buildSourceList20($children, $roles, $sourceDir, '', null, $packageName);
  8207. $namespaces = $package->getNamespaces();
  8208. $package->registerXPathNamespace('ns', $namespaces['']);
  8209. $releaseNodes = $package->xpath('ns:phprelease');
  8210. $this->applyRelease($result, $releaseNodes, $vars);
  8211. } else {
  8212. throw new \RuntimeException('Unsupported schema version of package definition file.');
  8213. }
  8214. return $result;
  8215. }
  8216. private function applyRelease(&$actions, $releaseNodes, $vars)
  8217. {
  8218. foreach ($releaseNodes as $releaseNode) {
  8219. $requiredOs = $releaseNode->installconditions && $releaseNode->installconditions->os && $releaseNode->installconditions->os->name ? (string) $releaseNode->installconditions->os->name : '';
  8220. if ($requiredOs && $vars['os'] != $requiredOs) {
  8221. continue;
  8222. }
  8223. if ($releaseNode->filelist) {
  8224. foreach ($releaseNode->filelist->children() as $action) {
  8225. if ('install' == $action->getName()) {
  8226. $name = (string) $action['name'];
  8227. $as = (string) $action['as'];
  8228. if (isset($actions[$name])) {
  8229. $actions[$name]['to'] = $as;
  8230. }
  8231. } elseif ('ignore' == $action->getName()) {
  8232. $name = (string) $action['name'];
  8233. unset($actions[$name]);
  8234. } else {
  8235. }
  8236. }
  8237. }
  8238. break;
  8239. }
  8240. }
  8241. private function buildSourceList10($children, $targetRoles, $source, $target, $role, $packageName)
  8242. {
  8243. $result = array();
  8244. foreach ($children as $child) {
  8245. if ($child->getName() == 'dir') {
  8246. $dirSource = $this->combine($source, (string) $child['name']);
  8247. $dirTarget = $child['baseinstalldir'] ?: $target;
  8248. $dirRole = $child['role'] ?: $role;
  8249. $dirFiles = $this->buildSourceList10($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName);
  8250. $result = array_merge($result, $dirFiles);
  8251. } elseif ($child->getName() == 'file') {
  8252. $fileRole = (string) $child['role'] ?: $role;
  8253. if (isset($targetRoles[$fileRole])) {
  8254. $fileName = (string) ($child['name'] ?: $child[0]);
  8255. $fileSource = $this->combine($source, $fileName);
  8256. $fileTarget = $this->combine((string) $child['baseinstalldir'] ?: $target, $fileName);
  8257. if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) {
  8258. $fileTarget = $packageName . '/' . $fileTarget;
  8259. }
  8260. $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => array());
  8261. }
  8262. }
  8263. }
  8264. return $result;
  8265. }
  8266. private function buildSourceList20($children, $targetRoles, $source, $target, $role, $packageName)
  8267. {
  8268. $result = array();
  8269. foreach ($children as $child) {
  8270. if ('dir' == $child->getName()) {
  8271. $dirSource = $this->combine($source, $child['name']);
  8272. $dirTarget = $child['baseinstalldir'] ?: $target;
  8273. $dirRole = $child['role'] ?: $role;
  8274. $dirFiles = $this->buildSourceList20($child->children(), $targetRoles, $dirSource, $dirTarget, $dirRole, $packageName);
  8275. $result = array_merge($result, $dirFiles);
  8276. } elseif ('file' == $child->getName()) {
  8277. $fileRole = (string) $child['role'] ?: $role;
  8278. if (isset($targetRoles[$fileRole])) {
  8279. $fileSource = $this->combine($source, (string) $child['name']);
  8280. $fileTarget = $this->combine((string) ($child['baseinstalldir'] ?: $target), (string) $child['name']);
  8281. $fileTasks = array();
  8282. foreach ($child->children('http://pear.php.net/dtd/tasks-1.0') as $taskNode) {
  8283. if ('replace' == $taskNode->getName()) {
  8284. $fileTasks[] = array('from' => (string) $taskNode->attributes()->from, 'to' => (string) $taskNode->attributes()->to);
  8285. }
  8286. }
  8287. if (!in_array($fileRole, self::$rolesWithoutPackageNamePrefix)) {
  8288. $fileTarget = $packageName . '/' . $fileTarget;
  8289. }
  8290. $result[(string) $child['name']] = array('from' => $fileSource, 'to' => $fileTarget, 'role' => $fileRole, 'tasks' => $fileTasks);
  8291. }
  8292. }
  8293. }
  8294. return $result;
  8295. }
  8296. private function combine($left, $right)
  8297. {
  8298. return rtrim($left, '/') . '/' . ltrim($right, '/');
  8299. }
  8300. }
  8301. <?php
  8302. namespace Composer\Downloader;
  8303. use Composer\Package\PackageInterface;
  8304. use Composer\Repository\VcsRepository;
  8305. use Composer\Util\Perforce;
  8306. class PerforceDownloader extends VcsDownloader
  8307. {
  8308. protected $perforce;
  8309. public function doDownload(PackageInterface $package, $path, $url)
  8310. {
  8311. $ref = $package->getSourceReference();
  8312. $label = $this->getLabelFromSourceReference($ref);
  8313. $this->io->writeError(' Cloning ' . $ref);
  8314. $this->initPerforce($package, $path, $url);
  8315. $this->perforce->setStream($ref);
  8316. $this->perforce->p4Login($this->io);
  8317. $this->perforce->writeP4ClientSpec();
  8318. $this->perforce->connectClient();
  8319. $this->perforce->syncCodeBase($label);
  8320. $this->perforce->cleanupClientSpec();
  8321. }
  8322. private function getLabelFromSourceReference($ref)
  8323. {
  8324. $pos = strpos($ref,'@');
  8325. if (false !== $pos) {
  8326. return substr($ref, $pos + 1);
  8327. }
  8328. return null;
  8329. }
  8330. public function initPerforce($package, $path, $url)
  8331. {
  8332. if (!empty($this->perforce)) {
  8333. $this->perforce->initializePath($path);
  8334. return;
  8335. }
  8336. $repository = $package->getRepository();
  8337. $repoConfig = null;
  8338. if ($repository instanceof VcsRepository) {
  8339. $repoConfig = $this->getRepoConfig($repository);
  8340. }
  8341. $this->perforce = Perforce::create($repoConfig, $url, $path, $this->process, $this->io);
  8342. }
  8343. private function getRepoConfig(VcsRepository $repository)
  8344. {
  8345. return $repository->getRepoConfig();
  8346. }
  8347. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  8348. {
  8349. $this->doDownload($target, $path, $url);
  8350. }
  8351. public function getLocalChanges(PackageInterface $package, $path)
  8352. {
  8353. $this->io->writeError('Perforce driver does not check for local changes before overriding', true);
  8354. return;
  8355. }
  8356. protected function getCommitLogs($fromReference, $toReference, $path)
  8357. {
  8358. $commitLogs = $this->perforce->getCommitLogs($fromReference, $toReference);
  8359. return $commitLogs;
  8360. }
  8361. public function setPerforce($perforce)
  8362. {
  8363. $this->perforce = $perforce;
  8364. }
  8365. }
  8366. <?php
  8367. namespace Composer\Downloader;
  8368. class PharDownloader extends ArchiveDownloader
  8369. {
  8370. protected function extract($file, $path)
  8371. {
  8372. $archive = new \Phar($file);
  8373. $archive->extractTo($path, null, true);
  8374. }
  8375. }
  8376. <?php
  8377. namespace Composer\Downloader;
  8378. use Composer\Config;
  8379. use Composer\Cache;
  8380. use Composer\EventDispatcher\EventDispatcher;
  8381. use Composer\Util\ProcessExecutor;
  8382. use Composer\IO\IOInterface;
  8383. use RarArchive;
  8384. class RarDownloader extends ArchiveDownloader
  8385. {
  8386. protected $process;
  8387. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
  8388. {
  8389. $this->process = $process ?: new ProcessExecutor($io);
  8390. parent::__construct($io, $config, $eventDispatcher, $cache);
  8391. }
  8392. protected function extract($file, $path)
  8393. {
  8394. $processError = null;
  8395. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  8396. $command = 'unrar x ' . ProcessExecutor::escape($file) . ' ' . ProcessExecutor::escape($path) . ' && chmod -R u+w ' . ProcessExecutor::escape($path);
  8397. if (0 === $this->process->execute($command, $ignoredOutput)) {
  8398. return;
  8399. }
  8400. $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
  8401. }
  8402. if (!class_exists('RarArchive')) {
  8403. $iniPath = php_ini_loaded_file();
  8404. if ($iniPath) {
  8405. $iniMessage = 'The php.ini used by your command-line PHP is: ' . $iniPath;
  8406. } else {
  8407. $iniMessage = 'A php.ini file does not exist. You will have to create one.';
  8408. }
  8409. $error = "Could not decompress the archive, enable the PHP rar extension or install unrar.\n"
  8410. . $iniMessage . "\n" . $processError;
  8411. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  8412. $error = "Could not decompress the archive, enable the PHP rar extension.\n" . $iniMessage;
  8413. }
  8414. throw new \RuntimeException($error);
  8415. }
  8416. $rarArchive = RarArchive::open($file);
  8417. if (false === $rarArchive) {
  8418. throw new \UnexpectedValueException('Could not open RAR archive: ' . $file);
  8419. }
  8420. $entries = $rarArchive->getEntries();
  8421. if (false === $entries) {
  8422. throw new \RuntimeException('Could not retrieve RAR archive entries');
  8423. }
  8424. foreach ($entries as $entry) {
  8425. if (false === $entry->extract($path)) {
  8426. throw new \RuntimeException('Could not extract entry');
  8427. }
  8428. }
  8429. $rarArchive->close();
  8430. }
  8431. }
  8432. <?php
  8433. namespace Composer\Downloader;
  8434. use Composer\Package\PackageInterface;
  8435. use Composer\Util\Svn as SvnUtil;
  8436. class SvnDownloader extends VcsDownloader
  8437. {
  8438. public function doDownload(PackageInterface $package, $path, $url)
  8439. {
  8440. SvnUtil::cleanEnv();
  8441. $ref = $package->getSourceReference();
  8442. $this->io->writeError(" Checking out ".$package->getSourceReference());
  8443. $this->execute($url, "svn co", sprintf("%s/%s", $url, $ref), null, $path);
  8444. }
  8445. public function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url)
  8446. {
  8447. SvnUtil::cleanEnv();
  8448. $ref = $target->getSourceReference();
  8449. if (!is_dir($path.'/.svn')) {
  8450. throw new \RuntimeException('The .svn directory is missing from '.$path.', see http://getcomposer.org/commit-deps for more information');
  8451. }
  8452. $flags = "";
  8453. if (0 === $this->process->execute('svn --version', $output)) {
  8454. if (preg_match('{(\d+(?:\.\d+)+)}', $output, $match) && version_compare($match[1], '1.7.0', '>=')) {
  8455. $flags .= ' --ignore-ancestry';
  8456. }
  8457. }
  8458. $this->io->writeError(" Checking out " . $ref);
  8459. $this->execute($url, "svn switch" . $flags, sprintf("%s/%s", $url, $ref), $path);
  8460. }
  8461. public function getLocalChanges(PackageInterface $package, $path)
  8462. {
  8463. if (!is_dir($path.'/.svn')) {
  8464. return;
  8465. }
  8466. $this->process->execute('svn status --ignore-externals', $output, $path);
  8467. return preg_match('{^ *[^X ] +}m', $output) ? $output : null;
  8468. }
  8469. protected function execute($baseUrl, $command, $url, $cwd = null, $path = null)
  8470. {
  8471. $util = new SvnUtil($baseUrl, $this->io, $this->config);
  8472. try {
  8473. return $util->execute($command, $url, $cwd, $path, $this->io->isVerbose());
  8474. } catch (\RuntimeException $e) {
  8475. throw new \RuntimeException(
  8476. 'Package could not be downloaded, '.$e->getMessage()
  8477. );
  8478. }
  8479. }
  8480. protected function cleanChanges(PackageInterface $package, $path, $update)
  8481. {
  8482. if (!$changes = $this->getLocalChanges($package, $path)) {
  8483. return;
  8484. }
  8485. if (!$this->io->isInteractive()) {
  8486. if (true === $this->config->get('discard-changes')) {
  8487. return $this->discardChanges($path);
  8488. }
  8489. return parent::cleanChanges($package, $path, $update);
  8490. }
  8491. $changes = array_map(function ($elem) {
  8492. return ' '.$elem;
  8493. }, preg_split('{\s*\r?\n\s*}', $changes));
  8494. $this->io->writeError(' <error>The package has modified files:</error>');
  8495. $this->io->writeError(array_slice($changes, 0, 10));
  8496. if (count($changes) > 10) {
  8497. $this->io->writeError(' <info>'.count($changes) - 10 . ' more files modified, choose "v" to view the full list</info>');
  8498. }
  8499. while (true) {
  8500. switch ($this->io->ask(' <info>Discard changes [y,n,v,?]?</info> ', '?')) {
  8501. case 'y':
  8502. $this->discardChanges($path);
  8503. break 2;
  8504. case 'n':
  8505. throw new \RuntimeException('Update aborted');
  8506. case 'v':
  8507. $this->io->writeError($changes);
  8508. break;
  8509. case '?':
  8510. default:
  8511. $this->io->writeError(array(
  8512. ' y - discard changes and apply the '.($update ? 'update' : 'uninstall'),
  8513. ' n - abort the '.($update ? 'update' : 'uninstall').' and let you manually clean things up',
  8514. ' v - view modified files',
  8515. ' ? - print help',
  8516. ));
  8517. break;
  8518. }
  8519. }
  8520. }
  8521. protected function getCommitLogs($fromReference, $toReference, $path)
  8522. {
  8523. if (preg_match('{.*@(\d+)$}', $fromReference) && preg_match('{.*@(\d+)$}', $toReference) ) {
  8524. $fromRevision = preg_replace('{.*@(\d+)$}', '$1', $fromReference);
  8525. $toRevision = preg_replace('{.*@(\d+)$}', '$1', $toReference);
  8526. $command = sprintf('svn log -r%s:%s --incremental', $fromRevision, $toRevision);
  8527. if (0 !== $this->process->execute($command, $output, $path)) {
  8528. throw new \RuntimeException(
  8529. 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput()
  8530. );
  8531. }
  8532. } else {
  8533. $output = "Could not retrieve changes between $fromReference and $toReference due to missing revision information";
  8534. }
  8535. return $output;
  8536. }
  8537. protected function discardChanges($path)
  8538. {
  8539. if (0 !== $this->process->execute('svn revert -R .', $output, $path)) {
  8540. throw new \RuntimeException("Could not reset changes\n\n:".$this->process->getErrorOutput());
  8541. }
  8542. }
  8543. }
  8544. <?php
  8545. namespace Composer\Downloader;
  8546. class TarDownloader extends ArchiveDownloader
  8547. {
  8548. protected function extract($file, $path)
  8549. {
  8550. $archive = new \PharData($file);
  8551. $archive->extractTo($path, null, true);
  8552. }
  8553. }
  8554. <?php
  8555. namespace Composer\Downloader;
  8556. class TransportException extends \RuntimeException
  8557. {
  8558. protected $headers;
  8559. protected $response;
  8560. public function setHeaders($headers)
  8561. {
  8562. $this->headers = $headers;
  8563. }
  8564. public function getHeaders()
  8565. {
  8566. return $this->headers;
  8567. }
  8568. public function setResponse($response)
  8569. {
  8570. $this->response = $response;
  8571. }
  8572. public function getResponse()
  8573. {
  8574. return $this->response;
  8575. }
  8576. }
  8577. <?php
  8578. namespace Composer\Downloader;
  8579. use Composer\Config;
  8580. use Composer\Package\PackageInterface;
  8581. use Composer\Package\Version\VersionParser;
  8582. use Composer\Util\ProcessExecutor;
  8583. use Composer\IO\IOInterface;
  8584. use Composer\Util\Filesystem;
  8585. abstract class VcsDownloader implements DownloaderInterface, ChangeReportInterface
  8586. {
  8587. protected $io;
  8588. protected $config;
  8589. protected $process;
  8590. protected $filesystem;
  8591. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, Filesystem $fs = null)
  8592. {
  8593. $this->io = $io;
  8594. $this->config = $config;
  8595. $this->process = $process ?: new ProcessExecutor($io);
  8596. $this->filesystem = $fs ?: new Filesystem;
  8597. }
  8598. public function getInstallationSource()
  8599. {
  8600. return 'source';
  8601. }
  8602. public function download(PackageInterface $package, $path)
  8603. {
  8604. if (!$package->getSourceReference()) {
  8605. throw new \InvalidArgumentException('Package '.$package->getPrettyName().' is missing reference information');
  8606. }
  8607. $this->io->writeError(" - Installing <info>" . $package->getName() . "</info> (<comment>" . VersionParser::formatVersion($package) . "</comment>)");
  8608. $this->filesystem->emptyDirectory($path);
  8609. $urls = $package->getSourceUrls();
  8610. while ($url = array_shift($urls)) {
  8611. try {
  8612. if (Filesystem::isLocalPath($url)) {
  8613. $url = realpath($url);
  8614. }
  8615. $this->doDownload($package, $path, $url);
  8616. break;
  8617. } catch (\Exception $e) {
  8618. if ($this->io->isDebug()) {
  8619. $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getMessage());
  8620. } elseif (count($urls)) {
  8621. $this->io->writeError(' Failed, trying the next URL');
  8622. }
  8623. if (!count($urls)) {
  8624. throw $e;
  8625. }
  8626. }
  8627. }
  8628. $this->io->writeError('');
  8629. }
  8630. public function update(PackageInterface $initial, PackageInterface $target, $path)
  8631. {
  8632. if (!$target->getSourceReference()) {
  8633. throw new \InvalidArgumentException('Package '.$target->getPrettyName().' is missing reference information');
  8634. }
  8635. $name = $target->getName();
  8636. if ($initial->getPrettyVersion() == $target->getPrettyVersion()) {
  8637. if ($target->getSourceType() === 'svn') {
  8638. $from = $initial->getSourceReference();
  8639. $to = $target->getSourceReference();
  8640. } else {
  8641. $from = substr($initial->getSourceReference(), 0, 7);
  8642. $to = substr($target->getSourceReference(), 0, 7);
  8643. }
  8644. $name .= ' '.$initial->getPrettyVersion();
  8645. } else {
  8646. $from = VersionParser::formatVersion($initial);
  8647. $to = VersionParser::formatVersion($target);
  8648. }
  8649. $this->io->writeError(" - Updating <info>" . $name . "</info> (<comment>" . $from . "</comment> => <comment>" . $to . "</comment>)");
  8650. $this->cleanChanges($initial, $path, true);
  8651. $urls = $target->getSourceUrls();
  8652. while ($url = array_shift($urls)) {
  8653. try {
  8654. if (Filesystem::isLocalPath($url)) {
  8655. $url = realpath($url);
  8656. }
  8657. $this->doUpdate($initial, $target, $path, $url);
  8658. break;
  8659. } catch (\Exception $e) {
  8660. if ($this->io->isDebug()) {
  8661. $this->io->writeError('Failed: ['.get_class($e).'] '.$e->getMessage());
  8662. } elseif (count($urls)) {
  8663. $this->io->writeError(' Failed, trying the next URL');
  8664. } else {
  8665. $this->reapplyChanges($path);
  8666. throw $e;
  8667. }
  8668. }
  8669. }
  8670. $this->reapplyChanges($path);
  8671. if ($this->io->isVerbose()) {
  8672. $message = 'Pulling in changes:';
  8673. $logs = $this->getCommitLogs($initial->getSourceReference(), $target->getSourceReference(), $path);
  8674. if (!trim($logs)) {
  8675. $message = 'Rolling back changes:';
  8676. $logs = $this->getCommitLogs($target->getSourceReference(), $initial->getSourceReference(), $path);
  8677. }
  8678. if (trim($logs)) {
  8679. $logs = implode("\n", array_map(function ($line) {
  8680. return ' ' . $line;
  8681. }, explode("\n", $logs)));
  8682. $this->io->writeError(' '.$message);
  8683. $this->io->writeError($logs);
  8684. }
  8685. }
  8686. $this->io->writeError('');
  8687. }
  8688. public function remove(PackageInterface $package, $path)
  8689. {
  8690. $this->io->writeError(" - Removing <info>" . $package->getName() . "</info> (<comment>" . $package->getPrettyVersion() . "</comment>)");
  8691. $this->cleanChanges($package, $path, false);
  8692. if (!$this->filesystem->removeDirectory($path)) {
  8693. throw new \RuntimeException('Could not completely delete '.$path.', aborting.');
  8694. }
  8695. }
  8696. public function setOutputProgress($outputProgress)
  8697. {
  8698. return $this;
  8699. }
  8700. protected function cleanChanges(PackageInterface $package, $path, $update)
  8701. {
  8702. if (null !== $this->getLocalChanges($package, $path)) {
  8703. throw new \RuntimeException('Source directory ' . $path . ' has uncommitted changes.');
  8704. }
  8705. }
  8706. protected function reapplyChanges($path)
  8707. {
  8708. }
  8709. abstract protected function doDownload(PackageInterface $package, $path, $url);
  8710. abstract protected function doUpdate(PackageInterface $initial, PackageInterface $target, $path, $url);
  8711. abstract protected function getCommitLogs($fromReference, $toReference, $path);
  8712. }
  8713. <?php
  8714. namespace Composer\Downloader;
  8715. use Composer\Config;
  8716. use Composer\Cache;
  8717. use Composer\EventDispatcher\EventDispatcher;
  8718. use Composer\Util\ProcessExecutor;
  8719. use Composer\IO\IOInterface;
  8720. use ZipArchive;
  8721. class ZipDownloader extends ArchiveDownloader
  8722. {
  8723. protected $process;
  8724. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null, Cache $cache = null, ProcessExecutor $process = null)
  8725. {
  8726. $this->process = $process ?: new ProcessExecutor($io);
  8727. parent::__construct($io, $config, $eventDispatcher, $cache);
  8728. }
  8729. protected function extract($file, $path)
  8730. {
  8731. $processError = null;
  8732. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  8733. $command = 'unzip '.ProcessExecutor::escape($file).' -d '.ProcessExecutor::escape($path) . ' && chmod -R u+w ' . ProcessExecutor::escape($path);
  8734. try {
  8735. if (0 === $this->process->execute($command, $ignoredOutput)) {
  8736. return;
  8737. }
  8738. $processError = 'Failed to execute ' . $command . "\n\n" . $this->process->getErrorOutput();
  8739. } catch (\Exception $e) {
  8740. $processError = 'Failed to execute ' . $command . "\n\n" . $e->getMessage();
  8741. }
  8742. }
  8743. if (!class_exists('ZipArchive')) {
  8744. $iniPath = php_ini_loaded_file();
  8745. if ($iniPath) {
  8746. $iniMessage = 'The php.ini used by your command-line PHP is: ' . $iniPath;
  8747. } else {
  8748. $iniMessage = 'A php.ini file does not exist. You will have to create one.';
  8749. }
  8750. $error = "Could not decompress the archive, enable the PHP zip extension or install unzip.\n"
  8751. . $iniMessage . "\n" . $processError;
  8752. if (!defined('PHP_WINDOWS_VERSION_BUILD')) {
  8753. $error = "Could not decompress the archive, enable the PHP zip extension.\n" . $iniMessage;
  8754. }
  8755. throw new \RuntimeException($error);
  8756. }
  8757. $zipArchive = new ZipArchive();
  8758. if (true !== ($retval = $zipArchive->open($file))) {
  8759. throw new \UnexpectedValueException($this->getErrorMessage($retval, $file), $retval);
  8760. }
  8761. if (true !== $zipArchive->extractTo($path)) {
  8762. throw new \RuntimeException("There was an error extracting the ZIP file. Corrupt file?");
  8763. }
  8764. $zipArchive->close();
  8765. }
  8766. protected function getErrorMessage($retval, $file)
  8767. {
  8768. switch ($retval) {
  8769. case ZipArchive::ER_EXISTS:
  8770. return sprintf("File '%s' already exists.", $file);
  8771. case ZipArchive::ER_INCONS:
  8772. return sprintf("Zip archive '%s' is inconsistent.", $file);
  8773. case ZipArchive::ER_INVAL:
  8774. return sprintf("Invalid argument (%s)", $file);
  8775. case ZipArchive::ER_MEMORY:
  8776. return sprintf("Malloc failure (%s)", $file);
  8777. case ZipArchive::ER_NOENT:
  8778. return sprintf("No such zip file: '%s'", $file);
  8779. case ZipArchive::ER_NOZIP:
  8780. return sprintf("'%s' is not a zip archive.", $file);
  8781. case ZipArchive::ER_OPEN:
  8782. return sprintf("Can't open zip file: %s", $file);
  8783. case ZipArchive::ER_READ:
  8784. return sprintf("Zip read error (%s)", $file);
  8785. case ZipArchive::ER_SEEK:
  8786. return sprintf("Zip seek error (%s)", $file);
  8787. default:
  8788. return sprintf("'%s' is not a valid zip archive, got error code: %s", $file, $retval);
  8789. }
  8790. }
  8791. }
  8792. <?php
  8793. namespace Composer\EventDispatcher;
  8794. class Event
  8795. {
  8796. protected $name;
  8797. protected $args;
  8798. protected $flags;
  8799. private $propagationStopped = false;
  8800. public function __construct($name, array $args = array(), array $flags = array())
  8801. {
  8802. $this->name = $name;
  8803. $this->args = $args;
  8804. $this->flags = $flags;
  8805. }
  8806. public function getName()
  8807. {
  8808. return $this->name;
  8809. }
  8810. public function getArguments()
  8811. {
  8812. return $this->args;
  8813. }
  8814. public function getFlags()
  8815. {
  8816. return $this->flags;
  8817. }
  8818. public function isPropagationStopped()
  8819. {
  8820. return $this->propagationStopped;
  8821. }
  8822. public function stopPropagation()
  8823. {
  8824. $this->propagationStopped = true;
  8825. }
  8826. }
  8827. <?php
  8828. namespace Composer\EventDispatcher;
  8829. use Composer\DependencyResolver\PolicyInterface;
  8830. use Composer\DependencyResolver\Pool;
  8831. use Composer\DependencyResolver\Request;
  8832. use Composer\Installer\InstallerEvent;
  8833. use Composer\IO\IOInterface;
  8834. use Composer\Composer;
  8835. use Composer\DependencyResolver\Operation\OperationInterface;
  8836. use Composer\Repository\CompositeRepository;
  8837. use Composer\Script;
  8838. use Composer\Script\PackageEvent;
  8839. use Composer\Util\ProcessExecutor;
  8840. class EventDispatcher
  8841. {
  8842. protected $composer;
  8843. protected $io;
  8844. protected $loader;
  8845. protected $process;
  8846. protected $listeners;
  8847. public function __construct(Composer $composer, IOInterface $io, ProcessExecutor $process = null)
  8848. {
  8849. $this->composer = $composer;
  8850. $this->io = $io;
  8851. $this->process = $process ?: new ProcessExecutor($io);
  8852. }
  8853. public function dispatch($eventName, Event $event = null)
  8854. {
  8855. if (null == $event) {
  8856. $event = new Event($eventName);
  8857. }
  8858. return $this->doDispatch($event);
  8859. }
  8860. public function dispatchScript($eventName, $devMode = false, $additionalArgs = array(), $flags = array())
  8861. {
  8862. return $this->doDispatch(new Script\Event($eventName, $this->composer, $this->io, $devMode, $additionalArgs, $flags));
  8863. }
  8864. public function dispatchPackageEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation)
  8865. {
  8866. return $this->doDispatch(new PackageEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations, $operation));
  8867. }
  8868. public function dispatchInstallerEvent($eventName, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array())
  8869. {
  8870. return $this->doDispatch(new InstallerEvent($eventName, $this->composer, $this->io, $devMode, $policy, $pool, $installedRepo, $request, $operations));
  8871. }
  8872. protected function doDispatch(Event $event)
  8873. {
  8874. $listeners = $this->getListeners($event);
  8875. $return = 0;
  8876. foreach ($listeners as $callable) {
  8877. if (!is_string($callable) && is_callable($callable)) {
  8878. $event = $this->checkListenerExpectedEvent($callable, $event);
  8879. $return = false === call_user_func($callable, $event) ? 1 : 0;
  8880. } elseif ($this->isPhpScript($callable)) {
  8881. $className = substr($callable, 0, strpos($callable, '::'));
  8882. $methodName = substr($callable, strpos($callable, '::') + 2);
  8883. if (!class_exists($className)) {
  8884. $this->io->writeError('<warning>Class '.$className.' is not autoloadable, can not call '.$event->getName().' script</warning>');
  8885. continue;
  8886. }
  8887. if (!is_callable($callable)) {
  8888. $this->io->writeError('<warning>Method '.$callable.' is not callable, can not call '.$event->getName().' script</warning>');
  8889. continue;
  8890. }
  8891. try {
  8892. $return = false === $this->executeEventPhpScript($className, $methodName, $event) ? 1 : 0;
  8893. } catch (\Exception $e) {
  8894. $message = "Script %s handling the %s event terminated with an exception";
  8895. $this->io->writeError('<error>'.sprintf($message, $callable, $event->getName()).'</error>');
  8896. throw $e;
  8897. }
  8898. } else {
  8899. $args = implode(' ', array_map(array('Composer\Util\ProcessExecutor','escape'), $event->getArguments()));
  8900. if (0 !== ($exitCode = $this->process->execute($callable . ($args === '' ? '' : ' '.$args)))) {
  8901. $this->io->writeError(sprintf('<error>Script %s handling the %s event returned with an error</error>', $callable, $event->getName()));
  8902. throw new \RuntimeException('Error Output: '.$this->process->getErrorOutput(), $exitCode);
  8903. }
  8904. }
  8905. if ($event->isPropagationStopped()) {
  8906. break;
  8907. }
  8908. }
  8909. return $return;
  8910. }
  8911. protected function executeEventPhpScript($className, $methodName, Event $event)
  8912. {
  8913. $event = $this->checkListenerExpectedEvent(array($className, $methodName), $event);
  8914. return $className::$methodName($event);
  8915. }
  8916. protected function checkListenerExpectedEvent($target, Event $event)
  8917. {
  8918. try {
  8919. $reflected = new \ReflectionParameter($target, 0);
  8920. } catch (\Exception $e) {
  8921. return $event;
  8922. }
  8923. $typehint = $reflected->getClass();
  8924. if (!$typehint instanceof \ReflectionClass) {
  8925. return $event;
  8926. }
  8927. $expected = $typehint->getName();
  8928. if (!$event instanceof $expected && $expected === 'Composer\Script\CommandEvent') {
  8929. $event = new \Composer\Script\CommandEvent(
  8930. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(), $event->getArguments()
  8931. );
  8932. }
  8933. if (!$event instanceof $expected && $expected === 'Composer\Script\PackageEvent') {
  8934. $event = new \Composer\Script\PackageEvent(
  8935. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  8936. $event->getPolicy(), $event->getPool(), $event->getInstalledRepo(), $event->getRequest(),
  8937. $event->getOperations(), $event->getOperation()
  8938. );
  8939. }
  8940. if (!$event instanceof $expected && $expected === 'Composer\Script\Event') {
  8941. $event = new \Composer\Script\Event(
  8942. $event->getName(), $event->getComposer(), $event->getIO(), $event->isDevMode(),
  8943. $event->getArguments(), $event->getFlags()
  8944. );
  8945. }
  8946. return $event;
  8947. }
  8948. protected function addListener($eventName, $listener, $priority = 0)
  8949. {
  8950. $this->listeners[$eventName][$priority][] = $listener;
  8951. }
  8952. public function addSubscriber(EventSubscriberInterface $subscriber)
  8953. {
  8954. foreach ($subscriber->getSubscribedEvents() as $eventName => $params) {
  8955. if (is_string($params)) {
  8956. $this->addListener($eventName, array($subscriber, $params));
  8957. } elseif (is_string($params[0])) {
  8958. $this->addListener($eventName, array($subscriber, $params[0]), isset($params[1]) ? $params[1] : 0);
  8959. } else {
  8960. foreach ($params as $listener) {
  8961. $this->addListener($eventName, array($subscriber, $listener[0]), isset($listener[1]) ? $listener[1] : 0);
  8962. }
  8963. }
  8964. }
  8965. }
  8966. protected function getListeners(Event $event)
  8967. {
  8968. $scriptListeners = $this->getScriptListeners($event);
  8969. if (!isset($this->listeners[$event->getName()][0])) {
  8970. $this->listeners[$event->getName()][0] = array();
  8971. }
  8972. krsort($this->listeners[$event->getName()]);
  8973. $listeners = $this->listeners;
  8974. $listeners[$event->getName()][0] = array_merge($listeners[$event->getName()][0], $scriptListeners);
  8975. return call_user_func_array('array_merge', $listeners[$event->getName()]);
  8976. }
  8977. public function hasEventListeners(Event $event)
  8978. {
  8979. $listeners = $this->getListeners($event);
  8980. return count($listeners) > 0;
  8981. }
  8982. protected function getScriptListeners(Event $event)
  8983. {
  8984. $package = $this->composer->getPackage();
  8985. $scripts = $package->getScripts();
  8986. if (empty($scripts[$event->getName()])) {
  8987. return array();
  8988. }
  8989. if ($this->loader) {
  8990. $this->loader->unregister();
  8991. }
  8992. $generator = $this->composer->getAutoloadGenerator();
  8993. $packages = $this->composer->getRepositoryManager()->getLocalRepository()->getCanonicalPackages();
  8994. $packageMap = $generator->buildPackageMap($this->composer->getInstallationManager(), $package, $packages);
  8995. $map = $generator->parseAutoloads($packageMap, $package);
  8996. $this->loader = $generator->createLoader($map);
  8997. $this->loader->register();
  8998. return $scripts[$event->getName()];
  8999. }
  9000. protected function isPhpScript($callable)
  9001. {
  9002. return false === strpos($callable, ' ') && false !== strpos($callable, '::');
  9003. }
  9004. }
  9005. <?php
  9006. namespace Composer\EventDispatcher;
  9007. interface EventSubscriberInterface
  9008. {
  9009. public static function getSubscribedEvents();
  9010. }
  9011. <?php
  9012. namespace Composer;
  9013. use Composer\Config\JsonConfigSource;
  9014. use Composer\Json\JsonFile;
  9015. use Composer\IO\IOInterface;
  9016. use Composer\Package\Archiver;
  9017. use Composer\Repository\RepositoryManager;
  9018. use Composer\Repository\WritableRepositoryInterface;
  9019. use Composer\Util\ProcessExecutor;
  9020. use Composer\Util\RemoteFilesystem;
  9021. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  9022. use Composer\EventDispatcher\EventDispatcher;
  9023. use Composer\Autoload\AutoloadGenerator;
  9024. use Composer\Package\Version\VersionParser;
  9025. class Factory
  9026. {
  9027. protected static function getHomeDir()
  9028. {
  9029. $home = getenv('COMPOSER_HOME');
  9030. if (!$home) {
  9031. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  9032. if (!getenv('APPDATA')) {
  9033. throw new \RuntimeException('The APPDATA or COMPOSER_HOME environment variable must be set for composer to run correctly');
  9034. }
  9035. $home = strtr(getenv('APPDATA'), '\\', '/') . '/Composer';
  9036. } else {
  9037. if (!getenv('HOME')) {
  9038. throw new \RuntimeException('The HOME or COMPOSER_HOME environment variable must be set for composer to run correctly');
  9039. }
  9040. $home = rtrim(getenv('HOME'), '/') . '/.composer';
  9041. }
  9042. }
  9043. return $home;
  9044. }
  9045. protected static function getCacheDir($home)
  9046. {
  9047. $cacheDir = getenv('COMPOSER_CACHE_DIR');
  9048. if (!$cacheDir) {
  9049. if (defined('PHP_WINDOWS_VERSION_MAJOR')) {
  9050. if ($cacheDir = getenv('LOCALAPPDATA')) {
  9051. $cacheDir .= '/Composer';
  9052. } else {
  9053. $cacheDir = $home . '/cache';
  9054. }
  9055. $cacheDir = strtr($cacheDir, '\\', '/');
  9056. } else {
  9057. $cacheDir = $home.'/cache';
  9058. }
  9059. }
  9060. return $cacheDir;
  9061. }
  9062. public static function createConfig(IOInterface $io = null, $cwd = null)
  9063. {
  9064. $cwd = $cwd ?: getcwd();
  9065. $home = self::getHomeDir();
  9066. $cacheDir = self::getCacheDir($home);
  9067. foreach (array($home, $cacheDir) as $dir) {
  9068. if (!file_exists($dir . '/.htaccess')) {
  9069. if (!is_dir($dir)) {
  9070. @mkdir($dir, 0777, true);
  9071. }
  9072. @file_put_contents($dir . '/.htaccess', 'Deny from all');
  9073. }
  9074. }
  9075. $config = new Config(true, $cwd);
  9076. $config->merge(array('config' => array('home' => $home, 'cache-dir' => $cacheDir)));
  9077. $file = new JsonFile($home.'/config.json');
  9078. if ($file->exists()) {
  9079. if ($io && $io->isDebug()) {
  9080. $io->writeError('Loading config file ' . $file->getPath());
  9081. }
  9082. $config->merge($file->read());
  9083. }
  9084. $config->setConfigSource(new JsonConfigSource($file));
  9085. $file = new JsonFile($config->get('home').'/auth.json');
  9086. if ($file->exists()) {
  9087. if ($io && $io->isDebug()) {
  9088. $io->writeError('Loading config file ' . $file->getPath());
  9089. }
  9090. $config->merge(array('config' => $file->read()));
  9091. }
  9092. $config->setAuthConfigSource(new JsonConfigSource($file, true));
  9093. return $config;
  9094. }
  9095. public static function getComposerFile()
  9096. {
  9097. return trim(getenv('COMPOSER')) ?: './composer.json';
  9098. }
  9099. public static function createAdditionalStyles()
  9100. {
  9101. return array(
  9102. 'highlight' => new OutputFormatterStyle('red'),
  9103. 'warning' => new OutputFormatterStyle('black', 'yellow'),
  9104. );
  9105. }
  9106. public static function createDefaultRepositories(IOInterface $io = null, Config $config = null, RepositoryManager $rm = null)
  9107. {
  9108. $repos = array();
  9109. if (!$config) {
  9110. $config = static::createConfig($io);
  9111. }
  9112. if (!$rm) {
  9113. if (!$io) {
  9114. throw new \InvalidArgumentException('This function requires either an IOInterface or a RepositoryManager');
  9115. }
  9116. $factory = new static;
  9117. $rm = $factory->createRepositoryManager($io, $config);
  9118. }
  9119. foreach ($config->getRepositories() as $index => $repo) {
  9120. if (is_string($repo)) {
  9121. throw new \UnexpectedValueException('"repositories" should be an array of repository definitions, only a single repository was given');
  9122. }
  9123. if (!is_array($repo)) {
  9124. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') should be an array, '.gettype($repo).' given');
  9125. }
  9126. if (!isset($repo['type'])) {
  9127. throw new \UnexpectedValueException('Repository "'.$index.'" ('.json_encode($repo).') must have a type defined');
  9128. }
  9129. $name = is_int($index) && isset($repo['url']) ? preg_replace('{^https?://}i', '', $repo['url']) : $index;
  9130. while (isset($repos[$name])) {
  9131. $name .= '2';
  9132. }
  9133. $repos[$name] = $rm->createRepository($repo['type'], $repo);
  9134. }
  9135. return $repos;
  9136. }
  9137. public function createComposer(IOInterface $io, $localConfig = null, $disablePlugins = false, $cwd = null, $fullLoad = true)
  9138. {
  9139. $cwd = $cwd ?: getcwd();
  9140. if (null === $localConfig) {
  9141. $localConfig = static::getComposerFile();
  9142. }
  9143. if (is_string($localConfig)) {
  9144. $composerFile = $localConfig;
  9145. $file = new JsonFile($localConfig, new RemoteFilesystem($io));
  9146. if (!$file->exists()) {
  9147. if ($localConfig === './composer.json' || $localConfig === 'composer.json') {
  9148. $message = 'Composer could not find a composer.json file in '.$cwd;
  9149. } else {
  9150. $message = 'Composer could not find the config file: '.$localConfig;
  9151. }
  9152. $instructions = 'To initialize a project, please create a composer.json file as described in the http://getcomposer.org/ "Getting Started" section';
  9153. throw new \InvalidArgumentException($message.PHP_EOL.$instructions);
  9154. }
  9155. $file->validateSchema(JsonFile::LAX_SCHEMA);
  9156. $localConfig = $file->read();
  9157. }
  9158. $config = static::createConfig($io, $cwd);
  9159. $config->merge($localConfig);
  9160. if (isset($composerFile)) {
  9161. if ($io && $io->isDebug()) {
  9162. $io->writeError('Loading config file ' . $composerFile);
  9163. }
  9164. $localAuthFile = new JsonFile(dirname(realpath($composerFile)) . '/auth.json');
  9165. if ($localAuthFile->exists()) {
  9166. if ($io && $io->isDebug()) {
  9167. $io->writeError('Loading config file ' . $localAuthFile->getPath());
  9168. }
  9169. $config->merge(array('config' => $localAuthFile->read()));
  9170. $config->setAuthConfigSource(new JsonConfigSource($localAuthFile, true));
  9171. }
  9172. }
  9173. $vendorDir = $config->get('vendor-dir');
  9174. $binDir = $config->get('bin-dir');
  9175. $composer = new Composer();
  9176. $composer->setConfig($config);
  9177. if ($fullLoad) {
  9178. $io->loadConfiguration($config);
  9179. ProcessExecutor::setTimeout((int) $config->get('process-timeout'));
  9180. }
  9181. $dispatcher = new EventDispatcher($composer, $io);
  9182. $composer->setEventDispatcher($dispatcher);
  9183. $rm = $this->createRepositoryManager($io, $config, $dispatcher);
  9184. $composer->setRepositoryManager($rm);
  9185. $this->addLocalRepository($rm, $vendorDir);
  9186. $parser = new VersionParser;
  9187. $loader = new Package\Loader\RootPackageLoader($rm, $config, $parser, new ProcessExecutor($io));
  9188. $package = $loader->load($localConfig);
  9189. $composer->setPackage($package);
  9190. $im = $this->createInstallationManager();
  9191. $composer->setInstallationManager($im);
  9192. if ($fullLoad) {
  9193. $dm = $this->createDownloadManager($io, $config, $dispatcher);
  9194. $composer->setDownloadManager($dm);
  9195. $generator = new AutoloadGenerator($dispatcher, $io);
  9196. $composer->setAutoloadGenerator($generator);
  9197. }
  9198. $this->createDefaultInstallers($im, $composer, $io);
  9199. if ($fullLoad) {
  9200. $globalComposer = $this->createGlobalComposer($io, $config, $disablePlugins);
  9201. $pm = $this->createPluginManager($io, $composer, $globalComposer);
  9202. $composer->setPluginManager($pm);
  9203. if (!$disablePlugins) {
  9204. $pm->loadInstalledPlugins();
  9205. }
  9206. if ($rm->getLocalRepository()) {
  9207. $this->purgePackages($rm->getLocalRepository(), $im);
  9208. }
  9209. }
  9210. if ($fullLoad && isset($composerFile)) {
  9211. $lockFile = "json" === pathinfo($composerFile, PATHINFO_EXTENSION)
  9212. ? substr($composerFile, 0, -4).'lock'
  9213. : $composerFile . '.lock';
  9214. $locker = new Package\Locker($io, new JsonFile($lockFile, new RemoteFilesystem($io, $config)), $rm, $im, md5_file($composerFile));
  9215. $composer->setLocker($locker);
  9216. }
  9217. return $composer;
  9218. }
  9219. protected function createRepositoryManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  9220. {
  9221. $rm = new RepositoryManager($io, $config, $eventDispatcher);
  9222. $rm->setRepositoryClass('composer', 'Composer\Repository\ComposerRepository');
  9223. $rm->setRepositoryClass('vcs', 'Composer\Repository\VcsRepository');
  9224. $rm->setRepositoryClass('package', 'Composer\Repository\PackageRepository');
  9225. $rm->setRepositoryClass('pear', 'Composer\Repository\PearRepository');
  9226. $rm->setRepositoryClass('git', 'Composer\Repository\VcsRepository');
  9227. $rm->setRepositoryClass('gitlab', 'Composer\Repository\VcsRepository');
  9228. $rm->setRepositoryClass('svn', 'Composer\Repository\VcsRepository');
  9229. $rm->setRepositoryClass('perforce', 'Composer\Repository\VcsRepository');
  9230. $rm->setRepositoryClass('hg', 'Composer\Repository\VcsRepository');
  9231. $rm->setRepositoryClass('artifact', 'Composer\Repository\ArtifactRepository');
  9232. return $rm;
  9233. }
  9234. protected function addLocalRepository(RepositoryManager $rm, $vendorDir)
  9235. {
  9236. $rm->setLocalRepository(new Repository\InstalledFilesystemRepository(new JsonFile($vendorDir.'/composer/installed.json')));
  9237. }
  9238. protected function createGlobalComposer(IOInterface $io, Config $config, $disablePlugins)
  9239. {
  9240. if (realpath($config->get('home')) === getcwd()) {
  9241. return;
  9242. }
  9243. $composer = null;
  9244. try {
  9245. $composer = self::createComposer($io, $config->get('home') . '/composer.json', $disablePlugins, $config->get('home'), false);
  9246. } catch (\Exception $e) {
  9247. if ($io->isDebug()) {
  9248. $io->writeError('Failed to initialize global composer: '.$e->getMessage());
  9249. }
  9250. }
  9251. return $composer;
  9252. }
  9253. public function createDownloadManager(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  9254. {
  9255. $cache = null;
  9256. if ($config->get('cache-files-ttl') > 0) {
  9257. $cache = new Cache($io, $config->get('cache-files-dir'), 'a-z0-9_./');
  9258. }
  9259. $dm = new Downloader\DownloadManager($io);
  9260. switch ($config->get('preferred-install')) {
  9261. case 'dist':
  9262. $dm->setPreferDist(true);
  9263. break;
  9264. case 'source':
  9265. $dm->setPreferSource(true);
  9266. break;
  9267. case 'auto':
  9268. default:
  9269. break;
  9270. }
  9271. $dm->setDownloader('git', new Downloader\GitDownloader($io, $config));
  9272. $dm->setDownloader('svn', new Downloader\SvnDownloader($io, $config));
  9273. $dm->setDownloader('hg', new Downloader\HgDownloader($io, $config));
  9274. $dm->setDownloader('perforce', new Downloader\PerforceDownloader($io, $config));
  9275. $dm->setDownloader('zip', new Downloader\ZipDownloader($io, $config, $eventDispatcher, $cache));
  9276. $dm->setDownloader('rar', new Downloader\RarDownloader($io, $config, $eventDispatcher, $cache));
  9277. $dm->setDownloader('tar', new Downloader\TarDownloader($io, $config, $eventDispatcher, $cache));
  9278. $dm->setDownloader('gzip', new Downloader\GzipDownloader($io, $config, $eventDispatcher, $cache));
  9279. $dm->setDownloader('phar', new Downloader\PharDownloader($io, $config, $eventDispatcher, $cache));
  9280. $dm->setDownloader('file', new Downloader\FileDownloader($io, $config, $eventDispatcher, $cache));
  9281. return $dm;
  9282. }
  9283. public function createArchiveManager(Config $config, Downloader\DownloadManager $dm = null)
  9284. {
  9285. if (null === $dm) {
  9286. $io = new IO\NullIO();
  9287. $io->loadConfiguration($config);
  9288. $dm = $this->createDownloadManager($io, $config);
  9289. }
  9290. $am = new Archiver\ArchiveManager($dm);
  9291. $am->addArchiver(new Archiver\PharArchiver);
  9292. return $am;
  9293. }
  9294. protected function createPluginManager(IOInterface $io, Composer $composer, Composer $globalComposer = null)
  9295. {
  9296. return new Plugin\PluginManager($io, $composer, $globalComposer);
  9297. }
  9298. protected function createInstallationManager()
  9299. {
  9300. return new Installer\InstallationManager();
  9301. }
  9302. protected function createDefaultInstallers(Installer\InstallationManager $im, Composer $composer, IOInterface $io)
  9303. {
  9304. $im->addInstaller(new Installer\LibraryInstaller($io, $composer, null));
  9305. $im->addInstaller(new Installer\PearInstaller($io, $composer, 'pear-library'));
  9306. $im->addInstaller(new Installer\PluginInstaller($io, $composer));
  9307. $im->addInstaller(new Installer\MetapackageInstaller($io));
  9308. }
  9309. protected function purgePackages(WritableRepositoryInterface $repo, Installer\InstallationManager $im)
  9310. {
  9311. foreach ($repo->getPackages() as $package) {
  9312. if (!$im->isPackageInstalled($repo, $package)) {
  9313. $repo->removePackage($package);
  9314. }
  9315. }
  9316. }
  9317. public static function create(IOInterface $io, $config = null, $disablePlugins = false)
  9318. {
  9319. $factory = new static();
  9320. return $factory->createComposer($io, $config, $disablePlugins);
  9321. }
  9322. }
  9323. <?php
  9324. namespace Composer\Installer;
  9325. use Composer\Package\PackageInterface;
  9326. use Composer\Package\AliasPackage;
  9327. use Composer\Repository\RepositoryInterface;
  9328. use Composer\Repository\InstalledRepositoryInterface;
  9329. use Composer\DependencyResolver\Operation\OperationInterface;
  9330. use Composer\DependencyResolver\Operation\InstallOperation;
  9331. use Composer\DependencyResolver\Operation\UpdateOperation;
  9332. use Composer\DependencyResolver\Operation\UninstallOperation;
  9333. use Composer\DependencyResolver\Operation\MarkAliasInstalledOperation;
  9334. use Composer\DependencyResolver\Operation\MarkAliasUninstalledOperation;
  9335. use Composer\Util\StreamContextFactory;
  9336. class InstallationManager
  9337. {
  9338. private $installers = array();
  9339. private $cache = array();
  9340. private $notifiablePackages = array();
  9341. public function reset()
  9342. {
  9343. $this->notifiablePackages = array();
  9344. }
  9345. public function addInstaller(InstallerInterface $installer)
  9346. {
  9347. array_unshift($this->installers, $installer);
  9348. $this->cache = array();
  9349. }
  9350. public function removeInstaller(InstallerInterface $installer)
  9351. {
  9352. if (false !== ($key = array_search($installer, $this->installers, true))) {
  9353. array_splice($this->installers, $key, 1);
  9354. $this->cache = array();
  9355. }
  9356. }
  9357. public function disablePlugins()
  9358. {
  9359. foreach ($this->installers as $i => $installer) {
  9360. if (!$installer instanceof PluginInstaller) {
  9361. continue;
  9362. }
  9363. unset($this->installers[$i]);
  9364. }
  9365. }
  9366. public function getInstaller($type)
  9367. {
  9368. $type = strtolower($type);
  9369. if (isset($this->cache[$type])) {
  9370. return $this->cache[$type];
  9371. }
  9372. foreach ($this->installers as $installer) {
  9373. if ($installer->supports($type)) {
  9374. return $this->cache[$type] = $installer;
  9375. }
  9376. }
  9377. throw new \InvalidArgumentException('Unknown installer type: '.$type);
  9378. }
  9379. public function isPackageInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
  9380. {
  9381. if ($package instanceof AliasPackage) {
  9382. return $repo->hasPackage($package) && $this->isPackageInstalled($repo, $package->getAliasOf());
  9383. }
  9384. return $this->getInstaller($package->getType())->isInstalled($repo, $package);
  9385. }
  9386. public function execute(RepositoryInterface $repo, OperationInterface $operation)
  9387. {
  9388. $method = $operation->getJobType();
  9389. $this->$method($repo, $operation);
  9390. }
  9391. public function install(RepositoryInterface $repo, InstallOperation $operation)
  9392. {
  9393. $package = $operation->getPackage();
  9394. $installer = $this->getInstaller($package->getType());
  9395. $installer->install($repo, $package);
  9396. $this->markForNotification($package);
  9397. }
  9398. public function update(RepositoryInterface $repo, UpdateOperation $operation)
  9399. {
  9400. $initial = $operation->getInitialPackage();
  9401. $target = $operation->getTargetPackage();
  9402. $initialType = $initial->getType();
  9403. $targetType = $target->getType();
  9404. if ($initialType === $targetType) {
  9405. $installer = $this->getInstaller($initialType);
  9406. $installer->update($repo, $initial, $target);
  9407. $this->markForNotification($target);
  9408. } else {
  9409. $this->getInstaller($initialType)->uninstall($repo, $initial);
  9410. $this->getInstaller($targetType)->install($repo, $target);
  9411. }
  9412. }
  9413. public function uninstall(RepositoryInterface $repo, UninstallOperation $operation)
  9414. {
  9415. $package = $operation->getPackage();
  9416. $installer = $this->getInstaller($package->getType());
  9417. $installer->uninstall($repo, $package);
  9418. }
  9419. public function markAliasInstalled(RepositoryInterface $repo, MarkAliasInstalledOperation $operation)
  9420. {
  9421. $package = $operation->getPackage();
  9422. if (!$repo->hasPackage($package)) {
  9423. $repo->addPackage(clone $package);
  9424. }
  9425. }
  9426. public function markAliasUninstalled(RepositoryInterface $repo, MarkAliasUninstalledOperation $operation)
  9427. {
  9428. $package = $operation->getPackage();
  9429. $repo->removePackage($package);
  9430. }
  9431. public function getInstallPath(PackageInterface $package)
  9432. {
  9433. $installer = $this->getInstaller($package->getType());
  9434. return $installer->getInstallPath($package);
  9435. }
  9436. public function notifyInstalls()
  9437. {
  9438. foreach ($this->notifiablePackages as $repoUrl => $packages) {
  9439. if (strpos($repoUrl, '%package%')) {
  9440. foreach ($packages as $package) {
  9441. $url = str_replace('%package%', $package->getPrettyName(), $repoUrl);
  9442. $params = array(
  9443. 'version' => $package->getPrettyVersion(),
  9444. 'version_normalized' => $package->getVersion(),
  9445. );
  9446. $opts = array('http' =>
  9447. array(
  9448. 'method' => 'POST',
  9449. 'header' => array('Content-type: application/x-www-form-urlencoded'),
  9450. 'content' => http_build_query($params, '', '&'),
  9451. 'timeout' => 3,
  9452. )
  9453. );
  9454. $context = StreamContextFactory::getContext($url, $opts);
  9455. @file_get_contents($url, false, $context);
  9456. }
  9457. continue;
  9458. }
  9459. $postData = array('downloads' => array());
  9460. foreach ($packages as $package) {
  9461. $postData['downloads'][] = array(
  9462. 'name' => $package->getPrettyName(),
  9463. 'version' => $package->getVersion(),
  9464. );
  9465. }
  9466. $opts = array('http' =>
  9467. array(
  9468. 'method' => 'POST',
  9469. 'header' => array('Content-Type: application/json'),
  9470. 'content' => json_encode($postData),
  9471. 'timeout' => 6,
  9472. )
  9473. );
  9474. $context = StreamContextFactory::getContext($repoUrl, $opts);
  9475. @file_get_contents($repoUrl, false, $context);
  9476. }
  9477. $this->reset();
  9478. }
  9479. private function markForNotification(PackageInterface $package)
  9480. {
  9481. if ($package->getNotificationUrl()) {
  9482. $this->notifiablePackages[$package->getNotificationUrl()][$package->getName()] = $package;
  9483. }
  9484. }
  9485. }
  9486. <?php
  9487. namespace Composer\Installer;
  9488. use Composer\Composer;
  9489. use Composer\DependencyResolver\PolicyInterface;
  9490. use Composer\DependencyResolver\Operation\OperationInterface;
  9491. use Composer\DependencyResolver\Pool;
  9492. use Composer\DependencyResolver\Request;
  9493. use Composer\EventDispatcher\Event;
  9494. use Composer\IO\IOInterface;
  9495. use Composer\Repository\CompositeRepository;
  9496. class InstallerEvent extends Event
  9497. {
  9498. private $composer;
  9499. private $io;
  9500. private $devMode;
  9501. private $policy;
  9502. private $pool;
  9503. private $installedRepo;
  9504. private $request;
  9505. private $operations;
  9506. public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations = array())
  9507. {
  9508. parent::__construct($eventName);
  9509. $this->composer = $composer;
  9510. $this->io = $io;
  9511. $this->devMode = $devMode;
  9512. $this->policy = $policy;
  9513. $this->pool = $pool;
  9514. $this->installedRepo = $installedRepo;
  9515. $this->request = $request;
  9516. $this->operations = $operations;
  9517. }
  9518. public function getComposer()
  9519. {
  9520. return $this->composer;
  9521. }
  9522. public function getIO()
  9523. {
  9524. return $this->io;
  9525. }
  9526. public function isDevMode()
  9527. {
  9528. return $this->devMode;
  9529. }
  9530. public function getPolicy()
  9531. {
  9532. return $this->policy;
  9533. }
  9534. public function getPool()
  9535. {
  9536. return $this->pool;
  9537. }
  9538. public function getInstalledRepo()
  9539. {
  9540. return $this->installedRepo;
  9541. }
  9542. public function getRequest()
  9543. {
  9544. return $this->request;
  9545. }
  9546. public function getOperations()
  9547. {
  9548. return $this->operations;
  9549. }
  9550. }
  9551. <?php
  9552. namespace Composer\Installer;
  9553. class InstallerEvents
  9554. {
  9555. const PRE_DEPENDENCIES_SOLVING = 'pre-dependencies-solving';
  9556. const POST_DEPENDENCIES_SOLVING = 'post-dependencies-solving';
  9557. }
  9558. <?php
  9559. namespace Composer\Installer;
  9560. use Composer\Package\PackageInterface;
  9561. use Composer\Repository\InstalledRepositoryInterface;
  9562. interface InstallerInterface
  9563. {
  9564. public function supports($packageType);
  9565. public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package);
  9566. public function install(InstalledRepositoryInterface $repo, PackageInterface $package);
  9567. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target);
  9568. public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package);
  9569. public function getInstallPath(PackageInterface $package);
  9570. }
  9571. <?php
  9572. namespace Composer\Installer;
  9573. use Composer\Composer;
  9574. use Composer\IO\IOInterface;
  9575. use Composer\Repository\InstalledRepositoryInterface;
  9576. use Composer\Package\PackageInterface;
  9577. use Composer\Util\Filesystem;
  9578. use Composer\Util\ProcessExecutor;
  9579. class LibraryInstaller implements InstallerInterface
  9580. {
  9581. protected $composer;
  9582. protected $vendorDir;
  9583. protected $binDir;
  9584. protected $downloadManager;
  9585. protected $io;
  9586. protected $type;
  9587. protected $filesystem;
  9588. public function __construct(IOInterface $io, Composer $composer, $type = 'library', Filesystem $filesystem = null)
  9589. {
  9590. $this->composer = $composer;
  9591. $this->downloadManager = $composer->getDownloadManager();
  9592. $this->io = $io;
  9593. $this->type = $type;
  9594. $this->filesystem = $filesystem ?: new Filesystem();
  9595. $this->vendorDir = rtrim($composer->getConfig()->get('vendor-dir'), '/');
  9596. $this->binDir = rtrim($composer->getConfig()->get('bin-dir'), '/');
  9597. }
  9598. public function supports($packageType)
  9599. {
  9600. return $packageType === $this->type || null === $this->type;
  9601. }
  9602. public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
  9603. {
  9604. return $repo->hasPackage($package) && is_readable($this->getInstallPath($package));
  9605. }
  9606. public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
  9607. {
  9608. $this->initializeVendorDir();
  9609. $downloadPath = $this->getInstallPath($package);
  9610. if (!is_readable($downloadPath) && $repo->hasPackage($package)) {
  9611. $this->removeBinaries($package);
  9612. }
  9613. $this->installCode($package);
  9614. $this->installBinaries($package);
  9615. if (!$repo->hasPackage($package)) {
  9616. $repo->addPackage(clone $package);
  9617. }
  9618. }
  9619. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  9620. {
  9621. if (!$repo->hasPackage($initial)) {
  9622. throw new \InvalidArgumentException('Package is not installed: '.$initial);
  9623. }
  9624. $this->initializeVendorDir();
  9625. $this->removeBinaries($initial);
  9626. $this->updateCode($initial, $target);
  9627. $this->installBinaries($target);
  9628. $repo->removePackage($initial);
  9629. if (!$repo->hasPackage($target)) {
  9630. $repo->addPackage(clone $target);
  9631. }
  9632. }
  9633. public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
  9634. {
  9635. if (!$repo->hasPackage($package)) {
  9636. throw new \InvalidArgumentException('Package is not installed: '.$package);
  9637. }
  9638. $this->removeCode($package);
  9639. $this->removeBinaries($package);
  9640. $repo->removePackage($package);
  9641. $downloadPath = $this->getPackageBasePath($package);
  9642. if (strpos($package->getName(), '/')) {
  9643. $packageVendorDir = dirname($downloadPath);
  9644. if (is_dir($packageVendorDir) && $this->filesystem->isDirEmpty($packageVendorDir)) {
  9645. @rmdir($packageVendorDir);
  9646. }
  9647. }
  9648. }
  9649. public function getInstallPath(PackageInterface $package)
  9650. {
  9651. $targetDir = $package->getTargetDir();
  9652. return $this->getPackageBasePath($package) . ($targetDir ? '/'.$targetDir : '');
  9653. }
  9654. protected function getPackageBasePath(PackageInterface $package)
  9655. {
  9656. $this->initializeVendorDir();
  9657. return ($this->vendorDir ? $this->vendorDir.'/' : '') . $package->getPrettyName();
  9658. }
  9659. protected function installCode(PackageInterface $package)
  9660. {
  9661. $downloadPath = $this->getInstallPath($package);
  9662. $this->downloadManager->download($package, $downloadPath);
  9663. }
  9664. protected function updateCode(PackageInterface $initial, PackageInterface $target)
  9665. {
  9666. $initialDownloadPath = $this->getInstallPath($initial);
  9667. $targetDownloadPath = $this->getInstallPath($target);
  9668. if ($targetDownloadPath !== $initialDownloadPath) {
  9669. if (substr($initialDownloadPath, 0, strlen($targetDownloadPath)) === $targetDownloadPath
  9670. || substr($targetDownloadPath, 0, strlen($initialDownloadPath)) === $initialDownloadPath
  9671. ) {
  9672. $this->removeCode($initial);
  9673. $this->installCode($target);
  9674. return;
  9675. }
  9676. $this->filesystem->rename($initialDownloadPath, $targetDownloadPath);
  9677. }
  9678. $this->downloadManager->update($initial, $target, $targetDownloadPath);
  9679. }
  9680. protected function removeCode(PackageInterface $package)
  9681. {
  9682. $downloadPath = $this->getPackageBasePath($package);
  9683. $this->downloadManager->remove($package, $downloadPath);
  9684. }
  9685. protected function getBinaries(PackageInterface $package)
  9686. {
  9687. return $package->getBinaries();
  9688. }
  9689. protected function installBinaries(PackageInterface $package)
  9690. {
  9691. $binaries = $this->getBinaries($package);
  9692. if (!$binaries) {
  9693. return;
  9694. }
  9695. foreach ($binaries as $bin) {
  9696. $binPath = $this->getInstallPath($package).'/'.$bin;
  9697. if (!file_exists($binPath)) {
  9698. $this->io->writeError(' <warning>Skipped installation of bin '.$bin.' for package '.$package->getName().': file not found in package</warning>');
  9699. continue;
  9700. }
  9701. $binPath = realpath($binPath);
  9702. $this->initializeBinDir();
  9703. $link = $this->binDir.'/'.basename($bin);
  9704. if (file_exists($link)) {
  9705. if (is_link($link)) {
  9706. @chmod($link, 0777 & ~umask());
  9707. }
  9708. $this->io->writeError(' Skipped installation of bin '.$bin.' for package '.$package->getName().': name conflicts with an existing file');
  9709. continue;
  9710. }
  9711. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  9712. if ('.bat' !== substr($binPath, -4)) {
  9713. file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link));
  9714. @chmod($link, 0777 & ~umask());
  9715. $link .= '.bat';
  9716. if (file_exists($link)) {
  9717. $this->io->writeError(' Skipped installation of bin '.$bin.'.bat proxy for package '.$package->getName().': a .bat proxy was already installed');
  9718. }
  9719. }
  9720. if (!file_exists($link)) {
  9721. file_put_contents($link, $this->generateWindowsProxyCode($binPath, $link));
  9722. }
  9723. } else {
  9724. $cwd = getcwd();
  9725. try {
  9726. $relativeBin = $this->filesystem->findShortestPath($link, $binPath);
  9727. chdir(dirname($link));
  9728. if (false === symlink($relativeBin, $link)) {
  9729. throw new \ErrorException();
  9730. }
  9731. } catch (\ErrorException $e) {
  9732. file_put_contents($link, $this->generateUnixyProxyCode($binPath, $link));
  9733. }
  9734. chdir($cwd);
  9735. }
  9736. @chmod($link, 0777 & ~umask());
  9737. }
  9738. }
  9739. protected function removeBinaries(PackageInterface $package)
  9740. {
  9741. $binaries = $this->getBinaries($package);
  9742. if (!$binaries) {
  9743. return;
  9744. }
  9745. foreach ($binaries as $bin) {
  9746. $link = $this->binDir.'/'.basename($bin);
  9747. if (is_link($link) || file_exists($link)) {
  9748. $this->filesystem->unlink($link);
  9749. }
  9750. if (file_exists($link.'.bat')) {
  9751. $this->filesystem->unlink($link.'.bat');
  9752. }
  9753. }
  9754. }
  9755. protected function initializeVendorDir()
  9756. {
  9757. $this->filesystem->ensureDirectoryExists($this->vendorDir);
  9758. $this->vendorDir = realpath($this->vendorDir);
  9759. }
  9760. protected function initializeBinDir()
  9761. {
  9762. $this->filesystem->ensureDirectoryExists($this->binDir);
  9763. $this->binDir = realpath($this->binDir);
  9764. }
  9765. protected function generateWindowsProxyCode($bin, $link)
  9766. {
  9767. $binPath = $this->filesystem->findShortestPath($link, $bin);
  9768. if ('.bat' === substr($bin, -4) || '.exe' === substr($bin, -4)) {
  9769. $caller = 'call';
  9770. } else {
  9771. $handle = fopen($bin, 'r');
  9772. $line = fgets($handle);
  9773. fclose($handle);
  9774. if (preg_match('{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m', $line, $match)) {
  9775. $caller = trim($match[1]);
  9776. } else {
  9777. $caller = 'php';
  9778. }
  9779. }
  9780. return "@ECHO OFF\r\n".
  9781. "SET BIN_TARGET=%~dp0/".trim(ProcessExecutor::escape($binPath), '"')."\r\n".
  9782. "{$caller} \"%BIN_TARGET%\" %*\r\n";
  9783. }
  9784. protected function generateUnixyProxyCode($bin, $link)
  9785. {
  9786. $binPath = $this->filesystem->findShortestPath($link, $bin);
  9787. return "#!/usr/bin/env sh\n".
  9788. 'SRC_DIR="`pwd`"'."\n".
  9789. 'cd "`dirname "$0"`"'."\n".
  9790. 'cd '.ProcessExecutor::escape(dirname($binPath))."\n".
  9791. 'BIN_TARGET="`pwd`/'.basename($binPath)."\"\n".
  9792. 'cd "$SRC_DIR"'."\n".
  9793. '"$BIN_TARGET" "$@"'."\n";
  9794. }
  9795. }
  9796. <?php
  9797. namespace Composer\Installer;
  9798. use Composer\Repository\InstalledRepositoryInterface;
  9799. use Composer\Package\PackageInterface;
  9800. class MetapackageInstaller implements InstallerInterface
  9801. {
  9802. public function supports($packageType)
  9803. {
  9804. return $packageType === 'metapackage';
  9805. }
  9806. public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
  9807. {
  9808. return $repo->hasPackage($package);
  9809. }
  9810. public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
  9811. {
  9812. $repo->addPackage(clone $package);
  9813. }
  9814. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  9815. {
  9816. if (!$repo->hasPackage($initial)) {
  9817. throw new \InvalidArgumentException('Package is not installed: '.$initial);
  9818. }
  9819. $repo->removePackage($initial);
  9820. $repo->addPackage(clone $target);
  9821. }
  9822. public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
  9823. {
  9824. if (!$repo->hasPackage($package)) {
  9825. throw new \InvalidArgumentException('Package is not installed: '.$package);
  9826. }
  9827. $repo->removePackage($package);
  9828. }
  9829. public function getInstallPath(PackageInterface $package)
  9830. {
  9831. return '';
  9832. }
  9833. }
  9834. <?php
  9835. namespace Composer\Installer;
  9836. use Composer\Repository\InstalledRepositoryInterface;
  9837. use Composer\Package\PackageInterface;
  9838. class NoopInstaller implements InstallerInterface
  9839. {
  9840. public function supports($packageType)
  9841. {
  9842. return true;
  9843. }
  9844. public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
  9845. {
  9846. return $repo->hasPackage($package);
  9847. }
  9848. public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
  9849. {
  9850. if (!$repo->hasPackage($package)) {
  9851. $repo->addPackage(clone $package);
  9852. }
  9853. }
  9854. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  9855. {
  9856. if (!$repo->hasPackage($initial)) {
  9857. throw new \InvalidArgumentException('Package is not installed: '.$initial);
  9858. }
  9859. $repo->removePackage($initial);
  9860. if (!$repo->hasPackage($target)) {
  9861. $repo->addPackage(clone $target);
  9862. }
  9863. }
  9864. public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
  9865. {
  9866. if (!$repo->hasPackage($package)) {
  9867. throw new \InvalidArgumentException('Package is not installed: '.$package);
  9868. }
  9869. $repo->removePackage($package);
  9870. }
  9871. public function getInstallPath(PackageInterface $package)
  9872. {
  9873. $targetDir = $package->getTargetDir();
  9874. return $package->getPrettyName() . ($targetDir ? '/'.$targetDir : '');
  9875. }
  9876. }
  9877. <?php
  9878. namespace Composer\Installer;
  9879. use Composer\Composer;
  9880. use Composer\IO\IOInterface;
  9881. use Composer\DependencyResolver\Operation\OperationInterface;
  9882. use Composer\DependencyResolver\PolicyInterface;
  9883. use Composer\DependencyResolver\Pool;
  9884. use Composer\DependencyResolver\Request;
  9885. use Composer\EventDispatcher\Event;
  9886. use Composer\Repository\CompositeRepository;
  9887. class PackageEvent extends InstallerEvent
  9888. {
  9889. private $operation;
  9890. public function __construct($eventName, Composer $composer, IOInterface $io, $devMode, PolicyInterface $policy, Pool $pool, CompositeRepository $installedRepo, Request $request, array $operations, OperationInterface $operation)
  9891. {
  9892. parent::__construct($eventName, $composer, $io, $devMode, $policy, $pool, $installedRepo, $request, $operations);
  9893. $this->operation = $operation;
  9894. }
  9895. public function getOperation()
  9896. {
  9897. return $this->operation;
  9898. }
  9899. }
  9900. <?php
  9901. namespace Composer\Installer;
  9902. class PackageEvents
  9903. {
  9904. const PRE_PACKAGE_INSTALL = 'pre-package-install';
  9905. const POST_PACKAGE_INSTALL = 'post-package-install';
  9906. const PRE_PACKAGE_UPDATE = 'pre-package-update';
  9907. const POST_PACKAGE_UPDATE = 'post-package-update';
  9908. const PRE_PACKAGE_UNINSTALL = 'pre-package-uninstall';
  9909. const POST_PACKAGE_UNINSTALL = 'post-package-uninstall';
  9910. }
  9911. <?php
  9912. namespace Composer\Installer;
  9913. use Composer\IO\IOInterface;
  9914. use Composer\Composer;
  9915. use Composer\Downloader\PearPackageExtractor;
  9916. use Composer\Repository\InstalledRepositoryInterface;
  9917. use Composer\Package\PackageInterface;
  9918. use Composer\Util\ProcessExecutor;
  9919. class PearInstaller extends LibraryInstaller
  9920. {
  9921. public function __construct(IOInterface $io, Composer $composer, $type = 'pear-library')
  9922. {
  9923. parent::__construct($io, $composer, $type);
  9924. }
  9925. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  9926. {
  9927. $this->uninstall($repo, $initial);
  9928. $this->install($repo, $target);
  9929. }
  9930. protected function installCode(PackageInterface $package)
  9931. {
  9932. parent::installCode($package);
  9933. parent::initializeBinDir();
  9934. $isWindows = defined('PHP_WINDOWS_VERSION_BUILD');
  9935. $php_bin = $this->binDir . ($isWindows ? '/composer-php.bat' : '/composer-php');
  9936. if (!$isWindows) {
  9937. $php_bin = '/usr/bin/env ' . $php_bin;
  9938. }
  9939. $installPath = $this->getInstallPath($package);
  9940. $vars = array(
  9941. 'os' => $isWindows ? 'windows' : 'linux',
  9942. 'php_bin' => $php_bin,
  9943. 'pear_php' => $installPath,
  9944. 'php_dir' => $installPath,
  9945. 'bin_dir' => $installPath . '/bin',
  9946. 'data_dir' => $installPath . '/data',
  9947. 'version' => $package->getPrettyVersion(),
  9948. );
  9949. $packageArchive = $this->getInstallPath($package).'/'.pathinfo($package->getDistUrl(), PATHINFO_BASENAME);
  9950. $pearExtractor = new PearPackageExtractor($packageArchive);
  9951. $pearExtractor->extractTo($this->getInstallPath($package), array('php' => '/', 'script' => '/bin', 'data' => '/data'), $vars);
  9952. if ($this->io->isVerbose()) {
  9953. $this->io->writeError(' Cleaning up');
  9954. }
  9955. $this->filesystem->unlink($packageArchive);
  9956. }
  9957. protected function getBinaries(PackageInterface $package)
  9958. {
  9959. $binariesPath = $this->getInstallPath($package) . '/bin/';
  9960. $binaries = array();
  9961. if (file_exists($binariesPath)) {
  9962. foreach (new \FilesystemIterator($binariesPath, \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::CURRENT_AS_FILEINFO) as $fileName => $value) {
  9963. if (!$value->isDir()) {
  9964. $binaries[] = 'bin/'.$fileName;
  9965. }
  9966. }
  9967. }
  9968. return $binaries;
  9969. }
  9970. protected function initializeBinDir()
  9971. {
  9972. parent::initializeBinDir();
  9973. file_put_contents($this->binDir.'/composer-php', $this->generateUnixyPhpProxyCode());
  9974. @chmod($this->binDir.'/composer-php', 0777);
  9975. file_put_contents($this->binDir.'/composer-php.bat', $this->generateWindowsPhpProxyCode());
  9976. @chmod($this->binDir.'/composer-php.bat', 0777);
  9977. }
  9978. protected function generateWindowsProxyCode($bin, $link)
  9979. {
  9980. $binPath = $this->filesystem->findShortestPath($link, $bin);
  9981. if ('.bat' === substr($bin, -4)) {
  9982. $caller = 'call';
  9983. } else {
  9984. $handle = fopen($bin, 'r');
  9985. $line = fgets($handle);
  9986. fclose($handle);
  9987. if (preg_match('{^#!/(?:usr/bin/env )?(?:[^/]+/)*(.+)$}m', $line, $match)) {
  9988. $caller = trim($match[1]);
  9989. } else {
  9990. $caller = 'php';
  9991. }
  9992. if ($caller === 'php') {
  9993. return "@echo off\r\n".
  9994. "pushd .\r\n".
  9995. "cd %~dp0\r\n".
  9996. "set PHP_PROXY=%CD%\\composer-php.bat\r\n".
  9997. "cd ".ProcessExecutor::escape(dirname($binPath))."\r\n".
  9998. "set BIN_TARGET=%CD%\\".basename($binPath)."\r\n".
  9999. "popd\r\n".
  10000. "%PHP_PROXY% \"%BIN_TARGET%\" %*\r\n";
  10001. }
  10002. }
  10003. return "@echo off\r\n".
  10004. "pushd .\r\n".
  10005. "cd %~dp0\r\n".
  10006. "cd ".ProcessExecutor::escape(dirname($binPath))."\r\n".
  10007. "set BIN_TARGET=%CD%\\".basename($binPath)."\r\n".
  10008. "popd\r\n".
  10009. $caller." \"%BIN_TARGET%\" %*\r\n";
  10010. }
  10011. private function generateWindowsPhpProxyCode()
  10012. {
  10013. $binToVendor = $this->filesystem->findShortestPath($this->binDir, $this->vendorDir, true);
  10014. return
  10015. "@echo off\r\n" .
  10016. "setlocal enabledelayedexpansion\r\n" .
  10017. "set BIN_DIR=%~dp0\r\n" .
  10018. "set VENDOR_DIR=%BIN_DIR%\\".$binToVendor."\r\n" .
  10019. "set DIRS=.\r\n" .
  10020. "FOR /D %%V IN (%VENDOR_DIR%\\*) DO (\r\n" .
  10021. " FOR /D %%P IN (%%V\\*) DO (\r\n" .
  10022. " set DIRS=!DIRS!;%%~fP\r\n" .
  10023. " )\r\n" .
  10024. ")\r\n" .
  10025. "php.exe -d include_path=!DIRS! %*\r\n";
  10026. }
  10027. private function generateUnixyPhpProxyCode()
  10028. {
  10029. $binToVendor = $this->filesystem->findShortestPath($this->binDir, $this->vendorDir, true);
  10030. return
  10031. "#!/usr/bin/env sh\n".
  10032. "SRC_DIR=`pwd`\n".
  10033. "BIN_DIR=`dirname $0`\n".
  10034. "VENDOR_DIR=\$BIN_DIR/".escapeshellarg($binToVendor)."\n".
  10035. "DIRS=\"\"\n".
  10036. "for vendor in \$VENDOR_DIR/*; do\n".
  10037. " if [ -d \"\$vendor\" ]; then\n".
  10038. " for package in \$vendor/*; do\n".
  10039. " if [ -d \"\$package\" ]; then\n".
  10040. " DIRS=\"\${DIRS}:\${package}\"\n".
  10041. " fi\n".
  10042. " done\n".
  10043. " fi\n".
  10044. "done\n".
  10045. "php -d include_path=\".\$DIRS\" $@\n";
  10046. }
  10047. }
  10048. <?php
  10049. namespace Composer\Installer;
  10050. use Composer\Composer;
  10051. use Composer\Package\Package;
  10052. use Composer\IO\IOInterface;
  10053. use Composer\Repository\InstalledRepositoryInterface;
  10054. use Composer\Package\PackageInterface;
  10055. class PluginInstaller extends LibraryInstaller
  10056. {
  10057. private $installationManager;
  10058. private static $classCounter = 0;
  10059. public function __construct(IOInterface $io, Composer $composer, $type = 'library')
  10060. {
  10061. parent::__construct($io, $composer, 'composer-plugin');
  10062. $this->installationManager = $composer->getInstallationManager();
  10063. }
  10064. public function supports($packageType)
  10065. {
  10066. return $packageType === 'composer-plugin' || $packageType === 'composer-installer';
  10067. }
  10068. public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
  10069. {
  10070. $extra = $package->getExtra();
  10071. if (empty($extra['class'])) {
  10072. throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
  10073. }
  10074. parent::install($repo, $package);
  10075. $this->composer->getPluginManager()->registerPackage($package, true);
  10076. }
  10077. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  10078. {
  10079. $extra = $target->getExtra();
  10080. if (empty($extra['class'])) {
  10081. throw new \UnexpectedValueException('Error while installing '.$target->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
  10082. }
  10083. parent::update($repo, $initial, $target);
  10084. $this->composer->getPluginManager()->registerPackage($target, true);
  10085. }
  10086. }
  10087. <?php
  10088. namespace Composer\Installer;
  10089. use Composer\Package\PackageInterface;
  10090. use Composer\Downloader\DownloadManager;
  10091. use Composer\Repository\InstalledRepositoryInterface;
  10092. use Composer\Util\Filesystem;
  10093. class ProjectInstaller implements InstallerInterface
  10094. {
  10095. private $installPath;
  10096. private $downloadManager;
  10097. private $filesystem;
  10098. public function __construct($installPath, DownloadManager $dm)
  10099. {
  10100. $this->installPath = rtrim(strtr($installPath, '\\', '/'), '/').'/';
  10101. $this->downloadManager = $dm;
  10102. $this->filesystem = new Filesystem;
  10103. }
  10104. public function supports($packageType)
  10105. {
  10106. return true;
  10107. }
  10108. public function isInstalled(InstalledRepositoryInterface $repo, PackageInterface $package)
  10109. {
  10110. return false;
  10111. }
  10112. public function install(InstalledRepositoryInterface $repo, PackageInterface $package)
  10113. {
  10114. $installPath = $this->installPath;
  10115. if (file_exists($installPath) && !$this->filesystem->isDirEmpty($installPath)) {
  10116. throw new \InvalidArgumentException("Project directory $installPath is not empty.");
  10117. }
  10118. if (!is_dir($installPath)) {
  10119. mkdir($installPath, 0777, true);
  10120. }
  10121. $this->downloadManager->download($package, $installPath);
  10122. }
  10123. public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target)
  10124. {
  10125. throw new \InvalidArgumentException("not supported");
  10126. }
  10127. public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
  10128. {
  10129. throw new \InvalidArgumentException("not supported");
  10130. }
  10131. public function getInstallPath(PackageInterface $package)
  10132. {
  10133. return $this->installPath;
  10134. }
  10135. }
  10136. <?php
  10137. namespace Composer;
  10138. use Composer\Autoload\AutoloadGenerator;
  10139. use Composer\DependencyResolver\DefaultPolicy;
  10140. use Composer\DependencyResolver\Operation\UpdateOperation;
  10141. use Composer\DependencyResolver\Operation\InstallOperation;
  10142. use Composer\DependencyResolver\Operation\UninstallOperation;
  10143. use Composer\DependencyResolver\Operation\OperationInterface;
  10144. use Composer\DependencyResolver\Pool;
  10145. use Composer\DependencyResolver\Request;
  10146. use Composer\DependencyResolver\Rule;
  10147. use Composer\DependencyResolver\Solver;
  10148. use Composer\DependencyResolver\SolverProblemsException;
  10149. use Composer\Downloader\DownloadManager;
  10150. use Composer\EventDispatcher\EventDispatcher;
  10151. use Composer\Installer\InstallationManager;
  10152. use Composer\Installer\InstallerEvents;
  10153. use Composer\Installer\NoopInstaller;
  10154. use Composer\IO\IOInterface;
  10155. use Composer\Json\JsonFile;
  10156. use Composer\Package\AliasPackage;
  10157. use Composer\Package\CompletePackage;
  10158. use Composer\Package\Link;
  10159. use Composer\Package\LinkConstraint\VersionConstraint;
  10160. use Composer\Package\Locker;
  10161. use Composer\Package\PackageInterface;
  10162. use Composer\Package\RootPackageInterface;
  10163. use Composer\Repository\CompositeRepository;
  10164. use Composer\Repository\InstalledArrayRepository;
  10165. use Composer\Repository\InstalledFilesystemRepository;
  10166. use Composer\Repository\PlatformRepository;
  10167. use Composer\Repository\RepositoryInterface;
  10168. use Composer\Repository\RepositoryManager;
  10169. use Composer\Script\ScriptEvents;
  10170. class Installer
  10171. {
  10172. protected $io;
  10173. protected $config;
  10174. protected $package;
  10175. protected $downloadManager;
  10176. protected $repositoryManager;
  10177. protected $locker;
  10178. protected $installationManager;
  10179. protected $eventDispatcher;
  10180. protected $autoloadGenerator;
  10181. protected $preferSource = false;
  10182. protected $preferDist = false;
  10183. protected $optimizeAutoloader = false;
  10184. protected $devMode = false;
  10185. protected $dryRun = false;
  10186. protected $verbose = false;
  10187. protected $update = false;
  10188. protected $dumpAutoloader = true;
  10189. protected $runScripts = true;
  10190. protected $ignorePlatformReqs = false;
  10191. protected $preferStable = false;
  10192. protected $preferLowest = false;
  10193. protected $updateWhitelist = null;
  10194. protected $whitelistDependencies = false;
  10195. protected $suggestedPackages;
  10196. protected $additionalInstalledRepository;
  10197. public function __construct(IOInterface $io, Config $config, RootPackageInterface $package, DownloadManager $downloadManager, RepositoryManager $repositoryManager, Locker $locker, InstallationManager $installationManager, EventDispatcher $eventDispatcher, AutoloadGenerator $autoloadGenerator)
  10198. {
  10199. $this->io = $io;
  10200. $this->config = $config;
  10201. $this->package = $package;
  10202. $this->downloadManager = $downloadManager;
  10203. $this->repositoryManager = $repositoryManager;
  10204. $this->locker = $locker;
  10205. $this->installationManager = $installationManager;
  10206. $this->eventDispatcher = $eventDispatcher;
  10207. $this->autoloadGenerator = $autoloadGenerator;
  10208. }
  10209. public function run()
  10210. {
  10211. gc_collect_cycles();
  10212. gc_disable();
  10213. if ($this->dryRun) {
  10214. $this->verbose = true;
  10215. $this->runScripts = false;
  10216. $this->installationManager->addInstaller(new NoopInstaller);
  10217. $this->mockLocalRepositories($this->repositoryManager);
  10218. }
  10219. $devRepo = new InstalledFilesystemRepository(new JsonFile($this->config->get('vendor-dir').'/composer/installed_dev.json'));
  10220. if ($devRepo->getPackages()) {
  10221. $this->io->writeError('<warning>BC Notice: Removing old dev packages to migrate to the new require-dev handling.</warning>');
  10222. foreach ($devRepo->getPackages() as $package) {
  10223. if ($this->installationManager->isPackageInstalled($devRepo, $package)) {
  10224. $this->installationManager->uninstall($devRepo, new UninstallOperation($package));
  10225. }
  10226. }
  10227. unlink($this->config->get('vendor-dir').'/composer/installed_dev.json');
  10228. }
  10229. unset($devRepo, $package);
  10230. if ($this->runScripts) {
  10231. $eventName = $this->update ? ScriptEvents::PRE_UPDATE_CMD : ScriptEvents::PRE_INSTALL_CMD;
  10232. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  10233. }
  10234. $this->downloadManager->setPreferSource($this->preferSource);
  10235. $this->downloadManager->setPreferDist($this->preferDist);
  10236. $installedRootPackage = clone $this->package;
  10237. $installedRootPackage->setRequires(array());
  10238. $installedRootPackage->setDevRequires(array());
  10239. $localRepo = $this->repositoryManager->getLocalRepository();
  10240. $platformRepo = new PlatformRepository();
  10241. $repos = array(
  10242. $localRepo,
  10243. new InstalledArrayRepository(array($installedRootPackage)),
  10244. $platformRepo,
  10245. );
  10246. $installedRepo = new CompositeRepository($repos);
  10247. if ($this->additionalInstalledRepository) {
  10248. $installedRepo->addRepository($this->additionalInstalledRepository);
  10249. }
  10250. $aliases = $this->getRootAliases();
  10251. $this->aliasPlatformPackages($platformRepo, $aliases);
  10252. try {
  10253. $this->suggestedPackages = array();
  10254. $res = $this->doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $this->devMode);
  10255. if ($res !== 0) {
  10256. return $res;
  10257. }
  10258. } catch (\Exception $e) {
  10259. $this->installationManager->notifyInstalls();
  10260. throw $e;
  10261. }
  10262. $this->installationManager->notifyInstalls();
  10263. if ($this->devMode) {
  10264. foreach ($this->suggestedPackages as $suggestion) {
  10265. $target = $suggestion['target'];
  10266. foreach ($installedRepo->getPackages() as $package) {
  10267. if (in_array($target, $package->getNames())) {
  10268. continue 2;
  10269. }
  10270. }
  10271. $this->io->writeError($suggestion['source'].' suggests installing '.$suggestion['target'].' ('.$suggestion['reason'].')');
  10272. }
  10273. }
  10274. foreach ($localRepo->getPackages() as $package) {
  10275. if (!$package instanceof CompletePackage || !$package->isAbandoned()) {
  10276. continue;
  10277. }
  10278. $replacement = (is_string($package->getReplacementPackage()))
  10279. ? 'Use ' . $package->getReplacementPackage() . ' instead'
  10280. : 'No replacement was suggested';
  10281. $this->io->writeError(
  10282. sprintf(
  10283. "<error>Package %s is abandoned, you should avoid using it. %s.</error>",
  10284. $package->getPrettyName(),
  10285. $replacement
  10286. )
  10287. );
  10288. }
  10289. if (!$this->dryRun) {
  10290. if ($this->update || !$this->locker->isLocked()) {
  10291. $localRepo->reload();
  10292. $devPackages = ($this->devMode || !$this->package->getDevRequires()) ? array() : null;
  10293. if ($this->devMode && $this->package->getDevRequires()) {
  10294. $policy = $this->createPolicy();
  10295. $pool = $this->createPool(true);
  10296. $pool->addRepository($installedRepo, $aliases);
  10297. $request = $this->createRequest($pool, $this->package, $platformRepo);
  10298. $request->updateAll();
  10299. foreach ($this->package->getRequires() as $link) {
  10300. $request->install($link->getTarget(), $link->getConstraint());
  10301. }
  10302. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request);
  10303. $solver = new Solver($policy, $pool, $installedRepo);
  10304. $ops = $solver->solve($request, $this->ignorePlatformReqs);
  10305. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, false, $policy, $pool, $installedRepo, $request, $ops);
  10306. foreach ($ops as $op) {
  10307. if ($op->getJobType() === 'uninstall') {
  10308. $devPackages[] = $op->getPackage();
  10309. }
  10310. }
  10311. }
  10312. $platformReqs = $this->extractPlatformRequirements($this->package->getRequires());
  10313. $platformDevReqs = $this->devMode ? $this->extractPlatformRequirements($this->package->getDevRequires()) : array();
  10314. $updatedLock = $this->locker->setLockData(
  10315. array_diff($localRepo->getCanonicalPackages(), (array) $devPackages),
  10316. $devPackages,
  10317. $platformReqs,
  10318. $platformDevReqs,
  10319. $aliases,
  10320. $this->package->getMinimumStability(),
  10321. $this->package->getStabilityFlags(),
  10322. $this->preferStable || $this->package->getPreferStable(),
  10323. $this->preferLowest
  10324. );
  10325. if ($updatedLock) {
  10326. $this->io->writeError('<info>Writing lock file</info>');
  10327. }
  10328. }
  10329. if ($this->dumpAutoloader) {
  10330. if ($this->optimizeAutoloader) {
  10331. $this->io->writeError('<info>Generating optimized autoload files</info>');
  10332. } else {
  10333. $this->io->writeError('<info>Generating autoload files</info>');
  10334. }
  10335. $this->autoloadGenerator->setDevMode($this->devMode);
  10336. $this->autoloadGenerator->dump($this->config, $localRepo, $this->package, $this->installationManager, 'composer', $this->optimizeAutoloader);
  10337. }
  10338. if ($this->runScripts) {
  10339. $eventName = $this->update ? ScriptEvents::POST_UPDATE_CMD : ScriptEvents::POST_INSTALL_CMD;
  10340. $this->eventDispatcher->dispatchScript($eventName, $this->devMode);
  10341. }
  10342. $vendorDir = $this->config->get('vendor-dir');
  10343. if (is_dir($vendorDir)) {
  10344. touch($vendorDir);
  10345. }
  10346. }
  10347. return 0;
  10348. }
  10349. protected function doInstall($localRepo, $installedRepo, $platformRepo, $aliases, $withDevReqs)
  10350. {
  10351. $lockedRepository = null;
  10352. $repositories = null;
  10353. $installFromLock = false;
  10354. if (!$this->update && $this->locker->isLocked()) {
  10355. $installFromLock = true;
  10356. try {
  10357. $lockedRepository = $this->locker->getLockedRepository($withDevReqs);
  10358. } catch (\RuntimeException $e) {
  10359. if ($this->package->getDevRequires()) {
  10360. throw $e;
  10361. }
  10362. $lockedRepository = $this->locker->getLockedRepository();
  10363. }
  10364. }
  10365. $this->whitelistUpdateDependencies(
  10366. $localRepo,
  10367. $withDevReqs,
  10368. $this->package->getRequires(),
  10369. $this->package->getDevRequires()
  10370. );
  10371. $this->io->writeError('<info>Loading composer repositories with package information</info>');
  10372. $policy = $this->createPolicy();
  10373. $pool = $this->createPool($withDevReqs, $lockedRepository);
  10374. $pool->addRepository($installedRepo, $aliases);
  10375. if ($installFromLock) {
  10376. $pool->addRepository($lockedRepository, $aliases);
  10377. }
  10378. if (!$installFromLock) {
  10379. $repositories = $this->repositoryManager->getRepositories();
  10380. foreach ($repositories as $repository) {
  10381. $pool->addRepository($repository, $aliases);
  10382. }
  10383. }
  10384. $request = $this->createRequest($pool, $this->package, $platformRepo);
  10385. if (!$installFromLock) {
  10386. $removedUnstablePackages = array();
  10387. foreach ($localRepo->getPackages() as $package) {
  10388. if (
  10389. !$pool->isPackageAcceptable($package->getNames(), $package->getStability())
  10390. && $this->installationManager->isPackageInstalled($localRepo, $package)
  10391. ) {
  10392. $removedUnstablePackages[$package->getName()] = true;
  10393. $request->remove($package->getName(), new VersionConstraint('=', $package->getVersion()));
  10394. }
  10395. }
  10396. }
  10397. if ($this->update) {
  10398. $this->io->writeError('<info>Updating dependencies'.($withDevReqs ? ' (including require-dev)' : '').'</info>');
  10399. $request->updateAll();
  10400. if ($withDevReqs) {
  10401. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  10402. } else {
  10403. $links = $this->package->getRequires();
  10404. }
  10405. foreach ($links as $link) {
  10406. $request->install($link->getTarget(), $link->getConstraint());
  10407. }
  10408. if ($this->updateWhitelist) {
  10409. if ($this->locker->isLocked()) {
  10410. try {
  10411. $currentPackages = $this->locker->getLockedRepository($withDevReqs)->getPackages();
  10412. } catch (\RuntimeException $e) {
  10413. $currentPackages = $this->locker->getLockedRepository()->getPackages();
  10414. }
  10415. } else {
  10416. $currentPackages = $installedRepo->getPackages();
  10417. }
  10418. $candidates = array();
  10419. foreach ($links as $link) {
  10420. $candidates[$link->getTarget()] = true;
  10421. }
  10422. foreach ($localRepo->getPackages() as $package) {
  10423. $candidates[$package->getName()] = true;
  10424. }
  10425. foreach ($candidates as $candidate => $dummy) {
  10426. foreach ($currentPackages as $curPackage) {
  10427. if ($curPackage->getName() === $candidate) {
  10428. if (!$this->isUpdateable($curPackage) && !isset($removedUnstablePackages[$curPackage->getName()])) {
  10429. $constraint = new VersionConstraint('=', $curPackage->getVersion());
  10430. $request->install($curPackage->getName(), $constraint);
  10431. }
  10432. break;
  10433. }
  10434. }
  10435. }
  10436. }
  10437. } elseif ($installFromLock) {
  10438. $this->io->writeError('<info>Installing dependencies'.($withDevReqs ? ' (including require-dev)' : '').' from lock file</info>');
  10439. if (!$this->locker->isFresh()) {
  10440. $this->io->writeError('<warning>Warning: The lock file is not up to date with the latest changes in composer.json. You may be getting outdated dependencies. Run update to update them.</warning>');
  10441. }
  10442. foreach ($lockedRepository->getPackages() as $package) {
  10443. $version = $package->getVersion();
  10444. if (isset($aliases[$package->getName()][$version])) {
  10445. $version = $aliases[$package->getName()][$version]['alias_normalized'];
  10446. }
  10447. $constraint = new VersionConstraint('=', $version);
  10448. $constraint->setPrettyString($package->getPrettyVersion());
  10449. $request->install($package->getName(), $constraint);
  10450. }
  10451. foreach ($this->locker->getPlatformRequirements($withDevReqs) as $link) {
  10452. $request->install($link->getTarget(), $link->getConstraint());
  10453. }
  10454. } else {
  10455. $this->io->writeError('<info>Installing dependencies'.($withDevReqs ? ' (including require-dev)' : '').'</info>');
  10456. if ($withDevReqs) {
  10457. $links = array_merge($this->package->getRequires(), $this->package->getDevRequires());
  10458. } else {
  10459. $links = $this->package->getRequires();
  10460. }
  10461. foreach ($links as $link) {
  10462. $request->install($link->getTarget(), $link->getConstraint());
  10463. }
  10464. }
  10465. $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-links');
  10466. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::PRE_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request);
  10467. $solver = new Solver($policy, $pool, $installedRepo);
  10468. try {
  10469. $operations = $solver->solve($request, $this->ignorePlatformReqs);
  10470. $this->eventDispatcher->dispatchInstallerEvent(InstallerEvents::POST_DEPENDENCIES_SOLVING, $this->devMode, $policy, $pool, $installedRepo, $request, $operations);
  10471. } catch (SolverProblemsException $e) {
  10472. $this->io->writeError('<error>Your requirements could not be resolved to an installable set of packages.</error>');
  10473. $this->io->writeError($e->getMessage());
  10474. return max(1, $e->getCode());
  10475. }
  10476. $operations = $this->processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, 'force-updates', $operations);
  10477. if (!$operations) {
  10478. $this->io->writeError('Nothing to install or update');
  10479. }
  10480. $operations = $this->movePluginsToFront($operations);
  10481. $operations = $this->moveUninstallsToFront($operations);
  10482. foreach ($operations as $operation) {
  10483. if ('install' === $operation->getJobType()) {
  10484. foreach ($operation->getPackage()->getSuggests() as $target => $reason) {
  10485. $this->suggestedPackages[] = array(
  10486. 'source' => $operation->getPackage()->getPrettyName(),
  10487. 'target' => $target,
  10488. 'reason' => $reason,
  10489. );
  10490. }
  10491. }
  10492. if (!$installFromLock) {
  10493. $package = null;
  10494. if ('update' === $operation->getJobType()) {
  10495. $package = $operation->getTargetPackage();
  10496. } elseif ('install' === $operation->getJobType()) {
  10497. $package = $operation->getPackage();
  10498. }
  10499. if ($package && $package->isDev()) {
  10500. $references = $this->package->getReferences();
  10501. if (isset($references[$package->getName()])) {
  10502. $package->setSourceReference($references[$package->getName()]);
  10503. $package->setDistReference($references[$package->getName()]);
  10504. }
  10505. }
  10506. if ('update' === $operation->getJobType()
  10507. && $operation->getTargetPackage()->isDev()
  10508. && $operation->getTargetPackage()->getVersion() === $operation->getInitialPackage()->getVersion()
  10509. && $operation->getTargetPackage()->getSourceReference() === $operation->getInitialPackage()->getSourceReference()
  10510. ) {
  10511. if ($this->io->isDebug()) {
  10512. $this->io->writeError(' - Skipping update of '. $operation->getTargetPackage()->getPrettyName().' to the same reference-locked version');
  10513. $this->io->writeError('');
  10514. }
  10515. continue;
  10516. }
  10517. }
  10518. $event = 'Composer\Installer\PackageEvents::PRE_PACKAGE_'.strtoupper($operation->getJobType());
  10519. if (defined($event) && $this->runScripts) {
  10520. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  10521. }
  10522. if ($this->dryRun && false === strpos($operation->getJobType(), 'Alias')) {
  10523. $this->io->writeError(' - ' . $operation);
  10524. $this->io->writeError('');
  10525. } elseif ($this->io->isDebug() && false !== strpos($operation->getJobType(), 'Alias')) {
  10526. $this->io->writeError(' - ' . $operation);
  10527. $this->io->writeError('');
  10528. }
  10529. $this->installationManager->execute($localRepo, $operation);
  10530. if ($this->verbose && $this->io->isVeryVerbose() && in_array($operation->getJobType(), array('install', 'update'))) {
  10531. $reason = $operation->getReason();
  10532. if ($reason instanceof Rule) {
  10533. switch ($reason->getReason()) {
  10534. case Rule::RULE_JOB_INSTALL:
  10535. $this->io->writeError(' REASON: Required by root: '.$reason->getPrettyString($pool));
  10536. $this->io->writeError('');
  10537. break;
  10538. case Rule::RULE_PACKAGE_REQUIRES:
  10539. $this->io->writeError(' REASON: '.$reason->getPrettyString($pool));
  10540. $this->io->writeError('');
  10541. break;
  10542. }
  10543. }
  10544. }
  10545. $event = 'Composer\Installer\PackageEvents::POST_PACKAGE_'.strtoupper($operation->getJobType());
  10546. if (defined($event) && $this->runScripts) {
  10547. $this->eventDispatcher->dispatchPackageEvent(constant($event), $this->devMode, $policy, $pool, $installedRepo, $request, $operations, $operation);
  10548. }
  10549. if (!$this->dryRun) {
  10550. $localRepo->write();
  10551. }
  10552. }
  10553. return 0;
  10554. }
  10555. private function movePluginsToFront(array $operations)
  10556. {
  10557. $installerOps = array();
  10558. foreach ($operations as $idx => $op) {
  10559. if ($op instanceof InstallOperation) {
  10560. $package = $op->getPackage();
  10561. } elseif ($op instanceof UpdateOperation) {
  10562. $package = $op->getTargetPackage();
  10563. } else {
  10564. continue;
  10565. }
  10566. if ($package->getType() === 'composer-plugin' || $package->getType() === 'composer-installer') {
  10567. $requires = array_keys($package->getRequires());
  10568. foreach ($requires as $index => $req) {
  10569. if ($req === 'composer-plugin-api' || preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  10570. unset($requires[$index]);
  10571. }
  10572. }
  10573. if (!count($requires)) {
  10574. $installerOps[] = $op;
  10575. unset($operations[$idx]);
  10576. }
  10577. }
  10578. }
  10579. return array_merge($installerOps, $operations);
  10580. }
  10581. private function moveUninstallsToFront(array $operations)
  10582. {
  10583. $uninstOps = array();
  10584. foreach ($operations as $idx => $op) {
  10585. if ($op instanceof UninstallOperation) {
  10586. $uninstOps[] = $op;
  10587. unset($operations[$idx]);
  10588. }
  10589. }
  10590. return array_merge($uninstOps, $operations);
  10591. }
  10592. private function createPool($withDevReqs, RepositoryInterface $lockedRepository = null)
  10593. {
  10594. if (!$this->update && $this->locker->isLocked()) {
  10595. $minimumStability = $this->locker->getMinimumStability();
  10596. $stabilityFlags = $this->locker->getStabilityFlags();
  10597. $requires = array();
  10598. foreach ($lockedRepository->getPackages() as $package) {
  10599. $constraint = new VersionConstraint('=', $package->getVersion());
  10600. $constraint->setPrettyString($package->getPrettyVersion());
  10601. $requires[$package->getName()] = $constraint;
  10602. }
  10603. } else {
  10604. $minimumStability = $this->package->getMinimumStability();
  10605. $stabilityFlags = $this->package->getStabilityFlags();
  10606. $requires = $this->package->getRequires();
  10607. if ($withDevReqs) {
  10608. $requires = array_merge($requires, $this->package->getDevRequires());
  10609. }
  10610. }
  10611. $rootConstraints = array();
  10612. foreach ($requires as $req => $constraint) {
  10613. if ($this->ignorePlatformReqs && preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $req)) {
  10614. continue;
  10615. }
  10616. if ($constraint instanceof Link) {
  10617. $rootConstraints[$req] = $constraint->getConstraint();
  10618. } else {
  10619. $rootConstraints[$req] = $constraint;
  10620. }
  10621. }
  10622. return new Pool($minimumStability, $stabilityFlags, $rootConstraints);
  10623. }
  10624. private function createPolicy()
  10625. {
  10626. $preferStable = null;
  10627. $preferLowest = null;
  10628. if (!$this->update && $this->locker->isLocked()) {
  10629. $preferStable = $this->locker->getPreferStable();
  10630. $preferLowest = $this->locker->getPreferLowest();
  10631. }
  10632. if (null === $preferStable) {
  10633. $preferStable = $this->preferStable || $this->package->getPreferStable();
  10634. }
  10635. if (null === $preferLowest) {
  10636. $preferLowest = $this->preferLowest;
  10637. }
  10638. return new DefaultPolicy($preferStable, $preferLowest);
  10639. }
  10640. private function createRequest(Pool $pool, RootPackageInterface $rootPackage, PlatformRepository $platformRepo)
  10641. {
  10642. $request = new Request($pool);
  10643. $constraint = new VersionConstraint('=', $rootPackage->getVersion());
  10644. $constraint->setPrettyString($rootPackage->getPrettyVersion());
  10645. $request->install($rootPackage->getName(), $constraint);
  10646. $fixedPackages = $platformRepo->getPackages();
  10647. if ($this->additionalInstalledRepository) {
  10648. $additionalFixedPackages = $this->additionalInstalledRepository->getPackages();
  10649. $fixedPackages = array_merge($fixedPackages, $additionalFixedPackages);
  10650. }
  10651. $provided = $rootPackage->getProvides();
  10652. foreach ($fixedPackages as $package) {
  10653. $constraint = new VersionConstraint('=', $package->getVersion());
  10654. $constraint->setPrettyString($package->getPrettyVersion());
  10655. if ($package->getRepository() !== $platformRepo
  10656. || !isset($provided[$package->getName()])
  10657. || !$provided[$package->getName()]->getConstraint()->matches($constraint)
  10658. ) {
  10659. $request->fix($package->getName(), $constraint);
  10660. }
  10661. }
  10662. return $request;
  10663. }
  10664. private function processDevPackages($localRepo, $pool, $policy, $repositories, $lockedRepository, $installFromLock, $task, array $operations = null)
  10665. {
  10666. if ($task === 'force-updates' && null === $operations) {
  10667. throw new \InvalidArgumentException('Missing operations argument');
  10668. }
  10669. if ($task === 'force-links') {
  10670. $operations = array();
  10671. }
  10672. foreach ($localRepo->getCanonicalPackages() as $package) {
  10673. if (!$package->isDev()) {
  10674. continue;
  10675. }
  10676. foreach ($operations as $operation) {
  10677. if (('update' === $operation->getJobType() && $operation->getInitialPackage()->equals($package))
  10678. || ('uninstall' === $operation->getJobType() && $operation->getPackage()->equals($package))
  10679. ) {
  10680. continue 2;
  10681. }
  10682. }
  10683. if ($installFromLock) {
  10684. foreach ($lockedRepository->findPackages($package->getName()) as $lockedPackage) {
  10685. if ($lockedPackage->isDev() && $lockedPackage->getVersion() === $package->getVersion()) {
  10686. if ($task === 'force-links') {
  10687. $package->setRequires($lockedPackage->getRequires());
  10688. $package->setConflicts($lockedPackage->getConflicts());
  10689. $package->setProvides($lockedPackage->getProvides());
  10690. $package->setReplaces($lockedPackage->getReplaces());
  10691. } elseif ($task === 'force-updates') {
  10692. if (($lockedPackage->getSourceReference() && $lockedPackage->getSourceReference() !== $package->getSourceReference())
  10693. || ($lockedPackage->getDistReference() && $lockedPackage->getDistReference() !== $package->getDistReference())
  10694. ) {
  10695. $operations[] = new UpdateOperation($package, $lockedPackage);
  10696. }
  10697. }
  10698. break;
  10699. }
  10700. }
  10701. } else {
  10702. if ($this->update) {
  10703. if ($this->updateWhitelist && !$this->isUpdateable($package)) {
  10704. continue;
  10705. }
  10706. $matches = $pool->whatProvides($package->getName(), new VersionConstraint('=', $package->getVersion()));
  10707. foreach ($matches as $index => $match) {
  10708. if (!in_array($match->getRepository(), $repositories, true)) {
  10709. unset($matches[$index]);
  10710. continue;
  10711. }
  10712. if ($match->getName() !== $package->getName()) {
  10713. unset($matches[$index]);
  10714. continue;
  10715. }
  10716. $matches[$index] = $match->getId();
  10717. }
  10718. if ($matches && $matches = $policy->selectPreferedPackages($pool, array(), $matches)) {
  10719. $newPackage = $pool->literalToPackage($matches[0]);
  10720. if ($task === 'force-links' && $newPackage) {
  10721. $package->setRequires($newPackage->getRequires());
  10722. $package->setConflicts($newPackage->getConflicts());
  10723. $package->setProvides($newPackage->getProvides());
  10724. $package->setReplaces($newPackage->getReplaces());
  10725. }
  10726. if ($task === 'force-updates' && $newPackage && (
  10727. (($newPackage->getSourceReference() && $newPackage->getSourceReference() !== $package->getSourceReference())
  10728. || ($newPackage->getDistReference() && $newPackage->getDistReference() !== $package->getDistReference())
  10729. )
  10730. )) {
  10731. $operations[] = new UpdateOperation($package, $newPackage);
  10732. }
  10733. }
  10734. }
  10735. if ($task === 'force-updates') {
  10736. $references = $this->package->getReferences();
  10737. if (isset($references[$package->getName()]) && $references[$package->getName()] !== $package->getSourceReference()) {
  10738. $operations[] = new UpdateOperation($package, clone $package);
  10739. }
  10740. }
  10741. }
  10742. }
  10743. return $operations;
  10744. }
  10745. private function getRootAliases()
  10746. {
  10747. if (!$this->update && $this->locker->isLocked()) {
  10748. $aliases = $this->locker->getAliases();
  10749. } else {
  10750. $aliases = $this->package->getAliases();
  10751. }
  10752. $normalizedAliases = array();
  10753. foreach ($aliases as $alias) {
  10754. $normalizedAliases[$alias['package']][$alias['version']] = array(
  10755. 'alias' => $alias['alias'],
  10756. 'alias_normalized' => $alias['alias_normalized']
  10757. );
  10758. }
  10759. return $normalizedAliases;
  10760. }
  10761. private function aliasPlatformPackages(PlatformRepository $platformRepo, $aliases)
  10762. {
  10763. foreach ($aliases as $package => $versions) {
  10764. foreach ($versions as $version => $alias) {
  10765. $packages = $platformRepo->findPackages($package, $version);
  10766. foreach ($packages as $package) {
  10767. $aliasPackage = new AliasPackage($package, $alias['alias_normalized'], $alias['alias']);
  10768. $aliasPackage->setRootPackageAlias(true);
  10769. $platformRepo->addPackage($aliasPackage);
  10770. }
  10771. }
  10772. }
  10773. }
  10774. private function isUpdateable(PackageInterface $package)
  10775. {
  10776. if (!$this->updateWhitelist) {
  10777. throw new \LogicException('isUpdateable should only be called when a whitelist is present');
  10778. }
  10779. foreach ($this->updateWhitelist as $whiteListedPattern => $void) {
  10780. $patternRegexp = $this->packageNameToRegexp($whiteListedPattern);
  10781. if (preg_match($patternRegexp, $package->getName())) {
  10782. return true;
  10783. }
  10784. }
  10785. return false;
  10786. }
  10787. private function packageNameToRegexp($whiteListedPattern)
  10788. {
  10789. $cleanedWhiteListedPattern = str_replace('\\*', '.*', preg_quote($whiteListedPattern));
  10790. return "{^" . $cleanedWhiteListedPattern . "$}i";
  10791. }
  10792. private function extractPlatformRequirements($links)
  10793. {
  10794. $platformReqs = array();
  10795. foreach ($links as $link) {
  10796. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $link->getTarget())) {
  10797. $platformReqs[$link->getTarget()] = $link->getPrettyConstraint();
  10798. }
  10799. }
  10800. return $platformReqs;
  10801. }
  10802. private function whitelistUpdateDependencies($localRepo, $devMode, array $rootRequires, array $rootDevRequires)
  10803. {
  10804. if (!$this->updateWhitelist) {
  10805. return;
  10806. }
  10807. $requiredPackageNames = array();
  10808. foreach (array_merge($rootRequires, $rootDevRequires) as $require) {
  10809. $requiredPackageNames[] = $require->getTarget();
  10810. }
  10811. if ($devMode) {
  10812. $rootRequires = array_merge($rootRequires, $rootDevRequires);
  10813. }
  10814. $skipPackages = array();
  10815. foreach ($rootRequires as $require) {
  10816. $skipPackages[$require->getTarget()] = true;
  10817. }
  10818. $pool = new Pool;
  10819. $pool->addRepository($localRepo);
  10820. $seen = array();
  10821. $rootRequiredPackageNames = array_keys($rootRequires);
  10822. foreach ($this->updateWhitelist as $packageName => $void) {
  10823. $packageQueue = new \SplQueue;
  10824. $depPackages = $pool->whatProvides($packageName);
  10825. $nameMatchesRequiredPackage = in_array($packageName, $requiredPackageNames, true);
  10826. if (!$nameMatchesRequiredPackage) {
  10827. $whitelistPatternRegexp = $this->packageNameToRegexp($packageName);
  10828. foreach ($rootRequiredPackageNames as $rootRequiredPackageName) {
  10829. if (preg_match($whitelistPatternRegexp, $rootRequiredPackageName)) {
  10830. $nameMatchesRequiredPackage = true;
  10831. break;
  10832. }
  10833. }
  10834. }
  10835. if (count($depPackages) == 0 && !$nameMatchesRequiredPackage && !in_array($packageName, array('nothing', 'lock'))) {
  10836. $this->io->writeError('<warning>Package "' . $packageName . '" listed for update is not installed. Ignoring.</warning>');
  10837. }
  10838. foreach ($depPackages as $depPackage) {
  10839. $packageQueue->enqueue($depPackage);
  10840. }
  10841. while (!$packageQueue->isEmpty()) {
  10842. $package = $packageQueue->dequeue();
  10843. if (isset($seen[$package->getId()])) {
  10844. continue;
  10845. }
  10846. $seen[$package->getId()] = true;
  10847. $this->updateWhitelist[$package->getName()] = true;
  10848. if (!$this->whitelistDependencies) {
  10849. continue;
  10850. }
  10851. $requires = $package->getRequires();
  10852. foreach ($requires as $require) {
  10853. $requirePackages = $pool->whatProvides($require->getTarget());
  10854. foreach ($requirePackages as $requirePackage) {
  10855. if (isset($skipPackages[$requirePackage->getName()])) {
  10856. continue;
  10857. }
  10858. $packageQueue->enqueue($requirePackage);
  10859. }
  10860. }
  10861. }
  10862. }
  10863. }
  10864. private function mockLocalRepositories(RepositoryManager $rm)
  10865. {
  10866. $packages = array();
  10867. foreach ($rm->getLocalRepository()->getPackages() as $package) {
  10868. $packages[(string) $package] = clone $package;
  10869. }
  10870. foreach ($packages as $key => $package) {
  10871. if ($package instanceof AliasPackage) {
  10872. $alias = (string) $package->getAliasOf();
  10873. $packages[$key] = new AliasPackage($packages[$alias], $package->getVersion(), $package->getPrettyVersion());
  10874. }
  10875. }
  10876. $rm->setLocalRepository(
  10877. new InstalledArrayRepository($packages)
  10878. );
  10879. }
  10880. public static function create(IOInterface $io, Composer $composer)
  10881. {
  10882. return new static(
  10883. $io,
  10884. $composer->getConfig(),
  10885. $composer->getPackage(),
  10886. $composer->getDownloadManager(),
  10887. $composer->getRepositoryManager(),
  10888. $composer->getLocker(),
  10889. $composer->getInstallationManager(),
  10890. $composer->getEventDispatcher(),
  10891. $composer->getAutoloadGenerator()
  10892. );
  10893. }
  10894. public function setAdditionalInstalledRepository(RepositoryInterface $additionalInstalledRepository)
  10895. {
  10896. $this->additionalInstalledRepository = $additionalInstalledRepository;
  10897. return $this;
  10898. }
  10899. public function setDryRun($dryRun = true)
  10900. {
  10901. $this->dryRun = (boolean) $dryRun;
  10902. return $this;
  10903. }
  10904. public function isDryRun()
  10905. {
  10906. return $this->dryRun;
  10907. }
  10908. public function setPreferSource($preferSource = true)
  10909. {
  10910. $this->preferSource = (boolean) $preferSource;
  10911. return $this;
  10912. }
  10913. public function setPreferDist($preferDist = true)
  10914. {
  10915. $this->preferDist = (boolean) $preferDist;
  10916. return $this;
  10917. }
  10918. public function setOptimizeAutoloader($optimizeAutoloader = false)
  10919. {
  10920. $this->optimizeAutoloader = (boolean) $optimizeAutoloader;
  10921. return $this;
  10922. }
  10923. public function setUpdate($update = true)
  10924. {
  10925. $this->update = (boolean) $update;
  10926. return $this;
  10927. }
  10928. public function setDevMode($devMode = true)
  10929. {
  10930. $this->devMode = (boolean) $devMode;
  10931. return $this;
  10932. }
  10933. public function setDumpAutoloader($dumpAutoloader = true)
  10934. {
  10935. $this->dumpAutoloader = (boolean) $dumpAutoloader;
  10936. return $this;
  10937. }
  10938. public function setRunScripts($runScripts = true)
  10939. {
  10940. $this->runScripts = (boolean) $runScripts;
  10941. return $this;
  10942. }
  10943. public function setConfig(Config $config)
  10944. {
  10945. $this->config = $config;
  10946. return $this;
  10947. }
  10948. public function setVerbose($verbose = true)
  10949. {
  10950. $this->verbose = (boolean) $verbose;
  10951. return $this;
  10952. }
  10953. public function isVerbose()
  10954. {
  10955. return $this->verbose;
  10956. }
  10957. public function setIgnorePlatformRequirements($ignorePlatformReqs = false)
  10958. {
  10959. $this->ignorePlatformReqs = (boolean) $ignorePlatformReqs;
  10960. return $this;
  10961. }
  10962. public function setUpdateWhitelist(array $packages)
  10963. {
  10964. $this->updateWhitelist = array_flip(array_map('strtolower', $packages));
  10965. return $this;
  10966. }
  10967. public function setWhitelistDependencies($updateDependencies = true)
  10968. {
  10969. $this->whitelistDependencies = (boolean) $updateDependencies;
  10970. return $this;
  10971. }
  10972. public function setPreferStable($preferStable = true)
  10973. {
  10974. $this->preferStable = (boolean) $preferStable;
  10975. return $this;
  10976. }
  10977. public function setPreferLowest($preferLowest = true)
  10978. {
  10979. $this->preferLowest = (boolean) $preferLowest;
  10980. return $this;
  10981. }
  10982. public function disablePlugins()
  10983. {
  10984. $this->installationManager->disablePlugins();
  10985. return $this;
  10986. }
  10987. }
  10988. <?php
  10989. namespace Composer\IO;
  10990. use Composer\Config;
  10991. abstract class BaseIO implements IOInterface
  10992. {
  10993. protected $authentications = array();
  10994. public function getAuthentications()
  10995. {
  10996. return $this->authentications;
  10997. }
  10998. public function hasAuthentication($repositoryName)
  10999. {
  11000. return isset($this->authentications[$repositoryName]);
  11001. }
  11002. public function getAuthentication($repositoryName)
  11003. {
  11004. if (isset($this->authentications[$repositoryName])) {
  11005. return $this->authentications[$repositoryName];
  11006. }
  11007. return array('username' => null, 'password' => null);
  11008. }
  11009. public function setAuthentication($repositoryName, $username, $password = null)
  11010. {
  11011. $this->authentications[$repositoryName] = array('username' => $username, 'password' => $password);
  11012. }
  11013. public function loadConfiguration(Config $config)
  11014. {
  11015. if ($tokens = $config->get('github-oauth')) {
  11016. foreach ($tokens as $domain => $token) {
  11017. if (!preg_match('{^[a-z0-9]+$}', $token)) {
  11018. throw new \UnexpectedValueException('Your github oauth token for '.$domain.' contains invalid characters: "'.$token.'"');
  11019. }
  11020. $this->setAuthentication($domain, $token, 'x-oauth-basic');
  11021. }
  11022. }
  11023. if ($tokens = $config->get('gitlab-oauth')) {
  11024. foreach ($tokens as $domain => $token) {
  11025. $this->setAuthentication($domain, $token, 'oauth2');
  11026. }
  11027. }
  11028. if ($creds = $config->get('http-basic')) {
  11029. foreach ($creds as $domain => $cred) {
  11030. $this->setAuthentication($domain, $cred['username'], $cred['password']);
  11031. }
  11032. }
  11033. }
  11034. }
  11035. <?php
  11036. namespace Composer\IO;
  11037. use Symfony\Component\Console\Output\StreamOutput;
  11038. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  11039. use Symfony\Component\Console\Input\StringInput;
  11040. use Symfony\Component\Console\Helper\HelperSet;
  11041. class BufferIO extends ConsoleIO
  11042. {
  11043. public function __construct(
  11044. $input = '',
  11045. $verbosity = StreamOutput::VERBOSITY_NORMAL,
  11046. OutputFormatterInterface $formatter = null
  11047. ) {
  11048. $input = new StringInput($input);
  11049. $input->setInteractive(false);
  11050. $output = new StreamOutput(fopen('php://memory', 'rw'), $verbosity, !empty($formatter), $formatter);
  11051. parent::__construct($input, $output, new HelperSet(array()));
  11052. }
  11053. public function getOutput()
  11054. {
  11055. fseek($this->output->getStream(), 0);
  11056. $output = stream_get_contents($this->output->getStream());
  11057. $output = preg_replace_callback("{(?<=^|\n|\x08)(.+?)(\x08+)}", function ($matches) {
  11058. $pre = strip_tags($matches[1]);
  11059. if (strlen($pre) === strlen($matches[2])) {
  11060. return '';
  11061. }
  11062. return rtrim($matches[1])."\n";
  11063. }, $output);
  11064. return $output;
  11065. }
  11066. }
  11067. <?php
  11068. namespace Composer\IO;
  11069. use Symfony\Component\Console\Input\InputInterface;
  11070. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  11071. use Symfony\Component\Console\Output\OutputInterface;
  11072. use Symfony\Component\Console\Helper\HelperSet;
  11073. use Symfony\Component\Process\ExecutableFinder;
  11074. class ConsoleIO extends BaseIO
  11075. {
  11076. protected $input;
  11077. protected $output;
  11078. protected $helperSet;
  11079. protected $lastMessage;
  11080. protected $lastMessageErr;
  11081. private $startTime;
  11082. public function __construct(InputInterface $input, OutputInterface $output, HelperSet $helperSet)
  11083. {
  11084. $this->input = $input;
  11085. $this->output = $output;
  11086. $this->helperSet = $helperSet;
  11087. }
  11088. public function enableDebugging($startTime)
  11089. {
  11090. $this->startTime = $startTime;
  11091. }
  11092. public function isInteractive()
  11093. {
  11094. return $this->input->isInteractive();
  11095. }
  11096. public function isDecorated()
  11097. {
  11098. return $this->output->isDecorated();
  11099. }
  11100. public function isVerbose()
  11101. {
  11102. return $this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE;
  11103. }
  11104. public function isVeryVerbose()
  11105. {
  11106. return $this->output->getVerbosity() >= 3;
  11107. }
  11108. public function isDebug()
  11109. {
  11110. return $this->output->getVerbosity() >= 4;
  11111. }
  11112. public function write($messages, $newline = true)
  11113. {
  11114. $this->doWrite($messages, $newline, false);
  11115. }
  11116. public function writeError($messages, $newline = true)
  11117. {
  11118. $this->doWrite($messages, $newline, true);
  11119. }
  11120. private function doWrite($messages, $newline, $stderr)
  11121. {
  11122. if (null !== $this->startTime) {
  11123. $memoryUsage = memory_get_usage() / 1024 / 1024;
  11124. $timeSpent = microtime(true) - $this->startTime;
  11125. $messages = array_map(function ($message) use ($memoryUsage, $timeSpent) {
  11126. return sprintf('[%.1fMB/%.2fs] %s', $memoryUsage, $timeSpent, $message);
  11127. }, (array) $messages);
  11128. }
  11129. if (true === $stderr && $this->output instanceof ConsoleOutputInterface) {
  11130. $this->output->getErrorOutput()->write($messages, $newline);
  11131. $this->lastMessageErr = join($newline ? "\n" : '', (array) $messages);
  11132. return;
  11133. }
  11134. $this->output->write($messages, $newline);
  11135. $this->lastMessage = join($newline ? "\n" : '', (array) $messages);
  11136. }
  11137. public function overwrite($messages, $newline = true, $size = null)
  11138. {
  11139. $this->doOverwrite($messages, $newline, $size, false);
  11140. }
  11141. public function overwriteError($messages, $newline = true, $size = null)
  11142. {
  11143. $this->doOverwrite($messages, $newline, $size, true);
  11144. }
  11145. private function doOverwrite($messages, $newline, $size, $stderr)
  11146. {
  11147. if (true === $stderr && $this->output instanceof ConsoleOutputInterface) {
  11148. $output = $this->output->getErrorOutput();
  11149. } else {
  11150. $output = $this->output;
  11151. }
  11152. if (!$output->isDecorated()) {
  11153. if (!$messages) {
  11154. return;
  11155. }
  11156. $this->doWrite($messages, count($messages) === 1 || $newline, $stderr);
  11157. return;
  11158. }
  11159. $messages = join($newline ? "\n" : '', (array) $messages);
  11160. if (!isset($size)) {
  11161. $size = strlen(strip_tags($stderr ? $this->lastMessageErr : $this->lastMessage));
  11162. }
  11163. $this->doWrite(str_repeat("\x08", $size), false, $stderr);
  11164. $this->doWrite($messages, false, $stderr);
  11165. $fill = $size - strlen(strip_tags($messages));
  11166. if ($fill > 0) {
  11167. $this->doWrite(str_repeat(' ', $fill), false, $stderr);
  11168. $this->doWrite(str_repeat("\x08", $fill), false, $stderr);
  11169. }
  11170. if ($newline) {
  11171. $this->doWrite('', true, $stderr);
  11172. }
  11173. $this->lastMessage = $messages;
  11174. }
  11175. public function ask($question, $default = null)
  11176. {
  11177. $output = $this->output;
  11178. if ($output instanceof ConsoleOutputInterface) {
  11179. $output = $output->getErrorOutput();
  11180. }
  11181. $dialog = $this->helperSet->get('dialog');
  11182. return $dialog->ask($output, $question, $default);
  11183. }
  11184. public function askConfirmation($question, $default = true)
  11185. {
  11186. $output = $this->output;
  11187. if ($output instanceof ConsoleOutputInterface) {
  11188. $output = $output->getErrorOutput();
  11189. }
  11190. $dialog = $this->helperSet->get('dialog');
  11191. return $dialog->askConfirmation($output, $question, $default);
  11192. }
  11193. public function askAndValidate($question, $validator, $attempts = false, $default = null)
  11194. {
  11195. $output = $this->output;
  11196. if ($output instanceof ConsoleOutputInterface) {
  11197. $output = $output->getErrorOutput();
  11198. }
  11199. $dialog = $this->helperSet->get('dialog');
  11200. return $dialog->askAndValidate($output, $question, $validator, $attempts, $default);
  11201. }
  11202. public function askAndHideAnswer($question)
  11203. {
  11204. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  11205. $finder = new ExecutableFinder();
  11206. if ($finder->find('bash') && $finder->find('stty')) {
  11207. $this->writeError($question, false);
  11208. $value = rtrim(shell_exec('bash -c "stty -echo; read -n0 discard; read -r mypassword; stty echo; echo $mypassword"'));
  11209. $this->writeError('');
  11210. return $value;
  11211. }
  11212. $exe = __DIR__.'\\hiddeninput.exe';
  11213. if ('phar:' === substr(__FILE__, 0, 5)) {
  11214. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  11215. $source = fopen(__DIR__.'\\hiddeninput.exe', 'r');
  11216. $target = fopen($tmpExe, 'w+');
  11217. stream_copy_to_stream($source, $target);
  11218. fclose($source);
  11219. fclose($target);
  11220. unset($source, $target);
  11221. $exe = $tmpExe;
  11222. }
  11223. $this->writeError($question, false);
  11224. $value = rtrim(shell_exec($exe));
  11225. $this->writeError('');
  11226. if (isset($tmpExe)) {
  11227. unlink($tmpExe);
  11228. }
  11229. return $value;
  11230. }
  11231. if (file_exists('/usr/bin/env')) {
  11232. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  11233. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  11234. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  11235. $shell = $sh;
  11236. break;
  11237. }
  11238. }
  11239. if (isset($shell)) {
  11240. $this->writeError($question, false);
  11241. $readCmd = ($shell === 'csh') ? 'set mypassword = $<' : 'read -r mypassword';
  11242. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  11243. $value = rtrim(shell_exec($command));
  11244. $this->writeError('');
  11245. return $value;
  11246. }
  11247. }
  11248. return $this->ask($question);
  11249. }
  11250. }
  11251. <?php
  11252. namespace Composer\IO;
  11253. use Composer\Config;
  11254. interface IOInterface
  11255. {
  11256. public function isInteractive();
  11257. public function isVerbose();
  11258. public function isVeryVerbose();
  11259. public function isDebug();
  11260. public function isDecorated();
  11261. public function write($messages, $newline = true);
  11262. public function writeError($messages, $newline = true);
  11263. public function overwrite($messages, $newline = true, $size = null);
  11264. public function overwriteError($messages, $newline = true, $size = null);
  11265. public function ask($question, $default = null);
  11266. public function askConfirmation($question, $default = true);
  11267. public function askAndValidate($question, $validator, $attempts = false, $default = null);
  11268. public function askAndHideAnswer($question);
  11269. public function getAuthentications();
  11270. public function hasAuthentication($repositoryName);
  11271. public function getAuthentication($repositoryName);
  11272. public function setAuthentication($repositoryName, $username, $password = null);
  11273. public function loadConfiguration(Config $config);
  11274. }
  11275. <?php
  11276. namespace Composer\IO;
  11277. class NullIO extends BaseIO
  11278. {
  11279. public function isInteractive()
  11280. {
  11281. return false;
  11282. }
  11283. public function isVerbose()
  11284. {
  11285. return false;
  11286. }
  11287. public function isVeryVerbose()
  11288. {
  11289. return false;
  11290. }
  11291. public function isDebug()
  11292. {
  11293. return false;
  11294. }
  11295. public function isDecorated()
  11296. {
  11297. return false;
  11298. }
  11299. public function write($messages, $newline = true)
  11300. {
  11301. }
  11302. public function writeError($messages, $newline = true)
  11303. {
  11304. }
  11305. public function overwrite($messages, $newline = true, $size = 80)
  11306. {
  11307. }
  11308. public function overwriteError($messages, $newline = true, $size = 80)
  11309. {
  11310. }
  11311. public function ask($question, $default = null)
  11312. {
  11313. return $default;
  11314. }
  11315. public function askConfirmation($question, $default = true)
  11316. {
  11317. return $default;
  11318. }
  11319. public function askAndValidate($question, $validator, $attempts = false, $default = null)
  11320. {
  11321. return $default;
  11322. }
  11323. public function askAndHideAnswer($question)
  11324. {
  11325. return null;
  11326. }
  11327. }
  11328. <?php
  11329. namespace Composer\Json;
  11330. use JsonSchema\Validator;
  11331. use Seld\JsonLint\JsonParser;
  11332. use Seld\JsonLint\ParsingException;
  11333. use Composer\Util\RemoteFilesystem;
  11334. use Composer\Downloader\TransportException;
  11335. class JsonFile
  11336. {
  11337. const LAX_SCHEMA = 1;
  11338. const STRICT_SCHEMA = 2;
  11339. const JSON_UNESCAPED_SLASHES = 64;
  11340. const JSON_PRETTY_PRINT = 128;
  11341. const JSON_UNESCAPED_UNICODE = 256;
  11342. private $path;
  11343. private $rfs;
  11344. public function __construct($path, RemoteFilesystem $rfs = null)
  11345. {
  11346. $this->path = $path;
  11347. if (null === $rfs && preg_match('{^https?://}i', $path)) {
  11348. throw new \InvalidArgumentException('http urls require a RemoteFilesystem instance to be passed');
  11349. }
  11350. $this->rfs = $rfs;
  11351. }
  11352. public function getPath()
  11353. {
  11354. return $this->path;
  11355. }
  11356. public function exists()
  11357. {
  11358. return is_file($this->path);
  11359. }
  11360. public function read()
  11361. {
  11362. try {
  11363. if ($this->rfs) {
  11364. $json = $this->rfs->getContents($this->path, $this->path, false);
  11365. } else {
  11366. $json = file_get_contents($this->path);
  11367. }
  11368. } catch (TransportException $e) {
  11369. throw new \RuntimeException($e->getMessage(), 0, $e);
  11370. } catch (\Exception $e) {
  11371. throw new \RuntimeException('Could not read '.$this->path."\n\n".$e->getMessage());
  11372. }
  11373. return static::parseJson($json, $this->path);
  11374. }
  11375. public function write(array $hash, $options = 448)
  11376. {
  11377. $dir = dirname($this->path);
  11378. if (!is_dir($dir)) {
  11379. if (file_exists($dir)) {
  11380. throw new \UnexpectedValueException(
  11381. $dir.' exists and is not a directory.'
  11382. );
  11383. }
  11384. if (!@mkdir($dir, 0777, true)) {
  11385. throw new \UnexpectedValueException(
  11386. $dir.' does not exist and could not be created.'
  11387. );
  11388. }
  11389. }
  11390. $retries = 3;
  11391. while ($retries--) {
  11392. try {
  11393. file_put_contents($this->path, static::encode($hash, $options). ($options & self::JSON_PRETTY_PRINT ? "\n" : ''));
  11394. break;
  11395. } catch (\Exception $e) {
  11396. if ($retries) {
  11397. usleep(500000);
  11398. continue;
  11399. }
  11400. throw $e;
  11401. }
  11402. }
  11403. }
  11404. public function validateSchema($schema = self::STRICT_SCHEMA)
  11405. {
  11406. $content = file_get_contents($this->path);
  11407. $data = json_decode($content);
  11408. if (null === $data && 'null' !== $content) {
  11409. self::validateSyntax($content, $this->path);
  11410. }
  11411. $schemaFile = __DIR__ . '/../../../res/composer-schema.json';
  11412. $schemaData = json_decode(file_get_contents($schemaFile));
  11413. if ($schema === self::LAX_SCHEMA) {
  11414. $schemaData->additionalProperties = true;
  11415. $schemaData->required = array();
  11416. }
  11417. $validator = new Validator();
  11418. $validator->check($data, $schemaData);
  11419. if (!$validator->isValid()) {
  11420. $errors = array();
  11421. foreach ((array) $validator->getErrors() as $error) {
  11422. $errors[] = ($error['property'] ? $error['property'].' : ' : '').$error['message'];
  11423. }
  11424. throw new JsonValidationException('"'.$this->path.'" does not match the expected JSON schema', $errors);
  11425. }
  11426. return true;
  11427. }
  11428. public static function encode($data, $options = 448)
  11429. {
  11430. if (version_compare(PHP_VERSION, '5.4', '>=')) {
  11431. $json = json_encode($data, $options);
  11432. if (PHP_VERSION_ID < 50428 || (PHP_VERSION_ID >= 50500 && PHP_VERSION_ID < 50512) || (defined('JSON_C_VERSION') && version_compare(phpversion('json'), '1.3.6', '<'))) {
  11433. $json = preg_replace('/\[\s+\]/', '[]', $json);
  11434. $json = preg_replace('/\{\s+\}/', '{}', $json);
  11435. }
  11436. return $json;
  11437. }
  11438. $json = json_encode($data);
  11439. $prettyPrint = (bool) ($options & self::JSON_PRETTY_PRINT);
  11440. $unescapeUnicode = (bool) ($options & self::JSON_UNESCAPED_UNICODE);
  11441. $unescapeSlashes = (bool) ($options & self::JSON_UNESCAPED_SLASHES);
  11442. if (!$prettyPrint && !$unescapeUnicode && !$unescapeSlashes) {
  11443. return $json;
  11444. }
  11445. $result = JsonFormatter::format($json, $unescapeUnicode, $unescapeSlashes);
  11446. return $result;
  11447. }
  11448. public static function parseJson($json, $file = null)
  11449. {
  11450. $data = json_decode($json, true);
  11451. if (null === $data && JSON_ERROR_NONE !== json_last_error()) {
  11452. self::validateSyntax($json, $file);
  11453. }
  11454. return $data;
  11455. }
  11456. protected static function validateSyntax($json, $file = null)
  11457. {
  11458. $parser = new JsonParser();
  11459. $result = $parser->lint($json);
  11460. if (null === $result) {
  11461. if (defined('JSON_ERROR_UTF8') && JSON_ERROR_UTF8 === json_last_error()) {
  11462. throw new \UnexpectedValueException('"'.$file.'" is not UTF-8, could not parse as JSON');
  11463. }
  11464. return true;
  11465. }
  11466. throw new ParsingException('"'.$file.'" does not contain valid JSON'."\n".$result->getMessage(), $result->getDetails());
  11467. }
  11468. }
  11469. <?php
  11470. namespace Composer\Json;
  11471. class JsonFormatter
  11472. {
  11473. public static function format($json, $unescapeUnicode, $unescapeSlashes)
  11474. {
  11475. $result = '';
  11476. $pos = 0;
  11477. $strLen = strlen($json);
  11478. $indentStr = ' ';
  11479. $newLine = "\n";
  11480. $outOfQuotes = true;
  11481. $buffer = '';
  11482. $noescape = true;
  11483. for ($i = 0; $i < $strLen; $i++) {
  11484. $char = substr($json, $i, 1);
  11485. if ('"' === $char && $noescape) {
  11486. $outOfQuotes = !$outOfQuotes;
  11487. }
  11488. if (!$outOfQuotes) {
  11489. $buffer .= $char;
  11490. $noescape = '\\' === $char ? !$noescape : true;
  11491. continue;
  11492. } elseif ('' !== $buffer) {
  11493. if ($unescapeSlashes) {
  11494. $buffer = str_replace('\\/', '/', $buffer);
  11495. }
  11496. if ($unescapeUnicode && function_exists('mb_convert_encoding')) {
  11497. $buffer = preg_replace_callback('/(\\\\+)u([0-9a-f]{4})/i', function ($match) {
  11498. $l = strlen($match[1]);
  11499. if ($l % 2) {
  11500. return str_repeat('\\', $l - 1) . mb_convert_encoding(
  11501. pack('H*', $match[2]),
  11502. 'UTF-8',
  11503. 'UCS-2BE'
  11504. );
  11505. }
  11506. return $match[0];
  11507. }, $buffer);
  11508. }
  11509. $result .= $buffer.$char;
  11510. $buffer = '';
  11511. continue;
  11512. }
  11513. if (':' === $char) {
  11514. $char .= ' ';
  11515. } elseif (('}' === $char || ']' === $char)) {
  11516. $pos--;
  11517. $prevChar = substr($json, $i - 1, 1);
  11518. if ('{' !== $prevChar && '[' !== $prevChar) {
  11519. $result .= $newLine;
  11520. for ($j = 0; $j < $pos; $j++) {
  11521. $result .= $indentStr;
  11522. }
  11523. } else {
  11524. $result = rtrim($result);
  11525. }
  11526. }
  11527. $result .= $char;
  11528. if (',' === $char || '{' === $char || '[' === $char) {
  11529. $result .= $newLine;
  11530. if ('{' === $char || '[' === $char) {
  11531. $pos++;
  11532. }
  11533. for ($j = 0; $j < $pos; $j++) {
  11534. $result .= $indentStr;
  11535. }
  11536. }
  11537. }
  11538. return $result;
  11539. }
  11540. }
  11541. <?php
  11542. namespace Composer\Json;
  11543. class JsonManipulator
  11544. {
  11545. private static $RECURSE_BLOCKS;
  11546. private static $RECURSE_ARRAYS;
  11547. private static $JSON_VALUE;
  11548. private static $JSON_STRING;
  11549. private $contents;
  11550. private $newline;
  11551. private $indent;
  11552. public function __construct($contents)
  11553. {
  11554. if (!self::$RECURSE_BLOCKS) {
  11555. self::$RECURSE_BLOCKS = '(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{(?:[^{}]*|\{[^{}]*\})*\})*\})*\})*';
  11556. self::$RECURSE_ARRAYS = '(?:[^\]]*|\[(?:[^\]]*|\[(?:[^\]]*|\[(?:[^\]]*|\[[^\]]*\])*\])*\])*\]|'.self::$RECURSE_BLOCKS.')*';
  11557. self::$JSON_STRING = '"(?:[^\0-\x09\x0a-\x1f\\\\"]+|\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4})*"';
  11558. self::$JSON_VALUE = '(?:[0-9.]+|null|true|false|'.self::$JSON_STRING.'|\['.self::$RECURSE_ARRAYS.'\]|\{'.self::$RECURSE_BLOCKS.'\})';
  11559. }
  11560. $contents = trim($contents);
  11561. if ($contents === '') {
  11562. $contents = '{}';
  11563. }
  11564. if (!$this->pregMatch('#^\{(.*)\}$#s', $contents)) {
  11565. throw new \InvalidArgumentException('The json file must be an object ({})');
  11566. }
  11567. $this->newline = false !== strpos($contents, "\r\n") ? "\r\n" : "\n";
  11568. $this->contents = $contents === '{}' ? '{' . $this->newline . '}' : $contents;
  11569. $this->detectIndenting();
  11570. }
  11571. public function getContents()
  11572. {
  11573. return $this->contents . $this->newline;
  11574. }
  11575. public function addLink($type, $package, $constraint, $sortPackages = false)
  11576. {
  11577. $decoded = JsonFile::parseJson($this->contents);
  11578. if (!isset($decoded[$type])) {
  11579. return $this->addMainKey($type, array($package => $constraint));
  11580. }
  11581. $regex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
  11582. '('.preg_quote(JsonFile::encode($type)).'\s*:\s*)('.self::$JSON_VALUE.')(.*)}s';
  11583. if (!$this->pregMatch($regex, $this->contents, $matches)) {
  11584. return false;
  11585. }
  11586. $links = $matches[3];
  11587. if (isset($decoded[$type][$package])) {
  11588. $packageRegex = str_replace('/', '\\\\?/', preg_quote($package));
  11589. $links = preg_replace('{"'.$packageRegex.'"(\s*:\s*)'.self::$JSON_STRING.'}i', addcslashes(JsonFile::encode($package).'${1}"'.$constraint.'"', '\\'), $links);
  11590. } else {
  11591. if ($this->pregMatch('#^\s*\{\s*\S+.*?(\s*\}\s*)$#s', $links, $match)) {
  11592. $links = preg_replace(
  11593. '{'.preg_quote($match[1]).'$}',
  11594. addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $match[1], '\\'),
  11595. $links
  11596. );
  11597. } else {
  11598. $links = '{' . $this->newline .
  11599. $this->indent . $this->indent . JsonFile::encode($package).': '.JsonFile::encode($constraint) . $this->newline .
  11600. $this->indent . '}';
  11601. }
  11602. }
  11603. if (true === $sortPackages) {
  11604. $requirements = json_decode($links, true);
  11605. ksort($requirements);
  11606. $links = $this->format($requirements);
  11607. }
  11608. $this->contents = $matches[1] . $matches[2] . $links . $matches[4];
  11609. return true;
  11610. }
  11611. public function addRepository($name, $config)
  11612. {
  11613. return $this->addSubNode('repositories', $name, $config);
  11614. }
  11615. public function removeRepository($name)
  11616. {
  11617. return $this->removeSubNode('repositories', $name);
  11618. }
  11619. public function addConfigSetting($name, $value)
  11620. {
  11621. return $this->addSubNode('config', $name, $value);
  11622. }
  11623. public function removeConfigSetting($name)
  11624. {
  11625. return $this->removeSubNode('config', $name);
  11626. }
  11627. public function addSubNode($mainNode, $name, $value)
  11628. {
  11629. $decoded = JsonFile::parseJson($this->contents);
  11630. if (!isset($decoded[$mainNode])) {
  11631. $this->addMainKey($mainNode, array($name => $value));
  11632. return true;
  11633. }
  11634. $subName = null;
  11635. if (in_array($mainNode, array('config', 'repositories')) && false !== strpos($name, '.')) {
  11636. list($name, $subName) = explode('.', $name, 2);
  11637. }
  11638. $nodeRegex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
  11639. '('.preg_quote(JsonFile::encode($mainNode)).'\s*:\s*\{)('.self::$RECURSE_BLOCKS.')(\})(.*)}s';
  11640. try {
  11641. if (!$this->pregMatch($nodeRegex, $this->contents, $match)) {
  11642. return false;
  11643. }
  11644. } catch (\RuntimeException $e) {
  11645. if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) {
  11646. return false;
  11647. }
  11648. throw $e;
  11649. }
  11650. $children = $match[3];
  11651. if (!@json_decode('{'.$children.'}')) {
  11652. return false;
  11653. }
  11654. $that = $this;
  11655. if ($this->pregMatch('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', $children, $matches)) {
  11656. $children = preg_replace_callback('{("'.preg_quote($name).'"\s*:\s*)('.self::$JSON_VALUE.')(,?)}', function ($matches) use ($name, $subName, $value, $that) {
  11657. if ($subName !== null) {
  11658. $curVal = json_decode($matches[2], true);
  11659. $curVal[$subName] = $value;
  11660. $value = $curVal;
  11661. }
  11662. return $matches[1] . $that->format($value, 1) . $matches[3];
  11663. }, $children);
  11664. } elseif ($this->pregMatch('#[^\s](\s*)$#', $children, $match)) {
  11665. if ($subName !== null) {
  11666. $value = array($subName => $value);
  11667. }
  11668. $children = preg_replace(
  11669. '#'.$match[1].'$#',
  11670. addcslashes(',' . $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $match[1], '\\'),
  11671. $children
  11672. );
  11673. } else {
  11674. if ($subName !== null) {
  11675. $value = array($subName => $value);
  11676. }
  11677. $children = $this->newline . $this->indent . $this->indent . JsonFile::encode($name).': '.$this->format($value, 1) . $children;
  11678. }
  11679. $this->contents = preg_replace($nodeRegex, addcslashes('${1}${2}'.$children.'${4}${5}', '\\'), $this->contents);
  11680. return true;
  11681. }
  11682. public function removeSubNode($mainNode, $name)
  11683. {
  11684. $decoded = JsonFile::parseJson($this->contents);
  11685. if (empty($decoded[$mainNode])) {
  11686. return true;
  11687. }
  11688. $nodeRegex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
  11689. '('.preg_quote(JsonFile::encode($mainNode)).'\s*:\s*\{)('.self::$RECURSE_BLOCKS.')(\})(.*)}s';
  11690. try {
  11691. if (!$this->pregMatch($nodeRegex, $this->contents, $match)) {
  11692. return false;
  11693. }
  11694. } catch (\RuntimeException $e) {
  11695. if ($e->getCode() === PREG_BACKTRACK_LIMIT_ERROR) {
  11696. return false;
  11697. }
  11698. throw $e;
  11699. }
  11700. $children = $match[3];
  11701. if (!@json_decode('{'.$children.'}', true)) {
  11702. return false;
  11703. }
  11704. $subName = null;
  11705. if (in_array($mainNode, array('config', 'repositories')) && false !== strpos($name, '.')) {
  11706. list($name, $subName) = explode('.', $name, 2);
  11707. }
  11708. if (!isset($decoded[$mainNode][$name]) || ($subName && !isset($decoded[$mainNode][$name][$subName]))) {
  11709. return true;
  11710. }
  11711. if ($this->pregMatch('{"'.preg_quote($name).'"\s*:}i', $children)) {
  11712. if (preg_match_all('{"'.preg_quote($name).'"\s*:\s*(?:'.self::$JSON_VALUE.')}', $children, $matches)) {
  11713. $bestMatch = '';
  11714. foreach ($matches[0] as $match) {
  11715. if (strlen($bestMatch) < strlen($match)) {
  11716. $bestMatch = $match;
  11717. }
  11718. }
  11719. $childrenClean = preg_replace('{,\s*'.preg_quote($bestMatch).'}i', '', $children, -1, $count);
  11720. if (1 !== $count) {
  11721. $childrenClean = preg_replace('{'.preg_quote($bestMatch).'\s*,?\s*}i', '', $childrenClean, -1, $count);
  11722. if (1 !== $count) {
  11723. return false;
  11724. }
  11725. }
  11726. }
  11727. } else {
  11728. $childrenClean = $children;
  11729. }
  11730. if (!trim($childrenClean)) {
  11731. $this->contents = preg_replace($nodeRegex, '$1$2'.$this->newline.$this->indent.'$4$5', $this->contents);
  11732. if ($subName !== null) {
  11733. $curVal = json_decode('{'.$children.'}', true);
  11734. unset($curVal[$name][$subName]);
  11735. $this->addSubNode($mainNode, $name, $curVal[$name]);
  11736. }
  11737. return true;
  11738. }
  11739. $that = $this;
  11740. $this->contents = preg_replace_callback($nodeRegex, function ($matches) use ($that, $name, $subName, $childrenClean) {
  11741. if ($subName !== null) {
  11742. $curVal = json_decode('{'.$matches[3].'}', true);
  11743. unset($curVal[$name][$subName]);
  11744. $childrenClean = substr($that->format($curVal, 0), 1, -1);
  11745. }
  11746. return $matches[1] . $matches[2] . $childrenClean . $matches[4] . $matches[5];
  11747. }, $this->contents);
  11748. return true;
  11749. }
  11750. public function addMainKey($key, $content)
  11751. {
  11752. $decoded = JsonFile::parseJson($this->contents);
  11753. $content = $this->format($content);
  11754. $regex = '{^(\s*\{\s*(?:'.self::$JSON_STRING.'\s*:\s*'.self::$JSON_VALUE.'\s*,\s*)*?)'.
  11755. '('.preg_quote(JsonFile::encode($key)).'\s*:\s*'.self::$JSON_VALUE.')(.*)}s';
  11756. if (isset($decoded[$key]) && $this->pregMatch($regex, $this->contents, $matches)) {
  11757. if (!@json_decode('{'.$matches[2].'}')) {
  11758. return false;
  11759. }
  11760. $this->contents = $matches[1] . JsonFile::encode($key).': '.$content . $matches[3];
  11761. return true;
  11762. }
  11763. if ($this->pregMatch('#[^{\s](\s*)\}$#', $this->contents, $match)) {
  11764. $this->contents = preg_replace(
  11765. '#'.$match[1].'\}$#',
  11766. addcslashes(',' . $this->newline . $this->indent . JsonFile::encode($key). ': '. $content . $this->newline . '}', '\\'),
  11767. $this->contents
  11768. );
  11769. return true;
  11770. }
  11771. $this->contents = preg_replace(
  11772. '#\}$#',
  11773. addcslashes($this->indent . JsonFile::encode($key). ': '.$content . $this->newline . '}', '\\'),
  11774. $this->contents
  11775. );
  11776. return true;
  11777. }
  11778. public function format($data, $depth = 0)
  11779. {
  11780. if (is_array($data)) {
  11781. reset($data);
  11782. if (is_numeric(key($data))) {
  11783. foreach ($data as $key => $val) {
  11784. $data[$key] = $this->format($val, $depth + 1);
  11785. }
  11786. return '['.implode(', ', $data).']';
  11787. }
  11788. $out = '{' . $this->newline;
  11789. $elems = array();
  11790. foreach ($data as $key => $val) {
  11791. $elems[] = str_repeat($this->indent, $depth + 2) . JsonFile::encode($key). ': '.$this->format($val, $depth + 1);
  11792. }
  11793. return $out . implode(','.$this->newline, $elems) . $this->newline . str_repeat($this->indent, $depth + 1) . '}';
  11794. }
  11795. return JsonFile::encode($data);
  11796. }
  11797. protected function detectIndenting()
  11798. {
  11799. if ($this->pregMatch('{^(\s+)"}m', $this->contents, $match)) {
  11800. $this->indent = $match[1];
  11801. } else {
  11802. $this->indent = ' ';
  11803. }
  11804. }
  11805. protected function pregMatch($re, $str, &$matches = array())
  11806. {
  11807. $count = preg_match($re, $str, $matches);
  11808. if ($count === false) {
  11809. switch (preg_last_error()) {
  11810. case PREG_NO_ERROR:
  11811. throw new \RuntimeException('Failed to execute regex: PREG_NO_ERROR', PREG_NO_ERROR);
  11812. case PREG_INTERNAL_ERROR:
  11813. throw new \RuntimeException('Failed to execute regex: PREG_INTERNAL_ERROR', PREG_INTERNAL_ERROR);
  11814. case PREG_BACKTRACK_LIMIT_ERROR:
  11815. throw new \RuntimeException('Failed to execute regex: PREG_BACKTRACK_LIMIT_ERROR', PREG_BACKTRACK_LIMIT_ERROR);
  11816. case PREG_RECURSION_LIMIT_ERROR:
  11817. throw new \RuntimeException('Failed to execute regex: PREG_RECURSION_LIMIT_ERROR', PREG_RECURSION_LIMIT_ERROR);
  11818. case PREG_BAD_UTF8_ERROR:
  11819. throw new \RuntimeException('Failed to execute regex: PREG_BAD_UTF8_ERROR', PREG_BAD_UTF8_ERROR);
  11820. case PREG_BAD_UTF8_OFFSET_ERROR:
  11821. throw new \RuntimeException('Failed to execute regex: PREG_BAD_UTF8_OFFSET_ERROR', PREG_BAD_UTF8_OFFSET_ERROR);
  11822. default:
  11823. throw new \RuntimeException('Failed to execute regex: Unknown error');
  11824. }
  11825. }
  11826. return $count;
  11827. }
  11828. }
  11829. <?php
  11830. namespace Composer\Json;
  11831. use Exception;
  11832. class JsonValidationException extends Exception
  11833. {
  11834. protected $errors;
  11835. public function __construct($message, $errors = array(), Exception $previous = null)
  11836. {
  11837. $this->errors = $errors;
  11838. parent::__construct($message, 0, $previous);
  11839. }
  11840. public function getErrors()
  11841. {
  11842. return $this->errors;
  11843. }
  11844. }
  11845. <?php
  11846. namespace Composer\Package;
  11847. use Composer\Package\LinkConstraint\VersionConstraint;
  11848. use Composer\Package\Version\VersionParser;
  11849. class AliasPackage extends BasePackage implements CompletePackageInterface
  11850. {
  11851. protected $version;
  11852. protected $prettyVersion;
  11853. protected $dev;
  11854. protected $aliasOf;
  11855. protected $rootPackageAlias = false;
  11856. protected $stability;
  11857. protected $requires;
  11858. protected $conflicts;
  11859. protected $provides;
  11860. protected $replaces;
  11861. protected $recommends;
  11862. protected $suggests;
  11863. public function __construct(PackageInterface $aliasOf, $version, $prettyVersion)
  11864. {
  11865. parent::__construct($aliasOf->getName());
  11866. $this->version = $version;
  11867. $this->prettyVersion = $prettyVersion;
  11868. $this->aliasOf = $aliasOf;
  11869. $this->stability = VersionParser::parseStability($version);
  11870. $this->dev = $this->stability === 'dev';
  11871. foreach (array('requires', 'devRequires') as $type) {
  11872. $links = $aliasOf->{'get'.ucfirst($type)}();
  11873. foreach ($links as $index => $link) {
  11874. if ('self.version' === $link->getPrettyConstraint()) {
  11875. $links[$index] = new Link($link->getSource(), $link->getTarget(), new VersionConstraint('=', $this->version), $type, $prettyVersion);
  11876. }
  11877. }
  11878. $this->$type = $links;
  11879. }
  11880. foreach (array('conflicts', 'provides', 'replaces') as $type) {
  11881. $links = $aliasOf->{'get'.ucfirst($type)}();
  11882. $newLinks = array();
  11883. foreach ($links as $link) {
  11884. if ('self.version' === $link->getPrettyConstraint()) {
  11885. $newLinks[] = new Link($link->getSource(), $link->getTarget(), new VersionConstraint('=', $this->version), $type, $prettyVersion);
  11886. }
  11887. }
  11888. $this->$type = array_merge($links, $newLinks);
  11889. }
  11890. }
  11891. public function getAliasOf()
  11892. {
  11893. return $this->aliasOf;
  11894. }
  11895. public function getVersion()
  11896. {
  11897. return $this->version;
  11898. }
  11899. public function getStability()
  11900. {
  11901. return $this->stability;
  11902. }
  11903. public function getPrettyVersion()
  11904. {
  11905. return $this->prettyVersion;
  11906. }
  11907. public function isDev()
  11908. {
  11909. return $this->dev;
  11910. }
  11911. public function getRequires()
  11912. {
  11913. return $this->requires;
  11914. }
  11915. public function getConflicts()
  11916. {
  11917. return $this->conflicts;
  11918. }
  11919. public function getProvides()
  11920. {
  11921. return $this->provides;
  11922. }
  11923. public function getReplaces()
  11924. {
  11925. return $this->replaces;
  11926. }
  11927. public function getDevRequires()
  11928. {
  11929. return $this->devRequires;
  11930. }
  11931. public function setRootPackageAlias($value)
  11932. {
  11933. return $this->rootPackageAlias = $value;
  11934. }
  11935. public function isRootPackageAlias()
  11936. {
  11937. return $this->rootPackageAlias;
  11938. }
  11939. public function getType()
  11940. {
  11941. return $this->aliasOf->getType();
  11942. }
  11943. public function getTargetDir()
  11944. {
  11945. return $this->aliasOf->getTargetDir();
  11946. }
  11947. public function getExtra()
  11948. {
  11949. return $this->aliasOf->getExtra();
  11950. }
  11951. public function setInstallationSource($type)
  11952. {
  11953. $this->aliasOf->setInstallationSource($type);
  11954. }
  11955. public function getInstallationSource()
  11956. {
  11957. return $this->aliasOf->getInstallationSource();
  11958. }
  11959. public function getSourceType()
  11960. {
  11961. return $this->aliasOf->getSourceType();
  11962. }
  11963. public function getSourceUrl()
  11964. {
  11965. return $this->aliasOf->getSourceUrl();
  11966. }
  11967. public function getSourceUrls()
  11968. {
  11969. return $this->aliasOf->getSourceUrls();
  11970. }
  11971. public function getSourceReference()
  11972. {
  11973. return $this->aliasOf->getSourceReference();
  11974. }
  11975. public function setSourceReference($reference)
  11976. {
  11977. return $this->aliasOf->setSourceReference($reference);
  11978. }
  11979. public function setSourceMirrors($mirrors)
  11980. {
  11981. return $this->aliasOf->setSourceMirrors($mirrors);
  11982. }
  11983. public function getSourceMirrors()
  11984. {
  11985. return $this->aliasOf->getSourceMirrors();
  11986. }
  11987. public function getDistType()
  11988. {
  11989. return $this->aliasOf->getDistType();
  11990. }
  11991. public function getDistUrl()
  11992. {
  11993. return $this->aliasOf->getDistUrl();
  11994. }
  11995. public function getDistUrls()
  11996. {
  11997. return $this->aliasOf->getDistUrls();
  11998. }
  11999. public function getDistReference()
  12000. {
  12001. return $this->aliasOf->getDistReference();
  12002. }
  12003. public function setDistReference($reference)
  12004. {
  12005. return $this->aliasOf->setDistReference($reference);
  12006. }
  12007. public function getDistSha1Checksum()
  12008. {
  12009. return $this->aliasOf->getDistSha1Checksum();
  12010. }
  12011. public function setTransportOptions(array $options)
  12012. {
  12013. return $this->aliasOf->setTransportOptions($options);
  12014. }
  12015. public function getTransportOptions()
  12016. {
  12017. return $this->aliasOf->getTransportOptions();
  12018. }
  12019. public function setDistMirrors($mirrors)
  12020. {
  12021. return $this->aliasOf->setDistMirrors($mirrors);
  12022. }
  12023. public function getDistMirrors()
  12024. {
  12025. return $this->aliasOf->getDistMirrors();
  12026. }
  12027. public function getScripts()
  12028. {
  12029. return $this->aliasOf->getScripts();
  12030. }
  12031. public function getLicense()
  12032. {
  12033. return $this->aliasOf->getLicense();
  12034. }
  12035. public function getAutoload()
  12036. {
  12037. return $this->aliasOf->getAutoload();
  12038. }
  12039. public function getDevAutoload()
  12040. {
  12041. return $this->aliasOf->getDevAutoload();
  12042. }
  12043. public function getIncludePaths()
  12044. {
  12045. return $this->aliasOf->getIncludePaths();
  12046. }
  12047. public function getRepositories()
  12048. {
  12049. return $this->aliasOf->getRepositories();
  12050. }
  12051. public function getReleaseDate()
  12052. {
  12053. return $this->aliasOf->getReleaseDate();
  12054. }
  12055. public function getBinaries()
  12056. {
  12057. return $this->aliasOf->getBinaries();
  12058. }
  12059. public function getKeywords()
  12060. {
  12061. return $this->aliasOf->getKeywords();
  12062. }
  12063. public function getDescription()
  12064. {
  12065. return $this->aliasOf->getDescription();
  12066. }
  12067. public function getHomepage()
  12068. {
  12069. return $this->aliasOf->getHomepage();
  12070. }
  12071. public function getSuggests()
  12072. {
  12073. return $this->aliasOf->getSuggests();
  12074. }
  12075. public function getAuthors()
  12076. {
  12077. return $this->aliasOf->getAuthors();
  12078. }
  12079. public function getSupport()
  12080. {
  12081. return $this->aliasOf->getSupport();
  12082. }
  12083. public function getNotificationUrl()
  12084. {
  12085. return $this->aliasOf->getNotificationUrl();
  12086. }
  12087. public function getArchiveExcludes()
  12088. {
  12089. return $this->aliasOf->getArchiveExcludes();
  12090. }
  12091. public function isAbandoned()
  12092. {
  12093. return $this->aliasOf->isAbandoned();
  12094. }
  12095. public function getReplacementPackage()
  12096. {
  12097. return $this->aliasOf->getReplacementPackage();
  12098. }
  12099. public function __toString()
  12100. {
  12101. return parent::__toString().' (alias of '.$this->aliasOf->getVersion().')';
  12102. }
  12103. }
  12104. <?php
  12105. namespace Composer\Package\Archiver;
  12106. use Composer\Util\Filesystem;
  12107. use Symfony\Component\Finder;
  12108. class ArchivableFilesFinder extends \FilterIterator
  12109. {
  12110. protected $finder;
  12111. public function __construct($sources, array $excludes)
  12112. {
  12113. $fs = new Filesystem();
  12114. $sources = $fs->normalizePath($sources);
  12115. $filters = array(
  12116. new HgExcludeFilter($sources),
  12117. new GitExcludeFilter($sources),
  12118. new ComposerExcludeFilter($sources, $excludes),
  12119. );
  12120. $this->finder = new Finder\Finder();
  12121. $filter = function (\SplFileInfo $file) use ($sources, $filters, $fs) {
  12122. if ($file->isLink() && strpos($file->getLinkTarget(), $sources) !== 0) {
  12123. return false;
  12124. }
  12125. $relativePath = preg_replace(
  12126. '#^'.preg_quote($sources, '#').'#',
  12127. '',
  12128. $fs->normalizePath($file->getRealPath())
  12129. );
  12130. $exclude = false;
  12131. foreach ($filters as $filter) {
  12132. $exclude = $filter->filter($relativePath, $exclude);
  12133. }
  12134. return !$exclude;
  12135. };
  12136. if (method_exists($filter, 'bindTo')) {
  12137. $filter = $filter->bindTo(null);
  12138. }
  12139. $this->finder
  12140. ->in($sources)
  12141. ->filter($filter)
  12142. ->ignoreVCS(true)
  12143. ->ignoreDotFiles(false);
  12144. parent::__construct($this->finder->getIterator());
  12145. }
  12146. public function accept()
  12147. {
  12148. return !$this->getInnerIterator()->current()->isDir();
  12149. }
  12150. }
  12151. <?php
  12152. namespace Composer\Package\Archiver;
  12153. use Composer\Downloader\DownloadManager;
  12154. use Composer\Package\PackageInterface;
  12155. use Composer\Package\RootPackageInterface;
  12156. use Composer\Util\Filesystem;
  12157. use Composer\Json\JsonFile;
  12158. class ArchiveManager
  12159. {
  12160. protected $downloadManager;
  12161. protected $archivers = array();
  12162. protected $overwriteFiles = true;
  12163. public function __construct(DownloadManager $downloadManager)
  12164. {
  12165. $this->downloadManager = $downloadManager;
  12166. }
  12167. public function addArchiver(ArchiverInterface $archiver)
  12168. {
  12169. $this->archivers[] = $archiver;
  12170. }
  12171. public function setOverwriteFiles($overwriteFiles)
  12172. {
  12173. $this->overwriteFiles = $overwriteFiles;
  12174. return $this;
  12175. }
  12176. public function getPackageFilename(PackageInterface $package)
  12177. {
  12178. $nameParts = array(preg_replace('#[^a-z0-9-_]#i', '-', $package->getName()));
  12179. if (preg_match('{^[a-f0-9]{40}$}', $package->getDistReference())) {
  12180. $nameParts = array_merge($nameParts, array($package->getDistReference(), $package->getDistType()));
  12181. } else {
  12182. $nameParts = array_merge($nameParts, array($package->getPrettyVersion(), $package->getDistReference()));
  12183. }
  12184. if ($package->getSourceReference()) {
  12185. $nameParts[] = substr(sha1($package->getSourceReference()), 0, 6);
  12186. }
  12187. $name = implode('-', array_filter($nameParts, function ($p) {
  12188. return !empty($p);
  12189. }));
  12190. return str_replace('/', '-', $name);
  12191. }
  12192. public function archive(PackageInterface $package, $format, $targetDir)
  12193. {
  12194. if (empty($format)) {
  12195. throw new \InvalidArgumentException('Format must be specified');
  12196. }
  12197. $usableArchiver = null;
  12198. foreach ($this->archivers as $archiver) {
  12199. if ($archiver->supports($format, $package->getSourceType())) {
  12200. $usableArchiver = $archiver;
  12201. break;
  12202. }
  12203. }
  12204. if (null === $usableArchiver) {
  12205. throw new \RuntimeException(sprintf('No archiver found to support %s format', $format));
  12206. }
  12207. $filesystem = new Filesystem();
  12208. $packageName = $this->getPackageFilename($package);
  12209. $filesystem->ensureDirectoryExists($targetDir);
  12210. $target = realpath($targetDir).'/'.$packageName.'.'.$format;
  12211. $filesystem->ensureDirectoryExists(dirname($target));
  12212. if (!$this->overwriteFiles && file_exists($target)) {
  12213. return $target;
  12214. }
  12215. if ($package instanceof RootPackageInterface) {
  12216. $sourcePath = realpath('.');
  12217. } else {
  12218. $sourcePath = sys_get_temp_dir().'/composer_archive'.uniqid();
  12219. $filesystem->ensureDirectoryExists($sourcePath);
  12220. $this->downloadManager->download($package, $sourcePath);
  12221. if (file_exists($composerJsonPath = $sourcePath.'/composer.json')) {
  12222. $jsonFile = new JsonFile($composerJsonPath);
  12223. $jsonData = $jsonFile->read();
  12224. if (!empty($jsonData['archive']['exclude'])) {
  12225. $package->setArchiveExcludes($jsonData['archive']['exclude']);
  12226. }
  12227. }
  12228. }
  12229. $tempTarget = sys_get_temp_dir().'/composer_archive'.uniqid().'.'.$format;
  12230. $filesystem->ensureDirectoryExists(dirname($tempTarget));
  12231. $archivePath = $usableArchiver->archive($sourcePath, $tempTarget, $format, $package->getArchiveExcludes());
  12232. rename($archivePath, $target);
  12233. if (!$package instanceof RootPackageInterface) {
  12234. $filesystem->removeDirectory($sourcePath);
  12235. }
  12236. $filesystem->remove($tempTarget);
  12237. return $target;
  12238. }
  12239. }
  12240. <?php
  12241. namespace Composer\Package\Archiver;
  12242. interface ArchiverInterface
  12243. {
  12244. public function archive($sources, $target, $format, array $excludes = array());
  12245. public function supports($format, $sourceType);
  12246. }
  12247. <?php
  12248. namespace Composer\Package\Archiver;
  12249. use Symfony\Component\Finder;
  12250. abstract class BaseExcludeFilter
  12251. {
  12252. protected $sourcePath;
  12253. protected $excludePatterns;
  12254. public function __construct($sourcePath)
  12255. {
  12256. $this->sourcePath = $sourcePath;
  12257. $this->excludePatterns = array();
  12258. }
  12259. public function filter($relativePath, $exclude)
  12260. {
  12261. foreach ($this->excludePatterns as $patternData) {
  12262. list($pattern, $negate, $stripLeadingSlash) = $patternData;
  12263. if ($stripLeadingSlash) {
  12264. $path = substr($relativePath, 1);
  12265. } else {
  12266. $path = $relativePath;
  12267. }
  12268. if (preg_match($pattern, $path)) {
  12269. $exclude = !$negate;
  12270. }
  12271. }
  12272. return $exclude;
  12273. }
  12274. protected function parseLines(array $lines, $lineParser)
  12275. {
  12276. return array_filter(
  12277. array_map(
  12278. function ($line) use ($lineParser) {
  12279. $line = trim($line);
  12280. if (!$line || 0 === strpos($line, '#')) {
  12281. return;
  12282. }
  12283. return call_user_func($lineParser, $line);
  12284. },
  12285. $lines
  12286. ),
  12287. function ($pattern) {
  12288. return $pattern !== null;
  12289. }
  12290. );
  12291. }
  12292. protected function generatePatterns($rules)
  12293. {
  12294. $patterns = array();
  12295. foreach ($rules as $rule) {
  12296. $patterns[] = $this->generatePattern($rule);
  12297. }
  12298. return $patterns;
  12299. }
  12300. protected function generatePattern($rule)
  12301. {
  12302. $negate = false;
  12303. $pattern = '#';
  12304. if (strlen($rule) && $rule[0] === '!') {
  12305. $negate = true;
  12306. $rule = substr($rule, 1);
  12307. }
  12308. if (strlen($rule) && $rule[0] === '/') {
  12309. $pattern .= '^/';
  12310. $rule = substr($rule, 1);
  12311. } elseif (strlen($rule) - 1 === strpos($rule, '/')) {
  12312. $pattern .= '/';
  12313. $rule = substr($rule, 0, -1);
  12314. } elseif (false === strpos($rule, '/')) {
  12315. $pattern .= '/';
  12316. }
  12317. $pattern .= substr(Finder\Glob::toRegex($rule), 2, -2) . '(?=$|/)';
  12318. return array($pattern . '#', $negate, false);
  12319. }
  12320. }
  12321. <?php
  12322. namespace Composer\Package\Archiver;
  12323. class ComposerExcludeFilter extends BaseExcludeFilter
  12324. {
  12325. public function __construct($sourcePath, array $excludeRules)
  12326. {
  12327. parent::__construct($sourcePath);
  12328. $this->excludePatterns = $this->generatePatterns($excludeRules);
  12329. }
  12330. }
  12331. <?php
  12332. namespace Composer\Package\Archiver;
  12333. class GitExcludeFilter extends BaseExcludeFilter
  12334. {
  12335. public function __construct($sourcePath)
  12336. {
  12337. parent::__construct($sourcePath);
  12338. if (file_exists($sourcePath.'/.gitignore')) {
  12339. $this->excludePatterns = $this->parseLines(
  12340. file($sourcePath.'/.gitignore'),
  12341. array($this, 'parseGitIgnoreLine')
  12342. );
  12343. }
  12344. if (file_exists($sourcePath.'/.gitattributes')) {
  12345. $this->excludePatterns = array_merge(
  12346. $this->excludePatterns,
  12347. $this->parseLines(
  12348. file($sourcePath.'/.gitattributes'),
  12349. array($this, 'parseGitAttributesLine')
  12350. ));
  12351. }
  12352. }
  12353. public function parseGitIgnoreLine($line)
  12354. {
  12355. return $this->generatePattern($line);
  12356. }
  12357. public function parseGitAttributesLine($line)
  12358. {
  12359. $parts = preg_split('#\s+#', $line);
  12360. if (count($parts) != 2) {
  12361. return null;
  12362. }
  12363. if ($parts[1] === 'export-ignore') {
  12364. return $this->generatePattern($parts[0]);
  12365. }
  12366. }
  12367. }
  12368. <?php
  12369. namespace Composer\Package\Archiver;
  12370. use Symfony\Component\Finder;
  12371. class HgExcludeFilter extends BaseExcludeFilter
  12372. {
  12373. const HG_IGNORE_REGEX = 1;
  12374. const HG_IGNORE_GLOB = 2;
  12375. protected $patternMode;
  12376. public function __construct($sourcePath)
  12377. {
  12378. parent::__construct($sourcePath);
  12379. $this->patternMode = self::HG_IGNORE_REGEX;
  12380. if (file_exists($sourcePath.'/.hgignore')) {
  12381. $this->excludePatterns = $this->parseLines(
  12382. file($sourcePath.'/.hgignore'),
  12383. array($this, 'parseHgIgnoreLine')
  12384. );
  12385. }
  12386. }
  12387. public function parseHgIgnoreLine($line)
  12388. {
  12389. if (preg_match('#^syntax\s*:\s*(glob|regexp)$#', $line, $matches)) {
  12390. if ($matches[1] === 'glob') {
  12391. $this->patternMode = self::HG_IGNORE_GLOB;
  12392. } else {
  12393. $this->patternMode = self::HG_IGNORE_REGEX;
  12394. }
  12395. return null;
  12396. }
  12397. if ($this->patternMode == self::HG_IGNORE_GLOB) {
  12398. return $this->patternFromGlob($line);
  12399. } else {
  12400. return $this->patternFromRegex($line);
  12401. }
  12402. }
  12403. protected function patternFromGlob($line)
  12404. {
  12405. $pattern = '#'.substr(Finder\Glob::toRegex($line), 2, -1).'#';
  12406. $pattern = str_replace('[^/]*', '.*', $pattern);
  12407. return array($pattern, false, true);
  12408. }
  12409. public function patternFromRegex($line)
  12410. {
  12411. $pattern = '#'.preg_replace('/((?:\\\\\\\\)*)(\\\\?)#/', '\1\2\2\\#', $line).'#';
  12412. return array($pattern, false, true);
  12413. }
  12414. }
  12415. <?php
  12416. namespace Composer\Package\Archiver;
  12417. class PharArchiver implements ArchiverInterface
  12418. {
  12419. protected static $formats = array(
  12420. 'zip' => \Phar::ZIP,
  12421. 'tar' => \Phar::TAR,
  12422. );
  12423. public function archive($sources, $target, $format, array $excludes = array())
  12424. {
  12425. $sources = realpath($sources);
  12426. if (file_exists($target)) {
  12427. unlink($target);
  12428. }
  12429. try {
  12430. $phar = new \PharData($target, null, null, static::$formats[$format]);
  12431. $files = new ArchivableFilesFinder($sources, $excludes);
  12432. $phar->buildFromIterator($files, $sources);
  12433. return $target;
  12434. } catch (\UnexpectedValueException $e) {
  12435. $message = sprintf("Could not create archive '%s' from '%s': %s",
  12436. $target,
  12437. $sources,
  12438. $e->getMessage()
  12439. );
  12440. throw new \RuntimeException($message, $e->getCode(), $e);
  12441. }
  12442. }
  12443. public function supports($format, $sourceType)
  12444. {
  12445. return isset(static::$formats[$format]);
  12446. }
  12447. }
  12448. <?php
  12449. namespace Composer\Package;
  12450. use Composer\Repository\RepositoryInterface;
  12451. use Composer\Repository\PlatformRepository;
  12452. abstract class BasePackage implements PackageInterface
  12453. {
  12454. public static $supportedLinkTypes = array(
  12455. 'require' => array('description' => 'requires', 'method' => 'requires'),
  12456. 'conflict' => array('description' => 'conflicts', 'method' => 'conflicts'),
  12457. 'provide' => array('description' => 'provides', 'method' => 'provides'),
  12458. 'replace' => array('description' => 'replaces', 'method' => 'replaces'),
  12459. 'require-dev' => array('description' => 'requires (for development)', 'method' => 'devRequires'),
  12460. );
  12461. const STABILITY_STABLE = 0;
  12462. const STABILITY_RC = 5;
  12463. const STABILITY_BETA = 10;
  12464. const STABILITY_ALPHA = 15;
  12465. const STABILITY_DEV = 20;
  12466. public static $stabilities = array(
  12467. 'stable' => self::STABILITY_STABLE,
  12468. 'RC' => self::STABILITY_RC,
  12469. 'beta' => self::STABILITY_BETA,
  12470. 'alpha' => self::STABILITY_ALPHA,
  12471. 'dev' => self::STABILITY_DEV,
  12472. );
  12473. public $id;
  12474. protected $name;
  12475. protected $prettyName;
  12476. protected $repository;
  12477. protected $transportOptions;
  12478. public function __construct($name)
  12479. {
  12480. $this->prettyName = $name;
  12481. $this->name = strtolower($name);
  12482. $this->id = -1;
  12483. $this->transportOptions = array();
  12484. }
  12485. public function getName()
  12486. {
  12487. return $this->name;
  12488. }
  12489. public function getPrettyName()
  12490. {
  12491. return $this->prettyName;
  12492. }
  12493. public function getNames()
  12494. {
  12495. $names = array(
  12496. $this->getName() => true,
  12497. );
  12498. foreach ($this->getProvides() as $link) {
  12499. $names[$link->getTarget()] = true;
  12500. }
  12501. foreach ($this->getReplaces() as $link) {
  12502. $names[$link->getTarget()] = true;
  12503. }
  12504. return array_keys($names);
  12505. }
  12506. public function setId($id)
  12507. {
  12508. $this->id = $id;
  12509. }
  12510. public function getId()
  12511. {
  12512. return $this->id;
  12513. }
  12514. public function setRepository(RepositoryInterface $repository)
  12515. {
  12516. if ($this->repository && $repository !== $this->repository) {
  12517. throw new \LogicException('A package can only be added to one repository');
  12518. }
  12519. $this->repository = $repository;
  12520. }
  12521. public function getRepository()
  12522. {
  12523. return $this->repository;
  12524. }
  12525. public function getTransportOptions()
  12526. {
  12527. return $this->transportOptions;
  12528. }
  12529. public function setTransportOptions(array $options)
  12530. {
  12531. $this->transportOptions = $options;
  12532. }
  12533. public function isPlatform()
  12534. {
  12535. return $this->getRepository() instanceof PlatformRepository;
  12536. }
  12537. public function getUniqueName()
  12538. {
  12539. return $this->getName().'-'.$this->getVersion();
  12540. }
  12541. public function equals(PackageInterface $package)
  12542. {
  12543. $self = $this;
  12544. if ($this instanceof AliasPackage) {
  12545. $self = $this->getAliasOf();
  12546. }
  12547. if ($package instanceof AliasPackage) {
  12548. $package = $package->getAliasOf();
  12549. }
  12550. return $package === $self;
  12551. }
  12552. public function __toString()
  12553. {
  12554. return $this->getUniqueName();
  12555. }
  12556. public function getPrettyString()
  12557. {
  12558. return $this->getPrettyName().' '.$this->getPrettyVersion();
  12559. }
  12560. public function __clone()
  12561. {
  12562. $this->repository = null;
  12563. $this->id = -1;
  12564. }
  12565. }
  12566. <?php
  12567. namespace Composer\Package;
  12568. class CompletePackage extends Package implements CompletePackageInterface
  12569. {
  12570. protected $repositories;
  12571. protected $license = array();
  12572. protected $keywords;
  12573. protected $authors;
  12574. protected $description;
  12575. protected $homepage;
  12576. protected $scripts = array();
  12577. protected $support = array();
  12578. protected $abandoned = false;
  12579. public function setScripts(array $scripts)
  12580. {
  12581. $this->scripts = $scripts;
  12582. }
  12583. public function getScripts()
  12584. {
  12585. return $this->scripts;
  12586. }
  12587. public function setRepositories($repositories)
  12588. {
  12589. $this->repositories = $repositories;
  12590. }
  12591. public function getRepositories()
  12592. {
  12593. return $this->repositories;
  12594. }
  12595. public function setLicense(array $license)
  12596. {
  12597. $this->license = $license;
  12598. }
  12599. public function getLicense()
  12600. {
  12601. return $this->license;
  12602. }
  12603. public function setKeywords(array $keywords)
  12604. {
  12605. $this->keywords = $keywords;
  12606. }
  12607. public function getKeywords()
  12608. {
  12609. return $this->keywords;
  12610. }
  12611. public function setAuthors(array $authors)
  12612. {
  12613. $this->authors = $authors;
  12614. }
  12615. public function getAuthors()
  12616. {
  12617. return $this->authors;
  12618. }
  12619. public function setDescription($description)
  12620. {
  12621. $this->description = $description;
  12622. }
  12623. public function getDescription()
  12624. {
  12625. return $this->description;
  12626. }
  12627. public function setHomepage($homepage)
  12628. {
  12629. $this->homepage = $homepage;
  12630. }
  12631. public function getHomepage()
  12632. {
  12633. return $this->homepage;
  12634. }
  12635. public function setSupport(array $support)
  12636. {
  12637. $this->support = $support;
  12638. }
  12639. public function getSupport()
  12640. {
  12641. return $this->support;
  12642. }
  12643. public function isAbandoned()
  12644. {
  12645. return (boolean) $this->abandoned;
  12646. }
  12647. public function setAbandoned($abandoned)
  12648. {
  12649. $this->abandoned = $abandoned;
  12650. }
  12651. public function getReplacementPackage()
  12652. {
  12653. return is_string($this->abandoned) ? $this->abandoned : null;
  12654. }
  12655. }
  12656. <?php
  12657. namespace Composer\Package;
  12658. interface CompletePackageInterface extends PackageInterface
  12659. {
  12660. public function getScripts();
  12661. public function getRepositories();
  12662. public function getLicense();
  12663. public function getKeywords();
  12664. public function getDescription();
  12665. public function getHomepage();
  12666. public function getAuthors();
  12667. public function getSupport();
  12668. public function isAbandoned();
  12669. public function getReplacementPackage();
  12670. }
  12671. <?php
  12672. namespace Composer\Package\Dumper;
  12673. use Composer\Package\BasePackage;
  12674. use Composer\Package\PackageInterface;
  12675. use Composer\Package\CompletePackageInterface;
  12676. use Composer\Package\RootPackageInterface;
  12677. class ArrayDumper
  12678. {
  12679. public function dump(PackageInterface $package)
  12680. {
  12681. $keys = array(
  12682. 'binaries' => 'bin',
  12683. 'type',
  12684. 'extra',
  12685. 'installationSource' => 'installation-source',
  12686. 'autoload',
  12687. 'devAutoload' => 'autoload-dev',
  12688. 'notificationUrl' => 'notification-url',
  12689. 'includePaths' => 'include-path',
  12690. );
  12691. $data = array();
  12692. $data['name'] = $package->getPrettyName();
  12693. $data['version'] = $package->getPrettyVersion();
  12694. $data['version_normalized'] = $package->getVersion();
  12695. if ($package->getTargetDir()) {
  12696. $data['target-dir'] = $package->getTargetDir();
  12697. }
  12698. if ($package->getSourceType()) {
  12699. $data['source']['type'] = $package->getSourceType();
  12700. $data['source']['url'] = $package->getSourceUrl();
  12701. $data['source']['reference'] = $package->getSourceReference();
  12702. if ($mirrors = $package->getSourceMirrors()) {
  12703. $data['source']['mirrors'] = $mirrors;
  12704. }
  12705. }
  12706. if ($package->getDistType()) {
  12707. $data['dist']['type'] = $package->getDistType();
  12708. $data['dist']['url'] = $package->getDistUrl();
  12709. $data['dist']['reference'] = $package->getDistReference();
  12710. $data['dist']['shasum'] = $package->getDistSha1Checksum();
  12711. if ($mirrors = $package->getDistMirrors()) {
  12712. $data['dist']['mirrors'] = $mirrors;
  12713. }
  12714. }
  12715. if ($package->getArchiveExcludes()) {
  12716. $data['archive']['exclude'] = $package->getArchiveExcludes();
  12717. }
  12718. foreach (BasePackage::$supportedLinkTypes as $type => $opts) {
  12719. if ($links = $package->{'get'.ucfirst($opts['method'])}()) {
  12720. foreach ($links as $link) {
  12721. $data[$type][$link->getTarget()] = $link->getPrettyConstraint();
  12722. }
  12723. ksort($data[$type]);
  12724. }
  12725. }
  12726. if ($packages = $package->getSuggests()) {
  12727. ksort($packages);
  12728. $data['suggest'] = $packages;
  12729. }
  12730. if ($package->getReleaseDate()) {
  12731. $data['time'] = $package->getReleaseDate()->format('Y-m-d H:i:s');
  12732. }
  12733. $data = $this->dumpValues($package, $keys, $data);
  12734. if ($package instanceof CompletePackageInterface) {
  12735. $keys = array(
  12736. 'scripts',
  12737. 'license',
  12738. 'authors',
  12739. 'description',
  12740. 'homepage',
  12741. 'keywords',
  12742. 'repositories',
  12743. 'support',
  12744. );
  12745. $data = $this->dumpValues($package, $keys, $data);
  12746. if (isset($data['keywords']) && is_array($data['keywords'])) {
  12747. sort($data['keywords']);
  12748. }
  12749. if ($package->isAbandoned()) {
  12750. $data['abandoned'] = $package->getReplacementPackage() ?: true;
  12751. }
  12752. }
  12753. if ($package instanceof RootPackageInterface) {
  12754. $minimumStability = $package->getMinimumStability();
  12755. if ($minimumStability) {
  12756. $data['minimum-stability'] = $minimumStability;
  12757. }
  12758. }
  12759. if (count($package->getTransportOptions()) > 0) {
  12760. $data['transport-options'] = $package->getTransportOptions();
  12761. }
  12762. return $data;
  12763. }
  12764. private function dumpValues(PackageInterface $package, array $keys, array $data)
  12765. {
  12766. foreach ($keys as $method => $key) {
  12767. if (is_numeric($method)) {
  12768. $method = $key;
  12769. }
  12770. $getter = 'get'.ucfirst($method);
  12771. $value = $package->$getter();
  12772. if (null !== $value && !(is_array($value) && 0 === count($value))) {
  12773. $data[$key] = $value;
  12774. }
  12775. }
  12776. return $data;
  12777. }
  12778. }
  12779. <?php
  12780. namespace Composer\Package;
  12781. use Composer\Package\LinkConstraint\LinkConstraintInterface;
  12782. class Link
  12783. {
  12784. protected $source;
  12785. protected $target;
  12786. protected $constraint;
  12787. protected $description;
  12788. protected $prettyConstraint;
  12789. public function __construct($source, $target, LinkConstraintInterface $constraint = null, $description = 'relates to', $prettyConstraint = null)
  12790. {
  12791. $this->source = strtolower($source);
  12792. $this->target = strtolower($target);
  12793. $this->constraint = $constraint;
  12794. $this->description = $description;
  12795. $this->prettyConstraint = $prettyConstraint;
  12796. }
  12797. public function getSource()
  12798. {
  12799. return $this->source;
  12800. }
  12801. public function getTarget()
  12802. {
  12803. return $this->target;
  12804. }
  12805. public function getConstraint()
  12806. {
  12807. return $this->constraint;
  12808. }
  12809. public function getPrettyConstraint()
  12810. {
  12811. if (null === $this->prettyConstraint) {
  12812. throw new \UnexpectedValueException(sprintf('Link %s has been misconfigured and had no prettyConstraint given.', $this));
  12813. }
  12814. return $this->prettyConstraint;
  12815. }
  12816. public function __toString()
  12817. {
  12818. return $this->source.' '.$this->description.' '.$this->target.' ('.$this->constraint.')';
  12819. }
  12820. public function getPrettyString(PackageInterface $sourcePackage)
  12821. {
  12822. return $sourcePackage->getPrettyString().' '.$this->description.' '.$this->target.' '.$this->constraint->getPrettyString().'';
  12823. }
  12824. }
  12825. <?php
  12826. namespace Composer\Package\LinkConstraint;
  12827. class EmptyConstraint implements LinkConstraintInterface
  12828. {
  12829. protected $prettyString;
  12830. public function matches(LinkConstraintInterface $provider)
  12831. {
  12832. return true;
  12833. }
  12834. public function setPrettyString($prettyString)
  12835. {
  12836. $this->prettyString = $prettyString;
  12837. }
  12838. public function getPrettyString()
  12839. {
  12840. if ($this->prettyString) {
  12841. return $this->prettyString;
  12842. }
  12843. return $this->__toString();
  12844. }
  12845. public function __toString()
  12846. {
  12847. return '[]';
  12848. }
  12849. }
  12850. <?php
  12851. namespace Composer\Package\LinkConstraint;
  12852. interface LinkConstraintInterface
  12853. {
  12854. public function matches(LinkConstraintInterface $provider);
  12855. public function setPrettyString($prettyString);
  12856. public function getPrettyString();
  12857. public function __toString();
  12858. }
  12859. <?php
  12860. namespace Composer\Package\LinkConstraint;
  12861. class MultiConstraint implements LinkConstraintInterface
  12862. {
  12863. protected $constraints;
  12864. protected $prettyString;
  12865. protected $conjunctive;
  12866. public function __construct(array $constraints, $conjunctive = true)
  12867. {
  12868. $this->constraints = $constraints;
  12869. $this->conjunctive = $conjunctive;
  12870. }
  12871. public function matches(LinkConstraintInterface $provider)
  12872. {
  12873. if (false === $this->conjunctive) {
  12874. foreach ($this->constraints as $constraint) {
  12875. if ($constraint->matches($provider)) {
  12876. return true;
  12877. }
  12878. }
  12879. return false;
  12880. }
  12881. foreach ($this->constraints as $constraint) {
  12882. if (!$constraint->matches($provider)) {
  12883. return false;
  12884. }
  12885. }
  12886. return true;
  12887. }
  12888. public function setPrettyString($prettyString)
  12889. {
  12890. $this->prettyString = $prettyString;
  12891. }
  12892. public function getPrettyString()
  12893. {
  12894. if ($this->prettyString) {
  12895. return $this->prettyString;
  12896. }
  12897. return $this->__toString();
  12898. }
  12899. public function __toString()
  12900. {
  12901. $constraints = array();
  12902. foreach ($this->constraints as $constraint) {
  12903. $constraints[] = $constraint->__toString();
  12904. }
  12905. return '['.implode($this->conjunctive ? ' ' : ' || ', $constraints).']';
  12906. }
  12907. }
  12908. <?php
  12909. namespace Composer\Package\LinkConstraint;
  12910. abstract class SpecificConstraint implements LinkConstraintInterface
  12911. {
  12912. protected $prettyString;
  12913. public function matches(LinkConstraintInterface $provider)
  12914. {
  12915. if ($provider instanceof MultiConstraint) {
  12916. return $provider->matches($this);
  12917. } elseif ($provider instanceof $this) {
  12918. return $this->matchSpecific($provider);
  12919. }
  12920. return true;
  12921. }
  12922. public function setPrettyString($prettyString)
  12923. {
  12924. $this->prettyString = $prettyString;
  12925. }
  12926. public function getPrettyString()
  12927. {
  12928. if ($this->prettyString) {
  12929. return $this->prettyString;
  12930. }
  12931. return $this->__toString();
  12932. }
  12933. }
  12934. <?php
  12935. namespace Composer\Package\LinkConstraint;
  12936. class VersionConstraint extends SpecificConstraint
  12937. {
  12938. private $operator;
  12939. private $version;
  12940. public function __construct($operator, $version)
  12941. {
  12942. if ('=' === $operator) {
  12943. $operator = '==';
  12944. }
  12945. if ('<>' === $operator) {
  12946. $operator = '!=';
  12947. }
  12948. $this->operator = $operator;
  12949. $this->version = $version;
  12950. }
  12951. public function versionCompare($a, $b, $operator, $compareBranches = false)
  12952. {
  12953. $aIsBranch = 'dev-' === substr($a, 0, 4);
  12954. $bIsBranch = 'dev-' === substr($b, 0, 4);
  12955. if ($aIsBranch && $bIsBranch) {
  12956. return $operator == '==' && $a === $b;
  12957. }
  12958. if (!$compareBranches && ($aIsBranch || $bIsBranch)) {
  12959. return false;
  12960. }
  12961. return version_compare($a, $b, $operator);
  12962. }
  12963. public function matchSpecific(VersionConstraint $provider, $compareBranches = false)
  12964. {
  12965. static $cache = array();
  12966. if (isset($cache[$this->operator][$this->version][$provider->operator][$provider->version][$compareBranches])) {
  12967. return $cache[$this->operator][$this->version][$provider->operator][$provider->version][$compareBranches];
  12968. }
  12969. return $cache[$this->operator][$this->version][$provider->operator][$provider->version][$compareBranches] =
  12970. $this->doMatchSpecific($provider, $compareBranches);
  12971. }
  12972. private function doMatchSpecific(VersionConstraint $provider, $compareBranches = false)
  12973. {
  12974. $noEqualOp = str_replace('=', '', $this->operator);
  12975. $providerNoEqualOp = str_replace('=', '', $provider->operator);
  12976. $isEqualOp = '==' === $this->operator;
  12977. $isNonEqualOp = '!=' === $this->operator;
  12978. $isProviderEqualOp = '==' === $provider->operator;
  12979. $isProviderNonEqualOp = '!=' === $provider->operator;
  12980. if ($isNonEqualOp || $isProviderNonEqualOp) {
  12981. return !$isEqualOp && !$isProviderEqualOp
  12982. || $this->versionCompare($provider->version, $this->version, '!=', $compareBranches);
  12983. }
  12984. if ($this->operator != '==' && $noEqualOp == $providerNoEqualOp) {
  12985. return true;
  12986. }
  12987. if ($this->versionCompare($provider->version, $this->version, $this->operator, $compareBranches)) {
  12988. if ($provider->version == $this->version && $provider->operator == $providerNoEqualOp && $this->operator != $noEqualOp) {
  12989. return false;
  12990. }
  12991. return true;
  12992. }
  12993. return false;
  12994. }
  12995. public function __toString()
  12996. {
  12997. return $this->operator.' '.$this->version;
  12998. }
  12999. }
  13000. <?php
  13001. namespace Composer\Package\Loader;
  13002. use Composer\Package;
  13003. use Composer\Package\AliasPackage;
  13004. use Composer\Package\RootAliasPackage;
  13005. use Composer\Package\RootPackageInterface;
  13006. use Composer\Package\Version\VersionParser;
  13007. class ArrayLoader implements LoaderInterface
  13008. {
  13009. protected $versionParser;
  13010. protected $loadOptions;
  13011. public function __construct(VersionParser $parser = null, $loadOptions = false)
  13012. {
  13013. if (!$parser) {
  13014. $parser = new VersionParser;
  13015. }
  13016. $this->versionParser = $parser;
  13017. $this->loadOptions = $loadOptions;
  13018. }
  13019. public function load(array $config, $class = 'Composer\Package\CompletePackage')
  13020. {
  13021. if (!isset($config['name'])) {
  13022. throw new \UnexpectedValueException('Unknown package has no name defined ('.json_encode($config).').');
  13023. }
  13024. if (!isset($config['version'])) {
  13025. throw new \UnexpectedValueException('Package '.$config['name'].' has no version defined.');
  13026. }
  13027. if (isset($config['version_normalized'])) {
  13028. $version = $config['version_normalized'];
  13029. } else {
  13030. $version = $this->versionParser->normalize($config['version']);
  13031. }
  13032. $package = new $class($config['name'], $version, $config['version']);
  13033. $package->setType(isset($config['type']) ? strtolower($config['type']) : 'library');
  13034. if (isset($config['target-dir'])) {
  13035. $package->setTargetDir($config['target-dir']);
  13036. }
  13037. if (isset($config['extra']) && is_array($config['extra'])) {
  13038. $package->setExtra($config['extra']);
  13039. }
  13040. if (isset($config['bin'])) {
  13041. if (!is_array($config['bin'])) {
  13042. throw new \UnexpectedValueException('Package '.$config['name'].'\'s bin key should be an array, '.gettype($config['bin']).' given.');
  13043. }
  13044. foreach ($config['bin'] as $key => $bin) {
  13045. $config['bin'][$key] = ltrim($bin, '/');
  13046. }
  13047. $package->setBinaries($config['bin']);
  13048. }
  13049. if (isset($config['installation-source'])) {
  13050. $package->setInstallationSource($config['installation-source']);
  13051. }
  13052. if (isset($config['source'])) {
  13053. if (!isset($config['source']['type']) || !isset($config['source']['url']) || !isset($config['source']['reference'])) {
  13054. throw new \UnexpectedValueException(sprintf(
  13055. "Package %s's source key should be specified as {\"type\": ..., \"url\": ..., \"reference\": ...},\n%s given.",
  13056. $config['name'],
  13057. json_encode($config['source'])
  13058. ));
  13059. }
  13060. $package->setSourceType($config['source']['type']);
  13061. $package->setSourceUrl($config['source']['url']);
  13062. $package->setSourceReference($config['source']['reference']);
  13063. if (isset($config['source']['mirrors'])) {
  13064. $package->setSourceMirrors($config['source']['mirrors']);
  13065. }
  13066. }
  13067. if (isset($config['dist'])) {
  13068. if (!isset($config['dist']['type'])
  13069. || !isset($config['dist']['url'])) {
  13070. throw new \UnexpectedValueException(sprintf(
  13071. "Package %s's dist key should be specified as ".
  13072. "{\"type\": ..., \"url\": ..., \"reference\": ..., \"shasum\": ...},\n%s given.",
  13073. $config['name'],
  13074. json_encode($config['dist'])
  13075. ));
  13076. }
  13077. $package->setDistType($config['dist']['type']);
  13078. $package->setDistUrl($config['dist']['url']);
  13079. $package->setDistReference(isset($config['dist']['reference']) ? $config['dist']['reference'] : null);
  13080. $package->setDistSha1Checksum(isset($config['dist']['shasum']) ? $config['dist']['shasum'] : null);
  13081. if (isset($config['dist']['mirrors'])) {
  13082. $package->setDistMirrors($config['dist']['mirrors']);
  13083. }
  13084. }
  13085. foreach (Package\BasePackage::$supportedLinkTypes as $type => $opts) {
  13086. if (isset($config[$type])) {
  13087. $method = 'set'.ucfirst($opts['method']);
  13088. $package->{$method}(
  13089. $this->versionParser->parseLinks(
  13090. $package->getName(),
  13091. $package->getPrettyVersion(),
  13092. $opts['description'],
  13093. $config[$type]
  13094. )
  13095. );
  13096. }
  13097. }
  13098. if (isset($config['suggest']) && is_array($config['suggest'])) {
  13099. foreach ($config['suggest'] as $target => $reason) {
  13100. if ('self.version' === trim($reason)) {
  13101. $config['suggest'][$target] = $package->getPrettyVersion();
  13102. }
  13103. }
  13104. $package->setSuggests($config['suggest']);
  13105. }
  13106. if (isset($config['autoload'])) {
  13107. $package->setAutoload($config['autoload']);
  13108. }
  13109. if (isset($config['autoload-dev'])) {
  13110. $package->setDevAutoload($config['autoload-dev']);
  13111. }
  13112. if (isset($config['include-path'])) {
  13113. $package->setIncludePaths($config['include-path']);
  13114. }
  13115. if (!empty($config['time'])) {
  13116. $time = ctype_digit($config['time']) ? '@'.$config['time'] : $config['time'];
  13117. try {
  13118. $date = new \DateTime($time, new \DateTimeZone('UTC'));
  13119. $package->setReleaseDate($date);
  13120. } catch (\Exception $e) {
  13121. }
  13122. }
  13123. if (!empty($config['notification-url'])) {
  13124. $package->setNotificationUrl($config['notification-url']);
  13125. }
  13126. if (!empty($config['archive']['exclude'])) {
  13127. $package->setArchiveExcludes($config['archive']['exclude']);
  13128. }
  13129. if ($package instanceof Package\CompletePackageInterface) {
  13130. if (isset($config['scripts']) && is_array($config['scripts'])) {
  13131. foreach ($config['scripts'] as $event => $listeners) {
  13132. $config['scripts'][$event] = (array) $listeners;
  13133. }
  13134. $package->setScripts($config['scripts']);
  13135. }
  13136. if (!empty($config['description']) && is_string($config['description'])) {
  13137. $package->setDescription($config['description']);
  13138. }
  13139. if (!empty($config['homepage']) && is_string($config['homepage'])) {
  13140. $package->setHomepage($config['homepage']);
  13141. }
  13142. if (!empty($config['keywords']) && is_array($config['keywords'])) {
  13143. $package->setKeywords($config['keywords']);
  13144. }
  13145. if (!empty($config['license'])) {
  13146. $package->setLicense(is_array($config['license']) ? $config['license'] : array($config['license']));
  13147. }
  13148. if (!empty($config['authors']) && is_array($config['authors'])) {
  13149. $package->setAuthors($config['authors']);
  13150. }
  13151. if (isset($config['support'])) {
  13152. $package->setSupport($config['support']);
  13153. }
  13154. if (isset($config['abandoned'])) {
  13155. $package->setAbandoned($config['abandoned']);
  13156. }
  13157. }
  13158. if ($aliasNormalized = $this->getBranchAlias($config)) {
  13159. if ($package instanceof RootPackageInterface) {
  13160. $package = new RootAliasPackage($package, $aliasNormalized, preg_replace('{(\.9{7})+}', '.x', $aliasNormalized));
  13161. } else {
  13162. $package = new AliasPackage($package, $aliasNormalized, preg_replace('{(\.9{7})+}', '.x', $aliasNormalized));
  13163. }
  13164. }
  13165. if ($this->loadOptions && isset($config['transport-options'])) {
  13166. $package->setTransportOptions($config['transport-options']);
  13167. }
  13168. return $package;
  13169. }
  13170. public function getBranchAlias(array $config)
  13171. {
  13172. if (('dev-' !== substr($config['version'], 0, 4) && '-dev' !== substr($config['version'], -4))
  13173. || !isset($config['extra']['branch-alias'])
  13174. || !is_array($config['extra']['branch-alias'])
  13175. ) {
  13176. return;
  13177. }
  13178. foreach ($config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
  13179. if ('-dev' !== substr($targetBranch, -4)) {
  13180. continue;
  13181. }
  13182. $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
  13183. if ('-dev' !== substr($validatedTargetBranch, -4)) {
  13184. continue;
  13185. }
  13186. if (strtolower($config['version']) !== strtolower($sourceBranch)) {
  13187. continue;
  13188. }
  13189. if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
  13190. && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
  13191. && (stripos($targetPrefix, $sourcePrefix) !== 0)
  13192. ) {
  13193. continue;
  13194. }
  13195. return $validatedTargetBranch;
  13196. }
  13197. }
  13198. }
  13199. <?php
  13200. namespace Composer\Package\Loader;
  13201. class InvalidPackageException extends \Exception
  13202. {
  13203. private $errors;
  13204. private $warnings;
  13205. private $data;
  13206. public function __construct(array $errors, array $warnings, array $data)
  13207. {
  13208. $this->errors = $errors;
  13209. $this->warnings = $warnings;
  13210. $this->data = $data;
  13211. parent::__construct("Invalid package information: \n".implode("\n", array_merge($errors, $warnings)));
  13212. }
  13213. public function getData()
  13214. {
  13215. return $this->data;
  13216. }
  13217. public function getErrors()
  13218. {
  13219. return $this->errors;
  13220. }
  13221. public function getWarnings()
  13222. {
  13223. return $this->warnings;
  13224. }
  13225. }
  13226. <?php
  13227. namespace Composer\Package\Loader;
  13228. use Composer\Json\JsonFile;
  13229. class JsonLoader
  13230. {
  13231. private $loader;
  13232. public function __construct(LoaderInterface $loader)
  13233. {
  13234. $this->loader = $loader;
  13235. }
  13236. public function load($json)
  13237. {
  13238. if ($json instanceof JsonFile) {
  13239. $config = $json->read();
  13240. } elseif (file_exists($json)) {
  13241. $config = JsonFile::parseJson(file_get_contents($json), $json);
  13242. } elseif (is_string($json)) {
  13243. $config = JsonFile::parseJson($json);
  13244. }
  13245. return $this->loader->load($config);
  13246. }
  13247. }
  13248. <?php
  13249. namespace Composer\Package\Loader;
  13250. interface LoaderInterface
  13251. {
  13252. public function load(array $package, $class = 'Composer\Package\CompletePackage');
  13253. }
  13254. <?php
  13255. namespace Composer\Package\Loader;
  13256. use Composer\Package\BasePackage;
  13257. use Composer\Package\AliasPackage;
  13258. use Composer\Config;
  13259. use Composer\Factory;
  13260. use Composer\Package\Version\VersionParser;
  13261. use Composer\Repository\RepositoryManager;
  13262. use Composer\Repository\Vcs\HgDriver;
  13263. use Composer\IO\NullIO;
  13264. use Composer\Util\ProcessExecutor;
  13265. use Composer\Util\Git as GitUtil;
  13266. use Composer\Util\Svn as SvnUtil;
  13267. class RootPackageLoader extends ArrayLoader
  13268. {
  13269. private $manager;
  13270. private $config;
  13271. private $process;
  13272. public function __construct(RepositoryManager $manager, Config $config, VersionParser $parser = null, ProcessExecutor $process = null)
  13273. {
  13274. $this->manager = $manager;
  13275. $this->config = $config;
  13276. $this->process = $process ?: new ProcessExecutor();
  13277. parent::__construct($parser);
  13278. }
  13279. public function load(array $config, $class = 'Composer\Package\RootPackage')
  13280. {
  13281. if (!isset($config['name'])) {
  13282. $config['name'] = '__root__';
  13283. }
  13284. if (!isset($config['version'])) {
  13285. if (getenv('COMPOSER_ROOT_VERSION')) {
  13286. $version = getenv('COMPOSER_ROOT_VERSION');
  13287. } else {
  13288. $version = $this->guessVersion($config);
  13289. }
  13290. if (!$version) {
  13291. $version = '1.0.0';
  13292. }
  13293. $config['version'] = $version;
  13294. }
  13295. $realPackage = $package = parent::load($config, $class);
  13296. if ($realPackage instanceof AliasPackage) {
  13297. $realPackage = $package->getAliasOf();
  13298. }
  13299. if (isset($config['minimum-stability'])) {
  13300. $realPackage->setMinimumStability(VersionParser::normalizeStability($config['minimum-stability']));
  13301. }
  13302. $aliases = array();
  13303. $stabilityFlags = array();
  13304. $references = array();
  13305. foreach (array('require', 'require-dev') as $linkType) {
  13306. if (isset($config[$linkType])) {
  13307. $linkInfo = BasePackage::$supportedLinkTypes[$linkType];
  13308. $method = 'get'.ucfirst($linkInfo['method']);
  13309. $links = array();
  13310. foreach ($realPackage->$method() as $link) {
  13311. $links[$link->getTarget()] = $link->getConstraint()->getPrettyString();
  13312. }
  13313. $aliases = $this->extractAliases($links, $aliases);
  13314. $stabilityFlags = $this->extractStabilityFlags($links, $stabilityFlags, $realPackage->getMinimumStability());
  13315. $references = $this->extractReferences($links, $references);
  13316. }
  13317. }
  13318. $realPackage->setAliases($aliases);
  13319. $realPackage->setStabilityFlags($stabilityFlags);
  13320. $realPackage->setReferences($references);
  13321. if (isset($config['prefer-stable'])) {
  13322. $realPackage->setPreferStable((bool) $config['prefer-stable']);
  13323. }
  13324. $repos = Factory::createDefaultRepositories(null, $this->config, $this->manager);
  13325. foreach ($repos as $repo) {
  13326. $this->manager->addRepository($repo);
  13327. }
  13328. $realPackage->setRepositories($this->config->getRepositories());
  13329. return $package;
  13330. }
  13331. private function extractAliases(array $requires, array $aliases)
  13332. {
  13333. foreach ($requires as $reqName => $reqVersion) {
  13334. if (preg_match('{^([^,\s#]+)(?:#[^ ]+)? +as +([^,\s]+)$}', $reqVersion, $match)) {
  13335. $aliases[] = array(
  13336. 'package' => strtolower($reqName),
  13337. 'version' => $this->versionParser->normalize($match[1], $reqVersion),
  13338. 'alias' => $match[2],
  13339. 'alias_normalized' => $this->versionParser->normalize($match[2], $reqVersion),
  13340. );
  13341. }
  13342. }
  13343. return $aliases;
  13344. }
  13345. private function extractStabilityFlags(array $requires, array $stabilityFlags, $minimumStability)
  13346. {
  13347. $stabilities = BasePackage::$stabilities;
  13348. $minimumStability = $stabilities[$minimumStability];
  13349. foreach ($requires as $reqName => $reqVersion) {
  13350. if (preg_match('{^[^@]*?@('.implode('|', array_keys($stabilities)).')$}i', $reqVersion, $match)) {
  13351. $name = strtolower($reqName);
  13352. $stability = $stabilities[VersionParser::normalizeStability($match[1])];
  13353. if (isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) {
  13354. continue;
  13355. }
  13356. $stabilityFlags[$name] = $stability;
  13357. continue;
  13358. }
  13359. $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
  13360. if (preg_match('{^[^,\s@]+$}', $reqVersion) && 'stable' !== ($stabilityName = VersionParser::parseStability($reqVersion))) {
  13361. $name = strtolower($reqName);
  13362. $stability = $stabilities[$stabilityName];
  13363. if ((isset($stabilityFlags[$name]) && $stabilityFlags[$name] > $stability) || ($minimumStability > $stability)) {
  13364. continue;
  13365. }
  13366. $stabilityFlags[$name] = $stability;
  13367. }
  13368. }
  13369. return $stabilityFlags;
  13370. }
  13371. private function extractReferences(array $requires, array $references)
  13372. {
  13373. foreach ($requires as $reqName => $reqVersion) {
  13374. $reqVersion = preg_replace('{^([^,\s@]+) as .+$}', '$1', $reqVersion);
  13375. if (preg_match('{^[^,\s@]+?#([a-f0-9]+)$}', $reqVersion, $match) && 'dev' === ($stabilityName = VersionParser::parseStability($reqVersion))) {
  13376. $name = strtolower($reqName);
  13377. $references[$name] = $match[1];
  13378. }
  13379. }
  13380. return $references;
  13381. }
  13382. private function guessVersion(array $config)
  13383. {
  13384. if (function_exists('proc_open')) {
  13385. $version = $this->guessGitVersion($config);
  13386. if (null !== $version) {
  13387. return $version;
  13388. }
  13389. $version = $this->guessHgVersion($config);
  13390. if (null !== $version) {
  13391. return $version;
  13392. }
  13393. return $this->guessSvnVersion($config);
  13394. }
  13395. }
  13396. private function guessGitVersion(array $config)
  13397. {
  13398. GitUtil::cleanEnv();
  13399. if (0 === $this->process->execute('git describe --exact-match --tags', $output)) {
  13400. try {
  13401. return $this->versionParser->normalize(trim($output));
  13402. } catch (\Exception $e) {
  13403. }
  13404. }
  13405. if (0 === $this->process->execute('git branch --no-color --no-abbrev -v', $output)) {
  13406. $branches = array();
  13407. $isFeatureBranch = false;
  13408. $version = null;
  13409. foreach ($this->process->splitLines($output) as $branch) {
  13410. if ($branch && preg_match('{^(?:\* ) *(\(no branch\)|\(detached from \S+\)|\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
  13411. if ($match[1] === '(no branch)' || substr($match[1], 0, 10) === '(detached ') {
  13412. $version = 'dev-'.$match[2];
  13413. $isFeatureBranch = true;
  13414. } else {
  13415. $version = $this->versionParser->normalizeBranch($match[1]);
  13416. $isFeatureBranch = 0 === strpos($version, 'dev-');
  13417. if ('9999999-dev' === $version) {
  13418. $version = 'dev-'.$match[1];
  13419. }
  13420. }
  13421. }
  13422. if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) {
  13423. if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+) .*$}', $branch, $match)) {
  13424. $branches[] = $match[1];
  13425. }
  13426. }
  13427. }
  13428. if (!$isFeatureBranch) {
  13429. return $version;
  13430. }
  13431. $version = $this->guessFeatureVersion($config, $version, $branches, 'git rev-list %candidate%..%branch%');
  13432. return $version;
  13433. }
  13434. }
  13435. private function guessHgVersion(array $config)
  13436. {
  13437. if (0 === $this->process->execute('hg branch', $output)) {
  13438. $branch = trim($output);
  13439. $version = $this->versionParser->normalizeBranch($branch);
  13440. $isFeatureBranch = 0 === strpos($version, 'dev-');
  13441. if ('9999999-dev' === $version) {
  13442. $version = 'dev-'.$branch;
  13443. }
  13444. if (!$isFeatureBranch) {
  13445. return $version;
  13446. }
  13447. $config = array('url' => getcwd());
  13448. $driver = new HgDriver($config, new NullIO(), $this->config, $this->process);
  13449. $branches = array_keys($driver->getBranches());
  13450. $version = $this->guessFeatureVersion($config, $version, $branches, 'hg log -r "not ancestors(\'%candidate%\') and ancestors(\'%branch%\')" --template "{node}\\n"');
  13451. return $version;
  13452. }
  13453. }
  13454. private function guessFeatureVersion(array $config, $version, array $branches, $scmCmdline)
  13455. {
  13456. if ((isset($config['extra']['branch-alias']) && !isset($config['extra']['branch-alias'][$version]))
  13457. || strpos(json_encode($config), '"self.version"')
  13458. ) {
  13459. $branch = preg_replace('{^dev-}', '', $version);
  13460. $length = PHP_INT_MAX;
  13461. $nonFeatureBranches = '';
  13462. if (!empty($config['non-feature-branches'])) {
  13463. $nonFeatureBranches = implode('|', $config['non-feature-branches']);
  13464. }
  13465. foreach ($branches as $candidate) {
  13466. if ($candidate === $branch && preg_match('{^(' . $nonFeatureBranches . ')$}', $candidate)) {
  13467. return $version;
  13468. }
  13469. if ($candidate === $branch || !preg_match('{^(master|trunk|default|develop|\d+\..+)$}', $candidate, $match)) {
  13470. continue;
  13471. }
  13472. $cmdLine = str_replace(array('%candidate%', '%branch%'), array($candidate, $branch), $scmCmdline);
  13473. if (0 !== $this->process->execute($cmdLine, $output)) {
  13474. continue;
  13475. }
  13476. if (strlen($output) < $length) {
  13477. $length = strlen($output);
  13478. $version = $this->versionParser->normalizeBranch($candidate);
  13479. if ('9999999-dev' === $version) {
  13480. $version = 'dev-'.$match[1];
  13481. }
  13482. }
  13483. }
  13484. }
  13485. return $version;
  13486. }
  13487. private function guessSvnVersion(array $config)
  13488. {
  13489. SvnUtil::cleanEnv();
  13490. if (0 === $this->process->execute('svn info --xml', $output)) {
  13491. $trunkPath = isset($config['trunk-path']) ? preg_quote($config['trunk-path'], '#') : 'trunk';
  13492. $branchesPath = isset($config['branches-path']) ? preg_quote($config['branches-path'], '#') : 'branches';
  13493. $tagsPath = isset($config['tags-path']) ? preg_quote($config['tags-path'], '#') : 'tags';
  13494. $urlPattern = '#<url>.*/('.$trunkPath.'|('.$branchesPath.'|'. $tagsPath .')/(.*))</url>#';
  13495. if (preg_match($urlPattern, $output, $matches)) {
  13496. if (isset($matches[2]) && ($branchesPath === $matches[2] || $tagsPath === $matches[2])) {
  13497. $version = $this->versionParser->normalizeBranch($matches[3]);
  13498. if ('9999999-dev' === $version) {
  13499. $version = 'dev-'.$matches[3];
  13500. }
  13501. return $version;
  13502. }
  13503. return $this->versionParser->normalize(trim($matches[1]));
  13504. }
  13505. }
  13506. }
  13507. }
  13508. <?php
  13509. namespace Composer\Package\Loader;
  13510. use Composer\Package;
  13511. use Composer\Package\BasePackage;
  13512. use Composer\Package\LinkConstraint\VersionConstraint;
  13513. use Composer\Package\Version\VersionParser;
  13514. use Composer\Repository\PlatformRepository;
  13515. class ValidatingArrayLoader implements LoaderInterface
  13516. {
  13517. const CHECK_ALL = 1;
  13518. const CHECK_UNBOUND_CONSTRAINTS = 1;
  13519. private $loader;
  13520. private $versionParser;
  13521. private $errors;
  13522. private $warnings;
  13523. private $config;
  13524. private $strictName;
  13525. private $flags;
  13526. public function __construct(LoaderInterface $loader, $strictName = true, VersionParser $parser = null, $flags = 0)
  13527. {
  13528. $this->loader = $loader;
  13529. $this->versionParser = $parser ?: new VersionParser();
  13530. $this->strictName = $strictName;
  13531. $this->flags = $flags;
  13532. }
  13533. public function load(array $config, $class = 'Composer\Package\CompletePackage')
  13534. {
  13535. $this->errors = array();
  13536. $this->warnings = array();
  13537. $this->config = $config;
  13538. if ($this->strictName) {
  13539. $this->validateRegex('name', '[A-Za-z0-9][A-Za-z0-9_.-]*/[A-Za-z0-9][A-Za-z0-9_.-]*', true);
  13540. } else {
  13541. $this->validateString('name', true);
  13542. }
  13543. if (!empty($this->config['version'])) {
  13544. try {
  13545. $this->versionParser->normalize($this->config['version']);
  13546. } catch (\Exception $e) {
  13547. $this->errors[] = 'version : invalid value ('.$this->config['version'].'): '.$e->getMessage();
  13548. unset($this->config['version']);
  13549. }
  13550. }
  13551. $this->validateRegex('type', '[A-Za-z0-9-]+');
  13552. $this->validateString('target-dir');
  13553. $this->validateArray('extra');
  13554. $this->validateFlatArray('bin');
  13555. $this->validateArray('scripts');
  13556. $this->validateString('description');
  13557. $this->validateUrl('homepage');
  13558. $this->validateFlatArray('keywords', '[A-Za-z0-9 ._-]+');
  13559. if (isset($this->config['license'])) {
  13560. if (is_string($this->config['license'])) {
  13561. $this->validateRegex('license', '[A-Za-z0-9+. ()-]+');
  13562. } else {
  13563. $this->validateFlatArray('license', '[A-Za-z0-9+. ()-]+');
  13564. }
  13565. }
  13566. $this->validateString('time');
  13567. if (!empty($this->config['time'])) {
  13568. try {
  13569. $date = new \DateTime($this->config['time'], new \DateTimeZone('UTC'));
  13570. } catch (\Exception $e) {
  13571. $this->errors[] = 'time : invalid value ('.$this->config['time'].'): '.$e->getMessage();
  13572. unset($this->config['time']);
  13573. }
  13574. }
  13575. if ($this->validateArray('authors') && !empty($this->config['authors'])) {
  13576. foreach ($this->config['authors'] as $key => $author) {
  13577. if (!is_array($author)) {
  13578. $this->errors[] = 'authors.'.$key.' : should be an array, '.gettype($author).' given';
  13579. unset($this->config['authors'][$key]);
  13580. continue;
  13581. }
  13582. foreach (array('homepage', 'email', 'name', 'role') as $authorData) {
  13583. if (isset($author[$authorData]) && !is_string($author[$authorData])) {
  13584. $this->errors[] = 'authors.'.$key.'.'.$authorData.' : invalid value, must be a string';
  13585. unset($this->config['authors'][$key][$authorData]);
  13586. }
  13587. }
  13588. if (isset($author['homepage']) && !$this->filterUrl($author['homepage'])) {
  13589. $this->warnings[] = 'authors.'.$key.'.homepage : invalid value ('.$author['homepage'].'), must be an http/https URL';
  13590. unset($this->config['authors'][$key]['homepage']);
  13591. }
  13592. if (isset($author['email']) && !filter_var($author['email'], FILTER_VALIDATE_EMAIL)) {
  13593. $this->warnings[] = 'authors.'.$key.'.email : invalid value ('.$author['email'].'), must be a valid email address';
  13594. unset($this->config['authors'][$key]['email']);
  13595. }
  13596. if (empty($this->config['authors'][$key])) {
  13597. unset($this->config['authors'][$key]);
  13598. }
  13599. }
  13600. if (empty($this->config['authors'])) {
  13601. unset($this->config['authors']);
  13602. }
  13603. }
  13604. if ($this->validateArray('support') && !empty($this->config['support'])) {
  13605. foreach (array('issues', 'forum', 'wiki', 'source', 'email', 'irc') as $key) {
  13606. if (isset($this->config['support'][$key]) && !is_string($this->config['support'][$key])) {
  13607. $this->errors[] = 'support.'.$key.' : invalid value, must be a string';
  13608. unset($this->config['support'][$key]);
  13609. }
  13610. }
  13611. if (isset($this->config['support']['email']) && !filter_var($this->config['support']['email'], FILTER_VALIDATE_EMAIL)) {
  13612. $this->warnings[] = 'support.email : invalid value ('.$this->config['support']['email'].'), must be a valid email address';
  13613. unset($this->config['support']['email']);
  13614. }
  13615. if (isset($this->config['support']['irc']) && !$this->filterUrl($this->config['support']['irc'], array('irc'))) {
  13616. $this->warnings[] = 'support.irc : invalid value ('.$this->config['support']['irc'].'), must be a irc://<server>/<channel> URL';
  13617. unset($this->config['support']['irc']);
  13618. }
  13619. foreach (array('issues', 'forum', 'wiki', 'source') as $key) {
  13620. if (isset($this->config['support'][$key]) && !$this->filterUrl($this->config['support'][$key])) {
  13621. $this->warnings[] = 'support.'.$key.' : invalid value ('.$this->config['support'][$key].'), must be an http/https URL';
  13622. unset($this->config['support'][$key]);
  13623. }
  13624. }
  13625. if (empty($this->config['support'])) {
  13626. unset($this->config['support']);
  13627. }
  13628. }
  13629. $unboundConstraint = new VersionConstraint('=', $this->versionParser->normalize('dev-master'));
  13630. foreach (array_keys(BasePackage::$supportedLinkTypes) as $linkType) {
  13631. if ($this->validateArray($linkType) && isset($this->config[$linkType])) {
  13632. foreach ($this->config[$linkType] as $package => $constraint) {
  13633. if (!preg_match('{^[A-Za-z0-9_./-]+$}', $package)) {
  13634. $this->warnings[] = $linkType.'.'.$package.' : invalid key, package names must be strings containing only [A-Za-z0-9_./-]';
  13635. }
  13636. if (!is_string($constraint)) {
  13637. $this->errors[] = $linkType.'.'.$package.' : invalid value, must be a string containing a version constraint';
  13638. unset($this->config[$linkType][$package]);
  13639. } elseif ('self.version' !== $constraint) {
  13640. try {
  13641. $linkConstraint = $this->versionParser->parseConstraints($constraint);
  13642. } catch (\Exception $e) {
  13643. $this->errors[] = $linkType.'.'.$package.' : invalid version constraint ('.$e->getMessage().')';
  13644. unset($this->config[$linkType][$package]);
  13645. continue;
  13646. }
  13647. if (
  13648. ($this->flags & self::CHECK_UNBOUND_CONSTRAINTS)
  13649. && 'require' === $linkType
  13650. && $linkConstraint->matches($unboundConstraint)
  13651. && !preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $package)
  13652. ) {
  13653. $this->warnings[] = $linkType.'.'.$package.' : unbound version constraints ('.$constraint.') should be avoided';
  13654. }
  13655. }
  13656. }
  13657. }
  13658. }
  13659. if ($this->validateArray('suggest') && !empty($this->config['suggest'])) {
  13660. foreach ($this->config['suggest'] as $package => $description) {
  13661. if (!is_string($description)) {
  13662. $this->errors[] = 'suggest.'.$package.' : invalid value, must be a string describing why the package is suggested';
  13663. unset($this->config['suggest'][$package]);
  13664. }
  13665. }
  13666. }
  13667. if ($this->validateString('minimum-stability') && !empty($this->config['minimum-stability'])) {
  13668. if (!isset(BasePackage::$stabilities[$this->config['minimum-stability']])) {
  13669. $this->errors[] = 'minimum-stability : invalid value ('.$this->config['minimum-stability'].'), must be one of '.implode(', ', array_keys(BasePackage::$stabilities));
  13670. unset($this->config['minimum-stability']);
  13671. }
  13672. }
  13673. if ($this->validateArray('autoload') && !empty($this->config['autoload'])) {
  13674. $types = array('psr-0', 'psr-4', 'classmap', 'files');
  13675. foreach ($this->config['autoload'] as $type => $typeConfig) {
  13676. if (!in_array($type, $types)) {
  13677. $this->errors[] = 'autoload : invalid value ('.$type.'), must be one of '.implode(', ', $types);
  13678. unset($this->config['autoload'][$type]);
  13679. }
  13680. if ($type === 'psr-4') {
  13681. foreach ($typeConfig as $namespace => $dirs) {
  13682. if ($namespace !== '' && '\\' !== substr($namespace, -1)) {
  13683. $this->errors[] = 'autoload.psr-4 : invalid value ('.$namespace.'), namespaces must end with a namespace separator, should be '.$namespace.'\\';
  13684. }
  13685. }
  13686. }
  13687. }
  13688. }
  13689. if (!empty($this->config['autoload']['psr-4']) && !empty($this->config['target-dir'])) {
  13690. $this->errors[] = 'target-dir : this can not be used together with the autoload.psr-4 setting, remove target-dir to upgrade to psr-4';
  13691. unset($this->config['autoload']['psr-4']);
  13692. }
  13693. $this->validateFlatArray('include-path');
  13694. $this->validateArray('transport-options');
  13695. if (isset($this->config['extra']['branch-alias'])) {
  13696. if (!is_array($this->config['extra']['branch-alias'])) {
  13697. $this->errors[] = 'extra.branch-alias : must be an array of versions => aliases';
  13698. } else {
  13699. foreach ($this->config['extra']['branch-alias'] as $sourceBranch => $targetBranch) {
  13700. if ('-dev' !== substr($targetBranch, -4)) {
  13701. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must end in -dev';
  13702. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  13703. continue;
  13704. }
  13705. $validatedTargetBranch = $this->versionParser->normalizeBranch(substr($targetBranch, 0, -4));
  13706. if ('-dev' !== substr($validatedTargetBranch, -4)) {
  13707. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') must be a parseable number like 2.0-dev';
  13708. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  13709. continue;
  13710. }
  13711. if (($sourcePrefix = $this->versionParser->parseNumericAliasPrefix($sourceBranch))
  13712. && ($targetPrefix = $this->versionParser->parseNumericAliasPrefix($targetBranch))
  13713. && (stripos($targetPrefix, $sourcePrefix) !== 0)
  13714. ) {
  13715. $this->warnings[] = 'extra.branch-alias.'.$sourceBranch.' : the target branch ('.$targetBranch.') is not a valid numeric alias for this version';
  13716. unset($this->config['extra']['branch-alias'][$sourceBranch]);
  13717. }
  13718. }
  13719. }
  13720. }
  13721. if ($this->errors) {
  13722. throw new InvalidPackageException($this->errors, $this->warnings, $config);
  13723. }
  13724. $package = $this->loader->load($this->config, $class);
  13725. $this->config = null;
  13726. return $package;
  13727. }
  13728. public function getWarnings()
  13729. {
  13730. return $this->warnings;
  13731. }
  13732. public function getErrors()
  13733. {
  13734. return $this->errors;
  13735. }
  13736. private function validateRegex($property, $regex, $mandatory = false)
  13737. {
  13738. if (!$this->validateString($property, $mandatory)) {
  13739. return false;
  13740. }
  13741. if (!preg_match('{^'.$regex.'$}u', $this->config[$property])) {
  13742. $message = $property.' : invalid value ('.$this->config[$property].'), must match '.$regex;
  13743. if ($mandatory) {
  13744. $this->errors[] = $message;
  13745. } else {
  13746. $this->warnings[] = $message;
  13747. }
  13748. unset($this->config[$property]);
  13749. return false;
  13750. }
  13751. return true;
  13752. }
  13753. private function validateString($property, $mandatory = false)
  13754. {
  13755. if (isset($this->config[$property]) && !is_string($this->config[$property])) {
  13756. $this->errors[] = $property.' : should be a string, '.gettype($this->config[$property]).' given';
  13757. unset($this->config[$property]);
  13758. return false;
  13759. }
  13760. if (!isset($this->config[$property]) || trim($this->config[$property]) === '') {
  13761. if ($mandatory) {
  13762. $this->errors[] = $property.' : must be present';
  13763. }
  13764. unset($this->config[$property]);
  13765. return false;
  13766. }
  13767. return true;
  13768. }
  13769. private function validateArray($property, $mandatory = false)
  13770. {
  13771. if (isset($this->config[$property]) && !is_array($this->config[$property])) {
  13772. $this->errors[] = $property.' : should be an array, '.gettype($this->config[$property]).' given';
  13773. unset($this->config[$property]);
  13774. return false;
  13775. }
  13776. if (!isset($this->config[$property]) || !count($this->config[$property])) {
  13777. if ($mandatory) {
  13778. $this->errors[] = $property.' : must be present and contain at least one element';
  13779. }
  13780. unset($this->config[$property]);
  13781. return false;
  13782. }
  13783. return true;
  13784. }
  13785. private function validateFlatArray($property, $regex = null, $mandatory = false)
  13786. {
  13787. if (!$this->validateArray($property, $mandatory)) {
  13788. return false;
  13789. }
  13790. $pass = true;
  13791. foreach ($this->config[$property] as $key => $value) {
  13792. if (!is_string($value) && !is_numeric($value)) {
  13793. $this->errors[] = $property.'.'.$key.' : must be a string or int, '.gettype($value).' given';
  13794. unset($this->config[$property][$key]);
  13795. $pass = false;
  13796. continue;
  13797. }
  13798. if ($regex && !preg_match('{^'.$regex.'$}u', $value)) {
  13799. $this->warnings[] = $property.'.'.$key.' : invalid value ('.$value.'), must match '.$regex;
  13800. unset($this->config[$property][$key]);
  13801. $pass = false;
  13802. }
  13803. }
  13804. return $pass;
  13805. }
  13806. private function validateUrl($property, $mandatory = false)
  13807. {
  13808. if (!$this->validateString($property, $mandatory)) {
  13809. return false;
  13810. }
  13811. if (!$this->filterUrl($this->config[$property])) {
  13812. $this->warnings[] = $property.' : invalid value ('.$this->config[$property].'), must be an http/https URL';
  13813. unset($this->config[$property]);
  13814. return false;
  13815. }
  13816. return true;
  13817. }
  13818. private function filterUrl($value, array $schemes = array('http', 'https'))
  13819. {
  13820. if ($value === '') {
  13821. return true;
  13822. }
  13823. $bits = parse_url($value);
  13824. if (empty($bits['scheme']) || empty($bits['host'])) {
  13825. return false;
  13826. }
  13827. if (!in_array($bits['scheme'], $schemes, true)) {
  13828. return false;
  13829. }
  13830. return true;
  13831. }
  13832. }
  13833. <?php
  13834. namespace Composer\Package;
  13835. use Composer\Json\JsonFile;
  13836. use Composer\Installer\InstallationManager;
  13837. use Composer\Repository\RepositoryManager;
  13838. use Composer\Util\ProcessExecutor;
  13839. use Composer\Repository\ArrayRepository;
  13840. use Composer\Package\Dumper\ArrayDumper;
  13841. use Composer\Package\Loader\ArrayLoader;
  13842. use Composer\Package\Version\VersionParser;
  13843. use Composer\Util\Git as GitUtil;
  13844. use Composer\IO\IOInterface;
  13845. class Locker
  13846. {
  13847. private $lockFile;
  13848. private $repositoryManager;
  13849. private $installationManager;
  13850. private $hash;
  13851. private $loader;
  13852. private $dumper;
  13853. private $process;
  13854. private $lockDataCache;
  13855. public function __construct(IOInterface $io, JsonFile $lockFile, RepositoryManager $repositoryManager, InstallationManager $installationManager, $hash)
  13856. {
  13857. $this->lockFile = $lockFile;
  13858. $this->repositoryManager = $repositoryManager;
  13859. $this->installationManager = $installationManager;
  13860. $this->hash = $hash;
  13861. $this->loader = new ArrayLoader(null, true);
  13862. $this->dumper = new ArrayDumper();
  13863. $this->process = new ProcessExecutor($io);
  13864. }
  13865. public function isLocked()
  13866. {
  13867. if (!$this->lockFile->exists()) {
  13868. return false;
  13869. }
  13870. $data = $this->getLockData();
  13871. return isset($data['packages']);
  13872. }
  13873. public function isFresh()
  13874. {
  13875. $lock = $this->lockFile->read();
  13876. return $this->hash === $lock['hash'];
  13877. }
  13878. public function getLockedRepository($withDevReqs = false)
  13879. {
  13880. $lockData = $this->getLockData();
  13881. $packages = new ArrayRepository();
  13882. $lockedPackages = $lockData['packages'];
  13883. if ($withDevReqs) {
  13884. if (isset($lockData['packages-dev'])) {
  13885. $lockedPackages = array_merge($lockedPackages, $lockData['packages-dev']);
  13886. } else {
  13887. throw new \RuntimeException('The lock file does not contain require-dev information, run install with the --no-dev option or run update to install those packages.');
  13888. }
  13889. }
  13890. if (empty($lockedPackages)) {
  13891. return $packages;
  13892. }
  13893. if (isset($lockedPackages[0]['name'])) {
  13894. foreach ($lockedPackages as $info) {
  13895. $packages->addPackage($this->loader->load($info));
  13896. }
  13897. return $packages;
  13898. }
  13899. throw new \RuntimeException('Your composer.lock was created before 2012-09-15, and is not supported anymore. Run "composer update" to generate a new one.');
  13900. }
  13901. public function getPlatformRequirements($withDevReqs = false)
  13902. {
  13903. $lockData = $this->getLockData();
  13904. $versionParser = new VersionParser();
  13905. $requirements = array();
  13906. if (!empty($lockData['platform'])) {
  13907. $requirements = $versionParser->parseLinks(
  13908. '__ROOT__',
  13909. '1.0.0',
  13910. 'requires',
  13911. isset($lockData['platform']) ? $lockData['platform'] : array()
  13912. );
  13913. }
  13914. if ($withDevReqs && !empty($lockData['platform-dev'])) {
  13915. $devRequirements = $versionParser->parseLinks(
  13916. '__ROOT__',
  13917. '1.0.0',
  13918. 'requires',
  13919. isset($lockData['platform-dev']) ? $lockData['platform-dev'] : array()
  13920. );
  13921. $requirements = array_merge($requirements, $devRequirements);
  13922. }
  13923. return $requirements;
  13924. }
  13925. public function getMinimumStability()
  13926. {
  13927. $lockData = $this->getLockData();
  13928. return isset($lockData['minimum-stability']) ? $lockData['minimum-stability'] : 'stable';
  13929. }
  13930. public function getStabilityFlags()
  13931. {
  13932. $lockData = $this->getLockData();
  13933. return isset($lockData['stability-flags']) ? $lockData['stability-flags'] : array();
  13934. }
  13935. public function getPreferStable()
  13936. {
  13937. $lockData = $this->getLockData();
  13938. return isset($lockData['prefer-stable']) ? $lockData['prefer-stable'] : null;
  13939. }
  13940. public function getPreferLowest()
  13941. {
  13942. $lockData = $this->getLockData();
  13943. return isset($lockData['prefer-lowest']) ? $lockData['prefer-lowest'] : null;
  13944. }
  13945. public function getAliases()
  13946. {
  13947. $lockData = $this->getLockData();
  13948. return isset($lockData['aliases']) ? $lockData['aliases'] : array();
  13949. }
  13950. public function getLockData()
  13951. {
  13952. if (null !== $this->lockDataCache) {
  13953. return $this->lockDataCache;
  13954. }
  13955. if (!$this->lockFile->exists()) {
  13956. throw new \LogicException('No lockfile found. Unable to read locked packages');
  13957. }
  13958. return $this->lockDataCache = $this->lockFile->read();
  13959. }
  13960. public function setLockData(array $packages, $devPackages, array $platformReqs, $platformDevReqs, array $aliases, $minimumStability, array $stabilityFlags, $preferStable, $preferLowest)
  13961. {
  13962. $lock = array(
  13963. '_readme' => array('This file locks the dependencies of your project to a known state',
  13964. 'Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file',
  13965. 'This file is @gener'.'ated automatically'),
  13966. 'hash' => $this->hash,
  13967. 'packages' => null,
  13968. 'packages-dev' => null,
  13969. 'aliases' => array(),
  13970. 'minimum-stability' => $minimumStability,
  13971. 'stability-flags' => $stabilityFlags,
  13972. 'prefer-stable' => $preferStable,
  13973. 'prefer-lowest' => $preferLowest,
  13974. );
  13975. foreach ($aliases as $package => $versions) {
  13976. foreach ($versions as $version => $alias) {
  13977. $lock['aliases'][] = array(
  13978. 'alias' => $alias['alias'],
  13979. 'alias_normalized' => $alias['alias_normalized'],
  13980. 'version' => $version,
  13981. 'package' => $package,
  13982. );
  13983. }
  13984. }
  13985. $lock['packages'] = $this->lockPackages($packages);
  13986. if (null !== $devPackages) {
  13987. $lock['packages-dev'] = $this->lockPackages($devPackages);
  13988. }
  13989. $lock['platform'] = $platformReqs;
  13990. $lock['platform-dev'] = $platformDevReqs;
  13991. if (empty($lock['packages']) && empty($lock['packages-dev']) && empty($lock['platform']) && empty($lock['platform-dev'])) {
  13992. if ($this->lockFile->exists()) {
  13993. unlink($this->lockFile->getPath());
  13994. }
  13995. return false;
  13996. }
  13997. if (!$this->isLocked() || $lock !== $this->getLockData()) {
  13998. $this->lockFile->write($lock);
  13999. $this->lockDataCache = null;
  14000. return true;
  14001. }
  14002. return false;
  14003. }
  14004. private function lockPackages(array $packages)
  14005. {
  14006. $locked = array();
  14007. foreach ($packages as $package) {
  14008. if ($package instanceof AliasPackage) {
  14009. continue;
  14010. }
  14011. $name = $package->getPrettyName();
  14012. $version = $package->getPrettyVersion();
  14013. if (!$name || !$version) {
  14014. throw new \LogicException(sprintf(
  14015. 'Package "%s" has no version or name and can not be locked', $package
  14016. ));
  14017. }
  14018. $spec = $this->dumper->dump($package);
  14019. unset($spec['version_normalized']);
  14020. $time = isset($spec['time']) ? $spec['time'] : null;
  14021. unset($spec['time']);
  14022. if ($package->isDev() && $package->getInstallationSource() === 'source') {
  14023. $time = $this->getPackageTime($package) ?: $time;
  14024. }
  14025. if (null !== $time) {
  14026. $spec['time'] = $time;
  14027. }
  14028. unset($spec['installation-source']);
  14029. $locked[] = $spec;
  14030. }
  14031. usort($locked, function ($a, $b) {
  14032. $comparison = strcmp($a['name'], $b['name']);
  14033. if (0 !== $comparison) {
  14034. return $comparison;
  14035. }
  14036. return strcmp($a['version'], $b['version']);
  14037. });
  14038. return $locked;
  14039. }
  14040. private function getPackageTime(PackageInterface $package)
  14041. {
  14042. if (!function_exists('proc_open')) {
  14043. return null;
  14044. }
  14045. $path = realpath($this->installationManager->getInstallPath($package));
  14046. $sourceType = $package->getSourceType();
  14047. $datetime = null;
  14048. if ($path && in_array($sourceType, array('git', 'hg'))) {
  14049. $sourceRef = $package->getSourceReference() ?: $package->getDistReference();
  14050. switch ($sourceType) {
  14051. case 'git':
  14052. GitUtil::cleanEnv();
  14053. if (0 === $this->process->execute('git log -n1 --pretty=%ct '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*\d+\s*$}', $output)) {
  14054. $datetime = new \DateTime('@'.trim($output), new \DateTimeZone('UTC'));
  14055. }
  14056. break;
  14057. case 'hg':
  14058. if (0 === $this->process->execute('hg log --template "{date|hgdate}" -r '.ProcessExecutor::escape($sourceRef), $output, $path) && preg_match('{^\s*(\d+)\s*}', $output, $match)) {
  14059. $datetime = new \DateTime('@'.$match[1], new \DateTimeZone('UTC'));
  14060. }
  14061. break;
  14062. }
  14063. }
  14064. return $datetime ? $datetime->format('Y-m-d H:i:s') : null;
  14065. }
  14066. }
  14067. <?php
  14068. namespace Composer\Package;
  14069. use Composer\Package\Version\VersionParser;
  14070. use Composer\Util\ComposerMirror;
  14071. class Package extends BasePackage
  14072. {
  14073. protected $type;
  14074. protected $targetDir;
  14075. protected $installationSource;
  14076. protected $sourceType;
  14077. protected $sourceUrl;
  14078. protected $sourceReference;
  14079. protected $sourceMirrors;
  14080. protected $distType;
  14081. protected $distUrl;
  14082. protected $distReference;
  14083. protected $distSha1Checksum;
  14084. protected $distMirrors;
  14085. protected $version;
  14086. protected $prettyVersion;
  14087. protected $releaseDate;
  14088. protected $extra = array();
  14089. protected $binaries = array();
  14090. protected $dev;
  14091. protected $stability;
  14092. protected $notificationUrl;
  14093. protected $requires = array();
  14094. protected $conflicts = array();
  14095. protected $provides = array();
  14096. protected $replaces = array();
  14097. protected $devRequires = array();
  14098. protected $suggests = array();
  14099. protected $autoload = array();
  14100. protected $devAutoload = array();
  14101. protected $includePaths = array();
  14102. protected $archiveExcludes = array();
  14103. public function __construct($name, $version, $prettyVersion)
  14104. {
  14105. parent::__construct($name);
  14106. $this->version = $version;
  14107. $this->prettyVersion = $prettyVersion;
  14108. $this->stability = VersionParser::parseStability($version);
  14109. $this->dev = $this->stability === 'dev';
  14110. }
  14111. public function isDev()
  14112. {
  14113. return $this->dev;
  14114. }
  14115. public function setType($type)
  14116. {
  14117. $this->type = $type;
  14118. }
  14119. public function getType()
  14120. {
  14121. return $this->type ?: 'library';
  14122. }
  14123. public function getStability()
  14124. {
  14125. return $this->stability;
  14126. }
  14127. public function setTargetDir($targetDir)
  14128. {
  14129. $this->targetDir = $targetDir;
  14130. }
  14131. public function getTargetDir()
  14132. {
  14133. if (null === $this->targetDir) {
  14134. return;
  14135. }
  14136. return ltrim(preg_replace('{ (?:^|[\\\\/]+) \.\.? (?:[\\\\/]+|$) (?:\.\.? (?:[\\\\/]+|$) )*}x', '/', $this->targetDir), '/');
  14137. }
  14138. public function setExtra(array $extra)
  14139. {
  14140. $this->extra = $extra;
  14141. }
  14142. public function getExtra()
  14143. {
  14144. return $this->extra;
  14145. }
  14146. public function setBinaries(array $binaries)
  14147. {
  14148. $this->binaries = $binaries;
  14149. }
  14150. public function getBinaries()
  14151. {
  14152. return $this->binaries;
  14153. }
  14154. public function setInstallationSource($type)
  14155. {
  14156. $this->installationSource = $type;
  14157. }
  14158. public function getInstallationSource()
  14159. {
  14160. return $this->installationSource;
  14161. }
  14162. public function setSourceType($type)
  14163. {
  14164. $this->sourceType = $type;
  14165. }
  14166. public function getSourceType()
  14167. {
  14168. return $this->sourceType;
  14169. }
  14170. public function setSourceUrl($url)
  14171. {
  14172. $this->sourceUrl = $url;
  14173. }
  14174. public function getSourceUrl()
  14175. {
  14176. return $this->sourceUrl;
  14177. }
  14178. public function setSourceReference($reference)
  14179. {
  14180. $this->sourceReference = $reference;
  14181. }
  14182. public function getSourceReference()
  14183. {
  14184. return $this->sourceReference;
  14185. }
  14186. public function setSourceMirrors($mirrors)
  14187. {
  14188. $this->sourceMirrors = $mirrors;
  14189. }
  14190. public function getSourceMirrors()
  14191. {
  14192. return $this->sourceMirrors;
  14193. }
  14194. public function getSourceUrls()
  14195. {
  14196. return $this->getUrls($this->sourceUrl, $this->sourceMirrors, $this->sourceReference, $this->sourceType, 'source');
  14197. }
  14198. public function setDistType($type)
  14199. {
  14200. $this->distType = $type;
  14201. }
  14202. public function getDistType()
  14203. {
  14204. return $this->distType;
  14205. }
  14206. public function setDistUrl($url)
  14207. {
  14208. $this->distUrl = $url;
  14209. }
  14210. public function getDistUrl()
  14211. {
  14212. return $this->distUrl;
  14213. }
  14214. public function setDistReference($reference)
  14215. {
  14216. $this->distReference = $reference;
  14217. }
  14218. public function getDistReference()
  14219. {
  14220. return $this->distReference;
  14221. }
  14222. public function setDistSha1Checksum($sha1checksum)
  14223. {
  14224. $this->distSha1Checksum = $sha1checksum;
  14225. }
  14226. public function getDistSha1Checksum()
  14227. {
  14228. return $this->distSha1Checksum;
  14229. }
  14230. public function setDistMirrors($mirrors)
  14231. {
  14232. $this->distMirrors = $mirrors;
  14233. }
  14234. public function getDistMirrors()
  14235. {
  14236. return $this->distMirrors;
  14237. }
  14238. public function getDistUrls()
  14239. {
  14240. return $this->getUrls($this->distUrl, $this->distMirrors, $this->distReference, $this->distType, 'dist');
  14241. }
  14242. public function getVersion()
  14243. {
  14244. return $this->version;
  14245. }
  14246. public function getPrettyVersion()
  14247. {
  14248. return $this->prettyVersion;
  14249. }
  14250. public function setReleaseDate(\DateTime $releaseDate)
  14251. {
  14252. $this->releaseDate = $releaseDate;
  14253. }
  14254. public function getReleaseDate()
  14255. {
  14256. return $this->releaseDate;
  14257. }
  14258. public function setRequires(array $requires)
  14259. {
  14260. $this->requires = $requires;
  14261. }
  14262. public function getRequires()
  14263. {
  14264. return $this->requires;
  14265. }
  14266. public function setConflicts(array $conflicts)
  14267. {
  14268. $this->conflicts = $conflicts;
  14269. }
  14270. public function getConflicts()
  14271. {
  14272. return $this->conflicts;
  14273. }
  14274. public function setProvides(array $provides)
  14275. {
  14276. $this->provides = $provides;
  14277. }
  14278. public function getProvides()
  14279. {
  14280. return $this->provides;
  14281. }
  14282. public function setReplaces(array $replaces)
  14283. {
  14284. $this->replaces = $replaces;
  14285. }
  14286. public function getReplaces()
  14287. {
  14288. return $this->replaces;
  14289. }
  14290. public function setDevRequires(array $devRequires)
  14291. {
  14292. $this->devRequires = $devRequires;
  14293. }
  14294. public function getDevRequires()
  14295. {
  14296. return $this->devRequires;
  14297. }
  14298. public function setSuggests(array $suggests)
  14299. {
  14300. $this->suggests = $suggests;
  14301. }
  14302. public function getSuggests()
  14303. {
  14304. return $this->suggests;
  14305. }
  14306. public function setAutoload(array $autoload)
  14307. {
  14308. $this->autoload = $autoload;
  14309. }
  14310. public function getAutoload()
  14311. {
  14312. return $this->autoload;
  14313. }
  14314. public function setDevAutoload(array $devAutoload)
  14315. {
  14316. $this->devAutoload = $devAutoload;
  14317. }
  14318. public function getDevAutoload()
  14319. {
  14320. return $this->devAutoload;
  14321. }
  14322. public function setIncludePaths(array $includePaths)
  14323. {
  14324. $this->includePaths = $includePaths;
  14325. }
  14326. public function getIncludePaths()
  14327. {
  14328. return $this->includePaths;
  14329. }
  14330. public function setNotificationUrl($notificationUrl)
  14331. {
  14332. $this->notificationUrl = $notificationUrl;
  14333. }
  14334. public function getNotificationUrl()
  14335. {
  14336. return $this->notificationUrl;
  14337. }
  14338. public function setArchiveExcludes(array $excludes)
  14339. {
  14340. $this->archiveExcludes = $excludes;
  14341. }
  14342. public function getArchiveExcludes()
  14343. {
  14344. return $this->archiveExcludes;
  14345. }
  14346. public function replaceVersion($version, $prettyVersion)
  14347. {
  14348. $this->version = $version;
  14349. $this->prettyVersion = $prettyVersion;
  14350. $this->stability = VersionParser::parseStability($version);
  14351. $this->dev = $this->stability === 'dev';
  14352. }
  14353. protected function getUrls($url, $mirrors, $ref, $type, $urlType)
  14354. {
  14355. if (!$url) {
  14356. return array();
  14357. }
  14358. $urls = array($url);
  14359. if ($mirrors) {
  14360. foreach ($mirrors as $mirror) {
  14361. if ($urlType === 'dist') {
  14362. $mirrorUrl = ComposerMirror::processUrl($mirror['url'], $this->name, $this->version, $ref, $type);
  14363. } elseif ($urlType === 'source' && $type === 'git') {
  14364. $mirrorUrl = ComposerMirror::processGitUrl($mirror['url'], $this->name, $url, $type);
  14365. } elseif ($urlType === 'source' && $type === 'hg') {
  14366. $mirrorUrl = ComposerMirror::processHgUrl($mirror['url'], $this->name, $url, $type);
  14367. }
  14368. if (!in_array($mirrorUrl, $urls)) {
  14369. $func = $mirror['preferred'] ? 'array_unshift' : 'array_push';
  14370. $func($urls, $mirrorUrl);
  14371. }
  14372. }
  14373. }
  14374. return $urls;
  14375. }
  14376. }
  14377. <?php
  14378. namespace Composer\Package;
  14379. use Composer\Repository\RepositoryInterface;
  14380. interface PackageInterface
  14381. {
  14382. public function getName();
  14383. public function getPrettyName();
  14384. public function getNames();
  14385. public function setId($id);
  14386. public function getId();
  14387. public function isDev();
  14388. public function getType();
  14389. public function getTargetDir();
  14390. public function getExtra();
  14391. public function setInstallationSource($type);
  14392. public function getInstallationSource();
  14393. public function getSourceType();
  14394. public function getSourceUrl();
  14395. public function getSourceUrls();
  14396. public function getSourceReference();
  14397. public function getSourceMirrors();
  14398. public function getDistType();
  14399. public function getDistUrl();
  14400. public function getDistUrls();
  14401. public function getDistReference();
  14402. public function getDistSha1Checksum();
  14403. public function getDistMirrors();
  14404. public function getVersion();
  14405. public function getPrettyVersion();
  14406. public function getReleaseDate();
  14407. public function getStability();
  14408. public function getRequires();
  14409. public function getConflicts();
  14410. public function getProvides();
  14411. public function getReplaces();
  14412. public function getDevRequires();
  14413. public function getSuggests();
  14414. public function getAutoload();
  14415. public function getDevAutoload();
  14416. public function getIncludePaths();
  14417. public function setRepository(RepositoryInterface $repository);
  14418. public function getRepository();
  14419. public function getBinaries();
  14420. public function getUniqueName();
  14421. public function getNotificationUrl();
  14422. public function __toString();
  14423. public function getPrettyString();
  14424. public function getArchiveExcludes();
  14425. public function getTransportOptions();
  14426. }
  14427. <?php
  14428. namespace Composer\Package;
  14429. class RootAliasPackage extends AliasPackage implements RootPackageInterface
  14430. {
  14431. public function __construct(RootPackageInterface $aliasOf, $version, $prettyVersion)
  14432. {
  14433. parent::__construct($aliasOf, $version, $prettyVersion);
  14434. }
  14435. public function getAliases()
  14436. {
  14437. return $this->aliasOf->getAliases();
  14438. }
  14439. public function getMinimumStability()
  14440. {
  14441. return $this->aliasOf->getMinimumStability();
  14442. }
  14443. public function getStabilityFlags()
  14444. {
  14445. return $this->aliasOf->getStabilityFlags();
  14446. }
  14447. public function getReferences()
  14448. {
  14449. return $this->aliasOf->getReferences();
  14450. }
  14451. public function getPreferStable()
  14452. {
  14453. return $this->aliasOf->getPreferStable();
  14454. }
  14455. public function setRequires(array $require)
  14456. {
  14457. return $this->aliasOf->setRequires($require);
  14458. }
  14459. public function setDevRequires(array $devRequire)
  14460. {
  14461. return $this->aliasOf->setDevRequires($devRequire);
  14462. }
  14463. public function __clone()
  14464. {
  14465. parent::__clone();
  14466. $this->aliasOf = clone $this->aliasOf;
  14467. }
  14468. }
  14469. <?php
  14470. namespace Composer\Package;
  14471. class RootPackage extends CompletePackage implements RootPackageInterface
  14472. {
  14473. protected $minimumStability = 'stable';
  14474. protected $preferStable = false;
  14475. protected $stabilityFlags = array();
  14476. protected $references = array();
  14477. protected $aliases = array();
  14478. public function setMinimumStability($minimumStability)
  14479. {
  14480. $this->minimumStability = $minimumStability;
  14481. }
  14482. public function getMinimumStability()
  14483. {
  14484. return $this->minimumStability;
  14485. }
  14486. public function setStabilityFlags(array $stabilityFlags)
  14487. {
  14488. $this->stabilityFlags = $stabilityFlags;
  14489. }
  14490. public function getStabilityFlags()
  14491. {
  14492. return $this->stabilityFlags;
  14493. }
  14494. public function setPreferStable($preferStable)
  14495. {
  14496. $this->preferStable = $preferStable;
  14497. }
  14498. public function getPreferStable()
  14499. {
  14500. return $this->preferStable;
  14501. }
  14502. public function setReferences(array $references)
  14503. {
  14504. $this->references = $references;
  14505. }
  14506. public function getReferences()
  14507. {
  14508. return $this->references;
  14509. }
  14510. public function setAliases(array $aliases)
  14511. {
  14512. $this->aliases = $aliases;
  14513. }
  14514. public function getAliases()
  14515. {
  14516. return $this->aliases;
  14517. }
  14518. }
  14519. <?php
  14520. namespace Composer\Package;
  14521. interface RootPackageInterface extends CompletePackageInterface
  14522. {
  14523. public function getAliases();
  14524. public function getMinimumStability();
  14525. public function getStabilityFlags();
  14526. public function getReferences();
  14527. public function getPreferStable();
  14528. public function setRequires(array $requires);
  14529. public function setDevRequires(array $devRequires);
  14530. }
  14531. <?php
  14532. namespace Composer\Package\Version;
  14533. use Composer\Package\BasePackage;
  14534. use Composer\Package\PackageInterface;
  14535. use Composer\Package\Link;
  14536. use Composer\Package\LinkConstraint\EmptyConstraint;
  14537. use Composer\Package\LinkConstraint\MultiConstraint;
  14538. use Composer\Package\LinkConstraint\VersionConstraint;
  14539. class VersionParser
  14540. {
  14541. private static $modifierRegex = '[._-]?(?:(stable|beta|b|RC|alpha|a|patch|pl|p)(?:[.-]?(\d+))?)?([.-]?dev)?';
  14542. public static function parseStability($version)
  14543. {
  14544. $version = preg_replace('{#.+$}i', '', $version);
  14545. if ('dev-' === substr($version, 0, 4) || '-dev' === substr($version, -4)) {
  14546. return 'dev';
  14547. }
  14548. preg_match('{'.self::$modifierRegex.'$}i', strtolower($version), $match);
  14549. if (!empty($match[3])) {
  14550. return 'dev';
  14551. }
  14552. if (!empty($match[1])) {
  14553. if ('beta' === $match[1] || 'b' === $match[1]) {
  14554. return 'beta';
  14555. }
  14556. if ('alpha' === $match[1] || 'a' === $match[1]) {
  14557. return 'alpha';
  14558. }
  14559. if ('rc' === $match[1]) {
  14560. return 'RC';
  14561. }
  14562. }
  14563. return 'stable';
  14564. }
  14565. public static function normalizeStability($stability)
  14566. {
  14567. $stability = strtolower($stability);
  14568. return $stability === 'rc' ? 'RC' : $stability;
  14569. }
  14570. public static function formatVersion(PackageInterface $package, $truncate = true)
  14571. {
  14572. if (!$package->isDev() || !in_array($package->getSourceType(), array('hg', 'git'))) {
  14573. return $package->getPrettyVersion();
  14574. }
  14575. if ($truncate && strlen($package->getSourceReference()) === 40) {
  14576. return $package->getPrettyVersion() . ' ' . substr($package->getSourceReference(), 0, 7);
  14577. }
  14578. return $package->getPrettyVersion() . ' ' . $package->getSourceReference();
  14579. }
  14580. public function normalize($version, $fullVersion = null)
  14581. {
  14582. $version = trim($version);
  14583. if (null === $fullVersion) {
  14584. $fullVersion = $version;
  14585. }
  14586. if (preg_match('{^([^,\s]+) +as +([^,\s]+)$}', $version, $match)) {
  14587. $version = $match[1];
  14588. }
  14589. if (preg_match('{^([^,\s+]+)\+[^\s]+$}', $version, $match)) {
  14590. $version = $match[1];
  14591. }
  14592. if (preg_match('{^(?:dev-)?(?:master|trunk|default)$}i', $version)) {
  14593. return '9999999-dev';
  14594. }
  14595. if ('dev-' === strtolower(substr($version, 0, 4))) {
  14596. return 'dev-'.substr($version, 4);
  14597. }
  14598. if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  14599. $version = $matches[1]
  14600. .(!empty($matches[2]) ? $matches[2] : '.0')
  14601. .(!empty($matches[3]) ? $matches[3] : '.0')
  14602. .(!empty($matches[4]) ? $matches[4] : '.0');
  14603. $index = 5;
  14604. } elseif (preg_match('{^v?(\d{4}(?:[.:-]?\d{2}){1,6}(?:[.:-]?\d{1,3})?)'.self::$modifierRegex.'$}i', $version, $matches)) {
  14605. $version = preg_replace('{\D}', '-', $matches[1]);
  14606. $index = 2;
  14607. } elseif (preg_match('{^v?(\d{4,})(\.\d+)?(\.\d+)?(\.\d+)?'.self::$modifierRegex.'$}i', $version, $matches)) {
  14608. $version = $matches[1]
  14609. .(!empty($matches[2]) ? $matches[2] : '.0')
  14610. .(!empty($matches[3]) ? $matches[3] : '.0')
  14611. .(!empty($matches[4]) ? $matches[4] : '.0');
  14612. $index = 5;
  14613. }
  14614. if (isset($index)) {
  14615. if (!empty($matches[$index])) {
  14616. if ('stable' === $matches[$index]) {
  14617. return $version;
  14618. }
  14619. $version .= '-' . $this->expandStability($matches[$index]) . (!empty($matches[$index+1]) ? $matches[$index+1] : '');
  14620. }
  14621. if (!empty($matches[$index+2])) {
  14622. $version .= '-dev';
  14623. }
  14624. return $version;
  14625. }
  14626. if (preg_match('{(.*?)[.-]?dev$}i', $version, $match)) {
  14627. try {
  14628. return $this->normalizeBranch($match[1]);
  14629. } catch (\Exception $e) {
  14630. }
  14631. }
  14632. $extraMessage = '';
  14633. if (preg_match('{ +as +'.preg_quote($version).'$}', $fullVersion)) {
  14634. $extraMessage = ' in "'.$fullVersion.'", the alias must be an exact version';
  14635. } elseif (preg_match('{^'.preg_quote($version).' +as +}', $fullVersion)) {
  14636. $extraMessage = ' in "'.$fullVersion.'", the alias source must be an exact version, if it is a branch name you should prefix it with dev-';
  14637. }
  14638. throw new \UnexpectedValueException('Invalid version string "'.$version.'"'.$extraMessage);
  14639. }
  14640. public function parseNumericAliasPrefix($branch)
  14641. {
  14642. if (preg_match('/^(?P<version>(\d+\\.)*\d+)(?:\.x)?-dev$/i', $branch, $matches)) {
  14643. return $matches['version'].".";
  14644. }
  14645. return false;
  14646. }
  14647. public function normalizeBranch($name)
  14648. {
  14649. $name = trim($name);
  14650. if (in_array($name, array('master', 'trunk', 'default'))) {
  14651. return $this->normalize($name);
  14652. }
  14653. if (preg_match('#^v?(\d+)(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?(\.(?:\d+|[xX*]))?$#i', $name, $matches)) {
  14654. $version = '';
  14655. for ($i = 1; $i < 5; $i++) {
  14656. $version .= isset($matches[$i]) ? str_replace(array('*', 'X'), 'x', $matches[$i]) : '.x';
  14657. }
  14658. return str_replace('x', '9999999', $version).'-dev';
  14659. }
  14660. return 'dev-'.$name;
  14661. }
  14662. public function parseLinks($source, $sourceVersion, $description, $links)
  14663. {
  14664. $res = array();
  14665. foreach ($links as $target => $constraint) {
  14666. if ('self.version' === $constraint) {
  14667. $parsedConstraint = $this->parseConstraints($sourceVersion);
  14668. } else {
  14669. $parsedConstraint = $this->parseConstraints($constraint);
  14670. }
  14671. $res[strtolower($target)] = new Link($source, $target, $parsedConstraint, $description, $constraint);
  14672. }
  14673. return $res;
  14674. }
  14675. public function parseConstraints($constraints)
  14676. {
  14677. $prettyConstraint = $constraints;
  14678. if (preg_match('{^([^,\s]*?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraints, $match)) {
  14679. $constraints = empty($match[1]) ? '*' : $match[1];
  14680. }
  14681. if (preg_match('{^(dev-[^,\s@]+?|[^,\s@]+?\.x-dev)#.+$}i', $constraints, $match)) {
  14682. $constraints = $match[1];
  14683. }
  14684. $orConstraints = preg_split('{\s*\|\|?\s*}', trim($constraints));
  14685. $orGroups = array();
  14686. foreach ($orConstraints as $constraints) {
  14687. $andConstraints = preg_split('{(?<!^|as|[=>< ,]) *(?<!-)[, ](?!-) *(?!,|as|$)}', $constraints);
  14688. if (count($andConstraints) > 1) {
  14689. $constraintObjects = array();
  14690. foreach ($andConstraints as $constraint) {
  14691. $constraintObjects = array_merge($constraintObjects, $this->parseConstraint($constraint));
  14692. }
  14693. } else {
  14694. $constraintObjects = $this->parseConstraint($andConstraints[0]);
  14695. }
  14696. if (1 === count($constraintObjects)) {
  14697. $constraint = $constraintObjects[0];
  14698. } else {
  14699. $constraint = new MultiConstraint($constraintObjects);
  14700. }
  14701. $orGroups[] = $constraint;
  14702. }
  14703. if (1 === count($orGroups)) {
  14704. $constraint = $orGroups[0];
  14705. } else {
  14706. $constraint = new MultiConstraint($orGroups, false);
  14707. }
  14708. $constraint->setPrettyString($prettyConstraint);
  14709. return $constraint;
  14710. }
  14711. private function parseConstraint($constraint)
  14712. {
  14713. if (preg_match('{^([^,\s]+?)@('.implode('|', array_keys(BasePackage::$stabilities)).')$}i', $constraint, $match)) {
  14714. $constraint = $match[1];
  14715. if ($match[2] !== 'stable') {
  14716. $stabilityModifier = $match[2];
  14717. }
  14718. }
  14719. if (preg_match('{^[xX*](\.[xX*])*$}i', $constraint)) {
  14720. return array(new EmptyConstraint);
  14721. }
  14722. $versionRegex = '(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:\.(\d+))?'.self::$modifierRegex;
  14723. if (preg_match('{^~>?'.$versionRegex.'$}i', $constraint, $matches)) {
  14724. if (substr($constraint, 0, 2) === '~>') {
  14725. throw new \UnexpectedValueException(
  14726. 'Could not parse version constraint '.$constraint.': '.
  14727. 'Invalid operator "~>", you probably meant to use the "~" operator'
  14728. );
  14729. }
  14730. if (isset($matches[4]) && '' !== $matches[4]) {
  14731. $position = 4;
  14732. } elseif (isset($matches[3]) && '' !== $matches[3]) {
  14733. $position = 3;
  14734. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  14735. $position = 2;
  14736. } else {
  14737. $position = 1;
  14738. }
  14739. $stabilitySuffix = '';
  14740. if (!empty($matches[5])) {
  14741. $stabilitySuffix .= '-' . $this->expandStability($matches[5]) . (!empty($matches[6]) ? $matches[6] : '');
  14742. }
  14743. if (!empty($matches[7])) {
  14744. $stabilitySuffix .= '-dev';
  14745. }
  14746. if (!$stabilitySuffix) {
  14747. $stabilitySuffix = "-dev";
  14748. }
  14749. $lowVersion = $this->manipulateVersionString($matches, $position, 0) . $stabilitySuffix;
  14750. $lowerBound = new VersionConstraint('>=', $lowVersion);
  14751. $highPosition = max(1, $position - 1);
  14752. $highVersion = $this->manipulateVersionString($matches, $highPosition, 1) . '-dev';
  14753. $upperBound = new VersionConstraint('<', $highVersion);
  14754. return array(
  14755. $lowerBound,
  14756. $upperBound
  14757. );
  14758. }
  14759. if (preg_match('{^\^'.$versionRegex.'($)}i', $constraint, $matches)) {
  14760. if ('0' !== $matches[1] || '' === $matches[2]) {
  14761. $position = 1;
  14762. } elseif ('0' !== $matches[2] || '' === $matches[3]) {
  14763. $position = 2;
  14764. } else {
  14765. $position = 3;
  14766. }
  14767. $stabilitySuffix = '';
  14768. if (empty($matches[5]) && empty($matches[7])) {
  14769. $stabilitySuffix .= '-dev';
  14770. }
  14771. $lowVersion = $this->normalize(substr($constraint . $stabilitySuffix, 1));
  14772. $lowerBound = new VersionConstraint('>=', $lowVersion);
  14773. $highVersion = $this->manipulateVersionString($matches, $position, 1) . '-dev';
  14774. $upperBound = new VersionConstraint('<', $highVersion);
  14775. return array(
  14776. $lowerBound,
  14777. $upperBound
  14778. );
  14779. }
  14780. if (preg_match('{^(\d+)(?:\.(\d+))?(?:\.(\d+))?\.[xX*]$}', $constraint, $matches)) {
  14781. if (isset($matches[3]) && '' !== $matches[3]) {
  14782. $position = 3;
  14783. } elseif (isset($matches[2]) && '' !== $matches[2]) {
  14784. $position = 2;
  14785. } else {
  14786. $position = 1;
  14787. }
  14788. $lowVersion = $this->manipulateVersionString($matches, $position) . "-dev";
  14789. $highVersion = $this->manipulateVersionString($matches, $position, 1) . "-dev";
  14790. if ($lowVersion === "0.0.0.0-dev") {
  14791. return array(new VersionConstraint('<', $highVersion));
  14792. }
  14793. return array(
  14794. new VersionConstraint('>=', $lowVersion),
  14795. new VersionConstraint('<', $highVersion),
  14796. );
  14797. }
  14798. if (preg_match('{^(?P<from>'.$versionRegex.') +- +(?P<to>'.$versionRegex.')($)}i', $constraint, $matches)) {
  14799. $lowStabilitySuffix = '';
  14800. if (empty($matches[6]) && empty($matches[8])) {
  14801. $lowStabilitySuffix = '-dev';
  14802. }
  14803. $lowVersion = $this->normalize($matches['from']);
  14804. $lowerBound = new VersionConstraint('>=', $lowVersion . $lowStabilitySuffix);
  14805. $highVersion = $matches[10];
  14806. if ((!empty($matches[11]) && !empty($matches[12])) || !empty($matches[14]) || !empty($matches[16])) {
  14807. $highVersion = $this->normalize($matches['to']);
  14808. $upperBound = new VersionConstraint('<=', $highVersion);
  14809. } else {
  14810. $highMatch = array('', $matches[10], $matches[11], $matches[12], $matches[13]);
  14811. $highVersion = $this->manipulateVersionString($highMatch, empty($matches[11]) ? 1 : 2, 1) . '-dev';
  14812. $upperBound = new VersionConstraint('<', $highVersion);
  14813. }
  14814. return array(
  14815. $lowerBound,
  14816. $upperBound
  14817. );
  14818. }
  14819. if (preg_match('{^(<>|!=|>=?|<=?|==?)?\s*(.*)}', $constraint, $matches)) {
  14820. try {
  14821. $version = $this->normalize($matches[2]);
  14822. if (!empty($stabilityModifier) && $this->parseStability($version) === 'stable') {
  14823. $version .= '-' . $stabilityModifier;
  14824. } elseif ('<' === $matches[1]) {
  14825. if (!preg_match('/-' . self::$modifierRegex . '$/', strtolower($matches[2]))) {
  14826. $version .= '-dev';
  14827. }
  14828. }
  14829. return array(new VersionConstraint($matches[1] ?: '=', $version));
  14830. } catch (\Exception $e) {
  14831. }
  14832. }
  14833. $message = 'Could not parse version constraint '.$constraint;
  14834. if (isset($e)) {
  14835. $message .= ': '. $e->getMessage();
  14836. }
  14837. throw new \UnexpectedValueException($message);
  14838. }
  14839. private function manipulateVersionString($matches, $position, $increment = 0, $pad = '0')
  14840. {
  14841. for ($i = 4; $i > 0; $i--) {
  14842. if ($i > $position) {
  14843. $matches[$i] = $pad;
  14844. } elseif ($i == $position && $increment) {
  14845. $matches[$i] += $increment;
  14846. if ($matches[$i] < 0) {
  14847. $matches[$i] = $pad;
  14848. $position--;
  14849. if ($i == 1) {
  14850. return;
  14851. }
  14852. }
  14853. }
  14854. }
  14855. return $matches[1] . '.' . $matches[2] . '.' . $matches[3] . '.' . $matches[4];
  14856. }
  14857. private function expandStability($stability)
  14858. {
  14859. $stability = strtolower($stability);
  14860. switch ($stability) {
  14861. case 'a':
  14862. return 'alpha';
  14863. case 'b':
  14864. return 'beta';
  14865. case 'p':
  14866. case 'pl':
  14867. return 'patch';
  14868. case 'rc':
  14869. return 'RC';
  14870. default:
  14871. return $stability;
  14872. }
  14873. }
  14874. public function parseNameVersionPairs(array $pairs)
  14875. {
  14876. $pairs = array_values($pairs);
  14877. $result = array();
  14878. for ($i = 0, $count = count($pairs); $i < $count; $i++) {
  14879. $pair = preg_replace('{^([^=: ]+)[=: ](.*)$}', '$1 $2', trim($pairs[$i]));
  14880. if (false === strpos($pair, ' ') && isset($pairs[$i+1]) && false === strpos($pairs[$i+1], '/')) {
  14881. $pair .= ' '.$pairs[$i+1];
  14882. $i++;
  14883. }
  14884. if (strpos($pair, ' ')) {
  14885. list($name, $version) = explode(" ", $pair, 2);
  14886. $result[] = array('name' => $name, 'version' => $version);
  14887. } else {
  14888. $result[] = array('name' => $pair);
  14889. }
  14890. }
  14891. return $result;
  14892. }
  14893. }
  14894. <?php
  14895. namespace Composer\Package\Version;
  14896. use Composer\DependencyResolver\Pool;
  14897. use Composer\Package\PackageInterface;
  14898. use Composer\Package\Loader\ArrayLoader;
  14899. use Composer\Package\Dumper\ArrayDumper;
  14900. class VersionSelector
  14901. {
  14902. private $pool;
  14903. private $parser;
  14904. public function __construct(Pool $pool)
  14905. {
  14906. $this->pool = $pool;
  14907. }
  14908. public function findBestCandidate($packageName, $targetPackageVersion = null)
  14909. {
  14910. $constraint = $targetPackageVersion ? $this->getParser()->parseConstraints($targetPackageVersion) : null;
  14911. $candidates = $this->pool->whatProvides($packageName, $constraint, true);
  14912. if (!$candidates) {
  14913. return false;
  14914. }
  14915. $package = reset($candidates);
  14916. foreach ($candidates as $candidate) {
  14917. if (version_compare($package->getVersion(), $candidate->getVersion(), '<')) {
  14918. $package = $candidate;
  14919. }
  14920. }
  14921. return $package;
  14922. }
  14923. public function findRecommendedRequireVersion(PackageInterface $package)
  14924. {
  14925. $version = $package->getVersion();
  14926. if (!$package->isDev()) {
  14927. return $this->transformVersion($version, $package->getPrettyVersion(), $package->getStability());
  14928. }
  14929. $loader = new ArrayLoader($this->getParser());
  14930. $dumper = new ArrayDumper();
  14931. $extra = $loader->getBranchAlias($dumper->dump($package));
  14932. if ($extra) {
  14933. $extra = preg_replace('{^(\d+\.\d+\.\d+)(\.9999999)-dev$}', '$1.0', $extra, -1, $count);
  14934. if ($count) {
  14935. $extra = str_replace('.9999999', '.0', $extra);
  14936. return $this->transformVersion($extra, $extra, 'dev');
  14937. }
  14938. }
  14939. return $package->getPrettyVersion();
  14940. }
  14941. private function transformVersion($version, $prettyVersion, $stability)
  14942. {
  14943. $semanticVersionParts = explode('.', $version);
  14944. $op = '~';
  14945. if (count($semanticVersionParts) == 4 && preg_match('{^0\D?}', $semanticVersionParts[3])) {
  14946. if ($semanticVersionParts[0] === '0') {
  14947. if ($semanticVersionParts[1] === '0') {
  14948. $semanticVersionParts[3] = '*';
  14949. } else {
  14950. $semanticVersionParts[2] = '*';
  14951. unset($semanticVersionParts[3]);
  14952. }
  14953. $op = '';
  14954. } else {
  14955. unset($semanticVersionParts[2], $semanticVersionParts[3]);
  14956. }
  14957. $version = implode('.', $semanticVersionParts);
  14958. } else {
  14959. return $prettyVersion;
  14960. }
  14961. if ($stability != 'stable') {
  14962. $version .= '@'.$stability;
  14963. }
  14964. return $op.$version;
  14965. }
  14966. private function getParser()
  14967. {
  14968. if ($this->parser === null) {
  14969. $this->parser = new VersionParser();
  14970. }
  14971. return $this->parser;
  14972. }
  14973. }
  14974. <?php
  14975. namespace Composer\Plugin;
  14976. use Composer\EventDispatcher\Event;
  14977. use Symfony\Component\Console\Input\InputInterface;
  14978. use Symfony\Component\Console\Output\OutputInterface;
  14979. class CommandEvent extends Event
  14980. {
  14981. private $commandName;
  14982. private $input;
  14983. private $output;
  14984. public function __construct($name, $commandName, $input, $output, array $args = array(), array $flags = array())
  14985. {
  14986. parent::__construct($name, $args, $flags);
  14987. $this->commandName = $commandName;
  14988. $this->input = $input;
  14989. $this->output = $output;
  14990. }
  14991. public function getInput()
  14992. {
  14993. return $this->input;
  14994. }
  14995. public function getOutput()
  14996. {
  14997. return $this->output;
  14998. }
  14999. public function getCommandName()
  15000. {
  15001. return $this->commandName;
  15002. }
  15003. }
  15004. <?php
  15005. namespace Composer\Plugin;
  15006. class PluginEvents
  15007. {
  15008. const COMMAND = 'command';
  15009. const PRE_FILE_DOWNLOAD = 'pre-file-download';
  15010. }
  15011. <?php
  15012. namespace Composer\Plugin;
  15013. use Composer\Composer;
  15014. use Composer\IO\IOInterface;
  15015. interface PluginInterface
  15016. {
  15017. const PLUGIN_API_VERSION = '1.0.0';
  15018. public function activate(Composer $composer, IOInterface $io);
  15019. }
  15020. <?php
  15021. namespace Composer\Plugin;
  15022. use Composer\Composer;
  15023. use Composer\EventDispatcher\EventSubscriberInterface;
  15024. use Composer\IO\IOInterface;
  15025. use Composer\Package\Package;
  15026. use Composer\Package\Version\VersionParser;
  15027. use Composer\Repository\RepositoryInterface;
  15028. use Composer\Package\AliasPackage;
  15029. use Composer\Package\PackageInterface;
  15030. use Composer\Package\Link;
  15031. use Composer\Package\LinkConstraint\VersionConstraint;
  15032. use Composer\DependencyResolver\Pool;
  15033. class PluginManager
  15034. {
  15035. protected $composer;
  15036. protected $io;
  15037. protected $globalComposer;
  15038. protected $versionParser;
  15039. protected $plugins = array();
  15040. protected $registeredPlugins = array();
  15041. private static $classCounter = 0;
  15042. public function __construct(IOInterface $io, Composer $composer, Composer $globalComposer = null)
  15043. {
  15044. $this->io = $io;
  15045. $this->composer = $composer;
  15046. $this->globalComposer = $globalComposer;
  15047. $this->versionParser = new VersionParser();
  15048. }
  15049. public function loadInstalledPlugins()
  15050. {
  15051. $repo = $this->composer->getRepositoryManager()->getLocalRepository();
  15052. $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
  15053. if ($repo) {
  15054. $this->loadRepository($repo);
  15055. }
  15056. if ($globalRepo) {
  15057. $this->loadRepository($globalRepo);
  15058. }
  15059. }
  15060. public function addPlugin(PluginInterface $plugin)
  15061. {
  15062. if ($this->io->isDebug()) {
  15063. $this->io->writeError('Loading plugin '.get_class($plugin));
  15064. }
  15065. $this->plugins[] = $plugin;
  15066. $plugin->activate($this->composer, $this->io);
  15067. if ($plugin instanceof EventSubscriberInterface) {
  15068. $this->composer->getEventDispatcher()->addSubscriber($plugin);
  15069. }
  15070. }
  15071. public function getPlugins()
  15072. {
  15073. return $this->plugins;
  15074. }
  15075. public function loadRepository(RepositoryInterface $repo)
  15076. {
  15077. foreach ($repo->getPackages() as $package) {
  15078. if ($package instanceof AliasPackage) {
  15079. continue;
  15080. }
  15081. if ('composer-plugin' === $package->getType()) {
  15082. $requiresComposer = null;
  15083. foreach ($package->getRequires() as $link) {
  15084. if ($link->getTarget() == 'composer-plugin-api') {
  15085. $requiresComposer = $link->getConstraint();
  15086. }
  15087. }
  15088. if (!$requiresComposer) {
  15089. throw new \RuntimeException("Plugin ".$package->getName()." is missing a require statement for a version of the composer-plugin-api package.");
  15090. }
  15091. if (!$requiresComposer->matches(new VersionConstraint('==', $this->versionParser->normalize(PluginInterface::PLUGIN_API_VERSION)))) {
  15092. $this->io->writeError("<warning>The plugin ".$package->getName()." requires a version of composer-plugin-api that does not match your composer installation. You may need to run composer update with the '--no-plugins' option.</warning>");
  15093. }
  15094. $this->registerPackage($package);
  15095. }
  15096. if ('composer-installer' === $package->getType()) {
  15097. $this->registerPackage($package);
  15098. }
  15099. }
  15100. }
  15101. protected function collectDependencies(Pool $pool, array $collected, PackageInterface $package)
  15102. {
  15103. $requires = array_merge(
  15104. $package->getRequires(),
  15105. $package->getDevRequires()
  15106. );
  15107. foreach ($requires as $requireLink) {
  15108. $requiredPackage = $this->lookupInstalledPackage($pool, $requireLink);
  15109. if ($requiredPackage && !isset($collected[$requiredPackage->getName()])) {
  15110. $collected[$requiredPackage->getName()] = $requiredPackage;
  15111. $collected = $this->collectDependencies($pool, $collected, $requiredPackage);
  15112. }
  15113. }
  15114. return $collected;
  15115. }
  15116. protected function lookupInstalledPackage(Pool $pool, Link $link)
  15117. {
  15118. $packages = $pool->whatProvides($link->getTarget(), $link->getConstraint());
  15119. return (!empty($packages)) ? $packages[0] : null;
  15120. }
  15121. public function registerPackage(PackageInterface $package, $failOnMissingClasses = false)
  15122. {
  15123. $oldInstallerPlugin = ($package->getType() === 'composer-installer');
  15124. if (in_array($package->getName(), $this->registeredPlugins)) {
  15125. return;
  15126. }
  15127. $extra = $package->getExtra();
  15128. if (empty($extra['class'])) {
  15129. throw new \UnexpectedValueException('Error while installing '.$package->getPrettyName().', composer-plugin packages should have a class defined in their extra key to be usable.');
  15130. }
  15131. $classes = is_array($extra['class']) ? $extra['class'] : array($extra['class']);
  15132. $localRepo = $this->composer->getRepositoryManager()->getLocalRepository();
  15133. $globalRepo = $this->globalComposer ? $this->globalComposer->getRepositoryManager()->getLocalRepository() : null;
  15134. $pool = new Pool('dev');
  15135. $pool->addRepository($localRepo);
  15136. if ($globalRepo) {
  15137. $pool->addRepository($globalRepo);
  15138. }
  15139. $autoloadPackages = array($package->getName() => $package);
  15140. $autoloadPackages = $this->collectDependencies($pool, $autoloadPackages, $package);
  15141. $generator = $this->composer->getAutoloadGenerator();
  15142. $autoloads = array();
  15143. foreach ($autoloadPackages as $autoloadPackage) {
  15144. $downloadPath = $this->getInstallPath($autoloadPackage, ($globalRepo && $globalRepo->hasPackage($autoloadPackage)));
  15145. $autoloads[] = array($autoloadPackage, $downloadPath);
  15146. }
  15147. $map = $generator->parseAutoloads($autoloads, new Package('dummy', '1.0.0.0', '1.0.0'));
  15148. $classLoader = $generator->createLoader($map);
  15149. $classLoader->register();
  15150. foreach ($classes as $class) {
  15151. if (class_exists($class, false)) {
  15152. $code = file_get_contents($classLoader->findFile($class));
  15153. $code = preg_replace('{^(\s*)class\s+(\S+)}mi', '$1class $2_composer_tmp'.self::$classCounter, $code);
  15154. eval('?>'.$code);
  15155. $class .= '_composer_tmp'.self::$classCounter;
  15156. self::$classCounter++;
  15157. }
  15158. if ($oldInstallerPlugin) {
  15159. $installer = new $class($this->io, $this->composer);
  15160. $this->composer->getInstallationManager()->addInstaller($installer);
  15161. } elseif (class_exists($class)) {
  15162. $plugin = new $class();
  15163. $this->addPlugin($plugin);
  15164. $this->registeredPlugins[] = $package->getName();
  15165. } elseif ($failOnMissingClasses) {
  15166. throw new \UnexpectedValueException('Plugin '.$package->getName().' could not be initialized, class not found: '.$class);
  15167. }
  15168. }
  15169. }
  15170. public function getInstallPath(PackageInterface $package, $global = false)
  15171. {
  15172. if (!$global) {
  15173. return $this->composer->getInstallationManager()->getInstallPath($package);
  15174. }
  15175. return $this->globalComposer->getInstallationManager()->getInstallPath($package);
  15176. }
  15177. }
  15178. <?php
  15179. namespace Composer\Plugin;
  15180. use Composer\EventDispatcher\Event;
  15181. use Composer\Util\RemoteFilesystem;
  15182. class PreFileDownloadEvent extends Event
  15183. {
  15184. private $rfs;
  15185. private $processedUrl;
  15186. public function __construct($name, RemoteFilesystem $rfs, $processedUrl)
  15187. {
  15188. parent::__construct($name);
  15189. $this->rfs = $rfs;
  15190. $this->processedUrl = $processedUrl;
  15191. }
  15192. public function getRemoteFilesystem()
  15193. {
  15194. return $this->rfs;
  15195. }
  15196. public function setRemoteFilesystem(RemoteFilesystem $rfs)
  15197. {
  15198. $this->rfs = $rfs;
  15199. }
  15200. public function getProcessedUrl()
  15201. {
  15202. return $this->processedUrl;
  15203. }
  15204. }
  15205. <?php
  15206. namespace Composer\Repository;
  15207. use Composer\Package\AliasPackage;
  15208. use Composer\Package\PackageInterface;
  15209. use Composer\Package\CompletePackageInterface;
  15210. use Composer\Package\Version\VersionParser;
  15211. class ArrayRepository implements RepositoryInterface
  15212. {
  15213. protected $packages;
  15214. public function __construct(array $packages = array())
  15215. {
  15216. foreach ($packages as $package) {
  15217. $this->addPackage($package);
  15218. }
  15219. }
  15220. public function findPackage($name, $version)
  15221. {
  15222. $versionParser = new VersionParser();
  15223. $version = $versionParser->normalize($version);
  15224. $name = strtolower($name);
  15225. foreach ($this->getPackages() as $package) {
  15226. if ($name === $package->getName() && $version === $package->getVersion()) {
  15227. return $package;
  15228. }
  15229. }
  15230. }
  15231. public function findPackages($name, $version = null)
  15232. {
  15233. $name = strtolower($name);
  15234. if (null !== $version) {
  15235. $versionParser = new VersionParser();
  15236. $version = $versionParser->normalize($version);
  15237. }
  15238. $packages = array();
  15239. foreach ($this->getPackages() as $package) {
  15240. if ($package->getName() === $name && (null === $version || $version === $package->getVersion())) {
  15241. $packages[] = $package;
  15242. }
  15243. }
  15244. return $packages;
  15245. }
  15246. public function search($query, $mode = 0)
  15247. {
  15248. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  15249. $matches = array();
  15250. foreach ($this->getPackages() as $package) {
  15251. $name = $package->getName();
  15252. if (isset($matches[$name])) {
  15253. continue;
  15254. }
  15255. if (preg_match($regex, $name)
  15256. || ($mode === self::SEARCH_FULLTEXT && $package instanceof CompletePackageInterface && preg_match($regex, implode(' ', (array) $package->getKeywords()) . ' ' . $package->getDescription()))
  15257. ) {
  15258. $matches[$name] = array(
  15259. 'name' => $package->getPrettyName(),
  15260. 'description' => $package->getDescription(),
  15261. );
  15262. }
  15263. }
  15264. return array_values($matches);
  15265. }
  15266. public function hasPackage(PackageInterface $package)
  15267. {
  15268. $packageId = $package->getUniqueName();
  15269. foreach ($this->getPackages() as $repoPackage) {
  15270. if ($packageId === $repoPackage->getUniqueName()) {
  15271. return true;
  15272. }
  15273. }
  15274. return false;
  15275. }
  15276. public function addPackage(PackageInterface $package)
  15277. {
  15278. if (null === $this->packages) {
  15279. $this->initialize();
  15280. }
  15281. $package->setRepository($this);
  15282. $this->packages[] = $package;
  15283. if ($package instanceof AliasPackage) {
  15284. $aliasedPackage = $package->getAliasOf();
  15285. if (null === $aliasedPackage->getRepository()) {
  15286. $this->addPackage($aliasedPackage);
  15287. }
  15288. }
  15289. }
  15290. protected function createAliasPackage(PackageInterface $package, $alias, $prettyAlias)
  15291. {
  15292. return new AliasPackage($package instanceof AliasPackage ? $package->getAliasOf() : $package, $alias, $prettyAlias);
  15293. }
  15294. public function removePackage(PackageInterface $package)
  15295. {
  15296. $packageId = $package->getUniqueName();
  15297. foreach ($this->getPackages() as $key => $repoPackage) {
  15298. if ($packageId === $repoPackage->getUniqueName()) {
  15299. array_splice($this->packages, $key, 1);
  15300. return;
  15301. }
  15302. }
  15303. }
  15304. public function getPackages()
  15305. {
  15306. if (null === $this->packages) {
  15307. $this->initialize();
  15308. }
  15309. return $this->packages;
  15310. }
  15311. public function count()
  15312. {
  15313. return count($this->packages);
  15314. }
  15315. protected function initialize()
  15316. {
  15317. $this->packages = array();
  15318. }
  15319. }
  15320. <?php
  15321. namespace Composer\Repository;
  15322. use Composer\IO\IOInterface;
  15323. use Composer\Json\JsonFile;
  15324. use Composer\Package\Loader\ArrayLoader;
  15325. class ArtifactRepository extends ArrayRepository
  15326. {
  15327. protected $loader;
  15328. protected $lookup;
  15329. public function __construct(array $repoConfig, IOInterface $io)
  15330. {
  15331. if (!extension_loaded('zip')) {
  15332. throw new \RuntimeException('The artifact repository requires PHP\'s zip extension');
  15333. }
  15334. $this->loader = new ArrayLoader();
  15335. $this->lookup = $repoConfig['url'];
  15336. $this->io = $io;
  15337. }
  15338. protected function initialize()
  15339. {
  15340. parent::initialize();
  15341. $this->scanDirectory($this->lookup);
  15342. }
  15343. private function scanDirectory($path)
  15344. {
  15345. $io = $this->io;
  15346. $directory = new \RecursiveDirectoryIterator($path);
  15347. $iterator = new \RecursiveIteratorIterator($directory);
  15348. $regex = new \RegexIterator($iterator, '/^.+\.(zip|phar)$/i');
  15349. foreach ($regex as $file) {
  15350. if (!$file->isFile()) {
  15351. continue;
  15352. }
  15353. $package = $this->getComposerInformation($file);
  15354. if (!$package) {
  15355. if ($io->isVerbose()) {
  15356. $io->writeError("File <comment>{$file->getBasename()}</comment> doesn't seem to hold a package");
  15357. }
  15358. continue;
  15359. }
  15360. if ($io->isVerbose()) {
  15361. $template = 'Found package <info>%s</info> (<comment>%s</comment>) in file <info>%s</info>';
  15362. $io->writeError(sprintf($template, $package->getName(), $package->getPrettyVersion(), $file->getBasename()));
  15363. }
  15364. $this->addPackage($package);
  15365. }
  15366. }
  15367. private function locateFile(\ZipArchive $zip, $filename)
  15368. {
  15369. $indexOfShortestMatch = false;
  15370. $lengthOfShortestMatch = -1;
  15371. for ($i = 0; $i < $zip->numFiles; $i++) {
  15372. $stat = $zip->statIndex($i);
  15373. if (strcmp(basename($stat['name']), $filename) === 0) {
  15374. $directoryName = dirname($stat['name']);
  15375. if ($directoryName == '.') {
  15376. return $i;
  15377. }
  15378. if (strpos($directoryName, '\\') !== false ||
  15379. strpos($directoryName, '/') !== false) {
  15380. continue;
  15381. }
  15382. $length = strlen($stat['name']);
  15383. if ($indexOfShortestMatch == false || $length < $lengthOfShortestMatch) {
  15384. $contents = $zip->getFromIndex($i);
  15385. if ($contents !== false) {
  15386. $indexOfShortestMatch = $i;
  15387. $lengthOfShortestMatch = $length;
  15388. }
  15389. }
  15390. }
  15391. }
  15392. return $indexOfShortestMatch;
  15393. }
  15394. private function getComposerInformation(\SplFileInfo $file)
  15395. {
  15396. $zip = new \ZipArchive();
  15397. $zip->open($file->getPathname());
  15398. if (0 == $zip->numFiles) {
  15399. return false;
  15400. }
  15401. $foundFileIndex = $this->locateFile($zip, 'composer.json');
  15402. if (false === $foundFileIndex) {
  15403. return false;
  15404. }
  15405. $configurationFileName = $zip->getNameIndex($foundFileIndex);
  15406. $composerFile = "zip://{$file->getPathname()}#$configurationFileName";
  15407. $json = file_get_contents($composerFile);
  15408. $package = JsonFile::parseJson($json, $composerFile);
  15409. $package['dist'] = array(
  15410. 'type' => 'zip',
  15411. 'url' => $file->getPathname(),
  15412. 'shasum' => sha1_file($file->getRealPath())
  15413. );
  15414. $package = $this->loader->load($package);
  15415. return $package;
  15416. }
  15417. }
  15418. <?php
  15419. namespace Composer\Repository;
  15420. use Composer\Package\Loader\ArrayLoader;
  15421. use Composer\Package\Package;
  15422. use Composer\Package\PackageInterface;
  15423. use Composer\Package\AliasPackage;
  15424. use Composer\Package\Version\VersionParser;
  15425. use Composer\DependencyResolver\Pool;
  15426. use Composer\Json\JsonFile;
  15427. use Composer\Cache;
  15428. use Composer\Config;
  15429. use Composer\IO\IOInterface;
  15430. use Composer\Util\RemoteFilesystem;
  15431. use Composer\Plugin\PluginEvents;
  15432. use Composer\Plugin\PreFileDownloadEvent;
  15433. use Composer\EventDispatcher\EventDispatcher;
  15434. class ComposerRepository extends ArrayRepository
  15435. {
  15436. protected $config;
  15437. protected $options;
  15438. protected $url;
  15439. protected $baseUrl;
  15440. protected $io;
  15441. protected $rfs;
  15442. protected $cache;
  15443. protected $notifyUrl;
  15444. protected $searchUrl;
  15445. protected $hasProviders = false;
  15446. protected $providersUrl;
  15447. protected $lazyProvidersUrl;
  15448. protected $providerListing;
  15449. protected $providers = array();
  15450. protected $providersByUid = array();
  15451. protected $loader;
  15452. protected $rootAliases;
  15453. protected $allowSslDowngrade = false;
  15454. protected $eventDispatcher;
  15455. protected $sourceMirrors;
  15456. protected $distMirrors;
  15457. private $degradedMode = false;
  15458. private $rootData;
  15459. public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  15460. {
  15461. if (!preg_match('{^[\w.]+\??://}', $repoConfig['url'])) {
  15462. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  15463. }
  15464. $repoConfig['url'] = rtrim($repoConfig['url'], '/');
  15465. if ('https?' === substr($repoConfig['url'], 0, 6)) {
  15466. $repoConfig['url'] = (extension_loaded('openssl') ? 'https' : 'http') . substr($repoConfig['url'], 6);
  15467. }
  15468. $urlBits = parse_url($repoConfig['url']);
  15469. if ($urlBits === false || empty($urlBits['scheme'])) {
  15470. throw new \UnexpectedValueException('Invalid url given for Composer repository: '.$repoConfig['url']);
  15471. }
  15472. if (!isset($repoConfig['options'])) {
  15473. $repoConfig['options'] = array();
  15474. }
  15475. if (isset($repoConfig['allow_ssl_downgrade']) && true === $repoConfig['allow_ssl_downgrade']) {
  15476. $this->allowSslDowngrade = true;
  15477. }
  15478. $this->config = $config;
  15479. $this->options = $repoConfig['options'];
  15480. $this->url = $repoConfig['url'];
  15481. $this->baseUrl = rtrim(preg_replace('{^(.*)(?:/[^/\\]+.json)?(?:[?#].*)?$}', '$1', $this->url), '/');
  15482. $this->io = $io;
  15483. $this->cache = new Cache($io, $config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->url), 'a-z0-9.$');
  15484. $this->loader = new ArrayLoader();
  15485. $this->rfs = new RemoteFilesystem($this->io, $this->config, $this->options);
  15486. $this->eventDispatcher = $eventDispatcher;
  15487. }
  15488. public function setRootAliases(array $rootAliases)
  15489. {
  15490. $this->rootAliases = $rootAliases;
  15491. }
  15492. public function findPackage($name, $version)
  15493. {
  15494. if (!$this->hasProviders()) {
  15495. return parent::findPackage($name, $version);
  15496. }
  15497. $versionParser = new VersionParser();
  15498. $version = $versionParser->normalize($version);
  15499. $name = strtolower($name);
  15500. foreach ($this->getProviderNames() as $providerName) {
  15501. if ($name === $providerName) {
  15502. $packages = $this->whatProvides(new Pool('dev'), $providerName);
  15503. foreach ($packages as $package) {
  15504. if ($name == $package->getName() && $version === $package->getVersion()) {
  15505. return $package;
  15506. }
  15507. }
  15508. }
  15509. }
  15510. }
  15511. public function findPackages($name, $version = null)
  15512. {
  15513. if (!$this->hasProviders()) {
  15514. return parent::findPackages($name, $version);
  15515. }
  15516. $name = strtolower($name);
  15517. if (null !== $version) {
  15518. $versionParser = new VersionParser();
  15519. $version = $versionParser->normalize($version);
  15520. }
  15521. $packages = array();
  15522. foreach ($this->getProviderNames() as $providerName) {
  15523. if ($name === $providerName) {
  15524. $packages = $this->whatProvides(new Pool('dev'), $providerName);
  15525. foreach ($packages as $package) {
  15526. if ($name == $package->getName() && (null === $version || $version === $package->getVersion())) {
  15527. $packages[] = $package;
  15528. }
  15529. }
  15530. }
  15531. }
  15532. return $packages;
  15533. }
  15534. public function getPackages()
  15535. {
  15536. if ($this->hasProviders()) {
  15537. throw new \LogicException('Composer repositories that have providers can not load the complete list of packages, use getProviderNames instead.');
  15538. }
  15539. return parent::getPackages();
  15540. }
  15541. public function search($query, $mode = 0)
  15542. {
  15543. $this->loadRootServerFile();
  15544. if ($this->searchUrl && $mode === self::SEARCH_FULLTEXT) {
  15545. $url = str_replace('%query%', $query, $this->searchUrl);
  15546. $hostname = parse_url($url, PHP_URL_HOST) ?: $url;
  15547. $json = $this->rfs->getContents($hostname, $url, false);
  15548. $results = JsonFile::parseJson($json, $url);
  15549. return $results['results'];
  15550. }
  15551. if ($this->hasProviders()) {
  15552. $results = array();
  15553. $regex = '{(?:'.implode('|', preg_split('{\s+}', $query)).')}i';
  15554. foreach ($this->getProviderNames() as $name) {
  15555. if (preg_match($regex, $name)) {
  15556. $results[] = array('name' => $name);
  15557. }
  15558. }
  15559. return $results;
  15560. }
  15561. return parent::search($query, $mode);
  15562. }
  15563. public function getProviderNames()
  15564. {
  15565. $this->loadRootServerFile();
  15566. if (null === $this->providerListing) {
  15567. $this->loadProviderListings($this->loadRootServerFile());
  15568. }
  15569. if ($this->lazyProvidersUrl) {
  15570. return array();
  15571. }
  15572. if ($this->providersUrl) {
  15573. return array_keys($this->providerListing);
  15574. }
  15575. $providers = array();
  15576. foreach (array_keys($this->providerListing) as $provider) {
  15577. $providers[] = substr($provider, 2, -5);
  15578. }
  15579. return $providers;
  15580. }
  15581. protected function configurePackageTransportOptions(PackageInterface $package)
  15582. {
  15583. foreach ($package->getDistUrls() as $url) {
  15584. if (strpos($url, $this->baseUrl) === 0) {
  15585. $package->setTransportOptions($this->options);
  15586. return;
  15587. }
  15588. }
  15589. }
  15590. public function hasProviders()
  15591. {
  15592. $this->loadRootServerFile();
  15593. return $this->hasProviders;
  15594. }
  15595. public function resetPackageIds()
  15596. {
  15597. foreach ($this->providersByUid as $package) {
  15598. if ($package instanceof AliasPackage) {
  15599. $package->getAliasOf()->setId(-1);
  15600. }
  15601. $package->setId(-1);
  15602. }
  15603. }
  15604. public function whatProvides(Pool $pool, $name)
  15605. {
  15606. if (isset($this->providers[$name])) {
  15607. return $this->providers[$name];
  15608. }
  15609. if (preg_match(PlatformRepository::PLATFORM_PACKAGE_REGEX, $name) || '__root__' === $name) {
  15610. return array();
  15611. }
  15612. if (null === $this->providerListing) {
  15613. $this->loadProviderListings($this->loadRootServerFile());
  15614. }
  15615. if ($this->lazyProvidersUrl && !isset($this->providerListing[$name])) {
  15616. $hash = null;
  15617. $url = str_replace('%package%', $name, $this->lazyProvidersUrl);
  15618. $cacheKey = false;
  15619. } elseif ($this->providersUrl) {
  15620. if (!isset($this->providerListing[$name])) {
  15621. return array();
  15622. }
  15623. $hash = $this->providerListing[$name]['sha256'];
  15624. $url = str_replace(array('%package%', '%hash%'), array($name, $hash), $this->providersUrl);
  15625. $cacheKey = 'provider-'.strtr($name, '/', '$').'.json';
  15626. } else {
  15627. $url = 'p/'.$name.'.json';
  15628. if (!isset($this->providerListing[$url])) {
  15629. return array();
  15630. }
  15631. $hash = $this->providerListing[$url]['sha256'];
  15632. $cacheKey = null;
  15633. }
  15634. if ($cacheKey && $this->cache->sha256($cacheKey) === $hash) {
  15635. $packages = json_decode($this->cache->read($cacheKey), true);
  15636. } else {
  15637. $packages = $this->fetchFile($url, $cacheKey, $hash);
  15638. }
  15639. $this->providers[$name] = array();
  15640. foreach ($packages['packages'] as $versions) {
  15641. foreach ($versions as $version) {
  15642. if (isset($this->providersByUid[$version['uid']])) {
  15643. if (!isset($this->providers[$name][$version['uid']])) {
  15644. if ($this->providersByUid[$version['uid']] instanceof AliasPackage) {
  15645. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']]->getAliasOf();
  15646. $this->providers[$name][$version['uid'].'-alias'] = $this->providersByUid[$version['uid']];
  15647. } else {
  15648. $this->providers[$name][$version['uid']] = $this->providersByUid[$version['uid']];
  15649. }
  15650. if (isset($this->providersByUid[$version['uid'].'-root'])) {
  15651. $this->providers[$name][$version['uid'].'-root'] = $this->providersByUid[$version['uid'].'-root'];
  15652. }
  15653. }
  15654. } else {
  15655. if (!$pool->isPackageAcceptable(strtolower($version['name']), VersionParser::parseStability($version['version']))) {
  15656. continue;
  15657. }
  15658. $package = $this->createPackage($version, 'Composer\Package\Package');
  15659. $package->setRepository($this);
  15660. if ($package instanceof AliasPackage) {
  15661. $aliased = $package->getAliasOf();
  15662. $aliased->setRepository($this);
  15663. $this->providers[$name][$version['uid']] = $aliased;
  15664. $this->providers[$name][$version['uid'].'-alias'] = $package;
  15665. $this->providersByUid[$version['uid']] = $package;
  15666. } else {
  15667. $this->providers[$name][$version['uid']] = $package;
  15668. $this->providersByUid[$version['uid']] = $package;
  15669. }
  15670. unset($rootAliasData);
  15671. if (isset($this->rootAliases[$package->getName()][$package->getVersion()])) {
  15672. $rootAliasData = $this->rootAliases[$package->getName()][$package->getVersion()];
  15673. } elseif ($package instanceof AliasPackage && isset($this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()])) {
  15674. $rootAliasData = $this->rootAliases[$package->getName()][$package->getAliasOf()->getVersion()];
  15675. }
  15676. if (isset($rootAliasData)) {
  15677. $alias = $this->createAliasPackage($package, $rootAliasData['alias_normalized'], $rootAliasData['alias']);
  15678. $alias->setRepository($this);
  15679. $this->providers[$name][$version['uid'].'-root'] = $alias;
  15680. $this->providersByUid[$version['uid'].'-root'] = $alias;
  15681. }
  15682. }
  15683. }
  15684. }
  15685. return $this->providers[$name];
  15686. }
  15687. protected function initialize()
  15688. {
  15689. parent::initialize();
  15690. $repoData = $this->loadDataFromServer();
  15691. foreach ($repoData as $package) {
  15692. $this->addPackage($this->createPackage($package, 'Composer\Package\CompletePackage'));
  15693. }
  15694. }
  15695. public function addPackage(PackageInterface $package)
  15696. {
  15697. parent::addPackage($package);
  15698. $this->configurePackageTransportOptions($package);
  15699. }
  15700. protected function loadRootServerFile()
  15701. {
  15702. if (null !== $this->rootData) {
  15703. return $this->rootData;
  15704. }
  15705. if (!extension_loaded('openssl') && 'https' === substr($this->url, 0, 5)) {
  15706. throw new \RuntimeException('You must enable the openssl extension in your php.ini to load information from '.$this->url);
  15707. }
  15708. $jsonUrlParts = parse_url($this->url);
  15709. if (isset($jsonUrlParts['path']) && false !== strpos($jsonUrlParts['path'], '.json')) {
  15710. $jsonUrl = $this->url;
  15711. } else {
  15712. $jsonUrl = $this->url . '/packages.json';
  15713. }
  15714. $data = $this->fetchFile($jsonUrl, 'packages.json');
  15715. if (!empty($data['notify-batch'])) {
  15716. $this->notifyUrl = $this->canonicalizeUrl($data['notify-batch']);
  15717. } elseif (!empty($data['notify_batch'])) {
  15718. $this->notifyUrl = $this->canonicalizeUrl($data['notify_batch']);
  15719. } elseif (!empty($data['notify'])) {
  15720. $this->notifyUrl = $this->canonicalizeUrl($data['notify']);
  15721. }
  15722. if (!empty($data['search'])) {
  15723. $this->searchUrl = $this->canonicalizeUrl($data['search']);
  15724. }
  15725. if (!empty($data['mirrors'])) {
  15726. foreach ($data['mirrors'] as $mirror) {
  15727. if (!empty($mirror['git-url'])) {
  15728. $this->sourceMirrors['git'][] = array('url' => $mirror['git-url'], 'preferred' => !empty($mirror['preferred']));
  15729. }
  15730. if (!empty($mirror['hg-url'])) {
  15731. $this->sourceMirrors['hg'][] = array('url' => $mirror['hg-url'], 'preferred' => !empty($mirror['preferred']));
  15732. }
  15733. if (!empty($mirror['dist-url'])) {
  15734. $this->distMirrors[] = array('url' => $mirror['dist-url'], 'preferred' => !empty($mirror['preferred']));
  15735. }
  15736. }
  15737. }
  15738. if (!empty($data['warning'])) {
  15739. $this->io->writeError('<warning>Warning from '.$this->url.': '.$data['warning'].'</warning>');
  15740. }
  15741. if (!empty($data['providers-lazy-url'])) {
  15742. $this->lazyProvidersUrl = $this->canonicalizeUrl($data['providers-lazy-url']);
  15743. $this->hasProviders = true;
  15744. }
  15745. if ($this->allowSslDowngrade) {
  15746. $this->url = str_replace('https://', 'http://', $this->url);
  15747. }
  15748. if (!empty($data['providers-url'])) {
  15749. $this->providersUrl = $this->canonicalizeUrl($data['providers-url']);
  15750. $this->hasProviders = true;
  15751. }
  15752. if (!empty($data['providers']) || !empty($data['providers-includes'])) {
  15753. $this->hasProviders = true;
  15754. }
  15755. return $this->rootData = $data;
  15756. }
  15757. protected function canonicalizeUrl($url)
  15758. {
  15759. if ('/' === $url[0]) {
  15760. return preg_replace('{(https?://[^/]+).*}i', '$1' . $url, $this->url);
  15761. }
  15762. return $url;
  15763. }
  15764. protected function loadDataFromServer()
  15765. {
  15766. $data = $this->loadRootServerFile();
  15767. return $this->loadIncludes($data);
  15768. }
  15769. protected function loadProviderListings($data)
  15770. {
  15771. if (isset($data['providers'])) {
  15772. if (!is_array($this->providerListing)) {
  15773. $this->providerListing = array();
  15774. }
  15775. $this->providerListing = array_merge($this->providerListing, $data['providers']);
  15776. }
  15777. if ($this->providersUrl && isset($data['provider-includes'])) {
  15778. $includes = $data['provider-includes'];
  15779. foreach ($includes as $include => $metadata) {
  15780. $url = $this->baseUrl . '/' . str_replace('%hash%', $metadata['sha256'], $include);
  15781. $cacheKey = str_replace(array('%hash%','$'), '', $include);
  15782. if ($this->cache->sha256($cacheKey) === $metadata['sha256']) {
  15783. $includedData = json_decode($this->cache->read($cacheKey), true);
  15784. } else {
  15785. $includedData = $this->fetchFile($url, $cacheKey, $metadata['sha256']);
  15786. }
  15787. $this->loadProviderListings($includedData);
  15788. }
  15789. } elseif (isset($data['providers-includes'])) {
  15790. $includes = $data['providers-includes'];
  15791. foreach ($includes as $include => $metadata) {
  15792. if ($this->cache->sha256($include) === $metadata['sha256']) {
  15793. $includedData = json_decode($this->cache->read($include), true);
  15794. } else {
  15795. $includedData = $this->fetchFile($include, null, $metadata['sha256']);
  15796. }
  15797. $this->loadProviderListings($includedData);
  15798. }
  15799. }
  15800. }
  15801. protected function loadIncludes($data)
  15802. {
  15803. $packages = array();
  15804. if (!isset($data['packages']) && !isset($data['includes'])) {
  15805. foreach ($data as $pkg) {
  15806. foreach ($pkg['versions'] as $metadata) {
  15807. $packages[] = $metadata;
  15808. }
  15809. }
  15810. return $packages;
  15811. }
  15812. if (isset($data['packages'])) {
  15813. foreach ($data['packages'] as $package => $versions) {
  15814. foreach ($versions as $version => $metadata) {
  15815. $packages[] = $metadata;
  15816. }
  15817. }
  15818. }
  15819. if (isset($data['includes'])) {
  15820. foreach ($data['includes'] as $include => $metadata) {
  15821. if ($this->cache->sha1($include) === $metadata['sha1']) {
  15822. $includedData = json_decode($this->cache->read($include), true);
  15823. } else {
  15824. $includedData = $this->fetchFile($include);
  15825. }
  15826. $packages = array_merge($packages, $this->loadIncludes($includedData));
  15827. }
  15828. }
  15829. return $packages;
  15830. }
  15831. protected function createPackage(array $data, $class)
  15832. {
  15833. try {
  15834. if (!isset($data['notification-url'])) {
  15835. $data['notification-url'] = $this->notifyUrl;
  15836. }
  15837. $package = $this->loader->load($data, 'Composer\Package\CompletePackage');
  15838. if (isset($this->sourceMirrors[$package->getSourceType()])) {
  15839. $package->setSourceMirrors($this->sourceMirrors[$package->getSourceType()]);
  15840. }
  15841. $package->setDistMirrors($this->distMirrors);
  15842. $this->configurePackageTransportOptions($package);
  15843. return $package;
  15844. } catch (\Exception $e) {
  15845. throw new \RuntimeException('Could not load package '.(isset($data['name']) ? $data['name'] : json_encode($data)).' in '.$this->url.': ['.get_class($e).'] '.$e->getMessage(), 0, $e);
  15846. }
  15847. }
  15848. protected function fetchFile($filename, $cacheKey = null, $sha256 = null)
  15849. {
  15850. if (null === $cacheKey) {
  15851. $cacheKey = $filename;
  15852. $filename = $this->baseUrl.'/'.$filename;
  15853. }
  15854. $retries = 3;
  15855. while ($retries--) {
  15856. try {
  15857. $preFileDownloadEvent = new PreFileDownloadEvent(PluginEvents::PRE_FILE_DOWNLOAD, $this->rfs, $filename);
  15858. if ($this->eventDispatcher) {
  15859. $this->eventDispatcher->dispatch($preFileDownloadEvent->getName(), $preFileDownloadEvent);
  15860. }
  15861. $hostname = parse_url($filename, PHP_URL_HOST) ?: $filename;
  15862. $json = $preFileDownloadEvent->getRemoteFilesystem()->getContents($hostname, $filename, false);
  15863. if ($sha256 && $sha256 !== hash('sha256', $json)) {
  15864. if ($retries) {
  15865. usleep(100000);
  15866. continue;
  15867. }
  15868. throw new RepositorySecurityException('The contents of '.$filename.' do not match its signature. This should indicate a man-in-the-middle attack. Try running composer again and report this if you think it is a mistake.');
  15869. }
  15870. $data = JsonFile::parseJson($json, $filename);
  15871. if ($cacheKey) {
  15872. $this->cache->write($cacheKey, $json);
  15873. }
  15874. break;
  15875. } catch (\Exception $e) {
  15876. if ($retries) {
  15877. usleep(100000);
  15878. continue;
  15879. }
  15880. if ($e instanceof RepositorySecurityException) {
  15881. throw $e;
  15882. }
  15883. if ($cacheKey && ($contents = $this->cache->read($cacheKey))) {
  15884. if (!$this->degradedMode) {
  15885. $this->io->writeError('<warning>'.$e->getMessage().'</warning>');
  15886. $this->io->writeError('<warning>'.$this->url.' could not be fully loaded, package information was loaded from the local cache and may be out of date</warning>');
  15887. }
  15888. $this->degradedMode = true;
  15889. $data = JsonFile::parseJson($contents, $this->cache->getRoot().$cacheKey);
  15890. break;
  15891. }
  15892. throw $e;
  15893. }
  15894. }
  15895. return $data;
  15896. }
  15897. }
  15898. <?php
  15899. namespace Composer\Repository;
  15900. use Composer\Package\PackageInterface;
  15901. class CompositeRepository implements RepositoryInterface
  15902. {
  15903. private $repositories;
  15904. public function __construct(array $repositories)
  15905. {
  15906. $this->repositories = array();
  15907. foreach ($repositories as $repo) {
  15908. $this->addRepository($repo);
  15909. }
  15910. }
  15911. public function getRepositories()
  15912. {
  15913. return $this->repositories;
  15914. }
  15915. public function hasPackage(PackageInterface $package)
  15916. {
  15917. foreach ($this->repositories as $repository) {
  15918. if ($repository->hasPackage($package)) {
  15919. return true;
  15920. }
  15921. }
  15922. return false;
  15923. }
  15924. public function findPackage($name, $version)
  15925. {
  15926. foreach ($this->repositories as $repository) {
  15927. $package = $repository->findPackage($name, $version);
  15928. if (null !== $package) {
  15929. return $package;
  15930. }
  15931. }
  15932. return null;
  15933. }
  15934. public function findPackages($name, $version = null)
  15935. {
  15936. $packages = array();
  15937. foreach ($this->repositories as $repository) {
  15938. $packages[] = $repository->findPackages($name, $version);
  15939. }
  15940. return $packages ? call_user_func_array('array_merge', $packages) : array();
  15941. }
  15942. public function search($query, $mode = 0)
  15943. {
  15944. $matches = array();
  15945. foreach ($this->repositories as $repository) {
  15946. $matches[] = $repository->search($query, $mode);
  15947. }
  15948. return $matches ? call_user_func_array('array_merge', $matches) : array();
  15949. }
  15950. public function filterPackages($callback, $class = 'Composer\Package\Package')
  15951. {
  15952. foreach ($this->repositories as $repository) {
  15953. if (false === $repository->filterPackages($callback, $class)) {
  15954. return false;
  15955. }
  15956. }
  15957. return true;
  15958. }
  15959. public function getPackages()
  15960. {
  15961. $packages = array();
  15962. foreach ($this->repositories as $repository) {
  15963. $packages[] = $repository->getPackages();
  15964. }
  15965. return $packages ? call_user_func_array('array_merge', $packages) : array();
  15966. }
  15967. public function removePackage(PackageInterface $package)
  15968. {
  15969. foreach ($this->repositories as $repository) {
  15970. $repository->removePackage($package);
  15971. }
  15972. }
  15973. public function count()
  15974. {
  15975. $total = 0;
  15976. foreach ($this->repositories as $repository) {
  15977. $total += $repository->count();
  15978. }
  15979. return $total;
  15980. }
  15981. public function addRepository(RepositoryInterface $repository)
  15982. {
  15983. if ($repository instanceof self) {
  15984. foreach ($repository->getRepositories() as $repo) {
  15985. $this->addRepository($repo);
  15986. }
  15987. } else {
  15988. $this->repositories[] = $repository;
  15989. }
  15990. }
  15991. }
  15992. <?php
  15993. namespace Composer\Repository;
  15994. use Composer\Json\JsonFile;
  15995. use Composer\Package\Loader\ArrayLoader;
  15996. use Composer\Package\Dumper\ArrayDumper;
  15997. class FilesystemRepository extends WritableArrayRepository
  15998. {
  15999. private $file;
  16000. public function __construct(JsonFile $repositoryFile)
  16001. {
  16002. $this->file = $repositoryFile;
  16003. }
  16004. protected function initialize()
  16005. {
  16006. parent::initialize();
  16007. if (!$this->file->exists()) {
  16008. return;
  16009. }
  16010. try {
  16011. $packages = $this->file->read();
  16012. if (!is_array($packages)) {
  16013. throw new \UnexpectedValueException('Could not parse package list from the repository');
  16014. }
  16015. } catch (\Exception $e) {
  16016. throw new InvalidRepositoryException('Invalid repository data in '.$this->file->getPath().', packages could not be loaded: ['.get_class($e).'] '.$e->getMessage());
  16017. }
  16018. $loader = new ArrayLoader(null, true);
  16019. foreach ($packages as $packageData) {
  16020. $package = $loader->load($packageData);
  16021. $this->addPackage($package);
  16022. }
  16023. }
  16024. public function reload()
  16025. {
  16026. $this->packages = null;
  16027. $this->initialize();
  16028. }
  16029. public function write()
  16030. {
  16031. $data = array();
  16032. $dumper = new ArrayDumper();
  16033. foreach ($this->getCanonicalPackages() as $package) {
  16034. $data[] = $dumper->dump($package);
  16035. }
  16036. $this->file->write($data);
  16037. }
  16038. }
  16039. <?php
  16040. namespace Composer\Repository;
  16041. class InstalledArrayRepository extends WritableArrayRepository implements InstalledRepositoryInterface
  16042. {
  16043. }
  16044. <?php
  16045. namespace Composer\Repository;
  16046. class InstalledFilesystemRepository extends FilesystemRepository implements InstalledRepositoryInterface
  16047. {
  16048. }
  16049. <?php
  16050. namespace Composer\Repository;
  16051. interface InstalledRepositoryInterface extends WritableRepositoryInterface
  16052. {
  16053. }
  16054. <?php
  16055. namespace Composer\Repository;
  16056. class InvalidRepositoryException extends \Exception
  16057. {
  16058. }
  16059. <?php
  16060. namespace Composer\Repository;
  16061. use Composer\Package\Loader\ArrayLoader;
  16062. use Composer\Package\Loader\ValidatingArrayLoader;
  16063. class PackageRepository extends ArrayRepository
  16064. {
  16065. private $config;
  16066. public function __construct(array $config)
  16067. {
  16068. $this->config = $config['package'];
  16069. if (!is_numeric(key($this->config))) {
  16070. $this->config = array($this->config);
  16071. }
  16072. }
  16073. protected function initialize()
  16074. {
  16075. parent::initialize();
  16076. $loader = new ValidatingArrayLoader(new ArrayLoader, false);
  16077. foreach ($this->config as $package) {
  16078. try {
  16079. $package = $loader->load($package);
  16080. } catch (\Exception $e) {
  16081. throw new InvalidRepositoryException('A repository of type "package" contains an invalid package definition: '.$e->getMessage()."\n\nInvalid package definition:\n".json_encode($package));
  16082. }
  16083. $this->addPackage($package);
  16084. }
  16085. }
  16086. }
  16087. <?php
  16088. namespace Composer\Repository\Pear;
  16089. use Composer\Util\RemoteFilesystem;
  16090. abstract class BaseChannelReader
  16091. {
  16092. const CHANNEL_NS = 'http://pear.php.net/channel-1.0';
  16093. const ALL_CATEGORIES_NS = 'http://pear.php.net/dtd/rest.allcategories';
  16094. const CATEGORY_PACKAGES_INFO_NS = 'http://pear.php.net/dtd/rest.categorypackageinfo';
  16095. const ALL_PACKAGES_NS = 'http://pear.php.net/dtd/rest.allpackages';
  16096. const ALL_RELEASES_NS = 'http://pear.php.net/dtd/rest.allreleases';
  16097. const PACKAGE_INFO_NS = 'http://pear.php.net/dtd/rest.package';
  16098. private $rfs;
  16099. protected function __construct(RemoteFilesystem $rfs)
  16100. {
  16101. $this->rfs = $rfs;
  16102. }
  16103. protected function requestContent($origin, $path)
  16104. {
  16105. $url = rtrim($origin, '/') . '/' . ltrim($path, '/');
  16106. $content = $this->rfs->getContents($origin, $url, false);
  16107. if (!$content) {
  16108. throw new \UnexpectedValueException('The PEAR channel at ' . $url . ' did not respond.');
  16109. }
  16110. return $content;
  16111. }
  16112. protected function requestXml($origin, $path)
  16113. {
  16114. $xml = simplexml_load_string($this->requestContent($origin, $path), "SimpleXMLElement", LIBXML_NOERROR);
  16115. if (false == $xml) {
  16116. $url = rtrim($origin, '/') . '/' . ltrim($path, '/');
  16117. throw new \UnexpectedValueException(sprintf('The PEAR channel at ' . $origin . ' is broken. (Invalid XML at file `%s`)', $path));
  16118. }
  16119. return $xml;
  16120. }
  16121. }
  16122. <?php
  16123. namespace Composer\Repository\Pear;
  16124. class ChannelInfo
  16125. {
  16126. private $name;
  16127. private $alias;
  16128. private $packages;
  16129. public function __construct($name, $alias, array $packages)
  16130. {
  16131. $this->name = $name;
  16132. $this->alias = $alias;
  16133. $this->packages = $packages;
  16134. }
  16135. public function getName()
  16136. {
  16137. return $this->name;
  16138. }
  16139. public function getAlias()
  16140. {
  16141. return $this->alias;
  16142. }
  16143. public function getPackages()
  16144. {
  16145. return $this->packages;
  16146. }
  16147. }
  16148. <?php
  16149. namespace Composer\Repository\Pear;
  16150. use Composer\Util\RemoteFilesystem;
  16151. class ChannelReader extends BaseChannelReader
  16152. {
  16153. private $readerMap;
  16154. public function __construct(RemoteFilesystem $rfs)
  16155. {
  16156. parent::__construct($rfs);
  16157. $rest10reader = new ChannelRest10Reader($rfs);
  16158. $rest11reader = new ChannelRest11Reader($rfs);
  16159. $this->readerMap = array(
  16160. 'REST1.3' => $rest11reader,
  16161. 'REST1.2' => $rest11reader,
  16162. 'REST1.1' => $rest11reader,
  16163. 'REST1.0' => $rest10reader,
  16164. );
  16165. }
  16166. public function read($url)
  16167. {
  16168. $xml = $this->requestXml($url, "/channel.xml");
  16169. $channelName = (string) $xml->name;
  16170. $channelSummary = (string) $xml->summary;
  16171. $channelAlias = (string) $xml->suggestedalias;
  16172. $supportedVersions = array_keys($this->readerMap);
  16173. $selectedRestVersion = $this->selectRestVersion($xml, $supportedVersions);
  16174. if (!$selectedRestVersion) {
  16175. throw new \UnexpectedValueException(sprintf('PEAR repository %s does not supports any of %s protocols.', $url, implode(', ', $supportedVersions)));
  16176. }
  16177. $reader = $this->readerMap[$selectedRestVersion['version']];
  16178. $packageDefinitions = $reader->read($selectedRestVersion['baseUrl']);
  16179. return new ChannelInfo($channelName, $channelAlias, $packageDefinitions);
  16180. }
  16181. private function selectRestVersion($channelXml, $supportedVersions)
  16182. {
  16183. $channelXml->registerXPathNamespace('ns', self::CHANNEL_NS);
  16184. foreach ($supportedVersions as $version) {
  16185. $xpathTest = "ns:servers/ns:primary/ns:rest/ns:baseurl[@type='{$version}']";
  16186. $testResult = $channelXml->xpath($xpathTest);
  16187. if (count($testResult) > 0) {
  16188. return array('version' => $version, 'baseUrl' => (string) $testResult[0]);
  16189. }
  16190. }
  16191. return null;
  16192. }
  16193. }
  16194. <?php
  16195. namespace Composer\Repository\Pear;
  16196. use Composer\Downloader\TransportException;
  16197. class ChannelRest10Reader extends BaseChannelReader
  16198. {
  16199. private $dependencyReader;
  16200. public function __construct($rfs)
  16201. {
  16202. parent::__construct($rfs);
  16203. $this->dependencyReader = new PackageDependencyParser();
  16204. }
  16205. public function read($baseUrl)
  16206. {
  16207. return $this->readPackages($baseUrl);
  16208. }
  16209. private function readPackages($baseUrl)
  16210. {
  16211. $result = array();
  16212. $xmlPath = '/p/packages.xml';
  16213. $xml = $this->requestXml($baseUrl, $xmlPath);
  16214. $xml->registerXPathNamespace('ns', self::ALL_PACKAGES_NS);
  16215. foreach ($xml->xpath('ns:p') as $node) {
  16216. $packageName = (string) $node;
  16217. $packageInfo = $this->readPackage($baseUrl, $packageName);
  16218. $result[] = $packageInfo;
  16219. }
  16220. return $result;
  16221. }
  16222. private function readPackage($baseUrl, $packageName)
  16223. {
  16224. $xmlPath = '/p/' . strtolower($packageName) . '/info.xml';
  16225. $xml = $this->requestXml($baseUrl, $xmlPath);
  16226. $xml->registerXPathNamespace('ns', self::PACKAGE_INFO_NS);
  16227. $channelName = (string) $xml->c;
  16228. $packageName = (string) $xml->n;
  16229. $license = (string) $xml->l;
  16230. $shortDescription = (string) $xml->s;
  16231. $description = (string) $xml->d;
  16232. return new PackageInfo(
  16233. $channelName,
  16234. $packageName,
  16235. $license,
  16236. $shortDescription,
  16237. $description,
  16238. $this->readPackageReleases($baseUrl, $packageName)
  16239. );
  16240. }
  16241. private function readPackageReleases($baseUrl, $packageName)
  16242. {
  16243. $result = array();
  16244. try {
  16245. $xmlPath = '/r/' . strtolower($packageName) . '/allreleases.xml';
  16246. $xml = $this->requestXml($baseUrl, $xmlPath);
  16247. $xml->registerXPathNamespace('ns', self::ALL_RELEASES_NS);
  16248. foreach ($xml->xpath('ns:r') as $node) {
  16249. $releaseVersion = (string) $node->v;
  16250. $releaseStability = (string) $node->s;
  16251. try {
  16252. $result[$releaseVersion] = new ReleaseInfo(
  16253. $releaseStability,
  16254. $this->readPackageReleaseDependencies($baseUrl, $packageName, $releaseVersion)
  16255. );
  16256. } catch (TransportException $exception) {
  16257. if ($exception->getCode() != 404) {
  16258. throw $exception;
  16259. }
  16260. }
  16261. }
  16262. } catch (TransportException $exception) {
  16263. if ($exception->getCode() != 404) {
  16264. throw $exception;
  16265. }
  16266. }
  16267. return $result;
  16268. }
  16269. private function readPackageReleaseDependencies($baseUrl, $packageName, $version)
  16270. {
  16271. $dependencyReader = new PackageDependencyParser();
  16272. $depthPath = '/r/' . strtolower($packageName) . '/deps.' . $version . '.txt';
  16273. $content = $this->requestContent($baseUrl, $depthPath);
  16274. $dependencyArray = unserialize($content);
  16275. $result = $dependencyReader->buildDependencyInfo($dependencyArray);
  16276. return $result;
  16277. }
  16278. }
  16279. <?php
  16280. namespace Composer\Repository\Pear;
  16281. class ChannelRest11Reader extends BaseChannelReader
  16282. {
  16283. private $dependencyReader;
  16284. public function __construct($rfs)
  16285. {
  16286. parent::__construct($rfs);
  16287. $this->dependencyReader = new PackageDependencyParser();
  16288. }
  16289. public function read($baseUrl)
  16290. {
  16291. return $this->readChannelPackages($baseUrl);
  16292. }
  16293. private function readChannelPackages($baseUrl)
  16294. {
  16295. $result = array();
  16296. $xml = $this->requestXml($baseUrl, "/c/categories.xml");
  16297. $xml->registerXPathNamespace('ns', self::ALL_CATEGORIES_NS);
  16298. foreach ($xml->xpath('ns:c') as $node) {
  16299. $categoryName = (string) $node;
  16300. $categoryPackages = $this->readCategoryPackages($baseUrl, $categoryName);
  16301. $result = array_merge($result, $categoryPackages);
  16302. }
  16303. return $result;
  16304. }
  16305. private function readCategoryPackages($baseUrl, $categoryName)
  16306. {
  16307. $result = array();
  16308. $categoryPath = '/c/'.urlencode($categoryName).'/packagesinfo.xml';
  16309. $xml = $this->requestXml($baseUrl, $categoryPath);
  16310. $xml->registerXPathNamespace('ns', self::CATEGORY_PACKAGES_INFO_NS);
  16311. foreach ($xml->xpath('ns:pi') as $node) {
  16312. $packageInfo = $this->parsePackage($node);
  16313. $result[] = $packageInfo;
  16314. }
  16315. return $result;
  16316. }
  16317. private function parsePackage($packageInfo)
  16318. {
  16319. $packageInfo->registerXPathNamespace('ns', self::CATEGORY_PACKAGES_INFO_NS);
  16320. $channelName = (string) $packageInfo->p->c;
  16321. $packageName = (string) $packageInfo->p->n;
  16322. $license = (string) $packageInfo->p->l;
  16323. $shortDescription = (string) $packageInfo->p->s;
  16324. $description = (string) $packageInfo->p->d;
  16325. $dependencies = array();
  16326. foreach ($packageInfo->xpath('ns:deps') as $node) {
  16327. $dependencyVersion = (string) $node->v;
  16328. $dependencyArray = unserialize((string) $node->d);
  16329. $dependencyInfo = $this->dependencyReader->buildDependencyInfo($dependencyArray);
  16330. $dependencies[$dependencyVersion] = $dependencyInfo;
  16331. }
  16332. $releases = array();
  16333. $releasesInfo = $packageInfo->xpath('ns:a/ns:r');
  16334. if ($releasesInfo) {
  16335. foreach ($releasesInfo as $node) {
  16336. $releaseVersion = (string) $node->v;
  16337. $releaseStability = (string) $node->s;
  16338. $releases[$releaseVersion] = new ReleaseInfo(
  16339. $releaseStability,
  16340. isset($dependencies[$releaseVersion]) ? $dependencies[$releaseVersion] : new DependencyInfo(array(), array())
  16341. );
  16342. }
  16343. }
  16344. return new PackageInfo(
  16345. $channelName,
  16346. $packageName,
  16347. $license,
  16348. $shortDescription,
  16349. $description,
  16350. $releases
  16351. );
  16352. }
  16353. }
  16354. <?php
  16355. namespace Composer\Repository\Pear;
  16356. class DependencyConstraint
  16357. {
  16358. private $type;
  16359. private $constraint;
  16360. private $channelName;
  16361. private $packageName;
  16362. public function __construct($type, $constraint, $channelName, $packageName)
  16363. {
  16364. $this->type = $type;
  16365. $this->constraint = $constraint;
  16366. $this->channelName = $channelName;
  16367. $this->packageName = $packageName;
  16368. }
  16369. public function getChannelName()
  16370. {
  16371. return $this->channelName;
  16372. }
  16373. public function getConstraint()
  16374. {
  16375. return $this->constraint;
  16376. }
  16377. public function getPackageName()
  16378. {
  16379. return $this->packageName;
  16380. }
  16381. public function getType()
  16382. {
  16383. return $this->type;
  16384. }
  16385. }
  16386. <?php
  16387. namespace Composer\Repository\Pear;
  16388. class DependencyInfo
  16389. {
  16390. private $requires;
  16391. private $optionals;
  16392. public function __construct($requires, $optionals)
  16393. {
  16394. $this->requires = $requires;
  16395. $this->optionals = $optionals;
  16396. }
  16397. public function getRequires()
  16398. {
  16399. return $this->requires;
  16400. }
  16401. public function getOptionals()
  16402. {
  16403. return $this->optionals;
  16404. }
  16405. }
  16406. <?php
  16407. namespace Composer\Repository\Pear;
  16408. class PackageDependencyParser
  16409. {
  16410. public function buildDependencyInfo($depArray)
  16411. {
  16412. if (!is_array($depArray)) {
  16413. return new DependencyInfo(array(), array());
  16414. }
  16415. if (!$this->isHash($depArray)) {
  16416. return new DependencyInfo($this->buildDependency10Info($depArray), array());
  16417. }
  16418. return $this->buildDependency20Info($depArray);
  16419. }
  16420. private function buildDependency10Info($depArray)
  16421. {
  16422. static $dep10toOperatorMap = array('has' => '==', 'eq' => '==', 'ge' => '>=', 'gt' => '>', 'le' => '<=', 'lt' => '<', 'not' => '!=');
  16423. $result = array();
  16424. foreach ($depArray as $depItem) {
  16425. if (empty($depItem['rel']) || !array_key_exists($depItem['rel'], $dep10toOperatorMap)) {
  16426. continue;
  16427. }
  16428. $depType = !empty($depItem['optional']) && 'yes' == $depItem['optional']
  16429. ? 'optional'
  16430. : 'required';
  16431. $depType = 'not' == $depItem['rel']
  16432. ? 'conflicts'
  16433. : $depType;
  16434. $depVersion = !empty($depItem['version']) ? $this->parseVersion($depItem['version']) : '*';
  16435. $depVersionConstraint = ('has' == $depItem['rel'] || 'not' == $depItem['rel']) && '*' == $depVersion
  16436. ? '*'
  16437. : $dep10toOperatorMap[$depItem['rel']] . $depVersion;
  16438. switch ($depItem['type']) {
  16439. case 'php':
  16440. $depChannelName = 'php';
  16441. $depPackageName = '';
  16442. break;
  16443. case 'pkg':
  16444. $depChannelName = !empty($depItem['channel']) ? $depItem['channel'] : 'pear.php.net';
  16445. $depPackageName = $depItem['name'];
  16446. break;
  16447. case 'ext':
  16448. $depChannelName = 'ext';
  16449. $depPackageName = $depItem['name'];
  16450. break;
  16451. case 'os':
  16452. case 'sapi':
  16453. $depChannelName = '';
  16454. $depPackageName = '';
  16455. break;
  16456. default:
  16457. $depChannelName = '';
  16458. $depPackageName = '';
  16459. break;
  16460. }
  16461. if ('' != $depChannelName) {
  16462. $result[] = new DependencyConstraint(
  16463. $depType,
  16464. $depVersionConstraint,
  16465. $depChannelName,
  16466. $depPackageName
  16467. );
  16468. }
  16469. }
  16470. return $result;
  16471. }
  16472. private function buildDependency20Info($depArray)
  16473. {
  16474. $result = array();
  16475. $optionals = array();
  16476. $defaultOptionals = array();
  16477. foreach ($depArray as $depType => $depTypeGroup) {
  16478. if (!is_array($depTypeGroup)) {
  16479. continue;
  16480. }
  16481. if ('required' == $depType || 'optional' == $depType) {
  16482. foreach ($depTypeGroup as $depItemType => $depItem) {
  16483. switch ($depItemType) {
  16484. case 'php':
  16485. $result[] = new DependencyConstraint(
  16486. $depType,
  16487. $this->parse20VersionConstraint($depItem),
  16488. 'php',
  16489. ''
  16490. );
  16491. break;
  16492. case 'package':
  16493. $deps = $this->buildDepPackageConstraints($depItem, $depType);
  16494. $result = array_merge($result, $deps);
  16495. break;
  16496. case 'extension':
  16497. $deps = $this->buildDepExtensionConstraints($depItem, $depType);
  16498. $result = array_merge($result, $deps);
  16499. break;
  16500. case 'subpackage':
  16501. $deps = $this->buildDepPackageConstraints($depItem, 'replaces');
  16502. $defaultOptionals += $deps;
  16503. break;
  16504. case 'os':
  16505. case 'pearinstaller':
  16506. break;
  16507. default:
  16508. break;
  16509. }
  16510. }
  16511. } elseif ('group' == $depType) {
  16512. if ($this->isHash($depTypeGroup)) {
  16513. $depTypeGroup = array($depTypeGroup);
  16514. }
  16515. foreach ($depTypeGroup as $depItem) {
  16516. $groupName = $depItem['attribs']['name'];
  16517. if (!isset($optionals[$groupName])) {
  16518. $optionals[$groupName] = array();
  16519. }
  16520. if (isset($depItem['subpackage'])) {
  16521. $optionals[$groupName] += $this->buildDepPackageConstraints($depItem['subpackage'], 'replaces');
  16522. } else {
  16523. $result += $this->buildDepPackageConstraints($depItem['package'], 'optional');
  16524. }
  16525. }
  16526. }
  16527. }
  16528. if (count($defaultOptionals) > 0) {
  16529. $optionals['*'] = $defaultOptionals;
  16530. }
  16531. return new DependencyInfo($result, $optionals);
  16532. }
  16533. private function buildDepExtensionConstraints($depItem, $depType)
  16534. {
  16535. if ($this->isHash($depItem)) {
  16536. $depItem = array($depItem);
  16537. }
  16538. $result = array();
  16539. foreach ($depItem as $subDepItem) {
  16540. $depChannelName = 'ext';
  16541. $depPackageName = $subDepItem['name'];
  16542. $depVersionConstraint = $this->parse20VersionConstraint($subDepItem);
  16543. $result[] = new DependencyConstraint(
  16544. $depType,
  16545. $depVersionConstraint,
  16546. $depChannelName,
  16547. $depPackageName
  16548. );
  16549. }
  16550. return $result;
  16551. }
  16552. private function buildDepPackageConstraints($depItem, $depType)
  16553. {
  16554. if ($this->isHash($depItem)) {
  16555. $depItem = array($depItem);
  16556. }
  16557. $result = array();
  16558. foreach ($depItem as $subDepItem) {
  16559. $depChannelName = $subDepItem['channel'];
  16560. $depPackageName = $subDepItem['name'];
  16561. $depVersionConstraint = $this->parse20VersionConstraint($subDepItem);
  16562. if (isset($subDepItem['conflicts'])) {
  16563. $depType = 'conflicts';
  16564. }
  16565. $result[] = new DependencyConstraint(
  16566. $depType,
  16567. $depVersionConstraint,
  16568. $depChannelName,
  16569. $depPackageName
  16570. );
  16571. }
  16572. return $result;
  16573. }
  16574. private function parse20VersionConstraint(array $data)
  16575. {
  16576. static $dep20toOperatorMap = array('has' => '==', 'min' => '>=', 'max' => '<=', 'exclude' => '!=');
  16577. $versions = array();
  16578. $values = array_intersect_key($data, $dep20toOperatorMap);
  16579. if (0 == count($values)) {
  16580. return '*';
  16581. }
  16582. if (isset($values['min']) && isset($values['exclude']) && $data['min'] == $data['exclude']) {
  16583. $versions[] = '>' . $this->parseVersion($values['min']);
  16584. } elseif (isset($values['max']) && isset($values['exclude']) && $data['max'] == $data['exclude']) {
  16585. $versions[] = '<' . $this->parseVersion($values['max']);
  16586. } else {
  16587. foreach ($values as $op => $version) {
  16588. if ('exclude' == $op && is_array($version)) {
  16589. foreach ($version as $versionPart) {
  16590. $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($versionPart);
  16591. }
  16592. } else {
  16593. $versions[] = $dep20toOperatorMap[$op] . $this->parseVersion($version);
  16594. }
  16595. }
  16596. }
  16597. return implode(',', $versions);
  16598. }
  16599. private function parseVersion($version)
  16600. {
  16601. if (preg_match('{^v?(\d{1,3})(\.\d+)?(\.\d+)?(\.\d+)?}i', $version, $matches)) {
  16602. $version = $matches[1]
  16603. .(!empty($matches[2]) ? $matches[2] : '.0')
  16604. .(!empty($matches[3]) ? $matches[3] : '.0')
  16605. .(!empty($matches[4]) ? $matches[4] : '.0');
  16606. return $version;
  16607. }
  16608. return null;
  16609. }
  16610. private function isHash(array $array)
  16611. {
  16612. return !array_key_exists(1, $array) && !array_key_exists(0, $array);
  16613. }
  16614. }
  16615. <?php
  16616. namespace Composer\Repository\Pear;
  16617. class PackageInfo
  16618. {
  16619. private $channelName;
  16620. private $packageName;
  16621. private $license;
  16622. private $shortDescription;
  16623. private $description;
  16624. private $releases;
  16625. public function __construct($channelName, $packageName, $license, $shortDescription, $description, $releases)
  16626. {
  16627. $this->channelName = $channelName;
  16628. $this->packageName = $packageName;
  16629. $this->license = $license;
  16630. $this->shortDescription = $shortDescription;
  16631. $this->description = $description;
  16632. $this->releases = $releases;
  16633. }
  16634. public function getChannelName()
  16635. {
  16636. return $this->channelName;
  16637. }
  16638. public function getPackageName()
  16639. {
  16640. return $this->packageName;
  16641. }
  16642. public function getDescription()
  16643. {
  16644. return $this->description;
  16645. }
  16646. public function getShortDescription()
  16647. {
  16648. return $this->shortDescription;
  16649. }
  16650. public function getLicense()
  16651. {
  16652. return $this->license;
  16653. }
  16654. public function getReleases()
  16655. {
  16656. return $this->releases;
  16657. }
  16658. }
  16659. <?php
  16660. namespace Composer\Repository\Pear;
  16661. class ReleaseInfo
  16662. {
  16663. private $stability;
  16664. private $dependencyInfo;
  16665. public function __construct($stability, $dependencyInfo)
  16666. {
  16667. $this->stability = $stability;
  16668. $this->dependencyInfo = $dependencyInfo;
  16669. }
  16670. public function getDependencyInfo()
  16671. {
  16672. return $this->dependencyInfo;
  16673. }
  16674. public function getStability()
  16675. {
  16676. return $this->stability;
  16677. }
  16678. }
  16679. <?php
  16680. namespace Composer\Repository;
  16681. use Composer\IO\IOInterface;
  16682. use Composer\Package\Version\VersionParser;
  16683. use Composer\Repository\Pear\ChannelReader;
  16684. use Composer\Package\CompletePackage;
  16685. use Composer\Repository\Pear\ChannelInfo;
  16686. use Composer\EventDispatcher\EventDispatcher;
  16687. use Composer\Package\Link;
  16688. use Composer\Package\LinkConstraint\VersionConstraint;
  16689. use Composer\Util\RemoteFilesystem;
  16690. use Composer\Config;
  16691. class PearRepository extends ArrayRepository
  16692. {
  16693. private $url;
  16694. private $io;
  16695. private $rfs;
  16696. private $versionParser;
  16697. private $vendorAlias;
  16698. public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $dispatcher = null, RemoteFilesystem $rfs = null)
  16699. {
  16700. if (!preg_match('{^https?://}', $repoConfig['url'])) {
  16701. $repoConfig['url'] = 'http://'.$repoConfig['url'];
  16702. }
  16703. $urlBits = parse_url($repoConfig['url']);
  16704. if (empty($urlBits['scheme']) || empty($urlBits['host'])) {
  16705. throw new \UnexpectedValueException('Invalid url given for PEAR repository: '.$repoConfig['url']);
  16706. }
  16707. $this->url = rtrim($repoConfig['url'], '/');
  16708. $this->io = $io;
  16709. $this->rfs = $rfs ?: new RemoteFilesystem($this->io, $config);
  16710. $this->vendorAlias = isset($repoConfig['vendor-alias']) ? $repoConfig['vendor-alias'] : null;
  16711. $this->versionParser = new VersionParser();
  16712. }
  16713. protected function initialize()
  16714. {
  16715. parent::initialize();
  16716. $this->io->writeError('Initializing PEAR repository '.$this->url);
  16717. $reader = new ChannelReader($this->rfs);
  16718. try {
  16719. $channelInfo = $reader->read($this->url);
  16720. } catch (\Exception $e) {
  16721. $this->io->writeError('<warning>PEAR repository from '.$this->url.' could not be loaded. '.$e->getMessage().'</warning>');
  16722. return;
  16723. }
  16724. $packages = $this->buildComposerPackages($channelInfo, $this->versionParser);
  16725. foreach ($packages as $package) {
  16726. $this->addPackage($package);
  16727. }
  16728. }
  16729. private function buildComposerPackages(ChannelInfo $channelInfo, VersionParser $versionParser)
  16730. {
  16731. $result = array();
  16732. foreach ($channelInfo->getPackages() as $packageDefinition) {
  16733. foreach ($packageDefinition->getReleases() as $version => $releaseInfo) {
  16734. try {
  16735. $normalizedVersion = $versionParser->normalize($version);
  16736. } catch (\UnexpectedValueException $e) {
  16737. if ($this->io->isVerbose()) {
  16738. $this->io->writeError('Could not load '.$packageDefinition->getPackageName().' '.$version.': '.$e->getMessage());
  16739. }
  16740. continue;
  16741. }
  16742. $composerPackageName = $this->buildComposerPackageName($packageDefinition->getChannelName(), $packageDefinition->getPackageName());
  16743. $urlBits = parse_url($this->url);
  16744. $scheme = (isset($urlBits['scheme']) && 'https' === $urlBits['scheme'] && extension_loaded('openssl')) ? 'https' : 'http';
  16745. $distUrl = "{$scheme}://{$packageDefinition->getChannelName()}/get/{$packageDefinition->getPackageName()}-{$version}.tgz";
  16746. $requires = array();
  16747. $suggests = array();
  16748. $conflicts = array();
  16749. $replaces = array();
  16750. if ($channelInfo->getName() == $packageDefinition->getChannelName()) {
  16751. $composerPackageAlias = $this->buildComposerPackageName($channelInfo->getAlias(), $packageDefinition->getPackageName());
  16752. $aliasConstraint = new VersionConstraint('==', $normalizedVersion);
  16753. $replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
  16754. }
  16755. if (!empty($this->vendorAlias)
  16756. && ($this->vendorAlias != 'pear-'.$channelInfo->getAlias() || $channelInfo->getName() != $packageDefinition->getChannelName())
  16757. ) {
  16758. $composerPackageAlias = "{$this->vendorAlias}/{$packageDefinition->getPackageName()}";
  16759. $aliasConstraint = new VersionConstraint('==', $normalizedVersion);
  16760. $replaces[] = new Link($composerPackageName, $composerPackageAlias, $aliasConstraint, 'replaces', (string) $aliasConstraint);
  16761. }
  16762. foreach ($releaseInfo->getDependencyInfo()->getRequires() as $dependencyConstraint) {
  16763. $dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
  16764. $constraint = $versionParser->parseConstraints($dependencyConstraint->getConstraint());
  16765. $link = new Link($composerPackageName, $dependencyPackageName, $constraint, $dependencyConstraint->getType(), $dependencyConstraint->getConstraint());
  16766. switch ($dependencyConstraint->getType()) {
  16767. case 'required':
  16768. $requires[] = $link;
  16769. break;
  16770. case 'conflicts':
  16771. $conflicts[] = $link;
  16772. break;
  16773. case 'replaces':
  16774. $replaces[] = $link;
  16775. break;
  16776. }
  16777. }
  16778. foreach ($releaseInfo->getDependencyInfo()->getOptionals() as $group => $dependencyConstraints) {
  16779. foreach ($dependencyConstraints as $dependencyConstraint) {
  16780. $dependencyPackageName = $this->buildComposerPackageName($dependencyConstraint->getChannelName(), $dependencyConstraint->getPackageName());
  16781. $suggests[$group.'-'.$dependencyPackageName] = $dependencyConstraint->getConstraint();
  16782. }
  16783. }
  16784. $package = new CompletePackage($composerPackageName, $normalizedVersion, $version);
  16785. $package->setType('pear-library');
  16786. $package->setDescription($packageDefinition->getDescription());
  16787. $package->setLicense(array($packageDefinition->getLicense()));
  16788. $package->setDistType('file');
  16789. $package->setDistUrl($distUrl);
  16790. $package->setAutoload(array('classmap' => array('')));
  16791. $package->setIncludePaths(array('/'));
  16792. $package->setRequires($requires);
  16793. $package->setConflicts($conflicts);
  16794. $package->setSuggests($suggests);
  16795. $package->setReplaces($replaces);
  16796. $result[] = $package;
  16797. }
  16798. }
  16799. return $result;
  16800. }
  16801. private function buildComposerPackageName($channelName, $packageName)
  16802. {
  16803. if ('php' === $channelName) {
  16804. return "php";
  16805. }
  16806. if ('ext' === $channelName) {
  16807. return "ext-{$packageName}";
  16808. }
  16809. return "pear-{$channelName}/{$packageName}";
  16810. }
  16811. }
  16812. <?php
  16813. namespace Composer\Repository;
  16814. use Composer\Package\CompletePackage;
  16815. use Composer\Package\Version\VersionParser;
  16816. use Composer\Plugin\PluginInterface;
  16817. class PlatformRepository extends ArrayRepository
  16818. {
  16819. const PLATFORM_PACKAGE_REGEX = '{^(?:php(?:-64bit)?|hhvm|(?:ext|lib)-[^/]+)$}i';
  16820. protected function initialize()
  16821. {
  16822. parent::initialize();
  16823. $versionParser = new VersionParser();
  16824. $prettyVersion = PluginInterface::PLUGIN_API_VERSION;
  16825. $version = $versionParser->normalize($prettyVersion);
  16826. $composerPluginApi = new CompletePackage('composer-plugin-api', $version, $prettyVersion);
  16827. $composerPluginApi->setDescription('The Composer Plugin API');
  16828. parent::addPackage($composerPluginApi);
  16829. try {
  16830. $prettyVersion = PHP_VERSION;
  16831. $version = $versionParser->normalize($prettyVersion);
  16832. } catch (\UnexpectedValueException $e) {
  16833. $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', PHP_VERSION);
  16834. $version = $versionParser->normalize($prettyVersion);
  16835. }
  16836. $php = new CompletePackage('php', $version, $prettyVersion);
  16837. $php->setDescription('The PHP interpreter');
  16838. parent::addPackage($php);
  16839. if (PHP_INT_SIZE === 8) {
  16840. $php64 = new CompletePackage('php-64bit', $version, $prettyVersion);
  16841. $php64->setDescription('The PHP interpreter (64bit)');
  16842. parent::addPackage($php64);
  16843. }
  16844. $loadedExtensions = get_loaded_extensions();
  16845. foreach ($loadedExtensions as $name) {
  16846. if (in_array($name, array('standard', 'Core'))) {
  16847. continue;
  16848. }
  16849. $reflExt = new \ReflectionExtension($name);
  16850. try {
  16851. $prettyVersion = $reflExt->getVersion();
  16852. $version = $versionParser->normalize($prettyVersion);
  16853. } catch (\UnexpectedValueException $e) {
  16854. $prettyVersion = '0';
  16855. $version = $versionParser->normalize($prettyVersion);
  16856. }
  16857. $packageName = $this->buildPackageName($name);
  16858. $ext = new CompletePackage($packageName, $version, $prettyVersion);
  16859. $ext->setDescription('The '.$name.' PHP extension');
  16860. parent::addPackage($ext);
  16861. }
  16862. foreach ($loadedExtensions as $name) {
  16863. $prettyVersion = null;
  16864. switch ($name) {
  16865. case 'curl':
  16866. $curlVersion = curl_version();
  16867. $prettyVersion = $curlVersion['version'];
  16868. break;
  16869. case 'iconv':
  16870. $prettyVersion = ICONV_VERSION;
  16871. break;
  16872. case 'intl':
  16873. $name = 'ICU';
  16874. if (defined('INTL_ICU_VERSION')) {
  16875. $prettyVersion = INTL_ICU_VERSION;
  16876. } else {
  16877. $reflector = new \ReflectionExtension('intl');
  16878. ob_start();
  16879. $reflector->info();
  16880. $output = ob_get_clean();
  16881. preg_match('/^ICU version => (.*)$/m', $output, $matches);
  16882. $prettyVersion = $matches[1];
  16883. }
  16884. break;
  16885. case 'libxml':
  16886. $prettyVersion = LIBXML_DOTTED_VERSION;
  16887. break;
  16888. case 'openssl':
  16889. $prettyVersion = preg_replace_callback('{^(?:OpenSSL\s*)?([0-9.]+)([a-z]?).*}', function ($match) {
  16890. return $match[1] . (empty($match[2]) ? '' : '.'.(ord($match[2]) - 96));
  16891. }, OPENSSL_VERSION_TEXT);
  16892. break;
  16893. case 'pcre':
  16894. $prettyVersion = preg_replace('{^(\S+).*}', '$1', PCRE_VERSION);
  16895. break;
  16896. case 'uuid':
  16897. $prettyVersion = phpversion('uuid');
  16898. break;
  16899. case 'xsl':
  16900. $prettyVersion = LIBXSLT_DOTTED_VERSION;
  16901. break;
  16902. default:
  16903. continue 2;
  16904. }
  16905. try {
  16906. $version = $versionParser->normalize($prettyVersion);
  16907. } catch (\UnexpectedValueException $e) {
  16908. continue;
  16909. }
  16910. $lib = new CompletePackage('lib-'.$name, $version, $prettyVersion);
  16911. $lib->setDescription('The '.$name.' PHP library');
  16912. parent::addPackage($lib);
  16913. }
  16914. if (defined('HHVM_VERSION')) {
  16915. try {
  16916. $prettyVersion = HHVM_VERSION;
  16917. $version = $versionParser->normalize($prettyVersion);
  16918. } catch (\UnexpectedValueException $e) {
  16919. $prettyVersion = preg_replace('#^([^~+-]+).*$#', '$1', HHVM_VERSION);
  16920. $version = $versionParser->normalize($prettyVersion);
  16921. }
  16922. $hhvm = new CompletePackage('hhvm', $version, $prettyVersion);
  16923. $hhvm->setDescription('The HHVM Runtime (64bit)');
  16924. parent::addPackage($hhvm);
  16925. }
  16926. }
  16927. private function buildPackageName($name)
  16928. {
  16929. return 'ext-' . str_replace(' ', '-', $name);
  16930. }
  16931. }
  16932. <?php
  16933. namespace Composer\Repository;
  16934. use Composer\Package\PackageInterface;
  16935. interface RepositoryInterface extends \Countable
  16936. {
  16937. const SEARCH_FULLTEXT = 0;
  16938. const SEARCH_NAME = 1;
  16939. public function hasPackage(PackageInterface $package);
  16940. public function findPackage($name, $version);
  16941. public function findPackages($name, $version = null);
  16942. public function getPackages();
  16943. public function search($query, $mode = 0);
  16944. }
  16945. <?php
  16946. namespace Composer\Repository;
  16947. use Composer\IO\IOInterface;
  16948. use Composer\Config;
  16949. use Composer\EventDispatcher\EventDispatcher;
  16950. class RepositoryManager
  16951. {
  16952. private $localRepository;
  16953. private $repositories = array();
  16954. private $repositoryClasses = array();
  16955. private $io;
  16956. private $config;
  16957. private $eventDispatcher;
  16958. public function __construct(IOInterface $io, Config $config, EventDispatcher $eventDispatcher = null)
  16959. {
  16960. $this->io = $io;
  16961. $this->config = $config;
  16962. $this->eventDispatcher = $eventDispatcher;
  16963. }
  16964. public function findPackage($name, $version)
  16965. {
  16966. foreach ($this->repositories as $repository) {
  16967. if ($package = $repository->findPackage($name, $version)) {
  16968. return $package;
  16969. }
  16970. }
  16971. }
  16972. public function findPackages($name, $version)
  16973. {
  16974. $packages = array();
  16975. foreach ($this->repositories as $repository) {
  16976. $packages = array_merge($packages, $repository->findPackages($name, $version));
  16977. }
  16978. return $packages;
  16979. }
  16980. public function addRepository(RepositoryInterface $repository)
  16981. {
  16982. $this->repositories[] = $repository;
  16983. }
  16984. public function createRepository($type, $config)
  16985. {
  16986. if (!isset($this->repositoryClasses[$type])) {
  16987. throw new \InvalidArgumentException('Repository type is not registered: '.$type);
  16988. }
  16989. $class = $this->repositoryClasses[$type];
  16990. return new $class($config, $this->io, $this->config, $this->eventDispatcher);
  16991. }
  16992. public function setRepositoryClass($type, $class)
  16993. {
  16994. $this->repositoryClasses[$type] = $class;
  16995. }
  16996. public function getRepositories()
  16997. {
  16998. return $this->repositories;
  16999. }
  17000. public function setLocalRepository(WritableRepositoryInterface $repository)
  17001. {
  17002. $this->localRepository = $repository;
  17003. }
  17004. public function getLocalRepository()
  17005. {
  17006. return $this->localRepository;
  17007. }
  17008. public function getLocalRepositories()
  17009. {
  17010. trigger_error('This method is deprecated, use getLocalRepository instead since the getLocalDevRepository is now gone', E_USER_DEPRECATED);
  17011. return array($this->localRepository);
  17012. }
  17013. }
  17014. <?php
  17015. namespace Composer\Repository;
  17016. class RepositorySecurityException extends \Exception
  17017. {
  17018. }
  17019. <?php
  17020. namespace Composer\Repository\Vcs;
  17021. use Composer\Config;
  17022. use Composer\Json\JsonFile;
  17023. use Composer\IO\IOInterface;
  17024. class GitBitbucketDriver extends VcsDriver implements VcsDriverInterface
  17025. {
  17026. protected $owner;
  17027. protected $repository;
  17028. protected $tags;
  17029. protected $branches;
  17030. protected $rootIdentifier;
  17031. protected $infoCache = array();
  17032. public function initialize()
  17033. {
  17034. preg_match('#^https?://bitbucket\.org/([^/]+)/(.+?)\.git$#', $this->url, $match);
  17035. $this->owner = $match[1];
  17036. $this->repository = $match[2];
  17037. $this->originUrl = 'bitbucket.org';
  17038. }
  17039. public function getRootIdentifier()
  17040. {
  17041. if (null === $this->rootIdentifier) {
  17042. $resource = $this->getScheme() . '://api.bitbucket.org/1.0/repositories/'.$this->owner.'/'.$this->repository;
  17043. $repoData = JsonFile::parseJson($this->getContents($resource), $resource);
  17044. $this->rootIdentifier = !empty($repoData['main_branch']) ? $repoData['main_branch'] : 'master';
  17045. }
  17046. return $this->rootIdentifier;
  17047. }
  17048. public function getUrl()
  17049. {
  17050. return $this->url;
  17051. }
  17052. public function getSource($identifier)
  17053. {
  17054. return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier);
  17055. }
  17056. public function getDist($identifier)
  17057. {
  17058. $url = $this->getScheme() . '://bitbucket.org/'.$this->owner.'/'.$this->repository.'/get/'.$identifier.'.zip';
  17059. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  17060. }
  17061. public function getComposerInformation($identifier)
  17062. {
  17063. if (!isset($this->infoCache[$identifier])) {
  17064. $resource = $this->getScheme() . '://bitbucket.org/'.$this->owner.'/'.$this->repository.'/raw/'.$identifier.'/composer.json';
  17065. $composer = $this->getContents($resource);
  17066. if (!$composer) {
  17067. return;
  17068. }
  17069. $composer = JsonFile::parseJson($composer, $resource);
  17070. if (empty($composer['time'])) {
  17071. $resource = $this->getScheme() . '://api.bitbucket.org/1.0/repositories/'.$this->owner.'/'.$this->repository.'/changesets/'.$identifier;
  17072. $changeset = JsonFile::parseJson($this->getContents($resource), $resource);
  17073. $composer['time'] = $changeset['timestamp'];
  17074. }
  17075. $this->infoCache[$identifier] = $composer;
  17076. }
  17077. return $this->infoCache[$identifier];
  17078. }
  17079. public function getTags()
  17080. {
  17081. if (null === $this->tags) {
  17082. $resource = $this->getScheme() . '://api.bitbucket.org/1.0/repositories/'.$this->owner.'/'.$this->repository.'/tags';
  17083. $tagsData = JsonFile::parseJson($this->getContents($resource), $resource);
  17084. $this->tags = array();
  17085. foreach ($tagsData as $tag => $data) {
  17086. $this->tags[$tag] = $data['raw_node'];
  17087. }
  17088. }
  17089. return $this->tags;
  17090. }
  17091. public function getBranches()
  17092. {
  17093. if (null === $this->branches) {
  17094. $resource = $this->getScheme() . '://api.bitbucket.org/1.0/repositories/'.$this->owner.'/'.$this->repository.'/branches';
  17095. $branchData = JsonFile::parseJson($this->getContents($resource), $resource);
  17096. $this->branches = array();
  17097. foreach ($branchData as $branch => $data) {
  17098. $this->branches[$branch] = $data['raw_node'];
  17099. }
  17100. }
  17101. return $this->branches;
  17102. }
  17103. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17104. {
  17105. if (!preg_match('#^https?://bitbucket\.org/([^/]+)/(.+?)\.git$#', $url)) {
  17106. return false;
  17107. }
  17108. if (!extension_loaded('openssl')) {
  17109. if ($io->isVerbose()) {
  17110. $io->writeError('Skipping Bitbucket git driver for '.$url.' because the OpenSSL PHP extension is missing.');
  17111. }
  17112. return false;
  17113. }
  17114. return true;
  17115. }
  17116. }
  17117. <?php
  17118. namespace Composer\Repository\Vcs;
  17119. use Composer\Json\JsonFile;
  17120. use Composer\Util\ProcessExecutor;
  17121. use Composer\Util\Filesystem;
  17122. use Composer\Util\Git as GitUtil;
  17123. use Composer\IO\IOInterface;
  17124. use Composer\Cache;
  17125. use Composer\Config;
  17126. class GitDriver extends VcsDriver
  17127. {
  17128. protected $cache;
  17129. protected $tags;
  17130. protected $branches;
  17131. protected $rootIdentifier;
  17132. protected $repoDir;
  17133. protected $infoCache = array();
  17134. public function initialize()
  17135. {
  17136. if (Filesystem::isLocalPath($this->url)) {
  17137. $this->repoDir = $this->url;
  17138. $cacheUrl = realpath($this->url);
  17139. } else {
  17140. $this->repoDir = $this->config->get('cache-vcs-dir') . '/' . preg_replace('{[^a-z0-9.]}i', '-', $this->url) . '/';
  17141. GitUtil::cleanEnv();
  17142. $fs = new Filesystem();
  17143. $fs->ensureDirectoryExists(dirname($this->repoDir));
  17144. if (!is_writable(dirname($this->repoDir))) {
  17145. throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.dirname($this->repoDir).'" directory is not writable by the current user.');
  17146. }
  17147. if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $this->url)) {
  17148. throw new \InvalidArgumentException('The source URL '.$this->url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
  17149. }
  17150. $gitUtil = new GitUtil($this->io, $this->config, $this->process, $fs);
  17151. if (is_dir($this->repoDir) && 0 === $this->process->execute('git rev-parse --git-dir', $output, $this->repoDir) && trim($output) === '.') {
  17152. try {
  17153. $commandCallable = function ($url) {
  17154. return sprintf('git remote set-url origin %s && git remote update --prune origin', ProcessExecutor::escape($url));
  17155. };
  17156. $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir);
  17157. } catch (\Exception $e) {
  17158. $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$e->getMessage().')</error>');
  17159. }
  17160. } else {
  17161. $fs->removeDirectory($this->repoDir);
  17162. $repoDir = $this->repoDir;
  17163. $commandCallable = function ($url) use ($repoDir) {
  17164. return sprintf('git clone --mirror %s %s', ProcessExecutor::escape($url), ProcessExecutor::escape($repoDir));
  17165. };
  17166. $gitUtil->runCommand($commandCallable, $this->url, $this->repoDir, true);
  17167. }
  17168. $cacheUrl = $this->url;
  17169. }
  17170. $this->getTags();
  17171. $this->getBranches();
  17172. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $cacheUrl));
  17173. }
  17174. public function getRootIdentifier()
  17175. {
  17176. if (null === $this->rootIdentifier) {
  17177. $this->rootIdentifier = 'master';
  17178. $this->process->execute('git branch --no-color', $output, $this->repoDir);
  17179. $branches = $this->process->splitLines($output);
  17180. if (!in_array('* master', $branches)) {
  17181. foreach ($branches as $branch) {
  17182. if ($branch && preg_match('{^\* +(\S+)}', $branch, $match)) {
  17183. $this->rootIdentifier = $match[1];
  17184. break;
  17185. }
  17186. }
  17187. }
  17188. }
  17189. return $this->rootIdentifier;
  17190. }
  17191. public function getUrl()
  17192. {
  17193. return $this->url;
  17194. }
  17195. public function getSource($identifier)
  17196. {
  17197. return array('type' => 'git', 'url' => $this->getUrl(), 'reference' => $identifier);
  17198. }
  17199. public function getDist($identifier)
  17200. {
  17201. return null;
  17202. }
  17203. public function getComposerInformation($identifier)
  17204. {
  17205. if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) {
  17206. $this->infoCache[$identifier] = JsonFile::parseJson($res);
  17207. }
  17208. if (!isset($this->infoCache[$identifier])) {
  17209. $resource = sprintf('%s:composer.json', ProcessExecutor::escape($identifier));
  17210. $this->process->execute(sprintf('git show %s', $resource), $composer, $this->repoDir);
  17211. if (!trim($composer)) {
  17212. return;
  17213. }
  17214. $composer = JsonFile::parseJson($composer, $resource);
  17215. if (empty($composer['time'])) {
  17216. $this->process->execute(sprintf('git log -1 --format=%%at %s', ProcessExecutor::escape($identifier)), $output, $this->repoDir);
  17217. $date = new \DateTime('@'.trim($output), new \DateTimeZone('UTC'));
  17218. $composer['time'] = $date->format('Y-m-d H:i:s');
  17219. }
  17220. if (preg_match('{[a-f0-9]{40}}i', $identifier)) {
  17221. $this->cache->write($identifier, json_encode($composer));
  17222. }
  17223. $this->infoCache[$identifier] = $composer;
  17224. }
  17225. return $this->infoCache[$identifier];
  17226. }
  17227. public function getTags()
  17228. {
  17229. if (null === $this->tags) {
  17230. $this->tags = array();
  17231. $this->process->execute('git show-ref --tags', $output, $this->repoDir);
  17232. foreach ($output = $this->process->splitLines($output) as $tag) {
  17233. if ($tag && preg_match('{^([a-f0-9]{40}) refs/tags/(\S+)$}', $tag, $match)) {
  17234. $this->tags[$match[2]] = $match[1];
  17235. }
  17236. }
  17237. }
  17238. return $this->tags;
  17239. }
  17240. public function getBranches()
  17241. {
  17242. if (null === $this->branches) {
  17243. $branches = array();
  17244. $this->process->execute('git branch --no-color --no-abbrev -v', $output, $this->repoDir);
  17245. foreach ($this->process->splitLines($output) as $branch) {
  17246. if ($branch && !preg_match('{^ *[^/]+/HEAD }', $branch)) {
  17247. if (preg_match('{^(?:\* )? *(\S+) *([a-f0-9]+)(?: .*)?$}', $branch, $match)) {
  17248. $branches[$match[1]] = $match[2];
  17249. }
  17250. }
  17251. }
  17252. $this->branches = $branches;
  17253. }
  17254. return $this->branches;
  17255. }
  17256. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17257. {
  17258. if (preg_match('#(^git://|\.git$|git(?:olite)?@|//git\.|//github.com/)#i', $url)) {
  17259. return true;
  17260. }
  17261. if (Filesystem::isLocalPath($url)) {
  17262. $url = Filesystem::getPlatformPath($url);
  17263. if (!is_dir($url)) {
  17264. return false;
  17265. }
  17266. $process = new ProcessExecutor($io);
  17267. if ($process->execute('git tag', $output, $url) === 0) {
  17268. return true;
  17269. }
  17270. }
  17271. if (!$deep) {
  17272. return false;
  17273. }
  17274. $process = new ProcessExecutor($io);
  17275. if ($process->execute('git ls-remote --heads ' . ProcessExecutor::escape($url), $output) === 0) {
  17276. return true;
  17277. }
  17278. return false;
  17279. }
  17280. }
  17281. <?php
  17282. namespace Composer\Repository\Vcs;
  17283. use Composer\Config;
  17284. use Composer\Downloader\TransportException;
  17285. use Composer\Json\JsonFile;
  17286. use Composer\Cache;
  17287. use Composer\IO\IOInterface;
  17288. use Composer\Util\GitHub;
  17289. class GitHubDriver extends VcsDriver
  17290. {
  17291. protected $cache;
  17292. protected $owner;
  17293. protected $repository;
  17294. protected $tags;
  17295. protected $branches;
  17296. protected $rootIdentifier;
  17297. protected $hasIssues;
  17298. protected $infoCache = array();
  17299. protected $isPrivate = false;
  17300. protected $gitDriver;
  17301. public function initialize()
  17302. {
  17303. preg_match('#^(?:(?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\.git|/)?$#', $this->url, $match);
  17304. $this->owner = $match[3];
  17305. $this->repository = $match[4];
  17306. $this->originUrl = !empty($match[1]) ? $match[1] : $match[2];
  17307. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
  17308. if (isset($this->repoConfig['no-api']) && $this->repoConfig['no-api']) {
  17309. $this->setupGitDriver($this->url);
  17310. return;
  17311. }
  17312. $this->fetchRootIdentifier();
  17313. }
  17314. public function getRepositoryUrl()
  17315. {
  17316. return 'https://'.$this->originUrl.'/'.$this->owner.'/'.$this->repository;
  17317. }
  17318. public function getRootIdentifier()
  17319. {
  17320. if ($this->gitDriver) {
  17321. return $this->gitDriver->getRootIdentifier();
  17322. }
  17323. return $this->rootIdentifier;
  17324. }
  17325. public function getUrl()
  17326. {
  17327. if ($this->gitDriver) {
  17328. return $this->gitDriver->getUrl();
  17329. }
  17330. return 'https://' . $this->originUrl . '/'.$this->owner.'/'.$this->repository.'.git';
  17331. }
  17332. protected function getApiUrl()
  17333. {
  17334. if ('github.com' === $this->originUrl) {
  17335. $apiUrl = 'api.github.com';
  17336. } else {
  17337. $apiUrl = $this->originUrl . '/api/v3';
  17338. }
  17339. return 'https://' . $apiUrl;
  17340. }
  17341. public function getSource($identifier)
  17342. {
  17343. if ($this->gitDriver) {
  17344. return $this->gitDriver->getSource($identifier);
  17345. }
  17346. if ($this->isPrivate) {
  17347. $url = $this->generateSshUrl();
  17348. } else {
  17349. $url = $this->getUrl();
  17350. }
  17351. return array('type' => 'git', 'url' => $url, 'reference' => $identifier);
  17352. }
  17353. public function getDist($identifier)
  17354. {
  17355. $url = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/zipball/'.$identifier;
  17356. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  17357. }
  17358. public function getComposerInformation($identifier)
  17359. {
  17360. if ($this->gitDriver) {
  17361. return $this->gitDriver->getComposerInformation($identifier);
  17362. }
  17363. if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) {
  17364. $this->infoCache[$identifier] = JsonFile::parseJson($res);
  17365. }
  17366. if (!isset($this->infoCache[$identifier])) {
  17367. $notFoundRetries = 2;
  17368. while ($notFoundRetries) {
  17369. try {
  17370. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/contents/composer.json?ref='.urlencode($identifier);
  17371. $composer = JsonFile::parseJson($this->getContents($resource));
  17372. if (empty($composer['content']) || $composer['encoding'] !== 'base64' || !($composer = base64_decode($composer['content']))) {
  17373. throw new \RuntimeException('Could not retrieve composer.json from '.$resource);
  17374. }
  17375. break;
  17376. } catch (TransportException $e) {
  17377. if (404 !== $e->getCode()) {
  17378. throw $e;
  17379. }
  17380. $notFoundRetries--;
  17381. $composer = false;
  17382. }
  17383. }
  17384. if ($composer) {
  17385. $composer = JsonFile::parseJson($composer, $resource);
  17386. if (empty($composer['time'])) {
  17387. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/commits/'.urlencode($identifier);
  17388. $commit = JsonFile::parseJson($this->getContents($resource), $resource);
  17389. $composer['time'] = $commit['commit']['committer']['date'];
  17390. }
  17391. if (!isset($composer['support']['source'])) {
  17392. $label = array_search($identifier, $this->getTags()) ?: array_search($identifier, $this->getBranches()) ?: $identifier;
  17393. $composer['support']['source'] = sprintf('https://%s/%s/%s/tree/%s', $this->originUrl, $this->owner, $this->repository, $label);
  17394. }
  17395. if (!isset($composer['support']['issues']) && $this->hasIssues) {
  17396. $composer['support']['issues'] = sprintf('https://%s/%s/%s/issues', $this->originUrl, $this->owner, $this->repository);
  17397. }
  17398. }
  17399. if (preg_match('{[a-f0-9]{40}}i', $identifier)) {
  17400. $this->cache->write($identifier, json_encode($composer));
  17401. }
  17402. $this->infoCache[$identifier] = $composer;
  17403. }
  17404. return $this->infoCache[$identifier];
  17405. }
  17406. public function getTags()
  17407. {
  17408. if ($this->gitDriver) {
  17409. return $this->gitDriver->getTags();
  17410. }
  17411. if (null === $this->tags) {
  17412. $this->tags = array();
  17413. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/tags?per_page=100';
  17414. do {
  17415. $tagsData = JsonFile::parseJson($this->getContents($resource), $resource);
  17416. foreach ($tagsData as $tag) {
  17417. $this->tags[$tag['name']] = $tag['commit']['sha'];
  17418. }
  17419. $resource = $this->getNextPage();
  17420. } while ($resource);
  17421. }
  17422. return $this->tags;
  17423. }
  17424. public function getBranches()
  17425. {
  17426. if ($this->gitDriver) {
  17427. return $this->gitDriver->getBranches();
  17428. }
  17429. if (null === $this->branches) {
  17430. $this->branches = array();
  17431. $resource = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository.'/git/refs/heads?per_page=100';
  17432. $branchBlacklist = array('gh-pages');
  17433. do {
  17434. $branchData = JsonFile::parseJson($this->getContents($resource), $resource);
  17435. foreach ($branchData as $branch) {
  17436. $name = substr($branch['ref'], 11);
  17437. if (!in_array($name, $branchBlacklist)) {
  17438. $this->branches[$name] = $branch['object']['sha'];
  17439. }
  17440. }
  17441. $resource = $this->getNextPage();
  17442. } while ($resource);
  17443. }
  17444. return $this->branches;
  17445. }
  17446. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17447. {
  17448. if (!preg_match('#^((?:https?|git)://([^/]+)/|git@([^:]+):)([^/]+)/(.+?)(?:\.git|/)?$#', $url, $matches)) {
  17449. return false;
  17450. }
  17451. $originUrl = !empty($matches[2]) ? $matches[2] : $matches[3];
  17452. if (!in_array($originUrl, $config->get('github-domains'))) {
  17453. return false;
  17454. }
  17455. if (!extension_loaded('openssl')) {
  17456. if ($io->isVerbose()) {
  17457. $io->writeError('Skipping GitHub driver for '.$url.' because the OpenSSL PHP extension is missing.');
  17458. }
  17459. return false;
  17460. }
  17461. return true;
  17462. }
  17463. protected function generateSshUrl()
  17464. {
  17465. return 'git@' . $this->originUrl . ':'.$this->owner.'/'.$this->repository.'.git';
  17466. }
  17467. protected function getContents($url, $fetchingRepoData = false)
  17468. {
  17469. try {
  17470. return parent::getContents($url);
  17471. } catch (TransportException $e) {
  17472. $gitHubUtil = new GitHub($this->io, $this->config, $this->process, $this->remoteFilesystem);
  17473. switch ($e->getCode()) {
  17474. case 401:
  17475. case 404:
  17476. if (!$fetchingRepoData) {
  17477. throw $e;
  17478. }
  17479. if ($gitHubUtil->authorizeOAuth($this->originUrl)) {
  17480. return parent::getContents($url);
  17481. }
  17482. if (!$this->io->isInteractive()) {
  17483. return $this->attemptCloneFallback();
  17484. }
  17485. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'Your GitHub credentials are required to fetch private repository metadata (<info>'.$this->url.'</info>)');
  17486. return parent::getContents($url);
  17487. case 403:
  17488. if (!$this->io->hasAuthentication($this->originUrl) && $gitHubUtil->authorizeOAuth($this->originUrl)) {
  17489. return parent::getContents($url);
  17490. }
  17491. if (!$this->io->isInteractive() && $fetchingRepoData) {
  17492. return $this->attemptCloneFallback();
  17493. }
  17494. $rateLimited = false;
  17495. foreach ($e->getHeaders() as $header) {
  17496. if (preg_match('{^X-RateLimit-Remaining: *0$}i', trim($header))) {
  17497. $rateLimited = true;
  17498. }
  17499. }
  17500. if (!$this->io->hasAuthentication($this->originUrl)) {
  17501. if (!$this->io->isInteractive()) {
  17502. $this->io->writeError('<error>GitHub API limit exhausted. Failed to get metadata for the '.$this->url.' repository, try running in interactive mode so that you can enter your GitHub credentials to increase the API limit</error>');
  17503. throw $e;
  17504. }
  17505. $gitHubUtil->authorizeOAuthInteractively($this->originUrl, 'API limit exhausted. Enter your GitHub credentials to get a larger API limit (<info>'.$this->url.'</info>)');
  17506. return parent::getContents($url);
  17507. }
  17508. if ($rateLimited) {
  17509. $rateLimit = $this->getRateLimit($e->getHeaders());
  17510. $this->io->writeError(sprintf(
  17511. '<error>GitHub API limit (%d calls/hr) is exhausted. You are already authorized so you have to wait until %s before doing more requests</error>',
  17512. $rateLimit['limit'],
  17513. $rateLimit['reset']
  17514. ));
  17515. }
  17516. throw $e;
  17517. default:
  17518. throw $e;
  17519. }
  17520. }
  17521. }
  17522. protected function getRateLimit(array $headers)
  17523. {
  17524. $rateLimit = array(
  17525. 'limit' => '?',
  17526. 'reset' => '?',
  17527. );
  17528. foreach ($headers as $header) {
  17529. $header = trim($header);
  17530. if (false === strpos($header, 'X-RateLimit-')) {
  17531. continue;
  17532. }
  17533. list($type, $value) = explode(':', $header, 2);
  17534. switch ($type) {
  17535. case 'X-RateLimit-Limit':
  17536. $rateLimit['limit'] = (int) trim($value);
  17537. break;
  17538. case 'X-RateLimit-Reset':
  17539. $rateLimit['reset'] = date('Y-m-d H:i:s', (int) trim($value));
  17540. break;
  17541. }
  17542. }
  17543. return $rateLimit;
  17544. }
  17545. protected function fetchRootIdentifier()
  17546. {
  17547. $repoDataUrl = $this->getApiUrl() . '/repos/'.$this->owner.'/'.$this->repository;
  17548. $repoData = JsonFile::parseJson($this->getContents($repoDataUrl, true), $repoDataUrl);
  17549. if (null === $repoData && null !== $this->gitDriver) {
  17550. return;
  17551. }
  17552. $this->owner = $repoData['owner']['login'];
  17553. $this->repository = $repoData['name'];
  17554. $this->isPrivate = !empty($repoData['private']);
  17555. if (isset($repoData['default_branch'])) {
  17556. $this->rootIdentifier = $repoData['default_branch'];
  17557. } elseif (isset($repoData['master_branch'])) {
  17558. $this->rootIdentifier = $repoData['master_branch'];
  17559. } else {
  17560. $this->rootIdentifier = 'master';
  17561. }
  17562. $this->hasIssues = !empty($repoData['has_issues']);
  17563. }
  17564. protected function attemptCloneFallback()
  17565. {
  17566. $this->isPrivate = true;
  17567. try {
  17568. $this->setupGitDriver($this->generateSshUrl());
  17569. return;
  17570. } catch (\RuntimeException $e) {
  17571. $this->gitDriver = null;
  17572. $this->io->writeError('<error>Failed to clone the '.$this->generateSshUrl().' repository, try running in interactive mode so that you can enter your GitHub credentials</error>');
  17573. throw $e;
  17574. }
  17575. }
  17576. protected function setupGitDriver($url)
  17577. {
  17578. $this->gitDriver = new GitDriver(
  17579. array('url' => $url),
  17580. $this->io,
  17581. $this->config,
  17582. $this->process,
  17583. $this->remoteFilesystem
  17584. );
  17585. $this->gitDriver->initialize();
  17586. }
  17587. protected function getNextPage()
  17588. {
  17589. $headers = $this->remoteFilesystem->getLastHeaders();
  17590. foreach ($headers as $header) {
  17591. if (substr($header, 0, 5) === 'Link:') {
  17592. $links = explode(',', substr($header, 5));
  17593. foreach ($links as $link) {
  17594. if (preg_match('{<(.+?)>; *rel="next"}', $link, $match)) {
  17595. return $match[1];
  17596. }
  17597. }
  17598. }
  17599. }
  17600. }
  17601. }
  17602. <?php
  17603. namespace Composer\Repository\Vcs;
  17604. use Composer\Config;
  17605. use Composer\Cache;
  17606. use Composer\IO\IOInterface;
  17607. use Composer\Json\JsonFile;
  17608. use Composer\Downloader\TransportException;
  17609. use Composer\Util\RemoteFilesystem;
  17610. class GitLabDriver extends VcsDriver
  17611. {
  17612. private $scheme;
  17613. private $owner;
  17614. private $repository;
  17615. private $cache;
  17616. private $infoCache = array();
  17617. private $project;
  17618. private $commits = array();
  17619. private $tags;
  17620. private $branches;
  17621. public function initialize()
  17622. {
  17623. if (!preg_match('#^(https?)://([^/]+)/([^/]+)/([^/]+)(?:\.git|/)?$#', $this->url, $match)) {
  17624. throw new \InvalidArgumentException('The URL provided is invalid. It must be the HTTP URL of a GitLab project.');
  17625. }
  17626. $this->scheme = $match[1];
  17627. $this->originUrl = $match[2];
  17628. $this->owner = $match[3];
  17629. $this->repository = preg_replace('#(\.git)$#', '', $match[4]);
  17630. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.$this->originUrl.'/'.$this->owner.'/'.$this->repository);
  17631. $this->fetchProject();
  17632. }
  17633. public function setRemoteFilesystem(RemoteFilesystem $remoteFilesystem)
  17634. {
  17635. $this->remoteFilesystem = $remoteFilesystem;
  17636. }
  17637. public function getComposerInformation($identifier)
  17638. {
  17639. if (!preg_match('{[a-f0-9]{40}}i', $identifier)) {
  17640. $branches = $this->getBranches();
  17641. if (isset($branches[$identifier])) {
  17642. $identifier = $branches[$identifier];
  17643. }
  17644. }
  17645. if (isset($this->infoCache[$identifier])) {
  17646. return $this->infoCache[$identifier];
  17647. }
  17648. if (preg_match('{[a-f0-9]{40}}i', $identifier) && $res = $this->cache->read($identifier)) {
  17649. return $this->infoCache[$identifier] = JsonFile::parseJson($res, $res);
  17650. }
  17651. try {
  17652. $composer = $this->fetchComposerFile($identifier);
  17653. } catch (TransportException $e) {
  17654. if ($e->getCode() !== 404) {
  17655. throw $e;
  17656. }
  17657. $composer = false;
  17658. }
  17659. if ($composer && !isset($composer['time']) && isset($this->commits[$identifier])) {
  17660. $composer['time'] = $this->commits[$identifier]['committed_date'];
  17661. }
  17662. if (preg_match('{[a-f0-9]{40}}i', $identifier)) {
  17663. $this->cache->write($identifier, json_encode($composer));
  17664. }
  17665. return $this->infoCache[$identifier] = $composer;
  17666. }
  17667. public function getRepositoryUrl()
  17668. {
  17669. return $this->project['ssh_url_to_repo'];
  17670. }
  17671. public function getUrl()
  17672. {
  17673. return $this->project['web_url'];
  17674. }
  17675. public function getDist($identifier)
  17676. {
  17677. $url = $this->getApiUrl().'/repository/archive.zip?sha='.$identifier;
  17678. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  17679. }
  17680. public function getSource($identifier)
  17681. {
  17682. return array('type' => 'git', 'url' => $this->getRepositoryUrl(), 'reference' => $identifier);
  17683. }
  17684. public function getRootIdentifier()
  17685. {
  17686. return $this->project['default_branch'];
  17687. }
  17688. public function getBranches()
  17689. {
  17690. if (!$this->branches) {
  17691. $this->branches = $this->getReferences('branches');
  17692. }
  17693. return $this->branches;
  17694. }
  17695. public function getTags()
  17696. {
  17697. if (!$this->tags) {
  17698. $this->tags = $this->getReferences('tags');
  17699. }
  17700. return $this->tags;
  17701. }
  17702. protected function fetchComposerFile($identifier)
  17703. {
  17704. $resource = $this->getApiUrl().'/repository/blobs/'.$identifier.'?filepath=composer.json';
  17705. return JsonFile::parseJson($this->getContents($resource), $resource);
  17706. }
  17707. public function getApiUrl()
  17708. {
  17709. return $this->scheme.'://'.$this->originUrl.'/api/v3/projects/'.$this->owner.'%2F'.$this->repository;
  17710. }
  17711. protected function getReferences($type)
  17712. {
  17713. $resource = $this->getApiUrl().'/repository/'.$type;
  17714. $data = JsonFile::parseJson($this->getContents($resource), $resource);
  17715. $references = array();
  17716. foreach ($data as $datum) {
  17717. $references[$datum['name']] = $datum['commit']['id'];
  17718. $this->commits[$datum['commit']['id']] = $datum['commit'];
  17719. }
  17720. return $references;
  17721. }
  17722. protected function fetchProject()
  17723. {
  17724. $resource = $this->getApiUrl();
  17725. $this->project = JsonFile::parseJson($this->getContents($resource), $resource);
  17726. }
  17727. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17728. {
  17729. if (!preg_match('#^(https?)://([^/]+)/([^/]+)/([^/]+)(?:\.git|/)?$#', $url, $match)) {
  17730. return false;
  17731. }
  17732. $scheme = $match[1];
  17733. $originUrl = $match[2];
  17734. if (!in_array($originUrl, (array) $config->get('gitlab-domains'))) {
  17735. return false;
  17736. }
  17737. if ('https' === $scheme && !extension_loaded('openssl')) {
  17738. if ($io->isVerbose()) {
  17739. $io->write('Skipping GitLab driver for '.$url.' because the OpenSSL PHP extension is missing.');
  17740. }
  17741. return false;
  17742. }
  17743. return true;
  17744. }
  17745. }
  17746. <?php
  17747. namespace Composer\Repository\Vcs;
  17748. use Composer\Config;
  17749. use Composer\Json\JsonFile;
  17750. use Composer\IO\IOInterface;
  17751. class HgBitbucketDriver extends VcsDriver
  17752. {
  17753. protected $owner;
  17754. protected $repository;
  17755. protected $tags;
  17756. protected $branches;
  17757. protected $rootIdentifier;
  17758. protected $infoCache = array();
  17759. public function initialize()
  17760. {
  17761. preg_match('#^https?://bitbucket\.org/([^/]+)/([^/]+)/?$#', $this->url, $match);
  17762. $this->owner = $match[1];
  17763. $this->repository = $match[2];
  17764. $this->originUrl = 'bitbucket.org';
  17765. }
  17766. public function getRootIdentifier()
  17767. {
  17768. if (null === $this->rootIdentifier) {
  17769. $resource = $this->getScheme() . '://bitbucket.org/api/1.0/repositories/'.$this->owner.'/'.$this->repository.'/tags';
  17770. $repoData = JsonFile::parseJson($this->getContents($resource), $resource);
  17771. if (array() === $repoData || !isset($repoData['tip'])) {
  17772. throw new \RuntimeException($this->url.' does not appear to be a mercurial repository, use '.$this->url.'.git if this is a git bitbucket repository');
  17773. }
  17774. $this->rootIdentifier = $repoData['tip']['raw_node'];
  17775. }
  17776. return $this->rootIdentifier;
  17777. }
  17778. public function getUrl()
  17779. {
  17780. return $this->url;
  17781. }
  17782. public function getSource($identifier)
  17783. {
  17784. return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier);
  17785. }
  17786. public function getDist($identifier)
  17787. {
  17788. $url = $this->getScheme() . '://bitbucket.org/'.$this->owner.'/'.$this->repository.'/get/'.$identifier.'.zip';
  17789. return array('type' => 'zip', 'url' => $url, 'reference' => $identifier, 'shasum' => '');
  17790. }
  17791. public function getComposerInformation($identifier)
  17792. {
  17793. if (!isset($this->infoCache[$identifier])) {
  17794. $resource = $this->getScheme() . '://bitbucket.org/api/1.0/repositories/'.$this->owner.'/'.$this->repository.'/src/'.$identifier.'/composer.json';
  17795. $repoData = JsonFile::parseJson($this->getContents($resource), $resource);
  17796. if (!array_key_exists('data', $repoData)) {
  17797. return;
  17798. }
  17799. $composer = JsonFile::parseJson($repoData['data'], $resource);
  17800. if (empty($composer['time'])) {
  17801. $resource = $this->getScheme() . '://bitbucket.org/api/1.0/repositories/'.$this->owner.'/'.$this->repository.'/changesets/'.$identifier;
  17802. $changeset = JsonFile::parseJson($this->getContents($resource), $resource);
  17803. $composer['time'] = $changeset['timestamp'];
  17804. }
  17805. $this->infoCache[$identifier] = $composer;
  17806. }
  17807. return $this->infoCache[$identifier];
  17808. }
  17809. public function getTags()
  17810. {
  17811. if (null === $this->tags) {
  17812. $resource = $this->getScheme() . '://bitbucket.org/api/1.0/repositories/'.$this->owner.'/'.$this->repository.'/tags';
  17813. $tagsData = JsonFile::parseJson($this->getContents($resource), $resource);
  17814. $this->tags = array();
  17815. foreach ($tagsData as $tag => $data) {
  17816. $this->tags[$tag] = $data['raw_node'];
  17817. }
  17818. unset($this->tags['tip']);
  17819. }
  17820. return $this->tags;
  17821. }
  17822. public function getBranches()
  17823. {
  17824. if (null === $this->branches) {
  17825. $resource = $this->getScheme() . '://bitbucket.org/api/1.0/repositories/'.$this->owner.'/'.$this->repository.'/branches';
  17826. $branchData = JsonFile::parseJson($this->getContents($resource), $resource);
  17827. $this->branches = array();
  17828. foreach ($branchData as $branch => $data) {
  17829. $this->branches[$branch] = $data['raw_node'];
  17830. }
  17831. }
  17832. return $this->branches;
  17833. }
  17834. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17835. {
  17836. if (!preg_match('#^https?://bitbucket\.org/([^/]+)/([^/]+)/?$#', $url)) {
  17837. return false;
  17838. }
  17839. if (!extension_loaded('openssl')) {
  17840. if ($io->isVerbose()) {
  17841. $io->writeError('Skipping Bitbucket hg driver for '.$url.' because the OpenSSL PHP extension is missing.');
  17842. }
  17843. return false;
  17844. }
  17845. return true;
  17846. }
  17847. }
  17848. <?php
  17849. namespace Composer\Repository\Vcs;
  17850. use Composer\Config;
  17851. use Composer\Json\JsonFile;
  17852. use Composer\Util\ProcessExecutor;
  17853. use Composer\Util\Filesystem;
  17854. use Composer\IO\IOInterface;
  17855. class HgDriver extends VcsDriver
  17856. {
  17857. protected $tags;
  17858. protected $branches;
  17859. protected $rootIdentifier;
  17860. protected $repoDir;
  17861. protected $infoCache = array();
  17862. public function initialize()
  17863. {
  17864. if (Filesystem::isLocalPath($this->url)) {
  17865. $this->repoDir = $this->url;
  17866. } else {
  17867. $cacheDir = $this->config->get('cache-vcs-dir');
  17868. $this->repoDir = $cacheDir . '/' . preg_replace('{[^a-z0-9]}i', '-', $this->url) . '/';
  17869. $fs = new Filesystem();
  17870. $fs->ensureDirectoryExists($cacheDir);
  17871. if (!is_writable(dirname($this->repoDir))) {
  17872. throw new \RuntimeException('Can not clone '.$this->url.' to access package information. The "'.$cacheDir.'" directory is not writable by the current user.');
  17873. }
  17874. if (is_dir($this->repoDir) && 0 === $this->process->execute('hg summary', $output, $this->repoDir)) {
  17875. if (0 !== $this->process->execute('hg pull', $output, $this->repoDir)) {
  17876. $this->io->writeError('<error>Failed to update '.$this->url.', package information from this repository may be outdated ('.$this->process->getErrorOutput().')</error>');
  17877. }
  17878. } else {
  17879. $fs->removeDirectory($this->repoDir);
  17880. if (0 !== $this->process->execute(sprintf('hg clone --noupdate %s %s', ProcessExecutor::escape($this->url), ProcessExecutor::escape($this->repoDir)), $output, $cacheDir)) {
  17881. $output = $this->process->getErrorOutput();
  17882. if (0 !== $this->process->execute('hg --version', $ignoredOutput)) {
  17883. throw new \RuntimeException('Failed to clone '.$this->url.', hg was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  17884. }
  17885. throw new \RuntimeException('Failed to clone '.$this->url.', could not read packages from it' . "\n\n" .$output);
  17886. }
  17887. }
  17888. }
  17889. $this->getTags();
  17890. $this->getBranches();
  17891. }
  17892. public function getRootIdentifier()
  17893. {
  17894. if (null === $this->rootIdentifier) {
  17895. $this->process->execute(sprintf('hg tip --template "{node}"'), $output, $this->repoDir);
  17896. $output = $this->process->splitLines($output);
  17897. $this->rootIdentifier = $output[0];
  17898. }
  17899. return $this->rootIdentifier;
  17900. }
  17901. public function getUrl()
  17902. {
  17903. return $this->url;
  17904. }
  17905. public function getSource($identifier)
  17906. {
  17907. return array('type' => 'hg', 'url' => $this->getUrl(), 'reference' => $identifier);
  17908. }
  17909. public function getDist($identifier)
  17910. {
  17911. return null;
  17912. }
  17913. public function getComposerInformation($identifier)
  17914. {
  17915. if (!isset($this->infoCache[$identifier])) {
  17916. $this->process->execute(sprintf('hg cat -r %s composer.json', ProcessExecutor::escape($identifier)), $composer, $this->repoDir);
  17917. if (!trim($composer)) {
  17918. return;
  17919. }
  17920. $composer = JsonFile::parseJson($composer, $identifier);
  17921. if (empty($composer['time'])) {
  17922. $this->process->execute(sprintf('hg log --template "{date|rfc3339date}" -r %s', ProcessExecutor::escape($identifier)), $output, $this->repoDir);
  17923. $date = new \DateTime(trim($output), new \DateTimeZone('UTC'));
  17924. $composer['time'] = $date->format('Y-m-d H:i:s');
  17925. }
  17926. $this->infoCache[$identifier] = $composer;
  17927. }
  17928. return $this->infoCache[$identifier];
  17929. }
  17930. public function getTags()
  17931. {
  17932. if (null === $this->tags) {
  17933. $tags = array();
  17934. $this->process->execute('hg tags', $output, $this->repoDir);
  17935. foreach ($this->process->splitLines($output) as $tag) {
  17936. if ($tag && preg_match('(^([^\s]+)\s+\d+:(.*)$)', $tag, $match)) {
  17937. $tags[$match[1]] = $match[2];
  17938. }
  17939. }
  17940. unset($tags['tip']);
  17941. $this->tags = $tags;
  17942. }
  17943. return $this->tags;
  17944. }
  17945. public function getBranches()
  17946. {
  17947. if (null === $this->branches) {
  17948. $branches = array();
  17949. $bookmarks = array();
  17950. $this->process->execute('hg branches', $output, $this->repoDir);
  17951. foreach ($this->process->splitLines($output) as $branch) {
  17952. if ($branch && preg_match('(^([^\s]+)\s+\d+:([a-f0-9]+))', $branch, $match)) {
  17953. $branches[$match[1]] = $match[2];
  17954. }
  17955. }
  17956. $this->process->execute('hg bookmarks', $output, $this->repoDir);
  17957. foreach ($this->process->splitLines($output) as $branch) {
  17958. if ($branch && preg_match('(^(?:[\s*]*)([^\s]+)\s+\d+:(.*)$)', $branch, $match)) {
  17959. $bookmarks[$match[1]] = $match[2];
  17960. }
  17961. }
  17962. $this->branches = array_merge($bookmarks, $branches);
  17963. }
  17964. return $this->branches;
  17965. }
  17966. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  17967. {
  17968. if (preg_match('#(^(?:https?|ssh)://(?:[^@]@)?bitbucket.org|https://(?:.*?)\.kilnhg.com)#i', $url)) {
  17969. return true;
  17970. }
  17971. if (Filesystem::isLocalPath($url)) {
  17972. $url = Filesystem::getPlatformPath($url);
  17973. if (!is_dir($url)) {
  17974. return false;
  17975. }
  17976. $process = new ProcessExecutor();
  17977. if ($process->execute('hg summary', $output, $url) === 0) {
  17978. return true;
  17979. }
  17980. }
  17981. if (!$deep) {
  17982. return false;
  17983. }
  17984. $processExecutor = new ProcessExecutor();
  17985. $exit = $processExecutor->execute(sprintf('hg identify %s', ProcessExecutor::escape($url)), $ignored);
  17986. return $exit === 0;
  17987. }
  17988. }
  17989. <?php
  17990. namespace Composer\Repository\Vcs;
  17991. use Composer\Config;
  17992. use Composer\IO\IOInterface;
  17993. use Composer\Util\ProcessExecutor;
  17994. use Composer\Util\Perforce;
  17995. class PerforceDriver extends VcsDriver
  17996. {
  17997. protected $depot;
  17998. protected $branch;
  17999. protected $perforce;
  18000. protected $composerInfo;
  18001. protected $composerInfoIdentifier;
  18002. public function initialize()
  18003. {
  18004. $this->depot = $this->repoConfig['depot'];
  18005. $this->branch = '';
  18006. if (!empty($this->repoConfig['branch'])) {
  18007. $this->branch = $this->repoConfig['branch'];
  18008. }
  18009. $this->initPerforce($this->repoConfig);
  18010. $this->perforce->p4Login($this->io);
  18011. $this->perforce->checkStream($this->depot);
  18012. $this->perforce->writeP4ClientSpec();
  18013. $this->perforce->connectClient();
  18014. return true;
  18015. }
  18016. private function initPerforce($repoConfig)
  18017. {
  18018. if (!empty($this->perforce)) {
  18019. return;
  18020. }
  18021. $repoDir = $this->config->get('cache-vcs-dir') . '/' . $this->depot;
  18022. $this->perforce = Perforce::create($repoConfig, $this->getUrl(), $repoDir, $this->process, $this->io);
  18023. }
  18024. public function getComposerInformation($identifier)
  18025. {
  18026. if (!empty($this->composerInfoIdentifier)) {
  18027. if (strcmp($identifier, $this->composerInfoIdentifier) === 0) {
  18028. return $this->composerInfo;
  18029. }
  18030. }
  18031. $composer_info = $this->perforce->getComposerInformation($identifier);
  18032. return $composer_info;
  18033. }
  18034. public function getRootIdentifier()
  18035. {
  18036. return $this->branch;
  18037. }
  18038. public function getBranches()
  18039. {
  18040. $branches = $this->perforce->getBranches();
  18041. return $branches;
  18042. }
  18043. public function getTags()
  18044. {
  18045. $tags = $this->perforce->getTags();
  18046. return $tags;
  18047. }
  18048. public function getDist($identifier)
  18049. {
  18050. return null;
  18051. }
  18052. public function getSource($identifier)
  18053. {
  18054. $source = array(
  18055. 'type' => 'perforce',
  18056. 'url' => $this->repoConfig['url'],
  18057. 'reference' => $identifier,
  18058. 'p4user' => $this->perforce->getUser()
  18059. );
  18060. return $source;
  18061. }
  18062. public function getUrl()
  18063. {
  18064. return $this->url;
  18065. }
  18066. public function hasComposerFile($identifier)
  18067. {
  18068. $this->composerInfo = $this->perforce->getComposerInformation('//' . $this->depot . '/' . $identifier);
  18069. $this->composerInfoIdentifier = $identifier;
  18070. return !empty($this->composerInfo);
  18071. }
  18072. public function getContents($url)
  18073. {
  18074. return false;
  18075. }
  18076. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  18077. {
  18078. if ($deep || preg_match('#\b(perforce|p4)\b#i', $url)) {
  18079. return Perforce::checkServerExists($url, new ProcessExecutor($io));
  18080. }
  18081. return false;
  18082. }
  18083. public function cleanup()
  18084. {
  18085. $this->perforce->cleanupClientSpec();
  18086. $this->perforce = null;
  18087. }
  18088. public function getDepot()
  18089. {
  18090. return $this->depot;
  18091. }
  18092. public function getBranch()
  18093. {
  18094. return $this->branch;
  18095. }
  18096. }
  18097. <?php
  18098. namespace Composer\Repository\Vcs;
  18099. use Composer\Cache;
  18100. use Composer\Config;
  18101. use Composer\Json\JsonFile;
  18102. use Composer\Util\ProcessExecutor;
  18103. use Composer\Util\Filesystem;
  18104. use Composer\Util\Svn as SvnUtil;
  18105. use Composer\IO\IOInterface;
  18106. use Composer\Downloader\TransportException;
  18107. class SvnDriver extends VcsDriver
  18108. {
  18109. protected $cache;
  18110. protected $baseUrl;
  18111. protected $tags;
  18112. protected $branches;
  18113. protected $rootIdentifier;
  18114. protected $infoCache = array();
  18115. protected $trunkPath = 'trunk';
  18116. protected $branchesPath = 'branches';
  18117. protected $tagsPath = 'tags';
  18118. protected $packagePath = '';
  18119. protected $cacheCredentials = true;
  18120. private $util;
  18121. public function initialize()
  18122. {
  18123. $this->url = $this->baseUrl = rtrim(self::normalizeUrl($this->url), '/');
  18124. SvnUtil::cleanEnv();
  18125. if (isset($this->repoConfig['trunk-path'])) {
  18126. $this->trunkPath = $this->repoConfig['trunk-path'];
  18127. }
  18128. if (isset($this->repoConfig['branches-path'])) {
  18129. $this->branchesPath = $this->repoConfig['branches-path'];
  18130. }
  18131. if (isset($this->repoConfig['tags-path'])) {
  18132. $this->tagsPath = $this->repoConfig['tags-path'];
  18133. }
  18134. if (array_key_exists('svn-cache-credentials', $this->repoConfig)) {
  18135. $this->cacheCredentials = (bool) $this->repoConfig['svn-cache-credentials'];
  18136. }
  18137. if (isset($this->repoConfig['package-path'])) {
  18138. $this->packagePath = '/' . trim($this->repoConfig['package-path'], '/');
  18139. }
  18140. if (false !== ($pos = strrpos($this->url, '/' . $this->trunkPath))) {
  18141. $this->baseUrl = substr($this->url, 0, $pos);
  18142. }
  18143. $this->cache = new Cache($this->io, $this->config->get('cache-repo-dir').'/'.preg_replace('{[^a-z0-9.]}i', '-', $this->baseUrl));
  18144. $this->getBranches();
  18145. $this->getTags();
  18146. }
  18147. public function getRootIdentifier()
  18148. {
  18149. return $this->rootIdentifier ?: $this->trunkPath;
  18150. }
  18151. public function getUrl()
  18152. {
  18153. return $this->url;
  18154. }
  18155. public function getSource($identifier)
  18156. {
  18157. return array('type' => 'svn', 'url' => $this->baseUrl, 'reference' => $identifier);
  18158. }
  18159. public function getDist($identifier)
  18160. {
  18161. return null;
  18162. }
  18163. public function getComposerInformation($identifier)
  18164. {
  18165. $identifier = '/' . trim($identifier, '/') . '/';
  18166. if ($res = $this->cache->read($identifier.'.json')) {
  18167. $this->infoCache[$identifier] = JsonFile::parseJson($res);
  18168. }
  18169. if (!isset($this->infoCache[$identifier])) {
  18170. preg_match('{^(.+?)(@\d+)?/$}', $identifier, $match);
  18171. if (!empty($match[2])) {
  18172. $path = $match[1];
  18173. $rev = $match[2];
  18174. } else {
  18175. $path = $identifier;
  18176. $rev = '';
  18177. }
  18178. try {
  18179. $resource = $path.'composer.json';
  18180. $output = $this->execute('svn cat', $this->baseUrl . $resource . $rev);
  18181. if (!trim($output)) {
  18182. return;
  18183. }
  18184. } catch (\RuntimeException $e) {
  18185. throw new TransportException($e->getMessage());
  18186. }
  18187. $composer = JsonFile::parseJson($output, $this->baseUrl . $resource . $rev);
  18188. if (empty($composer['time'])) {
  18189. $output = $this->execute('svn info', $this->baseUrl . $path . $rev);
  18190. foreach ($this->process->splitLines($output) as $line) {
  18191. if ($line && preg_match('{^Last Changed Date: ([^(]+)}', $line, $match)) {
  18192. $date = new \DateTime($match[1], new \DateTimeZone('UTC'));
  18193. $composer['time'] = $date->format('Y-m-d H:i:s');
  18194. break;
  18195. }
  18196. }
  18197. }
  18198. $this->cache->write($identifier.'.json', json_encode($composer));
  18199. $this->infoCache[$identifier] = $composer;
  18200. }
  18201. return $this->infoCache[$identifier];
  18202. }
  18203. public function getTags()
  18204. {
  18205. if (null === $this->tags) {
  18206. $this->tags = array();
  18207. if ($this->tagsPath !== false) {
  18208. $output = $this->execute('svn ls --verbose', $this->baseUrl . '/' . $this->tagsPath);
  18209. if ($output) {
  18210. foreach ($this->process->splitLines($output) as $line) {
  18211. $line = trim($line);
  18212. if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) {
  18213. if (isset($match[1]) && isset($match[2]) && $match[2] !== './') {
  18214. $this->tags[rtrim($match[2], '/')] = $this->buildIdentifier(
  18215. '/' . $this->tagsPath . '/' . $match[2],
  18216. $match[1]
  18217. );
  18218. }
  18219. }
  18220. }
  18221. }
  18222. }
  18223. }
  18224. return $this->tags;
  18225. }
  18226. public function getBranches()
  18227. {
  18228. if (null === $this->branches) {
  18229. $this->branches = array();
  18230. if (false === $this->trunkPath) {
  18231. $trunkParent = $this->baseUrl . '/';
  18232. } else {
  18233. $trunkParent = $this->baseUrl . '/' . $this->trunkPath;
  18234. }
  18235. $output = $this->execute('svn ls --verbose', $trunkParent);
  18236. if ($output) {
  18237. foreach ($this->process->splitLines($output) as $line) {
  18238. $line = trim($line);
  18239. if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) {
  18240. if (isset($match[1]) && isset($match[2]) && $match[2] === './') {
  18241. $this->branches['trunk'] = $this->buildIdentifier(
  18242. '/' . $this->trunkPath,
  18243. $match[1]
  18244. );
  18245. $this->rootIdentifier = $this->branches['trunk'];
  18246. break;
  18247. }
  18248. }
  18249. }
  18250. }
  18251. unset($output);
  18252. if ($this->branchesPath !== false) {
  18253. $output = $this->execute('svn ls --verbose', $this->baseUrl . '/' . $this->branchesPath);
  18254. if ($output) {
  18255. foreach ($this->process->splitLines(trim($output)) as $line) {
  18256. $line = trim($line);
  18257. if ($line && preg_match('{^\s*(\S+).*?(\S+)\s*$}', $line, $match)) {
  18258. if (isset($match[1]) && isset($match[2]) && $match[2] !== './') {
  18259. $this->branches[rtrim($match[2], '/')] = $this->buildIdentifier(
  18260. '/' . $this->branchesPath . '/' . $match[2],
  18261. $match[1]
  18262. );
  18263. }
  18264. }
  18265. }
  18266. }
  18267. }
  18268. }
  18269. return $this->branches;
  18270. }
  18271. public static function supports(IOInterface $io, Config $config, $url, $deep = false)
  18272. {
  18273. $url = self::normalizeUrl($url);
  18274. if (preg_match('#(^svn://|^svn\+ssh://|svn\.)#i', $url)) {
  18275. return true;
  18276. }
  18277. if (!$deep && !Filesystem::isLocalPath($url)) {
  18278. return false;
  18279. }
  18280. $processExecutor = new ProcessExecutor();
  18281. $exit = $processExecutor->execute(
  18282. "svn info --non-interactive {$url}",
  18283. $ignoredOutput
  18284. );
  18285. if ($exit === 0) {
  18286. return true;
  18287. }
  18288. if (false !== stripos($processExecutor->getErrorOutput(), 'authorization failed:')) {
  18289. return true;
  18290. }
  18291. return false;
  18292. }
  18293. protected static function normalizeUrl($url)
  18294. {
  18295. $fs = new Filesystem();
  18296. if ($fs->isAbsolutePath($url)) {
  18297. return 'file://' . strtr($url, '\\', '/');
  18298. }
  18299. return $url;
  18300. }
  18301. protected function execute($command, $url)
  18302. {
  18303. if (null === $this->util) {
  18304. $this->util = new SvnUtil($this->baseUrl, $this->io, $this->config, $this->process);
  18305. $this->util->setCacheCredentials($this->cacheCredentials);
  18306. }
  18307. try {
  18308. return $this->util->execute($command, $url);
  18309. } catch (\RuntimeException $e) {
  18310. if (0 !== $this->process->execute('svn --version', $ignoredOutput)) {
  18311. throw new \RuntimeException('Failed to load '.$this->url.', svn was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  18312. }
  18313. throw new \RuntimeException(
  18314. 'Repository '.$this->url.' could not be processed, '.$e->getMessage()
  18315. );
  18316. }
  18317. }
  18318. protected function buildIdentifier($baseDir, $revision)
  18319. {
  18320. return rtrim($baseDir, '/') . $this->packagePath . '/@' . $revision;
  18321. }
  18322. }
  18323. <?php
  18324. namespace Composer\Repository\Vcs;
  18325. use Composer\Downloader\TransportException;
  18326. use Composer\Config;
  18327. use Composer\IO\IOInterface;
  18328. use Composer\Util\ProcessExecutor;
  18329. use Composer\Util\RemoteFilesystem;
  18330. use Composer\Util\Filesystem;
  18331. abstract class VcsDriver implements VcsDriverInterface
  18332. {
  18333. protected $url;
  18334. protected $originUrl;
  18335. protected $repoConfig;
  18336. protected $io;
  18337. protected $config;
  18338. protected $process;
  18339. protected $remoteFilesystem;
  18340. final public function __construct(array $repoConfig, IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null)
  18341. {
  18342. if (Filesystem::isLocalPath($repoConfig['url'])) {
  18343. $repoConfig['url'] = Filesystem::getPlatformPath($repoConfig['url']);
  18344. }
  18345. $this->url = $repoConfig['url'];
  18346. $this->originUrl = $repoConfig['url'];
  18347. $this->repoConfig = $repoConfig;
  18348. $this->io = $io;
  18349. $this->config = $config;
  18350. $this->process = $process ?: new ProcessExecutor($io);
  18351. $this->remoteFilesystem = $remoteFilesystem ?: new RemoteFilesystem($io, $config);
  18352. }
  18353. public function hasComposerFile($identifier)
  18354. {
  18355. try {
  18356. return (bool) $this->getComposerInformation($identifier);
  18357. } catch (TransportException $e) {
  18358. }
  18359. return false;
  18360. }
  18361. protected function getScheme()
  18362. {
  18363. if (extension_loaded('openssl')) {
  18364. return 'https';
  18365. }
  18366. return 'http';
  18367. }
  18368. protected function getContents($url)
  18369. {
  18370. return $this->remoteFilesystem->getContents($this->originUrl, $url, false);
  18371. }
  18372. public function cleanup()
  18373. {
  18374. return;
  18375. }
  18376. }
  18377. <?php
  18378. namespace Composer\Repository\Vcs;
  18379. use Composer\Config;
  18380. use Composer\IO\IOInterface;
  18381. interface VcsDriverInterface
  18382. {
  18383. public function initialize();
  18384. public function getComposerInformation($identifier);
  18385. public function getRootIdentifier();
  18386. public function getBranches();
  18387. public function getTags();
  18388. public function getDist($identifier);
  18389. public function getSource($identifier);
  18390. public function getUrl();
  18391. public function hasComposerFile($identifier);
  18392. public function cleanup();
  18393. public static function supports(IOInterface $io, Config $config, $url, $deep = false);
  18394. }
  18395. <?php
  18396. namespace Composer\Repository;
  18397. use Composer\Downloader\TransportException;
  18398. use Composer\Repository\Vcs\VcsDriverInterface;
  18399. use Composer\Package\Version\VersionParser;
  18400. use Composer\Package\Loader\ArrayLoader;
  18401. use Composer\Package\Loader\ValidatingArrayLoader;
  18402. use Composer\Package\Loader\InvalidPackageException;
  18403. use Composer\Package\Loader\LoaderInterface;
  18404. use Composer\EventDispatcher\EventDispatcher;
  18405. use Composer\IO\IOInterface;
  18406. use Composer\Config;
  18407. class VcsRepository extends ArrayRepository
  18408. {
  18409. protected $url;
  18410. protected $packageName;
  18411. protected $verbose;
  18412. protected $io;
  18413. protected $config;
  18414. protected $versionParser;
  18415. protected $type;
  18416. protected $loader;
  18417. protected $repoConfig;
  18418. protected $branchErrorOccurred = false;
  18419. public function __construct(array $repoConfig, IOInterface $io, Config $config, EventDispatcher $dispatcher = null, array $drivers = null)
  18420. {
  18421. $this->drivers = $drivers ?: array(
  18422. 'github' => 'Composer\Repository\Vcs\GitHubDriver',
  18423. 'gitlab' => 'Composer\Repository\Vcs\GitLabDriver',
  18424. 'git-bitbucket' => 'Composer\Repository\Vcs\GitBitbucketDriver',
  18425. 'git' => 'Composer\Repository\Vcs\GitDriver',
  18426. 'hg-bitbucket' => 'Composer\Repository\Vcs\HgBitbucketDriver',
  18427. 'hg' => 'Composer\Repository\Vcs\HgDriver',
  18428. 'perforce' => 'Composer\Repository\Vcs\PerforceDriver',
  18429. 'svn' => 'Composer\Repository\Vcs\SvnDriver',
  18430. );
  18431. $this->url = $repoConfig['url'];
  18432. $this->io = $io;
  18433. $this->type = isset($repoConfig['type']) ? $repoConfig['type'] : 'vcs';
  18434. $this->verbose = $io->isVerbose();
  18435. $this->config = $config;
  18436. $this->repoConfig = $repoConfig;
  18437. }
  18438. public function getRepoConfig()
  18439. {
  18440. return $this->repoConfig;
  18441. }
  18442. public function setLoader(LoaderInterface $loader)
  18443. {
  18444. $this->loader = $loader;
  18445. }
  18446. public function getDriver()
  18447. {
  18448. if (isset($this->drivers[$this->type])) {
  18449. $class = $this->drivers[$this->type];
  18450. $driver = new $class($this->repoConfig, $this->io, $this->config);
  18451. $driver->initialize();
  18452. return $driver;
  18453. }
  18454. foreach ($this->drivers as $driver) {
  18455. if ($driver::supports($this->io, $this->config, $this->url)) {
  18456. $driver = new $driver($this->repoConfig, $this->io, $this->config);
  18457. $driver->initialize();
  18458. return $driver;
  18459. }
  18460. }
  18461. foreach ($this->drivers as $driver) {
  18462. if ($driver::supports($this->io, $this->config, $this->url, true)) {
  18463. $driver = new $driver($this->repoConfig, $this->io, $this->config);
  18464. $driver->initialize();
  18465. return $driver;
  18466. }
  18467. }
  18468. }
  18469. public function hadInvalidBranches()
  18470. {
  18471. return $this->branchErrorOccurred;
  18472. }
  18473. protected function initialize()
  18474. {
  18475. parent::initialize();
  18476. $verbose = $this->verbose;
  18477. $driver = $this->getDriver();
  18478. if (!$driver) {
  18479. throw new \InvalidArgumentException('No driver found to handle VCS repository '.$this->url);
  18480. }
  18481. $this->versionParser = new VersionParser;
  18482. if (!$this->loader) {
  18483. $this->loader = new ArrayLoader($this->versionParser);
  18484. }
  18485. try {
  18486. if ($driver->hasComposerFile($driver->getRootIdentifier())) {
  18487. $data = $driver->getComposerInformation($driver->getRootIdentifier());
  18488. $this->packageName = !empty($data['name']) ? $data['name'] : null;
  18489. }
  18490. } catch (\Exception $e) {
  18491. if ($verbose) {
  18492. $this->io->writeError('<error>Skipped parsing '.$driver->getRootIdentifier().', '.$e->getMessage().'</error>');
  18493. }
  18494. }
  18495. foreach ($driver->getTags() as $tag => $identifier) {
  18496. $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $tag . '</comment>)';
  18497. if ($verbose) {
  18498. $this->io->writeError($msg);
  18499. } else {
  18500. $this->io->overwriteError($msg, false);
  18501. }
  18502. $tag = str_replace('release-', '', $tag);
  18503. if (!$parsedTag = $this->validateTag($tag)) {
  18504. if ($verbose) {
  18505. $this->io->writeError('<warning>Skipped tag '.$tag.', invalid tag name</warning>');
  18506. }
  18507. continue;
  18508. }
  18509. try {
  18510. if (!$data = $driver->getComposerInformation($identifier)) {
  18511. if ($verbose) {
  18512. $this->io->writeError('<warning>Skipped tag '.$tag.', no composer file</warning>');
  18513. }
  18514. continue;
  18515. }
  18516. if (isset($data['version'])) {
  18517. $data['version_normalized'] = $this->versionParser->normalize($data['version']);
  18518. } else {
  18519. $data['version'] = $tag;
  18520. $data['version_normalized'] = $parsedTag;
  18521. }
  18522. $data['version'] = preg_replace('{[.-]?dev$}i', '', $data['version']);
  18523. $data['version_normalized'] = preg_replace('{(^dev-|[.-]?dev$)}i', '', $data['version_normalized']);
  18524. if ($data['version_normalized'] !== $parsedTag) {
  18525. if ($verbose) {
  18526. $this->io->writeError('<warning>Skipped tag '.$tag.', tag ('.$parsedTag.') does not match version ('.$data['version_normalized'].') in composer.json</warning>');
  18527. }
  18528. continue;
  18529. }
  18530. if ($verbose) {
  18531. $this->io->writeError('Importing tag '.$tag.' ('.$data['version_normalized'].')');
  18532. }
  18533. $this->addPackage($this->loader->load($this->preProcess($driver, $data, $identifier)));
  18534. } catch (\Exception $e) {
  18535. if ($verbose) {
  18536. $this->io->writeError('<warning>Skipped tag '.$tag.', '.($e instanceof TransportException ? 'no composer file was found' : $e->getMessage()).'</warning>');
  18537. }
  18538. continue;
  18539. }
  18540. }
  18541. if (!$verbose) {
  18542. $this->io->overwriteError('', false);
  18543. }
  18544. foreach ($driver->getBranches() as $branch => $identifier) {
  18545. $msg = 'Reading composer.json of <info>' . ($this->packageName ?: $this->url) . '</info> (<comment>' . $branch . '</comment>)';
  18546. if ($verbose) {
  18547. $this->io->writeError($msg);
  18548. } else {
  18549. $this->io->overwriteError($msg, false);
  18550. }
  18551. if (!$parsedBranch = $this->validateBranch($branch)) {
  18552. if ($verbose) {
  18553. $this->io->writeError('<warning>Skipped branch '.$branch.', invalid name</warning>');
  18554. }
  18555. continue;
  18556. }
  18557. try {
  18558. if (!$data = $driver->getComposerInformation($identifier)) {
  18559. if ($verbose) {
  18560. $this->io->writeError('<warning>Skipped branch '.$branch.', no composer file</warning>');
  18561. }
  18562. continue;
  18563. }
  18564. $data['version'] = $branch;
  18565. $data['version_normalized'] = $parsedBranch;
  18566. if ('dev-' === substr($parsedBranch, 0, 4) || '9999999-dev' === $parsedBranch) {
  18567. $data['version'] = 'dev-' . $data['version'];
  18568. } else {
  18569. $data['version'] = preg_replace('{(\.9{7})+}', '.x', $parsedBranch);
  18570. }
  18571. if ($verbose) {
  18572. $this->io->writeError('Importing branch '.$branch.' ('.$data['version'].')');
  18573. }
  18574. $packageData = $this->preProcess($driver, $data, $identifier);
  18575. $package = $this->loader->load($packageData);
  18576. if ($this->loader instanceof ValidatingArrayLoader && $this->loader->getWarnings()) {
  18577. throw new InvalidPackageException($this->loader->getErrors(), $this->loader->getWarnings(), $packageData);
  18578. }
  18579. $this->addPackage($package);
  18580. } catch (TransportException $e) {
  18581. if ($verbose) {
  18582. $this->io->writeError('<warning>Skipped branch '.$branch.', no composer file was found</warning>');
  18583. }
  18584. continue;
  18585. } catch (\Exception $e) {
  18586. if (!$verbose) {
  18587. $this->io->writeError('');
  18588. }
  18589. $this->branchErrorOccurred = true;
  18590. $this->io->writeError('<error>Skipped branch '.$branch.', '.$e->getMessage().'</error>');
  18591. $this->io->writeError('');
  18592. continue;
  18593. }
  18594. }
  18595. $driver->cleanup();
  18596. if (!$verbose) {
  18597. $this->io->overwriteError('', false);
  18598. }
  18599. if (!$this->getPackages()) {
  18600. throw new InvalidRepositoryException('No valid composer.json was found in any branch or tag of '.$this->url.', could not load a package from it.');
  18601. }
  18602. }
  18603. protected function preProcess(VcsDriverInterface $driver, array $data, $identifier)
  18604. {
  18605. $data['name'] = $this->packageName ?: $data['name'];
  18606. if (!isset($data['dist'])) {
  18607. $data['dist'] = $driver->getDist($identifier);
  18608. }
  18609. if (!isset($data['source'])) {
  18610. $data['source'] = $driver->getSource($identifier);
  18611. }
  18612. return $data;
  18613. }
  18614. private function validateBranch($branch)
  18615. {
  18616. try {
  18617. return $this->versionParser->normalizeBranch($branch);
  18618. } catch (\Exception $e) {
  18619. }
  18620. return false;
  18621. }
  18622. private function validateTag($version)
  18623. {
  18624. try {
  18625. return $this->versionParser->normalize($version);
  18626. } catch (\Exception $e) {
  18627. }
  18628. return false;
  18629. }
  18630. }
  18631. <?php
  18632. namespace Composer\Repository;
  18633. use Composer\Package\AliasPackage;
  18634. class WritableArrayRepository extends ArrayRepository implements WritableRepositoryInterface
  18635. {
  18636. public function write()
  18637. {
  18638. }
  18639. public function reload()
  18640. {
  18641. }
  18642. public function getCanonicalPackages()
  18643. {
  18644. $packages = $this->getPackages();
  18645. $packagesByName = array();
  18646. foreach ($packages as $package) {
  18647. if (!isset($packagesByName[$package->getName()]) || $packagesByName[$package->getName()] instanceof AliasPackage) {
  18648. $packagesByName[$package->getName()] = $package;
  18649. }
  18650. }
  18651. $canonicalPackages = array();
  18652. foreach ($packagesByName as $package) {
  18653. while ($package instanceof AliasPackage) {
  18654. $package = $package->getAliasOf();
  18655. }
  18656. $canonicalPackages[] = $package;
  18657. }
  18658. return $canonicalPackages;
  18659. }
  18660. }
  18661. <?php
  18662. namespace Composer\Repository;
  18663. use Composer\Package\PackageInterface;
  18664. interface WritableRepositoryInterface extends RepositoryInterface
  18665. {
  18666. public function write();
  18667. public function addPackage(PackageInterface $package);
  18668. public function removePackage(PackageInterface $package);
  18669. public function getCanonicalPackages();
  18670. public function reload();
  18671. }
  18672. <?php
  18673. namespace Composer\Script;
  18674. class CommandEvent extends Event
  18675. {
  18676. }
  18677. <?php
  18678. namespace Composer\Script;
  18679. use Composer\Composer;
  18680. use Composer\IO\IOInterface;
  18681. use Composer\EventDispatcher\Event as BaseEvent;
  18682. class Event extends BaseEvent
  18683. {
  18684. private $composer;
  18685. private $io;
  18686. private $devMode;
  18687. public function __construct($name, Composer $composer, IOInterface $io, $devMode = false, array $args = array(), array $flags = array())
  18688. {
  18689. parent::__construct($name, $args, $flags);
  18690. $this->composer = $composer;
  18691. $this->io = $io;
  18692. $this->devMode = $devMode;
  18693. }
  18694. public function getComposer()
  18695. {
  18696. return $this->composer;
  18697. }
  18698. public function getIO()
  18699. {
  18700. return $this->io;
  18701. }
  18702. public function isDevMode()
  18703. {
  18704. return $this->devMode;
  18705. }
  18706. }
  18707. <?php
  18708. namespace Composer\Script;
  18709. use Composer\Installer\PackageEvent as BasePackageEvent;
  18710. class PackageEvent extends BasePackageEvent
  18711. {
  18712. }
  18713. <?php
  18714. namespace Composer\Script;
  18715. class ScriptEvents
  18716. {
  18717. const PRE_INSTALL_CMD = 'pre-install-cmd';
  18718. const POST_INSTALL_CMD = 'post-install-cmd';
  18719. const PRE_UPDATE_CMD = 'pre-update-cmd';
  18720. const POST_UPDATE_CMD = 'post-update-cmd';
  18721. const PRE_STATUS_CMD = 'pre-status-cmd';
  18722. const POST_STATUS_CMD = 'post-status-cmd';
  18723. const PRE_AUTOLOAD_DUMP = 'pre-autoload-dump';
  18724. const POST_AUTOLOAD_DUMP = 'post-autoload-dump';
  18725. const POST_ROOT_PACKAGE_INSTALL = 'post-root-package-install';
  18726. const POST_CREATE_PROJECT_CMD = 'post-create-project-cmd';
  18727. const PRE_ARCHIVE_CMD = 'pre-archive-cmd';
  18728. const POST_ARCHIVE_CMD = 'post-archive-cmd';
  18729. const PRE_PACKAGE_INSTALL = 'pre-package-install';
  18730. const POST_PACKAGE_INSTALL = 'post-package-install';
  18731. const PRE_PACKAGE_UPDATE = 'pre-package-update';
  18732. const POST_PACKAGE_UPDATE = 'post-package-update';
  18733. const PRE_PACKAGE_UNINSTALL = 'pre-package-uninstall';
  18734. const POST_PACKAGE_UNINSTALL = 'post-package-uninstall';
  18735. }
  18736. <?php
  18737. namespace Composer\Util;
  18738. use Composer\Config;
  18739. use Composer\IO\IOInterface;
  18740. class AuthHelper
  18741. {
  18742. protected $io;
  18743. protected $config;
  18744. public function __construct(IOInterface $io, Config $config)
  18745. {
  18746. $this->io = $io;
  18747. $this->config = $config;
  18748. }
  18749. public function storeAuth($originUrl, $storeAuth)
  18750. {
  18751. $store = false;
  18752. $configSource = $this->config->getAuthConfigSource();
  18753. if ($storeAuth === true) {
  18754. $store = $configSource;
  18755. } elseif ($storeAuth === 'prompt') {
  18756. $answer = $this->io->askAndValidate(
  18757. 'Do you want to store credentials for '.$originUrl.' in '.$configSource->getName().' ? [Yn] ',
  18758. function ($value) {
  18759. $input = strtolower(substr(trim($value), 0, 1));
  18760. if (in_array($input, array('y','n'))) {
  18761. return $input;
  18762. }
  18763. throw new \RuntimeException('Please answer (y)es or (n)o');
  18764. },
  18765. false,
  18766. 'y'
  18767. );
  18768. if ($answer === 'y') {
  18769. $store = $configSource;
  18770. }
  18771. }
  18772. if ($store) {
  18773. $store->addConfigSetting(
  18774. 'http-basic.'.$originUrl,
  18775. $this->io->getAuthentication($originUrl)
  18776. );
  18777. }
  18778. }
  18779. }
  18780. <?php
  18781. namespace Composer\Util;
  18782. class ComposerMirror
  18783. {
  18784. public static function processUrl($mirrorUrl, $packageName, $version, $reference, $type)
  18785. {
  18786. if ($reference) {
  18787. $reference = preg_match('{^([a-f0-9]*|%reference%)$}', $reference) ? $reference : md5($reference);
  18788. }
  18789. $version = strpos($version, '/') === false ? $version : md5($version);
  18790. return str_replace(
  18791. array('%package%', '%version%', '%reference%', '%type%'),
  18792. array($packageName, $version, $reference, $type),
  18793. $mirrorUrl
  18794. );
  18795. }
  18796. public static function processGitUrl($mirrorUrl, $packageName, $url, $type)
  18797. {
  18798. if (preg_match('#^(?:(?:https?|git)://github\.com/|git@github\.com:)([^/]+)/(.+?)(?:\.git)?$#', $url, $match)) {
  18799. $url = 'gh-'.$match[1].'/'.$match[2];
  18800. } elseif (preg_match('#^https://bitbucket\.org/([^/]+)/(.+?)(?:\.git)?/?$#', $url, $match)) {
  18801. $url = 'bb-'.$match[1].'/'.$match[2];
  18802. } else {
  18803. $url = preg_replace('{[^a-z0-9_.-]}i', '-', trim($url, '/'));
  18804. }
  18805. return str_replace(
  18806. array('%package%', '%normalizedUrl%', '%type%'),
  18807. array($packageName, $url, $type),
  18808. $mirrorUrl
  18809. );
  18810. }
  18811. public static function processHgUrl($mirrorUrl, $packageName, $url, $type)
  18812. {
  18813. return self::processGitUrl($mirrorUrl, $packageName, $url, $type);
  18814. }
  18815. }
  18816. <?php
  18817. namespace Composer\Util;
  18818. use Composer\Package\Loader\ArrayLoader;
  18819. use Composer\Package\Loader\ValidatingArrayLoader;
  18820. use Composer\Package\Loader\InvalidPackageException;
  18821. use Composer\Json\JsonValidationException;
  18822. use Composer\IO\IOInterface;
  18823. use Composer\Json\JsonFile;
  18824. class ConfigValidator
  18825. {
  18826. private $io;
  18827. public function __construct(IOInterface $io)
  18828. {
  18829. $this->io = $io;
  18830. }
  18831. public function validate($file, $arrayLoaderValidationFlags = ValidatingArrayLoader::CHECK_ALL)
  18832. {
  18833. $errors = array();
  18834. $publishErrors = array();
  18835. $warnings = array();
  18836. $laxValid = false;
  18837. try {
  18838. $json = new JsonFile($file, new RemoteFilesystem($this->io));
  18839. $manifest = $json->read();
  18840. $json->validateSchema(JsonFile::LAX_SCHEMA);
  18841. $laxValid = true;
  18842. $json->validateSchema();
  18843. } catch (JsonValidationException $e) {
  18844. foreach ($e->getErrors() as $message) {
  18845. if ($laxValid) {
  18846. $publishErrors[] = $message;
  18847. } else {
  18848. $errors[] = $message;
  18849. }
  18850. }
  18851. } catch (\Exception $e) {
  18852. $errors[] = $e->getMessage();
  18853. return array($errors, $publishErrors, $warnings);
  18854. }
  18855. if (!empty($manifest['license'])) {
  18856. if (is_array($manifest['license'])) {
  18857. foreach ($manifest['license'] as $key => $license) {
  18858. if ('proprietary' === $license) {
  18859. unset($manifest['license'][$key]);
  18860. }
  18861. }
  18862. }
  18863. $licenseValidator = new SpdxLicenseIdentifier();
  18864. if ('proprietary' !== $manifest['license'] && array() !== $manifest['license'] && !$licenseValidator->validate($manifest['license'])) {
  18865. $warnings[] = sprintf(
  18866. 'License %s is not a valid SPDX license identifier, see http://www.spdx.org/licenses/ if you use an open license.'
  18867. ."\nIf the software is closed-source, you may use \"proprietary\" as license.",
  18868. json_encode($manifest['license'])
  18869. );
  18870. }
  18871. } else {
  18872. $warnings[] = 'No license specified, it is recommended to do so. For closed-source software you may use "proprietary" as license.';
  18873. }
  18874. if (isset($manifest['version'])) {
  18875. $warnings[] = 'The version field is present, it is recommended to leave it out if the package is published on Packagist.';
  18876. }
  18877. if (!empty($manifest['name']) && preg_match('{[A-Z]}', $manifest['name'])) {
  18878. $suggestName = preg_replace('{(?:([a-z])([A-Z])|([A-Z])([A-Z][a-z]))}', '\\1\\3-\\2\\4', $manifest['name']);
  18879. $suggestName = strtolower($suggestName);
  18880. $warnings[] = sprintf(
  18881. 'Name "%s" does not match the best practice (e.g. lower-cased/with-dashes). We suggest using "%s" instead. As such you will not be able to submit it to Packagist.',
  18882. $manifest['name'],
  18883. $suggestName
  18884. );
  18885. }
  18886. if (!empty($manifest['type']) && $manifest['type'] == 'composer-installer') {
  18887. $warnings[] = "The package type 'composer-installer' is deprecated. Please distribute your custom installers as plugins from now on. See http://getcomposer.org/doc/articles/plugins.md for plugin documentation.";
  18888. }
  18889. if (isset($manifest['require']) && isset($manifest['require-dev'])) {
  18890. $requireOverrides = array_intersect_key($manifest['require'], $manifest['require-dev']);
  18891. if (!empty($requireOverrides)) {
  18892. $plural = (count($requireOverrides) > 1) ? 'are' : 'is';
  18893. $warnings[] = implode(', ', array_keys($requireOverrides)). " {$plural} required both in require and require-dev, this can lead to unexpected behavior";
  18894. }
  18895. }
  18896. try {
  18897. $loader = new ValidatingArrayLoader(new ArrayLoader(), true, null, $arrayLoaderValidationFlags);
  18898. if (!isset($manifest['version'])) {
  18899. $manifest['version'] = '1.0.0';
  18900. }
  18901. if (!isset($manifest['name'])) {
  18902. $manifest['name'] = 'dummy/dummy';
  18903. }
  18904. $loader->load($manifest);
  18905. } catch (InvalidPackageException $e) {
  18906. $errors = array_merge($errors, $e->getErrors());
  18907. }
  18908. $warnings = array_merge($warnings, $loader->getWarnings());
  18909. return array($errors, $publishErrors, $warnings);
  18910. }
  18911. }
  18912. <?php
  18913. namespace Composer\Util;
  18914. class ErrorHandler
  18915. {
  18916. public static function handle($level, $message, $file, $line)
  18917. {
  18918. if (!error_reporting()) {
  18919. return;
  18920. }
  18921. if (ini_get('xdebug.scream')) {
  18922. $message .= "\n\nWarning: You have xdebug.scream enabled, the warning above may be".
  18923. "\na legitimately suppressed error that you were not supposed to see.";
  18924. }
  18925. throw new \ErrorException($message, 0, $level, $file, $line);
  18926. }
  18927. public static function register()
  18928. {
  18929. set_error_handler(array(__CLASS__, 'handle'));
  18930. }
  18931. }
  18932. <?php
  18933. namespace Composer\Util;
  18934. use RecursiveDirectoryIterator;
  18935. use RecursiveIteratorIterator;
  18936. use Symfony\Component\Finder\Finder;
  18937. class Filesystem
  18938. {
  18939. private $processExecutor;
  18940. public function __construct(ProcessExecutor $executor = null)
  18941. {
  18942. $this->processExecutor = $executor ?: new ProcessExecutor();
  18943. }
  18944. public function remove($file)
  18945. {
  18946. if (is_dir($file)) {
  18947. return $this->removeDirectory($file);
  18948. }
  18949. if (file_exists($file)) {
  18950. return $this->unlink($file);
  18951. }
  18952. return false;
  18953. }
  18954. public function isDirEmpty($dir)
  18955. {
  18956. $finder = Finder::create()
  18957. ->ignoreVCS(false)
  18958. ->ignoreDotFiles(false)
  18959. ->depth(0)
  18960. ->in($dir);
  18961. return count($finder) === 0;
  18962. }
  18963. public function emptyDirectory($dir, $ensureDirectoryExists = true)
  18964. {
  18965. if (file_exists($dir) && is_link($dir)) {
  18966. $this->unlink($dir);
  18967. }
  18968. if ($ensureDirectoryExists) {
  18969. $this->ensureDirectoryExists($dir);
  18970. }
  18971. if (is_dir($dir)) {
  18972. $finder = Finder::create()
  18973. ->ignoreVCS(false)
  18974. ->ignoreDotFiles(false)
  18975. ->depth(0)
  18976. ->in($dir);
  18977. foreach ($finder as $path) {
  18978. $this->remove((string) $path);
  18979. }
  18980. }
  18981. }
  18982. public function removeDirectory($directory)
  18983. {
  18984. if ($this->isSymlinkedDirectory($directory)) {
  18985. return $this->unlinkSymlinkedDirectory($directory);
  18986. }
  18987. if (!file_exists($directory) || !is_dir($directory)) {
  18988. return true;
  18989. }
  18990. if (preg_match('{^(?:[a-z]:)?[/\\\\]+$}i', $directory)) {
  18991. throw new \RuntimeException('Aborting an attempted deletion of '.$directory.', this was probably not intended, if it is a real use case please report it.');
  18992. }
  18993. if (!function_exists('proc_open')) {
  18994. return $this->removeDirectoryPhp($directory);
  18995. }
  18996. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  18997. $cmd = sprintf('rmdir /S /Q %s', ProcessExecutor::escape(realpath($directory)));
  18998. } else {
  18999. $cmd = sprintf('rm -rf %s', ProcessExecutor::escape($directory));
  19000. }
  19001. $result = $this->getProcess()->execute($cmd, $output) === 0;
  19002. clearstatcache();
  19003. if ($result && !file_exists($directory)) {
  19004. return true;
  19005. }
  19006. return $this->removeDirectoryPhp($directory);
  19007. }
  19008. public function removeDirectoryPhp($directory)
  19009. {
  19010. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  19011. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  19012. foreach ($ri as $file) {
  19013. if ($file->isDir()) {
  19014. $this->rmdir($file->getPathname());
  19015. } else {
  19016. $this->unlink($file->getPathname());
  19017. }
  19018. }
  19019. return $this->rmdir($directory);
  19020. }
  19021. public function ensureDirectoryExists($directory)
  19022. {
  19023. if (!is_dir($directory)) {
  19024. if (file_exists($directory)) {
  19025. throw new \RuntimeException(
  19026. $directory.' exists and is not a directory.'
  19027. );
  19028. }
  19029. if (!@mkdir($directory, 0777, true)) {
  19030. throw new \RuntimeException(
  19031. $directory.' does not exist and could not be created.'
  19032. );
  19033. }
  19034. }
  19035. }
  19036. public function unlink($path)
  19037. {
  19038. if (!@$this->unlinkImplementation($path)) {
  19039. if (!defined('PHP_WINDOWS_VERSION_BUILD') || (usleep(350000) && !@$this->unlinkImplementation($path))) {
  19040. $error = error_get_last();
  19041. $message = 'Could not delete '.$path.': ' . @$error['message'];
  19042. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  19043. $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed";
  19044. }
  19045. throw new \RuntimeException($message);
  19046. }
  19047. }
  19048. return true;
  19049. }
  19050. public function rmdir($path)
  19051. {
  19052. if (!@rmdir($path)) {
  19053. if (!defined('PHP_WINDOWS_VERSION_BUILD') || (usleep(350000) && !@rmdir($path))) {
  19054. $error = error_get_last();
  19055. $message = 'Could not delete '.$path.': ' . @$error['message'];
  19056. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  19057. $message .= "\nThis can be due to an antivirus or the Windows Search Indexer locking the file while they are analyzed";
  19058. }
  19059. throw new \RuntimeException($message);
  19060. }
  19061. }
  19062. return true;
  19063. }
  19064. public function copyThenRemove($source, $target)
  19065. {
  19066. if (!is_dir($source)) {
  19067. copy($source, $target);
  19068. $this->unlink($source);
  19069. return;
  19070. }
  19071. $it = new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS);
  19072. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::SELF_FIRST);
  19073. $this->ensureDirectoryExists($target);
  19074. foreach ($ri as $file) {
  19075. $targetPath = $target . DIRECTORY_SEPARATOR . $ri->getSubPathName();
  19076. if ($file->isDir()) {
  19077. $this->ensureDirectoryExists($targetPath);
  19078. } else {
  19079. copy($file->getPathname(), $targetPath);
  19080. }
  19081. }
  19082. $this->removeDirectoryPhp($source);
  19083. }
  19084. public function rename($source, $target)
  19085. {
  19086. if (true === @rename($source, $target)) {
  19087. return;
  19088. }
  19089. if (!function_exists('proc_open')) {
  19090. return $this->copyThenRemove($source, $target);
  19091. }
  19092. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  19093. $command = sprintf('xcopy %s %s /E /I /Q', ProcessExecutor::escape($source), ProcessExecutor::escape($target));
  19094. $result = $this->processExecutor->execute($command, $output);
  19095. clearstatcache();
  19096. if (0 === $result) {
  19097. $this->remove($source);
  19098. return;
  19099. }
  19100. } else {
  19101. $command = sprintf('mv %s %s', ProcessExecutor::escape($source), ProcessExecutor::escape($target));
  19102. $result = $this->processExecutor->execute($command, $output);
  19103. clearstatcache();
  19104. if (0 === $result) {
  19105. return;
  19106. }
  19107. }
  19108. return $this->copyThenRemove($source, $target);
  19109. }
  19110. public function findShortestPath($from, $to, $directories = false)
  19111. {
  19112. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  19113. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  19114. }
  19115. $from = lcfirst($this->normalizePath($from));
  19116. $to = lcfirst($this->normalizePath($to));
  19117. if ($directories) {
  19118. $from .= '/dummy_file';
  19119. }
  19120. if (dirname($from) === dirname($to)) {
  19121. return './'.basename($to);
  19122. }
  19123. $commonPath = $to;
  19124. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath)) {
  19125. $commonPath = strtr(dirname($commonPath), '\\', '/');
  19126. }
  19127. if (0 !== strpos($from, $commonPath) || '/' === $commonPath) {
  19128. return $to;
  19129. }
  19130. $commonPath = rtrim($commonPath, '/') . '/';
  19131. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/');
  19132. $commonPathCode = str_repeat('../', $sourcePathDepth);
  19133. return ($commonPathCode . substr($to, strlen($commonPath))) ?: './';
  19134. }
  19135. public function findShortestPathCode($from, $to, $directories = false)
  19136. {
  19137. if (!$this->isAbsolutePath($from) || !$this->isAbsolutePath($to)) {
  19138. throw new \InvalidArgumentException(sprintf('$from (%s) and $to (%s) must be absolute paths.', $from, $to));
  19139. }
  19140. $from = lcfirst($this->normalizePath($from));
  19141. $to = lcfirst($this->normalizePath($to));
  19142. if ($from === $to) {
  19143. return $directories ? '__DIR__' : '__FILE__';
  19144. }
  19145. $commonPath = $to;
  19146. while (strpos($from.'/', $commonPath.'/') !== 0 && '/' !== $commonPath && !preg_match('{^[a-z]:/?$}i', $commonPath) && '.' !== $commonPath) {
  19147. $commonPath = strtr(dirname($commonPath), '\\', '/');
  19148. }
  19149. if (0 !== strpos($from, $commonPath) || '/' === $commonPath || '.' === $commonPath) {
  19150. return var_export($to, true);
  19151. }
  19152. $commonPath = rtrim($commonPath, '/') . '/';
  19153. if (strpos($to, $from.'/') === 0) {
  19154. return '__DIR__ . '.var_export(substr($to, strlen($from)), true);
  19155. }
  19156. $sourcePathDepth = substr_count(substr($from, strlen($commonPath)), '/') + $directories;
  19157. $commonPathCode = str_repeat('dirname(', $sourcePathDepth).'__DIR__'.str_repeat(')', $sourcePathDepth);
  19158. $relTarget = substr($to, strlen($commonPath));
  19159. return $commonPathCode . (strlen($relTarget) ? '.' . var_export('/' . $relTarget, true) : '');
  19160. }
  19161. public function isAbsolutePath($path)
  19162. {
  19163. return substr($path, 0, 1) === '/' || substr($path, 1, 1) === ':';
  19164. }
  19165. public function size($path)
  19166. {
  19167. if (!file_exists($path)) {
  19168. throw new \RuntimeException("$path does not exist.");
  19169. }
  19170. if (is_dir($path)) {
  19171. return $this->directorySize($path);
  19172. }
  19173. return filesize($path);
  19174. }
  19175. public function normalizePath($path)
  19176. {
  19177. $parts = array();
  19178. $path = strtr($path, '\\', '/');
  19179. $prefix = '';
  19180. $absolute = false;
  19181. if (preg_match('{^([0-9a-z]+:(?://(?:[a-z]:)?)?)}i', $path, $match)) {
  19182. $prefix = $match[1];
  19183. $path = substr($path, strlen($prefix));
  19184. }
  19185. if (substr($path, 0, 1) === '/') {
  19186. $absolute = true;
  19187. $path = substr($path, 1);
  19188. }
  19189. $up = false;
  19190. foreach (explode('/', $path) as $chunk) {
  19191. if ('..' === $chunk && ($absolute || $up)) {
  19192. array_pop($parts);
  19193. $up = !(empty($parts) || '..' === end($parts));
  19194. } elseif ('.' !== $chunk && '' !== $chunk) {
  19195. $parts[] = $chunk;
  19196. $up = '..' !== $chunk;
  19197. }
  19198. }
  19199. return $prefix.($absolute ? '/' : '').implode('/', $parts);
  19200. }
  19201. public static function isLocalPath($path)
  19202. {
  19203. return (bool) preg_match('{^(file://|/|[a-z]:[\\\\/]|\.\.[\\\\/]|[a-z0-9_.-]+[\\\\/])}i', $path);
  19204. }
  19205. public static function getPlatformPath($path)
  19206. {
  19207. if (defined('PHP_WINDOWS_VERSION_BUILD')) {
  19208. $path = preg_replace('{^(?:file:///([a-z])/)}i', 'file://$1:/', $path);
  19209. }
  19210. return preg_replace('{^file://}i', '', $path);
  19211. }
  19212. protected function directorySize($directory)
  19213. {
  19214. $it = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
  19215. $ri = new RecursiveIteratorIterator($it, RecursiveIteratorIterator::CHILD_FIRST);
  19216. $size = 0;
  19217. foreach ($ri as $file) {
  19218. if ($file->isFile()) {
  19219. $size += $file->getSize();
  19220. }
  19221. }
  19222. return $size;
  19223. }
  19224. protected function getProcess()
  19225. {
  19226. return new ProcessExecutor;
  19227. }
  19228. private function unlinkImplementation($path)
  19229. {
  19230. if (defined('PHP_WINDOWS_VERSION_BUILD') && is_dir($path) && is_link($path)) {
  19231. return rmdir($path);
  19232. }
  19233. return unlink($path);
  19234. }
  19235. private function isSymlinkedDirectory($directory)
  19236. {
  19237. if (!is_dir($directory)) {
  19238. return false;
  19239. }
  19240. $resolved = $this->resolveSymlinkedDirectorySymlink($directory);
  19241. return is_link($resolved);
  19242. }
  19243. private function unlinkSymlinkedDirectory($directory)
  19244. {
  19245. $resolved = $this->resolveSymlinkedDirectorySymlink($directory);
  19246. return $this->unlink($resolved);
  19247. }
  19248. private function resolveSymlinkedDirectorySymlink($pathname)
  19249. {
  19250. if (!is_dir($pathname)) {
  19251. return $pathname;
  19252. }
  19253. $resolved = rtrim($pathname, '/');
  19254. if (!strlen($resolved)) {
  19255. return $pathname;
  19256. }
  19257. return $resolved;
  19258. }
  19259. }
  19260. <?php
  19261. namespace Composer\Util;
  19262. use Composer\Config;
  19263. use Composer\IO\IOInterface;
  19264. class Git
  19265. {
  19266. protected $io;
  19267. protected $config;
  19268. protected $process;
  19269. protected $filesystem;
  19270. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process, Filesystem $fs)
  19271. {
  19272. $this->io = $io;
  19273. $this->config = $config;
  19274. $this->process = $process;
  19275. $this->filesystem = $fs;
  19276. }
  19277. public function runCommand($commandCallable, $url, $cwd, $initialClone = false)
  19278. {
  19279. if ($initialClone) {
  19280. $origCwd = $cwd;
  19281. $cwd = null;
  19282. }
  19283. if (preg_match('{^ssh://[^@]+@[^:]+:[^0-9]+}', $url)) {
  19284. throw new \InvalidArgumentException('The source URL '.$url.' is invalid, ssh URLs should have a port number after ":".'."\n".'Use ssh://git@example.com:22/path or just git@example.com:path if you do not want to provide a password or custom port.');
  19285. }
  19286. if (!$initialClone) {
  19287. $this->process->execute('git remote -v', $output, $cwd);
  19288. if (preg_match('{^(?:composer|origin)\s+https?://(.+):(.+)@([^/]+)}im', $output, $match)) {
  19289. $this->io->setAuthentication($match[3], urldecode($match[1]), urldecode($match[2]));
  19290. }
  19291. }
  19292. $protocols = $this->config->get('github-protocols');
  19293. if (!is_array($protocols)) {
  19294. throw new \RuntimeException('Config value "github-protocols" must be an array, got '.gettype($protocols));
  19295. }
  19296. if (preg_match('{^(?:https?|git)://'.self::getGitHubDomainsRegex($this->config).'/(.*)}', $url, $match)) {
  19297. $messages = array();
  19298. foreach ($protocols as $protocol) {
  19299. if ('ssh' === $protocol) {
  19300. $url = "git@" . $match[1] . ":" . $match[2];
  19301. } else {
  19302. $url = $protocol ."://" . $match[1] . "/" . $match[2];
  19303. }
  19304. if (0 === $this->process->execute(call_user_func($commandCallable, $url), $ignoredOutput, $cwd)) {
  19305. return;
  19306. }
  19307. $messages[] = '- ' . $url . "\n" . preg_replace('#^#m', ' ', $this->process->getErrorOutput());
  19308. if ($initialClone) {
  19309. $this->filesystem->removeDirectory($origCwd);
  19310. }
  19311. }
  19312. $this->throwException('Failed to clone ' . self::sanitizeUrl($url) .' via '.implode(', ', $protocols).' protocols, aborting.' . "\n\n" . implode("\n", $messages), $url);
  19313. }
  19314. $bypassSshForGitHub = preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true);
  19315. $bypassSshForGitLab = preg_match('{^git@'.self::getGitLabDomainsRegex($this->config).':(.+?)\.git$}i', $url) && !in_array('ssh', $protocols, true);
  19316. $command = call_user_func($commandCallable, $url);
  19317. if ($bypassSshForGitHub || $bypassSshForGitLab || 0 !== $this->process->execute($command, $ignoredOutput, $cwd)) {
  19318. if (preg_match('{^git@'.self::getGitHubDomainsRegex($this->config).':(.+?)\.git$}i', $url, $match)) {
  19319. if (!$this->io->hasAuthentication($match[1])) {
  19320. $gitHubUtil = new GitHub($this->io, $this->config, $this->process);
  19321. $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
  19322. if (!$gitHubUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  19323. $gitHubUtil->authorizeOAuthInteractively($match[1], $message);
  19324. }
  19325. }
  19326. if ($this->io->hasAuthentication($match[1])) {
  19327. $auth = $this->io->getAuthentication($match[1]);
  19328. $url = 'https://'.rawurlencode($auth['username']) . ':' . rawurlencode($auth['password']) . '@'.$match[1].'/'.$match[2].'.git';
  19329. $command = call_user_func($commandCallable, $url);
  19330. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  19331. return;
  19332. }
  19333. }
  19334. } elseif (preg_match('{^git@'.self::getGitLabDomainsRegex($this->config).':(.+?)\.git$}i', $url, $match)) {
  19335. if (!$this->io->hasAuthentication($match[1])) {
  19336. $gitLabUtil = new GitLab($this->io, $this->config, $this->process);
  19337. $message = 'Cloning failed using an ssh key for authentication, enter your GitHub credentials to access private repos';
  19338. if (!$gitLabUtil->authorizeOAuth($match[1]) && $this->io->isInteractive()) {
  19339. $gitLabUtil->authorizeOAuthInteractively($match[1], $message);
  19340. }
  19341. }
  19342. if ($this->io->hasAuthentication($match[1])) {
  19343. $auth = $this->io->getAuthentication($match[1]);
  19344. $url = 'http://oauth2:' . rawurlencode($auth['username']) . '@'.$match[1].'/'.$match[2].'.git';
  19345. $command = call_user_func($commandCallable, $url);
  19346. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  19347. return;
  19348. }
  19349. }
  19350. } elseif (
  19351. preg_match('{(https?://)([^/]+)(.*)$}i', $url, $match) &&
  19352. strpos($this->process->getErrorOutput(), 'fatal: Authentication failed') !== false
  19353. ) {
  19354. if (strpos($match[2], '@')) {
  19355. list($authParts, $match[2]) = explode('@', $match[2], 2);
  19356. }
  19357. $storeAuth = false;
  19358. if ($this->io->hasAuthentication($match[2])) {
  19359. $auth = $this->io->getAuthentication($match[2]);
  19360. } elseif ($this->io->isInteractive()) {
  19361. $defaultUsername = null;
  19362. if (isset($authParts) && $authParts) {
  19363. if (false !== strpos($authParts, ':')) {
  19364. list($defaultUsername,) = explode(':', $authParts, 2);
  19365. } else {
  19366. $defaultUsername = $authParts;
  19367. }
  19368. }
  19369. $this->io->writeError(' Authentication required (<info>'.parse_url($url, PHP_URL_HOST).'</info>):');
  19370. $auth = array(
  19371. 'username' => $this->io->ask(' Username: ', $defaultUsername),
  19372. 'password' => $this->io->askAndHideAnswer(' Password: '),
  19373. );
  19374. $storeAuth = $this->config->get('store-auths');
  19375. }
  19376. if ($auth) {
  19377. $url = $match[1].rawurlencode($auth['username']).':'.rawurlencode($auth['password']).'@'.$match[2].$match[3];
  19378. $command = call_user_func($commandCallable, $url);
  19379. if (0 === $this->process->execute($command, $ignoredOutput, $cwd)) {
  19380. $this->io->setAuthentication($match[2], $auth['username'], $auth['password']);
  19381. $authHelper = new AuthHelper($this->io, $this->config);
  19382. $authHelper->storeAuth($match[2], $storeAuth);
  19383. return;
  19384. }
  19385. }
  19386. }
  19387. if ($initialClone) {
  19388. $this->filesystem->removeDirectory($origCwd);
  19389. }
  19390. $this->throwException('Failed to execute ' . self::sanitizeUrl($command) . "\n\n" . $this->process->getErrorOutput(), $url);
  19391. }
  19392. }
  19393. public static function cleanEnv()
  19394. {
  19395. if (ini_get('safe_mode') && false === strpos(ini_get('safe_mode_allowed_env_vars'), 'GIT_ASKPASS')) {
  19396. throw new \RuntimeException('safe_mode is enabled and safe_mode_allowed_env_vars does not contain GIT_ASKPASS, can not set env var. You can disable safe_mode with "-dsafe_mode=0" when running composer');
  19397. }
  19398. if (getenv('GIT_ASKPASS') !== 'echo') {
  19399. putenv('GIT_ASKPASS=echo');
  19400. }
  19401. if (getenv('GIT_DIR')) {
  19402. putenv('GIT_DIR');
  19403. }
  19404. if (getenv('GIT_WORK_TREE')) {
  19405. putenv('GIT_WORK_TREE');
  19406. }
  19407. putenv("DYLD_LIBRARY_PATH");
  19408. }
  19409. public static function getGitHubDomainsRegex(Config $config)
  19410. {
  19411. return '('.implode('|', array_map('preg_quote', $config->get('github-domains'))).')';
  19412. }
  19413. public static function getGitLabDomainsRegex(Config $config)
  19414. {
  19415. return '('.implode('|', array_map('preg_quote', $config->get('gitlab-domains'))).')';
  19416. }
  19417. public static function sanitizeUrl($message)
  19418. {
  19419. return preg_replace('{://([^@]+?):.+?@}', '://$1:***@', $message);
  19420. }
  19421. private function throwException($message, $url)
  19422. {
  19423. if (0 !== $this->process->execute('git --version', $ignoredOutput)) {
  19424. throw new \RuntimeException('Failed to clone '.self::sanitizeUrl($url).', git was not found, check that it is installed and in your PATH env.' . "\n\n" . $this->process->getErrorOutput());
  19425. }
  19426. throw new \RuntimeException($message);
  19427. }
  19428. }
  19429. <?php
  19430. namespace Composer\Util;
  19431. use Composer\IO\IOInterface;
  19432. use Composer\Config;
  19433. use Composer\Downloader\TransportException;
  19434. use Composer\Json\JsonFile;
  19435. class GitHub
  19436. {
  19437. protected $io;
  19438. protected $config;
  19439. protected $process;
  19440. protected $remoteFilesystem;
  19441. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null)
  19442. {
  19443. $this->io = $io;
  19444. $this->config = $config;
  19445. $this->process = $process ?: new ProcessExecutor;
  19446. $this->remoteFilesystem = $remoteFilesystem ?: new RemoteFilesystem($io, $config);
  19447. }
  19448. public function authorizeOAuth($originUrl)
  19449. {
  19450. if (!in_array($originUrl, $this->config->get('github-domains'))) {
  19451. return false;
  19452. }
  19453. if (0 === $this->process->execute('git config github.accesstoken', $output)) {
  19454. $this->io->setAuthentication($originUrl, trim($output), 'x-oauth-basic');
  19455. return true;
  19456. }
  19457. return false;
  19458. }
  19459. public function authorizeOAuthInteractively($originUrl, $message = null)
  19460. {
  19461. if ($message) {
  19462. $this->io->writeError($message);
  19463. }
  19464. $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', $this->config->getAuthConfigSource()->getName()));
  19465. $this->io->writeError('To revoke access to this token you can visit https://github.com/settings/applications');
  19466. $otp = null;
  19467. $attemptCounter = 0;
  19468. while ($attemptCounter++ < 5) {
  19469. try {
  19470. $response = $this->createToken($originUrl, $otp);
  19471. } catch (TransportException $e) {
  19472. if (in_array($e->getCode(), array(403, 401))) {
  19473. if (401 === $e->getCode() && $this->io->hasAuthentication($originUrl)) {
  19474. $otp = $this->checkTwoFactorAuthentication($e->getHeaders());
  19475. if (null !== $otp) {
  19476. continue;
  19477. }
  19478. }
  19479. if (401 === $e->getCode()) {
  19480. $this->io->writeError('Bad credentials.');
  19481. } else {
  19482. $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.');
  19483. }
  19484. $this->io->writeError('You can also manually create a personal token at https://github.com/settings/applications');
  19485. $this->io->writeError('Add it using "composer config github-oauth.github.com <token>"');
  19486. continue;
  19487. }
  19488. throw $e;
  19489. }
  19490. $this->io->setAuthentication($originUrl, $response['token'], 'x-oauth-basic');
  19491. $this->config->getConfigSource()->removeConfigSetting('github-oauth.'.$originUrl);
  19492. $this->config->getAuthConfigSource()->addConfigSetting('github-oauth.'.$originUrl, $response['token']);
  19493. return true;
  19494. }
  19495. throw new \RuntimeException("Invalid GitHub credentials 5 times in a row, aborting.");
  19496. }
  19497. private function createToken($originUrl, $otp = null)
  19498. {
  19499. if (null === $otp || !$this->io->hasAuthentication($originUrl)) {
  19500. $username = $this->io->ask('Username: ');
  19501. $password = $this->io->askAndHideAnswer('Password: ');
  19502. $this->io->setAuthentication($originUrl, $username, $password);
  19503. }
  19504. $headers = array('Content-Type: application/json');
  19505. if ($otp) {
  19506. $headers[] = 'X-GitHub-OTP: ' . $otp;
  19507. }
  19508. $note = 'Composer';
  19509. if ($this->config->get('github-expose-hostname') === true && 0 === $this->process->execute('hostname', $output)) {
  19510. $note .= ' on ' . trim($output);
  19511. }
  19512. $note .= ' [' . date('YmdHis') . ']';
  19513. $apiUrl = ('github.com' === $originUrl) ? 'api.github.com' : $originUrl . '/api/v3';
  19514. $json = $this->remoteFilesystem->getContents($originUrl, 'https://'. $apiUrl . '/authorizations', false, array(
  19515. 'retry-auth-failure' => false,
  19516. 'http' => array(
  19517. 'method' => 'POST',
  19518. 'follow_location' => false,
  19519. 'header' => $headers,
  19520. 'content' => json_encode(array(
  19521. 'scopes' => array('repo'),
  19522. 'note' => $note,
  19523. 'note_url' => 'https://getcomposer.org/',
  19524. )),
  19525. )
  19526. ));
  19527. $this->io->writeError('Token successfully created');
  19528. return JsonFile::parseJson($json);
  19529. }
  19530. private function checkTwoFactorAuthentication(array $headers)
  19531. {
  19532. $headerNames = array_map(
  19533. function ($header) {
  19534. return strtolower(strstr($header, ':', true));
  19535. },
  19536. $headers
  19537. );
  19538. if (false !== ($key = array_search('x-github-otp', $headerNames))) {
  19539. list($required, $method) = array_map('trim', explode(';', substr(strstr($headers[$key], ':'), 1)));
  19540. if ('required' === $required) {
  19541. $this->io->writeError('Two-factor Authentication');
  19542. if ('app' === $method) {
  19543. $this->io->writeError('Open the two-factor authentication app on your device to view your authentication code and verify your identity.');
  19544. }
  19545. if ('sms' === $method) {
  19546. $this->io->writeError('You have been sent an SMS message with an authentication code to verify your identity.');
  19547. }
  19548. return $this->io->ask('Authentication Code: ');
  19549. }
  19550. }
  19551. return null;
  19552. }
  19553. }
  19554. <?php
  19555. namespace Composer\Util;
  19556. use Composer\IO\IOInterface;
  19557. use Composer\Config;
  19558. use Composer\Downloader\TransportException;
  19559. use Composer\Json\JsonFile;
  19560. class GitLab
  19561. {
  19562. protected $io;
  19563. protected $config;
  19564. protected $process;
  19565. protected $remoteFilesystem;
  19566. public function __construct(IOInterface $io, Config $config, ProcessExecutor $process = null, RemoteFilesystem $remoteFilesystem = null)
  19567. {
  19568. $this->io = $io;
  19569. $this->config = $config;
  19570. $this->process = $process ?: new ProcessExecutor;
  19571. $this->remoteFilesystem = $remoteFilesystem ?: new RemoteFilesystem($io, $config);
  19572. }
  19573. public function authorizeOAuth($originUrl)
  19574. {
  19575. if (!in_array($originUrl, $this->config->get('gitlab-domains'))) {
  19576. return false;
  19577. }
  19578. if (0 === $this->process->execute('git config gitlab.accesstoken', $output)) {
  19579. $this->io->setAuthentication($originUrl, trim($output), 'oauth2');
  19580. return true;
  19581. }
  19582. return false;
  19583. }
  19584. public function authorizeOAuthInteractively($originUrl, $message = null)
  19585. {
  19586. if ($message) {
  19587. $this->io->writeError($message);
  19588. }
  19589. $this->io->writeError(sprintf('A token will be created and stored in "%s", your password will never be stored', $this->config->getAuthConfigSource()->getName()));
  19590. $this->io->writeError('To revoke access to this token you can visit ' . $this->config->get('gitlab-domains')[0] . '/profile/applications');
  19591. $otp = null;
  19592. $attemptCounter = 0;
  19593. while ($attemptCounter++ < 5) {
  19594. try {
  19595. $response = $this->createToken($originUrl, $otp);
  19596. } catch (TransportException $e) {
  19597. if (in_array($e->getCode(), array(403, 401))) {
  19598. if (401 === $e->getCode() && $this->io->hasAuthentication($originUrl)) {
  19599. $otp = $this->checkTwoFactorAuthentication($e->getHeaders());
  19600. if (null !== $otp) {
  19601. continue;
  19602. }
  19603. }
  19604. if (401 === $e->getCode()) {
  19605. $this->io->writeError('Bad credentials.');
  19606. } else {
  19607. $this->io->writeError('Maximum number of login attempts exceeded. Please try again later.');
  19608. }
  19609. $this->io->writeError('You can also manually create a personal token at ' . $this->config->get('gitlab-domains')[0] . '/profile/applications');
  19610. $this->io->writeError('Add it using "composer config gitlab-oauth.' . $this->config->get('gitlab-domains')[0] . ' <token>"');
  19611. continue;
  19612. }
  19613. throw $e;
  19614. }
  19615. $this->io->setAuthentication($originUrl, $response['access_token'], 'oauth2');
  19616. $this->config->getConfigSource()->removeConfigSetting('gitlab-oauth.'.$originUrl);
  19617. $this->config->getAuthConfigSource()->addConfigSetting('gitlab-oauth.'.$originUrl, $response['access_token']);
  19618. return true;
  19619. }
  19620. throw new \RuntimeException("Invalid GitLab credentials 5 times in a row, aborting.");
  19621. }
  19622. private function createToken($originUrl, $otp = null)
  19623. {
  19624. if (null === $otp || !$this->io->hasAuthentication($originUrl)) {
  19625. $username = $this->io->ask('Username: ');
  19626. $password = $this->io->askAndHideAnswer('Password: ');
  19627. $this->io->setAuthentication($originUrl, $username, $password);
  19628. }
  19629. $headers = array('Content-Type: application/x-www-form-urlencoded');
  19630. if ($otp) {
  19631. $headers[] = 'X-GitLab-OTP: ' . $otp;
  19632. }
  19633. $note = 'Composer';
  19634. if ($this->config->get('GitLab-expose-hostname') === true && 0 === $this->process->execute('hostname', $output)) {
  19635. $note .= ' on ' . trim($output);
  19636. }
  19637. $note .= ' [' . date('YmdHis') . ']';
  19638. $apiUrl = $originUrl ;
  19639. $data = http_build_query(
  19640. array(
  19641. 'username' => $username,
  19642. 'password' => $password,
  19643. 'grant_type' => 'password',
  19644. )
  19645. );
  19646. $options = array(
  19647. 'retry-auth-failure' => false,
  19648. 'http' => array(
  19649. 'method' => 'POST',
  19650. 'header' => $headers,
  19651. 'content' => $data
  19652. ));
  19653. $json = $this->remoteFilesystem->getContents($originUrl, 'http://'. $apiUrl . '/oauth/token', false, $options);
  19654. $this->io->writeError('Token successfully created');
  19655. return JsonFile::parseJson($json);
  19656. }
  19657. private function checkTwoFactorAuthentication(array $headers)
  19658. {
  19659. $headerNames = array_map(
  19660. function ($header) {
  19661. return strtolower(strstr($header, ':', true));
  19662. },
  19663. $headers
  19664. );
  19665. if (false !== ($key = array_search('x-GitLab-otp', $headerNames))) {
  19666. list($required, $method) = array_map('trim', explode(';', substr(strstr($headers[$key], ':'), 1)));
  19667. if ('required' === $required) {
  19668. $this->io->writeError('Two-factor Authentication');
  19669. if ('app' === $method) {
  19670. $this->io->writeError('Open the two-factor authentication app on your device to view your authentication code and verify your identity.');
  19671. }
  19672. if ('sms' === $method) {
  19673. $this->io->writeError('You have been sent an SMS message with an authentication code to verify your identity.');
  19674. }
  19675. return $this->io->ask('Authentication Code: ');
  19676. }
  19677. }
  19678. return null;
  19679. }
  19680. }
  19681. <?php
  19682. namespace Composer\Util;
  19683. class NoProxyPattern
  19684. {
  19685. protected $rules = array();
  19686. public function __construct($pattern)
  19687. {
  19688. $this->rules = preg_split("/[\s,]+/", $pattern);
  19689. }
  19690. public function test($url)
  19691. {
  19692. $host = parse_url($url, PHP_URL_HOST);
  19693. $port = parse_url($url, PHP_URL_PORT);
  19694. if (empty($port)) {
  19695. switch (parse_url($url, PHP_URL_SCHEME)) {
  19696. case 'http':
  19697. $port = 80;
  19698. break;
  19699. case 'https':
  19700. $port = 443;
  19701. break;
  19702. }
  19703. }
  19704. foreach ($this->rules as $rule) {
  19705. if ($rule == '*') {
  19706. return true;
  19707. }
  19708. $match = false;
  19709. list($ruleHost) = explode(':', $rule);
  19710. list($base) = explode('/', $ruleHost);
  19711. if (filter_var($base, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
  19712. if (!isset($ip)) {
  19713. $ip = gethostbyname($host);
  19714. }
  19715. if (strpos($ruleHost, '/') === false) {
  19716. $match = $ip === $ruleHost;
  19717. } else {
  19718. if ($ip === $host) {
  19719. $match = false;
  19720. } else {
  19721. $match = self::inCIDRBlock($ruleHost, $ip);
  19722. }
  19723. }
  19724. } else {
  19725. $haystack = '.' . trim($host, '.') . '.';
  19726. $needle = '.'. trim($ruleHost, '.') .'.';
  19727. $match = stripos(strrev($haystack), strrev($needle)) === 0;
  19728. }
  19729. if ($match && strpos($rule, ':') !== false) {
  19730. list(, $rulePort) = explode(':', $rule);
  19731. if (!empty($rulePort) && $port != $rulePort) {
  19732. $match = false;
  19733. }
  19734. }
  19735. if ($match) {
  19736. return true;
  19737. }
  19738. }
  19739. return false;
  19740. }
  19741. private static function inCIDRBlock($cidr, $ip)
  19742. {
  19743. list($base, $bits) = explode('/', $cidr);
  19744. list($a, $b, $c, $d) = explode('.', $base);
  19745. $i = ($a << 24) + ($b << 16) + ($c << 8) + $d;
  19746. $mask = $bits == 0 ? 0 : (~0 << (32 - $bits));
  19747. $low = $i & $mask;
  19748. $high = $i | (~$mask & 0xFFFFFFFF);
  19749. list($a, $b, $c, $d) = explode('.', $ip);
  19750. $check = ($a << 24) + ($b << 16) + ($c << 8) + $d;
  19751. return $check >= $low && $check <= $high;
  19752. }
  19753. }
  19754. <?php
  19755. namespace Composer\Util;
  19756. use Composer\IO\IOInterface;
  19757. use Symfony\Component\Process\Process;
  19758. class Perforce
  19759. {
  19760. protected $path;
  19761. protected $p4Depot;
  19762. protected $p4Client;
  19763. protected $p4User;
  19764. protected $p4Password;
  19765. protected $p4Port;
  19766. protected $p4Stream;
  19767. protected $p4ClientSpec;
  19768. protected $p4DepotType;
  19769. protected $p4Branch;
  19770. protected $process;
  19771. protected $uniquePerforceClientName;
  19772. protected $windowsFlag;
  19773. protected $commandResult;
  19774. protected $io;
  19775. protected $filesystem;
  19776. public function __construct($repoConfig, $port, $path, ProcessExecutor $process, $isWindows, IOInterface $io)
  19777. {
  19778. $this->windowsFlag = $isWindows;
  19779. $this->p4Port = $port;
  19780. $this->initializePath($path);
  19781. $this->process = $process;
  19782. $this->initialize($repoConfig);
  19783. $this->io = $io;
  19784. }
  19785. public static function create($repoConfig, $port, $path, ProcessExecutor $process, IOInterface $io)
  19786. {
  19787. $isWindows = defined('PHP_WINDOWS_VERSION_BUILD');
  19788. $perforce = new Perforce($repoConfig, $port, $path, $process, $isWindows, $io);
  19789. return $perforce;
  19790. }
  19791. public static function checkServerExists($url, ProcessExecutor $processExecutor)
  19792. {
  19793. $output = null;
  19794. return 0 === $processExecutor->execute('p4 -p ' . $url . ' info -s', $output);
  19795. }
  19796. public function initialize($repoConfig)
  19797. {
  19798. $this->uniquePerforceClientName = $this->generateUniquePerforceClientName();
  19799. if (null == $repoConfig) {
  19800. return;
  19801. }
  19802. if (isset($repoConfig['unique_perforce_client_name'])) {
  19803. $this->uniquePerforceClientName = $repoConfig['unique_perforce_client_name'];
  19804. }
  19805. if (isset($repoConfig['depot'])) {
  19806. $this->p4Depot = $repoConfig['depot'];
  19807. }
  19808. if (isset($repoConfig['branch'])) {
  19809. $this->p4Branch = $repoConfig['branch'];
  19810. }
  19811. if (isset($repoConfig['p4user'])) {
  19812. $this->p4User = $repoConfig['p4user'];
  19813. } else {
  19814. $this->p4User = $this->getP4variable('P4USER');
  19815. }
  19816. if (isset($repoConfig['p4password'])) {
  19817. $this->p4Password = $repoConfig['p4password'];
  19818. }
  19819. }
  19820. public function initializeDepotAndBranch($depot, $branch)
  19821. {
  19822. if (isset($depot)) {
  19823. $this->p4Depot = $depot;
  19824. }
  19825. if (isset($branch)) {
  19826. $this->p4Branch = $branch;
  19827. }
  19828. }
  19829. public function generateUniquePerforceClientName()
  19830. {
  19831. return gethostname() . "_" . time();
  19832. }
  19833. public function cleanupClientSpec()
  19834. {
  19835. $client = $this->getClient();
  19836. $task = 'client -d ' . $client;
  19837. $useP4Client = false;
  19838. $command = $this->generateP4Command($task, $useP4Client);
  19839. $this->executeCommand($command);
  19840. $clientSpec = $this->getP4ClientSpec();
  19841. $fileSystem = $this->getFilesystem();
  19842. $fileSystem->remove($clientSpec);
  19843. }
  19844. protected function executeCommand($command)
  19845. {
  19846. $this->commandResult = "";
  19847. $exit_code = $this->process->execute($command, $this->commandResult);
  19848. return $exit_code;
  19849. }
  19850. public function getClient()
  19851. {
  19852. if (!isset($this->p4Client)) {
  19853. $cleanStreamName = str_replace('@', '', str_replace('/', '_', str_replace('//', '', $this->getStream())));
  19854. $this->p4Client = 'composer_perforce_' . $this->uniquePerforceClientName . '_' . $cleanStreamName;
  19855. }
  19856. return $this->p4Client;
  19857. }
  19858. protected function getPath()
  19859. {
  19860. return $this->path;
  19861. }
  19862. public function initializePath($path)
  19863. {
  19864. $this->path = $path;
  19865. $fs = $this->getFilesystem();
  19866. $fs->ensureDirectoryExists($path);
  19867. }
  19868. protected function getPort()
  19869. {
  19870. return $this->p4Port;
  19871. }
  19872. public function setStream($stream)
  19873. {
  19874. $this->p4Stream = $stream;
  19875. $index = strrpos($stream, '/');
  19876. if ($index > 2) {
  19877. $this->p4DepotType = 'stream';
  19878. }
  19879. }
  19880. public function isStream()
  19881. {
  19882. return (strcmp($this->p4DepotType, 'stream') === 0);
  19883. }
  19884. public function getStream()
  19885. {
  19886. if (!isset($this->p4Stream)) {
  19887. if ($this->isStream()) {
  19888. $this->p4Stream = '//' . $this->p4Depot . '/' . $this->p4Branch;
  19889. } else {
  19890. $this->p4Stream = '//' . $this->p4Depot;
  19891. }
  19892. }
  19893. return $this->p4Stream;
  19894. }
  19895. public function getStreamWithoutLabel($stream)
  19896. {
  19897. $index = strpos($stream, '@');
  19898. if ($index === false) {
  19899. return $stream;
  19900. }
  19901. return substr($stream, 0, $index);
  19902. }
  19903. public function getP4ClientSpec()
  19904. {
  19905. $p4clientSpec = $this->path . '/' . $this->getClient() . '.p4.spec';
  19906. return $p4clientSpec;
  19907. }
  19908. public function getUser()
  19909. {
  19910. return $this->p4User;
  19911. }
  19912. public function setUser($user)
  19913. {
  19914. $this->p4User = $user;
  19915. }
  19916. public function queryP4User()
  19917. {
  19918. $this->getUser();
  19919. if (strlen($this->p4User) > 0) {
  19920. return;
  19921. }
  19922. $this->p4User = $this->getP4variable('P4USER');
  19923. if (strlen($this->p4User) > 0) {
  19924. return;
  19925. }
  19926. $this->p4User = $this->io->ask('Enter P4 User:');
  19927. if ($this->windowsFlag) {
  19928. $command = 'p4 set P4USER=' . $this->p4User;
  19929. } else {
  19930. $command = 'export P4USER=' . $this->p4User;
  19931. }
  19932. $this->executeCommand($command);
  19933. }
  19934. protected function getP4variable($name)
  19935. {
  19936. if ($this->windowsFlag) {
  19937. $command = 'p4 set';
  19938. $this->executeCommand($command);
  19939. $result = trim($this->commandResult);
  19940. $resArray = explode(PHP_EOL, $result);
  19941. foreach ($resArray as $line) {
  19942. $fields = explode('=', $line);
  19943. if (strcmp($name, $fields[0]) == 0) {
  19944. $index = strpos($fields[1], ' ');
  19945. if ($index === false) {
  19946. $value = $fields[1];
  19947. } else {
  19948. $value = substr($fields[1], 0, $index);
  19949. }
  19950. $value = trim($value);
  19951. return $value;
  19952. }
  19953. }
  19954. } else {
  19955. $command = 'echo $' . $name;
  19956. $this->executeCommand($command);
  19957. $result = trim($this->commandResult);
  19958. return $result;
  19959. }
  19960. }
  19961. public function queryP4Password()
  19962. {
  19963. if (isset($this->p4Password)) {
  19964. return $this->p4Password;
  19965. }
  19966. $password = $this->getP4variable('P4PASSWD');
  19967. if (strlen($password) <= 0) {
  19968. $password = $this->io->askAndHideAnswer('Enter password for Perforce user ' . $this->getUser() . ': ');
  19969. }
  19970. $this->p4Password = $password;
  19971. return $password;
  19972. }
  19973. public function generateP4Command($command, $useClient = true)
  19974. {
  19975. $p4Command = 'p4 ';
  19976. $p4Command = $p4Command . '-u ' . $this->getUser() . ' ';
  19977. if ($useClient) {
  19978. $p4Command = $p4Command . '-c ' . $this->getClient() . ' ';
  19979. }
  19980. $p4Command = $p4Command . '-p ' . $this->getPort() . ' ';
  19981. $p4Command = $p4Command . $command;
  19982. return $p4Command;
  19983. }
  19984. public function isLoggedIn()
  19985. {
  19986. $command = $this->generateP4Command('login -s', false);
  19987. $exitCode = $this->executeCommand($command);
  19988. if ($exitCode) {
  19989. $errorOutput = $this->process->getErrorOutput();
  19990. $index = strpos($errorOutput, $this->getUser());
  19991. if ($index === false) {
  19992. $index = strpos($errorOutput, 'p4');
  19993. if ($index === false) {
  19994. return false;
  19995. }
  19996. throw new \Exception('p4 command not found in path: ' . $errorOutput);
  19997. }
  19998. throw new \Exception('Invalid user name: ' . $this->getUser() );
  19999. }
  20000. return true;
  20001. }
  20002. public function connectClient()
  20003. {
  20004. $p4CreateClientCommand = $this->generateP4Command('client -i < ' . str_replace( " ", "\\ ", $this->getP4ClientSpec() ));
  20005. $this->executeCommand($p4CreateClientCommand);
  20006. }
  20007. public function syncCodeBase($sourceReference)
  20008. {
  20009. $prevDir = getcwd();
  20010. chdir($this->path);
  20011. $p4SyncCommand = $this->generateP4Command('sync -f ');
  20012. if (null != $sourceReference) {
  20013. $p4SyncCommand = $p4SyncCommand . '@' . $sourceReference;
  20014. }
  20015. $this->executeCommand($p4SyncCommand);
  20016. chdir($prevDir);
  20017. }
  20018. public function writeClientSpecToFile($spec)
  20019. {
  20020. fwrite($spec, 'Client: ' . $this->getClient() . PHP_EOL . PHP_EOL);
  20021. fwrite($spec, 'Update: ' . date('Y/m/d H:i:s') . PHP_EOL . PHP_EOL);
  20022. fwrite($spec, 'Access: ' . date('Y/m/d H:i:s') . PHP_EOL);
  20023. fwrite($spec, 'Owner: ' . $this->getUser() . PHP_EOL . PHP_EOL);
  20024. fwrite($spec, 'Description:' . PHP_EOL);
  20025. fwrite($spec, ' Created by ' . $this->getUser() . ' from composer.' . PHP_EOL . PHP_EOL);
  20026. fwrite($spec, 'Root: ' . $this->getPath() . PHP_EOL . PHP_EOL);
  20027. fwrite($spec, 'Options: noallwrite noclobber nocompress unlocked modtime rmdir' . PHP_EOL . PHP_EOL);
  20028. fwrite($spec, 'SubmitOptions: revertunchanged' . PHP_EOL . PHP_EOL);
  20029. fwrite($spec, 'LineEnd: local' . PHP_EOL . PHP_EOL);
  20030. if ($this->isStream()) {
  20031. fwrite($spec, 'Stream:' . PHP_EOL);
  20032. fwrite($spec, ' ' . $this->getStreamWithoutLabel($this->p4Stream) . PHP_EOL);
  20033. } else {
  20034. fwrite(
  20035. $spec,
  20036. 'View: ' . $this->getStream() . '/... //' . $this->getClient() . '/... ' . PHP_EOL
  20037. );
  20038. }
  20039. }
  20040. public function writeP4ClientSpec()
  20041. {
  20042. $clientSpec = $this->getP4ClientSpec();
  20043. $spec = fopen($clientSpec, 'w');
  20044. try {
  20045. $this->writeClientSpecToFile($spec);
  20046. } catch (\Exception $e) {
  20047. fclose($spec);
  20048. throw $e;
  20049. }
  20050. fclose($spec);
  20051. }
  20052. protected function read($pipe, $name)
  20053. {
  20054. if (feof($pipe)) {
  20055. return;
  20056. }
  20057. $line = fgets($pipe);
  20058. while ($line != false) {
  20059. $line = fgets($pipe);
  20060. }
  20061. return;
  20062. }
  20063. public function windowsLogin($password)
  20064. {
  20065. $command = $this->generateP4Command(' login -a');
  20066. $process = new Process($command, null, null, $password);
  20067. return $process->run();
  20068. }
  20069. public function p4Login()
  20070. {
  20071. $this->queryP4User();
  20072. if (!$this->isLoggedIn()) {
  20073. $password = $this->queryP4Password();
  20074. if ($this->windowsFlag) {
  20075. $this->windowsLogin($password);
  20076. } else {
  20077. $command = 'echo ' . $password . ' | ' . $this->generateP4Command(' login -a', false);
  20078. $exitCode = $this->executeCommand($command);
  20079. $result = trim($this->commandResult);
  20080. if ($exitCode) {
  20081. throw new \Exception("Error logging in:" . $this->process->getErrorOutput());
  20082. }
  20083. }
  20084. }
  20085. }
  20086. public function getComposerInformation($identifier)
  20087. {
  20088. $index = strpos($identifier, '@');
  20089. if ($index === false) {
  20090. $composerJson = $identifier. '/composer.json';
  20091. return $this->getComposerInformationFromPath($composerJson);
  20092. }
  20093. return $this->getComposerInformationFromLabel($identifier, $index);
  20094. }
  20095. public function getComposerInformationFromPath($composerJson)
  20096. {
  20097. $command = $this->generateP4Command(' print ' . $composerJson);
  20098. $this->executeCommand($command);
  20099. $result = $this->commandResult;
  20100. $index = strpos($result, '{');
  20101. if ($index === false) {
  20102. return '';
  20103. }
  20104. if ($index >= 0) {
  20105. $rawData = substr($result, $index);
  20106. $composer_info = json_decode($rawData, true);
  20107. return $composer_info;
  20108. }
  20109. return '';
  20110. }
  20111. public function getComposerInformationFromLabel($identifier, $index)
  20112. {
  20113. $composerJsonPath = substr($identifier, 0, $index) . '/composer.json' . substr($identifier, $index);
  20114. $command = $this->generateP4Command(' files ' . $composerJsonPath, false);
  20115. $this->executeCommand($command);
  20116. $result = $this->commandResult;
  20117. $index2 = strpos($result, 'no such file(s).');
  20118. if ($index2 === false) {
  20119. $index3 = strpos($result, 'change');
  20120. if (!($index3 === false)) {
  20121. $phrase = trim(substr($result, $index3));
  20122. $fields = explode(' ', $phrase);
  20123. $id = $fields[1];
  20124. $composerJson = substr($identifier, 0, $index) . '/composer.json@' . $id;
  20125. return $this->getComposerInformationFromPath($composerJson);
  20126. }
  20127. }
  20128. return "";
  20129. }
  20130. public function getBranches()
  20131. {
  20132. $possibleBranches = array();
  20133. if (!$this->isStream()) {
  20134. $possibleBranches[$this->p4Branch] = $this->getStream();
  20135. } else {
  20136. $command = $this->generateP4Command('streams //' . $this->p4Depot . '/...');
  20137. $this->executeCommand($command);
  20138. $result = $this->commandResult;
  20139. $resArray = explode(PHP_EOL, $result);
  20140. foreach ($resArray as $line) {
  20141. $resBits = explode(' ', $line);
  20142. if (count($resBits) > 4) {
  20143. $branch = preg_replace('/[^A-Za-z0-9 ]/', '', $resBits[4]);
  20144. $possibleBranches[$branch] = $resBits[1];
  20145. }
  20146. }
  20147. }
  20148. $command = $this->generateP4Command('changes '. $this->getStream() . '/...', false);
  20149. $this->executeCommand($command);
  20150. $result = $this->commandResult;
  20151. $resArray = explode(PHP_EOL, $result);
  20152. $lastCommit = $resArray[0];
  20153. $lastCommitArr = explode(' ', $lastCommit);
  20154. $lastCommitNum = $lastCommitArr[1];
  20155. $branches = array('master' => $possibleBranches[$this->p4Branch] . '@'. $lastCommitNum);
  20156. return $branches;
  20157. }
  20158. public function getTags()
  20159. {
  20160. $command = $this->generateP4Command('labels');
  20161. $this->executeCommand($command);
  20162. $result = $this->commandResult;
  20163. $resArray = explode(PHP_EOL, $result);
  20164. $tags = array();
  20165. foreach ($resArray as $line) {
  20166. $index = strpos($line, 'Label');
  20167. if (!($index === false)) {
  20168. $fields = explode(' ', $line);
  20169. $tags[$fields[1]] = $this->getStream() . '@' . $fields[1];
  20170. }
  20171. }
  20172. return $tags;
  20173. }
  20174. public function checkStream()
  20175. {
  20176. $command = $this->generateP4Command('depots', false);
  20177. $this->executeCommand($command);
  20178. $result = $this->commandResult;
  20179. $resArray = explode(PHP_EOL, $result);
  20180. foreach ($resArray as $line) {
  20181. $index = strpos($line, 'Depot');
  20182. if (!($index === false)) {
  20183. $fields = explode(' ', $line);
  20184. if (strcmp($this->p4Depot, $fields[1]) === 0) {
  20185. $this->p4DepotType = $fields[3];
  20186. return $this->isStream();
  20187. }
  20188. }
  20189. }
  20190. return false;
  20191. }
  20192. protected function getChangeList($reference)
  20193. {
  20194. $index = strpos($reference, '@');
  20195. if ($index === false) {
  20196. return;
  20197. }
  20198. $label = substr($reference, $index);
  20199. $command = $this->generateP4Command(' changes -m1 ' . $label);
  20200. $this->executeCommand($command);
  20201. $changes = $this->commandResult;
  20202. if (strpos($changes, 'Change') !== 0) {
  20203. return;
  20204. }
  20205. $fields = explode(' ', $changes);
  20206. $changeList = $fields[1];
  20207. return $changeList;
  20208. }
  20209. public function getCommitLogs($fromReference, $toReference)
  20210. {
  20211. $fromChangeList = $this->getChangeList($fromReference);
  20212. if ($fromChangeList == null) {
  20213. return;
  20214. }
  20215. $toChangeList = $this->getChangeList($toReference);
  20216. if ($toChangeList == null) {
  20217. return;
  20218. }
  20219. $index = strpos($fromReference, '@');
  20220. $main = substr($fromReference, 0, $index) . '/...';
  20221. $command = $this->generateP4Command('filelog ' . $main . '@' . $fromChangeList. ',' . $toChangeList);
  20222. $this->executeCommand($command);
  20223. $result = $this->commandResult;
  20224. return $result;
  20225. }
  20226. public function getFilesystem()
  20227. {
  20228. if (empty($this->filesystem)) {
  20229. $this->filesystem = new Filesystem($this->process);
  20230. }
  20231. return $this->filesystem;
  20232. }
  20233. public function setFilesystem(Filesystem $fs)
  20234. {
  20235. $this->filesystem = $fs;
  20236. }
  20237. }
  20238. <?php
  20239. namespace Composer\Util;
  20240. use Symfony\Component\Process\Process;
  20241. use Symfony\Component\Process\ProcessUtils;
  20242. use Composer\IO\IOInterface;
  20243. class ProcessExecutor
  20244. {
  20245. protected static $timeout = 300;
  20246. protected $captureOutput;
  20247. protected $errorOutput;
  20248. protected $io;
  20249. public function __construct(IOInterface $io = null)
  20250. {
  20251. $this->io = $io;
  20252. }
  20253. public function execute($command, &$output = null, $cwd = null)
  20254. {
  20255. if ($this->io && $this->io->isDebug()) {
  20256. $safeCommand = preg_replace('{(://[^:/\s]+:)[^@\s/]+}i', '$1****', $command);
  20257. $this->io->writeError('Executing command ('.($cwd ?: 'CWD').'): '.$safeCommand);
  20258. }
  20259. if (null === $cwd && defined('PHP_WINDOWS_VERSION_BUILD') && false !== strpos($command, 'git') && getcwd()) {
  20260. $cwd = realpath(getcwd());
  20261. }
  20262. $this->captureOutput = count(func_get_args()) > 1;
  20263. $this->errorOutput = null;
  20264. $process = new Process($command, $cwd, null, null, static::getTimeout());
  20265. $callback = is_callable($output) ? $output : array($this, 'outputHandler');
  20266. $process->run($callback);
  20267. if ($this->captureOutput && !is_callable($output)) {
  20268. $output = $process->getOutput();
  20269. }
  20270. $this->errorOutput = $process->getErrorOutput();
  20271. return $process->getExitCode();
  20272. }
  20273. public function splitLines($output)
  20274. {
  20275. $output = trim($output);
  20276. return ((string) $output === '') ? array() : preg_split('{\r?\n}', $output);
  20277. }
  20278. public function getErrorOutput()
  20279. {
  20280. return $this->errorOutput;
  20281. }
  20282. public function outputHandler($type, $buffer)
  20283. {
  20284. if ($this->captureOutput) {
  20285. return;
  20286. }
  20287. echo $buffer;
  20288. }
  20289. public static function getTimeout()
  20290. {
  20291. return static::$timeout;
  20292. }
  20293. public static function setTimeout($timeout)
  20294. {
  20295. static::$timeout = $timeout;
  20296. }
  20297. public static function escape($argument)
  20298. {
  20299. return ProcessUtils::escapeArgument($argument);
  20300. }
  20301. }
  20302. <?php
  20303. namespace Composer\Util;
  20304. use Composer\Composer;
  20305. use Composer\Config;
  20306. use Composer\IO\IOInterface;
  20307. use Composer\Downloader\TransportException;
  20308. class RemoteFilesystem
  20309. {
  20310. private $io;
  20311. private $config;
  20312. private $bytesMax;
  20313. private $originUrl;
  20314. private $fileUrl;
  20315. private $fileName;
  20316. private $retry;
  20317. private $progress;
  20318. private $lastProgress;
  20319. private $options;
  20320. private $retryAuthFailure;
  20321. private $lastHeaders;
  20322. private $storeAuth;
  20323. public function __construct(IOInterface $io, Config $config = null, array $options = array())
  20324. {
  20325. $this->io = $io;
  20326. $this->config = $config;
  20327. $this->options = $options;
  20328. }
  20329. public function copy($originUrl, $fileUrl, $fileName, $progress = true, $options = array())
  20330. {
  20331. return $this->get($originUrl, $fileUrl, $options, $fileName, $progress);
  20332. }
  20333. public function getContents($originUrl, $fileUrl, $progress = true, $options = array())
  20334. {
  20335. return $this->get($originUrl, $fileUrl, $options, null, $progress);
  20336. }
  20337. public function getOptions()
  20338. {
  20339. return $this->options;
  20340. }
  20341. public function getLastHeaders()
  20342. {
  20343. return $this->lastHeaders;
  20344. }
  20345. protected function get($originUrl, $fileUrl, $additionalOptions = array(), $fileName = null, $progress = true)
  20346. {
  20347. if (strpos($originUrl, '.github.com') === (strlen($originUrl) - 11)) {
  20348. $originUrl = 'github.com';
  20349. }
  20350. $this->bytesMax = 0;
  20351. $this->originUrl = $originUrl;
  20352. $this->fileUrl = $fileUrl;
  20353. $this->fileName = $fileName;
  20354. $this->progress = $progress;
  20355. $this->lastProgress = null;
  20356. $this->retryAuthFailure = true;
  20357. $this->lastHeaders = array();
  20358. if (preg_match('{^https?://(.+):(.+)@([^/]+)}i', $fileUrl, $match)) {
  20359. $this->io->setAuthentication($originUrl, urldecode($match[1]), urldecode($match[2]));
  20360. }
  20361. if (isset($additionalOptions['retry-auth-failure'])) {
  20362. $this->retryAuthFailure = (bool) $additionalOptions['retry-auth-failure'];
  20363. unset($additionalOptions['retry-auth-failure']);
  20364. }
  20365. $options = $this->getOptionsForUrl($originUrl, $additionalOptions);
  20366. if (isset($options['retry-auth-failure'])) {
  20367. $this->retryAuthFailure = (bool) $options['retry-auth-failure'];
  20368. unset($options['retry-auth-failure']);
  20369. }
  20370. if ($this->io->isDebug()) {
  20371. $this->io->writeError((substr($fileUrl, 0, 4) === 'http' ? 'Downloading ' : 'Reading ') . $fileUrl);
  20372. }
  20373. if (isset($options['github-token'])) {
  20374. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['github-token'];
  20375. unset($options['github-token']);
  20376. }
  20377. if (isset($options['gitlab-token'])) {
  20378. $fileUrl .= (false === strpos($fileUrl, '?') ? '?' : '&') . 'access_token='.$options['gitlab-token'];
  20379. unset($options['gitlab-token']);
  20380. }
  20381. if (isset($options['http'])) {
  20382. $options['http']['ignore_errors'] = true;
  20383. }
  20384. $ctx = StreamContextFactory::getContext($fileUrl, $options, array('notification' => array($this, 'callbackGet')));
  20385. if ($this->progress) {
  20386. $this->io->writeError(" Downloading: <comment>connection...</comment>", false);
  20387. }
  20388. $errorMessage = '';
  20389. $errorCode = 0;
  20390. $result = false;
  20391. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  20392. if ($errorMessage) {
  20393. $errorMessage .= "\n";
  20394. }
  20395. $errorMessage .= preg_replace('{^file_get_contents\(.*?\): }', '', $msg);
  20396. });
  20397. try {
  20398. $result = file_get_contents($fileUrl, false, $ctx);
  20399. } catch (\Exception $e) {
  20400. if ($e instanceof TransportException && !empty($http_response_header[0])) {
  20401. $e->setHeaders($http_response_header);
  20402. }
  20403. if ($e instanceof TransportException && $result !== false) {
  20404. $e->setResponse($result);
  20405. }
  20406. $result = false;
  20407. }
  20408. if ($errorMessage && !ini_get('allow_url_fopen')) {
  20409. $errorMessage = 'allow_url_fopen must be enabled in php.ini ('.$errorMessage.')';
  20410. }
  20411. restore_error_handler();
  20412. if (isset($e) && !$this->retry) {
  20413. throw $e;
  20414. }
  20415. if (!empty($http_response_header[0]) && preg_match('{^HTTP/\S+ ([45]\d\d)}i', $http_response_header[0], $match)) {
  20416. $errorCode = $match[1];
  20417. if (!$this->retry) {
  20418. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded ('.$http_response_header[0].')', $errorCode);
  20419. $e->setHeaders($http_response_header);
  20420. $e->setResponse($result);
  20421. throw $e;
  20422. }
  20423. $result = false;
  20424. }
  20425. if ($result && extension_loaded('zlib') && substr($fileUrl, 0, 4) === 'http') {
  20426. $decode = false;
  20427. foreach ($http_response_header as $header) {
  20428. if (preg_match('{^content-encoding: *gzip *$}i', $header)) {
  20429. $decode = true;
  20430. continue;
  20431. } elseif (preg_match('{^HTTP/}i', $header)) {
  20432. $decode = false;
  20433. }
  20434. }
  20435. if ($decode) {
  20436. if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
  20437. $result = zlib_decode($result);
  20438. } else {
  20439. $result = file_get_contents('compress.zlib://data:application/octet-stream;base64,'.base64_encode($result));
  20440. }
  20441. if (!$result) {
  20442. throw new TransportException('Failed to decode zlib stream');
  20443. }
  20444. }
  20445. }
  20446. if ($this->progress && !$this->retry) {
  20447. $this->io->overwriteError(" Downloading: <comment>100%</comment>");
  20448. }
  20449. if (false !== $result && null !== $fileName) {
  20450. if ('' === $result) {
  20451. throw new TransportException('"'.$this->fileUrl.'" appears broken, and returned an empty 200 response');
  20452. }
  20453. $errorMessage = '';
  20454. set_error_handler(function ($code, $msg) use (&$errorMessage) {
  20455. if ($errorMessage) {
  20456. $errorMessage .= "\n";
  20457. }
  20458. $errorMessage .= preg_replace('{^file_put_contents\(.*?\): }', '', $msg);
  20459. });
  20460. $result = (bool) file_put_contents($fileName, $result);
  20461. restore_error_handler();
  20462. if (false === $result) {
  20463. throw new TransportException('The "'.$this->fileUrl.'" file could not be written to '.$fileName.': '.$errorMessage);
  20464. }
  20465. }
  20466. if ($this->retry) {
  20467. $this->retry = false;
  20468. $result = $this->get($this->originUrl, $this->fileUrl, $additionalOptions, $this->fileName, $this->progress);
  20469. $authHelper = new AuthHelper($this->io, $this->config);
  20470. $authHelper->storeAuth($this->originUrl, $this->storeAuth);
  20471. $this->storeAuth = false;
  20472. return $result;
  20473. }
  20474. if (false === $result) {
  20475. $e = new TransportException('The "'.$this->fileUrl.'" file could not be downloaded: '.$errorMessage, $errorCode);
  20476. if (!empty($http_response_header[0])) {
  20477. $e->setHeaders($http_response_header);
  20478. }
  20479. throw $e;
  20480. }
  20481. if (!empty($http_response_header[0])) {
  20482. $this->lastHeaders = $http_response_header;
  20483. }
  20484. return $result;
  20485. }
  20486. protected function callbackGet($notificationCode, $severity, $message, $messageCode, $bytesTransferred, $bytesMax)
  20487. {
  20488. switch ($notificationCode) {
  20489. case STREAM_NOTIFY_FAILURE:
  20490. case STREAM_NOTIFY_AUTH_REQUIRED:
  20491. if (401 === $messageCode) {
  20492. if (!$this->retryAuthFailure) {
  20493. break;
  20494. }
  20495. $this->promptAuthAndRetry($messageCode);
  20496. break;
  20497. }
  20498. break;
  20499. case STREAM_NOTIFY_AUTH_RESULT:
  20500. if (403 === $messageCode) {
  20501. $this->promptAuthAndRetry($messageCode, $message);
  20502. break;
  20503. }
  20504. break;
  20505. case STREAM_NOTIFY_FILE_SIZE_IS:
  20506. if ($this->bytesMax < $bytesMax) {
  20507. $this->bytesMax = $bytesMax;
  20508. }
  20509. break;
  20510. case STREAM_NOTIFY_PROGRESS:
  20511. if ($this->bytesMax > 0 && $this->progress) {
  20512. $progression = 0;
  20513. if ($this->bytesMax > 0) {
  20514. $progression = round($bytesTransferred / $this->bytesMax * 100);
  20515. }
  20516. if ((0 === $progression % 5) && $progression !== $this->lastProgress) {
  20517. $this->lastProgress = $progression;
  20518. $this->io->overwriteError(" Downloading: <comment>$progression%</comment>", false);
  20519. }
  20520. }
  20521. break;
  20522. default:
  20523. break;
  20524. }
  20525. }
  20526. protected function promptAuthAndRetry($httpStatus, $reason = null)
  20527. {
  20528. if ($this->config && in_array($this->originUrl, $this->config->get('github-domains'), true)) {
  20529. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your GitHub credentials '.($httpStatus === 404 ? 'to access private repos' : 'to go over the API rate limit');
  20530. $gitHubUtil = new GitHub($this->io, $this->config, null);
  20531. if (!$gitHubUtil->authorizeOAuth($this->originUrl)
  20532. && (!$this->io->isInteractive() || !$gitHubUtil->authorizeOAuthInteractively($this->originUrl, $message))
  20533. ) {
  20534. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  20535. }
  20536. } else if ($this->config && in_array($this->originUrl, $this->config->get('gitlab-domains'), true)) {
  20537. $message = "\n".'Could not fetch '.$this->fileUrl.', enter your ' . $this->config->get('gitlab-domains')[0] . ' credentials ' .($httpStatus === 401 ? 'to access private repos' : 'to go over the API rate limit');
  20538. $gitLabUtil = new GitLab($this->io, $this->config, null);
  20539. if (!$gitLabUtil->authorizeOAuth($this->originUrl)
  20540. && (!$this->io->isInteractive() || !$gitLabUtil->authorizeOAuthInteractively($this->originUrl, $message))
  20541. ) {
  20542. throw new TransportException('Could not authenticate against '.$this->originUrl, 401);
  20543. }
  20544. } else {
  20545. if ($httpStatus === 404) {
  20546. return;
  20547. }
  20548. if (!$this->io->isInteractive()) {
  20549. if ($httpStatus === 401) {
  20550. $message = "The '" . $this->fileUrl . "' URL required authentication.\nYou must be using the interactive console to authenticate";
  20551. }
  20552. if ($httpStatus === 403) {
  20553. $message = "The '" . $this->fileUrl . "' URL could not be accessed: " . $reason;
  20554. }
  20555. throw new TransportException($message, $httpStatus);
  20556. }
  20557. if ($this->io->hasAuthentication($this->originUrl)) {
  20558. throw new TransportException("Invalid credentials for '" . $this->fileUrl . "', aborting.", $httpStatus);
  20559. }
  20560. $this->io->overwriteError(' Authentication required (<info>'.parse_url($this->fileUrl, PHP_URL_HOST).'</info>):');
  20561. $username = $this->io->ask(' Username: ');
  20562. $password = $this->io->askAndHideAnswer(' Password: ');
  20563. $this->io->setAuthentication($this->originUrl, $username, $password);
  20564. $this->storeAuth = $this->config->get('store-auths');
  20565. }
  20566. $this->retry = true;
  20567. throw new TransportException('RETRY');
  20568. }
  20569. protected function getOptionsForUrl($originUrl, $additionalOptions)
  20570. {
  20571. if (defined('HHVM_VERSION')) {
  20572. $phpVersion = 'HHVM ' . HHVM_VERSION;
  20573. } else {
  20574. $phpVersion = 'PHP ' . PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;
  20575. }
  20576. $headers = array(
  20577. sprintf(
  20578. 'User-Agent: Composer/%s (%s; %s; %s)',
  20579. Composer::VERSION === '@package_version@' ? 'source' : Composer::VERSION,
  20580. php_uname('s'),
  20581. php_uname('r'),
  20582. $phpVersion
  20583. )
  20584. );
  20585. if (extension_loaded('zlib')) {
  20586. $headers[] = 'Accept-Encoding: gzip';
  20587. }
  20588. $options = array_replace_recursive($this->options, $additionalOptions);
  20589. if ($this->io->hasAuthentication($originUrl)) {
  20590. $auth = $this->io->getAuthentication($originUrl);
  20591. if ('github.com' === $originUrl && 'x-oauth-basic' === $auth['password']) {
  20592. $options['github-token'] = $auth['username'];
  20593. } elseif ($originUrl === $this->config->get('gitlab-domains')[0]) {
  20594. if($auth['password'] === 'oauth2') {
  20595. $headers[] = 'Authorization: Bearer '.$auth['username'];
  20596. }
  20597. } else {
  20598. $authStr = base64_encode($auth['username'] . ':' . $auth['password']);
  20599. $headers[] = 'Authorization: Basic '.$authStr;
  20600. }
  20601. }
  20602. if (isset($options['http']['header']) && !is_array($options['http']['header'])) {
  20603. $options['http']['header'] = explode("\r\n", trim($options['http']['header'], "\r\n"));
  20604. }
  20605. foreach ($headers as $header) {
  20606. $options['http']['header'][] = $header;
  20607. }
  20608. if($this->config && $this->config->get('gitlab-domains') && $originUrl == $this->config->get('gitlab-domains')[0]) {
  20609. $options['retry-auth-failure'] = false;
  20610. }
  20611. return $options;
  20612. }
  20613. }
  20614. <?php
  20615. namespace Composer\Util;
  20616. use Composer\Json\JsonFile;
  20617. class SpdxLicenseIdentifier
  20618. {
  20619. private $identifiers;
  20620. public function __construct()
  20621. {
  20622. $this->initIdentifiers();
  20623. }
  20624. public function validate($license)
  20625. {
  20626. if (is_array($license)) {
  20627. $count = count($license);
  20628. if ($count !== count(array_filter($license, 'is_string'))) {
  20629. throw new \InvalidArgumentException('Array of strings expected.');
  20630. }
  20631. $license = $count > 1 ? '('.implode(' or ', $license).')' : (string) reset($license);
  20632. }
  20633. if (!is_string($license)) {
  20634. throw new \InvalidArgumentException(sprintf(
  20635. 'Array or String expected, %s given.', gettype($license)
  20636. ));
  20637. }
  20638. return $this->isValidLicenseString($license);
  20639. }
  20640. private function initIdentifiers()
  20641. {
  20642. $jsonFile = new JsonFile(__DIR__ . '/../../../res/spdx-identifier.json');
  20643. $this->identifiers = $jsonFile->read();
  20644. }
  20645. private function isValidLicenseIdentifier($identifier)
  20646. {
  20647. return in_array($identifier, $this->identifiers);
  20648. }
  20649. private function isValidLicenseString($license)
  20650. {
  20651. $tokens = array(
  20652. 'po' => '\(',
  20653. 'pc' => '\)',
  20654. 'op' => '(?:or|and)',
  20655. 'lix' => '(?:NONE|NOASSERTION)',
  20656. 'lir' => 'LicenseRef-\d+',
  20657. 'lic' => '[-+_.a-zA-Z0-9]{3,}',
  20658. 'ws' => '\s+',
  20659. '_' => '.',
  20660. );
  20661. $next = function () use ($license, $tokens) {
  20662. static $offset = 0;
  20663. if ($offset >= strlen($license)) {
  20664. return null;
  20665. }
  20666. foreach ($tokens as $name => $token) {
  20667. if (false === $r = preg_match('{' . $token . '}', $license, $matches, PREG_OFFSET_CAPTURE, $offset)) {
  20668. throw new \RuntimeException('Pattern for token %s failed (regex error).', $name);
  20669. }
  20670. if ($r === 0) {
  20671. continue;
  20672. }
  20673. if ($matches[0][1] !== $offset) {
  20674. continue;
  20675. }
  20676. $offset += strlen($matches[0][0]);
  20677. return array($name, $matches[0][0]);
  20678. }
  20679. throw new \RuntimeException('At least the last pattern needs to match, but it did not (dot-match-all is missing?).');
  20680. };
  20681. $open = 0;
  20682. $require = 1;
  20683. $lastop = null;
  20684. while (list($token, $string) = $next()) {
  20685. switch ($token) {
  20686. case 'po':
  20687. if ($open || !$require) {
  20688. return false;
  20689. }
  20690. $open = 1;
  20691. break;
  20692. case 'pc':
  20693. if ($open !== 1 || $require || !$lastop) {
  20694. return false;
  20695. }
  20696. $open = 2;
  20697. break;
  20698. case 'op':
  20699. if ($require || !$open) {
  20700. return false;
  20701. }
  20702. $lastop || $lastop = $string;
  20703. if ($lastop !== $string) {
  20704. return false;
  20705. }
  20706. $require = 1;
  20707. break;
  20708. case 'lix':
  20709. if ($open) {
  20710. return false;
  20711. }
  20712. goto lir;
  20713. case 'lic':
  20714. if (!$this->isValidLicenseIdentifier($string)) {
  20715. return false;
  20716. }
  20717. case 'lir':
  20718. lir:
  20719. if (!$require) {
  20720. return false;
  20721. }
  20722. $require = 0;
  20723. break;
  20724. case 'ws':
  20725. break;
  20726. case '_':
  20727. return false;
  20728. default:
  20729. throw new \RuntimeException(sprintf('Unparsed token: %s.', print_r($token, true)));
  20730. }
  20731. }
  20732. return !($open % 2 || $require);
  20733. }
  20734. }
  20735. <?php
  20736. namespace Composer\Util;
  20737. final class StreamContextFactory
  20738. {
  20739. public static function getContext($url, array $defaultOptions = array(), array $defaultParams = array())
  20740. {
  20741. $options = array('http' => array(
  20742. 'follow_location' => 1,
  20743. 'max_redirects' => 20,
  20744. ));
  20745. if (!empty($_SERVER['HTTP_PROXY']) || !empty($_SERVER['http_proxy'])) {
  20746. $proxy = parse_url(!empty($_SERVER['http_proxy']) ? $_SERVER['http_proxy'] : $_SERVER['HTTP_PROXY']);
  20747. }
  20748. if (preg_match('{^https://}i', $url) && (!empty($_SERVER['HTTPS_PROXY']) || !empty($_SERVER['https_proxy']))) {
  20749. $proxy = parse_url(!empty($_SERVER['https_proxy']) ? $_SERVER['https_proxy'] : $_SERVER['HTTPS_PROXY']);
  20750. }
  20751. if (!empty($_SERVER['no_proxy']) && parse_url($url, PHP_URL_HOST)) {
  20752. $pattern = new NoProxyPattern($_SERVER['no_proxy']);
  20753. if ($pattern->test($url)) {
  20754. unset($proxy);
  20755. }
  20756. }
  20757. if (!empty($proxy)) {
  20758. $proxyURL = isset($proxy['scheme']) ? $proxy['scheme'] . '://' : '';
  20759. $proxyURL .= isset($proxy['host']) ? $proxy['host'] : '';
  20760. if (isset($proxy['port'])) {
  20761. $proxyURL .= ":" . $proxy['port'];
  20762. } elseif ('http://' == substr($proxyURL, 0, 7)) {
  20763. $proxyURL .= ":80";
  20764. } elseif ('https://' == substr($proxyURL, 0, 8)) {
  20765. $proxyURL .= ":443";
  20766. }
  20767. $proxyURL = str_replace(array('http://', 'https://'), array('tcp://', 'ssl://'), $proxyURL);
  20768. if (0 === strpos($proxyURL, 'ssl:') && !extension_loaded('openssl')) {
  20769. throw new \RuntimeException('You must enable the openssl extension to use a proxy over https');
  20770. }
  20771. $options['http']['proxy'] = $proxyURL;
  20772. switch (parse_url($url, PHP_URL_SCHEME)) {
  20773. case 'http':
  20774. $reqFullUriEnv = getenv('HTTP_PROXY_REQUEST_FULLURI');
  20775. if ($reqFullUriEnv === false || $reqFullUriEnv === '' || (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv)) {
  20776. $options['http']['request_fulluri'] = true;
  20777. }
  20778. break;
  20779. case 'https':
  20780. $reqFullUriEnv = getenv('HTTPS_PROXY_REQUEST_FULLURI');
  20781. if ($reqFullUriEnv === false || $reqFullUriEnv === '' || (strtolower($reqFullUriEnv) !== 'false' && (bool) $reqFullUriEnv)) {
  20782. $options['http']['request_fulluri'] = true;
  20783. }
  20784. break;
  20785. }
  20786. if ('https' === parse_url($url, PHP_URL_SCHEME)) {
  20787. $options['ssl']['SNI_enabled'] = true;
  20788. if (version_compare(PHP_VERSION, '5.6.0', '<')) {
  20789. $options['ssl']['SNI_server_name'] = parse_url($url, PHP_URL_HOST);
  20790. }
  20791. }
  20792. if (isset($proxy['user'])) {
  20793. $auth = urldecode($proxy['user']);
  20794. if (isset($proxy['pass'])) {
  20795. $auth .= ':' . urldecode($proxy['pass']);
  20796. }
  20797. $auth = base64_encode($auth);
  20798. if (isset($defaultOptions['http']['header'])) {
  20799. if (is_string($defaultOptions['http']['header'])) {
  20800. $defaultOptions['http']['header'] = array($defaultOptions['http']['header']);
  20801. }
  20802. $defaultOptions['http']['header'][] = "Proxy-Authorization: Basic {$auth}";
  20803. } else {
  20804. $options['http']['header'] = array("Proxy-Authorization: Basic {$auth}");
  20805. }
  20806. }
  20807. }
  20808. $options = array_replace_recursive($options, $defaultOptions);
  20809. if (isset($options['http']['header'])) {
  20810. $options['http']['header'] = self::fixHttpHeaderField($options['http']['header']);
  20811. }
  20812. return stream_context_create($options, $defaultParams);
  20813. }
  20814. private static function fixHttpHeaderField($header)
  20815. {
  20816. if (!is_array($header)) {
  20817. $header = explode("\r\n", $header);
  20818. }
  20819. uasort($header, function ($el) {
  20820. return preg_match('{^content-type}i', $el) ? 1 : -1;
  20821. });
  20822. return $header;
  20823. }
  20824. }
  20825. <?php
  20826. namespace Composer\Util;
  20827. use Composer\Config;
  20828. use Composer\IO\IOInterface;
  20829. class Svn
  20830. {
  20831. const MAX_QTY_AUTH_TRIES = 5;
  20832. protected $credentials;
  20833. protected $hasAuth;
  20834. protected $io;
  20835. protected $url;
  20836. protected $cacheCredentials = true;
  20837. protected $process;
  20838. protected $qtyAuthTries = 0;
  20839. protected $config;
  20840. public function __construct($url, IOInterface $io, Config $config, ProcessExecutor $process = null)
  20841. {
  20842. $this->url = $url;
  20843. $this->io = $io;
  20844. $this->config = $config;
  20845. $this->process = $process ?: new ProcessExecutor;
  20846. }
  20847. public static function cleanEnv()
  20848. {
  20849. putenv("DYLD_LIBRARY_PATH");
  20850. }
  20851. public function execute($command, $url, $cwd = null, $path = null, $verbose = false)
  20852. {
  20853. $svnCommand = $this->getCommand($command, $url, $path);
  20854. $output = null;
  20855. $io = $this->io;
  20856. $handler = function ($type, $buffer) use (&$output, $io, $verbose) {
  20857. if ($type !== 'out') {
  20858. return;
  20859. }
  20860. if ('Redirecting to URL ' === substr($buffer, 0, 19)) {
  20861. return;
  20862. }
  20863. $output .= $buffer;
  20864. if ($verbose) {
  20865. $io->writeError($buffer, false);
  20866. }
  20867. };
  20868. $status = $this->process->execute($svnCommand, $handler, $cwd);
  20869. if (0 === $status) {
  20870. return $output;
  20871. }
  20872. if (empty($output)) {
  20873. $output = $this->process->getErrorOutput();
  20874. }
  20875. if (false === stripos($output, 'Could not authenticate to server:')
  20876. && false === stripos($output, 'authorization failed')
  20877. && false === stripos($output, 'svn: E170001:')
  20878. && false === stripos($output, 'svn: E215004:')) {
  20879. throw new \RuntimeException($output);
  20880. }
  20881. if (!$this->hasAuth()) {
  20882. $this->doAuthDance();
  20883. }
  20884. if ($this->qtyAuthTries++ < self::MAX_QTY_AUTH_TRIES) {
  20885. return $this->execute($command, $url, $cwd, $path, $verbose);
  20886. }
  20887. throw new \RuntimeException(
  20888. 'wrong credentials provided ('.$output.')'
  20889. );
  20890. }
  20891. public function setCacheCredentials($cacheCredentials)
  20892. {
  20893. $this->cacheCredentials = $cacheCredentials;
  20894. }
  20895. protected function doAuthDance()
  20896. {
  20897. if (!$this->io->isInteractive()) {
  20898. throw new \RuntimeException(
  20899. 'can not ask for authentication in non interactive mode'
  20900. );
  20901. }
  20902. $this->io->writeError("The Subversion server ({$this->url}) requested credentials:");
  20903. $this->hasAuth = true;
  20904. $this->credentials['username'] = $this->io->ask("Username: ");
  20905. $this->credentials['password'] = $this->io->askAndHideAnswer("Password: ");
  20906. $this->cacheCredentials = $this->io->askConfirmation("Should Subversion cache these credentials? (yes/no) ", true);
  20907. return $this;
  20908. }
  20909. protected function getCommand($cmd, $url, $path = null)
  20910. {
  20911. $cmd = sprintf('%s %s%s %s',
  20912. $cmd,
  20913. '--non-interactive ',
  20914. $this->getCredentialString(),
  20915. ProcessExecutor::escape($url)
  20916. );
  20917. if ($path) {
  20918. $cmd .= ' ' . ProcessExecutor::escape($path);
  20919. }
  20920. return $cmd;
  20921. }
  20922. protected function getCredentialString()
  20923. {
  20924. if (!$this->hasAuth()) {
  20925. return '';
  20926. }
  20927. return sprintf(
  20928. ' %s--username %s --password %s ',
  20929. $this->getAuthCache(),
  20930. ProcessExecutor::escape($this->getUsername()),
  20931. ProcessExecutor::escape($this->getPassword())
  20932. );
  20933. }
  20934. protected function getPassword()
  20935. {
  20936. if ($this->credentials === null) {
  20937. throw new \LogicException("No svn auth detected.");
  20938. }
  20939. return isset($this->credentials['password']) ? $this->credentials['password'] : '';
  20940. }
  20941. protected function getUsername()
  20942. {
  20943. if ($this->credentials === null) {
  20944. throw new \LogicException("No svn auth detected.");
  20945. }
  20946. return $this->credentials['username'];
  20947. }
  20948. protected function hasAuth()
  20949. {
  20950. if (null !== $this->hasAuth) {
  20951. return $this->hasAuth;
  20952. }
  20953. if (false === $this->createAuthFromConfig()) {
  20954. $this->createAuthFromUrl();
  20955. }
  20956. return $this->hasAuth;
  20957. }
  20958. protected function getAuthCache()
  20959. {
  20960. return $this->cacheCredentials ? '' : '--no-auth-cache ';
  20961. }
  20962. private function createAuthFromConfig()
  20963. {
  20964. if (!$this->config->has('http-basic')) {
  20965. return $this->hasAuth = false;
  20966. }
  20967. $authConfig = $this->config->get('http-basic');
  20968. $host = parse_url($this->url, PHP_URL_HOST);
  20969. if (isset($authConfig[$host])) {
  20970. $this->credentials['username'] = $authConfig[$host]['username'];
  20971. $this->credentials['password'] = $authConfig[$host]['password'];
  20972. return $this->hasAuth = true;
  20973. }
  20974. return $this->hasAuth = false;
  20975. }
  20976. private function createAuthFromUrl()
  20977. {
  20978. $uri = parse_url($this->url);
  20979. if (empty($uri['user'])) {
  20980. return $this->hasAuth = false;
  20981. }
  20982. $this->credentials['username'] = $uri['user'];
  20983. if (!empty($uri['pass'])) {
  20984. $this->credentials['password'] = $uri['pass'];
  20985. }
  20986. return $this->hasAuth = true;
  20987. }
  20988. }
  20989. <?php
  20990. /*
  20991. * This file is part of Composer.
  20992. *
  20993. * (c) Nils Adermann <naderman@naderman.de>
  20994. * Jordi Boggiano <j.boggiano@seld.be>
  20995. *
  20996. * For the full copyright and license information, please view the LICENSE
  20997. * file that was distributed with this source code.
  20998. */
  20999. namespace Composer\Autoload;
  21000. /**
  21001. * ClassLoader implements a PSR-0 class loader
  21002. *
  21003. * See https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md
  21004. *
  21005. * $loader = new \Composer\Autoload\ClassLoader();
  21006. *
  21007. * // register classes with namespaces
  21008. * $loader->add('Symfony\Component', __DIR__.'/component');
  21009. * $loader->add('Symfony', __DIR__.'/framework');
  21010. *
  21011. * // activate the autoloader
  21012. * $loader->register();
  21013. *
  21014. * // to enable searching the include path (eg. for PEAR packages)
  21015. * $loader->setUseIncludePath(true);
  21016. *
  21017. * In this example, if you try to use a class in the Symfony\Component
  21018. * namespace or one of its children (Symfony\Component\Console for instance),
  21019. * the autoloader will first look for the class under the component/
  21020. * directory, and it will then fallback to the framework/ directory if not
  21021. * found before giving up.
  21022. *
  21023. * This class is loosely based on the Symfony UniversalClassLoader.
  21024. *
  21025. * @author Fabien Potencier <fabien@symfony.com>
  21026. * @author Jordi Boggiano <j.boggiano@seld.be>
  21027. */
  21028. class ClassLoader
  21029. {
  21030. // PSR-4
  21031. private $prefixLengthsPsr4 = array();
  21032. private $prefixDirsPsr4 = array();
  21033. private $fallbackDirsPsr4 = array();
  21034. // PSR-0
  21035. private $prefixesPsr0 = array();
  21036. private $fallbackDirsPsr0 = array();
  21037. private $useIncludePath = false;
  21038. private $classMap = array();
  21039. private $classMapAuthoritative = false;
  21040. public function getPrefixes()
  21041. {
  21042. if (!empty($this->prefixesPsr0)) {
  21043. return call_user_func_array('array_merge', $this->prefixesPsr0);
  21044. }
  21045. return array();
  21046. }
  21047. public function getPrefixesPsr4()
  21048. {
  21049. return $this->prefixDirsPsr4;
  21050. }
  21051. public function getFallbackDirs()
  21052. {
  21053. return $this->fallbackDirsPsr0;
  21054. }
  21055. public function getFallbackDirsPsr4()
  21056. {
  21057. return $this->fallbackDirsPsr4;
  21058. }
  21059. public function getClassMap()
  21060. {
  21061. return $this->classMap;
  21062. }
  21063. /**
  21064. * @param array $classMap Class to filename map
  21065. */
  21066. public function addClassMap(array $classMap)
  21067. {
  21068. if ($this->classMap) {
  21069. $this->classMap = array_merge($this->classMap, $classMap);
  21070. } else {
  21071. $this->classMap = $classMap;
  21072. }
  21073. }
  21074. /**
  21075. * Registers a set of PSR-0 directories for a given prefix, either
  21076. * appending or prepending to the ones previously set for this prefix.
  21077. *
  21078. * @param string $prefix The prefix
  21079. * @param array|string $paths The PSR-0 root directories
  21080. * @param bool $prepend Whether to prepend the directories
  21081. */
  21082. public function add($prefix, $paths, $prepend = false)
  21083. {
  21084. if (!$prefix) {
  21085. if ($prepend) {
  21086. $this->fallbackDirsPsr0 = array_merge(
  21087. (array) $paths,
  21088. $this->fallbackDirsPsr0
  21089. );
  21090. } else {
  21091. $this->fallbackDirsPsr0 = array_merge(
  21092. $this->fallbackDirsPsr0,
  21093. (array) $paths
  21094. );
  21095. }
  21096. return;
  21097. }
  21098. $first = $prefix[0];
  21099. if (!isset($this->prefixesPsr0[$first][$prefix])) {
  21100. $this->prefixesPsr0[$first][$prefix] = (array) $paths;
  21101. return;
  21102. }
  21103. if ($prepend) {
  21104. $this->prefixesPsr0[$first][$prefix] = array_merge(
  21105. (array) $paths,
  21106. $this->prefixesPsr0[$first][$prefix]
  21107. );
  21108. } else {
  21109. $this->prefixesPsr0[$first][$prefix] = array_merge(
  21110. $this->prefixesPsr0[$first][$prefix],
  21111. (array) $paths
  21112. );
  21113. }
  21114. }
  21115. /**
  21116. * Registers a set of PSR-4 directories for a given namespace, either
  21117. * appending or prepending to the ones previously set for this namespace.
  21118. *
  21119. * @param string $prefix The prefix/namespace, with trailing '\\'
  21120. * @param array|string $paths The PSR-0 base directories
  21121. * @param bool $prepend Whether to prepend the directories
  21122. *
  21123. * @throws \InvalidArgumentException
  21124. */
  21125. public function addPsr4($prefix, $paths, $prepend = false)
  21126. {
  21127. if (!$prefix) {
  21128. // Register directories for the root namespace.
  21129. if ($prepend) {
  21130. $this->fallbackDirsPsr4 = array_merge(
  21131. (array) $paths,
  21132. $this->fallbackDirsPsr4
  21133. );
  21134. } else {
  21135. $this->fallbackDirsPsr4 = array_merge(
  21136. $this->fallbackDirsPsr4,
  21137. (array) $paths
  21138. );
  21139. }
  21140. } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
  21141. // Register directories for a new namespace.
  21142. $length = strlen($prefix);
  21143. if ('\\' !== $prefix[$length - 1]) {
  21144. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  21145. }
  21146. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  21147. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  21148. } elseif ($prepend) {
  21149. // Prepend directories for an already registered namespace.
  21150. $this->prefixDirsPsr4[$prefix] = array_merge(
  21151. (array) $paths,
  21152. $this->prefixDirsPsr4[$prefix]
  21153. );
  21154. } else {
  21155. // Append directories for an already registered namespace.
  21156. $this->prefixDirsPsr4[$prefix] = array_merge(
  21157. $this->prefixDirsPsr4[$prefix],
  21158. (array) $paths
  21159. );
  21160. }
  21161. }
  21162. /**
  21163. * Registers a set of PSR-0 directories for a given prefix,
  21164. * replacing any others previously set for this prefix.
  21165. *
  21166. * @param string $prefix The prefix
  21167. * @param array|string $paths The PSR-0 base directories
  21168. */
  21169. public function set($prefix, $paths)
  21170. {
  21171. if (!$prefix) {
  21172. $this->fallbackDirsPsr0 = (array) $paths;
  21173. } else {
  21174. $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
  21175. }
  21176. }
  21177. /**
  21178. * Registers a set of PSR-4 directories for a given namespace,
  21179. * replacing any others previously set for this namespace.
  21180. *
  21181. * @param string $prefix The prefix/namespace, with trailing '\\'
  21182. * @param array|string $paths The PSR-4 base directories
  21183. *
  21184. * @throws \InvalidArgumentException
  21185. */
  21186. public function setPsr4($prefix, $paths)
  21187. {
  21188. if (!$prefix) {
  21189. $this->fallbackDirsPsr4 = (array) $paths;
  21190. } else {
  21191. $length = strlen($prefix);
  21192. if ('\\' !== $prefix[$length - 1]) {
  21193. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  21194. }
  21195. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  21196. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  21197. }
  21198. }
  21199. /**
  21200. * Turns on searching the include path for class files.
  21201. *
  21202. * @param bool $useIncludePath
  21203. */
  21204. public function setUseIncludePath($useIncludePath)
  21205. {
  21206. $this->useIncludePath = $useIncludePath;
  21207. }
  21208. /**
  21209. * Can be used to check if the autoloader uses the include path to check
  21210. * for classes.
  21211. *
  21212. * @return bool
  21213. */
  21214. public function getUseIncludePath()
  21215. {
  21216. return $this->useIncludePath;
  21217. }
  21218. /**
  21219. * Turns off searching the prefix and fallback directories for classes
  21220. * that have not been registered with the class map.
  21221. *
  21222. * @param bool $classMapAuthoritative
  21223. */
  21224. public function setClassMapAuthoritative($classMapAuthoritative)
  21225. {
  21226. $this->classMapAuthoritative = $classMapAuthoritative;
  21227. }
  21228. /**
  21229. * Should class lookup fail if not found in the current class map?
  21230. *
  21231. * @return bool
  21232. */
  21233. public function isClassMapAuthoritative()
  21234. {
  21235. return $this->classMapAuthoritative;
  21236. }
  21237. /**
  21238. * Registers this instance as an autoloader.
  21239. *
  21240. * @param bool $prepend Whether to prepend the autoloader or not
  21241. */
  21242. public function register($prepend = false)
  21243. {
  21244. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  21245. }
  21246. /**
  21247. * Unregisters this instance as an autoloader.
  21248. */
  21249. public function unregister()
  21250. {
  21251. spl_autoload_unregister(array($this, 'loadClass'));
  21252. }
  21253. /**
  21254. * Loads the given class or interface.
  21255. *
  21256. * @param string $class The name of the class
  21257. * @return bool|null True if loaded, null otherwise
  21258. */
  21259. public function loadClass($class)
  21260. {
  21261. if ($file = $this->findFile($class)) {
  21262. includeFile($file);
  21263. return true;
  21264. }
  21265. }
  21266. /**
  21267. * Finds the path to the file where the class is defined.
  21268. *
  21269. * @param string $class The name of the class
  21270. *
  21271. * @return string|false The path if found, false otherwise
  21272. */
  21273. public function findFile($class)
  21274. {
  21275. // work around for PHP 5.3.0 - 5.3.2 https://bugs.php.net/50731
  21276. if ('\\' == $class[0]) {
  21277. $class = substr($class, 1);
  21278. }
  21279. // class map lookup
  21280. if (isset($this->classMap[$class])) {
  21281. return $this->classMap[$class];
  21282. }
  21283. if ($this->classMapAuthoritative) {
  21284. return false;
  21285. }
  21286. $file = $this->findFileWithExtension($class, '.php');
  21287. // Search for Hack files if we are running on HHVM
  21288. if ($file === null && defined('HHVM_VERSION')) {
  21289. $file = $this->findFileWithExtension($class, '.hh');
  21290. }
  21291. if ($file === null) {
  21292. // Remember that this class does not exist.
  21293. return $this->classMap[$class] = false;
  21294. }
  21295. return $file;
  21296. }
  21297. private function findFileWithExtension($class, $ext)
  21298. {
  21299. // PSR-4 lookup
  21300. $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  21301. $first = $class[0];
  21302. if (isset($this->prefixLengthsPsr4[$first])) {
  21303. foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
  21304. if (0 === strpos($class, $prefix)) {
  21305. foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
  21306. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
  21307. return $file;
  21308. }
  21309. }
  21310. }
  21311. }
  21312. }
  21313. // PSR-4 fallback dirs
  21314. foreach ($this->fallbackDirsPsr4 as $dir) {
  21315. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
  21316. return $file;
  21317. }
  21318. }
  21319. // PSR-0 lookup
  21320. if (false !== $pos = strrpos($class, '\\')) {
  21321. // namespaced class name
  21322. $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
  21323. . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  21324. } else {
  21325. // PEAR-like class name
  21326. $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  21327. }
  21328. if (isset($this->prefixesPsr0[$first])) {
  21329. foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
  21330. if (0 === strpos($class, $prefix)) {
  21331. foreach ($dirs as $dir) {
  21332. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  21333. return $file;
  21334. }
  21335. }
  21336. }
  21337. }
  21338. }
  21339. // PSR-0 fallback dirs
  21340. foreach ($this->fallbackDirsPsr0 as $dir) {
  21341. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  21342. return $file;
  21343. }
  21344. }
  21345. // PSR-0 include paths.
  21346. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
  21347. return $file;
  21348. }
  21349. }
  21350. }
  21351. /**
  21352. * Scope isolated include.
  21353. *
  21354. * Prevents access to $this/self from included files.
  21355. */
  21356. function includeFile($file)
  21357. {
  21358. include $file;
  21359. }
  21360. {
  21361. "$schema": "http://json-schema.org/draft-04/schema#",
  21362. "name": "Package",
  21363. "type": "object",
  21364. "additionalProperties": false,
  21365. "required": [ "name", "description" ],
  21366. "properties": {
  21367. "name": {
  21368. "type": "string",
  21369. "description": "Package name, including 'vendor-name/' prefix."
  21370. },
  21371. "type": {
  21372. "description": "Package type, either 'library' for common packages, 'composer-plugin' for plugins, 'metapackage' for empty packages, or a custom type ([a-z0-9-]+) defined by whatever project this package applies to.",
  21373. "type": "string"
  21374. },
  21375. "target-dir": {
  21376. "description": "DEPRECATED: Forces the package to be installed into the given subdirectory path. This is used for autoloading PSR-0 packages that do not contain their full path. Use forward slashes for cross-platform compatibility.",
  21377. "type": "string"
  21378. },
  21379. "description": {
  21380. "type": "string",
  21381. "description": "Short package description."
  21382. },
  21383. "keywords": {
  21384. "type": "array",
  21385. "items": {
  21386. "type": "string",
  21387. "description": "A tag/keyword that this package relates to."
  21388. }
  21389. },
  21390. "homepage": {
  21391. "type": "string",
  21392. "description": "Homepage URL for the project.",
  21393. "format": "uri"
  21394. },
  21395. "version": {
  21396. "type": "string",
  21397. "description": "Package version, see http://getcomposer.org/doc/04-schema.md#version for more info on valid schemes."
  21398. },
  21399. "time": {
  21400. "type": "string",
  21401. "description": "Package release date, in 'YYYY-MM-DD', 'YYYY-MM-DD HH:MM:SS' or 'YYYY-MM-DDTHH:MM:SSZ' format."
  21402. },
  21403. "license": {
  21404. "type": ["string", "array"],
  21405. "description": "License name. Or an array of license names."
  21406. },
  21407. "authors": {
  21408. "type": "array",
  21409. "description": "List of authors that contributed to the package. This is typically the main maintainers, not the full list.",
  21410. "items": {
  21411. "type": "object",
  21412. "additionalProperties": false,
  21413. "required": [ "name"],
  21414. "properties": {
  21415. "name": {
  21416. "type": "string",
  21417. "description": "Full name of the author."
  21418. },
  21419. "email": {
  21420. "type": "string",
  21421. "description": "Email address of the author.",
  21422. "format": "email"
  21423. },
  21424. "homepage": {
  21425. "type": "string",
  21426. "description": "Homepage URL for the author.",
  21427. "format": "uri"
  21428. },
  21429. "role": {
  21430. "type": "string",
  21431. "description": "Author's role in the project."
  21432. }
  21433. }
  21434. }
  21435. },
  21436. "require": {
  21437. "type": "object",
  21438. "description": "This is a hash of package name (keys) and version constraints (values) that are required to run this package.",
  21439. "additionalProperties": true
  21440. },
  21441. "replace": {
  21442. "type": "object",
  21443. "description": "This is a hash of package name (keys) and version constraints (values) that can be replaced by this package.",
  21444. "additionalProperties": true
  21445. },
  21446. "conflict": {
  21447. "type": "object",
  21448. "description": "This is a hash of package name (keys) and version constraints (values) that conflict with this package.",
  21449. "additionalProperties": true
  21450. },
  21451. "provide": {
  21452. "type": "object",
  21453. "description": "This is a hash of package name (keys) and version constraints (values) that this package provides in addition to this package's name.",
  21454. "additionalProperties": true
  21455. },
  21456. "require-dev": {
  21457. "type": "object",
  21458. "description": "This is a hash of package name (keys) and version constraints (values) that this package requires for developing it (testing tools and such).",
  21459. "additionalProperties": true
  21460. },
  21461. "suggest": {
  21462. "type": "object",
  21463. "description": "This is a hash of package name (keys) and descriptions (values) that this package suggests work well with it (this will be suggested to the user during installation).",
  21464. "additionalProperties": true
  21465. },
  21466. "config": {
  21467. "type": "object",
  21468. "description": "Composer options.",
  21469. "properties": {
  21470. "process-timeout": {
  21471. "type": "integer",
  21472. "description": "The timeout in seconds for process executions, defaults to 300 (5mins)."
  21473. },
  21474. "use-include-path": {
  21475. "type": "boolean",
  21476. "description": "If true, the Composer autoloader will also look for classes in the PHP include path."
  21477. },
  21478. "preferred-install": {
  21479. "type": "string",
  21480. "description": "The install method Composer will prefer to use, defaults to auto and can be any of source, dist or auto."
  21481. },
  21482. "notify-on-install": {
  21483. "type": "boolean",
  21484. "description": "Composer allows repositories to define a notification URL, so that they get notified whenever a package from that repository is installed. This option allows you to disable that behaviour, defaults to true."
  21485. },
  21486. "github-protocols": {
  21487. "type": "array",
  21488. "description": "A list of protocols to use for github.com clones, in priority order, defaults to [\"git\", \"https\", \"http\"].",
  21489. "items": {
  21490. "type": "string"
  21491. }
  21492. },
  21493. "github-oauth": {
  21494. "type": "object",
  21495. "description": "A hash of domain name => github API oauth tokens, typically {\"github.com\":\"<token>\"}.",
  21496. "additionalProperties": true
  21497. },
  21498. "http-basic": {
  21499. "type": "object",
  21500. "description": "A hash of domain name => {\"username\": \"...\", \"password\": \"...\"}.",
  21501. "additionalProperties": true
  21502. },
  21503. "store-auths": {
  21504. "type": ["string", "boolean"],
  21505. "description": "What to do after prompting for authentication, one of: true (store), false (do not store) or \"prompt\" (ask every time), defaults to prompt."
  21506. },
  21507. "vendor-dir": {
  21508. "type": "string",
  21509. "description": "The location where all packages are installed, defaults to \"vendor\"."
  21510. },
  21511. "bin-dir": {
  21512. "type": "string",
  21513. "description": "The location where all binaries are linked, defaults to \"vendor/bin\"."
  21514. },
  21515. "cache-dir": {
  21516. "type": "string",
  21517. "description": "The location where all caches are located, defaults to \"~/.composer/cache\" on *nix and \"%LOCALAPPDATA%\\Composer\" on windows."
  21518. },
  21519. "cache-files-dir": {
  21520. "type": "string",
  21521. "description": "The location where files (zip downloads) are cached, defaults to \"{$cache-dir}/files\"."
  21522. },
  21523. "cache-repo-dir": {
  21524. "type": "string",
  21525. "description": "The location where repo (git/hg repo clones) are cached, defaults to \"{$cache-dir}/repo\"."
  21526. },
  21527. "cache-vcs-dir": {
  21528. "type": "string",
  21529. "description": "The location where vcs infos (git clones, github api calls, etc. when reading vcs repos) are cached, defaults to \"{$cache-dir}/vcs\"."
  21530. },
  21531. "cache-ttl": {
  21532. "type": "integer",
  21533. "description": "The default cache time-to-live, defaults to 15552000 (6 months)."
  21534. },
  21535. "cache-files-ttl": {
  21536. "type": "integer",
  21537. "description": "The cache time-to-live for files, defaults to the value of cache-ttl."
  21538. },
  21539. "cache-files-maxsize": {
  21540. "type": ["string", "integer"],
  21541. "description": "The cache max size for the files cache, defaults to \"300MiB\"."
  21542. },
  21543. "discard-changes": {
  21544. "type": ["string", "boolean"],
  21545. "description": "The default style of handling dirty updates, defaults to false and can be any of true, false or \"stash\"."
  21546. },
  21547. "autoloader-suffix": {
  21548. "type": "string",
  21549. "description": "Optional string to be used as a suffix for the generated Composer autoloader. When null a random one will be generated."
  21550. },
  21551. "optimize-autoloader": {
  21552. "type": "boolean",
  21553. "description": "Always optimize when dumping the autoloader."
  21554. },
  21555. "prepend-autoloader": {
  21556. "type": "boolean",
  21557. "description": "If false, the composer autoloader will not be prepended to existing autoloaders, defaults to true."
  21558. },
  21559. "classmap-authoritative": {
  21560. "type": "boolean",
  21561. "description": "If true, the composer autoloader will not scan the filesystem for classes that are not found in the class map, defaults to false."
  21562. },
  21563. "github-domains": {
  21564. "type": "array",
  21565. "description": "A list of domains to use in github mode. This is used for GitHub Enterprise setups, defaults to [\"github.com\"].",
  21566. "items": {
  21567. "type": "string"
  21568. }
  21569. },
  21570. "github-expose-hostname": {
  21571. "type": "boolean",
  21572. "description": "Defaults to true. If set to false, the OAuth tokens created to access the github API will have a date instead of the machine hostname."
  21573. }
  21574. }
  21575. },
  21576. "extra": {
  21577. "type": ["object", "array"],
  21578. "description": "Arbitrary extra data that can be used by plugins, for example, package of type composer-plugin may have a 'class' key defining an installer class name.",
  21579. "additionalProperties": true
  21580. },
  21581. "autoload": {
  21582. "type": "object",
  21583. "description": "Description of how the package can be autoloaded.",
  21584. "properties": {
  21585. "psr-0": {
  21586. "type": "object",
  21587. "description": "This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.",
  21588. "additionalProperties": true
  21589. },
  21590. "psr-4": {
  21591. "type": "object",
  21592. "description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.",
  21593. "additionalProperties": true
  21594. },
  21595. "classmap": {
  21596. "type": "array",
  21597. "description": "This is an array of directories that contain classes to be included in the class-map generation process."
  21598. },
  21599. "files": {
  21600. "type": "array",
  21601. "description": "This is an array of files that are always required on every request."
  21602. }
  21603. }
  21604. },
  21605. "autoload-dev": {
  21606. "type": "object",
  21607. "description": "Description of additional autoload rules for development purpose (eg. a test suite).",
  21608. "properties": {
  21609. "psr-0": {
  21610. "type": "object",
  21611. "description": "This is a hash of namespaces (keys) and the directories they can be found into (values, can be arrays of paths) by the autoloader.",
  21612. "additionalProperties": true
  21613. },
  21614. "psr-4": {
  21615. "type": "object",
  21616. "description": "This is a hash of namespaces (keys) and the PSR-4 directories they can map to (values, can be arrays of paths) by the autoloader.",
  21617. "additionalProperties": true
  21618. },
  21619. "classmap": {
  21620. "type": "array",
  21621. "description": "This is an array of directories that contain classes to be included in the class-map generation process."
  21622. },
  21623. "files": {
  21624. "type": "array",
  21625. "description": "This is an array of files that are always required on every request."
  21626. }
  21627. }
  21628. },
  21629. "archive": {
  21630. "type": ["object"],
  21631. "description": "Options for creating package archives for distribution.",
  21632. "properties": {
  21633. "exclude": {
  21634. "type": "array",
  21635. "description": "A list of patterns for paths to exclude or include if prefixed with an exclamation mark."
  21636. }
  21637. }
  21638. },
  21639. "repositories": {
  21640. "type": ["object", "array"],
  21641. "description": "A set of additional repositories where packages can be found.",
  21642. "additionalProperties": true
  21643. },
  21644. "minimum-stability": {
  21645. "type": ["string"],
  21646. "description": "The minimum stability the packages must have to be install-able. Possible values are: dev, alpha, beta, RC, stable.",
  21647. "pattern": "^dev|alpha|beta|rc|RC|stable$"
  21648. },
  21649. "prefer-stable": {
  21650. "type": ["boolean"],
  21651. "description": "If set to true, stable packages will be prefered to dev packages when possible, even if the minimum-stability allows unstable packages."
  21652. },
  21653. "bin": {
  21654. "type": ["array"],
  21655. "description": "A set of files that should be treated as binaries and symlinked into bin-dir (from config).",
  21656. "items": {
  21657. "type": "string"
  21658. }
  21659. },
  21660. "include-path": {
  21661. "type": ["array"],
  21662. "description": "DEPRECATED: A list of directories which should get added to PHP's include path. This is only present to support legacy projects, and all new code should preferably use autoloading.",
  21663. "items": {
  21664. "type": "string"
  21665. }
  21666. },
  21667. "scripts": {
  21668. "type": ["object"],
  21669. "description": "Scripts listeners that will be executed before/after some events.",
  21670. "properties": {
  21671. "pre-install-cmd": {
  21672. "type": ["array", "string"],
  21673. "description": "Occurs before the install command is executed, contains one or more Class::method callables or shell commands."
  21674. },
  21675. "post-install-cmd": {
  21676. "type": ["array", "string"],
  21677. "description": "Occurs after the install command is executed, contains one or more Class::method callables or shell commands."
  21678. },
  21679. "pre-update-cmd": {
  21680. "type": ["array", "string"],
  21681. "description": "Occurs before the update command is executed, contains one or more Class::method callables or shell commands."
  21682. },
  21683. "post-update-cmd": {
  21684. "type": ["array", "string"],
  21685. "description": "Occurs after the update command is executed, contains one or more Class::method callables or shell commands."
  21686. },
  21687. "pre-status-cmd": {
  21688. "type": ["array", "string"],
  21689. "description": "Occurs before the status command is executed, contains one or more Class::method callables or shell commands."
  21690. },
  21691. "post-status-cmd": {
  21692. "type": ["array", "string"],
  21693. "description": "Occurs after the status command is executed, contains one or more Class::method callables or shell commands."
  21694. },
  21695. "pre-package-install": {
  21696. "type": ["array", "string"],
  21697. "description": "Occurs before a package is installed, contains one or more Class::method callables or shell commands."
  21698. },
  21699. "post-package-install": {
  21700. "type": ["array", "string"],
  21701. "description": "Occurs after a package is installed, contains one or more Class::method callables or shell commands."
  21702. },
  21703. "pre-package-update": {
  21704. "type": ["array", "string"],
  21705. "description": "Occurs before a package is updated, contains one or more Class::method callables or shell commands."
  21706. },
  21707. "post-package-update": {
  21708. "type": ["array", "string"],
  21709. "description": "Occurs after a package is updated, contains one or more Class::method callables or shell commands."
  21710. },
  21711. "pre-package-uninstall": {
  21712. "type": ["array", "string"],
  21713. "description": "Occurs before a package has been uninstalled, contains one or more Class::method callables or shell commands."
  21714. },
  21715. "post-package-uninstall": {
  21716. "type": ["array", "string"],
  21717. "description": "Occurs after a package has been uninstalled, contains one or more Class::method callables or shell commands."
  21718. },
  21719. "pre-autoload-dump": {
  21720. "type": ["array", "string"],
  21721. "description": "Occurs before the autoloader is dumped, contains one or more Class::method callables or shell commands."
  21722. },
  21723. "post-autoload-dump": {
  21724. "type": ["array", "string"],
  21725. "description": "Occurs after the autoloader is dumped, contains one or more Class::method callables or shell commands."
  21726. },
  21727. "post-root-package-install": {
  21728. "type": ["array", "string"],
  21729. "description": "Occurs after the root-package is installed, contains one or more Class::method callables or shell commands."
  21730. },
  21731. "post-create-project-cmd": {
  21732. "type": ["array", "string"],
  21733. "description": "Occurs after the create-project command is executed, contains one or more Class::method callables or shell commands."
  21734. }
  21735. }
  21736. },
  21737. "support": {
  21738. "type": "object",
  21739. "properties": {
  21740. "email": {
  21741. "type": "string",
  21742. "description": "Email address for support.",
  21743. "format": "email"
  21744. },
  21745. "issues": {
  21746. "type": "string",
  21747. "description": "URL to the Issue Tracker.",
  21748. "format": "uri"
  21749. },
  21750. "forum": {
  21751. "type": "string",
  21752. "description": "URL to the Forum.",
  21753. "format": "uri"
  21754. },
  21755. "wiki": {
  21756. "type": "string",
  21757. "description": "URL to the Wiki.",
  21758. "format": "uri"
  21759. },
  21760. "irc": {
  21761. "type": "string",
  21762. "description": "IRC channel for support, as irc://server/channel.",
  21763. "format": "uri"
  21764. },
  21765. "source": {
  21766. "type": "string",
  21767. "description": "URL to browse or download the sources.",
  21768. "format": "uri"
  21769. }
  21770. }
  21771. },
  21772. "non-feature-branches": {
  21773. "type": ["array"],
  21774. "description": "A set of string or regex patterns for non-numeric branch names that will not be handles as feature branches.",
  21775. "items": {
  21776. "type": "string"
  21777. }
  21778. }
  21779. }
  21780. }
  21781. [
  21782. "Glide", "Abstyles", "AFL-1.1", "AFL-1.2", "AFL-2.0", "AFL-2.1", "AFL-3.0",
  21783. "AMPAS", "APL-1.0", "Adobe-Glyph", "APAFML", "Adobe-2006", "AGPL-1.0",
  21784. "Afmparse", "Aladdin", "ADSL", "AMDPLPA", "ANTLR-PD", "Apache-1.0",
  21785. "Apache-1.1", "Apache-2.0", "AML", "APSL-1.0", "APSL-1.1", "APSL-1.2",
  21786. "APSL-2.0", "Artistic-1.0", "Artistic-1.0-Perl", "Artistic-1.0-cl8",
  21787. "Artistic-2.0", "AAL", "Bahyph", "Barr", "Beerware", "BitTorrent-1.0",
  21788. "BitTorrent-1.1", "BSL-1.0", "Borceux", "BSD-2-Clause",
  21789. "BSD-2-Clause-FreeBSD", "BSD-2-Clause-NetBSD", "BSD-3-Clause",
  21790. "BSD-3-Clause-Clear", "BSD-4-Clause", "BSD-Protection",
  21791. "BSD-3-Clause-Attribution", "BSD-4-Clause-UC", "bzip2-1.0.5", "bzip2-1.0.6",
  21792. "Caldera", "CECILL-1.0", "CECILL-1.1", "CECILL-2.0", "CECILL-B", "CECILL-C",
  21793. "ClArtistic", "MIT-CMU", "CNRI-Python", "CNRI-Python-GPL-Compatible",
  21794. "CPOL-1.02", "CDDL-1.0", "CDDL-1.1", "CPAL-1.0", "CPL-1.0", "CATOSL-1.1",
  21795. "Condor-1.1", "CC-BY-1.0", "CC-BY-2.0", "CC-BY-2.5", "CC-BY-3.0",
  21796. "CC-BY-4.0", "CC-BY-ND-1.0", "CC-BY-ND-2.0", "CC-BY-ND-2.5", "CC-BY-ND-3.0",
  21797. "CC-BY-ND-4.0", "CC-BY-NC-1.0", "CC-BY-NC-2.0", "CC-BY-NC-2.5",
  21798. "CC-BY-NC-3.0", "CC-BY-NC-4.0", "CC-BY-NC-ND-1.0", "CC-BY-NC-ND-2.0",
  21799. "CC-BY-NC-ND-2.5", "CC-BY-NC-ND-3.0", "CC-BY-NC-ND-4.0", "CC-BY-NC-SA-1.0",
  21800. "CC-BY-NC-SA-2.0", "CC-BY-NC-SA-2.5", "CC-BY-NC-SA-3.0", "CC-BY-NC-SA-4.0",
  21801. "CC-BY-SA-1.0", "CC-BY-SA-2.0", "CC-BY-SA-2.5", "CC-BY-SA-3.0",
  21802. "CC-BY-SA-4.0", "CC0-1.0", "Crossword", "CUA-OPL-1.0", "Cube", "D-FSL-1.0",
  21803. "diffmark", "WTFPL", "DOC", "Dotseqn", "DSDP", "dvipdfm", "EPL-1.0",
  21804. "eCos-2.0", "ECL-1.0", "ECL-2.0", "eGenix", "EFL-1.0", "EFL-2.0",
  21805. "MIT-advertising", "MIT-enna", "Entessa", "ErlPL-1.1", "EUDatagrid",
  21806. "EUPL-1.0", "EUPL-1.1", "Eurosym", "Fair", "MIT-feh", "Frameworx-1.0",
  21807. "FTL", "FSFUL", "FSFULLR", "Giftware", "GL2PS", "Glulxe", "AGPL-3.0",
  21808. "GFDL-1.1", "GFDL-1.2", "GFDL-1.3", "GPL-1.0", "GPL-1.0+", "GPL-2.0",
  21809. "GPL-2.0+", "GPL-2.0-with-autoconf-exception",
  21810. "GPL-2.0-with-bison-exception", "GPL-2.0-with-classpath-exception",
  21811. "GPL-2.0-with-font-exception", "GPL-2.0-with-GCC-exception", "GPL-3.0",
  21812. "GPL-3.0+", "GPL-3.0-with-autoconf-exception", "GPL-3.0-with-GCC-exception",
  21813. "LGPL-2.1", "LGPL-2.1+", "LGPL-3.0", "LGPL-3.0+", "LGPL-2.0", "LGPL-2.0+",
  21814. "gnuplot", "gSOAP-1.3b", "HaskellReport", "HPND", "IBM-pibs", "IPL-1.0",
  21815. "ImageMagick", "iMatix", "Imlib2", "IJG", "Intel-ACPI", "Intel", "IPA",
  21816. "ISC", "JasPer-2.0", "JSON", "LPPL-1.3a", "LPPL-1.0", "LPPL-1.1",
  21817. "LPPL-1.2", "LPPL-1.3c", "Latex2e", "BSD-3-Clause-LBNL", "Leptonica",
  21818. "Libpng", "libtiff", "LPL-1.02", "LPL-1.0", "MakeIndex", "MTLL", "MS-PL",
  21819. "MS-RL", "MirOS", "MITNFA", "MIT", "Motosoto", "MPL-1.0", "MPL-1.1",
  21820. "MPL-2.0", "MPL-2.0-no-copyleft-exception", "mpich2", "Multics", "Mup",
  21821. "NASA-1.3", "Naumen", "NBPL-1.0", "NetCDF", "NGPL", "NOSL", "NPL-1.0",
  21822. "NPL-1.1", "Newsletr", "NLPL", "Nokia", "NPOSL-3.0", "Noweb", "NRL", "NTP",
  21823. "Nunit", "OCLC-2.0", "ODbL-1.0", "PDDL-1.0", "OGTSL", "OLDAP-2.2.2",
  21824. "OLDAP-1.1", "OLDAP-1.2", "OLDAP-1.3", "OLDAP-1.4", "OLDAP-2.0",
  21825. "OLDAP-2.0.1", "OLDAP-2.1", "OLDAP-2.2", "OLDAP-2.2.1", "OLDAP-2.3",
  21826. "OLDAP-2.4", "OLDAP-2.5", "OLDAP-2.6", "OLDAP-2.7", "OML", "OPL-1.0",
  21827. "OSL-1.0", "OSL-1.1", "OSL-2.0", "OSL-2.1", "OSL-3.0", "OLDAP-2.8",
  21828. "OpenSSL", "PHP-3.0", "PHP-3.01", "Plexus", "PostgreSQL", "psfrag",
  21829. "psutils", "Python-2.0", "QPL-1.0", "Qhull", "Rdisc", "RPSL-1.0", "RPL-1.1",
  21830. "RPL-1.5", "RHeCos-1.1", "RSCPL", "Ruby", "SAX-PD", "Saxpath", "SCEA",
  21831. "SWL", "SGI-B-1.0", "SGI-B-1.1", "SGI-B-2.0", "OFL-1.0", "OFL-1.1",
  21832. "SimPL-2.0", "Sleepycat", "SNIA", "SMLNJ", "StandardML-NJ",
  21833. "SugarCRM-1.1.3", "SISSL", "SISSL-1.2", "SPL-1.0", "Watcom-1.0", "TCL",
  21834. "Unlicense", "TMate", "TORQUE-1.1", "TOSL", "Unicode-TOU", "NCSA", "Vim",
  21835. "VOSTROM", "VSL-1.0", "W3C", "Wsuipa", "WXwindows", "Xnet", "X11", "Xerox",
  21836. "XFree86-1.1", "xinetd", "xpp", "XSkat", "YPL-1.0", "YPL-1.1", "Zed",
  21837. "Zend-2.0", "Zimbra-1.3", "Zlib", "zlib-acknowledgement", "ZPL-1.1",
  21838. "ZPL-2.0", "ZPL-2.1"
  21839. ]
  21840. MZ��������ÿÿ��¸�������@�����������������������������������è���º�´ Í!¸LÍ!This program cannot be run in DOS mode.
  21841. $�������Æ,Í;§Bž;§Bž;§Bž2ßמ:§Bž2ßÁž-§Bž2ßÆž9§Bž2ßÑž?§Bža9ž8§Bž;§Cž§Bž2ßÈž:§Bž2ßÖž:§Bž2ßÓž:§BžRich;§Bž��������PE��L�¬MoO��������à�  ��
  21842. ���������8������ ����@����������������������`�����?œ���@�����������������������������"��P����@�� �������������������P��p���!�����������������������������8!��@������������ ��Ø���������������������������.text��� ������
  21843. ����������������� ��`.rdata����� ���
  21844. �����������������@��@.data�������0��������������������@��À.rsrc��� ���@��������������������@��@.reloc��Ì���P������"��������������@��B��������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������j$¸æ@�èx��jöÿ @�ƒeÐ�‹ð�EÐPVÿ� @�‹EЃàûPVÿ @��MÔÿX @�ƒeü��EÔPÿ5H @�ÿL @�YYÿ5\ @��EÔPÿ5` @�ÿD @�YY‹ÈÿP @�ƒMüÿ�MÔÿT @�3ÀèH��Ã; �0@�uóÃé¬��h€@�è£��¡l3@�Ç$40@�ÿ5h3@�£40@�h$0@�h(0@�h 0@�ÿ  @�ƒÄ£00@�…À}jè¹��YÃjh"@�è��3Û‰]üd¡���‹p‰]ä¿€3@�SVWÿ0 @�;Ãt;Æu3öF‰uäëhè��ÿ4 @�ëÚ3öF¡|3@�;Æu
  21845. jè\��Yë;¡|3@�…Àu,‰5|3@�hð @�hä @�è§��YY…ÀtÇEüþÿÿÿ¸ÿ���éÝ���‰5<0@�¡|3@�;Æuhà @�hØ @�èl��YYÇ|3@����9]äuSWÿ8 @�9Œ3@�thŒ3@�èƒ��Y…Àt
  21846. SjSÿŒ3@�¡$0@�‹ ¼ @�‰ÿ5$0@�ÿ5(0@�ÿ5 0@�èþÿÿƒÄ £80@�9,0@�u7PÿÀ @�‹Eì‹‹ ‰MàPQèŽ��YYËeè‹Eà£80@�3Û9,0@�uPÿh @�9<0@�uÿœ @�ÇEüþÿÿÿ¡80@�èû��øMZ��f9��@�t3ÀëM¡<�@��€��@��8PE��ué·H�ù ��t�ù ��uÕƒ¸„���vÌ3É9ˆø���ëƒxtv¼3É9ˆè���•Á‹Áj£,0@�ÿp @�jÿÿl @�YY£„3@�£ˆ3@�ÿÌ @�‹ t3@�‰ÿˆ @�‹ p3@�‰¡¨ @�‹�£x3@�èV��è¬��ƒ=0@��u hµ@�ÿ¬ @�Yèg��ƒ=0@�ÿu jÿÿ° @�Y3ÀÃè{��éŸýÿÿ‹ÿU‹ì�ì(��£H1@�‰ D1@�‰@1@�‰<1@�‰581@�‰=41@�fŒ`1@�fŒ T1@�fŒ01@�fŒ,1@�fŒ%(1@�fŒ-$1@�œ�X1@�‹E�£L1@�‹E£P1@��E£\1@�‹…àüÿÿǘ0@���¡P1@�£L0@�Ç@0@� �ÀÇD0@����¡�0@�‰…Øüÿÿ¡0@�‰…Üüÿÿÿ @�£�0@�jè?��Yj�ÿ @�h!@�ÿ$ @�ƒ=�0@��ujè��Yh �Àÿ( @�Pÿ, @�ÉËÿU‹ì‹E‹��8csmàu*ƒxu$‹@= “t=!“t="“t=�@™uèÐ��3À]Â�hH@�ÿ @�3ÀÃÿ%¤ @�jh("@�èb��ÿ5ˆ3@�‹5Œ @�ÿÖY‰Eäƒøÿu ÿuÿÄ @�Yëgjè’��Yƒeü�ÿ5ˆ3@�ÿÖ‰Eäÿ5„3@�ÿÖYY‰Eà�EàP�EäPÿu‹5l @�ÿÖYPèU��‰EÜÿuäÿÖ£ˆ3@�ÿuàÿփģ„3@�ÇEüþÿÿÿè ���‹EÜè��Ãjè��YËÿU‹ìÿuèNÿÿÿ÷ØÀ÷ØYH]ËÿV¸ü!@�¾ü!@�W‹ø;Æs‹…ÀtÿЃÇ;þrñ_^ËÿV¸"@�¾"@�W‹ø;Æs‹…ÀtÿЃÇ;þrñ_^Ãÿ%È @�ÌÌÌÌ‹ÿU‹ì‹M¸MZ��f9t3À]ËA<Á�8PE��uï3Ò¹ ��f9H”‹Â]ÃÌÌÌÌÌÌÌÌÌÌÌ‹ÿU‹ì‹E‹H<È·ASV·q3ÒW�D…öv‹} ‹H ;ùr ‹XÙ;ûr
  21847. BƒÀ(;Örè3À_^[]ÃÌÌÌÌÌÌÌÌÌÌÌÌ‹ÿU‹ìjþhH"@�he@�d¡����PƒìSVW¡�0@�1Eø3ÅP�Eðd£����‰eèÇEü����h��@�è*ÿÿÿƒÄ…ÀtU‹E-��@�Ph��@�èPÿÿÿƒÄ…Àt;‹@$Áè÷ЃàÇEüþÿÿÿ‹Mðd‰ ����Y_^[‹å]ËEì‹‹3Ò=��À”‹ÂËeèÇEüþÿÿÿ3À‹Mðd‰ ����Y_^[‹å]ÃÌÿ%¸ @�ÿ%´ @�ÌÌhe@�dÿ5����‹D$‰l$�l$+àSVW¡�0@�1Eü3ÅP‰eèÿuø‹EüÇEüþÿÿÿ‰Eø�Eðd£����ËMðd‰ ����Y__^[‹å]QËÿU‹ìÿuÿuÿu ÿuh‡@�h�0@�èç���ƒÄ]ËÿVh���h���3öVèÙ���ƒÄ …Àt VVVVVèÂ���ƒÄ^Ã3ÀËÿU‹ìƒì¡�0@�ƒeø�ƒeü�SW¿Næ@»»��ÿÿ;Çt …Ãt ÷У0@�ë`V�EøPÿ< @�‹uü3uøÿ @�3ðÿ @�3ðÿ @�3ð�EðPÿ @�‹Eô3Eð3ð;÷u¾Oæ@»ë …óu‹ÆÁà ð‰5�0@�÷Ö‰50@�^_[ÉÃÿ%t @�ÿ%x @�ÿ%| @�ÿ%€ @�ÿ%„ @�ÿ%� @�ÿ%” @�ÿ%˜ @�ÿ%Ð @�Pdÿ5�����D$ +d$ SVW‰(‹è¡�0@�3ÅP‰EðÿuüÇEüÿÿÿÿ�Eôd£����ËMôd‰ ����Y__^[‹å]QËMð3Íè¯÷ÿÿéÝÿÿÿ�MÔÿ%T @�‹T$�B ‹JÌ3Èè�÷ÿÿ‹Jü3Èè†÷ÿÿ¸l"@�ésÿÿÿ�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������¸#��Ê#��Ü#��ˆ)��r)��b)��H)��4)��)��ú(��æ(��Ò(��´(��¬(��–(��ž)������ú#��à$��%��Ê%��&��d&��®&��¤$������('��Ä'��Ö'��è'��þ'��(��((��6(��¦'��H(��Z(��t(��†(��'��'���'��–'��‚'��l'��^'��R'��F'��>'��>(��0'��¶'��¸)����������–@���������W@�Š@���������������������¬MoO�������l���€!��€��@0@�˜0@�bad allocation������H������������������������������������������������������������0@�ð!@����RSDSÑŒ³´�J¨!öÌëLZ����c:\users\seld\documents\visual studio 2010\Projects\hiddeninp\Release\hiddeninp.pdb�����e��æ������������������þÿÿÿ����Ðÿÿÿ����þÿÿÿ@�@�����þÿÿÿ����Ìÿÿÿ����þÿÿÿ����:@�����þÿÿÿ����Øÿÿÿ����þÿÿÿË@�ß@�ÿÿÿÿÝ@�"“���d"@������������������������à"����������ì#��� ��$#����������ô&��D ��H#����������(��h ����������������������¸#��Ê#��Ü#��ˆ)��r)��b)��H)��4)��)��ú(��æ(��Ò(��´(��¬(��–(��ž)������ú#��à$��%��Ê%��&��d&��®&��¤$������('��Ä'��Ö'��è'��þ'��(��((��6(��¦'��H(��Z(��t(��†(��'��'���'��–'��‚'��l'��^'��R'��F'��>'��>(��0'��¶'��¸)������•GetConsoleMode��·SetConsoleMode��;GetStdHandle��KERNEL32.dll���??$?6DU?$char_traits@D@std@@V?$allocator@D@1@@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@0@AAV10@ABV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@@Z�‘?cout@std@@3V?$basic_ostream@DU?$char_traits@D@std@@@1@A��J?cin@std@@3V?$basic_istream@DU?$char_traits@D@std@@@1@A�Â�??$getline@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@YAAAV?$basic_istream@DU?$char_traits@D@std@@@0@AAV10@AAV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@0@@Z�??6?$basic_ostream@DU?$char_traits@D@std@@@std@@QAEAAV01@P6AAAV01@AAV01@@Z@Z��_??1?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ��{??0?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAE@XZ��³?endl@std@@YAAAV?$basic_ostream@DU?$char_traits@D@std@@@1@AAV21@@Z��MSVCP90.dll�_amsg_exit��Ÿ�__getmainargs�,_cexit��|_exit�f�_XcptFilter�Ìexit�� �__initenv�_initterm�_initterm_e�<_configthreadlocale�ã�__setusermatherr�� _adjust_fdiv��Ë�__p__commode��Ï�__p__fmode��j_encode_pointer�à�__set_app_type��K_crt_debugger_hook��C�?terminate@@YAXXZ�MSVCR90.dll�æ_unlock�–�__dllonexit�v_lock�_onexit�`_decode_pointer�s_except_handler4_common� _invoke_watson��?_controlfp_s��½InterlockedExchange�!Sleep�ºInterlockedCompareExchange��-TerminateProcess��©GetCurrentProcess�>UnhandledExceptionFilter��SetUnhandledExceptionFilter�ÑIsDebuggerPresent�TQueryPerformanceCounter�fGetTickCount��­GetCurrentThreadId��ªGetCurrentProcessId�OGetSystemTimeAsFileTime�s�__CxxFrameHandler3����������������������������������������������������Næ@»±¿Dÿÿÿÿÿÿÿÿþÿÿÿ���$!@���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������� ��€���8��€�����������������P��€�����������������h��€�������������� ��€����������������� ������ @��(��ä������ÈC��V��ä������(4���V�S�_�V�E�R�S�I�O�N�_�I�N�F�O�����½ïþ������������������������������������������†���S�t�r�i�n�g�F�i�l�e�I�n�f�o���b���0�4�0�9�0�4�b�0���Ê�Q��F�i�l�e�D�e�s�c�r�i�p�t�i�o�n�����R�e�a�d�s� �f�r�o�m� �s�t�d�i�n� �w�i�t�h�o�u�t� �l�e�a�k�i�n�g� �i�n�f�o� �t�o� �t�h�e� �t�e�r�m�i�n�a�l� �a�n�d� �o�u�t�p�u�t�s� �b�a�c�k� �t�o� �s�t�d�o�u�t�����6� ��F�i�l�e�V�e�r�s�i�o�n�����1�,� �0�,� �0�,� �0�����8� ��I�n�t�e�r�n�a�l�N�a�m�e���h�i�d�d�e�n�i�n�p�u�t���P���L�e�g�a�l�C�o�p�y�r�i�g�h�t���J�o�r�d�i� �B�o�g�g�i�a�n�o� �-� �2�0�1�2���H���O�r�i�g�i�n�a�l�F�i�l�e�n�a�m�e���h�i�d�d�e�n�i�n�p�u�t�.�e�x�e���:� ��P�r�o�d�u�c�t�N�a�m�e�����H�i�d�d�e�n� �I�n�p�u�t�����:� ��P�r�o�d�u�c�t�V�e�r�s�i�o�n���1�,� �0�,� �0�,� �0�����D����V�a�r�F�i�l�e�I�n�f�o�����$����T�r�a�n�s�l�a�t�i�o�n����� °<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  21848. <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
  21849. <security>
  21850. <requestedPrivileges>
  21851. <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
  21852. </requestedPrivileges>
  21853. </security>
  21854. </trustInfo>
  21855. <dependency>
  21856. <dependentAssembly>
  21857. <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
  21858. </dependentAssembly>
  21859. </dependency>
  21860. </assembly>PAPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDINGPADDINGXXPADDING���@��00!0/080F0L0T0^0d0n0{0‰0—0¡0¨0®0³0¸0½0Â0È0Ð0ä0ÿ01#1-1@1J1O1T1v1{1„1‰1–1§1­1´1È1Í1Ó1Û1á1ç1ô1ú12"2*23292A2M2_2j2p2¹2¿2Ç2Î2Ó2Ù2ß2ç2í2ô2û2 333%303N3T3Z3`3f3l3s3z3�3ˆ3�3–3�3¥3­3µ3Á3Ê3Ï3Õ3ß3è3ó3ÿ34444%4;4B4‹4‘4š4¡4¬4²4Æ4Û4æ4þ45!5^5c5„5‰5¨5H6M6_6}6‘6—6�77 7*7w7|7Á7ä7ñ7ý78 88=8E8P8V8\8b8h8n8t8z8€8œ8â89��� ��$���Ü0è0ì01 1t1x12 2@2\2`2h2t2�0�� ���0��������������������������������������������������������������������������������������������������������������������������������������������������<?php
  21861. namespace Symfony\Component\Console;
  21862. use Symfony\Component\Console\Descriptor\TextDescriptor;
  21863. use Symfony\Component\Console\Descriptor\XmlDescriptor;
  21864. use Symfony\Component\Console\Helper\DebugFormatterHelper;
  21865. use Symfony\Component\Console\Helper\ProcessHelper;
  21866. use Symfony\Component\Console\Helper\QuestionHelper;
  21867. use Symfony\Component\Console\Input\InputInterface;
  21868. use Symfony\Component\Console\Input\ArgvInput;
  21869. use Symfony\Component\Console\Input\ArrayInput;
  21870. use Symfony\Component\Console\Input\InputDefinition;
  21871. use Symfony\Component\Console\Input\InputOption;
  21872. use Symfony\Component\Console\Input\InputArgument;
  21873. use Symfony\Component\Console\Input\InputAwareInterface;
  21874. use Symfony\Component\Console\Output\BufferedOutput;
  21875. use Symfony\Component\Console\Output\OutputInterface;
  21876. use Symfony\Component\Console\Output\ConsoleOutput;
  21877. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  21878. use Symfony\Component\Console\Command\Command;
  21879. use Symfony\Component\Console\Command\HelpCommand;
  21880. use Symfony\Component\Console\Command\ListCommand;
  21881. use Symfony\Component\Console\Helper\HelperSet;
  21882. use Symfony\Component\Console\Helper\FormatterHelper;
  21883. use Symfony\Component\Console\Helper\DialogHelper;
  21884. use Symfony\Component\Console\Helper\ProgressHelper;
  21885. use Symfony\Component\Console\Helper\TableHelper;
  21886. use Symfony\Component\Console\Event\ConsoleCommandEvent;
  21887. use Symfony\Component\Console\Event\ConsoleExceptionEvent;
  21888. use Symfony\Component\Console\Event\ConsoleTerminateEvent;
  21889. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  21890. class Application
  21891. {
  21892. private $commands = array();
  21893. private $wantHelps = false;
  21894. private $runningCommand;
  21895. private $name;
  21896. private $version;
  21897. private $catchExceptions = true;
  21898. private $autoExit = true;
  21899. private $definition;
  21900. private $helperSet;
  21901. private $dispatcher;
  21902. private $terminalDimensions;
  21903. private $defaultCommand;
  21904. public function __construct($name = 'UNKNOWN', $version = 'UNKNOWN')
  21905. {
  21906. $this->name = $name;
  21907. $this->version = $version;
  21908. $this->defaultCommand = 'list';
  21909. $this->helperSet = $this->getDefaultHelperSet();
  21910. $this->definition = $this->getDefaultInputDefinition();
  21911. foreach ($this->getDefaultCommands() as $command) {
  21912. $this->add($command);
  21913. }
  21914. }
  21915. public function setDispatcher(EventDispatcherInterface $dispatcher)
  21916. {
  21917. $this->dispatcher = $dispatcher;
  21918. }
  21919. public function run(InputInterface $input = null, OutputInterface $output = null)
  21920. {
  21921. if (null === $input) {
  21922. $input = new ArgvInput();
  21923. }
  21924. if (null === $output) {
  21925. $output = new ConsoleOutput();
  21926. }
  21927. $this->configureIO($input, $output);
  21928. try {
  21929. $exitCode = $this->doRun($input, $output);
  21930. } catch (\Exception $e) {
  21931. if (!$this->catchExceptions) {
  21932. throw $e;
  21933. }
  21934. if ($output instanceof ConsoleOutputInterface) {
  21935. $this->renderException($e, $output->getErrorOutput());
  21936. } else {
  21937. $this->renderException($e, $output);
  21938. }
  21939. $exitCode = $e->getCode();
  21940. if (is_numeric($exitCode)) {
  21941. $exitCode = (int) $exitCode;
  21942. if (0 === $exitCode) {
  21943. $exitCode = 1;
  21944. }
  21945. } else {
  21946. $exitCode = 1;
  21947. }
  21948. }
  21949. if ($this->autoExit) {
  21950. if ($exitCode > 255) {
  21951. $exitCode = 255;
  21952. }
  21953. exit($exitCode);
  21954. }
  21955. return $exitCode;
  21956. }
  21957. public function doRun(InputInterface $input, OutputInterface $output)
  21958. {
  21959. if (true === $input->hasParameterOption(array('--version', '-V'))) {
  21960. $output->writeln($this->getLongVersion());
  21961. return 0;
  21962. }
  21963. $name = $this->getCommandName($input);
  21964. if (true === $input->hasParameterOption(array('--help', '-h'))) {
  21965. if (!$name) {
  21966. $name = 'help';
  21967. $input = new ArrayInput(array('command' => 'help'));
  21968. } else {
  21969. $this->wantHelps = true;
  21970. }
  21971. }
  21972. if (!$name) {
  21973. $name = $this->defaultCommand;
  21974. $input = new ArrayInput(array('command' => $this->defaultCommand));
  21975. }
  21976. $command = $this->find($name);
  21977. $this->runningCommand = $command;
  21978. $exitCode = $this->doRunCommand($command, $input, $output);
  21979. $this->runningCommand = null;
  21980. return $exitCode;
  21981. }
  21982. public function setHelperSet(HelperSet $helperSet)
  21983. {
  21984. $this->helperSet = $helperSet;
  21985. }
  21986. public function getHelperSet()
  21987. {
  21988. return $this->helperSet;
  21989. }
  21990. public function setDefinition(InputDefinition $definition)
  21991. {
  21992. $this->definition = $definition;
  21993. }
  21994. public function getDefinition()
  21995. {
  21996. return $this->definition;
  21997. }
  21998. public function getHelp()
  21999. {
  22000. return $this->getLongVersion();
  22001. }
  22002. public function setCatchExceptions($boolean)
  22003. {
  22004. $this->catchExceptions = (bool) $boolean;
  22005. }
  22006. public function setAutoExit($boolean)
  22007. {
  22008. $this->autoExit = (bool) $boolean;
  22009. }
  22010. public function getName()
  22011. {
  22012. return $this->name;
  22013. }
  22014. public function setName($name)
  22015. {
  22016. $this->name = $name;
  22017. }
  22018. public function getVersion()
  22019. {
  22020. return $this->version;
  22021. }
  22022. public function setVersion($version)
  22023. {
  22024. $this->version = $version;
  22025. }
  22026. public function getLongVersion()
  22027. {
  22028. if ('UNKNOWN' !== $this->getName() && 'UNKNOWN' !== $this->getVersion()) {
  22029. return sprintf('<info>%s</info> version <comment>%s</comment>', $this->getName(), $this->getVersion());
  22030. }
  22031. return '<info>Console Tool</info>';
  22032. }
  22033. public function register($name)
  22034. {
  22035. return $this->add(new Command($name));
  22036. }
  22037. public function addCommands(array $commands)
  22038. {
  22039. foreach ($commands as $command) {
  22040. $this->add($command);
  22041. }
  22042. }
  22043. public function add(Command $command)
  22044. {
  22045. $command->setApplication($this);
  22046. if (!$command->isEnabled()) {
  22047. $command->setApplication(null);
  22048. return;
  22049. }
  22050. if (null === $command->getDefinition()) {
  22051. throw new \LogicException(sprintf('Command class "%s" is not correctly initialized. You probably forgot to call the parent constructor.', get_class($command)));
  22052. }
  22053. $this->commands[$command->getName()] = $command;
  22054. foreach ($command->getAliases() as $alias) {
  22055. $this->commands[$alias] = $command;
  22056. }
  22057. return $command;
  22058. }
  22059. public function get($name)
  22060. {
  22061. if (!isset($this->commands[$name])) {
  22062. throw new \InvalidArgumentException(sprintf('The command "%s" does not exist.', $name));
  22063. }
  22064. $command = $this->commands[$name];
  22065. if ($this->wantHelps) {
  22066. $this->wantHelps = false;
  22067. $helpCommand = $this->get('help');
  22068. $helpCommand->setCommand($command);
  22069. return $helpCommand;
  22070. }
  22071. return $command;
  22072. }
  22073. public function has($name)
  22074. {
  22075. return isset($this->commands[$name]);
  22076. }
  22077. public function getNamespaces()
  22078. {
  22079. $namespaces = array();
  22080. foreach ($this->commands as $command) {
  22081. $namespaces = array_merge($namespaces, $this->extractAllNamespaces($command->getName()));
  22082. foreach ($command->getAliases() as $alias) {
  22083. $namespaces = array_merge($namespaces, $this->extractAllNamespaces($alias));
  22084. }
  22085. }
  22086. return array_values(array_unique(array_filter($namespaces)));
  22087. }
  22088. public function findNamespace($namespace)
  22089. {
  22090. $allNamespaces = $this->getNamespaces();
  22091. $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $namespace);
  22092. $namespaces = preg_grep('{^'.$expr.'}', $allNamespaces);
  22093. if (empty($namespaces)) {
  22094. $message = sprintf('There are no commands defined in the "%s" namespace.', $namespace);
  22095. if ($alternatives = $this->findAlternatives($namespace, $allNamespaces, array())) {
  22096. if (1 == count($alternatives)) {
  22097. $message .= "\n\nDid you mean this?\n ";
  22098. } else {
  22099. $message .= "\n\nDid you mean one of these?\n ";
  22100. }
  22101. $message .= implode("\n ", $alternatives);
  22102. }
  22103. throw new \InvalidArgumentException($message);
  22104. }
  22105. $exact = in_array($namespace, $namespaces, true);
  22106. if (count($namespaces) > 1 && !$exact) {
  22107. throw new \InvalidArgumentException(sprintf('The namespace "%s" is ambiguous (%s).', $namespace, $this->getAbbreviationSuggestions(array_values($namespaces))));
  22108. }
  22109. return $exact ? $namespace : reset($namespaces);
  22110. }
  22111. public function find($name)
  22112. {
  22113. $allCommands = array_keys($this->commands);
  22114. $expr = preg_replace_callback('{([^:]+|)}', function ($matches) { return preg_quote($matches[1]).'[^:]*'; }, $name);
  22115. $commands = preg_grep('{^'.$expr.'}', $allCommands);
  22116. if (empty($commands) || count(preg_grep('{^'.$expr.'$}', $commands)) < 1) {
  22117. if (false !== $pos = strrpos($name, ':')) {
  22118. $this->findNamespace(substr($name, 0, $pos));
  22119. }
  22120. $message = sprintf('Command "%s" is not defined.', $name);
  22121. if ($alternatives = $this->findAlternatives($name, $allCommands, array())) {
  22122. if (1 == count($alternatives)) {
  22123. $message .= "\n\nDid you mean this?\n ";
  22124. } else {
  22125. $message .= "\n\nDid you mean one of these?\n ";
  22126. }
  22127. $message .= implode("\n ", $alternatives);
  22128. }
  22129. throw new \InvalidArgumentException($message);
  22130. }
  22131. if (count($commands) > 1) {
  22132. $commandList = $this->commands;
  22133. $commands = array_filter($commands, function ($nameOrAlias) use ($commandList, $commands) {
  22134. $commandName = $commandList[$nameOrAlias]->getName();
  22135. return $commandName === $nameOrAlias || !in_array($commandName, $commands);
  22136. });
  22137. }
  22138. $exact = in_array($name, $commands, true);
  22139. if (count($commands) > 1 && !$exact) {
  22140. $suggestions = $this->getAbbreviationSuggestions(array_values($commands));
  22141. throw new \InvalidArgumentException(sprintf('Command "%s" is ambiguous (%s).', $name, $suggestions));
  22142. }
  22143. return $this->get($exact ? $name : reset($commands));
  22144. }
  22145. public function all($namespace = null)
  22146. {
  22147. if (null === $namespace) {
  22148. return $this->commands;
  22149. }
  22150. $commands = array();
  22151. foreach ($this->commands as $name => $command) {
  22152. if ($namespace === $this->extractNamespace($name, substr_count($namespace, ':') + 1)) {
  22153. $commands[$name] = $command;
  22154. }
  22155. }
  22156. return $commands;
  22157. }
  22158. public static function getAbbreviations($names)
  22159. {
  22160. $abbrevs = array();
  22161. foreach ($names as $name) {
  22162. for ($len = strlen($name); $len > 0; --$len) {
  22163. $abbrev = substr($name, 0, $len);
  22164. $abbrevs[$abbrev][] = $name;
  22165. }
  22166. }
  22167. return $abbrevs;
  22168. }
  22169. public function asText($namespace = null, $raw = false)
  22170. {
  22171. $descriptor = new TextDescriptor();
  22172. $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, !$raw);
  22173. $descriptor->describe($output, $this, array('namespace' => $namespace, 'raw_output' => true));
  22174. return $output->fetch();
  22175. }
  22176. public function asXml($namespace = null, $asDom = false)
  22177. {
  22178. $descriptor = new XmlDescriptor();
  22179. if ($asDom) {
  22180. return $descriptor->getApplicationDocument($this, $namespace);
  22181. }
  22182. $output = new BufferedOutput();
  22183. $descriptor->describe($output, $this, array('namespace' => $namespace));
  22184. return $output->fetch();
  22185. }
  22186. public function renderException($e, $output)
  22187. {
  22188. do {
  22189. $title = sprintf(' [%s] ', get_class($e));
  22190. $len = $this->stringWidth($title);
  22191. $width = $this->getTerminalWidth() ? $this->getTerminalWidth() - 1 : PHP_INT_MAX;
  22192. if (defined('HHVM_VERSION') && $width > 1 << 31) {
  22193. $width = 1 << 31;
  22194. }
  22195. $formatter = $output->getFormatter();
  22196. $lines = array();
  22197. foreach (preg_split('/\r?\n/', $e->getMessage()) as $line) {
  22198. foreach ($this->splitStringByWidth($line, $width - 4) as $line) {
  22199. $lineLength = $this->stringWidth(preg_replace('/\[[^m]*m/', '', $formatter->format($line))) + 4;
  22200. $lines[] = array($line, $lineLength);
  22201. $len = max($lineLength, $len);
  22202. }
  22203. }
  22204. $messages = array('', '');
  22205. $messages[] = $emptyLine = $formatter->format(sprintf('<error>%s</error>', str_repeat(' ', $len)));
  22206. $messages[] = $formatter->format(sprintf('<error>%s%s</error>', $title, str_repeat(' ', max(0, $len - $this->stringWidth($title)))));
  22207. foreach ($lines as $line) {
  22208. $messages[] = $formatter->format(sprintf('<error> %s %s</error>', $line[0], str_repeat(' ', $len - $line[1])));
  22209. }
  22210. $messages[] = $emptyLine;
  22211. $messages[] = '';
  22212. $messages[] = '';
  22213. $output->writeln($messages, OutputInterface::OUTPUT_RAW);
  22214. if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) {
  22215. $output->writeln('<comment>Exception trace:</comment>');
  22216. $trace = $e->getTrace();
  22217. array_unshift($trace, array(
  22218. 'function' => '',
  22219. 'file' => $e->getFile() !== null ? $e->getFile() : 'n/a',
  22220. 'line' => $e->getLine() !== null ? $e->getLine() : 'n/a',
  22221. 'args' => array(),
  22222. ));
  22223. for ($i = 0, $count = count($trace); $i < $count; $i++) {
  22224. $class = isset($trace[$i]['class']) ? $trace[$i]['class'] : '';
  22225. $type = isset($trace[$i]['type']) ? $trace[$i]['type'] : '';
  22226. $function = $trace[$i]['function'];
  22227. $file = isset($trace[$i]['file']) ? $trace[$i]['file'] : 'n/a';
  22228. $line = isset($trace[$i]['line']) ? $trace[$i]['line'] : 'n/a';
  22229. $output->writeln(sprintf(' %s%s%s() at <info>%s:%s</info>', $class, $type, $function, $file, $line));
  22230. }
  22231. $output->writeln("");
  22232. $output->writeln("");
  22233. }
  22234. } while ($e = $e->getPrevious());
  22235. if (null !== $this->runningCommand) {
  22236. $output->writeln(sprintf('<info>%s</info>', sprintf($this->runningCommand->getSynopsis(), $this->getName())));
  22237. $output->writeln("");
  22238. $output->writeln("");
  22239. }
  22240. }
  22241. protected function getTerminalWidth()
  22242. {
  22243. $dimensions = $this->getTerminalDimensions();
  22244. return $dimensions[0];
  22245. }
  22246. protected function getTerminalHeight()
  22247. {
  22248. $dimensions = $this->getTerminalDimensions();
  22249. return $dimensions[1];
  22250. }
  22251. public function getTerminalDimensions()
  22252. {
  22253. if ($this->terminalDimensions) {
  22254. return $this->terminalDimensions;
  22255. }
  22256. if ('\\' === DIRECTORY_SEPARATOR) {
  22257. if (preg_match('/^(\d+)x\d+ \(\d+x(\d+)\)$/', trim(getenv('ANSICON')), $matches)) {
  22258. return array((int) $matches[1], (int) $matches[2]);
  22259. }
  22260. if (preg_match('/^(\d+)x(\d+)$/', $this->getConsoleMode(), $matches)) {
  22261. return array((int) $matches[1], (int) $matches[2]);
  22262. }
  22263. }
  22264. if ($sttyString = $this->getSttyColumns()) {
  22265. if (preg_match('/rows.(\d+);.columns.(\d+);/i', $sttyString, $matches)) {
  22266. return array((int) $matches[2], (int) $matches[1]);
  22267. }
  22268. if (preg_match('/;.(\d+).rows;.(\d+).columns/i', $sttyString, $matches)) {
  22269. return array((int) $matches[2], (int) $matches[1]);
  22270. }
  22271. }
  22272. return array(null, null);
  22273. }
  22274. public function setTerminalDimensions($width, $height)
  22275. {
  22276. $this->terminalDimensions = array($width, $height);
  22277. return $this;
  22278. }
  22279. protected function configureIO(InputInterface $input, OutputInterface $output)
  22280. {
  22281. if (true === $input->hasParameterOption(array('--ansi'))) {
  22282. $output->setDecorated(true);
  22283. } elseif (true === $input->hasParameterOption(array('--no-ansi'))) {
  22284. $output->setDecorated(false);
  22285. }
  22286. if (true === $input->hasParameterOption(array('--no-interaction', '-n'))) {
  22287. $input->setInteractive(false);
  22288. } elseif (function_exists('posix_isatty') && $this->getHelperSet()->has('question')) {
  22289. $inputStream = $this->getHelperSet()->get('question')->getInputStream();
  22290. if (!@posix_isatty($inputStream)) {
  22291. $input->setInteractive(false);
  22292. }
  22293. }
  22294. if (true === $input->hasParameterOption(array('--quiet', '-q'))) {
  22295. $output->setVerbosity(OutputInterface::VERBOSITY_QUIET);
  22296. } else {
  22297. if ($input->hasParameterOption('-vvv') || $input->hasParameterOption('--verbose=3') || $input->getParameterOption('--verbose') === 3) {
  22298. $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
  22299. } elseif ($input->hasParameterOption('-vv') || $input->hasParameterOption('--verbose=2') || $input->getParameterOption('--verbose') === 2) {
  22300. $output->setVerbosity(OutputInterface::VERBOSITY_VERY_VERBOSE);
  22301. } elseif ($input->hasParameterOption('-v') || $input->hasParameterOption('--verbose=1') || $input->hasParameterOption('--verbose') || $input->getParameterOption('--verbose')) {
  22302. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  22303. }
  22304. }
  22305. }
  22306. protected function doRunCommand(Command $command, InputInterface $input, OutputInterface $output)
  22307. {
  22308. foreach ($command->getHelperSet() as $helper) {
  22309. if ($helper instanceof InputAwareInterface) {
  22310. $helper->setInput($input);
  22311. }
  22312. }
  22313. if (null === $this->dispatcher) {
  22314. return $command->run($input, $output);
  22315. }
  22316. $event = new ConsoleCommandEvent($command, $input, $output);
  22317. $this->dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
  22318. if ($event->commandShouldRun()) {
  22319. try {
  22320. $exitCode = $command->run($input, $output);
  22321. } catch (\Exception $e) {
  22322. $event = new ConsoleTerminateEvent($command, $input, $output, $e->getCode());
  22323. $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
  22324. $event = new ConsoleExceptionEvent($command, $input, $output, $e, $event->getExitCode());
  22325. $this->dispatcher->dispatch(ConsoleEvents::EXCEPTION, $event);
  22326. throw $event->getException();
  22327. }
  22328. } else {
  22329. $exitCode = ConsoleCommandEvent::RETURN_CODE_DISABLED;
  22330. }
  22331. $event = new ConsoleTerminateEvent($command, $input, $output, $exitCode);
  22332. $this->dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
  22333. return $event->getExitCode();
  22334. }
  22335. protected function getCommandName(InputInterface $input)
  22336. {
  22337. return $input->getFirstArgument();
  22338. }
  22339. protected function getDefaultInputDefinition()
  22340. {
  22341. return new InputDefinition(array(
  22342. new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
  22343. new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
  22344. new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
  22345. new InputOption('--verbose', '-v|vv|vvv', InputOption::VALUE_NONE, 'Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug'),
  22346. new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version'),
  22347. new InputOption('--ansi', '', InputOption::VALUE_NONE, 'Force ANSI output'),
  22348. new InputOption('--no-ansi', '', InputOption::VALUE_NONE, 'Disable ANSI output'),
  22349. new InputOption('--no-interaction', '-n', InputOption::VALUE_NONE, 'Do not ask any interactive question'),
  22350. ));
  22351. }
  22352. protected function getDefaultCommands()
  22353. {
  22354. return array(new HelpCommand(), new ListCommand());
  22355. }
  22356. protected function getDefaultHelperSet()
  22357. {
  22358. return new HelperSet(array(
  22359. new FormatterHelper(),
  22360. new DialogHelper(),
  22361. new ProgressHelper(),
  22362. new TableHelper(),
  22363. new DebugFormatterHelper(),
  22364. new ProcessHelper(),
  22365. new QuestionHelper(),
  22366. ));
  22367. }
  22368. private function getSttyColumns()
  22369. {
  22370. if (!function_exists('proc_open')) {
  22371. return;
  22372. }
  22373. $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
  22374. $process = proc_open('stty -a | grep columns', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
  22375. if (is_resource($process)) {
  22376. $info = stream_get_contents($pipes[1]);
  22377. fclose($pipes[1]);
  22378. fclose($pipes[2]);
  22379. proc_close($process);
  22380. return $info;
  22381. }
  22382. }
  22383. private function getConsoleMode()
  22384. {
  22385. if (!function_exists('proc_open')) {
  22386. return;
  22387. }
  22388. $descriptorspec = array(1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
  22389. $process = proc_open('mode CON', $descriptorspec, $pipes, null, null, array('suppress_errors' => true));
  22390. if (is_resource($process)) {
  22391. $info = stream_get_contents($pipes[1]);
  22392. fclose($pipes[1]);
  22393. fclose($pipes[2]);
  22394. proc_close($process);
  22395. if (preg_match('/--------+\r?\n.+?(\d+)\r?\n.+?(\d+)\r?\n/', $info, $matches)) {
  22396. return $matches[2].'x'.$matches[1];
  22397. }
  22398. }
  22399. }
  22400. private function getAbbreviationSuggestions($abbrevs)
  22401. {
  22402. return sprintf('%s, %s%s', $abbrevs[0], $abbrevs[1], count($abbrevs) > 2 ? sprintf(' and %d more', count($abbrevs) - 2) : '');
  22403. }
  22404. public function extractNamespace($name, $limit = null)
  22405. {
  22406. $parts = explode(':', $name);
  22407. array_pop($parts);
  22408. return implode(':', null === $limit ? $parts : array_slice($parts, 0, $limit));
  22409. }
  22410. private function findAlternatives($name, $collection)
  22411. {
  22412. $threshold = 1e3;
  22413. $alternatives = array();
  22414. $collectionParts = array();
  22415. foreach ($collection as $item) {
  22416. $collectionParts[$item] = explode(':', $item);
  22417. }
  22418. foreach (explode(':', $name) as $i => $subname) {
  22419. foreach ($collectionParts as $collectionName => $parts) {
  22420. $exists = isset($alternatives[$collectionName]);
  22421. if (!isset($parts[$i]) && $exists) {
  22422. $alternatives[$collectionName] += $threshold;
  22423. continue;
  22424. } elseif (!isset($parts[$i])) {
  22425. continue;
  22426. }
  22427. $lev = levenshtein($subname, $parts[$i]);
  22428. if ($lev <= strlen($subname) / 3 || '' !== $subname && false !== strpos($parts[$i], $subname)) {
  22429. $alternatives[$collectionName] = $exists ? $alternatives[$collectionName] + $lev : $lev;
  22430. } elseif ($exists) {
  22431. $alternatives[$collectionName] += $threshold;
  22432. }
  22433. }
  22434. }
  22435. foreach ($collection as $item) {
  22436. $lev = levenshtein($name, $item);
  22437. if ($lev <= strlen($name) / 3 || false !== strpos($item, $name)) {
  22438. $alternatives[$item] = isset($alternatives[$item]) ? $alternatives[$item] - $lev : $lev;
  22439. }
  22440. }
  22441. $alternatives = array_filter($alternatives, function ($lev) use ($threshold) { return $lev < 2*$threshold; });
  22442. asort($alternatives);
  22443. return array_keys($alternatives);
  22444. }
  22445. public function setDefaultCommand($commandName)
  22446. {
  22447. $this->defaultCommand = $commandName;
  22448. }
  22449. private function stringWidth($string)
  22450. {
  22451. if (!function_exists('mb_strwidth')) {
  22452. return strlen($string);
  22453. }
  22454. if (false === $encoding = mb_detect_encoding($string)) {
  22455. return strlen($string);
  22456. }
  22457. return mb_strwidth($string, $encoding);
  22458. }
  22459. private function splitStringByWidth($string, $width)
  22460. {
  22461. if (!function_exists('mb_strwidth')) {
  22462. return str_split($string, $width);
  22463. }
  22464. if (false === $encoding = mb_detect_encoding($string)) {
  22465. return str_split($string, $width);
  22466. }
  22467. $utf8String = mb_convert_encoding($string, 'utf8', $encoding);
  22468. $lines = array();
  22469. $line = '';
  22470. foreach (preg_split('//u', $utf8String) as $char) {
  22471. if (mb_strwidth($line.$char, 'utf8') <= $width) {
  22472. $line .= $char;
  22473. continue;
  22474. }
  22475. $lines[] = str_pad($line, $width);
  22476. $line = $char;
  22477. }
  22478. if (strlen($line)) {
  22479. $lines[] = count($lines) ? str_pad($line, $width) : $line;
  22480. }
  22481. mb_convert_variables($encoding, 'utf8', $lines);
  22482. return $lines;
  22483. }
  22484. private function extractAllNamespaces($name)
  22485. {
  22486. $parts = explode(':', $name, -1);
  22487. $namespaces = array();
  22488. foreach ($parts as $part) {
  22489. if (count($namespaces)) {
  22490. $namespaces[] = end($namespaces).':'.$part;
  22491. } else {
  22492. $namespaces[] = $part;
  22493. }
  22494. }
  22495. return $namespaces;
  22496. }
  22497. }
  22498. <?php
  22499. namespace Symfony\Component\Console\Command;
  22500. use Symfony\Component\Console\Descriptor\TextDescriptor;
  22501. use Symfony\Component\Console\Descriptor\XmlDescriptor;
  22502. use Symfony\Component\Console\Input\InputDefinition;
  22503. use Symfony\Component\Console\Input\InputOption;
  22504. use Symfony\Component\Console\Input\InputArgument;
  22505. use Symfony\Component\Console\Input\InputInterface;
  22506. use Symfony\Component\Console\Output\BufferedOutput;
  22507. use Symfony\Component\Console\Output\OutputInterface;
  22508. use Symfony\Component\Console\Application;
  22509. use Symfony\Component\Console\Helper\HelperSet;
  22510. class Command
  22511. {
  22512. private $application;
  22513. private $name;
  22514. private $processTitle;
  22515. private $aliases = array();
  22516. private $definition;
  22517. private $help;
  22518. private $description;
  22519. private $ignoreValidationErrors = false;
  22520. private $applicationDefinitionMerged = false;
  22521. private $applicationDefinitionMergedWithArgs = false;
  22522. private $code;
  22523. private $synopsis;
  22524. private $helperSet;
  22525. public function __construct($name = null)
  22526. {
  22527. $this->definition = new InputDefinition();
  22528. if (null !== $name) {
  22529. $this->setName($name);
  22530. }
  22531. $this->configure();
  22532. if (!$this->name) {
  22533. throw new \LogicException(sprintf('The command defined in "%s" cannot have an empty name.', get_class($this)));
  22534. }
  22535. }
  22536. public function ignoreValidationErrors()
  22537. {
  22538. $this->ignoreValidationErrors = true;
  22539. }
  22540. public function setApplication(Application $application = null)
  22541. {
  22542. $this->application = $application;
  22543. if ($application) {
  22544. $this->setHelperSet($application->getHelperSet());
  22545. } else {
  22546. $this->helperSet = null;
  22547. }
  22548. }
  22549. public function setHelperSet(HelperSet $helperSet)
  22550. {
  22551. $this->helperSet = $helperSet;
  22552. }
  22553. public function getHelperSet()
  22554. {
  22555. return $this->helperSet;
  22556. }
  22557. public function getApplication()
  22558. {
  22559. return $this->application;
  22560. }
  22561. public function isEnabled()
  22562. {
  22563. return true;
  22564. }
  22565. protected function configure()
  22566. {
  22567. }
  22568. protected function execute(InputInterface $input, OutputInterface $output)
  22569. {
  22570. throw new \LogicException('You must override the execute() method in the concrete command class.');
  22571. }
  22572. protected function interact(InputInterface $input, OutputInterface $output)
  22573. {
  22574. }
  22575. protected function initialize(InputInterface $input, OutputInterface $output)
  22576. {
  22577. }
  22578. public function run(InputInterface $input, OutputInterface $output)
  22579. {
  22580. $this->getSynopsis();
  22581. $this->mergeApplicationDefinition();
  22582. try {
  22583. $input->bind($this->definition);
  22584. } catch (\Exception $e) {
  22585. if (!$this->ignoreValidationErrors) {
  22586. throw $e;
  22587. }
  22588. }
  22589. $this->initialize($input, $output);
  22590. if (null !== $this->processTitle) {
  22591. if (function_exists('cli_set_process_title')) {
  22592. cli_set_process_title($this->processTitle);
  22593. } elseif (function_exists('setproctitle')) {
  22594. setproctitle($this->processTitle);
  22595. } elseif (OutputInterface::VERBOSITY_VERY_VERBOSE === $output->getVerbosity()) {
  22596. $output->writeln('<comment>Install the proctitle PECL to be able to change the process title.</comment>');
  22597. }
  22598. }
  22599. if ($input->isInteractive()) {
  22600. $this->interact($input, $output);
  22601. }
  22602. $input->validate();
  22603. if ($this->code) {
  22604. $statusCode = call_user_func($this->code, $input, $output);
  22605. } else {
  22606. $statusCode = $this->execute($input, $output);
  22607. }
  22608. return is_numeric($statusCode) ? (int) $statusCode : 0;
  22609. }
  22610. public function setCode($code)
  22611. {
  22612. if (!is_callable($code)) {
  22613. throw new \InvalidArgumentException('Invalid callable provided to Command::setCode.');
  22614. }
  22615. $this->code = $code;
  22616. return $this;
  22617. }
  22618. public function mergeApplicationDefinition($mergeArgs = true)
  22619. {
  22620. if (null === $this->application || (true === $this->applicationDefinitionMerged && ($this->applicationDefinitionMergedWithArgs || !$mergeArgs))) {
  22621. return;
  22622. }
  22623. if ($mergeArgs) {
  22624. $currentArguments = $this->definition->getArguments();
  22625. $this->definition->setArguments($this->application->getDefinition()->getArguments());
  22626. $this->definition->addArguments($currentArguments);
  22627. }
  22628. $this->definition->addOptions($this->application->getDefinition()->getOptions());
  22629. $this->applicationDefinitionMerged = true;
  22630. if ($mergeArgs) {
  22631. $this->applicationDefinitionMergedWithArgs = true;
  22632. }
  22633. }
  22634. public function setDefinition($definition)
  22635. {
  22636. if ($definition instanceof InputDefinition) {
  22637. $this->definition = $definition;
  22638. } else {
  22639. $this->definition->setDefinition($definition);
  22640. }
  22641. $this->applicationDefinitionMerged = false;
  22642. return $this;
  22643. }
  22644. public function getDefinition()
  22645. {
  22646. return $this->definition;
  22647. }
  22648. public function getNativeDefinition()
  22649. {
  22650. return $this->getDefinition();
  22651. }
  22652. public function addArgument($name, $mode = null, $description = '', $default = null)
  22653. {
  22654. $this->definition->addArgument(new InputArgument($name, $mode, $description, $default));
  22655. return $this;
  22656. }
  22657. public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null)
  22658. {
  22659. $this->definition->addOption(new InputOption($name, $shortcut, $mode, $description, $default));
  22660. return $this;
  22661. }
  22662. public function setName($name)
  22663. {
  22664. $this->validateName($name);
  22665. $this->name = $name;
  22666. return $this;
  22667. }
  22668. public function setProcessTitle($title)
  22669. {
  22670. $this->processTitle = $title;
  22671. return $this;
  22672. }
  22673. public function getName()
  22674. {
  22675. return $this->name;
  22676. }
  22677. public function setDescription($description)
  22678. {
  22679. $this->description = $description;
  22680. return $this;
  22681. }
  22682. public function getDescription()
  22683. {
  22684. return $this->description;
  22685. }
  22686. public function setHelp($help)
  22687. {
  22688. $this->help = $help;
  22689. return $this;
  22690. }
  22691. public function getHelp()
  22692. {
  22693. return $this->help;
  22694. }
  22695. public function getProcessedHelp()
  22696. {
  22697. $name = $this->name;
  22698. $placeholders = array(
  22699. '%command.name%',
  22700. '%command.full_name%',
  22701. );
  22702. $replacements = array(
  22703. $name,
  22704. $_SERVER['PHP_SELF'].' '.$name,
  22705. );
  22706. return str_replace($placeholders, $replacements, $this->getHelp());
  22707. }
  22708. public function setAliases($aliases)
  22709. {
  22710. if (!is_array($aliases) && !$aliases instanceof \Traversable) {
  22711. throw new \InvalidArgumentException('$aliases must be an array or an instance of \Traversable');
  22712. }
  22713. foreach ($aliases as $alias) {
  22714. $this->validateName($alias);
  22715. }
  22716. $this->aliases = $aliases;
  22717. return $this;
  22718. }
  22719. public function getAliases()
  22720. {
  22721. return $this->aliases;
  22722. }
  22723. public function getSynopsis()
  22724. {
  22725. if (null === $this->synopsis) {
  22726. $this->synopsis = trim(sprintf('%s %s', $this->name, $this->definition->getSynopsis()));
  22727. }
  22728. return $this->synopsis;
  22729. }
  22730. public function getHelper($name)
  22731. {
  22732. return $this->helperSet->get($name);
  22733. }
  22734. public function asText()
  22735. {
  22736. $descriptor = new TextDescriptor();
  22737. $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
  22738. $descriptor->describe($output, $this, array('raw_output' => true));
  22739. return $output->fetch();
  22740. }
  22741. public function asXml($asDom = false)
  22742. {
  22743. $descriptor = new XmlDescriptor();
  22744. if ($asDom) {
  22745. return $descriptor->getCommandDocument($this);
  22746. }
  22747. $output = new BufferedOutput();
  22748. $descriptor->describe($output, $this);
  22749. return $output->fetch();
  22750. }
  22751. private function validateName($name)
  22752. {
  22753. if (!preg_match('/^[^\:]++(\:[^\:]++)*$/', $name)) {
  22754. throw new \InvalidArgumentException(sprintf('Command name "%s" is invalid.', $name));
  22755. }
  22756. }
  22757. }
  22758. <?php
  22759. namespace Symfony\Component\Console\Command;
  22760. use Symfony\Component\Console\Helper\DescriptorHelper;
  22761. use Symfony\Component\Console\Input\InputArgument;
  22762. use Symfony\Component\Console\Input\InputOption;
  22763. use Symfony\Component\Console\Input\InputInterface;
  22764. use Symfony\Component\Console\Output\OutputInterface;
  22765. class HelpCommand extends Command
  22766. {
  22767. private $command;
  22768. protected function configure()
  22769. {
  22770. $this->ignoreValidationErrors();
  22771. $this
  22772. ->setName('help')
  22773. ->setDefinition(array(
  22774. new InputArgument('command_name', InputArgument::OPTIONAL, 'The command name', 'help'),
  22775. new InputOption('xml', null, InputOption::VALUE_NONE, 'To output help as XML'),
  22776. new InputOption('format', null, InputOption::VALUE_REQUIRED, 'To output help in other formats', 'txt'),
  22777. new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command help'),
  22778. ))
  22779. ->setDescription('Displays help for a command')
  22780. ->setHelp(<<<EOF
  22781. The <info>%command.name%</info> command displays help for a given command:
  22782. <info>php %command.full_name% list</info>
  22783. You can also output the help in other formats by using the <comment>--format</comment> option:
  22784. <info>php %command.full_name% --format=xml list</info>
  22785. To display the list of available commands, please use the <info>list</info> command.
  22786. EOF
  22787. )
  22788. ;
  22789. }
  22790. public function setCommand(Command $command)
  22791. {
  22792. $this->command = $command;
  22793. }
  22794. protected function execute(InputInterface $input, OutputInterface $output)
  22795. {
  22796. if (null === $this->command) {
  22797. $this->command = $this->getApplication()->find($input->getArgument('command_name'));
  22798. }
  22799. if ($input->getOption('xml')) {
  22800. $input->setOption('format', 'xml');
  22801. }
  22802. $helper = new DescriptorHelper();
  22803. $helper->describe($output, $this->command, array(
  22804. 'format' => $input->getOption('format'),
  22805. 'raw' => $input->getOption('raw'),
  22806. ));
  22807. $this->command = null;
  22808. }
  22809. }
  22810. <?php
  22811. namespace Symfony\Component\Console\Command;
  22812. use Symfony\Component\Console\Helper\DescriptorHelper;
  22813. use Symfony\Component\Console\Input\InputArgument;
  22814. use Symfony\Component\Console\Input\InputOption;
  22815. use Symfony\Component\Console\Input\InputInterface;
  22816. use Symfony\Component\Console\Output\OutputInterface;
  22817. use Symfony\Component\Console\Input\InputDefinition;
  22818. class ListCommand extends Command
  22819. {
  22820. protected function configure()
  22821. {
  22822. $this
  22823. ->setName('list')
  22824. ->setDefinition($this->createDefinition())
  22825. ->setDescription('Lists commands')
  22826. ->setHelp(<<<EOF
  22827. The <info>%command.name%</info> command lists all commands:
  22828. <info>php %command.full_name%</info>
  22829. You can also display the commands for a specific namespace:
  22830. <info>php %command.full_name% test</info>
  22831. You can also output the information in other formats by using the <comment>--format</comment> option:
  22832. <info>php %command.full_name% --format=xml</info>
  22833. It's also possible to get raw list of commands (useful for embedding command runner):
  22834. <info>php %command.full_name% --raw</info>
  22835. EOF
  22836. )
  22837. ;
  22838. }
  22839. public function getNativeDefinition()
  22840. {
  22841. return $this->createDefinition();
  22842. }
  22843. protected function execute(InputInterface $input, OutputInterface $output)
  22844. {
  22845. if ($input->getOption('xml')) {
  22846. $input->setOption('format', 'xml');
  22847. }
  22848. $helper = new DescriptorHelper();
  22849. $helper->describe($output, $this->getApplication(), array(
  22850. 'format' => $input->getOption('format'),
  22851. 'raw_text' => $input->getOption('raw'),
  22852. 'namespace' => $input->getArgument('namespace'),
  22853. ));
  22854. }
  22855. private function createDefinition()
  22856. {
  22857. return new InputDefinition(array(
  22858. new InputArgument('namespace', InputArgument::OPTIONAL, 'The namespace name'),
  22859. new InputOption('xml', null, InputOption::VALUE_NONE, 'To output list as XML'),
  22860. new InputOption('raw', null, InputOption::VALUE_NONE, 'To output raw command list'),
  22861. new InputOption('format', null, InputOption::VALUE_REQUIRED, 'To output list in other formats', 'txt'),
  22862. ));
  22863. }
  22864. }
  22865. <?php
  22866. namespace Symfony\Component\Console;
  22867. final class ConsoleEvents
  22868. {
  22869. const COMMAND = 'console.command';
  22870. const TERMINATE = 'console.terminate';
  22871. const EXCEPTION = 'console.exception';
  22872. }
  22873. <?php
  22874. namespace Symfony\Component\Console\Descriptor;
  22875. use Symfony\Component\Console\Application;
  22876. use Symfony\Component\Console\Command\Command;
  22877. class ApplicationDescription
  22878. {
  22879. const GLOBAL_NAMESPACE = '_global';
  22880. private $application;
  22881. private $namespace;
  22882. private $namespaces;
  22883. private $commands;
  22884. private $aliases;
  22885. public function __construct(Application $application, $namespace = null)
  22886. {
  22887. $this->application = $application;
  22888. $this->namespace = $namespace;
  22889. }
  22890. public function getNamespaces()
  22891. {
  22892. if (null === $this->namespaces) {
  22893. $this->inspectApplication();
  22894. }
  22895. return $this->namespaces;
  22896. }
  22897. public function getCommands()
  22898. {
  22899. if (null === $this->commands) {
  22900. $this->inspectApplication();
  22901. }
  22902. return $this->commands;
  22903. }
  22904. public function getCommand($name)
  22905. {
  22906. if (!isset($this->commands[$name]) && !isset($this->aliases[$name])) {
  22907. throw new \InvalidArgumentException(sprintf('Command %s does not exist.', $name));
  22908. }
  22909. return isset($this->commands[$name]) ? $this->commands[$name] : $this->aliases[$name];
  22910. }
  22911. private function inspectApplication()
  22912. {
  22913. $this->commands = array();
  22914. $this->namespaces = array();
  22915. $all = $this->application->all($this->namespace ? $this->application->findNamespace($this->namespace) : null);
  22916. foreach ($this->sortCommands($all) as $namespace => $commands) {
  22917. $names = array();
  22918. foreach ($commands as $name => $command) {
  22919. if (!$command->getName()) {
  22920. continue;
  22921. }
  22922. if ($command->getName() === $name) {
  22923. $this->commands[$name] = $command;
  22924. } else {
  22925. $this->aliases[$name] = $command;
  22926. }
  22927. $names[] = $name;
  22928. }
  22929. $this->namespaces[$namespace] = array('id' => $namespace, 'commands' => $names);
  22930. }
  22931. }
  22932. private function sortCommands(array $commands)
  22933. {
  22934. $namespacedCommands = array();
  22935. foreach ($commands as $name => $command) {
  22936. $key = $this->application->extractNamespace($name, 1);
  22937. if (!$key) {
  22938. $key = '_global';
  22939. }
  22940. $namespacedCommands[$key][$name] = $command;
  22941. }
  22942. ksort($namespacedCommands);
  22943. foreach ($namespacedCommands as &$commands) {
  22944. ksort($commands);
  22945. }
  22946. return $namespacedCommands;
  22947. }
  22948. }
  22949. <?php
  22950. namespace Symfony\Component\Console\Descriptor;
  22951. use Symfony\Component\Console\Application;
  22952. use Symfony\Component\Console\Command\Command;
  22953. use Symfony\Component\Console\Input\InputArgument;
  22954. use Symfony\Component\Console\Input\InputDefinition;
  22955. use Symfony\Component\Console\Input\InputOption;
  22956. use Symfony\Component\Console\Output\OutputInterface;
  22957. abstract class Descriptor implements DescriptorInterface
  22958. {
  22959. private $output;
  22960. public function describe(OutputInterface $output, $object, array $options = array())
  22961. {
  22962. $this->output = $output;
  22963. switch (true) {
  22964. case $object instanceof InputArgument:
  22965. $this->describeInputArgument($object, $options);
  22966. break;
  22967. case $object instanceof InputOption:
  22968. $this->describeInputOption($object, $options);
  22969. break;
  22970. case $object instanceof InputDefinition:
  22971. $this->describeInputDefinition($object, $options);
  22972. break;
  22973. case $object instanceof Command:
  22974. $this->describeCommand($object, $options);
  22975. break;
  22976. case $object instanceof Application:
  22977. $this->describeApplication($object, $options);
  22978. break;
  22979. default:
  22980. throw new \InvalidArgumentException(sprintf('Object of type "%s" is not describable.', get_class($object)));
  22981. }
  22982. }
  22983. protected function write($content, $decorated = false)
  22984. {
  22985. $this->output->write($content, false, $decorated ? OutputInterface::OUTPUT_NORMAL : OutputInterface::OUTPUT_RAW);
  22986. }
  22987. abstract protected function describeInputArgument(InputArgument $argument, array $options = array());
  22988. abstract protected function describeInputOption(InputOption $option, array $options = array());
  22989. abstract protected function describeInputDefinition(InputDefinition $definition, array $options = array());
  22990. abstract protected function describeCommand(Command $command, array $options = array());
  22991. abstract protected function describeApplication(Application $application, array $options = array());
  22992. }
  22993. <?php
  22994. namespace Symfony\Component\Console\Descriptor;
  22995. use Symfony\Component\Console\Output\OutputInterface;
  22996. interface DescriptorInterface
  22997. {
  22998. public function describe(OutputInterface $output, $object, array $options = array());
  22999. }
  23000. <?php
  23001. namespace Symfony\Component\Console\Descriptor;
  23002. use Symfony\Component\Console\Application;
  23003. use Symfony\Component\Console\Command\Command;
  23004. use Symfony\Component\Console\Input\InputArgument;
  23005. use Symfony\Component\Console\Input\InputDefinition;
  23006. use Symfony\Component\Console\Input\InputOption;
  23007. class JsonDescriptor extends Descriptor
  23008. {
  23009. protected function describeInputArgument(InputArgument $argument, array $options = array())
  23010. {
  23011. $this->writeData($this->getInputArgumentData($argument), $options);
  23012. }
  23013. protected function describeInputOption(InputOption $option, array $options = array())
  23014. {
  23015. $this->writeData($this->getInputOptionData($option), $options);
  23016. }
  23017. protected function describeInputDefinition(InputDefinition $definition, array $options = array())
  23018. {
  23019. $this->writeData($this->getInputDefinitionData($definition), $options);
  23020. }
  23021. protected function describeCommand(Command $command, array $options = array())
  23022. {
  23023. $this->writeData($this->getCommandData($command), $options);
  23024. }
  23025. protected function describeApplication(Application $application, array $options = array())
  23026. {
  23027. $describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
  23028. $description = new ApplicationDescription($application, $describedNamespace);
  23029. $commands = array();
  23030. foreach ($description->getCommands() as $command) {
  23031. $commands[] = $this->getCommandData($command);
  23032. }
  23033. $data = $describedNamespace
  23034. ? array('commands' => $commands, 'namespace' => $describedNamespace)
  23035. : array('commands' => $commands, 'namespaces' => array_values($description->getNamespaces()));
  23036. $this->writeData($data, $options);
  23037. }
  23038. private function writeData(array $data, array $options)
  23039. {
  23040. $this->write(json_encode($data, isset($options['json_encoding']) ? $options['json_encoding'] : 0));
  23041. }
  23042. private function getInputArgumentData(InputArgument $argument)
  23043. {
  23044. return array(
  23045. 'name' => $argument->getName(),
  23046. 'is_required' => $argument->isRequired(),
  23047. 'is_array' => $argument->isArray(),
  23048. 'description' => $argument->getDescription(),
  23049. 'default' => $argument->getDefault(),
  23050. );
  23051. }
  23052. private function getInputOptionData(InputOption $option)
  23053. {
  23054. return array(
  23055. 'name' => '--'.$option->getName(),
  23056. 'shortcut' => $option->getShortcut() ? '-'.implode('|-', explode('|', $option->getShortcut())) : '',
  23057. 'accept_value' => $option->acceptValue(),
  23058. 'is_value_required' => $option->isValueRequired(),
  23059. 'is_multiple' => $option->isArray(),
  23060. 'description' => $option->getDescription(),
  23061. 'default' => $option->getDefault(),
  23062. );
  23063. }
  23064. private function getInputDefinitionData(InputDefinition $definition)
  23065. {
  23066. $inputArguments = array();
  23067. foreach ($definition->getArguments() as $name => $argument) {
  23068. $inputArguments[$name] = $this->getInputArgumentData($argument);
  23069. }
  23070. $inputOptions = array();
  23071. foreach ($definition->getOptions() as $name => $option) {
  23072. $inputOptions[$name] = $this->getInputOptionData($option);
  23073. }
  23074. return array('arguments' => $inputArguments, 'options' => $inputOptions);
  23075. }
  23076. private function getCommandData(Command $command)
  23077. {
  23078. $command->getSynopsis();
  23079. $command->mergeApplicationDefinition(false);
  23080. return array(
  23081. 'name' => $command->getName(),
  23082. 'usage' => $command->getSynopsis(),
  23083. 'description' => $command->getDescription(),
  23084. 'help' => $command->getProcessedHelp(),
  23085. 'aliases' => $command->getAliases(),
  23086. 'definition' => $this->getInputDefinitionData($command->getNativeDefinition()),
  23087. );
  23088. }
  23089. }
  23090. <?php
  23091. namespace Symfony\Component\Console\Descriptor;
  23092. use Symfony\Component\Console\Application;
  23093. use Symfony\Component\Console\Command\Command;
  23094. use Symfony\Component\Console\Input\InputArgument;
  23095. use Symfony\Component\Console\Input\InputDefinition;
  23096. use Symfony\Component\Console\Input\InputOption;
  23097. class MarkdownDescriptor extends Descriptor
  23098. {
  23099. protected function describeInputArgument(InputArgument $argument, array $options = array())
  23100. {
  23101. $this->write(
  23102. '**'.$argument->getName().':**'."\n\n"
  23103. .'* Name: '.($argument->getName() ?: '<none>')."\n"
  23104. .'* Is required: '.($argument->isRequired() ? 'yes' : 'no')."\n"
  23105. .'* Is array: '.($argument->isArray() ? 'yes' : 'no')."\n"
  23106. .'* Description: '.($argument->getDescription() ?: '<none>')."\n"
  23107. .'* Default: `'.str_replace("\n", '', var_export($argument->getDefault(), true)).'`'
  23108. );
  23109. }
  23110. protected function describeInputOption(InputOption $option, array $options = array())
  23111. {
  23112. $this->write(
  23113. '**'.$option->getName().':**'."\n\n"
  23114. .'* Name: `--'.$option->getName().'`'."\n"
  23115. .'* Shortcut: '.($option->getShortcut() ? '`-'.implode('|-', explode('|', $option->getShortcut())).'`' : '<none>')."\n"
  23116. .'* Accept value: '.($option->acceptValue() ? 'yes' : 'no')."\n"
  23117. .'* Is value required: '.($option->isValueRequired() ? 'yes' : 'no')."\n"
  23118. .'* Is multiple: '.($option->isArray() ? 'yes' : 'no')."\n"
  23119. .'* Description: '.($option->getDescription() ?: '<none>')."\n"
  23120. .'* Default: `'.str_replace("\n", '', var_export($option->getDefault(), true)).'`'
  23121. );
  23122. }
  23123. protected function describeInputDefinition(InputDefinition $definition, array $options = array())
  23124. {
  23125. if ($showArguments = count($definition->getArguments()) > 0) {
  23126. $this->write('### Arguments:');
  23127. foreach ($definition->getArguments() as $argument) {
  23128. $this->write("\n\n");
  23129. $this->write($this->describeInputArgument($argument));
  23130. }
  23131. }
  23132. if (count($definition->getOptions()) > 0) {
  23133. if ($showArguments) {
  23134. $this->write("\n\n");
  23135. }
  23136. $this->write('### Options:');
  23137. foreach ($definition->getOptions() as $option) {
  23138. $this->write("\n\n");
  23139. $this->write($this->describeInputOption($option));
  23140. }
  23141. }
  23142. }
  23143. protected function describeCommand(Command $command, array $options = array())
  23144. {
  23145. $command->getSynopsis();
  23146. $command->mergeApplicationDefinition(false);
  23147. $this->write(
  23148. $command->getName()."\n"
  23149. .str_repeat('-', strlen($command->getName()))."\n\n"
  23150. .'* Description: '.($command->getDescription() ?: '<none>')."\n"
  23151. .'* Usage: `'.$command->getSynopsis().'`'."\n"
  23152. .'* Aliases: '.(count($command->getAliases()) ? '`'.implode('`, `', $command->getAliases()).'`' : '<none>')
  23153. );
  23154. if ($help = $command->getProcessedHelp()) {
  23155. $this->write("\n\n");
  23156. $this->write($help);
  23157. }
  23158. if ($command->getNativeDefinition()) {
  23159. $this->write("\n\n");
  23160. $this->describeInputDefinition($command->getNativeDefinition());
  23161. }
  23162. }
  23163. protected function describeApplication(Application $application, array $options = array())
  23164. {
  23165. $describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
  23166. $description = new ApplicationDescription($application, $describedNamespace);
  23167. $this->write($application->getName()."\n".str_repeat('=', strlen($application->getName())));
  23168. foreach ($description->getNamespaces() as $namespace) {
  23169. if (ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
  23170. $this->write("\n\n");
  23171. $this->write('**'.$namespace['id'].':**');
  23172. }
  23173. $this->write("\n\n");
  23174. $this->write(implode("\n", array_map(function ($commandName) {
  23175. return '* '.$commandName;
  23176. }, $namespace['commands'])));
  23177. }
  23178. foreach ($description->getCommands() as $command) {
  23179. $this->write("\n\n");
  23180. $this->write($this->describeCommand($command));
  23181. }
  23182. }
  23183. }
  23184. <?php
  23185. namespace Symfony\Component\Console\Descriptor;
  23186. use Symfony\Component\Console\Application;
  23187. use Symfony\Component\Console\Command\Command;
  23188. use Symfony\Component\Console\Input\InputArgument;
  23189. use Symfony\Component\Console\Input\InputDefinition;
  23190. use Symfony\Component\Console\Input\InputOption;
  23191. class TextDescriptor extends Descriptor
  23192. {
  23193. protected function describeInputArgument(InputArgument $argument, array $options = array())
  23194. {
  23195. if (null !== $argument->getDefault() && (!is_array($argument->getDefault()) || count($argument->getDefault()))) {
  23196. $default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault()));
  23197. } else {
  23198. $default = '';
  23199. }
  23200. $nameWidth = isset($options['name_width']) ? $options['name_width'] : strlen($argument->getName());
  23201. $this->writeText(sprintf(" <info>%-${nameWidth}s</info> %s%s",
  23202. $argument->getName(),
  23203. str_replace("\n", "\n".str_repeat(' ', $nameWidth + 2), $argument->getDescription()),
  23204. $default
  23205. ), $options);
  23206. }
  23207. protected function describeInputOption(InputOption $option, array $options = array())
  23208. {
  23209. if ($option->acceptValue() && null !== $option->getDefault() && (!is_array($option->getDefault()) || count($option->getDefault()))) {
  23210. $default = sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($option->getDefault()));
  23211. } else {
  23212. $default = '';
  23213. }
  23214. $nameWidth = isset($options['name_width']) ? $options['name_width'] : strlen($option->getName());
  23215. $nameWithShortcutWidth = $nameWidth - strlen($option->getName()) - 2;
  23216. $this->writeText(sprintf(" <info>%s</info> %-${nameWithShortcutWidth}s%s%s%s",
  23217. '--'.$option->getName(),
  23218. $option->getShortcut() ? sprintf('(-%s) ', $option->getShortcut()) : '',
  23219. str_replace("\n", "\n".str_repeat(' ', $nameWidth + 2), $option->getDescription()),
  23220. $default,
  23221. $option->isArray() ? '<comment> (multiple values allowed)</comment>' : ''
  23222. ), $options);
  23223. }
  23224. protected function describeInputDefinition(InputDefinition $definition, array $options = array())
  23225. {
  23226. $nameWidth = 0;
  23227. foreach ($definition->getOptions() as $option) {
  23228. $nameLength = strlen($option->getName()) + 2;
  23229. if ($option->getShortcut()) {
  23230. $nameLength += strlen($option->getShortcut()) + 3;
  23231. }
  23232. $nameWidth = max($nameWidth, $nameLength);
  23233. }
  23234. foreach ($definition->getArguments() as $argument) {
  23235. $nameWidth = max($nameWidth, strlen($argument->getName()));
  23236. }
  23237. ++$nameWidth;
  23238. if ($definition->getArguments()) {
  23239. $this->writeText('<comment>Arguments:</comment>', $options);
  23240. $this->writeText("\n");
  23241. foreach ($definition->getArguments() as $argument) {
  23242. $this->describeInputArgument($argument, array_merge($options, array('name_width' => $nameWidth)));
  23243. $this->writeText("\n");
  23244. }
  23245. }
  23246. if ($definition->getArguments() && $definition->getOptions()) {
  23247. $this->writeText("\n");
  23248. }
  23249. if ($definition->getOptions()) {
  23250. $this->writeText('<comment>Options:</comment>', $options);
  23251. $this->writeText("\n");
  23252. foreach ($definition->getOptions() as $option) {
  23253. $this->describeInputOption($option, array_merge($options, array('name_width' => $nameWidth)));
  23254. $this->writeText("\n");
  23255. }
  23256. }
  23257. }
  23258. protected function describeCommand(Command $command, array $options = array())
  23259. {
  23260. $command->getSynopsis();
  23261. $command->mergeApplicationDefinition(false);
  23262. $this->writeText('<comment>Usage:</comment>', $options);
  23263. $this->writeText("\n");
  23264. $this->writeText(' '.$command->getSynopsis(), $options);
  23265. $this->writeText("\n");
  23266. if (count($command->getAliases()) > 0) {
  23267. $this->writeText("\n");
  23268. $this->writeText('<comment>Aliases:</comment> <info>'.implode(', ', $command->getAliases()).'</info>', $options);
  23269. }
  23270. if ($definition = $command->getNativeDefinition()) {
  23271. $this->writeText("\n");
  23272. $this->describeInputDefinition($definition, $options);
  23273. }
  23274. $this->writeText("\n");
  23275. if ($help = $command->getProcessedHelp()) {
  23276. $this->writeText('<comment>Help:</comment>', $options);
  23277. $this->writeText("\n");
  23278. $this->writeText(' '.str_replace("\n", "\n ", $help), $options);
  23279. $this->writeText("\n");
  23280. }
  23281. }
  23282. protected function describeApplication(Application $application, array $options = array())
  23283. {
  23284. $describedNamespace = isset($options['namespace']) ? $options['namespace'] : null;
  23285. $description = new ApplicationDescription($application, $describedNamespace);
  23286. if (isset($options['raw_text']) && $options['raw_text']) {
  23287. $width = $this->getColumnWidth($description->getCommands());
  23288. foreach ($description->getCommands() as $command) {
  23289. $this->writeText(sprintf("%-${width}s %s", $command->getName(), $command->getDescription()), $options);
  23290. $this->writeText("\n");
  23291. }
  23292. } else {
  23293. if ('' != $help = $application->getHelp()) {
  23294. $this->writeText("$help\n\n", $options);
  23295. }
  23296. $this->writeText("<comment>Usage:</comment>\n", $options);
  23297. $this->writeText(" [options] command [arguments]\n\n", $options);
  23298. $this->writeText('<comment>Options:</comment>', $options);
  23299. $inputOptions = $application->getDefinition()->getOptions();
  23300. $width = 0;
  23301. foreach ($inputOptions as $option) {
  23302. $nameLength = strlen($option->getName()) + 2;
  23303. if ($option->getShortcut()) {
  23304. $nameLength += strlen($option->getShortcut()) + 3;
  23305. }
  23306. $width = max($width, $nameLength);
  23307. }
  23308. ++$width;
  23309. foreach ($inputOptions as $option) {
  23310. $this->writeText("\n", $options);
  23311. $this->describeInputOption($option, array_merge($options, array('name_width' => $width)));
  23312. }
  23313. $this->writeText("\n\n", $options);
  23314. $width = $this->getColumnWidth($description->getCommands());
  23315. if ($describedNamespace) {
  23316. $this->writeText(sprintf("<comment>Available commands for the \"%s\" namespace:</comment>", $describedNamespace), $options);
  23317. } else {
  23318. $this->writeText('<comment>Available commands:</comment>', $options);
  23319. }
  23320. foreach ($description->getNamespaces() as $namespace) {
  23321. if (!$describedNamespace && ApplicationDescription::GLOBAL_NAMESPACE !== $namespace['id']) {
  23322. $this->writeText("\n");
  23323. $this->writeText('<comment>'.$namespace['id'].'</comment>', $options);
  23324. }
  23325. foreach ($namespace['commands'] as $name) {
  23326. $this->writeText("\n");
  23327. $this->writeText(sprintf(" <info>%-${width}s</info> %s", $name, $description->getCommand($name)->getDescription()), $options);
  23328. }
  23329. }
  23330. $this->writeText("\n");
  23331. }
  23332. }
  23333. private function writeText($content, array $options = array())
  23334. {
  23335. $this->write(
  23336. isset($options['raw_text']) && $options['raw_text'] ? strip_tags($content) : $content,
  23337. isset($options['raw_output']) ? !$options['raw_output'] : true
  23338. );
  23339. }
  23340. private function formatDefaultValue($default)
  23341. {
  23342. if (PHP_VERSION_ID < 50400) {
  23343. return str_replace('\/', '/', json_encode($default));
  23344. }
  23345. return json_encode($default, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
  23346. }
  23347. private function getColumnWidth(array $commands)
  23348. {
  23349. $width = 0;
  23350. foreach ($commands as $command) {
  23351. $width = strlen($command->getName()) > $width ? strlen($command->getName()) : $width;
  23352. }
  23353. return $width + 2;
  23354. }
  23355. }
  23356. <?php
  23357. namespace Symfony\Component\Console\Descriptor;
  23358. use Symfony\Component\Console\Application;
  23359. use Symfony\Component\Console\Command\Command;
  23360. use Symfony\Component\Console\Input\InputArgument;
  23361. use Symfony\Component\Console\Input\InputDefinition;
  23362. use Symfony\Component\Console\Input\InputOption;
  23363. class XmlDescriptor extends Descriptor
  23364. {
  23365. public function getInputDefinitionDocument(InputDefinition $definition)
  23366. {
  23367. $dom = new \DOMDocument('1.0', 'UTF-8');
  23368. $dom->appendChild($definitionXML = $dom->createElement('definition'));
  23369. $definitionXML->appendChild($argumentsXML = $dom->createElement('arguments'));
  23370. foreach ($definition->getArguments() as $argument) {
  23371. $this->appendDocument($argumentsXML, $this->getInputArgumentDocument($argument));
  23372. }
  23373. $definitionXML->appendChild($optionsXML = $dom->createElement('options'));
  23374. foreach ($definition->getOptions() as $option) {
  23375. $this->appendDocument($optionsXML, $this->getInputOptionDocument($option));
  23376. }
  23377. return $dom;
  23378. }
  23379. public function getCommandDocument(Command $command)
  23380. {
  23381. $dom = new \DOMDocument('1.0', 'UTF-8');
  23382. $dom->appendChild($commandXML = $dom->createElement('command'));
  23383. $command->getSynopsis();
  23384. $command->mergeApplicationDefinition(false);
  23385. $commandXML->setAttribute('id', $command->getName());
  23386. $commandXML->setAttribute('name', $command->getName());
  23387. $commandXML->appendChild($usageXML = $dom->createElement('usage'));
  23388. $usageXML->appendChild($dom->createTextNode(sprintf($command->getSynopsis(), '')));
  23389. $commandXML->appendChild($descriptionXML = $dom->createElement('description'));
  23390. $descriptionXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getDescription())));
  23391. $commandXML->appendChild($helpXML = $dom->createElement('help'));
  23392. $helpXML->appendChild($dom->createTextNode(str_replace("\n", "\n ", $command->getProcessedHelp())));
  23393. $commandXML->appendChild($aliasesXML = $dom->createElement('aliases'));
  23394. foreach ($command->getAliases() as $alias) {
  23395. $aliasesXML->appendChild($aliasXML = $dom->createElement('alias'));
  23396. $aliasXML->appendChild($dom->createTextNode($alias));
  23397. }
  23398. $definitionXML = $this->getInputDefinitionDocument($command->getNativeDefinition());
  23399. $this->appendDocument($commandXML, $definitionXML->getElementsByTagName('definition')->item(0));
  23400. return $dom;
  23401. }
  23402. public function getApplicationDocument(Application $application, $namespace = null)
  23403. {
  23404. $dom = new \DOMDocument('1.0', 'UTF-8');
  23405. $dom->appendChild($rootXml = $dom->createElement('symfony'));
  23406. if ($application->getName() !== 'UNKNOWN') {
  23407. $rootXml->setAttribute('name', $application->getName());
  23408. if ($application->getVersion() !== 'UNKNOWN') {
  23409. $rootXml->setAttribute('version', $application->getVersion());
  23410. }
  23411. }
  23412. $rootXml->appendChild($commandsXML = $dom->createElement('commands'));
  23413. $description = new ApplicationDescription($application, $namespace);
  23414. if ($namespace) {
  23415. $commandsXML->setAttribute('namespace', $namespace);
  23416. }
  23417. foreach ($description->getCommands() as $command) {
  23418. $this->appendDocument($commandsXML, $this->getCommandDocument($command));
  23419. }
  23420. if (!$namespace) {
  23421. $rootXml->appendChild($namespacesXML = $dom->createElement('namespaces'));
  23422. foreach ($description->getNamespaces() as $namespaceDescription) {
  23423. $namespacesXML->appendChild($namespaceArrayXML = $dom->createElement('namespace'));
  23424. $namespaceArrayXML->setAttribute('id', $namespaceDescription['id']);
  23425. foreach ($namespaceDescription['commands'] as $name) {
  23426. $namespaceArrayXML->appendChild($commandXML = $dom->createElement('command'));
  23427. $commandXML->appendChild($dom->createTextNode($name));
  23428. }
  23429. }
  23430. }
  23431. return $dom;
  23432. }
  23433. protected function describeInputArgument(InputArgument $argument, array $options = array())
  23434. {
  23435. $this->writeDocument($this->getInputArgumentDocument($argument));
  23436. }
  23437. protected function describeInputOption(InputOption $option, array $options = array())
  23438. {
  23439. $this->writeDocument($this->getInputOptionDocument($option));
  23440. }
  23441. protected function describeInputDefinition(InputDefinition $definition, array $options = array())
  23442. {
  23443. $this->writeDocument($this->getInputDefinitionDocument($definition));
  23444. }
  23445. protected function describeCommand(Command $command, array $options = array())
  23446. {
  23447. $this->writeDocument($this->getCommandDocument($command));
  23448. }
  23449. protected function describeApplication(Application $application, array $options = array())
  23450. {
  23451. $this->writeDocument($this->getApplicationDocument($application, isset($options['namespace']) ? $options['namespace'] : null));
  23452. }
  23453. private function appendDocument(\DOMNode $parentNode, \DOMNode $importedParent)
  23454. {
  23455. foreach ($importedParent->childNodes as $childNode) {
  23456. $parentNode->appendChild($parentNode->ownerDocument->importNode($childNode, true));
  23457. }
  23458. }
  23459. private function writeDocument(\DOMDocument $dom)
  23460. {
  23461. $dom->formatOutput = true;
  23462. $this->write($dom->saveXML());
  23463. }
  23464. private function getInputArgumentDocument(InputArgument $argument)
  23465. {
  23466. $dom = new \DOMDocument('1.0', 'UTF-8');
  23467. $dom->appendChild($objectXML = $dom->createElement('argument'));
  23468. $objectXML->setAttribute('name', $argument->getName());
  23469. $objectXML->setAttribute('is_required', $argument->isRequired() ? 1 : 0);
  23470. $objectXML->setAttribute('is_array', $argument->isArray() ? 1 : 0);
  23471. $objectXML->appendChild($descriptionXML = $dom->createElement('description'));
  23472. $descriptionXML->appendChild($dom->createTextNode($argument->getDescription()));
  23473. $objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
  23474. $defaults = is_array($argument->getDefault()) ? $argument->getDefault() : (is_bool($argument->getDefault()) ? array(var_export($argument->getDefault(), true)) : ($argument->getDefault() ? array($argument->getDefault()) : array()));
  23475. foreach ($defaults as $default) {
  23476. $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
  23477. $defaultXML->appendChild($dom->createTextNode($default));
  23478. }
  23479. return $dom;
  23480. }
  23481. private function getInputOptionDocument(InputOption $option)
  23482. {
  23483. $dom = new \DOMDocument('1.0', 'UTF-8');
  23484. $dom->appendChild($objectXML = $dom->createElement('option'));
  23485. $objectXML->setAttribute('name', '--'.$option->getName());
  23486. $pos = strpos($option->getShortcut(), '|');
  23487. if (false !== $pos) {
  23488. $objectXML->setAttribute('shortcut', '-'.substr($option->getShortcut(), 0, $pos));
  23489. $objectXML->setAttribute('shortcuts', '-'.implode('|-', explode('|', $option->getShortcut())));
  23490. } else {
  23491. $objectXML->setAttribute('shortcut', $option->getShortcut() ? '-'.$option->getShortcut() : '');
  23492. }
  23493. $objectXML->setAttribute('accept_value', $option->acceptValue() ? 1 : 0);
  23494. $objectXML->setAttribute('is_value_required', $option->isValueRequired() ? 1 : 0);
  23495. $objectXML->setAttribute('is_multiple', $option->isArray() ? 1 : 0);
  23496. $objectXML->appendChild($descriptionXML = $dom->createElement('description'));
  23497. $descriptionXML->appendChild($dom->createTextNode($option->getDescription()));
  23498. if ($option->acceptValue()) {
  23499. $defaults = is_array($option->getDefault()) ? $option->getDefault() : (is_bool($option->getDefault()) ? array(var_export($option->getDefault(), true)) : ($option->getDefault() ? array($option->getDefault()) : array()));
  23500. $objectXML->appendChild($defaultsXML = $dom->createElement('defaults'));
  23501. if (!empty($defaults)) {
  23502. foreach ($defaults as $default) {
  23503. $defaultsXML->appendChild($defaultXML = $dom->createElement('default'));
  23504. $defaultXML->appendChild($dom->createTextNode($default));
  23505. }
  23506. }
  23507. }
  23508. return $dom;
  23509. }
  23510. }
  23511. <?php
  23512. namespace Symfony\Component\Console\Event;
  23513. class ConsoleCommandEvent extends ConsoleEvent
  23514. {
  23515. const RETURN_CODE_DISABLED = 113;
  23516. private $commandShouldRun = true;
  23517. public function disableCommand()
  23518. {
  23519. return $this->commandShouldRun = false;
  23520. }
  23521. public function enableCommand()
  23522. {
  23523. return $this->commandShouldRun = true;
  23524. }
  23525. public function commandShouldRun()
  23526. {
  23527. return $this->commandShouldRun;
  23528. }
  23529. }
  23530. <?php
  23531. namespace Symfony\Component\Console\Event;
  23532. use Symfony\Component\Console\Command\Command;
  23533. use Symfony\Component\Console\Input\InputInterface;
  23534. use Symfony\Component\Console\Output\OutputInterface;
  23535. use Symfony\Component\EventDispatcher\Event;
  23536. class ConsoleEvent extends Event
  23537. {
  23538. protected $command;
  23539. private $input;
  23540. private $output;
  23541. public function __construct(Command $command, InputInterface $input, OutputInterface $output)
  23542. {
  23543. $this->command = $command;
  23544. $this->input = $input;
  23545. $this->output = $output;
  23546. }
  23547. public function getCommand()
  23548. {
  23549. return $this->command;
  23550. }
  23551. public function getInput()
  23552. {
  23553. return $this->input;
  23554. }
  23555. public function getOutput()
  23556. {
  23557. return $this->output;
  23558. }
  23559. }
  23560. <?php
  23561. namespace Symfony\Component\Console\Event;
  23562. use Symfony\Component\Console\Command\Command;
  23563. use Symfony\Component\Console\Input\InputInterface;
  23564. use Symfony\Component\Console\Output\OutputInterface;
  23565. class ConsoleExceptionEvent extends ConsoleEvent
  23566. {
  23567. private $exception;
  23568. private $exitCode;
  23569. public function __construct(Command $command, InputInterface $input, OutputInterface $output, \Exception $exception, $exitCode)
  23570. {
  23571. parent::__construct($command, $input, $output);
  23572. $this->setException($exception);
  23573. $this->exitCode = (int) $exitCode;
  23574. }
  23575. public function getException()
  23576. {
  23577. return $this->exception;
  23578. }
  23579. public function setException(\Exception $exception)
  23580. {
  23581. $this->exception = $exception;
  23582. }
  23583. public function getExitCode()
  23584. {
  23585. return $this->exitCode;
  23586. }
  23587. }
  23588. <?php
  23589. namespace Symfony\Component\Console\Event;
  23590. use Symfony\Component\Console\Command\Command;
  23591. use Symfony\Component\Console\Input\InputInterface;
  23592. use Symfony\Component\Console\Output\OutputInterface;
  23593. class ConsoleTerminateEvent extends ConsoleEvent
  23594. {
  23595. private $exitCode;
  23596. public function __construct(Command $command, InputInterface $input, OutputInterface $output, $exitCode)
  23597. {
  23598. parent::__construct($command, $input, $output);
  23599. $this->setExitCode($exitCode);
  23600. }
  23601. public function setExitCode($exitCode)
  23602. {
  23603. $this->exitCode = (int) $exitCode;
  23604. }
  23605. public function getExitCode()
  23606. {
  23607. return $this->exitCode;
  23608. }
  23609. }
  23610. <?php
  23611. namespace Symfony\Component\Console\Formatter;
  23612. class OutputFormatter implements OutputFormatterInterface
  23613. {
  23614. private $decorated;
  23615. private $styles = array();
  23616. private $styleStack;
  23617. public static function escape($text)
  23618. {
  23619. return preg_replace('/([^\\\\]?)</is', '$1\\<', $text);
  23620. }
  23621. public function __construct($decorated = false, array $styles = array())
  23622. {
  23623. $this->decorated = (bool) $decorated;
  23624. $this->setStyle('error', new OutputFormatterStyle('white', 'red'));
  23625. $this->setStyle('info', new OutputFormatterStyle('green'));
  23626. $this->setStyle('comment', new OutputFormatterStyle('yellow'));
  23627. $this->setStyle('question', new OutputFormatterStyle('black', 'cyan'));
  23628. foreach ($styles as $name => $style) {
  23629. $this->setStyle($name, $style);
  23630. }
  23631. $this->styleStack = new OutputFormatterStyleStack();
  23632. }
  23633. public function setDecorated($decorated)
  23634. {
  23635. $this->decorated = (bool) $decorated;
  23636. }
  23637. public function isDecorated()
  23638. {
  23639. return $this->decorated;
  23640. }
  23641. public function setStyle($name, OutputFormatterStyleInterface $style)
  23642. {
  23643. $this->styles[strtolower($name)] = $style;
  23644. }
  23645. public function hasStyle($name)
  23646. {
  23647. return isset($this->styles[strtolower($name)]);
  23648. }
  23649. public function getStyle($name)
  23650. {
  23651. if (!$this->hasStyle($name)) {
  23652. throw new \InvalidArgumentException(sprintf('Undefined style: %s', $name));
  23653. }
  23654. return $this->styles[strtolower($name)];
  23655. }
  23656. public function format($message)
  23657. {
  23658. $offset = 0;
  23659. $output = '';
  23660. $tagRegex = '[a-z][a-z0-9_=;-]*';
  23661. preg_match_all("#<(($tagRegex) | /($tagRegex)?)>#isx", $message, $matches, PREG_OFFSET_CAPTURE);
  23662. foreach ($matches[0] as $i => $match) {
  23663. $pos = $match[1];
  23664. $text = $match[0];
  23665. $output .= $this->applyCurrentStyle(substr($message, $offset, $pos - $offset));
  23666. $offset = $pos + strlen($text);
  23667. if ($open = '/' != $text[1]) {
  23668. $tag = $matches[1][$i][0];
  23669. } else {
  23670. $tag = isset($matches[3][$i][0]) ? $matches[3][$i][0] : '';
  23671. }
  23672. if (!$open && !$tag) {
  23673. $this->styleStack->pop();
  23674. } elseif ($pos && '\\' == $message[$pos - 1]) {
  23675. $output .= $this->applyCurrentStyle($text);
  23676. } elseif (false === $style = $this->createStyleFromString(strtolower($tag))) {
  23677. $output .= $this->applyCurrentStyle($text);
  23678. } elseif ($open) {
  23679. $this->styleStack->push($style);
  23680. } else {
  23681. $this->styleStack->pop($style);
  23682. }
  23683. }
  23684. $output .= $this->applyCurrentStyle(substr($message, $offset));
  23685. return str_replace('\\<', '<', $output);
  23686. }
  23687. public function getStyleStack()
  23688. {
  23689. return $this->styleStack;
  23690. }
  23691. private function createStyleFromString($string)
  23692. {
  23693. if (isset($this->styles[$string])) {
  23694. return $this->styles[$string];
  23695. }
  23696. if (!preg_match_all('/([^=]+)=([^;]+)(;|$)/', strtolower($string), $matches, PREG_SET_ORDER)) {
  23697. return false;
  23698. }
  23699. $style = new OutputFormatterStyle();
  23700. foreach ($matches as $match) {
  23701. array_shift($match);
  23702. if ('fg' == $match[0]) {
  23703. $style->setForeground($match[1]);
  23704. } elseif ('bg' == $match[0]) {
  23705. $style->setBackground($match[1]);
  23706. } else {
  23707. try {
  23708. $style->setOption($match[1]);
  23709. } catch (\InvalidArgumentException $e) {
  23710. return false;
  23711. }
  23712. }
  23713. }
  23714. return $style;
  23715. }
  23716. private function applyCurrentStyle($text)
  23717. {
  23718. return $this->isDecorated() && strlen($text) > 0 ? $this->styleStack->getCurrent()->apply($text) : $text;
  23719. }
  23720. }
  23721. <?php
  23722. namespace Symfony\Component\Console\Formatter;
  23723. interface OutputFormatterInterface
  23724. {
  23725. public function setDecorated($decorated);
  23726. public function isDecorated();
  23727. public function setStyle($name, OutputFormatterStyleInterface $style);
  23728. public function hasStyle($name);
  23729. public function getStyle($name);
  23730. public function format($message);
  23731. }
  23732. <?php
  23733. namespace Symfony\Component\Console\Formatter;
  23734. class OutputFormatterStyle implements OutputFormatterStyleInterface
  23735. {
  23736. private static $availableForegroundColors = array(
  23737. 'black' => array('set' => 30, 'unset' => 39),
  23738. 'red' => array('set' => 31, 'unset' => 39),
  23739. 'green' => array('set' => 32, 'unset' => 39),
  23740. 'yellow' => array('set' => 33, 'unset' => 39),
  23741. 'blue' => array('set' => 34, 'unset' => 39),
  23742. 'magenta' => array('set' => 35, 'unset' => 39),
  23743. 'cyan' => array('set' => 36, 'unset' => 39),
  23744. 'white' => array('set' => 37, 'unset' => 39),
  23745. );
  23746. private static $availableBackgroundColors = array(
  23747. 'black' => array('set' => 40, 'unset' => 49),
  23748. 'red' => array('set' => 41, 'unset' => 49),
  23749. 'green' => array('set' => 42, 'unset' => 49),
  23750. 'yellow' => array('set' => 43, 'unset' => 49),
  23751. 'blue' => array('set' => 44, 'unset' => 49),
  23752. 'magenta' => array('set' => 45, 'unset' => 49),
  23753. 'cyan' => array('set' => 46, 'unset' => 49),
  23754. 'white' => array('set' => 47, 'unset' => 49),
  23755. );
  23756. private static $availableOptions = array(
  23757. 'bold' => array('set' => 1, 'unset' => 22),
  23758. 'underscore' => array('set' => 4, 'unset' => 24),
  23759. 'blink' => array('set' => 5, 'unset' => 25),
  23760. 'reverse' => array('set' => 7, 'unset' => 27),
  23761. 'conceal' => array('set' => 8, 'unset' => 28),
  23762. );
  23763. private $foreground;
  23764. private $background;
  23765. private $options = array();
  23766. public function __construct($foreground = null, $background = null, array $options = array())
  23767. {
  23768. if (null !== $foreground) {
  23769. $this->setForeground($foreground);
  23770. }
  23771. if (null !== $background) {
  23772. $this->setBackground($background);
  23773. }
  23774. if (count($options)) {
  23775. $this->setOptions($options);
  23776. }
  23777. }
  23778. public function setForeground($color = null)
  23779. {
  23780. if (null === $color) {
  23781. $this->foreground = null;
  23782. return;
  23783. }
  23784. if (!isset(static::$availableForegroundColors[$color])) {
  23785. throw new \InvalidArgumentException(sprintf(
  23786. 'Invalid foreground color specified: "%s". Expected one of (%s)',
  23787. $color,
  23788. implode(', ', array_keys(static::$availableForegroundColors))
  23789. ));
  23790. }
  23791. $this->foreground = static::$availableForegroundColors[$color];
  23792. }
  23793. public function setBackground($color = null)
  23794. {
  23795. if (null === $color) {
  23796. $this->background = null;
  23797. return;
  23798. }
  23799. if (!isset(static::$availableBackgroundColors[$color])) {
  23800. throw new \InvalidArgumentException(sprintf(
  23801. 'Invalid background color specified: "%s". Expected one of (%s)',
  23802. $color,
  23803. implode(', ', array_keys(static::$availableBackgroundColors))
  23804. ));
  23805. }
  23806. $this->background = static::$availableBackgroundColors[$color];
  23807. }
  23808. public function setOption($option)
  23809. {
  23810. if (!isset(static::$availableOptions[$option])) {
  23811. throw new \InvalidArgumentException(sprintf(
  23812. 'Invalid option specified: "%s". Expected one of (%s)',
  23813. $option,
  23814. implode(', ', array_keys(static::$availableOptions))
  23815. ));
  23816. }
  23817. if (false === array_search(static::$availableOptions[$option], $this->options)) {
  23818. $this->options[] = static::$availableOptions[$option];
  23819. }
  23820. }
  23821. public function unsetOption($option)
  23822. {
  23823. if (!isset(static::$availableOptions[$option])) {
  23824. throw new \InvalidArgumentException(sprintf(
  23825. 'Invalid option specified: "%s". Expected one of (%s)',
  23826. $option,
  23827. implode(', ', array_keys(static::$availableOptions))
  23828. ));
  23829. }
  23830. $pos = array_search(static::$availableOptions[$option], $this->options);
  23831. if (false !== $pos) {
  23832. unset($this->options[$pos]);
  23833. }
  23834. }
  23835. public function setOptions(array $options)
  23836. {
  23837. $this->options = array();
  23838. foreach ($options as $option) {
  23839. $this->setOption($option);
  23840. }
  23841. }
  23842. public function apply($text)
  23843. {
  23844. $setCodes = array();
  23845. $unsetCodes = array();
  23846. if (null !== $this->foreground) {
  23847. $setCodes[] = $this->foreground['set'];
  23848. $unsetCodes[] = $this->foreground['unset'];
  23849. }
  23850. if (null !== $this->background) {
  23851. $setCodes[] = $this->background['set'];
  23852. $unsetCodes[] = $this->background['unset'];
  23853. }
  23854. if (count($this->options)) {
  23855. foreach ($this->options as $option) {
  23856. $setCodes[] = $option['set'];
  23857. $unsetCodes[] = $option['unset'];
  23858. }
  23859. }
  23860. if (0 === count($setCodes)) {
  23861. return $text;
  23862. }
  23863. return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
  23864. }
  23865. }
  23866. <?php
  23867. namespace Symfony\Component\Console\Formatter;
  23868. interface OutputFormatterStyleInterface
  23869. {
  23870. public function setForeground($color = null);
  23871. public function setBackground($color = null);
  23872. public function setOption($option);
  23873. public function unsetOption($option);
  23874. public function setOptions(array $options);
  23875. public function apply($text);
  23876. }
  23877. <?php
  23878. namespace Symfony\Component\Console\Formatter;
  23879. class OutputFormatterStyleStack
  23880. {
  23881. private $styles;
  23882. private $emptyStyle;
  23883. public function __construct(OutputFormatterStyleInterface $emptyStyle = null)
  23884. {
  23885. $this->emptyStyle = $emptyStyle ?: new OutputFormatterStyle();
  23886. $this->reset();
  23887. }
  23888. public function reset()
  23889. {
  23890. $this->styles = array();
  23891. }
  23892. public function push(OutputFormatterStyleInterface $style)
  23893. {
  23894. $this->styles[] = $style;
  23895. }
  23896. public function pop(OutputFormatterStyleInterface $style = null)
  23897. {
  23898. if (empty($this->styles)) {
  23899. return $this->emptyStyle;
  23900. }
  23901. if (null === $style) {
  23902. return array_pop($this->styles);
  23903. }
  23904. foreach (array_reverse($this->styles, true) as $index => $stackedStyle) {
  23905. if ($style->apply('') === $stackedStyle->apply('')) {
  23906. $this->styles = array_slice($this->styles, 0, $index);
  23907. return $stackedStyle;
  23908. }
  23909. }
  23910. throw new \InvalidArgumentException('Incorrectly nested style tag found.');
  23911. }
  23912. public function getCurrent()
  23913. {
  23914. if (empty($this->styles)) {
  23915. return $this->emptyStyle;
  23916. }
  23917. return $this->styles[count($this->styles)-1];
  23918. }
  23919. public function setEmptyStyle(OutputFormatterStyleInterface $emptyStyle)
  23920. {
  23921. $this->emptyStyle = $emptyStyle;
  23922. return $this;
  23923. }
  23924. public function getEmptyStyle()
  23925. {
  23926. return $this->emptyStyle;
  23927. }
  23928. }
  23929. <?php
  23930. namespace Symfony\Component\Console\Helper;
  23931. class DebugFormatterHelper extends Helper
  23932. {
  23933. private $colors = array('black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white');
  23934. private $started = array();
  23935. private $count = -1;
  23936. public function start($id, $message, $prefix = 'RUN')
  23937. {
  23938. $this->started[$id] = array('border' => ++$this->count % count($this->colors));
  23939. return sprintf("%s<bg=blue;fg=white> %s </> <fg=blue>%s</>\n", $this->getBorder($id), $prefix, $message);
  23940. }
  23941. public function progress($id, $buffer, $error = false, $prefix = 'OUT', $errorPrefix = 'ERR')
  23942. {
  23943. $message = '';
  23944. if ($error) {
  23945. if (isset($this->started[$id]['out'])) {
  23946. $message .= "\n";
  23947. unset($this->started[$id]['out']);
  23948. }
  23949. if (!isset($this->started[$id]['err'])) {
  23950. $message .= sprintf("%s<bg=red;fg=white> %s </> ", $this->getBorder($id), $errorPrefix);
  23951. $this->started[$id]['err'] = true;
  23952. }
  23953. $message .= str_replace("\n", sprintf("\n%s<bg=red;fg=white> %s </> ", $this->getBorder($id), $errorPrefix), $buffer);
  23954. } else {
  23955. if (isset($this->started[$id]['err'])) {
  23956. $message .= "\n";
  23957. unset($this->started[$id]['err']);
  23958. }
  23959. if (!isset($this->started[$id]['out'])) {
  23960. $message .= sprintf("%s<bg=green;fg=white> %s </> ", $this->getBorder($id), $prefix);
  23961. $this->started[$id]['out'] = true;
  23962. }
  23963. $message .= str_replace("\n", sprintf("\n%s<bg=green;fg=white> %s </> ", $this->getBorder($id), $prefix), $buffer);
  23964. }
  23965. return $message;
  23966. }
  23967. public function stop($id, $message, $successful, $prefix = 'RES')
  23968. {
  23969. $trailingEOL = isset($this->started[$id]['out']) || isset($this->started[$id]['err']) ? "\n" : '';
  23970. if ($successful) {
  23971. return sprintf("%s%s<bg=green;fg=white> %s </> <fg=green>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
  23972. }
  23973. $message = sprintf("%s%s<bg=red;fg=white> %s </> <fg=red>%s</>\n", $trailingEOL, $this->getBorder($id), $prefix, $message);
  23974. unset($this->started[$id]['out'], $this->started[$id]['err']);
  23975. return $message;
  23976. }
  23977. private function getBorder($id)
  23978. {
  23979. return sprintf('<bg=%s> </>', $this->colors[$this->started[$id]['border']]);
  23980. }
  23981. public function getName()
  23982. {
  23983. return 'debug_formatter';
  23984. }
  23985. }
  23986. <?php
  23987. namespace Symfony\Component\Console\Helper;
  23988. use Symfony\Component\Console\Descriptor\DescriptorInterface;
  23989. use Symfony\Component\Console\Descriptor\JsonDescriptor;
  23990. use Symfony\Component\Console\Descriptor\MarkdownDescriptor;
  23991. use Symfony\Component\Console\Descriptor\TextDescriptor;
  23992. use Symfony\Component\Console\Descriptor\XmlDescriptor;
  23993. use Symfony\Component\Console\Output\OutputInterface;
  23994. class DescriptorHelper extends Helper
  23995. {
  23996. private $descriptors = array();
  23997. public function __construct()
  23998. {
  23999. $this
  24000. ->register('txt', new TextDescriptor())
  24001. ->register('xml', new XmlDescriptor())
  24002. ->register('json', new JsonDescriptor())
  24003. ->register('md', new MarkdownDescriptor())
  24004. ;
  24005. }
  24006. public function describe(OutputInterface $output, $object, array $options = array())
  24007. {
  24008. $options = array_merge(array(
  24009. 'raw_text' => false,
  24010. 'format' => 'txt',
  24011. ), $options);
  24012. if (!isset($this->descriptors[$options['format']])) {
  24013. throw new \InvalidArgumentException(sprintf('Unsupported format "%s".', $options['format']));
  24014. }
  24015. $descriptor = $this->descriptors[$options['format']];
  24016. $descriptor->describe($output, $object, $options);
  24017. }
  24018. public function register($format, DescriptorInterface $descriptor)
  24019. {
  24020. $this->descriptors[$format] = $descriptor;
  24021. return $this;
  24022. }
  24023. public function getName()
  24024. {
  24025. return 'descriptor';
  24026. }
  24027. }
  24028. <?php
  24029. namespace Symfony\Component\Console\Helper;
  24030. use Symfony\Component\Console\Output\OutputInterface;
  24031. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  24032. class DialogHelper extends InputAwareHelper
  24033. {
  24034. private $inputStream;
  24035. private static $shell;
  24036. private static $stty;
  24037. public function select(OutputInterface $output, $question, $choices, $default = null, $attempts = false, $errorMessage = 'Value "%s" is invalid', $multiselect = false)
  24038. {
  24039. $width = max(array_map('strlen', array_keys($choices)));
  24040. $messages = (array) $question;
  24041. foreach ($choices as $key => $value) {
  24042. $messages[] = sprintf(" [<info>%-${width}s</info>] %s", $key, $value);
  24043. }
  24044. $output->writeln($messages);
  24045. $result = $this->askAndValidate($output, '> ', function ($picked) use ($choices, $errorMessage, $multiselect) {
  24046. $selectedChoices = str_replace(" ", "", $picked);
  24047. if ($multiselect) {
  24048. if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
  24049. throw new \InvalidArgumentException(sprintf($errorMessage, $picked));
  24050. }
  24051. $selectedChoices = explode(",", $selectedChoices);
  24052. } else {
  24053. $selectedChoices = array($picked);
  24054. }
  24055. $multiselectChoices = array();
  24056. foreach ($selectedChoices as $value) {
  24057. if (empty($choices[$value])) {
  24058. throw new \InvalidArgumentException(sprintf($errorMessage, $value));
  24059. }
  24060. array_push($multiselectChoices, $value);
  24061. }
  24062. if ($multiselect) {
  24063. return $multiselectChoices;
  24064. }
  24065. return $picked;
  24066. }, $attempts, $default);
  24067. return $result;
  24068. }
  24069. public function ask(OutputInterface $output, $question, $default = null, array $autocomplete = null)
  24070. {
  24071. if ($this->input && !$this->input->isInteractive()) {
  24072. return $default;
  24073. }
  24074. $output->write($question);
  24075. $inputStream = $this->inputStream ?: STDIN;
  24076. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  24077. $ret = fgets($inputStream, 4096);
  24078. if (false === $ret) {
  24079. throw new \RuntimeException('Aborted');
  24080. }
  24081. $ret = trim($ret);
  24082. } else {
  24083. $ret = '';
  24084. $i = 0;
  24085. $ofs = -1;
  24086. $matches = $autocomplete;
  24087. $numMatches = count($matches);
  24088. $sttyMode = shell_exec('stty -g');
  24089. shell_exec('stty -icanon -echo');
  24090. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  24091. while (!feof($inputStream)) {
  24092. $c = fread($inputStream, 1);
  24093. if ("\177" === $c) {
  24094. if (0 === $numMatches && 0 !== $i) {
  24095. $i--;
  24096. $output->write("\033[1D");
  24097. }
  24098. if ($i === 0) {
  24099. $ofs = -1;
  24100. $matches = $autocomplete;
  24101. $numMatches = count($matches);
  24102. } else {
  24103. $numMatches = 0;
  24104. }
  24105. $ret = substr($ret, 0, $i);
  24106. } elseif ("\033" === $c) {
  24107. $c .= fread($inputStream, 2);
  24108. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  24109. if ('A' === $c[2] && -1 === $ofs) {
  24110. $ofs = 0;
  24111. }
  24112. if (0 === $numMatches) {
  24113. continue;
  24114. }
  24115. $ofs += ('A' === $c[2]) ? -1 : 1;
  24116. $ofs = ($numMatches + $ofs) % $numMatches;
  24117. }
  24118. } elseif (ord($c) < 32) {
  24119. if ("\t" === $c || "\n" === $c) {
  24120. if ($numMatches > 0 && -1 !== $ofs) {
  24121. $ret = $matches[$ofs];
  24122. $output->write(substr($ret, $i));
  24123. $i = strlen($ret);
  24124. }
  24125. if ("\n" === $c) {
  24126. $output->write($c);
  24127. break;
  24128. }
  24129. $numMatches = 0;
  24130. }
  24131. continue;
  24132. } else {
  24133. $output->write($c);
  24134. $ret .= $c;
  24135. $i++;
  24136. $numMatches = 0;
  24137. $ofs = 0;
  24138. foreach ($autocomplete as $value) {
  24139. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  24140. $matches[$numMatches++] = $value;
  24141. }
  24142. }
  24143. }
  24144. $output->write("\033[K");
  24145. if ($numMatches > 0 && -1 !== $ofs) {
  24146. $output->write("\0337");
  24147. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  24148. $output->write("\0338");
  24149. }
  24150. }
  24151. shell_exec(sprintf('stty %s', $sttyMode));
  24152. }
  24153. return strlen($ret) > 0 ? $ret : $default;
  24154. }
  24155. public function askConfirmation(OutputInterface $output, $question, $default = true)
  24156. {
  24157. $answer = 'z';
  24158. while ($answer && !in_array(strtolower($answer[0]), array('y', 'n'))) {
  24159. $answer = $this->ask($output, $question);
  24160. }
  24161. if (false === $default) {
  24162. return $answer && 'y' == strtolower($answer[0]);
  24163. }
  24164. return !$answer || 'y' == strtolower($answer[0]);
  24165. }
  24166. public function askHiddenResponse(OutputInterface $output, $question, $fallback = true)
  24167. {
  24168. if ('\\' === DIRECTORY_SEPARATOR) {
  24169. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  24170. if ('phar:' === substr(__FILE__, 0, 5)) {
  24171. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  24172. copy($exe, $tmpExe);
  24173. $exe = $tmpExe;
  24174. }
  24175. $output->write($question);
  24176. $value = rtrim(shell_exec($exe));
  24177. $output->writeln('');
  24178. if (isset($tmpExe)) {
  24179. unlink($tmpExe);
  24180. }
  24181. return $value;
  24182. }
  24183. if ($this->hasSttyAvailable()) {
  24184. $output->write($question);
  24185. $sttyMode = shell_exec('stty -g');
  24186. shell_exec('stty -echo');
  24187. $value = fgets($this->inputStream ?: STDIN, 4096);
  24188. shell_exec(sprintf('stty %s', $sttyMode));
  24189. if (false === $value) {
  24190. throw new \RuntimeException('Aborted');
  24191. }
  24192. $value = trim($value);
  24193. $output->writeln('');
  24194. return $value;
  24195. }
  24196. if (false !== $shell = $this->getShell()) {
  24197. $output->write($question);
  24198. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  24199. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  24200. $value = rtrim(shell_exec($command));
  24201. $output->writeln('');
  24202. return $value;
  24203. }
  24204. if ($fallback) {
  24205. return $this->ask($output, $question);
  24206. }
  24207. throw new \RuntimeException('Unable to hide the response');
  24208. }
  24209. public function askAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $default = null, array $autocomplete = null)
  24210. {
  24211. $that = $this;
  24212. $interviewer = function () use ($output, $question, $default, $autocomplete, $that) {
  24213. return $that->ask($output, $question, $default, $autocomplete);
  24214. };
  24215. return $this->validateAttempts($interviewer, $output, $validator, $attempts);
  24216. }
  24217. public function askHiddenResponseAndValidate(OutputInterface $output, $question, $validator, $attempts = false, $fallback = true)
  24218. {
  24219. $that = $this;
  24220. $interviewer = function () use ($output, $question, $fallback, $that) {
  24221. return $that->askHiddenResponse($output, $question, $fallback);
  24222. };
  24223. return $this->validateAttempts($interviewer, $output, $validator, $attempts);
  24224. }
  24225. public function setInputStream($stream)
  24226. {
  24227. $this->inputStream = $stream;
  24228. }
  24229. public function getInputStream()
  24230. {
  24231. return $this->inputStream;
  24232. }
  24233. public function getName()
  24234. {
  24235. return 'dialog';
  24236. }
  24237. private function getShell()
  24238. {
  24239. if (null !== self::$shell) {
  24240. return self::$shell;
  24241. }
  24242. self::$shell = false;
  24243. if (file_exists('/usr/bin/env')) {
  24244. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  24245. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  24246. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  24247. self::$shell = $sh;
  24248. break;
  24249. }
  24250. }
  24251. }
  24252. return self::$shell;
  24253. }
  24254. private function hasSttyAvailable()
  24255. {
  24256. if (null !== self::$stty) {
  24257. return self::$stty;
  24258. }
  24259. exec('stty 2>&1', $output, $exitcode);
  24260. return self::$stty = $exitcode === 0;
  24261. }
  24262. private function validateAttempts($interviewer, OutputInterface $output, $validator, $attempts)
  24263. {
  24264. $error = null;
  24265. while (false === $attempts || $attempts--) {
  24266. if (null !== $error) {
  24267. $output->writeln($this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error'));
  24268. }
  24269. try {
  24270. return call_user_func($validator, $interviewer());
  24271. } catch (\Exception $error) {
  24272. }
  24273. }
  24274. throw $error;
  24275. }
  24276. }
  24277. <?php
  24278. namespace Symfony\Component\Console\Helper;
  24279. use Symfony\Component\Console\Formatter\OutputFormatter;
  24280. class FormatterHelper extends Helper
  24281. {
  24282. public function formatSection($section, $message, $style = 'info')
  24283. {
  24284. return sprintf('<%s>[%s]</%s> %s', $style, $section, $style, $message);
  24285. }
  24286. public function formatBlock($messages, $style, $large = false)
  24287. {
  24288. $messages = (array) $messages;
  24289. $len = 0;
  24290. $lines = array();
  24291. foreach ($messages as $message) {
  24292. $message = OutputFormatter::escape($message);
  24293. $lines[] = sprintf($large ? ' %s ' : ' %s ', $message);
  24294. $len = max($this->strlen($message) + ($large ? 4 : 2), $len);
  24295. }
  24296. $messages = $large ? array(str_repeat(' ', $len)) : array();
  24297. foreach ($lines as $line) {
  24298. $messages[] = $line.str_repeat(' ', $len - $this->strlen($line));
  24299. }
  24300. if ($large) {
  24301. $messages[] = str_repeat(' ', $len);
  24302. }
  24303. foreach ($messages as &$message) {
  24304. $message = sprintf('<%s>%s</%s>', $style, $message, $style);
  24305. }
  24306. return implode("\n", $messages);
  24307. }
  24308. public function getName()
  24309. {
  24310. return 'formatter';
  24311. }
  24312. }
  24313. <?php
  24314. namespace Symfony\Component\Console\Helper;
  24315. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  24316. abstract class Helper implements HelperInterface
  24317. {
  24318. protected $helperSet = null;
  24319. public function setHelperSet(HelperSet $helperSet = null)
  24320. {
  24321. $this->helperSet = $helperSet;
  24322. }
  24323. public function getHelperSet()
  24324. {
  24325. return $this->helperSet;
  24326. }
  24327. public static function strlen($string)
  24328. {
  24329. if (!function_exists('mb_strwidth')) {
  24330. return strlen($string);
  24331. }
  24332. if (false === $encoding = mb_detect_encoding($string)) {
  24333. return strlen($string);
  24334. }
  24335. return mb_strwidth($string, $encoding);
  24336. }
  24337. public static function formatTime($secs)
  24338. {
  24339. static $timeFormats = array(
  24340. array(0, '< 1 sec'),
  24341. array(2, '1 sec'),
  24342. array(59, 'secs', 1),
  24343. array(60, '1 min'),
  24344. array(3600, 'mins', 60),
  24345. array(5400, '1 hr'),
  24346. array(86400, 'hrs', 3600),
  24347. array(129600, '1 day'),
  24348. array(604800, 'days', 86400),
  24349. );
  24350. foreach ($timeFormats as $format) {
  24351. if ($secs >= $format[0]) {
  24352. continue;
  24353. }
  24354. if (2 == count($format)) {
  24355. return $format[1];
  24356. }
  24357. return ceil($secs / $format[2]).' '.$format[1];
  24358. }
  24359. }
  24360. public static function formatMemory($memory)
  24361. {
  24362. if ($memory >= 1024 * 1024 * 1024) {
  24363. return sprintf('%.1f GiB', $memory / 1024 / 1024 / 1024);
  24364. }
  24365. if ($memory >= 1024 * 1024) {
  24366. return sprintf('%.1f MiB', $memory / 1024 / 1024);
  24367. }
  24368. if ($memory >= 1024) {
  24369. return sprintf('%d KiB', $memory / 1024);
  24370. }
  24371. return sprintf('%d B', $memory);
  24372. }
  24373. public static function strlenWithoutDecoration(OutputFormatterInterface $formatter, $string)
  24374. {
  24375. $isDecorated = $formatter->isDecorated();
  24376. $formatter->setDecorated(false);
  24377. $string = $formatter->format($string);
  24378. $string = preg_replace("/\033\[[^m]*m/", '', $string);
  24379. $formatter->setDecorated($isDecorated);
  24380. return self::strlen($string);
  24381. }
  24382. }
  24383. <?php
  24384. namespace Symfony\Component\Console\Helper;
  24385. interface HelperInterface
  24386. {
  24387. public function setHelperSet(HelperSet $helperSet = null);
  24388. public function getHelperSet();
  24389. public function getName();
  24390. }
  24391. <?php
  24392. namespace Symfony\Component\Console\Helper;
  24393. use Symfony\Component\Console\Command\Command;
  24394. class HelperSet implements \IteratorAggregate
  24395. {
  24396. private $helpers = array();
  24397. private $command;
  24398. public function __construct(array $helpers = array())
  24399. {
  24400. foreach ($helpers as $alias => $helper) {
  24401. $this->set($helper, is_int($alias) ? null : $alias);
  24402. }
  24403. }
  24404. public function set(HelperInterface $helper, $alias = null)
  24405. {
  24406. $this->helpers[$helper->getName()] = $helper;
  24407. if (null !== $alias) {
  24408. $this->helpers[$alias] = $helper;
  24409. }
  24410. $helper->setHelperSet($this);
  24411. }
  24412. public function has($name)
  24413. {
  24414. return isset($this->helpers[$name]);
  24415. }
  24416. public function get($name)
  24417. {
  24418. if (!$this->has($name)) {
  24419. throw new \InvalidArgumentException(sprintf('The helper "%s" is not defined.', $name));
  24420. }
  24421. return $this->helpers[$name];
  24422. }
  24423. public function setCommand(Command $command = null)
  24424. {
  24425. $this->command = $command;
  24426. }
  24427. public function getCommand()
  24428. {
  24429. return $this->command;
  24430. }
  24431. public function getIterator()
  24432. {
  24433. return new \ArrayIterator($this->helpers);
  24434. }
  24435. }
  24436. <?php
  24437. namespace Symfony\Component\Console\Helper;
  24438. use Symfony\Component\Console\Input\InputInterface;
  24439. use Symfony\Component\Console\Input\InputAwareInterface;
  24440. abstract class InputAwareHelper extends Helper implements InputAwareInterface
  24441. {
  24442. protected $input;
  24443. public function setInput(InputInterface $input)
  24444. {
  24445. $this->input = $input;
  24446. }
  24447. }
  24448. <?php
  24449. namespace Symfony\Component\Console\Helper;
  24450. use Symfony\Component\Console\Output\OutputInterface;
  24451. use Symfony\Component\Process\Exception\ProcessFailedException;
  24452. use Symfony\Component\Process\Process;
  24453. use Symfony\Component\Process\ProcessBuilder;
  24454. class ProcessHelper extends Helper
  24455. {
  24456. public function run(OutputInterface $output, $cmd, $error = null, $callback = null, $verbosity = OutputInterface::VERBOSITY_VERY_VERBOSE)
  24457. {
  24458. $formatter = $this->getHelperSet()->get('debug_formatter');
  24459. if (is_array($cmd)) {
  24460. $process = ProcessBuilder::create($cmd)->getProcess();
  24461. } elseif ($cmd instanceof Process) {
  24462. $process = $cmd;
  24463. } else {
  24464. $process = new Process($cmd);
  24465. }
  24466. if ($verbosity <= $output->getVerbosity()) {
  24467. $output->write($formatter->start(spl_object_hash($process), $this->escapeString($process->getCommandLine())));
  24468. }
  24469. if ($output->isDebug()) {
  24470. $callback = $this->wrapCallback($output, $process, $callback);
  24471. }
  24472. $process->run($callback);
  24473. if ($verbosity <= $output->getVerbosity()) {
  24474. $message = $process->isSuccessful() ? 'Command ran successfully' : sprintf('%s Command did not run successfully', $process->getExitCode());
  24475. $output->write($formatter->stop(spl_object_hash($process), $message, $process->isSuccessful()));
  24476. }
  24477. if (!$process->isSuccessful() && null !== $error) {
  24478. $output->writeln(sprintf('<error>%s</error>', $this->escapeString($error)));
  24479. }
  24480. return $process;
  24481. }
  24482. public function mustRun(OutputInterface $output, $cmd, $error = null, $callback = null)
  24483. {
  24484. $process = $this->run($output, $cmd, $error, $callback);
  24485. if (!$process->isSuccessful()) {
  24486. throw new ProcessFailedException($process);
  24487. }
  24488. return $process;
  24489. }
  24490. public function wrapCallback(OutputInterface $output, Process $process, $callback = null)
  24491. {
  24492. $formatter = $this->getHelperSet()->get('debug_formatter');
  24493. $that = $this;
  24494. return function ($type, $buffer) use ($output, $process, $callback, $formatter, $that) {
  24495. $output->write($formatter->progress(spl_object_hash($process), $that->escapeString($buffer), Process::ERR === $type));
  24496. if (null !== $callback) {
  24497. call_user_func($callback, $type, $buffer);
  24498. }
  24499. };
  24500. }
  24501. public function escapeString($str)
  24502. {
  24503. return str_replace('<', '\\<', $str);
  24504. }
  24505. public function getName()
  24506. {
  24507. return 'process';
  24508. }
  24509. }
  24510. <?php
  24511. namespace Symfony\Component\Console\Helper;
  24512. use Symfony\Component\Console\Output\OutputInterface;
  24513. class ProgressBar
  24514. {
  24515. private $barWidth = 28;
  24516. private $barChar;
  24517. private $emptyBarChar = '-';
  24518. private $progressChar = '>';
  24519. private $format = null;
  24520. private $redrawFreq = 1;
  24521. private $output;
  24522. private $step = 0;
  24523. private $max;
  24524. private $startTime;
  24525. private $stepWidth;
  24526. private $percent = 0.0;
  24527. private $lastMessagesLength = 0;
  24528. private $formatLineCount;
  24529. private $messages;
  24530. private $overwrite = true;
  24531. private static $formatters;
  24532. private static $formats;
  24533. public function __construct(OutputInterface $output, $max = 0)
  24534. {
  24535. $this->output = $output;
  24536. $this->setMaxSteps($max);
  24537. if (!$this->output->isDecorated()) {
  24538. $this->overwrite = false;
  24539. if ($this->max > 10) {
  24540. $this->setRedrawFrequency($max / 10);
  24541. }
  24542. }
  24543. $this->setFormat($this->determineBestFormat());
  24544. $this->startTime = time();
  24545. }
  24546. public static function setPlaceholderFormatterDefinition($name, $callable)
  24547. {
  24548. if (!self::$formatters) {
  24549. self::$formatters = self::initPlaceholderFormatters();
  24550. }
  24551. self::$formatters[$name] = $callable;
  24552. }
  24553. public static function getPlaceholderFormatterDefinition($name)
  24554. {
  24555. if (!self::$formatters) {
  24556. self::$formatters = self::initPlaceholderFormatters();
  24557. }
  24558. return isset(self::$formatters[$name]) ? self::$formatters[$name] : null;
  24559. }
  24560. public static function setFormatDefinition($name, $format)
  24561. {
  24562. if (!self::$formats) {
  24563. self::$formats = self::initFormats();
  24564. }
  24565. self::$formats[$name] = $format;
  24566. }
  24567. public static function getFormatDefinition($name)
  24568. {
  24569. if (!self::$formats) {
  24570. self::$formats = self::initFormats();
  24571. }
  24572. return isset(self::$formats[$name]) ? self::$formats[$name] : null;
  24573. }
  24574. public function setMessage($message, $name = 'message')
  24575. {
  24576. $this->messages[$name] = $message;
  24577. }
  24578. public function getMessage($name = 'message')
  24579. {
  24580. return $this->messages[$name];
  24581. }
  24582. public function getStartTime()
  24583. {
  24584. return $this->startTime;
  24585. }
  24586. public function getMaxSteps()
  24587. {
  24588. return $this->max;
  24589. }
  24590. public function getStep()
  24591. {
  24592. return $this->getProgress();
  24593. }
  24594. public function getProgress()
  24595. {
  24596. return $this->step;
  24597. }
  24598. public function getStepWidth()
  24599. {
  24600. return $this->stepWidth;
  24601. }
  24602. public function getProgressPercent()
  24603. {
  24604. return $this->percent;
  24605. }
  24606. public function setBarWidth($size)
  24607. {
  24608. $this->barWidth = (int) $size;
  24609. }
  24610. public function getBarWidth()
  24611. {
  24612. return $this->barWidth;
  24613. }
  24614. public function setBarCharacter($char)
  24615. {
  24616. $this->barChar = $char;
  24617. }
  24618. public function getBarCharacter()
  24619. {
  24620. if (null === $this->barChar) {
  24621. return $this->max ? '=' : $this->emptyBarChar;
  24622. }
  24623. return $this->barChar;
  24624. }
  24625. public function setEmptyBarCharacter($char)
  24626. {
  24627. $this->emptyBarChar = $char;
  24628. }
  24629. public function getEmptyBarCharacter()
  24630. {
  24631. return $this->emptyBarChar;
  24632. }
  24633. public function setProgressCharacter($char)
  24634. {
  24635. $this->progressChar = $char;
  24636. }
  24637. public function getProgressCharacter()
  24638. {
  24639. return $this->progressChar;
  24640. }
  24641. public function setFormat($format)
  24642. {
  24643. if (!$this->max && null !== self::getFormatDefinition($format.'_nomax')) {
  24644. $this->format = self::getFormatDefinition($format.'_nomax');
  24645. } elseif (null !== self::getFormatDefinition($format)) {
  24646. $this->format = self::getFormatDefinition($format);
  24647. } else {
  24648. $this->format = $format;
  24649. }
  24650. $this->formatLineCount = substr_count($this->format, "\n");
  24651. }
  24652. public function setRedrawFrequency($freq)
  24653. {
  24654. $this->redrawFreq = (int) $freq;
  24655. }
  24656. public function start($max = null)
  24657. {
  24658. $this->startTime = time();
  24659. $this->step = 0;
  24660. $this->percent = 0.0;
  24661. if (null !== $max) {
  24662. $this->setMaxSteps($max);
  24663. }
  24664. $this->display();
  24665. }
  24666. public function advance($step = 1)
  24667. {
  24668. $this->setProgress($this->step + $step);
  24669. }
  24670. public function setCurrent($step)
  24671. {
  24672. $this->setProgress($step);
  24673. }
  24674. public function setOverwrite($overwrite)
  24675. {
  24676. $this->overwrite = (bool) $overwrite;
  24677. }
  24678. public function setProgress($step)
  24679. {
  24680. $step = (int) $step;
  24681. if ($step < $this->step) {
  24682. throw new \LogicException('You can\'t regress the progress bar.');
  24683. }
  24684. if ($this->max && $step > $this->max) {
  24685. $this->max = $step;
  24686. }
  24687. $prevPeriod = intval($this->step / $this->redrawFreq);
  24688. $currPeriod = intval($step / $this->redrawFreq);
  24689. $this->step = $step;
  24690. $this->percent = $this->max ? (float) $this->step / $this->max : 0;
  24691. if ($prevPeriod !== $currPeriod || $this->max === $step) {
  24692. $this->display();
  24693. }
  24694. }
  24695. public function finish()
  24696. {
  24697. if (!$this->max) {
  24698. $this->max = $this->step;
  24699. }
  24700. if ($this->step === $this->max && !$this->overwrite) {
  24701. return;
  24702. }
  24703. $this->setProgress($this->max);
  24704. }
  24705. public function display()
  24706. {
  24707. if (OutputInterface::VERBOSITY_QUIET === $this->output->getVerbosity()) {
  24708. return;
  24709. }
  24710. $self = $this;
  24711. $output = $this->output;
  24712. $messages = $this->messages;
  24713. $this->overwrite(preg_replace_callback("{%([a-z\-_]+)(?:\:([^%]+))?%}i", function ($matches) use ($self, $output, $messages) {
  24714. if ($formatter = $self::getPlaceholderFormatterDefinition($matches[1])) {
  24715. $text = call_user_func($formatter, $self, $output);
  24716. } elseif (isset($messages[$matches[1]])) {
  24717. $text = $messages[$matches[1]];
  24718. } else {
  24719. return $matches[0];
  24720. }
  24721. if (isset($matches[2])) {
  24722. $text = sprintf('%'.$matches[2], $text);
  24723. }
  24724. return $text;
  24725. }, $this->format));
  24726. }
  24727. public function clear()
  24728. {
  24729. if (!$this->overwrite) {
  24730. return;
  24731. }
  24732. $this->overwrite(str_repeat("\n", $this->formatLineCount));
  24733. }
  24734. private function setMaxSteps($max)
  24735. {
  24736. $this->max = max(0, (int) $max);
  24737. $this->stepWidth = $this->max ? Helper::strlen($this->max) : 4;
  24738. }
  24739. private function overwrite($message)
  24740. {
  24741. $lines = explode("\n", $message);
  24742. if (null !== $this->lastMessagesLength) {
  24743. foreach ($lines as $i => $line) {
  24744. if ($this->lastMessagesLength > Helper::strlenWithoutDecoration($this->output->getFormatter(), $line)) {
  24745. $lines[$i] = str_pad($line, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
  24746. }
  24747. }
  24748. }
  24749. if ($this->overwrite) {
  24750. $this->output->write("\x0D");
  24751. } elseif ($this->step > 0) {
  24752. $this->output->writeln('');
  24753. }
  24754. if ($this->formatLineCount) {
  24755. $this->output->write(sprintf("\033[%dA", $this->formatLineCount));
  24756. }
  24757. $this->output->write(implode("\n", $lines));
  24758. $this->lastMessagesLength = 0;
  24759. foreach ($lines as $line) {
  24760. $len = Helper::strlenWithoutDecoration($this->output->getFormatter(), $line);
  24761. if ($len > $this->lastMessagesLength) {
  24762. $this->lastMessagesLength = $len;
  24763. }
  24764. }
  24765. }
  24766. private function determineBestFormat()
  24767. {
  24768. switch ($this->output->getVerbosity()) {
  24769. case OutputInterface::VERBOSITY_VERBOSE:
  24770. return $this->max ? 'verbose' : 'verbose_nomax';
  24771. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  24772. return $this->max ? 'very_verbose' : 'very_verbose_nomax';
  24773. case OutputInterface::VERBOSITY_DEBUG:
  24774. return $this->max ? 'debug' : 'debug_nomax';
  24775. default:
  24776. return $this->max ? 'normal' : 'normal_nomax';
  24777. }
  24778. }
  24779. private static function initPlaceholderFormatters()
  24780. {
  24781. return array(
  24782. 'bar' => function (ProgressBar $bar, OutputInterface $output) {
  24783. $completeBars = floor($bar->getMaxSteps() > 0 ? $bar->getProgressPercent() * $bar->getBarWidth() : $bar->getProgress() % $bar->getBarWidth());
  24784. $display = str_repeat($bar->getBarCharacter(), $completeBars);
  24785. if ($completeBars < $bar->getBarWidth()) {
  24786. $emptyBars = $bar->getBarWidth() - $completeBars - Helper::strlenWithoutDecoration($output->getFormatter(), $bar->getProgressCharacter());
  24787. $display .= $bar->getProgressCharacter().str_repeat($bar->getEmptyBarCharacter(), $emptyBars);
  24788. }
  24789. return $display;
  24790. },
  24791. 'elapsed' => function (ProgressBar $bar) {
  24792. return Helper::formatTime(time() - $bar->getStartTime());
  24793. },
  24794. 'remaining' => function (ProgressBar $bar) {
  24795. if (!$bar->getMaxSteps()) {
  24796. throw new \LogicException('Unable to display the remaining time if the maximum number of steps is not set.');
  24797. }
  24798. if (!$bar->getProgress()) {
  24799. $remaining = 0;
  24800. } else {
  24801. $remaining = round((time() - $bar->getStartTime()) / $bar->getProgress() * ($bar->getMaxSteps() - $bar->getProgress()));
  24802. }
  24803. return Helper::formatTime($remaining);
  24804. },
  24805. 'estimated' => function (ProgressBar $bar) {
  24806. if (!$bar->getMaxSteps()) {
  24807. throw new \LogicException('Unable to display the estimated time if the maximum number of steps is not set.');
  24808. }
  24809. if (!$bar->getProgress()) {
  24810. $estimated = 0;
  24811. } else {
  24812. $estimated = round((time() - $bar->getStartTime()) / $bar->getProgress() * $bar->getMaxSteps());
  24813. }
  24814. return Helper::formatTime($estimated);
  24815. },
  24816. 'memory' => function (ProgressBar $bar) {
  24817. return Helper::formatMemory(memory_get_usage(true));
  24818. },
  24819. 'current' => function (ProgressBar $bar) {
  24820. return str_pad($bar->getProgress(), $bar->getStepWidth(), ' ', STR_PAD_LEFT);
  24821. },
  24822. 'max' => function (ProgressBar $bar) {
  24823. return $bar->getMaxSteps();
  24824. },
  24825. 'percent' => function (ProgressBar $bar) {
  24826. return floor($bar->getProgressPercent() * 100);
  24827. },
  24828. );
  24829. }
  24830. private static function initFormats()
  24831. {
  24832. return array(
  24833. 'normal' => ' %current%/%max% [%bar%] %percent:3s%%',
  24834. 'normal_nomax' => ' %current% [%bar%]',
  24835. 'verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%',
  24836. 'verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  24837. 'very_verbose' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%',
  24838. 'very_verbose_nomax' => ' %current% [%bar%] %elapsed:6s%',
  24839. 'debug' => ' %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% %memory:6s%',
  24840. 'debug_nomax' => ' %current% [%bar%] %elapsed:6s% %memory:6s%',
  24841. );
  24842. }
  24843. }
  24844. <?php
  24845. namespace Symfony\Component\Console\Helper;
  24846. use Symfony\Component\Console\Output\NullOutput;
  24847. use Symfony\Component\Console\Output\OutputInterface;
  24848. class ProgressHelper extends Helper
  24849. {
  24850. const FORMAT_QUIET = ' %percent%%';
  24851. const FORMAT_NORMAL = ' %current%/%max% [%bar%] %percent%%';
  24852. const FORMAT_VERBOSE = ' %current%/%max% [%bar%] %percent%% Elapsed: %elapsed%';
  24853. const FORMAT_QUIET_NOMAX = ' %current%';
  24854. const FORMAT_NORMAL_NOMAX = ' %current% [%bar%]';
  24855. const FORMAT_VERBOSE_NOMAX = ' %current% [%bar%] Elapsed: %elapsed%';
  24856. private $barWidth = 28;
  24857. private $barChar = '=';
  24858. private $emptyBarChar = '-';
  24859. private $progressChar = '>';
  24860. private $format = null;
  24861. private $redrawFreq = 1;
  24862. private $lastMessagesLength;
  24863. private $barCharOriginal;
  24864. private $output;
  24865. private $current;
  24866. private $max;
  24867. private $startTime;
  24868. private $defaultFormatVars = array(
  24869. 'current',
  24870. 'max',
  24871. 'bar',
  24872. 'percent',
  24873. 'elapsed',
  24874. );
  24875. private $formatVars;
  24876. private $widths = array(
  24877. 'current' => 4,
  24878. 'max' => 4,
  24879. 'percent' => 3,
  24880. 'elapsed' => 6,
  24881. );
  24882. private $timeFormats = array(
  24883. array(0, '???'),
  24884. array(2, '1 sec'),
  24885. array(59, 'secs', 1),
  24886. array(60, '1 min'),
  24887. array(3600, 'mins', 60),
  24888. array(5400, '1 hr'),
  24889. array(86400, 'hrs', 3600),
  24890. array(129600, '1 day'),
  24891. array(604800, 'days', 86400),
  24892. );
  24893. public function setBarWidth($size)
  24894. {
  24895. $this->barWidth = (int) $size;
  24896. }
  24897. public function setBarCharacter($char)
  24898. {
  24899. $this->barChar = $char;
  24900. }
  24901. public function setEmptyBarCharacter($char)
  24902. {
  24903. $this->emptyBarChar = $char;
  24904. }
  24905. public function setProgressCharacter($char)
  24906. {
  24907. $this->progressChar = $char;
  24908. }
  24909. public function setFormat($format)
  24910. {
  24911. $this->format = $format;
  24912. }
  24913. public function setRedrawFrequency($freq)
  24914. {
  24915. $this->redrawFreq = (int) $freq;
  24916. }
  24917. public function start(OutputInterface $output, $max = null)
  24918. {
  24919. $this->startTime = time();
  24920. $this->current = 0;
  24921. $this->max = (int) $max;
  24922. $this->output = $output->isDecorated() ? $output : new NullOutput();
  24923. $this->lastMessagesLength = 0;
  24924. $this->barCharOriginal = '';
  24925. if (null === $this->format) {
  24926. switch ($output->getVerbosity()) {
  24927. case OutputInterface::VERBOSITY_QUIET:
  24928. $this->format = self::FORMAT_QUIET_NOMAX;
  24929. if ($this->max > 0) {
  24930. $this->format = self::FORMAT_QUIET;
  24931. }
  24932. break;
  24933. case OutputInterface::VERBOSITY_VERBOSE:
  24934. case OutputInterface::VERBOSITY_VERY_VERBOSE:
  24935. case OutputInterface::VERBOSITY_DEBUG:
  24936. $this->format = self::FORMAT_VERBOSE_NOMAX;
  24937. if ($this->max > 0) {
  24938. $this->format = self::FORMAT_VERBOSE;
  24939. }
  24940. break;
  24941. default:
  24942. $this->format = self::FORMAT_NORMAL_NOMAX;
  24943. if ($this->max > 0) {
  24944. $this->format = self::FORMAT_NORMAL;
  24945. }
  24946. break;
  24947. }
  24948. }
  24949. $this->initialize();
  24950. }
  24951. public function advance($step = 1, $redraw = false)
  24952. {
  24953. $this->setCurrent($this->current + $step, $redraw);
  24954. }
  24955. public function setCurrent($current, $redraw = false)
  24956. {
  24957. if (null === $this->startTime) {
  24958. throw new \LogicException('You must start the progress bar before calling setCurrent().');
  24959. }
  24960. $current = (int) $current;
  24961. if ($current < $this->current) {
  24962. throw new \LogicException('You can\'t regress the progress bar');
  24963. }
  24964. if (0 === $this->current) {
  24965. $redraw = true;
  24966. }
  24967. $prevPeriod = intval($this->current / $this->redrawFreq);
  24968. $this->current = $current;
  24969. $currPeriod = intval($this->current / $this->redrawFreq);
  24970. if ($redraw || $prevPeriod !== $currPeriod || $this->max === $this->current) {
  24971. $this->display();
  24972. }
  24973. }
  24974. public function display($finish = false)
  24975. {
  24976. if (null === $this->startTime) {
  24977. throw new \LogicException('You must start the progress bar before calling display().');
  24978. }
  24979. $message = $this->format;
  24980. foreach ($this->generate($finish) as $name => $value) {
  24981. $message = str_replace("%{$name}%", $value, $message);
  24982. }
  24983. $this->overwrite($this->output, $message);
  24984. }
  24985. public function clear()
  24986. {
  24987. $this->overwrite($this->output, '');
  24988. }
  24989. public function finish()
  24990. {
  24991. if (null === $this->startTime) {
  24992. throw new \LogicException('You must start the progress bar before calling finish().');
  24993. }
  24994. if (null !== $this->startTime) {
  24995. if (!$this->max) {
  24996. $this->barChar = $this->barCharOriginal;
  24997. $this->display(true);
  24998. }
  24999. $this->startTime = null;
  25000. $this->output->writeln('');
  25001. $this->output = null;
  25002. }
  25003. }
  25004. private function initialize()
  25005. {
  25006. $this->formatVars = array();
  25007. foreach ($this->defaultFormatVars as $var) {
  25008. if (false !== strpos($this->format, "%{$var}%")) {
  25009. $this->formatVars[$var] = true;
  25010. }
  25011. }
  25012. if ($this->max > 0) {
  25013. $this->widths['max'] = $this->strlen($this->max);
  25014. $this->widths['current'] = $this->widths['max'];
  25015. } else {
  25016. $this->barCharOriginal = $this->barChar;
  25017. $this->barChar = $this->emptyBarChar;
  25018. }
  25019. }
  25020. private function generate($finish = false)
  25021. {
  25022. $vars = array();
  25023. $percent = 0;
  25024. if ($this->max > 0) {
  25025. $percent = (float) $this->current / $this->max;
  25026. }
  25027. if (isset($this->formatVars['bar'])) {
  25028. $completeBars = 0;
  25029. if ($this->max > 0) {
  25030. $completeBars = floor($percent * $this->barWidth);
  25031. } else {
  25032. if (!$finish) {
  25033. $completeBars = floor($this->current % $this->barWidth);
  25034. } else {
  25035. $completeBars = $this->barWidth;
  25036. }
  25037. }
  25038. $emptyBars = $this->barWidth - $completeBars - $this->strlen($this->progressChar);
  25039. $bar = str_repeat($this->barChar, $completeBars);
  25040. if ($completeBars < $this->barWidth) {
  25041. $bar .= $this->progressChar;
  25042. $bar .= str_repeat($this->emptyBarChar, $emptyBars);
  25043. }
  25044. $vars['bar'] = $bar;
  25045. }
  25046. if (isset($this->formatVars['elapsed'])) {
  25047. $elapsed = time() - $this->startTime;
  25048. $vars['elapsed'] = str_pad($this->humaneTime($elapsed), $this->widths['elapsed'], ' ', STR_PAD_LEFT);
  25049. }
  25050. if (isset($this->formatVars['current'])) {
  25051. $vars['current'] = str_pad($this->current, $this->widths['current'], ' ', STR_PAD_LEFT);
  25052. }
  25053. if (isset($this->formatVars['max'])) {
  25054. $vars['max'] = $this->max;
  25055. }
  25056. if (isset($this->formatVars['percent'])) {
  25057. $vars['percent'] = str_pad(floor($percent * 100), $this->widths['percent'], ' ', STR_PAD_LEFT);
  25058. }
  25059. return $vars;
  25060. }
  25061. private function humaneTime($secs)
  25062. {
  25063. $text = '';
  25064. foreach ($this->timeFormats as $format) {
  25065. if ($secs < $format[0]) {
  25066. if (count($format) == 2) {
  25067. $text = $format[1];
  25068. break;
  25069. } else {
  25070. $text = ceil($secs / $format[2]).' '.$format[1];
  25071. break;
  25072. }
  25073. }
  25074. }
  25075. return $text;
  25076. }
  25077. private function overwrite(OutputInterface $output, $message)
  25078. {
  25079. $length = $this->strlen($message);
  25080. if (null !== $this->lastMessagesLength && $this->lastMessagesLength > $length) {
  25081. $message = str_pad($message, $this->lastMessagesLength, "\x20", STR_PAD_RIGHT);
  25082. }
  25083. $output->write("\x0D");
  25084. $output->write($message);
  25085. $this->lastMessagesLength = $this->strlen($message);
  25086. }
  25087. public function getName()
  25088. {
  25089. return 'progress';
  25090. }
  25091. }
  25092. <?php
  25093. namespace Symfony\Component\Console\Helper;
  25094. use Symfony\Component\Console\Input\InputInterface;
  25095. use Symfony\Component\Console\Output\OutputInterface;
  25096. use Symfony\Component\Console\Formatter\OutputFormatterStyle;
  25097. use Symfony\Component\Console\Question\Question;
  25098. use Symfony\Component\Console\Question\ChoiceQuestion;
  25099. class QuestionHelper extends Helper
  25100. {
  25101. private $inputStream;
  25102. private static $shell;
  25103. private static $stty;
  25104. public function ask(InputInterface $input, OutputInterface $output, Question $question)
  25105. {
  25106. if (!$input->isInteractive()) {
  25107. return $question->getDefault();
  25108. }
  25109. if (!$question->getValidator()) {
  25110. return $this->doAsk($output, $question);
  25111. }
  25112. $that = $this;
  25113. $interviewer = function () use ($output, $question, $that) {
  25114. return $that->doAsk($output, $question);
  25115. };
  25116. return $this->validateAttempts($interviewer, $output, $question);
  25117. }
  25118. public function setInputStream($stream)
  25119. {
  25120. if (!is_resource($stream)) {
  25121. throw new \InvalidArgumentException('Input stream must be a valid resource.');
  25122. }
  25123. $this->inputStream = $stream;
  25124. }
  25125. public function getInputStream()
  25126. {
  25127. return $this->inputStream;
  25128. }
  25129. public function getName()
  25130. {
  25131. return 'question';
  25132. }
  25133. public function doAsk(OutputInterface $output, Question $question)
  25134. {
  25135. $inputStream = $this->inputStream ?: STDIN;
  25136. $message = $question->getQuestion();
  25137. if ($question instanceof ChoiceQuestion) {
  25138. $width = max(array_map('strlen', array_keys($question->getChoices())));
  25139. $messages = (array) $question->getQuestion();
  25140. foreach ($question->getChoices() as $key => $value) {
  25141. $messages[] = sprintf(" [<info>%-${width}s</info>] %s", $key, $value);
  25142. }
  25143. $output->writeln($messages);
  25144. $message = $question->getPrompt();
  25145. }
  25146. $output->write($message);
  25147. $autocomplete = $question->getAutocompleterValues();
  25148. if (null === $autocomplete || !$this->hasSttyAvailable()) {
  25149. $ret = false;
  25150. if ($question->isHidden()) {
  25151. try {
  25152. $ret = trim($this->getHiddenResponse($output, $inputStream));
  25153. } catch (\RuntimeException $e) {
  25154. if (!$question->isHiddenFallback()) {
  25155. throw $e;
  25156. }
  25157. }
  25158. }
  25159. if (false === $ret) {
  25160. $ret = fgets($inputStream, 4096);
  25161. if (false === $ret) {
  25162. throw new \RuntimeException('Aborted');
  25163. }
  25164. $ret = trim($ret);
  25165. }
  25166. } else {
  25167. $ret = trim($this->autocomplete($output, $question, $inputStream));
  25168. }
  25169. $ret = strlen($ret) > 0 ? $ret : $question->getDefault();
  25170. if ($normalizer = $question->getNormalizer()) {
  25171. return $normalizer($ret);
  25172. }
  25173. return $ret;
  25174. }
  25175. private function autocomplete(OutputInterface $output, Question $question, $inputStream)
  25176. {
  25177. $autocomplete = $question->getAutocompleterValues();
  25178. $ret = '';
  25179. $i = 0;
  25180. $ofs = -1;
  25181. $matches = $autocomplete;
  25182. $numMatches = count($matches);
  25183. $sttyMode = shell_exec('stty -g');
  25184. shell_exec('stty -icanon -echo');
  25185. $output->getFormatter()->setStyle('hl', new OutputFormatterStyle('black', 'white'));
  25186. while (!feof($inputStream)) {
  25187. $c = fread($inputStream, 1);
  25188. if ("\177" === $c) {
  25189. if (0 === $numMatches && 0 !== $i) {
  25190. $i--;
  25191. $output->write("\033[1D");
  25192. }
  25193. if ($i === 0) {
  25194. $ofs = -1;
  25195. $matches = $autocomplete;
  25196. $numMatches = count($matches);
  25197. } else {
  25198. $numMatches = 0;
  25199. }
  25200. $ret = substr($ret, 0, $i);
  25201. } elseif ("\033" === $c) {
  25202. $c .= fread($inputStream, 2);
  25203. if (isset($c[2]) && ('A' === $c[2] || 'B' === $c[2])) {
  25204. if ('A' === $c[2] && -1 === $ofs) {
  25205. $ofs = 0;
  25206. }
  25207. if (0 === $numMatches) {
  25208. continue;
  25209. }
  25210. $ofs += ('A' === $c[2]) ? -1 : 1;
  25211. $ofs = ($numMatches + $ofs) % $numMatches;
  25212. }
  25213. } elseif (ord($c) < 32) {
  25214. if ("\t" === $c || "\n" === $c) {
  25215. if ($numMatches > 0 && -1 !== $ofs) {
  25216. $ret = $matches[$ofs];
  25217. $output->write(substr($ret, $i));
  25218. $i = strlen($ret);
  25219. }
  25220. if ("\n" === $c) {
  25221. $output->write($c);
  25222. break;
  25223. }
  25224. $numMatches = 0;
  25225. }
  25226. continue;
  25227. } else {
  25228. $output->write($c);
  25229. $ret .= $c;
  25230. $i++;
  25231. $numMatches = 0;
  25232. $ofs = 0;
  25233. foreach ($autocomplete as $value) {
  25234. if (0 === strpos($value, $ret) && $i !== strlen($value)) {
  25235. $matches[$numMatches++] = $value;
  25236. }
  25237. }
  25238. }
  25239. $output->write("\033[K");
  25240. if ($numMatches > 0 && -1 !== $ofs) {
  25241. $output->write("\0337");
  25242. $output->write('<hl>'.substr($matches[$ofs], $i).'</hl>');
  25243. $output->write("\0338");
  25244. }
  25245. }
  25246. shell_exec(sprintf('stty %s', $sttyMode));
  25247. return $ret;
  25248. }
  25249. private function getHiddenResponse(OutputInterface $output, $inputStream)
  25250. {
  25251. if ('\\' === DIRECTORY_SEPARATOR) {
  25252. $exe = __DIR__.'/../Resources/bin/hiddeninput.exe';
  25253. if ('phar:' === substr(__FILE__, 0, 5)) {
  25254. $tmpExe = sys_get_temp_dir().'/hiddeninput.exe';
  25255. copy($exe, $tmpExe);
  25256. $exe = $tmpExe;
  25257. }
  25258. $value = rtrim(shell_exec($exe));
  25259. $output->writeln('');
  25260. if (isset($tmpExe)) {
  25261. unlink($tmpExe);
  25262. }
  25263. return $value;
  25264. }
  25265. if ($this->hasSttyAvailable()) {
  25266. $sttyMode = shell_exec('stty -g');
  25267. shell_exec('stty -echo');
  25268. $value = fgets($inputStream, 4096);
  25269. shell_exec(sprintf('stty %s', $sttyMode));
  25270. if (false === $value) {
  25271. throw new \RuntimeException('Aborted');
  25272. }
  25273. $value = trim($value);
  25274. $output->writeln('');
  25275. return $value;
  25276. }
  25277. if (false !== $shell = $this->getShell()) {
  25278. $readCmd = $shell === 'csh' ? 'set mypassword = $<' : 'read -r mypassword';
  25279. $command = sprintf("/usr/bin/env %s -c 'stty -echo; %s; stty echo; echo \$mypassword'", $shell, $readCmd);
  25280. $value = rtrim(shell_exec($command));
  25281. $output->writeln('');
  25282. return $value;
  25283. }
  25284. throw new \RuntimeException('Unable to hide the response.');
  25285. }
  25286. private function validateAttempts($interviewer, OutputInterface $output, Question $question)
  25287. {
  25288. $error = null;
  25289. $attempts = $question->getMaxAttempts();
  25290. while (null === $attempts || $attempts--) {
  25291. if (null !== $error) {
  25292. if (null !== $this->getHelperSet() && $this->getHelperSet()->has('formatter')) {
  25293. $message = $this->getHelperSet()->get('formatter')->formatBlock($error->getMessage(), 'error');
  25294. } else {
  25295. $message = '<error>'.$error->getMessage().'</error>';
  25296. }
  25297. $output->writeln($message);
  25298. }
  25299. try {
  25300. return call_user_func($question->getValidator(), $interviewer());
  25301. } catch (\Exception $error) {
  25302. }
  25303. }
  25304. throw $error;
  25305. }
  25306. private function getShell()
  25307. {
  25308. if (null !== self::$shell) {
  25309. return self::$shell;
  25310. }
  25311. self::$shell = false;
  25312. if (file_exists('/usr/bin/env')) {
  25313. $test = "/usr/bin/env %s -c 'echo OK' 2> /dev/null";
  25314. foreach (array('bash', 'zsh', 'ksh', 'csh') as $sh) {
  25315. if ('OK' === rtrim(shell_exec(sprintf($test, $sh)))) {
  25316. self::$shell = $sh;
  25317. break;
  25318. }
  25319. }
  25320. }
  25321. return self::$shell;
  25322. }
  25323. private function hasSttyAvailable()
  25324. {
  25325. if (null !== self::$stty) {
  25326. return self::$stty;
  25327. }
  25328. exec('stty 2>&1', $output, $exitcode);
  25329. return self::$stty = $exitcode === 0;
  25330. }
  25331. }
  25332. <?php
  25333. namespace Symfony\Component\Console\Helper;
  25334. use Symfony\Component\Console\Output\OutputInterface;
  25335. class Table
  25336. {
  25337. private $headers = array();
  25338. private $rows = array();
  25339. private $columnWidths = array();
  25340. private $numberOfColumns;
  25341. private $output;
  25342. private $style;
  25343. private static $styles;
  25344. public function __construct(OutputInterface $output)
  25345. {
  25346. $this->output = $output;
  25347. if (!self::$styles) {
  25348. self::$styles = self::initStyles();
  25349. }
  25350. $this->setStyle('default');
  25351. }
  25352. public static function setStyleDefinition($name, TableStyle $style)
  25353. {
  25354. if (!self::$styles) {
  25355. self::$styles = self::initStyles();
  25356. }
  25357. self::$styles[$name] = $style;
  25358. }
  25359. public static function getStyleDefinition($name)
  25360. {
  25361. if (!self::$styles) {
  25362. self::$styles = self::initStyles();
  25363. }
  25364. if (!self::$styles[$name]) {
  25365. throw new \InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  25366. }
  25367. return self::$styles[$name];
  25368. }
  25369. public function setStyle($name)
  25370. {
  25371. if ($name instanceof TableStyle) {
  25372. $this->style = $name;
  25373. } elseif (isset(self::$styles[$name])) {
  25374. $this->style = self::$styles[$name];
  25375. } else {
  25376. throw new \InvalidArgumentException(sprintf('Style "%s" is not defined.', $name));
  25377. }
  25378. return $this;
  25379. }
  25380. public function getStyle()
  25381. {
  25382. return $this->style;
  25383. }
  25384. public function setHeaders(array $headers)
  25385. {
  25386. $this->headers = array_values($headers);
  25387. return $this;
  25388. }
  25389. public function setRows(array $rows)
  25390. {
  25391. $this->rows = array();
  25392. return $this->addRows($rows);
  25393. }
  25394. public function addRows(array $rows)
  25395. {
  25396. foreach ($rows as $row) {
  25397. $this->addRow($row);
  25398. }
  25399. return $this;
  25400. }
  25401. public function addRow($row)
  25402. {
  25403. if ($row instanceof TableSeparator) {
  25404. $this->rows[] = $row;
  25405. return;
  25406. }
  25407. if (!is_array($row)) {
  25408. throw new \InvalidArgumentException('A row must be an array or a TableSeparator instance.');
  25409. }
  25410. $this->rows[] = array_values($row);
  25411. end($this->rows);
  25412. $rowKey = key($this->rows);
  25413. reset($this->rows);
  25414. foreach ($row as $key => $cellValue) {
  25415. if (!strstr($cellValue, "\n")) {
  25416. continue;
  25417. }
  25418. $lines = explode("\n", $cellValue);
  25419. $this->rows[$rowKey][$key] = $lines[0];
  25420. unset($lines[0]);
  25421. foreach ($lines as $lineKey => $line) {
  25422. $nextRowKey = $rowKey + $lineKey + 1;
  25423. if (isset($this->rows[$nextRowKey])) {
  25424. $this->rows[$nextRowKey][$key] = $line;
  25425. } else {
  25426. $this->rows[$nextRowKey] = array($key => $line);
  25427. }
  25428. }
  25429. }
  25430. return $this;
  25431. }
  25432. public function setRow($column, array $row)
  25433. {
  25434. $this->rows[$column] = $row;
  25435. return $this;
  25436. }
  25437. public function render()
  25438. {
  25439. $this->renderRowSeparator();
  25440. $this->renderRow($this->headers, $this->style->getCellHeaderFormat());
  25441. if (!empty($this->headers)) {
  25442. $this->renderRowSeparator();
  25443. }
  25444. foreach ($this->rows as $row) {
  25445. if ($row instanceof TableSeparator) {
  25446. $this->renderRowSeparator();
  25447. } else {
  25448. $this->renderRow($row, $this->style->getCellRowFormat());
  25449. }
  25450. }
  25451. if (!empty($this->rows)) {
  25452. $this->renderRowSeparator();
  25453. }
  25454. $this->cleanup();
  25455. }
  25456. private function renderRowSeparator()
  25457. {
  25458. if (0 === $count = $this->getNumberOfColumns()) {
  25459. return;
  25460. }
  25461. if (!$this->style->getHorizontalBorderChar() && !$this->style->getCrossingChar()) {
  25462. return;
  25463. }
  25464. $markup = $this->style->getCrossingChar();
  25465. for ($column = 0; $column < $count; $column++) {
  25466. $markup .= str_repeat($this->style->getHorizontalBorderChar(), $this->getColumnWidth($column)).$this->style->getCrossingChar();
  25467. }
  25468. $this->output->writeln(sprintf($this->style->getBorderFormat(), $markup));
  25469. }
  25470. private function renderColumnSeparator()
  25471. {
  25472. $this->output->write(sprintf($this->style->getBorderFormat(), $this->style->getVerticalBorderChar()));
  25473. }
  25474. private function renderRow(array $row, $cellFormat)
  25475. {
  25476. if (empty($row)) {
  25477. return;
  25478. }
  25479. $this->renderColumnSeparator();
  25480. for ($column = 0, $count = $this->getNumberOfColumns(); $column < $count; $column++) {
  25481. $this->renderCell($row, $column, $cellFormat);
  25482. $this->renderColumnSeparator();
  25483. }
  25484. $this->output->writeln('');
  25485. }
  25486. private function renderCell(array $row, $column, $cellFormat)
  25487. {
  25488. $cell = isset($row[$column]) ? $row[$column] : '';
  25489. $width = $this->getColumnWidth($column);
  25490. if (function_exists('mb_strlen') && false !== $encoding = mb_detect_encoding($cell)) {
  25491. $width += strlen($cell) - mb_strlen($cell, $encoding);
  25492. }
  25493. $width += Helper::strlen($cell) - Helper::strlenWithoutDecoration($this->output->getFormatter(), $cell);
  25494. $content = sprintf($this->style->getCellRowContentFormat(), $cell);
  25495. $this->output->write(sprintf($cellFormat, str_pad($content, $width, $this->style->getPaddingChar(), $this->style->getPadType())));
  25496. }
  25497. private function getNumberOfColumns()
  25498. {
  25499. if (null !== $this->numberOfColumns) {
  25500. return $this->numberOfColumns;
  25501. }
  25502. $columns = array(count($this->headers));
  25503. foreach ($this->rows as $row) {
  25504. $columns[] = count($row);
  25505. }
  25506. return $this->numberOfColumns = max($columns);
  25507. }
  25508. private function getColumnWidth($column)
  25509. {
  25510. if (isset($this->columnWidths[$column])) {
  25511. return $this->columnWidths[$column];
  25512. }
  25513. $lengths = array($this->getCellWidth($this->headers, $column));
  25514. foreach ($this->rows as $row) {
  25515. if ($row instanceof TableSeparator) {
  25516. continue;
  25517. }
  25518. $lengths[] = $this->getCellWidth($row, $column);
  25519. }
  25520. return $this->columnWidths[$column] = max($lengths) + strlen($this->style->getCellRowContentFormat()) - 2;
  25521. }
  25522. private function getCellWidth(array $row, $column)
  25523. {
  25524. return isset($row[$column]) ? Helper::strlenWithoutDecoration($this->output->getFormatter(), $row[$column]) : 0;
  25525. }
  25526. private function cleanup()
  25527. {
  25528. $this->columnWidths = array();
  25529. $this->numberOfColumns = null;
  25530. }
  25531. private static function initStyles()
  25532. {
  25533. $borderless = new TableStyle();
  25534. $borderless
  25535. ->setHorizontalBorderChar('=')
  25536. ->setVerticalBorderChar(' ')
  25537. ->setCrossingChar(' ')
  25538. ;
  25539. $compact = new TableStyle();
  25540. $compact
  25541. ->setHorizontalBorderChar('')
  25542. ->setVerticalBorderChar(' ')
  25543. ->setCrossingChar('')
  25544. ->setCellRowContentFormat('%s')
  25545. ;
  25546. return array(
  25547. 'default' => new TableStyle(),
  25548. 'borderless' => $borderless,
  25549. 'compact' => $compact,
  25550. );
  25551. }
  25552. }
  25553. <?php
  25554. namespace Symfony\Component\Console\Helper;
  25555. use Symfony\Component\Console\Output\OutputInterface;
  25556. use Symfony\Component\Console\Output\NullOutput;
  25557. class TableHelper extends Helper
  25558. {
  25559. const LAYOUT_DEFAULT = 0;
  25560. const LAYOUT_BORDERLESS = 1;
  25561. const LAYOUT_COMPACT = 2;
  25562. private $table;
  25563. public function __construct()
  25564. {
  25565. $this->table = new Table(new NullOutput());
  25566. }
  25567. public function setLayout($layout)
  25568. {
  25569. switch ($layout) {
  25570. case self::LAYOUT_BORDERLESS:
  25571. $this->table->setStyle('borderless');
  25572. break;
  25573. case self::LAYOUT_COMPACT:
  25574. $this->table->setStyle('compact');
  25575. break;
  25576. case self::LAYOUT_DEFAULT:
  25577. $this->table->setStyle('default');
  25578. break;
  25579. default:
  25580. throw new \InvalidArgumentException(sprintf('Invalid table layout "%s".', $layout));
  25581. };
  25582. return $this;
  25583. }
  25584. public function setHeaders(array $headers)
  25585. {
  25586. $this->table->setHeaders($headers);
  25587. return $this;
  25588. }
  25589. public function setRows(array $rows)
  25590. {
  25591. $this->table->setRows($rows);
  25592. return $this;
  25593. }
  25594. public function addRows(array $rows)
  25595. {
  25596. $this->table->addRows($rows);
  25597. return $this;
  25598. }
  25599. public function addRow(array $row)
  25600. {
  25601. $this->table->addRow($row);
  25602. return $this;
  25603. }
  25604. public function setRow($column, array $row)
  25605. {
  25606. $this->table->setRow($column, $row);
  25607. return $this;
  25608. }
  25609. public function setPaddingChar($paddingChar)
  25610. {
  25611. $this->table->getStyle()->setPaddingChar($paddingChar);
  25612. return $this;
  25613. }
  25614. public function setHorizontalBorderChar($horizontalBorderChar)
  25615. {
  25616. $this->table->getStyle()->setHorizontalBorderChar($horizontalBorderChar);
  25617. return $this;
  25618. }
  25619. public function setVerticalBorderChar($verticalBorderChar)
  25620. {
  25621. $this->table->getStyle()->setVerticalBorderChar($verticalBorderChar);
  25622. return $this;
  25623. }
  25624. public function setCrossingChar($crossingChar)
  25625. {
  25626. $this->table->getStyle()->setCrossingChar($crossingChar);
  25627. return $this;
  25628. }
  25629. public function setCellHeaderFormat($cellHeaderFormat)
  25630. {
  25631. $this->table->getStyle()->setCellHeaderFormat($cellHeaderFormat);
  25632. return $this;
  25633. }
  25634. public function setCellRowFormat($cellRowFormat)
  25635. {
  25636. $this->table->getStyle()->setCellHeaderFormat($cellRowFormat);
  25637. return $this;
  25638. }
  25639. public function setCellRowContentFormat($cellRowContentFormat)
  25640. {
  25641. $this->table->getStyle()->setCellRowContentFormat($cellRowContentFormat);
  25642. return $this;
  25643. }
  25644. public function setBorderFormat($borderFormat)
  25645. {
  25646. $this->table->getStyle()->setBorderFormat($borderFormat);
  25647. return $this;
  25648. }
  25649. public function setPadType($padType)
  25650. {
  25651. $this->table->getStyle()->setPadType($padType);
  25652. return $this;
  25653. }
  25654. public function render(OutputInterface $output)
  25655. {
  25656. $p = new \ReflectionProperty($this->table, 'output');
  25657. $p->setAccessible(true);
  25658. $p->setValue($this->table, $output);
  25659. $this->table->render();
  25660. }
  25661. public function getName()
  25662. {
  25663. return 'table';
  25664. }
  25665. }
  25666. <?php
  25667. namespace Symfony\Component\Console\Helper;
  25668. class TableSeparator
  25669. {
  25670. }
  25671. <?php
  25672. namespace Symfony\Component\Console\Helper;
  25673. class TableStyle
  25674. {
  25675. private $paddingChar = ' ';
  25676. private $horizontalBorderChar = '-';
  25677. private $verticalBorderChar = '|';
  25678. private $crossingChar = '+';
  25679. private $cellHeaderFormat = '<info>%s</info>';
  25680. private $cellRowFormat = '%s';
  25681. private $cellRowContentFormat = ' %s ';
  25682. private $borderFormat = '%s';
  25683. private $padType = STR_PAD_RIGHT;
  25684. public function setPaddingChar($paddingChar)
  25685. {
  25686. if (!$paddingChar) {
  25687. throw new \LogicException('The padding char must not be empty');
  25688. }
  25689. $this->paddingChar = $paddingChar;
  25690. return $this;
  25691. }
  25692. public function getPaddingChar()
  25693. {
  25694. return $this->paddingChar;
  25695. }
  25696. public function setHorizontalBorderChar($horizontalBorderChar)
  25697. {
  25698. $this->horizontalBorderChar = $horizontalBorderChar;
  25699. return $this;
  25700. }
  25701. public function getHorizontalBorderChar()
  25702. {
  25703. return $this->horizontalBorderChar;
  25704. }
  25705. public function setVerticalBorderChar($verticalBorderChar)
  25706. {
  25707. $this->verticalBorderChar = $verticalBorderChar;
  25708. return $this;
  25709. }
  25710. public function getVerticalBorderChar()
  25711. {
  25712. return $this->verticalBorderChar;
  25713. }
  25714. public function setCrossingChar($crossingChar)
  25715. {
  25716. $this->crossingChar = $crossingChar;
  25717. return $this;
  25718. }
  25719. public function getCrossingChar()
  25720. {
  25721. return $this->crossingChar;
  25722. }
  25723. public function setCellHeaderFormat($cellHeaderFormat)
  25724. {
  25725. $this->cellHeaderFormat = $cellHeaderFormat;
  25726. return $this;
  25727. }
  25728. public function getCellHeaderFormat()
  25729. {
  25730. return $this->cellHeaderFormat;
  25731. }
  25732. public function setCellRowFormat($cellRowFormat)
  25733. {
  25734. $this->cellRowFormat = $cellRowFormat;
  25735. return $this;
  25736. }
  25737. public function getCellRowFormat()
  25738. {
  25739. return $this->cellRowFormat;
  25740. }
  25741. public function setCellRowContentFormat($cellRowContentFormat)
  25742. {
  25743. $this->cellRowContentFormat = $cellRowContentFormat;
  25744. return $this;
  25745. }
  25746. public function getCellRowContentFormat()
  25747. {
  25748. return $this->cellRowContentFormat;
  25749. }
  25750. public function setBorderFormat($borderFormat)
  25751. {
  25752. $this->borderFormat = $borderFormat;
  25753. return $this;
  25754. }
  25755. public function getBorderFormat()
  25756. {
  25757. return $this->borderFormat;
  25758. }
  25759. public function setPadType($padType)
  25760. {
  25761. $this->padType = $padType;
  25762. return $this;
  25763. }
  25764. public function getPadType()
  25765. {
  25766. return $this->padType;
  25767. }
  25768. }
  25769. <?php
  25770. namespace Symfony\Component\Console\Input;
  25771. class ArgvInput extends Input
  25772. {
  25773. private $tokens;
  25774. private $parsed;
  25775. public function __construct(array $argv = null, InputDefinition $definition = null)
  25776. {
  25777. if (null === $argv) {
  25778. $argv = $_SERVER['argv'];
  25779. }
  25780. array_shift($argv);
  25781. $this->tokens = $argv;
  25782. parent::__construct($definition);
  25783. }
  25784. protected function setTokens(array $tokens)
  25785. {
  25786. $this->tokens = $tokens;
  25787. }
  25788. protected function parse()
  25789. {
  25790. $parseOptions = true;
  25791. $this->parsed = $this->tokens;
  25792. while (null !== $token = array_shift($this->parsed)) {
  25793. if ($parseOptions && '' == $token) {
  25794. $this->parseArgument($token);
  25795. } elseif ($parseOptions && '--' == $token) {
  25796. $parseOptions = false;
  25797. } elseif ($parseOptions && 0 === strpos($token, '--')) {
  25798. $this->parseLongOption($token);
  25799. } elseif ($parseOptions && '-' === $token[0] && '-' !== $token) {
  25800. $this->parseShortOption($token);
  25801. } else {
  25802. $this->parseArgument($token);
  25803. }
  25804. }
  25805. }
  25806. private function parseShortOption($token)
  25807. {
  25808. $name = substr($token, 1);
  25809. if (strlen($name) > 1) {
  25810. if ($this->definition->hasShortcut($name[0]) && $this->definition->getOptionForShortcut($name[0])->acceptValue()) {
  25811. $this->addShortOption($name[0], substr($name, 1));
  25812. } else {
  25813. $this->parseShortOptionSet($name);
  25814. }
  25815. } else {
  25816. $this->addShortOption($name, null);
  25817. }
  25818. }
  25819. private function parseShortOptionSet($name)
  25820. {
  25821. $len = strlen($name);
  25822. for ($i = 0; $i < $len; $i++) {
  25823. if (!$this->definition->hasShortcut($name[$i])) {
  25824. throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $name[$i]));
  25825. }
  25826. $option = $this->definition->getOptionForShortcut($name[$i]);
  25827. if ($option->acceptValue()) {
  25828. $this->addLongOption($option->getName(), $i === $len - 1 ? null : substr($name, $i + 1));
  25829. break;
  25830. } else {
  25831. $this->addLongOption($option->getName(), null);
  25832. }
  25833. }
  25834. }
  25835. private function parseLongOption($token)
  25836. {
  25837. $name = substr($token, 2);
  25838. if (false !== $pos = strpos($name, '=')) {
  25839. $this->addLongOption(substr($name, 0, $pos), substr($name, $pos + 1));
  25840. } else {
  25841. $this->addLongOption($name, null);
  25842. }
  25843. }
  25844. private function parseArgument($token)
  25845. {
  25846. $c = count($this->arguments);
  25847. if ($this->definition->hasArgument($c)) {
  25848. $arg = $this->definition->getArgument($c);
  25849. $this->arguments[$arg->getName()] = $arg->isArray() ? array($token) : $token;
  25850. } elseif ($this->definition->hasArgument($c - 1) && $this->definition->getArgument($c - 1)->isArray()) {
  25851. $arg = $this->definition->getArgument($c - 1);
  25852. $this->arguments[$arg->getName()][] = $token;
  25853. } else {
  25854. throw new \RuntimeException('Too many arguments.');
  25855. }
  25856. }
  25857. private function addShortOption($shortcut, $value)
  25858. {
  25859. if (!$this->definition->hasShortcut($shortcut)) {
  25860. throw new \RuntimeException(sprintf('The "-%s" option does not exist.', $shortcut));
  25861. }
  25862. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  25863. }
  25864. private function addLongOption($name, $value)
  25865. {
  25866. if (!$this->definition->hasOption($name)) {
  25867. throw new \RuntimeException(sprintf('The "--%s" option does not exist.', $name));
  25868. }
  25869. $option = $this->definition->getOption($name);
  25870. if (false === $value) {
  25871. $value = null;
  25872. }
  25873. if (null !== $value && !$option->acceptValue()) {
  25874. throw new \RuntimeException(sprintf('The "--%s" option does not accept a value.', $name, $value));
  25875. }
  25876. if (null === $value && $option->acceptValue() && count($this->parsed)) {
  25877. $next = array_shift($this->parsed);
  25878. if (isset($next[0]) && '-' !== $next[0]) {
  25879. $value = $next;
  25880. } elseif (empty($next)) {
  25881. $value = '';
  25882. } else {
  25883. array_unshift($this->parsed, $next);
  25884. }
  25885. }
  25886. if (null === $value) {
  25887. if ($option->isValueRequired()) {
  25888. throw new \RuntimeException(sprintf('The "--%s" option requires a value.', $name));
  25889. }
  25890. if (!$option->isArray()) {
  25891. $value = $option->isValueOptional() ? $option->getDefault() : true;
  25892. }
  25893. }
  25894. if ($option->isArray()) {
  25895. $this->options[$name][] = $value;
  25896. } else {
  25897. $this->options[$name] = $value;
  25898. }
  25899. }
  25900. public function getFirstArgument()
  25901. {
  25902. foreach ($this->tokens as $token) {
  25903. if ($token && '-' === $token[0]) {
  25904. continue;
  25905. }
  25906. return $token;
  25907. }
  25908. }
  25909. public function hasParameterOption($values)
  25910. {
  25911. $values = (array) $values;
  25912. foreach ($this->tokens as $token) {
  25913. foreach ($values as $value) {
  25914. if ($token === $value || 0 === strpos($token, $value.'=')) {
  25915. return true;
  25916. }
  25917. }
  25918. }
  25919. return false;
  25920. }
  25921. public function getParameterOption($values, $default = false)
  25922. {
  25923. $values = (array) $values;
  25924. $tokens = $this->tokens;
  25925. while (0 < count($tokens)) {
  25926. $token = array_shift($tokens);
  25927. foreach ($values as $value) {
  25928. if ($token === $value || 0 === strpos($token, $value.'=')) {
  25929. if (false !== $pos = strpos($token, '=')) {
  25930. return substr($token, $pos + 1);
  25931. }
  25932. return array_shift($tokens);
  25933. }
  25934. }
  25935. }
  25936. return $default;
  25937. }
  25938. public function __toString()
  25939. {
  25940. $self = $this;
  25941. $tokens = array_map(function ($token) use ($self) {
  25942. if (preg_match('{^(-[^=]+=)(.+)}', $token, $match)) {
  25943. return $match[1].$self->escapeToken($match[2]);
  25944. }
  25945. if ($token && $token[0] !== '-') {
  25946. return $self->escapeToken($token);
  25947. }
  25948. return $token;
  25949. }, $this->tokens);
  25950. return implode(' ', $tokens);
  25951. }
  25952. }
  25953. <?php
  25954. namespace Symfony\Component\Console\Input;
  25955. class ArrayInput extends Input
  25956. {
  25957. private $parameters;
  25958. public function __construct(array $parameters, InputDefinition $definition = null)
  25959. {
  25960. $this->parameters = $parameters;
  25961. parent::__construct($definition);
  25962. }
  25963. public function getFirstArgument()
  25964. {
  25965. foreach ($this->parameters as $key => $value) {
  25966. if ($key && '-' === $key[0]) {
  25967. continue;
  25968. }
  25969. return $value;
  25970. }
  25971. }
  25972. public function hasParameterOption($values)
  25973. {
  25974. $values = (array) $values;
  25975. foreach ($this->parameters as $k => $v) {
  25976. if (!is_int($k)) {
  25977. $v = $k;
  25978. }
  25979. if (in_array($v, $values)) {
  25980. return true;
  25981. }
  25982. }
  25983. return false;
  25984. }
  25985. public function getParameterOption($values, $default = false)
  25986. {
  25987. $values = (array) $values;
  25988. foreach ($this->parameters as $k => $v) {
  25989. if (is_int($k) && in_array($v, $values)) {
  25990. return true;
  25991. } elseif (in_array($k, $values)) {
  25992. return $v;
  25993. }
  25994. }
  25995. return $default;
  25996. }
  25997. public function __toString()
  25998. {
  25999. $params = array();
  26000. foreach ($this->parameters as $param => $val) {
  26001. if ($param && '-' === $param[0]) {
  26002. $params[] = $param.('' != $val ? '='.$this->escapeToken($val) : '');
  26003. } else {
  26004. $params[] = $this->escapeToken($val);
  26005. }
  26006. }
  26007. return implode(' ', $params);
  26008. }
  26009. protected function parse()
  26010. {
  26011. foreach ($this->parameters as $key => $value) {
  26012. if (0 === strpos($key, '--')) {
  26013. $this->addLongOption(substr($key, 2), $value);
  26014. } elseif ('-' === $key[0]) {
  26015. $this->addShortOption(substr($key, 1), $value);
  26016. } else {
  26017. $this->addArgument($key, $value);
  26018. }
  26019. }
  26020. }
  26021. private function addShortOption($shortcut, $value)
  26022. {
  26023. if (!$this->definition->hasShortcut($shortcut)) {
  26024. throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
  26025. }
  26026. $this->addLongOption($this->definition->getOptionForShortcut($shortcut)->getName(), $value);
  26027. }
  26028. private function addLongOption($name, $value)
  26029. {
  26030. if (!$this->definition->hasOption($name)) {
  26031. throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
  26032. }
  26033. $option = $this->definition->getOption($name);
  26034. if (null === $value) {
  26035. if ($option->isValueRequired()) {
  26036. throw new \InvalidArgumentException(sprintf('The "--%s" option requires a value.', $name));
  26037. }
  26038. $value = $option->isValueOptional() ? $option->getDefault() : true;
  26039. }
  26040. $this->options[$name] = $value;
  26041. }
  26042. private function addArgument($name, $value)
  26043. {
  26044. if (!$this->definition->hasArgument($name)) {
  26045. throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
  26046. }
  26047. $this->arguments[$name] = $value;
  26048. }
  26049. }
  26050. <?php
  26051. namespace Symfony\Component\Console\Input;
  26052. abstract class Input implements InputInterface
  26053. {
  26054. protected $definition;
  26055. protected $options = array();
  26056. protected $arguments = array();
  26057. protected $interactive = true;
  26058. public function __construct(InputDefinition $definition = null)
  26059. {
  26060. if (null === $definition) {
  26061. $this->definition = new InputDefinition();
  26062. } else {
  26063. $this->bind($definition);
  26064. $this->validate();
  26065. }
  26066. }
  26067. public function bind(InputDefinition $definition)
  26068. {
  26069. $this->arguments = array();
  26070. $this->options = array();
  26071. $this->definition = $definition;
  26072. $this->parse();
  26073. }
  26074. abstract protected function parse();
  26075. public function validate()
  26076. {
  26077. if (count($this->arguments) < $this->definition->getArgumentRequiredCount()) {
  26078. throw new \RuntimeException('Not enough arguments.');
  26079. }
  26080. }
  26081. public function isInteractive()
  26082. {
  26083. return $this->interactive;
  26084. }
  26085. public function setInteractive($interactive)
  26086. {
  26087. $this->interactive = (bool) $interactive;
  26088. }
  26089. public function getArguments()
  26090. {
  26091. return array_merge($this->definition->getArgumentDefaults(), $this->arguments);
  26092. }
  26093. public function getArgument($name)
  26094. {
  26095. if (!$this->definition->hasArgument($name)) {
  26096. throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
  26097. }
  26098. return isset($this->arguments[$name]) ? $this->arguments[$name] : $this->definition->getArgument($name)->getDefault();
  26099. }
  26100. public function setArgument($name, $value)
  26101. {
  26102. if (!$this->definition->hasArgument($name)) {
  26103. throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
  26104. }
  26105. $this->arguments[$name] = $value;
  26106. }
  26107. public function hasArgument($name)
  26108. {
  26109. return $this->definition->hasArgument($name);
  26110. }
  26111. public function getOptions()
  26112. {
  26113. return array_merge($this->definition->getOptionDefaults(), $this->options);
  26114. }
  26115. public function getOption($name)
  26116. {
  26117. if (!$this->definition->hasOption($name)) {
  26118. throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
  26119. }
  26120. return isset($this->options[$name]) ? $this->options[$name] : $this->definition->getOption($name)->getDefault();
  26121. }
  26122. public function setOption($name, $value)
  26123. {
  26124. if (!$this->definition->hasOption($name)) {
  26125. throw new \InvalidArgumentException(sprintf('The "%s" option does not exist.', $name));
  26126. }
  26127. $this->options[$name] = $value;
  26128. }
  26129. public function hasOption($name)
  26130. {
  26131. return $this->definition->hasOption($name);
  26132. }
  26133. public function escapeToken($token)
  26134. {
  26135. return preg_match('{^[\w-]+$}', $token) ? $token : escapeshellarg($token);
  26136. }
  26137. }
  26138. <?php
  26139. namespace Symfony\Component\Console\Input;
  26140. class InputArgument
  26141. {
  26142. const REQUIRED = 1;
  26143. const OPTIONAL = 2;
  26144. const IS_ARRAY = 4;
  26145. private $name;
  26146. private $mode;
  26147. private $default;
  26148. private $description;
  26149. public function __construct($name, $mode = null, $description = '', $default = null)
  26150. {
  26151. if (null === $mode) {
  26152. $mode = self::OPTIONAL;
  26153. } elseif (!is_int($mode) || $mode > 7 || $mode < 1) {
  26154. throw new \InvalidArgumentException(sprintf('Argument mode "%s" is not valid.', $mode));
  26155. }
  26156. $this->name = $name;
  26157. $this->mode = $mode;
  26158. $this->description = $description;
  26159. $this->setDefault($default);
  26160. }
  26161. public function getName()
  26162. {
  26163. return $this->name;
  26164. }
  26165. public function isRequired()
  26166. {
  26167. return self::REQUIRED === (self::REQUIRED & $this->mode);
  26168. }
  26169. public function isArray()
  26170. {
  26171. return self::IS_ARRAY === (self::IS_ARRAY & $this->mode);
  26172. }
  26173. public function setDefault($default = null)
  26174. {
  26175. if (self::REQUIRED === $this->mode && null !== $default) {
  26176. throw new \LogicException('Cannot set a default value except for InputArgument::OPTIONAL mode.');
  26177. }
  26178. if ($this->isArray()) {
  26179. if (null === $default) {
  26180. $default = array();
  26181. } elseif (!is_array($default)) {
  26182. throw new \LogicException('A default value for an array argument must be an array.');
  26183. }
  26184. }
  26185. $this->default = $default;
  26186. }
  26187. public function getDefault()
  26188. {
  26189. return $this->default;
  26190. }
  26191. public function getDescription()
  26192. {
  26193. return $this->description;
  26194. }
  26195. }
  26196. <?php
  26197. namespace Symfony\Component\Console\Input;
  26198. interface InputAwareInterface
  26199. {
  26200. public function setInput(InputInterface $input);
  26201. }
  26202. <?php
  26203. namespace Symfony\Component\Console\Input;
  26204. use Symfony\Component\Console\Descriptor\TextDescriptor;
  26205. use Symfony\Component\Console\Descriptor\XmlDescriptor;
  26206. use Symfony\Component\Console\Output\BufferedOutput;
  26207. class InputDefinition
  26208. {
  26209. private $arguments;
  26210. private $requiredCount;
  26211. private $hasAnArrayArgument = false;
  26212. private $hasOptional;
  26213. private $options;
  26214. private $shortcuts;
  26215. public function __construct(array $definition = array())
  26216. {
  26217. $this->setDefinition($definition);
  26218. }
  26219. public function setDefinition(array $definition)
  26220. {
  26221. $arguments = array();
  26222. $options = array();
  26223. foreach ($definition as $item) {
  26224. if ($item instanceof InputOption) {
  26225. $options[] = $item;
  26226. } else {
  26227. $arguments[] = $item;
  26228. }
  26229. }
  26230. $this->setArguments($arguments);
  26231. $this->setOptions($options);
  26232. }
  26233. public function setArguments($arguments = array())
  26234. {
  26235. $this->arguments = array();
  26236. $this->requiredCount = 0;
  26237. $this->hasOptional = false;
  26238. $this->hasAnArrayArgument = false;
  26239. $this->addArguments($arguments);
  26240. }
  26241. public function addArguments($arguments = array())
  26242. {
  26243. if (null !== $arguments) {
  26244. foreach ($arguments as $argument) {
  26245. $this->addArgument($argument);
  26246. }
  26247. }
  26248. }
  26249. public function addArgument(InputArgument $argument)
  26250. {
  26251. if (isset($this->arguments[$argument->getName()])) {
  26252. throw new \LogicException(sprintf('An argument with name "%s" already exists.', $argument->getName()));
  26253. }
  26254. if ($this->hasAnArrayArgument) {
  26255. throw new \LogicException('Cannot add an argument after an array argument.');
  26256. }
  26257. if ($argument->isRequired() && $this->hasOptional) {
  26258. throw new \LogicException('Cannot add a required argument after an optional one.');
  26259. }
  26260. if ($argument->isArray()) {
  26261. $this->hasAnArrayArgument = true;
  26262. }
  26263. if ($argument->isRequired()) {
  26264. ++$this->requiredCount;
  26265. } else {
  26266. $this->hasOptional = true;
  26267. }
  26268. $this->arguments[$argument->getName()] = $argument;
  26269. }
  26270. public function getArgument($name)
  26271. {
  26272. if (!$this->hasArgument($name)) {
  26273. throw new \InvalidArgumentException(sprintf('The "%s" argument does not exist.', $name));
  26274. }
  26275. $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
  26276. return $arguments[$name];
  26277. }
  26278. public function hasArgument($name)
  26279. {
  26280. $arguments = is_int($name) ? array_values($this->arguments) : $this->arguments;
  26281. return isset($arguments[$name]);
  26282. }
  26283. public function getArguments()
  26284. {
  26285. return $this->arguments;
  26286. }
  26287. public function getArgumentCount()
  26288. {
  26289. return $this->hasAnArrayArgument ? PHP_INT_MAX : count($this->arguments);
  26290. }
  26291. public function getArgumentRequiredCount()
  26292. {
  26293. return $this->requiredCount;
  26294. }
  26295. public function getArgumentDefaults()
  26296. {
  26297. $values = array();
  26298. foreach ($this->arguments as $argument) {
  26299. $values[$argument->getName()] = $argument->getDefault();
  26300. }
  26301. return $values;
  26302. }
  26303. public function setOptions($options = array())
  26304. {
  26305. $this->options = array();
  26306. $this->shortcuts = array();
  26307. $this->addOptions($options);
  26308. }
  26309. public function addOptions($options = array())
  26310. {
  26311. foreach ($options as $option) {
  26312. $this->addOption($option);
  26313. }
  26314. }
  26315. public function addOption(InputOption $option)
  26316. {
  26317. if (isset($this->options[$option->getName()]) && !$option->equals($this->options[$option->getName()])) {
  26318. throw new \LogicException(sprintf('An option named "%s" already exists.', $option->getName()));
  26319. }
  26320. if ($option->getShortcut()) {
  26321. foreach (explode('|', $option->getShortcut()) as $shortcut) {
  26322. if (isset($this->shortcuts[$shortcut]) && !$option->equals($this->options[$this->shortcuts[$shortcut]])) {
  26323. throw new \LogicException(sprintf('An option with shortcut "%s" already exists.', $shortcut));
  26324. }
  26325. }
  26326. }
  26327. $this->options[$option->getName()] = $option;
  26328. if ($option->getShortcut()) {
  26329. foreach (explode('|', $option->getShortcut()) as $shortcut) {
  26330. $this->shortcuts[$shortcut] = $option->getName();
  26331. }
  26332. }
  26333. }
  26334. public function getOption($name)
  26335. {
  26336. if (!$this->hasOption($name)) {
  26337. throw new \InvalidArgumentException(sprintf('The "--%s" option does not exist.', $name));
  26338. }
  26339. return $this->options[$name];
  26340. }
  26341. public function hasOption($name)
  26342. {
  26343. return isset($this->options[$name]);
  26344. }
  26345. public function getOptions()
  26346. {
  26347. return $this->options;
  26348. }
  26349. public function hasShortcut($name)
  26350. {
  26351. return isset($this->shortcuts[$name]);
  26352. }
  26353. public function getOptionForShortcut($shortcut)
  26354. {
  26355. return $this->getOption($this->shortcutToName($shortcut));
  26356. }
  26357. public function getOptionDefaults()
  26358. {
  26359. $values = array();
  26360. foreach ($this->options as $option) {
  26361. $values[$option->getName()] = $option->getDefault();
  26362. }
  26363. return $values;
  26364. }
  26365. private function shortcutToName($shortcut)
  26366. {
  26367. if (!isset($this->shortcuts[$shortcut])) {
  26368. throw new \InvalidArgumentException(sprintf('The "-%s" option does not exist.', $shortcut));
  26369. }
  26370. return $this->shortcuts[$shortcut];
  26371. }
  26372. public function getSynopsis()
  26373. {
  26374. $elements = array();
  26375. foreach ($this->getOptions() as $option) {
  26376. $shortcut = $option->getShortcut() ? sprintf('-%s|', $option->getShortcut()) : '';
  26377. $elements[] = sprintf('['.($option->isValueRequired() ? '%s--%s="..."' : ($option->isValueOptional() ? '%s--%s[="..."]' : '%s--%s')).']', $shortcut, $option->getName());
  26378. }
  26379. foreach ($this->getArguments() as $argument) {
  26380. $elements[] = sprintf($argument->isRequired() ? '%s' : '[%s]', $argument->getName().($argument->isArray() ? '1' : ''));
  26381. if ($argument->isArray()) {
  26382. $elements[] = sprintf('... [%sN]', $argument->getName());
  26383. }
  26384. }
  26385. return implode(' ', $elements);
  26386. }
  26387. public function asText()
  26388. {
  26389. $descriptor = new TextDescriptor();
  26390. $output = new BufferedOutput(BufferedOutput::VERBOSITY_NORMAL, true);
  26391. $descriptor->describe($output, $this, array('raw_output' => true));
  26392. return $output->fetch();
  26393. }
  26394. public function asXml($asDom = false)
  26395. {
  26396. $descriptor = new XmlDescriptor();
  26397. if ($asDom) {
  26398. return $descriptor->getInputDefinitionDocument($this);
  26399. }
  26400. $output = new BufferedOutput();
  26401. $descriptor->describe($output, $this);
  26402. return $output->fetch();
  26403. }
  26404. }
  26405. <?php
  26406. namespace Symfony\Component\Console\Input;
  26407. interface InputInterface
  26408. {
  26409. public function getFirstArgument();
  26410. public function hasParameterOption($values);
  26411. public function getParameterOption($values, $default = false);
  26412. public function bind(InputDefinition $definition);
  26413. public function validate();
  26414. public function getArguments();
  26415. public function getArgument($name);
  26416. public function setArgument($name, $value);
  26417. public function hasArgument($name);
  26418. public function getOptions();
  26419. public function getOption($name);
  26420. public function setOption($name, $value);
  26421. public function hasOption($name);
  26422. public function isInteractive();
  26423. public function setInteractive($interactive);
  26424. }
  26425. <?php
  26426. namespace Symfony\Component\Console\Input;
  26427. class InputOption
  26428. {
  26429. const VALUE_NONE = 1;
  26430. const VALUE_REQUIRED = 2;
  26431. const VALUE_OPTIONAL = 4;
  26432. const VALUE_IS_ARRAY = 8;
  26433. private $name;
  26434. private $shortcut;
  26435. private $mode;
  26436. private $default;
  26437. private $description;
  26438. public function __construct($name, $shortcut = null, $mode = null, $description = '', $default = null)
  26439. {
  26440. if (0 === strpos($name, '--')) {
  26441. $name = substr($name, 2);
  26442. }
  26443. if (empty($name)) {
  26444. throw new \InvalidArgumentException('An option name cannot be empty.');
  26445. }
  26446. if (empty($shortcut)) {
  26447. $shortcut = null;
  26448. }
  26449. if (null !== $shortcut) {
  26450. if (is_array($shortcut)) {
  26451. $shortcut = implode('|', $shortcut);
  26452. }
  26453. $shortcuts = preg_split('{(\|)-?}', ltrim($shortcut, '-'));
  26454. $shortcuts = array_filter($shortcuts);
  26455. $shortcut = implode('|', $shortcuts);
  26456. if (empty($shortcut)) {
  26457. throw new \InvalidArgumentException('An option shortcut cannot be empty.');
  26458. }
  26459. }
  26460. if (null === $mode) {
  26461. $mode = self::VALUE_NONE;
  26462. } elseif (!is_int($mode) || $mode > 15 || $mode < 1) {
  26463. throw new \InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode));
  26464. }
  26465. $this->name = $name;
  26466. $this->shortcut = $shortcut;
  26467. $this->mode = $mode;
  26468. $this->description = $description;
  26469. if ($this->isArray() && !$this->acceptValue()) {
  26470. throw new \InvalidArgumentException('Impossible to have an option mode VALUE_IS_ARRAY if the option does not accept a value.');
  26471. }
  26472. $this->setDefault($default);
  26473. }
  26474. public function getShortcut()
  26475. {
  26476. return $this->shortcut;
  26477. }
  26478. public function getName()
  26479. {
  26480. return $this->name;
  26481. }
  26482. public function acceptValue()
  26483. {
  26484. return $this->isValueRequired() || $this->isValueOptional();
  26485. }
  26486. public function isValueRequired()
  26487. {
  26488. return self::VALUE_REQUIRED === (self::VALUE_REQUIRED & $this->mode);
  26489. }
  26490. public function isValueOptional()
  26491. {
  26492. return self::VALUE_OPTIONAL === (self::VALUE_OPTIONAL & $this->mode);
  26493. }
  26494. public function isArray()
  26495. {
  26496. return self::VALUE_IS_ARRAY === (self::VALUE_IS_ARRAY & $this->mode);
  26497. }
  26498. public function setDefault($default = null)
  26499. {
  26500. if (self::VALUE_NONE === (self::VALUE_NONE & $this->mode) && null !== $default) {
  26501. throw new \LogicException('Cannot set a default value when using InputOption::VALUE_NONE mode.');
  26502. }
  26503. if ($this->isArray()) {
  26504. if (null === $default) {
  26505. $default = array();
  26506. } elseif (!is_array($default)) {
  26507. throw new \LogicException('A default value for an array option must be an array.');
  26508. }
  26509. }
  26510. $this->default = $this->acceptValue() ? $default : false;
  26511. }
  26512. public function getDefault()
  26513. {
  26514. return $this->default;
  26515. }
  26516. public function getDescription()
  26517. {
  26518. return $this->description;
  26519. }
  26520. public function equals(InputOption $option)
  26521. {
  26522. return $option->getName() === $this->getName()
  26523. && $option->getShortcut() === $this->getShortcut()
  26524. && $option->getDefault() === $this->getDefault()
  26525. && $option->isArray() === $this->isArray()
  26526. && $option->isValueRequired() === $this->isValueRequired()
  26527. && $option->isValueOptional() === $this->isValueOptional()
  26528. ;
  26529. }
  26530. }
  26531. <?php
  26532. namespace Symfony\Component\Console\Input;
  26533. class StringInput extends ArgvInput
  26534. {
  26535. const REGEX_STRING = '([^\s]+?)(?:\s|(?<!\\\\)"|(?<!\\\\)\'|$)';
  26536. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\'\\\\]*(?:\\\\.[^\'\\\\]*)*)\')';
  26537. public function __construct($input, InputDefinition $definition = null)
  26538. {
  26539. parent::__construct(array(), null);
  26540. $this->setTokens($this->tokenize($input));
  26541. if (null !== $definition) {
  26542. $this->bind($definition);
  26543. }
  26544. }
  26545. private function tokenize($input)
  26546. {
  26547. $tokens = array();
  26548. $length = strlen($input);
  26549. $cursor = 0;
  26550. while ($cursor < $length) {
  26551. if (preg_match('/\s+/A', $input, $match, null, $cursor)) {
  26552. } elseif (preg_match('/([^="\'\s]+?)(=?)('.self::REGEX_QUOTED_STRING.'+)/A', $input, $match, null, $cursor)) {
  26553. $tokens[] = $match[1].$match[2].stripcslashes(str_replace(array('"\'', '\'"', '\'\'', '""'), '', substr($match[3], 1, strlen($match[3]) - 2)));
  26554. } elseif (preg_match('/'.self::REGEX_QUOTED_STRING.'/A', $input, $match, null, $cursor)) {
  26555. $tokens[] = stripcslashes(substr($match[0], 1, strlen($match[0]) - 2));
  26556. } elseif (preg_match('/'.self::REGEX_STRING.'/A', $input, $match, null, $cursor)) {
  26557. $tokens[] = stripcslashes($match[1]);
  26558. } else {
  26559. throw new \InvalidArgumentException(sprintf('Unable to parse input near "... %s ..."', substr($input, $cursor, 10)));
  26560. }
  26561. $cursor += strlen($match[0]);
  26562. }
  26563. return $tokens;
  26564. }
  26565. }
  26566. Copyright (c) 2004-2015 Fabien Potencier
  26567. Permission is hereby granted, free of charge, to any person obtaining a copy
  26568. of this software and associated documentation files (the "Software"), to deal
  26569. in the Software without restriction, including without limitation the rights
  26570. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  26571. copies of the Software, and to permit persons to whom the Software is furnished
  26572. to do so, subject to the following conditions:
  26573. The above copyright notice and this permission notice shall be included in all
  26574. copies or substantial portions of the Software.
  26575. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  26576. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  26577. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  26578. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  26579. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26580. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  26581. THE SOFTWARE.
  26582. <?php
  26583. namespace Symfony\Component\Console\Logger;
  26584. use Psr\Log\AbstractLogger;
  26585. use Psr\Log\InvalidArgumentException;
  26586. use Psr\Log\LogLevel;
  26587. use Symfony\Component\Console\Output\OutputInterface;
  26588. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  26589. class ConsoleLogger extends AbstractLogger
  26590. {
  26591. const INFO = 'info';
  26592. const ERROR = 'error';
  26593. private $output;
  26594. private $verbosityLevelMap = array(
  26595. LogLevel::EMERGENCY => OutputInterface::VERBOSITY_NORMAL,
  26596. LogLevel::ALERT => OutputInterface::VERBOSITY_NORMAL,
  26597. LogLevel::CRITICAL => OutputInterface::VERBOSITY_NORMAL,
  26598. LogLevel::ERROR => OutputInterface::VERBOSITY_NORMAL,
  26599. LogLevel::WARNING => OutputInterface::VERBOSITY_NORMAL,
  26600. LogLevel::NOTICE => OutputInterface::VERBOSITY_VERBOSE,
  26601. LogLevel::INFO => OutputInterface::VERBOSITY_VERY_VERBOSE,
  26602. LogLevel::DEBUG => OutputInterface::VERBOSITY_DEBUG,
  26603. );
  26604. private $formatLevelMap = array(
  26605. LogLevel::EMERGENCY => self::ERROR,
  26606. LogLevel::ALERT => self::ERROR,
  26607. LogLevel::CRITICAL => self::ERROR,
  26608. LogLevel::ERROR => self::ERROR,
  26609. LogLevel::WARNING => self::INFO,
  26610. LogLevel::NOTICE => self::INFO,
  26611. LogLevel::INFO => self::INFO,
  26612. LogLevel::DEBUG => self::INFO,
  26613. );
  26614. public function __construct(OutputInterface $output, array $verbosityLevelMap = array(), array $formatLevelMap = array())
  26615. {
  26616. $this->output = $output;
  26617. $this->verbosityLevelMap = $verbosityLevelMap + $this->verbosityLevelMap;
  26618. $this->formatLevelMap = $formatLevelMap + $this->formatLevelMap;
  26619. }
  26620. public function log($level, $message, array $context = array())
  26621. {
  26622. if (!isset($this->verbosityLevelMap[$level])) {
  26623. throw new InvalidArgumentException(sprintf('The log level "%s" does not exist.', $level));
  26624. }
  26625. if ($this->formatLevelMap[$level] === self::ERROR && $this->output instanceof ConsoleOutputInterface) {
  26626. $output = $this->output->getErrorOutput();
  26627. } else {
  26628. $output = $this->output;
  26629. }
  26630. if ($output->getVerbosity() >= $this->verbosityLevelMap[$level]) {
  26631. $output->writeln(sprintf('<%1$s>[%2$s] %3$s</%1$s>', $this->formatLevelMap[$level], $level, $this->interpolate($message, $context)));
  26632. }
  26633. }
  26634. private function interpolate($message, array $context)
  26635. {
  26636. $replace = array();
  26637. foreach ($context as $key => $val) {
  26638. if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
  26639. $replace[sprintf('{%s}', $key)] = $val;
  26640. }
  26641. }
  26642. return strtr($message, $replace);
  26643. }
  26644. }
  26645. <?php
  26646. namespace Symfony\Component\Console\Output;
  26647. class BufferedOutput extends Output
  26648. {
  26649. private $buffer = '';
  26650. public function fetch()
  26651. {
  26652. $content = $this->buffer;
  26653. $this->buffer = '';
  26654. return $content;
  26655. }
  26656. protected function doWrite($message, $newline)
  26657. {
  26658. $this->buffer .= $message;
  26659. if ($newline) {
  26660. $this->buffer .= "\n";
  26661. }
  26662. }
  26663. }
  26664. <?php
  26665. namespace Symfony\Component\Console\Output;
  26666. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  26667. class ConsoleOutput extends StreamOutput implements ConsoleOutputInterface
  26668. {
  26669. private $stderr;
  26670. public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
  26671. {
  26672. $outputStream = 'php://stdout';
  26673. if (!$this->hasStdoutSupport()) {
  26674. $outputStream = 'php://output';
  26675. }
  26676. parent::__construct(fopen($outputStream, 'w'), $verbosity, $decorated, $formatter);
  26677. $this->stderr = new StreamOutput(fopen('php://stderr', 'w'), $verbosity, $decorated, $this->getFormatter());
  26678. }
  26679. public function setDecorated($decorated)
  26680. {
  26681. parent::setDecorated($decorated);
  26682. $this->stderr->setDecorated($decorated);
  26683. }
  26684. public function setFormatter(OutputFormatterInterface $formatter)
  26685. {
  26686. parent::setFormatter($formatter);
  26687. $this->stderr->setFormatter($formatter);
  26688. }
  26689. public function setVerbosity($level)
  26690. {
  26691. parent::setVerbosity($level);
  26692. $this->stderr->setVerbosity($level);
  26693. }
  26694. public function getErrorOutput()
  26695. {
  26696. return $this->stderr;
  26697. }
  26698. public function setErrorOutput(OutputInterface $error)
  26699. {
  26700. $this->stderr = $error;
  26701. }
  26702. protected function hasStdoutSupport()
  26703. {
  26704. return ('OS400' != php_uname('s'));
  26705. }
  26706. }
  26707. <?php
  26708. namespace Symfony\Component\Console\Output;
  26709. interface ConsoleOutputInterface extends OutputInterface
  26710. {
  26711. public function getErrorOutput();
  26712. public function setErrorOutput(OutputInterface $error);
  26713. }
  26714. <?php
  26715. namespace Symfony\Component\Console\Output;
  26716. use Symfony\Component\Console\Formatter\OutputFormatter;
  26717. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  26718. class NullOutput implements OutputInterface
  26719. {
  26720. public function setFormatter(OutputFormatterInterface $formatter)
  26721. {
  26722. }
  26723. public function getFormatter()
  26724. {
  26725. return new OutputFormatter();
  26726. }
  26727. public function setDecorated($decorated)
  26728. {
  26729. }
  26730. public function isDecorated()
  26731. {
  26732. return false;
  26733. }
  26734. public function setVerbosity($level)
  26735. {
  26736. }
  26737. public function getVerbosity()
  26738. {
  26739. return self::VERBOSITY_QUIET;
  26740. }
  26741. public function isQuiet()
  26742. {
  26743. return true;
  26744. }
  26745. public function isVerbose()
  26746. {
  26747. return false;
  26748. }
  26749. public function isVeryVerbose()
  26750. {
  26751. return false;
  26752. }
  26753. public function isDebug()
  26754. {
  26755. return false;
  26756. }
  26757. public function writeln($messages, $type = self::OUTPUT_NORMAL)
  26758. {
  26759. }
  26760. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
  26761. {
  26762. }
  26763. }
  26764. <?php
  26765. namespace Symfony\Component\Console\Output;
  26766. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  26767. use Symfony\Component\Console\Formatter\OutputFormatter;
  26768. abstract class Output implements OutputInterface
  26769. {
  26770. private $verbosity;
  26771. private $formatter;
  26772. public function __construct($verbosity = self::VERBOSITY_NORMAL, $decorated = false, OutputFormatterInterface $formatter = null)
  26773. {
  26774. $this->verbosity = null === $verbosity ? self::VERBOSITY_NORMAL : $verbosity;
  26775. $this->formatter = $formatter ?: new OutputFormatter();
  26776. $this->formatter->setDecorated($decorated);
  26777. }
  26778. public function setFormatter(OutputFormatterInterface $formatter)
  26779. {
  26780. $this->formatter = $formatter;
  26781. }
  26782. public function getFormatter()
  26783. {
  26784. return $this->formatter;
  26785. }
  26786. public function setDecorated($decorated)
  26787. {
  26788. $this->formatter->setDecorated($decorated);
  26789. }
  26790. public function isDecorated()
  26791. {
  26792. return $this->formatter->isDecorated();
  26793. }
  26794. public function setVerbosity($level)
  26795. {
  26796. $this->verbosity = (int) $level;
  26797. }
  26798. public function getVerbosity()
  26799. {
  26800. return $this->verbosity;
  26801. }
  26802. public function isQuiet()
  26803. {
  26804. return self::VERBOSITY_QUIET === $this->verbosity;
  26805. }
  26806. public function isVerbose()
  26807. {
  26808. return self::VERBOSITY_VERBOSE <= $this->verbosity;
  26809. }
  26810. public function isVeryVerbose()
  26811. {
  26812. return self::VERBOSITY_VERY_VERBOSE <= $this->verbosity;
  26813. }
  26814. public function isDebug()
  26815. {
  26816. return self::VERBOSITY_DEBUG <= $this->verbosity;
  26817. }
  26818. public function writeln($messages, $type = self::OUTPUT_NORMAL)
  26819. {
  26820. $this->write($messages, true, $type);
  26821. }
  26822. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL)
  26823. {
  26824. if (self::VERBOSITY_QUIET === $this->verbosity) {
  26825. return;
  26826. }
  26827. $messages = (array) $messages;
  26828. foreach ($messages as $message) {
  26829. switch ($type) {
  26830. case OutputInterface::OUTPUT_NORMAL:
  26831. $message = $this->formatter->format($message);
  26832. break;
  26833. case OutputInterface::OUTPUT_RAW:
  26834. break;
  26835. case OutputInterface::OUTPUT_PLAIN:
  26836. $message = strip_tags($this->formatter->format($message));
  26837. break;
  26838. default:
  26839. throw new \InvalidArgumentException(sprintf('Unknown output type given (%s)', $type));
  26840. }
  26841. $this->doWrite($message, $newline);
  26842. }
  26843. }
  26844. abstract protected function doWrite($message, $newline);
  26845. }
  26846. <?php
  26847. namespace Symfony\Component\Console\Output;
  26848. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  26849. interface OutputInterface
  26850. {
  26851. const VERBOSITY_QUIET = 0;
  26852. const VERBOSITY_NORMAL = 1;
  26853. const VERBOSITY_VERBOSE = 2;
  26854. const VERBOSITY_VERY_VERBOSE = 3;
  26855. const VERBOSITY_DEBUG = 4;
  26856. const OUTPUT_NORMAL = 0;
  26857. const OUTPUT_RAW = 1;
  26858. const OUTPUT_PLAIN = 2;
  26859. public function write($messages, $newline = false, $type = self::OUTPUT_NORMAL);
  26860. public function writeln($messages, $type = self::OUTPUT_NORMAL);
  26861. public function setVerbosity($level);
  26862. public function getVerbosity();
  26863. public function setDecorated($decorated);
  26864. public function isDecorated();
  26865. public function setFormatter(OutputFormatterInterface $formatter);
  26866. public function getFormatter();
  26867. }
  26868. <?php
  26869. namespace Symfony\Component\Console\Output;
  26870. use Symfony\Component\Console\Formatter\OutputFormatterInterface;
  26871. class StreamOutput extends Output
  26872. {
  26873. private $stream;
  26874. public function __construct($stream, $verbosity = self::VERBOSITY_NORMAL, $decorated = null, OutputFormatterInterface $formatter = null)
  26875. {
  26876. if (!is_resource($stream) || 'stream' !== get_resource_type($stream)) {
  26877. throw new \InvalidArgumentException('The StreamOutput class needs a stream as its first argument.');
  26878. }
  26879. $this->stream = $stream;
  26880. if (null === $decorated) {
  26881. $decorated = $this->hasColorSupport();
  26882. }
  26883. parent::__construct($verbosity, $decorated, $formatter);
  26884. }
  26885. public function getStream()
  26886. {
  26887. return $this->stream;
  26888. }
  26889. protected function doWrite($message, $newline)
  26890. {
  26891. if (false === @fwrite($this->stream, $message.($newline ? PHP_EOL : ''))) {
  26892. throw new \RuntimeException('Unable to write output.');
  26893. }
  26894. fflush($this->stream);
  26895. }
  26896. protected function hasColorSupport()
  26897. {
  26898. if (DIRECTORY_SEPARATOR == '\\') {
  26899. return false !== getenv('ANSICON') || 'ON' === getenv('ConEmuANSI');
  26900. }
  26901. return function_exists('posix_isatty') && @posix_isatty($this->stream);
  26902. }
  26903. }
  26904. <?php
  26905. namespace Symfony\Component\Console\Question;
  26906. class ChoiceQuestion extends Question
  26907. {
  26908. private $choices;
  26909. private $multiselect = false;
  26910. private $prompt = ' > ';
  26911. private $errorMessage = 'Value "%s" is invalid';
  26912. public function __construct($question, array $choices, $default = null)
  26913. {
  26914. parent::__construct($question, $default);
  26915. $this->choices = $choices;
  26916. $this->setValidator($this->getDefaultValidator());
  26917. $this->setAutocompleterValues(array_keys($choices));
  26918. }
  26919. public function getChoices()
  26920. {
  26921. return $this->choices;
  26922. }
  26923. public function setMultiselect($multiselect)
  26924. {
  26925. $this->multiselect = $multiselect;
  26926. $this->setValidator($this->getDefaultValidator());
  26927. return $this;
  26928. }
  26929. public function getPrompt()
  26930. {
  26931. return $this->prompt;
  26932. }
  26933. public function setPrompt($prompt)
  26934. {
  26935. $this->prompt = $prompt;
  26936. return $this;
  26937. }
  26938. public function setErrorMessage($errorMessage)
  26939. {
  26940. $this->errorMessage = $errorMessage;
  26941. $this->setValidator($this->getDefaultValidator());
  26942. return $this;
  26943. }
  26944. private function getDefaultValidator()
  26945. {
  26946. $choices = $this->choices;
  26947. $errorMessage = $this->errorMessage;
  26948. $multiselect = $this->multiselect;
  26949. return function ($selected) use ($choices, $errorMessage, $multiselect) {
  26950. $selectedChoices = str_replace(' ', '', $selected);
  26951. if ($multiselect) {
  26952. if (!preg_match('/^[a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*$/', $selectedChoices, $matches)) {
  26953. throw new \InvalidArgumentException(sprintf($errorMessage, $selected));
  26954. }
  26955. $selectedChoices = explode(',', $selectedChoices);
  26956. } else {
  26957. $selectedChoices = array($selected);
  26958. }
  26959. $multiselectChoices = array();
  26960. foreach ($selectedChoices as $value) {
  26961. if (empty($choices[$value])) {
  26962. throw new \InvalidArgumentException(sprintf($errorMessage, $value));
  26963. }
  26964. array_push($multiselectChoices, $choices[$value]);
  26965. }
  26966. if ($multiselect) {
  26967. return $multiselectChoices;
  26968. }
  26969. return $choices[$selected];
  26970. };
  26971. }
  26972. }
  26973. <?php
  26974. namespace Symfony\Component\Console\Question;
  26975. class ConfirmationQuestion extends Question
  26976. {
  26977. public function __construct($question, $default = true)
  26978. {
  26979. parent::__construct($question, (bool) $default);
  26980. $this->setNormalizer($this->getDefaultNormalizer());
  26981. }
  26982. private function getDefaultNormalizer()
  26983. {
  26984. $default = $this->getDefault();
  26985. return function ($answer) use ($default) {
  26986. if (is_bool($answer)) {
  26987. return $answer;
  26988. }
  26989. if (false === $default) {
  26990. return $answer && 'y' === strtolower($answer[0]);
  26991. }
  26992. return !$answer || 'y' === strtolower($answer[0]);
  26993. };
  26994. }
  26995. }
  26996. <?php
  26997. namespace Symfony\Component\Console\Question;
  26998. class Question
  26999. {
  27000. private $question;
  27001. private $attempts;
  27002. private $hidden = false;
  27003. private $hiddenFallback = true;
  27004. private $autocompleterValues;
  27005. private $validator;
  27006. private $default;
  27007. private $normalizer;
  27008. public function __construct($question, $default = null)
  27009. {
  27010. $this->question = $question;
  27011. $this->default = $default;
  27012. }
  27013. public function getQuestion()
  27014. {
  27015. return $this->question;
  27016. }
  27017. public function getDefault()
  27018. {
  27019. return $this->default;
  27020. }
  27021. public function isHidden()
  27022. {
  27023. return $this->hidden;
  27024. }
  27025. public function setHidden($hidden)
  27026. {
  27027. if ($this->autocompleterValues) {
  27028. throw new \LogicException('A hidden question cannot use the autocompleter.');
  27029. }
  27030. $this->hidden = (bool) $hidden;
  27031. return $this;
  27032. }
  27033. public function isHiddenFallback()
  27034. {
  27035. return $this->hiddenFallback;
  27036. }
  27037. public function setHiddenFallback($fallback)
  27038. {
  27039. $this->hiddenFallback = (bool) $fallback;
  27040. return $this;
  27041. }
  27042. public function getAutocompleterValues()
  27043. {
  27044. return $this->autocompleterValues;
  27045. }
  27046. public function setAutocompleterValues($values)
  27047. {
  27048. if (null !== $values && !is_array($values)) {
  27049. if (!$values instanceof \Traversable || $values instanceof \Countable) {
  27050. throw new \InvalidArgumentException('Autocompleter values can be either an array, `null` or an object implementing both `Countable` and `Traversable` interfaces.');
  27051. }
  27052. }
  27053. if ($this->hidden) {
  27054. throw new \LogicException('A hidden question cannot use the autocompleter.');
  27055. }
  27056. $this->autocompleterValues = $values;
  27057. return $this;
  27058. }
  27059. public function setValidator($validator)
  27060. {
  27061. $this->validator = $validator;
  27062. return $this;
  27063. }
  27064. public function getValidator()
  27065. {
  27066. return $this->validator;
  27067. }
  27068. public function setMaxAttempts($attempts)
  27069. {
  27070. if (null !== $attempts && $attempts < 1) {
  27071. throw new \InvalidArgumentException('Maximum number of attempts must be a positive value.');
  27072. }
  27073. $this->attempts = $attempts;
  27074. return $this;
  27075. }
  27076. public function getMaxAttempts()
  27077. {
  27078. return $this->attempts;
  27079. }
  27080. public function setNormalizer($normalizer)
  27081. {
  27082. $this->normalizer = $normalizer;
  27083. return $this;
  27084. }
  27085. public function getNormalizer()
  27086. {
  27087. return $this->normalizer;
  27088. }
  27089. }
  27090. <?php
  27091. namespace Symfony\Component\Console;
  27092. use Symfony\Component\Console\Input\StringInput;
  27093. use Symfony\Component\Console\Output\ConsoleOutput;
  27094. use Symfony\Component\Process\ProcessBuilder;
  27095. use Symfony\Component\Process\PhpExecutableFinder;
  27096. class Shell
  27097. {
  27098. private $application;
  27099. private $history;
  27100. private $output;
  27101. private $hasReadline;
  27102. private $processIsolation = false;
  27103. public function __construct(Application $application)
  27104. {
  27105. $this->hasReadline = function_exists('readline');
  27106. $this->application = $application;
  27107. $this->history = getenv('HOME').'/.history_'.$application->getName();
  27108. $this->output = new ConsoleOutput();
  27109. }
  27110. public function run()
  27111. {
  27112. $this->application->setAutoExit(false);
  27113. $this->application->setCatchExceptions(true);
  27114. if ($this->hasReadline) {
  27115. readline_read_history($this->history);
  27116. readline_completion_function(array($this, 'autocompleter'));
  27117. }
  27118. $this->output->writeln($this->getHeader());
  27119. $php = null;
  27120. if ($this->processIsolation) {
  27121. $finder = new PhpExecutableFinder();
  27122. $php = $finder->find();
  27123. $this->output->writeln(<<<EOF
  27124. <info>Running with process isolation, you should consider this:</info>
  27125. * each command is executed as separate process,
  27126. * commands don't support interactivity, all params must be passed explicitly,
  27127. * commands output is not colorized.
  27128. EOF
  27129. );
  27130. }
  27131. while (true) {
  27132. $command = $this->readline();
  27133. if (false === $command) {
  27134. $this->output->writeln("\n");
  27135. break;
  27136. }
  27137. if ($this->hasReadline) {
  27138. readline_add_history($command);
  27139. readline_write_history($this->history);
  27140. }
  27141. if ($this->processIsolation) {
  27142. $pb = new ProcessBuilder();
  27143. $process = $pb
  27144. ->add($php)
  27145. ->add($_SERVER['argv'][0])
  27146. ->add($command)
  27147. ->inheritEnvironmentVariables(true)
  27148. ->getProcess()
  27149. ;
  27150. $output = $this->output;
  27151. $process->run(function ($type, $data) use ($output) {
  27152. $output->writeln($data);
  27153. });
  27154. $ret = $process->getExitCode();
  27155. } else {
  27156. $ret = $this->application->run(new StringInput($command), $this->output);
  27157. }
  27158. if (0 !== $ret) {
  27159. $this->output->writeln(sprintf('<error>The command terminated with an error status (%s)</error>', $ret));
  27160. }
  27161. }
  27162. }
  27163. protected function getHeader()
  27164. {
  27165. return <<<EOF
  27166. Welcome to the <info>{$this->application->getName()}</info> shell (<comment>{$this->application->getVersion()}</comment>).
  27167. At the prompt, type <comment>help</comment> for some help,
  27168. or <comment>list</comment> to get a list of available commands.
  27169. To exit the shell, type <comment>^D</comment>.
  27170. EOF;
  27171. }
  27172. protected function getPrompt()
  27173. {
  27174. return $this->output->getFormatter()->format($this->application->getName().' > ');
  27175. }
  27176. protected function getOutput()
  27177. {
  27178. return $this->output;
  27179. }
  27180. protected function getApplication()
  27181. {
  27182. return $this->application;
  27183. }
  27184. private function autocompleter($text)
  27185. {
  27186. $info = readline_info();
  27187. $text = substr($info['line_buffer'], 0, $info['end']);
  27188. if ($info['point'] !== $info['end']) {
  27189. return true;
  27190. }
  27191. if (false === strpos($text, ' ') || !$text) {
  27192. return array_keys($this->application->all());
  27193. }
  27194. try {
  27195. $command = $this->application->find(substr($text, 0, strpos($text, ' ')));
  27196. } catch (\Exception $e) {
  27197. return true;
  27198. }
  27199. $list = array('--help');
  27200. foreach ($command->getDefinition()->getOptions() as $option) {
  27201. $list[] = '--'.$option->getName();
  27202. }
  27203. return $list;
  27204. }
  27205. private function readline()
  27206. {
  27207. if ($this->hasReadline) {
  27208. $line = readline($this->getPrompt());
  27209. } else {
  27210. $this->output->write($this->getPrompt());
  27211. $line = fgets(STDIN, 1024);
  27212. $line = (!$line && strlen($line) == 0) ? false : rtrim($line);
  27213. }
  27214. return $line;
  27215. }
  27216. public function getProcessIsolation()
  27217. {
  27218. return $this->processIsolation;
  27219. }
  27220. public function setProcessIsolation($processIsolation)
  27221. {
  27222. $this->processIsolation = (bool) $processIsolation;
  27223. if ($this->processIsolation && !class_exists('Symfony\\Component\\Process\\Process')) {
  27224. throw new \RuntimeException('Unable to isolate processes as the Symfony Process Component is not installed.');
  27225. }
  27226. }
  27227. }
  27228. <?php
  27229. namespace Symfony\Component\Console\Tester;
  27230. use Symfony\Component\Console\Application;
  27231. use Symfony\Component\Console\Input\ArrayInput;
  27232. use Symfony\Component\Console\Input\InputInterface;
  27233. use Symfony\Component\Console\Output\OutputInterface;
  27234. use Symfony\Component\Console\Output\StreamOutput;
  27235. class ApplicationTester
  27236. {
  27237. private $application;
  27238. private $input;
  27239. private $output;
  27240. private $statusCode;
  27241. public function __construct(Application $application)
  27242. {
  27243. $this->application = $application;
  27244. }
  27245. public function run(array $input, $options = array())
  27246. {
  27247. $this->input = new ArrayInput($input);
  27248. if (isset($options['interactive'])) {
  27249. $this->input->setInteractive($options['interactive']);
  27250. }
  27251. $this->output = new StreamOutput(fopen('php://memory', 'w', false));
  27252. if (isset($options['decorated'])) {
  27253. $this->output->setDecorated($options['decorated']);
  27254. }
  27255. if (isset($options['verbosity'])) {
  27256. $this->output->setVerbosity($options['verbosity']);
  27257. }
  27258. return $this->statusCode = $this->application->run($this->input, $this->output);
  27259. }
  27260. public function getDisplay($normalize = false)
  27261. {
  27262. rewind($this->output->getStream());
  27263. $display = stream_get_contents($this->output->getStream());
  27264. if ($normalize) {
  27265. $display = str_replace(PHP_EOL, "\n", $display);
  27266. }
  27267. return $display;
  27268. }
  27269. public function getInput()
  27270. {
  27271. return $this->input;
  27272. }
  27273. public function getOutput()
  27274. {
  27275. return $this->output;
  27276. }
  27277. public function getStatusCode()
  27278. {
  27279. return $this->statusCode;
  27280. }
  27281. }
  27282. <?php
  27283. namespace Symfony\Component\Console\Tester;
  27284. use Symfony\Component\Console\Command\Command;
  27285. use Symfony\Component\Console\Input\ArrayInput;
  27286. use Symfony\Component\Console\Output\StreamOutput;
  27287. use Symfony\Component\Console\Input\InputInterface;
  27288. use Symfony\Component\Console\Output\OutputInterface;
  27289. class CommandTester
  27290. {
  27291. private $command;
  27292. private $input;
  27293. private $output;
  27294. private $statusCode;
  27295. public function __construct(Command $command)
  27296. {
  27297. $this->command = $command;
  27298. }
  27299. public function execute(array $input, array $options = array())
  27300. {
  27301. if (!isset($input['command'])
  27302. && (null !== $application = $this->command->getApplication())
  27303. && $application->getDefinition()->hasArgument('command')
  27304. ) {
  27305. $input['command'] = $this->command->getName();
  27306. }
  27307. $this->input = new ArrayInput($input);
  27308. if (isset($options['interactive'])) {
  27309. $this->input->setInteractive($options['interactive']);
  27310. }
  27311. $this->output = new StreamOutput(fopen('php://memory', 'w', false));
  27312. if (isset($options['decorated'])) {
  27313. $this->output->setDecorated($options['decorated']);
  27314. }
  27315. if (isset($options['verbosity'])) {
  27316. $this->output->setVerbosity($options['verbosity']);
  27317. }
  27318. return $this->statusCode = $this->command->run($this->input, $this->output);
  27319. }
  27320. public function getDisplay($normalize = false)
  27321. {
  27322. rewind($this->output->getStream());
  27323. $display = stream_get_contents($this->output->getStream());
  27324. if ($normalize) {
  27325. $display = str_replace(PHP_EOL, "\n", $display);
  27326. }
  27327. return $display;
  27328. }
  27329. public function getInput()
  27330. {
  27331. return $this->input;
  27332. }
  27333. public function getOutput()
  27334. {
  27335. return $this->output;
  27336. }
  27337. public function getStatusCode()
  27338. {
  27339. return $this->statusCode;
  27340. }
  27341. }
  27342. <?php
  27343. namespace Symfony\Component\Finder\Adapter;
  27344. abstract class AbstractAdapter implements AdapterInterface
  27345. {
  27346. protected $followLinks = false;
  27347. protected $mode = 0;
  27348. protected $minDepth = 0;
  27349. protected $maxDepth = PHP_INT_MAX;
  27350. protected $exclude = array();
  27351. protected $names = array();
  27352. protected $notNames = array();
  27353. protected $contains = array();
  27354. protected $notContains = array();
  27355. protected $sizes = array();
  27356. protected $dates = array();
  27357. protected $filters = array();
  27358. protected $sort = false;
  27359. protected $paths = array();
  27360. protected $notPaths = array();
  27361. protected $ignoreUnreadableDirs = false;
  27362. private static $areSupported = array();
  27363. public function isSupported()
  27364. {
  27365. $name = $this->getName();
  27366. if (!array_key_exists($name, self::$areSupported)) {
  27367. self::$areSupported[$name] = $this->canBeUsed();
  27368. }
  27369. return self::$areSupported[$name];
  27370. }
  27371. public function setFollowLinks($followLinks)
  27372. {
  27373. $this->followLinks = $followLinks;
  27374. return $this;
  27375. }
  27376. public function setMode($mode)
  27377. {
  27378. $this->mode = $mode;
  27379. return $this;
  27380. }
  27381. public function setDepths(array $depths)
  27382. {
  27383. $this->minDepth = 0;
  27384. $this->maxDepth = PHP_INT_MAX;
  27385. foreach ($depths as $comparator) {
  27386. switch ($comparator->getOperator()) {
  27387. case '>':
  27388. $this->minDepth = $comparator->getTarget() + 1;
  27389. break;
  27390. case '>=':
  27391. $this->minDepth = $comparator->getTarget();
  27392. break;
  27393. case '<':
  27394. $this->maxDepth = $comparator->getTarget() - 1;
  27395. break;
  27396. case '<=':
  27397. $this->maxDepth = $comparator->getTarget();
  27398. break;
  27399. default:
  27400. $this->minDepth = $this->maxDepth = $comparator->getTarget();
  27401. }
  27402. }
  27403. return $this;
  27404. }
  27405. public function setExclude(array $exclude)
  27406. {
  27407. $this->exclude = $exclude;
  27408. return $this;
  27409. }
  27410. public function setNames(array $names)
  27411. {
  27412. $this->names = $names;
  27413. return $this;
  27414. }
  27415. public function setNotNames(array $notNames)
  27416. {
  27417. $this->notNames = $notNames;
  27418. return $this;
  27419. }
  27420. public function setContains(array $contains)
  27421. {
  27422. $this->contains = $contains;
  27423. return $this;
  27424. }
  27425. public function setNotContains(array $notContains)
  27426. {
  27427. $this->notContains = $notContains;
  27428. return $this;
  27429. }
  27430. public function setSizes(array $sizes)
  27431. {
  27432. $this->sizes = $sizes;
  27433. return $this;
  27434. }
  27435. public function setDates(array $dates)
  27436. {
  27437. $this->dates = $dates;
  27438. return $this;
  27439. }
  27440. public function setFilters(array $filters)
  27441. {
  27442. $this->filters = $filters;
  27443. return $this;
  27444. }
  27445. public function setSort($sort)
  27446. {
  27447. $this->sort = $sort;
  27448. return $this;
  27449. }
  27450. public function setPath(array $paths)
  27451. {
  27452. $this->paths = $paths;
  27453. return $this;
  27454. }
  27455. public function setNotPath(array $notPaths)
  27456. {
  27457. $this->notPaths = $notPaths;
  27458. return $this;
  27459. }
  27460. public function ignoreUnreadableDirs($ignore = true)
  27461. {
  27462. $this->ignoreUnreadableDirs = (bool) $ignore;
  27463. return $this;
  27464. }
  27465. abstract protected function canBeUsed();
  27466. }
  27467. <?php
  27468. namespace Symfony\Component\Finder\Adapter;
  27469. use Symfony\Component\Finder\Exception\AccessDeniedException;
  27470. use Symfony\Component\Finder\Iterator;
  27471. use Symfony\Component\Finder\Shell\Shell;
  27472. use Symfony\Component\Finder\Expression\Expression;
  27473. use Symfony\Component\Finder\Shell\Command;
  27474. use Symfony\Component\Finder\Comparator\NumberComparator;
  27475. use Symfony\Component\Finder\Comparator\DateComparator;
  27476. abstract class AbstractFindAdapter extends AbstractAdapter
  27477. {
  27478. protected $shell;
  27479. public function __construct()
  27480. {
  27481. $this->shell = new Shell();
  27482. }
  27483. public function searchInDirectory($dir)
  27484. {
  27485. $dir = realpath($dir);
  27486. if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode && ($this->contains || $this->notContains)) {
  27487. return new Iterator\FilePathsIterator(array(), $dir);
  27488. }
  27489. $command = Command::create();
  27490. $find = $this->buildFindCommand($command, $dir);
  27491. if ($this->followLinks) {
  27492. $find->add('-follow');
  27493. }
  27494. $find->add('-mindepth')->add($this->minDepth + 1);
  27495. if (PHP_INT_MAX !== $this->maxDepth) {
  27496. $find->add('-maxdepth')->add($this->maxDepth + 1);
  27497. }
  27498. if (Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES === $this->mode) {
  27499. $find->add('-type d');
  27500. } elseif (Iterator\FileTypeFilterIterator::ONLY_FILES === $this->mode) {
  27501. $find->add('-type f');
  27502. }
  27503. $this->buildNamesFiltering($find, $this->names);
  27504. $this->buildNamesFiltering($find, $this->notNames, true);
  27505. $this->buildPathsFiltering($find, $dir, $this->paths);
  27506. $this->buildPathsFiltering($find, $dir, $this->notPaths, true);
  27507. $this->buildSizesFiltering($find, $this->sizes);
  27508. $this->buildDatesFiltering($find, $this->dates);
  27509. $useGrep = $this->shell->testCommand('grep') && $this->shell->testCommand('xargs');
  27510. $useSort = is_int($this->sort) && $this->shell->testCommand('sort') && $this->shell->testCommand('cut');
  27511. if ($useGrep && ($this->contains || $this->notContains)) {
  27512. $grep = $command->ins('grep');
  27513. $this->buildContentFiltering($grep, $this->contains);
  27514. $this->buildContentFiltering($grep, $this->notContains, true);
  27515. }
  27516. if ($useSort) {
  27517. $this->buildSorting($command, $this->sort);
  27518. }
  27519. $command->setErrorHandler(
  27520. $this->ignoreUnreadableDirs
  27521. ? function ($stderr) { return; }
  27522. : function ($stderr) { throw new AccessDeniedException($stderr); }
  27523. );
  27524. $paths = $this->shell->testCommand('uniq') ? $command->add('| uniq')->execute() : array_unique($command->execute());
  27525. $iterator = new Iterator\FilePathsIterator($paths, $dir);
  27526. if ($this->exclude) {
  27527. $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
  27528. }
  27529. if (!$useGrep && ($this->contains || $this->notContains)) {
  27530. $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
  27531. }
  27532. if ($this->filters) {
  27533. $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
  27534. }
  27535. if (!$useSort && $this->sort) {
  27536. $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
  27537. $iterator = $iteratorAggregate->getIterator();
  27538. }
  27539. return $iterator;
  27540. }
  27541. protected function canBeUsed()
  27542. {
  27543. return $this->shell->testCommand('find');
  27544. }
  27545. protected function buildFindCommand(Command $command, $dir)
  27546. {
  27547. return $command
  27548. ->ins('find')
  27549. ->add('find ')
  27550. ->arg($dir)
  27551. ->add('-noleaf');
  27552. }
  27553. private function buildNamesFiltering(Command $command, array $names, $not = false)
  27554. {
  27555. if (0 === count($names)) {
  27556. return;
  27557. }
  27558. $command->add($not ? '-not' : null)->cmd('(');
  27559. foreach ($names as $i => $name) {
  27560. $expr = Expression::create($name);
  27561. if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
  27562. $expr = Expression::create($expr->getGlob()->toRegex(false));
  27563. }
  27564. if ($expr->isRegex()) {
  27565. $regex = $expr->getRegex();
  27566. $regex->prepend($regex->hasStartFlag() ? '/' : '/[^/]*')
  27567. ->setStartFlag(false)
  27568. ->setStartJoker(true)
  27569. ->replaceJokers('[^/]');
  27570. if (!$regex->hasEndFlag() || $regex->hasEndJoker()) {
  27571. $regex->setEndJoker(false)->append('[^/]*');
  27572. }
  27573. }
  27574. $command
  27575. ->add($i > 0 ? '-or' : null)
  27576. ->add($expr->isRegex()
  27577. ? ($expr->isCaseSensitive() ? '-regex' : '-iregex')
  27578. : ($expr->isCaseSensitive() ? '-name' : '-iname')
  27579. )
  27580. ->arg($expr->renderPattern());
  27581. }
  27582. $command->cmd(')');
  27583. }
  27584. private function buildPathsFiltering(Command $command, $dir, array $paths, $not = false)
  27585. {
  27586. if (0 === count($paths)) {
  27587. return;
  27588. }
  27589. $command->add($not ? '-not' : null)->cmd('(');
  27590. foreach ($paths as $i => $path) {
  27591. $expr = Expression::create($path);
  27592. if ($expr->isGlob() && $expr->getGlob()->isExpandable()) {
  27593. $expr = Expression::create($expr->getGlob()->toRegex(false));
  27594. }
  27595. if ($expr->isRegex()) {
  27596. $regex = $expr->getRegex();
  27597. $regex->prepend($regex->hasStartFlag() ? preg_quote($dir).DIRECTORY_SEPARATOR : '.*')->setEndJoker(!$regex->hasEndFlag());
  27598. } else {
  27599. $expr->prepend('*')->append('*');
  27600. }
  27601. $command
  27602. ->add($i > 0 ? '-or' : null)
  27603. ->add($expr->isRegex()
  27604. ? ($expr->isCaseSensitive() ? '-regex' : '-iregex')
  27605. : ($expr->isCaseSensitive() ? '-path' : '-ipath')
  27606. )
  27607. ->arg($expr->renderPattern());
  27608. }
  27609. $command->cmd(')');
  27610. }
  27611. private function buildSizesFiltering(Command $command, array $sizes)
  27612. {
  27613. foreach ($sizes as $i => $size) {
  27614. $command->add($i > 0 ? '-and' : null);
  27615. switch ($size->getOperator()) {
  27616. case '<=':
  27617. $command->add('-size -'.($size->getTarget() + 1).'c');
  27618. break;
  27619. case '>=':
  27620. $command->add('-size +'.($size->getTarget() - 1).'c');
  27621. break;
  27622. case '>':
  27623. $command->add('-size +'.$size->getTarget().'c');
  27624. break;
  27625. case '!=':
  27626. $command->add('-size -'.$size->getTarget().'c');
  27627. $command->add('-size +'.$size->getTarget().'c');
  27628. break;
  27629. case '<':
  27630. default:
  27631. $command->add('-size -'.$size->getTarget().'c');
  27632. }
  27633. }
  27634. }
  27635. private function buildDatesFiltering(Command $command, array $dates)
  27636. {
  27637. foreach ($dates as $i => $date) {
  27638. $command->add($i > 0 ? '-and' : null);
  27639. $mins = (int) round((time()-$date->getTarget()) / 60);
  27640. if (0 > $mins) {
  27641. $command->add(' -mmin -0');
  27642. return;
  27643. }
  27644. switch ($date->getOperator()) {
  27645. case '<=':
  27646. $command->add('-mmin +'.($mins - 1));
  27647. break;
  27648. case '>=':
  27649. $command->add('-mmin -'.($mins + 1));
  27650. break;
  27651. case '>':
  27652. $command->add('-mmin -'.$mins);
  27653. break;
  27654. case '!=':
  27655. $command->add('-mmin +'.$mins.' -or -mmin -'.$mins);
  27656. break;
  27657. case '<':
  27658. default:
  27659. $command->add('-mmin +'.$mins);
  27660. }
  27661. }
  27662. }
  27663. private function buildSorting(Command $command, $sort)
  27664. {
  27665. $this->buildFormatSorting($command, $sort);
  27666. }
  27667. abstract protected function buildFormatSorting(Command $command, $sort);
  27668. abstract protected function buildContentFiltering(Command $command, array $contains, $not = false);
  27669. }
  27670. <?php
  27671. namespace Symfony\Component\Finder\Adapter;
  27672. interface AdapterInterface
  27673. {
  27674. public function setFollowLinks($followLinks);
  27675. public function setMode($mode);
  27676. public function setExclude(array $exclude);
  27677. public function setDepths(array $depths);
  27678. public function setNames(array $names);
  27679. public function setNotNames(array $notNames);
  27680. public function setContains(array $contains);
  27681. public function setNotContains(array $notContains);
  27682. public function setSizes(array $sizes);
  27683. public function setDates(array $dates);
  27684. public function setFilters(array $filters);
  27685. public function setSort($sort);
  27686. public function setPath(array $paths);
  27687. public function setNotPath(array $notPaths);
  27688. public function ignoreUnreadableDirs($ignore = true);
  27689. public function searchInDirectory($dir);
  27690. public function isSupported();
  27691. public function getName();
  27692. }
  27693. <?php
  27694. namespace Symfony\Component\Finder\Adapter;
  27695. use Symfony\Component\Finder\Shell\Shell;
  27696. use Symfony\Component\Finder\Shell\Command;
  27697. use Symfony\Component\Finder\Iterator\SortableIterator;
  27698. use Symfony\Component\Finder\Expression\Expression;
  27699. class BsdFindAdapter extends AbstractFindAdapter
  27700. {
  27701. public function getName()
  27702. {
  27703. return 'bsd_find';
  27704. }
  27705. protected function canBeUsed()
  27706. {
  27707. return in_array($this->shell->getType(), array(Shell::TYPE_BSD, Shell::TYPE_DARWIN)) && parent::canBeUsed();
  27708. }
  27709. protected function buildFormatSorting(Command $command, $sort)
  27710. {
  27711. switch ($sort) {
  27712. case SortableIterator::SORT_BY_NAME:
  27713. $command->ins('sort')->add('| sort');
  27714. return;
  27715. case SortableIterator::SORT_BY_TYPE:
  27716. $format = '%HT';
  27717. break;
  27718. case SortableIterator::SORT_BY_ACCESSED_TIME:
  27719. $format = '%a';
  27720. break;
  27721. case SortableIterator::SORT_BY_CHANGED_TIME:
  27722. $format = '%c';
  27723. break;
  27724. case SortableIterator::SORT_BY_MODIFIED_TIME:
  27725. $format = '%m';
  27726. break;
  27727. default:
  27728. throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
  27729. }
  27730. $command
  27731. ->add('-print0 | xargs -0 stat -f')
  27732. ->arg($format.'%t%N')
  27733. ->add('| sort | cut -f 2');
  27734. }
  27735. protected function buildFindCommand(Command $command, $dir)
  27736. {
  27737. parent::buildFindCommand($command, $dir)->addAtIndex('-E', 1);
  27738. return $command;
  27739. }
  27740. protected function buildContentFiltering(Command $command, array $contains, $not = false)
  27741. {
  27742. foreach ($contains as $contain) {
  27743. $expr = Expression::create($contain);
  27744. $command
  27745. ->add('| grep -v \'^$\'')
  27746. ->add('| xargs -I{} grep -I')
  27747. ->add($expr->isCaseSensitive() ? null : '-i')
  27748. ->add($not ? '-L' : '-l')
  27749. ->add('-Ee')->arg($expr->renderPattern())
  27750. ->add('{}')
  27751. ;
  27752. }
  27753. }
  27754. }
  27755. <?php
  27756. namespace Symfony\Component\Finder\Adapter;
  27757. use Symfony\Component\Finder\Shell\Shell;
  27758. use Symfony\Component\Finder\Shell\Command;
  27759. use Symfony\Component\Finder\Iterator\SortableIterator;
  27760. use Symfony\Component\Finder\Expression\Expression;
  27761. class GnuFindAdapter extends AbstractFindAdapter
  27762. {
  27763. public function getName()
  27764. {
  27765. return 'gnu_find';
  27766. }
  27767. protected function buildFormatSorting(Command $command, $sort)
  27768. {
  27769. switch ($sort) {
  27770. case SortableIterator::SORT_BY_NAME:
  27771. $command->ins('sort')->add('| sort');
  27772. return;
  27773. case SortableIterator::SORT_BY_TYPE:
  27774. $format = '%y';
  27775. break;
  27776. case SortableIterator::SORT_BY_ACCESSED_TIME:
  27777. $format = '%A@';
  27778. break;
  27779. case SortableIterator::SORT_BY_CHANGED_TIME:
  27780. $format = '%C@';
  27781. break;
  27782. case SortableIterator::SORT_BY_MODIFIED_TIME:
  27783. $format = '%T@';
  27784. break;
  27785. default:
  27786. throw new \InvalidArgumentException(sprintf('Unknown sort options: %s.', $sort));
  27787. }
  27788. $command
  27789. ->get('find')
  27790. ->add('-printf')
  27791. ->arg($format.' %h/%f\\n')
  27792. ->add('| sort | cut')
  27793. ->arg('-d ')
  27794. ->arg('-f2-')
  27795. ;
  27796. }
  27797. protected function canBeUsed()
  27798. {
  27799. return $this->shell->getType() === Shell::TYPE_UNIX && parent::canBeUsed();
  27800. }
  27801. protected function buildFindCommand(Command $command, $dir)
  27802. {
  27803. return parent::buildFindCommand($command, $dir)->add('-regextype posix-extended');
  27804. }
  27805. protected function buildContentFiltering(Command $command, array $contains, $not = false)
  27806. {
  27807. foreach ($contains as $contain) {
  27808. $expr = Expression::create($contain);
  27809. $command
  27810. ->add('| xargs -I{} -r grep -I')
  27811. ->add($expr->isCaseSensitive() ? null : '-i')
  27812. ->add($not ? '-L' : '-l')
  27813. ->add('-Ee')->arg($expr->renderPattern())
  27814. ->add('{}')
  27815. ;
  27816. }
  27817. }
  27818. }
  27819. <?php
  27820. namespace Symfony\Component\Finder\Adapter;
  27821. use Symfony\Component\Finder\Iterator;
  27822. class PhpAdapter extends AbstractAdapter
  27823. {
  27824. public function searchInDirectory($dir)
  27825. {
  27826. $flags = \RecursiveDirectoryIterator::SKIP_DOTS;
  27827. if ($this->followLinks) {
  27828. $flags |= \RecursiveDirectoryIterator::FOLLOW_SYMLINKS;
  27829. }
  27830. $iterator = new \RecursiveIteratorIterator(
  27831. new Iterator\RecursiveDirectoryIterator($dir, $flags, $this->ignoreUnreadableDirs),
  27832. \RecursiveIteratorIterator::SELF_FIRST
  27833. );
  27834. if ($this->minDepth > 0 || $this->maxDepth < PHP_INT_MAX) {
  27835. $iterator = new Iterator\DepthRangeFilterIterator($iterator, $this->minDepth, $this->maxDepth);
  27836. }
  27837. if ($this->mode) {
  27838. $iterator = new Iterator\FileTypeFilterIterator($iterator, $this->mode);
  27839. }
  27840. if ($this->exclude) {
  27841. $iterator = new Iterator\ExcludeDirectoryFilterIterator($iterator, $this->exclude);
  27842. }
  27843. if ($this->names || $this->notNames) {
  27844. $iterator = new Iterator\FilenameFilterIterator($iterator, $this->names, $this->notNames);
  27845. }
  27846. if ($this->contains || $this->notContains) {
  27847. $iterator = new Iterator\FilecontentFilterIterator($iterator, $this->contains, $this->notContains);
  27848. }
  27849. if ($this->sizes) {
  27850. $iterator = new Iterator\SizeRangeFilterIterator($iterator, $this->sizes);
  27851. }
  27852. if ($this->dates) {
  27853. $iterator = new Iterator\DateRangeFilterIterator($iterator, $this->dates);
  27854. }
  27855. if ($this->filters) {
  27856. $iterator = new Iterator\CustomFilterIterator($iterator, $this->filters);
  27857. }
  27858. if ($this->sort) {
  27859. $iteratorAggregate = new Iterator\SortableIterator($iterator, $this->sort);
  27860. $iterator = $iteratorAggregate->getIterator();
  27861. }
  27862. if ($this->paths || $this->notPaths) {
  27863. $iterator = new Iterator\PathFilterIterator($iterator, $this->paths, $this->notPaths);
  27864. }
  27865. return $iterator;
  27866. }
  27867. public function getName()
  27868. {
  27869. return 'php';
  27870. }
  27871. protected function canBeUsed()
  27872. {
  27873. return true;
  27874. }
  27875. }
  27876. <?php
  27877. namespace Symfony\Component\Finder\Comparator;
  27878. class Comparator
  27879. {
  27880. private $target;
  27881. private $operator = '==';
  27882. public function getTarget()
  27883. {
  27884. return $this->target;
  27885. }
  27886. public function setTarget($target)
  27887. {
  27888. $this->target = $target;
  27889. }
  27890. public function getOperator()
  27891. {
  27892. return $this->operator;
  27893. }
  27894. public function setOperator($operator)
  27895. {
  27896. if (!$operator) {
  27897. $operator = '==';
  27898. }
  27899. if (!in_array($operator, array('>', '<', '>=', '<=', '==', '!='))) {
  27900. throw new \InvalidArgumentException(sprintf('Invalid operator "%s".', $operator));
  27901. }
  27902. $this->operator = $operator;
  27903. }
  27904. public function test($test)
  27905. {
  27906. switch ($this->operator) {
  27907. case '>':
  27908. return $test > $this->target;
  27909. case '>=':
  27910. return $test >= $this->target;
  27911. case '<':
  27912. return $test < $this->target;
  27913. case '<=':
  27914. return $test <= $this->target;
  27915. case '!=':
  27916. return $test != $this->target;
  27917. }
  27918. return $test == $this->target;
  27919. }
  27920. }
  27921. <?php
  27922. namespace Symfony\Component\Finder\Comparator;
  27923. class DateComparator extends Comparator
  27924. {
  27925. public function __construct($test)
  27926. {
  27927. if (!preg_match('#^\s*(==|!=|[<>]=?|after|since|before|until)?\s*(.+?)\s*$#i', $test, $matches)) {
  27928. throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a date test.', $test));
  27929. }
  27930. try {
  27931. $date = new \DateTime($matches[2]);
  27932. $target = $date->format('U');
  27933. } catch (\Exception $e) {
  27934. throw new \InvalidArgumentException(sprintf('"%s" is not a valid date.', $matches[2]));
  27935. }
  27936. $operator = isset($matches[1]) ? $matches[1] : '==';
  27937. if ('since' === $operator || 'after' === $operator) {
  27938. $operator = '>';
  27939. }
  27940. if ('until' === $operator || 'before' === $operator) {
  27941. $operator = '<';
  27942. }
  27943. $this->setOperator($operator);
  27944. $this->setTarget($target);
  27945. }
  27946. }
  27947. <?php
  27948. namespace Symfony\Component\Finder\Comparator;
  27949. class NumberComparator extends Comparator
  27950. {
  27951. public function __construct($test)
  27952. {
  27953. if (!preg_match('#^\s*(==|!=|[<>]=?)?\s*([0-9\.]+)\s*([kmg]i?)?\s*$#i', $test, $matches)) {
  27954. throw new \InvalidArgumentException(sprintf('Don\'t understand "%s" as a number test.', $test));
  27955. }
  27956. $target = $matches[2];
  27957. if (!is_numeric($target)) {
  27958. throw new \InvalidArgumentException(sprintf('Invalid number "%s".', $target));
  27959. }
  27960. if (isset($matches[3])) {
  27961. switch (strtolower($matches[3])) {
  27962. case 'k':
  27963. $target *= 1000;
  27964. break;
  27965. case 'ki':
  27966. $target *= 1024;
  27967. break;
  27968. case 'm':
  27969. $target *= 1000000;
  27970. break;
  27971. case 'mi':
  27972. $target *= 1024*1024;
  27973. break;
  27974. case 'g':
  27975. $target *= 1000000000;
  27976. break;
  27977. case 'gi':
  27978. $target *= 1024*1024*1024;
  27979. break;
  27980. }
  27981. }
  27982. $this->setTarget($target);
  27983. $this->setOperator(isset($matches[1]) ? $matches[1] : '==');
  27984. }
  27985. }
  27986. <?php
  27987. namespace Symfony\Component\Finder\Exception;
  27988. class AccessDeniedException extends \UnexpectedValueException
  27989. {
  27990. }
  27991. <?php
  27992. namespace Symfony\Component\Finder\Exception;
  27993. use Symfony\Component\Finder\Adapter\AdapterInterface;
  27994. class AdapterFailureException extends \RuntimeException implements ExceptionInterface
  27995. {
  27996. private $adapter;
  27997. public function __construct(AdapterInterface $adapter, $message = null, \Exception $previous = null)
  27998. {
  27999. $this->adapter = $adapter;
  28000. parent::__construct($message ?: 'Search failed with "'.$adapter->getName().'" adapter.', $previous);
  28001. }
  28002. public function getAdapter()
  28003. {
  28004. return $this->adapter;
  28005. }
  28006. }
  28007. <?php
  28008. namespace Symfony\Component\Finder\Exception;
  28009. interface ExceptionInterface
  28010. {
  28011. public function getAdapter();
  28012. }
  28013. <?php
  28014. namespace Symfony\Component\Finder\Exception;
  28015. class OperationNotPermitedException extends AdapterFailureException
  28016. {
  28017. }
  28018. <?php
  28019. namespace Symfony\Component\Finder\Exception;
  28020. use Symfony\Component\Finder\Adapter\AdapterInterface;
  28021. use Symfony\Component\Finder\Shell\Command;
  28022. class ShellCommandFailureException extends AdapterFailureException
  28023. {
  28024. private $command;
  28025. public function __construct(AdapterInterface $adapter, Command $command, \Exception $previous = null)
  28026. {
  28027. $this->command = $command;
  28028. parent::__construct($adapter, 'Shell command failed: "'.$command->join().'".', $previous);
  28029. }
  28030. public function getCommand()
  28031. {
  28032. return $this->command;
  28033. }
  28034. }
  28035. <?php
  28036. namespace Symfony\Component\Finder\Expression;
  28037. class Expression implements ValueInterface
  28038. {
  28039. const TYPE_REGEX = 1;
  28040. const TYPE_GLOB = 2;
  28041. private $value;
  28042. public static function create($expr)
  28043. {
  28044. return new self($expr);
  28045. }
  28046. public function __construct($expr)
  28047. {
  28048. try {
  28049. $this->value = Regex::create($expr);
  28050. } catch (\InvalidArgumentException $e) {
  28051. $this->value = new Glob($expr);
  28052. }
  28053. }
  28054. public function __toString()
  28055. {
  28056. return $this->render();
  28057. }
  28058. public function render()
  28059. {
  28060. return $this->value->render();
  28061. }
  28062. public function renderPattern()
  28063. {
  28064. return $this->value->renderPattern();
  28065. }
  28066. public function isCaseSensitive()
  28067. {
  28068. return $this->value->isCaseSensitive();
  28069. }
  28070. public function getType()
  28071. {
  28072. return $this->value->getType();
  28073. }
  28074. public function prepend($expr)
  28075. {
  28076. $this->value->prepend($expr);
  28077. return $this;
  28078. }
  28079. public function append($expr)
  28080. {
  28081. $this->value->append($expr);
  28082. return $this;
  28083. }
  28084. public function isRegex()
  28085. {
  28086. return self::TYPE_REGEX === $this->value->getType();
  28087. }
  28088. public function isGlob()
  28089. {
  28090. return self::TYPE_GLOB === $this->value->getType();
  28091. }
  28092. public function getGlob()
  28093. {
  28094. if (self::TYPE_GLOB !== $this->value->getType()) {
  28095. throw new \LogicException('Regex can\'t be transformed to glob.');
  28096. }
  28097. return $this->value;
  28098. }
  28099. public function getRegex()
  28100. {
  28101. return self::TYPE_REGEX === $this->value->getType() ? $this->value : $this->value->toRegex();
  28102. }
  28103. }
  28104. <?php
  28105. namespace Symfony\Component\Finder\Expression;
  28106. class Glob implements ValueInterface
  28107. {
  28108. private $pattern;
  28109. public function __construct($pattern)
  28110. {
  28111. $this->pattern = $pattern;
  28112. }
  28113. public function render()
  28114. {
  28115. return $this->pattern;
  28116. }
  28117. public function renderPattern()
  28118. {
  28119. return $this->pattern;
  28120. }
  28121. public function getType()
  28122. {
  28123. return Expression::TYPE_GLOB;
  28124. }
  28125. public function isCaseSensitive()
  28126. {
  28127. return true;
  28128. }
  28129. public function prepend($expr)
  28130. {
  28131. $this->pattern = $expr.$this->pattern;
  28132. return $this;
  28133. }
  28134. public function append($expr)
  28135. {
  28136. $this->pattern .= $expr;
  28137. return $this;
  28138. }
  28139. public function isExpandable()
  28140. {
  28141. return false !== strpos($this->pattern, '{')
  28142. && false !== strpos($this->pattern, '}');
  28143. }
  28144. public function toRegex($strictLeadingDot = true, $strictWildcardSlash = true)
  28145. {
  28146. $firstByte = true;
  28147. $escaping = false;
  28148. $inCurlies = 0;
  28149. $regex = '';
  28150. $sizeGlob = strlen($this->pattern);
  28151. for ($i = 0; $i < $sizeGlob; $i++) {
  28152. $car = $this->pattern[$i];
  28153. if ($firstByte) {
  28154. if ($strictLeadingDot && '.' !== $car) {
  28155. $regex .= '(?=[^\.])';
  28156. }
  28157. $firstByte = false;
  28158. }
  28159. if ('/' === $car) {
  28160. $firstByte = true;
  28161. }
  28162. if ('.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
  28163. $regex .= "\\$car";
  28164. } elseif ('*' === $car) {
  28165. $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
  28166. } elseif ('?' === $car) {
  28167. $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
  28168. } elseif ('{' === $car) {
  28169. $regex .= $escaping ? '\\{' : '(';
  28170. if (!$escaping) {
  28171. ++$inCurlies;
  28172. }
  28173. } elseif ('}' === $car && $inCurlies) {
  28174. $regex .= $escaping ? '}' : ')';
  28175. if (!$escaping) {
  28176. --$inCurlies;
  28177. }
  28178. } elseif (',' === $car && $inCurlies) {
  28179. $regex .= $escaping ? ',' : '|';
  28180. } elseif ('\\' === $car) {
  28181. if ($escaping) {
  28182. $regex .= '\\\\';
  28183. $escaping = false;
  28184. } else {
  28185. $escaping = true;
  28186. }
  28187. continue;
  28188. } else {
  28189. $regex .= $car;
  28190. }
  28191. $escaping = false;
  28192. }
  28193. return new Regex('^'.$regex.'$');
  28194. }
  28195. }
  28196. <?php
  28197. namespace Symfony\Component\Finder\Expression;
  28198. class Regex implements ValueInterface
  28199. {
  28200. const START_FLAG = '^';
  28201. const END_FLAG = '$';
  28202. const BOUNDARY = '~';
  28203. const JOKER = '.*';
  28204. const ESCAPING = '\\';
  28205. private $pattern;
  28206. private $options;
  28207. private $startFlag;
  28208. private $endFlag;
  28209. private $startJoker;
  28210. private $endJoker;
  28211. public static function create($expr)
  28212. {
  28213. if (preg_match('/^(.{3,}?)([imsxuADU]*)$/', $expr, $m)) {
  28214. $start = substr($m[1], 0, 1);
  28215. $end = substr($m[1], -1);
  28216. if (
  28217. ($start === $end && !preg_match('/[*?[:alnum:] \\\\]/', $start))
  28218. || ($start === '{' && $end === '}')
  28219. || ($start === '(' && $end === ')')
  28220. ) {
  28221. return new self(substr($m[1], 1, -1), $m[2], $end);
  28222. }
  28223. }
  28224. throw new \InvalidArgumentException('Given expression is not a regex.');
  28225. }
  28226. public function __construct($pattern, $options = '', $delimiter = null)
  28227. {
  28228. if (null !== $delimiter) {
  28229. $pattern = str_replace('\\'.$delimiter, $delimiter, $pattern);
  28230. }
  28231. $this->parsePattern($pattern);
  28232. $this->options = $options;
  28233. }
  28234. public function __toString()
  28235. {
  28236. return $this->render();
  28237. }
  28238. public function render()
  28239. {
  28240. return self::BOUNDARY
  28241. .$this->renderPattern()
  28242. .self::BOUNDARY
  28243. .$this->options;
  28244. }
  28245. public function renderPattern()
  28246. {
  28247. return ($this->startFlag ? self::START_FLAG : '')
  28248. .($this->startJoker ? self::JOKER : '')
  28249. .str_replace(self::BOUNDARY, '\\'.self::BOUNDARY, $this->pattern)
  28250. .($this->endJoker ? self::JOKER : '')
  28251. .($this->endFlag ? self::END_FLAG : '');
  28252. }
  28253. public function isCaseSensitive()
  28254. {
  28255. return !$this->hasOption('i');
  28256. }
  28257. public function getType()
  28258. {
  28259. return Expression::TYPE_REGEX;
  28260. }
  28261. public function prepend($expr)
  28262. {
  28263. $this->pattern = $expr.$this->pattern;
  28264. return $this;
  28265. }
  28266. public function append($expr)
  28267. {
  28268. $this->pattern .= $expr;
  28269. return $this;
  28270. }
  28271. public function hasOption($option)
  28272. {
  28273. return false !== strpos($this->options, $option);
  28274. }
  28275. public function addOption($option)
  28276. {
  28277. if (!$this->hasOption($option)) {
  28278. $this->options .= $option;
  28279. }
  28280. return $this;
  28281. }
  28282. public function removeOption($option)
  28283. {
  28284. $this->options = str_replace($option, '', $this->options);
  28285. return $this;
  28286. }
  28287. public function setStartFlag($startFlag)
  28288. {
  28289. $this->startFlag = $startFlag;
  28290. return $this;
  28291. }
  28292. public function hasStartFlag()
  28293. {
  28294. return $this->startFlag;
  28295. }
  28296. public function setEndFlag($endFlag)
  28297. {
  28298. $this->endFlag = (bool) $endFlag;
  28299. return $this;
  28300. }
  28301. public function hasEndFlag()
  28302. {
  28303. return $this->endFlag;
  28304. }
  28305. public function setStartJoker($startJoker)
  28306. {
  28307. $this->startJoker = $startJoker;
  28308. return $this;
  28309. }
  28310. public function hasStartJoker()
  28311. {
  28312. return $this->startJoker;
  28313. }
  28314. public function setEndJoker($endJoker)
  28315. {
  28316. $this->endJoker = (bool) $endJoker;
  28317. return $this;
  28318. }
  28319. public function hasEndJoker()
  28320. {
  28321. return $this->endJoker;
  28322. }
  28323. public function replaceJokers($replacement)
  28324. {
  28325. $replace = function ($subject) use ($replacement) {
  28326. $subject = $subject[0];
  28327. $replace = 0 === substr_count($subject, '\\') % 2;
  28328. return $replace ? str_replace('.', $replacement, $subject) : $subject;
  28329. };
  28330. $this->pattern = preg_replace_callback('~[\\\\]*\\.~', $replace, $this->pattern);
  28331. return $this;
  28332. }
  28333. private function parsePattern($pattern)
  28334. {
  28335. if ($this->startFlag = self::START_FLAG === substr($pattern, 0, 1)) {
  28336. $pattern = substr($pattern, 1);
  28337. }
  28338. if ($this->startJoker = self::JOKER === substr($pattern, 0, 2)) {
  28339. $pattern = substr($pattern, 2);
  28340. }
  28341. if ($this->endFlag = (self::END_FLAG === substr($pattern, -1) && self::ESCAPING !== substr($pattern, -2, -1))) {
  28342. $pattern = substr($pattern, 0, -1);
  28343. }
  28344. if ($this->endJoker = (self::JOKER === substr($pattern, -2) && self::ESCAPING !== substr($pattern, -3, -2))) {
  28345. $pattern = substr($pattern, 0, -2);
  28346. }
  28347. $this->pattern = $pattern;
  28348. }
  28349. }
  28350. <?php
  28351. namespace Symfony\Component\Finder\Expression;
  28352. interface ValueInterface
  28353. {
  28354. public function render();
  28355. public function renderPattern();
  28356. public function isCaseSensitive();
  28357. public function getType();
  28358. public function prepend($expr);
  28359. public function append($expr);
  28360. }
  28361. <?php
  28362. namespace Symfony\Component\Finder;
  28363. use Symfony\Component\Finder\Adapter\AdapterInterface;
  28364. use Symfony\Component\Finder\Adapter\GnuFindAdapter;
  28365. use Symfony\Component\Finder\Adapter\BsdFindAdapter;
  28366. use Symfony\Component\Finder\Adapter\PhpAdapter;
  28367. use Symfony\Component\Finder\Comparator\DateComparator;
  28368. use Symfony\Component\Finder\Comparator\NumberComparator;
  28369. use Symfony\Component\Finder\Exception\ExceptionInterface;
  28370. use Symfony\Component\Finder\Iterator\CustomFilterIterator;
  28371. use Symfony\Component\Finder\Iterator\DateRangeFilterIterator;
  28372. use Symfony\Component\Finder\Iterator\DepthRangeFilterIterator;
  28373. use Symfony\Component\Finder\Iterator\ExcludeDirectoryFilterIterator;
  28374. use Symfony\Component\Finder\Iterator\FilecontentFilterIterator;
  28375. use Symfony\Component\Finder\Iterator\FilenameFilterIterator;
  28376. use Symfony\Component\Finder\Iterator\SizeRangeFilterIterator;
  28377. use Symfony\Component\Finder\Iterator\SortableIterator;
  28378. class Finder implements \IteratorAggregate, \Countable
  28379. {
  28380. const IGNORE_VCS_FILES = 1;
  28381. const IGNORE_DOT_FILES = 2;
  28382. private $mode = 0;
  28383. private $names = array();
  28384. private $notNames = array();
  28385. private $exclude = array();
  28386. private $filters = array();
  28387. private $depths = array();
  28388. private $sizes = array();
  28389. private $followLinks = false;
  28390. private $sort = false;
  28391. private $ignore = 0;
  28392. private $dirs = array();
  28393. private $dates = array();
  28394. private $iterators = array();
  28395. private $contains = array();
  28396. private $notContains = array();
  28397. private $adapters = array();
  28398. private $paths = array();
  28399. private $notPaths = array();
  28400. private $ignoreUnreadableDirs = false;
  28401. private static $vcsPatterns = array('.svn', '_svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr', '.git', '.hg');
  28402. public function __construct()
  28403. {
  28404. $this->ignore = static::IGNORE_VCS_FILES | static::IGNORE_DOT_FILES;
  28405. $this
  28406. ->addAdapter(new GnuFindAdapter())
  28407. ->addAdapter(new BsdFindAdapter())
  28408. ->addAdapter(new PhpAdapter(), -50)
  28409. ->setAdapter('php')
  28410. ;
  28411. }
  28412. public static function create()
  28413. {
  28414. return new static();
  28415. }
  28416. public function addAdapter(AdapterInterface $adapter, $priority = 0)
  28417. {
  28418. $this->adapters[$adapter->getName()] = array(
  28419. 'adapter' => $adapter,
  28420. 'priority' => $priority,
  28421. 'selected' => false,
  28422. );
  28423. return $this->sortAdapters();
  28424. }
  28425. public function useBestAdapter()
  28426. {
  28427. $this->resetAdapterSelection();
  28428. return $this->sortAdapters();
  28429. }
  28430. public function setAdapter($name)
  28431. {
  28432. if (!isset($this->adapters[$name])) {
  28433. throw new \InvalidArgumentException(sprintf('Adapter "%s" does not exist.', $name));
  28434. }
  28435. $this->resetAdapterSelection();
  28436. $this->adapters[$name]['selected'] = true;
  28437. return $this->sortAdapters();
  28438. }
  28439. public function removeAdapters()
  28440. {
  28441. $this->adapters = array();
  28442. return $this;
  28443. }
  28444. public function getAdapters()
  28445. {
  28446. return array_values(array_map(function (array $adapter) {
  28447. return $adapter['adapter'];
  28448. }, $this->adapters));
  28449. }
  28450. public function directories()
  28451. {
  28452. $this->mode = Iterator\FileTypeFilterIterator::ONLY_DIRECTORIES;
  28453. return $this;
  28454. }
  28455. public function files()
  28456. {
  28457. $this->mode = Iterator\FileTypeFilterIterator::ONLY_FILES;
  28458. return $this;
  28459. }
  28460. public function depth($level)
  28461. {
  28462. $this->depths[] = new Comparator\NumberComparator($level);
  28463. return $this;
  28464. }
  28465. public function date($date)
  28466. {
  28467. $this->dates[] = new Comparator\DateComparator($date);
  28468. return $this;
  28469. }
  28470. public function name($pattern)
  28471. {
  28472. $this->names[] = $pattern;
  28473. return $this;
  28474. }
  28475. public function notName($pattern)
  28476. {
  28477. $this->notNames[] = $pattern;
  28478. return $this;
  28479. }
  28480. public function contains($pattern)
  28481. {
  28482. $this->contains[] = $pattern;
  28483. return $this;
  28484. }
  28485. public function notContains($pattern)
  28486. {
  28487. $this->notContains[] = $pattern;
  28488. return $this;
  28489. }
  28490. public function path($pattern)
  28491. {
  28492. $this->paths[] = $pattern;
  28493. return $this;
  28494. }
  28495. public function notPath($pattern)
  28496. {
  28497. $this->notPaths[] = $pattern;
  28498. return $this;
  28499. }
  28500. public function size($size)
  28501. {
  28502. $this->sizes[] = new Comparator\NumberComparator($size);
  28503. return $this;
  28504. }
  28505. public function exclude($dirs)
  28506. {
  28507. $this->exclude = array_merge($this->exclude, (array) $dirs);
  28508. return $this;
  28509. }
  28510. public function ignoreDotFiles($ignoreDotFiles)
  28511. {
  28512. if ($ignoreDotFiles) {
  28513. $this->ignore = $this->ignore | static::IGNORE_DOT_FILES;
  28514. } else {
  28515. $this->ignore = $this->ignore & ~static::IGNORE_DOT_FILES;
  28516. }
  28517. return $this;
  28518. }
  28519. public function ignoreVCS($ignoreVCS)
  28520. {
  28521. if ($ignoreVCS) {
  28522. $this->ignore = $this->ignore | static::IGNORE_VCS_FILES;
  28523. } else {
  28524. $this->ignore = $this->ignore & ~static::IGNORE_VCS_FILES;
  28525. }
  28526. return $this;
  28527. }
  28528. public static function addVCSPattern($pattern)
  28529. {
  28530. foreach ((array) $pattern as $p) {
  28531. self::$vcsPatterns[] = $p;
  28532. }
  28533. self::$vcsPatterns = array_unique(self::$vcsPatterns);
  28534. }
  28535. public function sort(\Closure $closure)
  28536. {
  28537. $this->sort = $closure;
  28538. return $this;
  28539. }
  28540. public function sortByName()
  28541. {
  28542. $this->sort = Iterator\SortableIterator::SORT_BY_NAME;
  28543. return $this;
  28544. }
  28545. public function sortByType()
  28546. {
  28547. $this->sort = Iterator\SortableIterator::SORT_BY_TYPE;
  28548. return $this;
  28549. }
  28550. public function sortByAccessedTime()
  28551. {
  28552. $this->sort = Iterator\SortableIterator::SORT_BY_ACCESSED_TIME;
  28553. return $this;
  28554. }
  28555. public function sortByChangedTime()
  28556. {
  28557. $this->sort = Iterator\SortableIterator::SORT_BY_CHANGED_TIME;
  28558. return $this;
  28559. }
  28560. public function sortByModifiedTime()
  28561. {
  28562. $this->sort = Iterator\SortableIterator::SORT_BY_MODIFIED_TIME;
  28563. return $this;
  28564. }
  28565. public function filter(\Closure $closure)
  28566. {
  28567. $this->filters[] = $closure;
  28568. return $this;
  28569. }
  28570. public function followLinks()
  28571. {
  28572. $this->followLinks = true;
  28573. return $this;
  28574. }
  28575. public function ignoreUnreadableDirs($ignore = true)
  28576. {
  28577. $this->ignoreUnreadableDirs = (bool) $ignore;
  28578. return $this;
  28579. }
  28580. public function in($dirs)
  28581. {
  28582. $resolvedDirs = array();
  28583. foreach ((array) $dirs as $dir) {
  28584. if (is_dir($dir)) {
  28585. $resolvedDirs[] = $dir;
  28586. } elseif ($glob = glob($dir, GLOB_BRACE | GLOB_ONLYDIR)) {
  28587. $resolvedDirs = array_merge($resolvedDirs, $glob);
  28588. } else {
  28589. throw new \InvalidArgumentException(sprintf('The "%s" directory does not exist.', $dir));
  28590. }
  28591. }
  28592. $this->dirs = array_merge($this->dirs, $resolvedDirs);
  28593. return $this;
  28594. }
  28595. public function getIterator()
  28596. {
  28597. if (0 === count($this->dirs) && 0 === count($this->iterators)) {
  28598. throw new \LogicException('You must call one of in() or append() methods before iterating over a Finder.');
  28599. }
  28600. if (1 === count($this->dirs) && 0 === count($this->iterators)) {
  28601. return $this->searchInDirectory($this->dirs[0]);
  28602. }
  28603. $iterator = new \AppendIterator();
  28604. foreach ($this->dirs as $dir) {
  28605. $iterator->append($this->searchInDirectory($dir));
  28606. }
  28607. foreach ($this->iterators as $it) {
  28608. $iterator->append($it);
  28609. }
  28610. return $iterator;
  28611. }
  28612. public function append($iterator)
  28613. {
  28614. if ($iterator instanceof \IteratorAggregate) {
  28615. $this->iterators[] = $iterator->getIterator();
  28616. } elseif ($iterator instanceof \Iterator) {
  28617. $this->iterators[] = $iterator;
  28618. } elseif ($iterator instanceof \Traversable || is_array($iterator)) {
  28619. $it = new \ArrayIterator();
  28620. foreach ($iterator as $file) {
  28621. $it->append($file instanceof \SplFileInfo ? $file : new \SplFileInfo($file));
  28622. }
  28623. $this->iterators[] = $it;
  28624. } else {
  28625. throw new \InvalidArgumentException('Finder::append() method wrong argument type.');
  28626. }
  28627. return $this;
  28628. }
  28629. public function count()
  28630. {
  28631. return iterator_count($this->getIterator());
  28632. }
  28633. private function sortAdapters()
  28634. {
  28635. uasort($this->adapters, function (array $a, array $b) {
  28636. if ($a['selected'] || $b['selected']) {
  28637. return $a['selected'] ? -1 : 1;
  28638. }
  28639. return $a['priority'] > $b['priority'] ? -1 : 1;
  28640. });
  28641. return $this;
  28642. }
  28643. private function searchInDirectory($dir)
  28644. {
  28645. if (static::IGNORE_VCS_FILES === (static::IGNORE_VCS_FILES & $this->ignore)) {
  28646. $this->exclude = array_merge($this->exclude, self::$vcsPatterns);
  28647. }
  28648. if (static::IGNORE_DOT_FILES === (static::IGNORE_DOT_FILES & $this->ignore)) {
  28649. $this->notPaths[] = '#(^|/)\..+(/|$)#';
  28650. }
  28651. foreach ($this->adapters as $adapter) {
  28652. if ($adapter['adapter']->isSupported()) {
  28653. try {
  28654. return $this
  28655. ->buildAdapter($adapter['adapter'])
  28656. ->searchInDirectory($dir);
  28657. } catch (ExceptionInterface $e) {
  28658. }
  28659. }
  28660. }
  28661. throw new \RuntimeException('No supported adapter found.');
  28662. }
  28663. private function buildAdapter(AdapterInterface $adapter)
  28664. {
  28665. return $adapter
  28666. ->setFollowLinks($this->followLinks)
  28667. ->setDepths($this->depths)
  28668. ->setMode($this->mode)
  28669. ->setExclude($this->exclude)
  28670. ->setNames($this->names)
  28671. ->setNotNames($this->notNames)
  28672. ->setContains($this->contains)
  28673. ->setNotContains($this->notContains)
  28674. ->setSizes($this->sizes)
  28675. ->setDates($this->dates)
  28676. ->setFilters($this->filters)
  28677. ->setSort($this->sort)
  28678. ->setPath($this->paths)
  28679. ->setNotPath($this->notPaths)
  28680. ->ignoreUnreadableDirs($this->ignoreUnreadableDirs);
  28681. }
  28682. private function resetAdapterSelection()
  28683. {
  28684. $this->adapters = array_map(function (array $properties) {
  28685. $properties['selected'] = false;
  28686. return $properties;
  28687. }, $this->adapters);
  28688. }
  28689. }
  28690. <?php
  28691. namespace Symfony\Component\Finder;
  28692. class Glob
  28693. {
  28694. public static function toRegex($glob, $strictLeadingDot = true, $strictWildcardSlash = true)
  28695. {
  28696. $firstByte = true;
  28697. $escaping = false;
  28698. $inCurlies = 0;
  28699. $regex = '';
  28700. $sizeGlob = strlen($glob);
  28701. for ($i = 0; $i < $sizeGlob; $i++) {
  28702. $car = $glob[$i];
  28703. if ($firstByte) {
  28704. if ($strictLeadingDot && '.' !== $car) {
  28705. $regex .= '(?=[^\.])';
  28706. }
  28707. $firstByte = false;
  28708. }
  28709. if ('/' === $car) {
  28710. $firstByte = true;
  28711. }
  28712. if ('.' === $car || '(' === $car || ')' === $car || '|' === $car || '+' === $car || '^' === $car || '$' === $car) {
  28713. $regex .= "\\$car";
  28714. } elseif ('*' === $car) {
  28715. $regex .= $escaping ? '\\*' : ($strictWildcardSlash ? '[^/]*' : '.*');
  28716. } elseif ('?' === $car) {
  28717. $regex .= $escaping ? '\\?' : ($strictWildcardSlash ? '[^/]' : '.');
  28718. } elseif ('{' === $car) {
  28719. $regex .= $escaping ? '\\{' : '(';
  28720. if (!$escaping) {
  28721. ++$inCurlies;
  28722. }
  28723. } elseif ('}' === $car && $inCurlies) {
  28724. $regex .= $escaping ? '}' : ')';
  28725. if (!$escaping) {
  28726. --$inCurlies;
  28727. }
  28728. } elseif (',' === $car && $inCurlies) {
  28729. $regex .= $escaping ? ',' : '|';
  28730. } elseif ('\\' === $car) {
  28731. if ($escaping) {
  28732. $regex .= '\\\\';
  28733. $escaping = false;
  28734. } else {
  28735. $escaping = true;
  28736. }
  28737. continue;
  28738. } else {
  28739. $regex .= $car;
  28740. }
  28741. $escaping = false;
  28742. }
  28743. return '#^'.$regex.'$#';
  28744. }
  28745. }
  28746. <?php
  28747. namespace Symfony\Component\Finder\Iterator;
  28748. class CustomFilterIterator extends FilterIterator
  28749. {
  28750. private $filters = array();
  28751. public function __construct(\Iterator $iterator, array $filters)
  28752. {
  28753. foreach ($filters as $filter) {
  28754. if (!is_callable($filter)) {
  28755. throw new \InvalidArgumentException('Invalid PHP callback.');
  28756. }
  28757. }
  28758. $this->filters = $filters;
  28759. parent::__construct($iterator);
  28760. }
  28761. public function accept()
  28762. {
  28763. $fileinfo = $this->current();
  28764. foreach ($this->filters as $filter) {
  28765. if (false === call_user_func($filter, $fileinfo)) {
  28766. return false;
  28767. }
  28768. }
  28769. return true;
  28770. }
  28771. }
  28772. <?php
  28773. namespace Symfony\Component\Finder\Iterator;
  28774. use Symfony\Component\Finder\Comparator\DateComparator;
  28775. class DateRangeFilterIterator extends FilterIterator
  28776. {
  28777. private $comparators = array();
  28778. public function __construct(\Iterator $iterator, array $comparators)
  28779. {
  28780. $this->comparators = $comparators;
  28781. parent::__construct($iterator);
  28782. }
  28783. public function accept()
  28784. {
  28785. $fileinfo = $this->current();
  28786. if (!file_exists($fileinfo->getRealPath())) {
  28787. return false;
  28788. }
  28789. $filedate = $fileinfo->getMTime();
  28790. foreach ($this->comparators as $compare) {
  28791. if (!$compare->test($filedate)) {
  28792. return false;
  28793. }
  28794. }
  28795. return true;
  28796. }
  28797. }
  28798. <?php
  28799. namespace Symfony\Component\Finder\Iterator;
  28800. class DepthRangeFilterIterator extends FilterIterator
  28801. {
  28802. private $minDepth = 0;
  28803. public function __construct(\RecursiveIteratorIterator $iterator, $minDepth = 0, $maxDepth = PHP_INT_MAX)
  28804. {
  28805. $this->minDepth = $minDepth;
  28806. $iterator->setMaxDepth(PHP_INT_MAX === $maxDepth ? -1 : $maxDepth);
  28807. parent::__construct($iterator);
  28808. }
  28809. public function accept()
  28810. {
  28811. return $this->getInnerIterator()->getDepth() >= $this->minDepth;
  28812. }
  28813. }
  28814. <?php
  28815. namespace Symfony\Component\Finder\Iterator;
  28816. class ExcludeDirectoryFilterIterator extends FilterIterator
  28817. {
  28818. private $patterns = array();
  28819. public function __construct(\Iterator $iterator, array $directories)
  28820. {
  28821. foreach ($directories as $directory) {
  28822. $this->patterns[] = '#(^|/)'.preg_quote($directory, '#').'(/|$)#';
  28823. }
  28824. parent::__construct($iterator);
  28825. }
  28826. public function accept()
  28827. {
  28828. $path = $this->isDir() ? $this->current()->getRelativePathname() : $this->current()->getRelativePath();
  28829. $path = strtr($path, '\\', '/');
  28830. foreach ($this->patterns as $pattern) {
  28831. if (preg_match($pattern, $path)) {
  28832. return false;
  28833. }
  28834. }
  28835. return true;
  28836. }
  28837. }
  28838. <?php
  28839. namespace Symfony\Component\Finder\Iterator;
  28840. class FilecontentFilterIterator extends MultiplePcreFilterIterator
  28841. {
  28842. public function accept()
  28843. {
  28844. if (!$this->matchRegexps && !$this->noMatchRegexps) {
  28845. return true;
  28846. }
  28847. $fileinfo = $this->current();
  28848. if ($fileinfo->isDir() || !$fileinfo->isReadable()) {
  28849. return false;
  28850. }
  28851. $content = $fileinfo->getContents();
  28852. if (!$content) {
  28853. return false;
  28854. }
  28855. foreach ($this->noMatchRegexps as $regex) {
  28856. if (preg_match($regex, $content)) {
  28857. return false;
  28858. }
  28859. }
  28860. $match = true;
  28861. if ($this->matchRegexps) {
  28862. $match = false;
  28863. foreach ($this->matchRegexps as $regex) {
  28864. if (preg_match($regex, $content)) {
  28865. return true;
  28866. }
  28867. }
  28868. }
  28869. return $match;
  28870. }
  28871. protected function toRegex($str)
  28872. {
  28873. return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
  28874. }
  28875. }
  28876. <?php
  28877. namespace Symfony\Component\Finder\Iterator;
  28878. use Symfony\Component\Finder\Expression\Expression;
  28879. class FilenameFilterIterator extends MultiplePcreFilterIterator
  28880. {
  28881. public function accept()
  28882. {
  28883. $filename = $this->current()->getFilename();
  28884. foreach ($this->noMatchRegexps as $regex) {
  28885. if (preg_match($regex, $filename)) {
  28886. return false;
  28887. }
  28888. }
  28889. $match = true;
  28890. if ($this->matchRegexps) {
  28891. $match = false;
  28892. foreach ($this->matchRegexps as $regex) {
  28893. if (preg_match($regex, $filename)) {
  28894. return true;
  28895. }
  28896. }
  28897. }
  28898. return $match;
  28899. }
  28900. protected function toRegex($str)
  28901. {
  28902. return Expression::create($str)->getRegex()->render();
  28903. }
  28904. }
  28905. <?php
  28906. namespace Symfony\Component\Finder\Iterator;
  28907. use Symfony\Component\Finder\SplFileInfo;
  28908. class FilePathsIterator extends \ArrayIterator
  28909. {
  28910. private $baseDir;
  28911. private $baseDirLength;
  28912. private $subPath;
  28913. private $subPathname;
  28914. private $current;
  28915. public function __construct(array $paths, $baseDir)
  28916. {
  28917. $this->baseDir = $baseDir;
  28918. $this->baseDirLength = strlen($baseDir);
  28919. parent::__construct($paths);
  28920. }
  28921. public function __call($name, array $arguments)
  28922. {
  28923. return call_user_func_array(array($this->current(), $name), $arguments);
  28924. }
  28925. public function current()
  28926. {
  28927. return $this->current;
  28928. }
  28929. public function key()
  28930. {
  28931. return $this->current->getPathname();
  28932. }
  28933. public function next()
  28934. {
  28935. parent::next();
  28936. $this->buildProperties();
  28937. }
  28938. public function rewind()
  28939. {
  28940. parent::rewind();
  28941. $this->buildProperties();
  28942. }
  28943. public function getSubPath()
  28944. {
  28945. return $this->subPath;
  28946. }
  28947. public function getSubPathname()
  28948. {
  28949. return $this->subPathname;
  28950. }
  28951. private function buildProperties()
  28952. {
  28953. $absolutePath = parent::current();
  28954. if ($this->baseDir === substr($absolutePath, 0, $this->baseDirLength)) {
  28955. $this->subPathname = ltrim(substr($absolutePath, $this->baseDirLength), '/\\');
  28956. $dir = dirname($this->subPathname);
  28957. $this->subPath = '.' === $dir ? '' : $dir;
  28958. } else {
  28959. $this->subPath = $this->subPathname = '';
  28960. }
  28961. $this->current = new SplFileInfo(parent::current(), $this->subPath, $this->subPathname);
  28962. }
  28963. }
  28964. <?php
  28965. namespace Symfony\Component\Finder\Iterator;
  28966. class FileTypeFilterIterator extends FilterIterator
  28967. {
  28968. const ONLY_FILES = 1;
  28969. const ONLY_DIRECTORIES = 2;
  28970. private $mode;
  28971. public function __construct(\Iterator $iterator, $mode)
  28972. {
  28973. $this->mode = $mode;
  28974. parent::__construct($iterator);
  28975. }
  28976. public function accept()
  28977. {
  28978. $fileinfo = $this->current();
  28979. if (self::ONLY_DIRECTORIES === (self::ONLY_DIRECTORIES & $this->mode) && $fileinfo->isFile()) {
  28980. return false;
  28981. } elseif (self::ONLY_FILES === (self::ONLY_FILES & $this->mode) && $fileinfo->isDir()) {
  28982. return false;
  28983. }
  28984. return true;
  28985. }
  28986. }
  28987. <?php
  28988. namespace Symfony\Component\Finder\Iterator;
  28989. abstract class FilterIterator extends \FilterIterator
  28990. {
  28991. public function rewind()
  28992. {
  28993. $iterator = $this;
  28994. while ($iterator instanceof \OuterIterator) {
  28995. $innerIterator = $iterator->getInnerIterator();
  28996. if ($innerIterator instanceof RecursiveDirectoryIterator) {
  28997. if ($innerIterator->isRewindable()) {
  28998. $innerIterator->next();
  28999. $innerIterator->rewind();
  29000. }
  29001. } elseif ($iterator->getInnerIterator() instanceof \FilesystemIterator) {
  29002. $iterator->getInnerIterator()->next();
  29003. $iterator->getInnerIterator()->rewind();
  29004. }
  29005. $iterator = $iterator->getInnerIterator();
  29006. }
  29007. parent::rewind();
  29008. }
  29009. }
  29010. <?php
  29011. namespace Symfony\Component\Finder\Iterator;
  29012. use Symfony\Component\Finder\Expression\Expression;
  29013. abstract class MultiplePcreFilterIterator extends FilterIterator
  29014. {
  29015. protected $matchRegexps = array();
  29016. protected $noMatchRegexps = array();
  29017. public function __construct(\Iterator $iterator, array $matchPatterns, array $noMatchPatterns)
  29018. {
  29019. foreach ($matchPatterns as $pattern) {
  29020. $this->matchRegexps[] = $this->toRegex($pattern);
  29021. }
  29022. foreach ($noMatchPatterns as $pattern) {
  29023. $this->noMatchRegexps[] = $this->toRegex($pattern);
  29024. }
  29025. parent::__construct($iterator);
  29026. }
  29027. protected function isRegex($str)
  29028. {
  29029. return Expression::create($str)->isRegex();
  29030. }
  29031. abstract protected function toRegex($str);
  29032. }
  29033. <?php
  29034. namespace Symfony\Component\Finder\Iterator;
  29035. class PathFilterIterator extends MultiplePcreFilterIterator
  29036. {
  29037. public function accept()
  29038. {
  29039. $filename = $this->current()->getRelativePathname();
  29040. if ('\\' === DIRECTORY_SEPARATOR) {
  29041. $filename = strtr($filename, '\\', '/');
  29042. }
  29043. foreach ($this->noMatchRegexps as $regex) {
  29044. if (preg_match($regex, $filename)) {
  29045. return false;
  29046. }
  29047. }
  29048. $match = true;
  29049. if ($this->matchRegexps) {
  29050. $match = false;
  29051. foreach ($this->matchRegexps as $regex) {
  29052. if (preg_match($regex, $filename)) {
  29053. return true;
  29054. }
  29055. }
  29056. }
  29057. return $match;
  29058. }
  29059. protected function toRegex($str)
  29060. {
  29061. return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
  29062. }
  29063. }
  29064. <?php
  29065. namespace Symfony\Component\Finder\Iterator;
  29066. use Symfony\Component\Finder\Exception\AccessDeniedException;
  29067. use Symfony\Component\Finder\SplFileInfo;
  29068. class RecursiveDirectoryIterator extends \RecursiveDirectoryIterator
  29069. {
  29070. private $ignoreUnreadableDirs;
  29071. private $rewindable;
  29072. public function __construct($path, $flags, $ignoreUnreadableDirs = false)
  29073. {
  29074. if ($flags & (self::CURRENT_AS_PATHNAME | self::CURRENT_AS_SELF)) {
  29075. throw new \RuntimeException('This iterator only support returning current as fileinfo.');
  29076. }
  29077. parent::__construct($path, $flags);
  29078. $this->ignoreUnreadableDirs = $ignoreUnreadableDirs;
  29079. }
  29080. public function current()
  29081. {
  29082. return new SplFileInfo(parent::current()->getPathname(), $this->getSubPath(), $this->getSubPathname());
  29083. }
  29084. public function getChildren()
  29085. {
  29086. try {
  29087. $children = parent::getChildren();
  29088. if ($children instanceof self) {
  29089. $children->ignoreUnreadableDirs = $this->ignoreUnreadableDirs;
  29090. }
  29091. return $children;
  29092. } catch (\UnexpectedValueException $e) {
  29093. if ($this->ignoreUnreadableDirs) {
  29094. return new \RecursiveArrayIterator(array());
  29095. } else {
  29096. throw new AccessDeniedException($e->getMessage(), $e->getCode(), $e);
  29097. }
  29098. }
  29099. }
  29100. public function rewind()
  29101. {
  29102. if (false === $this->isRewindable()) {
  29103. return;
  29104. }
  29105. parent::next();
  29106. parent::rewind();
  29107. }
  29108. public function isRewindable()
  29109. {
  29110. if (null !== $this->rewindable) {
  29111. return $this->rewindable;
  29112. }
  29113. if (false !== $stream = @opendir($this->getPath())) {
  29114. $infos = stream_get_meta_data($stream);
  29115. closedir($stream);
  29116. if ($infos['seekable']) {
  29117. return $this->rewindable = true;
  29118. }
  29119. }
  29120. return $this->rewindable = false;
  29121. }
  29122. }
  29123. <?php
  29124. namespace Symfony\Component\Finder\Iterator;
  29125. use Symfony\Component\Finder\Comparator\NumberComparator;
  29126. class SizeRangeFilterIterator extends FilterIterator
  29127. {
  29128. private $comparators = array();
  29129. public function __construct(\Iterator $iterator, array $comparators)
  29130. {
  29131. $this->comparators = $comparators;
  29132. parent::__construct($iterator);
  29133. }
  29134. public function accept()
  29135. {
  29136. $fileinfo = $this->current();
  29137. if (!$fileinfo->isFile()) {
  29138. return true;
  29139. }
  29140. $filesize = $fileinfo->getSize();
  29141. foreach ($this->comparators as $compare) {
  29142. if (!$compare->test($filesize)) {
  29143. return false;
  29144. }
  29145. }
  29146. return true;
  29147. }
  29148. }
  29149. <?php
  29150. namespace Symfony\Component\Finder\Iterator;
  29151. class SortableIterator implements \IteratorAggregate
  29152. {
  29153. const SORT_BY_NAME = 1;
  29154. const SORT_BY_TYPE = 2;
  29155. const SORT_BY_ACCESSED_TIME = 3;
  29156. const SORT_BY_CHANGED_TIME = 4;
  29157. const SORT_BY_MODIFIED_TIME = 5;
  29158. private $iterator;
  29159. private $sort;
  29160. public function __construct(\Traversable $iterator, $sort)
  29161. {
  29162. $this->iterator = $iterator;
  29163. if (self::SORT_BY_NAME === $sort) {
  29164. $this->sort = function ($a, $b) {
  29165. return strcmp($a->getRealpath(), $b->getRealpath());
  29166. };
  29167. } elseif (self::SORT_BY_TYPE === $sort) {
  29168. $this->sort = function ($a, $b) {
  29169. if ($a->isDir() && $b->isFile()) {
  29170. return -1;
  29171. } elseif ($a->isFile() && $b->isDir()) {
  29172. return 1;
  29173. }
  29174. return strcmp($a->getRealpath(), $b->getRealpath());
  29175. };
  29176. } elseif (self::SORT_BY_ACCESSED_TIME === $sort) {
  29177. $this->sort = function ($a, $b) {
  29178. return ($a->getATime() - $b->getATime());
  29179. };
  29180. } elseif (self::SORT_BY_CHANGED_TIME === $sort) {
  29181. $this->sort = function ($a, $b) {
  29182. return ($a->getCTime() - $b->getCTime());
  29183. };
  29184. } elseif (self::SORT_BY_MODIFIED_TIME === $sort) {
  29185. $this->sort = function ($a, $b) {
  29186. return ($a->getMTime() - $b->getMTime());
  29187. };
  29188. } elseif (is_callable($sort)) {
  29189. $this->sort = $sort;
  29190. } else {
  29191. throw new \InvalidArgumentException('The SortableIterator takes a PHP callable or a valid built-in sort algorithm as an argument.');
  29192. }
  29193. }
  29194. public function getIterator()
  29195. {
  29196. $array = iterator_to_array($this->iterator, true);
  29197. uasort($array, $this->sort);
  29198. return new \ArrayIterator($array);
  29199. }
  29200. }
  29201. Copyright (c) 2004-2015 Fabien Potencier
  29202. Permission is hereby granted, free of charge, to any person obtaining a copy
  29203. of this software and associated documentation files (the "Software"), to deal
  29204. in the Software without restriction, including without limitation the rights
  29205. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29206. copies of the Software, and to permit persons to whom the Software is furnished
  29207. to do so, subject to the following conditions:
  29208. The above copyright notice and this permission notice shall be included in all
  29209. copies or substantial portions of the Software.
  29210. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29211. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29212. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29213. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29214. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29215. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29216. THE SOFTWARE.
  29217. <?php
  29218. namespace Symfony\Component\Finder\Shell;
  29219. class Command
  29220. {
  29221. private $parent;
  29222. private $bits = array();
  29223. private $labels = array();
  29224. private $errorHandler;
  29225. public function __construct(Command $parent = null)
  29226. {
  29227. $this->parent = $parent;
  29228. }
  29229. public function __toString()
  29230. {
  29231. return $this->join();
  29232. }
  29233. public static function create(Command $parent = null)
  29234. {
  29235. return new self($parent);
  29236. }
  29237. public static function escape($input)
  29238. {
  29239. return escapeshellcmd($input);
  29240. }
  29241. public static function quote($input)
  29242. {
  29243. return escapeshellarg($input);
  29244. }
  29245. public function add($bit)
  29246. {
  29247. $this->bits[] = $bit;
  29248. return $this;
  29249. }
  29250. public function top($bit)
  29251. {
  29252. array_unshift($this->bits, $bit);
  29253. foreach ($this->labels as $label => $index) {
  29254. $this->labels[$label] += 1;
  29255. }
  29256. return $this;
  29257. }
  29258. public function arg($arg)
  29259. {
  29260. $this->bits[] = self::quote($arg);
  29261. return $this;
  29262. }
  29263. public function cmd($esc)
  29264. {
  29265. $this->bits[] = self::escape($esc);
  29266. return $this;
  29267. }
  29268. public function ins($label)
  29269. {
  29270. if (isset($this->labels[$label])) {
  29271. throw new \RuntimeException(sprintf('Label "%s" already exists.', $label));
  29272. }
  29273. $this->bits[] = self::create($this);
  29274. $this->labels[$label] = count($this->bits)-1;
  29275. return $this->bits[$this->labels[$label]];
  29276. }
  29277. public function get($label)
  29278. {
  29279. if (!isset($this->labels[$label])) {
  29280. throw new \RuntimeException(sprintf('Label "%s" does not exist.', $label));
  29281. }
  29282. return $this->bits[$this->labels[$label]];
  29283. }
  29284. public function end()
  29285. {
  29286. if (null === $this->parent) {
  29287. throw new \RuntimeException('Calling end on root command doesn\'t make sense.');
  29288. }
  29289. return $this->parent;
  29290. }
  29291. public function length()
  29292. {
  29293. return count($this->bits);
  29294. }
  29295. public function setErrorHandler(\Closure $errorHandler)
  29296. {
  29297. $this->errorHandler = $errorHandler;
  29298. return $this;
  29299. }
  29300. public function getErrorHandler()
  29301. {
  29302. return $this->errorHandler;
  29303. }
  29304. public function execute()
  29305. {
  29306. if (null === $errorHandler = $this->errorHandler) {
  29307. exec($this->join(), $output);
  29308. } else {
  29309. $process = proc_open($this->join(), array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w')), $pipes);
  29310. $output = preg_split('~(\r\n|\r|\n)~', stream_get_contents($pipes[1]), -1, PREG_SPLIT_NO_EMPTY);
  29311. if ($error = stream_get_contents($pipes[2])) {
  29312. $errorHandler($error);
  29313. }
  29314. proc_close($process);
  29315. }
  29316. return $output ?: array();
  29317. }
  29318. public function join()
  29319. {
  29320. return implode(' ', array_filter(
  29321. array_map(function ($bit) {
  29322. return $bit instanceof Command ? $bit->join() : ($bit ?: null);
  29323. }, $this->bits),
  29324. function ($bit) { return null !== $bit; }
  29325. ));
  29326. }
  29327. public function addAtIndex($bit, $index)
  29328. {
  29329. array_splice($this->bits, $index, 0, $bit);
  29330. return $this;
  29331. }
  29332. }
  29333. <?php
  29334. namespace Symfony\Component\Finder\Shell;
  29335. class Shell
  29336. {
  29337. const TYPE_UNIX = 1;
  29338. const TYPE_DARWIN = 2;
  29339. const TYPE_CYGWIN = 3;
  29340. const TYPE_WINDOWS = 4;
  29341. const TYPE_BSD = 5;
  29342. private $type;
  29343. public function getType()
  29344. {
  29345. if (null === $this->type) {
  29346. $this->type = $this->guessType();
  29347. }
  29348. return $this->type;
  29349. }
  29350. public function testCommand($command)
  29351. {
  29352. if (!function_exists('exec')) {
  29353. return false;
  29354. }
  29355. $testCommand = 'which ';
  29356. if (self::TYPE_WINDOWS === $this->type) {
  29357. $testCommand = 'where ';
  29358. }
  29359. $command = escapeshellcmd($command);
  29360. exec($testCommand.$command, $output, $code);
  29361. return 0 === $code && count($output) > 0;
  29362. }
  29363. private function guessType()
  29364. {
  29365. $os = strtolower(PHP_OS);
  29366. if (false !== strpos($os, 'cygwin')) {
  29367. return self::TYPE_CYGWIN;
  29368. }
  29369. if (false !== strpos($os, 'darwin')) {
  29370. return self::TYPE_DARWIN;
  29371. }
  29372. if (false !== strpos($os, 'bsd')) {
  29373. return self::TYPE_BSD;
  29374. }
  29375. if (0 === strpos($os, 'win')) {
  29376. return self::TYPE_WINDOWS;
  29377. }
  29378. return self::TYPE_UNIX;
  29379. }
  29380. }
  29381. <?php
  29382. namespace Symfony\Component\Finder;
  29383. class SplFileInfo extends \SplFileInfo
  29384. {
  29385. private $relativePath;
  29386. private $relativePathname;
  29387. public function __construct($file, $relativePath, $relativePathname)
  29388. {
  29389. parent::__construct($file);
  29390. $this->relativePath = $relativePath;
  29391. $this->relativePathname = $relativePathname;
  29392. }
  29393. public function getRelativePath()
  29394. {
  29395. return $this->relativePath;
  29396. }
  29397. public function getRelativePathname()
  29398. {
  29399. return $this->relativePathname;
  29400. }
  29401. public function getContents()
  29402. {
  29403. $level = error_reporting(0);
  29404. $content = file_get_contents($this->getPathname());
  29405. error_reporting($level);
  29406. if (false === $content) {
  29407. $error = error_get_last();
  29408. throw new \RuntimeException($error['message']);
  29409. }
  29410. return $content;
  29411. }
  29412. }
  29413. <?php
  29414. namespace Symfony\Component\Process\Exception;
  29415. interface ExceptionInterface
  29416. {
  29417. }
  29418. <?php
  29419. namespace Symfony\Component\Process\Exception;
  29420. class InvalidArgumentException extends \InvalidArgumentException implements ExceptionInterface
  29421. {
  29422. }
  29423. <?php
  29424. namespace Symfony\Component\Process\Exception;
  29425. class LogicException extends \LogicException implements ExceptionInterface
  29426. {
  29427. }
  29428. <?php
  29429. namespace Symfony\Component\Process\Exception;
  29430. use Symfony\Component\Process\Process;
  29431. class ProcessFailedException extends RuntimeException
  29432. {
  29433. private $process;
  29434. public function __construct(Process $process)
  29435. {
  29436. if ($process->isSuccessful()) {
  29437. throw new InvalidArgumentException('Expected a failed process, but the given process was successful.');
  29438. }
  29439. $error = sprintf('The command "%s" failed.'."\nExit Code: %s(%s)",
  29440. $process->getCommandLine(),
  29441. $process->getExitCode(),
  29442. $process->getExitCodeText()
  29443. );
  29444. if (!$process->isOutputDisabled()) {
  29445. $error .= sprintf("\n\nOutput:\n================\n%s\n\nError Output:\n================\n%s",
  29446. $process->getOutput(),
  29447. $process->getErrorOutput()
  29448. );
  29449. }
  29450. parent::__construct($error);
  29451. $this->process = $process;
  29452. }
  29453. public function getProcess()
  29454. {
  29455. return $this->process;
  29456. }
  29457. }
  29458. <?php
  29459. namespace Symfony\Component\Process\Exception;
  29460. use Symfony\Component\Process\Process;
  29461. class ProcessTimedOutException extends RuntimeException
  29462. {
  29463. const TYPE_GENERAL = 1;
  29464. const TYPE_IDLE = 2;
  29465. private $process;
  29466. private $timeoutType;
  29467. public function __construct(Process $process, $timeoutType)
  29468. {
  29469. $this->process = $process;
  29470. $this->timeoutType = $timeoutType;
  29471. parent::__construct(sprintf(
  29472. 'The process "%s" exceeded the timeout of %s seconds.',
  29473. $process->getCommandLine(),
  29474. $this->getExceededTimeout()
  29475. ));
  29476. }
  29477. public function getProcess()
  29478. {
  29479. return $this->process;
  29480. }
  29481. public function isGeneralTimeout()
  29482. {
  29483. return $this->timeoutType === self::TYPE_GENERAL;
  29484. }
  29485. public function isIdleTimeout()
  29486. {
  29487. return $this->timeoutType === self::TYPE_IDLE;
  29488. }
  29489. public function getExceededTimeout()
  29490. {
  29491. switch ($this->timeoutType) {
  29492. case self::TYPE_GENERAL:
  29493. return $this->process->getTimeout();
  29494. case self::TYPE_IDLE:
  29495. return $this->process->getIdleTimeout();
  29496. default:
  29497. throw new \LogicException(sprintf('Unknown timeout type "%d".', $this->timeoutType));
  29498. }
  29499. }
  29500. }
  29501. <?php
  29502. namespace Symfony\Component\Process\Exception;
  29503. class RuntimeException extends \RuntimeException implements ExceptionInterface
  29504. {
  29505. }
  29506. <?php
  29507. namespace Symfony\Component\Process;
  29508. class ExecutableFinder
  29509. {
  29510. private $suffixes = array('.exe', '.bat', '.cmd', '.com');
  29511. public function setSuffixes(array $suffixes)
  29512. {
  29513. $this->suffixes = $suffixes;
  29514. }
  29515. public function addSuffix($suffix)
  29516. {
  29517. $this->suffixes[] = $suffix;
  29518. }
  29519. public function find($name, $default = null, array $extraDirs = array())
  29520. {
  29521. if (ini_get('open_basedir')) {
  29522. $searchPath = explode(PATH_SEPARATOR, ini_get('open_basedir'));
  29523. $dirs = array();
  29524. foreach ($searchPath as $path) {
  29525. if (is_dir($path)) {
  29526. $dirs[] = $path;
  29527. } else {
  29528. if (basename($path) == $name && is_executable($path)) {
  29529. return $path;
  29530. }
  29531. }
  29532. }
  29533. } else {
  29534. $dirs = array_merge(
  29535. explode(PATH_SEPARATOR, getenv('PATH') ?: getenv('Path')),
  29536. $extraDirs
  29537. );
  29538. }
  29539. $suffixes = array('');
  29540. if ('\\' === DIRECTORY_SEPARATOR) {
  29541. $pathExt = getenv('PATHEXT');
  29542. $suffixes = $pathExt ? explode(PATH_SEPARATOR, $pathExt) : $this->suffixes;
  29543. }
  29544. foreach ($suffixes as $suffix) {
  29545. foreach ($dirs as $dir) {
  29546. if (is_file($file = $dir.DIRECTORY_SEPARATOR.$name.$suffix) && ('\\' === DIRECTORY_SEPARATOR || is_executable($file))) {
  29547. return $file;
  29548. }
  29549. }
  29550. }
  29551. return $default;
  29552. }
  29553. }
  29554. Copyright (c) 2004-2015 Fabien Potencier
  29555. Permission is hereby granted, free of charge, to any person obtaining a copy
  29556. of this software and associated documentation files (the "Software"), to deal
  29557. in the Software without restriction, including without limitation the rights
  29558. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  29559. copies of the Software, and to permit persons to whom the Software is furnished
  29560. to do so, subject to the following conditions:
  29561. The above copyright notice and this permission notice shall be included in all
  29562. copies or substantial portions of the Software.
  29563. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  29564. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  29565. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  29566. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  29567. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  29568. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  29569. THE SOFTWARE.
  29570. <?php
  29571. namespace Symfony\Component\Process;
  29572. class PhpExecutableFinder
  29573. {
  29574. private $executableFinder;
  29575. public function __construct()
  29576. {
  29577. $this->executableFinder = new ExecutableFinder();
  29578. }
  29579. public function find($includeArgs = true)
  29580. {
  29581. if (defined('HHVM_VERSION')) {
  29582. return (false !== ($hhvm = getenv('PHP_BINARY')) ? $hhvm : PHP_BINARY).($includeArgs ? ' '.implode(' ', $this->findArguments()) : '');
  29583. }
  29584. if (defined('PHP_BINARY') && PHP_BINARY && in_array(PHP_SAPI, array('cli', 'cli-server')) && is_file(PHP_BINARY)) {
  29585. return PHP_BINARY;
  29586. }
  29587. if ($php = getenv('PHP_PATH')) {
  29588. if (!is_executable($php)) {
  29589. return false;
  29590. }
  29591. return $php;
  29592. }
  29593. if ($php = getenv('PHP_PEAR_PHP_BIN')) {
  29594. if (is_executable($php)) {
  29595. return $php;
  29596. }
  29597. }
  29598. $dirs = array(PHP_BINDIR);
  29599. if ('\\' === DIRECTORY_SEPARATOR) {
  29600. $dirs[] = 'C:\xampp\php\\';
  29601. }
  29602. return $this->executableFinder->find('php', false, $dirs);
  29603. }
  29604. public function findArguments()
  29605. {
  29606. $arguments = array();
  29607. if (defined('HHVM_VERSION')) {
  29608. $arguments[] = '--php';
  29609. }
  29610. return $arguments;
  29611. }
  29612. }
  29613. <?php
  29614. namespace Symfony\Component\Process;
  29615. use Symfony\Component\Process\Exception\RuntimeException;
  29616. class PhpProcess extends Process
  29617. {
  29618. private $executableFinder;
  29619. public function __construct($script, $cwd = null, array $env = array(), $timeout = 60, array $options = array())
  29620. {
  29621. parent::__construct(null, $cwd, $env, $script, $timeout, $options);
  29622. $this->executableFinder = new PhpExecutableFinder();
  29623. }
  29624. public function setPhpBinary($php)
  29625. {
  29626. $this->setCommandLine($php);
  29627. }
  29628. public function start($callback = null)
  29629. {
  29630. if (null === $this->getCommandLine()) {
  29631. if (false === $php = $this->executableFinder->find()) {
  29632. throw new RuntimeException('Unable to find the PHP executable.');
  29633. }
  29634. $this->setCommandLine($php);
  29635. }
  29636. parent::start($callback);
  29637. }
  29638. }
  29639. <?php
  29640. namespace Symfony\Component\Process\Pipes;
  29641. abstract class AbstractPipes implements PipesInterface
  29642. {
  29643. public $pipes = array();
  29644. protected $inputBuffer = '';
  29645. protected $input;
  29646. private $blocked = true;
  29647. public function close()
  29648. {
  29649. foreach ($this->pipes as $pipe) {
  29650. fclose($pipe);
  29651. }
  29652. $this->pipes = array();
  29653. }
  29654. protected function hasSystemCallBeenInterrupted()
  29655. {
  29656. $lastError = error_get_last();
  29657. return isset($lastError['message']) && false !== stripos($lastError['message'], 'interrupted system call');
  29658. }
  29659. protected function unblock()
  29660. {
  29661. if (!$this->blocked) {
  29662. return;
  29663. }
  29664. foreach ($this->pipes as $pipe) {
  29665. stream_set_blocking($pipe, 0);
  29666. }
  29667. if (null !== $this->input) {
  29668. stream_set_blocking($this->input, 0);
  29669. }
  29670. $this->blocked = false;
  29671. }
  29672. }
  29673. <?php
  29674. namespace Symfony\Component\Process\Pipes;
  29675. interface PipesInterface
  29676. {
  29677. const CHUNK_SIZE = 16384;
  29678. public function getDescriptors();
  29679. public function getFiles();
  29680. public function readAndWrite($blocking, $close = false);
  29681. public function areOpen();
  29682. public function close();
  29683. }
  29684. <?php
  29685. namespace Symfony\Component\Process\Pipes;
  29686. use Symfony\Component\Process\Process;
  29687. class UnixPipes extends AbstractPipes
  29688. {
  29689. private $ttyMode;
  29690. private $ptyMode;
  29691. private $disableOutput;
  29692. public function __construct($ttyMode, $ptyMode, $input, $disableOutput)
  29693. {
  29694. $this->ttyMode = (bool) $ttyMode;
  29695. $this->ptyMode = (bool) $ptyMode;
  29696. $this->disableOutput = (bool) $disableOutput;
  29697. if (is_resource($input)) {
  29698. $this->input = $input;
  29699. } else {
  29700. $this->inputBuffer = (string) $input;
  29701. }
  29702. }
  29703. public function __destruct()
  29704. {
  29705. $this->close();
  29706. }
  29707. public function getDescriptors()
  29708. {
  29709. if ($this->disableOutput) {
  29710. $nullstream = fopen('/dev/null', 'c');
  29711. return array(
  29712. array('pipe', 'r'),
  29713. $nullstream,
  29714. $nullstream,
  29715. );
  29716. }
  29717. if ($this->ttyMode) {
  29718. return array(
  29719. array('file', '/dev/tty', 'r'),
  29720. array('file', '/dev/tty', 'w'),
  29721. array('file', '/dev/tty', 'w'),
  29722. );
  29723. }
  29724. if ($this->ptyMode && Process::isPtySupported()) {
  29725. return array(
  29726. array('pty'),
  29727. array('pty'),
  29728. array('pty'),
  29729. );
  29730. }
  29731. return array(
  29732. array('pipe', 'r'),
  29733. array('pipe', 'w'),
  29734. array('pipe', 'w'),
  29735. );
  29736. }
  29737. public function getFiles()
  29738. {
  29739. return array();
  29740. }
  29741. public function readAndWrite($blocking, $close = false)
  29742. {
  29743. if (1 === count($this->pipes) && array(0) === array_keys($this->pipes)) {
  29744. fclose($this->pipes[0]);
  29745. unset($this->pipes[0]);
  29746. }
  29747. if (empty($this->pipes)) {
  29748. return array();
  29749. }
  29750. $this->unblock();
  29751. $read = array();
  29752. if (null !== $this->input) {
  29753. $r = array_merge($this->pipes, array('input' => $this->input));
  29754. } else {
  29755. $r = $this->pipes;
  29756. }
  29757. unset($r[0]);
  29758. $w = isset($this->pipes[0]) ? array($this->pipes[0]) : null;
  29759. $e = null;
  29760. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
  29761. if (!$this->hasSystemCallBeenInterrupted()) {
  29762. $this->pipes = array();
  29763. }
  29764. return $read;
  29765. }
  29766. if (0 === $n) {
  29767. return $read;
  29768. }
  29769. foreach ($r as $pipe) {
  29770. $type = (false !== $found = array_search($pipe, $this->pipes)) ? $found : 'input';
  29771. $data = '';
  29772. while ('' !== $dataread = (string) fread($pipe, self::CHUNK_SIZE)) {
  29773. $data .= $dataread;
  29774. }
  29775. if ('' !== $data) {
  29776. if ($type === 'input') {
  29777. $this->inputBuffer .= $data;
  29778. } else {
  29779. $read[$type] = $data;
  29780. }
  29781. }
  29782. if (false === $data || (true === $close && feof($pipe) && '' === $data)) {
  29783. if ($type === 'input') {
  29784. $this->input = null;
  29785. } else {
  29786. fclose($this->pipes[$type]);
  29787. unset($this->pipes[$type]);
  29788. }
  29789. }
  29790. }
  29791. if (null !== $w && 0 < count($w)) {
  29792. while (strlen($this->inputBuffer)) {
  29793. $written = fwrite($w[0], $this->inputBuffer, 2 << 18);
  29794. if ($written > 0) {
  29795. $this->inputBuffer = (string) substr($this->inputBuffer, $written);
  29796. } else {
  29797. break;
  29798. }
  29799. }
  29800. }
  29801. if ('' === $this->inputBuffer && null === $this->input && isset($this->pipes[0])) {
  29802. fclose($this->pipes[0]);
  29803. unset($this->pipes[0]);
  29804. }
  29805. return $read;
  29806. }
  29807. public function areOpen()
  29808. {
  29809. return (bool) $this->pipes;
  29810. }
  29811. public static function create(Process $process, $input)
  29812. {
  29813. return new static($process->isTty(), $process->isPty(), $input, $process->isOutputDisabled());
  29814. }
  29815. }
  29816. <?php
  29817. namespace Symfony\Component\Process\Pipes;
  29818. use Symfony\Component\Process\Process;
  29819. use Symfony\Component\Process\Exception\RuntimeException;
  29820. class WindowsPipes extends AbstractPipes
  29821. {
  29822. private $files = array();
  29823. private $fileHandles = array();
  29824. private $readBytes = array(
  29825. Process::STDOUT => 0,
  29826. Process::STDERR => 0,
  29827. );
  29828. private $disableOutput;
  29829. public function __construct($disableOutput, $input)
  29830. {
  29831. $this->disableOutput = (bool) $disableOutput;
  29832. if (!$this->disableOutput) {
  29833. $this->files = array(
  29834. Process::STDOUT => tempnam(sys_get_temp_dir(), 'sf_proc_stdout'),
  29835. Process::STDERR => tempnam(sys_get_temp_dir(), 'sf_proc_stderr'),
  29836. );
  29837. foreach ($this->files as $offset => $file) {
  29838. $this->fileHandles[$offset] = fopen($this->files[$offset], 'rb');
  29839. if (false === $this->fileHandles[$offset]) {
  29840. throw new RuntimeException('A temporary file could not be opened to write the process output to, verify that your TEMP environment variable is writable');
  29841. }
  29842. }
  29843. }
  29844. if (is_resource($input)) {
  29845. $this->input = $input;
  29846. } else {
  29847. $this->inputBuffer = $input;
  29848. }
  29849. }
  29850. public function __destruct()
  29851. {
  29852. $this->close();
  29853. $this->removeFiles();
  29854. }
  29855. public function getDescriptors()
  29856. {
  29857. if ($this->disableOutput) {
  29858. $nullstream = fopen('NUL', 'c');
  29859. return array(
  29860. array('pipe', 'r'),
  29861. $nullstream,
  29862. $nullstream,
  29863. );
  29864. }
  29865. return array(
  29866. array('pipe', 'r'),
  29867. array('file', 'NUL', 'w'),
  29868. array('file', 'NUL', 'w'),
  29869. );
  29870. }
  29871. public function getFiles()
  29872. {
  29873. return $this->files;
  29874. }
  29875. public function readAndWrite($blocking, $close = false)
  29876. {
  29877. $this->write($blocking, $close);
  29878. $read = array();
  29879. $fh = $this->fileHandles;
  29880. foreach ($fh as $type => $fileHandle) {
  29881. if (0 !== fseek($fileHandle, $this->readBytes[$type])) {
  29882. continue;
  29883. }
  29884. $data = '';
  29885. $dataread = null;
  29886. while (!feof($fileHandle)) {
  29887. if (false !== $dataread = fread($fileHandle, self::CHUNK_SIZE)) {
  29888. $data .= $dataread;
  29889. }
  29890. }
  29891. if (0 < $length = strlen($data)) {
  29892. $this->readBytes[$type] += $length;
  29893. $read[$type] = $data;
  29894. }
  29895. if (false === $dataread || (true === $close && feof($fileHandle) && '' === $data)) {
  29896. fclose($this->fileHandles[$type]);
  29897. unset($this->fileHandles[$type]);
  29898. }
  29899. }
  29900. return $read;
  29901. }
  29902. public function areOpen()
  29903. {
  29904. return (bool) $this->pipes && (bool) $this->fileHandles;
  29905. }
  29906. public function close()
  29907. {
  29908. parent::close();
  29909. foreach ($this->fileHandles as $handle) {
  29910. fclose($handle);
  29911. }
  29912. $this->fileHandles = array();
  29913. }
  29914. public static function create(Process $process, $input)
  29915. {
  29916. return new static($process->isOutputDisabled(), $input);
  29917. }
  29918. private function removeFiles()
  29919. {
  29920. foreach ($this->files as $filename) {
  29921. if (file_exists($filename)) {
  29922. @unlink($filename);
  29923. }
  29924. }
  29925. $this->files = array();
  29926. }
  29927. private function write($blocking, $close)
  29928. {
  29929. if (empty($this->pipes)) {
  29930. return;
  29931. }
  29932. $this->unblock();
  29933. $r = null !== $this->input ? array('input' => $this->input) : null;
  29934. $w = isset($this->pipes[0]) ? array($this->pipes[0]) : null;
  29935. $e = null;
  29936. if (false === $n = @stream_select($r, $w, $e, 0, $blocking ? Process::TIMEOUT_PRECISION * 1E6 : 0)) {
  29937. if (!$this->hasSystemCallBeenInterrupted()) {
  29938. $this->pipes = array();
  29939. }
  29940. return;
  29941. }
  29942. if (0 === $n) {
  29943. return;
  29944. }
  29945. if (null !== $w && 0 < count($r)) {
  29946. $data = '';
  29947. while ($dataread = fread($r['input'], self::CHUNK_SIZE)) {
  29948. $data .= $dataread;
  29949. }
  29950. $this->inputBuffer .= $data;
  29951. if (false === $data || (true === $close && feof($r['input']) && '' === $data)) {
  29952. $this->input = null;
  29953. }
  29954. }
  29955. if (null !== $w && 0 < count($w)) {
  29956. while (strlen($this->inputBuffer)) {
  29957. $written = fwrite($w[0], $this->inputBuffer, 2 << 18);
  29958. if ($written > 0) {
  29959. $this->inputBuffer = (string) substr($this->inputBuffer, $written);
  29960. } else {
  29961. break;
  29962. }
  29963. }
  29964. }
  29965. if ('' === $this->inputBuffer && null === $this->input && isset($this->pipes[0])) {
  29966. fclose($this->pipes[0]);
  29967. unset($this->pipes[0]);
  29968. }
  29969. }
  29970. }
  29971. <?php
  29972. namespace Symfony\Component\Process;
  29973. use Symfony\Component\Process\Exception\InvalidArgumentException;
  29974. use Symfony\Component\Process\Exception\LogicException;
  29975. use Symfony\Component\Process\Exception\ProcessFailedException;
  29976. use Symfony\Component\Process\Exception\ProcessTimedOutException;
  29977. use Symfony\Component\Process\Exception\RuntimeException;
  29978. use Symfony\Component\Process\Pipes\PipesInterface;
  29979. use Symfony\Component\Process\Pipes\UnixPipes;
  29980. use Symfony\Component\Process\Pipes\WindowsPipes;
  29981. class Process
  29982. {
  29983. const ERR = 'err';
  29984. const OUT = 'out';
  29985. const STATUS_READY = 'ready';
  29986. const STATUS_STARTED = 'started';
  29987. const STATUS_TERMINATED = 'terminated';
  29988. const STDIN = 0;
  29989. const STDOUT = 1;
  29990. const STDERR = 2;
  29991. const TIMEOUT_PRECISION = 0.2;
  29992. private $callback;
  29993. private $commandline;
  29994. private $cwd;
  29995. private $env;
  29996. private $input;
  29997. private $starttime;
  29998. private $lastOutputTime;
  29999. private $timeout;
  30000. private $idleTimeout;
  30001. private $options;
  30002. private $exitcode;
  30003. private $fallbackExitcode;
  30004. private $processInformation;
  30005. private $outputDisabled = false;
  30006. private $stdout;
  30007. private $stderr;
  30008. private $enhanceWindowsCompatibility = true;
  30009. private $enhanceSigchildCompatibility;
  30010. private $process;
  30011. private $status = self::STATUS_READY;
  30012. private $incrementalOutputOffset = 0;
  30013. private $incrementalErrorOutputOffset = 0;
  30014. private $tty;
  30015. private $pty;
  30016. private $useFileHandles = false;
  30017. private $processPipes;
  30018. private $latestSignal;
  30019. private static $sigchild;
  30020. public static $exitCodes = array(
  30021. 0 => 'OK',
  30022. 1 => 'General error',
  30023. 2 => 'Misuse of shell builtins',
  30024. 126 => 'Invoked command cannot execute',
  30025. 127 => 'Command not found',
  30026. 128 => 'Invalid exit argument',
  30027. 129 => 'Hangup',
  30028. 130 => 'Interrupt',
  30029. 131 => 'Quit and dump core',
  30030. 132 => 'Illegal instruction',
  30031. 133 => 'Trace/breakpoint trap',
  30032. 134 => 'Process aborted',
  30033. 135 => 'Bus error: "access to undefined portion of memory object"',
  30034. 136 => 'Floating point exception: "erroneous arithmetic operation"',
  30035. 137 => 'Kill (terminate immediately)',
  30036. 138 => 'User-defined 1',
  30037. 139 => 'Segmentation violation',
  30038. 140 => 'User-defined 2',
  30039. 141 => 'Write to pipe with no one reading',
  30040. 142 => 'Signal raised by alarm',
  30041. 143 => 'Termination (request to terminate)',
  30042. 145 => 'Child process terminated, stopped (or continued*)',
  30043. 146 => 'Continue if stopped',
  30044. 147 => 'Stop executing temporarily',
  30045. 148 => 'Terminal stop signal',
  30046. 149 => 'Background process attempting to read from tty ("in")',
  30047. 150 => 'Background process attempting to write to tty ("out")',
  30048. 151 => 'Urgent data available on socket',
  30049. 152 => 'CPU time limit exceeded',
  30050. 153 => 'File size limit exceeded',
  30051. 154 => 'Signal raised by timer counting virtual time: "virtual timer expired"',
  30052. 155 => 'Profiling timer expired',
  30053. 157 => 'Pollable event',
  30054. 159 => 'Bad syscall',
  30055. );
  30056. public function __construct($commandline, $cwd = null, array $env = null, $input = null, $timeout = 60, array $options = array())
  30057. {
  30058. if (!function_exists('proc_open')) {
  30059. throw new RuntimeException('The Process class relies on proc_open, which is not available on your PHP installation.');
  30060. }
  30061. $this->commandline = $commandline;
  30062. $this->cwd = $cwd;
  30063. if (null === $this->cwd && (defined('ZEND_THREAD_SAFE') || '\\' === DIRECTORY_SEPARATOR)) {
  30064. $this->cwd = getcwd();
  30065. }
  30066. if (null !== $env) {
  30067. $this->setEnv($env);
  30068. }
  30069. $this->input = $input;
  30070. $this->setTimeout($timeout);
  30071. $this->useFileHandles = '\\' === DIRECTORY_SEPARATOR;
  30072. $this->pty = false;
  30073. $this->enhanceWindowsCompatibility = true;
  30074. $this->enhanceSigchildCompatibility = '\\' !== DIRECTORY_SEPARATOR && $this->isSigchildEnabled();
  30075. $this->options = array_replace(array('suppress_errors' => true, 'binary_pipes' => true), $options);
  30076. }
  30077. public function __destruct()
  30078. {
  30079. $this->stop();
  30080. }
  30081. public function __clone()
  30082. {
  30083. $this->resetProcessData();
  30084. }
  30085. public function run($callback = null)
  30086. {
  30087. $this->start($callback);
  30088. return $this->wait();
  30089. }
  30090. public function mustRun($callback = null)
  30091. {
  30092. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  30093. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  30094. }
  30095. if (0 !== $this->run($callback)) {
  30096. throw new ProcessFailedException($this);
  30097. }
  30098. return $this;
  30099. }
  30100. public function start($callback = null)
  30101. {
  30102. if ($this->isRunning()) {
  30103. throw new RuntimeException('Process is already running');
  30104. }
  30105. if ($this->outputDisabled && null !== $callback) {
  30106. throw new LogicException('Output has been disabled, enable it to allow the use of a callback.');
  30107. }
  30108. $this->resetProcessData();
  30109. $this->starttime = $this->lastOutputTime = microtime(true);
  30110. $this->callback = $this->buildCallback($callback);
  30111. $descriptors = $this->getDescriptors();
  30112. $commandline = $this->commandline;
  30113. if ('\\' === DIRECTORY_SEPARATOR && $this->enhanceWindowsCompatibility) {
  30114. $commandline = 'cmd /V:ON /E:ON /C "('.$commandline.')';
  30115. foreach ($this->processPipes->getFiles() as $offset => $filename) {
  30116. $commandline .= ' '.$offset.'>'.ProcessUtils::escapeArgument($filename);
  30117. }
  30118. $commandline .= '"';
  30119. if (!isset($this->options['bypass_shell'])) {
  30120. $this->options['bypass_shell'] = true;
  30121. }
  30122. }
  30123. $this->process = proc_open($commandline, $descriptors, $this->processPipes->pipes, $this->cwd, $this->env, $this->options);
  30124. if (!is_resource($this->process)) {
  30125. throw new RuntimeException('Unable to launch a new process.');
  30126. }
  30127. $this->status = self::STATUS_STARTED;
  30128. if ($this->tty) {
  30129. return;
  30130. }
  30131. $this->updateStatus(false);
  30132. $this->checkTimeout();
  30133. }
  30134. public function restart($callback = null)
  30135. {
  30136. if ($this->isRunning()) {
  30137. throw new RuntimeException('Process is already running');
  30138. }
  30139. $process = clone $this;
  30140. $process->start($callback);
  30141. return $process;
  30142. }
  30143. public function wait($callback = null)
  30144. {
  30145. $this->requireProcessIsStarted(__FUNCTION__);
  30146. $this->updateStatus(false);
  30147. if (null !== $callback) {
  30148. $this->callback = $this->buildCallback($callback);
  30149. }
  30150. do {
  30151. $this->checkTimeout();
  30152. $running = '\\' === DIRECTORY_SEPARATOR ? $this->isRunning() : $this->processPipes->areOpen();
  30153. $close = '\\' !== DIRECTORY_SEPARATOR || !$running;
  30154. $this->readPipes(true, $close);
  30155. } while ($running);
  30156. while ($this->isRunning()) {
  30157. usleep(1000);
  30158. }
  30159. if ($this->processInformation['signaled'] && $this->processInformation['termsig'] !== $this->latestSignal) {
  30160. throw new RuntimeException(sprintf('The process has been signaled with signal "%s".', $this->processInformation['termsig']));
  30161. }
  30162. return $this->exitcode;
  30163. }
  30164. public function getPid()
  30165. {
  30166. if ($this->isSigchildEnabled()) {
  30167. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process identifier can not be retrieved.');
  30168. }
  30169. $this->updateStatus(false);
  30170. return $this->isRunning() ? $this->processInformation['pid'] : null;
  30171. }
  30172. public function signal($signal)
  30173. {
  30174. $this->doSignal($signal, true);
  30175. return $this;
  30176. }
  30177. public function disableOutput()
  30178. {
  30179. if ($this->isRunning()) {
  30180. throw new RuntimeException('Disabling output while the process is running is not possible.');
  30181. }
  30182. if (null !== $this->idleTimeout) {
  30183. throw new LogicException('Output can not be disabled while an idle timeout is set.');
  30184. }
  30185. $this->outputDisabled = true;
  30186. return $this;
  30187. }
  30188. public function enableOutput()
  30189. {
  30190. if ($this->isRunning()) {
  30191. throw new RuntimeException('Enabling output while the process is running is not possible.');
  30192. }
  30193. $this->outputDisabled = false;
  30194. return $this;
  30195. }
  30196. public function isOutputDisabled()
  30197. {
  30198. return $this->outputDisabled;
  30199. }
  30200. public function getOutput()
  30201. {
  30202. if ($this->outputDisabled) {
  30203. throw new LogicException('Output has been disabled.');
  30204. }
  30205. $this->requireProcessIsStarted(__FUNCTION__);
  30206. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  30207. return $this->stdout;
  30208. }
  30209. public function getIncrementalOutput()
  30210. {
  30211. $this->requireProcessIsStarted(__FUNCTION__);
  30212. $data = $this->getOutput();
  30213. $latest = substr($data, $this->incrementalOutputOffset);
  30214. if (false === $latest) {
  30215. return '';
  30216. }
  30217. $this->incrementalOutputOffset = strlen($data);
  30218. return $latest;
  30219. }
  30220. public function clearOutput()
  30221. {
  30222. $this->stdout = '';
  30223. $this->incrementalOutputOffset = 0;
  30224. return $this;
  30225. }
  30226. public function getErrorOutput()
  30227. {
  30228. if ($this->outputDisabled) {
  30229. throw new LogicException('Output has been disabled.');
  30230. }
  30231. $this->requireProcessIsStarted(__FUNCTION__);
  30232. $this->readPipes(false, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  30233. return $this->stderr;
  30234. }
  30235. public function getIncrementalErrorOutput()
  30236. {
  30237. $this->requireProcessIsStarted(__FUNCTION__);
  30238. $data = $this->getErrorOutput();
  30239. $latest = substr($data, $this->incrementalErrorOutputOffset);
  30240. if (false === $latest) {
  30241. return '';
  30242. }
  30243. $this->incrementalErrorOutputOffset = strlen($data);
  30244. return $latest;
  30245. }
  30246. public function clearErrorOutput()
  30247. {
  30248. $this->stderr = '';
  30249. $this->incrementalErrorOutputOffset = 0;
  30250. return $this;
  30251. }
  30252. public function getExitCode()
  30253. {
  30254. if ($this->isSigchildEnabled() && !$this->enhanceSigchildCompatibility) {
  30255. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. You must use setEnhanceSigchildCompatibility() to use this method.');
  30256. }
  30257. $this->updateStatus(false);
  30258. return $this->exitcode;
  30259. }
  30260. public function getExitCodeText()
  30261. {
  30262. if (null === $exitcode = $this->getExitCode()) {
  30263. return;
  30264. }
  30265. return isset(self::$exitCodes[$exitcode]) ? self::$exitCodes[$exitcode] : 'Unknown error';
  30266. }
  30267. public function isSuccessful()
  30268. {
  30269. return 0 === $this->getExitCode();
  30270. }
  30271. public function hasBeenSignaled()
  30272. {
  30273. $this->requireProcessIsTerminated(__FUNCTION__);
  30274. if ($this->isSigchildEnabled()) {
  30275. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  30276. }
  30277. $this->updateStatus(false);
  30278. return $this->processInformation['signaled'];
  30279. }
  30280. public function getTermSignal()
  30281. {
  30282. $this->requireProcessIsTerminated(__FUNCTION__);
  30283. if ($this->isSigchildEnabled()) {
  30284. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. Term signal can not be retrieved.');
  30285. }
  30286. $this->updateStatus(false);
  30287. return $this->processInformation['termsig'];
  30288. }
  30289. public function hasBeenStopped()
  30290. {
  30291. $this->requireProcessIsTerminated(__FUNCTION__);
  30292. $this->updateStatus(false);
  30293. return $this->processInformation['stopped'];
  30294. }
  30295. public function getStopSignal()
  30296. {
  30297. $this->requireProcessIsTerminated(__FUNCTION__);
  30298. $this->updateStatus(false);
  30299. return $this->processInformation['stopsig'];
  30300. }
  30301. public function isRunning()
  30302. {
  30303. if (self::STATUS_STARTED !== $this->status) {
  30304. return false;
  30305. }
  30306. $this->updateStatus(false);
  30307. return $this->processInformation['running'];
  30308. }
  30309. public function isStarted()
  30310. {
  30311. return $this->status != self::STATUS_READY;
  30312. }
  30313. public function isTerminated()
  30314. {
  30315. $this->updateStatus(false);
  30316. return $this->status == self::STATUS_TERMINATED;
  30317. }
  30318. public function getStatus()
  30319. {
  30320. $this->updateStatus(false);
  30321. return $this->status;
  30322. }
  30323. public function stop($timeout = 10, $signal = null)
  30324. {
  30325. $timeoutMicro = microtime(true) + $timeout;
  30326. if ($this->isRunning()) {
  30327. if ('\\' === DIRECTORY_SEPARATOR && !$this->isSigchildEnabled()) {
  30328. exec(sprintf("taskkill /F /T /PID %d 2>&1", $this->getPid()), $output, $exitCode);
  30329. if ($exitCode > 0) {
  30330. throw new RuntimeException('Unable to kill the process');
  30331. }
  30332. }
  30333. $this->doSignal(15, false);
  30334. do {
  30335. usleep(1000);
  30336. } while ($this->isRunning() && microtime(true) < $timeoutMicro);
  30337. if ($this->isRunning() && !$this->isSigchildEnabled()) {
  30338. if (null !== $signal || defined('SIGKILL')) {
  30339. $this->doSignal($signal ?: SIGKILL, false);
  30340. }
  30341. }
  30342. }
  30343. $this->updateStatus(false);
  30344. if ($this->processInformation['running']) {
  30345. $this->close();
  30346. }
  30347. return $this->exitcode;
  30348. }
  30349. public function addOutput($line)
  30350. {
  30351. $this->lastOutputTime = microtime(true);
  30352. $this->stdout .= $line;
  30353. }
  30354. public function addErrorOutput($line)
  30355. {
  30356. $this->lastOutputTime = microtime(true);
  30357. $this->stderr .= $line;
  30358. }
  30359. public function getCommandLine()
  30360. {
  30361. return $this->commandline;
  30362. }
  30363. public function setCommandLine($commandline)
  30364. {
  30365. $this->commandline = $commandline;
  30366. return $this;
  30367. }
  30368. public function getTimeout()
  30369. {
  30370. return $this->timeout;
  30371. }
  30372. public function getIdleTimeout()
  30373. {
  30374. return $this->idleTimeout;
  30375. }
  30376. public function setTimeout($timeout)
  30377. {
  30378. $this->timeout = $this->validateTimeout($timeout);
  30379. return $this;
  30380. }
  30381. public function setIdleTimeout($timeout)
  30382. {
  30383. if (null !== $timeout && $this->outputDisabled) {
  30384. throw new LogicException('Idle timeout can not be set while the output is disabled.');
  30385. }
  30386. $this->idleTimeout = $this->validateTimeout($timeout);
  30387. return $this;
  30388. }
  30389. public function setTty($tty)
  30390. {
  30391. if ('\\' === DIRECTORY_SEPARATOR && $tty) {
  30392. throw new RuntimeException('TTY mode is not supported on Windows platform.');
  30393. }
  30394. $this->tty = (bool) $tty;
  30395. return $this;
  30396. }
  30397. public function isTty()
  30398. {
  30399. return $this->tty;
  30400. }
  30401. public function setPty($bool)
  30402. {
  30403. $this->pty = (bool) $bool;
  30404. return $this;
  30405. }
  30406. public function isPty()
  30407. {
  30408. return $this->pty;
  30409. }
  30410. public function getWorkingDirectory()
  30411. {
  30412. if (null === $this->cwd) {
  30413. return getcwd() ?: null;
  30414. }
  30415. return $this->cwd;
  30416. }
  30417. public function setWorkingDirectory($cwd)
  30418. {
  30419. $this->cwd = $cwd;
  30420. return $this;
  30421. }
  30422. public function getEnv()
  30423. {
  30424. return $this->env;
  30425. }
  30426. public function setEnv(array $env)
  30427. {
  30428. $env = array_filter($env, function ($value) {
  30429. return !is_array($value);
  30430. });
  30431. $this->env = array();
  30432. foreach ($env as $key => $value) {
  30433. $this->env[(binary) $key] = (binary) $value;
  30434. }
  30435. return $this;
  30436. }
  30437. public function getStdin()
  30438. {
  30439. return $this->getInput();
  30440. }
  30441. public function getInput()
  30442. {
  30443. return $this->input;
  30444. }
  30445. public function setStdin($stdin)
  30446. {
  30447. return $this->setInput($stdin);
  30448. }
  30449. public function setInput($input)
  30450. {
  30451. if ($this->isRunning()) {
  30452. throw new LogicException('Input can not be set while the process is running.');
  30453. }
  30454. $this->input = ProcessUtils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
  30455. return $this;
  30456. }
  30457. public function getOptions()
  30458. {
  30459. return $this->options;
  30460. }
  30461. public function setOptions(array $options)
  30462. {
  30463. $this->options = $options;
  30464. return $this;
  30465. }
  30466. public function getEnhanceWindowsCompatibility()
  30467. {
  30468. return $this->enhanceWindowsCompatibility;
  30469. }
  30470. public function setEnhanceWindowsCompatibility($enhance)
  30471. {
  30472. $this->enhanceWindowsCompatibility = (bool) $enhance;
  30473. return $this;
  30474. }
  30475. public function getEnhanceSigchildCompatibility()
  30476. {
  30477. return $this->enhanceSigchildCompatibility;
  30478. }
  30479. public function setEnhanceSigchildCompatibility($enhance)
  30480. {
  30481. $this->enhanceSigchildCompatibility = (bool) $enhance;
  30482. return $this;
  30483. }
  30484. public function checkTimeout()
  30485. {
  30486. if ($this->status !== self::STATUS_STARTED) {
  30487. return;
  30488. }
  30489. if (null !== $this->timeout && $this->timeout < microtime(true) - $this->starttime) {
  30490. $this->stop(0);
  30491. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_GENERAL);
  30492. }
  30493. if (null !== $this->idleTimeout && $this->idleTimeout < microtime(true) - $this->lastOutputTime) {
  30494. $this->stop(0);
  30495. throw new ProcessTimedOutException($this, ProcessTimedOutException::TYPE_IDLE);
  30496. }
  30497. }
  30498. public static function isPtySupported()
  30499. {
  30500. static $result;
  30501. if (null !== $result) {
  30502. return $result;
  30503. }
  30504. if ('\\' === DIRECTORY_SEPARATOR) {
  30505. return $result = false;
  30506. }
  30507. $proc = @proc_open('echo 1', array(array('pty'), array('pty'), array('pty')), $pipes);
  30508. if (is_resource($proc)) {
  30509. proc_close($proc);
  30510. return $result = true;
  30511. }
  30512. return $result = false;
  30513. }
  30514. private function getDescriptors()
  30515. {
  30516. if ('\\' === DIRECTORY_SEPARATOR) {
  30517. $this->processPipes = WindowsPipes::create($this, $this->input);
  30518. } else {
  30519. $this->processPipes = UnixPipes::create($this, $this->input);
  30520. }
  30521. $descriptors = $this->processPipes->getDescriptors($this->outputDisabled);
  30522. if (!$this->useFileHandles && $this->enhanceSigchildCompatibility && $this->isSigchildEnabled()) {
  30523. $descriptors = array_merge($descriptors, array(array('pipe', 'w')));
  30524. $this->commandline = '('.$this->commandline.') 3>/dev/null; code=$?; echo $code >&3; exit $code';
  30525. }
  30526. return $descriptors;
  30527. }
  30528. protected function buildCallback($callback)
  30529. {
  30530. $that = $this;
  30531. $out = self::OUT;
  30532. $callback = function ($type, $data) use ($that, $callback, $out) {
  30533. if ($out == $type) {
  30534. $that->addOutput($data);
  30535. } else {
  30536. $that->addErrorOutput($data);
  30537. }
  30538. if (null !== $callback) {
  30539. call_user_func($callback, $type, $data);
  30540. }
  30541. };
  30542. return $callback;
  30543. }
  30544. protected function updateStatus($blocking)
  30545. {
  30546. if (self::STATUS_STARTED !== $this->status) {
  30547. return;
  30548. }
  30549. $this->processInformation = proc_get_status($this->process);
  30550. $this->captureExitCode();
  30551. $this->readPipes($blocking, '\\' === DIRECTORY_SEPARATOR ? !$this->processInformation['running'] : true);
  30552. if (!$this->processInformation['running']) {
  30553. $this->close();
  30554. }
  30555. }
  30556. protected function isSigchildEnabled()
  30557. {
  30558. if (null !== self::$sigchild) {
  30559. return self::$sigchild;
  30560. }
  30561. if (!function_exists('phpinfo')) {
  30562. return self::$sigchild = false;
  30563. }
  30564. ob_start();
  30565. phpinfo(INFO_GENERAL);
  30566. return self::$sigchild = false !== strpos(ob_get_clean(), '--enable-sigchild');
  30567. }
  30568. private function validateTimeout($timeout)
  30569. {
  30570. $timeout = (float) $timeout;
  30571. if (0.0 === $timeout) {
  30572. $timeout = null;
  30573. } elseif ($timeout < 0) {
  30574. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  30575. }
  30576. return $timeout;
  30577. }
  30578. private function readPipes($blocking, $close)
  30579. {
  30580. $result = $this->processPipes->readAndWrite($blocking, $close);
  30581. $callback = $this->callback;
  30582. foreach ($result as $type => $data) {
  30583. if (3 == $type) {
  30584. $this->fallbackExitcode = (int) $data;
  30585. } else {
  30586. $callback($type === self::STDOUT ? self::OUT : self::ERR, $data);
  30587. }
  30588. }
  30589. }
  30590. private function captureExitCode()
  30591. {
  30592. if (isset($this->processInformation['exitcode']) && -1 != $this->processInformation['exitcode']) {
  30593. $this->exitcode = $this->processInformation['exitcode'];
  30594. }
  30595. }
  30596. private function close()
  30597. {
  30598. $this->processPipes->close();
  30599. if (is_resource($this->process)) {
  30600. $exitcode = proc_close($this->process);
  30601. } else {
  30602. $exitcode = -1;
  30603. }
  30604. $this->exitcode = -1 !== $exitcode ? $exitcode : (null !== $this->exitcode ? $this->exitcode : -1);
  30605. $this->status = self::STATUS_TERMINATED;
  30606. if (-1 === $this->exitcode && null !== $this->fallbackExitcode) {
  30607. $this->exitcode = $this->fallbackExitcode;
  30608. } elseif (-1 === $this->exitcode && $this->processInformation['signaled'] && 0 < $this->processInformation['termsig']) {
  30609. $this->exitcode = 128 + $this->processInformation['termsig'];
  30610. }
  30611. return $this->exitcode;
  30612. }
  30613. private function resetProcessData()
  30614. {
  30615. $this->starttime = null;
  30616. $this->callback = null;
  30617. $this->exitcode = null;
  30618. $this->fallbackExitcode = null;
  30619. $this->processInformation = null;
  30620. $this->stdout = null;
  30621. $this->stderr = null;
  30622. $this->process = null;
  30623. $this->latestSignal = null;
  30624. $this->status = self::STATUS_READY;
  30625. $this->incrementalOutputOffset = 0;
  30626. $this->incrementalErrorOutputOffset = 0;
  30627. }
  30628. private function doSignal($signal, $throwException)
  30629. {
  30630. if (!$this->isRunning()) {
  30631. if ($throwException) {
  30632. throw new LogicException('Can not send signal on a non running process.');
  30633. }
  30634. return false;
  30635. }
  30636. if ($this->isSigchildEnabled()) {
  30637. if ($throwException) {
  30638. throw new RuntimeException('This PHP has been compiled with --enable-sigchild. The process can not be signaled.');
  30639. }
  30640. return false;
  30641. }
  30642. if (true !== @proc_terminate($this->process, $signal)) {
  30643. if ($throwException) {
  30644. throw new RuntimeException(sprintf('Error while sending signal `%s`.', $signal));
  30645. }
  30646. return false;
  30647. }
  30648. $this->latestSignal = $signal;
  30649. return true;
  30650. }
  30651. private function requireProcessIsStarted($functionName)
  30652. {
  30653. if (!$this->isStarted()) {
  30654. throw new LogicException(sprintf('Process must be started before calling %s.', $functionName));
  30655. }
  30656. }
  30657. private function requireProcessIsTerminated($functionName)
  30658. {
  30659. if (!$this->isTerminated()) {
  30660. throw new LogicException(sprintf('Process must be terminated before calling %s.', $functionName));
  30661. }
  30662. }
  30663. }
  30664. <?php
  30665. namespace Symfony\Component\Process;
  30666. use Symfony\Component\Process\Exception\InvalidArgumentException;
  30667. use Symfony\Component\Process\Exception\LogicException;
  30668. class ProcessBuilder
  30669. {
  30670. private $arguments;
  30671. private $cwd;
  30672. private $env = array();
  30673. private $input;
  30674. private $timeout = 60;
  30675. private $options = array();
  30676. private $inheritEnv = true;
  30677. private $prefix = array();
  30678. private $outputDisabled = false;
  30679. public function __construct(array $arguments = array())
  30680. {
  30681. $this->arguments = $arguments;
  30682. }
  30683. public static function create(array $arguments = array())
  30684. {
  30685. return new static($arguments);
  30686. }
  30687. public function add($argument)
  30688. {
  30689. $this->arguments[] = $argument;
  30690. return $this;
  30691. }
  30692. public function setPrefix($prefix)
  30693. {
  30694. $this->prefix = is_array($prefix) ? $prefix : array($prefix);
  30695. return $this;
  30696. }
  30697. public function setArguments(array $arguments)
  30698. {
  30699. $this->arguments = $arguments;
  30700. return $this;
  30701. }
  30702. public function setWorkingDirectory($cwd)
  30703. {
  30704. $this->cwd = $cwd;
  30705. return $this;
  30706. }
  30707. public function inheritEnvironmentVariables($inheritEnv = true)
  30708. {
  30709. $this->inheritEnv = $inheritEnv;
  30710. return $this;
  30711. }
  30712. public function setEnv($name, $value)
  30713. {
  30714. $this->env[$name] = $value;
  30715. return $this;
  30716. }
  30717. public function addEnvironmentVariables(array $variables)
  30718. {
  30719. $this->env = array_replace($this->env, $variables);
  30720. return $this;
  30721. }
  30722. public function setInput($input)
  30723. {
  30724. $this->input = ProcessUtils::validateInput(sprintf('%s::%s', __CLASS__, __FUNCTION__), $input);
  30725. return $this;
  30726. }
  30727. public function setTimeout($timeout)
  30728. {
  30729. if (null === $timeout) {
  30730. $this->timeout = null;
  30731. return $this;
  30732. }
  30733. $timeout = (float) $timeout;
  30734. if ($timeout < 0) {
  30735. throw new InvalidArgumentException('The timeout value must be a valid positive integer or float number.');
  30736. }
  30737. $this->timeout = $timeout;
  30738. return $this;
  30739. }
  30740. public function setOption($name, $value)
  30741. {
  30742. $this->options[$name] = $value;
  30743. return $this;
  30744. }
  30745. public function disableOutput()
  30746. {
  30747. $this->outputDisabled = true;
  30748. return $this;
  30749. }
  30750. public function enableOutput()
  30751. {
  30752. $this->outputDisabled = false;
  30753. return $this;
  30754. }
  30755. public function getProcess()
  30756. {
  30757. if (0 === count($this->prefix) && 0 === count($this->arguments)) {
  30758. throw new LogicException('You must add() command arguments before calling getProcess().');
  30759. }
  30760. $options = $this->options;
  30761. $arguments = array_merge($this->prefix, $this->arguments);
  30762. $script = implode(' ', array_map(array(__NAMESPACE__.'\\ProcessUtils', 'escapeArgument'), $arguments));
  30763. if ($this->inheritEnv) {
  30764. $env = array_replace($_ENV, $_SERVER, $this->env);
  30765. } else {
  30766. $env = $this->env;
  30767. }
  30768. $process = new Process($script, $this->cwd, $env, $this->input, $this->timeout, $options);
  30769. if ($this->outputDisabled) {
  30770. $process->disableOutput();
  30771. }
  30772. return $process;
  30773. }
  30774. }
  30775. <?php
  30776. namespace Symfony\Component\Process;
  30777. use Symfony\Component\Process\Exception\InvalidArgumentException;
  30778. class ProcessUtils
  30779. {
  30780. private function __construct()
  30781. {
  30782. }
  30783. public static function escapeArgument($argument)
  30784. {
  30785. if ('\\' === DIRECTORY_SEPARATOR) {
  30786. if ('' === $argument) {
  30787. return escapeshellarg($argument);
  30788. }
  30789. $escapedArgument = '';
  30790. $quote = false;
  30791. foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
  30792. if ('"' === $part) {
  30793. $escapedArgument .= '\\"';
  30794. } elseif (self::isSurroundedBy($part, '%')) {
  30795. $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
  30796. } else {
  30797. if ('\\' === substr($part, -1)) {
  30798. $part .= '\\';
  30799. }
  30800. $quote = true;
  30801. $escapedArgument .= $part;
  30802. }
  30803. }
  30804. if ($quote) {
  30805. $escapedArgument = '"'.$escapedArgument.'"';
  30806. }
  30807. return $escapedArgument;
  30808. }
  30809. return escapeshellarg($argument);
  30810. }
  30811. public static function validateInput($caller, $input)
  30812. {
  30813. if (null !== $input) {
  30814. if (is_resource($input)) {
  30815. return $input;
  30816. }
  30817. if (is_scalar($input)) {
  30818. return (string) $input;
  30819. }
  30820. if (is_object($input) && method_exists($input, '__toString')) {
  30821. return (string) $input;
  30822. }
  30823. throw new InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller));
  30824. }
  30825. return $input;
  30826. }
  30827. private static function isSurroundedBy($arg, $char)
  30828. {
  30829. return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
  30830. }
  30831. }
  30832. <?php
  30833. namespace Symfony\Component\Yaml;
  30834. class Dumper
  30835. {
  30836. protected $indentation = 4;
  30837. public function setIndentation($num)
  30838. {
  30839. $this->indentation = (int) $num;
  30840. }
  30841. public function dump($input, $inline = 0, $indent = 0, $exceptionOnInvalidType = false, $objectSupport = false)
  30842. {
  30843. $output = '';
  30844. $prefix = $indent ? str_repeat(' ', $indent) : '';
  30845. if ($inline <= 0 || !is_array($input) || empty($input)) {
  30846. $output .= $prefix.Inline::dump($input, $exceptionOnInvalidType, $objectSupport);
  30847. } else {
  30848. $isAHash = array_keys($input) !== range(0, count($input) - 1);
  30849. foreach ($input as $key => $value) {
  30850. $willBeInlined = $inline - 1 <= 0 || !is_array($value) || empty($value);
  30851. $output .= sprintf('%s%s%s%s',
  30852. $prefix,
  30853. $isAHash ? Inline::dump($key, $exceptionOnInvalidType, $objectSupport).':' : '-',
  30854. $willBeInlined ? ' ' : "\n",
  30855. $this->dump($value, $inline - 1, $willBeInlined ? 0 : $indent + $this->indentation, $exceptionOnInvalidType, $objectSupport)
  30856. ).($willBeInlined ? "\n" : '');
  30857. }
  30858. }
  30859. return $output;
  30860. }
  30861. }
  30862. <?php
  30863. namespace Symfony\Component\Yaml;
  30864. class Escaper
  30865. {
  30866. const REGEX_CHARACTER_TO_ESCAPE = "[\\x00-\\x1f]|\xc2\x85|\xc2\xa0|\xe2\x80\xa8|\xe2\x80\xa9";
  30867. private static $escapees = array('\\', '\\\\', '\\"', '"',
  30868. "\x00", "\x01", "\x02", "\x03", "\x04", "\x05", "\x06", "\x07",
  30869. "\x08", "\x09", "\x0a", "\x0b", "\x0c", "\x0d", "\x0e", "\x0f",
  30870. "\x10", "\x11", "\x12", "\x13", "\x14", "\x15", "\x16", "\x17",
  30871. "\x18", "\x19", "\x1a", "\x1b", "\x1c", "\x1d", "\x1e", "\x1f",
  30872. "\xc2\x85", "\xc2\xa0", "\xe2\x80\xa8", "\xe2\x80\xa9",);
  30873. private static $escaped = array('\\\\', '\\"', '\\\\', '\\"',
  30874. "\\0", "\\x01", "\\x02", "\\x03", "\\x04", "\\x05", "\\x06", "\\a",
  30875. "\\b", "\\t", "\\n", "\\v", "\\f", "\\r", "\\x0e", "\\x0f",
  30876. "\\x10", "\\x11", "\\x12", "\\x13", "\\x14", "\\x15", "\\x16", "\\x17",
  30877. "\\x18", "\\x19", "\\x1a", "\\e", "\\x1c", "\\x1d", "\\x1e", "\\x1f",
  30878. "\\N", "\\_", "\\L", "\\P",);
  30879. public static function requiresDoubleQuoting($value)
  30880. {
  30881. return preg_match('/'.self::REGEX_CHARACTER_TO_ESCAPE.'/u', $value);
  30882. }
  30883. public static function escapeWithDoubleQuotes($value)
  30884. {
  30885. return sprintf('"%s"', str_replace(self::$escapees, self::$escaped, $value));
  30886. }
  30887. public static function requiresSingleQuoting($value)
  30888. {
  30889. if (in_array(strtolower($value), array('null', '~', 'true', 'false', 'y', 'n', 'yes', 'no', 'on', 'off'))) {
  30890. return true;
  30891. }
  30892. return preg_match('/[ \s \' " \: \{ \} \[ \] , & \* \# \?] | \A[ \- ? | < > = ! % @ ` ]/x', $value);
  30893. }
  30894. public static function escapeWithSingleQuotes($value)
  30895. {
  30896. return sprintf("'%s'", str_replace('\'', '\'\'', $value));
  30897. }
  30898. }
  30899. <?php
  30900. namespace Symfony\Component\Yaml\Exception;
  30901. class DumpException extends RuntimeException
  30902. {
  30903. }
  30904. <?php
  30905. namespace Symfony\Component\Yaml\Exception;
  30906. interface ExceptionInterface
  30907. {
  30908. }
  30909. <?php
  30910. namespace Symfony\Component\Yaml\Exception;
  30911. class ParseException extends RuntimeException
  30912. {
  30913. private $parsedFile;
  30914. private $parsedLine;
  30915. private $snippet;
  30916. private $rawMessage;
  30917. public function __construct($message, $parsedLine = -1, $snippet = null, $parsedFile = null, \Exception $previous = null)
  30918. {
  30919. $this->parsedFile = $parsedFile;
  30920. $this->parsedLine = $parsedLine;
  30921. $this->snippet = $snippet;
  30922. $this->rawMessage = $message;
  30923. $this->updateRepr();
  30924. parent::__construct($this->message, 0, $previous);
  30925. }
  30926. public function getSnippet()
  30927. {
  30928. return $this->snippet;
  30929. }
  30930. public function setSnippet($snippet)
  30931. {
  30932. $this->snippet = $snippet;
  30933. $this->updateRepr();
  30934. }
  30935. public function getParsedFile()
  30936. {
  30937. return $this->parsedFile;
  30938. }
  30939. public function setParsedFile($parsedFile)
  30940. {
  30941. $this->parsedFile = $parsedFile;
  30942. $this->updateRepr();
  30943. }
  30944. public function getParsedLine()
  30945. {
  30946. return $this->parsedLine;
  30947. }
  30948. public function setParsedLine($parsedLine)
  30949. {
  30950. $this->parsedLine = $parsedLine;
  30951. $this->updateRepr();
  30952. }
  30953. private function updateRepr()
  30954. {
  30955. $this->message = $this->rawMessage;
  30956. $dot = false;
  30957. if ('.' === substr($this->message, -1)) {
  30958. $this->message = substr($this->message, 0, -1);
  30959. $dot = true;
  30960. }
  30961. if (null !== $this->parsedFile) {
  30962. if (PHP_VERSION_ID >= 50400) {
  30963. $jsonOptions = JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE;
  30964. } else {
  30965. $jsonOptions = 0;
  30966. }
  30967. $this->message .= sprintf(' in %s', json_encode($this->parsedFile, $jsonOptions));
  30968. }
  30969. if ($this->parsedLine >= 0) {
  30970. $this->message .= sprintf(' at line %d', $this->parsedLine);
  30971. }
  30972. if ($this->snippet) {
  30973. $this->message .= sprintf(' (near "%s")', $this->snippet);
  30974. }
  30975. if ($dot) {
  30976. $this->message .= '.';
  30977. }
  30978. }
  30979. }
  30980. <?php
  30981. namespace Symfony\Component\Yaml\Exception;
  30982. class RuntimeException extends \RuntimeException implements ExceptionInterface
  30983. {
  30984. }
  30985. <?php
  30986. namespace Symfony\Component\Yaml;
  30987. use Symfony\Component\Yaml\Exception\ParseException;
  30988. use Symfony\Component\Yaml\Exception\DumpException;
  30989. class Inline
  30990. {
  30991. const REGEX_QUOTED_STRING = '(?:"([^"\\\\]*(?:\\\\.[^"\\\\]*)*)"|\'([^\']*(?:\'\'[^\']*)*)\')';
  30992. private static $exceptionOnInvalidType = false;
  30993. private static $objectSupport = false;
  30994. private static $objectForMap = false;
  30995. public static function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false, $references = array())
  30996. {
  30997. self::$exceptionOnInvalidType = $exceptionOnInvalidType;
  30998. self::$objectSupport = $objectSupport;
  30999. self::$objectForMap = $objectForMap;
  31000. $value = trim($value);
  31001. if (0 == strlen($value)) {
  31002. return '';
  31003. }
  31004. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  31005. $mbEncoding = mb_internal_encoding();
  31006. mb_internal_encoding('ASCII');
  31007. }
  31008. $i = 0;
  31009. switch ($value[0]) {
  31010. case '[':
  31011. $result = self::parseSequence($value, $i, $references);
  31012. ++$i;
  31013. break;
  31014. case '{':
  31015. $result = self::parseMapping($value, $i, $references);
  31016. ++$i;
  31017. break;
  31018. default:
  31019. $result = self::parseScalar($value, null, array('"', "'"), $i, true, $references);
  31020. }
  31021. if (preg_replace('/\s+#.*$/A', '', substr($value, $i))) {
  31022. throw new ParseException(sprintf('Unexpected characters near "%s".', substr($value, $i)));
  31023. }
  31024. if (isset($mbEncoding)) {
  31025. mb_internal_encoding($mbEncoding);
  31026. }
  31027. return $result;
  31028. }
  31029. public static function dump($value, $exceptionOnInvalidType = false, $objectSupport = false)
  31030. {
  31031. switch (true) {
  31032. case is_resource($value):
  31033. if ($exceptionOnInvalidType) {
  31034. throw new DumpException(sprintf('Unable to dump PHP resources in a YAML file ("%s").', get_resource_type($value)));
  31035. }
  31036. return 'null';
  31037. case is_object($value):
  31038. if ($objectSupport) {
  31039. return '!!php/object:'.serialize($value);
  31040. }
  31041. if ($exceptionOnInvalidType) {
  31042. throw new DumpException('Object support when dumping a YAML file has been disabled.');
  31043. }
  31044. return 'null';
  31045. case is_array($value):
  31046. return self::dumpArray($value, $exceptionOnInvalidType, $objectSupport);
  31047. case null === $value:
  31048. return 'null';
  31049. case true === $value:
  31050. return 'true';
  31051. case false === $value:
  31052. return 'false';
  31053. case ctype_digit($value):
  31054. return is_string($value) ? "'$value'" : (int) $value;
  31055. case is_numeric($value):
  31056. $locale = setlocale(LC_NUMERIC, 0);
  31057. if (false !== $locale) {
  31058. setlocale(LC_NUMERIC, 'C');
  31059. }
  31060. if (is_float($value)) {
  31061. $repr = strval($value);
  31062. if (is_infinite($value)) {
  31063. $repr = str_ireplace('INF', '.Inf', $repr);
  31064. } elseif (floor($value) == $value && $repr == $value) {
  31065. $repr = '!!float '.$repr;
  31066. }
  31067. } else {
  31068. $repr = is_string($value) ? "'$value'" : strval($value);
  31069. }
  31070. if (false !== $locale) {
  31071. setlocale(LC_NUMERIC, $locale);
  31072. }
  31073. return $repr;
  31074. case '' == $value:
  31075. return "''";
  31076. case Escaper::requiresDoubleQuoting($value):
  31077. return Escaper::escapeWithDoubleQuotes($value);
  31078. case Escaper::requiresSingleQuoting($value):
  31079. case preg_match(self::getTimestampRegex(), $value):
  31080. return Escaper::escapeWithSingleQuotes($value);
  31081. default:
  31082. return $value;
  31083. }
  31084. }
  31085. private static function dumpArray($value, $exceptionOnInvalidType, $objectSupport)
  31086. {
  31087. $keys = array_keys($value);
  31088. if ((1 == count($keys) && '0' == $keys[0])
  31089. || (count($keys) > 1 && array_reduce($keys, function ($v, $w) { return (int) $v + $w; }, 0) == count($keys) * (count($keys) - 1) / 2)
  31090. ) {
  31091. $output = array();
  31092. foreach ($value as $val) {
  31093. $output[] = self::dump($val, $exceptionOnInvalidType, $objectSupport);
  31094. }
  31095. return sprintf('[%s]', implode(', ', $output));
  31096. }
  31097. $output = array();
  31098. foreach ($value as $key => $val) {
  31099. $output[] = sprintf('%s: %s', self::dump($key, $exceptionOnInvalidType, $objectSupport), self::dump($val, $exceptionOnInvalidType, $objectSupport));
  31100. }
  31101. return sprintf('{ %s }', implode(', ', $output));
  31102. }
  31103. public static function parseScalar($scalar, $delimiters = null, $stringDelimiters = array('"', "'"), &$i = 0, $evaluate = true, $references = array())
  31104. {
  31105. if (in_array($scalar[$i], $stringDelimiters)) {
  31106. $output = self::parseQuotedScalar($scalar, $i);
  31107. if (null !== $delimiters) {
  31108. $tmp = ltrim(substr($scalar, $i), ' ');
  31109. if (!in_array($tmp[0], $delimiters)) {
  31110. throw new ParseException(sprintf('Unexpected characters (%s).', substr($scalar, $i)));
  31111. }
  31112. }
  31113. } else {
  31114. if (!$delimiters) {
  31115. $output = substr($scalar, $i);
  31116. $i += strlen($output);
  31117. if (false !== $strpos = strpos($output, ' #')) {
  31118. $output = rtrim(substr($output, 0, $strpos));
  31119. }
  31120. } elseif (preg_match('/^(.+?)('.implode('|', $delimiters).')/', substr($scalar, $i), $match)) {
  31121. $output = $match[1];
  31122. $i += strlen($output);
  31123. } else {
  31124. throw new ParseException(sprintf('Malformed inline YAML string (%s).', $scalar));
  31125. }
  31126. if ($evaluate) {
  31127. $output = self::evaluateScalar($output, $references);
  31128. }
  31129. }
  31130. return $output;
  31131. }
  31132. private static function parseQuotedScalar($scalar, &$i)
  31133. {
  31134. if (!preg_match('/'.self::REGEX_QUOTED_STRING.'/Au', substr($scalar, $i), $match)) {
  31135. throw new ParseException(sprintf('Malformed inline YAML string (%s).', substr($scalar, $i)));
  31136. }
  31137. $output = substr($match[0], 1, strlen($match[0]) - 2);
  31138. $unescaper = new Unescaper();
  31139. if ('"' == $scalar[$i]) {
  31140. $output = $unescaper->unescapeDoubleQuotedString($output);
  31141. } else {
  31142. $output = $unescaper->unescapeSingleQuotedString($output);
  31143. }
  31144. $i += strlen($match[0]);
  31145. return $output;
  31146. }
  31147. private static function parseSequence($sequence, &$i = 0, $references = array())
  31148. {
  31149. $output = array();
  31150. $len = strlen($sequence);
  31151. $i += 1;
  31152. while ($i < $len) {
  31153. switch ($sequence[$i]) {
  31154. case '[':
  31155. $output[] = self::parseSequence($sequence, $i, $references);
  31156. break;
  31157. case '{':
  31158. $output[] = self::parseMapping($sequence, $i, $references);
  31159. break;
  31160. case ']':
  31161. return $output;
  31162. case ',':
  31163. case ' ':
  31164. break;
  31165. default:
  31166. $isQuoted = in_array($sequence[$i], array('"', "'"));
  31167. $value = self::parseScalar($sequence, array(',', ']'), array('"', "'"), $i, true, $references);
  31168. if (!is_array($value) && !$isQuoted && false !== strpos($value, ': ')) {
  31169. try {
  31170. $pos = 0;
  31171. $value = self::parseMapping('{'.$value.'}', $pos, $references);
  31172. } catch (\InvalidArgumentException $e) {
  31173. }
  31174. }
  31175. $output[] = $value;
  31176. --$i;
  31177. }
  31178. ++$i;
  31179. }
  31180. throw new ParseException(sprintf('Malformed inline YAML string %s', $sequence));
  31181. }
  31182. private static function parseMapping($mapping, &$i = 0, $references = array())
  31183. {
  31184. $output = array();
  31185. $len = strlen($mapping);
  31186. $i += 1;
  31187. while ($i < $len) {
  31188. switch ($mapping[$i]) {
  31189. case ' ':
  31190. case ',':
  31191. ++$i;
  31192. continue 2;
  31193. case '}':
  31194. if (self::$objectForMap) {
  31195. return (object) $output;
  31196. }
  31197. return $output;
  31198. }
  31199. $key = self::parseScalar($mapping, array(':', ' '), array('"', "'"), $i, false);
  31200. $done = false;
  31201. while ($i < $len) {
  31202. switch ($mapping[$i]) {
  31203. case '[':
  31204. $value = self::parseSequence($mapping, $i, $references);
  31205. if (!isset($output[$key])) {
  31206. $output[$key] = $value;
  31207. }
  31208. $done = true;
  31209. break;
  31210. case '{':
  31211. $value = self::parseMapping($mapping, $i, $references);
  31212. if (!isset($output[$key])) {
  31213. $output[$key] = $value;
  31214. }
  31215. $done = true;
  31216. break;
  31217. case ':':
  31218. case ' ':
  31219. break;
  31220. default:
  31221. $value = self::parseScalar($mapping, array(',', '}'), array('"', "'"), $i, true, $references);
  31222. if (!isset($output[$key])) {
  31223. $output[$key] = $value;
  31224. }
  31225. $done = true;
  31226. --$i;
  31227. }
  31228. ++$i;
  31229. if ($done) {
  31230. continue 2;
  31231. }
  31232. }
  31233. }
  31234. throw new ParseException(sprintf('Malformed inline YAML string %s', $mapping));
  31235. }
  31236. private static function evaluateScalar($scalar, $references = array())
  31237. {
  31238. $scalar = trim($scalar);
  31239. $scalarLower = strtolower($scalar);
  31240. if (0 === strpos($scalar, '*')) {
  31241. if (false !== $pos = strpos($scalar, '#')) {
  31242. $value = substr($scalar, 1, $pos - 2);
  31243. } else {
  31244. $value = substr($scalar, 1);
  31245. }
  31246. if (false === $value || '' === $value) {
  31247. throw new ParseException('A reference must contain at least one character.');
  31248. }
  31249. if (!array_key_exists($value, $references)) {
  31250. throw new ParseException(sprintf('Reference "%s" does not exist.', $value));
  31251. }
  31252. return $references[$value];
  31253. }
  31254. switch (true) {
  31255. case 'null' === $scalarLower:
  31256. case '' === $scalar:
  31257. case '~' === $scalar:
  31258. return;
  31259. case 'true' === $scalarLower:
  31260. return true;
  31261. case 'false' === $scalarLower:
  31262. return false;
  31263. case $scalar[0] === '+' || $scalar[0] === '-' || $scalar[0] === '.' || $scalar[0] === '!' || is_numeric($scalar[0]):
  31264. switch (true) {
  31265. case 0 === strpos($scalar, '!str'):
  31266. return (string) substr($scalar, 5);
  31267. case 0 === strpos($scalar, '! '):
  31268. return intval(self::parseScalar(substr($scalar, 2)));
  31269. case 0 === strpos($scalar, '!!php/object:'):
  31270. if (self::$objectSupport) {
  31271. return unserialize(substr($scalar, 13));
  31272. }
  31273. if (self::$exceptionOnInvalidType) {
  31274. throw new ParseException('Object support when parsing a YAML file has been disabled.');
  31275. }
  31276. return;
  31277. case 0 === strpos($scalar, '!!float '):
  31278. return (float) substr($scalar, 8);
  31279. case ctype_digit($scalar):
  31280. $raw = $scalar;
  31281. $cast = intval($scalar);
  31282. return '0' == $scalar[0] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  31283. case '-' === $scalar[0] && ctype_digit(substr($scalar, 1)):
  31284. $raw = $scalar;
  31285. $cast = intval($scalar);
  31286. return '0' == $scalar[1] ? octdec($scalar) : (((string) $raw == (string) $cast) ? $cast : $raw);
  31287. case is_numeric($scalar):
  31288. return '0x' == $scalar[0].$scalar[1] ? hexdec($scalar) : floatval($scalar);
  31289. case '.inf' === $scalarLower:
  31290. case '.nan' === $scalarLower:
  31291. return -log(0);
  31292. case '-.inf' === $scalarLower:
  31293. return log(0);
  31294. case preg_match('/^(-|\+)?[0-9,]+(\.[0-9]+)?$/', $scalar):
  31295. return floatval(str_replace(',', '', $scalar));
  31296. case preg_match(self::getTimestampRegex(), $scalar):
  31297. return strtotime($scalar);
  31298. }
  31299. default:
  31300. return (string) $scalar;
  31301. }
  31302. }
  31303. private static function getTimestampRegex()
  31304. {
  31305. return <<<EOF
  31306. ~^
  31307. (?P<year>[0-9][0-9][0-9][0-9])
  31308. -(?P<month>[0-9][0-9]?)
  31309. -(?P<day>[0-9][0-9]?)
  31310. (?:(?:[Tt]|[ \t]+)
  31311. (?P<hour>[0-9][0-9]?)
  31312. :(?P<minute>[0-9][0-9])
  31313. :(?P<second>[0-9][0-9])
  31314. (?:\.(?P<fraction>[0-9]*))?
  31315. (?:[ \t]*(?P<tz>Z|(?P<tz_sign>[-+])(?P<tz_hour>[0-9][0-9]?)
  31316. (?::(?P<tz_minute>[0-9][0-9]))?))?)?
  31317. $~x
  31318. EOF;
  31319. }
  31320. }
  31321. Copyright (c) 2004-2015 Fabien Potencier
  31322. Permission is hereby granted, free of charge, to any person obtaining a copy
  31323. of this software and associated documentation files (the "Software"), to deal
  31324. in the Software without restriction, including without limitation the rights
  31325. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  31326. copies of the Software, and to permit persons to whom the Software is furnished
  31327. to do so, subject to the following conditions:
  31328. The above copyright notice and this permission notice shall be included in all
  31329. copies or substantial portions of the Software.
  31330. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31331. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31332. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31333. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31334. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  31335. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31336. THE SOFTWARE.
  31337. <?php
  31338. namespace Symfony\Component\Yaml;
  31339. use Symfony\Component\Yaml\Exception\ParseException;
  31340. class Parser
  31341. {
  31342. const FOLDED_SCALAR_PATTERN = '(?P<separator>\||>)(?P<modifiers>\+|\-|\d+|\+\d+|\-\d+|\d+\+|\d+\-)?(?P<comments> +#.*)?';
  31343. private $offset = 0;
  31344. private $lines = array();
  31345. private $currentLineNb = -1;
  31346. private $currentLine = '';
  31347. private $refs = array();
  31348. public function __construct($offset = 0)
  31349. {
  31350. $this->offset = $offset;
  31351. }
  31352. public function parse($value, $exceptionOnInvalidType = false, $objectSupport = false, $objectForMap = false)
  31353. {
  31354. $this->currentLineNb = -1;
  31355. $this->currentLine = '';
  31356. $this->lines = explode("\n", $this->cleanup($value));
  31357. if (!preg_match('//u', $value)) {
  31358. throw new ParseException('The YAML value does not appear to be valid UTF-8.');
  31359. }
  31360. if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) {
  31361. $mbEncoding = mb_internal_encoding();
  31362. mb_internal_encoding('UTF-8');
  31363. }
  31364. $data = array();
  31365. $context = null;
  31366. $allowOverwrite = false;
  31367. while ($this->moveToNextLine()) {
  31368. if ($this->isCurrentLineEmpty()) {
  31369. continue;
  31370. }
  31371. if ("\t" === $this->currentLine[0]) {
  31372. throw new ParseException('A YAML file cannot contain tabs as indentation.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31373. }
  31374. $isRef = $mergeNode = false;
  31375. if (preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) {
  31376. if ($context && 'mapping' == $context) {
  31377. throw new ParseException('You cannot define a sequence item when in a mapping');
  31378. }
  31379. $context = 'sequence';
  31380. if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
  31381. $isRef = $matches['ref'];
  31382. $values['value'] = $matches['value'];
  31383. }
  31384. if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  31385. $c = $this->getRealCurrentLineNb() + 1;
  31386. $parser = new Parser($c);
  31387. $parser->refs = & $this->refs;
  31388. $data[] = $parser->parse($this->getNextEmbedBlock(null, true), $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31389. } else {
  31390. if (isset($values['leadspaces'])
  31391. && preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\{\[].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)
  31392. ) {
  31393. $c = $this->getRealCurrentLineNb();
  31394. $parser = new Parser($c);
  31395. $parser->refs = & $this->refs;
  31396. $block = $values['value'];
  31397. if ($this->isNextLineIndented()) {
  31398. $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + strlen($values['leadspaces']) + 1);
  31399. }
  31400. $data[] = $parser->parse($block, $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31401. } else {
  31402. $data[] = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31403. }
  31404. }
  31405. } elseif (preg_match('#^(?P<key>'.Inline::REGEX_QUOTED_STRING.'|[^ \'"\[\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values) && (false === strpos($values['key'], ' #') || in_array($values['key'][0], array('"', "'")))) {
  31406. if ($context && 'sequence' == $context) {
  31407. throw new ParseException('You cannot define a mapping item when in a sequence');
  31408. }
  31409. $context = 'mapping';
  31410. Inline::parse(null, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  31411. try {
  31412. $key = Inline::parseScalar($values['key']);
  31413. } catch (ParseException $e) {
  31414. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  31415. $e->setSnippet($this->currentLine);
  31416. throw $e;
  31417. }
  31418. if ('<<' === $key) {
  31419. $mergeNode = true;
  31420. $allowOverwrite = true;
  31421. if (isset($values['value']) && 0 === strpos($values['value'], '*')) {
  31422. $refName = substr($values['value'], 1);
  31423. if (!array_key_exists($refName, $this->refs)) {
  31424. throw new ParseException(sprintf('Reference "%s" does not exist.', $refName), $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31425. }
  31426. $refValue = $this->refs[$refName];
  31427. if (!is_array($refValue)) {
  31428. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31429. }
  31430. foreach ($refValue as $key => $value) {
  31431. if (!isset($data[$key])) {
  31432. $data[$key] = $value;
  31433. }
  31434. }
  31435. } else {
  31436. if (isset($values['value']) && $values['value'] !== '') {
  31437. $value = $values['value'];
  31438. } else {
  31439. $value = $this->getNextEmbedBlock();
  31440. }
  31441. $c = $this->getRealCurrentLineNb() + 1;
  31442. $parser = new Parser($c);
  31443. $parser->refs = & $this->refs;
  31444. $parsed = $parser->parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31445. if (!is_array($parsed)) {
  31446. throw new ParseException('YAML merge keys used with a scalar value instead of an array.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31447. }
  31448. if (isset($parsed[0])) {
  31449. foreach ($parsed as $parsedItem) {
  31450. if (!is_array($parsedItem)) {
  31451. throw new ParseException('Merge items must be arrays.', $this->getRealCurrentLineNb() + 1, $parsedItem);
  31452. }
  31453. foreach ($parsedItem as $key => $value) {
  31454. if (!isset($data[$key])) {
  31455. $data[$key] = $value;
  31456. }
  31457. }
  31458. }
  31459. } else {
  31460. foreach ($parsed as $key => $value) {
  31461. if (!isset($data[$key])) {
  31462. $data[$key] = $value;
  31463. }
  31464. }
  31465. }
  31466. }
  31467. } elseif (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) {
  31468. $isRef = $matches['ref'];
  31469. $values['value'] = $matches['value'];
  31470. }
  31471. if ($mergeNode) {
  31472. } elseif (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) {
  31473. if (!$this->isNextLineIndented() && !$this->isNextLineUnIndentedCollection()) {
  31474. if ($allowOverwrite || !isset($data[$key])) {
  31475. $data[$key] = null;
  31476. }
  31477. } else {
  31478. $c = $this->getRealCurrentLineNb() + 1;
  31479. $parser = new Parser($c);
  31480. $parser->refs = & $this->refs;
  31481. $value = $parser->parse($this->getNextEmbedBlock(), $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31482. if ($allowOverwrite || !isset($data[$key])) {
  31483. $data[$key] = $value;
  31484. }
  31485. }
  31486. } else {
  31487. $value = $this->parseValue($values['value'], $exceptionOnInvalidType, $objectSupport, $objectForMap);
  31488. if ($allowOverwrite || !isset($data[$key])) {
  31489. $data[$key] = $value;
  31490. }
  31491. }
  31492. } else {
  31493. if ('---' === $this->currentLine) {
  31494. throw new ParseException('Multiple documents are not supported.');
  31495. }
  31496. $lineCount = count($this->lines);
  31497. if (1 === $lineCount || (2 === $lineCount && empty($this->lines[1]))) {
  31498. try {
  31499. $value = Inline::parse($this->lines[0], $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  31500. } catch (ParseException $e) {
  31501. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  31502. $e->setSnippet($this->currentLine);
  31503. throw $e;
  31504. }
  31505. if (is_array($value)) {
  31506. $first = reset($value);
  31507. if (is_string($first) && 0 === strpos($first, '*')) {
  31508. $data = array();
  31509. foreach ($value as $alias) {
  31510. $data[] = $this->refs[substr($alias, 1)];
  31511. }
  31512. $value = $data;
  31513. }
  31514. }
  31515. if (isset($mbEncoding)) {
  31516. mb_internal_encoding($mbEncoding);
  31517. }
  31518. return $value;
  31519. }
  31520. switch (preg_last_error()) {
  31521. case PREG_INTERNAL_ERROR:
  31522. $error = 'Internal PCRE error.';
  31523. break;
  31524. case PREG_BACKTRACK_LIMIT_ERROR:
  31525. $error = 'pcre.backtrack_limit reached.';
  31526. break;
  31527. case PREG_RECURSION_LIMIT_ERROR:
  31528. $error = 'pcre.recursion_limit reached.';
  31529. break;
  31530. case PREG_BAD_UTF8_ERROR:
  31531. $error = 'Malformed UTF-8 data.';
  31532. break;
  31533. case PREG_BAD_UTF8_OFFSET_ERROR:
  31534. $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point.';
  31535. break;
  31536. default:
  31537. $error = 'Unable to parse.';
  31538. }
  31539. throw new ParseException($error, $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31540. }
  31541. if ($isRef) {
  31542. $this->refs[$isRef] = end($data);
  31543. }
  31544. }
  31545. if (isset($mbEncoding)) {
  31546. mb_internal_encoding($mbEncoding);
  31547. }
  31548. return empty($data) ? null : $data;
  31549. }
  31550. private function getRealCurrentLineNb()
  31551. {
  31552. return $this->currentLineNb + $this->offset;
  31553. }
  31554. private function getCurrentLineIndentation()
  31555. {
  31556. return strlen($this->currentLine) - strlen(ltrim($this->currentLine, ' '));
  31557. }
  31558. private function getNextEmbedBlock($indentation = null, $inSequence = false)
  31559. {
  31560. $oldLineIndentation = $this->getCurrentLineIndentation();
  31561. if (!$this->moveToNextLine()) {
  31562. return;
  31563. }
  31564. if (null === $indentation) {
  31565. $newIndent = $this->getCurrentLineIndentation();
  31566. $unindentedEmbedBlock = $this->isStringUnIndentedCollectionItem($this->currentLine);
  31567. if (!$this->isCurrentLineEmpty() && 0 === $newIndent && !$unindentedEmbedBlock) {
  31568. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31569. }
  31570. } else {
  31571. $newIndent = $indentation;
  31572. }
  31573. $data = array();
  31574. if ($this->getCurrentLineIndentation() >= $newIndent) {
  31575. $data[] = substr($this->currentLine, $newIndent);
  31576. } else {
  31577. $this->moveToPreviousLine();
  31578. return;
  31579. }
  31580. if ($inSequence && $oldLineIndentation === $newIndent && '-' === $data[0][0]) {
  31581. $this->moveToPreviousLine();
  31582. return;
  31583. }
  31584. $isItUnindentedCollection = $this->isStringUnIndentedCollectionItem($this->currentLine);
  31585. $removeCommentsPattern = '~'.self::FOLDED_SCALAR_PATTERN.'$~';
  31586. $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
  31587. while ($this->moveToNextLine()) {
  31588. $indent = $this->getCurrentLineIndentation();
  31589. if ($indent === $newIndent) {
  31590. $removeComments = !preg_match($removeCommentsPattern, $this->currentLine);
  31591. }
  31592. if ($isItUnindentedCollection && !$this->isStringUnIndentedCollectionItem($this->currentLine) && $newIndent === $indent) {
  31593. $this->moveToPreviousLine();
  31594. break;
  31595. }
  31596. if ($this->isCurrentLineBlank()) {
  31597. $data[] = substr($this->currentLine, $newIndent);
  31598. continue;
  31599. }
  31600. if ($removeComments && $this->isCurrentLineComment()) {
  31601. continue;
  31602. }
  31603. if ($indent >= $newIndent) {
  31604. $data[] = substr($this->currentLine, $newIndent);
  31605. } elseif (0 == $indent) {
  31606. $this->moveToPreviousLine();
  31607. break;
  31608. } else {
  31609. throw new ParseException('Indentation problem.', $this->getRealCurrentLineNb() + 1, $this->currentLine);
  31610. }
  31611. }
  31612. return implode("\n", $data);
  31613. }
  31614. private function moveToNextLine()
  31615. {
  31616. if ($this->currentLineNb >= count($this->lines) - 1) {
  31617. return false;
  31618. }
  31619. $this->currentLine = $this->lines[++$this->currentLineNb];
  31620. return true;
  31621. }
  31622. private function moveToPreviousLine()
  31623. {
  31624. $this->currentLine = $this->lines[--$this->currentLineNb];
  31625. }
  31626. private function parseValue($value, $exceptionOnInvalidType, $objectSupport, $objectForMap)
  31627. {
  31628. if (0 === strpos($value, '*')) {
  31629. if (false !== $pos = strpos($value, '#')) {
  31630. $value = substr($value, 1, $pos - 2);
  31631. } else {
  31632. $value = substr($value, 1);
  31633. }
  31634. if (!array_key_exists($value, $this->refs)) {
  31635. throw new ParseException(sprintf('Reference "%s" does not exist.', $value), $this->currentLine);
  31636. }
  31637. return $this->refs[$value];
  31638. }
  31639. if (preg_match('/^'.self::FOLDED_SCALAR_PATTERN.'$/', $value, $matches)) {
  31640. $modifiers = isset($matches['modifiers']) ? $matches['modifiers'] : '';
  31641. return $this->parseFoldedScalar($matches['separator'], preg_replace('#\d+#', '', $modifiers), intval(abs($modifiers)));
  31642. }
  31643. try {
  31644. return Inline::parse($value, $exceptionOnInvalidType, $objectSupport, $objectForMap, $this->refs);
  31645. } catch (ParseException $e) {
  31646. $e->setParsedLine($this->getRealCurrentLineNb() + 1);
  31647. $e->setSnippet($this->currentLine);
  31648. throw $e;
  31649. }
  31650. }
  31651. private function parseFoldedScalar($separator, $indicator = '', $indentation = 0)
  31652. {
  31653. $notEOF = $this->moveToNextLine();
  31654. if (!$notEOF) {
  31655. return '';
  31656. }
  31657. $isCurrentLineBlank = $this->isCurrentLineBlank();
  31658. $text = '';
  31659. while ($notEOF && $isCurrentLineBlank) {
  31660. if ($notEOF = $this->moveToNextLine()) {
  31661. $text .= "\n";
  31662. $isCurrentLineBlank = $this->isCurrentLineBlank();
  31663. }
  31664. }
  31665. if (0 === $indentation) {
  31666. if (preg_match('/^ +/', $this->currentLine, $matches)) {
  31667. $indentation = strlen($matches[0]);
  31668. }
  31669. }
  31670. if ($indentation > 0) {
  31671. $pattern = sprintf('/^ {%d}(.*)$/', $indentation);
  31672. while (
  31673. $notEOF && (
  31674. $isCurrentLineBlank ||
  31675. preg_match($pattern, $this->currentLine, $matches)
  31676. )
  31677. ) {
  31678. if ($isCurrentLineBlank) {
  31679. $text .= substr($this->currentLine, $indentation);
  31680. } else {
  31681. $text .= $matches[1];
  31682. }
  31683. if ($notEOF = $this->moveToNextLine()) {
  31684. $text .= "\n";
  31685. $isCurrentLineBlank = $this->isCurrentLineBlank();
  31686. }
  31687. }
  31688. } elseif ($notEOF) {
  31689. $text .= "\n";
  31690. }
  31691. if ($notEOF) {
  31692. $this->moveToPreviousLine();
  31693. }
  31694. if ('>' === $separator) {
  31695. preg_match('/(\n*)$/', $text, $matches);
  31696. $text = preg_replace('/(?<!\n)\n(?!\n)/', ' ', rtrim($text, "\n"));
  31697. $text .= $matches[1];
  31698. }
  31699. if ('' === $indicator) {
  31700. $text = preg_replace('/\n+$/s', "\n", $text);
  31701. } elseif ('-' === $indicator) {
  31702. $text = preg_replace('/\n+$/s', '', $text);
  31703. }
  31704. return $text;
  31705. }
  31706. private function isNextLineIndented()
  31707. {
  31708. $currentIndentation = $this->getCurrentLineIndentation();
  31709. $EOF = !$this->moveToNextLine();
  31710. while (!$EOF && $this->isCurrentLineEmpty()) {
  31711. $EOF = !$this->moveToNextLine();
  31712. }
  31713. if ($EOF) {
  31714. return false;
  31715. }
  31716. $ret = false;
  31717. if ($this->getCurrentLineIndentation() > $currentIndentation) {
  31718. $ret = true;
  31719. }
  31720. $this->moveToPreviousLine();
  31721. return $ret;
  31722. }
  31723. private function isCurrentLineEmpty()
  31724. {
  31725. return $this->isCurrentLineBlank() || $this->isCurrentLineComment();
  31726. }
  31727. private function isCurrentLineBlank()
  31728. {
  31729. return '' == trim($this->currentLine, ' ');
  31730. }
  31731. private function isCurrentLineComment()
  31732. {
  31733. $ltrimmedLine = ltrim($this->currentLine, ' ');
  31734. return $ltrimmedLine[0] === '#';
  31735. }
  31736. private function cleanup($value)
  31737. {
  31738. $value = str_replace(array("\r\n", "\r"), "\n", $value);
  31739. $count = 0;
  31740. $value = preg_replace('#^\%YAML[: ][\d\.]+.*\n#u', '', $value, -1, $count);
  31741. $this->offset += $count;
  31742. $trimmedValue = preg_replace('#^(\#.*?\n)+#s', '', $value, -1, $count);
  31743. if ($count == 1) {
  31744. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  31745. $value = $trimmedValue;
  31746. }
  31747. $trimmedValue = preg_replace('#^\-\-\-.*?\n#s', '', $value, -1, $count);
  31748. if ($count == 1) {
  31749. $this->offset += substr_count($value, "\n") - substr_count($trimmedValue, "\n");
  31750. $value = $trimmedValue;
  31751. $value = preg_replace('#\.\.\.\s*$#s', '', $value);
  31752. }
  31753. return $value;
  31754. }
  31755. private function isNextLineUnIndentedCollection()
  31756. {
  31757. $currentIndentation = $this->getCurrentLineIndentation();
  31758. $notEOF = $this->moveToNextLine();
  31759. while ($notEOF && $this->isCurrentLineEmpty()) {
  31760. $notEOF = $this->moveToNextLine();
  31761. }
  31762. if (false === $notEOF) {
  31763. return false;
  31764. }
  31765. $ret = false;
  31766. if (
  31767. $this->getCurrentLineIndentation() == $currentIndentation
  31768. &&
  31769. $this->isStringUnIndentedCollectionItem($this->currentLine)
  31770. ) {
  31771. $ret = true;
  31772. }
  31773. $this->moveToPreviousLine();
  31774. return $ret;
  31775. }
  31776. private function isStringUnIndentedCollectionItem()
  31777. {
  31778. return (0 === strpos($this->currentLine, '- '));
  31779. }
  31780. }
  31781. <?php
  31782. namespace Symfony\Component\Yaml;
  31783. class Unescaper
  31784. {
  31785. const ENCODING = 'UTF-8';
  31786. const REGEX_ESCAPED_CHARACTER = "\\\\([0abt\tnvfre \\\"\\/\\\\N_LP]|x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8})";
  31787. public function unescapeSingleQuotedString($value)
  31788. {
  31789. return str_replace('\'\'', '\'', $value);
  31790. }
  31791. public function unescapeDoubleQuotedString($value)
  31792. {
  31793. $self = $this;
  31794. $callback = function ($match) use ($self) {
  31795. return $self->unescapeCharacter($match[0]);
  31796. };
  31797. return preg_replace_callback('/'.self::REGEX_ESCAPED_CHARACTER.'/u', $callback, $value);
  31798. }
  31799. public function unescapeCharacter($value)
  31800. {
  31801. switch ($value{1}) {
  31802. case '0':
  31803. return "\x0";
  31804. case 'a':
  31805. return "\x7";
  31806. case 'b':
  31807. return "\x8";
  31808. case 't':
  31809. return "\t";
  31810. case "\t":
  31811. return "\t";
  31812. case 'n':
  31813. return "\n";
  31814. case 'v':
  31815. return "\xB";
  31816. case 'f':
  31817. return "\xC";
  31818. case 'r':
  31819. return "\r";
  31820. case 'e':
  31821. return "\x1B";
  31822. case ' ':
  31823. return ' ';
  31824. case '"':
  31825. return '"';
  31826. case '/':
  31827. return '/';
  31828. case '\\':
  31829. return '\\';
  31830. case 'N':
  31831. return "\xC2\x85";
  31832. case '_':
  31833. return "\xC2\xA0";
  31834. case 'L':
  31835. return "\xE2\x80\xA8";
  31836. case 'P':
  31837. return "\xE2\x80\xA9";
  31838. case 'x':
  31839. return self::utf8chr(hexdec(substr($value, 2, 2)));
  31840. case 'u':
  31841. return self::utf8chr(hexdec(substr($value, 2, 4)));
  31842. case 'U':
  31843. return self::utf8chr(hexdec(substr($value, 2, 8)));
  31844. }
  31845. }
  31846. private static function utf8chr($c)
  31847. {
  31848. if (0x80 > $c %= 0x200000) {
  31849. return chr($c);
  31850. }
  31851. if (0x800 > $c) {
  31852. return chr(0xC0 | $c >> 6).chr(0x80 | $c & 0x3F);
  31853. }
  31854. if (0x10000 > $c) {
  31855. return chr(0xE0 | $c >> 12).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  31856. }
  31857. return chr(0xF0 | $c >> 18).chr(0x80 | $c >> 12 & 0x3F).chr(0x80 | $c >> 6 & 0x3F).chr(0x80 | $c & 0x3F);
  31858. }
  31859. }
  31860. <?php
  31861. namespace Symfony\Component\Yaml;
  31862. use Symfony\Component\Yaml\Exception\ParseException;
  31863. class Yaml
  31864. {
  31865. public static function parse($input, $exceptionOnInvalidType = false, $objectSupport = false)
  31866. {
  31867. $file = '';
  31868. if (strpos($input, "\n") === false && is_file($input)) {
  31869. if (false === is_readable($input)) {
  31870. throw new ParseException(sprintf('Unable to parse "%s" as the file is not readable.', $input));
  31871. }
  31872. $file = $input;
  31873. $input = file_get_contents($file);
  31874. }
  31875. $yaml = new Parser();
  31876. try {
  31877. return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport);
  31878. } catch (ParseException $e) {
  31879. if ($file) {
  31880. $e->setParsedFile($file);
  31881. }
  31882. throw $e;
  31883. }
  31884. }
  31885. public static function dump($array, $inline = 2, $indent = 4, $exceptionOnInvalidType = false, $objectSupport = false)
  31886. {
  31887. $yaml = new Dumper();
  31888. $yaml->setIndentation($indent);
  31889. return $yaml->dump($array, $inline, 0, $exceptionOnInvalidType, $objectSupport);
  31890. }
  31891. }
  31892. Copyright (c) 2011 Jordi Boggiano
  31893. Permission is hereby granted, free of charge, to any person obtaining a copy
  31894. of this software and associated documentation files (the "Software"), to deal
  31895. in the Software without restriction, including without limitation the rights
  31896. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  31897. copies of the Software, and to permit persons to whom the Software is furnished
  31898. to do so, subject to the following conditions:
  31899. The above copyright notice and this permission notice shall be included in all
  31900. copies or substantial portions of the Software.
  31901. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  31902. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  31903. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  31904. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  31905. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  31906. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  31907. THE SOFTWARE.
  31908. <?php
  31909. namespace Seld\JsonLint;
  31910. use stdClass;
  31911. class JsonParser
  31912. {
  31913. const DETECT_KEY_CONFLICTS = 1;
  31914. const ALLOW_DUPLICATE_KEYS = 2;
  31915. const PARSE_TO_ASSOC = 4;
  31916. private $lexer;
  31917. private $flags;
  31918. private $stack;
  31919. private $vstack;
  31920. private $lstack;
  31921. private $symbols = array(
  31922. 'error' => 2,
  31923. 'JSONString' => 3,
  31924. 'STRING' => 4,
  31925. 'JSONNumber' => 5,
  31926. 'NUMBER' => 6,
  31927. 'JSONNullLiteral' => 7,
  31928. 'NULL' => 8,
  31929. 'JSONBooleanLiteral' => 9,
  31930. 'TRUE' => 10,
  31931. 'FALSE' => 11,
  31932. 'JSONText' => 12,
  31933. 'JSONValue' => 13,
  31934. 'EOF' => 14,
  31935. 'JSONObject' => 15,
  31936. 'JSONArray' => 16,
  31937. '{' => 17,
  31938. '}' => 18,
  31939. 'JSONMemberList' => 19,
  31940. 'JSONMember' => 20,
  31941. ':' => 21,
  31942. ',' => 22,
  31943. '[' => 23,
  31944. ']' => 24,
  31945. 'JSONElementList' => 25,
  31946. '$accept' => 0,
  31947. '$end' => 1,
  31948. );
  31949. private $terminals_ = array(
  31950. 2 => "error",
  31951. 4 => "STRING",
  31952. 6 => "NUMBER",
  31953. 8 => "NULL",
  31954. 10 => "TRUE",
  31955. 11 => "FALSE",
  31956. 14 => "EOF",
  31957. 17 => "{",
  31958. 18 => "}",
  31959. 21 => ":",
  31960. 22 => ",",
  31961. 23 => "[",
  31962. 24 => "]",
  31963. );
  31964. private $productions_ = array(
  31965. 0,
  31966. array(3, 1),
  31967. array(5, 1),
  31968. array(7, 1),
  31969. array(9, 1),
  31970. array(9, 1),
  31971. array(12, 2),
  31972. array(13, 1),
  31973. array(13, 1),
  31974. array(13, 1),
  31975. array(13, 1),
  31976. array(13, 1),
  31977. array(13, 1),
  31978. array(15, 2),
  31979. array(15, 3),
  31980. array(20, 3),
  31981. array(19, 1),
  31982. array(19, 3),
  31983. array(16, 2),
  31984. array(16, 3),
  31985. array(25, 1),
  31986. array(25, 3)
  31987. );
  31988. private $table = array(array(3 => 5, 4 => array(1,12), 5 => 6, 6 => array(1,13), 7 => 3, 8 => array(1,9), 9 => 4, 10 => array(1,10), 11 => array(1,11), 12 => 1, 13 => 2, 15 => 7, 16 => 8, 17 => array(1,14), 23 => array(1,15)), array( 1 => array(3)), array( 14 => array(1,16)), array( 14 => array(2,7), 18 => array(2,7), 22 => array(2,7), 24 => array(2,7)), array( 14 => array(2,8), 18 => array(2,8), 22 => array(2,8), 24 => array(2,8)), array( 14 => array(2,9), 18 => array(2,9), 22 => array(2,9), 24 => array(2,9)), array( 14 => array(2,10), 18 => array(2,10), 22 => array(2,10), 24 => array(2,10)), array( 14 => array(2,11), 18 => array(2,11), 22 => array(2,11), 24 => array(2,11)), array( 14 => array(2,12), 18 => array(2,12), 22 => array(2,12), 24 => array(2,12)), array( 14 => array(2,3), 18 => array(2,3), 22 => array(2,3), 24 => array(2,3)), array( 14 => array(2,4), 18 => array(2,4), 22 => array(2,4), 24 => array(2,4)), array( 14 => array(2,5), 18 => array(2,5), 22 => array(2,5), 24 => array(2,5)), array( 14 => array(2,1), 18 => array(2,1), 21 => array(2,1), 22 => array(2,1), 24 => array(2,1)), array( 14 => array(2,2), 18 => array(2,2), 22 => array(2,2), 24 => array(2,2)), array( 3 => 20, 4 => array(1,12), 18 => array(1,17), 19 => 18, 20 => 19 ), array( 3 => 5, 4 => array(1,12), 5 => 6, 6 => array(1,13), 7 => 3, 8 => array(1,9), 9 => 4, 10 => array(1,10), 11 => array(1,11), 13 => 23, 15 => 7, 16 => 8, 17 => array(1,14), 23 => array(1,15), 24 => array(1,21), 25 => 22 ), array( 1 => array(2,6)), array( 14 => array(2,13), 18 => array(2,13), 22 => array(2,13), 24 => array(2,13)), array( 18 => array(1,24), 22 => array(1,25)), array( 18 => array(2,16), 22 => array(2,16)), array( 21 => array(1,26)), array( 14 => array(2,18), 18 => array(2,18), 22 => array(2,18), 24 => array(2,18)), array( 22 => array(1,28), 24 => array(1,27)), array( 22 => array(2,20), 24 => array(2,20)), array( 14 => array(2,14), 18 => array(2,14), 22 => array(2,14), 24 => array(2,14)), array( 3 => 20, 4 => array(1,12), 20 => 29 ), array( 3 => 5, 4 => array(1,12), 5 => 6, 6 => array(1,13), 7 => 3, 8 => array(1,9), 9 => 4, 10 => array(1,10), 11 => array(1,11), 13 => 30, 15 => 7, 16 => 8, 17 => array(1,14), 23 => array(1,15)), array( 14 => array(2,19), 18 => array(2,19), 22 => array(2,19), 24 => array(2,19)), array( 3 => 5, 4 => array(1,12), 5 => 6, 6 => array(1,13), 7 => 3, 8 => array(1,9), 9 => 4, 10 => array(1,10), 11 => array(1,11), 13 => 31, 15 => 7, 16 => 8, 17 => array(1,14), 23 => array(1,15)), array( 18 => array(2,17), 22 => array(2,17)), array( 18 => array(2,15), 22 => array(2,15)), array( 22 => array(2,21), 24 => array(2,21)),
  31989. );
  31990. private $defaultActions = array(
  31991. 16 => array(2, 6)
  31992. );
  31993. public function lint($input)
  31994. {
  31995. try {
  31996. $this->parse($input);
  31997. } catch (ParsingException $e) {
  31998. return $e;
  31999. }
  32000. }
  32001. public function parse($input, $flags = 0)
  32002. {
  32003. $this->failOnBOM($input);
  32004. $this->flags = $flags;
  32005. $this->stack = array(0);
  32006. $this->vstack = array(null);
  32007. $this->lstack = array();
  32008. $yytext = '';
  32009. $yylineno = 0;
  32010. $yyleng = 0;
  32011. $recovering = 0;
  32012. $TERROR = 2;
  32013. $EOF = 1;
  32014. $this->lexer = new Lexer();
  32015. $this->lexer->setInput($input);
  32016. $yyloc = $this->lexer->yylloc;
  32017. $this->lstack[] = $yyloc;
  32018. $symbol = null;
  32019. $preErrorSymbol = null;
  32020. $state = null;
  32021. $action = null;
  32022. $a = null;
  32023. $r = null;
  32024. $yyval = new stdClass;
  32025. $p = null;
  32026. $len = null;
  32027. $newState = null;
  32028. $expected = null;
  32029. $errStr = null;
  32030. while (true) {
  32031. $state = $this->stack[count($this->stack)-1];
  32032. if (isset($this->defaultActions[$state])) {
  32033. $action = $this->defaultActions[$state];
  32034. } else {
  32035. if ($symbol == null) {
  32036. $symbol = $this->lex();
  32037. }
  32038. $action = isset($this->table[$state][$symbol]) ? $this->table[$state][$symbol] : false;
  32039. }
  32040. if (!$action || !$action[0]) {
  32041. if (!$recovering) {
  32042. $expected = array();
  32043. foreach ($this->table[$state] as $p => $ignore) {
  32044. if (isset($this->terminals_[$p]) && $p > 2) {
  32045. $expected[] = "'" . $this->terminals_[$p] . "'";
  32046. }
  32047. }
  32048. $message = null;
  32049. if (in_array("'STRING'", $expected) && in_array(substr($this->lexer->match, 0, 1), array('"', "'"))) {
  32050. $message = "Invalid string";
  32051. if ("'" === substr($this->lexer->match, 0, 1)) {
  32052. $message .= ", it appears you used single quotes instead of double quotes";
  32053. } elseif (preg_match('{".+?(\\\\[^"bfnrt/\\\\u])}', $this->lexer->getUpcomingInput(), $match)) {
  32054. $message .= ", it appears you have an unescaped backslash at: ".$match[1];
  32055. } elseif (preg_match('{"(?:[^"]+|\\\\")*$}m', $this->lexer->getUpcomingInput())) {
  32056. $message .= ", it appears you forgot to terminated the string, or attempted to write a multiline string which is invalid";
  32057. }
  32058. }
  32059. $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n";
  32060. $errStr .= $this->lexer->showPosition() . "\n";
  32061. if ($message) {
  32062. $errStr .= $message;
  32063. } else {
  32064. $errStr .= (count($expected) > 1) ? "Expected one of: " : "Expected: ";
  32065. $errStr .= implode(', ', $expected);
  32066. }
  32067. if (',' === substr(trim($this->lexer->getPastInput()), -1)) {
  32068. $errStr .= " - It appears you have an extra trailing comma";
  32069. }
  32070. $this->parseError($errStr, array(
  32071. 'text' => $this->lexer->match,
  32072. 'token' => !empty($this->terminals_[$symbol]) ? $this->terminals_[$symbol] : $symbol,
  32073. 'line' => $this->lexer->yylineno,
  32074. 'loc' => $yyloc,
  32075. 'expected' => $expected,
  32076. ));
  32077. }
  32078. if ($recovering == 3) {
  32079. if ($symbol == $EOF) {
  32080. throw new ParsingException($errStr ?: 'Parsing halted.');
  32081. }
  32082. $yyleng = $this->lexer->yyleng;
  32083. $yytext = $this->lexer->yytext;
  32084. $yylineno = $this->lexer->yylineno;
  32085. $yyloc = $this->lexer->yylloc;
  32086. $symbol = $this->lex();
  32087. }
  32088. while (true) {
  32089. if (array_key_exists($TERROR, $this->table[$state])) {
  32090. break;
  32091. }
  32092. if ($state == 0) {
  32093. throw new ParsingException($errStr ?: 'Parsing halted.');
  32094. }
  32095. $this->popStack(1);
  32096. $state = $this->stack[count($this->stack)-1];
  32097. }
  32098. $preErrorSymbol = $symbol;
  32099. $symbol = $TERROR;
  32100. $state = $this->stack[count($this->stack)-1];
  32101. $action = isset($this->table[$state][$TERROR]) ? $this->table[$state][$TERROR] : false;
  32102. $recovering = 3;
  32103. }
  32104. if (is_array($action[0]) && count($action) > 1) {
  32105. throw new ParsingException('Parse Error: multiple actions possible at state: ' . $state . ', token: ' . $symbol);
  32106. }
  32107. switch ($action[0]) {
  32108. case 1:
  32109. $this->stack[] = $symbol;
  32110. $this->vstack[] = $this->lexer->yytext;
  32111. $this->lstack[] = $this->lexer->yylloc;
  32112. $this->stack[] = $action[1];
  32113. $symbol = null;
  32114. if (!$preErrorSymbol) {
  32115. $yyleng = $this->lexer->yyleng;
  32116. $yytext = $this->lexer->yytext;
  32117. $yylineno = $this->lexer->yylineno;
  32118. $yyloc = $this->lexer->yylloc;
  32119. if ($recovering > 0) {
  32120. $recovering--;
  32121. }
  32122. } else {
  32123. $symbol = $preErrorSymbol;
  32124. $preErrorSymbol = null;
  32125. }
  32126. break;
  32127. case 2:
  32128. $len = $this->productions_[$action[1]][1];
  32129. $yyval->token = $this->vstack[count($this->vstack) - $len];
  32130. $yyval->store = array(
  32131. 'first_line' => $this->lstack[count($this->lstack) - ($len ?: 1)]['first_line'],
  32132. 'last_line' => $this->lstack[count($this->lstack) - 1]['last_line'],
  32133. 'first_column' => $this->lstack[count($this->lstack) - ($len ?: 1)]['first_column'],
  32134. 'last_column' => $this->lstack[count($this->lstack) - 1]['last_column'],
  32135. );
  32136. $r = $this->performAction($yyval, $yytext, $yyleng, $yylineno, $action[1], $this->vstack, $this->lstack);
  32137. if (!$r instanceof Undefined) {
  32138. return $r;
  32139. }
  32140. if ($len) {
  32141. $this->popStack($len);
  32142. }
  32143. $this->stack[] = $this->productions_[$action[1]][0];
  32144. $this->vstack[] = $yyval->token;
  32145. $this->lstack[] = $yyval->store;
  32146. $newState = $this->table[$this->stack[count($this->stack)-2]][$this->stack[count($this->stack)-1]];
  32147. $this->stack[] = $newState;
  32148. break;
  32149. case 3:
  32150. return true;
  32151. }
  32152. }
  32153. return true;
  32154. }
  32155. protected function parseError($str, $hash)
  32156. {
  32157. throw new ParsingException($str, $hash);
  32158. }
  32159. private function performAction(stdClass $yyval, $yytext, $yyleng, $yylineno, $yystate, &$tokens)
  32160. {
  32161. $len = count($tokens) - 1;
  32162. switch ($yystate) {
  32163. case 1:
  32164. $yytext = preg_replace_callback('{(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4})}', array($this, 'stringInterpolation'), $yytext);
  32165. $yyval->token = $yytext;
  32166. break;
  32167. case 2:
  32168. if (strpos($yytext, 'e') !== false || strpos($yytext, 'E') !== false) {
  32169. $yyval->token = floatval($yytext);
  32170. } else {
  32171. $yyval->token = strpos($yytext, '.') === false ? intval($yytext) : floatval($yytext);
  32172. }
  32173. break;
  32174. case 3:
  32175. $yyval->token = null;
  32176. break;
  32177. case 4:
  32178. $yyval->token = true;
  32179. break;
  32180. case 5:
  32181. $yyval->token = false;
  32182. break;
  32183. case 6:
  32184. return $yyval->token = $tokens[$len-1];
  32185. case 13:
  32186. if ($this->flags & self::PARSE_TO_ASSOC) {
  32187. $yyval->token = array();
  32188. } else {
  32189. $yyval->token = new stdClass;
  32190. }
  32191. break;
  32192. case 14:
  32193. $yyval->token = $tokens[$len-1];
  32194. break;
  32195. case 15:
  32196. $yyval->token = array($tokens[$len-2], $tokens[$len]);
  32197. break;
  32198. case 16:
  32199. $property = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0];
  32200. if ($this->flags & self::PARSE_TO_ASSOC) {
  32201. $yyval->token = array();
  32202. $yyval->token[$property] = $tokens[$len][1];
  32203. } else {
  32204. $yyval->token = new stdClass;
  32205. $yyval->token->$property = $tokens[$len][1];
  32206. }
  32207. break;
  32208. case 17:
  32209. if ($this->flags & self::PARSE_TO_ASSOC) {
  32210. $yyval->token =& $tokens[$len-2];
  32211. $key = $tokens[$len][0];
  32212. if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2][$key])) {
  32213. $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n";
  32214. $errStr .= $this->lexer->showPosition() . "\n";
  32215. $errStr .= "Duplicate key: ".$tokens[$len][0];
  32216. throw new ParsingException($errStr);
  32217. } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2][$key])) {
  32218. $duplicateCount = 1;
  32219. do {
  32220. $duplicateKey = $key . '.' . $duplicateCount++;
  32221. } while (isset($tokens[$len-2][$duplicateKey]));
  32222. $key = $duplicateKey;
  32223. }
  32224. $tokens[$len-2][$key] = $tokens[$len][1];
  32225. } else {
  32226. $yyval->token = $tokens[$len-2];
  32227. $key = $tokens[$len][0] === '' ? '_empty_' : $tokens[$len][0];
  32228. if (($this->flags & self::DETECT_KEY_CONFLICTS) && isset($tokens[$len-2]->{$key})) {
  32229. $errStr = 'Parse error on line ' . ($yylineno+1) . ":\n";
  32230. $errStr .= $this->lexer->showPosition() . "\n";
  32231. $errStr .= "Duplicate key: ".$tokens[$len][0];
  32232. throw new ParsingException($errStr);
  32233. } elseif (($this->flags & self::ALLOW_DUPLICATE_KEYS) && isset($tokens[$len-2]->{$key})) {
  32234. $duplicateCount = 1;
  32235. do {
  32236. $duplicateKey = $key . '.' . $duplicateCount++;
  32237. } while (isset($tokens[$len-2]->$duplicateKey));
  32238. $key = $duplicateKey;
  32239. }
  32240. $tokens[$len-2]->$key = $tokens[$len][1];
  32241. }
  32242. break;
  32243. case 18:
  32244. $yyval->token = array();
  32245. break;
  32246. case 19:
  32247. $yyval->token = $tokens[$len-1];
  32248. break;
  32249. case 20:
  32250. $yyval->token = array($tokens[$len]);
  32251. break;
  32252. case 21:
  32253. $tokens[$len-2][] = $tokens[$len];
  32254. $yyval->token = $tokens[$len-2];
  32255. break;
  32256. }
  32257. return new Undefined();
  32258. }
  32259. private function stringInterpolation($match)
  32260. {
  32261. switch ($match[0]) {
  32262. case '\\\\':
  32263. return '\\';
  32264. case '\"':
  32265. return '"';
  32266. case '\b':
  32267. return chr(8);
  32268. case '\f':
  32269. return chr(12);
  32270. case '\n':
  32271. return "\n";
  32272. case '\r':
  32273. return "\r";
  32274. case '\t':
  32275. return "\t";
  32276. case '\/':
  32277. return "/";
  32278. default:
  32279. return html_entity_decode('&#x'.ltrim(substr($match[0], 2), '0').';', 0, 'UTF-8');
  32280. }
  32281. }
  32282. private function popStack($n)
  32283. {
  32284. $this->stack = array_slice($this->stack, 0, - (2 * $n));
  32285. $this->vstack = array_slice($this->vstack, 0, - $n);
  32286. $this->lstack = array_slice($this->lstack, 0, - $n);
  32287. }
  32288. private function lex()
  32289. {
  32290. $token = $this->lexer->lex() ?: 1;
  32291. if (!is_numeric($token)) {
  32292. $token = isset($this->symbols[$token]) ? $this->symbols[$token] : $token;
  32293. }
  32294. return $token;
  32295. }
  32296. private function failOnBOM($input)
  32297. {
  32298. $bom = "\xEF\xBB\xBF";
  32299. if (substr($input, 0, 3) === $bom) {
  32300. $this->parseError("BOM detected, make sure your input does not include a Unicode Byte-Order-Mark", array());
  32301. }
  32302. }
  32303. }
  32304. <?php
  32305. namespace Seld\JsonLint;
  32306. class Lexer
  32307. {
  32308. private $EOF = 1;
  32309. private $rules = array(
  32310. 0 => '/^\s+/',
  32311. 1 => '/^-?([0-9]|[1-9][0-9]+)(\.[0-9]+)?([eE][+-]?[0-9]+)?\b/',
  32312. 2 => '{^"(?:\\\\["bfnrt/\\\\]|\\\\u[a-fA-F0-9]{4}|[^\0-\x09\x0a-\x1f\\\\"]+)*"}',
  32313. 3 => '/^\{/',
  32314. 4 => '/^\}/',
  32315. 5 => '/^\[/',
  32316. 6 => '/^\]/',
  32317. 7 => '/^,/',
  32318. 8 => '/^:/',
  32319. 9 => '/^true\b/',
  32320. 10 => '/^false\b/',
  32321. 11 => '/^null\b/',
  32322. 12 => '/^$/',
  32323. 13 => '/^./',
  32324. );
  32325. private $conditions = array(
  32326. "INITIAL" => array(
  32327. "rules" => array(0,1,2,3,4,5,6,7,8,9,10,11,12,13),
  32328. "inclusive" => true,
  32329. ),
  32330. );
  32331. private $conditionStack;
  32332. private $input;
  32333. private $more;
  32334. private $done;
  32335. private $matched;
  32336. public $match;
  32337. public $yylineno;
  32338. public $yyleng;
  32339. public $yytext;
  32340. public $yylloc;
  32341. public function lex()
  32342. {
  32343. $r = $this->next();
  32344. if (!$r instanceof Undefined) {
  32345. return $r;
  32346. }
  32347. return $this->lex();
  32348. }
  32349. public function setInput($input)
  32350. {
  32351. $this->input = $input;
  32352. $this->more = false;
  32353. $this->done = false;
  32354. $this->yylineno = $this->yyleng = 0;
  32355. $this->yytext = $this->matched = $this->match = '';
  32356. $this->conditionStack = array('INITIAL');
  32357. $this->yylloc = array('first_line' => 1, 'first_column' => 0, 'last_line' => 1, 'last_column' => 0);
  32358. return $this;
  32359. }
  32360. public function showPosition()
  32361. {
  32362. $pre = str_replace("\n", '', $this->getPastInput());
  32363. $c = str_repeat('-', max(0, strlen($pre) - 1));
  32364. return $pre . str_replace("\n", '', $this->getUpcomingInput()) . "\n" . $c . "^";
  32365. }
  32366. public function getPastInput()
  32367. {
  32368. $past = substr($this->matched, 0, strlen($this->matched) - strlen($this->match));
  32369. return (strlen($past) > 20 ? '...' : '') . substr($past, -20);
  32370. }
  32371. public function getUpcomingInput()
  32372. {
  32373. $next = $this->match;
  32374. if (strlen($next) < 20) {
  32375. $next .= substr($this->input, 0, 20 - strlen($next));
  32376. }
  32377. return substr($next, 0, 20) . (strlen($next) > 20 ? '...' : '');
  32378. }
  32379. protected function parseError($str, $hash)
  32380. {
  32381. throw new \Exception($str);
  32382. }
  32383. private function next()
  32384. {
  32385. if ($this->done) {
  32386. return $this->EOF;
  32387. }
  32388. if (!$this->input) {
  32389. $this->done = true;
  32390. }
  32391. $token = null;
  32392. $match = null;
  32393. $col = null;
  32394. $lines = null;
  32395. if (!$this->more) {
  32396. $this->yytext = '';
  32397. $this->match = '';
  32398. }
  32399. $rules = $this->getCurrentRules();
  32400. $rulesLen = count($rules);
  32401. for ($i=0; $i < $rulesLen; $i++) {
  32402. if (preg_match($this->rules[$rules[$i]], $this->input, $match)) {
  32403. preg_match_all('/\n.*/', $match[0], $lines);
  32404. $lines = $lines[0];
  32405. if ($lines) {
  32406. $this->yylineno += count($lines);
  32407. }
  32408. $this->yylloc = array(
  32409. 'first_line' => $this->yylloc['last_line'],
  32410. 'last_line' => $this->yylineno+1,
  32411. 'first_column' => $this->yylloc['last_column'],
  32412. 'last_column' => $lines ? strlen($lines[count($lines) - 1]) - 1 : $this->yylloc['last_column'] + strlen($match[0]),
  32413. );
  32414. $this->yytext .= $match[0];
  32415. $this->match .= $match[0];
  32416. $this->yyleng = strlen($this->yytext);
  32417. $this->more = false;
  32418. $this->input = substr($this->input, strlen($match[0]));
  32419. $this->matched .= $match[0];
  32420. $token = $this->performAction($rules[$i], $this->conditionStack[count($this->conditionStack)-1]);
  32421. if ($token) {
  32422. return $token;
  32423. }
  32424. return new Undefined();
  32425. }
  32426. }
  32427. if ($this->input === "") {
  32428. return $this->EOF;
  32429. }
  32430. $this->parseError(
  32431. 'Lexical error on line ' . ($this->yylineno+1) . ". Unrecognized text.\n" . $this->showPosition(),
  32432. array(
  32433. 'text' => "",
  32434. 'token' => null,
  32435. 'line' => $this->yylineno,
  32436. )
  32437. );
  32438. }
  32439. private function getCurrentRules()
  32440. {
  32441. return $this->conditions[$this->conditionStack[count($this->conditionStack)-1]]['rules'];
  32442. }
  32443. private function performAction($avoiding_name_collisions, $YY_START)
  32444. {
  32445. switch ($avoiding_name_collisions) {
  32446. case 0:
  32447. break;
  32448. case 1:
  32449. return 6;
  32450. break;
  32451. case 2:
  32452. $this->yytext = substr($this->yytext, 1, $this->yyleng-2);
  32453. return 4;
  32454. case 3:
  32455. return 17;
  32456. case 4:
  32457. return 18;
  32458. case 5:
  32459. return 23;
  32460. case 6:
  32461. return 24;
  32462. case 7:
  32463. return 22;
  32464. case 8:
  32465. return 21;
  32466. case 9:
  32467. return 10;
  32468. case 10:
  32469. return 11;
  32470. case 11:
  32471. return 8;
  32472. case 12:
  32473. return 14;
  32474. case 13:
  32475. return 'INVALID';
  32476. }
  32477. }
  32478. }
  32479. <?php
  32480. namespace Seld\JsonLint;
  32481. class ParsingException extends \Exception
  32482. {
  32483. protected $details;
  32484. public function __construct($message, $details = array())
  32485. {
  32486. $this->details = $details;
  32487. parent::__construct($message);
  32488. }
  32489. public function getDetails()
  32490. {
  32491. return $this->details;
  32492. }
  32493. }
  32494. <?php
  32495. namespace Seld\JsonLint;
  32496. class Undefined
  32497. {
  32498. }
  32499. Copyright (c) 2008, Gradua Networks
  32500. Author: Bruno Prieto Reis
  32501. All rights reserved.
  32502. Redistribution and use in source and binary forms, with or without
  32503. modification, are permitted provided that the following conditions are met:
  32504. * Redistributions of source code must retain the above copyright notice, this
  32505. list of conditions and the following disclaimer.
  32506. * Redistributions in binary form must reproduce the above copyright notice,
  32507. this list of conditions and the following disclaimer in the documentation
  32508. and/or other materials provided with the distribution.
  32509. * Neither the name of the Gradua Networks nor the names of its contributors
  32510. may be used to endorse or promote products derived from this software
  32511. without specific prior written permission.
  32512. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  32513. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  32514. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  32515. DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  32516. FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  32517. DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  32518. SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32519. CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  32520. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  32521. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32522. <?php
  32523. namespace JsonSchema\Constraints;
  32524. class Collection extends Constraint
  32525. {
  32526. public function check($value, $schema = null, $path = null, $i = null)
  32527. {
  32528. if (isset($schema->minItems) && count($value) < $schema->minItems) {
  32529. $this->addError($path, "There must be a minimum of " . $schema->minItems . " in the array");
  32530. }
  32531. if (isset($schema->maxItems) && count($value) > $schema->maxItems) {
  32532. $this->addError($path, "There must be a maximum of " . $schema->maxItems . " in the array");
  32533. }
  32534. if (isset($schema->uniqueItems)) {
  32535. $unique = $value;
  32536. if (is_array($value) && count($value)) {
  32537. $unique = array_map(function($e) { return var_export($e, true); }, $value);
  32538. }
  32539. if (count(array_unique($unique)) != count($value)) {
  32540. $this->addError($path, "There are no duplicates allowed in the array");
  32541. }
  32542. }
  32543. if (isset($schema->items)) {
  32544. $this->validateItems($value, $schema, $path, $i);
  32545. }
  32546. }
  32547. protected function validateItems($value, $schema = null, $path = null, $i = null)
  32548. {
  32549. if (is_object($schema->items)) {
  32550. foreach ($value as $k => $v) {
  32551. $initErrors = $this->getErrors();
  32552. $this->checkUndefined($v, $schema->items, $path, $k);
  32553. if (count($initErrors) < count($this->getErrors()) && (isset($schema->additionalItems) && $schema->additionalItems !== false)) {
  32554. $secondErrors = $this->getErrors();
  32555. $this->checkUndefined($v, $schema->additionalItems, $path, $k);
  32556. }
  32557. if (isset($secondErrors) && count($secondErrors) < count($this->getErrors())) {
  32558. $this->errors = $secondErrors;
  32559. } else if (isset($secondErrors) && count($secondErrors) === count($this->getErrors())) {
  32560. $this->errors = $initErrors;
  32561. }
  32562. }
  32563. } else {
  32564. foreach ($value as $k => $v) {
  32565. if (array_key_exists($k, $schema->items)) {
  32566. $this->checkUndefined($v, $schema->items[$k], $path, $k);
  32567. } else {
  32568. if (property_exists($schema, 'additionalItems')) {
  32569. if ($schema->additionalItems !== false) {
  32570. $this->checkUndefined($v, $schema->additionalItems, $path, $k);
  32571. } else {
  32572. $this->addError(
  32573. $path, 'The item ' . $i . '[' . $k . '] is not defined and the definition does not allow additional items');
  32574. }
  32575. } else {
  32576. $this->checkUndefined($v, new \stdClass(), $path, $k);
  32577. }
  32578. }
  32579. }
  32580. if(count($value) > 0) {
  32581. for ($k = count($value); $k < count($schema->items); $k++) {
  32582. $this->checkUndefined(new Undefined(), $schema->items[$k], $path, $k);
  32583. }
  32584. }
  32585. }
  32586. }
  32587. }<?php
  32588. namespace JsonSchema\Constraints;
  32589. use JsonSchema\Uri\UriRetriever;
  32590. abstract class Constraint implements ConstraintInterface
  32591. {
  32592. protected $checkMode = self::CHECK_MODE_NORMAL;
  32593. protected $uriRetriever;
  32594. protected $errors = array();
  32595. protected $inlineSchemaProperty = '$schema';
  32596. const CHECK_MODE_NORMAL = 1;
  32597. const CHECK_MODE_TYPE_CAST = 2;
  32598. public function __construct($checkMode = self::CHECK_MODE_NORMAL, UriRetriever $uriRetriever = null)
  32599. {
  32600. $this->checkMode = $checkMode;
  32601. $this->uriRetriever = $uriRetriever;
  32602. }
  32603. public function getUriRetriever()
  32604. {
  32605. if (is_null($this->uriRetriever))
  32606. {
  32607. $this->setUriRetriever(new UriRetriever);
  32608. }
  32609. return $this->uriRetriever;
  32610. }
  32611. public function setUriRetriever(UriRetriever $uriRetriever)
  32612. {
  32613. $this->uriRetriever = $uriRetriever;
  32614. }
  32615. public function addError($path, $message)
  32616. {
  32617. $this->errors[] = array(
  32618. 'property' => $path,
  32619. 'message' => $message
  32620. );
  32621. }
  32622. public function addErrors(array $errors)
  32623. {
  32624. $this->errors = array_merge($this->errors, $errors);
  32625. }
  32626. public function getErrors()
  32627. {
  32628. return $this->errors;
  32629. }
  32630. public function isValid()
  32631. {
  32632. return !$this->getErrors();
  32633. }
  32634. public function reset()
  32635. {
  32636. $this->errors = array();
  32637. }
  32638. protected function incrementPath($path, $i)
  32639. {
  32640. if ($path !== '') {
  32641. if (is_int($i)) {
  32642. $path .= '[' . $i . ']';
  32643. } elseif ($i == '') {
  32644. $path .= '';
  32645. } else {
  32646. $path .= '.' . $i;
  32647. }
  32648. } else {
  32649. $path = $i;
  32650. }
  32651. return $path;
  32652. }
  32653. protected function checkArray($value, $schema = null, $path = null, $i = null)
  32654. {
  32655. $validator = new Collection($this->checkMode, $this->uriRetriever);
  32656. $validator->check($value, $schema, $path, $i);
  32657. $this->addErrors($validator->getErrors());
  32658. }
  32659. protected function checkObject($value, $schema = null, $path = null, $i = null, $patternProperties = null)
  32660. {
  32661. $validator = new Object($this->checkMode, $this->uriRetriever);
  32662. $validator->check($value, $schema, $path, $i, $patternProperties);
  32663. $this->addErrors($validator->getErrors());
  32664. }
  32665. protected function checkType($value, $schema = null, $path = null, $i = null)
  32666. {
  32667. $validator = new Type($this->checkMode, $this->uriRetriever);
  32668. $validator->check($value, $schema, $path, $i);
  32669. $this->addErrors($validator->getErrors());
  32670. }
  32671. protected function checkUndefined($value, $schema = null, $path = null, $i = null)
  32672. {
  32673. $validator = new Undefined($this->checkMode, $this->uriRetriever);
  32674. $validator->check($value, $schema, $path, $i);
  32675. $this->addErrors($validator->getErrors());
  32676. }
  32677. protected function checkString($value, $schema = null, $path = null, $i = null)
  32678. {
  32679. $validator = new String($this->checkMode, $this->uriRetriever);
  32680. $validator->check($value, $schema, $path, $i);
  32681. $this->addErrors($validator->getErrors());
  32682. }
  32683. protected function checkNumber($value, $schema = null, $path = null, $i = null)
  32684. {
  32685. $validator = new Number($this->checkMode, $this->uriRetriever);
  32686. $validator->check($value, $schema, $path, $i);
  32687. $this->addErrors($validator->getErrors());
  32688. }
  32689. protected function checkEnum($value, $schema = null, $path = null, $i = null)
  32690. {
  32691. $validator = new Enum($this->checkMode, $this->uriRetriever);
  32692. $validator->check($value, $schema, $path, $i);
  32693. $this->addErrors($validator->getErrors());
  32694. }
  32695. protected function checkFormat($value, $schema = null, $path = null, $i = null)
  32696. {
  32697. $validator = new Format($this->checkMode, $this->uriRetriever);
  32698. $validator->check($value, $schema, $path, $i);
  32699. $this->addErrors($validator->getErrors());
  32700. }
  32701. protected function retrieveUri($uri)
  32702. {
  32703. if (null === $this->uriRetriever) {
  32704. $this->setUriRetriever(new UriRetriever);
  32705. }
  32706. $jsonSchema = $this->uriRetriever->retrieve($uri);
  32707. return $jsonSchema;
  32708. }
  32709. }
  32710. <?php
  32711. namespace JsonSchema\Constraints;
  32712. interface ConstraintInterface
  32713. {
  32714. public function getErrors();
  32715. public function addErrors(array $errors);
  32716. public function addError($path, $message);
  32717. public function isValid();
  32718. public function check($value, $schema = null, $path = null, $i = null);
  32719. }<?php
  32720. namespace JsonSchema\Constraints;
  32721. class Enum extends Constraint
  32722. {
  32723. public function check($element, $schema = null, $path = null, $i = null)
  32724. {
  32725. if ($element instanceof Undefined && (!isset($schema->required) || !$schema->required)) {
  32726. return;
  32727. }
  32728. foreach ($schema->enum as $enum) {
  32729. if ((gettype($element) === gettype($enum)) && ($element == $enum)) {
  32730. return;
  32731. }
  32732. }
  32733. $this->addError($path, "does not have a value in the enumeration " . print_r($schema->enum, true));
  32734. }
  32735. }<?php
  32736. namespace JsonSchema\Constraints;
  32737. class Format extends Constraint
  32738. {
  32739. public function check($element, $schema = null, $path = null, $i = null)
  32740. {
  32741. if (!isset($schema->format)) {
  32742. return;
  32743. }
  32744. switch ($schema->format) {
  32745. case 'date':
  32746. if (!$date = $this->validateDateTime($element, 'Y-m-d')) {
  32747. $this->addError($path, sprintf('Invalid date %s, expected format YYYY-MM-DD', json_encode($element)));
  32748. }
  32749. break;
  32750. case 'time':
  32751. if (!$this->validateDateTime($element, 'H:i:s')) {
  32752. $this->addError($path, sprintf('Invalid time %s, expected format hh:mm:ss', json_encode($element)));
  32753. }
  32754. break;
  32755. case 'date-time':
  32756. if (!$this->validateDateTime($element, 'Y-m-d\TH:i:s\Z') &&
  32757. !$this->validateDateTime($element, 'Y-m-d\TH:i:s.u\Z') &&
  32758. !$this->validateDateTime($element, 'Y-m-d\TH:i:sP') &&
  32759. !$this->validateDateTime($element, 'Y-m-d\TH:i:sO')
  32760. ) {
  32761. $this->addError($path, sprintf('Invalid date-time %s, expected format YYYY-MM-DDThh:mm:ssZ or YYYY-MM-DDThh:mm:ss+hh:mm', json_encode($element)));
  32762. }
  32763. break;
  32764. case 'utc-millisec':
  32765. if (!$this->validateDateTime($element, 'U')) {
  32766. $this->addError($path, sprintf('Invalid time %s, expected integer of milliseconds since Epoch', json_encode($element)));
  32767. }
  32768. break;
  32769. case 'regex':
  32770. if (!$this->validateRegex($element)) {
  32771. $this->addError($path, 'Invalid regex format ' . $element);
  32772. }
  32773. break;
  32774. case 'color':
  32775. if (!$this->validateColor($element)) {
  32776. $this->addError($path, "Invalid color");
  32777. }
  32778. break;
  32779. case 'style':
  32780. if (!$this->validateStyle($element)) {
  32781. $this->addError($path, "Invalid style");
  32782. }
  32783. break;
  32784. case 'phone':
  32785. if (!$this->validatePhone($element)) {
  32786. $this->addError($path, "Invalid phone number");
  32787. }
  32788. break;
  32789. case 'uri':
  32790. if (null === filter_var($element, FILTER_VALIDATE_URL, FILTER_NULL_ON_FAILURE)) {
  32791. $this->addError($path, "Invalid URL format");
  32792. }
  32793. break;
  32794. case 'email':
  32795. if (null === filter_var($element, FILTER_VALIDATE_EMAIL, FILTER_NULL_ON_FAILURE)) {
  32796. $this->addError($path, "Invalid email");
  32797. }
  32798. break;
  32799. case 'ip-address':
  32800. case 'ipv4':
  32801. if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV4)) {
  32802. $this->addError($path, "Invalid IP address");
  32803. }
  32804. break;
  32805. case 'ipv6':
  32806. if (null === filter_var($element, FILTER_VALIDATE_IP, FILTER_NULL_ON_FAILURE | FILTER_FLAG_IPV6)) {
  32807. $this->addError($path, "Invalid IP address");
  32808. }
  32809. break;
  32810. case 'host-name':
  32811. case 'hostname':
  32812. if (!$this->validateHostname($element)) {
  32813. $this->addError($path, "Invalid hostname");
  32814. }
  32815. break;
  32816. default:
  32817. $this->addError($path, "Unknown format: " . json_encode($schema->format));
  32818. break;
  32819. }
  32820. }
  32821. protected function validateDateTime($datetime, $format)
  32822. {
  32823. $dt = \DateTime::createFromFormat($format, $datetime);
  32824. if (!$dt) {
  32825. return false;
  32826. }
  32827. return $datetime === $dt->format($format);
  32828. }
  32829. protected function validateRegex($regex)
  32830. {
  32831. return false !== @preg_match('/' . $regex . '/', '');
  32832. }
  32833. protected function validateColor($color)
  32834. {
  32835. if (in_array(strtolower($color), array('aqua', 'black', 'blue', 'fuchsia',
  32836. 'gray', 'green', 'lime', 'maroon', 'navy', 'olive', 'orange', 'purple',
  32837. 'red', 'silver', 'teal', 'white', 'yellow'))) {
  32838. return true;
  32839. }
  32840. return preg_match('/^#([a-f0-9]{3}|[a-f0-9]{6})$/i', $color);
  32841. }
  32842. protected function validateStyle($style)
  32843. {
  32844. $properties = explode(';', rtrim($style, ';'));
  32845. $invalidEntries = preg_grep('/^\s*[-a-z]+\s*:\s*.+$/i', $properties, PREG_GREP_INVERT);
  32846. return empty($invalidEntries);
  32847. }
  32848. protected function validatePhone($phone)
  32849. {
  32850. return preg_match('/^\+?(\(\d{3}\)|\d{3}) \d{3} \d{4}$/', $phone);
  32851. }
  32852. protected function validateHostname($host)
  32853. {
  32854. return preg_match('/^[_a-z]+\.([_a-z]+\.?)+$/i', $host);
  32855. }
  32856. }
  32857. <?php
  32858. namespace JsonSchema\Constraints;
  32859. class Number extends Constraint
  32860. {
  32861. public function check($element, $schema = null, $path = null, $i = null)
  32862. {
  32863. if (isset($schema->exclusiveMinimum)) {
  32864. if (isset($schema->minimum)) {
  32865. if ($schema->exclusiveMinimum && $element === $schema->minimum) {
  32866. $this->addError($path, "must have a minimum value greater than boundary value of " . $schema->minimum);
  32867. } else if ($element < $schema->minimum) {
  32868. $this->addError($path, "must have a minimum value of " . $schema->minimum);
  32869. }
  32870. } else {
  32871. $this->addError($path, "use of exclusiveMinimum requires presence of minimum");
  32872. }
  32873. } else if (isset($schema->minimum) && $element < $schema->minimum) {
  32874. $this->addError($path, "must have a minimum value of " . $schema->minimum);
  32875. }
  32876. if (isset($schema->exclusiveMaximum)) {
  32877. if (isset($schema->maximum)) {
  32878. if ($schema->exclusiveMaximum && $element === $schema->maximum) {
  32879. $this->addError($path, "must have a maximum value less than boundary value of " . $schema->maximum);
  32880. } else if ($element > $schema->maximum) {
  32881. $this->addError($path, "must have a maximum value of " . $schema->maximum);
  32882. }
  32883. } else {
  32884. $this->addError($path, "use of exclusiveMaximum requires presence of maximum");
  32885. }
  32886. } else if (isset($schema->maximum) && $element > $schema->maximum) {
  32887. $this->addError($path, "must have a maximum value of " . $schema->maximum);
  32888. }
  32889. if (isset($schema->divisibleBy) && $this->fmod($element, $schema->divisibleBy) != 0) {
  32890. $this->addError($path, "is not divisible by " . $schema->divisibleBy);
  32891. }
  32892. if (isset($schema->multipleOf) && $this->fmod($element, $schema->multipleOf) != 0) {
  32893. $this->addError($path, "must be a multiple of " . $schema->multipleOf);
  32894. }
  32895. $this->checkFormat($element, $schema, $path, $i);
  32896. }
  32897. private function fmod($number1, $number2)
  32898. {
  32899. $modulus = fmod($number1, $number2);
  32900. $precision = abs(0.0000000001);
  32901. $diff = (float)($modulus - $number2);
  32902. if (-$precision < $diff && $diff < $precision) {
  32903. return 0.0;
  32904. }
  32905. $decimals1 = mb_strpos($number1, ".") ? mb_strlen($number1) - mb_strpos($number1, ".") - 1 : 0;
  32906. $decimals2 = mb_strpos($number2, ".") ? mb_strlen($number2) - mb_strpos($number2, ".") - 1 : 0;
  32907. return (float)round($modulus, max($decimals1, $decimals2));
  32908. }
  32909. }
  32910. <?php
  32911. namespace JsonSchema\Constraints;
  32912. class Object extends Constraint
  32913. {
  32914. function check($element, $definition = null, $path = null, $additionalProp = null, $patternProperties = null)
  32915. {
  32916. if ($element instanceof Undefined) {
  32917. return;
  32918. }
  32919. $matches = array();
  32920. if ($patternProperties) {
  32921. $matches = $this->validatePatternProperties($element, $path, $patternProperties);
  32922. }
  32923. if ($definition) {
  32924. $this->validateDefinition($element, $definition, $path);
  32925. }
  32926. $this->validateElement($element, $matches, $definition, $path, $additionalProp);
  32927. }
  32928. public function validatePatternProperties($element, $path, $patternProperties)
  32929. {
  32930. $matches = array();
  32931. foreach ($patternProperties as $pregex => $schema) {
  32932. if (@preg_match('/'. $pregex . '/', '') === false) {
  32933. $this->addError($path, 'The pattern "' . $pregex . '" is invalid');
  32934. continue;
  32935. }
  32936. foreach ($element as $i => $value) {
  32937. if (preg_match('/' . $pregex . '/', $i)) {
  32938. $matches[] = $i;
  32939. $this->checkUndefined($value, $schema ? : new \stdClass(), $path, $i);
  32940. }
  32941. }
  32942. }
  32943. return $matches;
  32944. }
  32945. public function validateElement($element, $matches, $objectDefinition = null, $path = null, $additionalProp = null)
  32946. {
  32947. foreach ($element as $i => $value) {
  32948. $property = $this->getProperty($element, $i, new Undefined());
  32949. $definition = $this->getProperty($objectDefinition, $i);
  32950. if (!in_array($i, $matches) && $additionalProp === false && $this->inlineSchemaProperty !== $i && !$definition) {
  32951. $this->addError($path, "The property " . $i . " is not defined and the definition does not allow additional properties");
  32952. }
  32953. if (!in_array($i, $matches) && $additionalProp && !$definition) {
  32954. if ($additionalProp === true) {
  32955. $this->checkUndefined($value, null, $path, $i);
  32956. } else {
  32957. $this->checkUndefined($value, $additionalProp, $path, $i);
  32958. }
  32959. }
  32960. $require = $this->getProperty($definition, 'requires');
  32961. if ($require && !$this->getProperty($element, $require)) {
  32962. $this->addError($path, "the presence of the property " . $i . " requires that " . $require . " also be present");
  32963. }
  32964. if (!$definition) {
  32965. $this->checkUndefined($value, new \stdClass(), $path, $i);
  32966. }
  32967. }
  32968. }
  32969. public function validateDefinition($element, $objectDefinition = null, $path = null)
  32970. {
  32971. foreach ($objectDefinition as $i => $value) {
  32972. $property = $this->getProperty($element, $i, new Undefined());
  32973. $definition = $this->getProperty($objectDefinition, $i);
  32974. $this->checkUndefined($property, $definition, $path, $i);
  32975. }
  32976. }
  32977. protected function getProperty($element, $property, $fallback = null)
  32978. {
  32979. if (is_array($element) ) {
  32980. return array_key_exists($property, $element) ? $element[$property] : $fallback;
  32981. } elseif (is_object($element)) {
  32982. return property_exists($element, $property) ? $element->$property : $fallback;
  32983. }
  32984. return $fallback;
  32985. }
  32986. }<?php
  32987. namespace JsonSchema\Constraints;
  32988. use JsonSchema\Exception\InvalidArgumentException;
  32989. class Schema extends Constraint
  32990. {
  32991. public function check($element, $schema = null, $path = null, $i = null)
  32992. {
  32993. if ($schema !== null) {
  32994. $this->checkUndefined($element, $schema, '', '');
  32995. } elseif (property_exists($element, $this->inlineSchemaProperty)) {
  32996. $this->checkUndefined($element, $element->{$this->inlineSchemaProperty}, '', '');
  32997. } else {
  32998. throw new InvalidArgumentException('no schema found to verify against');
  32999. }
  33000. }
  33001. }<?php
  33002. namespace JsonSchema\Constraints;
  33003. class String extends Constraint
  33004. {
  33005. public function check($element, $schema = null, $path = null, $i = null)
  33006. {
  33007. if (isset($schema->maxLength) && $this->strlen($element) > $schema->maxLength) {
  33008. $this->addError($path, "must be at most " . $schema->maxLength . " characters long");
  33009. }
  33010. if (isset($schema->minLength) && $this->strlen($element) < $schema->minLength) {
  33011. $this->addError($path, "must be at least " . $schema->minLength . " characters long");
  33012. }
  33013. if (isset($schema->pattern) && !preg_match('#' . str_replace('#', '\\#', $schema->pattern) . '#', $element)) {
  33014. $this->addError($path, "does not match the regex pattern " . $schema->pattern);
  33015. }
  33016. $this->checkFormat($element, $schema, $path, $i);
  33017. }
  33018. private function strlen($string)
  33019. {
  33020. if (extension_loaded('mbstring')) {
  33021. return mb_strlen($string, mb_detect_encoding($string));
  33022. } else {
  33023. return strlen($string);
  33024. }
  33025. }
  33026. }
  33027. <?php
  33028. namespace JsonSchema\Constraints;
  33029. use JsonSchema\Exception\InvalidArgumentException;
  33030. use UnexpectedValueException as StandardUnexpectedValueException;
  33031. class Type extends Constraint
  33032. {
  33033. static $wording = array(
  33034. 'integer' => 'an integer',
  33035. 'number' => 'a number',
  33036. 'boolean' => 'a boolean',
  33037. 'object' => 'an object',
  33038. 'array' => 'an array',
  33039. 'string' => 'a string',
  33040. 'null' => 'a null',
  33041. 'any' => NULL,
  33042. 0 => NULL,
  33043. );
  33044. public function check($value = null, $schema = null, $path = null, $i = null)
  33045. {
  33046. $type = isset($schema->type) ? $schema->type : null;
  33047. $isValid = true;
  33048. if (is_array($type)) {
  33049. $validatedOneType = false;
  33050. $errors = array();
  33051. foreach ($type as $tp) {
  33052. $validator = new Type($this->checkMode);
  33053. $subSchema = new \stdClass();
  33054. $subSchema->type = $tp;
  33055. $validator->check($value, $subSchema, $path, null);
  33056. $error = $validator->getErrors();
  33057. if (!count($error)) {
  33058. $validatedOneType = true;
  33059. break;
  33060. }
  33061. $errors = $error;
  33062. }
  33063. if (!$validatedOneType) {
  33064. return $this->addErrors($errors);
  33065. }
  33066. } elseif (is_object($type)) {
  33067. $this->checkUndefined($value, $type, $path);
  33068. } else {
  33069. $isValid = $this->validateType($value, $type);
  33070. }
  33071. if ($isValid === false) {
  33072. if (!isset(self::$wording[$type])) {
  33073. throw new StandardUnexpectedValueException(
  33074. sprintf(
  33075. "No wording for %s available, expected wordings are: [%s]",
  33076. var_export($type, true),
  33077. implode(', ', array_filter(self::$wording)))
  33078. );
  33079. }
  33080. $this->addError($path, gettype($value) . " value found, but " . self::$wording[$type] . " is required");
  33081. }
  33082. }
  33083. protected function validateType($value, $type)
  33084. {
  33085. if (!$type) {
  33086. return true;
  33087. }
  33088. if ('integer' === $type) {
  33089. return is_int($value);
  33090. }
  33091. if ('number' === $type) {
  33092. return is_numeric($value) && !is_string($value);
  33093. }
  33094. if ('boolean' === $type) {
  33095. return is_bool($value);
  33096. }
  33097. if ('object' === $type) {
  33098. return is_object($value);
  33099. }
  33100. if ('array' === $type) {
  33101. return is_array($value);
  33102. }
  33103. if ('string' === $type) {
  33104. return is_string($value);
  33105. }
  33106. if ('null' === $type) {
  33107. return is_null($value);
  33108. }
  33109. if ('any' === $type) {
  33110. return true;
  33111. }
  33112. throw new InvalidArgumentException((is_object($value) ? 'object' : $value) . ' is an invalid type for ' . $type);
  33113. }
  33114. }<?php
  33115. namespace JsonSchema\Constraints;
  33116. use JsonSchema\Exception\InvalidArgumentException;
  33117. use JsonSchema\Uri\UriResolver;
  33118. class Undefined extends Constraint
  33119. {
  33120. public function check($value, $schema = null, $path = null, $i = null)
  33121. {
  33122. if (is_null($schema)) {
  33123. return;
  33124. }
  33125. if (!is_object($schema)) {
  33126. throw new InvalidArgumentException(
  33127. 'Given schema must be an object in ' . $path
  33128. . ' but is a ' . gettype($schema)
  33129. );
  33130. }
  33131. $i = is_null($i) ? "" : $i;
  33132. $path = $this->incrementPath($path, $i);
  33133. $this->validateCommonProperties($value, $schema, $path);
  33134. $this->validateOfProperties($value, $schema, $path);
  33135. $this->validateTypes($value, $schema, $path, $i);
  33136. }
  33137. public function validateTypes($value, $schema = null, $path = null, $i = null)
  33138. {
  33139. if (is_array($value)) {
  33140. $this->checkArray($value, $schema, $path, $i);
  33141. }
  33142. if (is_object($value) && (isset($schema->properties) || isset($schema->patternProperties))) {
  33143. $this->checkObject(
  33144. $value,
  33145. isset($schema->properties) ? $schema->properties : null,
  33146. $path,
  33147. isset($schema->additionalProperties) ? $schema->additionalProperties : null,
  33148. isset($schema->patternProperties) ? $schema->patternProperties : null
  33149. );
  33150. }
  33151. if (is_string($value)) {
  33152. $this->checkString($value, $schema, $path, $i);
  33153. }
  33154. if (is_numeric($value)) {
  33155. $this->checkNumber($value, $schema, $path, $i);
  33156. }
  33157. if (isset($schema->enum)) {
  33158. $this->checkEnum($value, $schema, $path, $i);
  33159. }
  33160. }
  33161. protected function validateCommonProperties($value, $schema = null, $path = null, $i = "")
  33162. {
  33163. if (isset($schema->extends)) {
  33164. if (is_string($schema->extends)) {
  33165. $schema->extends = $this->validateUri($schema, $schema->extends);
  33166. }
  33167. if (is_array($schema->extends)) {
  33168. foreach ($schema->extends as $extends) {
  33169. $this->checkUndefined($value, $extends, $path, $i);
  33170. }
  33171. } else {
  33172. $this->checkUndefined($value, $schema->extends, $path, $i);
  33173. }
  33174. }
  33175. if (is_object($value)) {
  33176. if (!($value instanceof Undefined) && isset($schema->required) && is_array($schema->required) ) {
  33177. foreach ($schema->required as $required) {
  33178. if (!property_exists($value, $required)) {
  33179. $this->addError($path, "the property " . $required . " is required");
  33180. }
  33181. }
  33182. } else if (isset($schema->required) && !is_array($schema->required)) {
  33183. if ( $schema->required && $value instanceof Undefined) {
  33184. $this->addError($path, "is missing and it is required");
  33185. }
  33186. }
  33187. }
  33188. if (!($value instanceof Undefined)) {
  33189. $this->checkType($value, $schema, $path);
  33190. }
  33191. if (isset($schema->disallow)) {
  33192. $initErrors = $this->getErrors();
  33193. $typeSchema = new \stdClass();
  33194. $typeSchema->type = $schema->disallow;
  33195. $this->checkType($value, $typeSchema, $path);
  33196. if (count($this->getErrors()) == count($initErrors)) {
  33197. $this->addError($path, "disallowed value was matched");
  33198. } else {
  33199. $this->errors = $initErrors;
  33200. }
  33201. }
  33202. if (isset($schema->not)) {
  33203. $initErrors = $this->getErrors();
  33204. $this->checkUndefined($value, $schema->not, $path, $i);
  33205. if (count($this->getErrors()) == count($initErrors)) {
  33206. $this->addError($path, "matched a schema which it should not");
  33207. } else {
  33208. $this->errors = $initErrors;
  33209. }
  33210. }
  33211. if (is_object($value)) {
  33212. if (isset($schema->minProperties)) {
  33213. if (count(get_object_vars($value)) < $schema->minProperties) {
  33214. $this->addError($path, "must contain a minimum of " . $schema->minProperties . " properties");
  33215. }
  33216. }
  33217. if (isset($schema->maxProperties)) {
  33218. if (count(get_object_vars($value)) > $schema->maxProperties) {
  33219. $this->addError($path, "must contain no more than " . $schema->maxProperties . " properties");
  33220. }
  33221. }
  33222. }
  33223. if (is_object($value) && isset($schema->dependencies)) {
  33224. $this->validateDependencies($value, $schema->dependencies, $path);
  33225. }
  33226. }
  33227. protected function validateOfProperties($value, $schema, $path, $i = "")
  33228. {
  33229. if ($value instanceof Undefined) {
  33230. return;
  33231. }
  33232. if (isset($schema->allOf)) {
  33233. $isValid = true;
  33234. foreach ($schema->allOf as $allOf) {
  33235. $initErrors = $this->getErrors();
  33236. $this->checkUndefined($value, $allOf, $path, $i);
  33237. $isValid = $isValid && (count($this->getErrors()) == count($initErrors));
  33238. }
  33239. if (!$isValid) {
  33240. $this->addError($path, "failed to match all schemas");
  33241. }
  33242. }
  33243. if (isset($schema->anyOf)) {
  33244. $isValid = false;
  33245. $startErrors = $this->getErrors();
  33246. foreach ($schema->anyOf as $anyOf) {
  33247. $initErrors = $this->getErrors();
  33248. $this->checkUndefined($value, $anyOf, $path, $i);
  33249. if ($isValid = (count($this->getErrors()) == count($initErrors))) {
  33250. break;
  33251. }
  33252. }
  33253. if (!$isValid) {
  33254. $this->addError($path, "failed to match at least one schema");
  33255. } else {
  33256. $this->errors = $startErrors;
  33257. }
  33258. }
  33259. if (isset($schema->oneOf)) {
  33260. $allErrors = array();
  33261. $matchedSchemas = 0;
  33262. $startErrors = $this->getErrors();
  33263. foreach ($schema->oneOf as $oneOf) {
  33264. $this->errors = array();
  33265. $this->checkUndefined($value, $oneOf, $path, $i);
  33266. if (count($this->getErrors()) == 0) {
  33267. $matchedSchemas++;
  33268. }
  33269. $allErrors = array_merge($allErrors, array_values($this->getErrors()));
  33270. }
  33271. if ($matchedSchemas !== 1) {
  33272. $this->addErrors(
  33273. array_merge(
  33274. $allErrors,
  33275. array(array(
  33276. 'property' => $path,
  33277. 'message' => "failed to match exactly one schema"
  33278. ),),
  33279. $startErrors
  33280. )
  33281. );
  33282. } else {
  33283. $this->errors = $startErrors;
  33284. }
  33285. }
  33286. }
  33287. protected function validateDependencies($value, $dependencies, $path, $i = "")
  33288. {
  33289. foreach ($dependencies as $key => $dependency) {
  33290. if (property_exists($value, $key)) {
  33291. if (is_string($dependency)) {
  33292. if (!property_exists($value, $dependency)) {
  33293. $this->addError($path, "$key depends on $dependency and $dependency is missing");
  33294. }
  33295. } else if (is_array($dependency)) {
  33296. foreach ($dependency as $d) {
  33297. if (!property_exists($value, $d)) {
  33298. $this->addError($path, "$key depends on $d and $d is missing");
  33299. }
  33300. }
  33301. } else if (is_object($dependency)) {
  33302. $this->checkUndefined($value, $dependency, $path, $i);
  33303. }
  33304. }
  33305. }
  33306. }
  33307. protected function validateUri($schema, $schemaUri = null)
  33308. {
  33309. $resolver = new UriResolver();
  33310. $retriever = $this->getUriRetriever();
  33311. $jsonSchema = null;
  33312. if ($resolver->isValid($schemaUri)) {
  33313. $schemaId = property_exists($schema, 'id') ? $schema->id : null;
  33314. $jsonSchema = $retriever->retrieve($schemaId, $schemaUri);
  33315. }
  33316. return $jsonSchema;
  33317. }
  33318. }
  33319. <?php
  33320. namespace JsonSchema\Exception;
  33321. class InvalidArgumentException extends \InvalidArgumentException
  33322. {
  33323. }<?php
  33324. namespace JsonSchema\Exception;
  33325. class InvalidSchemaMediaTypeException extends \RuntimeException
  33326. {
  33327. }<?php
  33328. namespace JsonSchema\Exception;
  33329. class InvalidSourceUriException extends InvalidArgumentException
  33330. {
  33331. }
  33332. <?php
  33333. namespace JsonSchema\Exception;
  33334. class JsonDecodingException extends \RuntimeException
  33335. {
  33336. public function __construct($code = JSON_ERROR_NONE, \Exception $previous = null)
  33337. {
  33338. switch ($code) {
  33339. case JSON_ERROR_DEPTH:
  33340. $message = 'The maximum stack depth has been exceeded';
  33341. break;
  33342. case JSON_ERROR_STATE_MISMATCH:
  33343. $message = 'Invalid or malformed JSON';
  33344. break;
  33345. case JSON_ERROR_CTRL_CHAR:
  33346. $message = 'Control character error, possibly incorrectly encoded';
  33347. break;
  33348. case JSON_ERROR_UTF8:
  33349. $message = 'Malformed UTF-8 characters, possibly incorrectly encoded';
  33350. break;
  33351. case JSON_ERROR_SYNTAX:
  33352. $message = 'JSON syntax is malformed';
  33353. break;
  33354. default:
  33355. $message = 'Syntax error';
  33356. }
  33357. parent::__construct($message, $code, $previous);
  33358. }
  33359. }<?php
  33360. namespace JsonSchema\Exception;
  33361. class ResourceNotFoundException extends \RuntimeException
  33362. {
  33363. }<?php
  33364. namespace JsonSchema\Exception;
  33365. class UriResolverException extends \RuntimeException
  33366. {
  33367. }<?php
  33368. namespace JsonSchema;
  33369. use JsonSchema\Uri\Retrievers\UriRetrieverInterface;
  33370. use JsonSchema\Uri\UriRetriever;
  33371. class RefResolver
  33372. {
  33373. protected static $depth = 0;
  33374. public static $maxDepth = 7;
  33375. protected $uriRetriever = null;
  33376. public function __construct($retriever = null)
  33377. {
  33378. $this->uriRetriever = $retriever;
  33379. }
  33380. public function fetchRef($ref, $sourceUri)
  33381. {
  33382. $retriever = $this->getUriRetriever();
  33383. $jsonSchema = $retriever->retrieve($ref, $sourceUri);
  33384. $this->resolve($jsonSchema);
  33385. return $jsonSchema;
  33386. }
  33387. public function getUriRetriever()
  33388. {
  33389. if (is_null($this->uriRetriever)) {
  33390. $this->setUriRetriever(new UriRetriever);
  33391. }
  33392. return $this->uriRetriever;
  33393. }
  33394. public function resolve($schema, $sourceUri = null)
  33395. {
  33396. if (self::$depth > self::$maxDepth) {
  33397. return;
  33398. }
  33399. ++self::$depth;
  33400. if (! is_object($schema)) {
  33401. --self::$depth;
  33402. return;
  33403. }
  33404. if (null === $sourceUri && ! empty($schema->id)) {
  33405. $sourceUri = $schema->id;
  33406. }
  33407. $this->resolveRef($schema, $sourceUri);
  33408. foreach (array('additionalItems', 'additionalProperties', 'extends', 'items') as $propertyName) {
  33409. $this->resolveProperty($schema, $propertyName, $sourceUri);
  33410. }
  33411. foreach (array('disallow', 'extends', 'items', 'type', 'allOf', 'anyOf', 'oneOf') as $propertyName) {
  33412. $this->resolveArrayOfSchemas($schema, $propertyName, $sourceUri);
  33413. }
  33414. foreach (array('dependencies', 'patternProperties', 'properties') as $propertyName) {
  33415. $this->resolveObjectOfSchemas($schema, $propertyName, $sourceUri);
  33416. }
  33417. --self::$depth;
  33418. }
  33419. public function resolveArrayOfSchemas($schema, $propertyName, $sourceUri)
  33420. {
  33421. if (! isset($schema->$propertyName) || ! is_array($schema->$propertyName)) {
  33422. return;
  33423. }
  33424. foreach ($schema->$propertyName as $possiblySchema) {
  33425. $this->resolve($possiblySchema, $sourceUri);
  33426. }
  33427. }
  33428. public function resolveObjectOfSchemas($schema, $propertyName, $sourceUri)
  33429. {
  33430. if (! isset($schema->$propertyName) || ! is_object($schema->$propertyName)) {
  33431. return;
  33432. }
  33433. foreach (get_object_vars($schema->$propertyName) as $possiblySchema) {
  33434. $this->resolve($possiblySchema, $sourceUri);
  33435. }
  33436. }
  33437. public function resolveProperty($schema, $propertyName, $sourceUri)
  33438. {
  33439. if (! isset($schema->$propertyName)) {
  33440. return;
  33441. }
  33442. $this->resolve($schema->$propertyName, $sourceUri);
  33443. }
  33444. public function resolveRef($schema, $sourceUri)
  33445. {
  33446. $ref = '$ref';
  33447. if (empty($schema->$ref)) {
  33448. return;
  33449. }
  33450. $refSchema = $this->fetchRef($schema->$ref, $sourceUri);
  33451. unset($schema->$ref);
  33452. foreach (get_object_vars($refSchema) as $prop => $value) {
  33453. $schema->$prop = $value;
  33454. }
  33455. }
  33456. public function setUriRetriever(UriRetriever $retriever)
  33457. {
  33458. $this->uriRetriever = $retriever;
  33459. return $this;
  33460. }
  33461. }
  33462. <?php
  33463. namespace JsonSchema\Uri\Retrievers;
  33464. abstract class AbstractRetriever implements UriRetrieverInterface
  33465. {
  33466. protected $contentType;
  33467. public function getContentType()
  33468. {
  33469. return $this->contentType;
  33470. }
  33471. }
  33472. <?php
  33473. namespace JsonSchema\Uri\Retrievers;
  33474. use JsonSchema\Validator;
  33475. class Curl extends AbstractRetriever
  33476. {
  33477. protected $messageBody;
  33478. public function __construct()
  33479. {
  33480. if (!function_exists('curl_init')) {
  33481. throw new \RuntimeException("cURL not installed");
  33482. }
  33483. }
  33484. public function retrieve($uri)
  33485. {
  33486. $ch = curl_init();
  33487. curl_setopt($ch, CURLOPT_URL, $uri);
  33488. curl_setopt($ch, CURLOPT_HEADER, true);
  33489. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  33490. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: ' . Validator::SCHEMA_MEDIA_TYPE));
  33491. $response = curl_exec($ch);
  33492. if (false === $response) {
  33493. throw new \JsonSchema\Exception\ResourceNotFoundException('JSON schema not found');
  33494. }
  33495. $this->fetchMessageBody($response);
  33496. $this->fetchContentType($response);
  33497. curl_close($ch);
  33498. return $this->messageBody;
  33499. }
  33500. private function fetchMessageBody($response)
  33501. {
  33502. preg_match("/(?:\r\n){2}(.*)$/ms", $response, $match);
  33503. $this->messageBody = $match[1];
  33504. }
  33505. protected function fetchContentType($response)
  33506. {
  33507. if (0 < preg_match("/Content-Type:(\V*)/ims", $response, $match)) {
  33508. $this->contentType = trim($match[1]);
  33509. return true;
  33510. }
  33511. return false;
  33512. }
  33513. }<?php
  33514. namespace JsonSchema\Uri\Retrievers;
  33515. use JsonSchema\Exception\ResourceNotFoundException;
  33516. use JsonSchema\Validator;
  33517. class FileGetContents extends AbstractRetriever
  33518. {
  33519. protected $messageBody;
  33520. public function retrieve($uri)
  33521. {
  33522. $context = stream_context_create(array(
  33523. 'http' => array(
  33524. 'method' => 'GET',
  33525. 'header' => "Accept: " . Validator::SCHEMA_MEDIA_TYPE
  33526. )));
  33527. $response = file_get_contents($uri);
  33528. if (false === $response) {
  33529. throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
  33530. }
  33531. if ($response == ''
  33532. && substr($uri, 0, 7) == 'file://' && substr($uri, -1) == '/'
  33533. ) {
  33534. throw new ResourceNotFoundException('JSON schema not found at ' . $uri);
  33535. }
  33536. $this->messageBody = $response;
  33537. if (! empty($http_response_header)) {
  33538. $this->fetchContentType($http_response_header);
  33539. } else {
  33540. $this->contentType = null;
  33541. }
  33542. return $this->messageBody;
  33543. }
  33544. private function fetchContentType(array $headers)
  33545. {
  33546. foreach ($headers as $header) {
  33547. if ($this->contentType = self::getContentTypeMatchInHeader($header)) {
  33548. return true;
  33549. }
  33550. }
  33551. return false;
  33552. }
  33553. protected static function getContentTypeMatchInHeader($header)
  33554. {
  33555. if (0 < preg_match("/Content-Type:(\V*)/ims", $header, $match)) {
  33556. return trim($match[1]);
  33557. }
  33558. }
  33559. }
  33560. <?php
  33561. namespace JsonSchema\Uri\Retrievers;
  33562. use JsonSchema\Validator;
  33563. use JsonSchema\Uri\Retrievers\UriRetrieverInterface;
  33564. class PredefinedArray extends AbstractRetriever
  33565. {
  33566. private $schemas;
  33567. public function __construct(array $schemas, $contentType = Validator::SCHEMA_MEDIA_TYPE)
  33568. {
  33569. $this->schemas = $schemas;
  33570. $this->contentType = $contentType;
  33571. }
  33572. public function retrieve($uri)
  33573. {
  33574. if (!array_key_exists($uri, $this->schemas)) {
  33575. throw new \JsonSchema\Exception\ResourceNotFoundException(sprintf(
  33576. 'The JSON schema "%s" was not found.',
  33577. $uri
  33578. ));
  33579. }
  33580. return $this->schemas[$uri];
  33581. }
  33582. }<?php
  33583. namespace JsonSchema\Uri\Retrievers;
  33584. interface UriRetrieverInterface
  33585. {
  33586. public function retrieve($uri);
  33587. public function getContentType();
  33588. }<?php
  33589. namespace JsonSchema\Uri;
  33590. use JsonSchema\Exception\UriResolverException;
  33591. class UriResolver
  33592. {
  33593. public function parse($uri)
  33594. {
  33595. preg_match('|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?|', $uri, $match);
  33596. $components = array();
  33597. if (5 < count($match)) {
  33598. $components = array(
  33599. 'scheme' => $match[2],
  33600. 'authority' => $match[4],
  33601. 'path' => $match[5]
  33602. );
  33603. }
  33604. if (7 < count($match)) {
  33605. $components['query'] = $match[7];
  33606. }
  33607. if (9 < count($match)) {
  33608. $components['fragment'] = $match[9];
  33609. }
  33610. return $components;
  33611. }
  33612. public function generate(array $components)
  33613. {
  33614. $uri = $components['scheme'] . '://'
  33615. . $components['authority']
  33616. . $components['path'];
  33617. if (array_key_exists('query', $components)) {
  33618. $uri .= $components['query'];
  33619. }
  33620. if (array_key_exists('fragment', $components)) {
  33621. $uri .= '#' . $components['fragment'];
  33622. }
  33623. return $uri;
  33624. }
  33625. public function resolve($uri, $baseUri = null)
  33626. {
  33627. if ($uri == '') {
  33628. return $baseUri;
  33629. }
  33630. $components = $this->parse($uri);
  33631. $path = $components['path'];
  33632. if (! empty($components['scheme'])) {
  33633. return $uri;
  33634. }
  33635. $baseComponents = $this->parse($baseUri);
  33636. $basePath = $baseComponents['path'];
  33637. $baseComponents['path'] = self::combineRelativePathWithBasePath($path, $basePath);
  33638. if (isset($components['fragment'])) {
  33639. $baseComponents['fragment'] = $components['fragment'];
  33640. }
  33641. return $this->generate($baseComponents);
  33642. }
  33643. public static function combineRelativePathWithBasePath($relativePath, $basePath)
  33644. {
  33645. $relativePath = self::normalizePath($relativePath);
  33646. if ($relativePath == '') {
  33647. return $basePath;
  33648. }
  33649. if ($relativePath{0} == '/') {
  33650. return $relativePath;
  33651. }
  33652. $basePathSegments = self::getPathSegments($basePath);
  33653. preg_match('|^/?(\.\./(?:\./)*)*|', $relativePath, $match);
  33654. $numLevelUp = strlen($match[0]) /3 + 1;
  33655. if ($numLevelUp >= count($basePathSegments)) {
  33656. throw new UriResolverException(sprintf("Unable to resolve URI '%s' from base '%s'", $relativePath, $basePath));
  33657. }
  33658. $basePathSegments = array_slice($basePathSegments, 0, -$numLevelUp);
  33659. $path = preg_replace('|^/?(\.\./(\./)*)*|', '', $relativePath);
  33660. return implode('/', $basePathSegments) . '/' . $path;
  33661. }
  33662. private static function normalizePath($path)
  33663. {
  33664. $path = preg_replace('|((?<!\.)\./)*|', '', $path);
  33665. $path = preg_replace('|//|', '/', $path);
  33666. return $path;
  33667. }
  33668. private static function getPathSegments($path) {
  33669. return explode('/', $path);
  33670. }
  33671. public function isValid($uri)
  33672. {
  33673. $components = $this->parse($uri);
  33674. return !empty($components);
  33675. }
  33676. }
  33677. <?php
  33678. namespace JsonSchema\Uri;
  33679. use JsonSchema\Uri\Retrievers\FileGetContents;
  33680. use JsonSchema\Uri\Retrievers\UriRetrieverInterface;
  33681. use JsonSchema\Validator;
  33682. use JsonSchema\Exception\InvalidSchemaMediaTypeException;
  33683. use JsonSchema\Exception\JsonDecodingException;
  33684. class UriRetriever
  33685. {
  33686. protected $uriRetriever = null;
  33687. public function confirmMediaType($uriRetriever, $uri)
  33688. {
  33689. $contentType = $uriRetriever->getContentType();
  33690. if (is_null($contentType)) {
  33691. return;
  33692. }
  33693. if (Validator::SCHEMA_MEDIA_TYPE === $contentType) {
  33694. return;
  33695. }
  33696. if (substr($uri, 0, 23) == 'http://json-schema.org/') {
  33697. return true;
  33698. }
  33699. throw new InvalidSchemaMediaTypeException(sprintf('Media type %s expected', Validator::SCHEMA_MEDIA_TYPE));
  33700. }
  33701. public function getUriRetriever()
  33702. {
  33703. if (is_null($this->uriRetriever)) {
  33704. $this->setUriRetriever(new FileGetContents);
  33705. }
  33706. return $this->uriRetriever;
  33707. }
  33708. public function resolvePointer($jsonSchema, $uri)
  33709. {
  33710. $resolver = new UriResolver();
  33711. $parsed = $resolver->parse($uri);
  33712. if (empty($parsed['fragment'])) {
  33713. return $jsonSchema;
  33714. }
  33715. $path = explode('/', $parsed['fragment']);
  33716. while ($path) {
  33717. $pathElement = array_shift($path);
  33718. if (! empty($pathElement)) {
  33719. $pathElement = str_replace('~1', '/', $pathElement);
  33720. $pathElement = str_replace('~0', '~', $pathElement);
  33721. if (! empty($jsonSchema->$pathElement)) {
  33722. $jsonSchema = $jsonSchema->$pathElement;
  33723. } else {
  33724. throw new \JsonSchema\Exception\ResourceNotFoundException(
  33725. 'Fragment "' . $parsed['fragment'] . '" not found'
  33726. . ' in ' . $uri
  33727. );
  33728. }
  33729. if (! is_object($jsonSchema)) {
  33730. throw new \JsonSchema\Exception\ResourceNotFoundException(
  33731. 'Fragment part "' . $pathElement . '" is no object '
  33732. . ' in ' . $uri
  33733. );
  33734. }
  33735. }
  33736. }
  33737. return $jsonSchema;
  33738. }
  33739. public function retrieve($uri, $baseUri = null)
  33740. {
  33741. $resolver = new UriResolver();
  33742. $resolvedUri = $fetchUri = $resolver->resolve($uri, $baseUri);
  33743. $arParts = $resolver->parse($resolvedUri);
  33744. if (isset($arParts['fragment'])) {
  33745. unset($arParts['fragment']);
  33746. $fetchUri = $resolver->generate($arParts);
  33747. }
  33748. $jsonSchema = $this->loadSchema($fetchUri);
  33749. $jsonSchema = $this->resolvePointer($jsonSchema, $resolvedUri);
  33750. $jsonSchema->id = $resolvedUri;
  33751. return $jsonSchema;
  33752. }
  33753. protected function loadSchema($fetchUri)
  33754. {
  33755. if (isset($this->schemaCache[$fetchUri])) {
  33756. return $this->schemaCache[$fetchUri];
  33757. }
  33758. $uriRetriever = $this->getUriRetriever();
  33759. $contents = $this->uriRetriever->retrieve($fetchUri);
  33760. $this->confirmMediaType($uriRetriever, $fetchUri);
  33761. $jsonSchema = json_decode($contents);
  33762. if (JSON_ERROR_NONE < $error = json_last_error()) {
  33763. throw new JsonDecodingException($error);
  33764. }
  33765. $this->schemaCache[$fetchUri] = $jsonSchema;
  33766. return $jsonSchema;
  33767. }
  33768. public function setUriRetriever(UriRetrieverInterface $uriRetriever)
  33769. {
  33770. $this->uriRetriever = $uriRetriever;
  33771. return $this;
  33772. }
  33773. public function parse($uri)
  33774. {
  33775. preg_match('|^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?|', $uri, $match);
  33776. $components = array();
  33777. if (5 < count($match)) {
  33778. $components = array(
  33779. 'scheme' => $match[2],
  33780. 'authority' => $match[4],
  33781. 'path' => $match[5]
  33782. );
  33783. }
  33784. if (7 < count($match)) {
  33785. $components['query'] = $match[7];
  33786. }
  33787. if (9 < count($match)) {
  33788. $components['fragment'] = $match[9];
  33789. }
  33790. return $components;
  33791. }
  33792. public function generate(array $components)
  33793. {
  33794. $uri = $components['scheme'] . '://'
  33795. . $components['authority']
  33796. . $components['path'];
  33797. if (array_key_exists('query', $components)) {
  33798. $uri .= $components['query'];
  33799. }
  33800. if (array_key_exists('fragment', $components)) {
  33801. $uri .= $components['fragment'];
  33802. }
  33803. return $uri;
  33804. }
  33805. public function resolve($uri, $baseUri = null)
  33806. {
  33807. $components = $this->parse($uri);
  33808. $path = $components['path'];
  33809. if ((array_key_exists('scheme', $components)) && ('http' === $components['scheme'])) {
  33810. return $uri;
  33811. }
  33812. $baseComponents = $this->parse($baseUri);
  33813. $basePath = $baseComponents['path'];
  33814. $baseComponents['path'] = self::combineRelativePathWithBasePath($path, $basePath);
  33815. return $this->generate($baseComponents);
  33816. }
  33817. private static function combineRelativePathWithBasePath($relativePath, $basePath)
  33818. {
  33819. $relativePath = self::normalizePath($relativePath);
  33820. $basePathSegments = self::getPathSegments($basePath);
  33821. preg_match('|^/?(\.\./(?:\./)*)*|', $relativePath, $match);
  33822. $numLevelUp = strlen($match[0]) /3 + 1;
  33823. if ($numLevelUp >= count($basePathSegments)) {
  33824. throw new \JsonSchema\Exception\UriResolverException(sprintf("Unable to resolve URI '%s' from base '%s'", $relativePath, $basePath));
  33825. }
  33826. $basePathSegments = array_slice($basePathSegments, 0, -$numLevelUp);
  33827. $path = preg_replace('|^/?(\.\./(\./)*)*|', '', $relativePath);
  33828. return implode('/', $basePathSegments) . '/' . $path;
  33829. }
  33830. private static function normalizePath($path)
  33831. {
  33832. $path = preg_replace('|((?<!\.)\./)*|', '', $path);
  33833. $path = preg_replace('|//|', '/', $path);
  33834. return $path;
  33835. }
  33836. private static function getPathSegments($path)
  33837. {
  33838. return explode('/', $path);
  33839. }
  33840. public function isValid($uri)
  33841. {
  33842. $components = $this->parse($uri);
  33843. return !empty($components);
  33844. }
  33845. }
  33846. <?php
  33847. namespace JsonSchema;
  33848. use JsonSchema\Constraints\Schema;
  33849. use JsonSchema\Constraints\Constraint;
  33850. use JsonSchema\Exception\InvalidSchemaMediaTypeException;
  33851. use JsonSchema\Exception\JsonDecodingException;
  33852. use JsonSchema\Uri\Retrievers\UriRetrieverInterface;
  33853. class Validator extends Constraint
  33854. {
  33855. const SCHEMA_MEDIA_TYPE = 'application/schema+json';
  33856. public function check($value, $schema = null, $path = null, $i = null)
  33857. {
  33858. $validator = new Schema($this->checkMode, $this->uriRetriever);
  33859. $validator->check($value, $schema);
  33860. $this->addErrors(array_unique($validator->getErrors(), SORT_REGULAR));
  33861. }
  33862. }
  33863. <?php
  33864. require_once __DIR__ . '/composer' . '/autoload_real.php';
  33865. return ComposerAutoloaderInite50dadd7af3a60367a2353872e1658c3::getLoader();
  33866. <?php
  33867. $vendorDir = dirname(dirname(__FILE__));
  33868. $baseDir = dirname($vendorDir);
  33869. return array(
  33870. 'phpDocumentor' => array($vendorDir . '/phpdocumentor/reflection-docblock/src'),
  33871. 'Symfony\\Component\\Yaml\\' => array($vendorDir . '/symfony/yaml'),
  33872. 'Symfony\\Component\\Process\\' => array($vendorDir . '/symfony/process'),
  33873. 'Symfony\\Component\\Finder\\' => array($vendorDir . '/symfony/finder'),
  33874. 'Symfony\\Component\\Console\\' => array($vendorDir . '/symfony/console'),
  33875. 'Prophecy\\' => array($vendorDir . '/phpspec/prophecy/src'),
  33876. 'JsonSchema' => array($vendorDir . '/justinrainbow/json-schema/src'),
  33877. 'Doctrine\\Instantiator\\' => array($vendorDir . '/doctrine/instantiator/src'),
  33878. 'Composer\\Test' => array($baseDir . '/tests'),
  33879. 'Composer' => array($baseDir . '/src'),
  33880. );
  33881. <?php
  33882. $vendorDir = dirname(dirname(__FILE__));
  33883. $baseDir = dirname($vendorDir);
  33884. return array(
  33885. 'Seld\\JsonLint\\' => array($vendorDir . '/seld/jsonlint/src/Seld/JsonLint'),
  33886. );
  33887. <?php
  33888. $vendorDir = dirname(dirname(__FILE__));
  33889. $baseDir = dirname($vendorDir);
  33890. return array(
  33891. 'File_Iterator' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator.php',
  33892. 'File_Iterator_Facade' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator/Facade.php',
  33893. 'File_Iterator_Factory' => $vendorDir . '/phpunit/php-file-iterator/File/Iterator/Factory.php',
  33894. 'PHPUnit_Exception' => $vendorDir . '/phpunit/phpunit/src/Exception.php',
  33895. 'PHPUnit_Extensions_GroupTestSuite' => $vendorDir . '/phpunit/phpunit/src/Extensions/GroupTestSuite.php',
  33896. 'PHPUnit_Extensions_PhptTestCase' => $vendorDir . '/phpunit/phpunit/src/Extensions/PhptTestCase.php',
  33897. 'PHPUnit_Extensions_PhptTestSuite' => $vendorDir . '/phpunit/phpunit/src/Extensions/PhptTestSuite.php',
  33898. 'PHPUnit_Extensions_RepeatedTest' => $vendorDir . '/phpunit/phpunit/src/Extensions/RepeatedTest.php',
  33899. 'PHPUnit_Extensions_TestDecorator' => $vendorDir . '/phpunit/phpunit/src/Extensions/TestDecorator.php',
  33900. 'PHPUnit_Extensions_TicketListener' => $vendorDir . '/phpunit/phpunit/src/Extensions/TicketListener.php',
  33901. 'PHPUnit_Framework_Assert' => $vendorDir . '/phpunit/phpunit/src/Framework/Assert.php',
  33902. 'PHPUnit_Framework_AssertionFailedError' => $vendorDir . '/phpunit/phpunit/src/Framework/AssertionFailedError.php',
  33903. 'PHPUnit_Framework_BaseTestListener' => $vendorDir . '/phpunit/phpunit/src/Framework/BaseTestListener.php',
  33904. 'PHPUnit_Framework_CodeCoverageException' => $vendorDir . '/phpunit/phpunit/src/Framework/CodeCoverageException.php',
  33905. 'PHPUnit_Framework_Constraint' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint.php',
  33906. 'PHPUnit_Framework_Constraint_And' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/And.php',
  33907. 'PHPUnit_Framework_Constraint_ArrayHasKey' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ArrayHasKey.php',
  33908. 'PHPUnit_Framework_Constraint_ArraySubset' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ArraySubset.php',
  33909. 'PHPUnit_Framework_Constraint_Attribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Attribute.php',
  33910. 'PHPUnit_Framework_Constraint_Callback' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Callback.php',
  33911. 'PHPUnit_Framework_Constraint_ClassHasAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ClassHasAttribute.php',
  33912. 'PHPUnit_Framework_Constraint_ClassHasStaticAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ClassHasStaticAttribute.php',
  33913. 'PHPUnit_Framework_Constraint_Composite' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Composite.php',
  33914. 'PHPUnit_Framework_Constraint_Count' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Count.php',
  33915. 'PHPUnit_Framework_Constraint_Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Exception.php',
  33916. 'PHPUnit_Framework_Constraint_ExceptionCode' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionCode.php',
  33917. 'PHPUnit_Framework_Constraint_ExceptionMessage' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessage.php',
  33918. 'PHPUnit_Framework_Constraint_ExceptionMessageRegExp' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ExceptionMessageRegExp.php',
  33919. 'PHPUnit_Framework_Constraint_FileExists' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/FileExists.php',
  33920. 'PHPUnit_Framework_Constraint_GreaterThan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/GreaterThan.php',
  33921. 'PHPUnit_Framework_Constraint_IsAnything' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsAnything.php',
  33922. 'PHPUnit_Framework_Constraint_IsEmpty' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsEmpty.php',
  33923. 'PHPUnit_Framework_Constraint_IsEqual' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsEqual.php',
  33924. 'PHPUnit_Framework_Constraint_IsFalse' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsFalse.php',
  33925. 'PHPUnit_Framework_Constraint_IsIdentical' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsIdentical.php',
  33926. 'PHPUnit_Framework_Constraint_IsInstanceOf' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsInstanceOf.php',
  33927. 'PHPUnit_Framework_Constraint_IsJson' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsJson.php',
  33928. 'PHPUnit_Framework_Constraint_IsNull' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsNull.php',
  33929. 'PHPUnit_Framework_Constraint_IsTrue' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsTrue.php',
  33930. 'PHPUnit_Framework_Constraint_IsType' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/IsType.php',
  33931. 'PHPUnit_Framework_Constraint_JsonMatches' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches.php',
  33932. 'PHPUnit_Framework_Constraint_JsonMatches_ErrorMessageProvider' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/JsonMatches/ErrorMessageProvider.php',
  33933. 'PHPUnit_Framework_Constraint_LessThan' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/LessThan.php',
  33934. 'PHPUnit_Framework_Constraint_Not' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Not.php',
  33935. 'PHPUnit_Framework_Constraint_ObjectHasAttribute' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/ObjectHasAttribute.php',
  33936. 'PHPUnit_Framework_Constraint_Or' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Or.php',
  33937. 'PHPUnit_Framework_Constraint_PCREMatch' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/PCREMatch.php',
  33938. 'PHPUnit_Framework_Constraint_SameSize' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/SameSize.php',
  33939. 'PHPUnit_Framework_Constraint_StringContains' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringContains.php',
  33940. 'PHPUnit_Framework_Constraint_StringEndsWith' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringEndsWith.php',
  33941. 'PHPUnit_Framework_Constraint_StringMatches' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringMatches.php',
  33942. 'PHPUnit_Framework_Constraint_StringStartsWith' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/StringStartsWith.php',
  33943. 'PHPUnit_Framework_Constraint_TraversableContains' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContains.php',
  33944. 'PHPUnit_Framework_Constraint_TraversableContainsOnly' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/TraversableContainsOnly.php',
  33945. 'PHPUnit_Framework_Constraint_Xor' => $vendorDir . '/phpunit/phpunit/src/Framework/Constraint/Xor.php',
  33946. 'PHPUnit_Framework_Error' => $vendorDir . '/phpunit/phpunit/src/Framework/Error.php',
  33947. 'PHPUnit_Framework_Error_Deprecated' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Deprecated.php',
  33948. 'PHPUnit_Framework_Error_Notice' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Notice.php',
  33949. 'PHPUnit_Framework_Error_Warning' => $vendorDir . '/phpunit/phpunit/src/Framework/Error/Warning.php',
  33950. 'PHPUnit_Framework_Exception' => $vendorDir . '/phpunit/phpunit/src/Framework/Exception.php',
  33951. 'PHPUnit_Framework_ExceptionWrapper' => $vendorDir . '/phpunit/phpunit/src/Framework/ExceptionWrapper.php',
  33952. 'PHPUnit_Framework_ExpectationFailedException' => $vendorDir . '/phpunit/phpunit/src/Framework/ExpectationFailedException.php',
  33953. 'PHPUnit_Framework_IncompleteTest' => $vendorDir . '/phpunit/phpunit/src/Framework/IncompleteTest.php',
  33954. 'PHPUnit_Framework_IncompleteTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/IncompleteTestCase.php',
  33955. 'PHPUnit_Framework_IncompleteTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/IncompleteTestError.php',
  33956. 'PHPUnit_Framework_InvalidCoversTargetError' => $vendorDir . '/phpunit/phpunit/src/Framework/InvalidCoversTargetError.php',
  33957. 'PHPUnit_Framework_InvalidCoversTargetException' => $vendorDir . '/phpunit/phpunit/src/Framework/InvalidCoversTargetException.php',
  33958. 'PHPUnit_Framework_MockObject_BadMethodCallException' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/BadMethodCallException.php',
  33959. 'PHPUnit_Framework_MockObject_Builder_Identity' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Identity.php',
  33960. 'PHPUnit_Framework_MockObject_Builder_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/InvocationMocker.php',
  33961. 'PHPUnit_Framework_MockObject_Builder_Match' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Match.php',
  33962. 'PHPUnit_Framework_MockObject_Builder_MethodNameMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/MethodNameMatch.php',
  33963. 'PHPUnit_Framework_MockObject_Builder_Namespace' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Namespace.php',
  33964. 'PHPUnit_Framework_MockObject_Builder_ParametersMatch' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/ParametersMatch.php',
  33965. 'PHPUnit_Framework_MockObject_Builder_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Builder/Stub.php',
  33966. 'PHPUnit_Framework_MockObject_Exception' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/Exception.php',
  33967. 'PHPUnit_Framework_MockObject_Generator' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Generator.php',
  33968. 'PHPUnit_Framework_MockObject_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation.php',
  33969. 'PHPUnit_Framework_MockObject_InvocationMocker' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/InvocationMocker.php',
  33970. 'PHPUnit_Framework_MockObject_Invocation_Object' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Object.php',
  33971. 'PHPUnit_Framework_MockObject_Invocation_Static' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invocation/Static.php',
  33972. 'PHPUnit_Framework_MockObject_Invokable' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Invokable.php',
  33973. 'PHPUnit_Framework_MockObject_Matcher' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher.php',
  33974. 'PHPUnit_Framework_MockObject_Matcher_AnyInvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyInvokedCount.php',
  33975. 'PHPUnit_Framework_MockObject_Matcher_AnyParameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/AnyParameters.php',
  33976. 'PHPUnit_Framework_MockObject_Matcher_ConsecutiveParameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/ConsecutiveParameters.php',
  33977. 'PHPUnit_Framework_MockObject_Matcher_Invocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Invocation.php',
  33978. 'PHPUnit_Framework_MockObject_Matcher_InvokedAtIndex' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtIndex.php',
  33979. 'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastCount.php',
  33980. 'PHPUnit_Framework_MockObject_Matcher_InvokedAtLeastOnce' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtLeastOnce.php',
  33981. 'PHPUnit_Framework_MockObject_Matcher_InvokedAtMostCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedAtMostCount.php',
  33982. 'PHPUnit_Framework_MockObject_Matcher_InvokedCount' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedCount.php',
  33983. 'PHPUnit_Framework_MockObject_Matcher_InvokedRecorder' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/InvokedRecorder.php',
  33984. 'PHPUnit_Framework_MockObject_Matcher_MethodName' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/MethodName.php',
  33985. 'PHPUnit_Framework_MockObject_Matcher_Parameters' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/Parameters.php',
  33986. 'PHPUnit_Framework_MockObject_Matcher_StatelessInvocation' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Matcher/StatelessInvocation.php',
  33987. 'PHPUnit_Framework_MockObject_MockBuilder' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockBuilder.php',
  33988. 'PHPUnit_Framework_MockObject_MockObject' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/MockObject.php',
  33989. 'PHPUnit_Framework_MockObject_RuntimeException' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Exception/RuntimeException.php',
  33990. 'PHPUnit_Framework_MockObject_Stub' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub.php',
  33991. 'PHPUnit_Framework_MockObject_Stub_ConsecutiveCalls' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ConsecutiveCalls.php',
  33992. 'PHPUnit_Framework_MockObject_Stub_Exception' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Exception.php',
  33993. 'PHPUnit_Framework_MockObject_Stub_MatcherCollection' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/MatcherCollection.php',
  33994. 'PHPUnit_Framework_MockObject_Stub_Return' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/Return.php',
  33995. 'PHPUnit_Framework_MockObject_Stub_ReturnArgument' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnArgument.php',
  33996. 'PHPUnit_Framework_MockObject_Stub_ReturnCallback' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnCallback.php',
  33997. 'PHPUnit_Framework_MockObject_Stub_ReturnSelf' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnSelf.php',
  33998. 'PHPUnit_Framework_MockObject_Stub_ReturnValueMap' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Stub/ReturnValueMap.php',
  33999. 'PHPUnit_Framework_MockObject_Verifiable' => $vendorDir . '/phpunit/phpunit-mock-objects/src/Framework/MockObject/Verifiable.php',
  34000. 'PHPUnit_Framework_OutputError' => $vendorDir . '/phpunit/phpunit/src/Framework/OutputError.php',
  34001. 'PHPUnit_Framework_RiskyTest' => $vendorDir . '/phpunit/phpunit/src/Framework/RiskyTest.php',
  34002. 'PHPUnit_Framework_RiskyTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/RiskyTestError.php',
  34003. 'PHPUnit_Framework_SelfDescribing' => $vendorDir . '/phpunit/phpunit/src/Framework/SelfDescribing.php',
  34004. 'PHPUnit_Framework_SkippedTest' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTest.php',
  34005. 'PHPUnit_Framework_SkippedTestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTestCase.php',
  34006. 'PHPUnit_Framework_SkippedTestError' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTestError.php',
  34007. 'PHPUnit_Framework_SkippedTestSuiteError' => $vendorDir . '/phpunit/phpunit/src/Framework/SkippedTestSuiteError.php',
  34008. 'PHPUnit_Framework_SyntheticError' => $vendorDir . '/phpunit/phpunit/src/Framework/SyntheticError.php',
  34009. 'PHPUnit_Framework_Test' => $vendorDir . '/phpunit/phpunit/src/Framework/Test.php',
  34010. 'PHPUnit_Framework_TestCase' => $vendorDir . '/phpunit/phpunit/src/Framework/TestCase.php',
  34011. 'PHPUnit_Framework_TestFailure' => $vendorDir . '/phpunit/phpunit/src/Framework/TestFailure.php',
  34012. 'PHPUnit_Framework_TestListener' => $vendorDir . '/phpunit/phpunit/src/Framework/TestListener.php',
  34013. 'PHPUnit_Framework_TestResult' => $vendorDir . '/phpunit/phpunit/src/Framework/TestResult.php',
  34014. 'PHPUnit_Framework_TestSuite' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuite.php',
  34015. 'PHPUnit_Framework_TestSuite_DataProvider' => $vendorDir . '/phpunit/phpunit/src/Framework/TestSuite/DataProvider.php',
  34016. 'PHPUnit_Framework_UnintentionallyCoveredCodeError' => $vendorDir . '/phpunit/phpunit/src/Framework/UnintentionallyCoveredCodeError.php',
  34017. 'PHPUnit_Framework_Warning' => $vendorDir . '/phpunit/phpunit/src/Framework/Warning.php',
  34018. 'PHPUnit_Runner_BaseTestRunner' => $vendorDir . '/phpunit/phpunit/src/Runner/BaseTestRunner.php',
  34019. 'PHPUnit_Runner_Exception' => $vendorDir . '/phpunit/phpunit/src/Runner/Exception.php',
  34020. 'PHPUnit_Runner_Filter_Factory' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Factory.php',
  34021. 'PHPUnit_Runner_Filter_GroupFilterIterator' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group.php',
  34022. 'PHPUnit_Runner_Filter_Group_Exclude' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group/Exclude.php',
  34023. 'PHPUnit_Runner_Filter_Group_Include' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Group/Include.php',
  34024. 'PHPUnit_Runner_Filter_Test' => $vendorDir . '/phpunit/phpunit/src/Runner/Filter/Test.php',
  34025. 'PHPUnit_Runner_StandardTestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/StandardTestSuiteLoader.php',
  34026. 'PHPUnit_Runner_TestSuiteLoader' => $vendorDir . '/phpunit/phpunit/src/Runner/TestSuiteLoader.php',
  34027. 'PHPUnit_Runner_Version' => $vendorDir . '/phpunit/phpunit/src/Runner/Version.php',
  34028. 'PHPUnit_TextUI_Command' => $vendorDir . '/phpunit/phpunit/src/TextUI/Command.php',
  34029. 'PHPUnit_TextUI_ResultPrinter' => $vendorDir . '/phpunit/phpunit/src/TextUI/ResultPrinter.php',
  34030. 'PHPUnit_TextUI_TestRunner' => $vendorDir . '/phpunit/phpunit/src/TextUI/TestRunner.php',
  34031. 'PHPUnit_Util_Blacklist' => $vendorDir . '/phpunit/phpunit/src/Util/Blacklist.php',
  34032. 'PHPUnit_Util_Configuration' => $vendorDir . '/phpunit/phpunit/src/Util/Configuration.php',
  34033. 'PHPUnit_Util_ErrorHandler' => $vendorDir . '/phpunit/phpunit/src/Util/ErrorHandler.php',
  34034. 'PHPUnit_Util_Fileloader' => $vendorDir . '/phpunit/phpunit/src/Util/Fileloader.php',
  34035. 'PHPUnit_Util_Filesystem' => $vendorDir . '/phpunit/phpunit/src/Util/Filesystem.php',
  34036. 'PHPUnit_Util_Filter' => $vendorDir . '/phpunit/phpunit/src/Util/Filter.php',
  34037. 'PHPUnit_Util_Getopt' => $vendorDir . '/phpunit/phpunit/src/Util/Getopt.php',
  34038. 'PHPUnit_Util_GlobalState' => $vendorDir . '/phpunit/phpunit/src/Util/GlobalState.php',
  34039. 'PHPUnit_Util_InvalidArgumentHelper' => $vendorDir . '/phpunit/phpunit/src/Util/InvalidArgumentHelper.php',
  34040. 'PHPUnit_Util_Log_JSON' => $vendorDir . '/phpunit/phpunit/src/Util/Log/JSON.php',
  34041. 'PHPUnit_Util_Log_JUnit' => $vendorDir . '/phpunit/phpunit/src/Util/Log/JUnit.php',
  34042. 'PHPUnit_Util_Log_TAP' => $vendorDir . '/phpunit/phpunit/src/Util/Log/TAP.php',
  34043. 'PHPUnit_Util_PHP' => $vendorDir . '/phpunit/phpunit/src/Util/PHP.php',
  34044. 'PHPUnit_Util_PHP_Default' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/Default.php',
  34045. 'PHPUnit_Util_PHP_Windows' => $vendorDir . '/phpunit/phpunit/src/Util/PHP/Windows.php',
  34046. 'PHPUnit_Util_Printer' => $vendorDir . '/phpunit/phpunit/src/Util/Printer.php',
  34047. 'PHPUnit_Util_Regex' => $vendorDir . '/phpunit/phpunit/src/Util/Regex.php',
  34048. 'PHPUnit_Util_String' => $vendorDir . '/phpunit/phpunit/src/Util/String.php',
  34049. 'PHPUnit_Util_Test' => $vendorDir . '/phpunit/phpunit/src/Util/Test.php',
  34050. 'PHPUnit_Util_TestDox_NamePrettifier' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/NamePrettifier.php',
  34051. 'PHPUnit_Util_TestDox_ResultPrinter' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter.php',
  34052. 'PHPUnit_Util_TestDox_ResultPrinter_HTML' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/HTML.php',
  34053. 'PHPUnit_Util_TestDox_ResultPrinter_Text' => $vendorDir . '/phpunit/phpunit/src/Util/TestDox/ResultPrinter/Text.php',
  34054. 'PHPUnit_Util_TestSuiteIterator' => $vendorDir . '/phpunit/phpunit/src/Util/TestSuiteIterator.php',
  34055. 'PHPUnit_Util_Type' => $vendorDir . '/phpunit/phpunit/src/Util/Type.php',
  34056. 'PHPUnit_Util_XML' => $vendorDir . '/phpunit/phpunit/src/Util/XML.php',
  34057. 'PHP_CodeCoverage' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage.php',
  34058. 'PHP_CodeCoverage_Driver' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Driver.php',
  34059. 'PHP_CodeCoverage_Driver_HHVM' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Driver/HHVM.php',
  34060. 'PHP_CodeCoverage_Driver_Xdebug' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Driver/Xdebug.php',
  34061. 'PHP_CodeCoverage_Exception' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Exception.php',
  34062. 'PHP_CodeCoverage_Exception_UnintentionallyCoveredCode' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Exception/UnintentionallyCoveredCode.php',
  34063. 'PHP_CodeCoverage_Filter' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Filter.php',
  34064. 'PHP_CodeCoverage_Report_Clover' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Clover.php',
  34065. 'PHP_CodeCoverage_Report_Crap4j' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Crap4j.php',
  34066. 'PHP_CodeCoverage_Report_Factory' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Factory.php',
  34067. 'PHP_CodeCoverage_Report_HTML' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/HTML.php',
  34068. 'PHP_CodeCoverage_Report_HTML_Renderer' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/HTML/Renderer.php',
  34069. 'PHP_CodeCoverage_Report_HTML_Renderer_Dashboard' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/HTML/Renderer/Dashboard.php',
  34070. 'PHP_CodeCoverage_Report_HTML_Renderer_Directory' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/HTML/Renderer/Directory.php',
  34071. 'PHP_CodeCoverage_Report_HTML_Renderer_File' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/HTML/Renderer/File.php',
  34072. 'PHP_CodeCoverage_Report_Node' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Node.php',
  34073. 'PHP_CodeCoverage_Report_Node_Directory' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Node/Directory.php',
  34074. 'PHP_CodeCoverage_Report_Node_File' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Node/File.php',
  34075. 'PHP_CodeCoverage_Report_Node_Iterator' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Node/Iterator.php',
  34076. 'PHP_CodeCoverage_Report_PHP' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/PHP.php',
  34077. 'PHP_CodeCoverage_Report_Text' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/Text.php',
  34078. 'PHP_CodeCoverage_Report_XML' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML.php',
  34079. 'PHP_CodeCoverage_Report_XML_Directory' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/Directory.php',
  34080. 'PHP_CodeCoverage_Report_XML_File' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/File.php',
  34081. 'PHP_CodeCoverage_Report_XML_File_Coverage' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/File/Coverage.php',
  34082. 'PHP_CodeCoverage_Report_XML_File_Method' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/File/Method.php',
  34083. 'PHP_CodeCoverage_Report_XML_File_Report' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/File/Report.php',
  34084. 'PHP_CodeCoverage_Report_XML_File_Unit' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/File/Unit.php',
  34085. 'PHP_CodeCoverage_Report_XML_Node' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/Node.php',
  34086. 'PHP_CodeCoverage_Report_XML_Project' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/Project.php',
  34087. 'PHP_CodeCoverage_Report_XML_Tests' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/Tests.php',
  34088. 'PHP_CodeCoverage_Report_XML_Totals' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Report/XML/Totals.php',
  34089. 'PHP_CodeCoverage_Util' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Util.php',
  34090. 'PHP_CodeCoverage_Util_InvalidArgumentHelper' => $vendorDir . '/phpunit/php-code-coverage/src/CodeCoverage/Util/InvalidArgumentHelper.php',
  34091. 'PHP_Timer' => $vendorDir . '/phpunit/php-timer/PHP/Timer.php',
  34092. 'PHP_Token' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34093. 'PHP_TokenWithScope' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34094. 'PHP_TokenWithScopeAndVisibility' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34095. 'PHP_Token_ABSTRACT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34096. 'PHP_Token_AMPERSAND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34097. 'PHP_Token_AND_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34098. 'PHP_Token_ARRAY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34099. 'PHP_Token_ARRAY_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34100. 'PHP_Token_AS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34101. 'PHP_Token_AT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34102. 'PHP_Token_BACKTICK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34103. 'PHP_Token_BAD_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34104. 'PHP_Token_BOOLEAN_AND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34105. 'PHP_Token_BOOLEAN_OR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34106. 'PHP_Token_BOOL_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34107. 'PHP_Token_BREAK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34108. 'PHP_Token_CALLABLE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34109. 'PHP_Token_CARET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34110. 'PHP_Token_CASE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34111. 'PHP_Token_CATCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34112. 'PHP_Token_CHARACTER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34113. 'PHP_Token_CLASS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34114. 'PHP_Token_CLASS_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34115. 'PHP_Token_CLASS_NAME_CONSTANT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34116. 'PHP_Token_CLONE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34117. 'PHP_Token_CLOSE_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34118. 'PHP_Token_CLOSE_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34119. 'PHP_Token_CLOSE_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34120. 'PHP_Token_CLOSE_TAG' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34121. 'PHP_Token_COLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34122. 'PHP_Token_COMMA' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34123. 'PHP_Token_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34124. 'PHP_Token_CONCAT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34125. 'PHP_Token_CONST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34126. 'PHP_Token_CONSTANT_ENCAPSED_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34127. 'PHP_Token_CONTINUE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34128. 'PHP_Token_CURLY_OPEN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34129. 'PHP_Token_DEC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34130. 'PHP_Token_DECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34131. 'PHP_Token_DEFAULT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34132. 'PHP_Token_DIR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34133. 'PHP_Token_DIV' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34134. 'PHP_Token_DIV_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34135. 'PHP_Token_DNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34136. 'PHP_Token_DO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34137. 'PHP_Token_DOC_COMMENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34138. 'PHP_Token_DOLLAR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34139. 'PHP_Token_DOLLAR_OPEN_CURLY_BRACES' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34140. 'PHP_Token_DOT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34141. 'PHP_Token_DOUBLE_ARROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34142. 'PHP_Token_DOUBLE_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34143. 'PHP_Token_DOUBLE_COLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34144. 'PHP_Token_DOUBLE_QUOTES' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34145. 'PHP_Token_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34146. 'PHP_Token_ELLIPSIS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34147. 'PHP_Token_ELSE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34148. 'PHP_Token_ELSEIF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34149. 'PHP_Token_EMPTY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34150. 'PHP_Token_ENCAPSED_AND_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34151. 'PHP_Token_ENDDECLARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34152. 'PHP_Token_ENDFOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34153. 'PHP_Token_ENDFOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34154. 'PHP_Token_ENDIF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34155. 'PHP_Token_ENDSWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34156. 'PHP_Token_ENDWHILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34157. 'PHP_Token_END_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34158. 'PHP_Token_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34159. 'PHP_Token_EVAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34160. 'PHP_Token_EXCLAMATION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34161. 'PHP_Token_EXIT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34162. 'PHP_Token_EXTENDS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34163. 'PHP_Token_FILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34164. 'PHP_Token_FINAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34165. 'PHP_Token_FINALLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34166. 'PHP_Token_FOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34167. 'PHP_Token_FOREACH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34168. 'PHP_Token_FUNCTION' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34169. 'PHP_Token_FUNC_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34170. 'PHP_Token_GLOBAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34171. 'PHP_Token_GOTO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34172. 'PHP_Token_GT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34173. 'PHP_Token_HALT_COMPILER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34174. 'PHP_Token_IF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34175. 'PHP_Token_IMPLEMENTS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34176. 'PHP_Token_INC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34177. 'PHP_Token_INCLUDE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34178. 'PHP_Token_INCLUDE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34179. 'PHP_Token_INLINE_HTML' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34180. 'PHP_Token_INSTANCEOF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34181. 'PHP_Token_INSTEADOF' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34182. 'PHP_Token_INTERFACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34183. 'PHP_Token_INT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34184. 'PHP_Token_ISSET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34185. 'PHP_Token_IS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34186. 'PHP_Token_IS_GREATER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34187. 'PHP_Token_IS_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34188. 'PHP_Token_IS_NOT_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34189. 'PHP_Token_IS_NOT_IDENTICAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34190. 'PHP_Token_IS_SMALLER_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34191. 'PHP_Token_Includes' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34192. 'PHP_Token_LAMBDA_ARROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34193. 'PHP_Token_LAMBDA_CP' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34194. 'PHP_Token_LAMBDA_OP' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34195. 'PHP_Token_LINE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34196. 'PHP_Token_LIST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34197. 'PHP_Token_LNUMBER' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34198. 'PHP_Token_LOGICAL_AND' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34199. 'PHP_Token_LOGICAL_OR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34200. 'PHP_Token_LOGICAL_XOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34201. 'PHP_Token_LT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34202. 'PHP_Token_METHOD_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34203. 'PHP_Token_MINUS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34204. 'PHP_Token_MINUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34205. 'PHP_Token_MOD_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34206. 'PHP_Token_MULT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34207. 'PHP_Token_MUL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34208. 'PHP_Token_NAMESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34209. 'PHP_Token_NEW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34210. 'PHP_Token_NS_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34211. 'PHP_Token_NS_SEPARATOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34212. 'PHP_Token_NUM_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34213. 'PHP_Token_OBJECT_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34214. 'PHP_Token_OBJECT_OPERATOR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34215. 'PHP_Token_OPEN_BRACKET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34216. 'PHP_Token_OPEN_CURLY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34217. 'PHP_Token_OPEN_SQUARE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34218. 'PHP_Token_OPEN_TAG' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34219. 'PHP_Token_OPEN_TAG_WITH_ECHO' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34220. 'PHP_Token_OR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34221. 'PHP_Token_PAAMAYIM_NEKUDOTAYIM' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34222. 'PHP_Token_PERCENT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34223. 'PHP_Token_PIPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34224. 'PHP_Token_PLUS' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34225. 'PHP_Token_PLUS_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34226. 'PHP_Token_POW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34227. 'PHP_Token_POW_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34228. 'PHP_Token_PRINT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34229. 'PHP_Token_PRIVATE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34230. 'PHP_Token_PROTECTED' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34231. 'PHP_Token_PUBLIC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34232. 'PHP_Token_QUESTION_MARK' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34233. 'PHP_Token_REQUIRE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34234. 'PHP_Token_REQUIRE_ONCE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34235. 'PHP_Token_RETURN' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34236. 'PHP_Token_SEMICOLON' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34237. 'PHP_Token_SHAPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34238. 'PHP_Token_SL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34239. 'PHP_Token_SL_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34240. 'PHP_Token_SR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34241. 'PHP_Token_SR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34242. 'PHP_Token_START_HEREDOC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34243. 'PHP_Token_STATIC' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34244. 'PHP_Token_STRING' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34245. 'PHP_Token_STRING_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34246. 'PHP_Token_STRING_VARNAME' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34247. 'PHP_Token_SWITCH' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34248. 'PHP_Token_Stream' => $vendorDir . '/phpunit/php-token-stream/src/Token/Stream.php',
  34249. 'PHP_Token_Stream_CachingFactory' => $vendorDir . '/phpunit/php-token-stream/src/Token/Stream/CachingFactory.php',
  34250. 'PHP_Token_THROW' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34251. 'PHP_Token_TILDE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34252. 'PHP_Token_TRAIT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34253. 'PHP_Token_TRAIT_C' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34254. 'PHP_Token_TRY' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34255. 'PHP_Token_TYPE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34256. 'PHP_Token_TYPELIST_GT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34257. 'PHP_Token_TYPELIST_LT' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34258. 'PHP_Token_UNSET' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34259. 'PHP_Token_UNSET_CAST' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34260. 'PHP_Token_USE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34261. 'PHP_Token_VAR' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34262. 'PHP_Token_VARIABLE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34263. 'PHP_Token_WHILE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34264. 'PHP_Token_WHITESPACE' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34265. 'PHP_Token_XOR_EQUAL' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34266. 'PHP_Token_YIELD' => $vendorDir . '/phpunit/php-token-stream/src/Token.php',
  34267. 'SebastianBergmann\\Comparator\\ArrayComparator' => $vendorDir . '/sebastian/comparator/src/ArrayComparator.php',
  34268. 'SebastianBergmann\\Comparator\\Comparator' => $vendorDir . '/sebastian/comparator/src/Comparator.php',
  34269. 'SebastianBergmann\\Comparator\\ComparisonFailure' => $vendorDir . '/sebastian/comparator/src/ComparisonFailure.php',
  34270. 'SebastianBergmann\\Comparator\\DOMNodeComparator' => $vendorDir . '/sebastian/comparator/src/DOMNodeComparator.php',
  34271. 'SebastianBergmann\\Comparator\\DateTimeComparator' => $vendorDir . '/sebastian/comparator/src/DateTimeComparator.php',
  34272. 'SebastianBergmann\\Comparator\\DoubleComparator' => $vendorDir . '/sebastian/comparator/src/DoubleComparator.php',
  34273. 'SebastianBergmann\\Comparator\\ExceptionComparator' => $vendorDir . '/sebastian/comparator/src/ExceptionComparator.php',
  34274. 'SebastianBergmann\\Comparator\\Factory' => $vendorDir . '/sebastian/comparator/src/Factory.php',
  34275. 'SebastianBergmann\\Comparator\\MockObjectComparator' => $vendorDir . '/sebastian/comparator/src/MockObjectComparator.php',
  34276. 'SebastianBergmann\\Comparator\\NumericComparator' => $vendorDir . '/sebastian/comparator/src/NumericComparator.php',
  34277. 'SebastianBergmann\\Comparator\\ObjectComparator' => $vendorDir . '/sebastian/comparator/src/ObjectComparator.php',
  34278. 'SebastianBergmann\\Comparator\\ResourceComparator' => $vendorDir . '/sebastian/comparator/src/ResourceComparator.php',
  34279. 'SebastianBergmann\\Comparator\\ScalarComparator' => $vendorDir . '/sebastian/comparator/src/ScalarComparator.php',
  34280. 'SebastianBergmann\\Comparator\\SplObjectStorageComparator' => $vendorDir . '/sebastian/comparator/src/SplObjectStorageComparator.php',
  34281. 'SebastianBergmann\\Comparator\\TypeComparator' => $vendorDir . '/sebastian/comparator/src/TypeComparator.php',
  34282. 'SebastianBergmann\\Diff\\Chunk' => $vendorDir . '/sebastian/diff/src/Chunk.php',
  34283. 'SebastianBergmann\\Diff\\Diff' => $vendorDir . '/sebastian/diff/src/Diff.php',
  34284. 'SebastianBergmann\\Diff\\Differ' => $vendorDir . '/sebastian/diff/src/Differ.php',
  34285. 'SebastianBergmann\\Diff\\LCS\\LongestCommonSubsequence' => $vendorDir . '/sebastian/diff/src/LCS/LongestCommonSubsequence.php',
  34286. 'SebastianBergmann\\Diff\\LCS\\MemoryEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/MemoryEfficientLongestCommonSubsequenceImplementation.php',
  34287. 'SebastianBergmann\\Diff\\LCS\\TimeEfficientImplementation' => $vendorDir . '/sebastian/diff/src/LCS/TimeEfficientLongestCommonSubsequenceImplementation.php',
  34288. 'SebastianBergmann\\Diff\\Line' => $vendorDir . '/sebastian/diff/src/Line.php',
  34289. 'SebastianBergmann\\Diff\\Parser' => $vendorDir . '/sebastian/diff/src/Parser.php',
  34290. 'SebastianBergmann\\Environment\\Console' => $vendorDir . '/sebastian/environment/src/Console.php',
  34291. 'SebastianBergmann\\Environment\\Runtime' => $vendorDir . '/sebastian/environment/src/Runtime.php',
  34292. 'SebastianBergmann\\Exporter\\Exporter' => $vendorDir . '/sebastian/exporter/src/Exporter.php',
  34293. 'SebastianBergmann\\GlobalState\\Blacklist' => $vendorDir . '/sebastian/global-state/src/Blacklist.php',
  34294. 'SebastianBergmann\\GlobalState\\Exception' => $vendorDir . '/sebastian/global-state/src/Exception.php',
  34295. 'SebastianBergmann\\GlobalState\\Restorer' => $vendorDir . '/sebastian/global-state/src/Restorer.php',
  34296. 'SebastianBergmann\\GlobalState\\RuntimeException' => $vendorDir . '/sebastian/global-state/src/RuntimeException.php',
  34297. 'SebastianBergmann\\GlobalState\\Snapshot' => $vendorDir . '/sebastian/global-state/src/Snapshot.php',
  34298. 'SebastianBergmann\\RecursionContext\\Context' => $vendorDir . '/sebastian/recursion-context/src/Context.php',
  34299. 'SebastianBergmann\\RecursionContext\\Exception' => $vendorDir . '/sebastian/recursion-context/src/Exception.php',
  34300. 'SebastianBergmann\\RecursionContext\\InvalidArgumentException' => $vendorDir . '/sebastian/recursion-context/src/InvalidArgumentException.php',
  34301. 'SebastianBergmann\\Version' => $vendorDir . '/sebastian/version/src/Version.php',
  34302. 'Text_Template' => $vendorDir . '/phpunit/php-text-template/Text/Template.php',
  34303. );
  34304. <?php
  34305. class ComposerAutoloaderInite50dadd7af3a60367a2353872e1658c3
  34306. {
  34307. private static $loader;
  34308. public static function loadClassLoader($class)
  34309. {
  34310. if ('Composer\Autoload\ClassLoader' === $class) {
  34311. require __DIR__ . '/ClassLoader.php';
  34312. }
  34313. }
  34314. public static function getLoader()
  34315. {
  34316. if (null !== self::$loader) {
  34317. return self::$loader;
  34318. }
  34319. spl_autoload_register(array('ComposerAutoloaderInite50dadd7af3a60367a2353872e1658c3', 'loadClassLoader'), true, true);
  34320. self::$loader = $loader = new \Composer\Autoload\ClassLoader();
  34321. spl_autoload_unregister(array('ComposerAutoloaderInite50dadd7af3a60367a2353872e1658c3', 'loadClassLoader'));
  34322. $includePaths = require __DIR__ . '/include_paths.php';
  34323. array_push($includePaths, get_include_path());
  34324. set_include_path(join(PATH_SEPARATOR, $includePaths));
  34325. $map = require __DIR__ . '/autoload_namespaces.php';
  34326. foreach ($map as $namespace => $path) {
  34327. $loader->set($namespace, $path);
  34328. }
  34329. $map = require __DIR__ . '/autoload_psr4.php';
  34330. foreach ($map as $namespace => $path) {
  34331. $loader->setPsr4($namespace, $path);
  34332. }
  34333. $classMap = require __DIR__ . '/autoload_classmap.php';
  34334. if ($classMap) {
  34335. $loader->addClassMap($classMap);
  34336. }
  34337. $loader->register(true);
  34338. return $loader;
  34339. }
  34340. }
  34341. function composerRequiree50dadd7af3a60367a2353872e1658c3($file)
  34342. {
  34343. require $file;
  34344. }
  34345. <?php
  34346. $vendorDir = dirname(dirname(__FILE__));
  34347. $baseDir = dirname($vendorDir);
  34348. return array(
  34349. $vendorDir . '/phpunit/php-text-template',
  34350. $vendorDir . '/phpunit/php-timer',
  34351. $vendorDir . '/phpunit/php-file-iterator',
  34352. );
  34353. <?php
  34354. namespace Composer\Autoload;
  34355. class ClassLoader
  34356. {
  34357. private $prefixLengthsPsr4 = array();
  34358. private $prefixDirsPsr4 = array();
  34359. private $fallbackDirsPsr4 = array();
  34360. private $prefixesPsr0 = array();
  34361. private $fallbackDirsPsr0 = array();
  34362. private $useIncludePath = false;
  34363. private $classMap = array();
  34364. private $classMapAuthoritative = false;
  34365. public function getPrefixes()
  34366. {
  34367. if (!empty($this->prefixesPsr0)) {
  34368. return call_user_func_array('array_merge', $this->prefixesPsr0);
  34369. }
  34370. return array();
  34371. }
  34372. public function getPrefixesPsr4()
  34373. {
  34374. return $this->prefixDirsPsr4;
  34375. }
  34376. public function getFallbackDirs()
  34377. {
  34378. return $this->fallbackDirsPsr0;
  34379. }
  34380. public function getFallbackDirsPsr4()
  34381. {
  34382. return $this->fallbackDirsPsr4;
  34383. }
  34384. public function getClassMap()
  34385. {
  34386. return $this->classMap;
  34387. }
  34388. public function addClassMap(array $classMap)
  34389. {
  34390. if ($this->classMap) {
  34391. $this->classMap = array_merge($this->classMap, $classMap);
  34392. } else {
  34393. $this->classMap = $classMap;
  34394. }
  34395. }
  34396. public function add($prefix, $paths, $prepend = false)
  34397. {
  34398. if (!$prefix) {
  34399. if ($prepend) {
  34400. $this->fallbackDirsPsr0 = array_merge(
  34401. (array) $paths,
  34402. $this->fallbackDirsPsr0
  34403. );
  34404. } else {
  34405. $this->fallbackDirsPsr0 = array_merge(
  34406. $this->fallbackDirsPsr0,
  34407. (array) $paths
  34408. );
  34409. }
  34410. return;
  34411. }
  34412. $first = $prefix[0];
  34413. if (!isset($this->prefixesPsr0[$first][$prefix])) {
  34414. $this->prefixesPsr0[$first][$prefix] = (array) $paths;
  34415. return;
  34416. }
  34417. if ($prepend) {
  34418. $this->prefixesPsr0[$first][$prefix] = array_merge(
  34419. (array) $paths,
  34420. $this->prefixesPsr0[$first][$prefix]
  34421. );
  34422. } else {
  34423. $this->prefixesPsr0[$first][$prefix] = array_merge(
  34424. $this->prefixesPsr0[$first][$prefix],
  34425. (array) $paths
  34426. );
  34427. }
  34428. }
  34429. public function addPsr4($prefix, $paths, $prepend = false)
  34430. {
  34431. if (!$prefix) {
  34432. if ($prepend) {
  34433. $this->fallbackDirsPsr4 = array_merge(
  34434. (array) $paths,
  34435. $this->fallbackDirsPsr4
  34436. );
  34437. } else {
  34438. $this->fallbackDirsPsr4 = array_merge(
  34439. $this->fallbackDirsPsr4,
  34440. (array) $paths
  34441. );
  34442. }
  34443. } elseif (!isset($this->prefixDirsPsr4[$prefix])) {
  34444. $length = strlen($prefix);
  34445. if ('\\' !== $prefix[$length - 1]) {
  34446. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  34447. }
  34448. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  34449. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  34450. } elseif ($prepend) {
  34451. $this->prefixDirsPsr4[$prefix] = array_merge(
  34452. (array) $paths,
  34453. $this->prefixDirsPsr4[$prefix]
  34454. );
  34455. } else {
  34456. $this->prefixDirsPsr4[$prefix] = array_merge(
  34457. $this->prefixDirsPsr4[$prefix],
  34458. (array) $paths
  34459. );
  34460. }
  34461. }
  34462. public function set($prefix, $paths)
  34463. {
  34464. if (!$prefix) {
  34465. $this->fallbackDirsPsr0 = (array) $paths;
  34466. } else {
  34467. $this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
  34468. }
  34469. }
  34470. public function setPsr4($prefix, $paths)
  34471. {
  34472. if (!$prefix) {
  34473. $this->fallbackDirsPsr4 = (array) $paths;
  34474. } else {
  34475. $length = strlen($prefix);
  34476. if ('\\' !== $prefix[$length - 1]) {
  34477. throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
  34478. }
  34479. $this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
  34480. $this->prefixDirsPsr4[$prefix] = (array) $paths;
  34481. }
  34482. }
  34483. public function setUseIncludePath($useIncludePath)
  34484. {
  34485. $this->useIncludePath = $useIncludePath;
  34486. }
  34487. public function getUseIncludePath()
  34488. {
  34489. return $this->useIncludePath;
  34490. }
  34491. public function setClassMapAuthoritative($classMapAuthoritative)
  34492. {
  34493. $this->classMapAuthoritative = $classMapAuthoritative;
  34494. }
  34495. public function isClassMapAuthoritative()
  34496. {
  34497. return $this->classMapAuthoritative;
  34498. }
  34499. public function register($prepend = false)
  34500. {
  34501. spl_autoload_register(array($this, 'loadClass'), true, $prepend);
  34502. }
  34503. public function unregister()
  34504. {
  34505. spl_autoload_unregister(array($this, 'loadClass'));
  34506. }
  34507. public function loadClass($class)
  34508. {
  34509. if ($file = $this->findFile($class)) {
  34510. includeFile($file);
  34511. return true;
  34512. }
  34513. }
  34514. public function findFile($class)
  34515. {
  34516. if ('\\' == $class[0]) {
  34517. $class = substr($class, 1);
  34518. }
  34519. if (isset($this->classMap[$class])) {
  34520. return $this->classMap[$class];
  34521. }
  34522. if ($this->classMapAuthoritative) {
  34523. return false;
  34524. }
  34525. $file = $this->findFileWithExtension($class, '.php');
  34526. if ($file === null && defined('HHVM_VERSION')) {
  34527. $file = $this->findFileWithExtension($class, '.hh');
  34528. }
  34529. if ($file === null) {
  34530. return $this->classMap[$class] = false;
  34531. }
  34532. return $file;
  34533. }
  34534. private function findFileWithExtension($class, $ext)
  34535. {
  34536. $logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
  34537. $first = $class[0];
  34538. if (isset($this->prefixLengthsPsr4[$first])) {
  34539. foreach ($this->prefixLengthsPsr4[$first] as $prefix => $length) {
  34540. if (0 === strpos($class, $prefix)) {
  34541. foreach ($this->prefixDirsPsr4[$prefix] as $dir) {
  34542. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $length))) {
  34543. return $file;
  34544. }
  34545. }
  34546. }
  34547. }
  34548. }
  34549. foreach ($this->fallbackDirsPsr4 as $dir) {
  34550. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
  34551. return $file;
  34552. }
  34553. }
  34554. if (false !== $pos = strrpos($class, '\\')) {
  34555. $logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
  34556. . strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
  34557. } else {
  34558. $logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
  34559. }
  34560. if (isset($this->prefixesPsr0[$first])) {
  34561. foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
  34562. if (0 === strpos($class, $prefix)) {
  34563. foreach ($dirs as $dir) {
  34564. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  34565. return $file;
  34566. }
  34567. }
  34568. }
  34569. }
  34570. }
  34571. foreach ($this->fallbackDirsPsr0 as $dir) {
  34572. if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
  34573. return $file;
  34574. }
  34575. }
  34576. if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
  34577. return $file;
  34578. }
  34579. }
  34580. }
  34581. function includeFile($file)
  34582. {
  34583. include $file;
  34584. }
  34585. <?php
  34586. if (PHP_SAPI !== 'cli') {
  34587. echo 'Warning: Composer should be invoked via the CLI version of PHP, not the '.PHP_SAPI.' SAPI'.PHP_EOL;
  34588. }
  34589. require __DIR__.'/../src/bootstrap.php';
  34590. use Composer\Console\Application;
  34591. error_reporting(-1);
  34592. if (function_exists('ini_set')) {
  34593. @ini_set('display_errors', 1);
  34594. $memoryInBytes = function ($value) {
  34595. $unit = strtolower(substr($value, -1, 1));
  34596. $value = (int) $value;
  34597. switch($unit) {
  34598. case 'g':
  34599. $value *= 1024;
  34600. // no break (cumulative multiplier)
  34601. case 'm':
  34602. $value *= 1024;
  34603. // no break (cumulative multiplier)
  34604. case 'k':
  34605. $value *= 1024;
  34606. }
  34607. return $value;
  34608. };
  34609. $memoryLimit = trim(ini_get('memory_limit'));
  34610. // Increase memory_limit if it is lower than 512M
  34611. if ($memoryLimit != -1 && $memoryInBytes($memoryLimit) < 512 * 1024 * 1024) {
  34612. @ini_set('memory_limit', '512M');
  34613. }
  34614. unset($memoryInBytes, $memoryLimit);
  34615. }
  34616. // run the command application
  34617. $application = new Application();
  34618. $application->run();
  34619. Copyright (c) 2011 Nils Adermann, Jordi Boggiano
  34620. Permission is hereby granted, free of charge, to any person obtaining a copy
  34621. of this software and associated documentation files (the "Software"), to deal
  34622. in the Software without restriction, including without limitation the rights
  34623. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  34624. copies of the Software, and to permit persons to whom the Software is furnished
  34625. to do so, subject to the following conditions:
  34626. The above copyright notice and this permission notice shall be included in all
  34627. copies or substantial portions of the Software.
  34628. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  34629. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  34630. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  34631. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  34632. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  34633. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  34634. THE SOFTWARE.
  34635. øB®ù”¿ê�Ìçw-¬G�¶Ì*á���GBMB