fileinput.js 277 KB

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