elFinderVolumeDriver.class.php 245 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455
  1. <?php
  2. /**
  3. * Base class for elFinder volume.
  4. * Provide 2 layers:
  5. * 1. Public API (commands)
  6. * 2. abstract fs API
  7. * All abstract methods begin with "_"
  8. *
  9. * @author Dmitry (dio) Levashov
  10. * @author Troex Nevelin
  11. * @author Alexey Sukhotin
  12. * @method netmountPrepare(array $options)
  13. * @method postNetmount(array $options)
  14. */
  15. abstract class elFinderVolumeDriver
  16. {
  17. /**
  18. * Net mount key
  19. *
  20. * @var string
  21. **/
  22. public $netMountKey = '';
  23. /**
  24. * Request args
  25. * $_POST or $_GET values
  26. *
  27. * @var array
  28. */
  29. protected $ARGS = array();
  30. /**
  31. * Driver id
  32. * Must be started from letter and contains [a-z0-9]
  33. * Used as part of volume id
  34. *
  35. * @var string
  36. **/
  37. protected $driverId = 'a';
  38. /**
  39. * Volume id - used as prefix for files hashes
  40. *
  41. * @var string
  42. **/
  43. protected $id = '';
  44. /**
  45. * Flag - volume "mounted" and available
  46. *
  47. * @var bool
  48. **/
  49. protected $mounted = false;
  50. /**
  51. * Root directory path
  52. *
  53. * @var string
  54. **/
  55. protected $root = '';
  56. /**
  57. * Root basename | alias
  58. *
  59. * @var string
  60. **/
  61. protected $rootName = '';
  62. /**
  63. * Default directory to open
  64. *
  65. * @var string
  66. **/
  67. protected $startPath = '';
  68. /**
  69. * Base URL
  70. *
  71. * @var string
  72. **/
  73. protected $URL = '';
  74. /**
  75. * Path to temporary directory
  76. *
  77. * @var string
  78. */
  79. protected $tmp;
  80. /**
  81. * A file save destination path when a temporary content URL is required
  82. * on a network volume or the like
  83. * If not specified, it tries to use "Connector Path/../files/.tmb".
  84. *
  85. * @var string
  86. */
  87. protected $tmpLinkPath = '';
  88. /**
  89. * A file save destination URL when a temporary content URL is required
  90. * on a network volume or the like
  91. * If not specified, it tries to use "Connector URL/../files/.tmb".
  92. *
  93. * @var string
  94. */
  95. protected $tmpLinkUrl = '';
  96. /**
  97. * Thumbnails dir path
  98. *
  99. * @var string
  100. **/
  101. protected $tmbPath = '';
  102. /**
  103. * Is thumbnails dir writable
  104. *
  105. * @var bool
  106. **/
  107. protected $tmbPathWritable = false;
  108. /**
  109. * Thumbnails base URL
  110. *
  111. * @var string
  112. **/
  113. protected $tmbURL = '';
  114. /**
  115. * Thumbnails size in px
  116. *
  117. * @var int
  118. **/
  119. protected $tmbSize = 48;
  120. /**
  121. * Image manipulation lib name
  122. * auto|imagick|gd|convert
  123. *
  124. * @var string
  125. **/
  126. protected $imgLib = 'auto';
  127. /**
  128. * Video to Image converter
  129. *
  130. * @var array
  131. */
  132. protected $imgConverter = array();
  133. /**
  134. * Library to crypt files name
  135. *
  136. * @var string
  137. **/
  138. protected $cryptLib = '';
  139. /**
  140. * Archivers config
  141. *
  142. * @var array
  143. **/
  144. protected $archivers = array(
  145. 'create' => array(),
  146. 'extract' => array()
  147. );
  148. /**
  149. * Server character encoding
  150. *
  151. * @var string or null
  152. **/
  153. protected $encoding = null;
  154. /**
  155. * How many subdirs levels return for tree
  156. *
  157. * @var int
  158. **/
  159. protected $treeDeep = 1;
  160. /**
  161. * Errors from last failed action
  162. *
  163. * @var array
  164. **/
  165. protected $error = array();
  166. /**
  167. * Today 24:00 timestamp
  168. *
  169. * @var int
  170. **/
  171. protected $today = 0;
  172. /**
  173. * Yesterday 24:00 timestamp
  174. *
  175. * @var int
  176. **/
  177. protected $yesterday = 0;
  178. /**
  179. * Force make dirctory on extract
  180. *
  181. * @var int
  182. **/
  183. protected $extractToNewdir = 'auto';
  184. /**
  185. * Object configuration
  186. *
  187. * @var array
  188. **/
  189. protected $options = array(
  190. // Driver ID (Prefix of volume ID), Normally, the value specified for each volume driver is used.
  191. 'driverId' => '',
  192. // Id (Suffix of volume ID), Normally, the number incremented according to the specified number of volumes is used.
  193. 'id' => '',
  194. // revision id of root directory that uses for caching control of root stat
  195. 'rootRev' => '',
  196. // driver type it uses volume root's CSS class name. e.g. 'group' -> Adds 'elfinder-group' to CSS class name.
  197. 'type' => '',
  198. // root directory path
  199. 'path' => '',
  200. // Folder hash value on elFinder to be the parent of this volume
  201. 'phash' => '',
  202. // Folder hash value on elFinder to trash bin of this volume, it require 'copyJoin' to true
  203. 'trashHash' => '',
  204. // open this path on initial request instead of root path
  205. 'startPath' => '',
  206. // how many subdirs levels return per request
  207. 'treeDeep' => 1,
  208. // root url, not set to disable sending URL to client (replacement for old "fileURL" option)
  209. 'URL' => '',
  210. // enable onetime URL to a file - (true, false or callable (A function that return onetime URL))
  211. 'onetimeUrl' => false,
  212. // directory link url to own manager url with folder hash (`true`, `false`, `'hide'`(No show) or default `'auto'`: URL is empty then `true` else `false`)
  213. 'dirUrlOwn' => 'auto',
  214. // directory separator. required by client to show paths correctly
  215. 'separator' => DIRECTORY_SEPARATOR,
  216. // Use '/' as directory separator when the path hash encode/decode on the Windows server too
  217. 'winHashFix' => false,
  218. // Server character encoding (default is '': UTF-8)
  219. 'encoding' => '',
  220. // for convert character encoding (default is '': Not change locale)
  221. 'locale' => '',
  222. // URL of volume icon image
  223. 'icon' => '',
  224. // CSS Class of volume root in tree
  225. 'rootCssClass' => '',
  226. // Items to disable session caching
  227. 'noSessionCache' => array(),
  228. // enable i18n folder name that convert name to elFinderInstance.messages['folder_'+name]
  229. 'i18nFolderName' => false,
  230. // Search timeout (sec)
  231. 'searchTimeout' => 30,
  232. // Search exclusion directory regex pattern (require demiliter e.g. '#/path/to/exclude_directory#i')
  233. 'searchExDirReg' => '',
  234. // library to crypt/uncrypt files names (not implemented)
  235. 'cryptLib' => '',
  236. // how to detect files mimetypes. (auto/internal/finfo/mime_content_type)
  237. 'mimeDetect' => 'auto',
  238. // mime.types file path (for mimeDetect==internal)
  239. 'mimefile' => '',
  240. // Static extension/MIME of general server side scripts to security issues
  241. 'staticMineMap' => array(
  242. 'php:*' => 'text/x-php',
  243. 'pht:*' => 'text/x-php',
  244. 'php3:*' => 'text/x-php',
  245. 'php4:*' => 'text/x-php',
  246. 'php5:*' => 'text/x-php',
  247. 'php7:*' => 'text/x-php',
  248. 'phtml:*' => 'text/x-php',
  249. 'cgi:*' => 'text/x-httpd-cgi',
  250. 'pl:*' => 'text/x-perl',
  251. 'asp:*' => 'text/x-asap',
  252. 'aspx:*' => 'text/x-asap',
  253. 'py:*' => 'text/x-python',
  254. 'rb:*' => 'text/x-ruby',
  255. 'jsp:*' => 'text/x-jsp'
  256. ),
  257. // mime type normalize map : Array '[ext]:[detected mime type]' => '[normalized mime]'
  258. 'mimeMap' => array(
  259. 'md:application/x-genesis-rom' => 'text/x-markdown',
  260. 'md:text/plain' => 'text/x-markdown',
  261. 'markdown:text/plain' => 'text/x-markdown',
  262. 'css:text/x-asm' => 'text/css',
  263. 'css:text/plain' => 'text/css',
  264. 'csv:text/plain' => 'text/csv',
  265. 'java:text/x-c' => 'text/x-java-source',
  266. 'json:text/plain' => 'application/json',
  267. 'sql:text/plain' => 'text/x-sql',
  268. 'rtf:text/rtf' => 'application/rtf',
  269. 'rtfd:text/rtfd' => 'application/rtfd',
  270. 'ico:image/vnd.microsoft.icon' => 'image/x-icon',
  271. 'svg:text/plain' => 'image/svg+xml',
  272. 'pxd:application/octet-stream' => 'image/x-pixlr-data',
  273. 'dng:image/tiff' => 'image/x-adobe-dng',
  274. 'sketch:application/zip' => 'image/x-sketch',
  275. 'sketch:application/octet-stream' => 'image/x-sketch',
  276. 'xcf:application/octet-stream' => 'image/x-xcf',
  277. 'amr:application/octet-stream' => 'audio/amr',
  278. 'm4a:video/mp4' => 'audio/mp4',
  279. 'oga:application/ogg' => 'audio/ogg',
  280. 'ogv:application/ogg' => 'video/ogg',
  281. 'zip:application/x-zip' => 'application/zip',
  282. 'm3u8:text/plain' => 'application/x-mpegURL',
  283. 'mpd:text/plain' => 'application/dash+xml',
  284. 'mpd:application/xml' => 'application/dash+xml',
  285. '*:application/x-dosexec' => 'application/x-executable',
  286. 'doc:application/vnd.ms-office' => 'application/msword',
  287. 'xls:application/vnd.ms-office' => 'application/vnd.ms-excel',
  288. 'ppt:application/vnd.ms-office' => 'application/vnd.ms-powerpoint',
  289. 'yml:text/plain' => 'text/x-yaml',
  290. 'ai:application/pdf' => 'application/postscript',
  291. 'cgm:text/plain' => 'image/cgm',
  292. 'dxf:text/plain' => 'image/vnd.dxf',
  293. 'hpgl:text/plain' => 'application/vnd.hp-hpgl',
  294. 'igs:text/plain' => 'model/iges',
  295. 'iges:text/plain' => 'model/iges',
  296. 'plt:application/octet-stream' => 'application/plt',
  297. 'plt:text/plain' => 'application/plt',
  298. 'sat:text/plain' => 'application/sat',
  299. 'step:text/plain' => 'application/step',
  300. 'stp:text/plain' => 'application/step'
  301. ),
  302. // An option to add MimeMap to the `mimeMap` option
  303. // Array '[ext]:[detected mime type]' => '[normalized mime]'
  304. 'additionalMimeMap' => array(),
  305. // MIME-Type of filetype detected as unknown
  306. 'mimeTypeUnknown' => 'application/octet-stream',
  307. // MIME regex of send HTTP header "Content-Disposition: inline" or allow preview in quicklook
  308. // '.' is allow inline of all of MIME types
  309. // '$^' is not allow inline of all of MIME types
  310. 'dispInlineRegex' => '^(?:(?:video|audio)|image/(?!.+\+xml)|application/(?:ogg|x-mpegURL|dash\+xml)|(?:text/plain|application/pdf)$)',
  311. // temporary content URL's base path
  312. 'tmpLinkPath' => '',
  313. // temporary content URL's base URL
  314. 'tmpLinkUrl' => '',
  315. // directory for thumbnails
  316. 'tmbPath' => '.tmb',
  317. // mode to create thumbnails dir
  318. 'tmbPathMode' => 0777,
  319. // thumbnails dir URL. Set it if store thumbnails outside root directory
  320. 'tmbURL' => '',
  321. // thumbnails size (px)
  322. 'tmbSize' => 48,
  323. // thumbnails crop (true - crop, false - scale image to fit thumbnail size)
  324. 'tmbCrop' => true,
  325. // thumbnails background color (hex #rrggbb or 'transparent')
  326. 'tmbBgColor' => 'transparent',
  327. // image rotate fallback background color (hex #rrggbb)
  328. 'bgColorFb' => '#ffffff',
  329. // image manipulations library
  330. 'imgLib' => 'auto',
  331. // Fallback self image to thumbnail (nothing imgLib)
  332. 'tmbFbSelf' => true,
  333. // Video to Image converters ['TYPE or MIME' => ['func' => function($file){ /* Converts $file to Image */ return true; }, 'maxlen' => (int)TransferLength]]
  334. 'imgConverter' => array(),
  335. // Max length of transfer to image converter
  336. 'tmbVideoConvLen' => 10000000,
  337. // Captre point seccond
  338. 'tmbVideoConvSec' => 6,
  339. // Resource path of fallback icon images defailt: php/resouces
  340. 'resourcePath' => '',
  341. // Jpeg image saveing quality
  342. 'jpgQuality' => 100,
  343. // Save as progressive JPEG on image editing
  344. 'jpgProgressive' => true,
  345. // enable to get substitute image with command `dim`
  346. 'substituteImg' => true,
  347. // on paste file - if true - old file will be replaced with new one, if false new file get name - original_name-number.ext
  348. 'copyOverwrite' => true,
  349. // if true - join new and old directories content on paste
  350. 'copyJoin' => true,
  351. // on upload - if true - old file will be replaced with new one, if false new file get name - original_name-number.ext
  352. 'uploadOverwrite' => true,
  353. // mimetypes allowed to upload
  354. 'uploadAllow' => array(),
  355. // mimetypes not allowed to upload
  356. 'uploadDeny' => array(),
  357. // order to process uploadAllow and uploadDeny options
  358. 'uploadOrder' => array('deny', 'allow'),
  359. // maximum upload file size. NOTE - this is size for every uploaded files
  360. 'uploadMaxSize' => 0,
  361. // maximum number of chunked upload connection. `-1` to disable chunked upload
  362. 'uploadMaxConn' => 3,
  363. // maximum get file size. NOTE - Maximum value is 50% of PHP memory_limit
  364. 'getMaxSize' => 0,
  365. // files dates format
  366. 'dateFormat' => 'j M Y H:i',
  367. // files time format
  368. 'timeFormat' => 'H:i',
  369. // if true - every folder will be check for children folders, -1 - every folder will be check asynchronously, false - all folders will be marked as having subfolders
  370. 'checkSubfolders' => true, // true, false or -1
  371. // allow to copy from this volume to other ones?
  372. 'copyFrom' => true,
  373. // allow to copy from other volumes to this one?
  374. 'copyTo' => true,
  375. // cmd duplicate suffix format e.g. '_%s_' to without spaces
  376. 'duplicateSuffix' => ' %s ',
  377. // unique name numbar format e.g. '(%d)' to (1), (2)...
  378. 'uniqueNumFormat' => '%d',
  379. // list of commands disabled on this root
  380. 'disabled' => array(),
  381. // enable file owner, group & mode info, `false` to inactivate "chmod" command.
  382. 'statOwner' => false,
  383. // allow exec chmod of read-only files
  384. 'allowChmodReadOnly' => false,
  385. // regexp or function name to validate new file name
  386. 'acceptedName' => '/^[^\.].*/', // Notice: overwritten it in some volume drivers contractor
  387. // regexp or function name to validate new directory name
  388. 'acceptedDirname' => '', // used `acceptedName` if empty value
  389. // function/class method to control files permissions
  390. 'accessControl' => null,
  391. // some data required by access control
  392. 'accessControlData' => null,
  393. // default permissions.
  394. 'defaults' => array(
  395. 'read' => true,
  396. 'write' => true,
  397. 'locked' => false,
  398. 'hidden' => false
  399. ),
  400. // files attributes
  401. 'attributes' => array(),
  402. // max allowed archive files size (0 - no limit)
  403. 'maxArcFilesSize' => 0,
  404. // Allowed archive's mimetypes to create. Leave empty for all available types.
  405. 'archiveMimes' => array(),
  406. // Manual config for archivers. See example below. Leave empty for auto detect
  407. 'archivers' => array(),
  408. // Use Archive function for remote volume
  409. 'useRemoteArchive' => false,
  410. // plugin settings
  411. 'plugin' => array(),
  412. // Is support parent directory time stamp update on add|remove|rename item
  413. // Default `null` is auto detection that is LocalFileSystem, FTP or Dropbox are `true`
  414. 'syncChkAsTs' => null,
  415. // Long pooling sync checker function for syncChkAsTs is true
  416. // Calls with args (TARGET DIRCTORY PATH, STAND-BY(sec), OLD TIMESTAMP, VOLUME DRIVER INSTANCE, ELFINDER INSTANCE)
  417. // This function must return the following values. Changed: New Timestamp or Same: Old Timestamp or Error: false
  418. // Default `null` is try use elFinderVolumeLocalFileSystem::localFileSystemInotify() on LocalFileSystem driver
  419. // another driver use elFinder stat() checker
  420. 'syncCheckFunc' => null,
  421. // Long polling sync stand-by time (sec)
  422. 'plStandby' => 30,
  423. // Sleep time (sec) for elFinder stat() checker (syncChkAsTs is true)
  424. 'tsPlSleep' => 10,
  425. // Sleep time (sec) for elFinder ls() checker (syncChkAsTs is false)
  426. 'lsPlSleep' => 30,
  427. // Client side sync interval minimum (ms)
  428. // Default `null` is auto set to ('tsPlSleep' or 'lsPlSleep') * 1000
  429. // `0` to disable auto sync
  430. 'syncMinMs' => null,
  431. // required to fix bug on macos
  432. // However, we recommend to use the Normalizer plugin instead this option
  433. 'utf8fix' => false,
  434. // й ё Й Ё Ø Å
  435. 'utf8patterns' => array("\u0438\u0306", "\u0435\u0308", "\u0418\u0306", "\u0415\u0308", "\u00d8A", "\u030a"),
  436. 'utf8replace' => array("\u0439", "\u0451", "\u0419", "\u0401", "\u00d8", "\u00c5"),
  437. // cache control HTTP headers for commands `file` and `get`
  438. 'cacheHeaders' => array(
  439. 'Cache-Control: max-age=3600',
  440. 'Expires:',
  441. 'Pragma:'
  442. ),
  443. // Header to use to accelerate sending local files to clients (e.g. 'X-Sendfile', 'X-Accel-Redirect')
  444. 'xsendfile' => '',
  445. // Root path to xsendfile target. Probably, this is required for 'X-Accel-Redirect' on Nginx.
  446. 'xsendfilePath' => ''
  447. );
  448. /**
  449. * Defaults permissions
  450. *
  451. * @var array
  452. **/
  453. protected $defaults = array(
  454. 'read' => true,
  455. 'write' => true,
  456. 'locked' => false,
  457. 'hidden' => false
  458. );
  459. /**
  460. * Access control function/class
  461. *
  462. * @var mixed
  463. **/
  464. protected $attributes = array();
  465. /**
  466. * Access control function/class
  467. *
  468. * @var mixed
  469. **/
  470. protected $access = null;
  471. /**
  472. * Mime types allowed to upload
  473. *
  474. * @var array
  475. **/
  476. protected $uploadAllow = array();
  477. /**
  478. * Mime types denied to upload
  479. *
  480. * @var array
  481. **/
  482. protected $uploadDeny = array();
  483. /**
  484. * Order to validate uploadAllow and uploadDeny
  485. *
  486. * @var array
  487. **/
  488. protected $uploadOrder = array();
  489. /**
  490. * Maximum allowed upload file size.
  491. * Set as number or string with unit - "10M", "500K", "1G"
  492. *
  493. * @var int|string
  494. **/
  495. protected $uploadMaxSize = 0;
  496. /**
  497. * Run time setting of overwrite items on upload
  498. *
  499. * @var string
  500. */
  501. protected $uploadOverwrite = true;
  502. /**
  503. * Maximum allowed get file size.
  504. * Set as number or string with unit - "10M", "500K", "1G"
  505. *
  506. * @var int|string
  507. **/
  508. protected $getMaxSize = -1;
  509. /**
  510. * Mimetype detect method
  511. *
  512. * @var string
  513. **/
  514. protected $mimeDetect = 'auto';
  515. /**
  516. * Flag - mimetypes from externail file was loaded
  517. *
  518. * @var bool
  519. **/
  520. private static $mimetypesLoaded = false;
  521. /**
  522. * Finfo resource for mimeDetect == 'finfo'
  523. *
  524. * @var resource
  525. **/
  526. protected $finfo = null;
  527. /**
  528. * List of disabled client's commands
  529. *
  530. * @var array
  531. **/
  532. protected $disabled = array();
  533. /**
  534. * overwrite extensions/mimetypes to mime.types
  535. *
  536. * @var array
  537. **/
  538. protected static $mimetypes = array(
  539. // applications
  540. 'exe' => 'application/x-executable',
  541. 'jar' => 'application/x-jar',
  542. // archives
  543. 'gz' => 'application/x-gzip',
  544. 'tgz' => 'application/x-gzip',
  545. 'tbz' => 'application/x-bzip2',
  546. 'rar' => 'application/x-rar',
  547. // texts
  548. 'php' => 'text/x-php',
  549. 'js' => 'text/javascript',
  550. 'rtfd' => 'application/rtfd',
  551. 'py' => 'text/x-python',
  552. 'rb' => 'text/x-ruby',
  553. 'sh' => 'text/x-shellscript',
  554. 'pl' => 'text/x-perl',
  555. 'xml' => 'text/xml',
  556. 'c' => 'text/x-csrc',
  557. 'h' => 'text/x-chdr',
  558. 'cpp' => 'text/x-c++src',
  559. 'hh' => 'text/x-c++hdr',
  560. 'md' => 'text/x-markdown',
  561. 'markdown' => 'text/x-markdown',
  562. 'yml' => 'text/x-yaml',
  563. // images
  564. 'bmp' => 'image/x-ms-bmp',
  565. 'tga' => 'image/x-targa',
  566. 'xbm' => 'image/xbm',
  567. 'pxm' => 'image/pxm',
  568. //audio
  569. 'wav' => 'audio/wav',
  570. // video
  571. 'dv' => 'video/x-dv',
  572. 'wm' => 'video/x-ms-wmv',
  573. 'ogm' => 'video/ogg',
  574. 'm2ts' => 'video/MP2T',
  575. 'mts' => 'video/MP2T',
  576. 'ts' => 'video/MP2T',
  577. 'm3u8' => 'application/x-mpegURL',
  578. 'mpd' => 'application/dash+xml'
  579. );
  580. /**
  581. * Directory separator - required by client
  582. *
  583. * @var string
  584. **/
  585. protected $separator = DIRECTORY_SEPARATOR;
  586. /**
  587. * Directory separator for decode/encode hash
  588. *
  589. * @var string
  590. **/
  591. protected $separatorForHash = '';
  592. /**
  593. * System Root path (Unix like: '/', Windows: '\', 'C:\' or 'D:\'...)
  594. *
  595. * @var string
  596. **/
  597. protected $systemRoot = DIRECTORY_SEPARATOR;
  598. /**
  599. * Mimetypes allowed to display
  600. *
  601. * @var array
  602. **/
  603. protected $onlyMimes = array();
  604. /**
  605. * Store files moved or overwrited files info
  606. *
  607. * @var array
  608. **/
  609. protected $removed = array();
  610. /**
  611. * Store files added files info
  612. *
  613. * @var array
  614. **/
  615. protected $added = array();
  616. /**
  617. * Cache storage
  618. *
  619. * @var array
  620. **/
  621. protected $cache = array();
  622. /**
  623. * Cache by folders
  624. *
  625. * @var array
  626. **/
  627. protected $dirsCache = array();
  628. /**
  629. * You should use `$this->sessionCache['subdirs']` instead
  630. *
  631. * @var array
  632. * @deprecated
  633. */
  634. protected $subdirsCache = array();
  635. /**
  636. * This volume session cache
  637. *
  638. * @var array
  639. */
  640. protected $sessionCache;
  641. /**
  642. * Session caching item list
  643. *
  644. * @var array
  645. */
  646. protected $sessionCaching = array('rootstat' => true, 'subdirs' => true);
  647. /**
  648. * elFinder session wrapper object
  649. *
  650. * @var elFinderSessionInterface
  651. */
  652. protected $session;
  653. /**
  654. * Search start time
  655. *
  656. * @var int
  657. */
  658. protected $searchStart;
  659. /**
  660. * Current query word on doSearch
  661. *
  662. * @var array
  663. **/
  664. protected $doSearchCurrentQuery = array();
  665. /**
  666. * Is root modified (for clear root stat cache)
  667. *
  668. * @var bool
  669. */
  670. protected $rootModified = false;
  671. /**
  672. * Is disable of command `url`
  673. *
  674. * @var string
  675. */
  676. protected $disabledGetUrl = false;
  677. /**
  678. * Accepted filename validator
  679. *
  680. * @var string | callable
  681. */
  682. protected $nameValidator;
  683. /**
  684. * Accepted dirname validator
  685. *
  686. * @var string | callable
  687. */
  688. protected $dirnameValidator;
  689. /*********************************************************************/
  690. /* INITIALIZATION */
  691. /*********************************************************************/
  692. /**
  693. * Prepare driver before mount volume.
  694. * Return true if volume is ready.
  695. *
  696. * @return bool
  697. * @author Dmitry (dio) Levashov
  698. **/
  699. protected function init()
  700. {
  701. return true;
  702. }
  703. /**
  704. * Configure after successfull mount.
  705. * By default set thumbnails path and image manipulation library.
  706. *
  707. * @return void
  708. * @throws elFinderAbortException
  709. * @author Dmitry (dio) Levashov
  710. */
  711. protected function configure()
  712. {
  713. // set thumbnails path
  714. $path = $this->options['tmbPath'];
  715. if ($path) {
  716. if (!file_exists($path)) {
  717. if (mkdir($path)) {
  718. chmod($path, $this->options['tmbPathMode']);
  719. } else {
  720. $path = '';
  721. }
  722. }
  723. if (is_dir($path) && is_readable($path)) {
  724. $this->tmbPath = $path;
  725. $this->tmbPathWritable = is_writable($path);
  726. }
  727. }
  728. // set resouce path
  729. if (!is_dir($this->options['resourcePath'])) {
  730. $this->options['resourcePath'] = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'resources';
  731. }
  732. // set image manipulation library
  733. $type = preg_match('/^(imagick|gd|convert|auto)$/i', $this->options['imgLib'])
  734. ? strtolower($this->options['imgLib'])
  735. : 'auto';
  736. if (($type === 'imagick' || $type === 'auto') && extension_loaded('imagick')) {
  737. $this->imgLib = 'imagick';
  738. } else if (($type === 'gd' || $type === 'auto') && function_exists('gd_info')) {
  739. $this->imgLib = 'gd';
  740. } else {
  741. $convertCache = 'imgLibConvert';
  742. if (($convertCmd = $this->session->get($convertCache, false)) !== false) {
  743. $this->imgLib = $convertCmd;
  744. } else {
  745. $this->imgLib = ($this->procExec(ELFINDER_CONVERT_PATH . ' -version') === 0) ? 'convert' : '';
  746. $this->session->set($convertCache, $this->imgLib);
  747. }
  748. }
  749. if ($type !== 'auto' && $this->imgLib === '') {
  750. // fallback
  751. $this->imgLib = extension_loaded('imagick') ? 'imagick' : (function_exists('gd_info') ? 'gd' : '');
  752. }
  753. // check video to img converter
  754. if (!empty($this->options['imgConverter']) && is_array($this->options['imgConverter'])) {
  755. foreach ($this->options['imgConverter'] as $_type => $_converter) {
  756. if (isset($_converter['func'])) {
  757. $this->imgConverter[strtolower($_type)] = $_converter;
  758. }
  759. }
  760. }
  761. if (!isset($this->imgConverter['video'])) {
  762. $videoLibCache = 'videoLib';
  763. if (($videoLibCmd = $this->session->get($videoLibCache, false)) === false) {
  764. $videoLibCmd = ($this->procExec(ELFINDER_FFMPEG_PATH . ' -version') === 0) ? 'ffmpeg' : '';
  765. $this->session->set($videoLibCache, $videoLibCmd);
  766. }
  767. if ($videoLibCmd) {
  768. $this->imgConverter['video'] = array(
  769. 'func' => array($this, $videoLibCmd . 'ToImg'),
  770. 'maxlen' => $this->options['tmbVideoConvLen']
  771. );
  772. }
  773. }
  774. // check archivers
  775. if (empty($this->archivers['create'])) {
  776. $this->disabled[] = 'archive';
  777. }
  778. if (empty($this->archivers['extract'])) {
  779. $this->disabled[] = 'extract';
  780. }
  781. $_arc = $this->getArchivers();
  782. if (empty($_arc['create'])) {
  783. $this->disabled[] = 'zipdl';
  784. }
  785. // check 'statOwner' for command `chmod`
  786. if (empty($this->options['statOwner'])) {
  787. $this->disabled[] = 'chmod';
  788. }
  789. // check 'mimeMap'
  790. if (!is_array($this->options['mimeMap'])) {
  791. $this->options['mimeMap'] = array();
  792. }
  793. if (is_array($this->options['staticMineMap']) && $this->options['staticMineMap']) {
  794. $this->options['mimeMap'] = array_merge($this->options['mimeMap'], $this->options['staticMineMap']);
  795. }
  796. if (is_array($this->options['additionalMimeMap']) && $this->options['additionalMimeMap']) {
  797. $this->options['mimeMap'] = array_merge($this->options['mimeMap'], $this->options['additionalMimeMap']);
  798. }
  799. // check 'url' in disabled commands
  800. if (in_array('url', $this->disabled)) {
  801. $this->disabledGetUrl = true;
  802. }
  803. // set run time setting uploadOverwrite
  804. $this->uploadOverwrite = $this->options['uploadOverwrite'];
  805. }
  806. /**
  807. * @deprecated
  808. */
  809. protected function sessionRestart()
  810. {
  811. $this->sessionCache = $this->session->start()->get($this->id, array());
  812. return true;
  813. }
  814. /*********************************************************************/
  815. /* PUBLIC API */
  816. /*********************************************************************/
  817. /**
  818. * Return driver id. Used as a part of volume id.
  819. *
  820. * @return string
  821. * @author Dmitry (dio) Levashov
  822. **/
  823. public function driverId()
  824. {
  825. return $this->driverId;
  826. }
  827. /**
  828. * Return volume id
  829. *
  830. * @return string
  831. * @author Dmitry (dio) Levashov
  832. **/
  833. public function id()
  834. {
  835. return $this->id;
  836. }
  837. /**
  838. * Assign elFinder session wrapper object
  839. *
  840. * @param $session elFinderSessionInterface
  841. */
  842. public function setSession($session)
  843. {
  844. $this->session = $session;
  845. }
  846. /**
  847. * Get elFinder sesson wrapper object
  848. *
  849. * @return object The session object
  850. */
  851. public function getSession()
  852. {
  853. return $this->session;
  854. }
  855. /**
  856. * Save session cache data
  857. * Calls this function before umount this volume on elFinder::exec()
  858. *
  859. * @return void
  860. */
  861. public function saveSessionCache()
  862. {
  863. $this->session->set($this->id, $this->sessionCache);
  864. }
  865. /**
  866. * Return debug info for client
  867. *
  868. * @return array
  869. * @author Dmitry (dio) Levashov
  870. **/
  871. public function debug()
  872. {
  873. return array(
  874. 'id' => $this->id(),
  875. 'name' => strtolower(substr(get_class($this), strlen('elfinderdriver'))),
  876. 'mimeDetect' => $this->mimeDetect,
  877. 'imgLib' => $this->imgLib
  878. );
  879. }
  880. /**
  881. * chmod a file or folder
  882. *
  883. * @param string $hash file or folder hash to chmod
  884. * @param string $mode octal string representing new permissions
  885. *
  886. * @return array|false
  887. * @author David Bartle
  888. **/
  889. public function chmod($hash, $mode)
  890. {
  891. if ($this->commandDisabled('chmod')) {
  892. return $this->setError(elFinder::ERROR_PERM_DENIED);
  893. }
  894. if (!($file = $this->file($hash))) {
  895. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  896. }
  897. if (!$this->options['allowChmodReadOnly']) {
  898. if (!$this->attr($this->decode($hash), 'write', null, ($file['mime'] === 'directory'))) {
  899. return $this->setError(elFinder::ERROR_PERM_DENIED, $file['name']);
  900. }
  901. }
  902. $path = $this->decode($hash);
  903. $write = $file['write'];
  904. if ($this->convEncOut(!$this->_chmod($this->convEncIn($path), $mode))) {
  905. return $this->setError(elFinder::ERROR_PERM_DENIED, $file['name']);
  906. }
  907. $this->clearstatcache();
  908. if ($path == $this->root) {
  909. $this->rootModified = true;
  910. }
  911. if ($file = $this->stat($path)) {
  912. $files = array($file);
  913. if ($file['mime'] === 'directory' && $write !== $file['write']) {
  914. foreach ($this->getScandir($path) as $stat) {
  915. if ($this->mimeAccepted($stat['mime'])) {
  916. $files[] = $stat;
  917. }
  918. }
  919. }
  920. return $files;
  921. } else {
  922. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  923. }
  924. }
  925. /**
  926. * stat a file or folder for elFinder cmd exec
  927. *
  928. * @param string $hash file or folder hash to chmod
  929. *
  930. * @return array
  931. * @author Naoki Sawada
  932. **/
  933. public function fstat($hash)
  934. {
  935. $path = $this->decode($hash);
  936. return $this->stat($path);
  937. }
  938. /**
  939. * Clear PHP stat cache & all of inner stat caches
  940. */
  941. public function clearstatcache()
  942. {
  943. clearstatcache();
  944. $this->clearcache();
  945. }
  946. /**
  947. * Clear inner stat caches for target hash
  948. *
  949. * @param string $hash
  950. */
  951. public function clearcaches($hash = null)
  952. {
  953. if ($hash === null) {
  954. $this->clearcache();
  955. } else {
  956. $path = $this->decode($hash);
  957. unset($this->cache[$path], $this->dirsCache[$path]);
  958. }
  959. }
  960. /**
  961. * "Mount" volume.
  962. * Return true if volume available for read or write,
  963. * false - otherwise
  964. *
  965. * @param array $opts
  966. *
  967. * @return bool
  968. * @throws elFinderAbortException
  969. * @author Dmitry (dio) Levashov
  970. * @author Alexey Sukhotin
  971. */
  972. public function mount(array $opts)
  973. {
  974. $this->options = array_merge($this->options, $opts);
  975. if (!isset($this->options['path']) || $this->options['path'] === '') {
  976. return $this->setError('Path undefined.');
  977. }
  978. if (!$this->session) {
  979. return $this->setError('Session wrapper dose not set. Need to `$volume->setSession(elFinderSessionInterface);` before mount.');
  980. }
  981. if (!($this->session instanceof elFinderSessionInterface)) {
  982. return $this->setError('Session wrapper instance must be "elFinderSessionInterface".');
  983. }
  984. // set driverId
  985. if (!empty($this->options['driverId'])) {
  986. $this->driverId = $this->options['driverId'];
  987. }
  988. $this->id = $this->driverId . (!empty($this->options['id']) ? $this->options['id'] : elFinder::$volumesCnt++) . '_';
  989. $this->root = $this->normpathCE($this->options['path']);
  990. $this->separator = isset($this->options['separator']) ? $this->options['separator'] : DIRECTORY_SEPARATOR;
  991. if (!empty($this->options['winHashFix'])) {
  992. $this->separatorForHash = ($this->separator !== '/') ? '/' : '';
  993. }
  994. $this->systemRoot = isset($this->options['systemRoot']) ? $this->options['systemRoot'] : $this->separator;
  995. // set ARGS
  996. $this->ARGS = $_SERVER['REQUEST_METHOD'] === 'POST' ? $_POST : $_GET;
  997. $argInit = !empty($this->ARGS['init']);
  998. // session cache
  999. if ($argInit) {
  1000. $this->session->set($this->id, array());
  1001. }
  1002. $this->sessionCache = $this->session->get($this->id, array());
  1003. // default file attribute
  1004. $this->defaults = array(
  1005. 'read' => isset($this->options['defaults']['read']) ? !!$this->options['defaults']['read'] : true,
  1006. 'write' => isset($this->options['defaults']['write']) ? !!$this->options['defaults']['write'] : true,
  1007. 'locked' => isset($this->options['defaults']['locked']) ? !!$this->options['defaults']['locked'] : false,
  1008. 'hidden' => isset($this->options['defaults']['hidden']) ? !!$this->options['defaults']['hidden'] : false
  1009. );
  1010. // root attributes
  1011. $this->attributes[] = array(
  1012. 'pattern' => '~^' . preg_quote($this->separator) . '$~',
  1013. 'locked' => true,
  1014. 'hidden' => false
  1015. );
  1016. // set files attributes
  1017. if (!empty($this->options['attributes']) && is_array($this->options['attributes'])) {
  1018. foreach ($this->options['attributes'] as $a) {
  1019. // attributes must contain pattern and at least one rule
  1020. if (!empty($a['pattern']) || count($a) > 1) {
  1021. $this->attributes[] = $a;
  1022. }
  1023. }
  1024. }
  1025. if (!empty($this->options['accessControl']) && is_callable($this->options['accessControl'])) {
  1026. $this->access = $this->options['accessControl'];
  1027. }
  1028. $this->today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
  1029. $this->yesterday = $this->today - 86400;
  1030. if (!$this->init()) {
  1031. return false;
  1032. }
  1033. // set server encoding
  1034. if (!empty($this->options['encoding']) && strtoupper($this->options['encoding']) !== 'UTF-8') {
  1035. $this->encoding = $this->options['encoding'];
  1036. } else {
  1037. $this->encoding = null;
  1038. }
  1039. // check some options is arrays
  1040. $this->uploadAllow = isset($this->options['uploadAllow']) && is_array($this->options['uploadAllow'])
  1041. ? $this->options['uploadAllow']
  1042. : array();
  1043. $this->uploadDeny = isset($this->options['uploadDeny']) && is_array($this->options['uploadDeny'])
  1044. ? $this->options['uploadDeny']
  1045. : array();
  1046. $this->options['uiCmdMap'] = (isset($this->options['uiCmdMap']) && is_array($this->options['uiCmdMap']))
  1047. ? $this->options['uiCmdMap']
  1048. : array();
  1049. if (is_string($this->options['uploadOrder'])) { // telephat_mode on, compatibility with 1.x
  1050. $parts = explode(',', isset($this->options['uploadOrder']) ? $this->options['uploadOrder'] : 'deny,allow');
  1051. $this->uploadOrder = array(trim($parts[0]), trim($parts[1]));
  1052. } else { // telephat_mode off
  1053. $this->uploadOrder = !empty($this->options['uploadOrder']) ? $this->options['uploadOrder'] : array('deny', 'allow');
  1054. }
  1055. if (!empty($this->options['uploadMaxSize'])) {
  1056. $this->uploadMaxSize = elFinder::getIniBytes('', $this->options['uploadMaxSize']);
  1057. }
  1058. // Set maximum to PHP_INT_MAX
  1059. if (!defined('PHP_INT_MAX')) {
  1060. define('PHP_INT_MAX', 2147483647);
  1061. }
  1062. if ($this->uploadMaxSize < 1 || $this->uploadMaxSize > PHP_INT_MAX) {
  1063. $this->uploadMaxSize = PHP_INT_MAX;
  1064. }
  1065. // Set to get maximum size to 50% of memory_limit
  1066. $memLimit = elFinder::getIniBytes('memory_limit') / 2;
  1067. if ($memLimit > 0) {
  1068. $this->getMaxSize = empty($this->options['getMaxSize']) ? $memLimit : min($memLimit, elFinder::getIniBytes('', $this->options['getMaxSize']));
  1069. } else {
  1070. $this->getMaxSize = -1;
  1071. }
  1072. $this->disabled = isset($this->options['disabled']) && is_array($this->options['disabled'])
  1073. ? array_values(array_diff($this->options['disabled'], array('open'))) // 'open' is required
  1074. : array();
  1075. $this->cryptLib = $this->options['cryptLib'];
  1076. $this->mimeDetect = $this->options['mimeDetect'];
  1077. // find available mimetype detect method
  1078. $type = strtolower($this->options['mimeDetect']);
  1079. $type = preg_match('/^(finfo|mime_content_type|internal|auto)$/i', $type) ? $type : 'auto';
  1080. $regexp = '/text\/x\-(php|c\+\+)/';
  1081. if (($type == 'finfo' || $type == 'auto')
  1082. && class_exists('finfo', false)) {
  1083. $tmpFileInfo = explode(';', finfo_file(finfo_open(FILEINFO_MIME), __FILE__));
  1084. } else {
  1085. $tmpFileInfo = false;
  1086. }
  1087. $type = 'internal';
  1088. if ($tmpFileInfo && preg_match($regexp, array_shift($tmpFileInfo))) {
  1089. $type = 'finfo';
  1090. $this->finfo = finfo_open(FILEINFO_MIME);
  1091. } elseif (($type == 'mime_content_type' || $type == 'auto') && function_exists('mime_content_type')) {
  1092. $_mimetypes = explode(';', mime_content_type(__FILE__));
  1093. if (preg_match($regexp, array_shift($_mimetypes))) {
  1094. $type = 'mime_content_type';
  1095. }
  1096. }
  1097. $this->mimeDetect = $type;
  1098. // load mimes from external file for mimeDetect == 'internal'
  1099. // based on Alexey Sukhotin idea and patch: http://elrte.org/redmine/issues/163
  1100. // file must be in file directory or in parent one
  1101. if ($this->mimeDetect === 'internal' && !elFinderVolumeDriver::$mimetypesLoaded) {
  1102. elFinderVolumeDriver::loadMimeTypes(!empty($this->options['mimefile']) ? $this->options['mimefile'] : '');
  1103. }
  1104. $this->rootName = empty($this->options['alias']) ? $this->basenameCE($this->root) : $this->options['alias'];
  1105. // This get's triggered if $this->root == '/' and alias is empty.
  1106. // Maybe modify _basename instead?
  1107. if ($this->rootName === '') $this->rootName = $this->separator;
  1108. $root = $this->stat($this->root);
  1109. if (!$root) {
  1110. return $this->setError('Root folder does not exist.');
  1111. }
  1112. if (!$root['read'] && !$root['write']) {
  1113. return $this->setError('Root folder has not read and write permissions.');
  1114. }
  1115. if ($root['read']) {
  1116. if ($argInit) {
  1117. // check startPath - path to open by default instead of root
  1118. $startPath = $this->options['startPath'] ? $this->normpathCE($this->options['startPath']) : '';
  1119. if ($startPath) {
  1120. $start = $this->stat($startPath);
  1121. if (!empty($start)
  1122. && $start['mime'] == 'directory'
  1123. && $start['read']
  1124. && empty($start['hidden'])
  1125. && $this->inpathCE($startPath, $this->root)) {
  1126. $this->startPath = $startPath;
  1127. if (substr($this->startPath, -1, 1) == $this->options['separator']) {
  1128. $this->startPath = substr($this->startPath, 0, -1);
  1129. }
  1130. }
  1131. }
  1132. }
  1133. } else {
  1134. $this->options['URL'] = '';
  1135. $this->options['tmbURL'] = '';
  1136. $this->options['tmbPath'] = '';
  1137. // read only volume
  1138. array_unshift($this->attributes, array(
  1139. 'pattern' => '/.*/',
  1140. 'read' => false
  1141. ));
  1142. }
  1143. $this->treeDeep = $this->options['treeDeep'] > 0 ? (int)$this->options['treeDeep'] : 1;
  1144. $this->tmbSize = $this->options['tmbSize'] > 0 ? (int)$this->options['tmbSize'] : 48;
  1145. $this->URL = $this->options['URL'];
  1146. if ($this->URL && preg_match("|[^/?&=]$|", $this->URL)) {
  1147. $this->URL .= '/';
  1148. }
  1149. $dirUrlOwn = strtolower($this->options['dirUrlOwn']);
  1150. if ($dirUrlOwn === 'auto') {
  1151. $this->options['dirUrlOwn'] = $this->URL ? false : true;
  1152. } else if ($dirUrlOwn === 'hide') {
  1153. $this->options['dirUrlOwn'] = 'hide';
  1154. } else {
  1155. $this->options['dirUrlOwn'] = (bool)$this->options['dirUrlOwn'];
  1156. }
  1157. $this->tmbURL = !empty($this->options['tmbURL']) ? $this->options['tmbURL'] : '';
  1158. if ($this->tmbURL && $this->tmbURL !== 'self' && preg_match("|[^/?&=]$|", $this->tmbURL)) {
  1159. $this->tmbURL .= '/';
  1160. }
  1161. $this->nameValidator = !empty($this->options['acceptedName']) && (is_string($this->options['acceptedName']) || is_callable($this->options['acceptedName']))
  1162. ? $this->options['acceptedName']
  1163. : '';
  1164. $this->dirnameValidator = !empty($this->options['acceptedDirname']) && (is_callable($this->options['acceptedDirname']) || (is_string($this->options['acceptedDirname']) && preg_match($this->options['acceptedDirname'], '') !== false))
  1165. ? $this->options['acceptedDirname']
  1166. : $this->nameValidator;
  1167. $this->_checkArchivers();
  1168. // enabling archivers['create'] with options['useRemoteArchive']
  1169. if ($this->options['useRemoteArchive'] && empty($this->archivers['create']) && $this->getTempPath()) {
  1170. $_archivers = $this->getArchivers();
  1171. $this->archivers['create'] = $_archivers['create'];
  1172. }
  1173. // manual control archive types to create
  1174. if (!empty($this->options['archiveMimes']) && is_array($this->options['archiveMimes'])) {
  1175. foreach ($this->archivers['create'] as $mime => $v) {
  1176. if (!in_array($mime, $this->options['archiveMimes'])) {
  1177. unset($this->archivers['create'][$mime]);
  1178. }
  1179. }
  1180. }
  1181. // manualy add archivers
  1182. if (!empty($this->options['archivers']['create']) && is_array($this->options['archivers']['create'])) {
  1183. foreach ($this->options['archivers']['create'] as $mime => $conf) {
  1184. if (strpos($mime, 'application/') === 0
  1185. && !empty($conf['cmd'])
  1186. && isset($conf['argc'])
  1187. && !empty($conf['ext'])
  1188. && !isset($this->archivers['create'][$mime])) {
  1189. $this->archivers['create'][$mime] = $conf;
  1190. }
  1191. }
  1192. }
  1193. if (!empty($this->options['archivers']['extract']) && is_array($this->options['archivers']['extract'])) {
  1194. foreach ($this->options['archivers']['extract'] as $mime => $conf) {
  1195. if (strpos($mime, 'application/') === 0
  1196. && !empty($conf['cmd'])
  1197. && isset($conf['argc'])
  1198. && !empty($conf['ext'])
  1199. && !isset($this->archivers['extract'][$mime])) {
  1200. $this->archivers['extract'][$mime] = $conf;
  1201. }
  1202. }
  1203. }
  1204. if (!empty($this->options['noSessionCache']) && is_array($this->options['noSessionCache'])) {
  1205. foreach ($this->options['noSessionCache'] as $_key) {
  1206. $this->sessionCaching[$_key] = false;
  1207. unset($this->sessionCache[$_key]);
  1208. }
  1209. }
  1210. if ($this->sessionCaching['subdirs']) {
  1211. if (!isset($this->sessionCache['subdirs'])) {
  1212. $this->sessionCache['subdirs'] = array();
  1213. }
  1214. }
  1215. $this->configure();
  1216. // Normalize disabled (array_merge`for type array of JSON)
  1217. $this->disabled = array_values(array_unique($this->disabled));
  1218. // fix sync interval
  1219. if ($this->options['syncMinMs'] !== 0) {
  1220. $this->options['syncMinMs'] = max($this->options[$this->options['syncChkAsTs'] ? 'tsPlSleep' : 'lsPlSleep'] * 1000, intval($this->options['syncMinMs']));
  1221. }
  1222. // ` copyJoin` is required for the trash function
  1223. if ($this->options['trashHash'] && empty($this->options['copyJoin'])) {
  1224. $this->options['trashHash'] = '';
  1225. }
  1226. // set tmpLinkPath
  1227. if (elFinder::$tmpLinkPath && !$this->options['tmpLinkPath']) {
  1228. if (is_writeable(elFinder::$tmpLinkPath)) {
  1229. $this->options['tmpLinkPath'] = elFinder::$tmpLinkPath;
  1230. } else {
  1231. elFinder::$tmpLinkPath = '';
  1232. }
  1233. }
  1234. if ($this->options['tmpLinkPath'] && is_writable($this->options['tmpLinkPath'])) {
  1235. $this->tmpLinkPath = realpath($this->options['tmpLinkPath']);
  1236. } else if (!$this->tmpLinkPath && $this->tmbURL && $this->tmbPath) {
  1237. $this->tmpLinkPath = $this->tmbPath;
  1238. $this->options['tmpLinkUrl'] = $this->tmbURL;
  1239. } else if (!$this->options['URL'] && is_writable('../files/.tmb')) {
  1240. $this->tmpLinkPath = realpath('../files/.tmb');
  1241. $this->options['tmpLinkUrl'] = '';
  1242. if (!elFinder::$tmpLinkPath) {
  1243. elFinder::$tmpLinkPath = $this->tmpLinkPath;
  1244. elFinder::$tmpLinkUrl = '';
  1245. }
  1246. }
  1247. // set tmpLinkUrl
  1248. if (elFinder::$tmpLinkUrl && !$this->options['tmpLinkUrl']) {
  1249. $this->options['tmpLinkUrl'] = elFinder::$tmpLinkUrl;
  1250. }
  1251. if ($this->options['tmpLinkUrl']) {
  1252. $this->tmpLinkUrl = $this->options['tmpLinkUrl'];
  1253. }
  1254. if ($this->tmpLinkPath && !$this->tmpLinkUrl) {
  1255. $cur = realpath('./');
  1256. $i = 0;
  1257. while ($cur !== $this->systemRoot && strpos($this->tmpLinkPath, $cur) !== 0) {
  1258. $i++;
  1259. $cur = dirname($cur);
  1260. }
  1261. list($req) = explode('?', $_SERVER['REQUEST_URI']);
  1262. $reqs = explode('/', dirname($req));
  1263. $uri = join('/', array_slice($reqs, 0, count($reqs) - 1)) . substr($this->tmpLinkPath, strlen($cur));
  1264. $https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off');
  1265. $this->tmpLinkUrl = ($https ? 'https://' : 'http://')
  1266. . $_SERVER['SERVER_NAME'] // host
  1267. . (((!$https && $_SERVER['SERVER_PORT'] == 80) || ($https && $_SERVER['SERVER_PORT'] == 443)) ? '' : (':' . $_SERVER['SERVER_PORT'])) // port
  1268. . $uri;
  1269. if (!elFinder::$tmpLinkUrl) {
  1270. elFinder::$tmpLinkUrl = $this->tmpLinkUrl;
  1271. }
  1272. }
  1273. // remove last '/'
  1274. if ($this->tmpLinkPath) {
  1275. $this->tmpLinkPath = rtrim($this->tmpLinkPath, '/');
  1276. }
  1277. if ($this->tmpLinkUrl) {
  1278. $this->tmpLinkUrl = rtrim($this->tmpLinkUrl, '/');
  1279. }
  1280. // to update options cache
  1281. $this->updateCache($this->root, $root);
  1282. return $this->mounted = true;
  1283. }
  1284. /**
  1285. * Some "unmount" stuffs - may be required by virtual fs
  1286. *
  1287. * @return void
  1288. * @author Dmitry (dio) Levashov
  1289. **/
  1290. public function umount()
  1291. {
  1292. }
  1293. /**
  1294. * Remove session cache of this volume
  1295. */
  1296. public function clearSessionCache()
  1297. {
  1298. $this->sessionCache = array();
  1299. }
  1300. /**
  1301. * Return error message from last failed action
  1302. *
  1303. * @return array
  1304. * @author Dmitry (dio) Levashov
  1305. **/
  1306. public function error()
  1307. {
  1308. return $this->error;
  1309. }
  1310. /**
  1311. * Return is uploadable that given file name
  1312. *
  1313. * @param string $name file name
  1314. * @param bool $allowUnknown
  1315. *
  1316. * @return bool
  1317. * @author Naoki Sawada
  1318. **/
  1319. public function isUploadableByName($name, $allowUnknown = false)
  1320. {
  1321. $mimeByName = $this->mimetype($name, true);
  1322. return (($allowUnknown && $mimeByName === 'unknown') || $this->allowPutMime($mimeByName));
  1323. }
  1324. /**
  1325. * Return Extention/MIME Table (elFinderVolumeDriver::$mimetypes)
  1326. *
  1327. * @return array
  1328. * @author Naoki Sawada
  1329. */
  1330. public function getMimeTable()
  1331. {
  1332. // load mime.types
  1333. if (!elFinderVolumeDriver::$mimetypesLoaded) {
  1334. elFinderVolumeDriver::loadMimeTypes();
  1335. }
  1336. return elFinderVolumeDriver::$mimetypes;
  1337. }
  1338. /**
  1339. * Return file extention detected by MIME type
  1340. *
  1341. * @param string $mime MIME type
  1342. * @param string $suffix Additional suffix
  1343. *
  1344. * @return string
  1345. * @author Naoki Sawada
  1346. */
  1347. public function getExtentionByMime($mime, $suffix = '')
  1348. {
  1349. static $extTable = null;
  1350. if (is_null($extTable)) {
  1351. $extTable = array_flip(array_unique($this->getMimeTable()));
  1352. foreach ($this->options['mimeMap'] as $pair => $_mime) {
  1353. list($ext) = explode(':', $pair);
  1354. if ($ext !== '*' && !isset($extTable[$_mime])) {
  1355. $extTable[$_mime] = $ext;
  1356. }
  1357. }
  1358. }
  1359. if ($mime && isset($extTable[$mime])) {
  1360. return $suffix ? ($extTable[$mime] . $suffix) : $extTable[$mime];
  1361. }
  1362. return '';
  1363. }
  1364. /**
  1365. * Set mimetypes allowed to display to client
  1366. *
  1367. * @param array $mimes
  1368. *
  1369. * @return void
  1370. * @author Dmitry (dio) Levashov
  1371. **/
  1372. public function setMimesFilter($mimes)
  1373. {
  1374. if (is_array($mimes)) {
  1375. $this->onlyMimes = $mimes;
  1376. }
  1377. }
  1378. /**
  1379. * Return root folder hash
  1380. *
  1381. * @return string
  1382. * @author Dmitry (dio) Levashov
  1383. **/
  1384. public function root()
  1385. {
  1386. return $this->encode($this->root);
  1387. }
  1388. /**
  1389. * Return root path
  1390. *
  1391. * @return string
  1392. * @author Naoki Sawada
  1393. **/
  1394. public function getRootPath()
  1395. {
  1396. return $this->root;
  1397. }
  1398. /**
  1399. * Return target path hash
  1400. *
  1401. * @param string $path
  1402. * @param string $name
  1403. *
  1404. * @author Naoki Sawada
  1405. * @return string
  1406. */
  1407. public function getHash($path, $name = '')
  1408. {
  1409. if ($name !== '') {
  1410. $path = $this->joinPathCE($path, $name);
  1411. }
  1412. return $this->encode($path);
  1413. }
  1414. /**
  1415. * Return decoded path of target hash
  1416. * This method do not check the stat of target
  1417. * Use method `realpath()` to do check of the stat of target
  1418. *
  1419. * @param string $hash
  1420. *
  1421. * @author Naoki Sawada
  1422. * @return string
  1423. */
  1424. public function getPath($hash)
  1425. {
  1426. return $this->decode($hash);
  1427. }
  1428. /**
  1429. * Return root or startPath hash
  1430. *
  1431. * @return string
  1432. * @author Dmitry (dio) Levashov
  1433. **/
  1434. public function defaultPath()
  1435. {
  1436. return $this->encode($this->startPath ? $this->startPath : $this->root);
  1437. }
  1438. /**
  1439. * Return volume options required by client:
  1440. *
  1441. * @param $hash
  1442. *
  1443. * @return array
  1444. * @author Dmitry (dio) Levashov
  1445. */
  1446. public function options($hash)
  1447. {
  1448. $create = $createext = array();
  1449. if (isset($this->archivers['create']) && is_array($this->archivers['create'])) {
  1450. foreach ($this->archivers['create'] as $m => $v) {
  1451. $create[] = $m;
  1452. $createext[$m] = $v['ext'];
  1453. }
  1454. }
  1455. $opts = array(
  1456. 'path' => $hash ? $this->path($hash) : '',
  1457. 'url' => $this->URL,
  1458. 'tmbUrl' => (!$this->imgLib && $this->options['tmbFbSelf']) ? 'self' : $this->tmbURL,
  1459. 'disabled' => $this->disabled,
  1460. 'separator' => $this->separator,
  1461. 'copyOverwrite' => intval($this->options['copyOverwrite']),
  1462. 'uploadOverwrite' => intval($this->options['uploadOverwrite']),
  1463. 'uploadMaxSize' => intval($this->uploadMaxSize),
  1464. 'uploadMaxConn' => intval($this->options['uploadMaxConn']),
  1465. 'uploadMime' => array(
  1466. 'firstOrder' => isset($this->uploadOrder[0]) ? $this->uploadOrder[0] : 'deny',
  1467. 'allow' => $this->uploadAllow,
  1468. 'deny' => $this->uploadDeny
  1469. ),
  1470. 'dispInlineRegex' => $this->options['dispInlineRegex'],
  1471. 'jpgQuality' => intval($this->options['jpgQuality']),
  1472. 'archivers' => array(
  1473. 'create' => $create,
  1474. 'extract' => isset($this->archivers['extract']) && is_array($this->archivers['extract']) ? array_keys($this->archivers['extract']) : array(),
  1475. 'createext' => $createext
  1476. ),
  1477. 'uiCmdMap' => (isset($this->options['uiCmdMap']) && is_array($this->options['uiCmdMap'])) ? $this->options['uiCmdMap'] : array(),
  1478. 'syncChkAsTs' => intval($this->options['syncChkAsTs']),
  1479. 'syncMinMs' => intval($this->options['syncMinMs']),
  1480. 'i18nFolderName' => intval($this->options['i18nFolderName']),
  1481. 'tmbCrop' => intval($this->options['tmbCrop']),
  1482. 'substituteImg' => (bool)$this->options['substituteImg'],
  1483. 'onetimeUrl' => (bool)$this->options['onetimeUrl'],
  1484. );
  1485. if (!empty($this->options['trashHash'])) {
  1486. $opts['trashHash'] = $this->options['trashHash'];
  1487. }
  1488. if ($hash === null) {
  1489. // call from getRootStatExtra()
  1490. if (!empty($this->options['icon'])) {
  1491. $opts['icon'] = $this->options['icon'];
  1492. }
  1493. if (!empty($this->options['rootCssClass'])) {
  1494. $opts['csscls'] = $this->options['rootCssClass'];
  1495. }
  1496. if (isset($this->options['netkey'])) {
  1497. $opts['netkey'] = $this->options['netkey'];
  1498. }
  1499. }
  1500. return $opts;
  1501. }
  1502. /**
  1503. * Get option value of this volume
  1504. *
  1505. * @param string $name target option name
  1506. *
  1507. * @return NULL|mixed target option value
  1508. * @author Naoki Sawada
  1509. */
  1510. public function getOption($name)
  1511. {
  1512. return isset($this->options[$name]) ? $this->options[$name] : null;
  1513. }
  1514. /**
  1515. * Get plugin values of this options
  1516. *
  1517. * @param string $name Plugin name
  1518. *
  1519. * @return NULL|array Plugin values
  1520. * @author Naoki Sawada
  1521. */
  1522. public function getOptionsPlugin($name = '')
  1523. {
  1524. if ($name) {
  1525. return isset($this->options['plugin'][$name]) ? $this->options['plugin'][$name] : array();
  1526. } else {
  1527. return $this->options['plugin'];
  1528. }
  1529. }
  1530. /**
  1531. * Return true if command disabled in options
  1532. *
  1533. * @param string $cmd command name
  1534. *
  1535. * @return bool
  1536. * @author Dmitry (dio) Levashov
  1537. **/
  1538. public function commandDisabled($cmd)
  1539. {
  1540. return in_array($cmd, $this->disabled);
  1541. }
  1542. /**
  1543. * Return true if mime is required mimes list
  1544. *
  1545. * @param string $mime mime type to check
  1546. * @param array $mimes allowed mime types list or not set to use client mimes list
  1547. * @param bool|null $empty what to return on empty list
  1548. *
  1549. * @return bool|null
  1550. * @author Dmitry (dio) Levashov
  1551. * @author Troex Nevelin
  1552. **/
  1553. public function mimeAccepted($mime, $mimes = null, $empty = true)
  1554. {
  1555. $mimes = is_array($mimes) ? $mimes : $this->onlyMimes;
  1556. if (empty($mimes)) {
  1557. return $empty;
  1558. }
  1559. return $mime == 'directory'
  1560. || in_array('all', $mimes)
  1561. || in_array('All', $mimes)
  1562. || in_array($mime, $mimes)
  1563. || in_array(substr($mime, 0, strpos($mime, '/')), $mimes);
  1564. }
  1565. /**
  1566. * Return true if voume is readable.
  1567. *
  1568. * @return bool
  1569. * @author Dmitry (dio) Levashov
  1570. **/
  1571. public function isReadable()
  1572. {
  1573. $stat = $this->stat($this->root);
  1574. return $stat['read'];
  1575. }
  1576. /**
  1577. * Return true if copy from this volume allowed
  1578. *
  1579. * @return bool
  1580. * @author Dmitry (dio) Levashov
  1581. **/
  1582. public function copyFromAllowed()
  1583. {
  1584. return !!$this->options['copyFrom'];
  1585. }
  1586. /**
  1587. * Return file path related to root with convert encoging
  1588. *
  1589. * @param string $hash file hash
  1590. *
  1591. * @return string
  1592. * @author Dmitry (dio) Levashov
  1593. **/
  1594. public function path($hash)
  1595. {
  1596. return $this->convEncOut($this->_path($this->convEncIn($this->decode($hash))));
  1597. }
  1598. /**
  1599. * Return file real path if file exists
  1600. *
  1601. * @param string $hash file hash
  1602. *
  1603. * @return string | false
  1604. * @author Dmitry (dio) Levashov
  1605. **/
  1606. public function realpath($hash)
  1607. {
  1608. $path = $this->decode($hash);
  1609. return $this->stat($path) ? $path : false;
  1610. }
  1611. /**
  1612. * Return list of moved/overwrited files
  1613. *
  1614. * @return array
  1615. * @author Dmitry (dio) Levashov
  1616. **/
  1617. public function removed()
  1618. {
  1619. if ($this->removed) {
  1620. $unsetSubdir = isset($this->sessionCache['subdirs']) ? true : false;
  1621. foreach ($this->removed as $item) {
  1622. if ($item['mime'] === 'directory') {
  1623. $path = $this->decode($item['hash']);
  1624. if ($unsetSubdir) {
  1625. unset($this->sessionCache['subdirs'][$path]);
  1626. }
  1627. if ($item['phash'] !== '') {
  1628. $parent = $this->decode($item['phash']);
  1629. unset($this->cache[$parent]);
  1630. if ($this->root === $parent) {
  1631. $this->sessionCache['rootstat'] = array();
  1632. }
  1633. if ($unsetSubdir) {
  1634. unset($this->sessionCache['subdirs'][$parent]);
  1635. }
  1636. }
  1637. }
  1638. }
  1639. $this->removed = array_values($this->removed);
  1640. }
  1641. return $this->removed;
  1642. }
  1643. /**
  1644. * Return list of added files
  1645. *
  1646. * @deprecated
  1647. * @return array
  1648. * @author Naoki Sawada
  1649. **/
  1650. public function added()
  1651. {
  1652. return $this->added;
  1653. }
  1654. /**
  1655. * Clean removed files list
  1656. *
  1657. * @return void
  1658. * @author Dmitry (dio) Levashov
  1659. **/
  1660. public function resetRemoved()
  1661. {
  1662. $this->resetResultStat();
  1663. }
  1664. /**
  1665. * Clean added/removed files list
  1666. *
  1667. * @return void
  1668. **/
  1669. public function resetResultStat()
  1670. {
  1671. $this->removed = array();
  1672. $this->added = array();
  1673. }
  1674. /**
  1675. * Return file/dir hash or first founded child hash with required attr == $val
  1676. *
  1677. * @param string $hash file hash
  1678. * @param string $attr attribute name
  1679. * @param bool $val attribute value
  1680. *
  1681. * @return string|false
  1682. * @author Dmitry (dio) Levashov
  1683. **/
  1684. public function closest($hash, $attr, $val)
  1685. {
  1686. return ($path = $this->closestByAttr($this->decode($hash), $attr, $val)) ? $this->encode($path) : false;
  1687. }
  1688. /**
  1689. * Return file info or false on error
  1690. *
  1691. * @param string $hash file hash
  1692. *
  1693. * @return array|false
  1694. * @internal param bool $realpath add realpath field to file info
  1695. * @author Dmitry (dio) Levashov
  1696. */
  1697. public function file($hash)
  1698. {
  1699. $file = $this->stat($this->decode($hash));
  1700. return ($file) ? $file : $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  1701. }
  1702. /**
  1703. * Return folder info
  1704. *
  1705. * @param string $hash folder hash
  1706. * @param bool $resolveLink
  1707. *
  1708. * @return array|false
  1709. * @internal param bool $hidden return hidden file info
  1710. * @author Dmitry (dio) Levashov
  1711. */
  1712. public function dir($hash, $resolveLink = false)
  1713. {
  1714. if (($dir = $this->file($hash)) == false) {
  1715. return $this->setError(elFinder::ERROR_DIR_NOT_FOUND);
  1716. }
  1717. if ($resolveLink && !empty($dir['thash'])) {
  1718. $dir = $this->file($dir['thash']);
  1719. }
  1720. return $dir && $dir['mime'] == 'directory' && empty($dir['hidden'])
  1721. ? $dir
  1722. : $this->setError(elFinder::ERROR_NOT_DIR);
  1723. }
  1724. /**
  1725. * Return directory content or false on error
  1726. *
  1727. * @param string $hash file hash
  1728. *
  1729. * @return array|false
  1730. * @author Dmitry (dio) Levashov
  1731. **/
  1732. public function scandir($hash)
  1733. {
  1734. if (($dir = $this->dir($hash)) == false) {
  1735. return false;
  1736. }
  1737. $path = $this->decode($hash);
  1738. if ($res = $dir['read']
  1739. ? $this->getScandir($path)
  1740. : $this->setError(elFinder::ERROR_PERM_DENIED)) {
  1741. $dirs = null;
  1742. if ($this->sessionCaching['subdirs'] && isset($this->sessionCache['subdirs'][$path])) {
  1743. $dirs = $this->sessionCache['subdirs'][$path];
  1744. }
  1745. if ($dirs !== null || (isset($dir['dirs']) && $dir['dirs'] != 1)) {
  1746. $_dir = $dir;
  1747. if ($dirs || $this->subdirs($hash)) {
  1748. $dir['dirs'] = 1;
  1749. } else {
  1750. unset($dir['dirs']);
  1751. }
  1752. if ($dir !== $_dir) {
  1753. $this->updateCache($path, $dir);
  1754. }
  1755. }
  1756. }
  1757. return $res;
  1758. }
  1759. /**
  1760. * Return dir files names list
  1761. *
  1762. * @param string $hash file hash
  1763. * @param null $intersect
  1764. *
  1765. * @return array|false
  1766. * @author Dmitry (dio) Levashov
  1767. */
  1768. public function ls($hash, $intersect = null)
  1769. {
  1770. if (($dir = $this->dir($hash)) == false || !$dir['read']) {
  1771. return false;
  1772. }
  1773. $list = array();
  1774. $path = $this->decode($hash);
  1775. $check = array();
  1776. if ($intersect) {
  1777. $check = array_flip($intersect);
  1778. }
  1779. foreach ($this->getScandir($path) as $stat) {
  1780. if (empty($stat['hidden']) && (!$check || isset($check[$stat['name']])) && $this->mimeAccepted($stat['mime'])) {
  1781. $list[$stat['hash']] = $stat['name'];
  1782. }
  1783. }
  1784. return $list;
  1785. }
  1786. /**
  1787. * Return subfolders for required folder or false on error
  1788. *
  1789. * @param string $hash folder hash or empty string to get tree from root folder
  1790. * @param int $deep subdir deep
  1791. * @param string $exclude dir hash which subfolders must be exluded from result, required to not get stat twice on cwd subfolders
  1792. *
  1793. * @return array|false
  1794. * @author Dmitry (dio) Levashov
  1795. **/
  1796. public function tree($hash = '', $deep = 0, $exclude = '')
  1797. {
  1798. $path = $hash ? $this->decode($hash) : $this->root;
  1799. if (($dir = $this->stat($path)) == false || $dir['mime'] != 'directory') {
  1800. return false;
  1801. }
  1802. $dirs = $this->gettree($path, $deep > 0 ? $deep - 1 : $this->treeDeep - 1, $exclude ? $this->decode($exclude) : null);
  1803. array_unshift($dirs, $dir);
  1804. return $dirs;
  1805. }
  1806. /**
  1807. * Return part of dirs tree from required dir up to root dir
  1808. *
  1809. * @param string $hash directory hash
  1810. * @param bool|null $lineal only lineal parents
  1811. *
  1812. * @return array|false
  1813. * @throws elFinderAbortException
  1814. * @author Dmitry (dio) Levashov
  1815. */
  1816. public function parents($hash, $lineal = false)
  1817. {
  1818. if (($current = $this->dir($hash)) == false) {
  1819. return false;
  1820. }
  1821. $args = func_get_args();
  1822. // checks 3rd param `$until` (elFinder >= 2.1.24)
  1823. $until = '';
  1824. if (isset($args[2])) {
  1825. $until = $args[2];
  1826. }
  1827. $path = $this->decode($hash);
  1828. $tree = array();
  1829. while ($path && $path != $this->root) {
  1830. elFinder::checkAborted();
  1831. $path = $this->dirnameCE($path);
  1832. if (!($stat = $this->stat($path)) || !empty($stat['hidden']) || !$stat['read']) {
  1833. return false;
  1834. }
  1835. array_unshift($tree, $stat);
  1836. if (!$lineal) {
  1837. foreach ($this->gettree($path, 0) as $dir) {
  1838. elFinder::checkAborted();
  1839. if (!isset($tree[$dir['hash']])) {
  1840. $tree[$dir['hash']] = $dir;
  1841. }
  1842. }
  1843. }
  1844. if ($until && $until === $this->encode($path)) {
  1845. break;
  1846. }
  1847. }
  1848. return $tree ? array_values($tree) : array($current);
  1849. }
  1850. /**
  1851. * Create thumbnail for required file and return its name or false on failed
  1852. *
  1853. * @param $hash
  1854. *
  1855. * @return false|string
  1856. * @throws ImagickException
  1857. * @throws elFinderAbortException
  1858. * @author Dmitry (dio) Levashov
  1859. */
  1860. public function tmb($hash)
  1861. {
  1862. $path = $this->decode($hash);
  1863. $stat = $this->stat($path);
  1864. if (isset($stat['tmb'])) {
  1865. $res = $stat['tmb'] == "1" ? $this->createTmb($path, $stat) : $stat['tmb'];
  1866. if (!$res) {
  1867. list($type) = explode('/', $stat['mime']);
  1868. $fallback = $this->options['resourcePath'] . DIRECTORY_SEPARATOR . strtolower($type) . '.png';
  1869. if (is_file($fallback)) {
  1870. $res = $this->tmbname($stat);
  1871. if (!copy($fallback, $this->tmbPath . DIRECTORY_SEPARATOR . $res)) {
  1872. $res = false;
  1873. }
  1874. }
  1875. }
  1876. return $res;
  1877. }
  1878. return false;
  1879. }
  1880. /**
  1881. * Return file size / total directory size
  1882. *
  1883. * @param string file hash
  1884. *
  1885. * @return array
  1886. * @throws elFinderAbortException
  1887. * @author Dmitry (dio) Levashov
  1888. */
  1889. public function size($hash)
  1890. {
  1891. return $this->countSize($this->decode($hash));
  1892. }
  1893. /**
  1894. * Open file for reading and return file pointer
  1895. *
  1896. * @param string file hash
  1897. *
  1898. * @return Resource|false
  1899. * @author Dmitry (dio) Levashov
  1900. **/
  1901. public function open($hash)
  1902. {
  1903. if (($file = $this->file($hash)) == false
  1904. || $file['mime'] == 'directory') {
  1905. return false;
  1906. }
  1907. return $this->fopenCE($this->decode($hash), 'rb');
  1908. }
  1909. /**
  1910. * Close file pointer
  1911. *
  1912. * @param Resource $fp file pointer
  1913. * @param string $hash file hash
  1914. *
  1915. * @return void
  1916. * @author Dmitry (dio) Levashov
  1917. **/
  1918. public function close($fp, $hash)
  1919. {
  1920. $this->fcloseCE($fp, $this->decode($hash));
  1921. }
  1922. /**
  1923. * Create directory and return dir info
  1924. *
  1925. * @param string $dsthash destination directory hash
  1926. * @param string $name directory name
  1927. *
  1928. * @return array|false
  1929. * @author Dmitry (dio) Levashov
  1930. **/
  1931. public function mkdir($dsthash, $name)
  1932. {
  1933. if ($this->commandDisabled('mkdir')) {
  1934. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1935. }
  1936. if (!$this->nameAccepted($name, true)) {
  1937. return $this->setError(elFinder::ERROR_INVALID_DIRNAME);
  1938. }
  1939. if (($dir = $this->dir($dsthash)) == false) {
  1940. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#' . $dsthash);
  1941. }
  1942. $path = $this->decode($dsthash);
  1943. if (!$dir['write'] || !$this->allowCreate($path, $name, true)) {
  1944. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1945. }
  1946. $dst = $this->joinPathCE($path, $name);
  1947. $stat = $this->isNameExists($dst);
  1948. if (!empty($stat)) {
  1949. return $this->setError(elFinder::ERROR_EXISTS, $name);
  1950. }
  1951. $this->clearcache();
  1952. $mkpath = $this->convEncOut($this->_mkdir($this->convEncIn($path), $this->convEncIn($name)));
  1953. if ($mkpath) {
  1954. $this->clearstatcache();
  1955. $this->updateSubdirsCache($path, true);
  1956. $this->updateSubdirsCache($mkpath, false);
  1957. }
  1958. return $mkpath ? $this->stat($mkpath) : false;
  1959. }
  1960. /**
  1961. * Create empty file and return its info
  1962. *
  1963. * @param string $dst destination directory
  1964. * @param string $name file name
  1965. *
  1966. * @return array|false
  1967. * @author Dmitry (dio) Levashov
  1968. **/
  1969. public function mkfile($dst, $name)
  1970. {
  1971. if ($this->commandDisabled('mkfile')) {
  1972. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1973. }
  1974. if (!$this->nameAccepted($name, false)) {
  1975. return $this->setError(elFinder::ERROR_INVALID_NAME);
  1976. }
  1977. $mimeByName = $this->mimetype($name, true);
  1978. if ($mimeByName && !$this->allowPutMime($mimeByName)) {
  1979. return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME, $name);
  1980. }
  1981. if (($dir = $this->dir($dst)) == false) {
  1982. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#' . $dst);
  1983. }
  1984. $path = $this->decode($dst);
  1985. if (!$dir['write'] || !$this->allowCreate($path, $name, false)) {
  1986. return $this->setError(elFinder::ERROR_PERM_DENIED);
  1987. }
  1988. if ($this->isNameExists($this->joinPathCE($path, $name))) {
  1989. return $this->setError(elFinder::ERROR_EXISTS, $name);
  1990. }
  1991. $this->clearcache();
  1992. $res = false;
  1993. if ($path = $this->convEncOut($this->_mkfile($this->convEncIn($path), $this->convEncIn($name)))) {
  1994. $this->clearstatcache();
  1995. $res = $this->stat($path);
  1996. }
  1997. return $res;
  1998. }
  1999. /**
  2000. * Rename file and return file info
  2001. *
  2002. * @param string $hash file hash
  2003. * @param string $name new file name
  2004. *
  2005. * @return array|false
  2006. * @throws elFinderAbortException
  2007. * @author Dmitry (dio) Levashov
  2008. */
  2009. public function rename($hash, $name)
  2010. {
  2011. if ($this->commandDisabled('rename')) {
  2012. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2013. }
  2014. if (!($file = $this->file($hash))) {
  2015. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  2016. }
  2017. if ($name === $file['name']) {
  2018. return $file;
  2019. }
  2020. if (!empty($file['locked'])) {
  2021. return $this->setError(elFinder::ERROR_LOCKED, $file['name']);
  2022. }
  2023. $isDir = ($file['mime'] === 'directory');
  2024. if (!$this->nameAccepted($name, $isDir)) {
  2025. return $this->setError($isDir ? elFinder::ERROR_INVALID_DIRNAME : elFinder::ERROR_INVALID_NAME);
  2026. }
  2027. if (!$isDir) {
  2028. $mimeByName = $this->mimetype($name, true);
  2029. if ($mimeByName && !$this->allowPutMime($mimeByName)) {
  2030. return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME, $name);
  2031. }
  2032. }
  2033. $path = $this->decode($hash);
  2034. $dir = $this->dirnameCE($path);
  2035. $stat = $this->isNameExists($this->joinPathCE($dir, $name));
  2036. if ($stat) {
  2037. return $this->setError(elFinder::ERROR_EXISTS, $name);
  2038. }
  2039. if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
  2040. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2041. }
  2042. $this->rmTmb($file); // remove old name tmbs, we cannot do this after dir move
  2043. if ($path = $this->convEncOut($this->_move($this->convEncIn($path), $this->convEncIn($dir), $this->convEncIn($name)))) {
  2044. $this->clearcache();
  2045. return $this->stat($path);
  2046. }
  2047. return false;
  2048. }
  2049. /**
  2050. * Create file copy with suffix "copy number" and return its info
  2051. *
  2052. * @param string $hash file hash
  2053. * @param string $suffix suffix to add to file name
  2054. *
  2055. * @return array|false
  2056. * @throws elFinderAbortException
  2057. * @author Dmitry (dio) Levashov
  2058. */
  2059. public function duplicate($hash, $suffix = 'copy')
  2060. {
  2061. if ($this->commandDisabled('duplicate')) {
  2062. return $this->setError(elFinder::ERROR_COPY, '#' . $hash, elFinder::ERROR_PERM_DENIED);
  2063. }
  2064. if (($file = $this->file($hash)) == false) {
  2065. return $this->setError(elFinder::ERROR_COPY, elFinder::ERROR_FILE_NOT_FOUND);
  2066. }
  2067. $path = $this->decode($hash);
  2068. $dir = $this->dirnameCE($path);
  2069. $name = $this->uniqueName($dir, $file['name'], sprintf($this->options['duplicateSuffix'], $suffix));
  2070. if (!$this->allowCreate($dir, $name, ($file['mime'] === 'directory'))) {
  2071. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2072. }
  2073. return ($path = $this->copy($path, $dir, $name)) == false
  2074. ? false
  2075. : $this->stat($path);
  2076. }
  2077. /**
  2078. * Save uploaded file.
  2079. * On success return array with new file stat and with removed file hash (if existed file was replaced)
  2080. *
  2081. * @param Resource $fp file pointer
  2082. * @param string $dst destination folder hash
  2083. * @param $name
  2084. * @param string $tmpname file tmp name - required to detect mime type
  2085. * @param array $hashes exists files hash array with filename as key
  2086. *
  2087. * @return array|false
  2088. * @throws elFinderAbortException
  2089. * @internal param string $src file name
  2090. * @author Dmitry (dio) Levashov
  2091. */
  2092. public function upload($fp, $dst, $name, $tmpname, $hashes = array())
  2093. {
  2094. if ($this->commandDisabled('upload')) {
  2095. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2096. }
  2097. if (($dir = $this->dir($dst)) == false) {
  2098. return $this->setError(elFinder::ERROR_TRGDIR_NOT_FOUND, '#' . $dst);
  2099. }
  2100. if (empty($dir['write'])) {
  2101. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2102. }
  2103. if (!$this->nameAccepted($name, false)) {
  2104. return $this->setError(elFinder::ERROR_INVALID_NAME);
  2105. }
  2106. $mimeByName = '';
  2107. if ($this->mimeDetect === 'internal') {
  2108. $mime = $this->mimetype($tmpname, $name);
  2109. } else {
  2110. $mime = $this->mimetype($tmpname, $name);
  2111. $mimeByName = $this->mimetype($name, true);
  2112. if ($mime === 'unknown') {
  2113. $mime = $mimeByName;
  2114. }
  2115. }
  2116. if (!$this->allowPutMime($mime) || ($mimeByName && !$this->allowPutMime($mimeByName))) {
  2117. return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME, '(' . $mime . ')');
  2118. }
  2119. $tmpsize = (int)sprintf('%u', filesize($tmpname));
  2120. if ($this->uploadMaxSize > 0 && $tmpsize > $this->uploadMaxSize) {
  2121. return $this->setError(elFinder::ERROR_UPLOAD_FILE_SIZE);
  2122. }
  2123. $dstpath = $this->decode($dst);
  2124. if (isset($hashes[$name])) {
  2125. $test = $this->decode($hashes[$name]);
  2126. $file = $this->stat($test);
  2127. } else {
  2128. $test = $this->joinPathCE($dstpath, $name);
  2129. $file = $this->isNameExists($test);
  2130. }
  2131. $this->clearcache();
  2132. if ($file && $file['name'] === $name) { // file exists and check filename for item ID based filesystem
  2133. if ($this->uploadOverwrite) {
  2134. if (!$file['write']) {
  2135. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2136. } elseif ($file['mime'] == 'directory') {
  2137. return $this->setError(elFinder::ERROR_NOT_REPLACE, $name);
  2138. }
  2139. $this->remove($test);
  2140. } else {
  2141. $name = $this->uniqueName($dstpath, $name, '-', false);
  2142. }
  2143. }
  2144. $stat = array(
  2145. 'mime' => $mime,
  2146. 'width' => 0,
  2147. 'height' => 0,
  2148. 'size' => $tmpsize);
  2149. // $w = $h = 0;
  2150. if (strpos($mime, 'image') === 0 && ($s = getimagesize($tmpname))) {
  2151. $stat['width'] = $s[0];
  2152. $stat['height'] = $s[1];
  2153. }
  2154. // $this->clearcache();
  2155. if (($path = $this->saveCE($fp, $dstpath, $name, $stat)) == false) {
  2156. return false;
  2157. }
  2158. $stat = $this->stat($path);
  2159. // Try get URL
  2160. if (empty($stat['url']) && ($url = $this->getContentUrl($stat['hash']))) {
  2161. $stat['url'] = $url;
  2162. }
  2163. return $stat;
  2164. }
  2165. /**
  2166. * Paste files
  2167. *
  2168. * @param Object $volume source volume
  2169. * @param $src
  2170. * @param string $dst destination dir hash
  2171. * @param bool $rmSrc remove source after copy?
  2172. * @param array $hashes
  2173. *
  2174. * @return array|false
  2175. * @throws elFinderAbortException
  2176. * @internal param string $source file hash
  2177. * @author Dmitry (dio) Levashov
  2178. */
  2179. public function paste($volume, $src, $dst, $rmSrc = false, $hashes = array())
  2180. {
  2181. $err = $rmSrc ? elFinder::ERROR_MOVE : elFinder::ERROR_COPY;
  2182. if ($this->commandDisabled('paste')) {
  2183. return $this->setError($err, '#' . $src, elFinder::ERROR_PERM_DENIED);
  2184. }
  2185. if (($file = $volume->file($src, $rmSrc)) == false) {
  2186. return $this->setError($err, '#' . $src, elFinder::ERROR_FILE_NOT_FOUND);
  2187. }
  2188. $name = $file['name'];
  2189. $errpath = $volume->path($file['hash']);
  2190. if (($dir = $this->dir($dst)) == false) {
  2191. return $this->setError($err, $errpath, elFinder::ERROR_TRGDIR_NOT_FOUND, '#' . $dst);
  2192. }
  2193. if (!$dir['write'] || !$file['read']) {
  2194. return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
  2195. }
  2196. $destination = $this->decode($dst);
  2197. if (($test = $volume->closest($src, $rmSrc ? 'locked' : 'read', $rmSrc))) {
  2198. return $rmSrc
  2199. ? $this->setError($err, $errpath, elFinder::ERROR_LOCKED, $volume->path($test))
  2200. : $this->setError($err, $errpath, empty($file['thash']) ? elFinder::ERROR_PERM_DENIED : elFinder::ERROR_MKOUTLINK);
  2201. }
  2202. if (isset($hashes[$name])) {
  2203. $test = $this->decode($hashes[$name]);
  2204. $stat = $this->stat($test);
  2205. } else {
  2206. $test = $this->joinPathCE($destination, $name);
  2207. $stat = $this->isNameExists($test);
  2208. }
  2209. $this->clearcache();
  2210. $dstDirExists = false;
  2211. if ($stat && $stat['name'] === $name) { // file exists and check filename for item ID based filesystem
  2212. if ($this->options['copyOverwrite']) {
  2213. // do not replace file with dir or dir with file
  2214. if (!$this->isSameType($file['mime'], $stat['mime'])) {
  2215. return $this->setError(elFinder::ERROR_NOT_REPLACE, $this->path($stat['hash']));
  2216. }
  2217. // existed file is not writable
  2218. if (empty($stat['write'])) {
  2219. return $this->setError($err, $errpath, elFinder::ERROR_PERM_DENIED);
  2220. }
  2221. if ($this->options['copyJoin']) {
  2222. if (!empty($stat['locked'])) {
  2223. return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
  2224. }
  2225. } else {
  2226. // existed file locked or has locked child
  2227. if (($locked = $this->closestByAttr($test, 'locked', true))) {
  2228. $stat = $this->stat($locked);
  2229. return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
  2230. }
  2231. }
  2232. // target is entity file of alias
  2233. if ($volume === $this && ((isset($file['target']) && $test == $file['target']) || $test == $this->decode($src))) {
  2234. return $this->setError(elFinder::ERROR_REPLACE, $errpath);
  2235. }
  2236. // remove existed file
  2237. if (!$this->options['copyJoin'] || $stat['mime'] !== 'directory') {
  2238. if (!$this->remove($test)) {
  2239. return $this->setError(elFinder::ERROR_REPLACE, $this->path($stat['hash']));
  2240. }
  2241. } else if ($stat['mime'] === 'directory') {
  2242. $dstDirExists = true;
  2243. }
  2244. } else {
  2245. $name = $this->uniqueName($destination, $name, ' ', false);
  2246. }
  2247. }
  2248. // copy/move inside current volume
  2249. if ($volume === $this) { // changing == operand to === fixes issue #1285 - Paul Canning 24/03/2016
  2250. $source = $this->decode($src);
  2251. // do not copy into itself
  2252. if ($this->inpathCE($destination, $source)) {
  2253. return $this->setError(elFinder::ERROR_COPY_ITSELF, $errpath);
  2254. }
  2255. $rmDir = false;
  2256. if ($rmSrc) {
  2257. if ($dstDirExists) {
  2258. $rmDir = true;
  2259. $method = 'copy';
  2260. } else {
  2261. $method = 'move';
  2262. }
  2263. } else {
  2264. $method = 'copy';
  2265. }
  2266. $this->clearcache();
  2267. if ($res = ($path = $this->$method($source, $destination, $name)) ? $this->stat($path) : false) {
  2268. if ($rmDir) {
  2269. $this->remove($source);
  2270. }
  2271. } else {
  2272. return false;
  2273. }
  2274. } else {
  2275. // copy/move from another volume
  2276. if (!$this->options['copyTo'] || !$volume->copyFromAllowed()) {
  2277. return $this->setError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED);
  2278. }
  2279. $this->error = array();
  2280. if (($path = $this->copyFrom($volume, $src, $destination, $name)) == false) {
  2281. return false;
  2282. }
  2283. if ($rmSrc && !$this->error()) {
  2284. if (!$volume->rm($src)) {
  2285. if ($volume->file($src)) {
  2286. $this->addError(elFinder::ERROR_RM_SRC);
  2287. } else {
  2288. $this->removed[] = $file;
  2289. }
  2290. }
  2291. }
  2292. $res = $this->stat($path);
  2293. }
  2294. return $res;
  2295. }
  2296. /**
  2297. * Return path info array to archive of target items
  2298. *
  2299. * @param array $hashes
  2300. *
  2301. * @return array|false
  2302. * @throws Exception
  2303. * @author Naoki Sawada
  2304. */
  2305. public function zipdl($hashes)
  2306. {
  2307. if ($this->commandDisabled('zipdl')) {
  2308. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2309. }
  2310. $archivers = $this->getArchivers();
  2311. $cmd = null;
  2312. if (!$archivers || empty($archivers['create'])) {
  2313. return false;
  2314. }
  2315. $archivers = $archivers['create'];
  2316. if (!$archivers) {
  2317. return false;
  2318. }
  2319. foreach (array('zip', 'tgz') as $ext) {
  2320. $mime = $this->mimetype('file.' . $ext, true);
  2321. if (isset($archivers[$mime])) {
  2322. $cmd = $archivers[$mime];
  2323. break;
  2324. }
  2325. }
  2326. if (!$cmd) {
  2327. $cmd = array_shift($archivers);
  2328. if (!empty($ext)) {
  2329. $mime = $this->mimetype('file.' . $ext, true);
  2330. }
  2331. }
  2332. $file = $mime = '';
  2333. $ext = $cmd['ext'];
  2334. $res = false;
  2335. $mixed = false;
  2336. $hashes = array_values($hashes);
  2337. $dirname = dirname(str_replace($this->separator, DIRECTORY_SEPARATOR, $this->path($hashes[0])));
  2338. $cnt = count($hashes);
  2339. if ($cnt > 1) {
  2340. for ($i = 1; $i < $cnt; $i++) {
  2341. if ($dirname !== dirname(str_replace($this->separator, DIRECTORY_SEPARATOR, $this->path($hashes[$i])))) {
  2342. $mixed = true;
  2343. break;
  2344. }
  2345. }
  2346. }
  2347. if ($mixed || $this->root == $this->dirnameCE($this->decode($hashes[0]))) {
  2348. $prefix = $this->rootName;
  2349. } else {
  2350. $prefix = basename($dirname);
  2351. }
  2352. if ($dir = $this->getItemsInHand($hashes)) {
  2353. $tmppre = (substr(PHP_OS, 0, 3) === 'WIN') ? 'zdl' : 'elfzdl';
  2354. $pdir = dirname($dir);
  2355. // garbage collection (expire 2h)
  2356. register_shutdown_function(array('elFinder', 'GlobGC'), $pdir . DIRECTORY_SEPARATOR . $tmppre . '*', 7200);
  2357. $files = self::localScandir($dir);
  2358. if ($files && ($arc = tempnam($dir, $tmppre))) {
  2359. unlink($arc);
  2360. $arc = $arc . '.' . $ext;
  2361. $name = basename($arc);
  2362. if ($arc = $this->makeArchive($dir, $files, $name, $cmd)) {
  2363. $file = tempnam($pdir, $tmppre);
  2364. unlink($file);
  2365. $res = rename($arc, $file);
  2366. $this->rmdirRecursive($dir);
  2367. }
  2368. }
  2369. }
  2370. return $res ? array('path' => $file, 'ext' => $ext, 'mime' => $mime, 'prefix' => $prefix) : false;
  2371. }
  2372. /**
  2373. * Return file contents
  2374. *
  2375. * @param string $hash file hash
  2376. *
  2377. * @return string|false
  2378. * @author Dmitry (dio) Levashov
  2379. **/
  2380. public function getContents($hash)
  2381. {
  2382. $file = $this->file($hash);
  2383. if (!$file) {
  2384. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  2385. }
  2386. if ($file['mime'] == 'directory') {
  2387. return $this->setError(elFinder::ERROR_NOT_FILE);
  2388. }
  2389. if (!$file['read']) {
  2390. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2391. }
  2392. if ($this->getMaxSize > 0 && $file['size'] > $this->getMaxSize) {
  2393. return $this->setError(elFinder::ERROR_UPLOAD_FILE_SIZE);
  2394. }
  2395. return $file['size'] ? $this->_getContents($this->convEncIn($this->decode($hash), true)) : '';
  2396. }
  2397. /**
  2398. * Put content in text file and return file info.
  2399. *
  2400. * @param string $hash file hash
  2401. * @param string $content new file content
  2402. *
  2403. * @return array|false
  2404. * @author Dmitry (dio) Levashov
  2405. **/
  2406. public function putContents($hash, $content)
  2407. {
  2408. if ($this->commandDisabled('edit')) {
  2409. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2410. }
  2411. $path = $this->decode($hash);
  2412. if (!($file = $this->file($hash))) {
  2413. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  2414. }
  2415. if (!$file['write']) {
  2416. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2417. }
  2418. // check data cheme
  2419. if (preg_match('~^\0data:(.+?/.+?);base64,~', $content, $m)) {
  2420. $dMime = $m[1];
  2421. if ($file['size'] > 0 && $dMime !== $file['mime']) {
  2422. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2423. }
  2424. $content = base64_decode(substr($content, strlen($m[0])));
  2425. }
  2426. // check MIME
  2427. $name = $this->basenameCE($path);
  2428. $mime = '';
  2429. $mimeByName = $this->mimetype($name, true);
  2430. if ($this->mimeDetect !== 'internal') {
  2431. if ($tp = $this->tmpfile()) {
  2432. fwrite($tp, $content);
  2433. $info = stream_get_meta_data($tp);
  2434. $filepath = $info['uri'];
  2435. $mime = $this->mimetype($filepath, $name);
  2436. fclose($tp);
  2437. }
  2438. }
  2439. if (!$this->allowPutMime($mimeByName) || ($mime && !$this->allowPutMime($mime))) {
  2440. return $this->setError(elFinder::ERROR_UPLOAD_FILE_MIME);
  2441. }
  2442. $this->clearcache();
  2443. $res = false;
  2444. if ($this->convEncOut($this->_filePutContents($this->convEncIn($path), $content))) {
  2445. $this->clearstatcache();
  2446. $res = $this->stat($path);
  2447. }
  2448. return $res;
  2449. }
  2450. /**
  2451. * Extract files from archive
  2452. *
  2453. * @param string $hash archive hash
  2454. * @param null $makedir
  2455. *
  2456. * @return array|bool
  2457. * @author Dmitry (dio) Levashov,
  2458. * @author Alexey Sukhotin
  2459. */
  2460. public function extract($hash, $makedir = null)
  2461. {
  2462. if ($this->commandDisabled('extract')) {
  2463. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2464. }
  2465. if (($file = $this->file($hash)) == false) {
  2466. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  2467. }
  2468. $archiver = isset($this->archivers['extract'][$file['mime']])
  2469. ? $this->archivers['extract'][$file['mime']]
  2470. : array();
  2471. if (!$archiver) {
  2472. return $this->setError(elFinder::ERROR_NOT_ARCHIVE);
  2473. }
  2474. $path = $this->decode($hash);
  2475. $parent = $this->stat($this->dirnameCE($path));
  2476. if (!$file['read'] || !$parent['write']) {
  2477. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2478. }
  2479. $this->clearcache();
  2480. $this->extractToNewdir = is_null($makedir) ? 'auto' : (bool)$makedir;
  2481. if ($path = $this->convEncOut($this->_extract($this->convEncIn($path), $archiver))) {
  2482. if (is_array($path)) {
  2483. foreach ($path as $_k => $_p) {
  2484. $path[$_k] = $this->stat($_p);
  2485. }
  2486. } else {
  2487. $path = $this->stat($path);
  2488. }
  2489. return $path;
  2490. } else {
  2491. return false;
  2492. }
  2493. }
  2494. /**
  2495. * Add files to archive
  2496. *
  2497. * @param $hashes
  2498. * @param $mime
  2499. * @param string $name
  2500. *
  2501. * @return array|bool
  2502. * @throws Exception
  2503. */
  2504. public function archive($hashes, $mime, $name = '')
  2505. {
  2506. if ($this->commandDisabled('archive')) {
  2507. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2508. }
  2509. if ($name !== '' && !$this->nameAccepted($name, false)) {
  2510. return $this->setError(elFinder::ERROR_INVALID_NAME);
  2511. }
  2512. $archiver = isset($this->archivers['create'][$mime])
  2513. ? $this->archivers['create'][$mime]
  2514. : array();
  2515. if (!$archiver) {
  2516. return $this->setError(elFinder::ERROR_ARCHIVE_TYPE);
  2517. }
  2518. $files = array();
  2519. $useRemoteArchive = !empty($this->options['useRemoteArchive']);
  2520. $dir = '';
  2521. foreach ($hashes as $hash) {
  2522. if (($file = $this->file($hash)) == false) {
  2523. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND, '#' . $hash);
  2524. }
  2525. if (!$file['read']) {
  2526. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2527. }
  2528. $path = $this->decode($hash);
  2529. if ($dir === '') {
  2530. $dir = $this->dirnameCE($path);
  2531. $stat = $this->stat($dir);
  2532. if (!$stat['write']) {
  2533. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2534. }
  2535. }
  2536. $files[] = $useRemoteArchive ? $hash : $this->basenameCE($path);
  2537. }
  2538. if ($name === '') {
  2539. $name = count($files) == 1 ? $files[0] : 'Archive';
  2540. } else {
  2541. $name = str_replace(array('/', '\\'), '_', preg_replace('/\.' . preg_quote($archiver['ext'], '/') . '$/i', '', $name));
  2542. }
  2543. $name .= '.' . $archiver['ext'];
  2544. $name = $this->uniqueName($dir, $name, '');
  2545. $this->clearcache();
  2546. if ($useRemoteArchive) {
  2547. return ($path = $this->remoteArchive($files, $name, $archiver)) ? $this->stat($path) : false;
  2548. } else {
  2549. return ($path = $this->convEncOut($this->_archive($this->convEncIn($dir), $this->convEncIn($files), $this->convEncIn($name), $archiver))) ? $this->stat($path) : false;
  2550. }
  2551. }
  2552. /**
  2553. * Create an archive from remote items
  2554. *
  2555. * @param array $hashes files hashes list
  2556. * @param string $name archive name
  2557. * @param array $arc archiver options
  2558. *
  2559. * @return string|boolean path of created archive
  2560. * @throws Exception
  2561. */
  2562. protected function remoteArchive($hashes, $name, $arc)
  2563. {
  2564. $resPath = false;
  2565. $file0 = $this->file($hashes[0]);
  2566. if ($file0 && ($dir = $this->getItemsInHand($hashes))) {
  2567. $files = self::localScandir($dir);
  2568. if ($files) {
  2569. if ($arc = $this->makeArchive($dir, $files, $name, $arc)) {
  2570. if ($fp = fopen($arc, 'rb')) {
  2571. $path = $this->decode($file0['phash']);
  2572. $stat = array();
  2573. $resPath = $this->saveCE($fp, $path, $name, $stat);
  2574. fclose($fp);
  2575. }
  2576. }
  2577. }
  2578. $this->rmdirRecursive($dir);
  2579. }
  2580. return $resPath;
  2581. }
  2582. /**
  2583. * Resize image
  2584. *
  2585. * @param string $hash image file
  2586. * @param int $width new width
  2587. * @param int $height new height
  2588. * @param int $x X start poistion for crop
  2589. * @param int $y Y start poistion for crop
  2590. * @param string $mode action how to mainpulate image
  2591. * @param string $bg background color
  2592. * @param int $degree rotete degree
  2593. * @param int $jpgQuality JEPG quality (1-100)
  2594. *
  2595. * @return array|false
  2596. * @throws ImagickException
  2597. * @throws elFinderAbortException
  2598. * @author Dmitry (dio) Levashov
  2599. * @author Alexey Sukhotin
  2600. * @author nao-pon
  2601. * @author Troex Nevelin
  2602. */
  2603. public function resize($hash, $width, $height, $x, $y, $mode = 'resize', $bg = '', $degree = 0, $jpgQuality = null)
  2604. {
  2605. if ($this->commandDisabled('resize')) {
  2606. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2607. }
  2608. if ($mode === 'rotate' && $degree == 0) {
  2609. return array('losslessRotate' => ($this->procExec(ELFINDER_EXIFTRAN_PATH . ' -h') === 0 || $this->procExec(ELFINDER_JPEGTRAN_PATH . ' -version') === 0));
  2610. }
  2611. if (($file = $this->file($hash)) == false) {
  2612. return $this->setError(elFinder::ERROR_FILE_NOT_FOUND);
  2613. }
  2614. if (!$file['write'] || !$file['read']) {
  2615. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2616. }
  2617. $path = $this->decode($hash);
  2618. $work_path = $this->getWorkFile($this->encoding ? $this->convEncIn($path, true) : $path);
  2619. if (!$work_path || !is_writable($work_path)) {
  2620. if ($work_path && $path !== $work_path && is_file($work_path)) {
  2621. unlink($work_path);
  2622. }
  2623. return $this->setError(elFinder::ERROR_PERM_DENIED);
  2624. }
  2625. if ($this->imgLib !== 'imagick' && $this->imgLib !== 'convert') {
  2626. if (elFinder::isAnimationGif($work_path)) {
  2627. return $this->setError(elFinder::ERROR_UNSUPPORT_TYPE);
  2628. }
  2629. }
  2630. if (elFinder::isAnimationPng($work_path)) {
  2631. return $this->setError(elFinder::ERROR_UNSUPPORT_TYPE);
  2632. }
  2633. switch ($mode) {
  2634. case 'propresize':
  2635. $result = $this->imgResize($work_path, $width, $height, true, true, null, $jpgQuality);
  2636. break;
  2637. case 'crop':
  2638. $result = $this->imgCrop($work_path, $width, $height, $x, $y, null, $jpgQuality);
  2639. break;
  2640. case 'fitsquare':
  2641. $result = $this->imgSquareFit($work_path, $width, $height, 'center', 'middle', ($bg ? $bg : $this->options['tmbBgColor']), null, $jpgQuality);
  2642. break;
  2643. case 'rotate':
  2644. $result = $this->imgRotate($work_path, $degree, ($bg ? $bg : $this->options['bgColorFb']), null, $jpgQuality);
  2645. break;
  2646. default:
  2647. $result = $this->imgResize($work_path, $width, $height, false, true, null, $jpgQuality);
  2648. break;
  2649. }
  2650. $ret = false;
  2651. if ($result) {
  2652. $this->rmTmb($file);
  2653. $this->clearstatcache();
  2654. $fstat = stat($work_path);
  2655. $imgsize = getimagesize($work_path);
  2656. if ($path !== $work_path) {
  2657. $file['size'] = $fstat['size'];
  2658. $file['ts'] = $fstat['mtime'];
  2659. if ($imgsize) {
  2660. $file['width'] = $imgsize[0];
  2661. $file['height'] = $imgsize[1];
  2662. }
  2663. if ($fp = fopen($work_path, 'rb')) {
  2664. $ret = $this->saveCE($fp, $this->dirnameCE($path), $this->basenameCE($path), $file);
  2665. fclose($fp);
  2666. }
  2667. } else {
  2668. $ret = true;
  2669. }
  2670. if ($ret) {
  2671. $this->clearcache();
  2672. $ret = $this->stat($path);
  2673. if ($imgsize) {
  2674. $ret['width'] = $imgsize[0];
  2675. $ret['height'] = $imgsize[1];
  2676. }
  2677. }
  2678. }
  2679. if ($path !== $work_path) {
  2680. is_file($work_path) && unlink($work_path);
  2681. }
  2682. return $ret;
  2683. }
  2684. /**
  2685. * Remove file/dir
  2686. *
  2687. * @param string $hash file hash
  2688. *
  2689. * @return bool
  2690. * @throws elFinderAbortException
  2691. * @author Dmitry (dio) Levashov
  2692. */
  2693. public function rm($hash)
  2694. {
  2695. return $this->commandDisabled('rm')
  2696. ? $this->setError(elFinder::ERROR_PERM_DENIED)
  2697. : $this->remove($this->decode($hash));
  2698. }
  2699. /**
  2700. * Search files
  2701. *
  2702. * @param string $q search string
  2703. * @param array $mimes
  2704. * @param null $hash
  2705. *
  2706. * @return array
  2707. * @throws elFinderAbortException
  2708. * @author Dmitry (dio) Levashov
  2709. */
  2710. public function search($q, $mimes, $hash = null)
  2711. {
  2712. $res = array();
  2713. $matchMethod = null;
  2714. $args = func_get_args();
  2715. if (!empty($args[3])) {
  2716. $matchMethod = 'searchMatch' . $args[3];
  2717. if (!is_callable(array($this, $matchMethod))) {
  2718. return array();
  2719. }
  2720. }
  2721. $dir = null;
  2722. if ($hash) {
  2723. $dir = $this->decode($hash);
  2724. $stat = $this->stat($dir);
  2725. if (!$stat || $stat['mime'] !== 'directory' || !$stat['read']) {
  2726. $q = '';
  2727. }
  2728. }
  2729. if ($mimes && $this->onlyMimes) {
  2730. $mimes = array_intersect($mimes, $this->onlyMimes);
  2731. if (!$mimes) {
  2732. $q = '';
  2733. }
  2734. }
  2735. $this->searchStart = time();
  2736. $qs = preg_split('/"([^"]+)"| +/', $q, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  2737. $query = $excludes = array();
  2738. foreach ($qs as $_q) {
  2739. $_q = trim($_q);
  2740. if ($_q !== '') {
  2741. if ($_q[0] === '-') {
  2742. if (isset($_q[1])) {
  2743. $excludes[] = substr($_q, 1);
  2744. }
  2745. } else {
  2746. $query[] = $_q;
  2747. }
  2748. }
  2749. }
  2750. if (!$query) {
  2751. $q = '';
  2752. } else {
  2753. $q = join(' ', $query);
  2754. $this->doSearchCurrentQuery = array(
  2755. 'q' => $q,
  2756. 'excludes' => $excludes,
  2757. 'matchMethod' => $matchMethod
  2758. );
  2759. }
  2760. if ($q === '' || $this->commandDisabled('search')) {
  2761. return $res;
  2762. }
  2763. // valided regex $this->options['searchExDirReg']
  2764. if ($this->options['searchExDirReg']) {
  2765. if (false === preg_match($this->options['searchExDirReg'], '')) {
  2766. $this->options['searchExDirReg'] = '';
  2767. }
  2768. }
  2769. // check the leaf root too
  2770. if (!$mimes && (is_null($dir) || $dir == $this->root)) {
  2771. $rootStat = $this->stat($this->root);
  2772. if (!empty($rootStat['phash'])) {
  2773. if ($this->stripos($rootStat['name'], $q) !== false) {
  2774. $res = array($rootStat);
  2775. }
  2776. }
  2777. }
  2778. return array_merge($res, $this->doSearch(is_null($dir) ? $this->root : $dir, $q, $mimes));
  2779. }
  2780. /**
  2781. * Return image dimensions
  2782. *
  2783. * @param string $hash file hash
  2784. *
  2785. * @return array|string
  2786. * @author Dmitry (dio) Levashov
  2787. **/
  2788. public function dimensions($hash)
  2789. {
  2790. if (($file = $this->file($hash)) == false) {
  2791. return false;
  2792. }
  2793. // Throw additional parameters for some drivers
  2794. if (func_num_args() > 1) {
  2795. $args = func_get_arg(1);
  2796. } else {
  2797. $args = array();
  2798. }
  2799. return $this->convEncOut($this->_dimensions($this->convEncIn($this->decode($hash)), $file['mime'], $args));
  2800. }
  2801. /**
  2802. * Return has subdirs
  2803. *
  2804. * @param string $hash file hash
  2805. *
  2806. * @return bool
  2807. * @author Naoki Sawada
  2808. **/
  2809. public function subdirs($hash)
  2810. {
  2811. return (bool)$this->subdirsCE($this->decode($hash));
  2812. }
  2813. /**
  2814. * Return content URL (for netmout volume driver)
  2815. * If file.url == 1 requests from JavaScript client with XHR
  2816. *
  2817. * @param string $hash file hash
  2818. * @param array $options options array
  2819. *
  2820. * @return boolean|string
  2821. * @author Naoki Sawada
  2822. */
  2823. public function getContentUrl($hash, $options = array())
  2824. {
  2825. if (($file = $this->file($hash)) === false) {
  2826. return false;
  2827. }
  2828. if (!empty($options['onetime']) && $this->options['onetimeUrl']) {
  2829. if (is_callable($this->options['onetimeUrl'])) {
  2830. return call_user_func_array($this->options['onetimeUrl'], array($file, $options, $this));
  2831. } else {
  2832. $ret = false;
  2833. if ($tmpdir = elFinder::getStaticVar('commonTempPath')) {
  2834. if ($source = $this->open($hash)) {
  2835. if ($_dat = tempnam($tmpdir, 'ELF')) {
  2836. $token = md5($_dat . session_id());
  2837. $dat = $tmpdir . DIRECTORY_SEPARATOR . 'ELF' . $token;
  2838. if (rename($_dat, $dat)) {
  2839. $info = stream_get_meta_data($source);
  2840. if (!empty($info['uri'])) {
  2841. $tmp = $info['uri'];
  2842. } else {
  2843. $tmp = tempnam($tmpdir, 'ELF');
  2844. if ($dest = fopen($tmp, 'wb')) {
  2845. if (!stream_copy_to_stream($source, $dest)) {
  2846. $tmp = false;
  2847. }
  2848. fclose($dest);
  2849. }
  2850. }
  2851. $this->close($source, $hash);
  2852. if ($tmp) {
  2853. $info = array(
  2854. 'file' => base64_encode($tmp),
  2855. 'name' => $file['name'],
  2856. 'mime' => $file['mime'],
  2857. 'ts' => $file['ts']
  2858. );
  2859. if (file_put_contents($dat, json_encode($info))) {
  2860. $ret = elFinder::getConnectorUrl() . '?cmd=file&onetime=1&target=' . $token;
  2861. }
  2862. }
  2863. if (!$ret) {
  2864. unlink($dat);
  2865. }
  2866. } else {
  2867. unlink($_dat);
  2868. }
  2869. }
  2870. }
  2871. }
  2872. return $ret;
  2873. }
  2874. }
  2875. if (empty($file['url']) && $this->URL) {
  2876. $path = str_replace($this->separator, '/', substr($this->decode($hash), strlen(rtrim($this->root, '/' . $this->separator)) + 1));
  2877. if ($this->encoding) {
  2878. $path = $this->convEncIn($path, true);
  2879. }
  2880. $path = str_replace('%2F', '/', rawurlencode($path));
  2881. return $this->URL . $path;
  2882. } else {
  2883. $ret = false;
  2884. if (!empty($file['url']) && $file['url'] != 1) {
  2885. return $file['url'];
  2886. } else if (!empty($options['temporary']) && ($tempInfo = $this->getTempLinkInfo('temp_' . md5($hash . session_id())))) {
  2887. if ($source = $this->open($hash)) {
  2888. if ($dest = fopen($tempInfo['path'], 'wb')) {
  2889. if (stream_copy_to_stream($source, $dest)) {
  2890. $ret = $tempInfo['url'] . '?' . rawurlencode($file['name']);
  2891. }
  2892. fclose($dest);
  2893. }
  2894. $this->close($source, $hash);
  2895. }
  2896. }
  2897. return $ret;
  2898. }
  2899. }
  2900. /**
  2901. * Get temporary contents link infomation
  2902. *
  2903. * @param string $name
  2904. *
  2905. * @return boolean|array
  2906. * @author Naoki Sawada
  2907. */
  2908. public function getTempLinkInfo($name = null)
  2909. {
  2910. if ($this->tmpLinkPath) {
  2911. if (!$name) {
  2912. $name = 'temp_' . md5($_SERVER['REMOTE_ADDR'] . (string)microtime(true));
  2913. } else if (substr($name, 0, 5) !== 'temp_') {
  2914. $name = 'temp_' . $name;
  2915. }
  2916. register_shutdown_function(array('elFinder', 'GlobGC'), $this->tmpLinkPath . DIRECTORY_SEPARATOR . 'temp_*', elFinder::$tmpLinkLifeTime);
  2917. return array(
  2918. 'path' => $path = $this->tmpLinkPath . DIRECTORY_SEPARATOR . $name,
  2919. 'url' => $this->tmpLinkUrl . '/' . $name
  2920. );
  2921. }
  2922. return false;
  2923. }
  2924. /**
  2925. * Get URL of substitute image by request args `substitute` or 4th argument $maxSize
  2926. *
  2927. * @param string $target Target hash
  2928. * @param array $srcSize Size info array [width, height]
  2929. * @param resource $srcfp Source file file pointer
  2930. * @param integer $maxSize Maximum pixel of substitute image
  2931. *
  2932. * @return boolean
  2933. * @throws ImagickException
  2934. * @throws elFinderAbortException
  2935. */
  2936. public function getSubstituteImgLink($target, $srcSize, $srcfp = null, $maxSize = null)
  2937. {
  2938. $url = false;
  2939. if (!$maxSize) {
  2940. $args = elFinder::$currentArgs;
  2941. if (!empty($args['substitute'])) {
  2942. $maxSize = $args['substitute'];
  2943. }
  2944. }
  2945. if ($maxSize && $srcSize[0] && $srcSize[1]) {
  2946. if ($this->getOption('substituteImg')) {
  2947. $maxSize = intval($maxSize);
  2948. $zoom = min(($maxSize / $srcSize[0]), ($maxSize / $srcSize[1]));
  2949. if ($zoom < 1) {
  2950. $width = round($srcSize[0] * $zoom);
  2951. $height = round($srcSize[1] * $zoom);
  2952. $jpgQuality = 50;
  2953. $preserveExif = false;
  2954. $unenlarge = true;
  2955. $checkAnimated = true;
  2956. if (!$srcfp) {
  2957. elFinder::checkAborted();
  2958. $srcfp = $this->open($target);
  2959. }
  2960. if ($srcfp && ($tempLink = $this->getTempLinkInfo())) {
  2961. elFinder::checkAborted();
  2962. $dest = fopen($tempLink['path'], 'wb');
  2963. if ($dest && stream_copy_to_stream($srcfp, $dest)) {
  2964. fclose($dest);
  2965. if ($this->imageUtil('resize', $tempLink['path'], compact('width', 'height', 'jpgQuality', 'preserveExif', 'unenlarge', 'checkAnimated'))) {
  2966. $url = $tempLink['url'];
  2967. // set expire to 1 min left
  2968. touch($tempLink['path'], time() - elFinder::$tmpLinkLifeTime + 60);
  2969. } else {
  2970. unlink($tempLink['path']);
  2971. }
  2972. }
  2973. $this->close($srcfp, $target);
  2974. }
  2975. }
  2976. }
  2977. }
  2978. return $url;
  2979. }
  2980. /**
  2981. * Return temp path
  2982. *
  2983. * @return string
  2984. * @author Naoki Sawada
  2985. */
  2986. public function getTempPath()
  2987. {
  2988. $tempPath = null;
  2989. if (isset($this->tmpPath) && $this->tmpPath && is_writable($this->tmpPath)) {
  2990. $tempPath = $this->tmpPath;
  2991. } else if (isset($this->tmp) && $this->tmp && is_writable($this->tmp)) {
  2992. $tempPath = $this->tmp;
  2993. } else if (elFinder::getStaticVar('commonTempPath') && is_writable(elFinder::getStaticVar('commonTempPath'))) {
  2994. $tempPath = elFinder::getStaticVar('commonTempPath');
  2995. } else if (function_exists('sys_get_temp_dir')) {
  2996. $tempPath = sys_get_temp_dir();
  2997. } else if ($this->tmbPathWritable) {
  2998. $tempPath = $this->tmbPath;
  2999. }
  3000. if ($tempPath && DIRECTORY_SEPARATOR !== '/') {
  3001. $tempPath = str_replace('/', DIRECTORY_SEPARATOR, $tempPath);
  3002. }
  3003. return $tempPath;
  3004. }
  3005. /**
  3006. * (Make &) Get upload taget dirctory hash
  3007. *
  3008. * @param string $baseTargetHash
  3009. * @param string $path
  3010. * @param array $result
  3011. *
  3012. * @return boolean|string
  3013. * @author Naoki Sawada
  3014. */
  3015. public function getUploadTaget($baseTargetHash, $path, & $result)
  3016. {
  3017. $base = $this->decode($baseTargetHash);
  3018. $targetHash = $baseTargetHash;
  3019. $path = ltrim($path, $this->separator);
  3020. $dirs = explode($this->separator, $path);
  3021. array_pop($dirs);
  3022. foreach ($dirs as $dir) {
  3023. $targetPath = $this->joinPathCE($base, $dir);
  3024. if (!$_realpath = $this->realpath($this->encode($targetPath))) {
  3025. if ($stat = $this->mkdir($targetHash, $dir)) {
  3026. $result['added'][] = $stat;
  3027. $targetHash = $stat['hash'];
  3028. $base = $this->decode($targetHash);
  3029. } else {
  3030. return false;
  3031. }
  3032. } else {
  3033. $targetHash = $this->encode($_realpath);
  3034. if ($this->dir($targetHash)) {
  3035. $base = $this->decode($targetHash);
  3036. } else {
  3037. return false;
  3038. }
  3039. }
  3040. }
  3041. return $targetHash;
  3042. }
  3043. /**
  3044. * Return this uploadMaxSize value
  3045. *
  3046. * @return integer
  3047. * @author Naoki Sawada
  3048. */
  3049. public function getUploadMaxSize()
  3050. {
  3051. return $this->uploadMaxSize;
  3052. }
  3053. public function setUploadOverwrite($var)
  3054. {
  3055. $this->uploadOverwrite = (bool)$var;
  3056. }
  3057. /**
  3058. * Image file utility
  3059. *
  3060. * @param string $mode 'resize', 'rotate', 'propresize', 'crop', 'fitsquare'
  3061. * @param string $src Image file local path
  3062. * @param array $options excute options
  3063. *
  3064. * @return bool
  3065. * @throws ImagickException
  3066. * @throws elFinderAbortException
  3067. * @author Naoki Sawada
  3068. */
  3069. public function imageUtil($mode, $src, $options = array())
  3070. {
  3071. if (!isset($options['jpgQuality'])) {
  3072. $options['jpgQuality'] = intval($this->options['jpgQuality']);
  3073. }
  3074. if (!isset($options['bgcolor'])) {
  3075. $options['bgcolor'] = '#ffffff';
  3076. }
  3077. if (!isset($options['bgColorFb'])) {
  3078. $options['bgColorFb'] = $this->options['bgColorFb'];
  3079. }
  3080. // check 'width' ,'height'
  3081. if (in_array($mode, array('resize', 'propresize', 'crop', 'fitsquare'))) {
  3082. if (empty($options['width']) || empty($options['height'])) {
  3083. return false;
  3084. }
  3085. }
  3086. if (!empty($options['checkAnimated'])) {
  3087. if ($this->imgLib !== 'imagick' && $this->imgLib !== 'convert') {
  3088. if (elFinder::isAnimationGif($src)) {
  3089. return false;
  3090. }
  3091. }
  3092. if (elFinder::isAnimationPng($src)) {
  3093. return false;
  3094. }
  3095. }
  3096. switch ($mode) {
  3097. case 'rotate':
  3098. if (empty($options['degree'])) {
  3099. return true;
  3100. }
  3101. return (bool)$this->imgRotate($src, $options['degree'], $options['bgColorFb'], null, $options['jpgQuality']);
  3102. case 'resize':
  3103. return (bool)$this->imgResize($src, $options['width'], $options['height'], false, true, null, $options['jpgQuality'], $options);
  3104. case 'propresize':
  3105. return (bool)$this->imgResize($src, $options['width'], $options['height'], true, true, null, $options['jpgQuality'], $options);
  3106. case 'crop':
  3107. if (isset($options['x']) && isset($options['y'])) {
  3108. return (bool)$this->imgCrop($src, $options['width'], $options['height'], $options['x'], $options['y'], null, $options['jpgQuality']);
  3109. }
  3110. break;
  3111. case 'fitsquare':
  3112. return (bool)$this->imgSquareFit($src, $options['width'], $options['height'], 'center', 'middle', $options['bgcolor'], null, $options['jpgQuality']);
  3113. }
  3114. return false;
  3115. }
  3116. /**
  3117. * Convert Video To Image by ffmpeg
  3118. *
  3119. * @param string $file video source file path
  3120. * @param array $stat file stat array
  3121. * @param object $self volume driver object
  3122. * @param int $ss start seconds
  3123. *
  3124. * @return bool
  3125. * @throws elFinderAbortException
  3126. * @author Naoki Sawada
  3127. */
  3128. public function ffmpegToImg($file, $stat, $self, $ss = null)
  3129. {
  3130. $name = basename($file);
  3131. $path = dirname($file);
  3132. $tmp = $path . DIRECTORY_SEPARATOR . md5($name);
  3133. // register auto delete on shutdown
  3134. $GLOBALS['elFinderTempFiles'][$tmp] = true;
  3135. if (rename($file, $tmp)) {
  3136. if ($ss === null) {
  3137. // specific start time by file name (xxx^[sec].[extention] - video^3.mp4)
  3138. if (preg_match('/\^(\d+(?:\.\d+)?)\.[^.]+$/', $stat['name'], $_m)) {
  3139. $ss = $_m[1];
  3140. } else {
  3141. $ss = $this->options['tmbVideoConvSec'];
  3142. }
  3143. }
  3144. $cmd = sprintf(ELFINDER_FFMPEG_PATH . ' -i %s -ss 00:00:%.3f -vframes 1 -f image2 -- %s', escapeshellarg($tmp), $ss, escapeshellarg($file));
  3145. $r = ($this->procExec($cmd) === 0);
  3146. clearstatcache();
  3147. if ($r && $ss > 0 && !file_exists($file)) {
  3148. // Retry by half of $ss
  3149. $ss = max(intval($ss / 2), 0);
  3150. rename($tmp, $file);
  3151. $r = $this->ffmpegToImg($file, $stat, $self, $ss);
  3152. } else {
  3153. unlink($tmp);
  3154. }
  3155. return $r;
  3156. }
  3157. return false;
  3158. }
  3159. /**
  3160. * Creates a temporary file and return file pointer
  3161. *
  3162. * @return resource|boolean
  3163. */
  3164. public function tmpfile()
  3165. {
  3166. if ($tmp = $this->getTempFile()) {
  3167. return fopen($tmp, 'wb');
  3168. }
  3169. return false;
  3170. }
  3171. /**
  3172. * Save error message
  3173. *
  3174. * @param array error
  3175. *
  3176. * @return boolean false
  3177. * @author Naoki Sawada
  3178. **/
  3179. protected function setError()
  3180. {
  3181. $this->error = array();
  3182. $this->addError(func_get_args());
  3183. return false;
  3184. }
  3185. /**
  3186. * Add error message
  3187. *
  3188. * @param array error
  3189. *
  3190. * @return false
  3191. * @author Dmitry(dio) Levashov
  3192. **/
  3193. protected function addError()
  3194. {
  3195. foreach (func_get_args() as $err) {
  3196. if (is_array($err)) {
  3197. $this->error = array_merge($this->error, $err);
  3198. } else {
  3199. $this->error[] = $err;
  3200. }
  3201. }
  3202. return false;
  3203. }
  3204. /*********************************************************************/
  3205. /* FS API */
  3206. /*********************************************************************/
  3207. /***************** server encoding support *******************/
  3208. /**
  3209. * Return parent directory path (with convert encoding)
  3210. *
  3211. * @param string $path file path
  3212. *
  3213. * @return string
  3214. * @author Naoki Sawada
  3215. **/
  3216. protected function dirnameCE($path)
  3217. {
  3218. $dirname = (!$this->encoding) ? $this->_dirname($path) : $this->convEncOut($this->_dirname($this->convEncIn($path)));
  3219. // check to infinite loop prevention
  3220. return ($dirname != $path) ? $dirname : '';
  3221. }
  3222. /**
  3223. * Return file name (with convert encoding)
  3224. *
  3225. * @param string $path file path
  3226. *
  3227. * @return string
  3228. * @author Naoki Sawada
  3229. **/
  3230. protected function basenameCE($path)
  3231. {
  3232. return (!$this->encoding) ? $this->_basename($path) : $this->convEncOut($this->_basename($this->convEncIn($path)));
  3233. }
  3234. /**
  3235. * Join dir name and file name and return full path. (with convert encoding)
  3236. * Some drivers (db) use int as path - so we give to concat path to driver itself
  3237. *
  3238. * @param string $dir dir path
  3239. * @param string $name file name
  3240. *
  3241. * @return string
  3242. * @author Naoki Sawada
  3243. **/
  3244. protected function joinPathCE($dir, $name)
  3245. {
  3246. return (!$this->encoding) ? $this->_joinPath($dir, $name) : $this->convEncOut($this->_joinPath($this->convEncIn($dir), $this->convEncIn($name)));
  3247. }
  3248. /**
  3249. * Return normalized path (with convert encoding)
  3250. *
  3251. * @param string $path file path
  3252. *
  3253. * @return string
  3254. * @author Naoki Sawada
  3255. **/
  3256. protected function normpathCE($path)
  3257. {
  3258. return (!$this->encoding) ? $this->_normpath($path) : $this->convEncOut($this->_normpath($this->convEncIn($path)));
  3259. }
  3260. /**
  3261. * Return file path related to root dir (with convert encoding)
  3262. *
  3263. * @param string $path file path
  3264. *
  3265. * @return string
  3266. * @author Naoki Sawada
  3267. **/
  3268. protected function relpathCE($path)
  3269. {
  3270. return (!$this->encoding) ? $this->_relpath($path) : $this->convEncOut($this->_relpath($this->convEncIn($path)));
  3271. }
  3272. /**
  3273. * Convert path related to root dir into real path (with convert encoding)
  3274. *
  3275. * @param string $path rel file path
  3276. *
  3277. * @return string
  3278. * @author Naoki Sawada
  3279. **/
  3280. protected function abspathCE($path)
  3281. {
  3282. return (!$this->encoding) ? $this->_abspath($path) : $this->convEncOut($this->_abspath($this->convEncIn($path)));
  3283. }
  3284. /**
  3285. * Return true if $path is children of $parent (with convert encoding)
  3286. *
  3287. * @param string $path path to check
  3288. * @param string $parent parent path
  3289. *
  3290. * @return bool
  3291. * @author Naoki Sawada
  3292. **/
  3293. protected function inpathCE($path, $parent)
  3294. {
  3295. return (!$this->encoding) ? $this->_inpath($path, $parent) : $this->convEncOut($this->_inpath($this->convEncIn($path), $this->convEncIn($parent)));
  3296. }
  3297. /**
  3298. * Open file and return file pointer (with convert encoding)
  3299. *
  3300. * @param string $path file path
  3301. * @param string $mode
  3302. *
  3303. * @return false|resource
  3304. * @internal param bool $write open file for writing
  3305. * @author Naoki Sawada
  3306. */
  3307. protected function fopenCE($path, $mode = 'rb')
  3308. {
  3309. return (!$this->encoding) ? $this->_fopen($path, $mode) : $this->convEncOut($this->_fopen($this->convEncIn($path), $mode));
  3310. }
  3311. /**
  3312. * Close opened file (with convert encoding)
  3313. *
  3314. * @param resource $fp file pointer
  3315. * @param string $path file path
  3316. *
  3317. * @return bool
  3318. * @author Naoki Sawada
  3319. **/
  3320. protected function fcloseCE($fp, $path = '')
  3321. {
  3322. return (!$this->encoding) ? $this->_fclose($fp, $path) : $this->convEncOut($this->_fclose($fp, $this->convEncIn($path)));
  3323. }
  3324. /**
  3325. * Create new file and write into it from file pointer. (with convert encoding)
  3326. * Return new file path or false on error.
  3327. *
  3328. * @param resource $fp file pointer
  3329. * @param string $dir target dir path
  3330. * @param string $name file name
  3331. * @param array $stat file stat (required by some virtual fs)
  3332. *
  3333. * @return bool|string
  3334. * @author Naoki Sawada
  3335. **/
  3336. protected function saveCE($fp, $dir, $name, $stat)
  3337. {
  3338. $res = (!$this->encoding) ? $this->_save($fp, $dir, $name, $stat) : $this->convEncOut($this->_save($fp, $this->convEncIn($dir), $this->convEncIn($name), $this->convEncIn($stat)));
  3339. if ($res !== false) {
  3340. $this->clearstatcache();
  3341. }
  3342. return $res;
  3343. }
  3344. /**
  3345. * Return true if path is dir and has at least one childs directory (with convert encoding)
  3346. *
  3347. * @param string $path dir path
  3348. *
  3349. * @return bool
  3350. * @author Naoki Sawada
  3351. **/
  3352. protected function subdirsCE($path)
  3353. {
  3354. if ($this->sessionCaching['subdirs']) {
  3355. if (isset($this->sessionCache['subdirs'][$path]) && !$this->isMyReload()) {
  3356. return $this->sessionCache['subdirs'][$path];
  3357. }
  3358. }
  3359. $hasdir = (bool)((!$this->encoding) ? $this->_subdirs($path) : $this->convEncOut($this->_subdirs($this->convEncIn($path))));
  3360. $this->updateSubdirsCache($path, $hasdir);
  3361. return $hasdir;
  3362. }
  3363. /**
  3364. * Return files list in directory (with convert encoding)
  3365. *
  3366. * @param string $path dir path
  3367. *
  3368. * @return array
  3369. * @author Naoki Sawada
  3370. **/
  3371. protected function scandirCE($path)
  3372. {
  3373. return (!$this->encoding) ? $this->_scandir($path) : $this->convEncOut($this->_scandir($this->convEncIn($path)));
  3374. }
  3375. /**
  3376. * Create symlink (with convert encoding)
  3377. *
  3378. * @param string $source file to link to
  3379. * @param string $targetDir folder to create link in
  3380. * @param string $name symlink name
  3381. *
  3382. * @return bool
  3383. * @author Naoki Sawada
  3384. **/
  3385. protected function symlinkCE($source, $targetDir, $name)
  3386. {
  3387. return (!$this->encoding) ? $this->_symlink($source, $targetDir, $name) : $this->convEncOut($this->_symlink($this->convEncIn($source), $this->convEncIn($targetDir), $this->convEncIn($name)));
  3388. }
  3389. /***************** paths *******************/
  3390. /**
  3391. * Encode path into hash
  3392. *
  3393. * @param string file path
  3394. *
  3395. * @return string
  3396. * @author Dmitry (dio) Levashov
  3397. * @author Troex Nevelin
  3398. **/
  3399. protected function encode($path)
  3400. {
  3401. if ($path !== '') {
  3402. // cut ROOT from $path for security reason, even if hacker decodes the path he will not know the root
  3403. $p = $this->relpathCE($path);
  3404. // if reqesting root dir $path will be empty, then assign '/' as we cannot leave it blank for crypt
  3405. if ($p === '') {
  3406. $p = $this->separator;
  3407. }
  3408. // change separator
  3409. if ($this->separatorForHash) {
  3410. $p = str_replace($this->separator, $this->separatorForHash, $p);
  3411. }
  3412. // TODO crypt path and return hash
  3413. $hash = $this->crypt($p);
  3414. // hash is used as id in HTML that means it must contain vaild chars
  3415. // make base64 html safe and append prefix in begining
  3416. $hash = strtr(base64_encode($hash), '+/=', '-_.');
  3417. // remove dots '.' at the end, before it was '=' in base64
  3418. $hash = rtrim($hash, '.');
  3419. // append volume id to make hash unique
  3420. return $this->id . $hash;
  3421. }
  3422. //TODO: Add return statement here
  3423. }
  3424. /**
  3425. * Decode path from hash
  3426. *
  3427. * @param string file hash
  3428. *
  3429. * @return string
  3430. * @author Dmitry (dio) Levashov
  3431. * @author Troex Nevelin
  3432. **/
  3433. protected function decode($hash)
  3434. {
  3435. if (strpos($hash, $this->id) === 0) {
  3436. // cut volume id after it was prepended in encode
  3437. $h = substr($hash, strlen($this->id));
  3438. // replace HTML safe base64 to normal
  3439. $h = base64_decode(strtr($h, '-_.', '+/='));
  3440. // TODO uncrypt hash and return path
  3441. $path = $this->uncrypt($h);
  3442. // change separator
  3443. if ($this->separatorForHash) {
  3444. $path = str_replace($this->separatorForHash, $this->separator, $path);
  3445. }
  3446. // append ROOT to path after it was cut in encode
  3447. return $this->abspathCE($path);//$this->root.($path === $this->separator ? '' : $this->separator.$path);
  3448. }
  3449. return '';
  3450. }
  3451. /**
  3452. * Return crypted path
  3453. * Not implemented
  3454. *
  3455. * @param string path
  3456. *
  3457. * @return mixed
  3458. * @author Dmitry (dio) Levashov
  3459. **/
  3460. protected function crypt($path)
  3461. {
  3462. return $path;
  3463. }
  3464. /**
  3465. * Return uncrypted path
  3466. * Not implemented
  3467. *
  3468. * @param mixed hash
  3469. *
  3470. * @return mixed
  3471. * @author Dmitry (dio) Levashov
  3472. **/
  3473. protected function uncrypt($hash)
  3474. {
  3475. return $hash;
  3476. }
  3477. /**
  3478. * Validate file name based on $this->options['acceptedName'] regexp or function
  3479. *
  3480. * @param string $name file name
  3481. * @param bool $isDir
  3482. *
  3483. * @return bool
  3484. * @author Dmitry (dio) Levashov
  3485. */
  3486. protected function nameAccepted($name, $isDir = false)
  3487. {
  3488. if (json_encode($name) === false) {
  3489. return false;
  3490. }
  3491. $nameValidator = $isDir ? $this->dirnameValidator : $this->nameValidator;
  3492. if ($nameValidator) {
  3493. if (is_callable($nameValidator)) {
  3494. $res = call_user_func($nameValidator, $name);
  3495. return $res;
  3496. }
  3497. if (preg_match($nameValidator, '') !== false) {
  3498. return preg_match($nameValidator, $name);
  3499. }
  3500. }
  3501. return true;
  3502. }
  3503. /**
  3504. * Return session rootstat cache key
  3505. *
  3506. * @return string
  3507. */
  3508. protected function getRootstatCachekey()
  3509. {
  3510. return md5($this->root . (isset($this->options['alias']) ? $this->options['alias'] : ''));
  3511. }
  3512. /**
  3513. * Return new unique name based on file name and suffix
  3514. *
  3515. * @param $dir
  3516. * @param $name
  3517. * @param string $suffix suffix append to name
  3518. * @param bool $checkNum
  3519. * @param int $start
  3520. *
  3521. * @return string
  3522. * @internal param string $path file path
  3523. * @author Dmitry (dio) Levashov
  3524. */
  3525. public function uniqueName($dir, $name, $suffix = ' copy', $checkNum = true, $start = 1)
  3526. {
  3527. static $lasts = null;
  3528. if ($lasts === null) {
  3529. $lasts = array();
  3530. }
  3531. $ext = '';
  3532. $splits = elFinder::splitFileExtention($name);
  3533. if ($splits[1]) {
  3534. $ext = '.' . $splits[1];
  3535. $name = $splits[0];
  3536. }
  3537. if ($checkNum && preg_match('/(' . preg_quote($suffix, '/') . ')(\d*)$/i', $name, $m)) {
  3538. $i = (int)$m[2];
  3539. $name = substr($name, 0, strlen($name) - strlen($m[2]));
  3540. } else {
  3541. $i = $start;
  3542. $name .= $suffix;
  3543. }
  3544. $max = $i + 100000;
  3545. if (isset($lasts[$name])) {
  3546. $i = max($i, $lasts[$name]);
  3547. }
  3548. while ($i <= $max) {
  3549. $n = $name . ($i > 0 ? sprintf($this->options['uniqueNumFormat'], $i) : '') . $ext;
  3550. if (!$this->isNameExists($this->joinPathCE($dir, $n))) {
  3551. $this->clearcache();
  3552. $lasts[$name] = ++$i;
  3553. return $n;
  3554. }
  3555. $i++;
  3556. }
  3557. return $name . md5($dir) . $ext;
  3558. }
  3559. /**
  3560. * Converts character encoding from UTF-8 to server's one
  3561. *
  3562. * @param mixed $var target string or array var
  3563. * @param bool $restoreLocale do retore global locale, default is false
  3564. * @param string $unknown replaces character for unknown
  3565. *
  3566. * @return mixed
  3567. * @author Naoki Sawada
  3568. */
  3569. public function convEncIn($var = null, $restoreLocale = false, $unknown = '_')
  3570. {
  3571. return (!$this->encoding) ? $var : $this->convEnc($var, 'UTF-8', $this->encoding, $this->options['locale'], $restoreLocale, $unknown);
  3572. }
  3573. /**
  3574. * Converts character encoding from server's one to UTF-8
  3575. *
  3576. * @param mixed $var target string or array var
  3577. * @param bool $restoreLocale do retore global locale, default is true
  3578. * @param string $unknown replaces character for unknown
  3579. *
  3580. * @return mixed
  3581. * @author Naoki Sawada
  3582. */
  3583. public function convEncOut($var = null, $restoreLocale = true, $unknown = '_')
  3584. {
  3585. return (!$this->encoding) ? $var : $this->convEnc($var, $this->encoding, 'UTF-8', $this->options['locale'], $restoreLocale, $unknown);
  3586. }
  3587. /**
  3588. * Converts character encoding (base function)
  3589. *
  3590. * @param mixed $var target string or array var
  3591. * @param string $from from character encoding
  3592. * @param string $to to character encoding
  3593. * @param string $locale local locale
  3594. * @param $restoreLocale
  3595. * @param string $unknown replaces character for unknown
  3596. *
  3597. * @return mixed
  3598. */
  3599. protected function convEnc($var, $from, $to, $locale, $restoreLocale, $unknown = '_')
  3600. {
  3601. if (strtoupper($from) !== strtoupper($to)) {
  3602. if ($locale) {
  3603. setlocale(LC_ALL, $locale);
  3604. }
  3605. if (is_array($var)) {
  3606. $_ret = array();
  3607. foreach ($var as $_k => $_v) {
  3608. $_ret[$_k] = $this->convEnc($_v, $from, $to, '', false, $unknown = '_');
  3609. }
  3610. $var = $_ret;
  3611. } else {
  3612. $_var = false;
  3613. if (is_string($var)) {
  3614. $_var = $var;
  3615. if (false !== ($_var = iconv($from, $to . '//TRANSLIT', $_var))) {
  3616. $_var = str_replace('?', $unknown, $_var);
  3617. }
  3618. }
  3619. if ($_var !== false) {
  3620. $var = $_var;
  3621. }
  3622. }
  3623. if ($restoreLocale) {
  3624. setlocale(LC_ALL, elFinder::$locale);
  3625. }
  3626. }
  3627. return $var;
  3628. }
  3629. /**
  3630. * Normalize MIME-Type by options['mimeMap']
  3631. *
  3632. * @param string $type MIME-Type
  3633. * @param string $name Filename
  3634. * @param string $ext File extention without first dot (optional)
  3635. *
  3636. * @return string Normalized MIME-Type
  3637. */
  3638. public function mimeTypeNormalize($type, $name, $ext = '')
  3639. {
  3640. if ($ext === '') {
  3641. $ext = (false === $pos = strrpos($name, '.')) ? '' : substr($name, $pos + 1);
  3642. }
  3643. $_checkKey = strtolower($ext . ':' . $type);
  3644. if ($type === '') {
  3645. $_keylen = strlen($_checkKey);
  3646. foreach ($this->options['mimeMap'] as $_key => $_type) {
  3647. if (substr($_key, 0, $_keylen) === $_checkKey) {
  3648. $type = $_type;
  3649. break;
  3650. }
  3651. }
  3652. } else if (isset($this->options['mimeMap'][$_checkKey])) {
  3653. $type = $this->options['mimeMap'][$_checkKey];
  3654. } else {
  3655. $_checkKey = strtolower($ext . ':*');
  3656. if (isset($this->options['mimeMap'][$_checkKey])) {
  3657. $type = $this->options['mimeMap'][$_checkKey];
  3658. } else {
  3659. $_checkKey = strtolower('*:' . $type);
  3660. if (isset($this->options['mimeMap'][$_checkKey])) {
  3661. $type = $this->options['mimeMap'][$_checkKey];
  3662. }
  3663. }
  3664. }
  3665. return $type;
  3666. }
  3667. /*********************** util mainly for inheritance class *********************/
  3668. /**
  3669. * Get temporary filename. Tempfile will be removed when after script execution finishes or exit() is called.
  3670. * When needing the unique file to a path, give $path to parameter.
  3671. *
  3672. * @param string $path for get unique file to a path
  3673. *
  3674. * @return string|false
  3675. * @author Naoki Sawada
  3676. */
  3677. protected function getTempFile($path = '')
  3678. {
  3679. static $cache = array();
  3680. $key = '';
  3681. if ($path !== '') {
  3682. $key = $this->id . '#' . $path;
  3683. if (isset($cache[$key])) {
  3684. return $cache[$key];
  3685. }
  3686. }
  3687. if ($tmpdir = $this->getTempPath()) {
  3688. $name = tempnam($tmpdir, 'ELF');
  3689. if ($key) {
  3690. $cache[$key] = $name;
  3691. }
  3692. // register auto delete on shutdown
  3693. $GLOBALS['elFinderTempFiles'][$name] = true;
  3694. return $name;
  3695. }
  3696. return false;
  3697. }
  3698. /**
  3699. * File path of local server side work file path
  3700. *
  3701. * @param string $path path need convert encoding to server encoding
  3702. *
  3703. * @return string
  3704. * @author Naoki Sawada
  3705. */
  3706. protected function getWorkFile($path)
  3707. {
  3708. if ($wfp = $this->tmpfile()) {
  3709. if ($fp = $this->_fopen($path)) {
  3710. while (!feof($fp)) {
  3711. fwrite($wfp, fread($fp, 8192));
  3712. }
  3713. $info = stream_get_meta_data($wfp);
  3714. fclose($wfp);
  3715. if ($info && !empty($info['uri'])) {
  3716. return $info['uri'];
  3717. }
  3718. }
  3719. }
  3720. return false;
  3721. }
  3722. /**
  3723. * Get image size array with `dimensions`
  3724. *
  3725. * @param string $path path need convert encoding to server encoding
  3726. * @param string $mime file mime type
  3727. *
  3728. * @return array|false
  3729. * @throws ImagickException
  3730. * @throws elFinderAbortException
  3731. */
  3732. public function getImageSize($path, $mime = '')
  3733. {
  3734. $size = false;
  3735. if ($mime === '' || strtolower(substr($mime, 0, 5)) === 'image') {
  3736. if ($work = $this->getWorkFile($path)) {
  3737. if ($size = getimagesize($work)) {
  3738. $size['dimensions'] = $size[0] . 'x' . $size[1];
  3739. $srcfp = fopen($work, 'rb');
  3740. $cArgs = elFinder::$currentArgs;
  3741. if (!empty($cArgs['target']) && $subImgLink = $this->getSubstituteImgLink($cArgs['target'], $size, $srcfp)) {
  3742. $size['url'] = $subImgLink;
  3743. }
  3744. }
  3745. }
  3746. is_file($work) && unlink($work);
  3747. }
  3748. return $size;
  3749. }
  3750. /**
  3751. * Delete dirctory trees
  3752. *
  3753. * @param string $localpath path need convert encoding to server encoding
  3754. *
  3755. * @return boolean
  3756. * @throws elFinderAbortException
  3757. * @author Naoki Sawada
  3758. */
  3759. protected function delTree($localpath)
  3760. {
  3761. foreach ($this->_scandir($localpath) as $p) {
  3762. elFinder::checkAborted();
  3763. $stat = $this->stat($this->convEncOut($p));
  3764. $this->convEncIn();
  3765. ($stat['mime'] === 'directory') ? $this->delTree($p) : $this->_unlink($p);
  3766. }
  3767. $res = $this->_rmdir($localpath);
  3768. $res && $this->clearstatcache();
  3769. return $res;
  3770. }
  3771. /**
  3772. * Copy items to a new temporary directory on the local server
  3773. *
  3774. * @param array $hashes target hashes
  3775. * @param string $dir destination directory (for recurcive)
  3776. * @param string $canLink it can use link() (for recurcive)
  3777. *
  3778. * @return string|false saved path name
  3779. * @throws elFinderAbortException
  3780. * @author Naoki Sawada
  3781. */
  3782. protected function getItemsInHand($hashes, $dir = null, $canLink = null)
  3783. {
  3784. static $totalSize = 0;
  3785. if (is_null($dir)) {
  3786. $totalSize = 0;
  3787. if (!$tmpDir = $this->getTempPath()) {
  3788. return false;
  3789. }
  3790. $dir = tempnam($tmpDir, 'elf');
  3791. if (!unlink($dir) || !mkdir($dir, 0700, true)) {
  3792. return false;
  3793. }
  3794. register_shutdown_function(array($this, 'rmdirRecursive'), $dir);
  3795. }
  3796. if (is_null($canLink)) {
  3797. $canLink = ($this instanceof elFinderVolumeLocalFileSystem);
  3798. }
  3799. elFinder::checkAborted();
  3800. $res = true;
  3801. $files = array();
  3802. foreach ($hashes as $hash) {
  3803. if (($file = $this->file($hash)) == false) {
  3804. continue;
  3805. }
  3806. if (!$file['read']) {
  3807. continue;
  3808. }
  3809. $name = $file['name'];
  3810. // for call from search results
  3811. if (isset($files[$name])) {
  3812. $name = preg_replace('/^(.*?)(\..*)?$/', '$1_' . $files[$name]++ . '$2', $name);
  3813. } else {
  3814. $files[$name] = 1;
  3815. }
  3816. $target = $dir . DIRECTORY_SEPARATOR . $name;
  3817. if ($file['mime'] === 'directory') {
  3818. $chashes = array();
  3819. $_files = $this->scandir($hash);
  3820. foreach ($_files as $_file) {
  3821. if ($file['read']) {
  3822. $chashes[] = $_file['hash'];
  3823. }
  3824. }
  3825. if (($res = mkdir($target, 0700, true)) && $chashes) {
  3826. $res = $this->getItemsInHand($chashes, $target, $canLink);
  3827. }
  3828. if (!$res) {
  3829. break;
  3830. }
  3831. !empty($file['ts']) && touch($target, $file['ts']);
  3832. } else {
  3833. $path = $this->decode($hash);
  3834. if (!$canLink || !($canLink = link($path, $target))) {
  3835. if ($fp = $this->fopenCE($path)) {
  3836. if ($tfp = fopen($target, 'wb')) {
  3837. $totalSize += stream_copy_to_stream($fp, $tfp);
  3838. fclose($tfp);
  3839. }
  3840. !empty($file['ts']) && touch($target, $file['ts']);
  3841. $this->fcloseCE($fp, $path);
  3842. }
  3843. } else {
  3844. $totalSize += filesize($path);
  3845. }
  3846. if ($this->options['maxArcFilesSize'] > 0 && $this->options['maxArcFilesSize'] < $totalSize) {
  3847. $res = $this->setError(elFinder::ERROR_ARC_MAXSIZE);
  3848. }
  3849. }
  3850. }
  3851. return $res ? $dir : false;
  3852. }
  3853. /*********************** file stat *********************/
  3854. /**
  3855. * Check file attribute
  3856. *
  3857. * @param string $path file path
  3858. * @param string $name attribute name (read|write|locked|hidden)
  3859. * @param bool $val attribute value returned by file system
  3860. * @param bool $isDir path is directory (true: directory, false: file)
  3861. *
  3862. * @return bool
  3863. * @author Dmitry (dio) Levashov
  3864. **/
  3865. protected function attr($path, $name, $val = null, $isDir = null)
  3866. {
  3867. if (!isset($this->defaults[$name])) {
  3868. return false;
  3869. }
  3870. $relpath = $this->relpathCE($path);
  3871. if ($this->separator !== '/') {
  3872. $relpath = str_replace($this->separator, '/', $relpath);
  3873. }
  3874. $relpath = '/' . $relpath;
  3875. $perm = null;
  3876. if ($this->access) {
  3877. $perm = call_user_func($this->access, $name, $path, $this->options['accessControlData'], $this, $isDir, $relpath);
  3878. if ($perm !== null) {
  3879. return !!$perm;
  3880. }
  3881. }
  3882. foreach ($this->attributes as $attrs) {
  3883. if (isset($attrs[$name]) && isset($attrs['pattern']) && preg_match($attrs['pattern'], $relpath)) {
  3884. $perm = $attrs[$name];
  3885. break;
  3886. }
  3887. }
  3888. return $perm === null ? (is_null($val) ? $this->defaults[$name] : $val) : !!$perm;
  3889. }
  3890. /**
  3891. * Return true if file with given name can be created in given folder.
  3892. *
  3893. * @param string $dir parent dir path
  3894. * @param string $name new file name
  3895. * @param null $isDir
  3896. *
  3897. * @return bool
  3898. * @author Dmitry (dio) Levashov
  3899. */
  3900. protected function allowCreate($dir, $name, $isDir = null)
  3901. {
  3902. return $this->attr($this->joinPathCE($dir, $name), 'write', true, $isDir);
  3903. }
  3904. /**
  3905. * Return true if file MIME type can save with check uploadOrder config.
  3906. *
  3907. * @param string $mime
  3908. *
  3909. * @return boolean
  3910. */
  3911. protected function allowPutMime($mime)
  3912. {
  3913. // logic based on http://httpd.apache.org/docs/2.2/mod/mod_authz_host.html#order
  3914. $allow = $this->mimeAccepted($mime, $this->uploadAllow, null);
  3915. $deny = $this->mimeAccepted($mime, $this->uploadDeny, null);
  3916. if (strtolower($this->uploadOrder[0]) == 'allow') { // array('allow', 'deny'), default is to 'deny'
  3917. $res = false; // default is deny
  3918. if (!$deny && ($allow === true)) { // match only allow
  3919. $res = true;
  3920. }// else (both match | no match | match only deny) { deny }
  3921. } else { // array('deny', 'allow'), default is to 'allow' - this is the default rule
  3922. $res = true; // default is allow
  3923. if (($deny === true) && !$allow) { // match only deny
  3924. $res = false;
  3925. } // else (both match | no match | match only allow) { allow }
  3926. }
  3927. return $res;
  3928. }
  3929. /**
  3930. * Return fileinfo
  3931. *
  3932. * @param string $path file cache
  3933. *
  3934. * @return array|bool
  3935. * @author Dmitry (dio) Levashov
  3936. **/
  3937. protected function stat($path)
  3938. {
  3939. if ($path === false || is_null($path)) {
  3940. return false;
  3941. }
  3942. $is_root = ($path == $this->root);
  3943. if ($is_root) {
  3944. $rootKey = $this->getRootstatCachekey();
  3945. if ($this->sessionCaching['rootstat'] && !isset($this->sessionCache['rootstat'])) {
  3946. $this->sessionCache['rootstat'] = array();
  3947. }
  3948. if (!isset($this->cache[$path]) && !$this->isMyReload()) {
  3949. // need $path as key for netmount/netunmount
  3950. if ($this->sessionCaching['rootstat'] && isset($this->sessionCache['rootstat'][$rootKey])) {
  3951. if ($ret = $this->sessionCache['rootstat'][$rootKey]) {
  3952. if ($this->options['rootRev'] === $ret['rootRev']) {
  3953. if (isset($this->options['phash'])) {
  3954. $ret['isroot'] = 1;
  3955. $ret['phash'] = $this->options['phash'];
  3956. }
  3957. return $ret;
  3958. }
  3959. }
  3960. }
  3961. }
  3962. }
  3963. $ret = isset($this->cache[$path])
  3964. ? $this->cache[$path]
  3965. : $this->updateCache($path, $this->convEncOut($this->_stat($this->convEncIn($path))));
  3966. if ($is_root && $this->sessionCaching['rootstat']) {
  3967. if ($ret) {
  3968. $this->rootModified = false;
  3969. if (!empty($rootKey)) {
  3970. $this->sessionCache['rootstat'][$rootKey] = $ret;
  3971. }
  3972. if (isset($this->options['phash'])) {
  3973. $ret['isroot'] = 1;
  3974. $ret['phash'] = $this->options['phash'];
  3975. }
  3976. } else if (!empty($rootKey)) {
  3977. unset($this->sessionCache['rootstat'][$rootKey]);
  3978. }
  3979. }
  3980. return $ret;
  3981. }
  3982. /**
  3983. * Get root stat extra key values
  3984. *
  3985. * @return array stat extras
  3986. * @author Naoki Sawada
  3987. */
  3988. protected function getRootStatExtra()
  3989. {
  3990. $stat = array();
  3991. if ($this->rootName) {
  3992. $stat['name'] = $this->rootName;
  3993. }
  3994. $stat['rootRev'] = $this->options['rootRev'];
  3995. $stat['options'] = $this->options(null);
  3996. return $stat;
  3997. }
  3998. /**
  3999. * Return fileinfo based on filename
  4000. * For item ID based path file system
  4001. * Please override if needed on each drivers
  4002. *
  4003. * @param string $path file cache
  4004. *
  4005. * @return array
  4006. */
  4007. protected function isNameExists($path)
  4008. {
  4009. return $this->stat($path);
  4010. }
  4011. /**
  4012. * Put file stat in cache and return it
  4013. *
  4014. * @param string $path file path
  4015. * @param array $stat file stat
  4016. *
  4017. * @return array
  4018. * @author Dmitry (dio) Levashov
  4019. **/
  4020. protected function updateCache($path, $stat)
  4021. {
  4022. if (empty($stat) || !is_array($stat)) {
  4023. return $this->cache[$path] = array();
  4024. }
  4025. $stat['hash'] = $this->encode($path);
  4026. $root = $path == $this->root;
  4027. $parent = '';
  4028. if ($root) {
  4029. $stat = array_merge($stat, $this->getRootStatExtra());
  4030. } else {
  4031. if (!isset($stat['name']) || $stat['name'] === '') {
  4032. $stat['name'] = $this->basenameCE($path);
  4033. }
  4034. if (empty($stat['phash'])) {
  4035. $parent = $this->dirnameCE($path);
  4036. $stat['phash'] = $this->encode($parent);
  4037. } else {
  4038. $parent = $this->decode($stat['phash']);
  4039. }
  4040. }
  4041. // name check
  4042. if (!$jeName = json_encode($stat['name'])) {
  4043. return $this->cache[$path] = array();
  4044. }
  4045. // fix name if required
  4046. if ($this->options['utf8fix'] && $this->options['utf8patterns'] && $this->options['utf8replace']) {
  4047. $stat['name'] = json_decode(str_replace($this->options['utf8patterns'], $this->options['utf8replace'], $jeName));
  4048. }
  4049. if (!isset($stat['size'])) {
  4050. $stat['size'] = 'unknown';
  4051. }
  4052. $mime = isset($stat['mime']) ? $stat['mime'] : '';
  4053. if ($isDir = ($mime === 'directory')) {
  4054. $stat['volumeid'] = $this->id;
  4055. } else {
  4056. if (empty($stat['mime']) || $stat['size'] == 0) {
  4057. $stat['mime'] = $this->mimetype($stat['name'], true, $stat['size'], $mime);
  4058. } else {
  4059. $stat['mime'] = $this->mimeTypeNormalize($stat['mime'], $stat['name']);
  4060. }
  4061. }
  4062. $stat['read'] = intval($this->attr($path, 'read', isset($stat['read']) ? !!$stat['read'] : null, $isDir));
  4063. $stat['write'] = intval($this->attr($path, 'write', isset($stat['write']) ? !!$stat['write'] : null, $isDir));
  4064. if ($root) {
  4065. $stat['locked'] = 1;
  4066. if ($this->options['type'] !== '') {
  4067. $stat['type'] = $this->options['type'];
  4068. }
  4069. } else {
  4070. // lock when parent directory is not writable
  4071. if (!isset($stat['locked'])) {
  4072. $pstat = $this->stat($parent);
  4073. if (isset($pstat['write']) && !$pstat['write']) {
  4074. $stat['locked'] = true;
  4075. }
  4076. }
  4077. if ($this->attr($path, 'locked', isset($stat['locked']) ? !!$stat['locked'] : null, $isDir)) {
  4078. $stat['locked'] = 1;
  4079. } else {
  4080. unset($stat['locked']);
  4081. }
  4082. }
  4083. if ($root) {
  4084. unset($stat['hidden']);
  4085. } elseif ($this->attr($path, 'hidden', isset($stat['hidden']) ? !!$stat['hidden'] : null, $isDir)
  4086. || !$this->mimeAccepted($stat['mime'])) {
  4087. $stat['hidden'] = 1;
  4088. } else {
  4089. unset($stat['hidden']);
  4090. }
  4091. if ($stat['read'] && empty($stat['hidden'])) {
  4092. if ($isDir) {
  4093. // caching parent's subdirs
  4094. if ($parent) {
  4095. $this->updateSubdirsCache($parent, true);
  4096. }
  4097. // for dir - check for subdirs
  4098. if ($this->options['checkSubfolders']) {
  4099. if (!isset($stat['dirs']) && intval($this->options['checkSubfolders']) === -1) {
  4100. $stat['dirs'] = -1;
  4101. }
  4102. if (isset($stat['dirs'])) {
  4103. if ($stat['dirs']) {
  4104. if ($stat['dirs'] == -1) {
  4105. $stat['dirs'] = ($this->sessionCaching['subdirs'] && isset($this->sessionCache['subdirs'][$path])) ? (int)$this->sessionCache['subdirs'][$path] : -1;
  4106. } else {
  4107. $stat['dirs'] = 1;
  4108. }
  4109. } else {
  4110. unset($stat['dirs']);
  4111. }
  4112. } elseif (!empty($stat['alias']) && !empty($stat['target'])) {
  4113. $stat['dirs'] = isset($this->cache[$stat['target']])
  4114. ? intval(isset($this->cache[$stat['target']]['dirs']))
  4115. : $this->subdirsCE($stat['target']);
  4116. } elseif ($this->subdirsCE($path)) {
  4117. $stat['dirs'] = 1;
  4118. }
  4119. } else {
  4120. $stat['dirs'] = 1;
  4121. }
  4122. if ($this->options['dirUrlOwn'] === true) {
  4123. // Set `null` to use the client option `commandsOptions.info.nullUrlDirLinkSelf = true`
  4124. $stat['url'] = null;
  4125. } else if ($this->options['dirUrlOwn'] === 'hide') {
  4126. // to hide link in info dialog of the elFinder client
  4127. $stat['url'] = '';
  4128. }
  4129. } else {
  4130. // for files - check for thumbnails
  4131. $p = isset($stat['target']) ? $stat['target'] : $path;
  4132. if ($this->tmbURL && !isset($stat['tmb']) && $this->canCreateTmb($p, $stat)) {
  4133. $tmb = $this->gettmb($p, $stat);
  4134. $stat['tmb'] = $tmb ? $tmb : 1;
  4135. }
  4136. }
  4137. if (!isset($stat['url']) && $this->URL && $this->encoding) {
  4138. $_path = str_replace($this->separator, '/', substr($path, strlen($this->root) + 1));
  4139. $stat['url'] = rtrim($this->URL, '/') . '/' . str_replace('%2F', '/', rawurlencode((substr(PHP_OS, 0, 3) === 'WIN') ? $_path : $this->convEncIn($_path, true)));
  4140. }
  4141. } else {
  4142. if ($isDir) {
  4143. unset($stat['dirs']);
  4144. }
  4145. }
  4146. if (!empty($stat['alias']) && !empty($stat['target'])) {
  4147. $stat['thash'] = $this->encode($stat['target']);
  4148. //$this->cache[$stat['target']] = $stat;
  4149. unset($stat['target']);
  4150. }
  4151. $this->cache[$path] = $stat;
  4152. if ($root && $this->sessionCaching['rootstat']) {
  4153. // to update session cache
  4154. $this->stat($path);
  4155. }
  4156. return $stat;
  4157. }
  4158. /**
  4159. * Get stat for folder content and put in cache
  4160. *
  4161. * @param string $path
  4162. *
  4163. * @return void
  4164. * @author Dmitry (dio) Levashov
  4165. **/
  4166. protected function cacheDir($path)
  4167. {
  4168. $this->dirsCache[$path] = array();
  4169. $hasDir = false;
  4170. foreach ($this->scandirCE($path) as $p) {
  4171. if (($stat = $this->stat($p)) && empty($stat['hidden'])) {
  4172. if (!$hasDir && $stat['mime'] === 'directory') {
  4173. $hasDir = true;
  4174. }
  4175. $this->dirsCache[$path][] = $p;
  4176. }
  4177. }
  4178. $this->updateSubdirsCache($path, $hasDir);
  4179. }
  4180. /**
  4181. * Clean cache
  4182. *
  4183. * @return void
  4184. * @author Dmitry (dio) Levashov
  4185. **/
  4186. protected function clearcache()
  4187. {
  4188. $this->cache = $this->dirsCache = array();
  4189. }
  4190. /**
  4191. * Return file mimetype
  4192. *
  4193. * @param string $path file path
  4194. * @param string|bool $name
  4195. * @param integer $size
  4196. * @param string $mime was notified from the volume driver
  4197. *
  4198. * @return string
  4199. * @author Dmitry (dio) Levashov
  4200. */
  4201. protected function mimetype($path, $name = '', $size = null, $mime = null)
  4202. {
  4203. $type = '';
  4204. $nameCheck = false;
  4205. if ($name === '') {
  4206. $name = $path;
  4207. } else if ($name === true) {
  4208. $name = $path;
  4209. $nameCheck = true;
  4210. }
  4211. $ext = (false === $pos = strrpos($name, '.')) ? '' : substr($name, $pos + 1);
  4212. if ($size === null) {
  4213. $size = file_exists($path) ? filesize($path) : -1;
  4214. }
  4215. if (!$nameCheck && is_readable($path) && $size > 0) {
  4216. // detecting by contents
  4217. if ($this->mimeDetect === 'finfo') {
  4218. $type = finfo_file($this->finfo, $path);
  4219. } else if ($this->mimeDetect === 'mime_content_type') {
  4220. $type = mime_content_type($path);
  4221. }
  4222. if ($type) {
  4223. $type = explode(';', $type);
  4224. $type = trim($type[0]);
  4225. if ($ext && preg_match('~^application/(?:octet-stream|(?:x-)?zip|xml)$~', $type)) {
  4226. // load default MIME table file "mime.types"
  4227. if (!elFinderVolumeDriver::$mimetypesLoaded) {
  4228. elFinderVolumeDriver::loadMimeTypes();
  4229. }
  4230. if (isset(elFinderVolumeDriver::$mimetypes[$ext])) {
  4231. $type = elFinderVolumeDriver::$mimetypes[$ext];
  4232. }
  4233. } else if ($ext === 'js' && preg_match('~^text/~', $type)) {
  4234. $type = 'text/javascript';
  4235. }
  4236. }
  4237. }
  4238. if (!$type) {
  4239. // detecting by filename
  4240. $type = elFinderVolumeDriver::mimetypeInternalDetect($name);
  4241. if ($type === 'unknown') {
  4242. if ($mime) {
  4243. $type = $mime;
  4244. } else {
  4245. $type = ($size == 0) ? 'text/plain' : $this->options['mimeTypeUnknown'];
  4246. }
  4247. }
  4248. }
  4249. // mime type normalization
  4250. $type = $this->mimeTypeNormalize($type, $name, $ext);
  4251. return $type;
  4252. }
  4253. /**
  4254. * Load file of mime.types
  4255. *
  4256. * @param string $mimeTypesFile The mime types file
  4257. */
  4258. static protected function loadMimeTypes($mimeTypesFile = '')
  4259. {
  4260. if (!elFinderVolumeDriver::$mimetypesLoaded) {
  4261. elFinderVolumeDriver::$mimetypesLoaded = true;
  4262. $file = false;
  4263. if (!empty($mimeTypesFile) && file_exists($mimeTypesFile)) {
  4264. $file = $mimeTypesFile;
  4265. } elseif (elFinder::$defaultMimefile && file_exists(elFinder::$defaultMimefile)) {
  4266. $file = elFinder::$defaultMimefile;
  4267. } elseif (file_exists(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mime.types')) {
  4268. $file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'mime.types';
  4269. } elseif (file_exists(dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'mime.types')) {
  4270. $file = dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'mime.types';
  4271. }
  4272. if ($file && file_exists($file)) {
  4273. $mimecf = file($file);
  4274. foreach ($mimecf as $line_num => $line) {
  4275. if (!preg_match('/^\s*#/', $line)) {
  4276. $mime = preg_split('/\s+/', $line, -1, PREG_SPLIT_NO_EMPTY);
  4277. for ($i = 1, $size = count($mime); $i < $size; $i++) {
  4278. if (!isset(self::$mimetypes[$mime[$i]])) {
  4279. self::$mimetypes[$mime[$i]] = $mime[0];
  4280. }
  4281. }
  4282. }
  4283. }
  4284. }
  4285. }
  4286. }
  4287. /**
  4288. * Detect file mimetype using "internal" method or Loading mime.types with $path = ''
  4289. *
  4290. * @param string $path file path
  4291. *
  4292. * @return string
  4293. * @author Dmitry (dio) Levashov
  4294. **/
  4295. static protected function mimetypeInternalDetect($path = '')
  4296. {
  4297. // load default MIME table file "mime.types"
  4298. if (!elFinderVolumeDriver::$mimetypesLoaded) {
  4299. elFinderVolumeDriver::loadMimeTypes();
  4300. }
  4301. $ext = '';
  4302. if ($path) {
  4303. $pinfo = pathinfo($path);
  4304. $ext = isset($pinfo['extension']) ? strtolower($pinfo['extension']) : '';
  4305. }
  4306. return ($ext && isset(elFinderVolumeDriver::$mimetypes[$ext])) ? elFinderVolumeDriver::$mimetypes[$ext] : 'unknown';
  4307. }
  4308. /**
  4309. * Return file/total directory size infomation
  4310. *
  4311. * @param string $path file path
  4312. *
  4313. * @return array
  4314. * @throws elFinderAbortException
  4315. * @author Dmitry (dio) Levashov
  4316. */
  4317. protected function countSize($path)
  4318. {
  4319. elFinder::checkAborted();
  4320. $result = array('size' => 0, 'files' => 0, 'dirs' => 0);
  4321. $stat = $this->stat($path);
  4322. if (empty($stat) || !$stat['read'] || !empty($stat['hidden'])) {
  4323. $result['size'] = 'unknown';
  4324. return $result;
  4325. }
  4326. if ($stat['mime'] !== 'directory') {
  4327. $result['size'] = intval($stat['size']);
  4328. $result['files'] = 1;
  4329. return $result;
  4330. }
  4331. $result['dirs'] = 1;
  4332. $subdirs = $this->options['checkSubfolders'];
  4333. $this->options['checkSubfolders'] = true;
  4334. foreach ($this->getScandir($path) as $stat) {
  4335. if ($isDir = ($stat['mime'] === 'directory' && $stat['read'])) {
  4336. ++$result['dirs'];
  4337. } else {
  4338. ++$result['files'];
  4339. }
  4340. $res = $isDir
  4341. ? $this->countSize($this->decode($stat['hash']))
  4342. : (isset($stat['size']) ? array('size' => intval($stat['size'])) : array());
  4343. if (!empty($res['size']) && is_numeric($res['size'])) {
  4344. $result['size'] += $res['size'];
  4345. }
  4346. if (!empty($res['files']) && is_numeric($res['files'])) {
  4347. $result['files'] += $res['files'];
  4348. }
  4349. if (!empty($res['dirs']) && is_numeric($res['dirs'])) {
  4350. $result['dirs'] += $res['dirs'];
  4351. --$result['dirs'];
  4352. }
  4353. }
  4354. $this->options['checkSubfolders'] = $subdirs;
  4355. return $result;
  4356. }
  4357. /**
  4358. * Return true if all mimes is directory or files
  4359. *
  4360. * @param string $mime1 mimetype
  4361. * @param string $mime2 mimetype
  4362. *
  4363. * @return bool
  4364. * @author Dmitry (dio) Levashov
  4365. **/
  4366. protected function isSameType($mime1, $mime2)
  4367. {
  4368. return ($mime1 == 'directory' && $mime1 == $mime2) || ($mime1 != 'directory' && $mime2 != 'directory');
  4369. }
  4370. /**
  4371. * If file has required attr == $val - return file path,
  4372. * If dir has child with has required attr == $val - return child path
  4373. *
  4374. * @param string $path file path
  4375. * @param string $attr attribute name
  4376. * @param bool $val attribute value
  4377. *
  4378. * @return string|false
  4379. * @author Dmitry (dio) Levashov
  4380. **/
  4381. protected function closestByAttr($path, $attr, $val)
  4382. {
  4383. $stat = $this->stat($path);
  4384. if (empty($stat)) {
  4385. return false;
  4386. }
  4387. $v = isset($stat[$attr]) ? $stat[$attr] : false;
  4388. if ($v == $val) {
  4389. return $path;
  4390. }
  4391. return $stat['mime'] == 'directory'
  4392. ? $this->childsByAttr($path, $attr, $val)
  4393. : false;
  4394. }
  4395. /**
  4396. * Return first found children with required attr == $val
  4397. *
  4398. * @param string $path file path
  4399. * @param string $attr attribute name
  4400. * @param bool $val attribute value
  4401. *
  4402. * @return string|false
  4403. * @author Dmitry (dio) Levashov
  4404. **/
  4405. protected function childsByAttr($path, $attr, $val)
  4406. {
  4407. foreach ($this->scandirCE($path) as $p) {
  4408. if (($_p = $this->closestByAttr($p, $attr, $val)) != false) {
  4409. return $_p;
  4410. }
  4411. }
  4412. return false;
  4413. }
  4414. protected function isMyReload($target = '', $ARGtarget = '')
  4415. {
  4416. if ($this->rootModified || (!empty($this->ARGS['cmd']) && $this->ARGS['cmd'] === 'parents')) {
  4417. return true;
  4418. }
  4419. if (!empty($this->ARGS['reload'])) {
  4420. if ($ARGtarget === '') {
  4421. $ARGtarget = isset($this->ARGS['target']) ? $this->ARGS['target']
  4422. : ((isset($this->ARGS['targets']) && is_array($this->ARGS['targets']) && count($this->ARGS['targets']) === 1) ?
  4423. $this->ARGS['targets'][0] : '');
  4424. }
  4425. if ($ARGtarget !== '') {
  4426. $ARGtarget = strval($ARGtarget);
  4427. if ($target === '') {
  4428. return (strpos($ARGtarget, $this->id) === 0);
  4429. } else {
  4430. $target = strval($target);
  4431. return ($target === $ARGtarget);
  4432. }
  4433. }
  4434. }
  4435. return false;
  4436. }
  4437. /**
  4438. * Update subdirs cache data
  4439. *
  4440. * @param string $path
  4441. * @param bool $subdirs
  4442. *
  4443. * @returnv void
  4444. */
  4445. protected function updateSubdirsCache($path, $subdirs)
  4446. {
  4447. if (isset($this->cache[$path])) {
  4448. if ($subdirs) {
  4449. $this->cache[$path]['dirs'] = 1;
  4450. } else {
  4451. unset($this->cache[$path]['dirs']);
  4452. }
  4453. }
  4454. if ($this->sessionCaching['subdirs']) {
  4455. $this->sessionCache['subdirs'][$path] = $subdirs;
  4456. }
  4457. if ($this->sessionCaching['rootstat'] && $path == $this->root) {
  4458. unset($this->sessionCache['rootstat'][$this->getRootstatCachekey()]);
  4459. }
  4460. }
  4461. /***************** get content *******************/
  4462. /**
  4463. * Return required dir's files info.
  4464. * If onlyMimes is set - return only dirs and files of required mimes
  4465. *
  4466. * @param string $path dir path
  4467. *
  4468. * @return array
  4469. * @author Dmitry (dio) Levashov
  4470. **/
  4471. protected function getScandir($path)
  4472. {
  4473. $files = array();
  4474. !isset($this->dirsCache[$path]) && $this->cacheDir($path);
  4475. foreach ($this->dirsCache[$path] as $p) {
  4476. if (($stat = $this->stat($p)) && empty($stat['hidden'])) {
  4477. $files[] = $stat;
  4478. }
  4479. }
  4480. return $files;
  4481. }
  4482. /**
  4483. * Return subdirs tree
  4484. *
  4485. * @param string $path parent dir path
  4486. * @param int $deep tree deep
  4487. * @param string $exclude
  4488. *
  4489. * @return array
  4490. * @author Dmitry (dio) Levashov
  4491. */
  4492. protected function gettree($path, $deep, $exclude = '')
  4493. {
  4494. $dirs = array();
  4495. !isset($this->dirsCache[$path]) && $this->cacheDir($path);
  4496. foreach ($this->dirsCache[$path] as $p) {
  4497. $stat = $this->stat($p);
  4498. if ($stat && empty($stat['hidden']) && $p != $exclude && $stat['mime'] == 'directory') {
  4499. $dirs[] = $stat;
  4500. if ($deep > 0 && !empty($stat['dirs'])) {
  4501. $dirs = array_merge($dirs, $this->gettree($p, $deep - 1));
  4502. }
  4503. }
  4504. }
  4505. return $dirs;
  4506. }
  4507. /**
  4508. * Recursive files search
  4509. *
  4510. * @param string $path dir path
  4511. * @param string $q search string
  4512. * @param array $mimes
  4513. *
  4514. * @return array
  4515. * @throws elFinderAbortException
  4516. * @author Dmitry (dio) Levashov
  4517. */
  4518. protected function doSearch($path, $q, $mimes)
  4519. {
  4520. $result = array();
  4521. $matchMethod = empty($this->doSearchCurrentQuery['matchMethod']) ? 'searchMatchName' : $this->doSearchCurrentQuery['matchMethod'];
  4522. $timeout = $this->options['searchTimeout'] ? $this->searchStart + $this->options['searchTimeout'] : 0;
  4523. if ($timeout && $timeout < time()) {
  4524. $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($path)));
  4525. return $result;
  4526. }
  4527. foreach ($this->scandirCE($path) as $p) {
  4528. elFinder::extendTimeLimit($this->options['searchTimeout'] + 30);
  4529. if ($timeout && ($this->error || $timeout < time())) {
  4530. !$this->error && $this->setError(elFinder::ERROR_SEARCH_TIMEOUT, $this->path($this->encode($path)));
  4531. break;
  4532. }
  4533. $stat = $this->stat($p);
  4534. if (!$stat) { // invalid links
  4535. continue;
  4536. }
  4537. if (!empty($stat['hidden']) || !$this->mimeAccepted($stat['mime'], $mimes)) {
  4538. continue;
  4539. }
  4540. $name = $stat['name'];
  4541. if ($this->doSearchCurrentQuery['excludes']) {
  4542. foreach ($this->doSearchCurrentQuery['excludes'] as $exclude) {
  4543. if ($this->stripos($name, $exclude) !== false) {
  4544. continue 2;
  4545. }
  4546. }
  4547. }
  4548. if ((!$mimes || $stat['mime'] !== 'directory') && $this->$matchMethod($name, $q, $p) !== false) {
  4549. $stat['path'] = $this->path($stat['hash']);
  4550. if ($this->URL && !isset($stat['url'])) {
  4551. $path = str_replace($this->separator, '/', substr($p, strlen($this->root) + 1));
  4552. if ($this->encoding) {
  4553. $path = str_replace('%2F', '/', rawurlencode($this->convEncIn($path, true)));
  4554. } else {
  4555. $path = str_replace('%2F', '/', rawurlencode($path));
  4556. }
  4557. $stat['url'] = $this->URL . $path;
  4558. }
  4559. $result[] = $stat;
  4560. }
  4561. if ($stat['mime'] == 'directory' && $stat['read'] && !isset($stat['alias'])) {
  4562. if (!$this->options['searchExDirReg'] || !preg_match($this->options['searchExDirReg'], $p)) {
  4563. $result = array_merge($result, $this->doSearch($p, $q, $mimes));
  4564. }
  4565. }
  4566. }
  4567. return $result;
  4568. }
  4569. /********************** manuipulations ******************/
  4570. /**
  4571. * Copy file/recursive copy dir only in current volume.
  4572. * Return new file path or false.
  4573. *
  4574. * @param string $src source path
  4575. * @param string $dst destination dir path
  4576. * @param string $name new file name (optionaly)
  4577. *
  4578. * @return string|false
  4579. * @throws elFinderAbortException
  4580. * @author Dmitry (dio) Levashov
  4581. */
  4582. protected function copy($src, $dst, $name)
  4583. {
  4584. elFinder::checkAborted();
  4585. $srcStat = $this->stat($src);
  4586. if (!empty($srcStat['thash'])) {
  4587. $target = $this->decode($srcStat['thash']);
  4588. if (!$this->inpathCE($target, $this->root)) {
  4589. return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']), elFinder::ERROR_MKOUTLINK);
  4590. }
  4591. $stat = $this->stat($target);
  4592. $this->clearcache();
  4593. return $stat && $this->symlinkCE($target, $dst, $name)
  4594. ? $this->joinPathCE($dst, $name)
  4595. : $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
  4596. }
  4597. if ($srcStat['mime'] === 'directory') {
  4598. $testStat = $this->isNameExists($this->joinPathCE($dst, $name));
  4599. $this->clearcache();
  4600. if (($testStat && $testStat['mime'] !== 'directory') || (!$testStat && !$testStat = $this->mkdir($this->encode($dst), $name))) {
  4601. return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
  4602. }
  4603. $dst = $this->decode($testStat['hash']);
  4604. foreach ($this->getScandir($src) as $stat) {
  4605. if (empty($stat['hidden'])) {
  4606. $name = $stat['name'];
  4607. $_src = $this->decode($stat['hash']);
  4608. if (!$this->copy($_src, $dst, $name)) {
  4609. $this->remove($dst, true); // fall back
  4610. return $this->setError($this->error, elFinder::ERROR_COPY, $this->_path($src));
  4611. }
  4612. }
  4613. }
  4614. $this->added[] = $testStat;
  4615. return $dst;
  4616. }
  4617. if ($this->options['copyJoin']) {
  4618. $test = $this->joinPathCE($dst, $name);
  4619. if ($this->isNameExists($test)) {
  4620. $this->remove($test);
  4621. }
  4622. }
  4623. if ($res = $this->convEncOut($this->_copy($this->convEncIn($src), $this->convEncIn($dst), $this->convEncIn($name)))) {
  4624. $path = is_string($res) ? $res : $this->joinPathCE($dst, $name);
  4625. $this->clearstatcache();
  4626. $this->added[] = $this->stat($path);
  4627. return $path;
  4628. }
  4629. return $this->setError(elFinder::ERROR_COPY, $this->path($srcStat['hash']));
  4630. }
  4631. /**
  4632. * Move file
  4633. * Return new file path or false.
  4634. *
  4635. * @param string $src source path
  4636. * @param string $dst destination dir path
  4637. * @param string $name new file name
  4638. *
  4639. * @return string|false
  4640. * @throws elFinderAbortException
  4641. * @author Dmitry (dio) Levashov
  4642. */
  4643. protected function move($src, $dst, $name)
  4644. {
  4645. $stat = $this->stat($src);
  4646. $stat['realpath'] = $src;
  4647. $this->rmTmb($stat); // can not do rmTmb() after _move()
  4648. $this->clearcache();
  4649. if ($res = $this->convEncOut($this->_move($this->convEncIn($src), $this->convEncIn($dst), $this->convEncIn($name)))) {
  4650. $this->clearstatcache();
  4651. if ($stat['mime'] === 'directory') {
  4652. $this->updateSubdirsCache($dst, true);
  4653. }
  4654. $path = is_string($res) ? $res : $this->joinPathCE($dst, $name);
  4655. $this->added[] = $this->stat($path);
  4656. $this->removed[] = $stat;
  4657. return $path;
  4658. }
  4659. return $this->setError(elFinder::ERROR_MOVE, $this->path($stat['hash']));
  4660. }
  4661. /**
  4662. * Copy file from another volume.
  4663. * Return new file path or false.
  4664. *
  4665. * @param Object $volume source volume
  4666. * @param string $src source file hash
  4667. * @param string $destination destination dir path
  4668. * @param string $name file name
  4669. *
  4670. * @return string|false
  4671. * @throws elFinderAbortException
  4672. * @author Dmitry (dio) Levashov
  4673. */
  4674. protected function copyFrom($volume, $src, $destination, $name)
  4675. {
  4676. elFinder::checkAborted();
  4677. if (($source = $volume->file($src)) == false) {
  4678. return $this->addError(elFinder::ERROR_COPY, '#' . $src, $volume->error());
  4679. }
  4680. $srcIsDir = ($source['mime'] === 'directory');
  4681. $errpath = $volume->path($source['hash']);
  4682. if (!$this->nameAccepted($source['name'], $srcIsDir)) {
  4683. return $this->addError(elFinder::ERROR_COPY, $errpath, $srcIsDir ? elFinder::ERROR_INVALID_DIRNAME : elFinder::ERROR_INVALID_NAME);
  4684. }
  4685. if (!$source['read']) {
  4686. return $this->addError(elFinder::ERROR_COPY, $errpath, elFinder::ERROR_PERM_DENIED);
  4687. }
  4688. if ($srcIsDir) {
  4689. $test = $this->isNameExists($this->joinPathCE($destination, $name));
  4690. $this->clearcache();
  4691. if (($test && $test['mime'] != 'directory') || (!$test && !$test = $this->mkdir($this->encode($destination), $name))) {
  4692. return $this->addError(elFinder::ERROR_COPY, $errpath);
  4693. }
  4694. //$path = $this->joinPathCE($destination, $name);
  4695. $path = $this->decode($test['hash']);
  4696. foreach ($volume->scandir($src) as $entr) {
  4697. $this->copyFrom($volume, $entr['hash'], $path, $entr['name']);
  4698. }
  4699. $this->added[] = $test;
  4700. } else {
  4701. // MIME check
  4702. $mimeByName = $this->mimetype($source['name'], true);
  4703. if ($source['mime'] === $mimeByName) {
  4704. $mimeByName = '';
  4705. }
  4706. if (!$this->allowPutMime($source['mime']) || ($mimeByName && !$this->allowPutMime($mimeByName))) {
  4707. return $this->addError(elFinder::ERROR_UPLOAD_FILE_MIME, $errpath);
  4708. }
  4709. if (strpos($source['mime'], 'image') === 0 && ($dim = $volume->dimensions($src))) {
  4710. if (is_array($dim)) {
  4711. $dim = isset($dim['dim']) ? $dim['dim'] : null;
  4712. }
  4713. if ($dim) {
  4714. $s = explode('x', $dim);
  4715. $source['width'] = $s[0];
  4716. $source['height'] = $s[1];
  4717. }
  4718. }
  4719. if (($fp = $volume->open($src)) == false
  4720. || ($path = $this->saveCE($fp, $destination, $name, $source)) == false) {
  4721. $fp && $volume->close($fp, $src);
  4722. return $this->addError(elFinder::ERROR_COPY, $errpath);
  4723. }
  4724. $volume->close($fp, $src);
  4725. $this->added[] = $this->stat($path);;
  4726. }
  4727. return $path;
  4728. }
  4729. /**
  4730. * Remove file/ recursive remove dir
  4731. *
  4732. * @param string $path file path
  4733. * @param bool $force try to remove even if file locked
  4734. *
  4735. * @return bool
  4736. * @throws elFinderAbortException
  4737. * @author Dmitry (dio) Levashov
  4738. */
  4739. protected function remove($path, $force = false)
  4740. {
  4741. $stat = $this->stat($path);
  4742. if (empty($stat)) {
  4743. return $this->setError(elFinder::ERROR_RM, $path, elFinder::ERROR_FILE_NOT_FOUND);
  4744. }
  4745. $stat['realpath'] = $path;
  4746. $this->rmTmb($stat);
  4747. $this->clearcache();
  4748. if (!$force && !empty($stat['locked'])) {
  4749. return $this->setError(elFinder::ERROR_LOCKED, $this->path($stat['hash']));
  4750. }
  4751. if ($stat['mime'] == 'directory' && empty($stat['thash'])) {
  4752. $ret = $this->delTree($this->convEncIn($path));
  4753. $this->convEncOut();
  4754. if (!$ret) {
  4755. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
  4756. }
  4757. } else {
  4758. if ($this->convEncOut(!$this->_unlink($this->convEncIn($path)))) {
  4759. return $this->setError(elFinder::ERROR_RM, $this->path($stat['hash']));
  4760. }
  4761. $this->clearstatcache();
  4762. }
  4763. $this->removed[] = $stat;
  4764. return true;
  4765. }
  4766. /************************* thumbnails **************************/
  4767. /**
  4768. * Return thumbnail file name for required file
  4769. *
  4770. * @param array $stat file stat
  4771. *
  4772. * @return string
  4773. * @author Dmitry (dio) Levashov
  4774. **/
  4775. protected function tmbname($stat)
  4776. {
  4777. $name = $stat['hash'] . (isset($stat['ts']) ? $stat['ts'] : '') . '.png';
  4778. if (strlen($name) > 255) {
  4779. $name = $this->id . md5($stat['hash']) . $stat['ts'] . '.png';
  4780. }
  4781. return $name;
  4782. }
  4783. /**
  4784. * Return thumnbnail name if exists
  4785. *
  4786. * @param string $path file path
  4787. * @param array $stat file stat
  4788. *
  4789. * @return string|false
  4790. * @author Dmitry (dio) Levashov
  4791. **/
  4792. protected function gettmb($path, $stat)
  4793. {
  4794. if ($this->tmbURL && $this->tmbPath) {
  4795. // file itself thumnbnail
  4796. if (strpos($path, $this->tmbPath) === 0) {
  4797. return basename($path);
  4798. }
  4799. $name = $this->tmbname($stat);
  4800. if (file_exists($this->tmbPath . DIRECTORY_SEPARATOR . $name)) {
  4801. return $name;
  4802. }
  4803. }
  4804. return false;
  4805. }
  4806. /**
  4807. * Return true if thumnbnail for required file can be created
  4808. *
  4809. * @param string $path thumnbnail path
  4810. * @param array $stat file stat
  4811. * @param bool $checkTmbPath
  4812. *
  4813. * @return string|bool
  4814. * @author Dmitry (dio) Levashov
  4815. **/
  4816. protected function canCreateTmb($path, $stat, $checkTmbPath = true)
  4817. {
  4818. if ((!$checkTmbPath || $this->tmbPathWritable)
  4819. && (!$this->tmbPath || strpos($path, $this->tmbPath) === false) // do not create thumnbnail for thumnbnail
  4820. ) {
  4821. $mime = strtolower($stat['mime']);
  4822. list($type) = explode('/', $mime);
  4823. if (!empty($this->imgConverter)) {
  4824. if (isset($this->imgConverter[$mime])) {
  4825. return true;
  4826. }
  4827. if (isset($this->imgConverter[$type])) {
  4828. return true;
  4829. }
  4830. }
  4831. return $this->imgLib
  4832. && (
  4833. ($type === 'image' && ($this->imgLib === 'gd' ? in_array($stat['mime'], array('image/jpeg', 'image/png', 'image/gif', 'image/x-ms-bmp')) : true))
  4834. ||
  4835. (ELFINDER_IMAGEMAGICK_PS && $this->imgLib !== 'gd' && in_array($stat['mime'], array('application/postscript', 'application/pdf')))
  4836. );
  4837. }
  4838. return false;
  4839. }
  4840. /**
  4841. * Return true if required file can be resized.
  4842. * By default - the same as canCreateTmb
  4843. *
  4844. * @param string $path thumnbnail path
  4845. * @param array $stat file stat
  4846. *
  4847. * @return string|bool
  4848. * @author Dmitry (dio) Levashov
  4849. **/
  4850. protected function canResize($path, $stat)
  4851. {
  4852. return $this->canCreateTmb($path, $stat, false);
  4853. }
  4854. /**
  4855. * Create thumnbnail and return it's URL on success
  4856. *
  4857. * @param string $path file path
  4858. * @param $stat
  4859. *
  4860. * @return false|string
  4861. * @internal param string $mime file mime type
  4862. * @throws elFinderAbortException
  4863. * @throws ImagickException
  4864. * @author Dmitry (dio) Levashov
  4865. */
  4866. protected function createTmb($path, $stat)
  4867. {
  4868. if (!$stat || !$this->canCreateTmb($path, $stat)) {
  4869. return false;
  4870. }
  4871. $name = $this->tmbname($stat);
  4872. $tmb = $this->tmbPath . DIRECTORY_SEPARATOR . $name;
  4873. $maxlength = -1;
  4874. $imgConverter = null;
  4875. // check imgConverter
  4876. $mime = strtolower($stat['mime']);
  4877. list($type) = explode('/', $mime);
  4878. if (isset($this->imgConverter[$mime])) {
  4879. $imgConverter = $this->imgConverter[$mime]['func'];
  4880. if (!empty($this->imgConverter[$mime]['maxlen'])) {
  4881. $maxlength = intval($this->imgConverter[$mime]['maxlen']);
  4882. }
  4883. } else if (isset($this->imgConverter[$type])) {
  4884. $imgConverter = $this->imgConverter[$type]['func'];
  4885. if (!empty($this->imgConverter[$type]['maxlen'])) {
  4886. $maxlength = intval($this->imgConverter[$type]['maxlen']);
  4887. }
  4888. }
  4889. if ($imgConverter && !is_callable($imgConverter)) {
  4890. return false;
  4891. }
  4892. // copy image into tmbPath so some drivers does not store files on local fs
  4893. if (($src = $this->fopenCE($path, 'rb')) == false) {
  4894. return false;
  4895. }
  4896. if (($trg = fopen($tmb, 'wb')) == false) {
  4897. $this->fcloseCE($src, $path);
  4898. return false;
  4899. }
  4900. stream_copy_to_stream($src, $trg, $maxlength);
  4901. $this->fcloseCE($src, $path);
  4902. fclose($trg);
  4903. // call imgConverter
  4904. if ($imgConverter) {
  4905. if (!call_user_func_array($imgConverter, array($tmb, $stat, $this))) {
  4906. file_exists($tmb) && unlink($tmb);
  4907. return false;
  4908. }
  4909. }
  4910. $result = false;
  4911. $tmbSize = $this->tmbSize;
  4912. if ($this->imgLib === 'imagick') {
  4913. try {
  4914. $imagickTest = new imagick($tmb . '[0]');
  4915. $imagickTest->clear();
  4916. $imagickTest = true;
  4917. } catch (Exception $e) {
  4918. $imagickTest = false;
  4919. }
  4920. }
  4921. if (($this->imgLib === 'imagick' && !$imagickTest) || ($s = getimagesize($tmb)) === false) {
  4922. if ($this->imgLib === 'imagick') {
  4923. $bgcolor = $this->options['tmbBgColor'];
  4924. if ($bgcolor === 'transparent') {
  4925. $bgcolor = 'rgba(255, 255, 255, 0.0)';
  4926. }
  4927. try {
  4928. $imagick = new imagick();
  4929. $imagick->setBackgroundColor(new ImagickPixel($bgcolor));
  4930. $imagick->readImage($this->getExtentionByMime($stat['mime'], ':') . $tmb . '[0]');
  4931. try {
  4932. $imagick->trimImage(0);
  4933. } catch (Exception $e) {
  4934. }
  4935. $imagick->setImageFormat('png');
  4936. $imagick->writeImage($tmb);
  4937. $imagick->clear();
  4938. if (($s = getimagesize($tmb)) !== false) {
  4939. $result = true;
  4940. }
  4941. } catch (Exception $e) {
  4942. }
  4943. } else if ($this->imgLib === 'convert') {
  4944. $convParams = $this->imageMagickConvertPrepare($tmb, 'png', 100, array(), $stat['mime']);
  4945. $cmd = sprintf('%s -colorspace sRGB -trim -- %s %s', ELFINDER_CONVERT_PATH, $convParams['quotedPath'], $convParams['quotedDstPath']);
  4946. $result = false;
  4947. if ($this->procExec($cmd) === 0) {
  4948. if (($s = getimagesize($tmb)) !== false) {
  4949. $result = true;
  4950. }
  4951. }
  4952. }
  4953. if (!$result) {
  4954. // fallback imgLib to GD
  4955. if (function_exists('gd_info') && ($s = getimagesize($tmb))) {
  4956. $this->imgLib = 'gd';
  4957. } else {
  4958. file_exists($tmb) && unlink($tmb);
  4959. return false;
  4960. }
  4961. }
  4962. }
  4963. /* If image smaller or equal thumbnail size - just fitting to thumbnail square */
  4964. if ($s[0] <= $tmbSize && $s[1] <= $tmbSize) {
  4965. $result = $this->imgSquareFit($tmb, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png');
  4966. } else {
  4967. if ($this->options['tmbCrop']) {
  4968. $result = $tmb;
  4969. /* Resize and crop if image bigger than thumbnail */
  4970. if (!(($s[0] > $tmbSize && $s[1] <= $tmbSize) || ($s[0] <= $tmbSize && $s[1] > $tmbSize)) || ($s[0] > $tmbSize && $s[1] > $tmbSize)) {
  4971. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, false, 'png');
  4972. }
  4973. if ($result && ($s = getimagesize($tmb)) != false) {
  4974. $x = $s[0] > $tmbSize ? intval(($s[0] - $tmbSize) / 2) : 0;
  4975. $y = $s[1] > $tmbSize ? intval(($s[1] - $tmbSize) / 2) : 0;
  4976. $result = $this->imgCrop($result, $tmbSize, $tmbSize, $x, $y, 'png');
  4977. } else {
  4978. $result = false;
  4979. }
  4980. } else {
  4981. $result = $this->imgResize($tmb, $tmbSize, $tmbSize, true, true, 'png');
  4982. }
  4983. if ($result) {
  4984. if ($s = getimagesize($tmb)) {
  4985. if ($s[0] !== $tmbSize || $s[1] !== $tmbSize) {
  4986. $result = $this->imgSquareFit($result, $tmbSize, $tmbSize, 'center', 'middle', $this->options['tmbBgColor'], 'png');
  4987. }
  4988. }
  4989. }
  4990. }
  4991. if (!$result) {
  4992. unlink($tmb);
  4993. return false;
  4994. }
  4995. return $name;
  4996. }
  4997. /**
  4998. * Resize image
  4999. *
  5000. * @param string $path image file
  5001. * @param int $width new width
  5002. * @param int $height new height
  5003. * @param bool $keepProportions crop image
  5004. * @param bool $resizeByBiggerSide resize image based on bigger side if true
  5005. * @param string $destformat image destination format
  5006. * @param int $jpgQuality JEPG quality (1-100)
  5007. * @param array $options Other extra options
  5008. *
  5009. * @return string|false
  5010. * @throws elFinderAbortException
  5011. * @author Dmitry (dio) Levashov
  5012. * @author Alexey Sukhotin
  5013. */
  5014. protected function imgResize($path, $width, $height, $keepProportions = false, $resizeByBiggerSide = true, $destformat = null, $jpgQuality = null, $options = array())
  5015. {
  5016. if (($s = getimagesize($path)) == false) {
  5017. return false;
  5018. }
  5019. if (!$jpgQuality) {
  5020. $jpgQuality = $this->options['jpgQuality'];
  5021. }
  5022. list($orig_w, $orig_h) = array($s[0], $s[1]);
  5023. list($size_w, $size_h) = array($width, $height);
  5024. if (empty($options['unenlarge']) || $orig_w > $size_w || $orig_h > $size_h) {
  5025. if ($keepProportions == true) {
  5026. /* Resizing by biggest side */
  5027. if ($resizeByBiggerSide) {
  5028. if ($orig_w > $orig_h) {
  5029. $size_h = round($orig_h * $width / $orig_w);
  5030. $size_w = $width;
  5031. } else {
  5032. $size_w = round($orig_w * $height / $orig_h);
  5033. $size_h = $height;
  5034. }
  5035. } else {
  5036. if ($orig_w > $orig_h) {
  5037. $size_w = round($orig_w * $height / $orig_h);
  5038. $size_h = $height;
  5039. } else {
  5040. $size_h = round($orig_h * $width / $orig_w);
  5041. $size_w = $width;
  5042. }
  5043. }
  5044. }
  5045. } else {
  5046. $size_w = $orig_w;
  5047. $size_h = $orig_h;
  5048. }
  5049. elFinder::extendTimeLimit(300);
  5050. switch ($this->imgLib) {
  5051. case 'imagick':
  5052. try {
  5053. $img = new imagick($path);
  5054. } catch (Exception $e) {
  5055. return false;
  5056. }
  5057. // Imagick::FILTER_BOX faster than FILTER_LANCZOS so use for createTmb
  5058. // resize bench: http://app-mgng.rhcloud.com/9
  5059. // resize sample: http://www.dylanbeattie.net/magick/filters/result.html
  5060. $filter = ($destformat === 'png' /* createTmb */) ? Imagick::FILTER_BOX : Imagick::FILTER_LANCZOS;
  5061. $ani = ($img->getNumberImages() > 1);
  5062. if ($ani && is_null($destformat)) {
  5063. $img = $img->coalesceImages();
  5064. do {
  5065. $img->resizeImage($size_w, $size_h, $filter, 1);
  5066. } while ($img->nextImage());
  5067. $img->optimizeImageLayers();
  5068. $result = $img->writeImages($path, true);
  5069. } else {
  5070. if ($ani) {
  5071. $img->setFirstIterator();
  5072. }
  5073. if (strtoupper($img->getImageFormat()) === 'JPEG') {
  5074. $img->setImageCompression(imagick::COMPRESSION_JPEG);
  5075. $img->setImageCompressionQuality($jpgQuality);
  5076. if (isset($options['preserveExif']) && !$options['preserveExif']) {
  5077. try {
  5078. $orientation = $img->getImageOrientation();
  5079. } catch (ImagickException $e) {
  5080. $orientation = 0;
  5081. }
  5082. $img->stripImage();
  5083. if ($orientation) {
  5084. $img->setImageOrientation($orientation);
  5085. }
  5086. }
  5087. if ($this->options['jpgProgressive']) {
  5088. $img->setInterlaceScheme(Imagick::INTERLACE_PLANE);
  5089. }
  5090. }
  5091. $img->resizeImage($size_w, $size_h, $filter, true);
  5092. if ($destformat) {
  5093. $result = $this->imagickImage($img, $path, $destformat, $jpgQuality);
  5094. } else {
  5095. $result = $img->writeImage($path);
  5096. }
  5097. }
  5098. $img->clear();
  5099. return $result ? $path : false;
  5100. break;
  5101. case 'convert':
  5102. extract($this->imageMagickConvertPrepare($path, $destformat, $jpgQuality, $s));
  5103. /**
  5104. * @var string $ani
  5105. * @var string $index
  5106. * @var string $coalesce
  5107. * @var string $deconstruct
  5108. * @var string $jpgQuality
  5109. * @var string $quotedPath
  5110. * @var string $quotedDstPath
  5111. * @var string $interlace
  5112. */
  5113. $filter = ($destformat === 'png' /* createTmb */) ? '-filter Box' : '-filter Lanczos';
  5114. $strip = (isset($options['preserveExif']) && !$options['preserveExif']) ? ' -strip' : '';
  5115. $cmd = sprintf('%s %s%s%s%s%s %s -geometry %dx%d! %s %s', ELFINDER_CONVERT_PATH, $quotedPath, $coalesce, $jpgQuality, $strip, $interlace, $filter, $size_w, $size_h, $deconstruct, $quotedDstPath);
  5116. $result = false;
  5117. if ($this->procExec($cmd) === 0) {
  5118. $result = true;
  5119. }
  5120. return $result ? $path : false;
  5121. break;
  5122. case 'gd':
  5123. elFinder::expandMemoryForGD(array($s, array($size_w, $size_h)));
  5124. $img = $this->gdImageCreate($path, $s['mime']);
  5125. if ($img && false != ($tmp = imagecreatetruecolor($size_w, $size_h))) {
  5126. $bgNum = false;
  5127. if ($s[2] === IMAGETYPE_GIF && (!$destformat || $destformat === 'gif')) {
  5128. $bgIdx = imagecolortransparent($img);
  5129. if ($bgIdx !== -1) {
  5130. $c = imagecolorsforindex($img, $bgIdx);
  5131. $bgNum = imagecolorallocate($tmp, $c['red'], $c['green'], $c['blue']);
  5132. imagefill($tmp, 0, 0, $bgNum);
  5133. imagecolortransparent($tmp, $bgNum);
  5134. }
  5135. }
  5136. if ($bgNum === false) {
  5137. $this->gdImageBackground($tmp, 'transparent');
  5138. }
  5139. if (!imagecopyresampled($tmp, $img, 0, 0, 0, 0, $size_w, $size_h, $s[0], $s[1])) {
  5140. return false;
  5141. }
  5142. $result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);
  5143. imagedestroy($img);
  5144. imagedestroy($tmp);
  5145. return $result ? $path : false;
  5146. }
  5147. break;
  5148. }
  5149. return false;
  5150. }
  5151. /**
  5152. * Crop image
  5153. *
  5154. * @param string $path image file
  5155. * @param int $width crop width
  5156. * @param int $height crop height
  5157. * @param bool $x crop left offset
  5158. * @param bool $y crop top offset
  5159. * @param string $destformat image destination format
  5160. * @param int $jpgQuality JEPG quality (1-100)
  5161. *
  5162. * @return string|false
  5163. * @throws elFinderAbortException
  5164. * @author Dmitry (dio) Levashov
  5165. * @author Alexey Sukhotin
  5166. */
  5167. protected function imgCrop($path, $width, $height, $x, $y, $destformat = null, $jpgQuality = null)
  5168. {
  5169. if (($s = getimagesize($path)) == false) {
  5170. return false;
  5171. }
  5172. if (!$jpgQuality) {
  5173. $jpgQuality = $this->options['jpgQuality'];
  5174. }
  5175. elFinder::extendTimeLimit(300);
  5176. switch ($this->imgLib) {
  5177. case 'imagick':
  5178. try {
  5179. $img = new imagick($path);
  5180. } catch (Exception $e) {
  5181. return false;
  5182. }
  5183. $ani = ($img->getNumberImages() > 1);
  5184. if ($ani && is_null($destformat)) {
  5185. $img = $img->coalesceImages();
  5186. do {
  5187. $img->setImagePage($s[0], $s[1], 0, 0);
  5188. $img->cropImage($width, $height, $x, $y);
  5189. $img->setImagePage($width, $height, 0, 0);
  5190. } while ($img->nextImage());
  5191. $img->optimizeImageLayers();
  5192. $result = $img->writeImages($path, true);
  5193. } else {
  5194. if ($ani) {
  5195. $img->setFirstIterator();
  5196. }
  5197. $img->setImagePage($s[0], $s[1], 0, 0);
  5198. $img->cropImage($width, $height, $x, $y);
  5199. $img->setImagePage($width, $height, 0, 0);
  5200. $result = $this->imagickImage($img, $path, $destformat, $jpgQuality);
  5201. }
  5202. $img->clear();
  5203. return $result ? $path : false;
  5204. break;
  5205. case 'convert':
  5206. extract($this->imageMagickConvertPrepare($path, $destformat, $jpgQuality, $s));
  5207. /**
  5208. * @var string $ani
  5209. * @var string $index
  5210. * @var string $coalesce
  5211. * @var string $deconstruct
  5212. * @var string $jpgQuality
  5213. * @var string $quotedPath
  5214. * @var string $quotedDstPath
  5215. * @var string $interlace
  5216. */
  5217. $cmd = sprintf('%s %s%s%s%s -crop %dx%d+%d+%d%s %s', ELFINDER_CONVERT_PATH, $quotedPath, $coalesce, $jpgQuality, $interlace, $width, $height, $x, $y, $deconstruct, $quotedDstPath);
  5218. $result = false;
  5219. if ($this->procExec($cmd) === 0) {
  5220. $result = true;
  5221. }
  5222. return $result ? $path : false;
  5223. break;
  5224. case 'gd':
  5225. elFinder::expandMemoryForGD(array($s, array($width, $height)));
  5226. $img = $this->gdImageCreate($path, $s['mime']);
  5227. if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) {
  5228. $bgNum = false;
  5229. if ($s[2] === IMAGETYPE_GIF && (!$destformat || $destformat === 'gif')) {
  5230. $bgIdx = imagecolortransparent($img);
  5231. if ($bgIdx !== -1) {
  5232. $c = imagecolorsforindex($img, $bgIdx);
  5233. $bgNum = imagecolorallocate($tmp, $c['red'], $c['green'], $c['blue']);
  5234. imagefill($tmp, 0, 0, $bgNum);
  5235. imagecolortransparent($tmp, $bgNum);
  5236. }
  5237. }
  5238. if ($bgNum === false) {
  5239. $this->gdImageBackground($tmp, 'transparent');
  5240. }
  5241. $size_w = $width;
  5242. $size_h = $height;
  5243. if ($s[0] < $width || $s[1] < $height) {
  5244. $size_w = $s[0];
  5245. $size_h = $s[1];
  5246. }
  5247. if (!imagecopy($tmp, $img, 0, 0, $x, $y, $size_w, $size_h)) {
  5248. return false;
  5249. }
  5250. $result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);
  5251. imagedestroy($img);
  5252. imagedestroy($tmp);
  5253. return $result ? $path : false;
  5254. }
  5255. break;
  5256. }
  5257. return false;
  5258. }
  5259. /**
  5260. * Put image to square
  5261. *
  5262. * @param string $path image file
  5263. * @param int $width square width
  5264. * @param int $height square height
  5265. * @param int|string $align reserved
  5266. * @param int|string $valign reserved
  5267. * @param string $bgcolor square background color in #rrggbb format
  5268. * @param string $destformat image destination format
  5269. * @param int $jpgQuality JEPG quality (1-100)
  5270. *
  5271. * @return false|string
  5272. * @throws ImagickException
  5273. * @throws elFinderAbortException
  5274. * @author Dmitry (dio) Levashov
  5275. * @author Alexey Sukhotin
  5276. */
  5277. protected function imgSquareFit($path, $width, $height, $align = 'center', $valign = 'middle', $bgcolor = '#0000ff', $destformat = null, $jpgQuality = null)
  5278. {
  5279. if (($s = getimagesize($path)) == false) {
  5280. return false;
  5281. }
  5282. $result = false;
  5283. /* Coordinates for image over square aligning */
  5284. $y = ceil(abs($height - $s[1]) / 2);
  5285. $x = ceil(abs($width - $s[0]) / 2);
  5286. if (!$jpgQuality) {
  5287. $jpgQuality = $this->options['jpgQuality'];
  5288. }
  5289. elFinder::extendTimeLimit(300);
  5290. switch ($this->imgLib) {
  5291. case 'imagick':
  5292. try {
  5293. $img = new imagick($path);
  5294. } catch (Exception $e) {
  5295. return false;
  5296. }
  5297. if ($bgcolor === 'transparent') {
  5298. $bgcolor = 'rgba(255, 255, 255, 0.0)';
  5299. }
  5300. $ani = ($img->getNumberImages() > 1);
  5301. if ($ani && is_null($destformat)) {
  5302. $img1 = new Imagick();
  5303. $img1->setFormat('gif');
  5304. $img = $img->coalesceImages();
  5305. do {
  5306. $gif = new Imagick();
  5307. $gif->newImage($width, $height, new ImagickPixel($bgcolor));
  5308. $gif->setImageColorspace($img->getImageColorspace());
  5309. $gif->setImageFormat('gif');
  5310. $gif->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y);
  5311. $gif->setImageDelay($img->getImageDelay());
  5312. $gif->setImageIterations($img->getImageIterations());
  5313. $img1->addImage($gif);
  5314. $gif->clear();
  5315. } while ($img->nextImage());
  5316. $img1->optimizeImageLayers();
  5317. $result = $img1->writeImages($path, true);
  5318. } else {
  5319. if ($ani) {
  5320. $img->setFirstIterator();
  5321. }
  5322. $img1 = new Imagick();
  5323. $img1->newImage($width, $height, new ImagickPixel($bgcolor));
  5324. $img1->setImageColorspace($img->getImageColorspace());
  5325. $img1->compositeImage($img, imagick::COMPOSITE_OVER, $x, $y);
  5326. $result = $this->imagickImage($img1, $path, $destformat, $jpgQuality);
  5327. }
  5328. $img1->clear();
  5329. $img->clear();
  5330. return $result ? $path : false;
  5331. break;
  5332. case 'convert':
  5333. extract($this->imageMagickConvertPrepare($path, $destformat, $jpgQuality, $s));
  5334. /**
  5335. * @var string $ani
  5336. * @var string $index
  5337. * @var string $coalesce
  5338. * @var string $deconstruct
  5339. * @var string $jpgQuality
  5340. * @var string $quotedPath
  5341. * @var string $quotedDstPath
  5342. * @var string $interlace
  5343. */
  5344. if ($bgcolor === 'transparent') {
  5345. $bgcolor = 'rgba(255, 255, 255, 0.0)';
  5346. }
  5347. $cmd = sprintf('%s -size %dx%d "xc:%s" png:- | convert%s%s%s png:- %s -geometry +%d+%d -compose over -composite%s %s', ELFINDER_CONVERT_PATH, $width, $height, $bgcolor, $coalesce, $jpgQuality, $interlace, $quotedPath, $x, $y, $deconstruct, $quotedDstPath);
  5348. $result = false;
  5349. if ($this->procExec($cmd) === 0) {
  5350. $result = true;
  5351. }
  5352. return $result ? $path : false;
  5353. break;
  5354. case 'gd':
  5355. elFinder::expandMemoryForGD(array($s, array($width, $height)));
  5356. $img = $this->gdImageCreate($path, $s['mime']);
  5357. if ($img && false != ($tmp = imagecreatetruecolor($width, $height))) {
  5358. $this->gdImageBackground($tmp, $bgcolor);
  5359. if ($bgcolor === 'transparent' && ($destformat === 'png' || $s[2] === IMAGETYPE_PNG)) {
  5360. $bgNum = imagecolorallocatealpha($tmp, 255, 255, 255, 127);
  5361. imagefill($tmp, 0, 0, $bgNum);
  5362. }
  5363. if (!imagecopy($tmp, $img, $x, $y, 0, 0, $s[0], $s[1])) {
  5364. return false;
  5365. }
  5366. $result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);
  5367. imagedestroy($img);
  5368. imagedestroy($tmp);
  5369. return $result ? $path : false;
  5370. }
  5371. break;
  5372. }
  5373. return false;
  5374. }
  5375. /**
  5376. * Rotate image
  5377. *
  5378. * @param string $path image file
  5379. * @param int $degree rotete degrees
  5380. * @param string $bgcolor square background color in #rrggbb format
  5381. * @param string $destformat image destination format
  5382. * @param int $jpgQuality JEPG quality (1-100)
  5383. *
  5384. * @return string|false
  5385. * @throws elFinderAbortException
  5386. * @author nao-pon
  5387. * @author Troex Nevelin
  5388. */
  5389. protected function imgRotate($path, $degree, $bgcolor = '#ffffff', $destformat = null, $jpgQuality = null)
  5390. {
  5391. if (($s = getimagesize($path)) == false || $degree % 360 === 0) {
  5392. return false;
  5393. }
  5394. $result = false;
  5395. // try lossless rotate
  5396. if ($degree % 90 === 0 && in_array($s[2], array(IMAGETYPE_JPEG, IMAGETYPE_JPEG2000))) {
  5397. $count = ($degree / 90) % 4;
  5398. $exiftran = array(
  5399. 1 => '-9',
  5400. 2 => '-1',
  5401. 3 => '-2'
  5402. );
  5403. $jpegtran = array(
  5404. 1 => '90',
  5405. 2 => '180',
  5406. 3 => '270'
  5407. );
  5408. $quotedPath = escapeshellarg($path);
  5409. $cmds = array();
  5410. if ($this->procExec(ELFINDER_EXIFTRAN_PATH . ' -h') === 0) {
  5411. $cmds[] = ELFINDER_EXIFTRAN_PATH . ' -i ' . $exiftran[$count] . ' -- ' . $quotedPath;
  5412. }
  5413. if ($this->procExec(ELFINDER_JPEGTRAN_PATH . ' -version') === 0) {
  5414. $cmds[] = ELFINDER_JPEGTRAN_PATH . ' -rotate ' . $jpegtran[$count] . ' -copy all -outfile ' . $quotedPath . ' -- ' . $quotedPath;
  5415. }
  5416. foreach ($cmds as $cmd) {
  5417. if ($this->procExec($cmd) === 0) {
  5418. $result = true;
  5419. break;
  5420. }
  5421. }
  5422. if ($result) {
  5423. return $path;
  5424. }
  5425. }
  5426. if (!$jpgQuality) {
  5427. $jpgQuality = $this->options['jpgQuality'];
  5428. }
  5429. elFinder::extendTimeLimit(300);
  5430. switch ($this->imgLib) {
  5431. case 'imagick':
  5432. try {
  5433. $img = new imagick($path);
  5434. } catch (Exception $e) {
  5435. return false;
  5436. }
  5437. if ($s[2] === IMAGETYPE_GIF || $s[2] === IMAGETYPE_PNG) {
  5438. $bgcolor = 'rgba(255, 255, 255, 0.0)';
  5439. }
  5440. if ($img->getNumberImages() > 1) {
  5441. $img = $img->coalesceImages();
  5442. do {
  5443. $img->rotateImage(new ImagickPixel($bgcolor), $degree);
  5444. } while ($img->nextImage());
  5445. $img->optimizeImageLayers();
  5446. $result = $img->writeImages($path, true);
  5447. } else {
  5448. $img->rotateImage(new ImagickPixel($bgcolor), $degree);
  5449. $result = $this->imagickImage($img, $path, $destformat, $jpgQuality);
  5450. }
  5451. $img->clear();
  5452. return $result ? $path : false;
  5453. break;
  5454. case 'convert':
  5455. extract($this->imageMagickConvertPrepare($path, $destformat, $jpgQuality, $s));
  5456. /**
  5457. * @var string $ani
  5458. * @var string $index
  5459. * @var string $coalesce
  5460. * @var string $deconstruct
  5461. * @var string $jpgQuality
  5462. * @var string $quotedPath
  5463. * @var string $quotedDstPath
  5464. * @var string $interlace
  5465. */
  5466. if ($s[2] === IMAGETYPE_GIF || $s[2] === IMAGETYPE_PNG) {
  5467. $bgcolor = 'rgba(255, 255, 255, 0.0)';
  5468. }
  5469. $cmd = sprintf('%s%s%s%s -background "%s" -rotate %d%s -- %s %s', ELFINDER_CONVERT_PATH, $coalesce, $jpgQuality, $interlace, $bgcolor, $degree, $deconstruct, $quotedPath, $quotedDstPath);
  5470. $result = false;
  5471. if ($this->procExec($cmd) === 0) {
  5472. $result = true;
  5473. }
  5474. return $result ? $path : false;
  5475. break;
  5476. case 'gd':
  5477. elFinder::expandMemoryForGD(array($s, $s));
  5478. $img = $this->gdImageCreate($path, $s['mime']);
  5479. $degree = 360 - $degree;
  5480. $bgNum = -1;
  5481. $bgIdx = false;
  5482. if ($s[2] === IMAGETYPE_GIF) {
  5483. $bgIdx = imagecolortransparent($img);
  5484. if ($bgIdx !== -1) {
  5485. $c = imagecolorsforindex($img, $bgIdx);
  5486. $w = imagesx($img);
  5487. $h = imagesy($img);
  5488. $newImg = imagecreatetruecolor($w, $h);
  5489. imagepalettecopy($newImg, $img);
  5490. $bgNum = imagecolorallocate($newImg, $c['red'], $c['green'], $c['blue']);
  5491. imagefill($newImg, 0, 0, $bgNum);
  5492. imagecolortransparent($newImg, $bgNum);
  5493. imagecopy($newImg, $img, 0, 0, 0, 0, $w, $h);
  5494. imagedestroy($img);
  5495. $img = $newImg;
  5496. $newImg = null;
  5497. }
  5498. } else if ($s[2] === IMAGETYPE_PNG) {
  5499. $bgNum = imagecolorallocatealpha($img, 255, 255, 255, 127);
  5500. }
  5501. if ($bgNum === -1) {
  5502. list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
  5503. $bgNum = imagecolorallocate($img, $r, $g, $b);
  5504. }
  5505. $tmp = imageRotate($img, $degree, $bgNum);
  5506. if ($bgIdx !== -1) {
  5507. imagecolortransparent($tmp, $bgNum);
  5508. }
  5509. $result = $this->gdImage($tmp, $path, $destformat, $s['mime'], $jpgQuality);
  5510. imageDestroy($img);
  5511. imageDestroy($tmp);
  5512. return $result ? $path : false;
  5513. break;
  5514. }
  5515. return false;
  5516. }
  5517. /**
  5518. * Execute shell command
  5519. *
  5520. * @param string $command command line
  5521. * @param string $output stdout strings
  5522. * @param int $return_var process exit code
  5523. * @param string $error_output stderr strings
  5524. *
  5525. * @return int exit code
  5526. * @throws elFinderAbortException
  5527. * @author Alexey Sukhotin
  5528. */
  5529. protected function procExec($command, &$output = '', &$return_var = -1, &$error_output = '')
  5530. {
  5531. static $allowed = null;
  5532. if ($allowed === null) {
  5533. if ($allowed = function_exists('proc_open')) {
  5534. if ($disabled = ini_get('disable_functions')) {
  5535. $funcs = array_map('trim', explode(',', $disabled));
  5536. $allowed = !in_array('proc_open', $funcs);
  5537. }
  5538. }
  5539. }
  5540. if (!$allowed) {
  5541. $return_var = -1;
  5542. return $return_var;
  5543. }
  5544. if (!$command) {
  5545. $return_var = 0;
  5546. return $return_var;
  5547. }
  5548. $descriptorspec = array(
  5549. 0 => array("pipe", "r"), // stdin
  5550. 1 => array("pipe", "w"), // stdout
  5551. 2 => array("pipe", "w") // stderr
  5552. );
  5553. $process = proc_open($command, $descriptorspec, $pipes, null, null);
  5554. if (is_resource($process)) {
  5555. stream_set_blocking($pipes[1], 0);
  5556. stream_set_blocking($pipes[2], 0);
  5557. fclose($pipes[0]);
  5558. $tmpout = '';
  5559. $tmperr = '';
  5560. while (feof($pipes[1]) === false || feof($pipes[2]) === false) {
  5561. elFinder::extendTimeLimit();
  5562. $read = array($pipes[1], $pipes[2]);
  5563. $write = null;
  5564. $except = null;
  5565. $ret = stream_select($read, $write, $except, 1);
  5566. if ($ret === false) {
  5567. // error
  5568. break;
  5569. } else if ($ret === 0) {
  5570. // timeout
  5571. continue;
  5572. } else {
  5573. foreach ($read as $sock) {
  5574. if ($sock === $pipes[1]) {
  5575. $tmpout .= fread($sock, 4096);
  5576. } else if ($sock === $pipes[2]) {
  5577. $tmperr .= fread($sock, 4096);
  5578. }
  5579. }
  5580. }
  5581. }
  5582. fclose($pipes[1]);
  5583. fclose($pipes[2]);
  5584. $output = $tmpout;
  5585. $error_output = $tmperr;
  5586. $return_var = proc_close($process);
  5587. } else {
  5588. $return_var = -1;
  5589. }
  5590. return $return_var;
  5591. }
  5592. /**
  5593. * Remove thumbnail, also remove recursively if stat is directory
  5594. *
  5595. * @param array $stat file stat
  5596. *
  5597. * @return void
  5598. * @throws elFinderAbortException
  5599. * @author Dmitry (dio) Levashov
  5600. * @author Naoki Sawada
  5601. * @author Troex Nevelin
  5602. */
  5603. protected function rmTmb($stat)
  5604. {
  5605. if ($this->tmbPathWritable) {
  5606. if ($stat['mime'] === 'directory') {
  5607. foreach ($this->scandirCE($this->decode($stat['hash'])) as $p) {
  5608. elFinder::extendTimeLimit(30);
  5609. $name = $this->basenameCE($p);
  5610. $name != '.' && $name != '..' && $this->rmTmb($this->stat($p));
  5611. }
  5612. } else if (!empty($stat['tmb']) && $stat['tmb'] != "1") {
  5613. $tmb = $this->tmbPath . DIRECTORY_SEPARATOR . rawurldecode($stat['tmb']);
  5614. file_exists($tmb) && unlink($tmb);
  5615. clearstatcache();
  5616. }
  5617. }
  5618. }
  5619. /**
  5620. * Create an gd image according to the specified mime type
  5621. *
  5622. * @param string $path image file
  5623. * @param string $mime
  5624. *
  5625. * @return resource|false GD image resource identifier
  5626. */
  5627. protected function gdImageCreate($path, $mime)
  5628. {
  5629. switch ($mime) {
  5630. case 'image/jpeg':
  5631. return imagecreatefromjpeg($path);
  5632. case 'image/png':
  5633. return imagecreatefrompng($path);
  5634. case 'image/gif':
  5635. return imagecreatefromgif($path);
  5636. case 'image/x-ms-bmp':
  5637. if (!function_exists('imagecreatefrombmp')) {
  5638. include_once dirname(__FILE__) . '/libs/GdBmp.php';
  5639. }
  5640. return imagecreatefrombmp($path);
  5641. case 'image/xbm':
  5642. return imagecreatefromxbm($path);
  5643. case 'image/xpm':
  5644. return imagecreatefromxpm($path);
  5645. }
  5646. return false;
  5647. }
  5648. /**
  5649. * Output gd image to file
  5650. *
  5651. * @param resource $image gd image resource
  5652. * @param string $filename The path to save the file to.
  5653. * @param string $destformat The Image type to use for $filename
  5654. * @param string $mime The original image mime type
  5655. * @param int $jpgQuality JEPG quality (1-100)
  5656. *
  5657. * @return bool
  5658. */
  5659. protected function gdImage($image, $filename, $destformat, $mime, $jpgQuality = null)
  5660. {
  5661. if (!$jpgQuality) {
  5662. $jpgQuality = $this->options['jpgQuality'];
  5663. }
  5664. if ($destformat) {
  5665. switch ($destformat) {
  5666. case 'jpg':
  5667. $mime = 'image/jpeg';
  5668. break;
  5669. case 'gif':
  5670. $mime = 'image/gif';
  5671. break;
  5672. case 'png':
  5673. default:
  5674. $mime = 'image/png';
  5675. break;
  5676. }
  5677. }
  5678. switch ($mime) {
  5679. case 'image/gif':
  5680. return imagegif($image, $filename);
  5681. case 'image/jpeg':
  5682. if ($this->options['jpgProgressive']) {
  5683. imageinterlace($image, true);
  5684. }
  5685. return imagejpeg($image, $filename, $jpgQuality);
  5686. case 'image/wbmp':
  5687. return imagewbmp($image, $filename);
  5688. case 'image/png':
  5689. default:
  5690. return imagepng($image, $filename);
  5691. }
  5692. }
  5693. /**
  5694. * Output imagick image to file
  5695. *
  5696. * @param imagick $img imagick image resource
  5697. * @param string $filename The path to save the file to.
  5698. * @param string $destformat The Image type to use for $filename
  5699. * @param int $jpgQuality JEPG quality (1-100)
  5700. *
  5701. * @return bool
  5702. */
  5703. protected function imagickImage($img, $filename, $destformat, $jpgQuality = null)
  5704. {
  5705. if (!$jpgQuality) {
  5706. $jpgQuality = $this->options['jpgQuality'];
  5707. }
  5708. try {
  5709. if ($destformat) {
  5710. if ($destformat === 'gif') {
  5711. $img->setImageFormat('gif');
  5712. } else if ($destformat === 'png') {
  5713. $img->setImageFormat('png');
  5714. } else if ($destformat === 'jpg') {
  5715. $img->setImageFormat('jpeg');
  5716. }
  5717. }
  5718. if (strtoupper($img->getImageFormat()) === 'JPEG') {
  5719. $img->setImageCompression(imagick::COMPRESSION_JPEG);
  5720. $img->setImageCompressionQuality($jpgQuality);
  5721. if ($this->options['jpgProgressive']) {
  5722. $img->setInterlaceScheme(Imagick::INTERLACE_PLANE);
  5723. }
  5724. try {
  5725. $orientation = $img->getImageOrientation();
  5726. } catch (ImagickException $e) {
  5727. $orientation = 0;
  5728. }
  5729. $img->stripImage();
  5730. if ($orientation) {
  5731. $img->setImageOrientation($orientation);
  5732. }
  5733. }
  5734. $result = $img->writeImage($filename);
  5735. } catch (Exception $e) {
  5736. $result = false;
  5737. }
  5738. return $result;
  5739. }
  5740. /**
  5741. * Assign the proper background to a gd image
  5742. *
  5743. * @param resource $image gd image resource
  5744. * @param string $bgcolor background color in #rrggbb format
  5745. */
  5746. protected function gdImageBackground($image, $bgcolor)
  5747. {
  5748. if ($bgcolor === 'transparent') {
  5749. imagealphablending($image, false);
  5750. imagesavealpha($image, true);
  5751. } else {
  5752. list($r, $g, $b) = sscanf($bgcolor, "#%02x%02x%02x");
  5753. $bgcolor1 = imagecolorallocate($image, $r, $g, $b);
  5754. imagefill($image, 0, 0, $bgcolor1);
  5755. }
  5756. }
  5757. /**
  5758. * Prepare variables for exec convert of ImageMagick
  5759. *
  5760. * @param string $path
  5761. * @param string $destformat
  5762. * @param int $jpgQuality
  5763. * @param array $imageSize
  5764. * @param null $mime
  5765. *
  5766. * @return array
  5767. * @throws elFinderAbortException
  5768. */
  5769. protected function imageMagickConvertPrepare($path, $destformat, $jpgQuality, $imageSize = null, $mime = null)
  5770. {
  5771. if (is_null($imageSize)) {
  5772. $imageSize = getimagesize($path);
  5773. }
  5774. if (is_null($mime)) {
  5775. $mime = $this->mimetype($path);
  5776. }
  5777. $srcType = $this->getExtentionByMime($mime, ':');
  5778. $ani = false;
  5779. if (preg_match('/^(?:gif|png|ico)/', $srcType)) {
  5780. $cmd = ELFINDER_IDENTIFY_PATH . ' -- ' . escapeshellarg($srcType . $path);
  5781. if ($this->procExec($cmd, $o) === 0) {
  5782. $ani = preg_split('/(?:\r\n|\n|\r)/', trim($o));
  5783. if (count($ani) < 2) {
  5784. $ani = false;
  5785. }
  5786. }
  5787. }
  5788. $coalesce = $index = $interlace = '';
  5789. $deconstruct = ' +repage';
  5790. if ($ani && $destformat !== 'png'/* not createTmb */) {
  5791. if (is_null($destformat)) {
  5792. $coalesce = ' -coalesce -repage 0x0';
  5793. $deconstruct = ' +repage -deconstruct -layers optimize';
  5794. } else if ($imageSize) {
  5795. if ($srcType === 'ico:') {
  5796. $index = '[0]';
  5797. foreach ($ani as $_i => $_info) {
  5798. if (preg_match('/ (\d+)x(\d+) /', $_info, $m)) {
  5799. if ($m[1] == $imageSize[0] && $m[2] == $imageSize[1]) {
  5800. $index = '[' . $_i . ']';
  5801. break;
  5802. }
  5803. }
  5804. }
  5805. }
  5806. }
  5807. } else {
  5808. $index = '[0]';
  5809. }
  5810. if ($imageSize && ($imageSize[2] === IMAGETYPE_JPEG || $imageSize[2] === IMAGETYPE_JPEG2000)) {
  5811. $jpgQuality = ' -quality ' . $jpgQuality;
  5812. if ($this->options['jpgProgressive']) {
  5813. $interlace = ' -interlace Plane';
  5814. }
  5815. } else {
  5816. $jpgQuality = '';
  5817. }
  5818. $quotedPath = escapeshellarg($srcType . $path . $index);
  5819. $quotedDstPath = escapeshellarg(($destformat ? ($destformat . ':') : $srcType) . $path);
  5820. return compact('ani', 'index', 'coalesce', 'deconstruct', 'jpgQuality', 'quotedPath', 'quotedDstPath', 'interlace');
  5821. }
  5822. /*********************** misc *************************/
  5823. /**
  5824. * Return smart formatted date
  5825. *
  5826. * @param int $ts file timestamp
  5827. *
  5828. * @return string
  5829. * @author Dmitry (dio) Levashov
  5830. **/
  5831. // protected function formatDate($ts) {
  5832. // if ($ts > $this->today) {
  5833. // return 'Today '.date($this->options['timeFormat'], $ts);
  5834. // }
  5835. //
  5836. // if ($ts > $this->yesterday) {
  5837. // return 'Yesterday '.date($this->options['timeFormat'], $ts);
  5838. // }
  5839. //
  5840. // return date($this->options['dateFormat'], $ts);
  5841. // }
  5842. /**
  5843. * Find position of first occurrence of string in a string with multibyte support
  5844. *
  5845. * @param string $haystack The string being checked.
  5846. * @param string $needle The string to find in haystack.
  5847. * @param int $offset The search offset. If it is not specified, 0 is used.
  5848. *
  5849. * @return int|bool
  5850. * @author Alexey Sukhotin
  5851. **/
  5852. protected function stripos($haystack, $needle, $offset = 0)
  5853. {
  5854. if (function_exists('mb_stripos')) {
  5855. return mb_stripos($haystack, $needle, $offset, 'UTF-8');
  5856. } else if (function_exists('mb_strtolower') && function_exists('mb_strpos')) {
  5857. return mb_strpos(mb_strtolower($haystack, 'UTF-8'), mb_strtolower($needle, 'UTF-8'), $offset);
  5858. }
  5859. return stripos($haystack, $needle, $offset);
  5860. }
  5861. /**
  5862. * Default serach match method (name match)
  5863. *
  5864. * @param String $name Item name
  5865. * @param String $query Query word
  5866. * @param String $path Item path
  5867. *
  5868. * @return bool @return bool
  5869. */
  5870. protected function searchMatchName($name, $query, $path)
  5871. {
  5872. return $this->stripos($name, $query) !== false;
  5873. }
  5874. /**
  5875. * Get server side available archivers
  5876. *
  5877. * @param bool $use_cache
  5878. *
  5879. * @return array
  5880. * @throws elFinderAbortException
  5881. */
  5882. protected function getArchivers($use_cache = true)
  5883. {
  5884. $sessionKey = 'archivers';
  5885. if ($use_cache) {
  5886. if (isset($this->options['archivers']) && is_array($this->options['archivers']) && $this->options['archivers']) {
  5887. $cache = $this->options['archivers'];
  5888. } else {
  5889. $cache = elFinder::$archivers;
  5890. }
  5891. if ($cache) {
  5892. return $cache;
  5893. } else {
  5894. if ($cache = $this->session->get($sessionKey, array())) {
  5895. return elFinder::$archivers = $cache;
  5896. }
  5897. }
  5898. }
  5899. $arcs = array(
  5900. 'create' => array(),
  5901. 'extract' => array()
  5902. );
  5903. if ($this->procExec('') === 0) {
  5904. $this->procExec(ELFINDER_TAR_PATH . ' --version', $o, $ctar);
  5905. if ($ctar == 0) {
  5906. $arcs['create']['application/x-tar'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-cf', 'ext' => 'tar');
  5907. $arcs['extract']['application/x-tar'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-xf', 'ext' => 'tar', 'toSpec' => '-C ');
  5908. unset($o);
  5909. $this->procExec(ELFINDER_GZIP_PATH . ' --version', $o, $c);
  5910. if ($c == 0) {
  5911. $arcs['create']['application/x-gzip'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-czf', 'ext' => 'tgz');
  5912. $arcs['extract']['application/x-gzip'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-xzf', 'ext' => 'tgz', 'toSpec' => '-C ');
  5913. }
  5914. unset($o);
  5915. $this->procExec(ELFINDER_BZIP2_PATH . ' --version', $o, $c);
  5916. if ($c == 0) {
  5917. $arcs['create']['application/x-bzip2'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-cjf', 'ext' => 'tbz');
  5918. $arcs['extract']['application/x-bzip2'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-xjf', 'ext' => 'tbz', 'toSpec' => '-C ');
  5919. }
  5920. unset($o);
  5921. $this->procExec(ELFINDER_XZ_PATH . ' --version', $o, $c);
  5922. if ($c == 0) {
  5923. $arcs['create']['application/x-xz'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-cJf', 'ext' => 'xz');
  5924. $arcs['extract']['application/x-xz'] = array('cmd' => ELFINDER_TAR_PATH, 'argc' => '-xJf', 'ext' => 'xz', 'toSpec' => '-C ');
  5925. }
  5926. }
  5927. unset($o);
  5928. $this->procExec(ELFINDER_ZIP_PATH . ' -h', $o, $c);
  5929. if ($c == 0) {
  5930. $arcs['create']['application/zip'] = array('cmd' => ELFINDER_ZIP_PATH, 'argc' => '-r9 -q', 'ext' => 'zip');
  5931. }
  5932. unset($o);
  5933. $this->procExec(ELFINDER_UNZIP_PATH . ' --help', $o, $c);
  5934. if ($c == 0) {
  5935. $arcs['extract']['application/zip'] = array('cmd' => ELFINDER_UNZIP_PATH, 'argc' => '-q', 'ext' => 'zip', 'toSpec' => '-d ');
  5936. }
  5937. unset($o);
  5938. $this->procExec(ELFINDER_RAR_PATH . ' --version', $o, $c);
  5939. if ($c == 0 || $c == 7) {
  5940. $arcs['create']['application/x-rar'] = array('cmd' => ELFINDER_RAR_PATH, 'argc' => 'a -inul', 'ext' => 'rar');
  5941. }
  5942. unset($o);
  5943. $this->procExec(ELFINDER_UNRAR_PATH, $o, $c);
  5944. if ($c == 0 || $c == 7) {
  5945. $arcs['extract']['application/x-rar'] = array('cmd' => ELFINDER_UNRAR_PATH, 'argc' => 'x -y', 'ext' => 'rar', 'toSpec' => '');
  5946. }
  5947. unset($o);
  5948. $this->procExec(ELFINDER_7Z_PATH, $o, $c);
  5949. if ($c == 0) {
  5950. $arcs['create']['application/x-7z-compressed'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'a', 'ext' => '7z');
  5951. $arcs['extract']['application/x-7z-compressed'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'x -y', 'ext' => '7z', 'toSpec' => '-o');
  5952. if (empty($arcs['create']['application/zip'])) {
  5953. $arcs['create']['application/zip'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'a -tzip', 'ext' => 'zip');
  5954. }
  5955. if (empty($arcs['extract']['application/zip'])) {
  5956. $arcs['extract']['application/zip'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'x -tzip -y', 'ext' => 'zip', 'toSpec' => '-o');
  5957. }
  5958. if (empty($arcs['create']['application/x-tar'])) {
  5959. $arcs['create']['application/x-tar'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'a -ttar', 'ext' => 'tar');
  5960. }
  5961. if (empty($arcs['extract']['application/x-tar'])) {
  5962. $arcs['extract']['application/x-tar'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'x -ttar -y', 'ext' => 'tar', 'toSpec' => '-o');
  5963. }
  5964. if (substr(PHP_OS, 0, 3) === 'WIN' && empty($arcs['extract']['application/x-rar'])) {
  5965. $arcs['extract']['application/x-rar'] = array('cmd' => ELFINDER_7Z_PATH, 'argc' => 'x -trar -y', 'ext' => 'rar', 'toSpec' => '-o');
  5966. }
  5967. }
  5968. }
  5969. // Use PHP ZipArchive Class
  5970. if (class_exists('ZipArchive', false)) {
  5971. if (empty($arcs['create']['application/zip'])) {
  5972. $arcs['create']['application/zip'] = array('cmd' => 'phpfunction', 'argc' => array('self', 'zipArchiveZip'), 'ext' => 'zip');
  5973. }
  5974. if (empty($arcs['extract']['application/zip'])) {
  5975. $arcs['extract']['application/zip'] = array('cmd' => 'phpfunction', 'argc' => array('self', 'zipArchiveUnzip'), 'ext' => 'zip');
  5976. }
  5977. }
  5978. $this->session->set($sessionKey, $arcs);
  5979. return elFinder::$archivers = $arcs;
  5980. }
  5981. /**
  5982. * Resolve relative / (Unix-like)absolute path
  5983. *
  5984. * @param string $path target path
  5985. * @param string $base base path
  5986. *
  5987. * @return string
  5988. */
  5989. protected function getFullPath($path, $base)
  5990. {
  5991. $separator = $this->separator;
  5992. $systemroot = $this->systemRoot;
  5993. $base = (string)$base;
  5994. if ($base[0] === $separator && substr($base, 0, strlen($systemroot)) !== $systemroot) {
  5995. $base = $systemroot . substr($base, 1);
  5996. }
  5997. if ($base !== $systemroot) {
  5998. $base = rtrim($base, $separator);
  5999. }
  6000. // 'Here'
  6001. if ($path === '' || $path === '.' . $separator) return $base;
  6002. $sepquoted = preg_quote($separator, '#');
  6003. if (substr($path, 0, 3) === '..' . $separator) {
  6004. $path = $base . $separator . $path;
  6005. }
  6006. // normalize `/../`
  6007. $normreg = '#(' . $sepquoted . ')[^' . $sepquoted . ']+' . $sepquoted . '\.\.' . $sepquoted . '#'; // '#(/)[^\/]+/\.\./#'
  6008. while (preg_match($normreg, $path)) {
  6009. $path = preg_replace($normreg, '$1', $path, 1);
  6010. }
  6011. if ($path !== $systemroot) {
  6012. $path = rtrim($path, $separator);
  6013. }
  6014. // Absolute path
  6015. if ($path[0] === $separator || strpos($path, $systemroot) === 0) {
  6016. return $path;
  6017. }
  6018. $preg_separator = '#' . $sepquoted . '#';
  6019. // Relative path from 'Here'
  6020. if (substr($path, 0, 2) === '.' . $separator || $path[0] !== '.') {
  6021. $arrn = preg_split($preg_separator, $path, -1, PREG_SPLIT_NO_EMPTY);
  6022. if ($arrn[0] !== '.') {
  6023. array_unshift($arrn, '.');
  6024. }
  6025. $arrn[0] = rtrim($base, $separator);
  6026. return join($separator, $arrn);
  6027. }
  6028. return $path;
  6029. }
  6030. /**
  6031. * Remove directory recursive on local file system
  6032. *
  6033. * @param string $dir Target dirctory path
  6034. *
  6035. * @return boolean
  6036. * @throws elFinderAbortException
  6037. * @author Naoki Sawada
  6038. */
  6039. public function rmdirRecursive($dir)
  6040. {
  6041. return self::localRmdirRecursive($dir);
  6042. }
  6043. /**
  6044. * Create archive and return its path
  6045. *
  6046. * @param string $dir target dir
  6047. * @param array $files files names list
  6048. * @param string $name archive name
  6049. * @param array $arc archiver options
  6050. *
  6051. * @return string|bool
  6052. * @throws elFinderAbortException
  6053. * @author Dmitry (dio) Levashov,
  6054. * @author Alexey Sukhotin
  6055. * @author Naoki Sawada
  6056. */
  6057. protected function makeArchive($dir, $files, $name, $arc)
  6058. {
  6059. if ($arc['cmd'] === 'phpfunction') {
  6060. if (is_callable($arc['argc'])) {
  6061. call_user_func_array($arc['argc'], array($dir, $files, $name));
  6062. }
  6063. } else {
  6064. $cwd = getcwd();
  6065. if (chdir($dir)) {
  6066. foreach ($files as $i => $file) {
  6067. $files[$i] = '.' . DIRECTORY_SEPARATOR . basename($file);
  6068. }
  6069. $files = array_map('escapeshellarg', $files);
  6070. $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg($name) . ' ' . implode(' ', $files);
  6071. $this->procExec($cmd, $o, $c);
  6072. chdir($cwd);
  6073. } else {
  6074. return false;
  6075. }
  6076. }
  6077. $path = $dir . DIRECTORY_SEPARATOR . $name;
  6078. return file_exists($path) ? $path : false;
  6079. }
  6080. /**
  6081. * Unpack archive
  6082. *
  6083. * @param string $path archive path
  6084. * @param array $arc archiver command and arguments (same as in $this->archivers)
  6085. * @param bool|string $mode bool: remove archive ( unlink($path) ) | string: extract to directory
  6086. *
  6087. * @return void
  6088. * @throws elFinderAbortException
  6089. * @author Dmitry (dio) Levashov
  6090. * @author Alexey Sukhotin
  6091. * @author Naoki Sawada
  6092. */
  6093. protected function unpackArchive($path, $arc, $mode = true)
  6094. {
  6095. if (is_string($mode)) {
  6096. $dir = $mode;
  6097. $chdir = null;
  6098. $remove = false;
  6099. } else {
  6100. $dir = dirname($path);
  6101. $chdir = $dir;
  6102. $remove = $mode;
  6103. }
  6104. $dir = realpath($dir);
  6105. $path = realpath($path);
  6106. if ($arc['cmd'] === 'phpfunction') {
  6107. if (is_callable($arc['argc'])) {
  6108. call_user_func_array($arc['argc'], array($path, $dir));
  6109. }
  6110. } else {
  6111. $cwd = getcwd();
  6112. if (!$chdir || chdir($dir)) {
  6113. if ($chdir) {
  6114. $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg(basename($path));
  6115. } else {
  6116. $cmd = $arc['cmd'] . ' ' . $arc['argc'] . ' ' . escapeshellarg($path) . ' ' . $arc['toSpec'] . escapeshellarg($dir);
  6117. }
  6118. $this->procExec($cmd, $o, $c);
  6119. $chdir && chdir($cwd);
  6120. }
  6121. }
  6122. $remove && unlink($path);
  6123. }
  6124. /**
  6125. * Check and filter the extracted items
  6126. *
  6127. * @param string $path target local path
  6128. * @param array $checks types to check default: ['symlink', 'name', 'writable', 'mime']
  6129. *
  6130. * @return array ['symlinks' => [], 'names' => [], 'writables' => [], 'mimes' => [], 'rmNames' => [], 'totalSize' => 0]
  6131. * @throws elFinderAbortException
  6132. * @throws Exception
  6133. * @author Naoki Sawada
  6134. */
  6135. protected function checkExtractItems($path, $checks = null)
  6136. {
  6137. if (is_null($checks) || !is_array($checks)) {
  6138. $checks = array('symlink', 'name', 'writable', 'mime');
  6139. }
  6140. $chkSymlink = in_array('symlink', $checks);
  6141. $chkName = in_array('name', $checks);
  6142. $chkWritable = in_array('writable', $checks);
  6143. $chkMime = in_array('mime', $checks);
  6144. $res = array(
  6145. 'symlinks' => array(),
  6146. 'names' => array(),
  6147. 'writables' => array(),
  6148. 'mimes' => array(),
  6149. 'rmNames' => array(),
  6150. 'totalSize' => 0
  6151. );
  6152. if (is_dir($path)) {
  6153. foreach (self::localScandir($path) as $name) {
  6154. $p = $path . DIRECTORY_SEPARATOR . $name;
  6155. if (!is_readable($p)) {
  6156. // Perhaps a symbolic link to open_basedir restricted location
  6157. self::localRmdirRecursive($p);
  6158. $res['symlinks'][] = $p;
  6159. $res['rmNames'][] = $name;
  6160. continue;
  6161. }
  6162. if ($chkSymlink && is_link($p)) {
  6163. self::localRmdirRecursive($p);
  6164. $res['symlinks'][] = $p;
  6165. $res['rmNames'][] = $name;
  6166. continue;
  6167. }
  6168. $isDir = is_dir($p);
  6169. if ($chkName && !$this->nameAccepted($name, $isDir)) {
  6170. self::localRmdirRecursive($p);
  6171. $res['names'][] = $p;
  6172. $res['rmNames'][] = $name;
  6173. continue;
  6174. }
  6175. if ($chkWritable && !$this->attr($p, 'write', null, $isDir)) {
  6176. self::localRmdirRecursive($p);
  6177. $res['writables'][] = $p;
  6178. $res['rmNames'][] = $name;
  6179. continue;
  6180. }
  6181. if ($chkMime && ($mimeByName = elFinderVolumeDriver::mimetypeInternalDetect($name)) && !$this->allowPutMime($mimeByName)) {
  6182. self::localRmdirRecursive($p);
  6183. $res['mimes'][] = $p;
  6184. $res['rmNames'][] = $name;
  6185. continue;
  6186. }
  6187. if ($isDir) {
  6188. $cRes = $this->checkExtractItems($p, $checks);
  6189. foreach ($cRes as $k => $v) {
  6190. if (is_array($v)) {
  6191. $res[$k] = array_merge($res[$k], $cRes[$k]);
  6192. } else {
  6193. $res[$k] += $cRes[$k];
  6194. }
  6195. }
  6196. } else {
  6197. $res['totalSize'] += (int)sprintf('%u', filesize($p));
  6198. }
  6199. }
  6200. $res['rmNames'] = array_unique($res['rmNames']);
  6201. } else {
  6202. $name = basename($path);
  6203. if ($chkSymlink && is_link($path)) {
  6204. unlink($path);
  6205. $res['symlinks'][] = $path;
  6206. $res['rmNames'][] = basename($path);
  6207. } else if ($chkName && !$this->nameAccepted($name, false)) {
  6208. unlink($path);
  6209. $res['names'][] = $path;
  6210. $res['rmNames'][] = $name;
  6211. } else if ($chkWritable && !$this->attr($path, 'write', null, false)) {
  6212. unlink($path);
  6213. $res['writables'][] = $path;
  6214. $res['rmNames'][] = $name;
  6215. } else if ($chkMime && ($mimeByName = elFinderVolumeDriver::mimetypeInternalDetect($name)) && !$this->allowPutMime($mimeByName)) {
  6216. unlink($path);
  6217. $res['mimes'][] = $path;
  6218. $res['rmNames'][] = $name;
  6219. } else {
  6220. $res['totalSize'] += (int)sprintf('%u', filesize($path));
  6221. }
  6222. }
  6223. return $res;
  6224. }
  6225. /**
  6226. * Return files of target directory that is dotfiles excludes.
  6227. *
  6228. * @param string $dir target directory path
  6229. *
  6230. * @return array
  6231. * @throws Exception
  6232. * @author Naoki Sawada
  6233. */
  6234. protected static function localScandir($dir)
  6235. {
  6236. // PHP function scandir() is not work well in specific environment. I dont know why.
  6237. // ref. https://github.com/Studio-42/elFinder/issues/1248
  6238. $files = array();
  6239. if ($dh = opendir($dir)) {
  6240. while (false !== ($file = readdir($dh))) {
  6241. if ($file !== '.' && $file !== '..') {
  6242. $files[] = $file;
  6243. }
  6244. }
  6245. closedir($dh);
  6246. } else {
  6247. throw new Exception('Can not open local directory.');
  6248. }
  6249. return $files;
  6250. }
  6251. /**
  6252. * Remove directory recursive on local file system
  6253. *
  6254. * @param string $dir Target dirctory path
  6255. *
  6256. * @return boolean
  6257. * @throws elFinderAbortException
  6258. * @author Naoki Sawada
  6259. */
  6260. protected static function localRmdirRecursive($dir)
  6261. {
  6262. // try system command
  6263. if (is_callable('exec')) {
  6264. $o = '';
  6265. $r = 1;
  6266. if (substr(PHP_OS, 0, 3) === 'WIN') {
  6267. if (!is_link($dir) && is_dir($dir)) {
  6268. exec('rd /S /Q ' . escapeshellarg($dir), $o, $r);
  6269. } else {
  6270. exec('del /F /Q ' . escapeshellarg($dir), $o, $r);
  6271. }
  6272. } else {
  6273. exec('rm -rf ' . escapeshellarg($dir), $o, $r);
  6274. }
  6275. if ($r === 0) {
  6276. return true;
  6277. }
  6278. }
  6279. if (!is_link($dir) && is_dir($dir)) {
  6280. chmod($dir, 0777);
  6281. if ($handle = opendir($dir)) {
  6282. while (false !== ($file = readdir($handle))) {
  6283. if ($file === '.' || $file === '..') {
  6284. continue;
  6285. }
  6286. elFinder::extendTimeLimit(30);
  6287. $path = $dir . DIRECTORY_SEPARATOR . $file;
  6288. if (!is_link($dir) && is_dir($path)) {
  6289. self::localRmdirRecursive($path);
  6290. } else {
  6291. chmod($path, 0666);
  6292. unlink($path);
  6293. }
  6294. }
  6295. closedir($handle);
  6296. }
  6297. return rmdir($dir);
  6298. } else {
  6299. chmod($dir, 0666);
  6300. return unlink($dir);
  6301. }
  6302. }
  6303. /**
  6304. * Move item recursive on local file system
  6305. *
  6306. * @param string $src
  6307. * @param string $target
  6308. * @param bool $overWrite
  6309. * @param bool $copyJoin
  6310. *
  6311. * @return boolean
  6312. * @throws elFinderAbortException
  6313. * @throws Exception
  6314. * @author Naoki Sawada
  6315. */
  6316. protected static function localMoveRecursive($src, $target, $overWrite = true, $copyJoin = true)
  6317. {
  6318. $res = false;
  6319. if (!file_exists($target)) {
  6320. return rename($src, $target);
  6321. }
  6322. if (!$copyJoin || !is_dir($target)) {
  6323. if ($overWrite) {
  6324. if (is_dir($target)) {
  6325. $del = self::localRmdirRecursive($target);
  6326. } else {
  6327. $del = unlink($target);
  6328. }
  6329. if ($del) {
  6330. return rename($src, $target);
  6331. }
  6332. }
  6333. } else {
  6334. foreach (self::localScandir($src) as $item) {
  6335. $res |= self::localMoveRecursive($src . DIRECTORY_SEPARATOR . $item, $target . DIRECTORY_SEPARATOR . $item, $overWrite, $copyJoin);
  6336. }
  6337. }
  6338. return (bool)$res;
  6339. }
  6340. /**
  6341. * Create Zip archive using PHP class ZipArchive
  6342. *
  6343. * @param string $dir target dir
  6344. * @param array $files files names list
  6345. * @param string|object $zipPath Zip archive name
  6346. *
  6347. * @return bool
  6348. * @author Naoki Sawada
  6349. */
  6350. protected static function zipArchiveZip($dir, $files, $zipPath)
  6351. {
  6352. try {
  6353. if ($start = is_string($zipPath)) {
  6354. $zip = new ZipArchive();
  6355. if ($zip->open($dir . DIRECTORY_SEPARATOR . $zipPath, ZipArchive::CREATE) !== true) {
  6356. $zip = false;
  6357. }
  6358. } else {
  6359. $zip = $zipPath;
  6360. }
  6361. if ($zip) {
  6362. foreach ($files as $file) {
  6363. $path = $dir . DIRECTORY_SEPARATOR . $file;
  6364. if (is_dir($path)) {
  6365. $zip->addEmptyDir($file);
  6366. $_files = array();
  6367. if ($handle = opendir($path)) {
  6368. while (false !== ($entry = readdir($handle))) {
  6369. if ($entry !== "." && $entry !== "..") {
  6370. $_files[] = $file . DIRECTORY_SEPARATOR . $entry;
  6371. }
  6372. }
  6373. closedir($handle);
  6374. }
  6375. if ($_files) {
  6376. self::zipArchiveZip($dir, $_files, $zip);
  6377. }
  6378. } else {
  6379. $zip->addFile($path, $file);
  6380. }
  6381. }
  6382. $start && $zip->close();
  6383. }
  6384. } catch (Exception $e) {
  6385. return false;
  6386. }
  6387. return true;
  6388. }
  6389. /**
  6390. * Unpack Zip archive using PHP class ZipArchive
  6391. *
  6392. * @param string $zipPath Zip archive name
  6393. * @param string $toDir Extract to path
  6394. *
  6395. * @return bool
  6396. * @author Naoki Sawada
  6397. */
  6398. protected static function zipArchiveUnzip($zipPath, $toDir)
  6399. {
  6400. try {
  6401. $zip = new ZipArchive();
  6402. if ($zip->open($zipPath) === true) {
  6403. $zip->extractTo($toDir);
  6404. $zip->close();
  6405. }
  6406. } catch (Exception $e) {
  6407. return false;
  6408. }
  6409. return true;
  6410. }
  6411. /**
  6412. * Recursive symlinks search
  6413. *
  6414. * @param string $path file/dir path
  6415. *
  6416. * @return bool
  6417. * @throws Exception
  6418. * @author Dmitry (dio) Levashov
  6419. */
  6420. protected static function localFindSymlinks($path)
  6421. {
  6422. if (is_link($path)) {
  6423. return true;
  6424. }
  6425. if (is_dir($path)) {
  6426. foreach (self::localScandir($path) as $name) {
  6427. $p = $path . DIRECTORY_SEPARATOR . $name;
  6428. if (is_link($p)) {
  6429. return true;
  6430. }
  6431. if (is_dir($p) && self::localFindSymlinks($p)) {
  6432. return true;
  6433. }
  6434. }
  6435. }
  6436. return false;
  6437. }
  6438. /**==================================* abstract methods *====================================**/
  6439. /*********************** paths/urls *************************/
  6440. /**
  6441. * Return parent directory path
  6442. *
  6443. * @param string $path file path
  6444. *
  6445. * @return string
  6446. * @author Dmitry (dio) Levashov
  6447. **/
  6448. abstract protected function _dirname($path);
  6449. /**
  6450. * Return file name
  6451. *
  6452. * @param string $path file path
  6453. *
  6454. * @return string
  6455. * @author Dmitry (dio) Levashov
  6456. **/
  6457. abstract protected function _basename($path);
  6458. /**
  6459. * Join dir name and file name and return full path.
  6460. * Some drivers (db) use int as path - so we give to concat path to driver itself
  6461. *
  6462. * @param string $dir dir path
  6463. * @param string $name file name
  6464. *
  6465. * @return string
  6466. * @author Dmitry (dio) Levashov
  6467. **/
  6468. abstract protected function _joinPath($dir, $name);
  6469. /**
  6470. * Return normalized path
  6471. *
  6472. * @param string $path file path
  6473. *
  6474. * @return string
  6475. * @author Dmitry (dio) Levashov
  6476. **/
  6477. abstract protected function _normpath($path);
  6478. /**
  6479. * Return file path related to root dir
  6480. *
  6481. * @param string $path file path
  6482. *
  6483. * @return string
  6484. * @author Dmitry (dio) Levashov
  6485. **/
  6486. abstract protected function _relpath($path);
  6487. /**
  6488. * Convert path related to root dir into real path
  6489. *
  6490. * @param string $path rel file path
  6491. *
  6492. * @return string
  6493. * @author Dmitry (dio) Levashov
  6494. **/
  6495. abstract protected function _abspath($path);
  6496. /**
  6497. * Return fake path started from root dir.
  6498. * Required to show path on client side.
  6499. *
  6500. * @param string $path file path
  6501. *
  6502. * @return string
  6503. * @author Dmitry (dio) Levashov
  6504. **/
  6505. abstract protected function _path($path);
  6506. /**
  6507. * Return true if $path is children of $parent
  6508. *
  6509. * @param string $path path to check
  6510. * @param string $parent parent path
  6511. *
  6512. * @return bool
  6513. * @author Dmitry (dio) Levashov
  6514. **/
  6515. abstract protected function _inpath($path, $parent);
  6516. /**
  6517. * Return stat for given path.
  6518. * Stat contains following fields:
  6519. * - (int) size file size in b. required
  6520. * - (int) ts file modification time in unix time. required
  6521. * - (string) mime mimetype. required for folders, others - optionally
  6522. * - (bool) read read permissions. required
  6523. * - (bool) write write permissions. required
  6524. * - (bool) locked is object locked. optionally
  6525. * - (bool) hidden is object hidden. optionally
  6526. * - (string) alias for symlinks - link target path relative to root path. optionally
  6527. * - (string) target for symlinks - link target path. optionally
  6528. * If file does not exists - returns empty array or false.
  6529. *
  6530. * @param string $path file path
  6531. *
  6532. * @return array|false
  6533. * @author Dmitry (dio) Levashov
  6534. **/
  6535. abstract protected function _stat($path);
  6536. /***************** file stat ********************/
  6537. /**
  6538. * Return true if path is dir and has at least one childs directory
  6539. *
  6540. * @param string $path dir path
  6541. *
  6542. * @return bool
  6543. * @author Dmitry (dio) Levashov
  6544. **/
  6545. abstract protected function _subdirs($path);
  6546. /**
  6547. * Return object width and height
  6548. * Ususaly used for images, but can be realize for video etc...
  6549. *
  6550. * @param string $path file path
  6551. * @param string $mime file mime type
  6552. *
  6553. * @return string
  6554. * @author Dmitry (dio) Levashov
  6555. **/
  6556. abstract protected function _dimensions($path, $mime);
  6557. /******************** file/dir content *********************/
  6558. /**
  6559. * Return files list in directory
  6560. *
  6561. * @param string $path dir path
  6562. *
  6563. * @return array
  6564. * @author Dmitry (dio) Levashov
  6565. **/
  6566. abstract protected function _scandir($path);
  6567. /**
  6568. * Open file and return file pointer
  6569. *
  6570. * @param string $path file path
  6571. * @param string $mode open mode
  6572. *
  6573. * @return resource|false
  6574. * @author Dmitry (dio) Levashov
  6575. **/
  6576. abstract protected function _fopen($path, $mode = "rb");
  6577. /**
  6578. * Close opened file
  6579. *
  6580. * @param resource $fp file pointer
  6581. * @param string $path file path
  6582. *
  6583. * @return bool
  6584. * @author Dmitry (dio) Levashov
  6585. **/
  6586. abstract protected function _fclose($fp, $path = '');
  6587. /******************** file/dir manipulations *************************/
  6588. /**
  6589. * Create dir and return created dir path or false on failed
  6590. *
  6591. * @param string $path parent dir path
  6592. * @param string $name new directory name
  6593. *
  6594. * @return string|bool
  6595. * @author Dmitry (dio) Levashov
  6596. **/
  6597. abstract protected function _mkdir($path, $name);
  6598. /**
  6599. * Create file and return it's path or false on failed
  6600. *
  6601. * @param string $path parent dir path
  6602. * @param string $name new file name
  6603. *
  6604. * @return string|bool
  6605. * @author Dmitry (dio) Levashov
  6606. **/
  6607. abstract protected function _mkfile($path, $name);
  6608. /**
  6609. * Create symlink
  6610. *
  6611. * @param string $source file to link to
  6612. * @param string $targetDir folder to create link in
  6613. * @param string $name symlink name
  6614. *
  6615. * @return bool
  6616. * @author Dmitry (dio) Levashov
  6617. **/
  6618. abstract protected function _symlink($source, $targetDir, $name);
  6619. /**
  6620. * Copy file into another file (only inside one volume)
  6621. *
  6622. * @param string $source source file path
  6623. * @param $targetDir
  6624. * @param string $name file name
  6625. *
  6626. * @return bool|string
  6627. * @internal param string $target target dir path
  6628. * @author Dmitry (dio) Levashov
  6629. */
  6630. abstract protected function _copy($source, $targetDir, $name);
  6631. /**
  6632. * Move file into another parent dir.
  6633. * Return new file path or false.
  6634. *
  6635. * @param string $source source file path
  6636. * @param $targetDir
  6637. * @param string $name file name
  6638. *
  6639. * @return bool|string
  6640. * @internal param string $target target dir path
  6641. * @author Dmitry (dio) Levashov
  6642. */
  6643. abstract protected function _move($source, $targetDir, $name);
  6644. /**
  6645. * Remove file
  6646. *
  6647. * @param string $path file path
  6648. *
  6649. * @return bool
  6650. * @author Dmitry (dio) Levashov
  6651. **/
  6652. abstract protected function _unlink($path);
  6653. /**
  6654. * Remove dir
  6655. *
  6656. * @param string $path dir path
  6657. *
  6658. * @return bool
  6659. * @author Dmitry (dio) Levashov
  6660. **/
  6661. abstract protected function _rmdir($path);
  6662. /**
  6663. * Create new file and write into it from file pointer.
  6664. * Return new file path or false on error.
  6665. *
  6666. * @param resource $fp file pointer
  6667. * @param string $dir target dir path
  6668. * @param string $name file name
  6669. * @param array $stat file stat (required by some virtual fs)
  6670. *
  6671. * @return bool|string
  6672. * @author Dmitry (dio) Levashov
  6673. **/
  6674. abstract protected function _save($fp, $dir, $name, $stat);
  6675. /**
  6676. * Get file contents
  6677. *
  6678. * @param string $path file path
  6679. *
  6680. * @return string|false
  6681. * @author Dmitry (dio) Levashov
  6682. **/
  6683. abstract protected function _getContents($path);
  6684. /**
  6685. * Write a string to a file
  6686. *
  6687. * @param string $path file path
  6688. * @param string $content new file content
  6689. *
  6690. * @return bool
  6691. * @author Dmitry (dio) Levashov
  6692. **/
  6693. abstract protected function _filePutContents($path, $content);
  6694. /**
  6695. * Extract files from archive
  6696. *
  6697. * @param string $path file path
  6698. * @param array $arc archiver options
  6699. *
  6700. * @return bool
  6701. * @author Dmitry (dio) Levashov,
  6702. * @author Alexey Sukhotin
  6703. **/
  6704. abstract protected function _extract($path, $arc);
  6705. /**
  6706. * Create archive and return its path
  6707. *
  6708. * @param string $dir target dir
  6709. * @param array $files files names list
  6710. * @param string $name archive name
  6711. * @param array $arc archiver options
  6712. *
  6713. * @return string|bool
  6714. * @author Dmitry (dio) Levashov,
  6715. * @author Alexey Sukhotin
  6716. **/
  6717. abstract protected function _archive($dir, $files, $name, $arc);
  6718. /**
  6719. * Detect available archivers
  6720. *
  6721. * @return void
  6722. * @author Dmitry (dio) Levashov,
  6723. * @author Alexey Sukhotin
  6724. **/
  6725. abstract protected function _checkArchivers();
  6726. /**
  6727. * Change file mode (chmod)
  6728. *
  6729. * @param string $path file path
  6730. * @param string $mode octal string such as '0755'
  6731. *
  6732. * @return bool
  6733. * @author David Bartle,
  6734. **/
  6735. abstract protected function _chmod($path, $mode);
  6736. } // END class