fileinput.js 260 KB

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