fileinput.js 257 KB

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