elFinderVolumeDriver.class.php 196 KB

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