fileinput.js 275 KB

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