fileinput.js 254 KB

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