fileinput.js 299 KB

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