fileinput.js 276 KB

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