elFinder.class.php 126 KB

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