elFinder.class.php 177 KB

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