elFinder.class.php 123 KB

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