fileinput.js 277 KB

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