fileinput.js 260 KB

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