fileinput.js 261 KB

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