fileinput.js 276 KB

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