fileinput.js 283 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260
  1. /*!
  2. * bootstrap-fileinput v5.2.3
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2021, Kartik Visweswaran, Krajee.com
  7. *
  8. * Licensed under the BSD-3-Clause
  9. * https://github.com/kartik-v/bootstrap-fileinput/blob/master/LICENSE.md
  10. */
  11. (function (factory) {
  12. 'use strict';
  13. if (typeof define === 'function' && define.amd) {
  14. define(['jquery'], factory);
  15. } else {
  16. if (typeof module === 'object' && module.exports) {
  17. //noinspection NpmUsedModulesInstalled
  18. module.exports = factory(require('jquery'));
  19. } else {
  20. factory(window.jQuery);
  21. }
  22. }
  23. }(function ($) {
  24. 'use strict';
  25. $.fn.fileinputLocales = {};
  26. $.fn.fileinputThemes = {};
  27. if (!$.fn.fileinputBsVersion) {
  28. $.fn.fileinputBsVersion = (window.Alert && window.Alert.VERSION) ||
  29. (window.bootstrap && window.bootstrap.Alert && bootstrap.Alert.VERSION) || '3.x.x';
  30. }
  31. String.prototype.setTokens = function (replacePairs) {
  32. var str = this.toString(), key, re;
  33. for (key in replacePairs) {
  34. if (replacePairs.hasOwnProperty(key)) {
  35. re = new RegExp('\{' + key + '\}', 'g');
  36. str = str.replace(re, replacePairs[key]);
  37. }
  38. }
  39. return str;
  40. };
  41. if (!Array.prototype.flatMap) { // polyfill flatMap
  42. Array.prototype.flatMap = function (lambda) {
  43. return [].concat(this.map(lambda));
  44. };
  45. }
  46. var $h, FileInput;
  47. // fileinput helper object for all global variables and internal helper methods
  48. $h = {
  49. FRAMES: '.kv-preview-thumb',
  50. SORT_CSS: 'file-sortable',
  51. INIT_FLAG: 'init-',
  52. OBJECT_PARAMS: '<param name="controller" value="true" />\n' +
  53. '<param name="allowFullScreen" value="true" />\n' +
  54. '<param name="allowScriptAccess" value="always" />\n' +
  55. '<param name="autoPlay" value="false" />\n' +
  56. '<param name="autoStart" value="false" />\n' +
  57. '<param name="quality" value="high" />\n',
  58. DEFAULT_PREVIEW: '<div class="file-preview-other">\n' +
  59. '<span class="{previewFileIconClass}">{previewFileIcon}</span>\n' +
  60. '</div>',
  61. MODAL_ID: 'kvFileinputModal',
  62. MODAL_EVENTS: ['show', 'shown', 'hide', 'hidden', 'loaded'],
  63. logMessages: {
  64. ajaxError: '{status}: {error}. Error Details: {text}.',
  65. badDroppedFiles: 'Error scanning dropped files!',
  66. badExifParser: 'Error loading the piexif.js library. {details}',
  67. badInputType: 'The input "type" must be set to "file" for initializing the "bootstrap-fileinput" plugin.',
  68. exifWarning: 'To avoid this warning, either set "autoOrientImage" to "false" OR ensure you have loaded ' +
  69. 'the "piexif.js" library correctly on your page before the "fileinput.js" script.',
  70. invalidChunkSize: 'Invalid upload chunk size: "{chunkSize}". Resumable uploads are disabled.',
  71. invalidThumb: 'Invalid thumb frame with id: "{id}".',
  72. noResumableSupport: 'The browser does not support resumable or chunk uploads.',
  73. noUploadUrl: 'The "uploadUrl" is not set. Ajax uploads and resumable uploads have been disabled.',
  74. retryStatus: 'Retrying upload for chunk # {chunk} for {filename}... retry # {retry}.',
  75. chunkQueueError: 'Could not push task to ajax pool for chunk index # {index}.',
  76. resumableMaxRetriesReached: 'Maximum resumable ajax retries ({n}) reached.',
  77. resumableRetryError: 'Could not retry the resumable request (try # {n})... aborting.',
  78. resumableAborting: 'Aborting / cancelling the resumable request.',
  79. resumableRequestError: 'Error processing resumable request. {msg}'
  80. },
  81. objUrl: window.URL || window.webkitURL,
  82. isBs: function (ver) {
  83. var chk = $.trim(($.fn.fileinputBsVersion || '') + '');
  84. ver = parseInt(ver, 10);
  85. if (!chk) {
  86. return ver === 4;
  87. }
  88. return ver === parseInt(chk.charAt(0), 10);
  89. },
  90. defaultButtonCss: function (fill) {
  91. return 'btn-default btn-' + (fill ? '' : 'outline-') + 'secondary';
  92. },
  93. now: function () {
  94. return new Date().getTime();
  95. },
  96. round: function (num) {
  97. num = parseFloat(num);
  98. return isNaN(num) ? 0 : Math.floor(Math.round(num));
  99. },
  100. getArray: function (obj) {
  101. var i, arr = [], len = obj && obj.length || 0;
  102. for (i = 0; i < len; i++) {
  103. arr.push(obj[i]);
  104. }
  105. return arr;
  106. },
  107. getFileRelativePath: function (file) {
  108. /** @namespace file.relativePath */
  109. /** @namespace file.webkitRelativePath */
  110. return String(file.newPath || file.relativePath || file.webkitRelativePath || $h.getFileName(file) || null);
  111. },
  112. getFileId: function (file, generateFileId) {
  113. var relativePath = $h.getFileRelativePath(file);
  114. if (typeof generateFileId === 'function') {
  115. return generateFileId(file);
  116. }
  117. if (!file) {
  118. return null;
  119. }
  120. if (!relativePath) {
  121. return null;
  122. }
  123. return (file.size + '_' + encodeURIComponent(relativePath).replace(/%/g, '_'));
  124. },
  125. getFrameSelector: function (id, selector) {
  126. selector = selector || '';
  127. return '[id="' + id + '"]' + selector;
  128. },
  129. getZoomSelector: function (id, selector) {
  130. return $h.getFrameSelector('zoom-' + id, selector);
  131. },
  132. getFrameElement: function ($element, id, selector) {
  133. return $element.find($h.getFrameSelector(id, selector));
  134. },
  135. getZoomElement: function ($element, id, selector) {
  136. return $element.find($h.getZoomSelector(id, selector));
  137. },
  138. getElapsed: function (seconds) {
  139. var delta = seconds, out = '', result = {}, structure = {
  140. year: 31536000,
  141. month: 2592000,
  142. week: 604800, // uncomment row to ignore
  143. day: 86400, // feel free to add your own row
  144. hour: 3600,
  145. minute: 60,
  146. second: 1
  147. };
  148. $h.getObjectKeys(structure).forEach(function (key) {
  149. result[key] = Math.floor(delta / structure[key]);
  150. delta -= result[key] * structure[key];
  151. });
  152. $.each(result, function (key, value) {
  153. if (value > 0) {
  154. out += (out ? ' ' : '') + value + key.substring(0, 1);
  155. }
  156. });
  157. return out;
  158. },
  159. debounce: function (func, delay) {
  160. var inDebounce;
  161. return function () {
  162. var args = arguments, context = this;
  163. clearTimeout(inDebounce);
  164. inDebounce = setTimeout(function () {
  165. func.apply(context, args);
  166. }, delay);
  167. };
  168. },
  169. stopEvent: function (e) {
  170. e.stopPropagation();
  171. e.preventDefault();
  172. },
  173. getFileName: function (file) {
  174. /** @namespace file.fileName */
  175. return file ? (file.fileName || file.name || '') : ''; // some confusion in different versions of Firefox
  176. },
  177. createObjectURL: function (data) {
  178. if ($h.objUrl && $h.objUrl.createObjectURL && data) {
  179. return $h.objUrl.createObjectURL(data);
  180. }
  181. return '';
  182. },
  183. revokeObjectURL: function (data) {
  184. if ($h.objUrl && $h.objUrl.revokeObjectURL && data) {
  185. $h.objUrl.revokeObjectURL(data);
  186. }
  187. },
  188. compare: function (input, str, exact) {
  189. return input !== undefined && (exact ? input === str : input.match(str));
  190. },
  191. isIE: function (ver) {
  192. var div, status;
  193. // check for IE versions < 11
  194. if (navigator.appName !== 'Microsoft Internet Explorer') {
  195. return false;
  196. }
  197. if (ver === 10) {
  198. return new RegExp('msie\\s' + ver, 'i').test(navigator.userAgent);
  199. }
  200. div = document.createElement('div');
  201. div.innerHTML = '<!--[if IE ' + ver + ']> <i></i> <![endif]-->';
  202. status = div.getElementsByTagName('i').length;
  203. document.body.appendChild(div);
  204. div.parentNode.removeChild(div);
  205. return status;
  206. },
  207. canOrientImage: function ($el) {
  208. var $img = $(document.createElement('img')).css({width: '1px', height: '1px'}).insertAfter($el),
  209. flag = $img.css('image-orientation');
  210. $img.remove();
  211. return !!flag;
  212. },
  213. canAssignFilesToInput: function () {
  214. var input = document.createElement('input');
  215. try {
  216. input.type = 'file';
  217. input.files = null;
  218. return true;
  219. } catch (err) {
  220. return false;
  221. }
  222. },
  223. getDragDropFolders: function (items) {
  224. var i, item, len = items ? items.length : 0, folders = 0;
  225. if (len > 0 && items[0].webkitGetAsEntry()) {
  226. for (i = 0; i < len; i++) {
  227. item = items[i].webkitGetAsEntry();
  228. if (item && item.isDirectory) {
  229. folders++;
  230. }
  231. }
  232. }
  233. return folders;
  234. },
  235. initModal: function ($modal) {
  236. var $body = $('body');
  237. if ($body.length) {
  238. $modal.appendTo($body);
  239. }
  240. },
  241. isFunction: function (v) {
  242. return typeof v === 'function';
  243. },
  244. isEmpty: function (value, trim) {
  245. if (value === undefined || value === null || value === '') {
  246. return true;
  247. }
  248. if ($h.isString(value) && trim) {
  249. return $.trim(value) === '';
  250. }
  251. if ($h.isArray(value)) {
  252. return value.length === 0;
  253. }
  254. if ($.isPlainObject(value) && $.isEmptyObject(value)) {
  255. return true
  256. }
  257. return false;
  258. },
  259. isArray: function (a) {
  260. return Array.isArray(a) || Object.prototype.toString.call(a) === '[object Array]';
  261. },
  262. isString: function (a) {
  263. return Object.prototype.toString.call(a) === '[object String]';
  264. },
  265. ifSet: function (needle, haystack, def) {
  266. def = def || '';
  267. return (haystack && typeof haystack === 'object' && needle in haystack) ? haystack[needle] : def;
  268. },
  269. cleanArray: function (arr) {
  270. if (!(arr instanceof Array)) {
  271. arr = [];
  272. }
  273. return arr.filter(function (e) {
  274. return (e !== undefined && e !== null);
  275. });
  276. },
  277. spliceArray: function (arr, index, reverseOrder) {
  278. var i, j = 0, out = [], newArr;
  279. if (!(arr instanceof Array)) {
  280. return [];
  281. }
  282. newArr = $.extend(true, [], arr);
  283. if (reverseOrder) {
  284. newArr.reverse();
  285. }
  286. for (i = 0; i < newArr.length; i++) {
  287. if (i !== index) {
  288. out[j] = newArr[i];
  289. j++;
  290. }
  291. }
  292. if (reverseOrder) {
  293. out.reverse();
  294. }
  295. return out;
  296. },
  297. getNum: function (num, def) {
  298. def = def || 0;
  299. if (typeof num === 'number') {
  300. return num;
  301. }
  302. if (typeof num === 'string') {
  303. num = parseFloat(num);
  304. }
  305. return isNaN(num) ? def : num;
  306. },
  307. hasFileAPISupport: function () {
  308. return !!(window.File && window.FileReader);
  309. },
  310. hasDragDropSupport: function () {
  311. var div = document.createElement('div');
  312. /** @namespace div.draggable */
  313. /** @namespace div.ondragstart */
  314. /** @namespace div.ondrop */
  315. return !$h.isIE(9) &&
  316. (div.draggable !== undefined || (div.ondragstart !== undefined && div.ondrop !== undefined));
  317. },
  318. hasFileUploadSupport: function () {
  319. return $h.hasFileAPISupport() && window.FormData;
  320. },
  321. hasBlobSupport: function () {
  322. try {
  323. return !!window.Blob && Boolean(new Blob());
  324. } catch (e) {
  325. return false;
  326. }
  327. },
  328. hasArrayBufferViewSupport: function () {
  329. try {
  330. return new Blob([new Uint8Array(100)]).size === 100;
  331. } catch (e) {
  332. return false;
  333. }
  334. },
  335. hasResumableUploadSupport: function () {
  336. /** @namespace Blob.prototype.webkitSlice */
  337. /** @namespace Blob.prototype.mozSlice */
  338. return $h.hasFileUploadSupport() && $h.hasBlobSupport() && $h.hasArrayBufferViewSupport() &&
  339. (!!Blob.prototype.webkitSlice || !!Blob.prototype.mozSlice || !!Blob.prototype.slice || false);
  340. },
  341. dataURI2Blob: function (dataURI) {
  342. var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder ||
  343. window.MSBlobBuilder, canBlob = $h.hasBlobSupport(), byteStr, arrayBuffer, intArray, i, mimeStr, bb,
  344. canProceed = (canBlob || BlobBuilder) && window.atob && window.ArrayBuffer && window.Uint8Array;
  345. if (!canProceed) {
  346. return null;
  347. }
  348. if (dataURI.split(',')[0].indexOf('base64') >= 0) {
  349. byteStr = atob(dataURI.split(',')[1]);
  350. } else {
  351. byteStr = decodeURIComponent(dataURI.split(',')[1]);
  352. }
  353. arrayBuffer = new ArrayBuffer(byteStr.length);
  354. intArray = new Uint8Array(arrayBuffer);
  355. for (i = 0; i < byteStr.length; i += 1) {
  356. intArray[i] = byteStr.charCodeAt(i);
  357. }
  358. mimeStr = dataURI.split(',')[0].split(':')[1].split(';')[0];
  359. if (canBlob) {
  360. return new Blob([$h.hasArrayBufferViewSupport() ? intArray : arrayBuffer], {type: mimeStr});
  361. }
  362. bb = new BlobBuilder();
  363. bb.append(arrayBuffer);
  364. return bb.getBlob(mimeStr);
  365. },
  366. arrayBuffer2String: function (buffer) {
  367. if (window.TextDecoder) {
  368. return new TextDecoder('utf-8').decode(buffer);
  369. }
  370. var array = Array.prototype.slice.apply(new Uint8Array(buffer)), out = '', i = 0, len, c, char2, char3;
  371. len = array.length;
  372. while (i < len) {
  373. c = array[i++];
  374. switch (c >> 4) { // jshint ignore:line
  375. case 0:
  376. case 1:
  377. case 2:
  378. case 3:
  379. case 4:
  380. case 5:
  381. case 6:
  382. case 7:
  383. // 0xxxxxxx
  384. out += String.fromCharCode(c);
  385. break;
  386. case 12:
  387. case 13:
  388. // 110x xxxx 10xx xxxx
  389. char2 = array[i++];
  390. out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F)); // jshint ignore:line
  391. break;
  392. case 14:
  393. // 1110 xxxx 10xx xxxx 10xx xxxx
  394. char2 = array[i++];
  395. char3 = array[i++];
  396. out += String.fromCharCode(((c & 0x0F) << 12) | // jshint ignore:line
  397. ((char2 & 0x3F) << 6) | // jshint ignore:line
  398. ((char3 & 0x3F) << 0)); // jshint ignore:line
  399. break;
  400. }
  401. }
  402. return out;
  403. },
  404. isHtml: function (str) {
  405. var a = document.createElement('div');
  406. a.innerHTML = str;
  407. for (var c = a.childNodes, i = c.length; i--;) {
  408. if (c[i].nodeType === 1) {
  409. return true;
  410. }
  411. }
  412. return false;
  413. },
  414. isSvg: function (str) {
  415. return str.match(/^\s*<\?xml/i) && (str.match(/<!DOCTYPE svg/i) || str.match(/<svg/i));
  416. },
  417. getMimeType: function (signature, contents, type) {
  418. switch (signature) {
  419. case 'ffd8ffe0':
  420. case 'ffd8ffe1':
  421. case 'ffd8ffe2':
  422. return 'image/jpeg';
  423. case '89504e47':
  424. return 'image/png';
  425. case '47494638':
  426. return 'image/gif';
  427. case '49492a00':
  428. return 'image/tiff';
  429. case '52494646':
  430. return 'image/webp';
  431. case '66747970':
  432. return 'video/3gp';
  433. case '4f676753':
  434. return 'video/ogg';
  435. case '1a45dfa3':
  436. return 'video/mkv';
  437. case '000001ba':
  438. case '000001b3':
  439. return 'video/mpeg';
  440. case '3026b275':
  441. return 'video/wmv';
  442. case '25504446':
  443. return 'application/pdf';
  444. case '25215053':
  445. return 'application/ps';
  446. case '504b0304':
  447. case '504b0506':
  448. case '504b0508':
  449. return 'application/zip';
  450. case '377abcaf':
  451. return 'application/7z';
  452. case '75737461':
  453. return 'application/tar';
  454. case '7801730d':
  455. return 'application/dmg';
  456. default:
  457. switch (signature.substring(0, 6)) {
  458. case '435753':
  459. return 'application/x-shockwave-flash';
  460. case '494433':
  461. return 'audio/mp3';
  462. case '425a68':
  463. return 'application/bzip';
  464. default:
  465. switch (signature.substring(0, 4)) {
  466. case '424d':
  467. return 'image/bmp';
  468. case 'fffb':
  469. return 'audio/mp3';
  470. case '4d5a':
  471. return 'application/exe';
  472. case '1f9d':
  473. case '1fa0':
  474. return 'application/zip';
  475. case '1f8b':
  476. return 'application/gzip';
  477. default:
  478. return contents && !contents.match(
  479. /[^\u0000-\u007f]/) ? 'application/text-plain' : type;
  480. }
  481. }
  482. }
  483. },
  484. addCss: function ($el, css) {
  485. $el.removeClass(css).addClass(css);
  486. },
  487. getElement: function (options, param, value) {
  488. return ($h.isEmpty(options) || $h.isEmpty(options[param])) ? value : $(options[param]);
  489. },
  490. createElement: function (str, tag) {
  491. tag = tag || 'div';
  492. return $($.parseHTML('<' + tag + '>' + str + '</' + tag + '>'));
  493. },
  494. uniqId: function () {
  495. return (new Date().getTime() + Math.floor(Math.random() * Math.pow(10, 15))).toString(36);
  496. },
  497. cspBuffer: {
  498. CSP_ATTRIB: 'data-csp-01928735', // a randomly named temporary attribute to store the CSP elem id
  499. domElementsStyles: {},
  500. stash: function (htmlString) {
  501. var self = this, outerDom = $.parseHTML('<div>' + htmlString + '</div>'), $el = $(outerDom);
  502. $el.find('[style]').each(function (key, elem) {
  503. var $elem = $(elem), styleDeclaration = $elem[0].style, id = $h.uniqId(), styles = {};
  504. if (styleDeclaration && styleDeclaration.length) {
  505. $(styleDeclaration).each(function () {
  506. styles[this] = styleDeclaration[this];
  507. });
  508. self.domElementsStyles[id] = styles;
  509. $elem.removeAttr('style').attr(self.CSP_ATTRIB, id);
  510. }
  511. });
  512. $el.filter('*').removeAttr('style'); // make sure all style attr are removed
  513. var values = Object.values ? Object.values(outerDom) : Object.keys(outerDom).map(function (itm) {
  514. return outerDom[itm];
  515. });
  516. return values.flatMap(function (elem) {
  517. return elem.innerHTML;
  518. }).join('');
  519. },
  520. apply: function (domElement) {
  521. var self = this, $el = $(domElement);
  522. $el.find('[' + self.CSP_ATTRIB + ']').each(function (key, elem) {
  523. var $elem = $(elem), id = $elem.attr(self.CSP_ATTRIB), styles = self.domElementsStyles[id];
  524. if (styles) {
  525. $elem.css(styles);
  526. }
  527. $elem.removeAttr(self.CSP_ATTRIB);
  528. });
  529. self.domElementsStyles = {};
  530. }
  531. },
  532. setHtml: function ($elem, htmlString) {
  533. var buf = $h.cspBuffer;
  534. $elem.html(buf.stash(htmlString));
  535. buf.apply($elem);
  536. return $elem;
  537. },
  538. htmlEncode: function (str, undefVal) {
  539. if (str === undefined) {
  540. return undefVal || null;
  541. }
  542. return str.replace(/&/g, '&amp;')
  543. .replace(/</g, '&lt;')
  544. .replace(/>/g, '&gt;')
  545. .replace(/"/g, '&quot;')
  546. .replace(/'/g, '&apos;');
  547. },
  548. replaceTags: function (str, tags) {
  549. var out = str;
  550. if (!tags) {
  551. return out;
  552. }
  553. $.each(tags, function (key, value) {
  554. if (typeof value === 'function') {
  555. value = value();
  556. }
  557. out = out.split(key).join(value);
  558. });
  559. return out;
  560. },
  561. cleanMemory: function ($thumb) {
  562. var data = $thumb.is('img') ? $thumb.attr('src') : $thumb.find('source').attr('src');
  563. $h.revokeObjectURL(data);
  564. },
  565. findFileName: function (filePath) {
  566. var sepIndex = filePath.lastIndexOf('/');
  567. if (sepIndex === -1) {
  568. sepIndex = filePath.lastIndexOf('\\');
  569. }
  570. return filePath.split(filePath.substring(sepIndex, sepIndex + 1)).pop();
  571. },
  572. checkFullScreen: function () {
  573. return document.fullscreenElement || document.mozFullScreenElement || document.webkitFullscreenElement ||
  574. document.msFullscreenElement;
  575. },
  576. toggleFullScreen: function (maximize) {
  577. var doc = document, de = doc.documentElement, isFullScreen = $h.checkFullScreen();
  578. if (de && maximize && !isFullScreen) {
  579. if (de.requestFullscreen) {
  580. de.requestFullscreen();
  581. } else {
  582. if (de.msRequestFullscreen) {
  583. de.msRequestFullscreen();
  584. } else {
  585. if (de.mozRequestFullScreen) {
  586. de.mozRequestFullScreen();
  587. } else {
  588. if (de.webkitRequestFullscreen) {
  589. de.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
  590. }
  591. }
  592. }
  593. }
  594. } else {
  595. if (isFullScreen) {
  596. if (doc.exitFullscreen) {
  597. doc.exitFullscreen();
  598. } else {
  599. if (doc.msExitFullscreen) {
  600. doc.msExitFullscreen();
  601. } else {
  602. if (doc.mozCancelFullScreen) {
  603. doc.mozCancelFullScreen();
  604. } else {
  605. if (doc.webkitExitFullscreen) {
  606. doc.webkitExitFullscreen();
  607. }
  608. }
  609. }
  610. }
  611. }
  612. }
  613. },
  614. moveArray: function (arr, oldIndex, newIndex, reverseOrder) {
  615. var newArr = $.extend(true, [], arr);
  616. if (reverseOrder) {
  617. newArr.reverse();
  618. }
  619. if (newIndex >= newArr.length) {
  620. var k = newIndex - newArr.length;
  621. while ((k--) + 1) {
  622. newArr.push(undefined);
  623. }
  624. }
  625. newArr.splice(newIndex, 0, newArr.splice(oldIndex, 1)[0]);
  626. if (reverseOrder) {
  627. newArr.reverse();
  628. }
  629. return newArr;
  630. },
  631. closeButton: function (css) {
  632. css = ($h.isBs(5) ? 'btn-close' : 'close') + (css ? ' ' + css : '');
  633. return '<button type="button" class="' + css + '" aria-label="Close">\n' +
  634. ($h.isBs(5) ? '' : ' <span aria-hidden="true">&times;</span>\n') +
  635. '</button>';
  636. },
  637. getRotation: function (value) {
  638. switch (value) {
  639. case 2:
  640. return 'rotateY(180deg)';
  641. case 3:
  642. return 'rotate(180deg)';
  643. case 4:
  644. return 'rotate(180deg) rotateY(180deg)';
  645. case 5:
  646. return 'rotate(270deg) rotateY(180deg)';
  647. case 6:
  648. return 'rotate(90deg)';
  649. case 7:
  650. return 'rotate(90deg) rotateY(180deg)';
  651. case 8:
  652. return 'rotate(270deg)';
  653. default:
  654. return '';
  655. }
  656. },
  657. setTransform: function (el, val) {
  658. if (!el) {
  659. return;
  660. }
  661. el.style.transform = val;
  662. el.style.webkitTransform = val;
  663. el.style['-moz-transform'] = val;
  664. el.style['-ms-transform'] = val;
  665. el.style['-o-transform'] = val;
  666. },
  667. getObjectKeys: function (obj) {
  668. var keys = [];
  669. if (obj) {
  670. $.each(obj, function (key) {
  671. keys.push(key);
  672. });
  673. }
  674. return keys;
  675. },
  676. getObjectSize: function (obj) {
  677. return $h.getObjectKeys(obj).length;
  678. },
  679. /**
  680. * Small dependency injection for the task manager
  681. * https://gist.github.com/fearphage/4341799
  682. */
  683. whenAll: function (array) {
  684. var s = [].slice, resolveValues = arguments.length === 1 && $h.isArray(array) ? array : s.call(arguments),
  685. deferred = $.Deferred(), i, failed = 0, value, length = resolveValues.length,
  686. remaining = length, rejectContexts, rejectValues, resolveContexts, updateFunc;
  687. rejectContexts = rejectValues = resolveContexts = Array(length);
  688. updateFunc = function (index, contexts, values) {
  689. return function () {
  690. if (values !== resolveValues) {
  691. failed++;
  692. }
  693. deferred.notifyWith(contexts[index] = this, values[index] = s.call(arguments));
  694. if (!(--remaining)) {
  695. deferred[(!failed ? 'resolve' : 'reject') + 'With'](contexts, values);
  696. }
  697. };
  698. };
  699. for (i = 0; i < length; i++) {
  700. if ((value = resolveValues[i]) && $.isFunction(value.promise)) {
  701. value.promise()
  702. .done(updateFunc(i, resolveContexts, resolveValues))
  703. .fail(updateFunc(i, rejectContexts, rejectValues));
  704. } else {
  705. deferred.notifyWith(this, value);
  706. --remaining;
  707. }
  708. }
  709. if (!remaining) {
  710. deferred.resolveWith(resolveContexts, resolveValues);
  711. }
  712. return deferred.promise();
  713. }
  714. };
  715. FileInput = function (element, options) {
  716. var self = this;
  717. self.$element = $(element);
  718. self.$parent = self.$element.parent();
  719. if (!self._validate()) {
  720. return;
  721. }
  722. self.isPreviewable = $h.hasFileAPISupport();
  723. self.isIE9 = $h.isIE(9);
  724. self.isIE10 = $h.isIE(10);
  725. if (self.isPreviewable || self.isIE9) {
  726. self._init(options);
  727. self._listen();
  728. }
  729. self.$element.removeClass('file-loading');
  730. };
  731. FileInput.prototype = {
  732. constructor: FileInput,
  733. _cleanup: function () {
  734. var self = this;
  735. self.reader = null;
  736. self.clearFileStack();
  737. self.fileBatchCompleted = true;
  738. self.isError = false;
  739. self.isDuplicateError = false;
  740. self.isPersistentError = false;
  741. self.cancelling = false;
  742. self.paused = false;
  743. self.lastProgress = 0;
  744. self._initAjax();
  745. },
  746. _isAborted: function () {
  747. var self = this;
  748. return self.cancelling || self.paused;
  749. },
  750. _initAjax: function () {
  751. var self = this, tm = self.taskManager = {
  752. pool: {},
  753. addPool: function (id) {
  754. return (tm.pool[id] = new tm.TasksPool(id));
  755. },
  756. getPool: function (id) {
  757. return tm.pool[id];
  758. },
  759. addTask: function (id, logic) { // add standalone task directly from task manager
  760. return new tm.Task(id, logic);
  761. },
  762. TasksPool: function (id) {
  763. var tp = this;
  764. tp.id = id;
  765. tp.cancelled = false;
  766. tp.cancelledDeferrer = $.Deferred();
  767. tp.tasks = {};
  768. tp.addTask = function (id, logic) {
  769. return (tp.tasks[id] = new tm.Task(id, logic));
  770. };
  771. tp.size = function () {
  772. return $h.getObjectSize(tp.tasks);
  773. };
  774. tp.run = function (maxThreads) {
  775. var i = 0, failed = false, task, tasksList = $h.getObjectKeys(tp.tasks).map(function (key) {
  776. return tp.tasks[key];
  777. }), tasksDone = [], deferred = $.Deferred(), enqueue, callback;
  778. if (tp.cancelled) {
  779. tp.cancelledDeferrer.resolve();
  780. return deferred.reject();
  781. }
  782. // if run all at once
  783. if (!maxThreads) {
  784. var tasksDeferredList = $h.getObjectKeys(tp.tasks).map(function (key) {
  785. return tp.tasks[key].deferred;
  786. });
  787. // when all are done
  788. $h.whenAll(tasksDeferredList).done(function () {
  789. var argv = $h.getArray(arguments);
  790. if (!tp.cancelled) {
  791. deferred.resolve.apply(null, argv);
  792. tp.cancelledDeferrer.reject();
  793. } else {
  794. deferred.reject.apply(null, argv);
  795. tp.cancelledDeferrer.resolve();
  796. }
  797. }).fail(function () {
  798. var argv = $h.getArray(arguments);
  799. deferred.reject.apply(null, argv);
  800. if (!tp.cancelled) {
  801. tp.cancelledDeferrer.reject();
  802. } else {
  803. tp.cancelledDeferrer.resolve();
  804. }
  805. });
  806. // run all tasks
  807. $.each(tp.tasks, function (id) {
  808. task = tp.tasks[id];
  809. task.run();
  810. });
  811. return deferred;
  812. }
  813. enqueue = function (task) {
  814. $.when(task.deferred)
  815. .fail(function () {
  816. failed = true;
  817. callback.apply(null, arguments);
  818. })
  819. .always(callback);
  820. };
  821. callback = function () {
  822. var argv = $h.getArray(arguments);
  823. // notify a task just ended
  824. deferred.notify(argv);
  825. tasksDone.push(argv);
  826. if (tp.cancelled) {
  827. deferred.reject.apply(null, tasksDone);
  828. tp.cancelledDeferrer.resolve();
  829. return;
  830. }
  831. if (tasksDone.length === tp.size()) {
  832. if (failed) {
  833. deferred.reject.apply(null, tasksDone);
  834. } else {
  835. deferred.resolve.apply(null, tasksDone);
  836. }
  837. }
  838. // if there are any tasks remaining
  839. if (tasksList.length) {
  840. task = tasksList.shift();
  841. enqueue(task);
  842. task.run();
  843. }
  844. };
  845. // run the first "maxThreads" tasks
  846. while (tasksList.length && i++ < maxThreads) {
  847. task = tasksList.shift();
  848. enqueue(task);
  849. task.run();
  850. }
  851. return deferred;
  852. };
  853. tp.cancel = function () {
  854. tp.cancelled = true;
  855. return tp.cancelledDeferrer;
  856. };
  857. },
  858. Task: function (id, logic) {
  859. var tk = this;
  860. tk.id = id;
  861. tk.deferred = $.Deferred();
  862. tk.logic = logic;
  863. tk.context = null;
  864. tk.run = function () {
  865. var argv = $h.getArray(arguments);
  866. argv.unshift(tk.deferred); // add deferrer as first argument
  867. logic.apply(tk.context, argv); // run task
  868. return tk.deferred; // return deferrer
  869. };
  870. tk.runWithContext = function (context) {
  871. tk.context = context;
  872. return tk.run();
  873. };
  874. }
  875. };
  876. self.ajaxQueue = [];
  877. self.ajaxRequests = [];
  878. self.ajaxAborted = false;
  879. },
  880. _init: function (options, refreshMode) {
  881. var self = this, f, $el = self.$element, $cont, t, tmp;
  882. self.options = options;
  883. self.canOrientImage = $h.canOrientImage($el);
  884. $.each(options, function (key, value) {
  885. switch (key) {
  886. case 'minFileCount':
  887. case 'maxFileCount':
  888. case 'maxTotalFileCount':
  889. case 'minFileSize':
  890. case 'maxFileSize':
  891. case 'maxFilePreviewSize':
  892. case 'resizeQuality':
  893. case 'resizeIfSizeMoreThan':
  894. case 'progressUploadThreshold':
  895. case 'initialPreviewCount':
  896. case 'zoomModalHeight':
  897. case 'minImageHeight':
  898. case 'maxImageHeight':
  899. case 'minImageWidth':
  900. case 'maxImageWidth':
  901. self[key] = $h.getNum(value);
  902. break;
  903. default:
  904. self[key] = value;
  905. break;
  906. }
  907. });
  908. if (self.errorCloseButton === undefined) {
  909. self.errorCloseButton = $h.closeButton('kv-error-close' + ($h.isBs(5) ? ' float-end' : ''));
  910. }
  911. if (self.maxTotalFileCount > 0 && self.maxTotalFileCount < self.maxFileCount) {
  912. self.maxTotalFileCount = self.maxFileCount;
  913. }
  914. if (self.rtl) { // swap buttons for rtl
  915. tmp = self.previewZoomButtonIcons.prev;
  916. self.previewZoomButtonIcons.prev = self.previewZoomButtonIcons.next;
  917. self.previewZoomButtonIcons.next = tmp;
  918. }
  919. // validate chunk threads to not exceed maxAjaxThreads
  920. if (!isNaN(self.maxAjaxThreads) && self.maxAjaxThreads < self.resumableUploadOptions.maxThreads) {
  921. self.resumableUploadOptions.maxThreads = self.maxAjaxThreads;
  922. }
  923. self._initFileManager();
  924. if (typeof self.autoOrientImage === 'function') {
  925. self.autoOrientImage = self.autoOrientImage();
  926. }
  927. if (typeof self.autoOrientImageInitial === 'function') {
  928. self.autoOrientImageInitial = self.autoOrientImageInitial();
  929. }
  930. if (!refreshMode) {
  931. self._cleanup();
  932. }
  933. self.duplicateErrors = [];
  934. self.$form = $el.closest('form');
  935. self._initTemplateDefaults();
  936. self.uploadFileAttr = !$h.isEmpty($el.attr('name')) ? $el.attr('name') : 'file_data';
  937. t = self._getLayoutTemplate('progress');
  938. self.progressTemplate = t.replace('{class}', self.progressClass);
  939. self.progressInfoTemplate = t.replace('{class}', self.progressInfoClass);
  940. self.progressPauseTemplate = t.replace('{class}', self.progressPauseClass);
  941. self.progressCompleteTemplate = t.replace('{class}', self.progressCompleteClass);
  942. self.progressErrorTemplate = t.replace('{class}', self.progressErrorClass);
  943. self.isDisabled = $el.attr('disabled') || $el.attr('readonly');
  944. if (self.isDisabled) {
  945. $el.attr('disabled', true);
  946. }
  947. self.isClickable = self.browseOnZoneClick && self.showPreview &&
  948. (self.dropZoneEnabled || !$h.isEmpty(self.defaultPreviewContent));
  949. self.isAjaxUpload = $h.hasFileUploadSupport() && !$h.isEmpty(self.uploadUrl);
  950. self.dropZoneEnabled = $h.hasDragDropSupport() && self.dropZoneEnabled;
  951. if (!self.isAjaxUpload) {
  952. self.dropZoneEnabled = self.dropZoneEnabled && $h.canAssignFilesToInput();
  953. }
  954. self.slug = typeof options.slugCallback === 'function' ? options.slugCallback : self._slugDefault;
  955. self.mainTemplate = self.showCaption ? self._getLayoutTemplate('main1') : self._getLayoutTemplate('main2');
  956. self.captionTemplate = self._getLayoutTemplate('caption');
  957. self.previewGenericTemplate = self._getPreviewTemplate('generic');
  958. if (!self.imageCanvas && self.resizeImage && (self.maxImageWidth || self.maxImageHeight)) {
  959. self.imageCanvas = document.createElement('canvas');
  960. self.imageCanvasContext = self.imageCanvas.getContext('2d');
  961. }
  962. if ($h.isEmpty($el.attr('id'))) {
  963. $el.attr('id', $h.uniqId());
  964. }
  965. self.namespace = '.fileinput_' + $el.attr('id').replace(/-/g, '_');
  966. if (self.$container === undefined) {
  967. self.$container = self._createContainer();
  968. } else {
  969. self._refreshContainer();
  970. }
  971. $cont = self.$container;
  972. self.$dropZone = $cont.find('.file-drop-zone');
  973. self.$progress = $cont.find('.kv-upload-progress');
  974. self.$btnUpload = $cont.find('.fileinput-upload');
  975. self.$captionContainer = $h.getElement(options, 'elCaptionContainer', $cont.find('.file-caption'));
  976. self.$caption = $h.getElement(options, 'elCaptionText', $cont.find('.file-caption-name'));
  977. if (!$h.isEmpty(self.msgPlaceholder)) {
  978. f = $el.attr('multiple') ? self.filePlural : self.fileSingle;
  979. self.$caption.attr('placeholder', self.msgPlaceholder.replace('{files}', f));
  980. }
  981. self.$captionIcon = self.$captionContainer.find('.file-caption-icon');
  982. self.$previewContainer = $h.getElement(options, 'elPreviewContainer', $cont.find('.file-preview'));
  983. self.$preview = $h.getElement(options, 'elPreviewImage', $cont.find('.file-preview-thumbnails'));
  984. self.$previewStatus = $h.getElement(options, 'elPreviewStatus', $cont.find('.file-preview-status'));
  985. self.$errorContainer = $h.getElement(options, 'elErrorContainer',
  986. self.$previewContainer.find('.kv-fileinput-error'));
  987. self._validateDisabled();
  988. if (!$h.isEmpty(self.msgErrorClass)) {
  989. $h.addCss(self.$errorContainer, self.msgErrorClass);
  990. }
  991. if (!refreshMode) {
  992. self._resetErrors();
  993. self.$errorContainer.hide();
  994. self.previewInitId = 'thumb-' + $el.attr('id');
  995. self._initPreviewCache();
  996. self._initPreview(true);
  997. self._initPreviewActions();
  998. if (self.$parent.hasClass('file-loading')) {
  999. self.$container.insertBefore(self.$parent);
  1000. self.$parent.remove();
  1001. }
  1002. } else {
  1003. if (!self._errorsExist()) {
  1004. self.$errorContainer.hide();
  1005. }
  1006. }
  1007. self._setFileDropZoneTitle();
  1008. if ($el.attr('disabled')) {
  1009. self.disable();
  1010. }
  1011. self._initZoom();
  1012. if (self.hideThumbnailContent) {
  1013. $h.addCss(self.$preview, 'hide-content');
  1014. }
  1015. },
  1016. _initFileManager: function () {
  1017. var self = this;
  1018. self.uploadStartTime = $h.now();
  1019. self.fileManager = {
  1020. stack: {},
  1021. filesProcessed: [],
  1022. errors: [],
  1023. loadedImages: {},
  1024. totalImages: 0,
  1025. totalFiles: null,
  1026. totalSize: null,
  1027. uploadedSize: 0,
  1028. stats: {},
  1029. bpsLog: [],
  1030. bps: 0,
  1031. initStats: function (id) {
  1032. var data = {started: $h.now()};
  1033. if (id) {
  1034. self.fileManager.stats[id] = data;
  1035. } else {
  1036. self.fileManager.stats = data;
  1037. }
  1038. },
  1039. getUploadStats: function (id, loaded, total) {
  1040. var fm = self.fileManager,
  1041. started = id ? fm.stats[id] && fm.stats[id].started || $h.now() : self.uploadStartTime,
  1042. elapsed = ($h.now() - started) / 1000,
  1043. speeds = ['B/s', 'KB/s', 'MB/s', 'GB/s', 'TB/s', 'PB/s', 'EB/s', 'ZB/s', 'YB/s'],
  1044. bps = Math.ceil(elapsed ? loaded / elapsed : 0),
  1045. pendingBytes = total - loaded, out, delay = fm.bpsLog.length ? self.bitrateUpdateDelay : 0;
  1046. setTimeout(function () {
  1047. var i, j = 0, n = 0, len, beg;
  1048. fm.bpsLog.push(bps);
  1049. fm.bpsLog.sort(function (a, b) {
  1050. return a - b;
  1051. });
  1052. len = fm.bpsLog.length;
  1053. beg = len > 10 ? len - 10 : Math.ceil(len / 2);
  1054. for (i = len; i > beg; i--) {
  1055. n = parseFloat(fm.bpsLog[i]);
  1056. j++;
  1057. }
  1058. fm.bps = (j > 0 ? n / j : 0) * 64;
  1059. }, delay);
  1060. out = {
  1061. fileId: id,
  1062. started: started,
  1063. elapsed: elapsed,
  1064. loaded: loaded,
  1065. total: total,
  1066. bps: fm.bps,
  1067. bitrate: self._getSize(fm.bps, speeds),
  1068. pendingBytes: pendingBytes
  1069. };
  1070. if (id) {
  1071. fm.stats[id] = out;
  1072. } else {
  1073. fm.stats = out;
  1074. }
  1075. return out;
  1076. },
  1077. exists: function (id) {
  1078. return $.inArray(id, self.fileManager.getIdList()) !== -1;
  1079. },
  1080. count: function () {
  1081. return self.fileManager.getIdList().length;
  1082. },
  1083. total: function () {
  1084. var fm = self.fileManager;
  1085. if (!fm.totalFiles) {
  1086. fm.totalFiles = fm.count();
  1087. }
  1088. return fm.totalFiles;
  1089. },
  1090. getTotalSize: function () {
  1091. var fm = self.fileManager;
  1092. if (fm.totalSize) {
  1093. return fm.totalSize;
  1094. }
  1095. fm.totalSize = 0;
  1096. $.each(self.getFileStack(), function (id, f) {
  1097. var size = parseFloat(f.size);
  1098. fm.totalSize += isNaN(size) ? 0 : size;
  1099. });
  1100. return fm.totalSize;
  1101. },
  1102. add: function (file, id) {
  1103. if (!id) {
  1104. id = self.fileManager.getId(file);
  1105. }
  1106. if (!id) {
  1107. return;
  1108. }
  1109. self.fileManager.stack[id] = {
  1110. file: file,
  1111. name: $h.getFileName(file),
  1112. relativePath: $h.getFileRelativePath(file),
  1113. size: file.size,
  1114. nameFmt: self._getFileName(file, ''),
  1115. sizeFmt: self._getSize(file.size)
  1116. };
  1117. },
  1118. remove: function ($thumb) {
  1119. var id = self._getThumbFileId($thumb);
  1120. self.fileManager.removeFile(id);
  1121. },
  1122. removeFile: function (id) {
  1123. var fm = self.fileManager;
  1124. if (!id) {
  1125. return;
  1126. }
  1127. delete fm.stack[id];
  1128. delete fm.loadedImages[id];
  1129. },
  1130. move: function (idFrom, idTo) {
  1131. var result = {}, stack = self.fileManager.stack;
  1132. if (!idFrom && !idTo || idFrom === idTo) {
  1133. return;
  1134. }
  1135. $.each(stack, function (k, v) {
  1136. if (k !== idFrom) {
  1137. result[k] = v;
  1138. }
  1139. if (k === idTo) {
  1140. result[idFrom] = stack[idFrom];
  1141. }
  1142. });
  1143. self.fileManager.stack = result;
  1144. },
  1145. list: function () {
  1146. var files = [];
  1147. $.each(self.getFileStack(), function (k, v) {
  1148. if (v && v.file) {
  1149. files.push(v.file);
  1150. }
  1151. });
  1152. return files;
  1153. },
  1154. isPending: function (id) {
  1155. return $.inArray(id, self.fileManager.filesProcessed) === -1 && self.fileManager.exists(id);
  1156. },
  1157. isProcessed: function () {
  1158. var filesProcessed = true, fm = self.fileManager;
  1159. $.each(self.getFileStack(), function (id) {
  1160. if (fm.isPending(id)) {
  1161. filesProcessed = false;
  1162. }
  1163. });
  1164. return filesProcessed;
  1165. },
  1166. clear: function () {
  1167. var fm = self.fileManager;
  1168. self.isDuplicateError = false;
  1169. self.isPersistentError = false;
  1170. fm.totalFiles = null;
  1171. fm.totalSize = null;
  1172. fm.uploadedSize = 0;
  1173. fm.stack = {};
  1174. fm.errors = [];
  1175. fm.filesProcessed = [];
  1176. fm.stats = {};
  1177. fm.bpsLog = [];
  1178. fm.bps = 0;
  1179. fm.clearImages();
  1180. },
  1181. clearImages: function () {
  1182. self.fileManager.loadedImages = {};
  1183. self.fileManager.totalImages = 0;
  1184. },
  1185. addImage: function (id, config) {
  1186. self.fileManager.loadedImages[id] = config;
  1187. },
  1188. removeImage: function (id) {
  1189. delete self.fileManager.loadedImages[id];
  1190. },
  1191. getImageIdList: function () {
  1192. return $h.getObjectKeys(self.fileManager.loadedImages);
  1193. },
  1194. getImageCount: function () {
  1195. return self.fileManager.getImageIdList().length;
  1196. },
  1197. getId: function (file) {
  1198. return self._getFileId(file);
  1199. },
  1200. getIndex: function (id) {
  1201. return self.fileManager.getIdList().indexOf(id);
  1202. },
  1203. getThumb: function (id) {
  1204. var $thumb = null;
  1205. self._getThumbs().each(function () {
  1206. var $t = $(this);
  1207. if (self._getThumbFileId($t) === id) {
  1208. $thumb = $t;
  1209. }
  1210. });
  1211. return $thumb;
  1212. },
  1213. getThumbIndex: function ($thumb) {
  1214. var id = self._getThumbFileId($thumb);
  1215. return self.fileManager.getIndex(id);
  1216. },
  1217. getIdList: function () {
  1218. return $h.getObjectKeys(self.fileManager.stack);
  1219. },
  1220. getFile: function (id) {
  1221. return self.fileManager.stack[id] || null;
  1222. },
  1223. getFileName: function (id, fmt) {
  1224. var file = self.fileManager.getFile(id);
  1225. if (!file) {
  1226. return '';
  1227. }
  1228. return fmt ? (file.nameFmt || '') : file.name || '';
  1229. },
  1230. getFirstFile: function () {
  1231. var ids = self.fileManager.getIdList(), id = ids && ids.length ? ids[0] : null;
  1232. return self.fileManager.getFile(id);
  1233. },
  1234. setFile: function (id, file) {
  1235. if (self.fileManager.getFile(id)) {
  1236. self.fileManager.stack[id].file = file;
  1237. } else {
  1238. self.fileManager.add(file, id);
  1239. }
  1240. },
  1241. setProcessed: function (id) {
  1242. self.fileManager.filesProcessed.push(id);
  1243. },
  1244. getProgress: function () {
  1245. var total = self.fileManager.total(), filesProcessed = self.fileManager.filesProcessed.length;
  1246. if (!total) {
  1247. return 0;
  1248. }
  1249. return Math.ceil(filesProcessed / total * 100);
  1250. },
  1251. setProgress: function (id, pct) {
  1252. var f = self.fileManager.getFile(id);
  1253. if (!isNaN(pct) && f) {
  1254. f.progress = pct;
  1255. }
  1256. }
  1257. };
  1258. },
  1259. _setUploadData: function (fd, config) {
  1260. var self = this;
  1261. $.each(config, function (key, value) {
  1262. var param = self.uploadParamNames[key] || key;
  1263. if ($h.isArray(value)) {
  1264. fd.append(param, value[0], value[1]);
  1265. } else {
  1266. fd.append(param, value);
  1267. }
  1268. });
  1269. },
  1270. _initResumableUpload: function () {
  1271. var self = this, opts = self.resumableUploadOptions, logs = $h.logMessages, rm, fm = self.fileManager;
  1272. if (!self.enableResumableUpload) {
  1273. return;
  1274. }
  1275. if (opts.fallback !== false && typeof opts.fallback !== 'function') {
  1276. opts.fallback = function (s) {
  1277. s._log(logs.noResumableSupport);
  1278. s.enableResumableUpload = false;
  1279. };
  1280. }
  1281. if (!$h.hasResumableUploadSupport() && opts.fallback !== false) {
  1282. opts.fallback(self);
  1283. return;
  1284. }
  1285. if (!self.uploadUrl && self.enableResumableUpload) {
  1286. self._log(logs.noUploadUrl);
  1287. self.enableResumableUpload = false;
  1288. return;
  1289. }
  1290. opts.chunkSize = parseFloat(opts.chunkSize);
  1291. if (opts.chunkSize <= 0 || isNaN(opts.chunkSize)) {
  1292. self._log(logs.invalidChunkSize, {chunkSize: opts.chunkSize});
  1293. self.enableResumableUpload = false;
  1294. return;
  1295. }
  1296. rm = self.resumableManager = {
  1297. init: function (id, f, index) {
  1298. rm.logs = [];
  1299. rm.stack = [];
  1300. rm.error = '';
  1301. rm.id = id;
  1302. rm.file = f.file;
  1303. rm.fileName = f.name;
  1304. rm.fileIndex = index;
  1305. rm.completed = false;
  1306. rm.lastProgress = 0;
  1307. if (self.showPreview) {
  1308. rm.$thumb = fm.getThumb(id) || null;
  1309. rm.$progress = rm.$btnDelete = null;
  1310. if (rm.$thumb && rm.$thumb.length) {
  1311. rm.$progress = rm.$thumb.find('.file-thumb-progress');
  1312. rm.$btnDelete = rm.$thumb.find('.kv-file-remove');
  1313. }
  1314. }
  1315. rm.chunkSize = opts.chunkSize * 1024;
  1316. rm.chunkCount = rm.getTotalChunks();
  1317. },
  1318. setAjaxError: function (jqXHR, textStatus, errorThrown, isTest) {
  1319. if (jqXHR.responseJSON && jqXHR.responseJSON.error) {
  1320. errorThrown = jqXHR.responseJSON.error.toString();
  1321. }
  1322. if (!isTest) {
  1323. rm.error = errorThrown;
  1324. }
  1325. if (opts.showErrorLog) {
  1326. self._log(logs.ajaxError, {
  1327. status: jqXHR.status,
  1328. error: errorThrown,
  1329. text: jqXHR.responseText || ''
  1330. });
  1331. }
  1332. },
  1333. reset: function () {
  1334. rm.stack = [];
  1335. rm.chunksProcessed = {};
  1336. },
  1337. setProcessed: function (status) {
  1338. var id = rm.id, msg, $thumb = rm.$thumb, $prog = rm.$progress, hasThumb = $thumb && $thumb.length,
  1339. params = {id: hasThumb ? $thumb.attr('id') : '', index: fm.getIndex(id), fileId: id}, tokens,
  1340. skipErrorsAndProceed = self.resumableUploadOptions.skipErrorsAndProceed;
  1341. rm.completed = true;
  1342. rm.lastProgress = 0;
  1343. if (hasThumb) {
  1344. $thumb.removeClass('file-uploading');
  1345. }
  1346. if (status === 'success') {
  1347. fm.uploadedSize += rm.file.size;
  1348. if (self.showPreview) {
  1349. self._setProgress(101, $prog);
  1350. self._setThumbStatus($thumb, 'Success');
  1351. self._initUploadSuccess(rm.chunksProcessed[id].data, $thumb);
  1352. }
  1353. fm.removeFile(id);
  1354. delete rm.chunksProcessed[id];
  1355. self._raise('fileuploaded', [params.id, params.index, params.fileId]);
  1356. if (fm.isProcessed()) {
  1357. self._setProgress(101);
  1358. }
  1359. } else {
  1360. if (status !== 'cancel') {
  1361. if (self.showPreview) {
  1362. self._setThumbStatus($thumb, 'Error');
  1363. self._setPreviewError($thumb, true);
  1364. self._setProgress(101, $prog, self.msgProgressError);
  1365. self._setProgress(101, self.$progress, self.msgProgressError);
  1366. self.cancelling = !skipErrorsAndProceed;
  1367. }
  1368. if (!self.$errorContainer.find('li[data-file-id="' + params.fileId + '"]').length) {
  1369. tokens = {file: rm.fileName, max: opts.maxRetries, error: rm.error};
  1370. msg = self.msgResumableUploadRetriesExceeded.setTokens(tokens);
  1371. $.extend(params, tokens);
  1372. self._showFileError(msg, params, 'filemaxretries');
  1373. if (skipErrorsAndProceed) {
  1374. fm.removeFile(id);
  1375. delete rm.chunksProcessed[id];
  1376. if (fm.isProcessed()) {
  1377. self._setProgress(101);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. }
  1383. if (fm.isProcessed()) {
  1384. rm.reset();
  1385. }
  1386. },
  1387. check: function () {
  1388. var status = true;
  1389. $.each(rm.logs, function (index, value) {
  1390. if (!value) {
  1391. status = false;
  1392. return false;
  1393. }
  1394. });
  1395. },
  1396. processedResumables: function () {
  1397. var logs = rm.logs, i, count = 0;
  1398. if (!logs || !logs.length) {
  1399. return 0;
  1400. }
  1401. for (i = 0; i < logs.length; i++) {
  1402. if (logs[i] === true) {
  1403. count++;
  1404. }
  1405. }
  1406. return count;
  1407. },
  1408. getUploadedSize: function () {
  1409. var size = rm.processedResumables() * rm.chunkSize;
  1410. return size > rm.file.size ? rm.file.size : size;
  1411. },
  1412. getTotalChunks: function () {
  1413. var chunkSize = parseFloat(rm.chunkSize);
  1414. if (!isNaN(chunkSize) && chunkSize > 0) {
  1415. return Math.ceil(rm.file.size / chunkSize);
  1416. }
  1417. return 0;
  1418. },
  1419. getProgress: function () {
  1420. var chunksProcessed = rm.processedResumables(), total = rm.chunkCount;
  1421. if (total === 0) {
  1422. return 0;
  1423. }
  1424. return Math.ceil(chunksProcessed / total * 100);
  1425. },
  1426. checkAborted: function (intervalId) {
  1427. if (self._isAborted()) {
  1428. clearInterval(intervalId);
  1429. self.unlock();
  1430. }
  1431. },
  1432. upload: function () {
  1433. var ids = fm.getIdList(), flag = 'new', intervalId;
  1434. intervalId = setInterval(function () {
  1435. var id;
  1436. rm.checkAborted(intervalId);
  1437. if (flag === 'new') {
  1438. self.lock();
  1439. flag = 'processing';
  1440. id = ids.shift();
  1441. fm.initStats(id);
  1442. if (fm.stack[id]) {
  1443. rm.init(id, fm.stack[id], fm.getIndex(id));
  1444. rm.processUpload();
  1445. }
  1446. }
  1447. if (!fm.isPending(id) && rm.completed) {
  1448. flag = 'new';
  1449. }
  1450. if (fm.isProcessed()) {
  1451. var $initThumbs = self.$preview.find('.file-preview-initial');
  1452. if ($initThumbs.length) {
  1453. $h.addCss($initThumbs, $h.SORT_CSS);
  1454. self._initSortable();
  1455. }
  1456. clearInterval(intervalId);
  1457. self._clearFileInput();
  1458. self.unlock();
  1459. setTimeout(function () {
  1460. var data = self.previewCache.data;
  1461. if (data) {
  1462. self.initialPreview = data.content;
  1463. self.initialPreviewConfig = data.config;
  1464. self.initialPreviewThumbTags = data.tags;
  1465. }
  1466. self._raise('filebatchuploadcomplete', [
  1467. self.initialPreview,
  1468. self.initialPreviewConfig,
  1469. self.initialPreviewThumbTags,
  1470. self._getExtraData()
  1471. ]);
  1472. }, self.processDelay);
  1473. }
  1474. }, self.processDelay);
  1475. },
  1476. uploadResumable: function () {
  1477. var i, pool, tm = self.taskManager, total = rm.chunkCount;
  1478. pool = tm.addPool(rm.id);
  1479. for (i = 0; i < total; i++) {
  1480. rm.logs[i] = !!(rm.chunksProcessed[rm.id] && rm.chunksProcessed[rm.id][i]);
  1481. if (!rm.logs[i]) {
  1482. rm.pushAjax(i, 0);
  1483. }
  1484. }
  1485. pool.run(opts.maxThreads)
  1486. .done(function () {
  1487. rm.setProcessed('success');
  1488. })
  1489. .fail(function () {
  1490. rm.setProcessed(pool.cancelled ? 'cancel' : 'error');
  1491. });
  1492. },
  1493. processUpload: function () {
  1494. var fd, f, id = rm.id, fnBefore, fnSuccess, fnError, fnComplete, outData;
  1495. if (!opts.testUrl) {
  1496. rm.uploadResumable();
  1497. return;
  1498. }
  1499. fd = new FormData();
  1500. f = fm.stack[id];
  1501. self._setUploadData(fd, {
  1502. fileId: id,
  1503. fileName: f.fileName,
  1504. fileSize: f.size,
  1505. fileRelativePath: f.relativePath,
  1506. chunkSize: rm.chunkSize,
  1507. chunkCount: rm.chunkCount
  1508. });
  1509. fnBefore = function (jqXHR) {
  1510. outData = self._getOutData(fd, jqXHR);
  1511. self._raise('filetestbeforesend', [id, fm, rm, outData]);
  1512. };
  1513. fnSuccess = function (data, textStatus, jqXHR) {
  1514. outData = self._getOutData(fd, jqXHR, data);
  1515. var pNames = self.uploadParamNames, chunksUploaded = pNames.chunksUploaded || 'chunksUploaded',
  1516. params = [id, fm, rm, outData];
  1517. if (!data[chunksUploaded] || !$h.isArray(data[chunksUploaded])) {
  1518. self._raise('filetesterror', params);
  1519. } else {
  1520. if (!rm.chunksProcessed[id]) {
  1521. rm.chunksProcessed[id] = {};
  1522. }
  1523. $.each(data[chunksUploaded], function (key, index) {
  1524. rm.logs[index] = true;
  1525. rm.chunksProcessed[id][index] = true;
  1526. });
  1527. rm.chunksProcessed[id].data = data;
  1528. self._raise('filetestsuccess', params);
  1529. }
  1530. rm.uploadResumable();
  1531. };
  1532. fnError = function (jqXHR, textStatus, errorThrown) {
  1533. outData = self._getOutData(fd, jqXHR);
  1534. self._raise('filetestajaxerror', [id, fm, rm, outData]);
  1535. rm.setAjaxError(jqXHR, textStatus, errorThrown, true);
  1536. rm.uploadResumable();
  1537. };
  1538. fnComplete = function () {
  1539. self._raise('filetestcomplete', [id, fm, rm, self._getOutData(fd)]);
  1540. };
  1541. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex, opts.testUrl);
  1542. },
  1543. pushAjax: function (index, retry) {
  1544. var tm = self.taskManager, pool = tm.getPool(rm.id);
  1545. pool.addTask(pool.size() + 1, function (deferrer) {
  1546. // use fifo chunk stack
  1547. var arr = rm.stack.shift(), index;
  1548. index = arr[0];
  1549. if (!rm.chunksProcessed[rm.id] || !rm.chunksProcessed[rm.id][index]) {
  1550. rm.sendAjax(index, arr[1], deferrer);
  1551. } else {
  1552. self._log(logs.chunkQueueError, {index: index});
  1553. }
  1554. });
  1555. rm.stack.push([index, retry]);
  1556. },
  1557. sendAjax: function (index, retry, deferrer) {
  1558. var f, chunkSize = rm.chunkSize, id = rm.id, file = rm.file, $thumb = rm.$thumb,
  1559. msgs = $h.logMessages, $btnDelete = rm.$btnDelete, logError = function (msg, tokens) {
  1560. if (tokens) {
  1561. msg = msg.setTokens(tokens);
  1562. }
  1563. msg = msgs.resumableRequestError.setTokens({msg: msg});
  1564. self._log(msg);
  1565. deferrer.reject(msg);
  1566. };
  1567. if (rm.chunksProcessed[id] && rm.chunksProcessed[id][index]) {
  1568. return;
  1569. }
  1570. if (retry > opts.maxRetries) {
  1571. logError(msgs.resumableMaxRetriesReached, {n: opts.maxRetries});
  1572. rm.setProcessed('error');
  1573. return;
  1574. }
  1575. var fd, outData, fnBefore, fnSuccess, fnError, fnComplete, slice = file.slice ? 'slice' :
  1576. (file.mozSlice ? 'mozSlice' : (file.webkitSlice ? 'webkitSlice' : 'slice')),
  1577. blob = file[slice](chunkSize * index, chunkSize * (index + 1));
  1578. fd = new FormData();
  1579. f = fm.stack[id];
  1580. self._setUploadData(fd, {
  1581. chunkCount: rm.chunkCount,
  1582. chunkIndex: index,
  1583. chunkSize: chunkSize,
  1584. chunkSizeStart: chunkSize * index,
  1585. fileBlob: [blob, rm.fileName],
  1586. fileId: id,
  1587. fileName: rm.fileName,
  1588. fileRelativePath: f.relativePath,
  1589. fileSize: file.size,
  1590. retryCount: retry
  1591. });
  1592. if (rm.$progress && rm.$progress.length) {
  1593. rm.$progress.show();
  1594. }
  1595. fnBefore = function (jqXHR) {
  1596. outData = self._getOutData(fd, jqXHR);
  1597. if (self.showPreview) {
  1598. if (!$thumb.hasClass('file-preview-success')) {
  1599. self._setThumbStatus($thumb, 'Loading');
  1600. $h.addCss($thumb, 'file-uploading');
  1601. }
  1602. $btnDelete.attr('disabled', true);
  1603. }
  1604. self._raise('filechunkbeforesend', [id, index, retry, fm, rm, outData]);
  1605. };
  1606. fnSuccess = function (data, textStatus, jqXHR) {
  1607. if (self._isAborted()) {
  1608. logError(msgs.resumableAborting);
  1609. return;
  1610. }
  1611. outData = self._getOutData(fd, jqXHR, data);
  1612. var paramNames = self.uploadParamNames, chunkIndex = paramNames.chunkIndex || 'chunkIndex',
  1613. params = [id, index, retry, fm, rm, outData];
  1614. if (data.error) {
  1615. if (opts.showErrorLog) {
  1616. self._log(logs.retryStatus, {
  1617. retry: retry + 1,
  1618. filename: rm.fileName,
  1619. chunk: index
  1620. });
  1621. }
  1622. self._raise('filechunkerror', params);
  1623. rm.pushAjax(index, retry + 1);
  1624. rm.error = data.error;
  1625. logError(data.error);
  1626. } else {
  1627. rm.logs[data[chunkIndex]] = true;
  1628. if (!rm.chunksProcessed[id]) {
  1629. rm.chunksProcessed[id] = {};
  1630. }
  1631. rm.chunksProcessed[id][data[chunkIndex]] = true;
  1632. rm.chunksProcessed[id].data = data;
  1633. deferrer.resolve.call(null, data);
  1634. self._raise('filechunksuccess', params);
  1635. rm.check();
  1636. }
  1637. };
  1638. fnError = function (jqXHR, textStatus, errorThrown) {
  1639. if (self._isAborted()) {
  1640. logError(msgs.resumableAborting);
  1641. return;
  1642. }
  1643. outData = self._getOutData(fd, jqXHR);
  1644. rm.setAjaxError(jqXHR, textStatus, errorThrown);
  1645. self._raise('filechunkajaxerror', [id, index, retry, fm, rm, outData]);
  1646. rm.pushAjax(index, retry + 1); // push another task
  1647. logError(msgs.resumableRetryError, {n: retry - 1}); // resolve the current task
  1648. };
  1649. fnComplete = function () {
  1650. if (!self._isAborted()) {
  1651. self._raise('filechunkcomplete', [id, index, retry, fm, rm, self._getOutData(fd)]);
  1652. }
  1653. };
  1654. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, fd, id, rm.fileIndex);
  1655. }
  1656. };
  1657. rm.reset();
  1658. },
  1659. _initTemplateDefaults: function () {
  1660. var self = this, tMain1, tMain2, tPreview, tFileIcon, tClose, tCaption, tBtnDefault, tBtnLink, tBtnBrowse,
  1661. tModalMain, tModal, tProgress, tSize, tFooter, tActions, tActionDelete, tActionUpload, tActionDownload,
  1662. tActionZoom, tActionDrag, tIndicator, tTagBef, tTagBef1, tTagBef2, tTagAft, tGeneric, tHtml, tImage,
  1663. tText, tOffice, tGdocs, tVideo, tAudio, tFlash, tObject, tPdf, tOther, tStyle, tZoomCache, vDefaultDim,
  1664. tStats, tModalLabel, renderObject = function (type, mime) {
  1665. return '<object class="kv-preview-data file-preview-' + type + '" title="{caption}" ' +
  1666. 'data="{data}" type="' + mime + '"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1667. }, defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss();
  1668. tMain1 = '{preview}\n' +
  1669. '<div class="kv-upload-progress kv-hidden"></div><div class="clearfix"></div>\n' +
  1670. '<div class="file-caption {class}">\n' +
  1671. ' <div class="input-group {inputGroupClass}">\n' +
  1672. ' {caption}\n<span class="file-caption-icon"></span>\n' +
  1673. ($h.isBs(5) ? '' : '<div class="input-group-btn input-group-append">\n') +
  1674. ' {remove}\n' +
  1675. ' {cancel}\n' +
  1676. ' {pause}\n' +
  1677. ' {upload}\n' +
  1678. ' {browse}\n' +
  1679. ($h.isBs(5) ? '' : ' </div>\n') +
  1680. ' </div>'
  1681. '</div>';
  1682. tMain2 = '{preview}\n<div class="kv-upload-progress kv-hidden"></div>\n<div class="clearfix"></div>\n' +
  1683. '<span class="{class}">{remove}\n{cancel}\n{upload}\n{browse}\n</span>';
  1684. tPreview = '<div class="file-preview {class}">\n' +
  1685. ' {close}' +
  1686. ' <div class="{dropClass} clearfix">\n' +
  1687. ' <div class="file-preview-thumbnails clearfix">\n' +
  1688. ' </div>\n' +
  1689. ' <div class="file-preview-status text-center text-success"></div>\n' +
  1690. ' <div class="kv-fileinput-error"></div>\n' +
  1691. ' </div>\n' +
  1692. '</div>';
  1693. tClose = $h.closeButton('fileinput-remove');
  1694. tFileIcon = '<i class="bi-file-earmark-arrow-up"></i>';
  1695. // noinspection HtmlUnknownAttribute
  1696. tCaption = '<input readonly class="file-caption-name form-control {class}">\n';
  1697. //noinspection HtmlUnknownAttribute
  1698. tBtnDefault = '<button type="{type}" title="{title}" class="{css}" ' +
  1699. '{status} {tabIndexConfig}>{icon} {label}</button>';
  1700. //noinspection HtmlUnknownTarget,HtmlUnknownAttribute
  1701. tBtnLink = '<a href="{href}" title="{title}" class="{css}" {status} {tabIndexConfig}>{icon} {label}</a>';
  1702. //noinspection HtmlUnknownAttribute
  1703. tBtnBrowse = '<div class="{css}" {status} {tabIndexConfig}>{icon} {label}</div>';
  1704. tModalLabel = $h.MODAL_ID + 'Label';
  1705. tModalMain = '<div id="' + $h.MODAL_ID + '" class="file-zoom-dialog modal fade" ' +
  1706. 'aria-labelledby="' + tModalLabel + '" {tabIndexConfig}></div>';
  1707. tModal = '<div class="modal-dialog modal-lg{rtl}" role="document">\n' +
  1708. ' <div class="modal-content">\n' +
  1709. ' <div class="modal-header">\n' +
  1710. ' <h5 class="modal-title" id="' + tModalLabel + '">{heading}</h5>\n' +
  1711. ' <span class="kv-zoom-title"></span>\n' +
  1712. ' <div class="kv-zoom-actions">{toggleheader}{fullscreen}{borderless}{close}</div>\n' +
  1713. ' </div>\n' +
  1714. ' <div class="modal-body">\n' +
  1715. ' <div class="floating-buttons"></div>\n' +
  1716. ' <div class="kv-zoom-body file-zoom-content {zoomFrameClass}"></div>\n' + '{prev} {next}\n' +
  1717. ' </div>\n' +
  1718. ' </div>\n' +
  1719. '</div>\n';
  1720. tProgress = '<div class="progress">\n' +
  1721. ' <div class="{class}" role="progressbar"' +
  1722. ' aria-valuenow="{percent}" aria-valuemin="0" aria-valuemax="100" style="width:{percent}%;">\n' +
  1723. ' {status}\n' +
  1724. ' </div>\n' +
  1725. '</div>{stats}';
  1726. tStats = '<div class="text-primary file-upload-stats">' +
  1727. '<span class="pending-time">{pendingTime}</span> ' +
  1728. '<span class="upload-speed">{uploadSpeed}</span>' +
  1729. '</div>';
  1730. tSize = ' <samp>({sizeText})</samp>';
  1731. tFooter = '<div class="file-thumbnail-footer">\n' +
  1732. ' <div class="file-footer-caption" title="{caption}">\n' +
  1733. ' <div class="file-caption-info">{caption}</div>\n' +
  1734. ' <div class="file-size-info">{size}</div>\n' +
  1735. ' </div>\n' +
  1736. ' {progress}\n{indicator}\n{actions}\n' +
  1737. '</div>';
  1738. tActions = '<div class="file-actions">\n' +
  1739. ' <div class="file-footer-buttons">\n' +
  1740. ' {download} {upload} {delete} {zoom} {other}' +
  1741. ' </div>\n' +
  1742. '</div>\n' +
  1743. '{drag}\n' +
  1744. '<div class="clearfix"></div>';
  1745. //noinspection HtmlUnknownAttribute
  1746. tActionDelete = '<button type="button" class="kv-file-remove {removeClass}" ' +
  1747. 'title="{removeTitle}" {dataUrl}{dataKey}>{removeIcon}</button>\n';
  1748. tActionUpload = '<button type="button" class="kv-file-upload {uploadClass}" title="{uploadTitle}">' +
  1749. '{uploadIcon}</button>';
  1750. tActionDownload = '<a class="kv-file-download {downloadClass}" title="{downloadTitle}" ' +
  1751. 'href="{downloadUrl}" download="{caption}" target="_blank">{downloadIcon}</a>';
  1752. tActionZoom = '<button type="button" class="kv-file-zoom {zoomClass}" ' +
  1753. 'title="{zoomTitle}">{zoomIcon}</button>';
  1754. tActionDrag = '<span class="file-drag-handle {dragClass}" title="{dragTitle}">{dragIcon}</span>';
  1755. tIndicator = '<div class="file-upload-indicator" title="{indicatorTitle}">{indicator}</div>';
  1756. tTagBef = '<div class="file-preview-frame {frameClass}" id="{previewId}" data-fileindex="{fileindex}"' +
  1757. ' data-fileid="{fileid}" data-template="{template}" data-zoom="{zoomData}"';
  1758. tTagBef1 = tTagBef + '><div class="kv-file-content">\n';
  1759. tTagBef2 = tTagBef + ' title="{caption}"><div class="kv-file-content">\n';
  1760. tTagAft = '</div>{footer}\n{zoomCache}</div>\n';
  1761. tGeneric = '{content}\n';
  1762. tStyle = ' {style}';
  1763. tHtml = renderObject('html', 'text/html');
  1764. tText = renderObject('text', 'text/plain;charset=UTF-8');
  1765. tPdf = renderObject('pdf', 'application/pdf');
  1766. tImage = '<img src="{data}" class="file-preview-image kv-preview-data" title="{title}" alt="{alt}"' +
  1767. tStyle + '>\n';
  1768. tOffice = '<iframe class="kv-preview-data file-preview-office" ' +
  1769. 'src="https://view.officeapps.live.com/op/embed.aspx?src={data}"' + tStyle + '></iframe>';
  1770. tGdocs = '<iframe class="kv-preview-data file-preview-gdocs" ' +
  1771. 'src="https://docs.google.com/gview?url={data}&embedded=true"' + tStyle + '></iframe>';
  1772. tVideo = '<video class="kv-preview-data file-preview-video" controls' + tStyle + '>\n' +
  1773. '<source src="{data}" type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</video>\n';
  1774. tAudio = '<!--suppress ALL --><audio class="kv-preview-data file-preview-audio" controls' + tStyle + '>\n<source src="{data}" ' +
  1775. 'type="{type}">\n' + $h.DEFAULT_PREVIEW + '\n</audio>\n';
  1776. tFlash = '<embed class="kv-preview-data file-preview-flash" src="{data}" type="application/x-shockwave-flash"' + tStyle + '>\n';
  1777. tObject = '<object class="kv-preview-data file-preview-object file-object {typeCss}" ' +
  1778. 'data="{data}" type="{type}"' + tStyle + '>\n' + '<param name="movie" value="{caption}" />\n' +
  1779. $h.OBJECT_PARAMS + ' ' + $h.DEFAULT_PREVIEW + '\n</object>\n';
  1780. tOther = '<div class="kv-preview-data file-preview-other-frame"' + tStyle + '>\n' + $h.DEFAULT_PREVIEW + '\n</div>\n';
  1781. tZoomCache = '<div class="kv-zoom-cache">{zoomContent}</div>';
  1782. vDefaultDim = {width: '100%', height: '100%', 'min-height': '480px'};
  1783. if (self._isPdfRendered()) {
  1784. tPdf = self.pdfRendererTemplate.replace('{renderer}', self._encodeURI(self.pdfRendererUrl));
  1785. }
  1786. self.defaults = {
  1787. layoutTemplates: {
  1788. main1: tMain1,
  1789. main2: tMain2,
  1790. preview: tPreview,
  1791. close: tClose,
  1792. fileIcon: tFileIcon,
  1793. caption: tCaption,
  1794. modalMain: tModalMain,
  1795. modal: tModal,
  1796. progress: tProgress,
  1797. stats: tStats,
  1798. size: tSize,
  1799. footer: tFooter,
  1800. indicator: tIndicator,
  1801. actions: tActions,
  1802. actionDelete: tActionDelete,
  1803. actionUpload: tActionUpload,
  1804. actionDownload: tActionDownload,
  1805. actionZoom: tActionZoom,
  1806. actionDrag: tActionDrag,
  1807. btnDefault: tBtnDefault,
  1808. btnLink: tBtnLink,
  1809. btnBrowse: tBtnBrowse,
  1810. zoomCache: tZoomCache
  1811. },
  1812. previewMarkupTags: {
  1813. tagBefore1: tTagBef1,
  1814. tagBefore2: tTagBef2,
  1815. tagAfter: tTagAft
  1816. },
  1817. previewContentTemplates: {
  1818. generic: tGeneric,
  1819. html: tHtml,
  1820. image: tImage,
  1821. text: tText,
  1822. office: tOffice,
  1823. gdocs: tGdocs,
  1824. video: tVideo,
  1825. audio: tAudio,
  1826. flash: tFlash,
  1827. object: tObject,
  1828. pdf: tPdf,
  1829. other: tOther
  1830. },
  1831. allowedPreviewTypes: ['image', 'html', 'text', 'video', 'audio', 'flash', 'pdf', 'object'],
  1832. previewTemplates: {},
  1833. previewSettings: {
  1834. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1835. html: {width: '213px', height: '160px'},
  1836. text: {width: '213px', height: '160px'},
  1837. office: {width: '213px', height: '160px'},
  1838. gdocs: {width: '213px', height: '160px'},
  1839. video: {width: '213px', height: '160px'},
  1840. audio: {width: '100%', height: '30px'},
  1841. flash: {width: '213px', height: '160px'},
  1842. object: {width: '213px', height: '160px'},
  1843. pdf: {width: '100%', height: '160px', 'position': 'relative'},
  1844. other: {width: '213px', height: '160px'}
  1845. },
  1846. previewSettingsSmall: {
  1847. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1848. html: {width: '100%', height: '160px'},
  1849. text: {width: '100%', height: '160px'},
  1850. office: {width: '100%', height: '160px'},
  1851. gdocs: {width: '100%', height: '160px'},
  1852. video: {width: '100%', height: 'auto'},
  1853. audio: {width: '100%', height: '30px'},
  1854. flash: {width: '100%', height: 'auto'},
  1855. object: {width: '100%', height: 'auto'},
  1856. pdf: {width: '100%', height: '160px'},
  1857. other: {width: '100%', height: '160px'}
  1858. },
  1859. previewZoomSettings: {
  1860. image: {width: 'auto', height: 'auto', 'max-width': '100%', 'max-height': '100%'},
  1861. html: vDefaultDim,
  1862. text: vDefaultDim,
  1863. office: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1864. gdocs: {width: '100%', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1865. video: {width: 'auto', height: '100%', 'max-width': '100%'},
  1866. audio: {width: '100%', height: '30px'},
  1867. flash: {width: 'auto', height: '480px'},
  1868. object: {width: 'auto', height: '100%', 'max-width': '100%', 'min-height': '480px'},
  1869. pdf: vDefaultDim,
  1870. other: {width: 'auto', height: '100%', 'min-height': '480px'}
  1871. },
  1872. mimeTypeAliases: {
  1873. 'video/quicktime': 'video/mp4'
  1874. },
  1875. fileTypeSettings: {
  1876. image: function (vType, vName) {
  1877. return ($h.compare(vType, 'image.*') && !$h.compare(vType, /(tiff?|wmf)$/i) ||
  1878. $h.compare(vName, /\.(gif|png|jpe?g)$/i));
  1879. },
  1880. html: function (vType, vName) {
  1881. return $h.compare(vType, 'text/html') || $h.compare(vName, /\.(htm|html)$/i);
  1882. },
  1883. office: function (vType, vName) {
  1884. return $h.compare(vType, /(word|excel|powerpoint|office)$/i) ||
  1885. $h.compare(vName, /\.(docx?|xlsx?|pptx?|pps|potx?)$/i);
  1886. },
  1887. gdocs: function (vType, vName) {
  1888. return $h.compare(vType, /(word|excel|powerpoint|office|iwork-pages|tiff?)$/i) ||
  1889. $h.compare(vName,
  1890. /\.(docx?|xlsx?|pptx?|pps|potx?|rtf|ods|odt|pages|ai|dxf|ttf|tiff?|wmf|e?ps)$/i);
  1891. },
  1892. text: function (vType, vName) {
  1893. return $h.compare(vType, 'text.*') || $h.compare(vName, /\.(xml|javascript)$/i) ||
  1894. $h.compare(vName, /\.(txt|md|nfo|ini|json|php|js|css)$/i);
  1895. },
  1896. video: function (vType, vName) {
  1897. return $h.compare(vType, 'video.*') && ($h.compare(vType, /(ogg|mp4|mp?g|mov|webm|3gp)$/i) ||
  1898. $h.compare(vName, /\.(og?|mp4|webm|mp?g|mov|3gp)$/i));
  1899. },
  1900. audio: function (vType, vName) {
  1901. return $h.compare(vType, 'audio.*') && ($h.compare(vName, /(ogg|mp3|mp?g|wav)$/i) ||
  1902. $h.compare(vName, /\.(og?|mp3|mp?g|wav)$/i));
  1903. },
  1904. flash: function (vType, vName) {
  1905. return $h.compare(vType, 'application/x-shockwave-flash', true) || $h.compare(vName,
  1906. /\.(swf)$/i);
  1907. },
  1908. pdf: function (vType, vName) {
  1909. return $h.compare(vType, 'application/pdf', true) || $h.compare(vName, /\.(pdf)$/i);
  1910. },
  1911. object: function () {
  1912. return true;
  1913. },
  1914. other: function () {
  1915. return true;
  1916. }
  1917. },
  1918. fileActionSettings: {
  1919. showRemove: true,
  1920. showUpload: true,
  1921. showDownload: true,
  1922. showZoom: true,
  1923. showDrag: true,
  1924. removeIcon: '<i class="bi-trash"></i>',
  1925. removeClass: defBtnCss1,
  1926. removeErrorClass: 'btn btn-sm btn-kv btn-danger',
  1927. removeTitle: 'Remove file',
  1928. uploadIcon: '<i class="bi-upload"></i>',
  1929. uploadClass: defBtnCss1,
  1930. uploadTitle: 'Upload file',
  1931. uploadRetryIcon: '<i class="bi-arrow-clockwise"></i>',
  1932. uploadRetryTitle: 'Retry upload',
  1933. downloadIcon: '<i class="bi-download"></i>',
  1934. downloadClass: defBtnCss1,
  1935. downloadTitle: 'Download file',
  1936. zoomIcon: '<i class="bi-zoom-in"></i>',
  1937. zoomClass: defBtnCss1,
  1938. zoomTitle: 'View Details',
  1939. dragIcon: '<i class="bi-arrows-move"></i>',
  1940. dragClass: 'text-primary',
  1941. dragTitle: 'Move / Rearrange',
  1942. dragSettings: {},
  1943. indicatorNew: '<i class="bi-plus-lg text-warning"></i>',
  1944. indicatorSuccess: '<i class="bi-check-lg text-success"></i>',
  1945. indicatorError: '<i class="bi-exclamation-lg text-danger"></i>',
  1946. indicatorLoading: '<i class="bi-hourglass-bottom text-muted"></i>',
  1947. indicatorPaused: '<i class="bi-pause-fill text-primary"></i>',
  1948. indicatorNewTitle: 'Not uploaded yet',
  1949. indicatorSuccessTitle: 'Uploaded',
  1950. indicatorErrorTitle: 'Upload Error',
  1951. indicatorLoadingTitle: 'Uploading &hellip;',
  1952. indicatorPausedTitle: 'Upload Paused'
  1953. }
  1954. };
  1955. $.each(self.defaults, function (key, setting) {
  1956. if (key === 'allowedPreviewTypes') {
  1957. if (self.allowedPreviewTypes === undefined) {
  1958. self.allowedPreviewTypes = setting;
  1959. }
  1960. return;
  1961. }
  1962. self[key] = $.extend(true, {}, setting, self[key]);
  1963. });
  1964. self._initPreviewTemplates();
  1965. },
  1966. _initPreviewTemplates: function () {
  1967. var self = this, tags = self.previewMarkupTags, tagBef, tagAft = tags.tagAfter;
  1968. $.each(self.previewContentTemplates, function (key, value) {
  1969. if ($h.isEmpty(self.previewTemplates[key])) {
  1970. tagBef = tags.tagBefore2;
  1971. if (key === 'generic' || key === 'image') {
  1972. tagBef = tags.tagBefore1;
  1973. }
  1974. if (self._isPdfRendered() && key === 'pdf') {
  1975. tagBef = tagBef.replace('kv-file-content', 'kv-file-content kv-pdf-rendered');
  1976. }
  1977. self.previewTemplates[key] = tagBef + value + tagAft;
  1978. }
  1979. });
  1980. },
  1981. _initPreviewCache: function () {
  1982. var self = this;
  1983. self.previewCache = {
  1984. data: {},
  1985. init: function () {
  1986. var content = self.initialPreview;
  1987. if (content.length > 0 && !$h.isArray(content)) {
  1988. content = content.split(self.initialPreviewDelimiter);
  1989. }
  1990. self.previewCache.data = {
  1991. content: content,
  1992. config: self.initialPreviewConfig,
  1993. tags: self.initialPreviewThumbTags
  1994. };
  1995. },
  1996. count: function (skipNull) {
  1997. if (!self.previewCache.data || !self.previewCache.data.content) {
  1998. return 0;
  1999. }
  2000. if (skipNull) {
  2001. var chk = self.previewCache.data.content.filter(function (n) {
  2002. return n !== null;
  2003. });
  2004. return chk.length;
  2005. }
  2006. return self.previewCache.data.content.length;
  2007. },
  2008. get: function (i, isDisabled) {
  2009. var ind = $h.INIT_FLAG + i, data = self.previewCache.data, config = data.config[i],
  2010. content = data.content[i], out, $tmp, cat, ftr,
  2011. fname, ftype, frameClass, asData = $h.ifSet('previewAsData', config, self.initialPreviewAsData),
  2012. a = config ? {title: config.title || null, alt: config.alt || null} : {title: null, alt: null},
  2013. parseTemplate = function (cat, dat, fname, ftype, ftr, ind, fclass, t) {
  2014. var fc = ' file-preview-initial ' + $h.SORT_CSS + (fclass ? ' ' + fclass : ''),
  2015. id = self.previewInitId + '-' + ind,
  2016. fileId = config && config.fileId || id;
  2017. /** @namespace config.zoomData */
  2018. return self._generatePreviewTemplate(cat, dat, fname, ftype, id, fileId, false, null, fc,
  2019. ftr, ind, t, a, config && config.zoomData || dat);
  2020. };
  2021. if (!content || !content.length) {
  2022. return '';
  2023. }
  2024. isDisabled = isDisabled === undefined ? true : isDisabled;
  2025. cat = $h.ifSet('type', config, self.initialPreviewFileType || 'generic');
  2026. fname = $h.ifSet('filename', config, $h.ifSet('caption', config));
  2027. ftype = $h.ifSet('filetype', config, cat);
  2028. ftr = self.previewCache.footer(i, isDisabled, (config && config.size || null));
  2029. frameClass = $h.ifSet('frameClass', config);
  2030. if (asData) {
  2031. out = parseTemplate(cat, content, fname, ftype, ftr, ind, frameClass);
  2032. } else {
  2033. out = parseTemplate('generic', content, fname, ftype, ftr, ind, frameClass, cat)
  2034. .setTokens({'content': data.content[i]});
  2035. }
  2036. if (data.tags.length && data.tags[i]) {
  2037. out = $h.replaceTags(out, data.tags[i]);
  2038. }
  2039. /** @namespace config.frameAttr */
  2040. if (!$h.isEmpty(config) && !$h.isEmpty(config.frameAttr)) {
  2041. $tmp = $h.createElement(out);
  2042. $tmp.find('.file-preview-initial').attr(config.frameAttr);
  2043. out = $tmp.html();
  2044. $tmp.remove();
  2045. }
  2046. return out;
  2047. },
  2048. clean: function (data) {
  2049. data.content = $h.cleanArray(data.content);
  2050. data.config = $h.cleanArray(data.config);
  2051. data.tags = $h.cleanArray(data.tags);
  2052. self.previewCache.data = data;
  2053. },
  2054. add: function (content, config, tags, append) {
  2055. var data = self.previewCache.data, index;
  2056. if (!content || !content.length) {
  2057. return 0;
  2058. }
  2059. index = content.length - 1;
  2060. if (!$h.isArray(content)) {
  2061. content = content.split(self.initialPreviewDelimiter);
  2062. }
  2063. if (append && data.content) {
  2064. index = data.content.push(content[0]) - 1;
  2065. data.config[index] = config;
  2066. data.tags[index] = tags;
  2067. } else {
  2068. data.content = content;
  2069. data.config = config;
  2070. data.tags = tags;
  2071. }
  2072. self.previewCache.clean(data);
  2073. return index;
  2074. },
  2075. set: function (content, config, tags, append) {
  2076. var data = self.previewCache.data, i, chk;
  2077. if (!content || !content.length) {
  2078. return;
  2079. }
  2080. if (!$h.isArray(content)) {
  2081. content = content.split(self.initialPreviewDelimiter);
  2082. }
  2083. chk = content.filter(function (n) {
  2084. return n !== null;
  2085. });
  2086. if (!chk.length) {
  2087. return;
  2088. }
  2089. if (data.content === undefined) {
  2090. data.content = [];
  2091. }
  2092. if (data.config === undefined) {
  2093. data.config = [];
  2094. }
  2095. if (data.tags === undefined) {
  2096. data.tags = [];
  2097. }
  2098. if (append) {
  2099. for (i = 0; i < content.length; i++) {
  2100. if (content[i]) {
  2101. data.content.push(content[i]);
  2102. }
  2103. }
  2104. for (i = 0; i < config.length; i++) {
  2105. if (config[i]) {
  2106. data.config.push(config[i]);
  2107. }
  2108. }
  2109. for (i = 0; i < tags.length; i++) {
  2110. if (tags[i]) {
  2111. data.tags.push(tags[i]);
  2112. }
  2113. }
  2114. } else {
  2115. data.content = content;
  2116. data.config = config;
  2117. data.tags = tags;
  2118. }
  2119. self.previewCache.clean(data);
  2120. },
  2121. unset: function (index) {
  2122. var chk = self.previewCache.count(), rev = self.reversePreviewOrder;
  2123. if (!chk) {
  2124. return;
  2125. }
  2126. if (chk === 1) {
  2127. self.previewCache.data.content = [];
  2128. self.previewCache.data.config = [];
  2129. self.previewCache.data.tags = [];
  2130. self.initialPreview = [];
  2131. self.initialPreviewConfig = [];
  2132. self.initialPreviewThumbTags = [];
  2133. return;
  2134. }
  2135. self.previewCache.data.content = $h.spliceArray(self.previewCache.data.content, index, rev);
  2136. self.previewCache.data.config = $h.spliceArray(self.previewCache.data.config, index, rev);
  2137. self.previewCache.data.tags = $h.spliceArray(self.previewCache.data.tags, index, rev);
  2138. var data = $.extend(true, {}, self.previewCache.data);
  2139. self.previewCache.clean(data);
  2140. },
  2141. out: function () {
  2142. var html = '', caption, len = self.previewCache.count(), i, content;
  2143. if (len === 0) {
  2144. return {content: '', caption: ''};
  2145. }
  2146. for (i = 0; i < len; i++) {
  2147. content = self.previewCache.get(i);
  2148. html = self.reversePreviewOrder ? (content + html) : (html + content);
  2149. }
  2150. caption = self._getMsgSelected(len);
  2151. return {content: html, caption: caption};
  2152. },
  2153. footer: function (i, isDisabled, size) {
  2154. var data = self.previewCache.data || {};
  2155. if ($h.isEmpty(data.content)) {
  2156. return '';
  2157. }
  2158. if ($h.isEmpty(data.config) || $h.isEmpty(data.config[i])) {
  2159. data.config[i] = {};
  2160. }
  2161. isDisabled = isDisabled === undefined ? true : isDisabled;
  2162. var config = data.config[i], caption = $h.ifSet('caption', config), a,
  2163. width = $h.ifSet('width', config, 'auto'), url = $h.ifSet('url', config, false),
  2164. key = $h.ifSet('key', config, null), fileId = $h.ifSet('fileId', config, null),
  2165. fs = self.fileActionSettings, initPreviewShowDel = self.initialPreviewShowDelete || false,
  2166. downloadInitialUrl = !self.initialPreviewDownloadUrl ? '' :
  2167. self.initialPreviewDownloadUrl + '?key=' + key + (fileId ? '&fileId=' + fileId : ''),
  2168. dUrl = config.downloadUrl || downloadInitialUrl,
  2169. dFil = config.filename || config.caption || '',
  2170. initPreviewShowDwl = !!(dUrl),
  2171. sDel = $h.ifSet('showRemove', config, initPreviewShowDel),
  2172. sDwl = $h.ifSet('showDownload', config, $h.ifSet('showDownload', fs, initPreviewShowDwl)),
  2173. sZm = $h.ifSet('showZoom', config, $h.ifSet('showZoom', fs, true)),
  2174. sDrg = $h.ifSet('showDrag', config, $h.ifSet('showDrag', fs, true)),
  2175. dis = (url === false) && isDisabled;
  2176. sDwl = sDwl && config.downloadUrl !== false && !!dUrl;
  2177. a = self._renderFileActions(config, false, sDwl, sDel, sZm, sDrg, dis, url, key, true, dUrl, dFil);
  2178. return self._getLayoutTemplate('footer').setTokens({
  2179. 'progress': self._renderThumbProgress(),
  2180. 'actions': a,
  2181. 'caption': caption,
  2182. 'size': self._getSize(size),
  2183. 'width': width,
  2184. 'indicator': ''
  2185. });
  2186. }
  2187. };
  2188. self.previewCache.init();
  2189. },
  2190. _isPdfRendered: function () {
  2191. var self = this, useLib = self.usePdfRenderer,
  2192. flag = typeof useLib === 'function' ? useLib() : !!useLib;
  2193. return flag && self.pdfRendererUrl;
  2194. },
  2195. _handler: function ($el, event, callback) {
  2196. var self = this, ns = self.namespace, ev = event.split(' ').join(ns + ' ') + ns;
  2197. if (!$el || !$el.length) {
  2198. return;
  2199. }
  2200. $el.off(ev).on(ev, callback);
  2201. },
  2202. _encodeURI: function (vUrl) {
  2203. var self = this;
  2204. return self.encodeUrl ? encodeURI(vUrl) : vUrl;
  2205. },
  2206. _log: function (msg, tokens) {
  2207. var self = this, id = self.$element.attr('id');
  2208. if (!self.showConsoleLogs) {
  2209. return;
  2210. }
  2211. if (id) {
  2212. msg = '"' + id + '": ' + msg;
  2213. }
  2214. msg = 'bootstrap-fileinput: ' + msg;
  2215. if (typeof tokens === 'object') {
  2216. msg = msg.setTokens(tokens);
  2217. }
  2218. if (window.console && typeof window.console.log !== 'undefined') {
  2219. window.console.log(msg);
  2220. } else {
  2221. window.alert(msg);
  2222. }
  2223. },
  2224. _validate: function () {
  2225. var self = this, status = self.$element.attr('type') === 'file';
  2226. if (!status) {
  2227. self._log($h.logMessages.badInputType);
  2228. }
  2229. return status;
  2230. },
  2231. _errorsExist: function () {
  2232. var self = this, $err, $errList = self.$errorContainer.find('li');
  2233. if ($errList.length) {
  2234. return true;
  2235. }
  2236. $err = $h.createElement(self.$errorContainer.html());
  2237. $err.find('.kv-error-close').remove();
  2238. $err.find('ul').remove();
  2239. return !!$.trim($err.text()).length;
  2240. },
  2241. _errorHandler: function (evt, caption) {
  2242. var self = this, err = evt.target.error, showError = function (msg) {
  2243. self._showError(msg.replace('{name}', caption));
  2244. };
  2245. /** @namespace err.NOT_FOUND_ERR */
  2246. /** @namespace err.SECURITY_ERR */
  2247. /** @namespace err.NOT_READABLE_ERR */
  2248. if (err.code === err.NOT_FOUND_ERR) {
  2249. showError(self.msgFileNotFound);
  2250. } else {
  2251. if (err.code === err.SECURITY_ERR) {
  2252. showError(self.msgFileSecured);
  2253. } else {
  2254. if (err.code === err.NOT_READABLE_ERR) {
  2255. showError(self.msgFileNotReadable);
  2256. } else {
  2257. if (err.code === err.ABORT_ERR) {
  2258. showError(self.msgFilePreviewAborted);
  2259. } else {
  2260. showError(self.msgFilePreviewError);
  2261. }
  2262. }
  2263. }
  2264. }
  2265. },
  2266. _addError: function (msg) {
  2267. var self = this, $error = self.$errorContainer;
  2268. if (msg && $error.length) {
  2269. $h.setHtml($error, self.errorCloseButton + msg);
  2270. self._handler($error.find('.kv-error-close'), 'click', function () {
  2271. setTimeout(function () {
  2272. if (self.showPreview && !self.getFrames().length) {
  2273. self.clear();
  2274. }
  2275. $error.fadeOut('slow');
  2276. }, self.processDelay);
  2277. });
  2278. }
  2279. },
  2280. _setValidationError: function (css) {
  2281. var self = this;
  2282. css = (css ? css + ' ' : '') + 'has-error';
  2283. self.$container.removeClass(css).addClass('has-error');
  2284. $h.addCss(self.$caption, 'is-invalid');
  2285. },
  2286. _resetErrors: function (fade) {
  2287. var self = this, $error = self.$errorContainer, history = self.resumableUploadOptions.retainErrorHistory;
  2288. if (self.isPersistentError || (self.enableResumableUpload && history)) {
  2289. return;
  2290. }
  2291. self.isError = false;
  2292. self.$container.removeClass('has-error');
  2293. self.$caption.removeClass('is-invalid is-valid file-processing');
  2294. $error.html('');
  2295. if (fade) {
  2296. $error.fadeOut('slow');
  2297. } else {
  2298. $error.hide();
  2299. }
  2300. },
  2301. _showFolderError: function (folders) {
  2302. var self = this, $error = self.$errorContainer, msg;
  2303. if (!folders) {
  2304. return;
  2305. }
  2306. if (!self.isAjaxUpload) {
  2307. self._clearFileInput();
  2308. }
  2309. msg = self.msgFoldersNotAllowed.replace('{n}', folders);
  2310. self._addError(msg);
  2311. self._setValidationError();
  2312. $error.fadeIn(self.fadeDelay);
  2313. self._raise('filefoldererror', [folders, msg]);
  2314. },
  2315. _showFileError: function (msg, params, event) {
  2316. var self = this, $error = self.$errorContainer, ev = event || 'fileuploaderror',
  2317. fId = params && params.fileId || '', e = params && params.id ?
  2318. '<li data-thumb-id="' + params.id + '" data-file-id="' + fId + '">' + msg + '</li>' : '<li>' + msg + '</li>';
  2319. if ($error.find('ul').length === 0) {
  2320. self._addError('<ul>' + e + '</ul>');
  2321. } else {
  2322. $error.find('ul').append(e);
  2323. }
  2324. $error.fadeIn(self.fadeDelay);
  2325. self._raise(ev, [params, msg]);
  2326. self._setValidationError('file-input-new');
  2327. return true;
  2328. },
  2329. _showError: function (msg, params, event) {
  2330. var self = this, $error = self.$errorContainer, ev = event || 'fileerror';
  2331. params = params || {};
  2332. params.reader = self.reader;
  2333. self._addError(msg);
  2334. $error.fadeIn(self.fadeDelay);
  2335. self._raise(ev, [params, msg]);
  2336. if (!self.isAjaxUpload) {
  2337. self._clearFileInput();
  2338. }
  2339. self._setValidationError('file-input-new');
  2340. self.$btnUpload.attr('disabled', true);
  2341. return true;
  2342. },
  2343. _noFilesError: function (params) {
  2344. var self = this, label = self.minFileCount > 1 ? self.filePlural : self.fileSingle,
  2345. msg = self.msgFilesTooLess.replace('{n}', self.minFileCount).replace('{files}', label),
  2346. $error = self.$errorContainer;
  2347. msg = '<li>' + msg + '</li>';
  2348. if ($error.find('ul').length === 0) {
  2349. self._addError('<ul>' + msg + '</ul>');
  2350. } else {
  2351. $error.find('ul').append(msg);
  2352. }
  2353. self.isError = true;
  2354. self._updateFileDetails(0);
  2355. $error.fadeIn(self.fadeDelay);
  2356. self._raise('fileerror', [params, msg]);
  2357. self._clearFileInput();
  2358. self._setValidationError();
  2359. },
  2360. _parseError: function (operation, jqXHR, errorThrown, fileName) {
  2361. /** @namespace jqXHR.responseJSON */
  2362. var self = this, errMsg = $.trim(errorThrown + ''), textPre, errText, text;
  2363. errText = jqXHR.responseJSON && jqXHR.responseJSON.error ? jqXHR.responseJSON.error.toString() : '';
  2364. text = errText ? errText : jqXHR.responseText;
  2365. if (self.cancelling && self.msgUploadAborted) {
  2366. errMsg = self.msgUploadAborted;
  2367. }
  2368. if (self.showAjaxErrorDetails && text) {
  2369. if (errText) {
  2370. errMsg = $.trim(errText + '');
  2371. } else {
  2372. text = $.trim(text.replace(/\n\s*\n/g, '\n'));
  2373. textPre = text.length ? '<pre>' + text + '</pre>' : '';
  2374. errMsg += errMsg ? textPre : text;
  2375. }
  2376. }
  2377. if (!errMsg) {
  2378. errMsg = self.msgAjaxError.replace('{operation}', operation);
  2379. }
  2380. self.cancelling = false;
  2381. return fileName ? '<b>' + fileName + ': </b>' + errMsg : errMsg;
  2382. },
  2383. _parseFileType: function (type, name) {
  2384. var self = this, isValid, vType, cat, i, types = self.allowedPreviewTypes || [];
  2385. if (type === 'application/text-plain') {
  2386. return 'text';
  2387. }
  2388. for (i = 0; i < types.length; i++) {
  2389. cat = types[i];
  2390. isValid = self.fileTypeSettings[cat];
  2391. vType = isValid(type, name) ? cat : '';
  2392. if (!$h.isEmpty(vType)) {
  2393. return vType;
  2394. }
  2395. }
  2396. return 'other';
  2397. },
  2398. _getPreviewIcon: function (fname) {
  2399. var self = this, ext, out = null;
  2400. if (fname && fname.indexOf('.') > -1) {
  2401. ext = fname.split('.').pop();
  2402. if (self.previewFileIconSettings) {
  2403. out = self.previewFileIconSettings[ext] || self.previewFileIconSettings[ext.toLowerCase()] || null;
  2404. }
  2405. if (self.previewFileExtSettings) {
  2406. $.each(self.previewFileExtSettings, function (key, func) {
  2407. if (self.previewFileIconSettings[key] && func(ext)) {
  2408. out = self.previewFileIconSettings[key];
  2409. //noinspection UnnecessaryReturnStatementJS
  2410. return;
  2411. }
  2412. });
  2413. }
  2414. }
  2415. return out || self.previewFileIcon;
  2416. },
  2417. _parseFilePreviewIcon: function (content, fname) {
  2418. var self = this, icn = self._getPreviewIcon(fname), out = content;
  2419. if (out.indexOf('{previewFileIcon}') > -1) {
  2420. out = out.setTokens({'previewFileIconClass': self.previewFileIconClass, 'previewFileIcon': icn});
  2421. }
  2422. return out;
  2423. },
  2424. _raise: function (event, params) {
  2425. var self = this, e = $.Event(event);
  2426. if (params !== undefined) {
  2427. self.$element.trigger(e, params);
  2428. } else {
  2429. self.$element.trigger(e);
  2430. }
  2431. var out = e.result, isAborted = out === false;
  2432. if (e.isDefaultPrevented() || isAborted) {
  2433. return false;
  2434. }
  2435. if (e.type === 'filebatchpreupload' && (out || isAborted)) {
  2436. self.ajaxAborted = out;
  2437. return false;
  2438. }
  2439. switch (event) {
  2440. // ignore these events
  2441. case 'filebatchuploadcomplete':
  2442. case 'filebatchuploadsuccess':
  2443. case 'fileuploaded':
  2444. case 'fileclear':
  2445. case 'filecleared':
  2446. case 'filereset':
  2447. case 'fileerror':
  2448. case 'filefoldererror':
  2449. case 'fileuploaderror':
  2450. case 'filebatchuploaderror':
  2451. case 'filedeleteerror':
  2452. case 'filecustomerror':
  2453. case 'filesuccessremove':
  2454. break;
  2455. // receive data response via `filecustomerror` event`
  2456. default:
  2457. if (!self.ajaxAborted) {
  2458. self.ajaxAborted = out;
  2459. }
  2460. break;
  2461. }
  2462. return true;
  2463. },
  2464. _listenFullScreen: function (isFullScreen) {
  2465. var self = this, $modal = self.$modal, $btnFull, $btnBord;
  2466. if (!$modal || !$modal.length) {
  2467. return;
  2468. }
  2469. $btnFull = $modal && $modal.find('.btn-kv-fullscreen');
  2470. $btnBord = $modal && $modal.find('.btn-kv-borderless');
  2471. if (!$btnFull.length || !$btnBord.length) {
  2472. return;
  2473. }
  2474. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2475. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2476. if (isFullScreen) {
  2477. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2478. } else {
  2479. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2480. }
  2481. if ($modal.hasClass('file-zoom-fullscreen')) {
  2482. self._maximizeZoomDialog();
  2483. } else {
  2484. if (isFullScreen) {
  2485. self._maximizeZoomDialog();
  2486. } else {
  2487. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2488. }
  2489. }
  2490. },
  2491. _listen: function () {
  2492. var self = this, $el = self.$element, $form = self.$form, $cont = self.$container, fullScreenEv;
  2493. self._handler($el, 'click', function (e) {
  2494. self._initFileSelected();
  2495. if ($el.hasClass('file-no-browse')) {
  2496. if ($el.data('zoneClicked')) {
  2497. $el.data('zoneClicked', false);
  2498. } else {
  2499. e.preventDefault();
  2500. }
  2501. }
  2502. });
  2503. self._handler($el, 'change', $.proxy(self._change, self));
  2504. self._handler(self.$caption, 'paste', $.proxy(self.paste, self));
  2505. if (self.showBrowse) {
  2506. self._handler(self.$btnFile, 'click', $.proxy(self._browse, self));
  2507. self._handler(self.$btnFile, 'keypress', function (e) {
  2508. var keycode = e.keyCode || e.which
  2509. if (keycode === 13) {
  2510. $el.trigger('click');
  2511. self._browse(e);
  2512. }
  2513. });
  2514. }
  2515. self._handler($cont.find('.fileinput-remove:not([disabled])'), 'click', $.proxy(self.clear, self));
  2516. self._handler($cont.find('.fileinput-cancel'), 'click', $.proxy(self.cancel, self));
  2517. self._handler($cont.find('.fileinput-pause'), 'click', $.proxy(self.pause, self));
  2518. self._initDragDrop();
  2519. self._handler($form, 'reset', $.proxy(self.clear, self));
  2520. if (!self.isAjaxUpload) {
  2521. self._handler($form, 'submit', $.proxy(self._submitForm, self));
  2522. }
  2523. self._handler(self.$container.find('.fileinput-upload'), 'click', $.proxy(self._uploadClick, self));
  2524. self._handler($(window), 'resize', function () {
  2525. self._listenFullScreen(screen.width === window.innerWidth && screen.height === window.innerHeight);
  2526. });
  2527. fullScreenEv = 'webkitfullscreenchange mozfullscreenchange fullscreenchange MSFullscreenChange';
  2528. self._handler($(document), fullScreenEv, function () {
  2529. self._listenFullScreen($h.checkFullScreen());
  2530. });
  2531. self.$caption.on('focus', function () {
  2532. self.$captionContainer.focus();
  2533. });
  2534. self._autoFitContent();
  2535. self._initClickable();
  2536. self._refreshPreview();
  2537. },
  2538. _autoFitContent: function () {
  2539. var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  2540. self = this, config = width < 400 ? (self.previewSettingsSmall || self.defaults.previewSettingsSmall) :
  2541. (self.previewSettings || self.defaults.previewSettings), sel;
  2542. $.each(config, function (cat, settings) {
  2543. sel = '.file-preview-frame .file-preview-' + cat;
  2544. self.$preview.find(sel + '.kv-preview-data,' + sel + ' .kv-preview-data').css(settings);
  2545. });
  2546. },
  2547. _scanDroppedItems: function (item, files, path) {
  2548. path = path || '';
  2549. var self = this, i, dirReader, readDir, errorHandler = function (e) {
  2550. self._log($h.logMessages.badDroppedFiles);
  2551. self._log(e);
  2552. };
  2553. if (item.isFile) {
  2554. item.file(function (file) {
  2555. if (path) {
  2556. file.newPath = path + file.name;
  2557. }
  2558. files.push(file);
  2559. }, errorHandler);
  2560. } else {
  2561. if (item.isDirectory) {
  2562. dirReader = item.createReader();
  2563. readDir = function () {
  2564. dirReader.readEntries(function (entries) {
  2565. if (entries && entries.length > 0) {
  2566. for (i = 0; i < entries.length; i++) {
  2567. self._scanDroppedItems(entries[i], files, path + item.name + '/');
  2568. }
  2569. // recursively call readDir() again, since browser can only handle first 100 entries.
  2570. readDir();
  2571. }
  2572. return null;
  2573. }, errorHandler);
  2574. };
  2575. readDir();
  2576. }
  2577. }
  2578. },
  2579. _initDragDrop: function () {
  2580. var self = this, $zone = self.$dropZone;
  2581. if (self.dropZoneEnabled && self.showPreview) {
  2582. self._handler($zone, 'dragenter dragover', $.proxy(self._zoneDragEnter, self));
  2583. self._handler($zone, 'dragleave', $.proxy(self._zoneDragLeave, self));
  2584. self._handler($zone, 'drop', $.proxy(self._zoneDrop, self));
  2585. self._handler($(document), 'dragenter dragover drop', self._zoneDragDropInit);
  2586. }
  2587. },
  2588. _zoneDragDropInit: function (e) {
  2589. e.stopPropagation();
  2590. e.preventDefault();
  2591. },
  2592. _zoneDragEnter: function (e) {
  2593. var self = this, dt = e.originalEvent.dataTransfer, hasFiles = $.inArray('Files', dt.types) > -1;
  2594. self._zoneDragDropInit(e);
  2595. if (self.isDisabled || !hasFiles) {
  2596. dt.effectAllowed = 'none';
  2597. dt.dropEffect = 'none';
  2598. return;
  2599. }
  2600. dt.dropEffect = 'copy';
  2601. if (self._raise('fileDragEnter', {'sourceEvent': e, 'files': dt.types.Files})) {
  2602. $h.addCss(self.$dropZone, 'file-highlighted');
  2603. }
  2604. },
  2605. _zoneDragLeave: function (e) {
  2606. var self = this;
  2607. self._zoneDragDropInit(e);
  2608. if (self.isDisabled) {
  2609. return;
  2610. }
  2611. if (self._raise('fileDragLeave', {'sourceEvent': e})) {
  2612. self.$dropZone.removeClass('file-highlighted');
  2613. }
  2614. },
  2615. _dropFiles: function (e, files) {
  2616. var self = this, $el = self.$element;
  2617. if (!self.isAjaxUpload) {
  2618. self.changeTriggered = true;
  2619. $el.get(0).files = files;
  2620. setTimeout(function () {
  2621. self.changeTriggered = false;
  2622. $el.trigger('change' + self.namespace);
  2623. }, self.processDelay);
  2624. } else {
  2625. self._change(e, files);
  2626. }
  2627. self.$dropZone.removeClass('file-highlighted');
  2628. },
  2629. _zoneDrop: function (e) {
  2630. /** @namespace e.originalEvent.dataTransfer */
  2631. var self = this, i, $el = self.$element, dt = e.originalEvent.dataTransfer,
  2632. files = dt.files, items = dt.items, folders = $h.getDragDropFolders(items);
  2633. e.preventDefault();
  2634. if (self.isDisabled || $h.isEmpty(files)) {
  2635. return;
  2636. }
  2637. if (!self._raise('fileDragDrop', {'sourceEvent': e, 'files': files})) {
  2638. return;
  2639. }
  2640. if (folders > 0) {
  2641. if (!self.isAjaxUpload) {
  2642. self._showFolderError(folders);
  2643. return;
  2644. }
  2645. files = [];
  2646. for (i = 0; i < items.length; i++) {
  2647. var item = items[i].webkitGetAsEntry();
  2648. if (item) {
  2649. self._scanDroppedItems(item, files);
  2650. }
  2651. }
  2652. setTimeout(function () {
  2653. self._dropFiles(e, files);
  2654. }, 500);
  2655. } else {
  2656. self._dropFiles(e, files);
  2657. }
  2658. },
  2659. _uploadClick: function (e) {
  2660. var self = this, $btn = self.$container.find('.fileinput-upload'), $form,
  2661. isEnabled = !$btn.hasClass('disabled') && $h.isEmpty($btn.attr('disabled'));
  2662. if (e && e.isDefaultPrevented()) {
  2663. return;
  2664. }
  2665. if (!self.isAjaxUpload) {
  2666. if (isEnabled && $btn.attr('type') !== 'submit') {
  2667. $form = $btn.closest('form');
  2668. // downgrade to normal form submit if possible
  2669. if ($form.length) {
  2670. $form.trigger('submit');
  2671. }
  2672. e.preventDefault();
  2673. }
  2674. return;
  2675. }
  2676. e.preventDefault();
  2677. if (isEnabled) {
  2678. self.upload();
  2679. }
  2680. },
  2681. _submitForm: function () {
  2682. var self = this;
  2683. return self._isFileSelectionValid() && !self._abort({});
  2684. },
  2685. _clearPreview: function () {
  2686. var self = this,
  2687. $thumbs = self.showUploadedThumbs ? self.getFrames(':not(.file-preview-success)') : self.getFrames();
  2688. $thumbs.each(function () {
  2689. var $thumb = $(this);
  2690. $thumb.remove();
  2691. });
  2692. if (!self.getFrames().length || !self.showPreview) {
  2693. self._resetUpload();
  2694. }
  2695. self._validateDefaultPreview();
  2696. },
  2697. _initSortable: function () {
  2698. var self = this, $el = self.$preview, settings, selector = '.' + $h.SORT_CSS, $cont, $body = $('body'),
  2699. $html = $('html'), rev = self.reversePreviewOrder, Sortable = window.Sortable, beginGrab, endGrab;
  2700. if (!Sortable || $el.find(selector).length === 0) {
  2701. return;
  2702. }
  2703. $cont = $body.length ? $body : ($html.length ? $html : self.$container);
  2704. beginGrab = function () {
  2705. $cont.addClass('file-grabbing');
  2706. };
  2707. endGrab = function () {
  2708. $cont.removeClass('file-grabbing');
  2709. };
  2710. settings = {
  2711. handle: '.drag-handle-init',
  2712. dataIdAttr: 'data-fileid',
  2713. animation: 600,
  2714. draggable: selector,
  2715. scroll: false,
  2716. forceFallback: true,
  2717. onChoose: beginGrab,
  2718. onStart: beginGrab,
  2719. onUnchoose: endGrab,
  2720. onEnd: endGrab,
  2721. onSort: function (e) {
  2722. var oldIndex = e.oldIndex, newIndex = e.newIndex, i = 0, len = self.initialPreviewConfig.length,
  2723. exceedsLast = len > 0 && newIndex >= len, $item = $(e.item), $first;
  2724. if (exceedsLast) {
  2725. newIndex = len - 1;
  2726. }
  2727. self.initialPreview = $h.moveArray(self.initialPreview, oldIndex, newIndex, rev);
  2728. self.initialPreviewConfig = $h.moveArray(self.initialPreviewConfig, oldIndex, newIndex, rev);
  2729. self.previewCache.init();
  2730. self.getFrames('.file-preview-initial').each(function () {
  2731. $(this).attr('data-fileindex', $h.INIT_FLAG + i);
  2732. i++;
  2733. });
  2734. if (exceedsLast) {
  2735. $first = self.getFrames(':not(.file-preview-initial):first');
  2736. if ($first.length) {
  2737. $item.slideUp(function () {
  2738. $item.insertBefore($first).slideDown();
  2739. });
  2740. }
  2741. }
  2742. self._raise('filesorted', {
  2743. previewId: $item.attr('id'),
  2744. 'oldIndex': oldIndex,
  2745. 'newIndex': newIndex,
  2746. stack: self.initialPreviewConfig
  2747. });
  2748. },
  2749. };
  2750. $.extend(true, settings, self.fileActionSettings.dragSettings);
  2751. if (self.sortable) {
  2752. self.sortable.destroy();
  2753. }
  2754. self.sortable = Sortable.create($el[0], settings);
  2755. },
  2756. _setPreviewContent: function (content) {
  2757. var self = this;
  2758. $h.setHtml(self.$preview, content);
  2759. self._autoFitContent();
  2760. },
  2761. _initPreviewImageOrientations: function () {
  2762. var self = this, i = 0, canOrientImage = self.canOrientImage;
  2763. if (!self.autoOrientImageInitial && !canOrientImage) {
  2764. return;
  2765. }
  2766. self.getFrames('.file-preview-initial').each(function () {
  2767. var $thumb = $(this), $img, $zoomImg, id, config = self.initialPreviewConfig[i];
  2768. /** @namespace config.exif */
  2769. if (config && config.exif && config.exif.Orientation) {
  2770. id = $thumb.attr('id');
  2771. $img = $thumb.find('>.kv-file-content img');
  2772. $zoomImg = self._getZoom(id, ' >.kv-file-content img');
  2773. if (canOrientImage) {
  2774. $img.css('image-orientation', (self.autoOrientImageInitial ? 'from-image' : 'none'));
  2775. } else {
  2776. self.setImageOrientation($img, $zoomImg, config.exif.Orientation, $thumb);
  2777. }
  2778. }
  2779. i++;
  2780. });
  2781. },
  2782. _initPreview: function (isInit) {
  2783. var self = this, cap = self.initialCaption || '', out;
  2784. if (!self.previewCache.count(true)) {
  2785. self._clearPreview();
  2786. if (isInit) {
  2787. self._setCaption(cap);
  2788. } else {
  2789. self._initCaption();
  2790. }
  2791. return;
  2792. }
  2793. out = self.previewCache.out();
  2794. cap = isInit && self.initialCaption ? self.initialCaption : out.caption;
  2795. self._setPreviewContent(out.content);
  2796. self._setInitThumbAttr();
  2797. self._setCaption(cap);
  2798. self._initSortable();
  2799. if (!$h.isEmpty(out.content)) {
  2800. self.$container.removeClass('file-input-new');
  2801. }
  2802. self._initPreviewImageOrientations();
  2803. },
  2804. _getZoomButton: function (type) {
  2805. var self = this, label = self.previewZoomButtonIcons[type], css = self.previewZoomButtonClasses[type],
  2806. title = ' title="' + (self.previewZoomButtonTitles[type] || '') + '" ', tag = $h.isBs(5) ? 'bs-' : '',
  2807. params = title + (type === 'close' ? ' data-' + tag + 'dismiss="modal" aria-hidden="true"' : '');
  2808. if (type === 'fullscreen' || type === 'borderless' || type === 'toggleheader') {
  2809. params += ' data-toggle="button" aria-pressed="false" autocomplete="off"';
  2810. }
  2811. return '<button type="button" class="' + css + ' btn-kv-' + type + '"' + params + '>' + label + '</button>';
  2812. },
  2813. _getModalContent: function () {
  2814. var self = this;
  2815. return self._getLayoutTemplate('modal').setTokens({
  2816. 'rtl': self.rtl ? ' kv-rtl' : '',
  2817. 'zoomFrameClass': self.frameClass,
  2818. 'heading': self.msgZoomModalHeading,
  2819. 'prev': self._getZoomButton('prev'),
  2820. 'next': self._getZoomButton('next'),
  2821. 'toggleheader': self._getZoomButton('toggleheader'),
  2822. 'fullscreen': self._getZoomButton('fullscreen'),
  2823. 'borderless': self._getZoomButton('borderless'),
  2824. 'close': self._getZoomButton('close')
  2825. });
  2826. },
  2827. _listenModalEvent: function (event) {
  2828. var self = this, $modal = self.$modal, getParams = function (e) {
  2829. return {
  2830. sourceEvent: e,
  2831. previewId: $modal.data('previewId'),
  2832. modal: $modal
  2833. };
  2834. };
  2835. $modal.on(event + '.bs.modal', function (e) {
  2836. if (e.namespace !== 'bs.modal') {
  2837. return;
  2838. }
  2839. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  2840. if ($modal.data('fileinputPluginId') === self.$element.attr('id')) {
  2841. self._raise('filezoom' + event, getParams(e));
  2842. }
  2843. if (event === 'shown') {
  2844. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2845. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2846. if ($modal.hasClass('file-zoom-fullscreen')) {
  2847. self._maximizeZoomDialog();
  2848. if ($h.checkFullScreen()) {
  2849. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2850. } else {
  2851. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2852. }
  2853. }
  2854. }
  2855. });
  2856. },
  2857. _initZoom: function () {
  2858. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  2859. modalMain = self._setTabIndex('modal', modalMain);
  2860. if (!self.showPreview) {
  2861. return;
  2862. }
  2863. self.$modal = $(modalId);
  2864. if (!self.$modal || !self.$modal.length) {
  2865. $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container);
  2866. self.$modal = $(modalId).insertBefore($dialog);
  2867. $h.cspBuffer.apply(self.$modal);
  2868. $dialog.remove();
  2869. }
  2870. $h.initModal(self.$modal);
  2871. self.$modal.html($h.cspBuffer.stash(self._getModalContent()));
  2872. $h.cspBuffer.apply(self.$modal);
  2873. $.each($h.MODAL_EVENTS, function (key, event) {
  2874. self._listenModalEvent(event);
  2875. });
  2876. },
  2877. _initZoomButtons: function () {
  2878. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  2879. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-kv-prev'),
  2880. $next = self.$modal.find('.btn-kv-next');
  2881. if (thumbs.length < 2) {
  2882. $prev.hide();
  2883. $next.hide();
  2884. return;
  2885. } else {
  2886. $prev.show();
  2887. $next.show();
  2888. }
  2889. if (!len) {
  2890. return;
  2891. }
  2892. $first = $(thumbs[0]);
  2893. $last = $(thumbs[len - 1]);
  2894. $prev.removeAttr('disabled');
  2895. $next.removeAttr('disabled');
  2896. if (self.reversePreviewOrder) {
  2897. [$prev, $next] = [$next, $prev]; // swap
  2898. }
  2899. if ($first.length && $first.attr('id') === previewId) {
  2900. $prev.attr('disabled', true);
  2901. }
  2902. if ($last.length && $last.attr('id') === previewId) {
  2903. $next.attr('disabled', true);
  2904. }
  2905. },
  2906. _maximizeZoomDialog: function () {
  2907. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  2908. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  2909. h = $(window).height(), diff = 0;
  2910. $modal.addClass('file-zoom-fullscreen');
  2911. if ($head && $head.length) {
  2912. h -= $head.outerHeight(true);
  2913. }
  2914. if ($foot && $foot.length) {
  2915. h -= $foot.outerHeight(true);
  2916. }
  2917. if ($body && $body.length) {
  2918. diff = $body.outerHeight(true) - $body.height();
  2919. h -= diff;
  2920. }
  2921. $modal.find('.kv-zoom-body').height(h);
  2922. },
  2923. _resizeZoomDialog: function (fullScreen) {
  2924. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-kv-fullscreen'),
  2925. $btnBord = $modal.find('.btn-kv-borderless');
  2926. if ($modal.hasClass('file-zoom-fullscreen')) {
  2927. $h.toggleFullScreen(false);
  2928. if (!fullScreen) {
  2929. if (!$btnFull.hasClass('active')) {
  2930. $modal.removeClass('file-zoom-fullscreen');
  2931. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  2932. } else {
  2933. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2934. }
  2935. } else {
  2936. if (!$btnFull.hasClass('active')) {
  2937. $modal.removeClass('file-zoom-fullscreen');
  2938. self._resizeZoomDialog(true);
  2939. if ($btnBord.hasClass('active')) {
  2940. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2941. }
  2942. }
  2943. }
  2944. } else {
  2945. if (!fullScreen) {
  2946. self._maximizeZoomDialog();
  2947. return;
  2948. }
  2949. $h.toggleFullScreen(true);
  2950. }
  2951. $modal.focus();
  2952. },
  2953. _setZoomContent: function ($frame, navigate) {
  2954. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
  2955. $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp,
  2956. $btnFull = $modal.find('.btn-kv-fullscreen'), $btnBord = $modal.find('.btn-kv-borderless'), cap, size,
  2957. $btnTogh = $modal.find('.btn-kv-toggleheader'), dir = navigate === 'prev' ? 'Left' : 'Right',
  2958. slideIn = 'slideIn' + dir, slideOut = 'slideOut' + dir, parsed, zoomData = $frame.data('zoom');
  2959. if (zoomData) {
  2960. zoomData = decodeURIComponent(zoomData);
  2961. parsed = $zoomPreview.html().setTokens({zoomData: zoomData});
  2962. $zoomPreview.html(parsed);
  2963. $frame.data('zoom', '');
  2964. $zoomPreview.attr('data-zoom', zoomData);
  2965. }
  2966. tmplt = $zoomPreview.attr('data-template') || 'generic';
  2967. $content = $zoomPreview.find('.kv-file-content');
  2968. body = $content.length ? '<span class="kv-spacer"></span>\n' + $content.html() : '';
  2969. cap = $frame.data('caption') || '';
  2970. size = $frame.data('size') || '';
  2971. title = cap + ' ' + size;
  2972. $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
  2973. $body = $modal.find('.kv-zoom-body');
  2974. $modal.removeClass('kv-single-content');
  2975. if (navigate) {
  2976. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  2977. $h.setHtml($body, body).hide();
  2978. $tmp.fadeOut('fast', function () {
  2979. $body.fadeIn('fast', function () {
  2980. $body.removeClass('file-thumb-loading');
  2981. });
  2982. $tmp.remove();
  2983. });
  2984. } else {
  2985. $h.setHtml($body, body);
  2986. }
  2987. config = self.previewZoomSettings[tmplt];
  2988. if (config) {
  2989. $dataEl = $body.find('.kv-preview-data');
  2990. $h.addCss($dataEl, 'file-zoom-detail');
  2991. $.each(config, function (key, value) {
  2992. $dataEl.css(key, value);
  2993. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  2994. $dataEl.removeAttr(key);
  2995. }
  2996. });
  2997. }
  2998. $modal.data('previewId', previewId);
  2999. self._handler($modal.find('.btn-kv-prev'), 'click', function () {
  3000. self._zoomSlideShow('prev', previewId);
  3001. });
  3002. self._handler($modal.find('.btn-kv-next'), 'click', function () {
  3003. self._zoomSlideShow('next', previewId);
  3004. });
  3005. self._handler($btnFull, 'click', function () {
  3006. self._resizeZoomDialog(true);
  3007. });
  3008. self._handler($btnBord, 'click', function () {
  3009. self._resizeZoomDialog(false);
  3010. });
  3011. self._handler($btnTogh, 'click', function () {
  3012. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  3013. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  3014. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  3015. if ($modal.hasClass('file-zoom-fullscreen')) {
  3016. h = $body.outerHeight(true);
  3017. if (!height) {
  3018. h = h - $header.outerHeight(true);
  3019. }
  3020. }
  3021. $body.css('height', height ? h + height : h);
  3022. };
  3023. if ($header.is(':visible')) {
  3024. ht = $header.outerHeight(true);
  3025. $header.slideUp('slow', function () {
  3026. $actions.find('.btn').appendTo($floatBar);
  3027. resize(ht);
  3028. });
  3029. } else {
  3030. $floatBar.find('.btn').appendTo($actions);
  3031. $header.slideDown('slow', function () {
  3032. resize();
  3033. });
  3034. }
  3035. $modal.focus();
  3036. });
  3037. self._handler($modal, 'keydown', function (e) {
  3038. var key = e.which || e.keyCode, delay = self.processDelay + 1, $prev = $(this).find('.btn-kv-prev'),
  3039. $next = $(this).find('.btn-kv-next'), vId = $(this).data('previewId'), vPrevKey, vNextKey;
  3040. [vPrevKey, vNextKey] = self.rtl ? [39, 37] : [37, 39];
  3041. $.each({prev: [$prev, vPrevKey], next: [$next, vNextKey]}, function (direction, config) {
  3042. var $btn = config[0], vKey = config[1];
  3043. if (key === vKey && $btn.length) {
  3044. $modal.focus();
  3045. if (!$btn.attr('disabled')) {
  3046. $btn.focus();
  3047. self._zoomSlideShow(direction, vId);
  3048. setTimeout(function () {
  3049. if ($btn.attr('disabled')) {
  3050. $modal.focus();
  3051. }
  3052. }, delay);
  3053. }
  3054. }
  3055. });
  3056. });
  3057. },
  3058. _showModal: function ($frame) {
  3059. var self = this, $modal = self.$modal, bs5Modal;
  3060. if (!$frame || !$frame.length) {
  3061. return;
  3062. }
  3063. $h.initModal($modal);
  3064. $h.setHtml($modal, self._getModalContent());
  3065. self._setZoomContent($frame);
  3066. $modal.data({backdrop: false});
  3067. //$modal.data('fileinputPluginId', self.$element.attr('id'));
  3068. $modal.modal('show');
  3069. self._initZoomButtons();
  3070. },
  3071. _zoomPreview: function ($btn) {
  3072. var self = this, $frame;
  3073. if (!$btn.length) {
  3074. throw 'Cannot zoom to detailed preview!';
  3075. }
  3076. $frame = $btn.closest($h.FRAMES);
  3077. self._showModal($frame);
  3078. },
  3079. _zoomSlideShow: function (dir, previewId) {
  3080. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-kv-' + dir), $targFrame, i, $thumb,
  3081. thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out;
  3082. if (self.reversePreviewOrder) {
  3083. dir = dir === 'prev' ? 'next' : 'prev';
  3084. }
  3085. if ($btn.attr('disabled')) {
  3086. return;
  3087. }
  3088. for (i = 0; i < len; i++) {
  3089. $thumb = $(thumbsData[i]);
  3090. if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) {
  3091. thumbs.push(thumbsData[i]);
  3092. }
  3093. }
  3094. len = thumbs.length;
  3095. for (i = 0; i < len; i++) {
  3096. if ($(thumbs[i]).attr('id') === previewId) {
  3097. out = dir === 'prev' ? i - 1 : i + 1;
  3098. break;
  3099. }
  3100. }
  3101. if (out < 0 || out >= len || !thumbs[out]) {
  3102. return;
  3103. }
  3104. $targFrame = $(thumbs[out]);
  3105. if ($targFrame.length) {
  3106. self._setZoomContent($targFrame, dir);
  3107. }
  3108. self._initZoomButtons();
  3109. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  3110. },
  3111. _initZoomButton: function () {
  3112. var self = this;
  3113. self.$preview.find('.kv-file-zoom').each(function () {
  3114. var $el = $(this);
  3115. self._handler($el, 'click', function () {
  3116. self._zoomPreview($el);
  3117. });
  3118. });
  3119. },
  3120. _inputFileCount: function () {
  3121. return this.$element[0].files.length;
  3122. },
  3123. _refreshPreview: function () {
  3124. var self = this, files;
  3125. if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
  3126. return;
  3127. }
  3128. if (self.isAjaxUpload) {
  3129. if (self.fileManager.count() > 0) {
  3130. files = $.extend(true, {}, self.getFileList());
  3131. self.fileManager.clear();
  3132. self._clearFileInput();
  3133. } else {
  3134. files = self.$element[0].files;
  3135. }
  3136. } else {
  3137. files = self.$element[0].files;
  3138. }
  3139. if (files && files.length) {
  3140. self.readFiles(files);
  3141. self._setFileDropZoneTitle();
  3142. }
  3143. },
  3144. _clearObjects: function ($el) {
  3145. $el.find('video audio').each(function () {
  3146. this.pause();
  3147. $(this).remove();
  3148. });
  3149. $el.find('img object div').each(function () {
  3150. $(this).remove();
  3151. });
  3152. },
  3153. _clearFileInput: function () {
  3154. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  3155. if (!self._inputFileCount()) {
  3156. return;
  3157. }
  3158. $srcFrm = $el.closest('form');
  3159. $tmpFrm = $(document.createElement('form'));
  3160. $tmpEl = $(document.createElement('div'));
  3161. $el.before($tmpEl);
  3162. if ($srcFrm.length) {
  3163. $srcFrm.after($tmpFrm);
  3164. } else {
  3165. $tmpEl.after($tmpFrm);
  3166. }
  3167. $tmpFrm.append($el).trigger('reset');
  3168. $tmpEl.before($el).remove();
  3169. $tmpFrm.remove();
  3170. },
  3171. _resetUpload: function () {
  3172. var self = this;
  3173. self.uploadStartTime = $h.now();
  3174. self.uploadCache = [];
  3175. self.$btnUpload.removeAttr('disabled');
  3176. self._setProgress(0);
  3177. self._hideProgress();
  3178. self._resetErrors(false);
  3179. self._initAjax();
  3180. self.fileManager.clearImages();
  3181. self._resetCanvas();
  3182. if (self.overwriteInitial) {
  3183. self.initialPreview = [];
  3184. self.initialPreviewConfig = [];
  3185. self.initialPreviewThumbTags = [];
  3186. self.previewCache.data = {
  3187. content: [],
  3188. config: [],
  3189. tags: []
  3190. };
  3191. }
  3192. },
  3193. _resetCanvas: function () {
  3194. var self = this;
  3195. if (self.imageCanvas && self.imageCanvasContext) {
  3196. self.imageCanvasContext.clearRect(0, 0, self.imageCanvas.width, self.imageCanvas.height);
  3197. }
  3198. },
  3199. _hasInitialPreview: function () {
  3200. var self = this;
  3201. return !self.overwriteInitial && self.previewCache.count(true);
  3202. },
  3203. _resetPreview: function () {
  3204. var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError,
  3205. includeProcessed = (hasSuc || hasErr) && self.isDuplicateError;
  3206. if (self.previewCache.count(true)) {
  3207. out = self.previewCache.out();
  3208. if (includeProcessed) {
  3209. $div = $h.createElement('').insertAfter(self.$container);
  3210. self.getFrames().each(function () {
  3211. var $thumb = $(this);
  3212. if ((hasSuc && $thumb.hasClass('file-preview-success')) ||
  3213. (hasErr && $thumb.hasClass('file-preview-error'))) {
  3214. $div.append($thumb);
  3215. }
  3216. });
  3217. }
  3218. self._setPreviewContent(out.content);
  3219. self._setInitThumbAttr();
  3220. cap = self.initialCaption ? self.initialCaption : out.caption;
  3221. self._setCaption(cap);
  3222. if (includeProcessed) {
  3223. $div.contents().appendTo(self.$preview);
  3224. $div.remove();
  3225. }
  3226. } else {
  3227. self._clearPreview();
  3228. self._initCaption();
  3229. }
  3230. if (self.showPreview) {
  3231. self._initZoom();
  3232. self._initSortable();
  3233. }
  3234. self.isDuplicateError = false;
  3235. },
  3236. _clearDefaultPreview: function () {
  3237. var self = this;
  3238. self.$preview.find('.file-default-preview').remove();
  3239. },
  3240. _validateDefaultPreview: function () {
  3241. var self = this;
  3242. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  3243. return;
  3244. }
  3245. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  3246. self.$container.removeClass('file-input-new');
  3247. self._initClickable();
  3248. },
  3249. _resetPreviewThumbs: function (isAjax) {
  3250. var self = this, out;
  3251. if (isAjax) {
  3252. self._clearPreview();
  3253. self.clearFileStack();
  3254. return;
  3255. }
  3256. if (self._hasInitialPreview()) {
  3257. out = self.previewCache.out();
  3258. self._setPreviewContent(out.content);
  3259. self._setInitThumbAttr();
  3260. self._setCaption(out.caption);
  3261. self._initPreviewActions();
  3262. } else {
  3263. self._clearPreview();
  3264. }
  3265. },
  3266. _getLayoutTemplate: function (t) {
  3267. var self = this, template = self.layoutTemplates[t];
  3268. if ($h.isEmpty(self.customLayoutTags)) {
  3269. return template;
  3270. }
  3271. return $h.replaceTags(template, self.customLayoutTags);
  3272. },
  3273. _getPreviewTemplate: function (t) {
  3274. var self = this, templates = self.previewTemplates, template = templates[t] || templates.other;
  3275. if ($h.isEmpty(self.customPreviewTags)) {
  3276. return template;
  3277. }
  3278. return $h.replaceTags(template, self.customPreviewTags);
  3279. },
  3280. _getOutData: function (formdata, jqXHR, responseData, filesData) {
  3281. var self = this;
  3282. jqXHR = jqXHR || {};
  3283. responseData = responseData || {};
  3284. filesData = filesData || self.fileManager.list();
  3285. return {
  3286. formdata: formdata,
  3287. files: filesData,
  3288. filenames: self.filenames,
  3289. filescount: self.getFilesCount(),
  3290. extra: self._getExtraData(),
  3291. response: responseData,
  3292. reader: self.reader,
  3293. jqXHR: jqXHR
  3294. };
  3295. },
  3296. _getMsgSelected: function (n, processing) {
  3297. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  3298. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) :
  3299. (processing ? self.msgProcessing : self.msgNoFilesSelected);
  3300. },
  3301. _getFrame: function (id, skipWarning) {
  3302. var self = this, $frame = $h.getFrameElement(self.$preview, id);
  3303. if (self.showPreview && !skipWarning && !$frame.length) {
  3304. self._log($h.logMessages.invalidThumb, {id: id});
  3305. }
  3306. return $frame;
  3307. },
  3308. _getZoom: function (id, selector) {
  3309. var self = this, $frame = $h.getZoomElement(self.$preview, id, selector);
  3310. if (self.showPreview && !$frame.length) {
  3311. self._log($h.logMessages.invalidThumb, {id: id});
  3312. }
  3313. return $frame;
  3314. },
  3315. _getThumbs: function (css) {
  3316. css = css || '';
  3317. return this.getFrames(':not(.file-preview-initial)' + css);
  3318. },
  3319. _getThumbId: function (fileId) {
  3320. var self = this;
  3321. return self.previewInitId + '-' + fileId;
  3322. },
  3323. _getExtraData: function (fileId, index) {
  3324. var self = this, data = self.uploadExtraData;
  3325. if (typeof self.uploadExtraData === 'function') {
  3326. data = self.uploadExtraData(fileId, index);
  3327. }
  3328. return data;
  3329. },
  3330. _initXhr: function (xhrobj, fileId) {
  3331. var self = this, fm = self.fileManager, func = function (event) {
  3332. var pct = 0, total = event.total, loaded = event.loaded || event.position,
  3333. stats = fm.getUploadStats(fileId, loaded, total);
  3334. /** @namespace event.lengthComputable */
  3335. if (event.lengthComputable && !self.enableResumableUpload) {
  3336. pct = $h.round(loaded / total * 100);
  3337. }
  3338. if (fileId) {
  3339. self._setFileUploadStats(fileId, pct, stats);
  3340. } else {
  3341. self._setProgress(pct, null, null, self._getStats(stats));
  3342. }
  3343. self._raise('fileajaxprogress', [stats]);
  3344. };
  3345. if (xhrobj.upload) {
  3346. if (self.progressDelay) {
  3347. func = $h.debounce(func, self.progressDelay);
  3348. }
  3349. xhrobj.upload.addEventListener('progress', func, false);
  3350. }
  3351. return xhrobj;
  3352. },
  3353. _initAjaxSettings: function () {
  3354. var self = this;
  3355. self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
  3356. self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
  3357. },
  3358. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  3359. var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  3360. if (type === 'delete') {
  3361. settings = self._ajaxDeleteSettings;
  3362. flag = self.mergeAjaxDeleteCallbacks;
  3363. }
  3364. targFunc = settings[funcName];
  3365. if (flag && typeof targFunc === 'function') {
  3366. if (flag === 'before') {
  3367. settings[funcName] = function () {
  3368. targFunc.apply(this, arguments);
  3369. srcFunc.apply(this, arguments);
  3370. };
  3371. } else {
  3372. settings[funcName] = function () {
  3373. srcFunc.apply(this, arguments);
  3374. targFunc.apply(this, arguments);
  3375. };
  3376. }
  3377. } else {
  3378. settings[funcName] = srcFunc;
  3379. }
  3380. },
  3381. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) {
  3382. var self = this, settings, defaults, data, ajaxTask;
  3383. if (!self._raise('filepreajax', [formdata, fileId, index])) {
  3384. return;
  3385. }
  3386. formdata.append('initialPreview', JSON.stringify(self.initialPreview));
  3387. formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig));
  3388. formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags));
  3389. self._initAjaxSettings();
  3390. self._mergeAjaxCallback('beforeSend', fnBefore);
  3391. self._mergeAjaxCallback('success', fnSuccess);
  3392. self._mergeAjaxCallback('complete', fnComplete);
  3393. self._mergeAjaxCallback('error', fnError);
  3394. vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl;
  3395. if (typeof vUrl === 'function') {
  3396. vUrl = vUrl();
  3397. }
  3398. data = self._getExtraData(fileId, index) || {};
  3399. if (typeof data === 'object') {
  3400. $.each(data, function (key, value) {
  3401. formdata.append(key, value);
  3402. });
  3403. }
  3404. defaults = {
  3405. xhr: function () {
  3406. var xhrobj = $.ajaxSettings.xhr();
  3407. return self._initXhr(xhrobj, fileId);
  3408. },
  3409. url: self._encodeURI(vUrl),
  3410. type: 'POST',
  3411. dataType: 'json',
  3412. data: formdata,
  3413. cache: false,
  3414. processData: false,
  3415. contentType: false
  3416. };
  3417. settings = $.extend(true, {}, defaults, self._ajaxSettings);
  3418. ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () {
  3419. var self = this.self, config, xhr;
  3420. config = self.ajaxQueue.shift();
  3421. xhr = $.ajax(config);
  3422. self.ajaxRequests.push(xhr);
  3423. });
  3424. self.ajaxQueue.push(settings);
  3425. ajaxTask.runWithContext({self: self});
  3426. },
  3427. _mergeArray: function (prop, content) {
  3428. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  3429. self[prop] = arr1.concat(arr2);
  3430. },
  3431. _initUploadSuccess: function (out, $thumb, allFiles) {
  3432. var self = this, append, data, index, $div, $newCache, content, config, tags, id, i;
  3433. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  3434. self._resetCaption();
  3435. return;
  3436. }
  3437. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  3438. self.hasInitData = true;
  3439. content = out.initialPreview || [];
  3440. config = out.initialPreviewConfig || [];
  3441. tags = out.initialPreviewThumbTags || [];
  3442. append = out.append === undefined || out.append;
  3443. if (content.length > 0 && !$h.isArray(content)) {
  3444. content = content.split(self.initialPreviewDelimiter);
  3445. }
  3446. if (content.length) {
  3447. self._mergeArray('initialPreview', content);
  3448. self._mergeArray('initialPreviewConfig', config);
  3449. self._mergeArray('initialPreviewThumbTags', tags);
  3450. }
  3451. if ($thumb !== undefined) {
  3452. if (!allFiles) {
  3453. index = self.previewCache.add(content[0], config[0], tags[0], append);
  3454. data = self.previewCache.get(index, false);
  3455. $div = $h.createElement(data).hide().appendTo($thumb);
  3456. $newCache = $div.find('.kv-zoom-cache');
  3457. if ($newCache && $newCache.length) {
  3458. $newCache.appendTo($thumb);
  3459. }
  3460. $thumb.fadeOut('slow', function () {
  3461. var $newThumb = $div.find('.file-preview-frame');
  3462. if ($newThumb && $newThumb.length) {
  3463. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  3464. }
  3465. self._initPreviewActions();
  3466. self._clearFileInput();
  3467. $thumb.remove();
  3468. $div.remove();
  3469. self._initSortable();
  3470. });
  3471. } else {
  3472. id = $thumb.attr('id');
  3473. i = self._getUploadCacheIndex(id);
  3474. if (i !== null) {
  3475. self.uploadCache[i] = {
  3476. id: id,
  3477. content: content[0],
  3478. config: config[0] || [],
  3479. tags: tags[0] || [],
  3480. append: append
  3481. };
  3482. }
  3483. }
  3484. } else {
  3485. self.previewCache.set(content, config, tags, append);
  3486. self._initPreview();
  3487. self._initPreviewActions();
  3488. }
  3489. }
  3490. self._resetCaption();
  3491. },
  3492. _getUploadCacheIndex: function (id) {
  3493. var self = this, i, len = self.uploadCache.length, config;
  3494. for (i = 0; i < len; i++) {
  3495. config = self.uploadCache[i];
  3496. if (config.id === id) {
  3497. return i;
  3498. }
  3499. }
  3500. return null;
  3501. },
  3502. _initSuccessThumbs: function () {
  3503. var self = this;
  3504. if (!self.showPreview) {
  3505. return;
  3506. }
  3507. setTimeout(function () {
  3508. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  3509. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  3510. $remove.removeAttr('disabled');
  3511. self._handler($remove, 'click', function () {
  3512. var id = $thumb.attr('id'),
  3513. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  3514. $h.cleanMemory($thumb);
  3515. if (out === false) {
  3516. return;
  3517. }
  3518. self.$caption.attr('title', '');
  3519. $thumb.fadeOut('slow', function () {
  3520. var fm = self.fileManager;
  3521. $thumb.remove();
  3522. if (!self.getFrames().length) {
  3523. self.reset();
  3524. }
  3525. });
  3526. });
  3527. });
  3528. }, self.processDelay);
  3529. },
  3530. _updateInitialPreview: function () {
  3531. var self = this, u = self.uploadCache;
  3532. if (self.showPreview) {
  3533. $.each(u, function (key, setting) {
  3534. self.previewCache.add(setting.content, setting.config, setting.tags, setting.append);
  3535. });
  3536. if (self.hasInitData) {
  3537. self._initPreview();
  3538. self._initPreviewActions();
  3539. }
  3540. }
  3541. },
  3542. _getThumbFileId: function ($thumb) {
  3543. var self = this;
  3544. if (self.showPreview && $thumb !== undefined) {
  3545. return $thumb.attr('data-fileid');
  3546. }
  3547. return null;
  3548. },
  3549. _getThumbFile: function ($thumb) {
  3550. var self = this, id = self._getThumbFileId($thumb);
  3551. return id ? self.fileManager.getFile(id) : null;
  3552. },
  3553. _uploadSingle: function (i, id, isBatch) {
  3554. var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData,
  3555. previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete,
  3556. hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore,
  3557. errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb,
  3558. fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id},
  3559. fileName = self.fileManager.getFileName(id, true);
  3560. if (self.enableResumableUpload) { // not enabled for resumable uploads
  3561. return;
  3562. }
  3563. if (self.showPreview) {
  3564. $thumb = fm.getThumb(id);
  3565. $prog = $thumb.find('.file-thumb-progress');
  3566. $btnUpload = $thumb.find('.kv-file-upload');
  3567. $btnDelete = $thumb.find('.kv-file-remove');
  3568. $prog.show();
  3569. }
  3570. if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) ||
  3571. self._abort(params)) {
  3572. return;
  3573. }
  3574. updateUploadLog = function () {
  3575. if (!uploadFailed) {
  3576. fm.removeFile(id);
  3577. } else {
  3578. fm.errors.push(id);
  3579. }
  3580. fm.setProcessed(id);
  3581. if (fm.isProcessed()) {
  3582. self.fileBatchCompleted = true;
  3583. chkComplete();
  3584. }
  3585. };
  3586. chkComplete = function () {
  3587. var $initThumbs;
  3588. if (!self.fileBatchCompleted) {
  3589. return;
  3590. }
  3591. setTimeout(function () {
  3592. var triggerReset = fm.count() === 0, errCount = fm.errors.length;
  3593. self._updateInitialPreview();
  3594. self.unlock(triggerReset);
  3595. if (triggerReset) {
  3596. self._clearFileInput();
  3597. }
  3598. $initThumbs = self.$preview.find('.file-preview-initial');
  3599. if (self.uploadAsync && $initThumbs.length) {
  3600. $h.addCss($initThumbs, $h.SORT_CSS);
  3601. self._initSortable();
  3602. }
  3603. self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]);
  3604. if (!self.retryErrorUploads || errCount === 0) {
  3605. fm.clear();
  3606. }
  3607. self._setProgress(101);
  3608. self.ajaxAborted = false;
  3609. }, self.processDelay);
  3610. };
  3611. fnBefore = function (jqXHR) {
  3612. outData = self._getOutData(formdata, jqXHR);
  3613. fm.initStats(id);
  3614. self.fileBatchCompleted = false;
  3615. if (!isBatch) {
  3616. self.ajaxAborted = false;
  3617. }
  3618. if (self.showPreview) {
  3619. if (!$thumb.hasClass('file-preview-success')) {
  3620. self._setThumbStatus($thumb, 'Loading');
  3621. $h.addCss($thumb, 'file-uploading');
  3622. }
  3623. $btnUpload.attr('disabled', true);
  3624. $btnDelete.attr('disabled', true);
  3625. }
  3626. if (!isBatch) {
  3627. self.lock();
  3628. }
  3629. if (fm.errors.indexOf(id) !== -1) {
  3630. delete fm.errors[id];
  3631. }
  3632. self._raise('filepreupload', [outData, previewId, i, self._getThumbFileId($thumb)]);
  3633. $.extend(true, params, outData);
  3634. if (self._abort(params)) {
  3635. jqXHR.abort();
  3636. if (!isBatch) {
  3637. self._setThumbStatus($thumb, 'New');
  3638. $thumb.removeClass('file-uploading');
  3639. $btnUpload.removeAttr('disabled');
  3640. $btnDelete.removeAttr('disabled');
  3641. }
  3642. self._setProgressCancelled();
  3643. }
  3644. };
  3645. fnSuccess = function (data, textStatus, jqXHR) {
  3646. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  3647. outData = self._getOutData(formdata, jqXHR, data);
  3648. $.extend(true, params, outData);
  3649. setTimeout(function () {
  3650. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3651. if (self.showPreview) {
  3652. self._setThumbStatus($thumb, 'Success');
  3653. $btnUpload.hide();
  3654. self._initUploadSuccess(data, $thumb, isBatch);
  3655. self._setProgress(101, $prog);
  3656. }
  3657. self._raise('fileuploaded', [outData, pid, i, self._getThumbFileId($thumb)]);
  3658. if (!isBatch) {
  3659. self.fileManager.remove($thumb);
  3660. } else {
  3661. updateUploadLog();
  3662. }
  3663. } else {
  3664. uploadFailed = true;
  3665. errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id));
  3666. self._showFileError(errMsg, params);
  3667. self._setPreviewError($thumb, true);
  3668. if (!self.retryErrorUploads) {
  3669. $btnUpload.hide();
  3670. }
  3671. if (isBatch) {
  3672. updateUploadLog();
  3673. }
  3674. self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'),
  3675. self.msgUploadError);
  3676. }
  3677. }, self.processDelay);
  3678. };
  3679. fnComplete = function () {
  3680. if (self.showPreview) {
  3681. $btnUpload.removeAttr('disabled');
  3682. $btnDelete.removeAttr('disabled');
  3683. $thumb.removeClass('file-uploading');
  3684. }
  3685. if (!isBatch) {
  3686. self.unlock(false);
  3687. self._clearFileInput();
  3688. } else {
  3689. chkComplete();
  3690. }
  3691. self._initSuccessThumbs();
  3692. };
  3693. fnError = function (jqXHR, textStatus, errorThrown) {
  3694. errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id));
  3695. uploadFailed = true;
  3696. setTimeout(function () {
  3697. var $prog;
  3698. if (isBatch) {
  3699. updateUploadLog();
  3700. }
  3701. self.fileManager.setProgress(id, 100);
  3702. self._setPreviewError($thumb, true);
  3703. if (!self.retryErrorUploads) {
  3704. $btnUpload.hide();
  3705. }
  3706. $.extend(true, params, self._getOutData(formdata, jqXHR));
  3707. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3708. $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : '';
  3709. self._setProgress(101, $prog, self.msgUploadError);
  3710. self._showFileError(errMsg, params);
  3711. }, self.processDelay);
  3712. };
  3713. self._setFileData(formdata, fileObj.file, fileName, id);
  3714. self._setUploadData(formdata, {fileId: id});
  3715. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i);
  3716. },
  3717. _setFileData: function (formdata, file, fileName, fileId) {
  3718. var self = this, preProcess = self.preProcessUpload;
  3719. if (preProcess && typeof preProcess === 'function') {
  3720. formdata.append(self.uploadFileAttr, preProcess(fileId, file));
  3721. } else {
  3722. formdata.append(self.uploadFileAttr, file, fileName);
  3723. }
  3724. },
  3725. _checkBatchPreupload: function (outData, jqXHR) {
  3726. var self = this, out = self._raise('filebatchpreupload', [outData]);
  3727. if (out) {
  3728. return true;
  3729. }
  3730. self._abort(outData);
  3731. if (jqXHR) {
  3732. jqXHR.abort();
  3733. }
  3734. self._getThumbs().each(function () {
  3735. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3736. $btnDelete = $thumb.find('.kv-file-remove');
  3737. if ($thumb.hasClass('file-preview-loading')) {
  3738. self._setThumbStatus($thumb, 'New');
  3739. $thumb.removeClass('file-uploading');
  3740. }
  3741. $btnUpload.removeAttr('disabled');
  3742. $btnDelete.removeAttr('disabled');
  3743. });
  3744. self._setProgressCancelled();
  3745. return false;
  3746. },
  3747. _uploadBatch: function () {
  3748. var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError,
  3749. fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg,
  3750. setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch;
  3751. if (total === 0 || !hasPostData || self._abort(params)) {
  3752. return;
  3753. }
  3754. setAllUploaded = function () {
  3755. self.fileManager.clear();
  3756. self._clearFileInput();
  3757. };
  3758. fnBefore = function (jqXHR) {
  3759. self.lock();
  3760. fm.initStats();
  3761. var outData = self._getOutData(formdata, jqXHR);
  3762. self.ajaxAborted = false;
  3763. if (self.showPreview) {
  3764. self._getThumbs().each(function () {
  3765. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3766. $btnDelete = $thumb.find('.kv-file-remove');
  3767. if (!$thumb.hasClass('file-preview-success')) {
  3768. self._setThumbStatus($thumb, 'Loading');
  3769. $h.addCss($thumb, 'file-uploading');
  3770. }
  3771. $btnUpload.attr('disabled', true);
  3772. $btnDelete.attr('disabled', true);
  3773. });
  3774. }
  3775. self._checkBatchPreupload(outData, jqXHR);
  3776. };
  3777. fnSuccess = function (data, textStatus, jqXHR) {
  3778. /** @namespace data.errorkeys */
  3779. var outData = self._getOutData(formdata, jqXHR, data), key = 0,
  3780. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  3781. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  3782. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3783. self._raise('filebatchuploadsuccess', [outData]);
  3784. setAllUploaded();
  3785. if (self.showPreview) {
  3786. $thumbs.each(function () {
  3787. var $thumb = $(this);
  3788. self._setThumbStatus($thumb, 'Success');
  3789. $thumb.removeClass('file-uploading');
  3790. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  3791. });
  3792. self._initUploadSuccess(data);
  3793. } else {
  3794. self.reset();
  3795. }
  3796. self._setProgress(101);
  3797. } else {
  3798. if (self.showPreview) {
  3799. $thumbs.each(function () {
  3800. var $thumb = $(this);
  3801. $thumb.removeClass('file-uploading');
  3802. $thumb.find('.kv-file-upload').removeAttr('disabled');
  3803. $thumb.find('.kv-file-remove').removeAttr('disabled');
  3804. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  3805. self._setPreviewError($thumb, true);
  3806. if (!self.retryErrorUploads) {
  3807. $thumb.find('.kv-file-upload').hide();
  3808. self.fileManager.remove($thumb);
  3809. }
  3810. } else {
  3811. $thumb.find('.kv-file-upload').hide();
  3812. self._setThumbStatus($thumb, 'Success');
  3813. self.fileManager.remove($thumb);
  3814. }
  3815. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  3816. key++;
  3817. }
  3818. });
  3819. self._initUploadSuccess(data);
  3820. }
  3821. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3822. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3823. self._setProgress(101, self.$progress, self.msgUploadError);
  3824. }
  3825. };
  3826. fnComplete = function () {
  3827. self.unlock();
  3828. self._initSuccessThumbs();
  3829. self._clearFileInput();
  3830. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3831. };
  3832. fnError = function (jqXHR, textStatus, errorThrown) {
  3833. var outData = self._getOutData(formdata, jqXHR);
  3834. errMsg = self._parseError(op, jqXHR, errorThrown);
  3835. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3836. self.uploadFileCount = total - 1;
  3837. if (!self.showPreview) {
  3838. return;
  3839. }
  3840. self._getThumbs().each(function () {
  3841. var $thumb = $(this);
  3842. $thumb.removeClass('file-uploading');
  3843. if (self._getThumbFile($thumb)) {
  3844. self._setPreviewError($thumb);
  3845. }
  3846. });
  3847. self._getThumbs().removeClass('file-uploading');
  3848. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  3849. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  3850. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3851. };
  3852. var ctr = 0;
  3853. $.each(self.fileManager.stack, function (key, data) {
  3854. if (!$h.isEmpty(data.file)) {
  3855. self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key);
  3856. }
  3857. ctr++;
  3858. });
  3859. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3860. },
  3861. _uploadExtraOnly: function () {
  3862. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg,
  3863. op = self.ajaxOperations.uploadExtra;
  3864. fnBefore = function (jqXHR) {
  3865. self.lock();
  3866. var outData = self._getOutData(formdata, jqXHR);
  3867. self._setProgress(50);
  3868. params.data = outData;
  3869. params.xhr = jqXHR;
  3870. self._checkBatchPreupload(outData, jqXHR);
  3871. };
  3872. fnSuccess = function (data, textStatus, jqXHR) {
  3873. var outData = self._getOutData(formdata, jqXHR, data);
  3874. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3875. self._raise('filebatchuploadsuccess', [outData]);
  3876. self._clearFileInput();
  3877. self._initUploadSuccess(data);
  3878. self._setProgress(101);
  3879. } else {
  3880. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3881. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3882. }
  3883. };
  3884. fnComplete = function () {
  3885. self.unlock();
  3886. self._clearFileInput();
  3887. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3888. };
  3889. fnError = function (jqXHR, textStatus, errorThrown) {
  3890. var outData = self._getOutData(formdata, jqXHR);
  3891. errMsg = self._parseError(op, jqXHR, errorThrown);
  3892. params.data = outData;
  3893. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3894. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3895. };
  3896. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3897. },
  3898. _deleteFileIndex: function ($frame) {
  3899. var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
  3900. if (ind.substring(0, 5) === $h.INIT_FLAG) {
  3901. ind = parseInt(ind.replace($h.INIT_FLAG, ''));
  3902. self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
  3903. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
  3904. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
  3905. self.getFrames().each(function () {
  3906. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  3907. if (nInd.substring(0, 5) === $h.INIT_FLAG) {
  3908. nInd = parseInt(nInd.replace($h.INIT_FLAG, ''));
  3909. if (nInd > ind) {
  3910. nInd--;
  3911. $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd);
  3912. }
  3913. }
  3914. });
  3915. }
  3916. },
  3917. _resetCaption: function () {
  3918. var self = this;
  3919. setTimeout(function () {
  3920. var cap, n, chk = self.previewCache.count(true), len = self.fileManager.count(), file,
  3921. incomplete = ':not(.file-preview-success):not(.file-preview-error)',
  3922. hasThumb = self.showPreview && self.getFrames(incomplete).length;
  3923. if (len === 0 && chk === 0 && !hasThumb) {
  3924. self.reset();
  3925. } else {
  3926. n = chk + len;
  3927. if (n > 1) {
  3928. cap = self._getMsgSelected(n);
  3929. } else {
  3930. file = self.fileManager.getFirstFile();
  3931. cap = file ? file.nameFmt : '_';
  3932. }
  3933. self._setCaption(cap);
  3934. }
  3935. }, self.processDelay);
  3936. },
  3937. _initFileActions: function () {
  3938. var self = this;
  3939. if (!self.showPreview) {
  3940. return;
  3941. }
  3942. self._initZoomButton();
  3943. self.getFrames(' .kv-file-remove').each(function () {
  3944. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  3945. ind = $frame.attr('data-fileindex'), status, fm = self.fileManager;
  3946. self._handler($el, 'click', function () {
  3947. status = self._raise('filepreremove', [id, ind]);
  3948. if (status === false || !self._validateMinCount()) {
  3949. return false;
  3950. }
  3951. hasError = $frame.hasClass('file-preview-error');
  3952. $h.cleanMemory($frame);
  3953. $frame.fadeOut('slow', function () {
  3954. self.fileManager.remove($frame);
  3955. self._clearObjects($frame);
  3956. $frame.remove();
  3957. if (id && hasError) {
  3958. self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () {
  3959. $(this).remove();
  3960. if (!self._errorsExist()) {
  3961. self._resetErrors();
  3962. }
  3963. });
  3964. }
  3965. self._clearFileInput();
  3966. self._resetCaption();
  3967. self._raise('fileremoved', [id, ind]);
  3968. });
  3969. });
  3970. });
  3971. self.getFrames(' .kv-file-upload').each(function () {
  3972. var $el = $(this);
  3973. self._handler($el, 'click', function () {
  3974. var $frame = $el.closest($h.FRAMES), fileId = self._getThumbFileId($frame);
  3975. self._hideProgress();
  3976. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  3977. return;
  3978. }
  3979. self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false);
  3980. });
  3981. });
  3982. },
  3983. _initPreviewActions: function () {
  3984. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  3985. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  3986. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  3987. resetProgress = function () {
  3988. var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount();
  3989. if (!self.getFrames().length && !hasFiles) {
  3990. self._setCaption('');
  3991. self.reset();
  3992. self.initialCaption = '';
  3993. }
  3994. };
  3995. self._initZoomButton();
  3996. $preview.find(btnRemove).each(function () {
  3997. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore,
  3998. fnSuccess, fnError, op = self.ajaxOperations.deleteThumb;
  3999. if ($h.isEmpty(vUrl) || vKey === undefined) {
  4000. return;
  4001. }
  4002. if (typeof vUrl === 'function') {
  4003. vUrl = vUrl();
  4004. }
  4005. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config,
  4006. fileName, extraData, index = $frame.attr('data-fileindex');
  4007. index = parseInt(index.replace($h.INIT_FLAG, ''));
  4008. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  4009. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  4010. fileName = config && (config.filename || config.caption) || '';
  4011. if (typeof extraData === 'function') {
  4012. extraData = extraData();
  4013. }
  4014. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  4015. fnBefore = function (jqXHR) {
  4016. self.ajaxAborted = false;
  4017. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  4018. if (self._abort()) {
  4019. jqXHR.abort();
  4020. } else {
  4021. $el.removeClass(errClass);
  4022. $h.addCss($frame, 'file-uploading');
  4023. $h.addCss($el, 'disabled ' + origClass);
  4024. }
  4025. };
  4026. fnSuccess = function (data, textStatus, jqXHR) {
  4027. var n, cap;
  4028. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  4029. params.jqXHR = jqXHR;
  4030. params.response = data;
  4031. errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName);
  4032. self._showFileError(errMsg, params, 'filedeleteerror');
  4033. $frame.removeClass('file-uploading');
  4034. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4035. resetProgress();
  4036. return;
  4037. }
  4038. $frame.removeClass('file-uploading').addClass('file-deleted');
  4039. $frame.fadeOut('slow', function () {
  4040. index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, ''));
  4041. self.previewCache.unset(index);
  4042. self._deleteFileIndex($frame);
  4043. n = self.previewCache.count(true);
  4044. cap = n > 0 ? self._getMsgSelected(n) : '';
  4045. self._setCaption(cap);
  4046. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  4047. self._clearObjects($frame);
  4048. $frame.remove();
  4049. resetProgress();
  4050. });
  4051. };
  4052. fnError = function (jqXHR, textStatus, errorThrown) {
  4053. var errMsg = self._parseError(op, jqXHR, errorThrown, fileName);
  4054. params.jqXHR = jqXHR;
  4055. params.response = {};
  4056. self._showFileError(errMsg, params, 'filedeleteerror');
  4057. $frame.removeClass('file-uploading');
  4058. $el.removeClass('disabled ' + origClass).addClass(errClass);
  4059. resetProgress();
  4060. };
  4061. self._initAjaxSettings();
  4062. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  4063. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  4064. self._mergeAjaxCallback('error', fnError, 'delete');
  4065. settings = $.extend(true, {}, {
  4066. url: self._encodeURI(vUrl),
  4067. type: 'POST',
  4068. dataType: 'json',
  4069. data: $.extend(true, {}, {key: vKey}, extraData)
  4070. }, self._ajaxDeleteSettings);
  4071. self._handler($el, 'click', function () {
  4072. if (!self._validateMinCount()) {
  4073. return false;
  4074. }
  4075. self.ajaxAborted = false;
  4076. self._raise('filebeforedelete', [vKey, extraData]);
  4077. if (self.ajaxAborted instanceof Promise) {
  4078. self.ajaxAborted.then(function (result) {
  4079. if (!result) {
  4080. $.ajax(settings);
  4081. }
  4082. });
  4083. } else {
  4084. if (!self.ajaxAborted) {
  4085. $.ajax(settings);
  4086. }
  4087. }
  4088. });
  4089. });
  4090. },
  4091. _hideFileIcon: function () {
  4092. var self = this;
  4093. if (self.overwriteInitial) {
  4094. self.$captionContainer.removeClass('icon-visible');
  4095. }
  4096. },
  4097. _showFileIcon: function () {
  4098. var self = this;
  4099. $h.addCss(self.$captionContainer, 'icon-visible');
  4100. },
  4101. _getSize: function (bytes, sizes) {
  4102. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out;
  4103. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  4104. return '';
  4105. }
  4106. if (typeof func === 'function') {
  4107. out = func(size);
  4108. } else {
  4109. if (size === 0) {
  4110. out = '0.00 B';
  4111. } else {
  4112. if (!sizes) {
  4113. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  4114. }
  4115. i = Math.floor(Math.log(size) / Math.log(1024));
  4116. out = (size / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
  4117. }
  4118. }
  4119. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  4120. },
  4121. _getFileType: function (ftype) {
  4122. var self = this;
  4123. return self.mimeTypeAliases[ftype] || ftype;
  4124. },
  4125. _generatePreviewTemplate: function (
  4126. cat,
  4127. data,
  4128. fname,
  4129. ftype,
  4130. previewId,
  4131. fileId,
  4132. isError,
  4133. size,
  4134. frameClass,
  4135. foot,
  4136. ind,
  4137. templ,
  4138. attrs,
  4139. zoomData
  4140. ) {
  4141. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  4142. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  4143. config, title = caption, alt = caption, typeCss = 'type-default', getContent,
  4144. footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError),
  4145. forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview,
  4146. newCat = forcePrevIcon ? 'other' : cat;
  4147. config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
  4148. (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
  4149. if (config) {
  4150. $.each(config, function (key, val) {
  4151. styleAttribs += key + ':' + val + ';';
  4152. });
  4153. }
  4154. getContent = function (vCat, vData, zoom, frameCss, vZoomData) {
  4155. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(vCat),
  4156. css = (frameClass || '') + ' ' + frameCss, tokens;
  4157. if (self.frameClass) {
  4158. css = self.frameClass + ' ' + css;
  4159. }
  4160. if (zoom) {
  4161. css = css.replace(' ' + $h.SORT_CSS, '');
  4162. }
  4163. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  4164. if (cat === 'object' && !ftype) {
  4165. $.each(self.defaults.fileTypeSettings, function (key, func) {
  4166. if (key === 'object' || key === 'other') {
  4167. return;
  4168. }
  4169. if (func(fname, ftype)) {
  4170. typeCss = 'type-' + key;
  4171. }
  4172. });
  4173. }
  4174. if (!$h.isEmpty(attrs)) {
  4175. if (attrs.title !== undefined && attrs.title !== null) {
  4176. title = attrs.title;
  4177. }
  4178. if (attrs.alt !== undefined && attrs.alt !== null) {
  4179. title = attrs.alt;
  4180. }
  4181. }
  4182. tokens = {
  4183. 'previewId': id,
  4184. 'caption': caption,
  4185. 'title': title,
  4186. 'alt': alt,
  4187. 'frameClass': css,
  4188. 'type': self._getFileType(ftype),
  4189. 'fileindex': ind,
  4190. 'fileid': fileId || '',
  4191. 'typeCss': typeCss,
  4192. 'footer': footer,
  4193. 'data': zoom && vZoomData ? '{zoomData}' : vData,
  4194. 'template': templ || cat,
  4195. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : '',
  4196. 'zoomData': vZoomData ? encodeURIComponent(vZoomData) : ''
  4197. };
  4198. if (zoom) {
  4199. tokens.zoomCache = '';
  4200. tokens.zoomData = '{zoomData}';
  4201. }
  4202. return tmplt.setTokens(tokens);
  4203. };
  4204. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  4205. if (self.fileActionSettings.showZoom) {
  4206. zoomContent = getContent((forceZoomIcon ? 'other' : cat), data, true, 'kv-zoom-thumb', zoomData);
  4207. }
  4208. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  4209. if (typeof self.sanitizeZoomCache === 'function') {
  4210. zoomContent = self.sanitizeZoomCache(zoomContent);
  4211. }
  4212. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb', zoomData);
  4213. return prevContent.setTokens({zoomCache: zoomContent});
  4214. },
  4215. _addToPreview: function ($preview, content) {
  4216. var self = this, $el;
  4217. content = $h.cspBuffer.stash(content);
  4218. $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  4219. $h.cspBuffer.apply($preview);
  4220. return $el;
  4221. },
  4222. _previewDefault: function (file, isDisabled) {
  4223. var self = this, $preview = self.$preview;
  4224. if (!self.showPreview) {
  4225. return;
  4226. }
  4227. var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
  4228. caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
  4229. data = $h.createObjectURL(file), fileId = self.fileManager.getId(file),
  4230. previewId = self._getThumbId(fileId);
  4231. self._clearDefaultPreview();
  4232. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
  4233. self._addToPreview($preview, content);
  4234. self._setThumbAttr(previewId, caption, size);
  4235. if (isDisabled === true && self.isAjaxUpload) {
  4236. self._setThumbStatus(self._getFrame(previewId), 'Error');
  4237. }
  4238. },
  4239. _previewFile: function (i, file, theFile, data, fileInfo) {
  4240. if (!this.showPreview) {
  4241. return;
  4242. }
  4243. var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name,
  4244. cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0,
  4245. iData = cat === 'image' ? theFile.target.result : data, fm = self.fileManager,
  4246. fileId = fm.getId(file), previewId = self._getThumbId(fileId);
  4247. /** @namespace window.DOMPurify */
  4248. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize);
  4249. self._clearDefaultPreview();
  4250. self._addToPreview($preview, content);
  4251. var $thumb = self._getFrame(previewId);
  4252. self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData);
  4253. self._setThumbAttr(previewId, caption, fsize);
  4254. self._initSortable();
  4255. },
  4256. _setThumbAttr: function (id, caption, size) {
  4257. var self = this, $frame = self._getFrame(id);
  4258. if ($frame.length) {
  4259. size = size && size > 0 ? self._getSize(size) : '';
  4260. $frame.data({'caption': caption, 'size': size});
  4261. }
  4262. },
  4263. _setInitThumbAttr: function () {
  4264. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  4265. caption, size, previewId;
  4266. if (len === 0) {
  4267. return;
  4268. }
  4269. for (var i = 0; i < len; i++) {
  4270. config = data.config[i];
  4271. previewId = self.previewInitId + '-' + $h.INIT_FLAG + i;
  4272. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  4273. size = $h.ifSet('size', config);
  4274. self._setThumbAttr(previewId, caption, size);
  4275. }
  4276. },
  4277. _slugDefault: function (text) {
  4278. // noinspection RegExpRedundantEscape
  4279. return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  4280. },
  4281. _updateFileDetails: function (numFiles, skipRaiseEvent) {
  4282. var self = this, $el = self.$element, label, n, log, nFiles, file,
  4283. name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
  4284. if (!name && self.fileManager.count() > 0) {
  4285. file = self.fileManager.getFirstFile();
  4286. label = file.nameFmt;
  4287. } else {
  4288. label = name ? self.slug(name) : '_';
  4289. }
  4290. n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
  4291. nFiles = self.previewCache.count(true) + n;
  4292. log = n === 1 ? label : self._getMsgSelected(nFiles, !self.isAjaxUpload && !self.isError);
  4293. if (self.isError) {
  4294. self.$previewContainer.removeClass('file-thumb-loading');
  4295. self._initCapStatus();
  4296. self.$previewStatus.html('');
  4297. self.$captionContainer.removeClass('icon-visible');
  4298. } else {
  4299. self._showFileIcon();
  4300. }
  4301. self._setCaption(log, self.isError);
  4302. self.$container.removeClass('file-input-new file-input-ajax-new');
  4303. if (!skipRaiseEvent) {
  4304. self._raise('fileselect', [numFiles, label]);
  4305. }
  4306. if (self.previewCache.count(true)) {
  4307. self._initPreviewActions();
  4308. }
  4309. },
  4310. _setThumbStatus: function ($thumb, status) {
  4311. var self = this;
  4312. if (!self.showPreview) {
  4313. return;
  4314. }
  4315. var icon = 'indicator' + status, msg = icon + 'Title',
  4316. css = 'file-preview-' + status.toLowerCase(),
  4317. $indicator = $thumb.find('.file-upload-indicator'),
  4318. config = self.fileActionSettings;
  4319. $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
  4320. if (status === 'Success') {
  4321. $thumb.find('.file-drag-handle').remove();
  4322. }
  4323. $h.setHtml($indicator, config[icon]);
  4324. $indicator.attr('title', config[msg]);
  4325. $thumb.addClass(css);
  4326. if (status === 'Error' && !self.retryErrorUploads) {
  4327. $thumb.find('.kv-file-upload').attr('disabled', true);
  4328. }
  4329. },
  4330. _setProgressCancelled: function () {
  4331. var self = this;
  4332. self._setProgress(101, self.$progress, self.msgCancelled);
  4333. },
  4334. _setProgress: function (p, $el, error, stats) {
  4335. var self = this;
  4336. $el = $el || self.$progress;
  4337. if (!$el.length) {
  4338. return;
  4339. }
  4340. var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  4341. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  4342. template = pct < 100 ? self.progressTemplate :
  4343. (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
  4344. if (p >= 100) {
  4345. stats = '';
  4346. }
  4347. if (!$h.isEmpty(template)) {
  4348. if (pctLimit && pct > pctLimit && p <= 100) {
  4349. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  4350. } else {
  4351. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  4352. }
  4353. stats = stats || '';
  4354. out = out.setTokens({stats: stats});
  4355. $h.setHtml($el, out);
  4356. if (error) {
  4357. $h.setHtml($el.find('[role="progressbar"]'), error);
  4358. }
  4359. }
  4360. },
  4361. _hasFiles: function () {
  4362. var el = this.$element[0];
  4363. return !!(el && el.files && el.files.length);
  4364. },
  4365. _setFileDropZoneTitle: function () {
  4366. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  4367. if (self.isClickable) {
  4368. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  4369. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  4370. }
  4371. $zone.find('.' + self.dropZoneTitleClass).remove();
  4372. if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
  4373. self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) {
  4374. return;
  4375. }
  4376. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  4377. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  4378. }
  4379. self.$container.removeClass('file-input-new');
  4380. $h.addCss(self.$container, 'file-input-ajax-new');
  4381. },
  4382. _getStats: function (stats) {
  4383. var self = this, pendingTime, t;
  4384. if (!self.showUploadStats || !stats || !stats.bitrate) {
  4385. return '';
  4386. }
  4387. t = self._getLayoutTemplate('stats');
  4388. pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
  4389. self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
  4390. return t.setTokens({
  4391. uploadSpeed: stats.bitrate,
  4392. pendingTime: pendingTime
  4393. });
  4394. },
  4395. _setResumableProgress: function (pct, stats, $thumb) {
  4396. var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
  4397. $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
  4398. if (obj.lastProgress === 0) {
  4399. obj.lastProgress = pct;
  4400. }
  4401. if (pct < obj.lastProgress) {
  4402. pct = obj.lastProgress;
  4403. }
  4404. self._setProgress(pct, $prog, null, self._getStats(stats));
  4405. obj.lastProgress = pct;
  4406. },
  4407. _toggleResumableProgress: function (template, message) {
  4408. var self = this, $progress = self.$progress;
  4409. if ($progress && $progress.length) {
  4410. $h.setHtml($progress, template.setTokens({
  4411. percent: 101,
  4412. status: message,
  4413. stats: ''
  4414. }));
  4415. }
  4416. },
  4417. _setFileUploadStats: function (id, pct, stats) {
  4418. var self = this, $prog = self.$progress;
  4419. if (!self.showPreview && (!$prog || !$prog.length)) {
  4420. return;
  4421. }
  4422. var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot,
  4423. totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
  4424. if (self.enableResumableUpload) {
  4425. var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
  4426. loaded += currUplSize;
  4427. totLoaded = fm.uploadedSize + loaded;
  4428. pct = $h.round(100 * loaded / currTotSize);
  4429. stats.pendingBytes = currTotSize - currUplSize;
  4430. self._setResumableProgress(pct, stats, $thumb);
  4431. pctTot = Math.floor(100 * totLoaded / totSize);
  4432. totStats.pendingBytes = totSize - totLoaded;
  4433. self._setResumableProgress(pctTot, totStats);
  4434. } else {
  4435. fm.setProgress(id, pct);
  4436. $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
  4437. self._setProgress(pct, $prog, null, self._getStats(stats));
  4438. $.each(fm.stats, function (id, cfg) {
  4439. totUpSize += cfg.loaded;
  4440. });
  4441. totStats.pendingBytes = totSize - totUpSize;
  4442. pctTot = $h.round(totUpSize / totSize * 100);
  4443. self._setProgress(pctTot, null, null, self._getStats(totStats));
  4444. }
  4445. },
  4446. _validateMinCount: function () {
  4447. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  4448. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  4449. self._noFilesError({});
  4450. return false;
  4451. }
  4452. return true;
  4453. },
  4454. _getFileCount: function (fileCount, includeInitial) {
  4455. var self = this, addCount = 0;
  4456. if (includeInitial === undefined) {
  4457. includeInitial = self.validateInitialCount && !self.overwriteInitial;
  4458. }
  4459. if (includeInitial) {
  4460. addCount = self.previewCache.count(true);
  4461. fileCount += addCount;
  4462. }
  4463. return fileCount;
  4464. },
  4465. _getFileId: function (file) {
  4466. return $h.getFileId(file, this.generateFileId);
  4467. },
  4468. _getFileName: function (file, defaultValue) {
  4469. var self = this, fileName = $h.getFileName(file);
  4470. return fileName ? self.slug(fileName) : defaultValue;
  4471. },
  4472. _getFileNames: function (skipNull) {
  4473. var self = this;
  4474. return self.filenames.filter(function (n) {
  4475. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  4476. });
  4477. },
  4478. _setPreviewError: function ($thumb, keepFile) {
  4479. var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
  4480. if (!keepFile || removeFrame) {
  4481. self.fileManager.remove($thumb);
  4482. }
  4483. if (!self.showPreview) {
  4484. return;
  4485. }
  4486. if (removeFrame) {
  4487. $thumb.remove();
  4488. return;
  4489. } else {
  4490. self._setThumbStatus($thumb, 'Error');
  4491. }
  4492. self._refreshUploadButton($thumb);
  4493. },
  4494. _refreshUploadButton: function ($thumb) {
  4495. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  4496. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  4497. if (!$btn.length) {
  4498. return;
  4499. }
  4500. if (self.retryErrorUploads) {
  4501. icon = cfg.uploadRetryIcon;
  4502. title = cfg.uploadRetryTitle;
  4503. }
  4504. $btn.attr('title', title);
  4505. $h.setHtml($btn, icon);
  4506. },
  4507. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  4508. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  4509. $imgEl, isValid;
  4510. if ($h.isEmpty(limit) || !$img.length) {
  4511. return;
  4512. }
  4513. $imgEl = $img[0];
  4514. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  4515. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  4516. if (isValid) {
  4517. return;
  4518. }
  4519. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  4520. self._showFileError(msg, params);
  4521. self._setPreviewError($thumb);
  4522. },
  4523. _getExifObj: function (data) {
  4524. var self = this, exifObj, error = $h.logMessages.exifWarning;
  4525. if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
  4526. exifObj = null;
  4527. return;
  4528. }
  4529. try {
  4530. exifObj = window.piexif ? window.piexif.load(data) : null;
  4531. } catch (err) {
  4532. exifObj = null;
  4533. error = err && err.message || '';
  4534. }
  4535. if (!exifObj) {
  4536. self._log($h.logMessages.badExifParser, {details: error});
  4537. }
  4538. return exifObj;
  4539. },
  4540. setImageOrientation: function ($img, $zoomImg, value, $thumb) {
  4541. var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
  4542. isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
  4543. if (invalidImg && invalidZoomImg) {
  4544. return;
  4545. }
  4546. ev = 'load.fileinputimageorient';
  4547. if (zoomOnly) {
  4548. $img = $zoomImg;
  4549. $zoomImg = null;
  4550. $img.css(self.previewSettings.image);
  4551. $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
  4552. $mark = $(document.createElement('span')).insertBefore($img);
  4553. $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
  4554. } else {
  4555. isHidden = !$img.is(':visible');
  4556. }
  4557. $img.off(ev).on(ev, function () {
  4558. if (isHidden) {
  4559. self.$preview.removeClass('hide-content');
  4560. $thumb.find('.kv-file-content').css('visibility', 'hidden');
  4561. }
  4562. var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null,
  4563. h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
  4564. if (isHidden) {
  4565. $thumb.find('.kv-file-content').css('visibility', 'visible');
  4566. self.$preview.addClass('hide-content');
  4567. }
  4568. $img.data('orientation', value);
  4569. if (zoomImg) {
  4570. $zoomImg.data('orientation', value);
  4571. }
  4572. if (value < 5) {
  4573. $h.setTransform(img, r);
  4574. $h.setTransform(zoomImg, r);
  4575. return;
  4576. }
  4577. var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
  4578. scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
  4579. s = ' scale(' + Math.abs(scale) + ')';
  4580. $h.setTransform(img, r + s);
  4581. $h.setTransform(zoomImg, r + s);
  4582. if (zoomOnly) {
  4583. $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
  4584. $mark.remove();
  4585. $div.remove();
  4586. }
  4587. });
  4588. },
  4589. _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
  4590. var self = this, exifObj = null, value, autoOrientImage = self.autoOrientImage, selector;
  4591. if (self.canOrientImage) {
  4592. $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none'));
  4593. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4594. return;
  4595. }
  4596. selector = $h.getZoomSelector(previewId, ' img');
  4597. exifObj = autoOrientImage ? self._getExifObj(iData) : null;
  4598. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  4599. if (!value) {
  4600. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4601. return;
  4602. }
  4603. self.setImageOrientation($img, $(selector), value, self._getFrame(previewId));
  4604. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  4605. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4606. },
  4607. _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
  4608. var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId),
  4609. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  4610. fname = fname || 'Untitled';
  4611. $img.one('load', function () {
  4612. w1 = $thumb.width();
  4613. w2 = $preview.width();
  4614. if (w1 > w2) {
  4615. $img.css('width', '100%');
  4616. }
  4617. params = {ind: i, id: previewId, fileId: fileId};
  4618. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  4619. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  4620. if (!self.resizeImage) {
  4621. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  4622. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  4623. }
  4624. self._raise('fileimageloaded', [previewId]);
  4625. self.fileManager.addImage(fileId, {
  4626. ind: i,
  4627. img: $img,
  4628. thumb: $thumb,
  4629. pid: previewId,
  4630. typ: ftype,
  4631. siz: fsize,
  4632. validated: false,
  4633. imgData: iData,
  4634. exifObj: exifObj
  4635. });
  4636. $thumb.data('exif', exifObj);
  4637. self._validateAllImages();
  4638. }).one('error', function () {
  4639. self._raise('fileimageloaderror', [previewId]);
  4640. });
  4641. },
  4642. _validateAllImages: function () {
  4643. var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
  4644. minSize = self.resizeIfSizeMoreThan;
  4645. if (numImgs !== self.fileManager.totalImages) {
  4646. return;
  4647. }
  4648. self._raise('fileimagesloaded');
  4649. if (!self.resizeImage) {
  4650. return;
  4651. }
  4652. $.each(self.fileManager.loadedImages, function (id, config) {
  4653. if (!config.validated) {
  4654. fsize = config.siz;
  4655. if (fsize && fsize > minSize * 1000) {
  4656. self._getResizedImage(id, config, counter, numImgs);
  4657. }
  4658. config.validated = true;
  4659. }
  4660. });
  4661. },
  4662. _getResizedImage: function (id, config, counter, numImgs) {
  4663. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  4664. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  4665. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  4666. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  4667. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
  4668. throwError = function (msg, params, ev) {
  4669. if (self.isAjaxUpload) {
  4670. self._showFileError(msg, params, ev);
  4671. } else {
  4672. self._showError(msg, params, ev);
  4673. }
  4674. self._setPreviewError($thumb);
  4675. };
  4676. file = self.fileManager.getFile(id);
  4677. params = {id: pid, 'index': ind, fileId: id};
  4678. evParams = [id, pid, ind];
  4679. if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  4680. if (isValidImage && file) {
  4681. self._raise('fileimageresized', evParams);
  4682. }
  4683. counter.val++;
  4684. if (counter.val === numImgs) {
  4685. self._raise('fileimagesresized');
  4686. }
  4687. if (!isValidImage) {
  4688. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4689. return;
  4690. }
  4691. }
  4692. type = type || self.resizeDefaultImageType;
  4693. chkWidth = width > maxWidth;
  4694. chkHeight = height > maxHeight;
  4695. if (self.resizePreference === 'width') {
  4696. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  4697. } else {
  4698. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  4699. }
  4700. self._resetCanvas();
  4701. width *= ratio;
  4702. height *= ratio;
  4703. canvas.width = width;
  4704. canvas.height = height;
  4705. try {
  4706. context.drawImage(img, 0, 0, width, height);
  4707. dataURI = canvas.toDataURL(type, self.resizeQuality);
  4708. if (exifObj) {
  4709. exifStr = window.piexif.dump(exifObj);
  4710. dataURI = window.piexif.insert(exifStr, dataURI);
  4711. }
  4712. blob = $h.dataURI2Blob(dataURI);
  4713. self.fileManager.setFile(id, blob);
  4714. self._raise('fileimageresized', evParams);
  4715. counter.val++;
  4716. if (counter.val === numImgs) {
  4717. self._raise('fileimagesresized', [undefined, undefined]);
  4718. }
  4719. if (!(blob instanceof Blob)) {
  4720. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4721. }
  4722. } catch (err) {
  4723. counter.val++;
  4724. if (counter.val === numImgs) {
  4725. self._raise('fileimagesresized', [undefined, undefined]);
  4726. }
  4727. msg = self.msgImageResizeException.replace('{errors}', err.message);
  4728. throwError(msg, params, 'fileimageresizeexception');
  4729. }
  4730. },
  4731. _showProgress: function () {
  4732. var self = this;
  4733. if (self.$progress && self.$progress.length) {
  4734. self.$progress.show();
  4735. }
  4736. },
  4737. _hideProgress: function () {
  4738. var self = this;
  4739. if (self.$progress && self.$progress.length) {
  4740. self.$progress.hide();
  4741. }
  4742. },
  4743. _initBrowse: function ($container) {
  4744. var self = this, $el = self.$element;
  4745. if (self.showBrowse) {
  4746. self.$btnFile = $container.find('.btn-file').append($el);
  4747. } else {
  4748. $el.appendTo($container).attr('tabindex', -1);
  4749. $h.addCss($el, 'file-no-browse');
  4750. }
  4751. },
  4752. _initClickable: function () {
  4753. var self = this, $zone, $tmpZone;
  4754. if (!self.isClickable) {
  4755. return;
  4756. }
  4757. $zone = self.$dropZone;
  4758. if (!self.isAjaxUpload) {
  4759. $tmpZone = self.$preview.find('.file-default-preview');
  4760. if ($tmpZone.length) {
  4761. $zone = $tmpZone;
  4762. }
  4763. }
  4764. $h.addCss($zone, 'clickable');
  4765. $zone.attr('tabindex', -1);
  4766. self._handler($zone, 'click', function (e) {
  4767. var $tar = $(e.target);
  4768. if (!self.$errorContainer.is(':visible') && (!$tar.parents(
  4769. '.file-preview-thumbnails').length || $tar.parents(
  4770. '.file-default-preview').length)) {
  4771. self.$element.data('zoneClicked', true).trigger('click');
  4772. $zone.blur();
  4773. }
  4774. });
  4775. },
  4776. _initCaption: function () {
  4777. var self = this, cap = self.initialCaption || '';
  4778. if (self.overwriteInitial || $h.isEmpty(cap)) {
  4779. self.$caption.val('');
  4780. return false;
  4781. }
  4782. self._setCaption(cap);
  4783. return true;
  4784. },
  4785. _setCaption: function (content, isError) {
  4786. var self = this, title, out, icon, n, cap, file;
  4787. if (!self.$caption.length) {
  4788. return;
  4789. }
  4790. self.$captionContainer.removeClass('icon-visible');
  4791. if (isError) {
  4792. title = $('<div>' + self.msgValidationError + '</div>').text();
  4793. n = self.fileManager.count();
  4794. if (n) {
  4795. file = self.fileManager.getFirstFile();
  4796. cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
  4797. } else {
  4798. cap = self._getMsgSelected(self.msgNo);
  4799. }
  4800. out = $h.isEmpty(content) ? cap : content;
  4801. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  4802. } else {
  4803. if ($h.isEmpty(content)) {
  4804. self.$caption.attr('title', '');
  4805. return;
  4806. }
  4807. title = $('<div>' + content + '</div>').text();
  4808. out = title;
  4809. icon = self._getLayoutTemplate('fileIcon');
  4810. }
  4811. self.$captionContainer.addClass('icon-visible');
  4812. self.$caption.attr('title', title).val(out);
  4813. $h.setHtml(self.$captionIcon, icon);
  4814. },
  4815. _createContainer: function () {
  4816. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  4817. $container = $h.createElement($h.cspBuffer.stash(self._renderMain()));
  4818. $h.cspBuffer.apply($container);
  4819. $container.insertBefore(self.$element).attr(attribs);
  4820. self._initBrowse($container);
  4821. if (self.theme) {
  4822. $container.addClass('theme-' + self.theme);
  4823. }
  4824. return $container;
  4825. },
  4826. _refreshContainer: function () {
  4827. var self = this, $container = self.$container, $el = self.$element;
  4828. $el.insertAfter($container);
  4829. $h.setHtml($container, self._renderMain());
  4830. self._initBrowse($container);
  4831. self._validateDisabled();
  4832. },
  4833. _validateDisabled: function () {
  4834. var self = this;
  4835. self.$caption.attr({readonly: self.isDisabled});
  4836. },
  4837. _setTabIndex: function (type, html) {
  4838. var self = this, index = self.tabIndexConfig[type];
  4839. return html.setTokens({
  4840. tabIndexConfig: index === undefined || index === null ? '' : 'tabindex="' + index + '"'
  4841. });
  4842. },
  4843. _renderMain: function () {
  4844. var self = this,
  4845. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  4846. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  4847. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  4848. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  4849. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  4850. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  4851. caption = self._setTabIndex('caption', caption);
  4852. return self.mainTemplate.setTokens({
  4853. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  4854. 'inputGroupClass': self.inputGroupClass,
  4855. 'preview': preview,
  4856. 'close': close,
  4857. 'caption': caption,
  4858. 'upload': self._renderButton('upload'),
  4859. 'remove': self._renderButton('remove'),
  4860. 'cancel': self._renderButton('cancel'),
  4861. 'pause': self._renderButton('pause'),
  4862. 'browse': self._renderButton('browse')
  4863. });
  4864. },
  4865. _renderButton: function (type) {
  4866. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  4867. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  4868. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  4869. switch (type) {
  4870. case 'remove':
  4871. if (!self.showRemove) {
  4872. return '';
  4873. }
  4874. break;
  4875. case 'cancel':
  4876. if (!self.showCancel) {
  4877. return '';
  4878. }
  4879. css += ' kv-hidden';
  4880. break;
  4881. case 'pause':
  4882. if (!self.showPause) {
  4883. return '';
  4884. }
  4885. css += ' kv-hidden';
  4886. break;
  4887. case 'upload':
  4888. if (!self.showUpload) {
  4889. return '';
  4890. }
  4891. if (self.isAjaxUpload && !self.isDisabled) {
  4892. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  4893. } else {
  4894. btnType = 'submit';
  4895. }
  4896. break;
  4897. case 'browse':
  4898. if (!self.showBrowse) {
  4899. return '';
  4900. }
  4901. tmplt = self._getLayoutTemplate('btnBrowse');
  4902. break;
  4903. default:
  4904. return '';
  4905. }
  4906. tmplt = self._setTabIndex(type, tmplt);
  4907. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  4908. if (!$h.isEmpty(label)) {
  4909. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  4910. }
  4911. return tmplt.setTokens({
  4912. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  4913. });
  4914. },
  4915. _renderThumbProgress: function () {
  4916. var self = this;
  4917. return '<div class="file-thumb-progress kv-hidden">' +
  4918. self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
  4919. '</div>';
  4920. },
  4921. _renderFileFooter: function (cat, caption, size, width, isError) {
  4922. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  4923. upl = config.showUpload, zoom = config.showZoom, out, params,
  4924. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  4925. ind = isError ? config.indicatorError : config.indicatorNew,
  4926. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  4927. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  4928. size = self._getSize(size);
  4929. params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
  4930. if (self.isAjaxUpload) {
  4931. params.progress = self._renderThumbProgress();
  4932. params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false);
  4933. } else {
  4934. params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false);
  4935. }
  4936. out = template.setTokens(params);
  4937. out = $h.replaceTags(out, self.previewThumbTags);
  4938. return out;
  4939. },
  4940. _renderFileActions: function (
  4941. cfg,
  4942. showUpl,
  4943. showDwn,
  4944. showDel,
  4945. showZoom,
  4946. showDrag,
  4947. disabled,
  4948. url,
  4949. key,
  4950. isInit,
  4951. dUrl,
  4952. dFile
  4953. ) {
  4954. var self = this;
  4955. if (!cfg.type && isInit) {
  4956. cfg.type = 'image';
  4957. }
  4958. if (self.enableResumableUpload) {
  4959. showUpl = false;
  4960. } else {
  4961. if (typeof showUpl === 'function') {
  4962. showUpl = showUpl(cfg);
  4963. }
  4964. }
  4965. if (typeof showDwn === 'function') {
  4966. showDwn = showDwn(cfg);
  4967. }
  4968. if (typeof showDel === 'function') {
  4969. showDel = showDel(cfg);
  4970. }
  4971. if (typeof showZoom === 'function') {
  4972. showZoom = showZoom(cfg);
  4973. }
  4974. if (typeof showDrag === 'function') {
  4975. showDrag = showDrag(cfg);
  4976. }
  4977. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  4978. return '';
  4979. }
  4980. var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css,
  4981. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  4982. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  4983. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  4984. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  4985. if (showDel) {
  4986. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  4987. 'removeClass': removeClass,
  4988. 'removeIcon': config.removeIcon,
  4989. 'removeTitle': config.removeTitle,
  4990. 'dataUrl': vUrl,
  4991. 'dataKey': vKey,
  4992. 'key': key
  4993. });
  4994. }
  4995. if (showUpl) {
  4996. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  4997. 'uploadClass': config.uploadClass,
  4998. 'uploadIcon': config.uploadIcon,
  4999. 'uploadTitle': config.uploadTitle
  5000. });
  5001. }
  5002. if (showDwn) {
  5003. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  5004. 'downloadClass': config.downloadClass,
  5005. 'downloadIcon': config.downloadIcon,
  5006. 'downloadTitle': config.downloadTitle,
  5007. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  5008. });
  5009. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  5010. }
  5011. if (showZoom) {
  5012. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  5013. 'zoomClass': config.zoomClass,
  5014. 'zoomIcon': config.zoomIcon,
  5015. 'zoomTitle': config.zoomTitle
  5016. });
  5017. }
  5018. if (showDrag && isInit) {
  5019. css = 'drag-handle-init ' + config.dragClass;
  5020. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  5021. 'dragClass': css,
  5022. 'dragTitle': config.dragTitle,
  5023. 'dragIcon': config.dragIcon
  5024. });
  5025. }
  5026. return template.setTokens({
  5027. 'delete': btnDelete,
  5028. 'upload': btnUpload,
  5029. 'download': btnDownload,
  5030. 'zoom': btnZoom,
  5031. 'drag': btnDrag,
  5032. 'other': otherButtons
  5033. });
  5034. },
  5035. _browse: function (e) {
  5036. var self = this;
  5037. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  5038. return;
  5039. }
  5040. if (self.isError && !self.isAjaxUpload) {
  5041. self.clear();
  5042. }
  5043. if (self.focusCaptionOnBrowse) {
  5044. self.$captionContainer.focus();
  5045. }
  5046. },
  5047. _change: function (e) {
  5048. var self = this;
  5049. $(document.body).off('focusin.fileinput focusout.fileinput');
  5050. if (self.changeTriggered) {
  5051. return;
  5052. }
  5053. self._setLoading('show');
  5054. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  5055. tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(),
  5056. total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')),
  5057. maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount,
  5058. inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0),
  5059. throwError = function (mesg, file, previewId, index) {
  5060. var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
  5061. p2 = {id: previewId, index: index, file: file, files: files};
  5062. self.isPersistentError = true;
  5063. self._setLoading('hide');
  5064. return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
  5065. },
  5066. maxCountCheck = function (n, m, all) {
  5067. var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany;
  5068. msg = msg.replace('{m}', m).replace('{n}', n);
  5069. self.isError = throwError(msg, null, null, null);
  5070. self.$captionContainer.removeClass('icon-visible');
  5071. self._setCaption('', true);
  5072. self.$container.removeClass('file-input-new file-input-ajax-new');
  5073. };
  5074. self.reader = null;
  5075. self._resetUpload();
  5076. self._hideFileIcon();
  5077. if (self.dropZoneEnabled) {
  5078. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5079. }
  5080. if (!isAjaxUpload) {
  5081. if (e.target && e.target.files === undefined) {
  5082. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  5083. } else {
  5084. files = e.target.files || {};
  5085. }
  5086. }
  5087. tfiles = files;
  5088. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  5089. if (!isAjaxUpload) {
  5090. self.clear();
  5091. }
  5092. self._raise('fileselectnone');
  5093. return;
  5094. }
  5095. self._resetErrors();
  5096. len = tfiles.length;
  5097. initCount = isAjaxUpload ? (self.fileManager.count() + len) : len;
  5098. total = self._getFileCount(initCount, inclAll ? false : undefined);
  5099. if (maxCount > 0 && total > maxCount) {
  5100. if (!self.autoReplace || len > maxCount) {
  5101. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  5102. return;
  5103. }
  5104. if (total > maxCount) {
  5105. self._resetPreviewThumbs(isAjaxUpload);
  5106. }
  5107. } else {
  5108. if (inclAll) {
  5109. total = self._getFileCount(initCount, true);
  5110. if (maxTotCount > 0 && total > maxTotCount) {
  5111. if (!self.autoReplace || len > maxCount) {
  5112. maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true);
  5113. return;
  5114. }
  5115. if (total > maxCount) {
  5116. self._resetPreviewThumbs(isAjaxUpload);
  5117. }
  5118. }
  5119. }
  5120. if (!isAjaxUpload || flagSingle) {
  5121. self._resetPreviewThumbs(false);
  5122. if (flagSingle) {
  5123. self.clearFileStack();
  5124. }
  5125. } else {
  5126. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
  5127. self._resetPreviewThumbs(true);
  5128. }
  5129. }
  5130. }
  5131. self.readFiles(tfiles);
  5132. self._setLoading('hide');
  5133. },
  5134. _abort: function (params) {
  5135. var self = this, data;
  5136. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  5137. data = $.extend(true, {}, self._getOutData(null), params);
  5138. data.abortData = self.ajaxAborted.data || {};
  5139. data.abortMessage = self.ajaxAborted.message;
  5140. self._setProgress(101, self.$progress, self.msgCancelled);
  5141. self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
  5142. self.cancel();
  5143. self.unlock();
  5144. return true;
  5145. }
  5146. return !!self.ajaxAborted;
  5147. },
  5148. _resetFileStack: function () {
  5149. var self = this, i = 0;
  5150. self._getThumbs().each(function () {
  5151. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
  5152. if (ind === '-1' || ind === -1) {
  5153. return;
  5154. }
  5155. if (!self._getThumbFile($thumb)) {
  5156. $thumb.attr({'data-fileindex': i});
  5157. i++;
  5158. } else {
  5159. $thumb.attr({'data-fileindex': '-1'});
  5160. }
  5161. self._getZoom(pid).attr({
  5162. 'data-fileindex': $thumb.attr('data-fileindex')
  5163. });
  5164. });
  5165. },
  5166. _isFileSelectionValid: function (cnt) {
  5167. var self = this;
  5168. cnt = cnt || 0;
  5169. if (self.required && !self.getFilesCount()) {
  5170. self.$errorContainer.html('');
  5171. self._showFileError(self.msgFileRequired);
  5172. return false;
  5173. }
  5174. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  5175. self._noFilesError({});
  5176. return false;
  5177. }
  5178. return true;
  5179. },
  5180. _canPreview: function (file) {
  5181. var self = this;
  5182. if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
  5183. return false;
  5184. }
  5185. var name = file.name || '', type = file.type || '', size = (file.size || 0) / 1000,
  5186. cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
  5187. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  5188. exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
  5189. dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
  5190. maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
  5191. expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
  5192. expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
  5193. allowedTypes = !types || types.indexOf(cat) !== -1;
  5194. allowedMimes = !mimes || mimes.indexOf(type) !== -1;
  5195. allowedExts = !exts.length || $h.compare(name, expAllExt);
  5196. skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
  5197. (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
  5198. return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
  5199. },
  5200. addToStack: function (file, id) {
  5201. this.fileManager.add(file, id);
  5202. },
  5203. clearFileStack: function () {
  5204. var self = this;
  5205. self.fileManager.clear();
  5206. self._initResumableUpload();
  5207. if (self.enableResumableUpload) {
  5208. if (self.showPause === null) {
  5209. self.showPause = true;
  5210. }
  5211. if (self.showCancel === null) {
  5212. self.showCancel = false;
  5213. }
  5214. } else {
  5215. self.showPause = false;
  5216. if (self.showCancel === null) {
  5217. self.showCancel = true;
  5218. }
  5219. }
  5220. return self.$element;
  5221. },
  5222. getFileStack: function () {
  5223. return this.fileManager.stack;
  5224. },
  5225. getFileList: function () {
  5226. return this.fileManager.list();
  5227. },
  5228. getFilesSize: function () {
  5229. return this.fileManager.getTotalSize();
  5230. },
  5231. getFilesCount: function (includeInitial) {
  5232. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  5233. if (includeInitial) {
  5234. len += self.previewCache.count(true);
  5235. }
  5236. return self._getFileCount(len);
  5237. },
  5238. _initCapStatus: function (status) {
  5239. var self = this, $cap = self.$caption;
  5240. $cap.removeClass('is-valid file-processing');
  5241. if (!status) {
  5242. return;
  5243. }
  5244. if (status === 'processing') {
  5245. $cap.addClass('file-processing');
  5246. } else {
  5247. $cap.addClass('is-valid');
  5248. }
  5249. },
  5250. _setLoading: function (type) {
  5251. var self = this;
  5252. self.$previewStatus.html(type === 'hide' ? '' : self.msgProcessing);
  5253. self.$container.removeClass('file-thumb-loading');
  5254. self._initCapStatus(type === 'hide' ? '' : 'processing');
  5255. if (type !== 'hide') {
  5256. if (self.dropZoneEnabled) {
  5257. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  5258. }
  5259. self.$container.addClass('file-thumb-loading');
  5260. }
  5261. },
  5262. _initFileSelected: function () {
  5263. var self = this, $el = self.$element, $body = $(document.body), ev = 'focusin.fileinput focusout.fileinput';
  5264. if ($body.length) {
  5265. $body.off(ev).on('focusout.fileinput', function () {
  5266. self._setLoading('show');
  5267. }).on('focusin.fileinput', function () {
  5268. setTimeout(function () {
  5269. if (!$el.val()) {
  5270. self._setLoading('hide');
  5271. self._setFileDropZoneTitle();
  5272. }
  5273. $body.off(ev);
  5274. }, 2500);
  5275. });
  5276. } else {
  5277. self._setLoading('hide');
  5278. }
  5279. },
  5280. readFiles: function (files) {
  5281. this.reader = new FileReader();
  5282. var self = this, reader = self.reader, $container = self.$previewContainer,
  5283. $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress,
  5284. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  5285. readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  5286. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  5287. throwError = function (msg, file, previewId, index, fileId) {
  5288. var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
  5289. {id: previewId, index: index, fileId: fileId}),
  5290. p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
  5291. self._previewDefault(file, true);
  5292. $thumb = self._getFrame(previewId, true);
  5293. self._setLoading('hide');
  5294. if (self.isAjaxUpload) {
  5295. setTimeout(function () {
  5296. readFile(index + 1);
  5297. }, self.processDelay);
  5298. } else {
  5299. self.unlock();
  5300. numFiles = 0;
  5301. }
  5302. if (self.removeFromPreviewOnError && $thumb.length) {
  5303. $thumb.remove();
  5304. } else {
  5305. self._initFileActions();
  5306. $thumb.find('.kv-file-upload').remove();
  5307. }
  5308. self.isPersistentError = true;
  5309. self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
  5310. self._updateFileDetails(numFiles);
  5311. };
  5312. self.fileManager.clearImages();
  5313. $.each(files, function (key, file) {
  5314. var func = self.fileTypeSettings.image;
  5315. if (func && func(file.type)) {
  5316. self.fileManager.totalImages++;
  5317. }
  5318. });
  5319. readFile = function (i) {
  5320. var $error = self.$errorContainer, errors, fm = self.fileManager;
  5321. if (i >= numFiles) {
  5322. self.unlock();
  5323. if (self.duplicateErrors.length) {
  5324. errors = '<li>' + self.duplicateErrors.join('</li><li>') + '</li>';
  5325. if ($error.find('ul').length === 0) {
  5326. $h.setHtml($error, self.errorCloseButton + '<ul>' + errors + '</ul>');
  5327. } else {
  5328. $error.find('ul').append(errors);
  5329. }
  5330. $error.fadeIn(self.fadeDelay);
  5331. self._handler($error.find('.kv-error-close'), 'click', function () {
  5332. $error.fadeOut(self.fadeDelay);
  5333. });
  5334. self.duplicateErrors = [];
  5335. }
  5336. if (self.isAjaxUpload) {
  5337. self._raise('filebatchselected', [fm.stack]);
  5338. if (fm.count() === 0 && !self.isError) {
  5339. self.reset();
  5340. }
  5341. } else {
  5342. self._raise('filebatchselected', [files]);
  5343. }
  5344. $container.removeClass('file-thumb-loading');
  5345. self._initCapStatus('valid');
  5346. $status.html('');
  5347. return;
  5348. }
  5349. self.lock(true);
  5350. var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg,
  5351. fnImage = settings.image, typ, chk, typ1, typ2,
  5352. caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / 1000,
  5353. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  5354. strTypes = '', fileId, canLoad, fileReaderAborted = false,
  5355. func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () {
  5356. var isImageResized = !!fm.loadedImages[id], msg = msgProgress.setTokens({
  5357. 'index': i + 1,
  5358. 'files': numFiles,
  5359. 'percent': 50,
  5360. 'name': caption
  5361. });
  5362. setTimeout(function () {
  5363. $status.html(msg);
  5364. self._updateFileDetails(numFiles);
  5365. readFile(i + 1);
  5366. }, self.processDelay);
  5367. if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) {
  5368. if (!isImageResized) {
  5369. fm.add(file);
  5370. }
  5371. } else {
  5372. if (isImageResized) {
  5373. fm.removeFile(id);
  5374. }
  5375. }
  5376. };
  5377. if (!file) {
  5378. return;
  5379. }
  5380. fileId = fm.getId(file);
  5381. if (typLen > 0) {
  5382. for (j = 0; j < typLen; j++) {
  5383. typ1 = fileTypes[j];
  5384. typ2 = self.msgFileTypes[typ1] || typ1;
  5385. strTypes += j === 0 ? typ2 : ', ' + typ2;
  5386. }
  5387. }
  5388. if (caption === false) {
  5389. readFile(i + 1);
  5390. return;
  5391. }
  5392. if (caption.length === 0) {
  5393. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  5394. throwError(msg, file, previewId, i, fileId);
  5395. return;
  5396. }
  5397. if (!$h.isEmpty(fileExt)) {
  5398. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  5399. }
  5400. fSizeKB = fileSize.toFixed(2);
  5401. if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) {
  5402. var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files};
  5403. msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB});
  5404. if (self.isAjaxUpload) {
  5405. self.duplicateErrors.push(msg);
  5406. self.isDuplicateError = true;
  5407. self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]);
  5408. readFile(i + 1);
  5409. self._updateFileDetails(numFiles);
  5410. } else {
  5411. self._showError(msg, p2);
  5412. self.unlock();
  5413. numFiles = 0;
  5414. self._clearFileInput();
  5415. self.reset();
  5416. self._updateFileDetails(numFiles);
  5417. }
  5418. return;
  5419. }
  5420. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  5421. msg = self.msgSizeTooLarge.setTokens({
  5422. 'name': caption,
  5423. 'size': fSizeKB,
  5424. 'maxSize': self.maxFileSize
  5425. });
  5426. throwError(msg, file, previewId, i, fileId);
  5427. return;
  5428. }
  5429. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  5430. msg = self.msgSizeTooSmall.setTokens({
  5431. 'name': caption,
  5432. 'size': fSizeKB,
  5433. 'minSize': self.minFileSize
  5434. });
  5435. throwError(msg, file, previewId, i, fileId);
  5436. return;
  5437. }
  5438. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  5439. for (j = 0; j < fileTypes.length; j += 1) {
  5440. typ = fileTypes[j];
  5441. func = settings[typ];
  5442. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  5443. $h.getFileName(file)) ? 1 : 0);
  5444. }
  5445. if (fileCount === 0) {
  5446. msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
  5447. throwError(msg, file, previewId, i, fileId);
  5448. return;
  5449. }
  5450. }
  5451. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  5452. chk = $h.compare(caption, fileExtExpr);
  5453. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  5454. if (fileCount === 0) {
  5455. msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
  5456. throwError(msg, file, previewId, i, fileId);
  5457. return;
  5458. }
  5459. }
  5460. if (!self._canPreview(file)) {
  5461. canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]);
  5462. if (self.isAjaxUpload && canLoad) {
  5463. fm.add(file);
  5464. }
  5465. if (self.showPreview && canLoad) {
  5466. $container.addClass('file-thumb-loading');
  5467. self._initCapStatus('processing');
  5468. self._previewDefault(file);
  5469. self._initFileActions();
  5470. }
  5471. setTimeout(function () {
  5472. if (canLoad) {
  5473. self._updateFileDetails(numFiles);
  5474. }
  5475. readFile(i + 1);
  5476. self._raise('fileloaded', [file, previewId, id, i]);
  5477. }, 10);
  5478. return;
  5479. }
  5480. isImage = fnImage(file.type, caption);
  5481. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  5482. $container.addClass('file-thumb-loading');
  5483. self._initCapStatus('processing');
  5484. reader.onerror = function (evt) {
  5485. self._errorHandler(evt, caption);
  5486. };
  5487. reader.onload = function (theFile) {
  5488. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () {
  5489. var newReader = new FileReader();
  5490. newReader.onerror = function (theFileNew) {
  5491. self._errorHandler(theFileNew, caption);
  5492. };
  5493. newReader.onload = function (theFileNew) {
  5494. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5495. fileReaderAborted = true;
  5496. self._resetCaption();
  5497. reader.abort();
  5498. $status.html('');
  5499. $container.removeClass('file-thumb-loading');
  5500. self._initCapStatus('valid');
  5501. self.enable();
  5502. return;
  5503. }
  5504. self._previewFile(i, file, theFileNew, previewData, fileInfo);
  5505. self._initFileActions();
  5506. processFileLoaded();
  5507. };
  5508. newReader.readAsDataURL(file);
  5509. };
  5510. fileInfo = {'name': caption, 'type': file.type};
  5511. $.each(settings, function (k, f) {
  5512. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  5513. knownTypes++;
  5514. }
  5515. });
  5516. if (knownTypes === 0) { // auto detect mime types from content if no known file types detected
  5517. uint = new Uint8Array(theFile.target.result);
  5518. for (j = 0; j < uint.length; j++) {
  5519. byte = uint[j].toString(16);
  5520. bytes.push(byte);
  5521. }
  5522. hex = bytes.join('').toLowerCase().substring(0, 8);
  5523. mime = $h.getMimeType(hex, '', '');
  5524. if ($h.isEmpty(mime)) { // look for ascii text content
  5525. contents = $h.arrayBuffer2String(reader.result);
  5526. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  5527. }
  5528. fileInfo = {'name': caption, 'type': mime};
  5529. isImage = fnImage(mime, '');
  5530. if (isImage) {
  5531. readImage(txtFlag);
  5532. return;
  5533. }
  5534. }
  5535. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5536. fileReaderAborted = true;
  5537. self._resetCaption();
  5538. reader.abort();
  5539. $status.html('');
  5540. $container.removeClass('file-thumb-loading');
  5541. self._initCapStatus('valid');
  5542. self.enable();
  5543. return;
  5544. }
  5545. self._previewFile(i, file, theFile, previewData, fileInfo);
  5546. self._initFileActions();
  5547. processFileLoaded();
  5548. };
  5549. reader.onprogress = function (data) {
  5550. if (data.lengthComputable) {
  5551. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  5552. msg = msgProgress.setTokens({
  5553. 'index': i + 1,
  5554. 'files': numFiles,
  5555. 'percent': progress,
  5556. 'name': caption
  5557. });
  5558. setTimeout(function () {
  5559. if (!fileReaderAborted) {
  5560. $status.html(msg);
  5561. }
  5562. }, self.processDelay);
  5563. }
  5564. };
  5565. if (isImage) {
  5566. reader.readAsDataURL(file);
  5567. } else {
  5568. reader.readAsArrayBuffer(file);
  5569. }
  5570. };
  5571. readFile(0);
  5572. self._updateFileDetails(numFiles, true);
  5573. },
  5574. lock: function (selectMode) {
  5575. var self = this, $container = self.$container;
  5576. self._resetErrors();
  5577. self.disable();
  5578. if (!selectMode && self.showCancel) {
  5579. $container.find('.fileinput-cancel').show();
  5580. }
  5581. if (!selectMode && self.showPause) {
  5582. $container.find('.fileinput-pause').show();
  5583. }
  5584. self._initCapStatus('processing');
  5585. self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
  5586. return self.$element;
  5587. },
  5588. unlock: function (reset) {
  5589. var self = this, $container = self.$container;
  5590. if (reset === undefined) {
  5591. reset = true;
  5592. }
  5593. self.enable();
  5594. $container.removeClass('is-locked');
  5595. if (self.showCancel) {
  5596. $container.find('.fileinput-cancel').hide();
  5597. }
  5598. if (self.showPause) {
  5599. $container.find('.fileinput-pause').hide();
  5600. }
  5601. if (reset) {
  5602. self._resetFileStack();
  5603. }
  5604. self._initCapStatus();
  5605. self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
  5606. return self.$element;
  5607. },
  5608. resume: function () {
  5609. var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager;
  5610. fm.bpsLog = [];
  5611. fm.bps = 0;
  5612. if (!self.enableResumableUpload) {
  5613. return self.$element;
  5614. }
  5615. if (self.paused) {
  5616. self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume);
  5617. } else {
  5618. flag = true;
  5619. }
  5620. self.paused = false;
  5621. if (flag) {
  5622. self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin);
  5623. }
  5624. setTimeout(function () {
  5625. rm.upload();
  5626. }, self.processDelay);
  5627. return self.$element;
  5628. },
  5629. paste: function (e) {
  5630. var self = this, ev = e.originalEvent, files = ev.clipboardData && ev.clipboardData.files || null;
  5631. if (files) {
  5632. self._dropFiles(e, files);
  5633. }
  5634. return self.$element;
  5635. },
  5636. pause: function () {
  5637. var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
  5638. pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager,
  5639. pool = tm.getPool(rm.id);
  5640. if (!self.enableResumableUpload) {
  5641. return self.$element;
  5642. } else {
  5643. if (pool) {
  5644. pool.cancel();
  5645. }
  5646. }
  5647. self._raise('fileuploadpaused', [self.fileManager, rm]);
  5648. if (len > 0) {
  5649. for (i = 0; i < len; i += 1) {
  5650. self.paused = true;
  5651. xhr[i].abort();
  5652. }
  5653. }
  5654. if (self.showPreview) {
  5655. self._getThumbs().each(function () {
  5656. var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats,
  5657. $indicator = $thumb.find('.file-upload-indicator');
  5658. $thumb.removeClass('file-uploading');
  5659. if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
  5660. self._setThumbStatus($thumb, 'Paused');
  5661. stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
  5662. self.paused = true;
  5663. self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
  5664. }
  5665. if (!self._getThumbFile($thumb)) {
  5666. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5667. }
  5668. });
  5669. }
  5670. self._setProgress(101, self.$progress, self.msgPaused);
  5671. return self.$element;
  5672. },
  5673. cancel: function () {
  5674. var self = this, xhr = self.ajaxRequests,
  5675. rm = self.resumableManager, tm = self.taskManager,
  5676. pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i;
  5677. if (self.enableResumableUpload && pool) {
  5678. pool.cancel().done(function () {
  5679. self._setProgressCancelled();
  5680. });
  5681. rm.reset();
  5682. self._raise('fileuploadcancelled', [self.fileManager, rm]);
  5683. } else {
  5684. self._raise('fileuploadcancelled', [self.fileManager]);
  5685. }
  5686. self._initAjax();
  5687. if (len > 0) {
  5688. for (i = 0; i < len; i += 1) {
  5689. self.cancelling = true;
  5690. xhr[i].abort();
  5691. }
  5692. }
  5693. self._getThumbs().each(function () {
  5694. var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress');
  5695. $thumb.removeClass('file-uploading');
  5696. self._setProgress(0, $prog);
  5697. $prog.hide();
  5698. if (!self._getThumbFile($thumb)) {
  5699. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  5700. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5701. }
  5702. self.unlock();
  5703. });
  5704. setTimeout(function () {
  5705. self._setProgressCancelled();
  5706. }, self.processDelay);
  5707. return self.$element;
  5708. },
  5709. clear: function () {
  5710. var self = this, cap;
  5711. if (!self._raise('fileclear')) {
  5712. return;
  5713. }
  5714. self.$btnUpload.removeAttr('disabled');
  5715. self._getThumbs().find('video,audio,img').each(function () {
  5716. $h.cleanMemory($(this));
  5717. });
  5718. self._clearFileInput();
  5719. self._resetUpload();
  5720. self.clearFileStack();
  5721. self.isDuplicateError = false;
  5722. self.isPersistentError = false;
  5723. self._resetErrors(true);
  5724. if (self._hasInitialPreview()) {
  5725. self._showFileIcon();
  5726. self._resetPreview();
  5727. self._initPreviewActions();
  5728. self.$container.removeClass('file-input-new');
  5729. } else {
  5730. self._getThumbs().each(function () {
  5731. self._clearObjects($(this));
  5732. });
  5733. if (self.isAjaxUpload) {
  5734. self.previewCache.data = {};
  5735. }
  5736. self.$preview.html('');
  5737. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  5738. self.$caption.attr('title', '').val(cap);
  5739. $h.addCss(self.$container, 'file-input-new');
  5740. self._validateDefaultPreview();
  5741. }
  5742. if (self.$container.find($h.FRAMES).length === 0) {
  5743. if (!self._initCaption()) {
  5744. self.$captionContainer.removeClass('icon-visible');
  5745. }
  5746. }
  5747. self._hideFileIcon();
  5748. if (self.focusCaptionOnClear) {
  5749. self.$captionContainer.focus();
  5750. }
  5751. self._setFileDropZoneTitle();
  5752. self._raise('filecleared');
  5753. return self.$element;
  5754. },
  5755. reset: function () {
  5756. var self = this;
  5757. if (!self._raise('filereset')) {
  5758. return;
  5759. }
  5760. self.lastProgress = 0;
  5761. self._resetPreview();
  5762. self.$container.find('.fileinput-filename').text('');
  5763. $h.addCss(self.$container, 'file-input-new');
  5764. if (self.getFrames().length) {
  5765. self.$container.removeClass('file-input-new');
  5766. }
  5767. self.clearFileStack();
  5768. self._setFileDropZoneTitle();
  5769. return self.$element;
  5770. },
  5771. disable: function () {
  5772. var self = this, $container = self.$container;
  5773. self.isDisabled = true;
  5774. self._raise('filedisabled');
  5775. self.$element.attr('disabled', 'disabled');
  5776. $container.addClass('is-locked');
  5777. $h.addCss($container.find('.btn-file'), 'disabled');
  5778. $container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  5779. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5780. .attr('disabled', true);
  5781. self._initDragDrop();
  5782. return self.$element;
  5783. },
  5784. enable: function () {
  5785. var self = this, $container = self.$container;
  5786. self.isDisabled = false;
  5787. self._raise('fileenabled');
  5788. self.$element.removeAttr('disabled');
  5789. $container.removeClass('is-locked');
  5790. $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  5791. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5792. .removeAttr('disabled');
  5793. $container.find('.btn-file').removeClass('disabled');
  5794. self._initDragDrop();
  5795. return self.$element;
  5796. },
  5797. upload: function () {
  5798. var self = this, fm = self.fileManager, totLen = fm.count(), i, outData,
  5799. hasExtraData = !$.isEmptyObject(self._getExtraData());
  5800. fm.bpsLog = [];
  5801. fm.bps = 0;
  5802. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  5803. return;
  5804. }
  5805. self.lastProgress = 0;
  5806. self._resetUpload();
  5807. if (totLen === 0 && !hasExtraData) {
  5808. self._showFileError(self.msgUploadEmpty);
  5809. return;
  5810. }
  5811. self.cancelling = false;
  5812. self._showProgress();
  5813. self.lock();
  5814. if (totLen === 0 && hasExtraData) {
  5815. self._setProgress(2);
  5816. self._uploadExtraOnly();
  5817. return;
  5818. }
  5819. if (self.enableResumableUpload) {
  5820. return self.resume();
  5821. }
  5822. if (self.uploadAsync || self.enableResumableUpload) {
  5823. outData = self._getOutData(null);
  5824. if (!self._checkBatchPreupload(outData)) {
  5825. return;
  5826. }
  5827. self.fileBatchCompleted = false;
  5828. self.uploadCache = [];
  5829. $.each(self.getFileStack(), function (id) {
  5830. var previewId = self._getThumbId(id);
  5831. self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true});
  5832. });
  5833. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  5834. self._initSortable();
  5835. }
  5836. self._setProgress(2);
  5837. self.hasInitData = false;
  5838. if (self.uploadAsync) {
  5839. i = 0;
  5840. $.each(self.getFileStack(), function (id) {
  5841. self._uploadSingle(i, id, true);
  5842. i++;
  5843. });
  5844. return;
  5845. }
  5846. self._uploadBatch();
  5847. return self.$element;
  5848. },
  5849. destroy: function () {
  5850. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  5851. $(document).off(ns);
  5852. $(window).off(ns);
  5853. if ($form && $form.length) {
  5854. $form.off(ns);
  5855. }
  5856. if (self.isAjaxUpload) {
  5857. self._clearFileInput();
  5858. }
  5859. self._cleanup();
  5860. self._initPreviewCache();
  5861. $el.insertBefore($cont).off(ns).removeData();
  5862. $cont.off().remove();
  5863. return $el;
  5864. },
  5865. refresh: function (options) {
  5866. var self = this, $el = self.$element;
  5867. if (typeof options !== 'object' || $h.isEmpty(options)) {
  5868. options = self.options;
  5869. } else {
  5870. options = $.extend(true, {}, self.options, options);
  5871. }
  5872. self._init(options, true);
  5873. self._listen();
  5874. return $el;
  5875. },
  5876. zoom: function (frameId) {
  5877. var self = this, $frame = self._getFrame(frameId);
  5878. self._showModal($frame);
  5879. },
  5880. getExif: function (frameId) {
  5881. var self = this, $frame = self._getFrame(frameId);
  5882. return $frame && $frame.data('exif') || null;
  5883. },
  5884. getFrames: function (cssFilter) {
  5885. var self = this, $frames;
  5886. cssFilter = cssFilter || '';
  5887. $frames = self.$preview.find($h.FRAMES + cssFilter);
  5888. if (self.reversePreviewOrder) {
  5889. $frames = $($frames.get().reverse());
  5890. }
  5891. return $frames;
  5892. },
  5893. getPreview: function () {
  5894. var self = this;
  5895. return {
  5896. content: self.initialPreview,
  5897. config: self.initialPreviewConfig,
  5898. tags: self.initialPreviewThumbTags
  5899. };
  5900. }
  5901. };
  5902. $.fn.fileinput = function (option) {
  5903. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  5904. return;
  5905. }
  5906. var args = Array.apply(null, arguments), retvals = [];
  5907. args.shift();
  5908. this.each(function () {
  5909. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  5910. theme = options.theme || self.data('theme'), l = {}, t = {},
  5911. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  5912. if (!data) {
  5913. if (theme) {
  5914. t = $.fn.fileinputThemes[theme] || {};
  5915. }
  5916. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  5917. l = $.fn.fileinputLocales[lang] || {};
  5918. }
  5919. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  5920. data = new FileInput(this, opt);
  5921. self.data('fileinput', data);
  5922. }
  5923. if (typeof option === 'string') {
  5924. retvals.push(data[option].apply(data, args));
  5925. }
  5926. });
  5927. switch (retvals.length) {
  5928. case 0:
  5929. return this;
  5930. case 1:
  5931. return retvals[0];
  5932. default:
  5933. return retvals;
  5934. }
  5935. };
  5936. var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}',
  5937. defBtnCss1 = 'btn btn-sm btn-kv ' + $h.defaultButtonCss(), defBtnCss2 = 'btn ' + $h.defaultButtonCss(true);
  5938. $.fn.fileinput.defaults = {
  5939. language: 'en',
  5940. showCaption: true,
  5941. showBrowse: true,
  5942. showPreview: true,
  5943. showRemove: true,
  5944. showUpload: true,
  5945. showUploadStats: true,
  5946. showCancel: null,
  5947. showPause: null,
  5948. showClose: true,
  5949. showUploadedThumbs: true,
  5950. showConsoleLogs: false,
  5951. browseOnZoneClick: false,
  5952. autoReplace: false,
  5953. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  5954. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  5955. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  5956. return !iOSSafari;
  5957. },
  5958. autoOrientImageInitial: true,
  5959. required: false,
  5960. rtl: false,
  5961. hideThumbnailContent: false,
  5962. encodeUrl: true,
  5963. focusCaptionOnBrowse: true,
  5964. focusCaptionOnClear: true,
  5965. generateFileId: null,
  5966. previewClass: '',
  5967. captionClass: '',
  5968. frameClass: 'krajee-default',
  5969. mainClass: '',
  5970. inputGroupClass: '',
  5971. mainTemplate: null,
  5972. fileSizeGetter: null,
  5973. initialCaption: '',
  5974. initialPreview: [],
  5975. initialPreviewDelimiter: '*$$*',
  5976. initialPreviewAsData: false,
  5977. initialPreviewFileType: 'image',
  5978. initialPreviewConfig: [],
  5979. initialPreviewThumbTags: [],
  5980. previewThumbTags: {},
  5981. initialPreviewShowDelete: true,
  5982. initialPreviewDownloadUrl: '',
  5983. removeFromPreviewOnError: false,
  5984. deleteUrl: '',
  5985. deleteExtraData: {},
  5986. overwriteInitial: true,
  5987. sanitizeZoomCache: function (content) {
  5988. var $container = $h.createElement(content);
  5989. $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove();
  5990. return $container.html();
  5991. },
  5992. previewZoomButtonIcons: {
  5993. prev: '<i class="bi-chevron-left"></i>',
  5994. next: '<i class="bi-chevron-right"></i>',
  5995. toggleheader: '<i class="bi-arrows-expand"></i>',
  5996. fullscreen: '<i class="bi-arrows-fullscreen"></i>',
  5997. borderless: '<i class="bi-arrows-angle-expand"></i>',
  5998. close: '<i class="bi-x-lg"></i>'
  5999. },
  6000. previewZoomButtonClasses: {
  6001. prev: 'btn btn-navigate',
  6002. next: 'btn btn-navigate',
  6003. toggleheader: defBtnCss1,
  6004. fullscreen: defBtnCss1,
  6005. borderless: defBtnCss1,
  6006. close: defBtnCss1
  6007. },
  6008. previewTemplates: {},
  6009. previewContentTemplates: {},
  6010. preferIconicPreview: false,
  6011. preferIconicZoomPreview: false,
  6012. allowedFileTypes: null,
  6013. allowedFileExtensions: null,
  6014. allowedPreviewTypes: undefined,
  6015. allowedPreviewMimeTypes: null,
  6016. allowedPreviewExtensions: null,
  6017. disabledPreviewTypes: undefined,
  6018. disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
  6019. disabledPreviewMimeTypes: null,
  6020. defaultPreviewContent: null,
  6021. customLayoutTags: {},
  6022. customPreviewTags: {},
  6023. previewFileIcon: '<i class="bi-file-earmark-fill"></i>',
  6024. previewFileIconClass: 'file-other-icon',
  6025. previewFileIconSettings: {},
  6026. previewFileExtSettings: {},
  6027. buttonLabelClass: 'hidden-xs',
  6028. browseIcon: '<i class="bi-folder2-open"></i> ',
  6029. browseClass: 'btn btn-primary',
  6030. removeIcon: '<i class="bi-trash"></i>',
  6031. removeClass: defBtnCss2,
  6032. cancelIcon: '<i class="bi-slash-circle"></i>',
  6033. cancelClass: defBtnCss2,
  6034. pauseIcon: '<i class="bi-pause-fill"></i>',
  6035. pauseClass: defBtnCss2,
  6036. uploadIcon: '<i class="bi-upload"></i>',
  6037. uploadClass: defBtnCss2,
  6038. uploadUrl: null,
  6039. uploadUrlThumb: null,
  6040. uploadAsync: true,
  6041. uploadParamNames: {
  6042. chunkCount: 'chunkCount',
  6043. chunkIndex: 'chunkIndex',
  6044. chunkSize: 'chunkSize',
  6045. chunkSizeStart: 'chunkSizeStart',
  6046. chunksUploaded: 'chunksUploaded',
  6047. fileBlob: 'fileBlob',
  6048. fileId: 'fileId',
  6049. fileName: 'fileName',
  6050. fileRelativePath: 'fileRelativePath',
  6051. fileSize: 'fileSize',
  6052. retryCount: 'retryCount'
  6053. },
  6054. maxAjaxThreads: 5,
  6055. fadeDelay: 800,
  6056. processDelay: 100,
  6057. bitrateUpdateDelay: 500,
  6058. queueDelay: 10, // must be lesser than process delay
  6059. progressDelay: 0, // must be lesser than process delay
  6060. enableResumableUpload: false,
  6061. resumableUploadOptions: {
  6062. fallback: null,
  6063. testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
  6064. chunkSize: 2 * 1024, // in KB
  6065. maxThreads: 4,
  6066. maxRetries: 3,
  6067. showErrorLog: true,
  6068. retainErrorHistory: true, // display complete error history always unless user explicitly resets upload
  6069. skipErrorsAndProceed: false // when set to true, files with errors will be skipped and upload will continue with other files
  6070. },
  6071. uploadExtraData: {},
  6072. zoomModalHeight: 480,
  6073. minImageWidth: null,
  6074. minImageHeight: null,
  6075. maxImageWidth: null,
  6076. maxImageHeight: null,
  6077. resizeImage: false,
  6078. resizePreference: 'width',
  6079. resizeQuality: 0.92,
  6080. resizeDefaultImageType: 'image/jpeg',
  6081. resizeIfSizeMoreThan: 0, // in KB
  6082. minFileSize: -1,
  6083. maxFileSize: 0,
  6084. maxFilePreviewSize: 25600, // 25 MB
  6085. minFileCount: 0,
  6086. maxFileCount: 0,
  6087. maxTotalFileCount: 0,
  6088. validateInitialCount: false,
  6089. msgValidationErrorClass: 'text-danger',
  6090. msgValidationErrorIcon: '<i class="bi-exclamation-circle-fill"></i> ',
  6091. msgErrorClass: 'file-error-message',
  6092. progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated',
  6093. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated',
  6094. progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated',
  6095. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  6096. progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated',
  6097. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  6098. progressUploadThreshold: 99,
  6099. previewFileType: 'image',
  6100. elCaptionContainer: null,
  6101. elCaptionText: null,
  6102. elPreviewContainer: null,
  6103. elPreviewImage: null,
  6104. elPreviewStatus: null,
  6105. elErrorContainer: null,
  6106. errorCloseButton: undefined,
  6107. slugCallback: null,
  6108. dropZoneEnabled: true,
  6109. dropZoneTitleClass: 'file-drop-zone-title',
  6110. fileActionSettings: {},
  6111. otherActionButtons: '',
  6112. textEncoding: 'UTF-8',
  6113. preProcessUpload: null,
  6114. ajaxSettings: {},
  6115. ajaxDeleteSettings: {},
  6116. showAjaxErrorDetails: true,
  6117. mergeAjaxCallbacks: false,
  6118. mergeAjaxDeleteCallbacks: false,
  6119. retryErrorUploads: true,
  6120. reversePreviewOrder: false,
  6121. usePdfRenderer: function () {
  6122. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  6123. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  6124. },
  6125. pdfRendererUrl: '',
  6126. pdfRendererTemplate: '<iframe ' + IFRAME_ATTRIBS + '></iframe>',
  6127. tabIndexConfig: {
  6128. browse: 500,
  6129. remove: 500,
  6130. upload: 500,
  6131. cancel: null,
  6132. pause: null,
  6133. modal: -1
  6134. }
  6135. };
  6136. // noinspection HtmlUnknownAttribute
  6137. $.fn.fileinputLocales.en = {
  6138. fileSingle: 'file',
  6139. filePlural: 'files',
  6140. browseLabel: 'Browse &hellip;',
  6141. removeLabel: 'Remove',
  6142. removeTitle: 'Clear all unprocessed files',
  6143. cancelLabel: 'Cancel',
  6144. cancelTitle: 'Abort ongoing upload',
  6145. pauseLabel: 'Pause',
  6146. pauseTitle: 'Pause ongoing upload',
  6147. uploadLabel: 'Upload',
  6148. uploadTitle: 'Upload selected files',
  6149. msgNo: 'No',
  6150. msgNoFilesSelected: 'No files selected',
  6151. msgCancelled: 'Cancelled',
  6152. msgPaused: 'Paused',
  6153. msgPlaceholder: 'Select {files} ...',
  6154. msgZoomModalHeading: 'Detailed Preview',
  6155. msgFileRequired: 'You must select a file to upload.',
  6156. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  6157. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  6158. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  6159. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  6160. msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
  6161. msgFileNotFound: 'File "{name}" not found!',
  6162. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  6163. msgFileNotReadable: 'File "{name}" is not readable.',
  6164. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  6165. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  6166. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  6167. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  6168. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  6169. msgFileTypes: {
  6170. 'image': 'image',
  6171. 'html': 'HTML',
  6172. 'text': 'text',
  6173. 'video': 'video',
  6174. 'audio': 'audio',
  6175. 'flash': 'flash',
  6176. 'pdf': 'PDF',
  6177. 'object': 'object'
  6178. },
  6179. msgUploadAborted: 'The file upload was aborted',
  6180. msgUploadThreshold: 'Processing &hellip;',
  6181. msgUploadBegin: 'Initializing &hellip;',
  6182. msgUploadEnd: 'Done',
  6183. msgUploadResume: 'Resuming upload &hellip;',
  6184. msgUploadEmpty: 'No valid data available for upload.',
  6185. msgUploadError: 'Upload Error',
  6186. msgDeleteError: 'Delete Error',
  6187. msgProgressError: 'Error',
  6188. msgValidationError: 'Validation Error',
  6189. msgLoading: 'Loading file {index} of {files} &hellip;',
  6190. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  6191. msgSelected: '{n} {files} selected',
  6192. msgProcessing: 'Processing ...',
  6193. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  6194. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  6195. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  6196. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  6197. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  6198. msgImageResizeError: 'Could not get the image dimensions to resize.',
  6199. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  6200. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  6201. msgAjaxProgressError: '{operation} failed',
  6202. msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
  6203. msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
  6204. msgPendingTime: '{time} remaining',
  6205. msgCalculatingTime: 'calculating time remaining',
  6206. ajaxOperations: {
  6207. deleteThumb: 'file delete',
  6208. uploadThumb: 'file upload',
  6209. uploadBatch: 'batch file upload',
  6210. uploadExtra: 'form data upload'
  6211. },
  6212. dropZoneTitle: 'Drag & drop files here &hellip;',
  6213. dropZoneClickTitle: '<br>(or click to select {files})',
  6214. previewZoomButtonTitles: {
  6215. prev: 'View previous file',
  6216. next: 'View next file',
  6217. toggleheader: 'Toggle header',
  6218. fullscreen: 'Toggle full screen',
  6219. borderless: 'Toggle borderless mode',
  6220. close: 'Close detailed preview'
  6221. }
  6222. };
  6223. $.fn.fileinput.Constructor = FileInput;
  6224. /**
  6225. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  6226. */
  6227. $(document).ready(function () {
  6228. var $input = $('input.file[type=file]');
  6229. if ($input.length) {
  6230. $input.fileinput();
  6231. }
  6232. });
  6233. }));