fileinput.js 276 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089
  1. /*!
  2. * bootstrap-fileinput v5.1.4
  3. * http://plugins.krajee.com/file-input
  4. *
  5. * Author: Kartik Visweswaran
  6. * Copyright: 2014 - 2020, 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.fileManager.stack, 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.fileManager.stack, 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(fm.stack, 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. var $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless');
  2790. if ($modal.data('fileinputPluginId') === self.$element.attr('id')) {
  2791. self._raise('filezoom' + event, getParams(e));
  2792. }
  2793. if (event === 'shown') {
  2794. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2795. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2796. if ($modal.hasClass('file-zoom-fullscreen')) {
  2797. self._maximizeZoomDialog();
  2798. if ($h.checkFullScreen()) {
  2799. $btnFull.addClass('active').attr('aria-pressed', 'true');
  2800. } else {
  2801. $btnBord.addClass('active').attr('aria-pressed', 'true');
  2802. }
  2803. }
  2804. }
  2805. });
  2806. },
  2807. _initZoom: function () {
  2808. var self = this, $dialog, modalMain = self._getLayoutTemplate('modalMain'), modalId = '#' + $h.MODAL_ID;
  2809. if (!self.showPreview) {
  2810. return;
  2811. }
  2812. self.$modal = $(modalId);
  2813. if (!self.$modal || !self.$modal.length) {
  2814. $dialog = $h.createElement($h.cspBuffer.stash(modalMain)).insertAfter(self.$container);
  2815. self.$modal = $(modalId).insertBefore($dialog);
  2816. $h.cspBuffer.apply(self.$modal);
  2817. $dialog.remove();
  2818. }
  2819. $h.initModal(self.$modal);
  2820. self.$modal.html($h.cspBuffer.stash(self._getModalContent()));
  2821. $h.cspBuffer.apply(self.$modal);
  2822. $.each($h.MODAL_EVENTS, function (key, event) {
  2823. self._listenModalEvent(event);
  2824. });
  2825. },
  2826. _initZoomButtons: function () {
  2827. var self = this, previewId = self.$modal.data('previewId') || '', $first, $last,
  2828. thumbs = self.getFrames().toArray(), len = thumbs.length, $prev = self.$modal.find('.btn-prev'),
  2829. $next = self.$modal.find('.btn-next');
  2830. if (thumbs.length < 2) {
  2831. $prev.hide();
  2832. $next.hide();
  2833. return;
  2834. } else {
  2835. $prev.show();
  2836. $next.show();
  2837. }
  2838. if (!len) {
  2839. return;
  2840. }
  2841. $first = $(thumbs[0]);
  2842. $last = $(thumbs[len - 1]);
  2843. $prev.removeAttr('disabled');
  2844. $next.removeAttr('disabled');
  2845. if ($first.length && $first.attr('id') === previewId) {
  2846. $prev.attr('disabled', true);
  2847. }
  2848. if ($last.length && $last.attr('id') === previewId) {
  2849. $next.attr('disabled', true);
  2850. }
  2851. },
  2852. _maximizeZoomDialog: function () {
  2853. var self = this, $modal = self.$modal, $head = $modal.find('.modal-header:visible'),
  2854. $foot = $modal.find('.modal-footer:visible'), $body = $modal.find('.modal-body'),
  2855. h = $(window).height(), diff = 0;
  2856. $modal.addClass('file-zoom-fullscreen');
  2857. if ($head && $head.length) {
  2858. h -= $head.outerHeight(true);
  2859. }
  2860. if ($foot && $foot.length) {
  2861. h -= $foot.outerHeight(true);
  2862. }
  2863. if ($body && $body.length) {
  2864. diff = $body.outerHeight(true) - $body.height();
  2865. h -= diff;
  2866. }
  2867. $modal.find('.kv-zoom-body').height(h);
  2868. },
  2869. _resizeZoomDialog: function (fullScreen) {
  2870. var self = this, $modal = self.$modal, $btnFull = $modal.find('.btn-fullscreen'),
  2871. $btnBord = $modal.find('.btn-borderless');
  2872. if ($modal.hasClass('file-zoom-fullscreen')) {
  2873. $h.toggleFullScreen(false);
  2874. if (!fullScreen) {
  2875. if (!$btnFull.hasClass('active')) {
  2876. $modal.removeClass('file-zoom-fullscreen');
  2877. self.$modal.find('.kv-zoom-body').css('height', self.zoomModalHeight);
  2878. } else {
  2879. $btnFull.removeClass('active').attr('aria-pressed', 'false');
  2880. }
  2881. } else {
  2882. if (!$btnFull.hasClass('active')) {
  2883. $modal.removeClass('file-zoom-fullscreen');
  2884. self._resizeZoomDialog(true);
  2885. if ($btnBord.hasClass('active')) {
  2886. $btnBord.removeClass('active').attr('aria-pressed', 'false');
  2887. }
  2888. }
  2889. }
  2890. } else {
  2891. if (!fullScreen) {
  2892. self._maximizeZoomDialog();
  2893. return;
  2894. }
  2895. $h.toggleFullScreen(true);
  2896. }
  2897. $modal.focus();
  2898. },
  2899. _setZoomContent: function ($frame, animate) {
  2900. var self = this, $content, tmplt, body, title, $body, $dataEl, config, previewId = $frame.attr('id'),
  2901. $zoomPreview = self._getZoom(previewId), $modal = self.$modal, $tmp,
  2902. $btnFull = $modal.find('.btn-fullscreen'), $btnBord = $modal.find('.btn-borderless'), cap, size,
  2903. $btnTogh = $modal.find('.btn-toggleheader');
  2904. tmplt = $zoomPreview.attr('data-template') || 'generic';
  2905. $content = $zoomPreview.find('.kv-file-content');
  2906. body = $content.length ? $content.html() : '';
  2907. cap = $frame.data('caption') || '';
  2908. size = $frame.data('size') || '';
  2909. title = cap + ' ' + size;
  2910. $modal.find('.kv-zoom-title').attr('title', $('<div/>').html(title).text()).html(title);
  2911. $body = $modal.find('.kv-zoom-body');
  2912. $modal.removeClass('kv-single-content');
  2913. if (animate) {
  2914. $tmp = $body.addClass('file-thumb-loading').clone().insertAfter($body);
  2915. $h.setHtml($body, body).hide();
  2916. $tmp.fadeOut('fast', function () {
  2917. $body.fadeIn('fast', function () {
  2918. $body.removeClass('file-thumb-loading');
  2919. });
  2920. $tmp.remove();
  2921. });
  2922. } else {
  2923. $h.setHtml($body, body);
  2924. }
  2925. config = self.previewZoomSettings[tmplt];
  2926. if (config) {
  2927. $dataEl = $body.find('.kv-preview-data');
  2928. $h.addCss($dataEl, 'file-zoom-detail');
  2929. $.each(config, function (key, value) {
  2930. $dataEl.css(key, value);
  2931. if (($dataEl.attr('width') && key === 'width') || ($dataEl.attr('height') && key === 'height')) {
  2932. $dataEl.removeAttr(key);
  2933. }
  2934. });
  2935. }
  2936. $modal.data('previewId', previewId);
  2937. self._handler($modal.find('.btn-prev'), 'click', function () {
  2938. self._zoomSlideShow('prev', previewId);
  2939. });
  2940. self._handler($modal.find('.btn-next'), 'click', function () {
  2941. self._zoomSlideShow('next', previewId);
  2942. });
  2943. self._handler($btnFull, 'click', function () {
  2944. self._resizeZoomDialog(true);
  2945. });
  2946. self._handler($btnBord, 'click', function () {
  2947. self._resizeZoomDialog(false);
  2948. });
  2949. self._handler($btnTogh, 'click', function () {
  2950. var $header = $modal.find('.modal-header'), $floatBar = $modal.find('.modal-body .floating-buttons'),
  2951. ht, $actions = $header.find('.kv-zoom-actions'), resize = function (height) {
  2952. var $body = self.$modal.find('.kv-zoom-body'), h = self.zoomModalHeight;
  2953. if ($modal.hasClass('file-zoom-fullscreen')) {
  2954. h = $body.outerHeight(true);
  2955. if (!height) {
  2956. h = h - $header.outerHeight(true);
  2957. }
  2958. }
  2959. $body.css('height', height ? h + height : h);
  2960. };
  2961. if ($header.is(':visible')) {
  2962. ht = $header.outerHeight(true);
  2963. $header.slideUp('slow', function () {
  2964. $actions.find('.btn').appendTo($floatBar);
  2965. resize(ht);
  2966. });
  2967. } else {
  2968. $floatBar.find('.btn').appendTo($actions);
  2969. $header.slideDown('slow', function () {
  2970. resize();
  2971. });
  2972. }
  2973. $modal.focus();
  2974. });
  2975. self._handler($modal, 'keydown', function (e) {
  2976. var key = e.which || e.keyCode, $prev = $(this).find('.btn-prev'), $next = $(this).find('.btn-next'),
  2977. vId = $(this).data('previewId'), vPrevKey = self.rtl ? 39 : 37, vNextKey = self.rtl ? 37 : 39;
  2978. if (key === vPrevKey && $prev.length && !$prev.attr('disabled')) {
  2979. self._zoomSlideShow('prev', vId);
  2980. }
  2981. if (key === vNextKey && $next.length && !$next.attr('disabled')) {
  2982. self._zoomSlideShow('next', vId);
  2983. }
  2984. });
  2985. },
  2986. _showModal: function ($frame) {
  2987. var self = this, $modal = self.$modal;
  2988. if (!$frame || !$frame.length) {
  2989. return;
  2990. }
  2991. $h.initModal($modal);
  2992. $h.setHtml($modal, self._getModalContent());
  2993. self._setZoomContent($frame);
  2994. $modal.data('fileinputPluginId', self.$element.attr('id'));
  2995. $modal.modal('show');
  2996. self._initZoomButtons();
  2997. },
  2998. _zoomPreview: function ($btn) {
  2999. var self = this, $frame;
  3000. if (!$btn.length) {
  3001. throw 'Cannot zoom to detailed preview!';
  3002. }
  3003. $frame = $btn.closest($h.FRAMES);
  3004. self._showModal($frame);
  3005. },
  3006. _zoomSlideShow: function (dir, previewId) {
  3007. var self = this, $btn = self.$modal.find('.kv-zoom-actions .btn-' + dir), $targFrame, i, $thumb,
  3008. thumbsData = self.getFrames().toArray(), thumbs = [], len = thumbsData.length, out;
  3009. if ($btn.attr('disabled')) {
  3010. return;
  3011. }
  3012. for (i = 0; i < len; i++) {
  3013. $thumb = $(thumbsData[i]);
  3014. if ($thumb && $thumb.length && $thumb.find('.kv-file-zoom:visible').length) {
  3015. thumbs.push(thumbsData[i]);
  3016. }
  3017. }
  3018. len = thumbs.length;
  3019. for (i = 0; i < len; i++) {
  3020. if ($(thumbs[i]).attr('id') === previewId) {
  3021. out = dir === 'prev' ? i - 1 : i + 1;
  3022. break;
  3023. }
  3024. }
  3025. if (out < 0 || out >= len || !thumbs[out]) {
  3026. return;
  3027. }
  3028. $targFrame = $(thumbs[out]);
  3029. if ($targFrame.length) {
  3030. self._setZoomContent($targFrame, true);
  3031. }
  3032. self._initZoomButtons();
  3033. self._raise('filezoom' + dir, {'previewId': previewId, modal: self.$modal});
  3034. },
  3035. _initZoomButton: function () {
  3036. var self = this;
  3037. self.$preview.find('.kv-file-zoom').each(function () {
  3038. var $el = $(this);
  3039. self._handler($el, 'click', function () {
  3040. self._zoomPreview($el);
  3041. });
  3042. });
  3043. },
  3044. _inputFileCount: function () {
  3045. return this.$element[0].files.length;
  3046. },
  3047. _refreshPreview: function () {
  3048. var self = this, files;
  3049. if ((!self._inputFileCount() && !self.isAjaxUpload) || !self.showPreview || !self.isPreviewable) {
  3050. return;
  3051. }
  3052. if (self.isAjaxUpload) {
  3053. if (self.fileManager.count() > 0) {
  3054. files = $.extend(true, {}, self.fileManager.stack);
  3055. self.fileManager.clear();
  3056. self._clearFileInput();
  3057. } else {
  3058. files = self.$element[0].files;
  3059. }
  3060. } else {
  3061. files = self.$element[0].files;
  3062. }
  3063. if (files && files.length) {
  3064. self.readFiles(files);
  3065. self._setFileDropZoneTitle();
  3066. }
  3067. },
  3068. _clearObjects: function ($el) {
  3069. $el.find('video audio').each(function () {
  3070. this.pause();
  3071. $(this).remove();
  3072. });
  3073. $el.find('img object div').each(function () {
  3074. $(this).remove();
  3075. });
  3076. },
  3077. _clearFileInput: function () {
  3078. var self = this, $el = self.$element, $srcFrm, $tmpFrm, $tmpEl;
  3079. if (!self._inputFileCount()) {
  3080. return;
  3081. }
  3082. $srcFrm = $el.closest('form');
  3083. $tmpFrm = $(document.createElement('form'));
  3084. $tmpEl = $(document.createElement('div'));
  3085. $el.before($tmpEl);
  3086. if ($srcFrm.length) {
  3087. $srcFrm.after($tmpFrm);
  3088. } else {
  3089. $tmpEl.after($tmpFrm);
  3090. }
  3091. $tmpFrm.append($el).trigger('reset');
  3092. $tmpEl.before($el).remove();
  3093. $tmpFrm.remove();
  3094. },
  3095. _resetUpload: function () {
  3096. var self = this;
  3097. self.uploadStartTime = $h.now();
  3098. self.uploadCache = [];
  3099. self.$btnUpload.removeAttr('disabled');
  3100. self._setProgress(0);
  3101. self._hideProgress();
  3102. self._resetErrors(false);
  3103. self._initAjax();
  3104. self.fileManager.clearImages();
  3105. self._resetCanvas();
  3106. if (self.overwriteInitial) {
  3107. self.initialPreview = [];
  3108. self.initialPreviewConfig = [];
  3109. self.initialPreviewThumbTags = [];
  3110. self.previewCache.data = {
  3111. content: [],
  3112. config: [],
  3113. tags: []
  3114. };
  3115. }
  3116. },
  3117. _resetCanvas: function () {
  3118. var self = this;
  3119. if (self.canvas && self.imageCanvasContext) {
  3120. self.imageCanvasContext.clearRect(0, 0, self.canvas.width, self.canvas.height);
  3121. }
  3122. },
  3123. _hasInitialPreview: function () {
  3124. var self = this;
  3125. return !self.overwriteInitial && self.previewCache.count(true);
  3126. },
  3127. _resetPreview: function () {
  3128. var self = this, out, cap, $div, hasSuc = self.showUploadedThumbs, hasErr = !self.removeFromPreviewOnError,
  3129. includeProcessed = (hasSuc || hasErr) && self.isDuplicateError;
  3130. if (self.previewCache.count(true)) {
  3131. out = self.previewCache.out();
  3132. if (includeProcessed) {
  3133. $div = $h.createElement('').insertAfter(self.$container);
  3134. self.getFrames().each(function () {
  3135. var $thumb = $(this);
  3136. if ((hasSuc && $thumb.hasClass('file-preview-success')) ||
  3137. (hasErr && $thumb.hasClass('file-preview-error'))) {
  3138. $div.append($thumb);
  3139. }
  3140. });
  3141. }
  3142. self._setPreviewContent(out.content);
  3143. self._setInitThumbAttr();
  3144. cap = self.initialCaption ? self.initialCaption : out.caption;
  3145. self._setCaption(cap);
  3146. if (includeProcessed) {
  3147. $div.contents().appendTo(self.$preview);
  3148. $div.remove();
  3149. }
  3150. } else {
  3151. self._clearPreview();
  3152. self._initCaption();
  3153. }
  3154. if (self.showPreview) {
  3155. self._initZoom();
  3156. self._initSortable();
  3157. }
  3158. self.isDuplicateError = false;
  3159. },
  3160. _clearDefaultPreview: function () {
  3161. var self = this;
  3162. self.$preview.find('.file-default-preview').remove();
  3163. },
  3164. _validateDefaultPreview: function () {
  3165. var self = this;
  3166. if (!self.showPreview || $h.isEmpty(self.defaultPreviewContent)) {
  3167. return;
  3168. }
  3169. self._setPreviewContent('<div class="file-default-preview">' + self.defaultPreviewContent + '</div>');
  3170. self.$container.removeClass('file-input-new');
  3171. self._initClickable();
  3172. },
  3173. _resetPreviewThumbs: function (isAjax) {
  3174. var self = this, out;
  3175. if (isAjax) {
  3176. self._clearPreview();
  3177. self.clearFileStack();
  3178. return;
  3179. }
  3180. if (self._hasInitialPreview()) {
  3181. out = self.previewCache.out();
  3182. self._setPreviewContent(out.content);
  3183. self._setInitThumbAttr();
  3184. self._setCaption(out.caption);
  3185. self._initPreviewActions();
  3186. } else {
  3187. self._clearPreview();
  3188. }
  3189. },
  3190. _getLayoutTemplate: function (t) {
  3191. var self = this, template = self.layoutTemplates[t];
  3192. if ($h.isEmpty(self.customLayoutTags)) {
  3193. return template;
  3194. }
  3195. return $h.replaceTags(template, self.customLayoutTags);
  3196. },
  3197. _getPreviewTemplate: function (t) {
  3198. var self = this, templates = self.previewTemplates, template = templates[t] || templates.other;
  3199. if ($h.isEmpty(self.customPreviewTags)) {
  3200. return template;
  3201. }
  3202. return $h.replaceTags(template, self.customPreviewTags);
  3203. },
  3204. _getOutData: function (formdata, jqXHR, responseData, filesData) {
  3205. var self = this;
  3206. jqXHR = jqXHR || {};
  3207. responseData = responseData || {};
  3208. filesData = filesData || self.fileManager.list();
  3209. return {
  3210. formdata: formdata,
  3211. files: filesData,
  3212. filenames: self.filenames,
  3213. filescount: self.getFilesCount(),
  3214. extra: self._getExtraData(),
  3215. response: responseData,
  3216. reader: self.reader,
  3217. jqXHR: jqXHR
  3218. };
  3219. },
  3220. _getMsgSelected: function (n) {
  3221. var self = this, strFiles = n === 1 ? self.fileSingle : self.filePlural;
  3222. return n > 0 ? self.msgSelected.replace('{n}', n).replace('{files}', strFiles) : self.msgNoFilesSelected;
  3223. },
  3224. _getFrame: function (id, skipWarning) {
  3225. var self = this, $frame = $h.getFrameElement(self.$preview, id);
  3226. if (self.showPreview && !skipWarning && !$frame.length) {
  3227. self._log($h.logMessages.invalidThumb, {id: id});
  3228. }
  3229. return $frame;
  3230. },
  3231. _getZoom: function (id, selector) {
  3232. var self = this, $frame = $h.getZoomElement(self.$preview, id, selector);
  3233. if (self.showPreview && !$frame.length) {
  3234. self._log($h.logMessages.invalidThumb, {id: id});
  3235. }
  3236. return $frame;
  3237. },
  3238. _getThumbs: function (css) {
  3239. css = css || '';
  3240. return this.getFrames(':not(.file-preview-initial)' + css);
  3241. },
  3242. _getThumbId: function (fileId) {
  3243. var self = this;
  3244. return self.previewInitId + '-' + fileId;
  3245. },
  3246. _getExtraData: function (fileId, index) {
  3247. var self = this, data = self.uploadExtraData;
  3248. if (typeof self.uploadExtraData === 'function') {
  3249. data = self.uploadExtraData(fileId, index);
  3250. }
  3251. return data;
  3252. },
  3253. _initXhr: function (xhrobj, fileId) {
  3254. var self = this, fm = self.fileManager, func = function (event) {
  3255. var pct = 0, total = event.total, loaded = event.loaded || event.position,
  3256. stats = fm.getUploadStats(fileId, loaded, total);
  3257. /** @namespace event.lengthComputable */
  3258. if (event.lengthComputable && !self.enableResumableUpload) {
  3259. pct = $h.round(loaded / total * 100);
  3260. }
  3261. if (fileId) {
  3262. self._setFileUploadStats(fileId, pct, stats);
  3263. } else {
  3264. self._setProgress(pct, null, null, self._getStats(stats));
  3265. }
  3266. self._raise('fileajaxprogress', [stats]);
  3267. };
  3268. if (xhrobj.upload) {
  3269. if (self.progressDelay) {
  3270. func = $h.debounce(func, self.progressDelay);
  3271. }
  3272. xhrobj.upload.addEventListener('progress', func, false);
  3273. }
  3274. return xhrobj;
  3275. },
  3276. _initAjaxSettings: function () {
  3277. var self = this;
  3278. self._ajaxSettings = $.extend(true, {}, self.ajaxSettings);
  3279. self._ajaxDeleteSettings = $.extend(true, {}, self.ajaxDeleteSettings);
  3280. },
  3281. _mergeAjaxCallback: function (funcName, srcFunc, type) {
  3282. var self = this, settings = self._ajaxSettings, flag = self.mergeAjaxCallbacks, targFunc;
  3283. if (type === 'delete') {
  3284. settings = self._ajaxDeleteSettings;
  3285. flag = self.mergeAjaxDeleteCallbacks;
  3286. }
  3287. targFunc = settings[funcName];
  3288. if (flag && typeof targFunc === 'function') {
  3289. if (flag === 'before') {
  3290. settings[funcName] = function () {
  3291. targFunc.apply(this, arguments);
  3292. srcFunc.apply(this, arguments);
  3293. };
  3294. } else {
  3295. settings[funcName] = function () {
  3296. srcFunc.apply(this, arguments);
  3297. targFunc.apply(this, arguments);
  3298. };
  3299. }
  3300. } else {
  3301. settings[funcName] = srcFunc;
  3302. }
  3303. },
  3304. _ajaxSubmit: function (fnBefore, fnSuccess, fnComplete, fnError, formdata, fileId, index, vUrl) {
  3305. var self = this, settings, defaults, data, ajaxTask;
  3306. if (!self._raise('filepreajax', [formdata, fileId, index])) {
  3307. return;
  3308. }
  3309. formdata.append('initialPreview', JSON.stringify(self.initialPreview));
  3310. formdata.append('initialPreviewConfig', JSON.stringify(self.initialPreviewConfig));
  3311. formdata.append('initialPreviewThumbTags', JSON.stringify(self.initialPreviewThumbTags));
  3312. self._initAjaxSettings();
  3313. self._mergeAjaxCallback('beforeSend', fnBefore);
  3314. self._mergeAjaxCallback('success', fnSuccess);
  3315. self._mergeAjaxCallback('complete', fnComplete);
  3316. self._mergeAjaxCallback('error', fnError);
  3317. vUrl = vUrl || self.uploadUrlThumb || self.uploadUrl;
  3318. if (typeof vUrl === 'function') {
  3319. vUrl = vUrl();
  3320. }
  3321. data = self._getExtraData(fileId, index) || {};
  3322. if (typeof data === 'object') {
  3323. $.each(data, function (key, value) {
  3324. formdata.append(key, value);
  3325. });
  3326. }
  3327. defaults = {
  3328. xhr: function () {
  3329. var xhrobj = $.ajaxSettings.xhr();
  3330. return self._initXhr(xhrobj, fileId);
  3331. },
  3332. url: self._encodeURI(vUrl),
  3333. type: 'POST',
  3334. dataType: 'json',
  3335. data: formdata,
  3336. cache: false,
  3337. processData: false,
  3338. contentType: false
  3339. };
  3340. settings = $.extend(true, {}, defaults, self._ajaxSettings);
  3341. ajaxTask = self.taskManager.addTask(fileId + '-' + index, function () {
  3342. var self = this.self, config, xhr;
  3343. config = self.ajaxQueue.shift();
  3344. xhr = $.ajax(config);
  3345. self.ajaxRequests.push(xhr);
  3346. });
  3347. self.ajaxQueue.push(settings);
  3348. ajaxTask.runWithContext({self: self});
  3349. },
  3350. _mergeArray: function (prop, content) {
  3351. var self = this, arr1 = $h.cleanArray(self[prop]), arr2 = $h.cleanArray(content);
  3352. self[prop] = arr1.concat(arr2);
  3353. },
  3354. _initUploadSuccess: function (out, $thumb, allFiles) {
  3355. var self = this, append, data, index, $div, $newCache, content, config, tags, id, i;
  3356. if (!self.showPreview || typeof out !== 'object' || $.isEmptyObject(out)) {
  3357. self._resetCaption();
  3358. return;
  3359. }
  3360. if (out.initialPreview !== undefined && out.initialPreview.length > 0) {
  3361. self.hasInitData = true;
  3362. content = out.initialPreview || [];
  3363. config = out.initialPreviewConfig || [];
  3364. tags = out.initialPreviewThumbTags || [];
  3365. append = out.append === undefined || out.append;
  3366. if (content.length > 0 && !$h.isArray(content)) {
  3367. content = content.split(self.initialPreviewDelimiter);
  3368. }
  3369. if (content.length) {
  3370. self._mergeArray('initialPreview', content);
  3371. self._mergeArray('initialPreviewConfig', config);
  3372. self._mergeArray('initialPreviewThumbTags', tags);
  3373. }
  3374. if ($thumb !== undefined) {
  3375. if (!allFiles) {
  3376. index = self.previewCache.add(content[0], config[0], tags[0], append);
  3377. data = self.previewCache.get(index, false);
  3378. $div = $h.createElement(data).hide().appendTo($thumb);
  3379. $newCache = $div.find('.kv-zoom-cache');
  3380. if ($newCache && $newCache.length) {
  3381. $newCache.appendTo($thumb);
  3382. }
  3383. $thumb.fadeOut('slow', function () {
  3384. var $newThumb = $div.find('.file-preview-frame');
  3385. if ($newThumb && $newThumb.length) {
  3386. $newThumb.insertBefore($thumb).fadeIn('slow').css('display:inline-block');
  3387. }
  3388. self._initPreviewActions();
  3389. self._clearFileInput();
  3390. $thumb.remove();
  3391. $div.remove();
  3392. self._initSortable();
  3393. });
  3394. } else {
  3395. id = $thumb.attr('id');
  3396. i = self._getUploadCacheIndex(id);
  3397. if (i !== null) {
  3398. self.uploadCache[i] = {
  3399. id: id,
  3400. content: content[0],
  3401. config: config[0] || [],
  3402. tags: tags[0] || [],
  3403. append: append
  3404. };
  3405. }
  3406. }
  3407. } else {
  3408. self.previewCache.set(content, config, tags, append);
  3409. self._initPreview();
  3410. self._initPreviewActions();
  3411. }
  3412. }
  3413. self._resetCaption();
  3414. },
  3415. _getUploadCacheIndex: function (id) {
  3416. var self = this, i, len = self.uploadCache.length, config;
  3417. for (i = 0; i < len; i++) {
  3418. config = self.uploadCache[i];
  3419. if (config.id === id) {
  3420. return i;
  3421. }
  3422. }
  3423. return null;
  3424. },
  3425. _initSuccessThumbs: function () {
  3426. var self = this;
  3427. if (!self.showPreview) {
  3428. return;
  3429. }
  3430. self._getThumbs($h.FRAMES + '.file-preview-success').each(function () {
  3431. var $thumb = $(this), $remove = $thumb.find('.kv-file-remove');
  3432. $remove.removeAttr('disabled');
  3433. self._handler($remove, 'click', function () {
  3434. var id = $thumb.attr('id'),
  3435. out = self._raise('filesuccessremove', [id, $thumb.attr('data-fileindex')]);
  3436. $h.cleanMemory($thumb);
  3437. if (out === false) {
  3438. return;
  3439. }
  3440. $thumb.fadeOut('slow', function () {
  3441. $thumb.remove();
  3442. if (!self.getFrames().length) {
  3443. self.reset();
  3444. }
  3445. });
  3446. });
  3447. });
  3448. },
  3449. _updateInitialPreview: function () {
  3450. var self = this, u = self.uploadCache;
  3451. if (self.showPreview) {
  3452. $.each(u, function (key, setting) {
  3453. self.previewCache.add(setting.content, setting.config, setting.tags, setting.append);
  3454. });
  3455. if (self.hasInitData) {
  3456. self._initPreview();
  3457. self._initPreviewActions();
  3458. }
  3459. }
  3460. },
  3461. _getThumbFileId: function ($thumb) {
  3462. var self = this;
  3463. if (self.showPreview && $thumb !== undefined) {
  3464. return $thumb.attr('data-fileid');
  3465. }
  3466. return null;
  3467. },
  3468. _getThumbFile: function ($thumb) {
  3469. var self = this, id = self._getThumbFileId($thumb);
  3470. return id ? self.fileManager.getFile(id) : null;
  3471. },
  3472. _uploadSingle: function (i, id, isBatch) {
  3473. var self = this, fm = self.fileManager, count = fm.count(), formdata = new FormData(), outData,
  3474. previewId = self._getThumbId(id), $thumb, chkComplete, $btnUpload, $btnDelete,
  3475. hasPostData = count > 0 || !$.isEmptyObject(self.uploadExtraData), uploadFailed, $prog, fnBefore,
  3476. errMsg, fnSuccess, fnComplete, fnError, updateUploadLog, op = self.ajaxOperations.uploadThumb,
  3477. fileObj = fm.getFile(id), params = {id: previewId, index: i, fileId: id},
  3478. fileName = self.fileManager.getFileName(id, true);
  3479. if (self.enableResumableUpload) { // not enabled for resumable uploads
  3480. return;
  3481. }
  3482. if (self.showPreview) {
  3483. $thumb = self.fileManager.getThumb(id);
  3484. $prog = $thumb.find('.file-thumb-progress');
  3485. $btnUpload = $thumb.find('.kv-file-upload');
  3486. $btnDelete = $thumb.find('.kv-file-remove');
  3487. $prog.show();
  3488. }
  3489. if (count === 0 || !hasPostData || (self.showPreview && $btnUpload && $btnUpload.hasClass('disabled')) ||
  3490. self._abort(params)) {
  3491. return;
  3492. }
  3493. updateUploadLog = function () {
  3494. if (!uploadFailed) {
  3495. fm.removeFile(id);
  3496. } else {
  3497. fm.errors.push(id);
  3498. }
  3499. fm.setProcessed(id);
  3500. if (fm.isProcessed()) {
  3501. self.fileBatchCompleted = true;
  3502. chkComplete();
  3503. }
  3504. };
  3505. chkComplete = function () {
  3506. var $initThumbs;
  3507. if (!self.fileBatchCompleted) {
  3508. return;
  3509. }
  3510. setTimeout(function () {
  3511. var triggerReset = fm.count() === 0, errCount = fm.errors.length;
  3512. self._updateInitialPreview();
  3513. self.unlock(triggerReset);
  3514. if (triggerReset) {
  3515. self._clearFileInput();
  3516. }
  3517. $initThumbs = self.$preview.find('.file-preview-initial');
  3518. if (self.uploadAsync && $initThumbs.length) {
  3519. $h.addCss($initThumbs, $h.SORT_CSS);
  3520. self._initSortable();
  3521. }
  3522. self._raise('filebatchuploadcomplete', [fm.stack, self._getExtraData()]);
  3523. if (!self.retryErrorUploads || errCount === 0) {
  3524. fm.clear();
  3525. }
  3526. self._setProgress(101);
  3527. self.ajaxAborted = false;
  3528. }, self.processDelay);
  3529. };
  3530. fnBefore = function (jqXHR) {
  3531. outData = self._getOutData(formdata, jqXHR);
  3532. fm.initStats(id);
  3533. self.fileBatchCompleted = false;
  3534. if (!isBatch) {
  3535. self.ajaxAborted = false;
  3536. }
  3537. if (self.showPreview) {
  3538. if (!$thumb.hasClass('file-preview-success')) {
  3539. self._setThumbStatus($thumb, 'Loading');
  3540. $h.addCss($thumb, 'file-uploading');
  3541. }
  3542. $btnUpload.attr('disabled', true);
  3543. $btnDelete.attr('disabled', true);
  3544. }
  3545. if (!isBatch) {
  3546. self.lock();
  3547. }
  3548. if (fm.errors.indexOf(id) !== -1) {
  3549. delete fm.errors[id];
  3550. }
  3551. self._raise('filepreupload', [outData, previewId, i, self._getThumbFileId($thumb)]);
  3552. $.extend(true, params, outData);
  3553. if (self._abort(params)) {
  3554. jqXHR.abort();
  3555. if (!isBatch) {
  3556. self._setThumbStatus($thumb, 'New');
  3557. $thumb.removeClass('file-uploading');
  3558. $btnUpload.removeAttr('disabled');
  3559. $btnDelete.removeAttr('disabled');
  3560. self.unlock();
  3561. }
  3562. self._setProgressCancelled();
  3563. }
  3564. };
  3565. fnSuccess = function (data, textStatus, jqXHR) {
  3566. var pid = self.showPreview && $thumb.attr('id') ? $thumb.attr('id') : previewId;
  3567. outData = self._getOutData(formdata, jqXHR, data);
  3568. $.extend(true, params, outData);
  3569. setTimeout(function () {
  3570. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3571. if (self.showPreview) {
  3572. self._setThumbStatus($thumb, 'Success');
  3573. $btnUpload.hide();
  3574. self._initUploadSuccess(data, $thumb, isBatch);
  3575. self._setProgress(101, $prog);
  3576. }
  3577. self._raise('fileuploaded', [outData, pid, i, self._getThumbFileId($thumb)]);
  3578. if (!isBatch) {
  3579. self.fileManager.remove($thumb);
  3580. } else {
  3581. updateUploadLog();
  3582. }
  3583. } else {
  3584. uploadFailed = true;
  3585. errMsg = self._parseError(op, jqXHR, self.msgUploadError, self.fileManager.getFileName(id));
  3586. self._showFileError(errMsg, params);
  3587. self._setPreviewError($thumb, true);
  3588. if (!self.retryErrorUploads) {
  3589. $btnUpload.hide();
  3590. }
  3591. if (isBatch) {
  3592. updateUploadLog();
  3593. }
  3594. self._setProgress(101, self._getFrame(pid).find('.file-thumb-progress'),
  3595. self.msgUploadError);
  3596. }
  3597. }, self.processDelay);
  3598. };
  3599. fnComplete = function () {
  3600. if (self.showPreview) {
  3601. $btnUpload.removeAttr('disabled');
  3602. $btnDelete.removeAttr('disabled');
  3603. $thumb.removeClass('file-uploading');
  3604. }
  3605. if (!isBatch) {
  3606. self.unlock(false);
  3607. self._clearFileInput();
  3608. } else {
  3609. chkComplete();
  3610. }
  3611. self._initSuccessThumbs();
  3612. };
  3613. fnError = function (jqXHR, textStatus, errorThrown) {
  3614. errMsg = self._parseError(op, jqXHR, errorThrown, self.fileManager.getFileName(id));
  3615. uploadFailed = true;
  3616. setTimeout(function () {
  3617. var $prog;
  3618. if (isBatch) {
  3619. updateUploadLog();
  3620. }
  3621. self.fileManager.setProgress(id, 100);
  3622. self._setPreviewError($thumb, true);
  3623. if (!self.retryErrorUploads) {
  3624. $btnUpload.hide();
  3625. }
  3626. $.extend(true, params, self._getOutData(formdata, jqXHR));
  3627. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3628. $prog = self.showPreview && $thumb ? $thumb.find('.file-thumb-progress') : '';
  3629. self._setProgress(101, $prog, self.msgUploadError);
  3630. self._showFileError(errMsg, params);
  3631. }, self.processDelay);
  3632. };
  3633. self._setFileData(formdata, fileObj.file, fileName, id);
  3634. self._setUploadData(formdata, {fileId: id});
  3635. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata, id, i);
  3636. },
  3637. _setFileData: function (formdata, file, fileName, fileId) {
  3638. var self = this, preProcess = self.preProcessUpload;
  3639. if (preProcess && typeof preProcess === 'function') {
  3640. formdata.append(self.uploadFileAttr, preProcess(fileId, file));
  3641. } else {
  3642. formdata.append(self.uploadFileAttr, file, fileName);
  3643. }
  3644. },
  3645. _uploadBatch: function () {
  3646. var self = this, fm = self.fileManager, total = fm.total(), params = {}, fnBefore, fnSuccess, fnError,
  3647. fnComplete, hasPostData = total > 0 || !$.isEmptyObject(self.uploadExtraData), errMsg,
  3648. setAllUploaded, formdata = new FormData(), op = self.ajaxOperations.uploadBatch;
  3649. if (total === 0 || !hasPostData || self._abort(params)) {
  3650. return;
  3651. }
  3652. setAllUploaded = function () {
  3653. self.fileManager.clear();
  3654. self._clearFileInput();
  3655. };
  3656. fnBefore = function (jqXHR) {
  3657. self.lock();
  3658. fm.initStats();
  3659. var outData = self._getOutData(formdata, jqXHR);
  3660. self.ajaxAborted = false;
  3661. if (self.showPreview) {
  3662. self._getThumbs().each(function () {
  3663. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3664. $btnDelete = $thumb.find('.kv-file-remove');
  3665. if (!$thumb.hasClass('file-preview-success')) {
  3666. self._setThumbStatus($thumb, 'Loading');
  3667. $h.addCss($thumb, 'file-uploading');
  3668. }
  3669. $btnUpload.attr('disabled', true);
  3670. $btnDelete.attr('disabled', true);
  3671. });
  3672. }
  3673. self._raise('filebatchpreupload', [outData]);
  3674. if (self._abort(outData)) {
  3675. jqXHR.abort();
  3676. self._getThumbs().each(function () {
  3677. var $thumb = $(this), $btnUpload = $thumb.find('.kv-file-upload'),
  3678. $btnDelete = $thumb.find('.kv-file-remove');
  3679. if ($thumb.hasClass('file-preview-loading')) {
  3680. self._setThumbStatus($thumb, 'New');
  3681. $thumb.removeClass('file-uploading');
  3682. }
  3683. $btnUpload.removeAttr('disabled');
  3684. $btnDelete.removeAttr('disabled');
  3685. });
  3686. self._setProgressCancelled();
  3687. }
  3688. };
  3689. fnSuccess = function (data, textStatus, jqXHR) {
  3690. /** @namespace data.errorkeys */
  3691. var outData = self._getOutData(formdata, jqXHR, data), key = 0,
  3692. $thumbs = self._getThumbs(':not(.file-preview-success)'),
  3693. keys = $h.isEmpty(data) || $h.isEmpty(data.errorkeys) ? [] : data.errorkeys;
  3694. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3695. self._raise('filebatchuploadsuccess', [outData]);
  3696. setAllUploaded();
  3697. if (self.showPreview) {
  3698. $thumbs.each(function () {
  3699. var $thumb = $(this);
  3700. self._setThumbStatus($thumb, 'Success');
  3701. $thumb.removeClass('file-uploading');
  3702. $thumb.find('.kv-file-upload').hide().removeAttr('disabled');
  3703. });
  3704. self._initUploadSuccess(data);
  3705. } else {
  3706. self.reset();
  3707. }
  3708. self._setProgress(101);
  3709. } else {
  3710. if (self.showPreview) {
  3711. $thumbs.each(function () {
  3712. var $thumb = $(this);
  3713. $thumb.removeClass('file-uploading');
  3714. $thumb.find('.kv-file-upload').removeAttr('disabled');
  3715. $thumb.find('.kv-file-remove').removeAttr('disabled');
  3716. if (keys.length === 0 || $.inArray(key, keys) !== -1) {
  3717. self._setPreviewError($thumb, true);
  3718. if (!self.retryErrorUploads) {
  3719. $thumb.find('.kv-file-upload').hide();
  3720. self.fileManager.remove($thumb);
  3721. }
  3722. } else {
  3723. $thumb.find('.kv-file-upload').hide();
  3724. self._setThumbStatus($thumb, 'Success');
  3725. self.fileManager.remove($thumb);
  3726. }
  3727. if (!$thumb.hasClass('file-preview-error') || self.retryErrorUploads) {
  3728. key++;
  3729. }
  3730. });
  3731. self._initUploadSuccess(data);
  3732. }
  3733. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3734. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3735. self._setProgress(101, self.$progress, self.msgUploadError);
  3736. }
  3737. };
  3738. fnComplete = function () {
  3739. self.unlock();
  3740. self._initSuccessThumbs();
  3741. self._clearFileInput();
  3742. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3743. };
  3744. fnError = function (jqXHR, textStatus, errorThrown) {
  3745. var outData = self._getOutData(formdata, jqXHR);
  3746. errMsg = self._parseError(op, jqXHR, errorThrown);
  3747. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3748. self.uploadFileCount = total - 1;
  3749. if (!self.showPreview) {
  3750. return;
  3751. }
  3752. self._getThumbs().each(function () {
  3753. var $thumb = $(this);
  3754. $thumb.removeClass('file-uploading');
  3755. if (self._getThumbFile($thumb)) {
  3756. self._setPreviewError($thumb);
  3757. }
  3758. });
  3759. self._getThumbs().removeClass('file-uploading');
  3760. self._getThumbs(' .kv-file-upload').removeAttr('disabled');
  3761. self._getThumbs(' .kv-file-delete').removeAttr('disabled');
  3762. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3763. };
  3764. var ctr = 0;
  3765. $.each(self.fileManager.stack, function (key, data) {
  3766. if (!$h.isEmpty(data.file)) {
  3767. self._setFileData(formdata, data.file, (data.nameFmt || ('untitled_' + ctr)), key);
  3768. }
  3769. ctr++;
  3770. });
  3771. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3772. },
  3773. _uploadExtraOnly: function () {
  3774. var self = this, params = {}, fnBefore, fnSuccess, fnComplete, fnError, formdata = new FormData(), errMsg,
  3775. op = self.ajaxOperations.uploadExtra;
  3776. if (self._abort(params)) {
  3777. return;
  3778. }
  3779. fnBefore = function (jqXHR) {
  3780. self.lock();
  3781. var outData = self._getOutData(formdata, jqXHR);
  3782. self._raise('filebatchpreupload', [outData]);
  3783. self._setProgress(50);
  3784. params.data = outData;
  3785. params.xhr = jqXHR;
  3786. if (self._abort(params)) {
  3787. jqXHR.abort();
  3788. self._setProgressCancelled();
  3789. }
  3790. };
  3791. fnSuccess = function (data, textStatus, jqXHR) {
  3792. var outData = self._getOutData(formdata, jqXHR, data);
  3793. if ($h.isEmpty(data) || $h.isEmpty(data.error)) {
  3794. self._raise('filebatchuploadsuccess', [outData]);
  3795. self._clearFileInput();
  3796. self._initUploadSuccess(data);
  3797. self._setProgress(101);
  3798. } else {
  3799. errMsg = self._parseError(op, jqXHR, self.msgUploadError);
  3800. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3801. }
  3802. };
  3803. fnComplete = function () {
  3804. self.unlock();
  3805. self._clearFileInput();
  3806. self._raise('filebatchuploadcomplete', [self.fileManager.stack, self._getExtraData()]);
  3807. };
  3808. fnError = function (jqXHR, textStatus, errorThrown) {
  3809. var outData = self._getOutData(formdata, jqXHR);
  3810. errMsg = self._parseError(op, jqXHR, errorThrown);
  3811. params.data = outData;
  3812. self._showFileError(errMsg, outData, 'filebatchuploaderror');
  3813. self._setProgress(101, self.$progress, self.msgAjaxProgressError.replace('{operation}', op));
  3814. };
  3815. self._ajaxSubmit(fnBefore, fnSuccess, fnComplete, fnError, formdata);
  3816. },
  3817. _deleteFileIndex: function ($frame) {
  3818. var self = this, ind = $frame.attr('data-fileindex'), rev = self.reversePreviewOrder;
  3819. if (ind.substring(0, 5) === $h.INIT_FLAG) {
  3820. ind = parseInt(ind.replace($h.INIT_FLAG, ''));
  3821. self.initialPreview = $h.spliceArray(self.initialPreview, ind, rev);
  3822. self.initialPreviewConfig = $h.spliceArray(self.initialPreviewConfig, ind, rev);
  3823. self.initialPreviewThumbTags = $h.spliceArray(self.initialPreviewThumbTags, ind, rev);
  3824. self.getFrames().each(function () {
  3825. var $nFrame = $(this), nInd = $nFrame.attr('data-fileindex');
  3826. if (nInd.substring(0, 5) === $h.INIT_FLAG) {
  3827. nInd = parseInt(nInd.replace($h.INIT_FLAG, ''));
  3828. if (nInd > ind) {
  3829. nInd--;
  3830. $nFrame.attr('data-fileindex', $h.INIT_FLAG + nInd);
  3831. }
  3832. }
  3833. });
  3834. }
  3835. },
  3836. _resetCaption: function () {
  3837. var self = this;
  3838. setTimeout(function () {
  3839. var cap, n, chk = self.previewCache.count(true), len = self.fileManager.count(), file,
  3840. incomplete = ':not(.file-preview-success):not(.file-preview-error)',
  3841. hasThumb = self.showPreview && self.getFrames(incomplete).length;
  3842. if (len === 0 && chk === 0 && !hasThumb) {
  3843. self.reset();
  3844. } else {
  3845. n = chk + len;
  3846. if (n > 1) {
  3847. cap = self._getMsgSelected(n);
  3848. } else {
  3849. file = self.fileManager.getFirstFile();
  3850. cap = file ? file.nameFmt : '_';
  3851. }
  3852. self._setCaption(cap);
  3853. }
  3854. }, self.processDelay);
  3855. },
  3856. _initFileActions: function () {
  3857. var self = this;
  3858. if (!self.showPreview) {
  3859. return;
  3860. }
  3861. self._initZoomButton();
  3862. self.getFrames(' .kv-file-remove').each(function () {
  3863. var $el = $(this), $frame = $el.closest($h.FRAMES), hasError, id = $frame.attr('id'),
  3864. ind = $frame.attr('data-fileindex'), status;
  3865. self._handler($el, 'click', function () {
  3866. status = self._raise('filepreremove', [id, ind]);
  3867. if (status === false || !self._validateMinCount()) {
  3868. return false;
  3869. }
  3870. hasError = $frame.hasClass('file-preview-error');
  3871. $h.cleanMemory($frame);
  3872. $frame.fadeOut('slow', function () {
  3873. self.fileManager.remove($frame);
  3874. self._clearObjects($frame);
  3875. $frame.remove();
  3876. if (id && hasError) {
  3877. self.$errorContainer.find('li[data-thumb-id="' + id + '"]').fadeOut('fast', function () {
  3878. $(this).remove();
  3879. if (!self._errorsExist()) {
  3880. self._resetErrors();
  3881. }
  3882. });
  3883. }
  3884. self._clearFileInput();
  3885. self._resetCaption();
  3886. self._raise('fileremoved', [id, ind]);
  3887. });
  3888. });
  3889. });
  3890. self.getFrames(' .kv-file-upload').each(function () {
  3891. var $el = $(this);
  3892. self._handler($el, 'click', function () {
  3893. var $frame = $el.closest($h.FRAMES), fileId = self._getThumbFile($frame);
  3894. self._hideProgress();
  3895. if ($frame.hasClass('file-preview-error') && !self.retryErrorUploads) {
  3896. return;
  3897. }
  3898. self._uploadSingle(self.fileManager.getIndex(fileId), fileId, false);
  3899. });
  3900. });
  3901. },
  3902. _initPreviewActions: function () {
  3903. var self = this, $preview = self.$preview, deleteExtraData = self.deleteExtraData || {},
  3904. btnRemove = $h.FRAMES + ' .kv-file-remove', settings = self.fileActionSettings,
  3905. origClass = settings.removeClass, errClass = settings.removeErrorClass,
  3906. resetProgress = function () {
  3907. var hasFiles = self.isAjaxUpload ? self.previewCache.count(true) : self._inputFileCount();
  3908. if (!self.getFrames().length && !hasFiles) {
  3909. self._setCaption('');
  3910. self.reset();
  3911. self.initialCaption = '';
  3912. }
  3913. };
  3914. self._initZoomButton();
  3915. $preview.find(btnRemove).each(function () {
  3916. var $el = $(this), vUrl = $el.data('url') || self.deleteUrl, vKey = $el.data('key'), errMsg, fnBefore,
  3917. fnSuccess, fnError, op = self.ajaxOperations.deleteThumb;
  3918. if ($h.isEmpty(vUrl) || vKey === undefined) {
  3919. return;
  3920. }
  3921. if (typeof vUrl === 'function') {
  3922. vUrl = vUrl();
  3923. }
  3924. var $frame = $el.closest($h.FRAMES), cache = self.previewCache.data, settings, params, config,
  3925. fileName, extraData, index = $frame.attr('data-fileindex');
  3926. index = parseInt(index.replace($h.INIT_FLAG, ''));
  3927. config = $h.isEmpty(cache.config) && $h.isEmpty(cache.config[index]) ? null : cache.config[index];
  3928. extraData = $h.isEmpty(config) || $h.isEmpty(config.extra) ? deleteExtraData : config.extra;
  3929. fileName = config && (config.filename || config.caption) || '';
  3930. if (typeof extraData === 'function') {
  3931. extraData = extraData();
  3932. }
  3933. params = {id: $el.attr('id'), key: vKey, extra: extraData};
  3934. fnBefore = function (jqXHR) {
  3935. self.ajaxAborted = false;
  3936. self._raise('filepredelete', [vKey, jqXHR, extraData]);
  3937. if (self._abort()) {
  3938. jqXHR.abort();
  3939. } else {
  3940. $el.removeClass(errClass);
  3941. $h.addCss($frame, 'file-uploading');
  3942. $h.addCss($el, 'disabled ' + origClass);
  3943. }
  3944. };
  3945. fnSuccess = function (data, textStatus, jqXHR) {
  3946. var n, cap;
  3947. if (!$h.isEmpty(data) && !$h.isEmpty(data.error)) {
  3948. params.jqXHR = jqXHR;
  3949. params.response = data;
  3950. errMsg = self._parseError(op, jqXHR, self.msgDeleteError, fileName);
  3951. self._showFileError(errMsg, params, 'filedeleteerror');
  3952. $frame.removeClass('file-uploading');
  3953. $el.removeClass('disabled ' + origClass).addClass(errClass);
  3954. resetProgress();
  3955. return;
  3956. }
  3957. $frame.removeClass('file-uploading').addClass('file-deleted');
  3958. $frame.fadeOut('slow', function () {
  3959. index = parseInt(($frame.attr('data-fileindex')).replace($h.INIT_FLAG, ''));
  3960. self.previewCache.unset(index);
  3961. self._deleteFileIndex($frame);
  3962. n = self.previewCache.count(true);
  3963. cap = n > 0 ? self._getMsgSelected(n) : '';
  3964. self._setCaption(cap);
  3965. self._raise('filedeleted', [vKey, jqXHR, extraData]);
  3966. self._clearObjects($frame);
  3967. $frame.remove();
  3968. resetProgress();
  3969. });
  3970. };
  3971. fnError = function (jqXHR, textStatus, errorThrown) {
  3972. var errMsg = self._parseError(op, jqXHR, errorThrown, fileName);
  3973. params.jqXHR = jqXHR;
  3974. params.response = {};
  3975. self._showFileError(errMsg, params, 'filedeleteerror');
  3976. $frame.removeClass('file-uploading');
  3977. $el.removeClass('disabled ' + origClass).addClass(errClass);
  3978. resetProgress();
  3979. };
  3980. self._initAjaxSettings();
  3981. self._mergeAjaxCallback('beforeSend', fnBefore, 'delete');
  3982. self._mergeAjaxCallback('success', fnSuccess, 'delete');
  3983. self._mergeAjaxCallback('error', fnError, 'delete');
  3984. settings = $.extend(true, {}, {
  3985. url: self._encodeURI(vUrl),
  3986. type: 'POST',
  3987. dataType: 'json',
  3988. data: $.extend(true, {}, {key: vKey}, extraData)
  3989. }, self._ajaxDeleteSettings);
  3990. self._handler($el, 'click', function () {
  3991. if (!self._validateMinCount()) {
  3992. return false;
  3993. }
  3994. self.ajaxAborted = false;
  3995. self._raise('filebeforedelete', [vKey, extraData]);
  3996. if (self.ajaxAborted instanceof Promise) {
  3997. self.ajaxAborted.then(function (result) {
  3998. if (!result) {
  3999. $.ajax(settings);
  4000. }
  4001. });
  4002. } else {
  4003. if (!self.ajaxAborted) {
  4004. $.ajax(settings);
  4005. }
  4006. }
  4007. });
  4008. });
  4009. },
  4010. _hideFileIcon: function () {
  4011. var self = this;
  4012. if (self.overwriteInitial) {
  4013. self.$captionContainer.removeClass('icon-visible');
  4014. }
  4015. },
  4016. _showFileIcon: function () {
  4017. var self = this;
  4018. $h.addCss(self.$captionContainer, 'icon-visible');
  4019. },
  4020. _getSize: function (bytes, sizes) {
  4021. var self = this, size = parseFloat(bytes), i, func = self.fileSizeGetter, out;
  4022. if (!$.isNumeric(bytes) || !$.isNumeric(size)) {
  4023. return '';
  4024. }
  4025. if (typeof func === 'function') {
  4026. out = func(size);
  4027. } else {
  4028. if (size === 0) {
  4029. out = '0.00 B';
  4030. } else {
  4031. if (!sizes) {
  4032. sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
  4033. }
  4034. i = Math.floor(Math.log(size) / Math.log(1024));
  4035. out = (size / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i];
  4036. }
  4037. }
  4038. return self._getLayoutTemplate('size').replace('{sizeText}', out);
  4039. },
  4040. _getFileType: function (ftype) {
  4041. var self = this;
  4042. return self.mimeTypeAliases[ftype] || ftype;
  4043. },
  4044. _generatePreviewTemplate: function (
  4045. cat,
  4046. data,
  4047. fname,
  4048. ftype,
  4049. previewId,
  4050. fileId,
  4051. isError,
  4052. size,
  4053. frameClass,
  4054. foot,
  4055. ind,
  4056. templ,
  4057. attrs,
  4058. zoomData
  4059. ) {
  4060. var self = this, caption = self.slug(fname), prevContent, zoomContent = '', styleAttribs = '',
  4061. screenW = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
  4062. config, title = caption, alt = caption, typeCss = 'type-default', getContent,
  4063. footer = foot || self._renderFileFooter(cat, caption, size, 'auto', isError),
  4064. forcePrevIcon = self.preferIconicPreview, forceZoomIcon = self.preferIconicZoomPreview,
  4065. newCat = forcePrevIcon ? 'other' : cat;
  4066. config = screenW < 400 ? (self.previewSettingsSmall[newCat] || self.defaults.previewSettingsSmall[newCat]) :
  4067. (self.previewSettings[newCat] || self.defaults.previewSettings[newCat]);
  4068. if (config) {
  4069. $.each(config, function (key, val) {
  4070. styleAttribs += key + ':' + val + ';';
  4071. });
  4072. }
  4073. getContent = function (c, d, zoom, frameCss) {
  4074. var id = zoom ? 'zoom-' + previewId : previewId, tmplt = self._getPreviewTemplate(c),
  4075. css = (frameClass || '') + ' ' + frameCss;
  4076. if (self.frameClass) {
  4077. css = self.frameClass + ' ' + css;
  4078. }
  4079. if (zoom) {
  4080. css = css.replace(' ' + $h.SORT_CSS, '');
  4081. }
  4082. tmplt = self._parseFilePreviewIcon(tmplt, fname);
  4083. if (cat === 'object' && !ftype) {
  4084. $.each(self.defaults.fileTypeSettings, function (key, func) {
  4085. if (key === 'object' || key === 'other') {
  4086. return;
  4087. }
  4088. if (func(fname, ftype)) {
  4089. typeCss = 'type-' + key;
  4090. }
  4091. });
  4092. }
  4093. if (!$h.isEmpty(attrs)) {
  4094. if (attrs.title !== undefined && attrs.title !== null) {
  4095. title = attrs.title;
  4096. }
  4097. if (attrs.alt !== undefined && attrs.alt !== null) {
  4098. title = attrs.alt;
  4099. }
  4100. }
  4101. return tmplt.setTokens({
  4102. 'previewId': id,
  4103. 'caption': caption,
  4104. 'title': title,
  4105. 'alt': alt,
  4106. 'frameClass': css,
  4107. 'type': self._getFileType(ftype),
  4108. 'fileindex': ind,
  4109. 'fileid': fileId || '',
  4110. 'typeCss': typeCss,
  4111. 'footer': footer,
  4112. 'data': d,
  4113. 'template': templ || cat,
  4114. 'style': styleAttribs ? 'style="' + styleAttribs + '"' : ''
  4115. });
  4116. };
  4117. ind = ind || previewId.slice(previewId.lastIndexOf('-') + 1);
  4118. if (self.fileActionSettings.showZoom) {
  4119. zoomContent = getContent((forceZoomIcon ? 'other' : cat), zoomData ? zoomData : data, true,
  4120. 'kv-zoom-thumb');
  4121. }
  4122. zoomContent = '\n' + self._getLayoutTemplate('zoomCache').replace('{zoomContent}', zoomContent);
  4123. if (typeof self.sanitizeZoomCache === 'function') {
  4124. zoomContent = self.sanitizeZoomCache(zoomContent);
  4125. }
  4126. prevContent = getContent((forcePrevIcon ? 'other' : cat), data, false, 'kv-preview-thumb');
  4127. return prevContent.setTokens({zoomCache: zoomContent});
  4128. },
  4129. _addToPreview: function ($preview, content) {
  4130. var self = this, $el;
  4131. content = $h.cspBuffer.stash(content);
  4132. $el = self.reversePreviewOrder ? $preview.prepend(content) : $preview.append(content);
  4133. $h.cspBuffer.apply($preview);
  4134. return $el;
  4135. },
  4136. _previewDefault: function (file, isDisabled) {
  4137. var self = this, $preview = self.$preview;
  4138. if (!self.showPreview) {
  4139. return;
  4140. }
  4141. var fname = $h.getFileName(file), ftype = file ? file.type : '', content, size = file.size || 0,
  4142. caption = self._getFileName(file, ''), isError = isDisabled === true && !self.isAjaxUpload,
  4143. data = $h.createObjectURL(file), fileId = self.fileManager.getId(file),
  4144. previewId = self._getThumbId(fileId);
  4145. self._clearDefaultPreview();
  4146. content = self._generatePreviewTemplate('other', data, fname, ftype, previewId, fileId, isError, size);
  4147. self._addToPreview($preview, content);
  4148. self._setThumbAttr(previewId, caption, size);
  4149. if (isDisabled === true && self.isAjaxUpload) {
  4150. self._setThumbStatus(self._getFrame(previewId), 'Error');
  4151. }
  4152. },
  4153. _previewFile: function (i, file, theFile, data, fileInfo) {
  4154. if (!this.showPreview) {
  4155. return;
  4156. }
  4157. var self = this, fname = $h.getFileName(file), ftype = fileInfo.type, caption = fileInfo.name,
  4158. cat = self._parseFileType(ftype, fname), content, $preview = self.$preview, fsize = file.size || 0,
  4159. iData = cat === 'image' ? theFile.target.result : data,
  4160. fileId = self.fileManager.getId(file), previewId = self._getThumbId(fileId);
  4161. /** @namespace window.DOMPurify */
  4162. content = self._generatePreviewTemplate(cat, iData, fname, ftype, previewId, fileId, false, fsize);
  4163. self._clearDefaultPreview();
  4164. self._addToPreview($preview, content);
  4165. var $thumb = self._getFrame(previewId);
  4166. self._validateImageOrientation($thumb.find('img'), file, previewId, fileId, caption, ftype, fsize, iData);
  4167. self._setThumbAttr(previewId, caption, fsize);
  4168. self._initSortable();
  4169. },
  4170. _setThumbAttr: function (id, caption, size) {
  4171. var self = this, $frame = self._getFrame(id);
  4172. if ($frame.length) {
  4173. size = size && size > 0 ? self._getSize(size) : '';
  4174. $frame.data({'caption': caption, 'size': size});
  4175. }
  4176. },
  4177. _setInitThumbAttr: function () {
  4178. var self = this, data = self.previewCache.data, len = self.previewCache.count(true), config,
  4179. caption, size, previewId;
  4180. if (len === 0) {
  4181. return;
  4182. }
  4183. for (var i = 0; i < len; i++) {
  4184. config = data.config[i];
  4185. previewId = self.previewInitId + '-' + $h.INIT_FLAG + i;
  4186. caption = $h.ifSet('caption', config, $h.ifSet('filename', config));
  4187. size = $h.ifSet('size', config);
  4188. self._setThumbAttr(previewId, caption, size);
  4189. }
  4190. },
  4191. _slugDefault: function (text) {
  4192. // noinspection RegExpRedundantEscape
  4193. return $h.isEmpty(text, true) ? '' : String(text).replace(/[\[\]\/\{}:;#%=\(\)\*\+\?\\\^\$\|<>&"']/g, '_');
  4194. },
  4195. _updateFileDetails: function (numFiles, skipRaiseEvent) {
  4196. var self = this, $el = self.$element, label, n, log, nFiles, file,
  4197. name = ($h.isIE(9) && $h.findFileName($el.val())) || ($el[0].files[0] && $el[0].files[0].name);
  4198. if (!name && self.fileManager.count() > 0) {
  4199. file = self.fileManager.getFirstFile();
  4200. label = file.nameFmt;
  4201. } else {
  4202. label = name ? self.slug(name) : '_';
  4203. }
  4204. n = self.isAjaxUpload ? self.fileManager.count() : numFiles;
  4205. nFiles = self.previewCache.count(true) + n;
  4206. log = n === 1 ? label : self._getMsgSelected(nFiles);
  4207. if (self.isError) {
  4208. self.$previewContainer.removeClass('file-thumb-loading');
  4209. self.$previewStatus.html('');
  4210. self.$captionContainer.removeClass('icon-visible');
  4211. } else {
  4212. self._showFileIcon();
  4213. }
  4214. self._setCaption(log, self.isError);
  4215. self.$container.removeClass('file-input-new file-input-ajax-new');
  4216. if (!skipRaiseEvent) {
  4217. self._raise('fileselect', [numFiles, label]);
  4218. }
  4219. if (self.previewCache.count(true)) {
  4220. self._initPreviewActions();
  4221. }
  4222. },
  4223. _setThumbStatus: function ($thumb, status) {
  4224. var self = this;
  4225. if (!self.showPreview) {
  4226. return;
  4227. }
  4228. var icon = 'indicator' + status, msg = icon + 'Title',
  4229. css = 'file-preview-' + status.toLowerCase(),
  4230. $indicator = $thumb.find('.file-upload-indicator'),
  4231. config = self.fileActionSettings;
  4232. $thumb.removeClass('file-preview-success file-preview-error file-preview-paused file-preview-loading');
  4233. if (status === 'Success') {
  4234. $thumb.find('.file-drag-handle').remove();
  4235. }
  4236. $h.setHtml($indicator, config[icon]);
  4237. $indicator.attr('title', config[msg]);
  4238. $thumb.addClass(css);
  4239. if (status === 'Error' && !self.retryErrorUploads) {
  4240. $thumb.find('.kv-file-upload').attr('disabled', true);
  4241. }
  4242. },
  4243. _setProgressCancelled: function () {
  4244. var self = this;
  4245. self._setProgress(101, self.$progress, self.msgCancelled);
  4246. },
  4247. _setProgress: function (p, $el, error, stats) {
  4248. var self = this;
  4249. $el = $el || self.$progress;
  4250. if (!$el.length) {
  4251. return;
  4252. }
  4253. var pct = Math.min(p, 100), out, pctLimit = self.progressUploadThreshold,
  4254. t = p <= 100 ? self.progressTemplate : self.progressCompleteTemplate,
  4255. template = pct < 100 ? self.progressTemplate :
  4256. (error ? (self.paused ? self.progressPauseTemplate : self.progressErrorTemplate) : t);
  4257. if (p >= 100) {
  4258. stats = '';
  4259. }
  4260. if (!$h.isEmpty(template)) {
  4261. if (pctLimit && pct > pctLimit && p <= 100) {
  4262. out = template.setTokens({'percent': pctLimit, 'status': self.msgUploadThreshold});
  4263. } else {
  4264. out = template.setTokens({'percent': pct, 'status': (p > 100 ? self.msgUploadEnd : pct + '%')});
  4265. }
  4266. stats = stats || '';
  4267. out = out.setTokens({stats: stats});
  4268. $h.setHtml($el, out);
  4269. if (error) {
  4270. $h.setHtml($el.find('[role="progressbar"]'), error);
  4271. }
  4272. }
  4273. },
  4274. _hasFiles: function () {
  4275. var el = this.$element[0];
  4276. return !!(el && el.files && el.files.length);
  4277. },
  4278. _setFileDropZoneTitle: function () {
  4279. var self = this, $zone = self.$container.find('.file-drop-zone'), title = self.dropZoneTitle, strFiles;
  4280. if (self.isClickable) {
  4281. strFiles = $h.isEmpty(self.$element.attr('multiple')) ? self.fileSingle : self.filePlural;
  4282. title += self.dropZoneClickTitle.replace('{files}', strFiles);
  4283. }
  4284. $zone.find('.' + self.dropZoneTitleClass).remove();
  4285. if (!self.showPreview || $zone.length === 0 || self.fileManager.count() > 0 || !self.dropZoneEnabled ||
  4286. self.previewCache.count() > 0 || (!self.isAjaxUpload && self._hasFiles())) {
  4287. return;
  4288. }
  4289. if ($zone.find($h.FRAMES).length === 0 && $h.isEmpty(self.defaultPreviewContent)) {
  4290. $zone.prepend('<div class="' + self.dropZoneTitleClass + '">' + title + '</div>');
  4291. }
  4292. self.$container.removeClass('file-input-new');
  4293. $h.addCss(self.$container, 'file-input-ajax-new');
  4294. },
  4295. _getStats: function (stats) {
  4296. var self = this, pendingTime, t;
  4297. if (!self.showUploadStats || !stats || !stats.bitrate) {
  4298. return '';
  4299. }
  4300. t = self._getLayoutTemplate('stats');
  4301. pendingTime = (!stats.elapsed || !stats.bps) ? self.msgCalculatingTime :
  4302. self.msgPendingTime.setTokens({time: $h.getElapsed(Math.ceil(stats.pendingBytes / stats.bps))});
  4303. return t.setTokens({
  4304. uploadSpeed: stats.bitrate,
  4305. pendingTime: pendingTime
  4306. });
  4307. },
  4308. _setResumableProgress: function (pct, stats, $thumb) {
  4309. var self = this, rm = self.resumableManager, obj = $thumb ? rm : self,
  4310. $prog = $thumb ? $thumb.find('.file-thumb-progress') : null;
  4311. if (obj.lastProgress === 0) {
  4312. obj.lastProgress = pct;
  4313. }
  4314. if (pct < obj.lastProgress) {
  4315. pct = obj.lastProgress;
  4316. }
  4317. self._setProgress(pct, $prog, null, self._getStats(stats));
  4318. obj.lastProgress = pct;
  4319. },
  4320. _toggleResumableProgress: function (template, message) {
  4321. var self = this, $progress = self.$progress;
  4322. if ($progress && $progress.length) {
  4323. $h.setHtml($progress, template.setTokens({
  4324. percent: 101,
  4325. status: message,
  4326. stats: ''
  4327. }));
  4328. }
  4329. },
  4330. _setFileUploadStats: function (id, pct, stats) {
  4331. var self = this, $prog = self.$progress;
  4332. if (!self.showPreview && (!$prog || !$prog.length)) {
  4333. return;
  4334. }
  4335. var fm = self.fileManager, rm = self.resumableManager, $thumb = fm.getThumb(id), pctTot,
  4336. totUpSize = 0, totSize = fm.getTotalSize(), totStats = $.extend(true, {}, stats);
  4337. if (self.enableResumableUpload) {
  4338. var loaded = stats.loaded, currUplSize = rm.getUploadedSize(), currTotSize = rm.file.size, totLoaded;
  4339. loaded += currUplSize;
  4340. totLoaded = fm.uploadedSize + loaded;
  4341. pct = $h.round(100 * loaded / currTotSize);
  4342. stats.pendingBytes = currTotSize - currUplSize;
  4343. self._setResumableProgress(pct, stats, $thumb);
  4344. pctTot = Math.floor(100 * totLoaded / totSize);
  4345. totStats.pendingBytes = totSize - totLoaded;
  4346. self._setResumableProgress(pctTot, totStats);
  4347. } else {
  4348. fm.setProgress(id, pct);
  4349. $prog = $thumb && $thumb.length ? $thumb.find('.file-thumb-progress') : null;
  4350. self._setProgress(pct, $prog, null, self._getStats(stats));
  4351. $.each(fm.stats, function (id, cfg) {
  4352. totUpSize += cfg.loaded;
  4353. });
  4354. totStats.pendingBytes = totSize - totUpSize;
  4355. pctTot = $h.round(totUpSize / totSize * 100);
  4356. self._setProgress(pctTot, null, null, self._getStats(totStats));
  4357. }
  4358. },
  4359. _validateMinCount: function () {
  4360. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  4361. if (self.validateInitialCount && self.minFileCount > 0 && self._getFileCount(len - 1) < self.minFileCount) {
  4362. self._noFilesError({});
  4363. return false;
  4364. }
  4365. return true;
  4366. },
  4367. _getFileCount: function (fileCount, includeInitial) {
  4368. var self = this, addCount = 0;
  4369. if (includeInitial === undefined) {
  4370. includeInitial = self.validateInitialCount && !self.overwriteInitial;
  4371. }
  4372. if (includeInitial) {
  4373. addCount = self.previewCache.count(true);
  4374. fileCount += addCount;
  4375. }
  4376. return fileCount;
  4377. },
  4378. _getFileId: function (file) {
  4379. return $h.getFileId(file, this.generateFileId);
  4380. },
  4381. _getFileName: function (file, defaultValue) {
  4382. var self = this, fileName = $h.getFileName(file);
  4383. return fileName ? self.slug(fileName) : defaultValue;
  4384. },
  4385. _getFileNames: function (skipNull) {
  4386. var self = this;
  4387. return self.filenames.filter(function (n) {
  4388. return (skipNull ? n !== undefined : n !== undefined && n !== null);
  4389. });
  4390. },
  4391. _setPreviewError: function ($thumb, keepFile) {
  4392. var self = this, removeFrame = self.removeFromPreviewOnError && !self.retryErrorUploads;
  4393. if (!keepFile || removeFrame) {
  4394. self.fileManager.remove($thumb);
  4395. }
  4396. if (!self.showPreview) {
  4397. return;
  4398. }
  4399. if (removeFrame) {
  4400. $thumb.remove();
  4401. return;
  4402. } else {
  4403. self._setThumbStatus($thumb, 'Error');
  4404. }
  4405. self._refreshUploadButton($thumb);
  4406. },
  4407. _refreshUploadButton: function ($thumb) {
  4408. var self = this, $btn = $thumb.find('.kv-file-upload'), cfg = self.fileActionSettings,
  4409. icon = cfg.uploadIcon, title = cfg.uploadTitle;
  4410. if (!$btn.length) {
  4411. return;
  4412. }
  4413. if (self.retryErrorUploads) {
  4414. icon = cfg.uploadRetryIcon;
  4415. title = cfg.uploadRetryTitle;
  4416. }
  4417. $btn.attr('title', title);
  4418. $h.setHtml($btn, icon);
  4419. },
  4420. _checkDimensions: function (i, chk, $img, $thumb, fname, type, params) {
  4421. var self = this, msg, dim, tag = chk === 'Small' ? 'min' : 'max', limit = self[tag + 'Image' + type],
  4422. $imgEl, isValid;
  4423. if ($h.isEmpty(limit) || !$img.length) {
  4424. return;
  4425. }
  4426. $imgEl = $img[0];
  4427. dim = (type === 'Width') ? $imgEl.naturalWidth || $imgEl.width : $imgEl.naturalHeight || $imgEl.height;
  4428. isValid = chk === 'Small' ? dim >= limit : dim <= limit;
  4429. if (isValid) {
  4430. return;
  4431. }
  4432. msg = self['msgImage' + type + chk].setTokens({'name': fname, 'size': limit});
  4433. self._showFileError(msg, params);
  4434. self._setPreviewError($thumb);
  4435. },
  4436. _getExifObj: function (data) {
  4437. var self = this, exifObj, error = $h.logMessages.exifWarning;
  4438. if (data.slice(0, 23) !== 'data:image/jpeg;base64,' && data.slice(0, 22) !== 'data:image/jpg;base64,') {
  4439. exifObj = null;
  4440. return;
  4441. }
  4442. try {
  4443. exifObj = window.piexif ? window.piexif.load(data) : null;
  4444. } catch (err) {
  4445. exifObj = null;
  4446. error = err && err.message || '';
  4447. }
  4448. if (!exifObj) {
  4449. self._log($h.logMessages.badExifParser, {details: error});
  4450. }
  4451. return exifObj;
  4452. },
  4453. setImageOrientation: function ($img, $zoomImg, value, $thumb) {
  4454. var self = this, invalidImg = !$img || !$img.length, invalidZoomImg = !$zoomImg || !$zoomImg.length, $mark,
  4455. isHidden = false, $div, zoomOnly = invalidImg && $thumb && $thumb.attr('data-template') === 'image', ev;
  4456. if (invalidImg && invalidZoomImg) {
  4457. return;
  4458. }
  4459. ev = 'load.fileinputimageorient';
  4460. if (zoomOnly) {
  4461. $img = $zoomImg;
  4462. $zoomImg = null;
  4463. $img.css(self.previewSettings.image);
  4464. $div = $(document.createElement('div')).appendTo($thumb.find('.kv-file-content'));
  4465. $mark = $(document.createElement('span')).insertBefore($img);
  4466. $img.css('visibility', 'hidden').removeClass('file-zoom-detail').appendTo($div);
  4467. } else {
  4468. isHidden = !$img.is(':visible');
  4469. }
  4470. $img.off(ev).on(ev, function () {
  4471. if (isHidden) {
  4472. self.$preview.removeClass('hide-content');
  4473. $thumb.find('.kv-file-content').css('visibility', 'hidden');
  4474. }
  4475. var img = $img[0], zoomImg = $zoomImg && $zoomImg.length ? $zoomImg[0] : null,
  4476. h = img.offsetHeight, w = img.offsetWidth, r = $h.getRotation(value);
  4477. if (isHidden) {
  4478. $thumb.find('.kv-file-content').css('visibility', 'visible');
  4479. self.$preview.addClass('hide-content');
  4480. }
  4481. $img.data('orientation', value);
  4482. if (zoomImg) {
  4483. $zoomImg.data('orientation', value);
  4484. }
  4485. if (value < 5) {
  4486. $h.setTransform(img, r);
  4487. $h.setTransform(zoomImg, r);
  4488. return;
  4489. }
  4490. var offsetAngle = Math.atan(w / h), origFactor = Math.sqrt(Math.pow(h, 2) + Math.pow(w, 2)),
  4491. scale = !origFactor ? 1 : (h / Math.cos(Math.PI / 2 + offsetAngle)) / origFactor,
  4492. s = ' scale(' + Math.abs(scale) + ')';
  4493. $h.setTransform(img, r + s);
  4494. $h.setTransform(zoomImg, r + s);
  4495. if (zoomOnly) {
  4496. $img.css('visibility', 'visible').insertAfter($mark).addClass('file-zoom-detail');
  4497. $mark.remove();
  4498. $div.remove();
  4499. }
  4500. });
  4501. },
  4502. _validateImageOrientation: function ($img, file, previewId, fileId, caption, ftype, fsize, iData) {
  4503. var self = this, exifObj, value, autoOrientImage = self.autoOrientImage, selector;
  4504. if (self.canOrientImage) {
  4505. $img.css('image-orientation', (autoOrientImage ? 'from-image' : 'none'));
  4506. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4507. return;
  4508. }
  4509. selector = $h.getZoomSelector(previewId, ' img');
  4510. exifObj = autoOrientImage ? self._getExifObj(iData) : null;
  4511. value = exifObj ? exifObj['0th'][piexif.ImageIFD.Orientation] : null; // jshint ignore:line
  4512. if (!value) {
  4513. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4514. return;
  4515. }
  4516. self.setImageOrientation($img, $(selector), value, self._getFrame(previewId));
  4517. self._raise('fileimageoriented', {'$img': $img, 'file': file});
  4518. self._validateImage(previewId, fileId, caption, ftype, fsize, iData, exifObj);
  4519. },
  4520. _validateImage: function (previewId, fileId, fname, ftype, fsize, iData, exifObj) {
  4521. var self = this, $preview = self.$preview, params, w1, w2, $thumb = self._getFrame(previewId),
  4522. i = $thumb.attr('data-fileindex'), $img = $thumb.find('img');
  4523. fname = fname || 'Untitled';
  4524. $img.one('load', function () {
  4525. w1 = $thumb.width();
  4526. w2 = $preview.width();
  4527. if (w1 > w2) {
  4528. $img.css('width', '100%');
  4529. }
  4530. params = {ind: i, id: previewId, fileId: fileId};
  4531. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Width', params);
  4532. self._checkDimensions(i, 'Small', $img, $thumb, fname, 'Height', params);
  4533. if (!self.resizeImage) {
  4534. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Width', params);
  4535. self._checkDimensions(i, 'Large', $img, $thumb, fname, 'Height', params);
  4536. }
  4537. self._raise('fileimageloaded', [previewId]);
  4538. self.fileManager.addImage(fileId, {
  4539. ind: i,
  4540. img: $img,
  4541. thumb: $thumb,
  4542. pid: previewId,
  4543. typ: ftype,
  4544. siz: fsize,
  4545. validated: false,
  4546. imgData: iData,
  4547. exifObj: exifObj
  4548. });
  4549. $thumb.data('exif', exifObj);
  4550. self._validateAllImages();
  4551. }).one('error', function () {
  4552. self._raise('fileimageloaderror', [previewId]);
  4553. }).each(function () {
  4554. if (this.complete) {
  4555. $(this).trigger('load');
  4556. } else {
  4557. if (this.error) {
  4558. $(this).trigger('error');
  4559. }
  4560. }
  4561. });
  4562. },
  4563. _validateAllImages: function () {
  4564. var self = this, counter = {val: 0}, numImgs = self.fileManager.getImageCount(), fsize,
  4565. minSize = self.resizeIfSizeMoreThan;
  4566. if (numImgs !== self.fileManager.totalImages) {
  4567. return;
  4568. }
  4569. self._raise('fileimagesloaded');
  4570. if (!self.resizeImage) {
  4571. return;
  4572. }
  4573. $.each(self.fileManager.loadedImages, function (id, config) {
  4574. if (!config.validated) {
  4575. fsize = config.siz;
  4576. if (fsize && fsize > minSize * 1000) {
  4577. self._getResizedImage(id, config, counter, numImgs);
  4578. }
  4579. config.validated = true;
  4580. }
  4581. });
  4582. },
  4583. _getResizedImage: function (id, config, counter, numImgs) {
  4584. var self = this, img = $(config.img)[0], width = img.naturalWidth, height = img.naturalHeight, blob,
  4585. ratio = 1, maxWidth = self.maxImageWidth || width, maxHeight = self.maxImageHeight || height,
  4586. isValidImage = !!(width && height), chkWidth, chkHeight, canvas = self.imageCanvas, dataURI,
  4587. context = self.imageCanvasContext, type = config.typ, pid = config.pid, ind = config.ind,
  4588. $thumb = config.thumb, throwError, msg, exifObj = config.exifObj, exifStr, file, params, evParams;
  4589. throwError = function (msg, params, ev) {
  4590. if (self.isAjaxUpload) {
  4591. self._showFileError(msg, params, ev);
  4592. } else {
  4593. self._showError(msg, params, ev);
  4594. }
  4595. self._setPreviewError($thumb);
  4596. };
  4597. file = self.fileManager.getFile(id);
  4598. params = {id: pid, 'index': ind, fileId: id};
  4599. evParams = [id, pid, ind];
  4600. if (!file || !isValidImage || (width <= maxWidth && height <= maxHeight)) {
  4601. if (isValidImage && file) {
  4602. self._raise('fileimageresized', evParams);
  4603. }
  4604. counter.val++;
  4605. if (counter.val === numImgs) {
  4606. self._raise('fileimagesresized');
  4607. }
  4608. if (!isValidImage) {
  4609. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4610. return;
  4611. }
  4612. }
  4613. type = type || self.resizeDefaultImageType;
  4614. chkWidth = width > maxWidth;
  4615. chkHeight = height > maxHeight;
  4616. if (self.resizePreference === 'width') {
  4617. ratio = chkWidth ? maxWidth / width : (chkHeight ? maxHeight / height : 1);
  4618. } else {
  4619. ratio = chkHeight ? maxHeight / height : (chkWidth ? maxWidth / width : 1);
  4620. }
  4621. self._resetCanvas();
  4622. width *= ratio;
  4623. height *= ratio;
  4624. canvas.width = width;
  4625. canvas.height = height;
  4626. try {
  4627. context.drawImage(img, 0, 0, width, height);
  4628. dataURI = canvas.toDataURL(type, self.resizeQuality);
  4629. if (exifObj) {
  4630. exifStr = window.piexif.dump(exifObj);
  4631. dataURI = window.piexif.insert(exifStr, dataURI);
  4632. }
  4633. blob = $h.dataURI2Blob(dataURI);
  4634. self.fileManager.setFile(id, blob);
  4635. self._raise('fileimageresized', evParams);
  4636. counter.val++;
  4637. if (counter.val === numImgs) {
  4638. self._raise('fileimagesresized', [undefined, undefined]);
  4639. }
  4640. if (!(blob instanceof Blob)) {
  4641. throwError(self.msgImageResizeError, params, 'fileimageresizeerror');
  4642. }
  4643. } catch (err) {
  4644. counter.val++;
  4645. if (counter.val === numImgs) {
  4646. self._raise('fileimagesresized', [undefined, undefined]);
  4647. }
  4648. msg = self.msgImageResizeException.replace('{errors}', err.message);
  4649. throwError(msg, params, 'fileimageresizeexception');
  4650. }
  4651. },
  4652. _showProgress: function () {
  4653. var self = this;
  4654. if (self.$progress && self.$progress.length) {
  4655. self.$progress.show();
  4656. }
  4657. },
  4658. _hideProgress: function () {
  4659. var self = this;
  4660. if (self.$progress && self.$progress.length) {
  4661. self.$progress.hide();
  4662. }
  4663. },
  4664. _initBrowse: function ($container) {
  4665. var self = this, $el = self.$element;
  4666. if (self.showBrowse) {
  4667. self.$btnFile = $container.find('.btn-file').append($el);
  4668. } else {
  4669. $el.appendTo($container).attr('tabindex', -1);
  4670. $h.addCss($el, 'file-no-browse');
  4671. }
  4672. },
  4673. _initClickable: function () {
  4674. var self = this, $zone, $tmpZone;
  4675. if (!self.isClickable) {
  4676. return;
  4677. }
  4678. $zone = self.$dropZone;
  4679. if (!self.isAjaxUpload) {
  4680. $tmpZone = self.$preview.find('.file-default-preview');
  4681. if ($tmpZone.length) {
  4682. $zone = $tmpZone;
  4683. }
  4684. }
  4685. $h.addCss($zone, 'clickable');
  4686. $zone.attr('tabindex', -1);
  4687. self._handler($zone, 'click', function (e) {
  4688. var $tar = $(e.target);
  4689. if (!self.$errorContainer.is(':visible') && (!$tar.parents(
  4690. '.file-preview-thumbnails').length || $tar.parents(
  4691. '.file-default-preview').length)) {
  4692. self.$element.data('zoneClicked', true).trigger('click');
  4693. $zone.blur();
  4694. }
  4695. });
  4696. },
  4697. _initCaption: function () {
  4698. var self = this, cap = self.initialCaption || '';
  4699. if (self.overwriteInitial || $h.isEmpty(cap)) {
  4700. self.$caption.val('');
  4701. return false;
  4702. }
  4703. self._setCaption(cap);
  4704. return true;
  4705. },
  4706. _setCaption: function (content, isError) {
  4707. var self = this, title, out, icon, n, cap, file;
  4708. if (!self.$caption.length) {
  4709. return;
  4710. }
  4711. self.$captionContainer.removeClass('icon-visible');
  4712. if (isError) {
  4713. title = $('<div>' + self.msgValidationError + '</div>').text();
  4714. n = self.fileManager.count();
  4715. if (n) {
  4716. file = self.fileManager.getFirstFile();
  4717. cap = n === 1 && file ? file.nameFmt : self._getMsgSelected(n);
  4718. } else {
  4719. cap = self._getMsgSelected(self.msgNo);
  4720. }
  4721. out = $h.isEmpty(content) ? cap : content;
  4722. icon = '<span class="' + self.msgValidationErrorClass + '">' + self.msgValidationErrorIcon + '</span>';
  4723. } else {
  4724. if ($h.isEmpty(content)) {
  4725. return;
  4726. }
  4727. title = $('<div>' + content + '</div>').text();
  4728. out = title;
  4729. icon = self._getLayoutTemplate('fileIcon');
  4730. }
  4731. self.$captionContainer.addClass('icon-visible');
  4732. self.$caption.attr('title', title).val(out);
  4733. $h.setHtml(self.$captionIcon, icon);
  4734. },
  4735. _createContainer: function () {
  4736. var self = this, attribs = {'class': 'file-input file-input-new' + (self.rtl ? ' kv-rtl' : '')},
  4737. $container = $h.createElement($h.cspBuffer.stash(self._renderMain()));
  4738. $h.cspBuffer.apply($container);
  4739. $container.insertBefore(self.$element).attr(attribs);
  4740. self._initBrowse($container);
  4741. if (self.theme) {
  4742. $container.addClass('theme-' + self.theme);
  4743. }
  4744. return $container;
  4745. },
  4746. _refreshContainer: function () {
  4747. var self = this, $container = self.$container, $el = self.$element;
  4748. $el.insertAfter($container);
  4749. $h.setHtml($container, self._renderMain());
  4750. self._initBrowse($container);
  4751. self._validateDisabled();
  4752. },
  4753. _validateDisabled: function () {
  4754. var self = this;
  4755. self.$caption.attr({readonly: self.isDisabled});
  4756. },
  4757. _renderMain: function () {
  4758. var self = this,
  4759. dropCss = self.dropZoneEnabled ? ' file-drop-zone' : 'file-drop-disabled',
  4760. close = !self.showClose ? '' : self._getLayoutTemplate('close'),
  4761. preview = !self.showPreview ? '' : self._getLayoutTemplate('preview')
  4762. .setTokens({'class': self.previewClass, 'dropClass': dropCss}),
  4763. css = self.isDisabled ? self.captionClass + ' file-caption-disabled' : self.captionClass,
  4764. caption = self.captionTemplate.setTokens({'class': css + ' kv-fileinput-caption'});
  4765. return self.mainTemplate.setTokens({
  4766. 'class': self.mainClass + (!self.showBrowse && self.showCaption ? ' no-browse' : ''),
  4767. 'preview': preview,
  4768. 'close': close,
  4769. 'caption': caption,
  4770. 'upload': self._renderButton('upload'),
  4771. 'remove': self._renderButton('remove'),
  4772. 'cancel': self._renderButton('cancel'),
  4773. 'pause': self._renderButton('pause'),
  4774. 'browse': self._renderButton('browse')
  4775. });
  4776. },
  4777. _renderButton: function (type) {
  4778. var self = this, tmplt = self._getLayoutTemplate('btnDefault'), css = self[type + 'Class'],
  4779. title = self[type + 'Title'], icon = self[type + 'Icon'], label = self[type + 'Label'],
  4780. status = self.isDisabled ? ' disabled' : '', btnType = 'button';
  4781. switch (type) {
  4782. case 'remove':
  4783. if (!self.showRemove) {
  4784. return '';
  4785. }
  4786. break;
  4787. case 'cancel':
  4788. if (!self.showCancel) {
  4789. return '';
  4790. }
  4791. css += ' kv-hidden';
  4792. break;
  4793. case 'pause':
  4794. if (!self.showPause) {
  4795. return '';
  4796. }
  4797. css += ' kv-hidden';
  4798. break;
  4799. case 'upload':
  4800. if (!self.showUpload) {
  4801. return '';
  4802. }
  4803. if (self.isAjaxUpload && !self.isDisabled) {
  4804. tmplt = self._getLayoutTemplate('btnLink').replace('{href}', self.uploadUrl);
  4805. } else {
  4806. btnType = 'submit';
  4807. }
  4808. break;
  4809. case 'browse':
  4810. if (!self.showBrowse) {
  4811. return '';
  4812. }
  4813. tmplt = self._getLayoutTemplate('btnBrowse');
  4814. break;
  4815. default:
  4816. return '';
  4817. }
  4818. css += type === 'browse' ? ' btn-file' : ' fileinput-' + type + ' fileinput-' + type + '-button';
  4819. if (!$h.isEmpty(label)) {
  4820. label = ' <span class="' + self.buttonLabelClass + '">' + label + '</span>';
  4821. }
  4822. return tmplt.setTokens({
  4823. 'type': btnType, 'css': css, 'title': title, 'status': status, 'icon': icon, 'label': label
  4824. });
  4825. },
  4826. _renderThumbProgress: function () {
  4827. var self = this;
  4828. return '<div class="file-thumb-progress kv-hidden">' +
  4829. self.progressInfoTemplate.setTokens({percent: 101, status: self.msgUploadBegin, stats: ''}) +
  4830. '</div>';
  4831. },
  4832. _renderFileFooter: function (cat, caption, size, width, isError) {
  4833. var self = this, config = self.fileActionSettings, rem = config.showRemove, drg = config.showDrag,
  4834. upl = config.showUpload, zoom = config.showZoom, out, params,
  4835. template = self._getLayoutTemplate('footer'), tInd = self._getLayoutTemplate('indicator'),
  4836. ind = isError ? config.indicatorError : config.indicatorNew,
  4837. title = isError ? config.indicatorErrorTitle : config.indicatorNewTitle,
  4838. indicator = tInd.setTokens({'indicator': ind, 'indicatorTitle': title});
  4839. size = self._getSize(size);
  4840. params = {type: cat, caption: caption, size: size, width: width, progress: '', indicator: indicator};
  4841. if (self.isAjaxUpload) {
  4842. params.progress = self._renderThumbProgress();
  4843. params.actions = self._renderFileActions(params, upl, false, rem, zoom, drg, false, false, false);
  4844. } else {
  4845. params.actions = self._renderFileActions(params, false, false, false, zoom, drg, false, false, false);
  4846. }
  4847. out = template.setTokens(params);
  4848. out = $h.replaceTags(out, self.previewThumbTags);
  4849. return out;
  4850. },
  4851. _renderFileActions: function (
  4852. cfg,
  4853. showUpl,
  4854. showDwn,
  4855. showDel,
  4856. showZoom,
  4857. showDrag,
  4858. disabled,
  4859. url,
  4860. key,
  4861. isInit,
  4862. dUrl,
  4863. dFile
  4864. ) {
  4865. var self = this;
  4866. if (!cfg.type && isInit) {
  4867. cfg.type = 'image';
  4868. }
  4869. if (self.enableResumableUpload) {
  4870. showUpl = false;
  4871. } else {
  4872. if (typeof showUpl === 'function') {
  4873. showUpl = showUpl(cfg);
  4874. }
  4875. }
  4876. if (typeof showDwn === 'function') {
  4877. showDwn = showDwn(cfg);
  4878. }
  4879. if (typeof showDel === 'function') {
  4880. showDel = showDel(cfg);
  4881. }
  4882. if (typeof showZoom === 'function') {
  4883. showZoom = showZoom(cfg);
  4884. }
  4885. if (typeof showDrag === 'function') {
  4886. showDrag = showDrag(cfg);
  4887. }
  4888. if (!showUpl && !showDwn && !showDel && !showZoom && !showDrag) {
  4889. return '';
  4890. }
  4891. var vUrl = url === false ? '' : ' data-url="' + url + '"', btnZoom = '', btnDrag = '', css,
  4892. vKey = key === false ? '' : ' data-key="' + key + '"', btnDelete = '', btnUpload = '', btnDownload = '',
  4893. template = self._getLayoutTemplate('actions'), config = self.fileActionSettings,
  4894. otherButtons = self.otherActionButtons.setTokens({'dataKey': vKey, 'key': key}),
  4895. removeClass = disabled ? config.removeClass + ' disabled' : config.removeClass;
  4896. if (showDel) {
  4897. btnDelete = self._getLayoutTemplate('actionDelete').setTokens({
  4898. 'removeClass': removeClass,
  4899. 'removeIcon': config.removeIcon,
  4900. 'removeTitle': config.removeTitle,
  4901. 'dataUrl': vUrl,
  4902. 'dataKey': vKey,
  4903. 'key': key
  4904. });
  4905. }
  4906. if (showUpl) {
  4907. btnUpload = self._getLayoutTemplate('actionUpload').setTokens({
  4908. 'uploadClass': config.uploadClass,
  4909. 'uploadIcon': config.uploadIcon,
  4910. 'uploadTitle': config.uploadTitle
  4911. });
  4912. }
  4913. if (showDwn) {
  4914. btnDownload = self._getLayoutTemplate('actionDownload').setTokens({
  4915. 'downloadClass': config.downloadClass,
  4916. 'downloadIcon': config.downloadIcon,
  4917. 'downloadTitle': config.downloadTitle,
  4918. 'downloadUrl': dUrl || self.initialPreviewDownloadUrl
  4919. });
  4920. btnDownload = btnDownload.setTokens({'filename': dFile, 'key': key});
  4921. }
  4922. if (showZoom) {
  4923. btnZoom = self._getLayoutTemplate('actionZoom').setTokens({
  4924. 'zoomClass': config.zoomClass,
  4925. 'zoomIcon': config.zoomIcon,
  4926. 'zoomTitle': config.zoomTitle
  4927. });
  4928. }
  4929. if (showDrag && isInit) {
  4930. css = 'drag-handle-init ' + config.dragClass;
  4931. btnDrag = self._getLayoutTemplate('actionDrag').setTokens({
  4932. 'dragClass': css,
  4933. 'dragTitle': config.dragTitle,
  4934. 'dragIcon': config.dragIcon
  4935. });
  4936. }
  4937. return template.setTokens({
  4938. 'delete': btnDelete,
  4939. 'upload': btnUpload,
  4940. 'download': btnDownload,
  4941. 'zoom': btnZoom,
  4942. 'drag': btnDrag,
  4943. 'other': otherButtons
  4944. });
  4945. },
  4946. _browse: function (e) {
  4947. var self = this;
  4948. if (e && e.isDefaultPrevented() || !self._raise('filebrowse')) {
  4949. return;
  4950. }
  4951. if (self.isError && !self.isAjaxUpload) {
  4952. self.clear();
  4953. }
  4954. if (self.focusCaptionOnBrowse) {
  4955. self.$captionContainer.focus();
  4956. }
  4957. },
  4958. _change: function (e) {
  4959. var self = this;
  4960. if (self.changeTriggered) {
  4961. return;
  4962. }
  4963. var $el = self.$element, isDragDrop = arguments.length > 1, isAjaxUpload = self.isAjaxUpload,
  4964. tfiles, files = isDragDrop ? arguments[1] : $el[0].files, ctr = self.fileManager.count(),
  4965. total, initCount, len, isSingleUpl = $h.isEmpty($el.attr('multiple')),
  4966. maxCount = !isAjaxUpload && isSingleUpl ? 1 : self.maxFileCount, maxTotCount = self.maxTotalFileCount,
  4967. inclAll = maxTotCount > 0 && maxTotCount > maxCount, flagSingle = (isSingleUpl && ctr > 0),
  4968. throwError = function (mesg, file, previewId, index) {
  4969. var p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files), {id: previewId, index: index}),
  4970. p2 = {id: previewId, index: index, file: file, files: files};
  4971. self.isPersistentError = true;
  4972. return isAjaxUpload ? self._showFileError(mesg, p1) : self._showError(mesg, p2);
  4973. },
  4974. maxCountCheck = function (n, m, all) {
  4975. var msg = all ? self.msgTotalFilesTooMany : self.msgFilesTooMany;
  4976. msg = msg.replace('{m}', m).replace('{n}', n);
  4977. self.isError = throwError(msg, null, null, null);
  4978. self.$captionContainer.removeClass('icon-visible');
  4979. self._setCaption('', true);
  4980. self.$container.removeClass('file-input-new file-input-ajax-new');
  4981. };
  4982. self.reader = null;
  4983. self._resetUpload();
  4984. self._hideFileIcon();
  4985. if (self.dropZoneEnabled) {
  4986. self.$container.find('.file-drop-zone .' + self.dropZoneTitleClass).remove();
  4987. }
  4988. if (!isAjaxUpload) {
  4989. if (e.target && e.target.files === undefined) {
  4990. files = e.target.value ? [{name: e.target.value.replace(/^.+\\/, '')}] : [];
  4991. } else {
  4992. files = e.target.files || {};
  4993. }
  4994. }
  4995. tfiles = files;
  4996. if ($h.isEmpty(tfiles) || tfiles.length === 0) {
  4997. if (!isAjaxUpload) {
  4998. self.clear();
  4999. }
  5000. self._raise('fileselectnone');
  5001. return;
  5002. }
  5003. self._resetErrors();
  5004. len = tfiles.length;
  5005. initCount = isAjaxUpload ? (self.fileManager.count() + len) : len;
  5006. total = self._getFileCount(initCount, inclAll ? false : undefined);
  5007. if (maxCount > 0 && total > maxCount) {
  5008. if (!self.autoReplace || len > maxCount) {
  5009. maxCountCheck((self.autoReplace && len > maxCount ? len : total), maxCount);
  5010. return;
  5011. }
  5012. if (total > maxCount) {
  5013. self._resetPreviewThumbs(isAjaxUpload);
  5014. }
  5015. } else {
  5016. if (inclAll) {
  5017. total = self._getFileCount(initCount, true);
  5018. if (maxTotCount > 0 && total > maxTotCount) {
  5019. if (!self.autoReplace || len > maxCount) {
  5020. maxCountCheck((self.autoReplace && len > maxTotCount ? len : total), maxTotCount, true);
  5021. return;
  5022. }
  5023. if (total > maxCount) {
  5024. self._resetPreviewThumbs(isAjaxUpload);
  5025. }
  5026. }
  5027. }
  5028. if (!isAjaxUpload || flagSingle) {
  5029. self._resetPreviewThumbs(false);
  5030. if (flagSingle) {
  5031. self.clearFileStack();
  5032. }
  5033. } else {
  5034. if (isAjaxUpload && ctr === 0 && (!self.previewCache.count(true) || self.overwriteInitial)) {
  5035. self._resetPreviewThumbs(true);
  5036. }
  5037. }
  5038. }
  5039. self.readFiles(tfiles);
  5040. },
  5041. _abort: function (params) {
  5042. var self = this, data;
  5043. if (self.ajaxAborted && typeof self.ajaxAborted === 'object' && self.ajaxAborted.message !== undefined) {
  5044. data = $.extend(true, {}, self._getOutData(null), params);
  5045. data.abortData = self.ajaxAborted.data || {};
  5046. data.abortMessage = self.ajaxAborted.message;
  5047. self._setProgress(101, self.$progress, self.msgCancelled);
  5048. self._showFileError(self.ajaxAborted.message, data, 'filecustomerror');
  5049. self.cancel();
  5050. return true;
  5051. }
  5052. return !!self.ajaxAborted;
  5053. },
  5054. _resetFileStack: function () {
  5055. var self = this, i = 0;
  5056. self._getThumbs().each(function () {
  5057. var $thumb = $(this), ind = $thumb.attr('data-fileindex'), pid = $thumb.attr('id');
  5058. if (ind === '-1' || ind === -1) {
  5059. return;
  5060. }
  5061. if (!self._getThumbFile($thumb)) {
  5062. $thumb.attr({'data-fileindex': i});
  5063. i++;
  5064. } else {
  5065. $thumb.attr({'data-fileindex': '-1'});
  5066. }
  5067. self._getZoom(pid).attr({
  5068. 'data-fileindex': $thumb.attr('data-fileindex')
  5069. });
  5070. });
  5071. },
  5072. _isFileSelectionValid: function (cnt) {
  5073. var self = this;
  5074. cnt = cnt || 0;
  5075. if (self.required && !self.getFilesCount()) {
  5076. self.$errorContainer.html('');
  5077. self._showFileError(self.msgFileRequired);
  5078. return false;
  5079. }
  5080. if (self.minFileCount > 0 && self._getFileCount(cnt) < self.minFileCount) {
  5081. self._noFilesError({});
  5082. return false;
  5083. }
  5084. return true;
  5085. },
  5086. _canPreview: function (file) {
  5087. var self = this;
  5088. if (!file || !self.showPreview || !self.$preview || !self.$preview.length) {
  5089. return false;
  5090. }
  5091. var name = file.name || '', type = file.type || '', size = (file.size || 0) / 1000,
  5092. cat = self._parseFileType(type, name), allowedTypes, allowedMimes, allowedExts, skipPreview,
  5093. types = self.allowedPreviewTypes, mimes = self.allowedPreviewMimeTypes,
  5094. exts = self.allowedPreviewExtensions || [], dTypes = self.disabledPreviewTypes,
  5095. dMimes = self.disabledPreviewMimeTypes, dExts = self.disabledPreviewExtensions || [],
  5096. maxSize = self.maxFilePreviewSize && parseFloat(self.maxFilePreviewSize) || 0,
  5097. expAllExt = new RegExp('\\.(' + exts.join('|') + ')$', 'i'),
  5098. expDisExt = new RegExp('\\.(' + dExts.join('|') + ')$', 'i');
  5099. allowedTypes = !types || types.indexOf(cat) !== -1;
  5100. allowedMimes = !mimes || mimes.indexOf(type) !== -1;
  5101. allowedExts = !exts.length || $h.compare(name, expAllExt);
  5102. skipPreview = (dTypes && dTypes.indexOf(cat) !== -1) || (dMimes && dMimes.indexOf(type) !== -1) ||
  5103. (dExts.length && $h.compare(name, expDisExt)) || (maxSize && !isNaN(maxSize) && size > maxSize);
  5104. return !skipPreview && (allowedTypes || allowedMimes || allowedExts);
  5105. },
  5106. addToStack: function (file, id) {
  5107. this.fileManager.add(file, id);
  5108. },
  5109. clearFileStack: function () {
  5110. var self = this;
  5111. self.fileManager.clear();
  5112. self._initResumableUpload();
  5113. if (self.enableResumableUpload) {
  5114. if (self.showPause === null) {
  5115. self.showPause = true;
  5116. }
  5117. if (self.showCancel === null) {
  5118. self.showCancel = false;
  5119. }
  5120. } else {
  5121. self.showPause = false;
  5122. if (self.showCancel === null) {
  5123. self.showCancel = true;
  5124. }
  5125. }
  5126. return self.$element;
  5127. },
  5128. getFileStack: function () {
  5129. return this.fileManager.stack;
  5130. },
  5131. getFileList: function () {
  5132. return this.fileManager.list();
  5133. },
  5134. getFilesSize: function () {
  5135. return this.fileManager.getTotalSize();
  5136. },
  5137. getFilesCount: function (includeInitial) {
  5138. var self = this, len = self.isAjaxUpload ? self.fileManager.count() : self._inputFileCount();
  5139. if (includeInitial) {
  5140. len += self.previewCache.count(true);
  5141. }
  5142. return self._getFileCount(len);
  5143. },
  5144. readFiles: function (files) {
  5145. this.reader = new FileReader();
  5146. var self = this, reader = self.reader, $container = self.$previewContainer,
  5147. $status = self.$previewStatus, msgLoading = self.msgLoading, msgProgress = self.msgProgress,
  5148. previewInitId = self.previewInitId, numFiles = files.length, settings = self.fileTypeSettings,
  5149. readFile, fileTypes = self.allowedFileTypes, typLen = fileTypes ? fileTypes.length : 0,
  5150. fileExt = self.allowedFileExtensions, strExt = $h.isEmpty(fileExt) ? '' : fileExt.join(', '),
  5151. throwError = function (msg, file, previewId, index, fileId) {
  5152. var $thumb, p1 = $.extend(true, {}, self._getOutData(null, {}, {}, files),
  5153. {id: previewId, index: index, fileId: fileId}),
  5154. p2 = {id: previewId, index: index, fileId: fileId, file: file, files: files};
  5155. self._previewDefault(file, true);
  5156. $thumb = self._getFrame(previewId, true);
  5157. if (self.isAjaxUpload) {
  5158. setTimeout(function () {
  5159. readFile(index + 1);
  5160. }, self.processDelay);
  5161. } else {
  5162. self.unlock();
  5163. numFiles = 0;
  5164. }
  5165. if (self.removeFromPreviewOnError && $thumb.length) {
  5166. $thumb.remove();
  5167. } else {
  5168. self._initFileActions();
  5169. $thumb.find('.kv-file-upload').remove();
  5170. }
  5171. self.isPersistentError = true;
  5172. self.isError = self.isAjaxUpload ? self._showFileError(msg, p1) : self._showError(msg, p2);
  5173. self._updateFileDetails(numFiles);
  5174. };
  5175. self.fileManager.clearImages();
  5176. $.each(files, function (key, file) {
  5177. var func = self.fileTypeSettings.image;
  5178. if (func && func(file.type)) {
  5179. self.fileManager.totalImages++;
  5180. }
  5181. });
  5182. readFile = function (i) {
  5183. var $error = self.$errorContainer, errors, fm = self.fileManager;
  5184. if (i >= numFiles) {
  5185. self.unlock();
  5186. if (self.duplicateErrors.length) {
  5187. errors = '<li>' + self.duplicateErrors.join('</li><li>') + '</li>';
  5188. if ($error.find('ul').length === 0) {
  5189. $h.setHtml($error, self.errorCloseButton + '<ul>' + errors + '</ul>');
  5190. } else {
  5191. $error.find('ul').append(errors);
  5192. }
  5193. $error.fadeIn(self.fadeDelay);
  5194. self._handler($error.find('.kv-error-close'), 'click', function () {
  5195. $error.fadeOut(self.fadeDelay);
  5196. });
  5197. self.duplicateErrors = [];
  5198. }
  5199. if (self.isAjaxUpload) {
  5200. self._raise('filebatchselected', [fm.stack]);
  5201. if (fm.count() === 0 && !self.isError) {
  5202. self.reset();
  5203. }
  5204. } else {
  5205. self._raise('filebatchselected', [files]);
  5206. }
  5207. $container.removeClass('file-thumb-loading');
  5208. $status.html('');
  5209. return;
  5210. }
  5211. self.lock(true);
  5212. var file = files[i], id = self._getFileId(file), previewId = previewInitId + '-' + id, fSizeKB, j, msg,
  5213. fnText = settings.text, fnImage = settings.image, fnHtml = settings.html, typ, chk, typ1, typ2,
  5214. caption = self._getFileName(file, ''), fileSize = (file && file.size || 0) / 1000,
  5215. fileExtExpr = '', previewData = $h.createObjectURL(file), fileCount = 0,
  5216. strTypes = '', fileId, canLoad, fileReaderAborted = false,
  5217. func, knownTypes = 0, isImage, txtFlag, processFileLoaded = function () {
  5218. var msg = msgProgress.setTokens({
  5219. 'index': i + 1,
  5220. 'files': numFiles,
  5221. 'percent': 50,
  5222. 'name': caption
  5223. });
  5224. setTimeout(function () {
  5225. $status.html(msg);
  5226. self._updateFileDetails(numFiles);
  5227. readFile(i + 1);
  5228. }, self.processDelay);
  5229. if (self._raise('fileloaded', [file, previewId, id, i, reader]) && self.isAjaxUpload) {
  5230. fm.add(file);
  5231. }
  5232. };
  5233. if (!file) {
  5234. return;
  5235. }
  5236. fileId = fm.getId(file);
  5237. if (typLen > 0) {
  5238. for (j = 0; j < typLen; j++) {
  5239. typ1 = fileTypes[j];
  5240. typ2 = self.msgFileTypes[typ1] || typ1;
  5241. strTypes += j === 0 ? typ2 : ', ' + typ2;
  5242. }
  5243. }
  5244. if (caption === false) {
  5245. readFile(i + 1);
  5246. return;
  5247. }
  5248. if (caption.length === 0) {
  5249. msg = self.msgInvalidFileName.replace('{name}', $h.htmlEncode($h.getFileName(file), '[unknown]'));
  5250. throwError(msg, file, previewId, i, fileId);
  5251. return;
  5252. }
  5253. if (!$h.isEmpty(fileExt)) {
  5254. fileExtExpr = new RegExp('\\.(' + fileExt.join('|') + ')$', 'i');
  5255. }
  5256. fSizeKB = fileSize.toFixed(2);
  5257. if (self.isAjaxUpload && fm.exists(fileId) || self._getFrame(previewId, true).length) {
  5258. var p2 = {id: previewId, index: i, fileId: fileId, file: file, files: files};
  5259. msg = self.msgDuplicateFile.setTokens({name: caption, size: fSizeKB});
  5260. if (self.isAjaxUpload) {
  5261. self.duplicateErrors.push(msg);
  5262. self.isDuplicateError = true;
  5263. self._raise('fileduplicateerror', [file, fileId, caption, fSizeKB, previewId, i]);
  5264. readFile(i + 1);
  5265. self._updateFileDetails(numFiles);
  5266. } else {
  5267. self._showError(msg, p2);
  5268. self.unlock();
  5269. numFiles = 0;
  5270. self._clearFileInput();
  5271. self.reset();
  5272. self._updateFileDetails(numFiles);
  5273. }
  5274. return;
  5275. }
  5276. if (self.maxFileSize > 0 && fileSize > self.maxFileSize) {
  5277. msg = self.msgSizeTooLarge.setTokens({
  5278. 'name': caption,
  5279. 'size': fSizeKB,
  5280. 'maxSize': self.maxFileSize
  5281. });
  5282. throwError(msg, file, previewId, i, fileId);
  5283. return;
  5284. }
  5285. if (self.minFileSize !== null && fileSize <= $h.getNum(self.minFileSize)) {
  5286. msg = self.msgSizeTooSmall.setTokens({
  5287. 'name': caption,
  5288. 'size': fSizeKB,
  5289. 'minSize': self.minFileSize
  5290. });
  5291. throwError(msg, file, previewId, i, fileId);
  5292. return;
  5293. }
  5294. if (!$h.isEmpty(fileTypes) && $h.isArray(fileTypes)) {
  5295. for (j = 0; j < fileTypes.length; j += 1) {
  5296. typ = fileTypes[j];
  5297. func = settings[typ];
  5298. fileCount += !func || (typeof func !== 'function') ? 0 : (func(file.type,
  5299. $h.getFileName(file)) ? 1 : 0);
  5300. }
  5301. if (fileCount === 0) {
  5302. msg = self.msgInvalidFileType.setTokens({name: caption, types: strTypes});
  5303. throwError(msg, file, previewId, i, fileId);
  5304. return;
  5305. }
  5306. }
  5307. if (fileCount === 0 && !$h.isEmpty(fileExt) && $h.isArray(fileExt) && !$h.isEmpty(fileExtExpr)) {
  5308. chk = $h.compare(caption, fileExtExpr);
  5309. fileCount += $h.isEmpty(chk) ? 0 : chk.length;
  5310. if (fileCount === 0) {
  5311. msg = self.msgInvalidFileExtension.setTokens({name: caption, extensions: strExt});
  5312. throwError(msg, file, previewId, i, fileId);
  5313. return;
  5314. }
  5315. }
  5316. if (!self._canPreview(file)) {
  5317. canLoad = self.isAjaxUpload && self._raise('filebeforeload', [file, i, reader]);
  5318. if (self.isAjaxUpload && canLoad) {
  5319. fm.add(file);
  5320. }
  5321. if (self.showPreview && canLoad) {
  5322. $container.addClass('file-thumb-loading');
  5323. self._previewDefault(file);
  5324. self._initFileActions();
  5325. }
  5326. setTimeout(function () {
  5327. if (canLoad) {
  5328. self._updateFileDetails(numFiles);
  5329. }
  5330. readFile(i + 1);
  5331. self._raise('fileloaded', [file, previewId, id, i]);
  5332. }, 10);
  5333. return;
  5334. }
  5335. isImage = fnImage(file.type, caption);
  5336. $status.html(msgLoading.replace('{index}', i + 1).replace('{files}', numFiles));
  5337. $container.addClass('file-thumb-loading');
  5338. reader.onerror = function (evt) {
  5339. self._errorHandler(evt, caption);
  5340. };
  5341. reader.onload = function (theFile) {
  5342. var hex, fileInfo, uint, byte, bytes = [], contents, mime, readImage = function () {
  5343. var newReader = new FileReader();
  5344. newReader.onerror = function (theFileNew) {
  5345. self._errorHandler(theFileNew, caption);
  5346. };
  5347. newReader.onload = function (theFileNew) {
  5348. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5349. fileReaderAborted = true;
  5350. self._resetCaption();
  5351. reader.abort();
  5352. $status.html('');
  5353. $container.removeClass('file-thumb-loading');
  5354. self.enable();
  5355. return;
  5356. }
  5357. self._previewFile(i, file, theFileNew, previewData, fileInfo);
  5358. self._initFileActions();
  5359. processFileLoaded();
  5360. };
  5361. newReader.readAsDataURL(file);
  5362. };
  5363. fileInfo = {'name': caption, 'type': file.type};
  5364. $.each(settings, function (k, f) {
  5365. if (k !== 'object' && k !== 'other' && typeof f === 'function' && f(file.type, caption)) {
  5366. knownTypes++;
  5367. }
  5368. });
  5369. if (knownTypes === 0) { // auto detect mime types from content if no known file types detected
  5370. uint = new Uint8Array(theFile.target.result);
  5371. for (j = 0; j < uint.length; j++) {
  5372. byte = uint[j].toString(16);
  5373. bytes.push(byte);
  5374. }
  5375. hex = bytes.join('').toLowerCase().substring(0, 8);
  5376. mime = $h.getMimeType(hex, '', '');
  5377. if ($h.isEmpty(mime)) { // look for ascii text content
  5378. contents = $h.arrayBuffer2String(reader.result);
  5379. mime = $h.isSvg(contents) ? 'image/svg+xml' : $h.getMimeType(hex, contents, file.type);
  5380. }
  5381. fileInfo = {'name': caption, 'type': mime};
  5382. isImage = fnImage(mime, '');
  5383. if (isImage) {
  5384. readImage(txtFlag);
  5385. return;
  5386. }
  5387. }
  5388. if (self.isAjaxUpload && !self._raise('filebeforeload', [file, i, reader])) {
  5389. fileReaderAborted = true;
  5390. self._resetCaption();
  5391. reader.abort();
  5392. $status.html('');
  5393. $container.removeClass('file-thumb-loading');
  5394. self.enable();
  5395. return;
  5396. }
  5397. self._previewFile(i, file, theFile, previewData, fileInfo);
  5398. self._initFileActions();
  5399. processFileLoaded();
  5400. };
  5401. reader.onprogress = function (data) {
  5402. if (data.lengthComputable) {
  5403. var fact = (data.loaded / data.total) * 100, progress = Math.ceil(fact);
  5404. msg = msgProgress.setTokens({
  5405. 'index': i + 1,
  5406. 'files': numFiles,
  5407. 'percent': progress,
  5408. 'name': caption
  5409. });
  5410. setTimeout(function () {
  5411. if (!fileReaderAborted) {
  5412. $status.html(msg);
  5413. }
  5414. }, self.processDelay);
  5415. }
  5416. };
  5417. if (isImage) {
  5418. reader.readAsDataURL(file);
  5419. } else {
  5420. reader.readAsArrayBuffer(file);
  5421. }
  5422. };
  5423. readFile(0);
  5424. self._updateFileDetails(numFiles, true);
  5425. },
  5426. lock: function (selectMode) {
  5427. var self = this, $container = self.$container;
  5428. self._resetErrors();
  5429. self.disable();
  5430. if (!selectMode && self.showCancel) {
  5431. $container.find('.fileinput-cancel').show();
  5432. }
  5433. if (!selectMode && self.showPause) {
  5434. $container.find('.fileinput-pause').show();
  5435. }
  5436. self._raise('filelock', [self.fileManager.stack, self._getExtraData()]);
  5437. return self.$element;
  5438. },
  5439. unlock: function (reset) {
  5440. var self = this, $container = self.$container;
  5441. if (reset === undefined) {
  5442. reset = true;
  5443. }
  5444. self.enable();
  5445. $container.removeClass('is-locked');
  5446. if (self.showCancel) {
  5447. $container.find('.fileinput-cancel').hide();
  5448. }
  5449. if (self.showPause) {
  5450. $container.find('.fileinput-pause').hide();
  5451. }
  5452. if (reset) {
  5453. self._resetFileStack();
  5454. }
  5455. self._raise('fileunlock', [self.fileManager.stack, self._getExtraData()]);
  5456. return self.$element;
  5457. },
  5458. resume: function () {
  5459. var self = this, fm = self.fileManager, flag = false, rm = self.resumableManager;
  5460. fm.bpsLog = [];
  5461. fm.bps = 0;
  5462. if (!self.enableResumableUpload) {
  5463. return self.$element;
  5464. }
  5465. if (self.paused) {
  5466. self._toggleResumableProgress(self.progressPauseTemplate, self.msgUploadResume);
  5467. } else {
  5468. flag = true;
  5469. }
  5470. self.paused = false;
  5471. if (flag) {
  5472. self._toggleResumableProgress(self.progressInfoTemplate, self.msgUploadBegin);
  5473. }
  5474. setTimeout(function () {
  5475. rm.upload();
  5476. }, self.processDelay);
  5477. return self.$element;
  5478. },
  5479. pause: function () {
  5480. var self = this, rm = self.resumableManager, xhr = self.ajaxRequests, len = xhr.length, i,
  5481. pct = rm.getProgress(), actions = self.fileActionSettings, tm = self.taskManager,
  5482. pool = tm.getPool(rm.id);
  5483. if (!self.enableResumableUpload) {
  5484. return self.$element;
  5485. } else {
  5486. if (pool) {
  5487. pool.cancel();
  5488. }
  5489. }
  5490. self._raise('fileuploadpaused', [self.fileManager, rm]);
  5491. if (len > 0) {
  5492. for (i = 0; i < len; i += 1) {
  5493. self.paused = true;
  5494. xhr[i].abort();
  5495. }
  5496. }
  5497. if (self.showPreview) {
  5498. self._getThumbs().each(function () {
  5499. var $thumb = $(this), t = self._getLayoutTemplate('stats'), stats,
  5500. $indicator = $thumb.find('.file-upload-indicator');
  5501. $thumb.removeClass('file-uploading');
  5502. if ($indicator.attr('title') === actions.indicatorLoadingTitle) {
  5503. self._setThumbStatus($thumb, 'Paused');
  5504. stats = t.setTokens({pendingTime: self.msgPaused, uploadSpeed: ''});
  5505. self.paused = true;
  5506. self._setProgress(pct, $thumb.find('.file-thumb-progress'), pct + '%', stats);
  5507. }
  5508. if (!self._getThumbFile($thumb)) {
  5509. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5510. }
  5511. });
  5512. }
  5513. self._setProgress(101, self.$progress, self.msgPaused);
  5514. return self.$element;
  5515. },
  5516. cancel: function () {
  5517. var self = this, xhr = self.ajaxRequests,
  5518. rm = self.resumableManager, tm = self.taskManager,
  5519. pool = rm ? tm.getPool(rm.id) : undefined, len = xhr.length, i;
  5520. if (self.enableResumableUpload && pool) {
  5521. pool.cancel().done(function () {
  5522. self._setProgressCancelled();
  5523. });
  5524. rm.reset();
  5525. self._raise('fileuploadcancelled', [self.fileManager, rm]);
  5526. } else {
  5527. self._raise('fileuploadcancelled', [self.fileManager]);
  5528. }
  5529. self._initAjax();
  5530. if (len > 0) {
  5531. for (i = 0; i < len; i += 1) {
  5532. self.cancelling = true;
  5533. xhr[i].abort();
  5534. }
  5535. }
  5536. self._getThumbs().each(function () {
  5537. var $thumb = $(this), $prog = $thumb.find('.file-thumb-progress');
  5538. $thumb.removeClass('file-uploading');
  5539. self._setProgress(0, $prog);
  5540. $prog.hide();
  5541. if (!self._getThumbFile($thumb)) {
  5542. $thumb.find('.kv-file-upload').removeClass('disabled').removeAttr('disabled');
  5543. $thumb.find('.kv-file-remove').removeClass('disabled').removeAttr('disabled');
  5544. }
  5545. self.unlock();
  5546. });
  5547. setTimeout(function () {
  5548. self._setProgressCancelled();
  5549. }, self.processDelay);
  5550. return self.$element;
  5551. },
  5552. clear: function () {
  5553. var self = this, cap;
  5554. if (!self._raise('fileclear')) {
  5555. return;
  5556. }
  5557. self.$btnUpload.removeAttr('disabled');
  5558. self._getThumbs().find('video,audio,img').each(function () {
  5559. $h.cleanMemory($(this));
  5560. });
  5561. self._clearFileInput();
  5562. self._resetUpload();
  5563. self.clearFileStack();
  5564. self.isDuplicateError = false;
  5565. self.isPersistentError = false;
  5566. self._resetErrors(true);
  5567. if (self._hasInitialPreview()) {
  5568. self._showFileIcon();
  5569. self._resetPreview();
  5570. self._initPreviewActions();
  5571. self.$container.removeClass('file-input-new');
  5572. } else {
  5573. self._getThumbs().each(function () {
  5574. self._clearObjects($(this));
  5575. });
  5576. if (self.isAjaxUpload) {
  5577. self.previewCache.data = {};
  5578. }
  5579. self.$preview.html('');
  5580. cap = (!self.overwriteInitial && self.initialCaption.length > 0) ? self.initialCaption : '';
  5581. self.$caption.attr('title', '').val(cap);
  5582. $h.addCss(self.$container, 'file-input-new');
  5583. self._validateDefaultPreview();
  5584. }
  5585. if (self.$container.find($h.FRAMES).length === 0) {
  5586. if (!self._initCaption()) {
  5587. self.$captionContainer.removeClass('icon-visible');
  5588. }
  5589. }
  5590. self._hideFileIcon();
  5591. if (self.focusCaptionOnClear) {
  5592. self.$captionContainer.focus();
  5593. }
  5594. self._setFileDropZoneTitle();
  5595. self._raise('filecleared');
  5596. return self.$element;
  5597. },
  5598. reset: function () {
  5599. var self = this;
  5600. if (!self._raise('filereset')) {
  5601. return;
  5602. }
  5603. self.lastProgress = 0;
  5604. self._resetPreview();
  5605. self.$container.find('.fileinput-filename').text('');
  5606. $h.addCss(self.$container, 'file-input-new');
  5607. if (self.getFrames().length) {
  5608. self.$container.removeClass('file-input-new');
  5609. }
  5610. self.clearFileStack();
  5611. self._setFileDropZoneTitle();
  5612. return self.$element;
  5613. },
  5614. disable: function () {
  5615. var self = this, $container = self.$container;
  5616. self.isDisabled = true;
  5617. self._raise('filedisabled');
  5618. self.$element.attr('disabled', 'disabled');
  5619. $container.addClass('is-locked');
  5620. $h.addCss($container.find('.btn-file'), 'disabled');
  5621. $container.find('.kv-fileinput-caption').addClass('file-caption-disabled');
  5622. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5623. .attr('disabled', true);
  5624. self._initDragDrop();
  5625. return self.$element;
  5626. },
  5627. enable: function () {
  5628. var self = this, $container = self.$container;
  5629. self.isDisabled = false;
  5630. self._raise('fileenabled');
  5631. self.$element.removeAttr('disabled');
  5632. $container.removeClass('is-locked');
  5633. $container.find('.kv-fileinput-caption').removeClass('file-caption-disabled');
  5634. $container.find('.fileinput-remove, .fileinput-upload, .file-preview-frame button')
  5635. .removeAttr('disabled');
  5636. $container.find('.btn-file').removeClass('disabled');
  5637. self._initDragDrop();
  5638. return self.$element;
  5639. },
  5640. upload: function () {
  5641. var self = this, fm = self.fileManager, totLen = fm.count(), i, outData,
  5642. hasExtraData = !$.isEmptyObject(self._getExtraData());
  5643. fm.bpsLog = [];
  5644. fm.bps = 0;
  5645. if (!self.isAjaxUpload || self.isDisabled || !self._isFileSelectionValid(totLen)) {
  5646. return;
  5647. }
  5648. self.lastProgress = 0;
  5649. self._resetUpload();
  5650. if (totLen === 0 && !hasExtraData) {
  5651. self._showFileError(self.msgUploadEmpty);
  5652. return;
  5653. }
  5654. self.cancelling = false;
  5655. self._showProgress();
  5656. self.lock();
  5657. if (totLen === 0 && hasExtraData) {
  5658. self._setProgress(2);
  5659. self._uploadExtraOnly();
  5660. return;
  5661. }
  5662. if (self.enableResumableUpload) {
  5663. return self.resume();
  5664. }
  5665. if (self.uploadAsync || self.enableResumableUpload) {
  5666. outData = self._getOutData(null);
  5667. self._raise('filebatchpreupload', [outData]);
  5668. self.fileBatchCompleted = false;
  5669. self.uploadCache = [];
  5670. $.each(self.getFileStack(), function (id) {
  5671. var previewId = self._getThumbId(id);
  5672. self.uploadCache.push({id: previewId, content: null, config: null, tags: null, append: true});
  5673. });
  5674. self.$preview.find('.file-preview-initial').removeClass($h.SORT_CSS);
  5675. self._initSortable();
  5676. }
  5677. self._setProgress(2);
  5678. self.hasInitData = false;
  5679. if (self.uploadAsync) {
  5680. i = 0;
  5681. $.each(fm.stack, function (id) {
  5682. self._uploadSingle(i, id, true);
  5683. i++;
  5684. });
  5685. return;
  5686. }
  5687. self._uploadBatch();
  5688. return self.$element;
  5689. },
  5690. destroy: function () {
  5691. var self = this, $form = self.$form, $cont = self.$container, $el = self.$element, ns = self.namespace;
  5692. $(document).off(ns);
  5693. $(window).off(ns);
  5694. if ($form && $form.length) {
  5695. $form.off(ns);
  5696. }
  5697. if (self.isAjaxUpload) {
  5698. self._clearFileInput();
  5699. }
  5700. self._cleanup();
  5701. self._initPreviewCache();
  5702. $el.insertBefore($cont).off(ns).removeData();
  5703. $cont.off().remove();
  5704. return $el;
  5705. },
  5706. refresh: function (options) {
  5707. var self = this, $el = self.$element;
  5708. if (typeof options !== 'object' || $h.isEmpty(options)) {
  5709. options = self.options;
  5710. } else {
  5711. options = $.extend(true, {}, self.options, options);
  5712. }
  5713. self._init(options, true);
  5714. self._listen();
  5715. return $el;
  5716. },
  5717. zoom: function (frameId) {
  5718. var self = this, $frame = self._getFrame(frameId);
  5719. self._showModal($frame);
  5720. },
  5721. getExif: function (frameId) {
  5722. var self = this, $frame = self._getFrame(frameId);
  5723. return $frame && $frame.data('exif') || null;
  5724. },
  5725. getFrames: function (cssFilter) {
  5726. var self = this, $frames;
  5727. cssFilter = cssFilter || '';
  5728. $frames = self.$preview.find($h.FRAMES + cssFilter);
  5729. if (self.reversePreviewOrder) {
  5730. $frames = $($frames.get().reverse());
  5731. }
  5732. return $frames;
  5733. },
  5734. getPreview: function () {
  5735. var self = this;
  5736. return {
  5737. content: self.initialPreview,
  5738. config: self.initialPreviewConfig,
  5739. tags: self.initialPreviewThumbTags
  5740. };
  5741. }
  5742. };
  5743. $.fn.fileinput = function (option) {
  5744. if (!$h.hasFileAPISupport() && !$h.isIE(9)) {
  5745. return;
  5746. }
  5747. var args = Array.apply(null, arguments), retvals = [];
  5748. args.shift();
  5749. this.each(function () {
  5750. var self = $(this), data = self.data('fileinput'), options = typeof option === 'object' && option,
  5751. theme = options.theme || self.data('theme'), l = {}, t = {},
  5752. lang = options.language || self.data('language') || $.fn.fileinput.defaults.language || 'en', opt;
  5753. if (!data) {
  5754. if (theme) {
  5755. t = $.fn.fileinputThemes[theme] || {};
  5756. }
  5757. if (lang !== 'en' && !$h.isEmpty($.fn.fileinputLocales[lang])) {
  5758. l = $.fn.fileinputLocales[lang] || {};
  5759. }
  5760. opt = $.extend(true, {}, $.fn.fileinput.defaults, t, $.fn.fileinputLocales.en, l, options, self.data());
  5761. data = new FileInput(this, opt);
  5762. self.data('fileinput', data);
  5763. }
  5764. if (typeof option === 'string') {
  5765. retvals.push(data[option].apply(data, args));
  5766. }
  5767. });
  5768. switch (retvals.length) {
  5769. case 0:
  5770. return this;
  5771. case 1:
  5772. return retvals[0];
  5773. default:
  5774. return retvals;
  5775. }
  5776. };
  5777. var IFRAME_ATTRIBS = 'class="kv-preview-data file-preview-pdf" src="{renderer}?file={data}" {style}';
  5778. $.fn.fileinput.defaults = {
  5779. language: 'en',
  5780. showCaption: true,
  5781. showBrowse: true,
  5782. showPreview: true,
  5783. showRemove: true,
  5784. showUpload: true,
  5785. showUploadStats: true,
  5786. showCancel: null,
  5787. showPause: null,
  5788. showClose: true,
  5789. showUploadedThumbs: true,
  5790. showConsoleLogs: false,
  5791. browseOnZoneClick: false,
  5792. autoReplace: false,
  5793. autoOrientImage: function () { // applicable for JPEG images only and non ios safari
  5794. var ua = window.navigator.userAgent, webkit = !!ua.match(/WebKit/i),
  5795. iOS = !!ua.match(/iP(od|ad|hone)/i), iOSSafari = iOS && webkit && !ua.match(/CriOS/i);
  5796. return !iOSSafari;
  5797. },
  5798. autoOrientImageInitial: true,
  5799. required: false,
  5800. rtl: false,
  5801. hideThumbnailContent: false,
  5802. encodeUrl: true,
  5803. focusCaptionOnBrowse: true,
  5804. focusCaptionOnClear: true,
  5805. generateFileId: null,
  5806. previewClass: '',
  5807. captionClass: '',
  5808. frameClass: 'krajee-default',
  5809. mainClass: 'file-caption-main',
  5810. mainTemplate: null,
  5811. fileSizeGetter: null,
  5812. initialCaption: '',
  5813. initialPreview: [],
  5814. initialPreviewDelimiter: '*$$*',
  5815. initialPreviewAsData: false,
  5816. initialPreviewFileType: 'image',
  5817. initialPreviewConfig: [],
  5818. initialPreviewThumbTags: [],
  5819. previewThumbTags: {},
  5820. initialPreviewShowDelete: true,
  5821. initialPreviewDownloadUrl: '',
  5822. removeFromPreviewOnError: false,
  5823. deleteUrl: '',
  5824. deleteExtraData: {},
  5825. overwriteInitial: true,
  5826. sanitizeZoomCache: function (content) {
  5827. var $container = $h.createElement(content);
  5828. $container.find('input,textarea,select,datalist,form,.file-thumbnail-footer').remove();
  5829. return $container.html();
  5830. },
  5831. previewZoomButtonIcons: {
  5832. prev: '<i class="glyphicon glyphicon-triangle-left"></i>',
  5833. next: '<i class="glyphicon glyphicon-triangle-right"></i>',
  5834. toggleheader: '<i class="glyphicon glyphicon-resize-vertical"></i>',
  5835. fullscreen: '<i class="glyphicon glyphicon-fullscreen"></i>',
  5836. borderless: '<i class="glyphicon glyphicon-resize-full"></i>',
  5837. close: '<i class="glyphicon glyphicon-remove"></i>'
  5838. },
  5839. previewZoomButtonClasses: {
  5840. prev: 'btn btn-navigate',
  5841. next: 'btn btn-navigate',
  5842. toggleheader: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  5843. fullscreen: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  5844. borderless: 'btn btn-sm btn-kv btn-default btn-outline-secondary',
  5845. close: 'btn btn-sm btn-kv btn-default btn-outline-secondary'
  5846. },
  5847. previewTemplates: {},
  5848. previewContentTemplates: {},
  5849. preferIconicPreview: false,
  5850. preferIconicZoomPreview: false,
  5851. allowedFileTypes: null,
  5852. allowedFileExtensions: null,
  5853. allowedPreviewTypes: undefined,
  5854. allowedPreviewMimeTypes: null,
  5855. allowedPreviewExtensions: null,
  5856. disabledPreviewTypes: undefined,
  5857. disabledPreviewExtensions: ['msi', 'exe', 'com', 'zip', 'rar', 'app', 'vb', 'scr'],
  5858. disabledPreviewMimeTypes: null,
  5859. defaultPreviewContent: null,
  5860. customLayoutTags: {},
  5861. customPreviewTags: {},
  5862. previewFileIcon: '<i class="glyphicon glyphicon-file"></i>',
  5863. previewFileIconClass: 'file-other-icon',
  5864. previewFileIconSettings: {},
  5865. previewFileExtSettings: {},
  5866. buttonLabelClass: 'hidden-xs',
  5867. browseIcon: '<i class="glyphicon glyphicon-folder-open"></i>&nbsp;',
  5868. browseClass: 'btn btn-primary',
  5869. removeIcon: '<i class="glyphicon glyphicon-trash"></i>',
  5870. removeClass: 'btn btn-default btn-secondary',
  5871. cancelIcon: '<i class="glyphicon glyphicon-ban-circle"></i>',
  5872. cancelClass: 'btn btn-default btn-secondary',
  5873. pauseIcon: '<i class="glyphicon glyphicon-pause"></i>',
  5874. pauseClass: 'btn btn-default btn-secondary',
  5875. uploadIcon: '<i class="glyphicon glyphicon-upload"></i>',
  5876. uploadClass: 'btn btn-default btn-secondary',
  5877. uploadUrl: null,
  5878. uploadUrlThumb: null,
  5879. uploadAsync: true,
  5880. uploadParamNames: {
  5881. chunkCount: 'chunkCount',
  5882. chunkIndex: 'chunkIndex',
  5883. chunkSize: 'chunkSize',
  5884. chunkSizeStart: 'chunkSizeStart',
  5885. chunksUploaded: 'chunksUploaded',
  5886. fileBlob: 'fileBlob',
  5887. fileId: 'fileId',
  5888. fileName: 'fileName',
  5889. fileRelativePath: 'fileRelativePath',
  5890. fileSize: 'fileSize',
  5891. retryCount: 'retryCount'
  5892. },
  5893. maxAjaxThreads: 5,
  5894. fadeDelay: 800,
  5895. processDelay: 100,
  5896. bitrateUpdateDelay: 500,
  5897. queueDelay: 10, // must be lesser than process delay
  5898. progressDelay: 0, // must be lesser than process delay
  5899. enableResumableUpload: false,
  5900. resumableUploadOptions: {
  5901. fallback: null,
  5902. testUrl: null, // used for checking status of chunks/ files previously / partially uploaded
  5903. chunkSize: 2 * 1024, // in KB
  5904. maxThreads: 4,
  5905. maxRetries: 3,
  5906. showErrorLog: true
  5907. },
  5908. uploadExtraData: {},
  5909. zoomModalHeight: 480,
  5910. minImageWidth: null,
  5911. minImageHeight: null,
  5912. maxImageWidth: null,
  5913. maxImageHeight: null,
  5914. resizeImage: false,
  5915. resizePreference: 'width',
  5916. resizeQuality: 0.92,
  5917. resizeDefaultImageType: 'image/jpeg',
  5918. resizeIfSizeMoreThan: 0, // in KB
  5919. minFileSize: -1,
  5920. maxFileSize: 0,
  5921. maxFilePreviewSize: 25600, // 25 MB
  5922. minFileCount: 0,
  5923. maxFileCount: 0,
  5924. maxTotalFileCount: 0,
  5925. validateInitialCount: false,
  5926. msgValidationErrorClass: 'text-danger',
  5927. msgValidationErrorIcon: '<i class="glyphicon glyphicon-exclamation-sign"></i> ',
  5928. msgErrorClass: 'file-error-message',
  5929. progressThumbClass: 'progress-bar progress-bar-striped active progress-bar-animated',
  5930. progressClass: 'progress-bar bg-success progress-bar-success progress-bar-striped active progress-bar-animated',
  5931. progressInfoClass: 'progress-bar bg-info progress-bar-info progress-bar-striped active progress-bar-animated',
  5932. progressCompleteClass: 'progress-bar bg-success progress-bar-success',
  5933. progressPauseClass: 'progress-bar bg-primary progress-bar-primary progress-bar-striped active progress-bar-animated',
  5934. progressErrorClass: 'progress-bar bg-danger progress-bar-danger',
  5935. progressUploadThreshold: 99,
  5936. previewFileType: 'image',
  5937. elCaptionContainer: null,
  5938. elCaptionText: null,
  5939. elPreviewContainer: null,
  5940. elPreviewImage: null,
  5941. elPreviewStatus: null,
  5942. elErrorContainer: null,
  5943. errorCloseButton: $h.closeButton('kv-error-close'),
  5944. slugCallback: null,
  5945. dropZoneEnabled: true,
  5946. dropZoneTitleClass: 'file-drop-zone-title',
  5947. fileActionSettings: {},
  5948. otherActionButtons: '',
  5949. textEncoding: 'UTF-8',
  5950. preProcessUpload: null,
  5951. ajaxSettings: {},
  5952. ajaxDeleteSettings: {},
  5953. showAjaxErrorDetails: true,
  5954. mergeAjaxCallbacks: false,
  5955. mergeAjaxDeleteCallbacks: false,
  5956. retryErrorUploads: true,
  5957. reversePreviewOrder: false,
  5958. usePdfRenderer: function () {
  5959. var isIE11 = !!window.MSInputMethodContext && !!document.documentMode;
  5960. return !!navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/i) || isIE11;
  5961. },
  5962. pdfRendererUrl: '',
  5963. pdfRendererTemplate: '<iframe ' + IFRAME_ATTRIBS + '></iframe>'
  5964. };
  5965. // noinspection HtmlUnknownAttribute
  5966. $.fn.fileinputLocales.en = {
  5967. fileSingle: 'file',
  5968. filePlural: 'files',
  5969. browseLabel: 'Browse &hellip;',
  5970. removeLabel: 'Remove',
  5971. removeTitle: 'Clear all unprocessed files',
  5972. cancelLabel: 'Cancel',
  5973. cancelTitle: 'Abort ongoing upload',
  5974. pauseLabel: 'Pause',
  5975. pauseTitle: 'Pause ongoing upload',
  5976. uploadLabel: 'Upload',
  5977. uploadTitle: 'Upload selected files',
  5978. msgNo: 'No',
  5979. msgNoFilesSelected: 'No files selected',
  5980. msgCancelled: 'Cancelled',
  5981. msgPaused: 'Paused',
  5982. msgPlaceholder: 'Select {files} ...',
  5983. msgZoomModalHeading: 'Detailed Preview',
  5984. msgFileRequired: 'You must select a file to upload.',
  5985. msgSizeTooSmall: 'File "{name}" (<b>{size} KB</b>) is too small and must be larger than <b>{minSize} KB</b>.',
  5986. msgSizeTooLarge: 'File "{name}" (<b>{size} KB</b>) exceeds maximum allowed upload size of <b>{maxSize} KB</b>.',
  5987. msgFilesTooLess: 'You must select at least <b>{n}</b> {files} to upload.',
  5988. msgFilesTooMany: 'Number of files selected for upload <b>({n})</b> exceeds maximum allowed limit of <b>{m}</b>.',
  5989. msgTotalFilesTooMany: 'You can upload a maximum of <b>{m}</b> files (<b>{n}</b> files detected).',
  5990. msgFileNotFound: 'File "{name}" not found!',
  5991. msgFileSecured: 'Security restrictions prevent reading the file "{name}".',
  5992. msgFileNotReadable: 'File "{name}" is not readable.',
  5993. msgFilePreviewAborted: 'File preview aborted for "{name}".',
  5994. msgFilePreviewError: 'An error occurred while reading the file "{name}".',
  5995. msgInvalidFileName: 'Invalid or unsupported characters in file name "{name}".',
  5996. msgInvalidFileType: 'Invalid type for file "{name}". Only "{types}" files are supported.',
  5997. msgInvalidFileExtension: 'Invalid extension for file "{name}". Only "{extensions}" files are supported.',
  5998. msgFileTypes: {
  5999. 'image': 'image',
  6000. 'html': 'HTML',
  6001. 'text': 'text',
  6002. 'video': 'video',
  6003. 'audio': 'audio',
  6004. 'flash': 'flash',
  6005. 'pdf': 'PDF',
  6006. 'object': 'object'
  6007. },
  6008. msgUploadAborted: 'The file upload was aborted',
  6009. msgUploadThreshold: 'Processing &hellip;',
  6010. msgUploadBegin: 'Initializing &hellip;',
  6011. msgUploadEnd: 'Done',
  6012. msgUploadResume: 'Resuming upload &hellip;',
  6013. msgUploadEmpty: 'No valid data available for upload.',
  6014. msgUploadError: 'Upload Error',
  6015. msgDeleteError: 'Delete Error',
  6016. msgProgressError: 'Error',
  6017. msgValidationError: 'Validation Error',
  6018. msgLoading: 'Loading file {index} of {files} &hellip;',
  6019. msgProgress: 'Loading file {index} of {files} - {name} - {percent}% completed.',
  6020. msgSelected: '{n} {files} selected',
  6021. msgFoldersNotAllowed: 'Drag & drop files only! {n} folder(s) dropped were skipped.',
  6022. msgImageWidthSmall: 'Width of image file "{name}" must be at least {size} px.',
  6023. msgImageHeightSmall: 'Height of image file "{name}" must be at least {size} px.',
  6024. msgImageWidthLarge: 'Width of image file "{name}" cannot exceed {size} px.',
  6025. msgImageHeightLarge: 'Height of image file "{name}" cannot exceed {size} px.',
  6026. msgImageResizeError: 'Could not get the image dimensions to resize.',
  6027. msgImageResizeException: 'Error while resizing the image.<pre>{errors}</pre>',
  6028. msgAjaxError: 'Something went wrong with the {operation} operation. Please try again later!',
  6029. msgAjaxProgressError: '{operation} failed',
  6030. msgDuplicateFile: 'File "{name}" of same size "{size} KB" has already been selected earlier. Skipping duplicate selection.',
  6031. msgResumableUploadRetriesExceeded: 'Upload aborted beyond <b>{max}</b> retries for file <b>{file}</b>! Error Details: <pre>{error}</pre>',
  6032. msgPendingTime: '{time} remaining',
  6033. msgCalculatingTime: 'calculating time remaining',
  6034. ajaxOperations: {
  6035. deleteThumb: 'file delete',
  6036. uploadThumb: 'file upload',
  6037. uploadBatch: 'batch file upload',
  6038. uploadExtra: 'form data upload'
  6039. },
  6040. dropZoneTitle: 'Drag & drop files here &hellip;',
  6041. dropZoneClickTitle: '<br>(or click to select {files})',
  6042. previewZoomButtonTitles: {
  6043. prev: 'View previous file',
  6044. next: 'View next file',
  6045. toggleheader: 'Toggle header',
  6046. fullscreen: 'Toggle full screen',
  6047. borderless: 'Toggle borderless mode',
  6048. close: 'Close detailed preview'
  6049. }
  6050. };
  6051. $.fn.fileinput.Constructor = FileInput;
  6052. /**
  6053. * Convert automatically file inputs with class 'file' into a bootstrap fileinput control.
  6054. */
  6055. $(document).ready(function () {
  6056. var $input = $('input.file[type=file]');
  6057. if ($input.length) {
  6058. $input.fileinput();
  6059. }
  6060. });
  6061. }));