fileinput.js 268 KB

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