fileinput.js 285 KB

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