fileinput.js 278 KB

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