elFinder.class.php 164 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848
  1. <?php
  2. /**
  3. * elFinder - file manager for web.
  4. * Core class.
  5. *
  6. * @package elfinder
  7. * @author Dmitry (dio) Levashov
  8. * @author Troex Nevelin
  9. * @author Alexey Sukhotin
  10. **/
  11. class elFinder
  12. {
  13. /**
  14. * API version number
  15. *
  16. * @var float
  17. **/
  18. protected static $ApiVersion = 2.1;
  19. /**
  20. * API version number
  21. *
  22. * @deprecated
  23. * @var string
  24. **/
  25. protected $version;
  26. /**
  27. * API revision that this connector supports all functions
  28. *
  29. * @var integer
  30. */
  31. protected static $ApiRevision = 49;
  32. /**
  33. * Storages (root dirs)
  34. *
  35. * @var array
  36. **/
  37. protected $volumes = array();
  38. /**
  39. * elFinder instance
  40. *
  41. * @var object
  42. */
  43. public static $instance = null;
  44. /**
  45. * Current request args
  46. *
  47. * @var array
  48. */
  49. public static $currentArgs = array();
  50. /**
  51. * Network mount drivers
  52. *
  53. * @var array
  54. */
  55. public static $netDrivers = array();
  56. /**
  57. * elFinder global locale
  58. *
  59. * @var string
  60. */
  61. public static $locale = '';
  62. /**
  63. * elFinderVolumeDriver default mime.type file path
  64. *
  65. * @var string
  66. */
  67. public static $defaultMimefile = '';
  68. /**
  69. * A file save destination path when a temporary content URL is required
  70. * on a network volume or the like
  71. * It can be overwritten by volume route setting
  72. *
  73. * @var string
  74. */
  75. public static $tmpLinkPath = '';
  76. /**
  77. * A file save destination URL when a temporary content URL is required
  78. * on a network volume or the like
  79. * It can be overwritten by volume route setting
  80. *
  81. * @var string
  82. */
  83. public static $tmpLinkUrl = '';
  84. /**
  85. * Temporary content URL lifetime (seconds)
  86. *
  87. * @var integer
  88. */
  89. public static $tmpLinkLifeTime = 3600;
  90. /**
  91. * MIME type list handled as a text file
  92. *
  93. * @var array
  94. */
  95. public static $textMimes = array(
  96. 'application/dash+xml',
  97. 'application/docbook+xml',
  98. 'application/javascript',
  99. 'application/json',
  100. 'application/plt',
  101. 'application/sat',
  102. 'application/sql',
  103. 'application/step',
  104. 'application/vnd.hp-hpgl',
  105. 'application/x-awk',
  106. 'application/x-config',
  107. 'application/x-csh',
  108. 'application/x-empty',
  109. 'application/x-mpegurl',
  110. 'application/x-perl',
  111. 'application/x-php',
  112. 'application/x-web-config',
  113. 'application/xhtml+xml',
  114. 'application/xml',
  115. 'audio/x-mp3-playlist',
  116. 'image/cgm',
  117. 'image/svg+xml',
  118. 'image/vnd.dxf',
  119. 'model/iges'
  120. );
  121. /**
  122. * Maximum memory size to be extended during GD processing
  123. * (0: not expanded, -1: unlimited or memory size notation)
  124. *
  125. * @var integer|string
  126. */
  127. public static $memoryLimitGD = 0;
  128. /**
  129. * Path of current request flag file for abort check
  130. *
  131. * @var string
  132. */
  133. protected static $abortCheckFile = null;
  134. /**
  135. * elFinder session wrapper object
  136. *
  137. * @var elFinderSessionInterface
  138. */
  139. protected $session;
  140. /**
  141. * elFinder global sessionCacheKey
  142. *
  143. * @deprecated
  144. * @var string
  145. */
  146. public static $sessionCacheKey = '';
  147. /**
  148. * Is session closed
  149. *
  150. * @deprecated
  151. * @var bool
  152. */
  153. private static $sessionClosed = false;
  154. /**
  155. * elFinder base64encodeSessionData
  156. * elFinder save session data as `UTF-8`
  157. * If the session storage mechanism of the system does not allow `UTF-8`
  158. * And it must be `true` option 'base64encodeSessionData' of elFinder
  159. * WARNING: When enabling this option, if saving the data passed from the user directly to the session variable,
  160. * it make vulnerable to the object injection attack, so use it carefully.
  161. * see https://github.com/Studio-42/elFinder/issues/2345
  162. *
  163. * @var bool
  164. */
  165. protected static $base64encodeSessionData = false;
  166. /**
  167. * elFinder common tempraly path
  168. *
  169. * @var string
  170. * @default "./.tmp" or sys_get_temp_dir()
  171. **/
  172. protected static $commonTempPath = '';
  173. /**
  174. * Callable function for URL upload filter
  175. * The first argument is a URL and the second argument is an instance of the elFinder class
  176. * A filter should be return true (to allow) / false (to disallow)
  177. *
  178. * @var callable
  179. * @default null
  180. */
  181. protected $urlUploadFilter = null;
  182. /**
  183. * Connection flag files path that connection check of current request
  184. *
  185. * @var string
  186. * @default value of $commonTempPath
  187. */
  188. protected static $connectionFlagsPath = '';
  189. /**
  190. * Additional volume root options for network mounting volume
  191. *
  192. * @var array
  193. */
  194. protected $optionsNetVolumes = array();
  195. /**
  196. * Session key of net mount volumes
  197. *
  198. * @deprecated
  199. * @var string
  200. */
  201. protected $netVolumesSessionKey = '';
  202. /**
  203. * Mounted volumes count
  204. * Required to create unique volume id
  205. *
  206. * @var int
  207. **/
  208. public static $volumesCnt = 1;
  209. /**
  210. * Default root (storage)
  211. *
  212. * @var elFinderVolumeDriver
  213. **/
  214. protected $default = null;
  215. /**
  216. * Commands and required arguments list
  217. *
  218. * @var array
  219. **/
  220. protected $commands = array(
  221. 'abort' => array('id' => true),
  222. 'archive' => array('targets' => true, 'type' => true, 'mimes' => false, 'name' => false),
  223. 'callback' => array('node' => true, 'json' => false, 'bind' => false, 'done' => false),
  224. 'chmod' => array('targets' => true, 'mode' => true),
  225. 'dim' => array('target' => true, 'substitute' => false),
  226. 'duplicate' => array('targets' => true, 'suffix' => false),
  227. 'editor' => array('name' => true, 'method' => true, 'args' => false),
  228. 'extract' => array('target' => true, 'mimes' => false, 'makedir' => false),
  229. 'file' => array('target' => true, 'download' => false, 'cpath' => false, 'onetime' => false),
  230. 'get' => array('target' => true, 'conv' => false),
  231. 'info' => array('targets' => true, 'compare' => false),
  232. 'ls' => array('target' => true, 'mimes' => false, 'intersect' => false),
  233. 'mkdir' => array('target' => true, 'name' => false, 'dirs' => false),
  234. 'mkfile' => array('target' => true, 'name' => true, 'mimes' => false),
  235. 'netmount' => array('protocol' => true, 'host' => true, 'path' => false, 'port' => false, 'user' => false, 'pass' => false, 'alias' => false, 'options' => false),
  236. 'open' => array('target' => false, 'tree' => false, 'init' => false, 'mimes' => false, 'compare' => false),
  237. 'parents' => array('target' => true, 'until' => false),
  238. 'paste' => array('dst' => true, 'targets' => true, 'cut' => false, 'mimes' => false, 'renames' => false, 'hashes' => false, 'suffix' => false),
  239. 'put' => array('target' => true, 'content' => '', 'mimes' => false, 'encoding' => false),
  240. 'rename' => array('target' => true, 'name' => true, 'mimes' => false, 'targets' => false, 'q' => false),
  241. 'resize' => array('target' => true, 'width' => false, 'height' => false, 'mode' => false, 'x' => false, 'y' => false, 'degree' => false, 'quality' => false, 'bg' => false),
  242. 'rm' => array('targets' => true),
  243. 'search' => array('q' => true, 'mimes' => false, 'target' => false, 'type' => false),
  244. 'size' => array('targets' => true),
  245. 'subdirs' => array('targets' => true),
  246. 'tmb' => array('targets' => true),
  247. 'tree' => array('target' => true),
  248. 'upload' => array('target' => true, 'FILES' => true, 'mimes' => false, 'html' => false, 'upload' => false, 'name' => false, 'upload_path' => false, 'chunk' => false, 'cid' => false, 'node' => false, 'renames' => false, 'hashes' => false, 'suffix' => false, 'mtime' => false, 'overwrite' => false, 'contentSaveId' => false),
  249. 'url' => array('target' => true, 'options' => false),
  250. 'zipdl' => array('targets' => true, 'download' => false)
  251. );
  252. /**
  253. * Plugins instance
  254. *
  255. * @var array
  256. **/
  257. protected $plugins = array();
  258. /**
  259. * Commands listeners
  260. *
  261. * @var array
  262. **/
  263. protected $listeners = array();
  264. /**
  265. * script work time for debug
  266. *
  267. * @var string
  268. **/
  269. protected $time = 0;
  270. /**
  271. * Is elFinder init correctly?
  272. *
  273. * @var bool
  274. **/
  275. protected $loaded = false;
  276. /**
  277. * Send debug to client?
  278. *
  279. * @var string
  280. **/
  281. protected $debug = false;
  282. /**
  283. * Call `session_write_close()` before exec command?
  284. *
  285. * @var bool
  286. */
  287. protected $sessionCloseEarlier = true;
  288. /**
  289. * SESSION use commands @see __construct()
  290. *
  291. * @var array
  292. */
  293. protected $sessionUseCmds = array();
  294. /**
  295. * session expires timeout
  296. *
  297. * @var int
  298. **/
  299. protected $timeout = 0;
  300. /**
  301. * Temp dir path for Upload
  302. *
  303. * @var string
  304. */
  305. protected $uploadTempPath = '';
  306. /**
  307. * Max allowed archive files size (0 - no limit)
  308. *
  309. * @var integer
  310. */
  311. protected $maxArcFilesSize = 0;
  312. /**
  313. * undocumented class variable
  314. *
  315. * @var string
  316. **/
  317. protected $uploadDebug = '';
  318. /**
  319. * Max allowed numbar of targets (0 - no limit)
  320. *
  321. * @var integer
  322. */
  323. public $maxTargets = 1000;
  324. /**
  325. * Errors from PHP
  326. *
  327. * @var array
  328. **/
  329. public static $phpErrors = array();
  330. /**
  331. * Errors from not mounted volumes
  332. *
  333. * @var array
  334. **/
  335. public $mountErrors = array();
  336. /**
  337. * Archivers cache
  338. *
  339. * @var array
  340. */
  341. public static $archivers = array();
  342. /**
  343. * URL for callback output window for CORS
  344. * redirect to this URL when callback output
  345. *
  346. * @var string URL
  347. */
  348. protected $callbackWindowURL = '';
  349. /**
  350. * hash of items to unlock on command completion
  351. *
  352. * @var array hashes
  353. */
  354. protected $autoUnlocks = array();
  355. /**
  356. * Item locking expiration (seconds)
  357. * Default: 3600 secs
  358. *
  359. * @var integer
  360. */
  361. protected $itemLockExpire = 3600;
  362. /**
  363. * Additional request querys
  364. *
  365. * @var array|null
  366. */
  367. protected $customData = null;
  368. /**
  369. * Ids to remove of session var "urlContentSaveIds" for contents uploading by URL
  370. *
  371. * @var array
  372. */
  373. protected $removeContentSaveIds = array();
  374. /**
  375. * Flag of throw Error on exec()
  376. *
  377. * @var boolean
  378. */
  379. protected $throwErrorOnExec = false;
  380. // Errors messages
  381. const ERROR_ACCESS_DENIED = 'errAccess';
  382. const ERROR_ARC_MAXSIZE = 'errArcMaxSize';
  383. const ERROR_ARC_SYMLINKS = 'errArcSymlinks';
  384. const ERROR_ARCHIVE = 'errArchive';
  385. const ERROR_ARCHIVE_EXEC = 'errArchiveExec';
  386. const ERROR_ARCHIVE_TYPE = 'errArcType';
  387. const ERROR_CONF = 'errConf';
  388. const ERROR_CONF_NO_JSON = 'errJSON';
  389. const ERROR_CONF_NO_VOL = 'errNoVolumes';
  390. const ERROR_CONV_UTF8 = 'errConvUTF8';
  391. const ERROR_COPY = 'errCopy';
  392. const ERROR_COPY_FROM = 'errCopyFrom';
  393. const ERROR_COPY_ITSELF = 'errCopyInItself';
  394. const ERROR_COPY_TO = 'errCopyTo';
  395. const ERROR_CREATING_TEMP_DIR = 'errCreatingTempDir';
  396. const ERROR_DIR_NOT_FOUND = 'errFolderNotFound';
  397. const ERROR_EXISTS = 'errExists'; // 'File named "$1" already exists.'
  398. const ERROR_EXTRACT = 'errExtract';
  399. const ERROR_EXTRACT_EXEC = 'errExtractExec';
  400. const ERROR_FILE_NOT_FOUND = 'errFileNotFound'; // 'File not found.'
  401. const ERROR_FTP_DOWNLOAD_FILE = 'errFtpDownloadFile';
  402. const ERROR_FTP_MKDIR = 'errFtpMkdir';
  403. const ERROR_FTP_UPLOAD_FILE = 'errFtpUploadFile';
  404. const ERROR_INV_PARAMS = 'errCmdParams';
  405. const ERROR_INVALID_DIRNAME = 'errInvDirname'; // 'Invalid folder name.'
  406. const ERROR_INVALID_NAME = 'errInvName'; // 'Invalid file name.'
  407. const ERROR_LOCKED = 'errLocked'; // '"$1" is locked and can not be renamed, moved or removed.'
  408. const ERROR_MAX_TARGTES = 'errMaxTargets'; // 'Max number of selectable items is $1.'
  409. const ERROR_MKDIR = 'errMkdir';
  410. const ERROR_MKFILE = 'errMkfile';
  411. const ERROR_MKOUTLINK = 'errMkOutLink'; // 'Unable to create a link to outside the volume root.'
  412. const ERROR_MOVE = 'errMove';
  413. const ERROR_NETMOUNT = 'errNetMount';
  414. const ERROR_NETMOUNT_FAILED = 'errNetMountFailed';
  415. const ERROR_NETMOUNT_NO_DRIVER = 'errNetMountNoDriver';
  416. const ERROR_NETUNMOUNT = 'errNetUnMount';
  417. const ERROR_NOT_ARCHIVE = 'errNoArchive';
  418. const ERROR_NOT_DIR = 'errNotFolder';
  419. const ERROR_NOT_FILE = 'errNotFile';
  420. const ERROR_NOT_REPLACE = 'errNotReplace'; // Object "$1" already exists at this location and can not be replaced with object of another type.
  421. const ERROR_NOT_UTF8_CONTENT = 'errNotUTF8Content';
  422. const ERROR_OPEN = 'errOpen';
  423. const ERROR_PERM_DENIED = 'errPerm';
  424. const ERROR_REAUTH_REQUIRE = 'errReauthRequire'; // 'Re-authorization is required.'
  425. const ERROR_RENAME = 'errRename';
  426. const ERROR_REPLACE = 'errReplace'; // 'Unable to replace "$1".'
  427. const ERROR_RESIZE = 'errResize';
  428. const ERROR_RESIZESIZE = 'errResizeSize';
  429. const ERROR_RM = 'errRm'; // 'Unable to remove "$1".'
  430. const ERROR_RM_SRC = 'errRmSrc'; // 'Unable remove source file(s)'
  431. const ERROR_SAVE = 'errSave';
  432. const ERROR_SEARCH_TIMEOUT = 'errSearchTimeout'; // 'Timed out while searching "$1". Search result is partial.'
  433. const ERROR_SESSION_EXPIRES = 'errSessionExpires';
  434. const ERROR_TRGDIR_NOT_FOUND = 'errTrgFolderNotFound'; // 'Target folder "$1" not found.'
  435. const ERROR_UNKNOWN = 'errUnknown';
  436. const ERROR_UNKNOWN_CMD = 'errUnknownCmd';
  437. const ERROR_UNSUPPORT_TYPE = 'errUsupportType';
  438. const ERROR_UPLOAD = 'errUpload'; // 'Upload error.'
  439. const ERROR_UPLOAD_FILE = 'errUploadFile'; // 'Unable to upload "$1".'
  440. const ERROR_UPLOAD_FILE_MIME = 'errUploadMime'; // 'File type not allowed.'
  441. const ERROR_UPLOAD_FILE_SIZE = 'errUploadFileSize'; // 'File exceeds maximum allowed size.'
  442. const ERROR_UPLOAD_NO_FILES = 'errUploadNoFiles'; // 'No files found for upload.'
  443. const ERROR_UPLOAD_TEMP = 'errUploadTemp'; // 'Unable to make temporary file for upload.'
  444. const ERROR_UPLOAD_TOTAL_SIZE = 'errUploadTotalSize'; // 'Data exceeds the maximum allowed size.'
  445. const ERROR_UPLOAD_TRANSFER = 'errUploadTransfer'; // '"$1" transfer error.'
  446. /**
  447. * Constructor
  448. *
  449. * @param array elFinder and roots configurations
  450. *
  451. * @author Dmitry (dio) Levashov
  452. */
  453. public function __construct($opts)
  454. {
  455. // set default_charset
  456. if (version_compare(PHP_VERSION, '5.6', '>=')) {
  457. if (($_val = ini_get('iconv.internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
  458. ini_set('iconv.internal_encoding', '');
  459. }
  460. if (($_val = ini_get('mbstring.internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
  461. ini_set('mbstring.internal_encoding', '');
  462. }
  463. if (($_val = ini_get('internal_encoding')) && strtoupper($_val) !== 'UTF-8') {
  464. ini_set('internal_encoding', '');
  465. }
  466. } else {
  467. if (function_exists('iconv_set_encoding') && strtoupper(iconv_get_encoding('internal_encoding')) !== 'UTF-8') {
  468. iconv_set_encoding('internal_encoding', 'UTF-8');
  469. }
  470. if (function_exists('mb_internal_encoding') && strtoupper(mb_internal_encoding()) !== 'UTF-8') {
  471. mb_internal_encoding('UTF-8');
  472. }
  473. }
  474. ini_set('default_charset', 'UTF-8');
  475. // define accept constant of server commands path
  476. !defined('ELFINDER_TAR_PATH') && define('ELFINDER_TAR_PATH', 'tar');
  477. !defined('ELFINDER_GZIP_PATH') && define('ELFINDER_GZIP_PATH', 'gzip');
  478. !defined('ELFINDER_BZIP2_PATH') && define('ELFINDER_BZIP2_PATH', 'bzip2');
  479. !defined('ELFINDER_XZ_PATH') && define('ELFINDER_XZ_PATH', 'xz');
  480. !defined('ELFINDER_ZIP_PATH') && define('ELFINDER_ZIP_PATH', 'zip');
  481. !defined('ELFINDER_UNZIP_PATH') && define('ELFINDER_UNZIP_PATH', 'unzip');
  482. !defined('ELFINDER_RAR_PATH') && define('ELFINDER_RAR_PATH', 'rar');
  483. !defined('ELFINDER_UNRAR_PATH') && define('ELFINDER_UNRAR_PATH', 'unrar');
  484. !defined('ELFINDER_7Z_PATH') && define('ELFINDER_7Z_PATH', (substr(PHP_OS, 0, 3) === 'WIN') ? '7z' : '7za');
  485. !defined('ELFINDER_CONVERT_PATH') && define('ELFINDER_CONVERT_PATH', 'convert');
  486. !defined('ELFINDER_IDENTIFY_PATH') && define('ELFINDER_IDENTIFY_PATH', 'identify');
  487. !defined('ELFINDER_EXIFTRAN_PATH') && define('ELFINDER_EXIFTRAN_PATH', 'exiftran');
  488. !defined('ELFINDER_JPEGTRAN_PATH') && define('ELFINDER_JPEGTRAN_PATH', 'jpegtran');
  489. !defined('ELFINDER_FFMPEG_PATH') && define('ELFINDER_FFMPEG_PATH', 'ffmpeg');
  490. !defined('ELFINDER_DISABLE_ZIPEDITOR') && define('ELFINDER_DISABLE_ZIPEDITOR', false);
  491. // enable(true)/disable(false) handling postscript on ImageMagick
  492. // Should be `false` as long as there is a Ghostscript vulnerability
  493. // see https://artifex.com/news/ghostscript-security-resolved/
  494. !defined('ELFINDER_IMAGEMAGICK_PS') && define('ELFINDER_IMAGEMAGICK_PS', false);
  495. // for backward compat
  496. $this->version = (string)self::$ApiVersion;
  497. // set error handler of WARNING, NOTICE
  498. $errLevel = E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE | E_STRICT | E_RECOVERABLE_ERROR;
  499. if (defined('E_DEPRECATED')) {
  500. $errLevel |= E_DEPRECATED | E_USER_DEPRECATED;
  501. }
  502. set_error_handler('elFinder::phpErrorHandler', $errLevel);
  503. // Associative array of files to delete at the end of script: ['temp file path' => true]
  504. $GLOBALS['elFinderTempFiles'] = array();
  505. // regist Shutdown function
  506. register_shutdown_function(array('elFinder', 'onShutdown'));
  507. // convert PATH_INFO to GET query
  508. if (!empty($_SERVER['PATH_INFO'])) {
  509. $_ps = explode('/', trim($_SERVER['PATH_INFO'], '/'));
  510. if (!isset($_GET['cmd'])) {
  511. $_cmd = $_ps[0];
  512. if (isset($this->commands[$_cmd])) {
  513. $_GET['cmd'] = $_cmd;
  514. $_i = 1;
  515. foreach (array_keys($this->commands[$_cmd]) as $_k) {
  516. if (isset($_ps[$_i])) {
  517. if (!isset($_GET[$_k])) {
  518. $_GET[$_k] = $_ps[$_i];
  519. }
  520. } else {
  521. break;
  522. }
  523. }
  524. }
  525. }
  526. }
  527. // set elFinder instance
  528. elFinder::$instance = $this;
  529. // setup debug mode
  530. $this->debug = (isset($opts['debug']) && $opts['debug'] ? true : false);
  531. if ($this->debug) {
  532. error_reporting(defined('ELFINDER_DEBUG_ERRORLEVEL') ? ELFINDER_DEBUG_ERRORLEVEL : -1);
  533. ini_set('display_errors', '1');
  534. // clear output buffer and stop output filters
  535. while (ob_get_level() && ob_end_clean()) {
  536. }
  537. }
  538. if (!interface_exists('elFinderSessionInterface')) {
  539. include_once dirname(__FILE__) . '/elFinderSessionInterface.php';
  540. }
  541. // session handler
  542. if (!empty($opts['session']) && $opts['session'] instanceof elFinderSessionInterface) {
  543. $this->session = $opts['session'];
  544. } else {
  545. $sessionOpts = array(
  546. 'base64encode' => !empty($opts['base64encodeSessionData']),
  547. 'keys' => array(
  548. 'default' => !empty($opts['sessionCacheKey']) ? $opts['sessionCacheKey'] : 'elFinderCaches',
  549. 'netvolume' => !empty($opts['netVolumesSessionKey']) ? $opts['netVolumesSessionKey'] : 'elFinderNetVolumes'
  550. )
  551. );
  552. if (!class_exists('elFinderSession')) {
  553. include_once dirname(__FILE__) . '/elFinderSession.php';
  554. }
  555. $this->session = new elFinderSession($sessionOpts);
  556. }
  557. // try session start | restart
  558. $this->session->start();
  559. // 'netmount' added to handle requests synchronously on unmount
  560. $sessionUseCmds = array('netmount');
  561. if (isset($opts['sessionUseCmds']) && is_array($opts['sessionUseCmds'])) {
  562. $sessionUseCmds = array_merge($sessionUseCmds, $opts['sessionUseCmds']);
  563. }
  564. // set self::$volumesCnt by HTTP header "X-elFinder-VolumesCntStart"
  565. if (isset($_SERVER['HTTP_X_ELFINDER_VOLUMESCNTSTART']) && ($volumesCntStart = intval($_SERVER['HTTP_X_ELFINDER_VOLUMESCNTSTART']))) {
  566. self::$volumesCnt = $volumesCntStart;
  567. }
  568. $this->time = $this->utime();
  569. $this->sessionCloseEarlier = isset($opts['sessionCloseEarlier']) ? (bool)$opts['sessionCloseEarlier'] : true;
  570. $this->sessionUseCmds = array_flip($sessionUseCmds);
  571. $this->timeout = (isset($opts['timeout']) ? $opts['timeout'] : 0);
  572. $this->uploadTempPath = (isset($opts['uploadTempPath']) ? $opts['uploadTempPath'] : '');
  573. $this->callbackWindowURL = (isset($opts['callbackWindowURL']) ? $opts['callbackWindowURL'] : '');
  574. $this->maxTargets = (isset($opts['maxTargets']) ? intval($opts['maxTargets']) : $this->maxTargets);
  575. elFinder::$commonTempPath = (isset($opts['commonTempPath']) ? realpath($opts['commonTempPath']) : dirname(__FILE__) . '/.tmp');
  576. if (!is_writable(elFinder::$commonTempPath)) {
  577. elFinder::$commonTempPath = sys_get_temp_dir();
  578. if (!is_writable(elFinder::$commonTempPath)) {
  579. elFinder::$commonTempPath = '';
  580. }
  581. }
  582. if (isset($opts['connectionFlagsPath']) && is_writable($opts['connectionFlagsPath'] = realpath($opts['connectionFlagsPath']))) {
  583. elFinder::$connectionFlagsPath = $opts['connectionFlagsPath'];
  584. } else {
  585. elFinder::$connectionFlagsPath = elFinder::$commonTempPath;
  586. }
  587. if (!empty($opts['tmpLinkPath'])) {
  588. elFinder::$tmpLinkPath = realpath($opts['tmpLinkPath']);
  589. }
  590. if (!empty($opts['tmpLinkUrl'])) {
  591. elFinder::$tmpLinkUrl = $opts['tmpLinkUrl'];
  592. }
  593. if (!empty($opts['tmpLinkLifeTime'])) {
  594. elFinder::$tmpLinkLifeTime = $opts['tmpLinkLifeTime'];
  595. }
  596. if (!empty($opts['textMimes']) && is_array($opts['textMimes'])) {
  597. elfinder::$textMimes = $opts['textMimes'];
  598. }
  599. if (!empty($opts['urlUploadFilter'])) {
  600. $this->urlUploadFilter = $opts['urlUploadFilter'];
  601. }
  602. $this->maxArcFilesSize = isset($opts['maxArcFilesSize']) ? intval($opts['maxArcFilesSize']) : 0;
  603. $this->optionsNetVolumes = (isset($opts['optionsNetVolumes']) && is_array($opts['optionsNetVolumes'])) ? $opts['optionsNetVolumes'] : array();
  604. if (isset($opts['itemLockExpire'])) {
  605. $this->itemLockExpire = intval($opts['itemLockExpire']);
  606. }
  607. // deprecated settings
  608. $this->netVolumesSessionKey = !empty($opts['netVolumesSessionKey']) ? $opts['netVolumesSessionKey'] : 'elFinderNetVolumes';
  609. self::$sessionCacheKey = !empty($opts['sessionCacheKey']) ? $opts['sessionCacheKey'] : 'elFinderCaches';
  610. // check session cache
  611. $_optsMD5 = md5(json_encode($opts['roots']));
  612. if ($this->session->get('_optsMD5') !== $_optsMD5) {
  613. $this->session->set('_optsMD5', $_optsMD5);
  614. }
  615. // setlocale and global locale regists to elFinder::locale
  616. self::$locale = !empty($opts['locale']) ? $opts['locale'] : (substr(PHP_OS, 0, 3) === 'WIN' ? 'C' : 'en_US.UTF-8');
  617. if (false === setlocale(LC_ALL, self::$locale)) {
  618. self::$locale = setlocale(LC_ALL, '0');
  619. }
  620. // set defaultMimefile
  621. elFinder::$defaultMimefile = isset($opts['defaultMimefile']) ? $opts['defaultMimefile'] : '';
  622. // set memoryLimitGD
  623. elFinder::$memoryLimitGD = isset($opts['memoryLimitGD']) ? $opts['memoryLimitGD'] : 0;
  624. // set flag of throwErrorOnExec
  625. // `true` need `try{}` block for `$connector->run();`
  626. $this->throwErrorOnExec = !empty($opts['throwErrorOnExec']);
  627. // set archivers
  628. elFinder::$archivers = isset($opts['archivers']) && is_array($opts['archivers']) ? $opts['archivers'] : array();
  629. // bind events listeners
  630. if (!empty($opts['bind']) && is_array($opts['bind'])) {
  631. $_req = $_SERVER["REQUEST_METHOD"] == 'POST' ? $_POST : $_GET;
  632. $_reqCmd = isset($_req['cmd']) ? $_req['cmd'] : '';
  633. foreach ($opts['bind'] as $cmd => $handlers) {
  634. $doRegist = (strpos($cmd, '*') !== false);
  635. if (!$doRegist) {
  636. $doRegist = ($_reqCmd && in_array($_reqCmd, array_map('self::getCmdOfBind', explode(' ', $cmd))));
  637. }
  638. if ($doRegist) {
  639. // for backward compatibility
  640. if (!is_array($handlers)) {
  641. $handlers = array($handlers);
  642. } else {
  643. if (count($handlers) === 2 && is_callable($handlers)) {
  644. $handlers = array($handlers);
  645. }
  646. }
  647. foreach ($handlers as $handler) {
  648. if ($handler) {
  649. if (is_string($handler) && strpos($handler, '.')) {
  650. list($_domain, $_name, $_method) = array_pad(explode('.', $handler), 3, '');
  651. if (strcasecmp($_domain, 'plugin') === 0) {
  652. if ($plugin = $this->getPluginInstance($_name, isset($opts['plugin'][$_name]) ? $opts['plugin'][$_name] : array())
  653. and method_exists($plugin, $_method)) {
  654. $this->bind($cmd, array($plugin, $_method));
  655. }
  656. }
  657. } else {
  658. $this->bind($cmd, $handler);
  659. }
  660. }
  661. }
  662. }
  663. }
  664. }
  665. if (!isset($opts['roots']) || !is_array($opts['roots'])) {
  666. $opts['roots'] = array();
  667. }
  668. // try to enable elFinderVolumeFlysystemZipArchiveNetmount to zip editing
  669. if (empty(elFinder::$netDrivers['ziparchive'])) {
  670. elFinder::$netDrivers['ziparchive'] = 'FlysystemZipArchiveNetmount';
  671. }
  672. // check for net volumes stored in session
  673. $netVolumes = $this->getNetVolumes();
  674. foreach ($netVolumes as $key => $root) {
  675. if (!isset($root['id'])) {
  676. // given fixed unique id
  677. if (!$root['id'] = $this->getNetVolumeUniqueId($netVolumes)) {
  678. $this->mountErrors[] = 'Netmount Driver "' . $root['driver'] . '" : Could\'t given volume id.';
  679. continue;
  680. }
  681. }
  682. $opts['roots'][$key] = $root;
  683. }
  684. // "mount" volumes
  685. foreach ($opts['roots'] as $i => $o) {
  686. $class = 'elFinderVolume' . (isset($o['driver']) ? $o['driver'] : '');
  687. if (class_exists($class)) {
  688. /* @var elFinderVolumeDriver $volume */
  689. $volume = new $class();
  690. try {
  691. if ($this->maxArcFilesSize && (empty($o['maxArcFilesSize']) || $this->maxArcFilesSize < $o['maxArcFilesSize'])) {
  692. $o['maxArcFilesSize'] = $this->maxArcFilesSize;
  693. }
  694. // pass session handler
  695. $volume->setSession($this->session);
  696. if ($volume->mount($o)) {
  697. // unique volume id (ends on "_") - used as prefix to files hash
  698. $id = $volume->id();
  699. $this->volumes[$id] = $volume;
  700. if ((!$this->default || $volume->root() !== $volume->defaultPath()) && $volume->isReadable()) {
  701. $this->default = $this->volumes[$id];
  702. }
  703. } else {
  704. $this->removeNetVolume($i, $volume);
  705. $this->mountErrors[] = 'Driver "' . $class . '" : ' . implode(' ', $volume->error());
  706. }
  707. } catch (Exception $e) {
  708. $this->removeNetVolume($i, $volume);
  709. $this->mountErrors[] = 'Driver "' . $class . '" : ' . $e->getMessage();
  710. }
  711. } else {
  712. $this->removeNetVolume($i, null);
  713. $this->mountErrors[] = 'Driver "' . $class . '" does not exist';
  714. }
  715. }
  716. // if at least one readable volume - ii desu >_<
  717. $this->loaded = !empty($this->default);
  718. // restore error handler for now
  719. restore_error_handler();
  720. }
  721. /**
  722. * Return elFinder session wrapper instance
  723. *
  724. * @return elFinderSessionInterface
  725. **/
  726. public function getSession()
  727. {
  728. return $this->session;
  729. }
  730. /**
  731. * Return true if fm init correctly
  732. *
  733. * @return bool
  734. * @author Dmitry (dio) Levashov
  735. **/
  736. public function loaded()
  737. {
  738. return $this->loaded;
  739. }
  740. /**
  741. * Return version (api) number
  742. *
  743. * @return string
  744. * @author Dmitry (dio) Levashov
  745. **/
  746. public function version()
  747. {
  748. return self::$ApiVersion;
  749. }
  750. /**
  751. * Return revision (api) number
  752. *
  753. * @return string
  754. * @author Naoki Sawada
  755. **/
  756. public function revision()
  757. {
  758. return self::$ApiRevision;
  759. }
  760. /**
  761. * Add handler to elFinder command
  762. *
  763. * @param string command name
  764. * @param string|array callback name or array(object, method)
  765. *
  766. * @return elFinder
  767. * @author Dmitry (dio) Levashov
  768. **/
  769. public function bind($cmd, $handler)
  770. {
  771. $allCmds = array_keys($this->commands);
  772. $cmds = array();
  773. foreach (explode(' ', $cmd) as $_cmd) {
  774. if ($_cmd !== '') {
  775. if ($all = strpos($_cmd, '*') !== false) {
  776. list(, $sub) = array_pad(explode('.', $_cmd), 2, '');
  777. if ($sub) {
  778. $sub = str_replace('\'', '\\\'', $sub);
  779. $subs = array_fill(0, count($allCmds), $sub);
  780. $cmds = array_merge($cmds, array_map(array('elFinder', 'addSubToBindName'), $allCmds, $subs));
  781. } else {
  782. $cmds = array_merge($cmds, $allCmds);
  783. }
  784. } else {
  785. $cmds[] = $_cmd;
  786. }
  787. }
  788. }
  789. $cmds = array_unique($cmds);
  790. foreach ($cmds as $cmd) {
  791. if (!isset($this->listeners[$cmd])) {
  792. $this->listeners[$cmd] = array();
  793. }
  794. if (is_callable($handler)) {
  795. $this->listeners[$cmd][] = $handler;
  796. }
  797. }
  798. return $this;
  799. }
  800. /**
  801. * Remove event (command exec) handler
  802. *
  803. * @param string command name
  804. * @param string|array callback name or array(object, method)
  805. *
  806. * @return elFinder
  807. * @author Dmitry (dio) Levashov
  808. **/
  809. public function unbind($cmd, $handler)
  810. {
  811. if (!empty($this->listeners[$cmd])) {
  812. foreach ($this->listeners[$cmd] as $i => $h) {
  813. if ($h === $handler) {
  814. unset($this->listeners[$cmd][$i]);
  815. return $this;
  816. }
  817. }
  818. }
  819. return $this;
  820. }
  821. /**
  822. * Return true if command exists
  823. *
  824. * @param string command name
  825. *
  826. * @return bool
  827. * @author Dmitry (dio) Levashov
  828. **/
  829. public function commandExists($cmd)
  830. {
  831. return $this->loaded && isset($this->commands[$cmd]) && method_exists($this, $cmd);
  832. }
  833. /**
  834. * Return root - file's owner (public func of volume())
  835. *
  836. * @param string file hash
  837. *
  838. * @return elFinderVolumeDriver
  839. * @author Naoki Sawada
  840. */
  841. public function getVolume($hash)
  842. {
  843. return $this->volume($hash);
  844. }
  845. /**
  846. * Return command required arguments info
  847. *
  848. * @param string command name
  849. *
  850. * @return array
  851. * @author Dmitry (dio) Levashov
  852. **/
  853. public function commandArgsList($cmd)
  854. {
  855. if ($this->commandExists($cmd)) {
  856. $list = $this->commands[$cmd];
  857. $list['reqid'] = false;
  858. } else {
  859. $list = array();
  860. }
  861. return $list;
  862. }
  863. private function session_expires()
  864. {
  865. if (!$last = $this->session->get(':LAST_ACTIVITY')) {
  866. $this->session->set(':LAST_ACTIVITY', time());
  867. return false;
  868. }
  869. if (($this->timeout > 0) && (time() - $last > $this->timeout)) {
  870. return true;
  871. }
  872. $this->session->set(':LAST_ACTIVITY', time());
  873. return false;
  874. }
  875. /**
  876. * Exec command and return result
  877. *
  878. * @param string $cmd command name
  879. * @param array $args command arguments
  880. *
  881. * @return array
  882. * @throws elFinderAbortException|Exception
  883. * @author Dmitry (dio) Levashov
  884. **/
  885. public function exec($cmd, $args)
  886. {
  887. // set error handler of WARNING, NOTICE
  888. set_error_handler('elFinder::phpErrorHandler', E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE);
  889. // set current request args
  890. self::$currentArgs = $args;
  891. if (!$this->loaded) {
  892. return array('error' => $this->error(self::ERROR_CONF, self::ERROR_CONF_NO_VOL));
  893. }
  894. if ($this->session_expires()) {
  895. return array('error' => $this->error(self::ERROR_SESSION_EXPIRES));
  896. }
  897. if (!$this->commandExists($cmd)) {
  898. return array('error' => $this->error(self::ERROR_UNKNOWN_CMD));
  899. }
  900. // check request id
  901. $args['reqid'] = preg_replace('[^0-9a-fA-F]', '', !empty($args['reqid']) ? $args['reqid'] : (!empty($_SERVER['HTTP_X_ELFINDERREQID']) ? $_SERVER['HTTP_X_ELFINDERREQID'] : ''));
  902. // to abort this request
  903. if ($cmd === 'abort') {
  904. $this->abort($args);
  905. return array('error' => 0);
  906. }
  907. // make flag file and set self::$abortCheckFile
  908. if ($args['reqid']) {
  909. $this->abort(array('makeFile' => $args['reqid']));
  910. }
  911. if (!empty($args['mimes']) && is_array($args['mimes'])) {
  912. foreach ($this->volumes as $id => $v) {
  913. $this->volumes[$id]->setMimesFilter($args['mimes']);
  914. }
  915. }
  916. // regist shutdown function as fallback
  917. register_shutdown_function(array($this, 'itemAutoUnlock'));
  918. // detect destination dirHash and volume
  919. $dstVolume = false;
  920. $dst = !empty($args['target']) ? $args['target'] : (!empty($args['dst']) ? $args['dst'] : '');
  921. if ($dst) {
  922. $dstVolume = $this->volume($dst);
  923. } else if (isset($args['targets']) && is_array($args['targets']) && isset($args['targets'][0])) {
  924. $dst = $args['targets'][0];
  925. $dstVolume = $this->volume($dst);
  926. if ($dstVolume && ($_stat = $dstVolume->file($dst)) && !empty($_stat['phash'])) {
  927. $dst = $_stat['phash'];
  928. } else {
  929. $dst = '';
  930. }
  931. } else if ($cmd === 'open') {
  932. // for initial open without args `target`
  933. $dstVolume = $this->default;
  934. $dst = $dstVolume->defaultPath();
  935. }
  936. $result = null;
  937. // call pre handlers for this command
  938. $args['sessionCloseEarlier'] = isset($this->sessionUseCmds[$cmd]) ? false : $this->sessionCloseEarlier;
  939. if (!empty($this->listeners[$cmd . '.pre'])) {
  940. foreach ($this->listeners[$cmd . '.pre'] as $handler) {
  941. $_res = call_user_func_array($handler, array($cmd, &$args, $this, $dstVolume));
  942. if (is_array($_res)) {
  943. if (!empty($_res['preventexec'])) {
  944. $result = array('error' => true);
  945. if ($cmd === 'upload' && !empty($args['node'])) {
  946. $result['callback'] = array(
  947. 'node' => $args['node'],
  948. 'bind' => $cmd
  949. );
  950. }
  951. if (!empty($_res['results']) && is_array($_res['results'])) {
  952. $result = array_merge($result, $_res['results']);
  953. }
  954. break;
  955. }
  956. }
  957. }
  958. }
  959. // unlock session data for multiple access
  960. if ($this->sessionCloseEarlier && $args['sessionCloseEarlier']) {
  961. $this->session->close();
  962. // deprecated property
  963. elFinder::$sessionClosed = true;
  964. }
  965. if (substr(PHP_OS, 0, 3) === 'WIN') {
  966. // set time out
  967. elFinder::extendTimeLimit(300);
  968. }
  969. if (!is_array($result)) {
  970. try {
  971. $result = $this->$cmd($args);
  972. } catch (elFinderAbortException $e) {
  973. throw $e;
  974. } catch (Exception $e) {
  975. $result = array(
  976. 'error' => htmlspecialchars($e->getMessage()),
  977. 'sync' => true
  978. );
  979. if ($this->throwErrorOnExec) {
  980. throw $e;
  981. }
  982. }
  983. }
  984. // check change dstDir
  985. $changeDst = false;
  986. if ($dst && $dstVolume && (!empty($result['added']) || !empty($result['removed']))) {
  987. $changeDst = true;
  988. }
  989. foreach ($this->volumes as $volume) {
  990. $removed = $volume->removed();
  991. if (!empty($removed)) {
  992. if (!isset($result['removed'])) {
  993. $result['removed'] = array();
  994. }
  995. $result['removed'] = array_merge($result['removed'], $removed);
  996. if (!$changeDst && $dst && $dstVolume && $volume === $dstVolume) {
  997. $changeDst = true;
  998. }
  999. }
  1000. $added = $volume->added();
  1001. if (!empty($added)) {
  1002. if (!isset($result['added'])) {
  1003. $result['added'] = array();
  1004. }
  1005. $result['added'] = array_merge($result['added'], $added);
  1006. if (!$changeDst && $dst && $dstVolume && $volume === $dstVolume) {
  1007. $changeDst = true;
  1008. }
  1009. }
  1010. $volume->resetResultStat();
  1011. }
  1012. // dstDir is changed
  1013. if ($changeDst) {
  1014. if ($dstDir = $dstVolume->dir($dst)) {
  1015. if (!isset($result['changed'])) {
  1016. $result['changed'] = array();
  1017. }
  1018. $result['changed'][] = $dstDir;
  1019. }
  1020. }
  1021. // call handlers for this command
  1022. if (!empty($this->listeners[$cmd])) {
  1023. foreach ($this->listeners[$cmd] as $handler) {
  1024. if (call_user_func_array($handler, array($cmd, &$result, $args, $this, $dstVolume))) {
  1025. // handler return true to force sync client after command completed
  1026. $result['sync'] = true;
  1027. }
  1028. }
  1029. }
  1030. // replace removed files info with removed files hashes
  1031. if (!empty($result['removed'])) {
  1032. $removed = array();
  1033. foreach ($result['removed'] as $file) {
  1034. $removed[] = $file['hash'];
  1035. }
  1036. $result['removed'] = array_unique($removed);
  1037. }
  1038. // remove hidden files and filter files by mimetypes
  1039. if (!empty($result['added'])) {
  1040. $result['added'] = $this->filter($result['added']);
  1041. }
  1042. // remove hidden files and filter files by mimetypes
  1043. if (!empty($result['changed'])) {
  1044. $result['changed'] = $this->filter($result['changed']);
  1045. }
  1046. if ($this->debug || !empty($args['debug'])) {
  1047. $result['debug'] = array(
  1048. 'connector' => 'php',
  1049. 'phpver' => PHP_VERSION,
  1050. 'time' => $this->utime() - $this->time,
  1051. 'memory' => (function_exists('memory_get_peak_usage') ? ceil(memory_get_peak_usage() / 1024) . 'Kb / ' : '') . ceil(memory_get_usage() / 1024) . 'Kb / ' . ini_get('memory_limit'),
  1052. 'upload' => $this->uploadDebug,
  1053. 'volumes' => array(),
  1054. 'mountErrors' => $this->mountErrors,
  1055. 'phpErrors' => elFinder::$phpErrors
  1056. );
  1057. elFinder::$phpErrors = array();
  1058. foreach ($this->volumes as $id => $volume) {
  1059. $result['debug']['volumes'][] = $volume->debug();
  1060. }
  1061. }
  1062. // remove sesstion var 'urlContentSaveIds'
  1063. if ($this->removeContentSaveIds) {
  1064. $urlContentSaveIds = $this->session->get('urlContentSaveIds', array());
  1065. foreach (array_keys($this->removeContentSaveIds) as $contentSaveId) {
  1066. if (isset($urlContentSaveIds[$contentSaveId])) {
  1067. unset($urlContentSaveIds[$contentSaveId]);
  1068. }
  1069. }
  1070. if ($urlContentSaveIds) {
  1071. $this->session->set('urlContentSaveIds', $urlContentSaveIds);
  1072. } else {
  1073. $this->session->remove('urlContentSaveIds');
  1074. }
  1075. }
  1076. foreach ($this->volumes as $volume) {
  1077. $volume->saveSessionCache();
  1078. $volume->umount();
  1079. }
  1080. // unlock locked items
  1081. $this->itemAutoUnlock();
  1082. // custom data
  1083. if ($this->customData !== null) {
  1084. $result['customData'] = $this->customData ? json_encode($this->customData) : '';
  1085. }
  1086. if (!empty($result['callback'])) {
  1087. $result['callback']['json'] = json_encode($result);
  1088. $this->callback($result['callback']);
  1089. return array();
  1090. } else {
  1091. return $result;
  1092. }
  1093. }
  1094. /**
  1095. * Return file real path
  1096. *
  1097. * @param string $hash file hash
  1098. *
  1099. * @return string
  1100. * @author Dmitry (dio) Levashov
  1101. **/
  1102. public function realpath($hash)
  1103. {
  1104. if (($volume = $this->volume($hash)) == false) {
  1105. return false;
  1106. }
  1107. return $volume->realpath($hash);
  1108. }
  1109. /**
  1110. * Sets custom data(s).
  1111. *
  1112. * @param string|array $key The key or data array
  1113. * @param mixed $val The value
  1114. *
  1115. * @return self ( elFinder instance )
  1116. */
  1117. public function setCustomData($key, $val = null)
  1118. {
  1119. if (is_array($key)) {
  1120. foreach ($key as $k => $v) {
  1121. $this->customData[$k] = $v;
  1122. }
  1123. } else {
  1124. $this->customData[$key] = $val;
  1125. }
  1126. return $this;
  1127. }
  1128. /**
  1129. * Removes a custom data.
  1130. *
  1131. * @param string $key The key
  1132. *
  1133. * @return self ( elFinder instance )
  1134. */
  1135. public function removeCustomData($key)
  1136. {
  1137. $this->customData[$key] = null;
  1138. return $this;
  1139. }
  1140. /**
  1141. * Update sesstion value of a NetVolume option
  1142. *
  1143. * @param string $netKey
  1144. * @param string $optionKey
  1145. * @param mixed $val
  1146. */
  1147. public function updateNetVolumeOption($netKey, $optionKey, $val)
  1148. {
  1149. $netVolumes = $this->getNetVolumes();
  1150. if (is_string($netKey) && isset($netVolumes[$netKey]) && is_string($optionKey)) {
  1151. $netVolumes[$netKey][$optionKey] = $val;
  1152. }
  1153. }
  1154. /**
  1155. * remove of session var "urlContentSaveIds"
  1156. *
  1157. * @param string $id
  1158. */
  1159. public function removeUrlContentSaveId($id)
  1160. {
  1161. $this->removeContentSaveIds[$id] = true;
  1162. }
  1163. /**
  1164. * Return network volumes config.
  1165. *
  1166. * @return array
  1167. * @author Dmitry (dio) Levashov
  1168. */
  1169. protected function getNetVolumes()
  1170. {
  1171. if ($data = $this->session->get('netvolume', array())) {
  1172. return $data;
  1173. }
  1174. return array();
  1175. }
  1176. /**
  1177. * Save network volumes config.
  1178. *
  1179. * @param array $volumes volumes config
  1180. *
  1181. * @return void
  1182. * @author Dmitry (dio) Levashov
  1183. */
  1184. protected function saveNetVolumes($volumes)
  1185. {
  1186. $this->session->set('netvolume', $volumes);
  1187. }
  1188. /**
  1189. * Remove netmount volume
  1190. *
  1191. * @param string $key netvolume key
  1192. * @param object $volume volume driver instance
  1193. *
  1194. * @return bool
  1195. */
  1196. protected function removeNetVolume($key, $volume)
  1197. {
  1198. $netVolumes = $this->getNetVolumes();
  1199. $res = true;
  1200. if (is_object($volume) && method_exists($volume, 'netunmount')) {
  1201. $res = $volume->netunmount($netVolumes, $key);
  1202. $volume->clearSessionCache();
  1203. }
  1204. if ($res) {
  1205. if (is_string($key) && isset($netVolumes[$key])) {
  1206. unset($netVolumes[$key]);
  1207. $this->saveNetVolumes($netVolumes);
  1208. return true;
  1209. }
  1210. }
  1211. return false;
  1212. }
  1213. /**
  1214. * Get plugin instance & set to $this->plugins
  1215. *
  1216. * @param string $name Plugin name (dirctory name)
  1217. * @param array $opts Plugin options (optional)
  1218. *
  1219. * @return object | bool Plugin object instance Or false
  1220. * @author Naoki Sawada
  1221. */
  1222. protected function getPluginInstance($name, $opts = array())
  1223. {
  1224. $key = strtolower($name);
  1225. if (!isset($this->plugins[$key])) {
  1226. $class = 'elFinderPlugin' . $name;
  1227. // to try auto load
  1228. if (!class_exists($class)) {
  1229. $p_file = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'plugins' . DIRECTORY_SEPARATOR . $name . DIRECTORY_SEPARATOR . 'plugin.php';
  1230. if (is_file($p_file)) {
  1231. include_once $p_file;
  1232. }
  1233. }
  1234. if (class_exists($class, false)) {
  1235. $this->plugins[$key] = new $class($opts);
  1236. } else {
  1237. $this->plugins[$key] = false;
  1238. }
  1239. }
  1240. return $this->plugins[$key];
  1241. }
  1242. /***************************************************************************/
  1243. /* commands */
  1244. /***************************************************************************/
  1245. /**
  1246. * Normalize error messages
  1247. *
  1248. * @return array
  1249. * @author Dmitry (dio) Levashov
  1250. **/
  1251. public function error()
  1252. {
  1253. $errors = array();
  1254. foreach (func_get_args() as $msg) {
  1255. if (is_array($msg)) {
  1256. $errors = array_merge($errors, $msg);
  1257. } else {
  1258. $errors[] = $msg;
  1259. }
  1260. }
  1261. return count($errors) ? $errors : array(self::ERROR_UNKNOWN);
  1262. }
  1263. /**
  1264. * @param $args
  1265. *
  1266. * @return array
  1267. * @throws elFinderAbortException
  1268. */
  1269. protected function netmount($args)
  1270. {
  1271. $options = array();
  1272. $protocol = $args['protocol'];
  1273. $toast = '';
  1274. if ($protocol === 'netunmount') {
  1275. if (!empty($args['user']) && $volume = $this->volume($args['user'])) {
  1276. if ($this->removeNetVolume($args['host'], $volume)) {
  1277. return array('removed' => array(array('hash' => $volume->root())));
  1278. }
  1279. }
  1280. return array('sync' => true, 'error' => $this->error(self::ERROR_NETUNMOUNT));
  1281. }
  1282. $driver = isset(self::$netDrivers[$protocol]) ? self::$netDrivers[$protocol] : '';
  1283. $class = 'elFinderVolume' . $driver;
  1284. if (!class_exists($class)) {
  1285. return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], self::ERROR_NETMOUNT_NO_DRIVER));
  1286. }
  1287. if (!$args['path']) {
  1288. $args['path'] = '/';
  1289. }
  1290. foreach ($args as $k => $v) {
  1291. if ($k != 'options' && $k != 'protocol' && $v) {
  1292. $options[$k] = $v;
  1293. }
  1294. }
  1295. if (is_array($args['options'])) {
  1296. foreach ($args['options'] as $key => $value) {
  1297. $options[$key] = $value;
  1298. }
  1299. }
  1300. /* @var elFinderVolumeDriver $volume */
  1301. $volume = new $class();
  1302. // pass session handler
  1303. $volume->setSession($this->session);
  1304. if (is_callable(array($volume, 'netmountPrepare'))) {
  1305. $options = $volume->netmountPrepare($options);
  1306. if (isset($options['exit'])) {
  1307. if ($options['exit'] === 'callback') {
  1308. $this->callback($options['out']);
  1309. }
  1310. return $options;
  1311. }
  1312. if (!empty($options['toast'])) {
  1313. $toast = $options['toast'];
  1314. unset($options['toast']);
  1315. }
  1316. }
  1317. $netVolumes = $this->getNetVolumes();
  1318. if (!isset($options['id'])) {
  1319. // given fixed unique id
  1320. if (!$options['id'] = $this->getNetVolumeUniqueId($netVolumes)) {
  1321. return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], 'Could\'t given volume id.'));
  1322. }
  1323. }
  1324. // load additional volume root options
  1325. if (!empty($this->optionsNetVolumes['*'])) {
  1326. $options = array_merge($this->optionsNetVolumes['*'], $options);
  1327. }
  1328. if (!empty($this->optionsNetVolumes[$protocol])) {
  1329. $options = array_merge($this->optionsNetVolumes[$protocol], $options);
  1330. }
  1331. if (!$key = $volume->netMountKey) {
  1332. $key = md5($protocol . '-' . serialize($options));
  1333. }
  1334. $options['netkey'] = $key;
  1335. if (!isset($netVolumes[$key]) && $volume->mount($options)) {
  1336. // call post-process function of netmount
  1337. if (is_callable(array($volume, 'postNetmount'))) {
  1338. $volume->postNetmount($options);
  1339. }
  1340. $options['driver'] = $driver;
  1341. $netVolumes[$key] = $options;
  1342. $this->saveNetVolumes($netVolumes);
  1343. $rootstat = $volume->file($volume->root());
  1344. $res = array('added' => array($rootstat));
  1345. if ($toast) {
  1346. $res['toast'] = $toast;
  1347. }
  1348. return $res;
  1349. } else {
  1350. $this->removeNetVolume(null, $volume);
  1351. return array('error' => $this->error(self::ERROR_NETMOUNT, $args['host'], implode(' ', $volume->error())));
  1352. }
  1353. }
  1354. /**
  1355. * "Open" directory
  1356. * Return array with following elements
  1357. * - cwd - opened dir info
  1358. * - files - opened dir content [and dirs tree if $args[tree]]
  1359. * - api - api version (if $args[init])
  1360. * - uplMaxSize - if $args[init]
  1361. * - error - on failed
  1362. *
  1363. * @param array command arguments
  1364. *
  1365. * @return array
  1366. * @throws elFinderAbortException
  1367. * @author Dmitry (dio) Levashov
  1368. */
  1369. protected function open($args)
  1370. {
  1371. $target = $args['target'];
  1372. $init = !empty($args['init']);
  1373. $tree = !empty($args['tree']);
  1374. $volume = $this->volume($target);
  1375. $cwd = $volume ? $volume->dir($target) : false;
  1376. $hash = $init ? 'default folder' : '#' . $target;
  1377. $compare = '';
  1378. // on init request we can get invalid dir hash -
  1379. // dir which can not be opened now, but remembered by client,
  1380. // so open default dir
  1381. if ((!$cwd || !$cwd['read']) && $init) {
  1382. $volume = $this->default;
  1383. $target = $volume->defaultPath();
  1384. $cwd = $volume->dir($target);
  1385. }
  1386. if (!$cwd) {
  1387. return array('error' => $this->error(self::ERROR_OPEN, $hash, self::ERROR_DIR_NOT_FOUND));
  1388. }
  1389. if (!$cwd['read']) {
  1390. return array('error' => $this->error(self::ERROR_OPEN, $hash, self::ERROR_PERM_DENIED));
  1391. }
  1392. $files = array();
  1393. // get current working directory files list
  1394. if (($ls = $volume->scandir($cwd['hash'])) === false) {
  1395. return array('error' => $this->error(self::ERROR_OPEN, $cwd['name'], $volume->error()));
  1396. }
  1397. if (isset($cwd['dirs']) && $cwd['dirs'] != 1) {
  1398. $cwd = $volume->dir($target);
  1399. }
  1400. // get other volume root
  1401. if ($tree) {
  1402. foreach ($this->volumes as $id => $v) {
  1403. $files[] = $v->file($v->root());
  1404. }
  1405. }
  1406. // long polling mode
  1407. if ($args['compare']) {
  1408. $sleep = max(1, (int)$volume->getOption('lsPlSleep'));
  1409. $standby = (int)$volume->getOption('plStandby');
  1410. if ($standby > 0 && $sleep > $standby) {
  1411. $standby = $sleep;
  1412. }
  1413. $limit = max(0, floor($standby / $sleep)) + 1;
  1414. do {
  1415. elFinder::extendTimeLimit(30 + $sleep);
  1416. $_mtime = 0;
  1417. foreach ($ls as $_f) {
  1418. $_mtime = max($_mtime, $_f['ts']);
  1419. }
  1420. $compare = strval(count($ls)) . ':' . strval($_mtime);
  1421. if ($compare !== $args['compare']) {
  1422. break;
  1423. }
  1424. if (--$limit) {
  1425. sleep($sleep);
  1426. $volume->clearstatcache();
  1427. if (($ls = $volume->scandir($cwd['hash'])) === false) {
  1428. break;
  1429. }
  1430. }
  1431. } while ($limit);
  1432. if ($ls === false) {
  1433. return array('error' => $this->error(self::ERROR_OPEN, $cwd['name'], $volume->error()));
  1434. }
  1435. }
  1436. if ($ls) {
  1437. if ($files) {
  1438. $files = array_merge($files, $ls);
  1439. } else {
  1440. $files = $ls;
  1441. }
  1442. }
  1443. $result = array(
  1444. 'cwd' => $cwd,
  1445. 'options' => $volume->options($cwd['hash']),
  1446. 'files' => $files
  1447. );
  1448. if ($compare) {
  1449. $result['cwd']['compare'] = $compare;
  1450. }
  1451. if (!empty($args['init'])) {
  1452. $result['api'] = sprintf('%.1F%03d', self::$ApiVersion, self::$ApiRevision);
  1453. $result['uplMaxSize'] = ini_get('upload_max_filesize');
  1454. $result['uplMaxFile'] = ini_get('max_file_uploads');
  1455. $result['netDrivers'] = array_keys(self::$netDrivers);
  1456. $result['maxTargets'] = $this->maxTargets;
  1457. if ($volume) {
  1458. $result['cwd']['root'] = $volume->root();
  1459. }
  1460. if (elfinder::$textMimes) {
  1461. $result['textMimes'] = elfinder::$textMimes;
  1462. }
  1463. }
  1464. return $result;
  1465. }
  1466. /**
  1467. * Return dir files names list
  1468. *
  1469. * @param array command arguments
  1470. *
  1471. * @return array
  1472. * @author Dmitry (dio) Levashov
  1473. **/
  1474. protected function ls($args)
  1475. {
  1476. $target = $args['target'];
  1477. $intersect = isset($args['intersect']) ? $args['intersect'] : array();
  1478. if (($volume = $this->volume($target)) == false
  1479. || ($list = $volume->ls($target, $intersect)) === false) {
  1480. return array('error' => $this->error(self::ERROR_OPEN, '#' . $target));
  1481. }
  1482. return array('list' => $list);
  1483. }
  1484. /**
  1485. * Return subdirs for required directory
  1486. *
  1487. * @param array command arguments
  1488. *
  1489. * @return array
  1490. * @author Dmitry (dio) Levashov
  1491. **/
  1492. protected function tree($args)
  1493. {
  1494. $target = $args['target'];
  1495. if (($volume = $this->volume($target)) == false
  1496. || ($tree = $volume->tree($target)) == false) {
  1497. return array('error' => $this->error(self::ERROR_OPEN, '#' . $target));
  1498. }
  1499. return array('tree' => $tree);
  1500. }
  1501. /**
  1502. * Return parents dir for required directory
  1503. *
  1504. * @param array command arguments
  1505. *
  1506. * @return array
  1507. * @throws elFinderAbortException
  1508. * @author Dmitry (dio) Levashov
  1509. */
  1510. protected function parents($args)
  1511. {
  1512. $target = $args['target'];
  1513. $until = $args['until'];
  1514. if (($volume = $this->volume($target)) == false
  1515. || ($tree = $volume->parents($target, false, $until)) == false) {
  1516. return array('error' => $this->error(self::ERROR_OPEN, '#' . $target));
  1517. }
  1518. return array('tree' => $tree);
  1519. }
  1520. /**
  1521. * Return new created thumbnails list
  1522. *
  1523. * @param array command arguments
  1524. *
  1525. * @return array
  1526. * @throws ImagickException
  1527. * @throws elFinderAbortException
  1528. * @author Dmitry (dio) Levashov
  1529. */
  1530. protected function tmb($args)
  1531. {
  1532. $result = array('images' => array());
  1533. $targets = $args['targets'];
  1534. foreach ($targets as $target) {
  1535. elFinder::checkAborted();
  1536. if (($volume = $this->volume($target)) != false
  1537. && (($tmb = $volume->tmb($target)) != false)) {
  1538. $result['images'][$target] = $tmb;
  1539. }
  1540. }
  1541. return $result;
  1542. }
  1543. /**
  1544. * Download files/folders as an archive file
  1545. * 1st: Return srrsy contains download archive file info
  1546. * 2nd: Return array contains opened file pointer, root itself and required headers
  1547. *
  1548. * @param array command arguments
  1549. *
  1550. * @return array
  1551. * @throws Exception
  1552. * @author Naoki Sawada
  1553. */
  1554. protected function zipdl($args)
  1555. {
  1556. $targets = $args['targets'];
  1557. $download = !empty($args['download']);
  1558. $h404 = 'HTTP/1.x 404 Not Found';
  1559. if (!$download) {
  1560. //1st: Return array contains download archive file info
  1561. $error = array(self::ERROR_ARCHIVE);
  1562. if (($volume = $this->volume($targets[0])) !== false) {
  1563. if ($dlres = $volume->zipdl($targets)) {
  1564. $path = $dlres['path'];
  1565. register_shutdown_function(array('elFinder', 'rmFileInDisconnected'), $path);
  1566. if (count($targets) === 1) {
  1567. $name = basename($volume->path($targets[0]));
  1568. } else {
  1569. $name = $dlres['prefix'] . '_Files';
  1570. }
  1571. $name .= '.' . $dlres['ext'];
  1572. $uniqid = uniqid();
  1573. $this->session->set('zipdl' . $uniqid, basename($path));
  1574. $result = array(
  1575. 'zipdl' => array(
  1576. 'file' => $uniqid,
  1577. 'name' => $name,
  1578. 'mime' => $dlres['mime']
  1579. )
  1580. );
  1581. return $result;
  1582. }
  1583. $error = array_merge($error, $volume->error());
  1584. }
  1585. return array('error' => $error);
  1586. } else {
  1587. // 2nd: Return array contains opened file session key, root itself and required headers
  1588. if (count($targets) !== 4 || ($volume = $this->volume($targets[0])) == false || !($file = $this->session->get('zipdl' . $targets[1]))) {
  1589. return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
  1590. }
  1591. $this->session->remove('zipdl' . $targets[1]);
  1592. if ($volume->commandDisabled('zipdl')) {
  1593. return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
  1594. }
  1595. $path = $volume->getTempPath() . DIRECTORY_SEPARATOR . basename($file);
  1596. if (!is_readable($path) || !is_writable($path)) {
  1597. return array('error' => 'File not found', 'header' => $h404, 'raw' => true);
  1598. }
  1599. // register auto delete on shutdown
  1600. $GLOBALS['elFinderTempFiles'][$path] = true;
  1601. // for HTTP headers
  1602. $name = $targets[2];
  1603. $mime = $targets[3];
  1604. $filenameEncoded = rawurlencode($name);
  1605. if (strpos($filenameEncoded, '%') === false) { // ASCII only
  1606. $filename = 'filename="' . $name . '"';
  1607. } else {
  1608. $ua = $_SERVER['HTTP_USER_AGENT'];
  1609. if (preg_match('/MSIE [4-8]/', $ua)) { // IE < 9 do not support RFC 6266 (RFC 2231/RFC 5987)
  1610. $filename = 'filename="' . $filenameEncoded . '"';
  1611. } elseif (strpos($ua, 'Chrome') === false && strpos($ua, 'Safari') !== false && preg_match('#Version/[3-5]#', $ua)) { // Safari < 6
  1612. $filename = 'filename="' . str_replace('"', '', $name) . '"';
  1613. } else { // RFC 6266 (RFC 2231/RFC 5987)
  1614. $filename = 'filename*=UTF-8\'\'' . $filenameEncoded;
  1615. }
  1616. }
  1617. $fp = fopen($path, 'rb');
  1618. $file = fstat($fp);
  1619. $result = array(
  1620. 'pointer' => $fp,
  1621. 'header' => array(
  1622. 'Content-Type: ' . $mime,
  1623. 'Content-Disposition: attachment; ' . $filename,
  1624. 'Content-Transfer-Encoding: binary',
  1625. 'Content-Length: ' . $file['size'],
  1626. 'Accept-Ranges: none',
  1627. 'Connection: close'
  1628. )
  1629. );
  1630. return $result;
  1631. }
  1632. }
  1633. /**
  1634. * Required to output file in browser when volume URL is not set
  1635. * Return array contains opened file pointer, root itself and required headers
  1636. *
  1637. * @param array command arguments
  1638. *
  1639. * @return array
  1640. * @throws elFinderAbortException
  1641. * @author Dmitry (dio) Levashov
  1642. */
  1643. protected function file($args)
  1644. {
  1645. $target = $args['target'];
  1646. $download = !empty($args['download']);
  1647. $onetime = !empty($args['onetime']);
  1648. //$h304 = 'HTTP/1.1 304 Not Modified';
  1649. //$h403 = 'HTTP/1.0 403 Access Denied';
  1650. $h404 = 'HTTP/1.0 404 Not Found';
  1651. $a404 = array('error' => 'File not found', 'header' => $h404, 'raw' => true);
  1652. if ($onetime) {
  1653. $volume = null;
  1654. $tmpdir = elFinder::$commonTempPath;
  1655. if (!$tmpdir || !is_file($tmpf = $tmpdir . DIRECTORY_SEPARATOR . 'ELF' . $target)) {
  1656. return $a404;
  1657. }
  1658. $GLOBALS['elFinderTempFiles'][$tmpf] = true;
  1659. if ($file = json_decode(file_get_contents($tmpf), true)) {
  1660. $src = base64_decode($file['file']);
  1661. if (!is_file($src) || !($fp = fopen($src, 'rb'))) {
  1662. return $a404;
  1663. }
  1664. if (strpos($src, $tmpdir) === 0) {
  1665. $GLOBALS['elFinderTempFiles'][$src] = true;
  1666. }
  1667. unset($file['file']);
  1668. $file['read'] = true;
  1669. $file['size'] = filesize($src);
  1670. } else {
  1671. return $a404;
  1672. }
  1673. } else {
  1674. if (($volume = $this->volume($target)) == false) {
  1675. return $a404;
  1676. }
  1677. if (($file = $volume->file($target)) == false) {
  1678. return $a404;
  1679. }
  1680. if (!$file['read']) {
  1681. return $a404;
  1682. }
  1683. if (($fp = $volume->open($target)) == false) {
  1684. return $a404;
  1685. }
  1686. }
  1687. // check aborted by user
  1688. elFinder::checkAborted();
  1689. // allow change MIME type by 'file.pre' callback functions
  1690. $mime = isset($args['mime']) ? $args['mime'] : $file['mime'];
  1691. if ($download || $onetime) {
  1692. $disp = 'attachment';
  1693. } else {
  1694. $dispInlineRegex = $volume->getOption('dispInlineRegex');
  1695. $inlineRegex = false;
  1696. if ($dispInlineRegex) {
  1697. $inlineRegex = '#' . str_replace('#', '\\#', $dispInlineRegex) . '#';
  1698. try {
  1699. preg_match($inlineRegex, '');
  1700. } catch (Exception $e) {
  1701. $inlineRegex = false;
  1702. }
  1703. }
  1704. if (!$inlineRegex) {
  1705. $inlineRegex = '#^(?:(?:image|text)|application/x-shockwave-flash$)#';
  1706. }
  1707. $disp = preg_match($inlineRegex, $mime) ? 'inline' : 'attachment';
  1708. }
  1709. $filenameEncoded = rawurlencode($file['name']);
  1710. if (strpos($filenameEncoded, '%') === false) { // ASCII only
  1711. $filename = 'filename="' . $file['name'] . '"';
  1712. } else {
  1713. $ua = isset($_SERVER['HTTP_USER_AGENT'])? $_SERVER['HTTP_USER_AGENT'] : '';
  1714. if (preg_match('/MSIE [4-8]/', $ua)) { // IE < 9 do not support RFC 6266 (RFC 2231/RFC 5987)
  1715. $filename = 'filename="' . $filenameEncoded . '"';
  1716. } elseif (strpos($ua, 'Chrome') === false && strpos($ua, 'Safari') !== false && preg_match('#Version/[3-5]#', $ua)) { // Safari < 6
  1717. $filename = 'filename="' . str_replace('"', '', $file['name']) . '"';
  1718. } else { // RFC 6266 (RFC 2231/RFC 5987)
  1719. $filename = 'filename*=UTF-8\'\'' . $filenameEncoded;
  1720. }
  1721. }
  1722. if ($args['cpath'] && $args['reqid']) {
  1723. setcookie('elfdl' . $args['reqid'], '1', 0, $args['cpath']);
  1724. }
  1725. $result = array(
  1726. 'volume' => $volume,
  1727. 'pointer' => $fp,
  1728. 'info' => $file,
  1729. 'header' => array(
  1730. 'Content-Type: ' . $mime,
  1731. 'Content-Disposition: ' . $disp . '; ' . $filename,
  1732. 'Content-Transfer-Encoding: binary',
  1733. 'Content-Length: ' . $file['size'],
  1734. 'Last-Modified: ' . gmdate('D, d M Y H:i:s T', $file['ts']),
  1735. 'Connection: close'
  1736. )
  1737. );
  1738. if (!$onetime) {
  1739. // add cache control headers
  1740. if ($cacheHeaders = $volume->getOption('cacheHeaders')) {
  1741. $result['header'] = array_merge($result['header'], $cacheHeaders);
  1742. }
  1743. // check 'xsendfile'
  1744. $xsendfile = $volume->getOption('xsendfile');
  1745. $path = null;
  1746. if ($xsendfile) {
  1747. $info = stream_get_meta_data($fp);
  1748. if ($path = empty($info['uri']) ? null : $info['uri']) {
  1749. $basePath = rtrim($volume->getOption('xsendfilePath'), DIRECTORY_SEPARATOR);
  1750. if ($basePath) {
  1751. $root = rtrim($volume->getRootPath(), DIRECTORY_SEPARATOR);
  1752. if (strpos($path, $root) === 0) {
  1753. $path = $basePath . substr($path, strlen($root));
  1754. } else {
  1755. $path = null;
  1756. }
  1757. }
  1758. }
  1759. }
  1760. if ($path) {
  1761. $result['header'][] = $xsendfile . ': ' . $path;
  1762. $result['info']['xsendfile'] = $xsendfile;
  1763. }
  1764. }
  1765. // add "Content-Location" if file has url data
  1766. if (isset($file['url']) && $file['url'] && $file['url'] != 1) {
  1767. $result['header'][] = 'Content-Location: ' . $file['url'];
  1768. }
  1769. return $result;
  1770. }
  1771. /**
  1772. * Count total files size
  1773. *
  1774. * @param array command arguments
  1775. *
  1776. * @return array
  1777. * @throws elFinderAbortException
  1778. * @author Dmitry (dio) Levashov
  1779. */
  1780. protected function size($args)
  1781. {
  1782. $size = 0;
  1783. $files = 0;
  1784. $dirs = 0;
  1785. $itemCount = true;
  1786. $sizes = array();
  1787. foreach ($args['targets'] as $target) {
  1788. elFinder::checkAborted();
  1789. if (($volume = $this->volume($target)) == false
  1790. || ($file = $volume->file($target)) == false
  1791. || !$file['read']) {
  1792. return array('error' => $this->error(self::ERROR_OPEN, '#' . $target));
  1793. }
  1794. $volRes = $volume->size($target);
  1795. if (is_array($volRes)) {
  1796. $sizeInfo = array('size' => 0, 'fileCnt' => 0, 'dirCnt' => 0);
  1797. if (!empty($volRes['size'])) {
  1798. $sizeInfo['size'] = $volRes['size'];
  1799. $size += $volRes['size'];
  1800. }
  1801. if (!empty($volRes['files'])) {
  1802. $sizeInfo['fileCnt'] = $volRes['files'];
  1803. }
  1804. if (!empty($volRes['dirs'])) {
  1805. $sizeInfo['dirCnt'] = $volRes['dirs'];
  1806. }
  1807. if ($itemCount) {
  1808. $files += $sizeInfo['fileCnt'];
  1809. $dirs += $sizeInfo['dirCnt'];
  1810. }
  1811. $sizes[$target] = $sizeInfo;
  1812. } else if (is_numeric($volRes)) {
  1813. $size += $volRes;
  1814. $files = $dirs = 'unknown';
  1815. $itemCount = false;
  1816. }
  1817. }
  1818. return array('size' => $size, 'fileCnt' => $files, 'dirCnt' => $dirs, 'sizes' => $sizes);
  1819. }
  1820. /**
  1821. * Create directory
  1822. *
  1823. * @param array command arguments
  1824. *
  1825. * @return array
  1826. * @author Dmitry (dio) Levashov
  1827. **/
  1828. protected function mkdir($args)
  1829. {
  1830. $target = $args['target'];
  1831. $name = $args['name'];
  1832. $dirs = $args['dirs'];
  1833. if ($name === '' && !$dirs) {
  1834. return array('error' => $this->error(self::ERROR_INV_PARAMS, 'mkdir'));
  1835. }
  1836. if (($volume = $this->volume($target)) == false) {
  1837. return array('error' => $this->error(self::ERROR_MKDIR, $name, self::ERROR_TRGDIR_NOT_FOUND, '#' . $target));
  1838. }
  1839. if ($dirs) {
  1840. sort($dirs);
  1841. $reset = null;
  1842. $mkdirs = array();
  1843. foreach ($dirs as $dir) {
  1844. $tgt =& $mkdirs;
  1845. $_names = explode('/', trim($dir, '/'));
  1846. foreach ($_names as $_key => $_name) {
  1847. if (!isset($tgt[$_name])) {
  1848. $tgt[$_name] = array();
  1849. }
  1850. $tgt =& $tgt[$_name];
  1851. }
  1852. $tgt =& $reset;
  1853. }
  1854. $res = $this->ensureDirsRecursively($volume, $target, $mkdirs);
  1855. $ret = array(
  1856. 'added' => $res['stats'],
  1857. 'hashes' => $res['hashes']
  1858. );
  1859. if ($res['error']) {
  1860. $ret['warning'] = $this->error(self::ERROR_MKDIR, $res['error'][0], $volume->error());
  1861. }
  1862. return $ret;
  1863. } else {
  1864. return ($dir = $volume->mkdir($target, $name)) == false
  1865. ? array('error' => $this->error(self::ERROR_MKDIR, $name, $volume->error()))
  1866. : array('added' => array($dir));
  1867. }
  1868. }
  1869. /**
  1870. * Create empty file
  1871. *
  1872. * @param array command arguments
  1873. *
  1874. * @return array
  1875. * @author Dmitry (dio) Levashov
  1876. **/
  1877. protected function mkfile($args)
  1878. {
  1879. $target = $args['target'];
  1880. $name = $args['name'];
  1881. if (($volume = $this->volume($target)) == false) {
  1882. return array('error' => $this->error(self::ERROR_MKFILE, $name, self::ERROR_TRGDIR_NOT_FOUND, '#' . $target));
  1883. }
  1884. return ($file = $volume->mkfile($target, $args['name'])) == false
  1885. ? array('error' => $this->error(self::ERROR_MKFILE, $name, $volume->error()))
  1886. : array('added' => array($file));
  1887. }
  1888. /**
  1889. * Rename file, Accept multiple items >= API 2.1031
  1890. *
  1891. * @param array $args
  1892. *
  1893. * @return array
  1894. * @throws elFinderAbortException
  1895. * @author Dmitry (dio) Levashov
  1896. * @author Naoki Sawada
  1897. */
  1898. protected function rename($args)
  1899. {
  1900. $target = $args['target'];
  1901. $name = $args['name'];
  1902. $query = (strpos($args['q'], '*') !== false) ? $args['q'] : '';
  1903. $targets = $args['targets'];
  1904. $rms = array();
  1905. $notfounds = array();
  1906. $locked = array();
  1907. $errs = array();
  1908. $files = array();
  1909. $removed = array();
  1910. $res = array();
  1911. $type = 'normal';
  1912. if (!($volume = $this->volume($target))) {
  1913. return array('error' => $this->error(self::ERROR_RENAME, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  1914. }
  1915. if ($targets) {
  1916. array_unshift($targets, $target);
  1917. foreach ($targets as $h) {
  1918. if ($rm = $volume->file($h)) {
  1919. if ($this->itemLocked($h)) {
  1920. $locked[] = $rm['name'];
  1921. } else {
  1922. $rm['realpath'] = $volume->realpath($h);
  1923. $rms[] = $rm;
  1924. }
  1925. } else {
  1926. $notfounds[] = '#' . $h;
  1927. }
  1928. }
  1929. if (!$rms) {
  1930. $res['error'] = array();
  1931. if ($notfounds) {
  1932. $res['error'] = array(self::ERROR_RENAME, join(', ', $notfounds), self::ERROR_FILE_NOT_FOUND);
  1933. }
  1934. if ($locked) {
  1935. array_push($res['error'], self::ERROR_LOCKED, join(', ', $locked));
  1936. }
  1937. return $res;
  1938. }
  1939. $res['warning'] = array();
  1940. if ($notfounds) {
  1941. array_push($res['warning'], self::ERROR_RENAME, join(', ', $notfounds), self::ERROR_FILE_NOT_FOUND);
  1942. }
  1943. if ($locked) {
  1944. array_push($res['warning'], self::ERROR_LOCKED, join(', ', $locked));
  1945. }
  1946. if ($query) {
  1947. // batch rename
  1948. $splits = elFinder::splitFileExtention($query);
  1949. if ($splits[1] && $splits[0] === '*') {
  1950. $type = 'extention';
  1951. $name = $splits[1];
  1952. } else if (strlen($splits[0]) > 1) {
  1953. if (substr($splits[0], -1) === '*') {
  1954. $type = 'prefix';
  1955. $name = substr($splits[0], 0, strlen($splits[0]) - 1);
  1956. } else if (substr($splits[0], 0, 1) === '*') {
  1957. $type = 'suffix';
  1958. $name = substr($splits[0], 1);
  1959. }
  1960. }
  1961. if ($type !== 'normal') {
  1962. if (!empty($this->listeners['rename.pre'])) {
  1963. $_args = array('name' => $name);
  1964. foreach ($this->listeners['rename.pre'] as $handler) {
  1965. $_res = call_user_func_array($handler, array('rename', &$_args, $this, $volume));
  1966. if (!empty($_res['preventexec'])) {
  1967. break;
  1968. }
  1969. }
  1970. $name = $_args['name'];
  1971. }
  1972. }
  1973. }
  1974. foreach ($rms as $rm) {
  1975. if ($type === 'normal') {
  1976. $rname = $volume->uniqueName($volume->realpath($rm['phash']), $name, '', false);
  1977. } else {
  1978. $rname = $name;
  1979. if ($type === 'extention') {
  1980. $splits = elFinder::splitFileExtention($rm['name']);
  1981. $rname = $splits[0] . '.' . $name;
  1982. } else if ($type === 'prefix') {
  1983. $rname = $name . $rm['name'];
  1984. } else if ($type === 'suffix') {
  1985. $splits = elFinder::splitFileExtention($rm['name']);
  1986. $rname = $splits[0] . $name . ($splits[1] ? ('.' . $splits[1]) : '');
  1987. }
  1988. $rname = $volume->uniqueName($volume->realpath($rm['phash']), $rname, '', true);
  1989. }
  1990. if ($file = $volume->rename($rm['hash'], $rname)) {
  1991. $files[] = $file;
  1992. $removed[] = $rm;
  1993. } else {
  1994. $errs[] = $rm['name'];
  1995. }
  1996. }
  1997. if (!$files) {
  1998. $res['error'] = $this->error(self::ERROR_RENAME, join(', ', $errs), $volume->error());
  1999. if (!$res['warning']) {
  2000. unset($res['warning']);
  2001. }
  2002. return $res;
  2003. }
  2004. if ($errs) {
  2005. array_push($res['warning'], self::ERROR_RENAME, join(', ', $errs), $volume->error());
  2006. }
  2007. if (!$res['warning']) {
  2008. unset($res['warning']);
  2009. }
  2010. $res['added'] = $files;
  2011. $res['removed'] = $removed;
  2012. return $res;
  2013. } else {
  2014. if (!($rm = $volume->file($target))) {
  2015. return array('error' => $this->error(self::ERROR_RENAME, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  2016. }
  2017. if ($this->itemLocked($target)) {
  2018. return array('error' => $this->error(self::ERROR_LOCKED, $rm['name']));
  2019. }
  2020. $rm['realpath'] = $volume->realpath($target);
  2021. return ($file = $volume->rename($target, $name)) == false
  2022. ? array('error' => $this->error(self::ERROR_RENAME, $rm['name'], $volume->error()))
  2023. : array('added' => array($file), 'removed' => array($rm));
  2024. }
  2025. }
  2026. /**
  2027. * Duplicate file - create copy with "copy %d" suffix
  2028. *
  2029. * @param array $args command arguments
  2030. *
  2031. * @return array
  2032. * @throws elFinderAbortException
  2033. * @author Dmitry (dio) Levashov
  2034. */
  2035. protected function duplicate($args)
  2036. {
  2037. $targets = is_array($args['targets']) ? $args['targets'] : array();
  2038. $result = array();
  2039. $suffix = empty($args['suffix']) ? 'copy' : $args['suffix'];
  2040. $this->itemLock($targets);
  2041. foreach ($targets as $target) {
  2042. elFinder::checkAborted();
  2043. if (($volume = $this->volume($target)) == false
  2044. || ($src = $volume->file($target)) == false) {
  2045. $result['warning'] = $this->error(self::ERROR_COPY, '#' . $target, self::ERROR_FILE_NOT_FOUND);
  2046. break;
  2047. }
  2048. if (($file = $volume->duplicate($target, $suffix)) == false) {
  2049. $result['warning'] = $this->error($volume->error());
  2050. break;
  2051. }
  2052. }
  2053. return $result;
  2054. }
  2055. /**
  2056. * Remove dirs/files
  2057. *
  2058. * @param array command arguments
  2059. *
  2060. * @return array
  2061. * @throws elFinderAbortException
  2062. * @author Dmitry (dio) Levashov
  2063. */
  2064. protected function rm($args)
  2065. {
  2066. $targets = is_array($args['targets']) ? $args['targets'] : array();
  2067. $result = array('removed' => array());
  2068. foreach ($targets as $target) {
  2069. elFinder::checkAborted();
  2070. if (($volume = $this->volume($target)) == false) {
  2071. $result['warning'] = $this->error(self::ERROR_RM, '#' . $target, self::ERROR_FILE_NOT_FOUND);
  2072. break;
  2073. }
  2074. if ($this->itemLocked($target)) {
  2075. $rm = $volume->file($target);
  2076. $result['warning'] = $this->error(self::ERROR_LOCKED, $rm['name']);
  2077. break;
  2078. }
  2079. if (!$volume->rm($target)) {
  2080. $result['warning'] = $this->error($volume->error());
  2081. break;
  2082. }
  2083. }
  2084. return $result;
  2085. }
  2086. /**
  2087. * Return has subdirs
  2088. *
  2089. * @param array command arguments
  2090. *
  2091. * @return array
  2092. * @author Dmitry Naoki Sawada
  2093. **/
  2094. protected function subdirs($args)
  2095. {
  2096. $result = array('subdirs' => array());
  2097. $targets = $args['targets'];
  2098. foreach ($targets as $target) {
  2099. if (($volume = $this->volume($target)) !== false) {
  2100. $result['subdirs'][$target] = $volume->subdirs($target) ? 1 : 0;
  2101. }
  2102. }
  2103. return $result;
  2104. }
  2105. /**
  2106. * Gateway for custom contents editor
  2107. *
  2108. * @param array $args command arguments
  2109. *
  2110. * @return array
  2111. * @author Naoki Sawada
  2112. */
  2113. protected function editor($args = array())
  2114. {
  2115. /* @var elFinderEditor $editor */
  2116. $name = $args['name'];
  2117. if (is_array($name)) {
  2118. $res = array();
  2119. foreach ($name as $c) {
  2120. $class = 'elFinderEditor' . $c;
  2121. if (class_exists($class)) {
  2122. $editor = new $class($this, $args['args']);
  2123. $res[$c] = $editor->enabled();
  2124. } else {
  2125. $res[$c] = 0;
  2126. }
  2127. }
  2128. return $res;
  2129. } else {
  2130. $class = 'elFinderEditor' . $name;
  2131. $method = '';
  2132. if (class_exists($class)) {
  2133. $editor = new $class($this, $args['args']);
  2134. $method = $args['method'];
  2135. if ($editor->isAllowedMethod($method) && method_exists($editor, $method)) {
  2136. return $editor->$method();
  2137. }
  2138. }
  2139. return array('error', $this->error(self::ERROR_UNKNOWN_CMD, 'editor.' . $name . '.' . $method));
  2140. }
  2141. }
  2142. /**
  2143. * Abort current request and make flag file to running check
  2144. *
  2145. * @param array $args
  2146. *
  2147. * @return void
  2148. */
  2149. protected function abort($args = array())
  2150. {
  2151. if (!elFinder::$connectionFlagsPath || $_SERVER['REQUEST_METHOD'] === 'HEAD') {
  2152. return;
  2153. }
  2154. $flagFile = elFinder::$connectionFlagsPath . DIRECTORY_SEPARATOR . 'elfreq%s';
  2155. if (!empty($args['makeFile'])) {
  2156. self::$abortCheckFile = sprintf($flagFile, $args['makeFile']);
  2157. touch(self::$abortCheckFile);
  2158. $GLOBALS['elFinderTempFiles'][self::$abortCheckFile] = true;
  2159. return;
  2160. }
  2161. $file = !empty($args['id']) ? sprintf($flagFile, $args['id']) : self::$abortCheckFile;
  2162. $file && is_file($file) && unlink($file);
  2163. }
  2164. /**
  2165. * Get remote contents
  2166. *
  2167. * @param string $url target url
  2168. * @param int $timeout timeout (sec)
  2169. * @param int $redirect_max redirect max count
  2170. * @param string $ua
  2171. * @param resource $fp
  2172. *
  2173. * @return string, resource or bool(false)
  2174. * @retval string contents
  2175. * @retval resource conttents
  2176. * @rettval false error
  2177. * @author Naoki Sawada
  2178. **/
  2179. protected function get_remote_contents(&$url, $timeout = 30, $redirect_max = 5, $ua = 'Mozilla/5.0', $fp = null)
  2180. {
  2181. if (preg_match('~^(?:ht|f)tps?://[-_.!\~*\'()a-z0-9;/?:\@&=+\$,%#\*\[\]]+~i', $url)) {
  2182. $info = parse_url($url);
  2183. $host = trim(strtolower($info['host']), '.');
  2184. // do not support IPv6 address
  2185. if (preg_match('/^\[.*\]$/', $host)) {
  2186. return false;
  2187. }
  2188. // do not support non dot host
  2189. if (strpos($host, '.') === false) {
  2190. return false;
  2191. }
  2192. // do not support URL-encoded host
  2193. if (strpos($host, '%') !== false) {
  2194. return false;
  2195. }
  2196. // disallow including "localhost" and "localdomain"
  2197. if (preg_match('/\b(?:localhost|localdomain)\b/', $host)) {
  2198. return false;
  2199. }
  2200. // wildcard DNS (e.g xip.io)
  2201. if (preg_match('/0x[0-9a-f]+|[0-9]+(?:\.(?:0x[0-9a-f]+|[0-9]+)){1,3}/', $host)) {
  2202. $host = gethostbyname($host);
  2203. }
  2204. // check IPv4 local loopback, private network and link local
  2205. if (preg_match('/^0x[0-9a-f]+|[0-9]+(?:\.(?:0x[0-9a-f]+|[0-9]+)){1,3}$/', $host, $m)) {
  2206. $long = (int)sprintf('%u', ip2long($host));
  2207. if (!$long) {
  2208. return false;
  2209. }
  2210. $local = (int)sprintf('%u', ip2long('127.255.255.255')) >> 24;
  2211. $prv1 = (int)sprintf('%u', ip2long('10.255.255.255')) >> 24;
  2212. $prv2 = (int)sprintf('%u', ip2long('172.31.255.255')) >> 20;
  2213. $prv3 = (int)sprintf('%u', ip2long('192.168.255.255')) >> 16;
  2214. $link = (int)sprintf('%u', ip2long('169.254.255.255')) >> 16;
  2215. if ($long >> 24 === $local || $long >> 24 === $prv1 || $long >> 20 === $prv2 || $long >> 16 === $prv3 || $long >> 16 === $link) {
  2216. return false;
  2217. }
  2218. }
  2219. // dose not support 'user' and 'pass' for security reasons
  2220. $url = $info['scheme'].'://'.$host.(!empty($info['port'])? (':'.$info['port']) : '').$info['path'].(!empty($info['query'])? ('?'.$info['query']) : '').(!empty($info['fragment'])? ('#'.$info['fragment']) : '');
  2221. // check by URL upload filter
  2222. if ($this->urlUploadFilter && is_callable($this->urlUploadFilter)) {
  2223. if (!call_user_func_array($this->urlUploadFilter, array($url, $this))) {
  2224. return false;
  2225. }
  2226. }
  2227. $method = (function_exists('curl_exec') && !ini_get('safe_mode') && !ini_get('open_basedir')) ? 'curl_get_contents' : 'fsock_get_contents';
  2228. return $this->$method($url, $timeout, $redirect_max, $ua, $fp);
  2229. }
  2230. return false;
  2231. }
  2232. /**
  2233. * Get remote contents with cURL
  2234. *
  2235. * @param string $url target url
  2236. * @param int $timeout timeout (sec)
  2237. * @param int $redirect_max redirect max count
  2238. * @param string $ua
  2239. * @param resource $outfp
  2240. *
  2241. * @return string, resource or bool(false)
  2242. * @retval string contents
  2243. * @retval resource conttents
  2244. * @retval false error
  2245. * @author Naoki Sawada
  2246. **/
  2247. protected function curl_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp)
  2248. {
  2249. $ch = curl_init();
  2250. curl_setopt($ch, CURLOPT_URL, $url);
  2251. curl_setopt($ch, CURLOPT_HEADER, false);
  2252. if ($outfp) {
  2253. curl_setopt($ch, CURLOPT_FILE, $outfp);
  2254. } else {
  2255. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  2256. curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
  2257. }
  2258. curl_setopt($ch, CURLOPT_LOW_SPEED_LIMIT, 1);
  2259. curl_setopt($ch, CURLOPT_LOW_SPEED_TIME, $timeout);
  2260. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  2261. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  2262. curl_setopt($ch, CURLOPT_MAXREDIRS, $redirect_max);
  2263. curl_setopt($ch, CURLOPT_USERAGENT, $ua);
  2264. $result = curl_exec($ch);
  2265. $url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
  2266. curl_close($ch);
  2267. return $outfp ? $outfp : $result;
  2268. }
  2269. /**
  2270. * Get remote contents with fsockopen()
  2271. *
  2272. * @param string $url url
  2273. * @param int $timeout timeout (sec)
  2274. * @param int $redirect_max redirect max count
  2275. * @param string $ua
  2276. * @param resource $outfp
  2277. *
  2278. * @return string, resource or bool(false)
  2279. * @retval string contents
  2280. * @retval resource conttents
  2281. * @retval false error
  2282. * @throws elFinderAbortException
  2283. * @author Naoki Sawada
  2284. */
  2285. protected function fsock_get_contents(&$url, $timeout, $redirect_max, $ua, $outfp)
  2286. {
  2287. $connect_timeout = 3;
  2288. $connect_try = 3;
  2289. $method = 'GET';
  2290. $readsize = 4096;
  2291. $ssl = '';
  2292. $getSize = null;
  2293. $headers = '';
  2294. $arr = parse_url($url);
  2295. if (!$arr) {
  2296. // Bad request
  2297. return false;
  2298. }
  2299. if ($arr['scheme'] === 'https') {
  2300. $ssl = 'ssl://';
  2301. }
  2302. // query
  2303. $arr['query'] = isset($arr['query']) ? '?' . $arr['query'] : '';
  2304. // port
  2305. $port = isset($arr['port']) ? $arr['port'] : '';
  2306. $arr['port'] = $port ? $port : ($ssl ? 443 : 80);
  2307. $url_base = $arr['scheme'] . '://' . $arr['host'] . ($port ? (':' . $port) : '');
  2308. $url_path = isset($arr['path']) ? $arr['path'] : '/';
  2309. $uri = $url_path . $arr['query'];
  2310. $query = $method . ' ' . $uri . " HTTP/1.0\r\n";
  2311. $query .= "Host: " . $arr['host'] . "\r\n";
  2312. $query .= "Accept: */*\r\n";
  2313. $query .= "Connection: close\r\n";
  2314. if (!empty($ua)) $query .= "User-Agent: " . $ua . "\r\n";
  2315. if (!is_null($getSize)) $query .= 'Range: bytes=0-' . ($getSize - 1) . "\r\n";
  2316. $query .= $headers;
  2317. $query .= "\r\n";
  2318. $fp = $connect_try_count = 0;
  2319. while (!$fp && $connect_try_count < $connect_try) {
  2320. $errno = 0;
  2321. $errstr = "";
  2322. $fp = fsockopen(
  2323. $ssl . $arr['host'],
  2324. $arr['port'],
  2325. $errno, $errstr, $connect_timeout);
  2326. if ($fp) break;
  2327. $connect_try_count++;
  2328. if (connection_aborted()) {
  2329. throw new elFinderAbortException();
  2330. }
  2331. sleep(1); // wait 1sec
  2332. }
  2333. if (!$fp) {
  2334. return false;
  2335. }
  2336. $fwrite = 0;
  2337. for ($written = 0; $written < strlen($query); $written += $fwrite) {
  2338. $fwrite = fwrite($fp, substr($query, $written));
  2339. if (!$fwrite) {
  2340. break;
  2341. }
  2342. }
  2343. if ($timeout) {
  2344. socket_set_timeout($fp, $timeout);
  2345. }
  2346. $_response = '';
  2347. $header = '';
  2348. while ($_response !== "\r\n") {
  2349. $_response = fgets($fp, $readsize);
  2350. $header .= $_response;
  2351. };
  2352. $rccd = array_pad(explode(' ', $header, 2), 2, ''); // array('HTTP/1.1','200')
  2353. $rc = (int)$rccd[1];
  2354. $ret = false;
  2355. // Redirect
  2356. switch ($rc) {
  2357. case 307: // Temporary Redirect
  2358. case 303: // See Other
  2359. case 302: // Moved Temporarily
  2360. case 301: // Moved Permanently
  2361. $matches = array();
  2362. if (preg_match('/^Location: (.+?)(#.+)?$/im', $header, $matches) && --$redirect_max > 0) {
  2363. $_url = $url;
  2364. $url = trim($matches[1]);
  2365. if (!preg_match('/^https?:\//', $url)) { // no scheme
  2366. if ($url{0} != '/') { // Relative path
  2367. // to Absolute path
  2368. $url = substr($url_path, 0, strrpos($url_path, '/')) . '/' . $url;
  2369. }
  2370. // add sheme,host
  2371. $url = $url_base . $url;
  2372. }
  2373. if ($_url === $url) {
  2374. sleep(1);
  2375. }
  2376. fclose($fp);
  2377. return $this->fsock_get_contents($url, $timeout, $redirect_max, $ua, $outfp);
  2378. }
  2379. break;
  2380. case 200:
  2381. $ret = true;
  2382. }
  2383. if (!$ret) {
  2384. fclose($fp);
  2385. return false;
  2386. }
  2387. $body = '';
  2388. if (!$outfp) {
  2389. $outfp = fopen('php://temp', 'rwb');
  2390. $body = true;
  2391. }
  2392. while (fwrite($outfp, fread($fp, $readsize))) {
  2393. if ($timeout) {
  2394. $_status = socket_get_status($fp);
  2395. if ($_status['timed_out']) {
  2396. fclose($outfp);
  2397. fclose($fp);
  2398. return false; // Request Time-out
  2399. }
  2400. }
  2401. }
  2402. if ($body) {
  2403. rewind($outfp);
  2404. $body = stream_get_contents($outfp);
  2405. fclose($outfp);
  2406. $outfp = null;
  2407. }
  2408. fclose($fp);
  2409. return $outfp ? $outfp : $body; // Data
  2410. }
  2411. /**
  2412. * Parse Data URI scheme
  2413. *
  2414. * @param string $str
  2415. * @param array $extTable
  2416. * @param array $args
  2417. *
  2418. * @return array
  2419. * @author Naoki Sawada
  2420. */
  2421. protected function parse_data_scheme($str, $extTable, $args = null)
  2422. {
  2423. $data = $name = $mime = '';
  2424. // Scheme 'data://' require `allow_url_fopen` and `allow_url_include`
  2425. if ($fp = fopen('data://' . substr($str, 5), 'rb')) {
  2426. if ($data = stream_get_contents($fp)) {
  2427. $meta = stream_get_meta_data($fp);
  2428. $mime = $meta['mediatype'];
  2429. }
  2430. fclose($fp);
  2431. } else if (preg_match('~^data:(.+?/.+?)?(?:;charset=.+?)?;base64,~', substr($str, 0, 128), $m)) {
  2432. $data = base64_decode(substr($str, strlen($m[0])));
  2433. if ($m[1]) {
  2434. $mime = $m[1];
  2435. }
  2436. }
  2437. if ($data) {
  2438. $ext = ($mime && isset($extTable[$mime])) ? '.' . $extTable[$mime] : '';
  2439. // Set name if name eq 'image.png' and $args has 'name' array, e.g. clipboard data
  2440. if (is_array($args['name']) && isset($args['name'][0])) {
  2441. $name = $args['name'][0];
  2442. if ($ext) {
  2443. $name = preg_replace('/\.[^.]*$/', '', $name);
  2444. }
  2445. } else {
  2446. $name = substr(md5($data), 0, 8);
  2447. }
  2448. $name .= $ext;
  2449. } else {
  2450. $data = $name = '';
  2451. }
  2452. return array($data, $name);
  2453. }
  2454. /**
  2455. * Detect file MIME Type by local path
  2456. *
  2457. * @param string $path Local path
  2458. *
  2459. * @return string file MIME Type
  2460. * @author Naoki Sawada
  2461. */
  2462. protected function detectMimeType($path)
  2463. {
  2464. static $type, $finfo;
  2465. if (!$type) {
  2466. if (class_exists('finfo', false)) {
  2467. $tmpFileInfo = explode(';', finfo_file(finfo_open(FILEINFO_MIME), __FILE__));
  2468. } else {
  2469. $tmpFileInfo = false;
  2470. }
  2471. $regexp = '/text\/x\-(php|c\+\+)/';
  2472. if ($tmpFileInfo && preg_match($regexp, array_shift($tmpFileInfo))) {
  2473. $type = 'finfo';
  2474. $finfo = finfo_open(FILEINFO_MIME);
  2475. } elseif (function_exists('mime_content_type')
  2476. && preg_match($regexp, array_shift(explode(';', mime_content_type(__FILE__))))) {
  2477. $type = 'mime_content_type';
  2478. } elseif (function_exists('getimagesize')) {
  2479. $type = 'getimagesize';
  2480. } else {
  2481. $type = 'none';
  2482. }
  2483. }
  2484. $mime = '';
  2485. if ($type === 'finfo') {
  2486. $mime = finfo_file($finfo, $path);
  2487. } elseif ($type === 'mime_content_type') {
  2488. $mime = mime_content_type($path);
  2489. } elseif ($type === 'getimagesize') {
  2490. if ($img = getimagesize($path)) {
  2491. $mime = $img['mime'];
  2492. }
  2493. }
  2494. if ($mime) {
  2495. $mime = explode(';', $mime);
  2496. $mime = trim($mime[0]);
  2497. if (in_array($mime, array('application/x-empty', 'inode/x-empty'))) {
  2498. // finfo return this mime for empty files
  2499. $mime = 'text/plain';
  2500. } elseif ($mime == 'application/x-zip') {
  2501. // http://elrte.org/redmine/issues/163
  2502. $mime = 'application/zip';
  2503. }
  2504. }
  2505. return $mime ? $mime : 'unknown';
  2506. }
  2507. /**
  2508. * Detect file type extension by local path
  2509. *
  2510. * @param object $volume elFinderVolumeDriver instance
  2511. * @param string $path Local path
  2512. * @param string $name Filename to save
  2513. *
  2514. * @return string file type extension with dot
  2515. * @author Naoki Sawada
  2516. */
  2517. protected function detectFileExtension($volume, $path, $name)
  2518. {
  2519. $mime = $this->detectMimeType($path);
  2520. if ($mime === 'unknown') {
  2521. $mime = 'application/octet-stream';
  2522. }
  2523. $ext = $volume->getExtentionByMime($volume->mimeTypeNormalize($mime, $name));
  2524. return $ext ? ('.' . $ext) : '';
  2525. }
  2526. /**
  2527. * Get temporary directory path
  2528. *
  2529. * @param string $volumeTempPath
  2530. *
  2531. * @return string
  2532. * @author Naoki Sawada
  2533. */
  2534. private function getTempDir($volumeTempPath = null)
  2535. {
  2536. $testDirs = array();
  2537. if ($this->uploadTempPath) {
  2538. $testDirs[] = rtrim(realpath($this->uploadTempPath), DIRECTORY_SEPARATOR);
  2539. }
  2540. if ($volumeTempPath) {
  2541. $testDirs[] = rtrim(realpath($volumeTempPath), DIRECTORY_SEPARATOR);
  2542. }
  2543. if (elFinder::$commonTempPath) {
  2544. $testDirs[] = elFinder::$commonTempPath;
  2545. }
  2546. $tempDir = '';
  2547. foreach ($testDirs as $testDir) {
  2548. if (!$testDir || !is_dir($testDir)) continue;
  2549. if (is_writable($testDir)) {
  2550. $tempDir = $testDir;
  2551. $gc = time() - 3600;
  2552. foreach (glob($tempDir . DIRECTORY_SEPARATOR . 'ELF*') as $cf) {
  2553. if (filemtime($cf) < $gc) {
  2554. unlink($cf);
  2555. }
  2556. }
  2557. break;
  2558. }
  2559. }
  2560. return $tempDir;
  2561. }
  2562. /**
  2563. * chmod
  2564. *
  2565. * @param array command arguments
  2566. *
  2567. * @return array
  2568. * @throws elFinderAbortException
  2569. * @author David Bartle
  2570. */
  2571. protected function chmod($args)
  2572. {
  2573. $targets = $args['targets'];
  2574. $mode = intval((string)$args['mode'], 8);
  2575. if (!is_array($targets)) {
  2576. $targets = array($targets);
  2577. }
  2578. $result = array();
  2579. if (($volume = $this->volume($targets[0])) == false) {
  2580. $result['error'] = $this->error(self::ERROR_CONF_NO_VOL);
  2581. return $result;
  2582. }
  2583. $this->itemLock($targets);
  2584. $files = array();
  2585. $errors = array();
  2586. foreach ($targets as $target) {
  2587. elFinder::checkAborted();
  2588. $file = $volume->chmod($target, $mode);
  2589. if ($file) {
  2590. $files = array_merge($files, is_array($file) ? $file : array($file));
  2591. } else {
  2592. $errors = array_merge($errors, $volume->error());
  2593. }
  2594. }
  2595. if ($files) {
  2596. $result['changed'] = $files;
  2597. if ($errors) {
  2598. $result['warning'] = $this->error($errors);
  2599. }
  2600. } else {
  2601. $result['error'] = $this->error($errors);
  2602. }
  2603. return $result;
  2604. }
  2605. /**
  2606. * Check chunked upload files
  2607. *
  2608. * @param string $tmpname uploaded temporary file path
  2609. * @param string $chunk uploaded chunk file name
  2610. * @param string $cid uploaded chunked file id
  2611. * @param string $tempDir temporary dirctroy path
  2612. * @param null $volume
  2613. *
  2614. * @return array|null
  2615. * @throws elFinderAbortException
  2616. * @author Naoki Sawada
  2617. */
  2618. private function checkChunkedFile($tmpname, $chunk, $cid, $tempDir, $volume = null)
  2619. {
  2620. /* @var elFinderVolumeDriver $volume */
  2621. if (preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m)) {
  2622. $fname = $m[1];
  2623. $encname = md5($cid . '_' . $fname);
  2624. $base = $tempDir . DIRECTORY_SEPARATOR . 'ELF' . $encname;
  2625. $clast = intval($m[3]);
  2626. if (is_null($tmpname)) {
  2627. ignore_user_abort(true);
  2628. // chunked file upload fail
  2629. foreach (glob($base . '*') as $cf) {
  2630. unlink($cf);
  2631. }
  2632. ignore_user_abort(false);
  2633. return null;
  2634. }
  2635. $range = isset($_POST['range']) ? trim($_POST['range']) : '';
  2636. if ($range && preg_match('/^(\d+),(\d+),(\d+)$/', $range, $ranges)) {
  2637. $start = $ranges[1];
  2638. $len = $ranges[2];
  2639. $size = $ranges[3];
  2640. $tmp = $base . '.part';
  2641. $csize = filesize($tmpname);
  2642. $tmpExists = is_file($tmp);
  2643. if (!$tmpExists) {
  2644. // check upload max size
  2645. $uploadMaxSize = $volume ? $volume->getUploadMaxSize() : 0;
  2646. if ($uploadMaxSize > 0 && $size > $uploadMaxSize) {
  2647. return array(self::ERROR_UPLOAD_FILE_SIZE, false);
  2648. }
  2649. // make temp file
  2650. $ok = false;
  2651. if ($fp = fopen($tmp, 'wb')) {
  2652. flock($fp, LOCK_EX);
  2653. $ok = ftruncate($fp, $size);
  2654. flock($fp, LOCK_UN);
  2655. fclose($fp);
  2656. touch($base);
  2657. }
  2658. if (!$ok) {
  2659. unlink($tmp);
  2660. return array(self::ERROR_UPLOAD_TEMP, false);
  2661. }
  2662. } else {
  2663. // wait until makeing temp file (for anothor session)
  2664. $cnt = 1200; // Time limit 120 sec
  2665. while (!is_file($base) && --$cnt) {
  2666. usleep(100000); // wait 100ms
  2667. }
  2668. if (!$cnt) {
  2669. return array(self::ERROR_UPLOAD_TEMP, false);
  2670. }
  2671. }
  2672. // check size info
  2673. if ($len != $csize || $start + $len > $size || ($tmpExists && $size != filesize($tmp))) {
  2674. return array(self::ERROR_UPLOAD_TEMP, false);
  2675. }
  2676. // write chunk data
  2677. $src = fopen($tmpname, 'rb');
  2678. $fp = fopen($tmp, 'cb');
  2679. fseek($fp, $start);
  2680. $writelen = stream_copy_to_stream($src, $fp, $len);
  2681. fclose($fp);
  2682. fclose($src);
  2683. try {
  2684. // to check connection is aborted
  2685. elFinder::checkAborted();
  2686. } catch (elFinderAbortException $e) {
  2687. unlink($tmpname);
  2688. is_file($tmp) && unlink($tmp);
  2689. is_file($base) && unlink($base);
  2690. throw $e;
  2691. }
  2692. if ($writelen != $len) {
  2693. return array(self::ERROR_UPLOAD_TEMP, false);
  2694. }
  2695. // write counts
  2696. file_put_contents($base, "\0", FILE_APPEND | LOCK_EX);
  2697. if (filesize($base) >= $clast + 1) {
  2698. // Completion
  2699. unlink($base);
  2700. return array($tmp, $fname);
  2701. }
  2702. } else {
  2703. // old way
  2704. $part = $base . $m[2];
  2705. if (move_uploaded_file($tmpname, $part)) {
  2706. chmod($part, 0600);
  2707. if ($clast < count(glob($base . '*'))) {
  2708. $parts = array();
  2709. for ($i = 0; $i <= $clast; $i++) {
  2710. $name = $base . '.' . $i . '_' . $clast;
  2711. if (is_readable($name)) {
  2712. $parts[] = $name;
  2713. } else {
  2714. $parts = null;
  2715. break;
  2716. }
  2717. }
  2718. if ($parts) {
  2719. if (!is_file($base)) {
  2720. touch($base);
  2721. if ($resfile = tempnam($tempDir, 'ELF')) {
  2722. $target = fopen($resfile, 'wb');
  2723. foreach ($parts as $f) {
  2724. $fp = fopen($f, 'rb');
  2725. while (!feof($fp)) {
  2726. fwrite($target, fread($fp, 8192));
  2727. }
  2728. fclose($fp);
  2729. unlink($f);
  2730. }
  2731. fclose($target);
  2732. unlink($base);
  2733. return array($resfile, $fname);
  2734. }
  2735. unlink($base);
  2736. }
  2737. }
  2738. }
  2739. }
  2740. }
  2741. }
  2742. return array('', '');
  2743. }
  2744. /**
  2745. * Save uploaded files
  2746. *
  2747. * @param array
  2748. *
  2749. * @return array
  2750. * @throws elFinderAbortException
  2751. * @author Dmitry (dio) Levashov
  2752. */
  2753. protected function upload($args)
  2754. {
  2755. $ngReg = '/[\/\\?*:|"<>]/';
  2756. $target = $args['target'];
  2757. $volume = $this->volume($target);
  2758. $files = isset($args['FILES']['upload']) && is_array($args['FILES']['upload']) ? $args['FILES']['upload'] : array();
  2759. $header = empty($args['html']) ? array() : array('header' => 'Content-Type: text/html; charset=utf-8');
  2760. $result = array_merge(array('added' => array()), $header);
  2761. $paths = $args['upload_path'] ? $args['upload_path'] : array();
  2762. $chunk = $args['chunk'] ? $args['chunk'] : '';
  2763. $cid = $args['cid'] ? (int)$args['cid'] : '';
  2764. $mtimes = $args['mtime'] ? $args['mtime'] : array();
  2765. $tmpfname = '';
  2766. if (!$volume) {
  2767. return array_merge(array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_TRGDIR_NOT_FOUND, '#' . $target)), $header);
  2768. }
  2769. // check $chunk
  2770. if (strpos($chunk, '/') !== false || strpos($chunk, '\\') !== false) {
  2771. return array('error' => $this->error(self::ERROR_UPLOAD));
  2772. }
  2773. if ($args['overwrite'] !== '') {
  2774. $volume->setUploadOverwrite($args['overwrite']);
  2775. }
  2776. $renames = $hashes = array();
  2777. $suffix = '~';
  2778. if ($args['renames'] && is_array($args['renames'])) {
  2779. $renames = array_flip($args['renames']);
  2780. if (is_string($args['suffix']) && !preg_match($ngReg, $args['suffix'])) {
  2781. $suffix = $args['suffix'];
  2782. }
  2783. }
  2784. if ($args['hashes'] && is_array($args['hashes'])) {
  2785. $hashes = array_flip($args['hashes']);
  2786. }
  2787. $this->itemLock($target);
  2788. // file extentions table by MIME
  2789. $extTable = array_flip(array_unique($volume->getMimeTable()));
  2790. if (empty($files)) {
  2791. if (isset($args['upload']) && is_array($args['upload']) && ($tempDir = $this->getTempDir($volume->getTempPath()))) {
  2792. $names = array();
  2793. foreach ($args['upload'] as $i => $url) {
  2794. // check chunked file upload commit
  2795. if ($chunk) {
  2796. if ($url === 'chunkfail' && $args['mimes'] === 'chunkfail') {
  2797. $this->checkChunkedFile(null, $chunk, $cid, $tempDir);
  2798. if (preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m)) {
  2799. $result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $m[1], self::ERROR_UPLOAD_TEMP);
  2800. }
  2801. return $result;
  2802. } else {
  2803. $tmpfname = $tempDir . '/' . $chunk;
  2804. $files['tmp_name'][$i] = $tmpfname;
  2805. $files['name'][$i] = $url;
  2806. $files['error'][$i] = 0;
  2807. $GLOBALS['elFinderTempFiles'][$tmpfname] = true;
  2808. break;
  2809. }
  2810. }
  2811. $tmpfname = $tempDir . DIRECTORY_SEPARATOR . 'ELF_FATCH_' . md5($url . microtime(true));
  2812. $GLOBALS['elFinderTempFiles'][$tmpfname] = true;
  2813. $_name = '';
  2814. // check is data:
  2815. if (substr($url, 0, 5) === 'data:') {
  2816. list($data, $args['name'][$i]) = $this->parse_data_scheme($url, $extTable, $args);
  2817. } else {
  2818. $fp = fopen($tmpfname, 'wb');
  2819. if ($data = $this->get_remote_contents($url, 30, 5, 'Mozilla/5.0', $fp)) {
  2820. // to check connection is aborted
  2821. elFinder::checkAborted();
  2822. $_name = preg_replace('~^.*?([^/#?]+)(?:\?.*)?(?:#.*)?$~', '$1', rawurldecode($url));
  2823. // Check `Content-Disposition` response header
  2824. if ($data && ($headers = get_headers($url, true)) && !empty($headers['Content-Disposition'])) {
  2825. if (preg_match('/filename\*=(?:([a-zA-Z0-9_-]+?)\'\')"?([a-z0-9_.~%-]+)"?/i', $headers['Content-Disposition'], $m)) {
  2826. $_name = rawurldecode($m[2]);
  2827. if ($m[1] && strtoupper($m[1]) !== 'UTF-8' && function_exists('mb_convert_encoding')) {
  2828. $_name = mb_convert_encoding($_name, 'UTF-8', $m[1]);
  2829. }
  2830. } else if (preg_match('/filename="?([ a-z0-9_.~%-]+)"?/i', $headers['Content-Disposition'], $m)) {
  2831. $_name = rawurldecode($m[1]);
  2832. }
  2833. }
  2834. }
  2835. }
  2836. if ($data) {
  2837. if (isset($args['name'][$i])) {
  2838. $_name = $args['name'][$i];
  2839. }
  2840. if ($_name) {
  2841. $_ext = '';
  2842. if (preg_match('/(\.[a-z0-9]{1,7})$/', $_name, $_match)) {
  2843. $_ext = $_match[1];
  2844. }
  2845. if ((is_resource($data) && fclose($data)) || file_put_contents($tmpfname, $data)) {
  2846. $GLOBALS['elFinderTempFiles'][$tmpfname] = true;
  2847. $_name = preg_replace($ngReg, '_', $_name);
  2848. list($_a, $_b) = array_pad(explode('.', $_name, 2), 2, '');
  2849. if ($_b === '') {
  2850. if ($_ext) {
  2851. rename($tmpfname, $tmpfname . $_ext);
  2852. $tmpfname = $tmpfname . $_ext;
  2853. }
  2854. $_b = $this->detectFileExtension($volume, $tmpfname, $_name);
  2855. $_name = $_a . $_b;
  2856. } else {
  2857. $_b = '.' . $_b;
  2858. }
  2859. if (isset($names[$_name])) {
  2860. $_name = $_a . '_' . $names[$_name]++ . $_b;
  2861. } else {
  2862. $names[$_name] = 1;
  2863. }
  2864. $files['tmp_name'][$i] = $tmpfname;
  2865. $files['name'][$i] = $_name;
  2866. $files['error'][$i] = 0;
  2867. // set to auto rename
  2868. $volume->setUploadOverwrite(false);
  2869. } else {
  2870. unlink($tmpfname);
  2871. }
  2872. }
  2873. }
  2874. }
  2875. }
  2876. if (empty($files)) {
  2877. return array_merge(array('error' => $this->error(self::ERROR_UPLOAD, self::ERROR_UPLOAD_NO_FILES)), $header);
  2878. }
  2879. }
  2880. $addedDirs = array();
  2881. $errors = array();
  2882. foreach ($files['name'] as $i => $name) {
  2883. if (($error = $files['error'][$i]) > 0) {
  2884. $result['warning'] = $this->error(self::ERROR_UPLOAD_FILE, $name, $error == UPLOAD_ERR_INI_SIZE || $error == UPLOAD_ERR_FORM_SIZE ? self::ERROR_UPLOAD_FILE_SIZE : self::ERROR_UPLOAD_TRANSFER, $error);
  2885. $this->uploadDebug = 'Upload error code: ' . $error;
  2886. break;
  2887. }
  2888. $tmpname = $files['tmp_name'][$i];
  2889. $thash = ($paths && isset($paths[$i])) ? $paths[$i] : $target;
  2890. $mtime = isset($mtimes[$i]) ? $mtimes[$i] : 0;
  2891. if ($name === 'blob') {
  2892. if ($chunk) {
  2893. if ($tempDir = $this->getTempDir($volume->getTempPath())) {
  2894. list($tmpname, $name) = $this->checkChunkedFile($tmpname, $chunk, $cid, $tempDir, $volume);
  2895. if ($tmpname) {
  2896. if ($name === false) {
  2897. preg_match('/^(.+)(\.\d+_(\d+))\.part$/s', $chunk, $m);
  2898. $result['error'] = $this->error(self::ERROR_UPLOAD_FILE, $m[1], $tmpname);
  2899. $result['_chunkfailure'] = true;
  2900. $this->uploadDebug = 'Upload error: ' . $tmpname;
  2901. } else if ($name) {
  2902. $result['_chunkmerged'] = basename($tmpname);
  2903. $result['_name'] = $name;
  2904. $result['_mtime'] = $mtime;
  2905. }
  2906. }
  2907. } else {
  2908. $result['error'] = $this->error(self::ERROR_UPLOAD_FILE, $chunk, self::ERROR_UPLOAD_TEMP);
  2909. $this->uploadDebug = 'Upload error: unable open tmp file';
  2910. }
  2911. return $result;
  2912. } else {
  2913. // for form clipboard with Google Chrome or Opera
  2914. $name = 'image.png';
  2915. }
  2916. }
  2917. // Set name if name eq 'image.png' and $args has 'name' array, e.g. clipboard data
  2918. if (strtolower(substr($name, 0, 5)) === 'image' && is_array($args['name']) && isset($args['name'][$i])) {
  2919. $type = $files['type'][$i];
  2920. $name = $args['name'][$i];
  2921. $ext = isset($extTable[$type]) ? '.' . $extTable[$type] : '';
  2922. if ($ext) {
  2923. $name = preg_replace('/\.[^.]*$/', '', $name);
  2924. }
  2925. $name .= $ext;
  2926. }
  2927. // do hook function 'upload.presave'
  2928. if (!empty($this->listeners['upload.presave'])) {
  2929. foreach ($this->listeners['upload.presave'] as $handler) {
  2930. $_res = call_user_func_array($handler, array(&$thash, &$name, $tmpname, $this, $volume));
  2931. if ($_res && is_array($_res)) {
  2932. $_err = !empty($_res['error'])? $_res['error'] : (!empty($_res['warning'])? $_res['warning'] : null);
  2933. if ($_err) {
  2934. if (is_array($_err)) {
  2935. $errors = array_merge($errors, $_err);
  2936. } else {
  2937. $errors[] = (string)$_err;
  2938. }
  2939. if ($_res['error']) {
  2940. if (!is_uploaded_file($tmpname)) {
  2941. if (unlink($tmpname) && $tmpfname) unset($GLOBALS['elFinderTempFiles'][$tmpfname]);
  2942. }
  2943. continue 2;
  2944. }
  2945. }
  2946. }
  2947. }
  2948. }
  2949. clearstatcache();
  2950. if ($mtime && is_file($tmpname)) {
  2951. // for keep timestamp option in the LocalFileSystem volume
  2952. touch($tmpname, $mtime);
  2953. }
  2954. $fp = null;
  2955. if (!is_file($tmpname) || ($fp = fopen($tmpname, 'rb')) === false) {
  2956. $errors = array_merge($errors, array(self::ERROR_UPLOAD_FILE, $name, ($fp === false? self::ERROR_UPLOAD_TEMP : self::ERROR_UPLOAD_TRANSFER)));
  2957. $this->uploadDebug = 'Upload error: unable open tmp file';
  2958. if (!is_uploaded_file($tmpname)) {
  2959. if (unlink($tmpname) && $tmpfname) unset($GLOBALS['elFinderTempFiles'][$tmpfname]);
  2960. continue;
  2961. }
  2962. break;
  2963. }
  2964. $rnres = array();
  2965. if ($thash !== '' && $thash !== $target) {
  2966. if ($dir = $volume->dir($thash)) {
  2967. $_target = $thash;
  2968. if (!isset($addedDirs[$thash])) {
  2969. $addedDirs[$thash] = true;
  2970. $result['added'][] = $dir;
  2971. // to support multi-level directory creation
  2972. $_phash = isset($dir['phash']) ? $dir['phash'] : null;
  2973. while ($_phash && !isset($addedDirs[$_phash]) && $_phash !== $target) {
  2974. if ($_dir = $volume->dir($_phash)) {
  2975. $addedDirs[$_phash] = true;
  2976. $result['added'][] = $_dir;
  2977. $_phash = isset($_dir['phash']) ? $_dir['phash'] : null;
  2978. } else {
  2979. break;
  2980. }
  2981. }
  2982. }
  2983. } else {
  2984. $result['error'] = $this->error(self::ERROR_UPLOAD, self::ERROR_TRGDIR_NOT_FOUND, 'hash@' . $thash);
  2985. break;
  2986. }
  2987. } else {
  2988. $_target = $target;
  2989. // file rename for backup
  2990. if (isset($renames[$name])) {
  2991. $dir = $volume->realpath($_target);
  2992. if (isset($hashes[$name])) {
  2993. $hash = $hashes[$name];
  2994. } else {
  2995. $hash = $volume->getHash($dir, $name);
  2996. }
  2997. $rnres = $this->rename(array('target' => $hash, 'name' => $volume->uniqueName($dir, $name, $suffix, true, 0)));
  2998. if (!empty($rnres['error'])) {
  2999. $result['warning'] = $rnres['error'];
  3000. if (!is_array($rnres['error'])) {
  3001. $errors = array_push($errors, $rnres['error']);
  3002. } else {
  3003. $errors = array_merge($errors, $rnres['error']);
  3004. }
  3005. continue;
  3006. }
  3007. }
  3008. }
  3009. if (!$_target || ($file = $volume->upload($fp, $_target, $name, $tmpname, ($_target === $target) ? $hashes : array())) === false) {
  3010. $errors = array_merge($errors, $this->error(self::ERROR_UPLOAD_FILE, $name, $volume->error()));
  3011. fclose($fp);
  3012. if (!is_uploaded_file($tmpname) && unlink($tmpname)) {
  3013. unset($GLOBALS['elFinderTempFiles'][$tmpname]);
  3014. }
  3015. continue;
  3016. }
  3017. is_resource($fp) && fclose($fp);
  3018. if (!is_uploaded_file($tmpname)) {
  3019. clearstatcache();
  3020. if (!is_file($tmpname) || unlink($tmpname)) {
  3021. unset($GLOBALS['elFinderTempFiles'][$tmpname]);
  3022. }
  3023. }
  3024. $result['added'][] = $file;
  3025. if ($rnres) {
  3026. $result = array_merge_recursive($result, $rnres);
  3027. }
  3028. }
  3029. if ($errors) {
  3030. $result['warning'] = $errors;
  3031. }
  3032. if ($GLOBALS['elFinderTempFiles']) {
  3033. foreach (array_keys($GLOBALS['elFinderTempFiles']) as $_temp) {
  3034. is_file($_temp) && unlink($_temp);
  3035. }
  3036. }
  3037. $result['removed'] = $volume->removed();
  3038. if (!empty($args['node'])) {
  3039. $result['callback'] = array(
  3040. 'node' => $args['node'],
  3041. 'bind' => 'upload'
  3042. );
  3043. }
  3044. return $result;
  3045. }
  3046. /**
  3047. * Copy/move files into new destination
  3048. *
  3049. * @param array command arguments
  3050. *
  3051. * @return array
  3052. * @throws elFinderAbortException
  3053. * @author Dmitry (dio) Levashov
  3054. */
  3055. protected function paste($args)
  3056. {
  3057. $dst = $args['dst'];
  3058. $targets = is_array($args['targets']) ? $args['targets'] : array();
  3059. $cut = !empty($args['cut']);
  3060. $error = $cut ? self::ERROR_MOVE : self::ERROR_COPY;
  3061. $result = array('changed' => array(), 'added' => array(), 'removed' => array(), 'warning' => array());
  3062. if (($dstVolume = $this->volume($dst)) == false) {
  3063. return array('error' => $this->error($error, '#' . $targets[0], self::ERROR_TRGDIR_NOT_FOUND, '#' . $dst));
  3064. }
  3065. $this->itemLock($dst);
  3066. $hashes = $renames = array();
  3067. $suffix = '~';
  3068. if (!empty($args['renames'])) {
  3069. $renames = array_flip($args['renames']);
  3070. if (is_string($args['suffix']) && !preg_match('/[\/\\?*:|"<>]/', $args['suffix'])) {
  3071. $suffix = $args['suffix'];
  3072. }
  3073. }
  3074. if (!empty($args['hashes'])) {
  3075. $hashes = array_flip($args['hashes']);
  3076. }
  3077. foreach ($targets as $target) {
  3078. elFinder::checkAborted();
  3079. if (($srcVolume = $this->volume($target)) == false) {
  3080. $result['warning'] = array_merge($result['warning'], $this->error($error, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  3081. continue;
  3082. }
  3083. $rnres = array();
  3084. if ($renames) {
  3085. $file = $srcVolume->file($target);
  3086. if (isset($renames[$file['name']])) {
  3087. $dir = $dstVolume->realpath($dst);
  3088. if (isset($hashes[$file['name']])) {
  3089. $hash = $hashes[$file['name']];
  3090. } else {
  3091. $hash = $dstVolume->getHash($dir, $file['name']);
  3092. }
  3093. $rnres = $this->rename(array('target' => $hash, 'name' => $dstVolume->uniqueName($dir, $file['name'], $suffix, true, 0)));
  3094. if (!empty($rnres['error'])) {
  3095. $result['warning'] = array_merge($result['warning'], $rnres['error']);
  3096. continue;
  3097. }
  3098. }
  3099. }
  3100. if ($cut && $this->itemLocked($target)) {
  3101. $rm = $srcVolume->file($target);
  3102. $result['warning'] = array_merge($result['warning'], $this->error(self::ERROR_LOCKED, $rm['name']));
  3103. continue;
  3104. }
  3105. if (($file = $dstVolume->paste($srcVolume, $target, $dst, $cut, $hashes)) == false) {
  3106. $result['warning'] = array_merge($result['warning'], $this->error($dstVolume->error()));
  3107. continue;
  3108. }
  3109. if ($error = $dstVolume->error()) {
  3110. $result['warning'] = array_merge($result['warning'], $this->error($error));
  3111. }
  3112. if ($rnres) {
  3113. $result = array_merge_recursive($result, $rnres);
  3114. }
  3115. }
  3116. if (count($result['warning']) < 1) {
  3117. unset($result['warning']);
  3118. } else {
  3119. $result['sync'] = true;
  3120. }
  3121. return $result;
  3122. }
  3123. /**
  3124. * Return file content
  3125. *
  3126. * @param array $args command arguments
  3127. *
  3128. * @return array
  3129. * @author Dmitry (dio) Levashov
  3130. **/
  3131. protected function get($args)
  3132. {
  3133. $target = $args['target'];
  3134. $volume = $this->volume($target);
  3135. $enc = false;
  3136. if (!$volume || ($file = $volume->file($target)) == false) {
  3137. return array('error' => $this->error(self::ERROR_OPEN, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  3138. }
  3139. if (($content = $volume->getContents($target)) === false) {
  3140. return array('error' => $this->error(self::ERROR_OPEN, $volume->path($target), $volume->error()));
  3141. }
  3142. $mime = isset($file['mime']) ? $file['mime'] : '';
  3143. if ($mime && (strtolower(substr($mime, 0, 4)) === 'text' || in_array(strtolower($mime), self::$textMimes))) {
  3144. $enc = '';
  3145. if ($content !== '') {
  3146. if (!$args['conv'] || $args['conv'] == '1') {
  3147. // detect encoding
  3148. if (function_exists('mb_detect_encoding')) {
  3149. if ($enc = mb_detect_encoding($content, mb_detect_order(), true)) {
  3150. $encu = strtoupper($enc);
  3151. if ($encu === 'UTF-8' || $encu === 'ASCII') {
  3152. $enc = '';
  3153. }
  3154. } else {
  3155. $enc = 'unknown';
  3156. }
  3157. } else if (!preg_match('//u', $content)) {
  3158. $enc = 'unknown';
  3159. }
  3160. if ($enc === 'unknown') {
  3161. $enc = $volume->getOption('encoding');
  3162. if (!$enc || strtoupper($enc) === 'UTF-8') {
  3163. $enc = 'unknown';
  3164. }
  3165. }
  3166. if ($enc && $enc !== 'unknown') {
  3167. $utf8 = iconv($enc, 'UTF-8', $content);
  3168. if ($utf8 === false && function_exists('mb_convert_encoding')) {
  3169. $utf8 = mb_convert_encoding($content, 'UTF-8', $enc);
  3170. if (mb_convert_encoding($utf8, $enc, 'UTF-8') !== $content) {
  3171. $enc = 'unknown';
  3172. }
  3173. } else {
  3174. if ($utf8 === false || iconv('UTF-8', $enc, $utf8) !== $content) {
  3175. $enc = 'unknown';
  3176. }
  3177. }
  3178. if ($enc !== 'unknown') {
  3179. $content = $utf8;
  3180. }
  3181. }
  3182. if ($enc) {
  3183. if ($args['conv'] == '1') {
  3184. $args['conv'] = '';
  3185. if ($enc === 'unknown') {
  3186. $content = false;
  3187. }
  3188. } else if ($enc === 'unknown') {
  3189. return array('doconv' => $enc);
  3190. }
  3191. }
  3192. if ($args['conv'] == '1') {
  3193. $args['conv'] = '';
  3194. }
  3195. }
  3196. if ($args['conv']) {
  3197. $enc = $args['conv'];
  3198. if (strtoupper($enc) !== 'UTF-8') {
  3199. $_content = $content;
  3200. $content = iconv($enc, 'UTF-8', $content);
  3201. if ($content === false && function_exists('mb_convert_encoding')) {
  3202. $content = mb_convert_encoding($_content, 'UTF-8', $enc);
  3203. }
  3204. } else {
  3205. $enc = '';
  3206. }
  3207. }
  3208. }
  3209. } else {
  3210. $content = 'data:' . ($mime ? $mime : 'application/octet-stream') . ';base64,' . base64_encode($content);
  3211. }
  3212. if ($enc !== false) {
  3213. $json = false;
  3214. if ($content !== false) {
  3215. $json = json_encode($content);
  3216. }
  3217. if ($content === false || $json === false || strlen($json) < strlen($content)) {
  3218. return array('error' => $this->error(self::ERROR_CONV_UTF8, self::ERROR_NOT_UTF8_CONTENT, $volume->path($target)));
  3219. }
  3220. }
  3221. $res = array(
  3222. 'header' => array(
  3223. 'Content-Type: application/json'
  3224. ),
  3225. 'content' => $content
  3226. );
  3227. // add cache control headers
  3228. if ($cacheHeaders = $volume->getOption('cacheHeaders')) {
  3229. $res['header'] = array_merge($res['header'], $cacheHeaders);
  3230. }
  3231. if ($enc) {
  3232. $res['encoding'] = $enc;
  3233. }
  3234. return $res;
  3235. }
  3236. /**
  3237. * Save content into text file
  3238. *
  3239. * @param $args
  3240. *
  3241. * @return array
  3242. * @author Dmitry (dio) Levashov
  3243. */
  3244. protected function put($args)
  3245. {
  3246. $target = $args['target'];
  3247. $encoding = isset($args['encoding']) ? $args['encoding'] : '';
  3248. if (($volume = $this->volume($target)) == false
  3249. || ($file = $volume->file($target)) == false) {
  3250. return array('error' => $this->error(self::ERROR_SAVE, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  3251. }
  3252. $this->itemLock($target);
  3253. if ($encoding === 'scheme') {
  3254. if (preg_match('~^https?://~i', $args['content'])) {
  3255. /** @var resource $fp */
  3256. $fp = $this->get_remote_contents($args['content'], 30, 5, 'Mozilla/5.0', $volume->tmpfile());
  3257. if (!$fp) {
  3258. return array('error' => self::ERROR_SAVE, $args['content'], self::ERROR_FILE_NOT_FOUND);
  3259. }
  3260. $fmeta = stream_get_meta_data($fp);
  3261. $mime = $this->detectMimeType($fmeta['uri']);
  3262. if ($mime === 'unknown') {
  3263. $mime = 'application/octet-stream';
  3264. }
  3265. $mime = $volume->mimeTypeNormalize($mime, $file['name']);
  3266. $args['content'] = 'data:' . $mime . ';base64,' . base64_encode(file_get_contents($fmeta['uri']));
  3267. }
  3268. $encoding = '';
  3269. $args['content'] = "\0" . $args['content'];
  3270. } else if ($encoding === 'hash') {
  3271. $_hash = $args['content'];
  3272. if ($_src = $this->getVolume($_hash)) {
  3273. if ($_file = $_src->file($_hash)) {
  3274. if ($_data = $_src->getContents($_hash)) {
  3275. $args['content'] = 'data:' . $file['mime'] . ';base64,' . base64_encode($_data);
  3276. }
  3277. }
  3278. }
  3279. $encoding = '';
  3280. $args['content'] = "\0" . $args['content'];
  3281. }
  3282. if ($encoding) {
  3283. $content = iconv('UTF-8', $encoding, $args['content']);
  3284. if ($content === false && function_exists('mb_detect_encoding')) {
  3285. $content = mb_convert_encoding($args['content'], $encoding, 'UTF-8');
  3286. }
  3287. if ($content !== false) {
  3288. $args['content'] = $content;
  3289. }
  3290. }
  3291. if (($file = $volume->putContents($target, $args['content'])) == false) {
  3292. return array('error' => $this->error(self::ERROR_SAVE, $volume->path($target), $volume->error()));
  3293. }
  3294. return array('changed' => array($file));
  3295. }
  3296. /**
  3297. * Extract files from archive
  3298. *
  3299. * @param array $args command arguments
  3300. *
  3301. * @return array
  3302. * @author Dmitry (dio) Levashov,
  3303. * @author Alexey Sukhotin
  3304. **/
  3305. protected function extract($args)
  3306. {
  3307. $target = $args['target'];
  3308. $makedir = isset($args['makedir']) ? (bool)$args['makedir'] : null;
  3309. if (($volume = $this->volume($target)) == false
  3310. || ($file = $volume->file($target)) == false) {
  3311. return array('error' => $this->error(self::ERROR_EXTRACT, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  3312. }
  3313. $res = array();
  3314. if ($file = $volume->extract($target, $makedir)) {
  3315. $res['added'] = isset($file['read']) ? array($file) : $file;
  3316. if ($err = $volume->error()) {
  3317. $res['warning'] = $err;
  3318. }
  3319. } else {
  3320. $res['error'] = $this->error(self::ERROR_EXTRACT, $volume->path($target), $volume->error());
  3321. }
  3322. return $res;
  3323. }
  3324. /**
  3325. * Create archive
  3326. *
  3327. * @param array $args command arguments
  3328. *
  3329. * @return array
  3330. * @throws Exception
  3331. * @author Dmitry (dio) Levashov,
  3332. * @author Alexey Sukhotin
  3333. */
  3334. protected function archive($args)
  3335. {
  3336. $targets = isset($args['targets']) && is_array($args['targets']) ? $args['targets'] : array();
  3337. $name = isset($args['name']) ? $args['name'] : '';
  3338. if (($volume = $this->volume($targets[0])) == false) {
  3339. return $this->error(self::ERROR_ARCHIVE, self::ERROR_TRGDIR_NOT_FOUND);
  3340. }
  3341. foreach ($targets as $target) {
  3342. $this->itemLock($target);
  3343. }
  3344. return ($file = $volume->archive($targets, $args['type'], $name))
  3345. ? array('added' => array($file))
  3346. : array('error' => $this->error(self::ERROR_ARCHIVE, $volume->error()));
  3347. }
  3348. /**
  3349. * Search files
  3350. *
  3351. * @param array $args command arguments
  3352. *
  3353. * @return array
  3354. * @throws elFinderAbortException
  3355. * @author Dmitry Levashov
  3356. */
  3357. protected function search($args)
  3358. {
  3359. $q = trim($args['q']);
  3360. $mimes = !empty($args['mimes']) && is_array($args['mimes']) ? $args['mimes'] : array();
  3361. $target = !empty($args['target']) ? $args['target'] : null;
  3362. $type = !empty($args['type']) ? $args['type'] : null;
  3363. $result = array();
  3364. $errors = array();
  3365. if ($target) {
  3366. if ($volume = $this->volume($target)) {
  3367. $result = $volume->search($q, $mimes, $target, $type);
  3368. $errors = array_merge($errors, $volume->error());
  3369. }
  3370. } else {
  3371. foreach ($this->volumes as $volume) {
  3372. $result = array_merge($result, $volume->search($q, $mimes, null, $type));
  3373. $errors = array_merge($errors, $volume->error());
  3374. }
  3375. }
  3376. $result = array('files' => $result);
  3377. if ($errors) {
  3378. $result['warning'] = $errors;
  3379. }
  3380. return $result;
  3381. }
  3382. /**
  3383. * Return file info (used by client "places" ui)
  3384. *
  3385. * @param array $args command arguments
  3386. *
  3387. * @return array
  3388. * @throws elFinderAbortException
  3389. * @author Dmitry Levashov
  3390. */
  3391. protected function info($args)
  3392. {
  3393. $files = array();
  3394. $compare = null;
  3395. // long polling mode
  3396. if ($args['compare'] && count($args['targets']) === 1) {
  3397. $compare = intval($args['compare']);
  3398. $hash = $args['targets'][0];
  3399. if ($volume = $this->volume($hash)) {
  3400. $standby = (int)$volume->getOption('plStandby');
  3401. $_compare = false;
  3402. if (($syncCheckFunc = $volume->getOption('syncCheckFunc')) && is_callable($syncCheckFunc)) {
  3403. $_compare = call_user_func_array($syncCheckFunc, array($volume->realpath($hash), $standby, $compare, $volume, $this));
  3404. }
  3405. if ($_compare !== false) {
  3406. $compare = $_compare;
  3407. } else {
  3408. $sleep = max(1, (int)$volume->getOption('tsPlSleep'));
  3409. $limit = max(1, $standby / $sleep) + 1;
  3410. do {
  3411. elFinder::extendTimeLimit(30 + $sleep);
  3412. $volume->clearstatcache();
  3413. if (($info = $volume->file($hash)) != false) {
  3414. if ($info['ts'] != $compare) {
  3415. $compare = $info['ts'];
  3416. break;
  3417. }
  3418. } else {
  3419. $compare = 0;
  3420. break;
  3421. }
  3422. if (--$limit) {
  3423. sleep($sleep);
  3424. }
  3425. } while ($limit);
  3426. }
  3427. }
  3428. } else {
  3429. foreach ($args['targets'] as $hash) {
  3430. elFinder::checkAborted();
  3431. if (($volume = $this->volume($hash)) != false
  3432. && ($info = $volume->file($hash)) != false) {
  3433. $info['path'] = $volume->path($hash);
  3434. $files[] = $info;
  3435. }
  3436. }
  3437. }
  3438. $result = array('files' => $files);
  3439. if (!is_null($compare)) {
  3440. $result['compare'] = strval($compare);
  3441. }
  3442. return $result;
  3443. }
  3444. /**
  3445. * Return image dimensions
  3446. *
  3447. * @param array $args command arguments
  3448. *
  3449. * @return array
  3450. * @throws ImagickException
  3451. * @throws elFinderAbortException
  3452. * @author Dmitry (dio) Levashov
  3453. */
  3454. protected function dim($args)
  3455. {
  3456. $res = array();
  3457. $target = $args['target'];
  3458. if (($volume = $this->volume($target)) != false) {
  3459. if ($dim = $volume->dimensions($target, $args)) {
  3460. if (is_array($dim) && isset($dim['dim'])) {
  3461. $res = $dim;
  3462. } else {
  3463. $res = array('dim' => $dim);
  3464. if ($subImgLink = $volume->getSubstituteImgLink($target, explode('x', $dim))) {
  3465. $res['url'] = $subImgLink;
  3466. }
  3467. }
  3468. }
  3469. }
  3470. return $res;
  3471. }
  3472. /**
  3473. * Resize image
  3474. *
  3475. * @param array command arguments
  3476. *
  3477. * @return array
  3478. * @throws ImagickException
  3479. * @throws elFinderAbortException
  3480. * @author Dmitry (dio) Levashov
  3481. * @author Alexey Sukhotin
  3482. */
  3483. protected function resize($args)
  3484. {
  3485. $target = $args['target'];
  3486. $width = (int)$args['width'];
  3487. $height = (int)$args['height'];
  3488. $x = (int)$args['x'];
  3489. $y = (int)$args['y'];
  3490. $mode = $args['mode'];
  3491. $bg = $args['bg'];
  3492. $degree = (int)$args['degree'];
  3493. $quality = (int)$args['quality'];
  3494. if (($volume = $this->volume($target)) == false
  3495. || ($file = $volume->file($target)) == false) {
  3496. return array('error' => $this->error(self::ERROR_RESIZE, '#' . $target, self::ERROR_FILE_NOT_FOUND));
  3497. }
  3498. if ($mode !== 'rotate' && ($width < 1 || $height < 1)) {
  3499. return array('error' => $this->error(self::ERROR_RESIZESIZE));
  3500. }
  3501. return ($file = $volume->resize($target, $width, $height, $x, $y, $mode, $bg, $degree, $quality))
  3502. ? (!empty($file['losslessRotate']) ? $file : array('changed' => array($file)))
  3503. : array('error' => $this->error(self::ERROR_RESIZE, $volume->path($target), $volume->error()));
  3504. }
  3505. /**
  3506. * Return content URL
  3507. *
  3508. * @param array $args command arguments
  3509. *
  3510. * @return array
  3511. * @author Naoki Sawada
  3512. **/
  3513. protected function url($args)
  3514. {
  3515. $target = $args['target'];
  3516. $options = isset($args['options']) ? $args['options'] : array();
  3517. if (($volume = $this->volume($target)) != false) {
  3518. if (!$volume->commandDisabled('url')) {
  3519. $url = $volume->getContentUrl($target, $options);
  3520. return $url ? array('url' => $url) : array();
  3521. }
  3522. }
  3523. return array();
  3524. }
  3525. /**
  3526. * Output callback result with JavaScript that control elFinder
  3527. * or HTTP redirect to callbackWindowURL
  3528. *
  3529. * @param array command arguments
  3530. *
  3531. * @throws elFinderAbortException
  3532. * @author Naoki Sawada
  3533. */
  3534. protected function callback($args)
  3535. {
  3536. $checkReg = '/[^a-zA-Z0-9;._-]/';
  3537. $node = (isset($args['node']) && !preg_match($checkReg, $args['node'])) ? $args['node'] : '';
  3538. $json = (isset($args['json']) && json_decode($args['json'])) ? $args['json'] : '{}';
  3539. $bind = (isset($args['bind']) && !preg_match($checkReg, $args['bind'])) ? $args['bind'] : '';
  3540. $done = (!empty($args['done']));
  3541. while (ob_get_level()) {
  3542. if (!ob_end_clean()) {
  3543. break;
  3544. }
  3545. }
  3546. if ($done || !$this->callbackWindowURL) {
  3547. $script = '';
  3548. if ($node) {
  3549. if ($bind) {
  3550. $trigger = 'elf.trigger(\'' . $bind . '\', data);';
  3551. $triggerdone = 'elf.trigger(\'' . $bind . 'done\');';
  3552. $triggerfail = 'elf.trigger(\'' . $bind . 'fail\', data);';
  3553. } else {
  3554. $trigger = $triggerdone = $triggerfail = '';
  3555. }
  3556. $script .= '
  3557. var w = window.opener || window.parent || window;
  3558. try {
  3559. var elf = w.document.getElementById(\'' . $node . '\').elfinder;
  3560. if (elf) {
  3561. var data = ' . $json . ';
  3562. if (data.error) {
  3563. ' . $triggerfail . '
  3564. elf.error(data.error);
  3565. } else {
  3566. data.warning && elf.error(data.warning);
  3567. data.removed && data.removed.length && elf.remove(data);
  3568. data.added && data.added.length && elf.add(data);
  3569. data.changed && data.changed.length && elf.change(data);
  3570. ' . $trigger . '
  3571. ' . $triggerdone . '
  3572. data.sync && elf.sync();
  3573. }
  3574. }
  3575. } catch(e) {
  3576. // for CORS
  3577. w.postMessage && w.postMessage(JSON.stringify({bind:\'' . $bind . '\',data:' . $json . '}), \'*\');
  3578. }';
  3579. }
  3580. $script .= 'window.close();';
  3581. $out = '<!DOCTYPE html><html><head><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script>' . $script . '</script></head><body><a href="#" onlick="window.close();return false;">Close this window</a></body></html>';
  3582. header('Content-Type: text/html; charset=utf-8');
  3583. header('Content-Length: ' . strlen($out));
  3584. header('Cache-Control: private');
  3585. header('Pragma: no-cache');
  3586. echo $out;
  3587. } else {
  3588. $url = $this->callbackWindowURL;
  3589. $url .= ((strpos($url, '?') === false) ? '?' : '&')
  3590. . '&node=' . rawurlencode($node)
  3591. . (($json !== '{}') ? ('&json=' . rawurlencode($json)) : '')
  3592. . ($bind ? ('&bind=' . rawurlencode($bind)) : '')
  3593. . '&done=1';
  3594. header('Location: ' . $url);
  3595. }
  3596. throw new elFinderAbortException();
  3597. }
  3598. /**
  3599. * PHP error handler, catch error types only E_WARNING | E_NOTICE | E_USER_WARNING | E_USER_NOTICE
  3600. *
  3601. * @param int $errno
  3602. * @param string $errstr
  3603. * @param string $errfile
  3604. * @param int $errline
  3605. *
  3606. * @return boolean
  3607. */
  3608. public static function phpErrorHandler($errno, $errstr, $errfile, $errline)
  3609. {
  3610. static $base = null;
  3611. $proc = false;
  3612. if (is_null($base)) {
  3613. $base = dirname(__FILE__) . DIRECTORY_SEPARATOR;
  3614. }
  3615. if (!(error_reporting() & $errno)) {
  3616. return $proc;
  3617. }
  3618. $errfile = str_replace($base, '', $errfile);
  3619. switch ($errno) {
  3620. case E_WARNING:
  3621. case E_USER_WARNING:
  3622. elFinder::$phpErrors[] = "WARNING: $errstr in $errfile line $errline.";
  3623. $proc = true;
  3624. break;
  3625. case E_NOTICE:
  3626. case E_USER_NOTICE:
  3627. elFinder::$phpErrors[] = "NOTICE: $errstr in $errfile line $errline.";
  3628. $proc = true;
  3629. break;
  3630. case E_STRICT:
  3631. elFinder::$phpErrors[] = "STRICT: $errstr in $errfile line $errline.";
  3632. $proc = true;
  3633. break;
  3634. case E_RECOVERABLE_ERROR:
  3635. elFinder::$phpErrors[] = "RECOVERABLE_ERROR: $errstr in $errfile line $errline.";
  3636. $proc = true;
  3637. break;
  3638. }
  3639. if (defined('E_DEPRECATED')) {
  3640. switch ($errno) {
  3641. case E_DEPRECATED:
  3642. case E_USER_DEPRECATED:
  3643. elFinder::$phpErrors[] = "DEPRECATED: $errstr in $errfile line $errline.";
  3644. $proc = true;
  3645. break;
  3646. }
  3647. }
  3648. return $proc;
  3649. }
  3650. /***************************************************************************/
  3651. /* utils */
  3652. /***************************************************************************/
  3653. /**
  3654. * Return root - file's owner
  3655. *
  3656. * @param string file hash
  3657. *
  3658. * @return elFinderVolumeDriver|boolean (false)
  3659. * @author Dmitry (dio) Levashov
  3660. **/
  3661. protected function volume($hash)
  3662. {
  3663. foreach ($this->volumes as $id => $v) {
  3664. if (strpos('' . $hash, $id) === 0) {
  3665. return $this->volumes[$id];
  3666. }
  3667. }
  3668. return false;
  3669. }
  3670. /**
  3671. * Return files info array
  3672. *
  3673. * @param array $data one file info or files info
  3674. *
  3675. * @return array
  3676. * @author Dmitry (dio) Levashov
  3677. **/
  3678. protected function toArray($data)
  3679. {
  3680. return isset($data['hash']) || !is_array($data) ? array($data) : $data;
  3681. }
  3682. /**
  3683. * Return fils hashes list
  3684. *
  3685. * @param array $files files info
  3686. *
  3687. * @return array
  3688. * @author Dmitry (dio) Levashov
  3689. **/
  3690. protected function hashes($files)
  3691. {
  3692. $ret = array();
  3693. foreach ($files as $file) {
  3694. $ret[] = $file['hash'];
  3695. }
  3696. return $ret;
  3697. }
  3698. /**
  3699. * Remove from files list hidden files and files with required mime types
  3700. *
  3701. * @param array $files files info
  3702. *
  3703. * @return array
  3704. * @author Dmitry (dio) Levashov
  3705. **/
  3706. protected function filter($files)
  3707. {
  3708. $exists = array();
  3709. foreach ($files as $i => $file) {
  3710. if (isset($exists[$file['hash']]) || !empty($file['hidden']) || !$this->default->mimeAccepted($file['mime'])) {
  3711. unset($files[$i]);
  3712. }
  3713. $exists[$file['hash']] = true;
  3714. }
  3715. return array_values($files);
  3716. }
  3717. protected function utime()
  3718. {
  3719. $time = explode(" ", microtime());
  3720. return (double)$time[1] + (double)$time[0];
  3721. }
  3722. /**
  3723. * Return Network mount volume unique ID
  3724. *
  3725. * @param array $netVolumes Saved netvolumes array
  3726. * @param string $prefix Id prefix
  3727. *
  3728. * @return string|false
  3729. * @author Naoki Sawada
  3730. **/
  3731. protected function getNetVolumeUniqueId($netVolumes = null, $prefix = 'nm')
  3732. {
  3733. if (is_null($netVolumes)) {
  3734. $netVolumes = $this->getNetVolumes();
  3735. }
  3736. $ids = array();
  3737. foreach ($netVolumes as $vOps) {
  3738. if (isset($vOps['id']) && strpos($vOps['id'], $prefix) === 0) {
  3739. $ids[$vOps['id']] = true;
  3740. }
  3741. }
  3742. if (!$ids) {
  3743. $id = $prefix . '1';
  3744. } else {
  3745. $i = 0;
  3746. while (isset($ids[$prefix . ++$i]) && $i < 10000) ;
  3747. $id = $prefix . $i;
  3748. if (isset($ids[$id])) {
  3749. $id = false;
  3750. }
  3751. }
  3752. return $id;
  3753. }
  3754. /**
  3755. * Is item locked?
  3756. *
  3757. * @param string $hash
  3758. *
  3759. * @return boolean
  3760. */
  3761. protected function itemLocked($hash)
  3762. {
  3763. if (!elFinder::$commonTempPath) {
  3764. return false;
  3765. }
  3766. $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
  3767. if (file_exists($lock)) {
  3768. if (filemtime($lock) + $this->itemLockExpire < time()) {
  3769. unlink($lock);
  3770. return false;
  3771. }
  3772. return true;
  3773. }
  3774. return false;
  3775. }
  3776. /**
  3777. * Do lock target item
  3778. *
  3779. * @param array|string $hashes
  3780. * @param boolean $autoUnlock
  3781. *
  3782. * @return void
  3783. */
  3784. protected function itemLock($hashes, $autoUnlock = true)
  3785. {
  3786. if (!elFinder::$commonTempPath) {
  3787. return;
  3788. }
  3789. if (!is_array($hashes)) {
  3790. $hashes = array($hashes);
  3791. }
  3792. foreach ($hashes as $hash) {
  3793. $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
  3794. if ($this->itemLocked($hash)) {
  3795. $cnt = file_get_contents($lock) + 1;
  3796. } else {
  3797. $cnt = 1;
  3798. }
  3799. if (file_put_contents($lock, $cnt, LOCK_EX)) {
  3800. if ($autoUnlock) {
  3801. $this->autoUnlocks[] = $hash;
  3802. }
  3803. }
  3804. }
  3805. }
  3806. /**
  3807. * Do unlock target item
  3808. *
  3809. * @param string $hash
  3810. *
  3811. * @return boolean
  3812. */
  3813. protected function itemUnlock($hash)
  3814. {
  3815. if (!$this->itemLocked($hash)) {
  3816. return true;
  3817. }
  3818. $lock = elFinder::$commonTempPath . DIRECTORY_SEPARATOR . $hash . '.lock';
  3819. $cnt = file_get_contents($lock);
  3820. if (--$cnt < 1) {
  3821. unlink($lock);
  3822. return true;
  3823. } else {
  3824. file_put_contents($lock, $cnt, LOCK_EX);
  3825. return false;
  3826. }
  3827. }
  3828. /**
  3829. * unlock locked items on command completion
  3830. *
  3831. * @return void
  3832. */
  3833. public function itemAutoUnlock()
  3834. {
  3835. if ($this->autoUnlocks) {
  3836. foreach ($this->autoUnlocks as $hash) {
  3837. $this->itemUnlock($hash);
  3838. }
  3839. $this->autoUnlocks = array();
  3840. }
  3841. }
  3842. /**
  3843. * Ensure directories recursively
  3844. *
  3845. * @param object $volume Volume object
  3846. * @param string $target Target hash
  3847. * @param array $dirs Array of directory tree to ensure
  3848. * @param string $path Relative path form target hash
  3849. *
  3850. * @return array|false array('stats' => array([stat of maked directory]), 'hashes' => array('[path]' => '[hash]'), 'makes' => array([New directory hashes]), 'error' => array([Error name]))
  3851. * @author Naoki Sawada
  3852. **/
  3853. protected function ensureDirsRecursively($volume, $target, $dirs, $path = '')
  3854. {
  3855. $res = array('stats' => array(), 'hashes' => array(), 'makes' => array(), 'error' => array());
  3856. foreach ($dirs as $name => $sub) {
  3857. $name = (string)$name;
  3858. $dir = $newDir = null;
  3859. if ((($parent = $volume->realpath($target)) && ($dir = $volume->dir($volume->getHash($parent, $name)))) || ($newDir = $volume->mkdir($target, $name))) {
  3860. $_path = $path . '/' . $name;
  3861. if ($newDir) {
  3862. $res['makes'][] = $newDir['hash'];
  3863. $dir = $newDir;
  3864. }
  3865. $res['stats'][] = $dir;
  3866. $res['hashes'][$_path] = $dir['hash'];
  3867. if (count($sub)) {
  3868. $res = array_merge_recursive($res, $this->ensureDirsRecursively($volume, $dir['hash'], $sub, $_path));
  3869. }
  3870. } else {
  3871. $res['error'][] = $name;
  3872. }
  3873. }
  3874. return $res;
  3875. }
  3876. /***************************************************************************/
  3877. /* static utils */
  3878. /***************************************************************************/
  3879. /**
  3880. * Return full version of API that this connector supports all functions
  3881. *
  3882. * @return string
  3883. */
  3884. public static function getApiFullVersion()
  3885. {
  3886. return (string)self::$ApiVersion . '.' . (string)self::$ApiRevision;
  3887. }
  3888. /**
  3889. * Return Is Animation Gif
  3890. *
  3891. * @param string $path server local path of target image
  3892. *
  3893. * @return bool
  3894. */
  3895. public static function isAnimationGif($path)
  3896. {
  3897. list(, , $type) = getimagesize($path);
  3898. switch ($type) {
  3899. case IMAGETYPE_GIF:
  3900. break;
  3901. default:
  3902. return false;
  3903. }
  3904. $imgcnt = 0;
  3905. $fp = fopen($path, 'rb');
  3906. fread($fp, 4);
  3907. $c = fread($fp, 1);
  3908. if (ord($c) != 0x39) { // GIF89a
  3909. return false;
  3910. }
  3911. while (!feof($fp)) {
  3912. do {
  3913. $c = fread($fp, 1);
  3914. } while (ord($c) != 0x21 && !feof($fp));
  3915. if (feof($fp)) {
  3916. break;
  3917. }
  3918. $c2 = fread($fp, 2);
  3919. if (bin2hex($c2) == "f904") {
  3920. $imgcnt++;
  3921. if ($imgcnt === 2) {
  3922. break;
  3923. }
  3924. }
  3925. if (feof($fp)) {
  3926. break;
  3927. }
  3928. }
  3929. if ($imgcnt > 1) {
  3930. return true;
  3931. } else {
  3932. return false;
  3933. }
  3934. }
  3935. /**
  3936. * Return Is Animation Png
  3937. *
  3938. * @param string $path server local path of target image
  3939. *
  3940. * @return bool
  3941. */
  3942. public static function isAnimationPng($path)
  3943. {
  3944. list(, , $type) = getimagesize($path);
  3945. switch ($type) {
  3946. case IMAGETYPE_PNG:
  3947. break;
  3948. default:
  3949. return false;
  3950. }
  3951. $fp = fopen($path, 'rb');
  3952. $img_bytes = fread($fp, 1024);
  3953. fclose($fp);
  3954. if ($img_bytes) {
  3955. if (strpos(substr($img_bytes, 0, strpos($img_bytes, 'IDAT')), 'acTL') !== false) {
  3956. return true;
  3957. }
  3958. }
  3959. return false;
  3960. }
  3961. /**
  3962. * Return Is seekable stream resource
  3963. *
  3964. * @param resource $resource
  3965. *
  3966. * @return bool
  3967. */
  3968. public static function isSeekableStream($resource)
  3969. {
  3970. $metadata = stream_get_meta_data($resource);
  3971. return $metadata['seekable'];
  3972. }
  3973. /**
  3974. * Rewind stream resource
  3975. *
  3976. * @param resource $resource
  3977. *
  3978. * @return void
  3979. */
  3980. public static function rewind($resource)
  3981. {
  3982. self::isSeekableStream($resource) && rewind($resource);
  3983. }
  3984. /**
  3985. * serialize and base64_encode of session data (If needed)
  3986. *
  3987. * @deprecated
  3988. *
  3989. * @param mixed $var target variable
  3990. *
  3991. * @author Naoki Sawada
  3992. * @return mixed|string
  3993. */
  3994. public static function sessionDataEncode($var)
  3995. {
  3996. if (self::$base64encodeSessionData) {
  3997. $var = base64_encode(serialize($var));
  3998. }
  3999. return $var;
  4000. }
  4001. /**
  4002. * base64_decode and unserialize of session data (If needed)
  4003. *
  4004. * @deprecated
  4005. *
  4006. * @param mixed $var target variable
  4007. * @param bool $checkIs data type for check (array|string|object|int)
  4008. *
  4009. * @author Naoki Sawada
  4010. * @return bool|mixed
  4011. */
  4012. public static function sessionDataDecode(&$var, $checkIs = null)
  4013. {
  4014. if (self::$base64encodeSessionData) {
  4015. $data = unserialize(base64_decode($var));
  4016. } else {
  4017. $data = $var;
  4018. }
  4019. $chk = true;
  4020. if ($checkIs) {
  4021. switch ($checkIs) {
  4022. case 'array':
  4023. $chk = is_array($data);
  4024. break;
  4025. case 'string':
  4026. $chk = is_string($data);
  4027. break;
  4028. case 'object':
  4029. $chk = is_object($data);
  4030. break;
  4031. case 'int':
  4032. $chk = is_int($data);
  4033. break;
  4034. }
  4035. }
  4036. if (!$chk) {
  4037. unset($var);
  4038. return false;
  4039. }
  4040. return $data;
  4041. }
  4042. /**
  4043. * Call session_write_close() if session is restarted
  4044. *
  4045. * @deprecated
  4046. * @return void
  4047. */
  4048. public static function sessionWrite()
  4049. {
  4050. if (session_id()) {
  4051. session_write_close();
  4052. }
  4053. }
  4054. /**
  4055. * Return elFinder static variable
  4056. *
  4057. * @param $key
  4058. *
  4059. * @return mixed|null
  4060. */
  4061. public static function getStaticVar($key)
  4062. {
  4063. return isset(elFinder::$$key) ? elFinder::$$key : null;
  4064. }
  4065. /**
  4066. * Extend PHP execution time limit and also check connection is aborted
  4067. *
  4068. * @param Int $time
  4069. *
  4070. * @return void
  4071. * @throws elFinderAbortException
  4072. */
  4073. public static function extendTimeLimit($time = null)
  4074. {
  4075. static $defLimit = null;
  4076. if (!self::aborted()) {
  4077. if (is_null($defLimit)) {
  4078. $defLimit = ini_get('max_execution_time');
  4079. }
  4080. if ($defLimit != 0) {
  4081. $time = is_null($time) ? $defLimit : max($defLimit, $time);
  4082. set_time_limit($time);
  4083. }
  4084. } else {
  4085. throw new elFinderAbortException();
  4086. }
  4087. }
  4088. /**
  4089. * Check connection is aborted
  4090. * Script stop immediately if connection aborted
  4091. *
  4092. * @return void
  4093. * @throws elFinderAbortException
  4094. */
  4095. public static function checkAborted()
  4096. {
  4097. elFinder::extendTimeLimit();
  4098. }
  4099. /**
  4100. * Return bytes from php.ini value
  4101. *
  4102. * @param string $iniName
  4103. * @param string $val
  4104. *
  4105. * @return number
  4106. */
  4107. public static function getIniBytes($iniName = '', $val = '')
  4108. {
  4109. if ($iniName !== '') {
  4110. $val = ini_get($iniName);
  4111. if ($val === false) {
  4112. return 0;
  4113. }
  4114. }
  4115. $val = trim($val, "bB \t\n\r\0\x0B");
  4116. $last = strtolower($val[strlen($val) - 1]);
  4117. $val = (int)$val;
  4118. switch ($last) {
  4119. case 't':
  4120. $val *= 1024;
  4121. case 'g':
  4122. $val *= 1024;
  4123. case 'm':
  4124. $val *= 1024;
  4125. case 'k':
  4126. $val *= 1024;
  4127. }
  4128. return $val;
  4129. }
  4130. /**
  4131. * Get script url.
  4132. *
  4133. * @return string full URL
  4134. * @author Naoki Sawada
  4135. */
  4136. public static function getConnectorUrl()
  4137. {
  4138. $https = (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) !== 'off');
  4139. $url = ($https ? 'https://' : 'http://')
  4140. . $_SERVER['SERVER_NAME'] // host
  4141. . (((!$https && $_SERVER['SERVER_PORT'] == 80) || ($https && $_SERVER['SERVER_PORT'] == 443)) ? '' : (':' . $_SERVER['SERVER_PORT'])) // port
  4142. . $_SERVER['REQUEST_URI']; // path & query
  4143. list($url) = explode('?', $url);
  4144. return $url;
  4145. }
  4146. /**
  4147. * Get stream resource pointer by URL
  4148. *
  4149. * @param array $data array('target'=>'URL', 'headers' => array())
  4150. * @param int $redirectLimit
  4151. *
  4152. * @return resource|boolean
  4153. * @author Naoki Sawada
  4154. */
  4155. public static function getStreamByUrl($data, $redirectLimit = 5)
  4156. {
  4157. if (isset($data['target'])) {
  4158. $data = array(
  4159. 'cnt' => 0,
  4160. 'url' => $data['target'],
  4161. 'headers' => isset($data['headers']) ? $data['headers'] : array(),
  4162. 'cookies' => array(),
  4163. );
  4164. }
  4165. if ($data['cnt'] > $redirectLimit) {
  4166. return false;
  4167. }
  4168. $dlurl = $data['url'];
  4169. $data['url'] = '';
  4170. $headers = $data['headers'];
  4171. if ($dlurl) {
  4172. $url = parse_url($dlurl);
  4173. $ports = array(
  4174. 'http' => '80',
  4175. 'https' => '443',
  4176. 'ftp' => '21'
  4177. );
  4178. $url['scheme'] = strtolower($url['scheme']);
  4179. if (!isset($url['port']) && isset($ports[$url['scheme']])) {
  4180. $url['port'] = $ports[$url['scheme']];
  4181. }
  4182. if (!isset($url['port'])) {
  4183. return false;
  4184. }
  4185. $cookies = array();
  4186. if ($data['cookies']) {
  4187. foreach ($data['cookies'] as $d => $c) {
  4188. if (strpos($url['host'], $d) !== false) {
  4189. $cookies[] = $c;
  4190. }
  4191. }
  4192. }
  4193. $transport = ($url['scheme'] === 'https') ? 'tls' : 'tcp';
  4194. $query = isset($url['query']) ? '?' . $url['query'] : '';
  4195. $stream = stream_socket_client($transport . '://' . $url['host'] . ':' . $url['port']);
  4196. stream_set_timeout($stream, 300);
  4197. fputs($stream, "GET {$url['path']}{$query} HTTP/1.1\r\n");
  4198. fputs($stream, "Host: {$url['host']}\r\n");
  4199. foreach ($headers as $header) {
  4200. fputs($stream, trim($header, "\r\n") . "\r\n");
  4201. }
  4202. fputs($stream, "Connection: Close\r\n");
  4203. if ($cookies) {
  4204. fputs($stream, 'Cookie: ' . implode('; ', $cookies) . "\r\n");
  4205. }
  4206. fputs($stream, "\r\n");
  4207. while (($res = trim(fgets($stream))) !== '') {
  4208. // find redirect
  4209. if (preg_match('/^Location: (.+)$/', $res, $m)) {
  4210. $data['url'] = $m[1];
  4211. }
  4212. // fetch cookie
  4213. if (strpos($res, 'Set-Cookie:') === 0) {
  4214. $domain = $url['host'];
  4215. if (preg_match('/^Set-Cookie:(.+)(?:domain=\s*([^ ;]+))?/i', $res, $c1)) {
  4216. if (!empty($c1[2])) {
  4217. $domain = trim($c1[2]);
  4218. }
  4219. if (preg_match('/([^ ]+=[^;]+)/', $c1[1], $c2)) {
  4220. $data['cookies'][$domain] = $c2[1];
  4221. }
  4222. }
  4223. }
  4224. }
  4225. if ($data['url']) {
  4226. ++$data['cnt'];
  4227. fclose($stream);
  4228. return self::getStreamByUrl($data, $redirectLimit);
  4229. }
  4230. return $stream;
  4231. }
  4232. return false;
  4233. }
  4234. /**
  4235. * Gets the fetch cookie file for curl.
  4236. *
  4237. * @return string The fetch cookie file.
  4238. */
  4239. public function getFetchCookieFile()
  4240. {
  4241. $file = '';
  4242. if ($tmpDir = $this->getTempDir()) {
  4243. $file = $tmpDir . '/.elFinderAnonymousCookie';
  4244. }
  4245. return $file;
  4246. }
  4247. /**
  4248. * Call curl_exec() with supported redirect on `safe_mode` or `open_basedir`
  4249. *
  4250. * @param resource $curl
  4251. * @param array $options
  4252. * @param array $headers
  4253. *
  4254. * @throws \Exception
  4255. * @return mixed
  4256. * @author Naoki Sawada
  4257. */
  4258. public static function curlExec($curl, $options = array(), $headers = array())
  4259. {
  4260. $followLocation = (!ini_get('safe_mode') && !ini_get('open_basedir'));
  4261. if ($followLocation) {
  4262. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
  4263. }
  4264. if ($options) {
  4265. curl_setopt_array($curl, $options);
  4266. }
  4267. if ($headers) {
  4268. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  4269. }
  4270. $result = curl_exec($curl);
  4271. if (!$followLocation && $redirect = curl_getinfo($curl, CURLINFO_REDIRECT_URL)) {
  4272. if ($stream = self::getStreamByUrl(array('target' => $redirect, 'headers' => $headers))) {
  4273. $result = stream_get_contents($stream);
  4274. }
  4275. }
  4276. if ($result === false) {
  4277. if (curl_errno($curl)) {
  4278. throw new \Exception('curl_exec() failed: ' . curl_error($curl));
  4279. } else {
  4280. throw new \Exception('curl_exec(): empty response');
  4281. }
  4282. }
  4283. curl_close($curl);
  4284. return $result;
  4285. }
  4286. /**
  4287. * Return bool that current request was aborted by client side
  4288. *
  4289. * @return boolean
  4290. */
  4291. public static function aborted()
  4292. {
  4293. if ($file = self::$abortCheckFile) {
  4294. (version_compare(PHP_VERSION, '5.3.0') >= 0) ? clearstatcache(true, $file) : clearstatcache();
  4295. if (!is_file($file)) {
  4296. // GC (expire 12h)
  4297. list($ptn) = explode('elfreq', $file);
  4298. self::GlobGC($ptn . 'elfreq*', 43200);
  4299. return true;
  4300. }
  4301. }
  4302. return false;
  4303. }
  4304. /**
  4305. * Return array ["name without extention", "extention"] by filename
  4306. *
  4307. * @param string $name
  4308. *
  4309. * @return array
  4310. */
  4311. public static function splitFileExtention($name)
  4312. {
  4313. if (preg_match('/^(.+?)?\.((?:tar\.(?:gz|bz|bz2|z|lzo))|cpio\.gz|ps\.gz|xcf\.(?:gz|bz2)|[a-z0-9]{1,10})$/i', $name, $m)) {
  4314. return array((string)$m[1], $m[2]);
  4315. } else {
  4316. return array($name, '');
  4317. }
  4318. }
  4319. /**
  4320. * Gets the memory size by imageinfo.
  4321. *
  4322. * @param array $imgInfo array that result of getimagesize()
  4323. *
  4324. * @return integer The memory size by imageinfo.
  4325. */
  4326. public static function getMemorySizeByImageInfo($imgInfo)
  4327. {
  4328. $width = $imgInfo[0];
  4329. $height = $imgInfo[1];
  4330. $bits = isset($imgInfo['bits']) ? $imgInfo['bits'] : 24;
  4331. $channels = isset($imgInfo['channels']) ? $imgInfo['channels'] : 3;
  4332. return round(($width * $height * $bits * $channels / 8 + Pow(2, 16)) * 1.65);
  4333. }
  4334. /**
  4335. * Auto expand memory for GD processing
  4336. *
  4337. * @param array $imgInfos The image infos
  4338. */
  4339. public static function expandMemoryForGD($imgInfos)
  4340. {
  4341. if (elFinder::$memoryLimitGD != 0 && $imgInfos && is_array($imgInfos)) {
  4342. if (!is_array($imgInfos[0])) {
  4343. $imgInfos = array($imgInfos);
  4344. }
  4345. $limit = self::getIniBytes('', elFinder::$memoryLimitGD);
  4346. $memLimit = self::getIniBytes('memory_limit');
  4347. $needs = 0;
  4348. foreach ($imgInfos as $info) {
  4349. $needs += self::getMemorySizeByImageInfo($info);
  4350. }
  4351. $needs += memory_get_usage();
  4352. if ($needs > $memLimit && ($limit == -1 || $limit > $needs)) {
  4353. ini_set('memory_limit', $needs);
  4354. }
  4355. }
  4356. }
  4357. /***************************************************************************/
  4358. /* callbacks */
  4359. /***************************************************************************/
  4360. /**
  4361. * Get command name of binded "commandName.subName"
  4362. *
  4363. * @param string $cmd
  4364. *
  4365. * @return string
  4366. */
  4367. protected static function getCmdOfBind($cmd)
  4368. {
  4369. list($ret) = explode('.', $cmd);
  4370. return trim($ret);
  4371. }
  4372. /**
  4373. * Add subName to commandName
  4374. *
  4375. * @param string $cmd
  4376. * @param string $sub
  4377. *
  4378. * @return string
  4379. */
  4380. protected static function addSubToBindName($cmd, $sub)
  4381. {
  4382. return $cmd . '.' . trim($sub);
  4383. }
  4384. /**
  4385. * Remove a file if connection is disconnected
  4386. *
  4387. * @param string $file
  4388. */
  4389. public static function rmFileInDisconnected($file)
  4390. {
  4391. (connection_aborted() || connection_status() !== CONNECTION_NORMAL) && is_file($file) && unlink($file);
  4392. }
  4393. /**
  4394. * Call back function on shutdown
  4395. * - delete files in $GLOBALS['elFinderTempFiles']
  4396. */
  4397. public static function onShutdown()
  4398. {
  4399. self::$abortCheckFile = null;
  4400. if (!empty($GLOBALS['elFinderTempFiles'])) {
  4401. foreach (array_keys($GLOBALS['elFinderTempFiles']) as $f) {
  4402. is_file($f) && unlink($f);
  4403. }
  4404. }
  4405. }
  4406. /**
  4407. * Garbage collection with glob
  4408. *
  4409. * @param string $pattern
  4410. * @param integer $time
  4411. */
  4412. public static function GlobGC($pattern, $time)
  4413. {
  4414. $now = time();
  4415. foreach (glob($pattern) as $file) {
  4416. (filemtime($file) < ($now - $time)) && unlink($file);
  4417. }
  4418. }
  4419. } // END class
  4420. /**
  4421. * Custom exception class for aborting request
  4422. */
  4423. class elFinderAbortException extends Exception
  4424. {
  4425. }