fileinput.js 276 KB

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