privatebin.js 198 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @name PrivateBin
  10. * @namespace
  11. */
  12. /**
  13. * draghover plugin replacement
  14. * adds draghoverstart and draghoverend events to an element
  15. */
  16. function draghover(element) {
  17. 'use strict';
  18. let collection = new Set();
  19. element.addEventListener('dragenter', function (e) {
  20. if (collection.size === 0) {
  21. element.dispatchEvent(new CustomEvent('draghoverstart'));
  22. }
  23. collection.add(e.target);
  24. });
  25. element.addEventListener('dragleave', function (e) {
  26. collection.delete(e.target);
  27. if (collection.size === 0) {
  28. element.dispatchEvent(new CustomEvent('draghoverend'));
  29. }
  30. });
  31. element.addEventListener('drop', function (e) {
  32. collection.delete(e.target);
  33. if (collection.size === 0) {
  34. element.dispatchEvent(new CustomEvent('draghoverend'));
  35. }
  36. });
  37. }
  38. window.PrivateBin = (function () {
  39. 'use strict';
  40. /**
  41. * zlib library interface
  42. *
  43. * @private
  44. */
  45. let z;
  46. /**
  47. * DOMpurify settings for HTML content
  48. *
  49. * @private
  50. */
  51. const purifyHtmlConfig = {
  52. ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|magnet):)/i,
  53. USE_PROFILES: {
  54. html: true
  55. }
  56. };
  57. /**
  58. * DOMpurify settings for HTML content, where only a strict subset is allowed.
  59. *
  60. * NOTE: The key {@link purifyHtmlConfig.USE_PROFILES} **must not** be included,
  61. * as otherwise `USE_PROFILES` takes precedence over {@link purifyHtmlConfigStrictSubset.ALLOWED_TAGS}.
  62. *
  63. * @private
  64. */
  65. const purifyHtmlConfigStrictSubset = {
  66. ALLOWED_URI_REGEXP: purifyHtmlConfig.ALLOWED_URI_REGEXP,
  67. ALLOWED_TAGS: ['a', 'i', 'span', 'kbd'],
  68. ALLOWED_ATTR: ['href', 'id']
  69. };
  70. /**
  71. * DOMpurify settings for SVG content
  72. *
  73. * @private
  74. */
  75. const purifySvgConfig = {
  76. USE_PROFILES: {
  77. svg: true,
  78. svgFilters: true
  79. }
  80. };
  81. /**
  82. * URL fragment prefix requiring load confirmation
  83. *
  84. * @private
  85. */
  86. const loadConfirmPrefix = '#-';
  87. /**
  88. * CryptoData class
  89. *
  90. * bundles helper functions used in both document and comment formats
  91. *
  92. * @name CryptoData
  93. * @class
  94. */
  95. function CryptoData(data) {
  96. // store all keys in the default locations for drop-in replacement
  97. for (const key in data) {
  98. if (Object.prototype.hasOwnProperty.call(data, key)) {
  99. this[key] = data[key];
  100. }
  101. }
  102. /**
  103. * gets the cipher data (cipher text + adata)
  104. *
  105. * @name CryptoData.getCipherData
  106. * @function
  107. * @return {Array}
  108. */
  109. this.getCipherData = function () {
  110. return [this.ct, this.adata];
  111. }
  112. }
  113. /**
  114. * Paste class
  115. *
  116. * bundles helper functions around the document formats
  117. *
  118. * @name Paste
  119. * @class
  120. */
  121. function Paste(data) {
  122. // inherit constructor and methods of CryptoData
  123. CryptoData.call(this, data);
  124. /**
  125. * gets the used formatter
  126. *
  127. * @name Paste.getFormat
  128. * @function
  129. * @return {string}
  130. */
  131. this.getFormat = function () {
  132. return this.adata[1];
  133. }
  134. /**
  135. * gets the remaining seconds before the document expires
  136. *
  137. * returns 0 if there is no expiration
  138. *
  139. * @name Paste.getTimeToLive
  140. * @function
  141. * @return {string}
  142. */
  143. this.getTimeToLive = function () {
  144. return this.meta.time_to_live || 0;
  145. }
  146. /**
  147. * is burn-after-reading enabled
  148. *
  149. * @name Paste.isBurnAfterReadingEnabled
  150. * @function
  151. * @return {bool}
  152. */
  153. this.isBurnAfterReadingEnabled = function () {
  154. return this.adata[3];
  155. }
  156. /**
  157. * are discussions enabled
  158. *
  159. * @name Paste.isDiscussionEnabled
  160. * @function
  161. * @return {bool}
  162. */
  163. this.isDiscussionEnabled = function () {
  164. return this.adata[2];
  165. }
  166. }
  167. /**
  168. * Comment class
  169. *
  170. * bundles helper functions around the comment formats
  171. *
  172. * @name Comment
  173. * @class
  174. */
  175. function Comment(data) {
  176. // inherit constructor and methods of CryptoData
  177. CryptoData.call(this, data);
  178. /**
  179. * gets the UNIX timestamp of the comment creation
  180. *
  181. * @name Comment.getCreated
  182. * @function
  183. * @return {int}
  184. */
  185. this.getCreated = function () {
  186. return this.meta['created'] || 0;
  187. }
  188. /**
  189. * gets the icon of the comment submitter
  190. *
  191. * @name Comment.getIcon
  192. * @function
  193. * @return {string}
  194. */
  195. this.getIcon = function () {
  196. return this.meta['icon'] || '';
  197. }
  198. }
  199. /**
  200. * static Helper methods
  201. *
  202. * @name Helper
  203. * @class
  204. */
  205. const Helper = (function () {
  206. const me = {};
  207. /**
  208. * character to HTML entity lookup table
  209. *
  210. * @see {@link https://github.com/janl/mustache.js/blob/master/mustache.js#L60}
  211. * @name Helper.entityMap
  212. * @private
  213. * @enum {Object}
  214. * @readonly
  215. */
  216. const entityMap = {
  217. '&': '&',
  218. '<': '&lt;',
  219. '>': '&gt;',
  220. '"': '&quot;',
  221. '\'': '&#39;',
  222. '/': '&#x2F;',
  223. '`': '&#x60;',
  224. '=': '&#x3D;'
  225. };
  226. /**
  227. * number of seconds in a minute
  228. *
  229. * @name Helper.minute
  230. * @private
  231. * @enum {number}
  232. * @readonly
  233. */
  234. const minute = 60;
  235. /**
  236. * number of seconds in an hour
  237. *
  238. * = 60 * 60 seconds
  239. *
  240. * @name Helper.minute
  241. * @private
  242. * @enum {number}
  243. * @readonly
  244. */
  245. const hour = 3600;
  246. /**
  247. * number of seconds in a day
  248. *
  249. * = 60 * 60 * 24 seconds
  250. *
  251. * @name Helper.day
  252. * @private
  253. * @enum {number}
  254. * @readonly
  255. */
  256. const day = 86400;
  257. /**
  258. * number of seconds in a week
  259. *
  260. * = 60 * 60 * 24 * 7 seconds
  261. *
  262. * @name Helper.week
  263. * @private
  264. * @enum {number}
  265. * @readonly
  266. */
  267. const week = 604800;
  268. /**
  269. * number of seconds in a month (30 days, an approximation)
  270. *
  271. * = 60 * 60 * 24 * 30 seconds
  272. *
  273. * @name Helper.month
  274. * @private
  275. * @enum {number}
  276. * @readonly
  277. */
  278. const month = 2592000;
  279. /**
  280. * number of seconds in a non-leap year
  281. *
  282. * = 60 * 60 * 24 * 365 seconds
  283. *
  284. * @name Helper.year
  285. * @private
  286. * @enum {number}
  287. * @readonly
  288. */
  289. const year = 31536000;
  290. /**
  291. * cache for script location
  292. *
  293. * @name Helper.baseUri
  294. * @private
  295. * @enum {string|null}
  296. */
  297. let baseUri = null;
  298. /**
  299. * converts a duration (in seconds) into human friendly approximation
  300. *
  301. * @name Helper.secondsToHuman
  302. * @function
  303. * @param {number} seconds
  304. * @return {Array}
  305. */
  306. me.secondsToHuman = function (seconds) {
  307. let v;
  308. if (seconds < minute) {
  309. v = Math.floor(seconds);
  310. return [v, 'second'];
  311. }
  312. if (seconds < hour) {
  313. v = Math.floor(seconds / minute);
  314. return [v, 'minute'];
  315. }
  316. if (seconds < day) {
  317. v = Math.floor(seconds / hour);
  318. return [v, 'hour'];
  319. }
  320. // If less than 2 months, display in days:
  321. if (seconds < (2 * month)) {
  322. v = Math.floor(seconds / day);
  323. return [v, 'day'];
  324. }
  325. v = Math.floor(seconds / month);
  326. return [v, 'month'];
  327. };
  328. /**
  329. * converts a duration string into seconds
  330. *
  331. * The string is expected to be optional digits, followed by a time.
  332. * Supported times are: min, hour, day, month, year, never
  333. * Examples: 5min, 13hour, never
  334. *
  335. * @name Helper.durationToSeconds
  336. * @function
  337. * @param {String} duration
  338. * @return {number}
  339. */
  340. me.durationToSeconds = function (duration) {
  341. let pieces = duration.split(/(\D+)/),
  342. factor = pieces[0] || 0,
  343. timespan = pieces[1] || pieces[0];
  344. switch (timespan) {
  345. case 'min':
  346. return factor * minute;
  347. case 'hour':
  348. return factor * hour;
  349. case 'day':
  350. return factor * day;
  351. case 'week':
  352. return factor * week;
  353. case 'month':
  354. return factor * month;
  355. case 'year':
  356. return factor * year;
  357. case 'never':
  358. return 0;
  359. default:
  360. return factor;
  361. }
  362. };
  363. /**
  364. * text range selection
  365. *
  366. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  367. * @name Helper.selectText
  368. * @function
  369. * @param {HTMLElement} element
  370. */
  371. me.selectText = function (element) {
  372. let range, selection;
  373. // MS
  374. if (document.body.createTextRange) {
  375. range = document.body.createTextRange();
  376. range.moveToElementText(element);
  377. range.select();
  378. } else if (window.getSelection) {
  379. selection = window.getSelection();
  380. range = document.createRange();
  381. range.selectNodeContents(element);
  382. selection.removeAllRanges();
  383. selection.addRange(range);
  384. }
  385. };
  386. /**
  387. * convert URLs to clickable links in the provided element.
  388. *
  389. * URLs to handle:
  390. * <pre>
  391. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  392. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  393. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  394. * </pre>
  395. *
  396. * @name Helper.urls2links
  397. * @function
  398. * @param {HTMLElement} element
  399. */
  400. me.urls2links = function (element) {
  401. const raw = element.innerHTML;
  402. element.innerHTML = DOMPurify.sanitize(
  403. raw.replace(
  404. /(((https?|ftp):\/\/[\w?!=&.\/;#@~%+*-]+(?![\w\s?!&.\/;#~%"=-]>))|((magnet):[\w?=&.\/;#@~%+*-]+))/ig,
  405. '<a href="$1" rel="nofollow noopener noreferrer">$1</a>'
  406. ),
  407. purifyHtmlConfigStrictSubset
  408. );
  409. };
  410. /**
  411. * minimal sprintf emulation for %s and %d formats
  412. *
  413. * Note that this function needs the parameters in the same order as the
  414. * format strings appear in the string, contrary to the original.
  415. *
  416. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  417. * @name Helper.sprintf
  418. * @function
  419. * @param {string} format
  420. * @param {...*} args - one or multiple parameters injected into format string
  421. * @return {string}
  422. */
  423. me.sprintf = function () {
  424. const args = Array.prototype.slice.call(arguments);
  425. let format = args[0],
  426. i = 1;
  427. return format.replace(/%(s|d)/g, function (m) {
  428. let val = args[i];
  429. if (m === '%d') {
  430. val = parseFloat(val);
  431. if (isNaN(val)) {
  432. val = 0;
  433. }
  434. }
  435. ++i;
  436. return val;
  437. });
  438. };
  439. /**
  440. * get value of cookie, if it was set, empty string otherwise
  441. *
  442. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  443. * @name Helper.getCookie
  444. * @function
  445. * @param {string} cname - may not be empty
  446. * @return {string}
  447. */
  448. me.getCookie = function (cname) {
  449. const name = cname + '=',
  450. ca = document.cookie.split(';');
  451. for (let i = 0; i < ca.length; ++i) {
  452. let c = ca[i];
  453. while (c.charAt(0) === ' ') {
  454. c = c.substring(1);
  455. }
  456. if (c.indexOf(name) === 0) {
  457. return c.substring(name.length, c.length);
  458. }
  459. }
  460. return '';
  461. };
  462. /**
  463. * get the current location (without search or hash part of the URL),
  464. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  465. *
  466. * @name Helper.baseUri
  467. * @function
  468. * @return {string}
  469. */
  470. me.baseUri = function () {
  471. // check for cached version
  472. if (baseUri !== null) {
  473. return baseUri;
  474. }
  475. baseUri = window.location.origin + window.location.pathname;
  476. return baseUri;
  477. };
  478. /**
  479. * wrap an object into a Paste, used for mocking in the unit tests
  480. *
  481. * @name Helper.PasteFactory
  482. * @function
  483. * @param {object} data
  484. * @return {Paste}
  485. */
  486. me.PasteFactory = function (data) {
  487. return new Paste(data);
  488. };
  489. /**
  490. * wrap an object into a Comment, used for mocking in the unit tests
  491. *
  492. * @name Helper.CommentFactory
  493. * @function
  494. * @param {object} data
  495. * @return {Comment}
  496. */
  497. me.CommentFactory = function (data) {
  498. return new Comment(data);
  499. };
  500. /**
  501. * convert all applicable characters to HTML entities
  502. *
  503. * @see {@link https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html}
  504. * @name Helper.htmlEntities
  505. * @function
  506. * @param {string} str
  507. * @return {string} escaped HTML
  508. */
  509. me.htmlEntities = function (str) {
  510. return String(str).replace(
  511. /[&<>"'`=\/]/g, function (s) {
  512. return entityMap[s];
  513. }
  514. );
  515. };
  516. /**
  517. * calculate expiration date given initial date and expiration period
  518. *
  519. * @name Helper.calculateExpirationDate
  520. * @function
  521. * @param {Date} initialDate - may not be empty
  522. * @param {string|number} expirationDisplayStringOrSecondsToExpire - may not be empty
  523. * @return {Date}
  524. */
  525. me.calculateExpirationDate = function (initialDate, expirationDisplayStringOrSecondsToExpire) {
  526. let expirationDate = new Date(initialDate),
  527. secondsToExpiration = expirationDisplayStringOrSecondsToExpire;
  528. if (typeof expirationDisplayStringOrSecondsToExpire === 'string') {
  529. secondsToExpiration = me.durationToSeconds(expirationDisplayStringOrSecondsToExpire);
  530. }
  531. if (typeof secondsToExpiration !== 'number') {
  532. throw new Error('Cannot calculate expiration date.');
  533. }
  534. if (secondsToExpiration === 0) {
  535. return null;
  536. }
  537. expirationDate = expirationDate.setUTCSeconds(expirationDate.getUTCSeconds() + secondsToExpiration);
  538. return expirationDate;
  539. };
  540. /**
  541. * Convert Bytes to kB/MB/GB/TB/PB/EB/ZB/YB
  542. *
  543. * @name Helper.formatBytes
  544. * @function
  545. *
  546. * @param {number} bytes
  547. * @return {string}
  548. */
  549. me.formatBytes = function (bytes) {
  550. let result = '';
  551. const kilobyte = 1000;
  552. const decimalPoint = 2;
  553. const sizes = [
  554. I18n._('B'), I18n._('kB'), I18n._('MB'), I18n._('GB'), I18n._('TB'),
  555. I18n._('PB'), I18n._('EB'), I18n._('ZB'), I18n._('YB')
  556. ];
  557. const index = Math.floor(Math.log(bytes) / Math.log(kilobyte));
  558. if (bytes > 0) {
  559. result = parseFloat((bytes / Math.pow(kilobyte, index)).toFixed(decimalPoint)) + ' ' + sizes[index];
  560. } else {
  561. result = `0 ${I18n._('B')}`;
  562. }
  563. return result;
  564. };
  565. /**
  566. * resets state, used for unit testing
  567. *
  568. * @name Helper.reset
  569. * @function
  570. */
  571. me.reset = function () {
  572. baseUri = null;
  573. };
  574. /**
  575. * check if bootstrap5 object detected
  576. *
  577. * @name Helper.isBootstrap5
  578. * @returns {Boolean}
  579. */
  580. me.isBootstrap5 = function () {
  581. return typeof bootstrap !== 'undefined';
  582. };
  583. return me;
  584. })();
  585. /**
  586. * internationalization module
  587. *
  588. * @name I18n
  589. * @class
  590. */
  591. const I18n = (function () {
  592. const me = {};
  593. /**
  594. * const for string of loaded language
  595. *
  596. * @name I18n.languageLoadedEvent
  597. * @private
  598. * @prop {string}
  599. * @readonly
  600. */
  601. const languageLoadedEvent = 'languageLoaded';
  602. /**
  603. * supported languages, minus the built in 'en'
  604. *
  605. * @name I18n.supportedLanguages
  606. * @private
  607. * @prop {string[]}
  608. * @readonly
  609. */
  610. const supportedLanguages = ['ar', 'bg', 'ca', 'co', 'cs', 'de', 'el', 'es', 'et', 'fa', 'fi', 'fr', 'he', 'hu', 'id', 'it', 'ja', 'jbo', 'lt', 'no', 'nl', 'pl', 'pt', 'oc', 'ro', 'ru', 'sk', 'sl', 'sv', 'th', 'tr', 'uk', 'zh'];
  611. /**
  612. * built in language
  613. *
  614. * @name I18n.language
  615. * @private
  616. * @prop {string|null}
  617. */
  618. let language = null;
  619. /**
  620. * translation cache
  621. *
  622. * @name I18n.translations
  623. * @private
  624. * @enum {Object}
  625. */
  626. let translations = {};
  627. /**
  628. * translate a string, alias for I18n.translate
  629. *
  630. * @name I18n._
  631. * @function
  632. * @param {HTMLElement} element - optional
  633. * @param {string} messageId
  634. * @param {...*} args - one or multiple parameters injected into placeholders
  635. * @return {string}
  636. */
  637. me._ = function () {
  638. return me.translate.apply(this, arguments);
  639. };
  640. /**
  641. * translate a string
  642. *
  643. * Optionally pass an HTMLElement as the first parameter, to automatically
  644. * let the text of this element be replaced. In case the (asynchronously
  645. * loaded) language is not downloaded yet, this will make sure the string
  646. * is replaced when it eventually gets loaded. Using this is both simpler
  647. * and more secure, as it avoids potential XSS when inserting text.
  648. * The next parameter is the message ID, matching the ones found in
  649. * the translation files under the i18n directory.
  650. * Any additional parameters will get inserted into the message ID in
  651. * place of %s (strings) or %d (digits), applying the appropriate plural
  652. * in case of digits. See also Helper.sprintf().
  653. *
  654. * @name I18n.translate
  655. * @function
  656. * @param {HTMLElement} element - optional
  657. * @param {string} messageId
  658. * @param {...*} args - one or multiple parameters injected into placeholders
  659. * @return {string}
  660. */
  661. me.translate = function () // eslint-disable-line complexity
  662. {
  663. // convert parameters to array
  664. let args = Array.prototype.slice.call(arguments),
  665. messageId,
  666. element = null;
  667. // parse arguments
  668. if (args[0] instanceof HTMLElement) {
  669. // optional HTMLElement as first parameter
  670. element = args[0];
  671. args.shift();
  672. }
  673. // extract messageId from arguments
  674. let usesPlurals = Array.isArray(args[0]);
  675. if (usesPlurals) {
  676. // use the first plural form as messageId, otherwise the singular
  677. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  678. } else {
  679. messageId = args[0];
  680. }
  681. if (messageId.length === 0) {
  682. return messageId;
  683. }
  684. // if no translation string cannot be found (in translations object)
  685. if (!translations.hasOwnProperty(messageId) || language === null) {
  686. // if language is still loading and we have an element assigned
  687. if (language === null && element !== null) {
  688. // handle the error by attaching the language loaded event
  689. let orgArguments = arguments;
  690. document.addEventListener(languageLoadedEvent, function () {
  691. // re-execute this function
  692. me.translate.apply(this, orgArguments);
  693. });
  694. // and fall back to English for now until the real language
  695. // file is loaded
  696. }
  697. // for all other languages than English for which this behaviour
  698. // is expected as it is built-in, log error
  699. if (language !== null && language !== 'en') {
  700. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  701. // fallback to English
  702. }
  703. // save English translation (should be the same on both sides)
  704. translations[messageId] = args[0];
  705. }
  706. // lookup plural translation
  707. if (usesPlurals && Array.isArray(translations[messageId])) {
  708. let n = parseInt(args[1] || 1, 10),
  709. key = me.getPluralForm(n),
  710. maxKey = translations[messageId].length - 1;
  711. if (key > maxKey) {
  712. key = maxKey;
  713. }
  714. args[0] = translations[messageId][key];
  715. args[1] = n;
  716. } else {
  717. // lookup singular translation
  718. args[0] = translations[messageId];
  719. }
  720. // messageID may contain HTML, but should be from a trusted source (code or translation JSON files)
  721. let containsHtml = isStringContainsHtml(args[0]);
  722. // prevent double encoding, when we insert into a text node
  723. if (containsHtml || element === null) {
  724. for (let i = 0; i < args.length; ++i) {
  725. // parameters (i > 0) may never contain HTML as they may come from untrusted parties
  726. if ((containsHtml ? i > 1 : i > 0) || !containsHtml) {
  727. args[i] = Helper.htmlEntities(args[i]);
  728. }
  729. }
  730. }
  731. // format string
  732. let output = Helper.sprintf.apply(this, args);
  733. if (containsHtml) {
  734. // only allow tags/attributes we actually use in translations
  735. output = DOMPurify.sanitize(output, purifyHtmlConfigStrictSubset);
  736. }
  737. // if element is given, insert translation
  738. if (element !== null) {
  739. if (containsHtml) {
  740. element.innerHTML = output;
  741. } else {
  742. // text node takes care of entity encoding
  743. element.textContent = output;
  744. }
  745. return '';
  746. }
  747. return output;
  748. };
  749. /**
  750. * get currently loaded language
  751. *
  752. * @name I18n.getLanguage
  753. * @function
  754. * @return {string}
  755. */
  756. me.getLanguage = function () {
  757. return language;
  758. };
  759. /**
  760. * per language functions to use to determine the plural form
  761. *
  762. * @see {@link https://docs.translatehouse.org/projects/localization-guide/en/latest/l10n/pluralforms.html}
  763. * @name I18n.getPluralForm
  764. * @function
  765. * @param {int} n
  766. * @return {int} array key
  767. */
  768. me.getPluralForm = function (n) { // eslint-disable-line complexity
  769. switch (language) {
  770. case 'ar':
  771. return n === 0 ? 0 : (n === 1 ? 1 : (n === 2 ? 2 : (n % 100 >= 3 && n % 100 <= 10 ? 3 : (n % 100 >= 11 ? 4 : 5))));
  772. case 'cs':
  773. case 'sk':
  774. return n === 1 ? 0 : (n >= 2 && n <= 4 ? 1 : 2);
  775. case 'co':
  776. case 'fa':
  777. case 'fr':
  778. case 'oc':
  779. case 'tr':
  780. case 'zh':
  781. return n > 1 ? 1 : 0;
  782. case 'he':
  783. return n === 1 ? 0 : (n === 2 ? 1 : ((n < 0 || n > 10) && (n % 10 === 0) ? 2 : 3));
  784. case 'id':
  785. case 'ja':
  786. case 'jbo':
  787. case 'th':
  788. return 0;
  789. case 'lt':
  790. return n % 10 === 1 && n % 100 !== 11 ? 0 : ((n % 10 >= 2 && n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  791. case 'pl':
  792. return n === 1 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  793. case 'ro':
  794. return n === 1 ? 0 : ((n === 0 || (n % 100 > 0 && n % 100 < 20)) ? 1 : 2);
  795. case 'ru':
  796. case 'uk':
  797. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  798. case 'sl':
  799. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  800. // bg, ca, de, el, en, es, et, fi, hu, it, nl, no, pt, sv
  801. default:
  802. return n !== 1 ? 1 : 0;
  803. }
  804. };
  805. /**
  806. * load translations into cache
  807. *
  808. * @name I18n.loadTranslations
  809. * @function
  810. */
  811. me.loadTranslations = function () {
  812. let newLanguage = Helper.getCookie('lang');
  813. // auto-select language based on browser settings
  814. if (newLanguage.length === 0) {
  815. newLanguage = (navigator.language || navigator.userLanguage || 'en');
  816. if (newLanguage.indexOf('-') > 0) {
  817. newLanguage = newLanguage.split('-')[0];
  818. }
  819. }
  820. // if language is already used skip update
  821. if (newLanguage === language) {
  822. return;
  823. }
  824. // if language is built-in (English) skip update
  825. if (newLanguage === 'en') {
  826. language = 'en';
  827. return;
  828. }
  829. // if language is not supported, show error
  830. if (supportedLanguages.indexOf(newLanguage) === -1) {
  831. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  832. language = 'en';
  833. return;
  834. }
  835. // load strings from JSON
  836. const scriptTag = document.querySelector('script[src^="js/privatebin.js"]');
  837. const cacheBreaker = scriptTag ? (scriptTag.getAttribute('src').split('.js')[1] || '') : '';
  838. fetch('i18n/' + newLanguage + '.json' + cacheBreaker)
  839. .then(response => {
  840. if (!response.ok) {
  841. throw new Error('HTTP ' + response.status + ' ' + response.statusText);
  842. }
  843. return response.json();
  844. })
  845. .then(data => {
  846. language = newLanguage;
  847. translations = data;
  848. document.dispatchEvent(new CustomEvent(languageLoadedEvent));
  849. })
  850. .catch(error => {
  851. console.error('Language \'%s\' could not be loaded (%s). Translation failed, fallback to English.', newLanguage, error.message);
  852. language = 'en';
  853. });
  854. };
  855. /**
  856. * resets state, used for unit testing
  857. *
  858. * @name I18n.reset
  859. * @function
  860. */
  861. me.reset = function (mockLanguage, mockTranslations) {
  862. language = mockLanguage || null;
  863. translations = mockTranslations || {};
  864. };
  865. /**
  866. * Check if string contains valid HTML code
  867. *
  868. * @name I18n.isStringContainsHtml
  869. * @function
  870. * @private
  871. * @param {string} messageId
  872. * @returns {boolean}
  873. */
  874. function isStringContainsHtml(messageId) {
  875. // message IDs are allowed to contain anchors, spans, keyboard and emphasis tags
  876. // we can recognize all of them by only checking for anchors and keyboard tags
  877. return messageId.indexOf('<a') !== -1 || messageId.indexOf('<kbd') !== -1;
  878. }
  879. return me;
  880. })();
  881. /**
  882. * handles everything related to en/decryption
  883. *
  884. * @name CryptTool
  885. * @class
  886. */
  887. const CryptTool = (function () {
  888. const me = {};
  889. /**
  890. * base58 encoder & decoder
  891. *
  892. * @private
  893. */
  894. const base58 = new baseX('123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz');
  895. /**
  896. * convert UTF-8 string stored in a DOMString to a standard UTF-16 DOMString
  897. *
  898. * Iterates over the bytes of the message, converting them all hexadecimal
  899. * percent encoded representations, then URI decodes them all
  900. *
  901. * @name CryptTool.utf8To16
  902. * @function
  903. * @private
  904. * @param {string} message UTF-8 string
  905. * @return {string} UTF-16 string
  906. */
  907. function utf8To16(message) {
  908. return decodeURIComponent(
  909. message.split('').map(
  910. function (character) {
  911. return '%' + ('00' + character.charCodeAt(0).toString(16)).slice(-2);
  912. }
  913. ).join('')
  914. );
  915. }
  916. /**
  917. * convert DOMString (UTF-16) to a UTF-8 string stored in a DOMString
  918. *
  919. * URI encodes the message, then finds the percent encoded characters
  920. * and transforms these hexadecimal representation back into bytes
  921. *
  922. * @name CryptTool.utf16To8
  923. * @function
  924. * @private
  925. * @param {string} message UTF-16 string
  926. * @return {string} UTF-8 string
  927. */
  928. function utf16To8(message) {
  929. return encodeURIComponent(message).replace(
  930. /%([0-9A-F]{2})/g,
  931. function (match, hexCharacter) {
  932. return String.fromCharCode('0x' + hexCharacter);
  933. }
  934. );
  935. }
  936. /**
  937. * convert ArrayBuffer into a UTF-8 string
  938. *
  939. * Iterates over the bytes of the array, catenating them into a string
  940. *
  941. * @name CryptTool.arraybufferToString
  942. * @function
  943. * @private
  944. * @param {ArrayBuffer} messageArray
  945. * @return {string} message
  946. */
  947. function arraybufferToString(messageArray) {
  948. const array = new Uint8Array(messageArray);
  949. let message = '',
  950. i = 0;
  951. while (i < array.length) {
  952. message += String.fromCharCode(array[i++]);
  953. }
  954. return message;
  955. }
  956. /**
  957. * convert UTF-8 string into a Uint8Array
  958. *
  959. * Iterates over the bytes of the message, writing them to the array
  960. *
  961. * @name CryptTool.stringToArraybuffer
  962. * @function
  963. * @private
  964. * @param {string} message UTF-8 string
  965. * @return {Uint8Array} array
  966. */
  967. function stringToArraybuffer(message) {
  968. const messageArray = new Uint8Array(message.length);
  969. for (let i = 0; i < message.length; ++i) {
  970. messageArray[i] = message.charCodeAt(i);
  971. }
  972. return messageArray;
  973. }
  974. /**
  975. * compress a string (deflate compression), returns buffer
  976. *
  977. * @name CryptTool.compress
  978. * @async
  979. * @function
  980. * @private
  981. * @param {string} message
  982. * @param {string} mode
  983. * @param {object} zlib
  984. * @throws {string}
  985. * @return {ArrayBuffer} data
  986. */
  987. async function compress(message, mode, zlib) {
  988. message = stringToArraybuffer(
  989. utf16To8(message)
  990. );
  991. if (mode === 'zlib') {
  992. if (typeof zlib === 'undefined') {
  993. throw 'Error compressing document, due to missing WebAssembly support.'
  994. }
  995. return zlib.deflate(message).buffer;
  996. }
  997. return message;
  998. }
  999. /**
  1000. * decompress potentially base64 encoded, deflate compressed buffer, returns string
  1001. *
  1002. * @name CryptTool.decompress
  1003. * @async
  1004. * @function
  1005. * @private
  1006. * @param {ArrayBuffer} data
  1007. * @param {string} mode
  1008. * @param {object} zlib
  1009. * @throws {string}
  1010. * @return {string} message
  1011. */
  1012. async function decompress(data, mode, zlib) {
  1013. if (mode === 'zlib') {
  1014. if (typeof zlib === 'undefined') {
  1015. throw 'Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.'
  1016. }
  1017. data = zlib.inflate(
  1018. new Uint8Array(data)
  1019. ).buffer;
  1020. }
  1021. return utf8To16(
  1022. arraybufferToString(data)
  1023. );
  1024. }
  1025. /**
  1026. * returns specified number of random bytes
  1027. *
  1028. * @name CryptTool.getRandomBytes
  1029. * @function
  1030. * @private
  1031. * @param {int} length number of random bytes to fetch
  1032. * @throws {string}
  1033. * @return {string} random bytes
  1034. */
  1035. function getRandomBytes(length) {
  1036. let bytes = '';
  1037. const byteArray = new Uint8Array(length);
  1038. window.crypto.getRandomValues(byteArray);
  1039. for (let i = 0; i < length; ++i) {
  1040. bytes += String.fromCharCode(byteArray[i]);
  1041. }
  1042. return bytes;
  1043. }
  1044. /**
  1045. * derive cryptographic key from key string and password
  1046. *
  1047. * @name CryptTool.deriveKey
  1048. * @async
  1049. * @function
  1050. * @private
  1051. * @param {string} key
  1052. * @param {string} password
  1053. * @param {array} spec cryptographic specification
  1054. * @return {CryptoKey} derived key
  1055. */
  1056. async function deriveKey(key, password, spec) {
  1057. let keyArray = stringToArraybuffer(key);
  1058. if (password.length > 0) {
  1059. let passwordArray = stringToArraybuffer(password),
  1060. newKeyArray = new Uint8Array(keyArray.length + passwordArray.length);
  1061. newKeyArray.set(keyArray, 0);
  1062. newKeyArray.set(passwordArray, keyArray.length);
  1063. keyArray = newKeyArray;
  1064. }
  1065. // import raw key
  1066. const importedKey = await window.crypto.subtle.importKey(
  1067. 'raw', // only 'raw' is allowed
  1068. keyArray,
  1069. { name: 'PBKDF2' }, // we use PBKDF2 for key derivation
  1070. false, // the key may not be exported
  1071. ['deriveKey'] // we may only use it for key derivation
  1072. ).catch(Alert.showError);
  1073. // derive a stronger key for use with AES
  1074. return window.crypto.subtle.deriveKey(
  1075. {
  1076. name: 'PBKDF2', // we use PBKDF2 for key derivation
  1077. salt: stringToArraybuffer(spec[1]), // salt used in HMAC
  1078. iterations: spec[2], // amount of iterations to apply
  1079. hash: { name: 'SHA-256' } // can be "SHA-1", "SHA-256", "SHA-384" or "SHA-512"
  1080. },
  1081. importedKey,
  1082. {
  1083. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1084. length: spec[3] // can be 128, 192 or 256
  1085. },
  1086. false, // the key may not be exported
  1087. ['encrypt', 'decrypt'] // we may only use it for en- and decryption
  1088. ).catch(Alert.showError);
  1089. }
  1090. /**
  1091. * gets crypto settings from specification and authenticated data
  1092. *
  1093. * @name CryptTool.cryptoSettings
  1094. * @function
  1095. * @private
  1096. * @param {string} adata authenticated data
  1097. * @param {array} spec cryptographic specification
  1098. * @return {object} crypto settings
  1099. */
  1100. function cryptoSettings(adata, spec) {
  1101. return {
  1102. name: 'AES-' + spec[6].toUpperCase(), // can be any supported AES algorithm ("AES-CTR", "AES-CBC", "AES-CMAC", "AES-GCM", "AES-CFB", "AES-KW", "ECDH", "DH" or "HMAC")
  1103. iv: stringToArraybuffer(spec[0]), // the initialization vector you used to encrypt
  1104. additionalData: stringToArraybuffer(adata), // the addtional data you used during encryption (if any)
  1105. tagLength: spec[4] // the length of the tag you used to encrypt (if any)
  1106. };
  1107. }
  1108. /**
  1109. * compress, then encrypt message with given key and password
  1110. *
  1111. * @name CryptTool.cipher
  1112. * @async
  1113. * @function
  1114. * @param {string} key
  1115. * @param {string} password
  1116. * @param {string} message
  1117. * @param {array} adata
  1118. * @return {array} encrypted message in base64 encoding & adata containing encryption spec
  1119. */
  1120. me.cipher = async function (key, password, message, adata) {
  1121. let zlib = (await z);
  1122. // AES in Galois Counter Mode, keysize 256 bit,
  1123. // authentication tag 128 bit, 10000 iterations in key derivation
  1124. const compression = (
  1125. typeof zlib === 'undefined' ?
  1126. 'none' : // client lacks support for WASM
  1127. (document.body.dataset.compression || 'zlib')
  1128. ),
  1129. spec = [
  1130. getRandomBytes(16), // initialization vector
  1131. getRandomBytes(8), // salt
  1132. 100000, // iterations
  1133. 256, // key size
  1134. 128, // tag size
  1135. 'aes', // algorithm
  1136. 'gcm', // algorithm mode
  1137. compression // compression
  1138. ], encodedSpec = [];
  1139. for (let i = 0; i < spec.length; ++i) {
  1140. encodedSpec[i] = i < 2 ? btoa(spec[i]) : spec[i];
  1141. }
  1142. if (adata.length === 0) {
  1143. // comment
  1144. adata = encodedSpec;
  1145. } else if (adata[0] === null) {
  1146. // paste
  1147. adata[0] = encodedSpec;
  1148. }
  1149. // finally, encrypt message
  1150. return [
  1151. btoa(
  1152. arraybufferToString(
  1153. await window.crypto.subtle.encrypt(
  1154. cryptoSettings(JSON.stringify(adata), spec),
  1155. await deriveKey(key, password, spec),
  1156. await compress(message, compression, zlib)
  1157. ).catch(Alert.showError)
  1158. )
  1159. ),
  1160. adata
  1161. ];
  1162. };
  1163. /**
  1164. * decrypt message with key, then decompress
  1165. *
  1166. * @name CryptTool.decipher
  1167. * @async
  1168. * @function
  1169. * @param {string} key
  1170. * @param {string} password
  1171. * @param {string|object} data encrypted message
  1172. * @return {string} decrypted message, empty if decryption failed
  1173. */
  1174. me.decipher = async function (key, password, data) {
  1175. let adataString, spec, cipherMessage, plaintext;
  1176. let zlib = (await z);
  1177. if (data instanceof Array) {
  1178. // version 2
  1179. adataString = JSON.stringify(data[1]);
  1180. // clone the array instead of passing the reference
  1181. spec = (data[1][0] instanceof Array ? data[1][0] : data[1]).slice();
  1182. cipherMessage = data[0];
  1183. } else {
  1184. throw 'unsupported message format';
  1185. }
  1186. spec[0] = atob(spec[0]);
  1187. spec[1] = atob(spec[1]);
  1188. if (spec[7] === 'zlib') {
  1189. if (typeof zlib === 'undefined') {
  1190. throw 'Error decompressing document, your browser does not support WebAssembly. Please use another browser to view this document.';
  1191. }
  1192. }
  1193. try {
  1194. plaintext = await window.crypto.subtle.decrypt(
  1195. cryptoSettings(adataString, spec),
  1196. await deriveKey(key, password, spec),
  1197. stringToArraybuffer(
  1198. atob(cipherMessage)
  1199. )
  1200. );
  1201. } catch (err) {
  1202. console.error(err);
  1203. return '';
  1204. }
  1205. try {
  1206. return await decompress(plaintext, spec[7], zlib);
  1207. } catch (err) {
  1208. Alert.showError(err);
  1209. return err;
  1210. }
  1211. };
  1212. /**
  1213. * returns a random symmetric key
  1214. *
  1215. * generates 256 bit long keys (8 Bits * 32) for AES with 256 bit long blocks
  1216. *
  1217. * @name CryptTool.getSymmetricKey
  1218. * @function
  1219. * @throws {string}
  1220. * @return {string} raw bytes
  1221. */
  1222. me.getSymmetricKey = function () {
  1223. return getRandomBytes(32);
  1224. };
  1225. /**
  1226. * base58 encode a DOMString (UTF-16)
  1227. *
  1228. * @name CryptTool.base58encode
  1229. * @function
  1230. * @param {string} input
  1231. * @return {string} output
  1232. */
  1233. me.base58encode = function (input) {
  1234. return base58.encode(
  1235. stringToArraybuffer(input)
  1236. );
  1237. }
  1238. /**
  1239. * base58 decode a DOMString (UTF-16)
  1240. *
  1241. * @name CryptTool.base58decode
  1242. * @function
  1243. * @param {string} input
  1244. * @return {string} output
  1245. */
  1246. me.base58decode = function (input) {
  1247. return arraybufferToString(
  1248. base58.decode(input)
  1249. );
  1250. }
  1251. return me;
  1252. })();
  1253. /**
  1254. * (Model) Data source (aka MVC)
  1255. *
  1256. * @name Model
  1257. * @class
  1258. */
  1259. const Model = (function () {
  1260. const me = {};
  1261. let id = null,
  1262. pasteData = null,
  1263. symmetricKey = null,
  1264. templates;
  1265. /**
  1266. * returns the expiration set in the HTML
  1267. *
  1268. * @name Model.getExpirationDefault
  1269. * @function
  1270. * @return string
  1271. */
  1272. me.getExpirationDefault = function () {
  1273. const element = document.getElementById('pasteExpiration');
  1274. return element ? element.value : '';
  1275. };
  1276. /**
  1277. * returns the format set in the HTML
  1278. *
  1279. * @name Model.getFormatDefault
  1280. * @function
  1281. * @return string
  1282. */
  1283. me.getFormatDefault = function () {
  1284. const element = document.getElementById('pasteFormatter');
  1285. return element ? element.value : '';
  1286. };
  1287. /**
  1288. * returns the document data (including the cipher data)
  1289. *
  1290. * @name Model.getPasteData
  1291. * @function
  1292. * @param {function} callback (optional) Called when data is available
  1293. * @param {function} useCache (optional) Whether to use the cache or
  1294. * force a data reload. Default: true
  1295. * @return string
  1296. */
  1297. me.getPasteData = function (callback, useCache) {
  1298. // use cache if possible/allowed
  1299. if (useCache !== false && pasteData !== null) {
  1300. //execute callback
  1301. if (typeof callback === 'function') {
  1302. return callback(pasteData);
  1303. }
  1304. // alternatively just using inline
  1305. return pasteData;
  1306. }
  1307. // reload data
  1308. ServerInteraction.prepare();
  1309. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + me.getPasteId());
  1310. ServerInteraction.setFailure(function (status, data) {
  1311. // revert loading status…
  1312. Alert.hideLoading();
  1313. TopNav.showViewButtons();
  1314. // show error message
  1315. Alert.showError(ServerInteraction.parseUploadError(status, data, 'get document data'));
  1316. });
  1317. ServerInteraction.setSuccess(function (status, data) {
  1318. pasteData = new Paste(data);
  1319. if (typeof callback === 'function') {
  1320. return callback(pasteData);
  1321. }
  1322. });
  1323. ServerInteraction.run();
  1324. };
  1325. /**
  1326. * get the documents unique identifier from the URL,
  1327. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  1328. *
  1329. * @name Model.getPasteId
  1330. * @function
  1331. * @return {string} unique identifier
  1332. * @throws {string}
  1333. */
  1334. me.getPasteId = function () {
  1335. const idRegEx = /^[a-z0-9]{16}$/;
  1336. // return cached value
  1337. if (id !== null) {
  1338. return id;
  1339. }
  1340. // do use URL interface, if possible
  1341. const url = new URL(window.location);
  1342. for (const param of url.searchParams) {
  1343. const key = param[0];
  1344. const value = param[1];
  1345. if (value === '' && idRegEx.test(key)) {
  1346. // safe, as the whole regex is matched
  1347. id = key;
  1348. return key;
  1349. }
  1350. }
  1351. if (id === null) {
  1352. throw 'no document id given';
  1353. }
  1354. return id;
  1355. }
  1356. /**
  1357. * returns true, when the URL has a delete token and the current call was used for deleting a document.
  1358. *
  1359. * @name Model.hasDeleteToken
  1360. * @function
  1361. * @return {bool}
  1362. */
  1363. me.hasDeleteToken = function () {
  1364. return window.location.search.indexOf('deletetoken') !== -1;
  1365. }
  1366. /**
  1367. * return the deciphering key stored in anchor part of the URL
  1368. *
  1369. * @name Model.getPasteKey
  1370. * @function
  1371. * @return {string|null} key
  1372. * @throws {string}
  1373. */
  1374. me.getPasteKey = function () {
  1375. if (symmetricKey === null) {
  1376. let startPos = 1;
  1377. if (window.location.hash.startsWith(loadConfirmPrefix)) {
  1378. startPos = loadConfirmPrefix.length;
  1379. }
  1380. let newKey = window.location.hash.substring(startPos);
  1381. // Some web 2.0 services and redirectors add data AFTER the anchor
  1382. // (such as &utm_source=...). We will strip any additional data.
  1383. let ampersandPos = newKey.indexOf('&');
  1384. if (ampersandPos > -1) {
  1385. newKey = newKey.substring(0, ampersandPos);
  1386. }
  1387. if (newKey === '') {
  1388. throw 'no encryption key given';
  1389. }
  1390. // version 2 uses base58, version 1 uses base64 without decoding
  1391. try {
  1392. // base58 encode strips NULL bytes at the beginning of the
  1393. // string, so we re-add them if necessary
  1394. symmetricKey = CryptTool.base58decode(newKey).padStart(32, '\u0000');
  1395. } catch (e) {
  1396. throw 'encryption key of unsupported format given or incomplete, mangled URL';
  1397. }
  1398. }
  1399. return symmetricKey;
  1400. };
  1401. /**
  1402. * returns a copy of the HTML template
  1403. *
  1404. * @name Model.getTemplate
  1405. * @function
  1406. * @param {string} name - the name of the template
  1407. * @return {HTMLElement}
  1408. */
  1409. me.getTemplate = function (name) {
  1410. // find template
  1411. const template = templates.querySelector('#' + name + 'template');
  1412. if (!template) {
  1413. return null;
  1414. }
  1415. let element = template.cloneNode(true);
  1416. // change ID to avoid collisions (one ID should really be unique)
  1417. element.id = name;
  1418. return element;
  1419. };
  1420. /**
  1421. * resets state, used for unit testing
  1422. *
  1423. * @name Model.reset
  1424. * @function
  1425. */
  1426. me.reset = function () {
  1427. pasteData = templates = id = symmetricKey = null;
  1428. };
  1429. /**
  1430. * init navigation manager
  1431. *
  1432. * preloads elements
  1433. *
  1434. * @name Model.init
  1435. * @function
  1436. */
  1437. me.init = function () {
  1438. templates = document.getElementById('templates');
  1439. };
  1440. return me;
  1441. })();
  1442. /**
  1443. * Helper functions for user interface
  1444. *
  1445. * everything directly UI-related, which fits nowhere else
  1446. *
  1447. * @name UiHelper
  1448. * @class
  1449. */
  1450. const UiHelper = (function () {
  1451. const me = {};
  1452. /**
  1453. * handle history (pop) state changes
  1454. *
  1455. * currently this does only handle redirects to the home page.
  1456. *
  1457. * @name UiHelper.historyChange
  1458. * @private
  1459. * @function
  1460. * @param {Event} event
  1461. */
  1462. function historyChange(event) {
  1463. let currentLocation = Helper.baseUri();
  1464. if (event.originalEvent.state === null && // no state object passed
  1465. event.target.location.href === currentLocation && // target location is home page
  1466. window.location.href === currentLocation // and we are not already on the home page
  1467. ) {
  1468. // redirect to home page
  1469. window.location.href = currentLocation;
  1470. }
  1471. }
  1472. /**
  1473. * reload the page
  1474. *
  1475. * This takes the user to the PrivateBin homepage.
  1476. *
  1477. * @name UiHelper.reloadHome
  1478. * @function
  1479. */
  1480. me.reloadHome = function () {
  1481. window.location.href = Helper.baseUri();
  1482. };
  1483. /**
  1484. * checks whether the element is currently visible in the viewport (so
  1485. * the user can actually see it)
  1486. *
  1487. * @see {@link https://stackoverflow.com/a/40658647}
  1488. * @name UiHelper.isVisible
  1489. * @function
  1490. * @param {HTMLElement} element The link hash to move to.
  1491. */
  1492. me.isVisible = function (element) {
  1493. let elementTop = element.getBoundingClientRect().top + window.scrollY,
  1494. viewportTop = window.scrollY,
  1495. viewportBottom = viewportTop + window.innerHeight;
  1496. return elementTop > viewportTop && elementTop < viewportBottom;
  1497. };
  1498. /**
  1499. * scrolls to a specific element
  1500. *
  1501. * @name UiHelper.scrollTo
  1502. * @function
  1503. * @param {HTMLElement} element The link hash to move to.
  1504. * @param {(number|string)} animationDuration when set to 0 the animation is skipped
  1505. * @param {string} animationEffect ignored
  1506. * @param {function} finishedCallback function to call after animation finished
  1507. */
  1508. me.scrollTo = function (element, animationDuration, animationEffect, finishedCallback) {
  1509. let margin = 50,
  1510. dest = 0;
  1511. // calculate destination place
  1512. let elementTop = element.getBoundingClientRect().top + window.scrollY;
  1513. // if it would scroll out of the screen at the bottom only scroll it as
  1514. // far as the screen can go
  1515. if (elementTop > document.documentElement.scrollHeight - window.innerHeight) {
  1516. dest = document.documentElement.scrollHeight - window.innerHeight;
  1517. } else {
  1518. dest = elementTop - margin;
  1519. }
  1520. // scroll to destination
  1521. window.scrollTo({
  1522. top: dest,
  1523. behavior: animationDuration === 0 ? 'auto' : 'smooth'
  1524. });
  1525. // call callback
  1526. if (typeof finishedCallback !== 'undefined') {
  1527. if (animationDuration === 0) {
  1528. finishedCallback();
  1529. } else {
  1530. // approximate time for smooth scroll
  1531. setTimeout(finishedCallback, 500);
  1532. }
  1533. }
  1534. };
  1535. /**
  1536. * trigger a history (pop) state change
  1537. *
  1538. * used to test the UiHelper.historyChange private function
  1539. *
  1540. * @name UiHelper.mockHistoryChange
  1541. * @function
  1542. * @param {string} state (optional) state to mock
  1543. */
  1544. me.mockHistoryChange = function (state) {
  1545. if (typeof state === 'undefined') {
  1546. state = null;
  1547. }
  1548. historyChange({ originalEvent: new PopStateEvent('popstate', { state: state }), target: window });
  1549. };
  1550. /**
  1551. * initialize
  1552. *
  1553. * @name UiHelper.init
  1554. * @function
  1555. */
  1556. me.init = function () {
  1557. // update link to home page
  1558. document.querySelectorAll('.reloadlink').forEach(link => link.href = Helper.baseUri());
  1559. window.addEventListener('popstate', historyChange);
  1560. };
  1561. return me;
  1562. })();
  1563. /**
  1564. * Alert/error manager
  1565. *
  1566. * @name Alert
  1567. * @class
  1568. */
  1569. const Alert = (function () {
  1570. const me = {};
  1571. let errorMessage,
  1572. loadingIndicator,
  1573. statusMessage,
  1574. remainingTime,
  1575. currentIcon,
  1576. customHandler;
  1577. const alertType = [
  1578. 'loading', // not in bootstrap CSS, but using a plausible value here
  1579. 'info', // status icon
  1580. 'warning', // warning icon
  1581. 'danger' // error icon
  1582. ];
  1583. /**
  1584. * forwards a request to the i18n module and shows the element
  1585. *
  1586. * @name Alert.handleNotification
  1587. * @private
  1588. * @function
  1589. * @param {number} id - id of notification
  1590. * @param {HTMLElement} element - HTML element
  1591. * @param {string|array} args
  1592. * @param {string|null} icon - optional, icon
  1593. */
  1594. function handleNotification(id, element, args, icon) {
  1595. // basic parsing/conversion of parameters
  1596. if (typeof icon === 'undefined') {
  1597. icon = null;
  1598. }
  1599. if (typeof args === 'undefined') {
  1600. args = null;
  1601. } else if (typeof args === 'string') {
  1602. // convert string to array if needed
  1603. args = [args];
  1604. } else if (args instanceof Error) {
  1605. // extract message into array if needed
  1606. args = [args.message];
  1607. }
  1608. // pass to custom handler if defined
  1609. if (typeof customHandler === 'function') {
  1610. let handlerResult = customHandler(alertType[id], element, args, icon);
  1611. if (handlerResult === true) {
  1612. // if it returns true, skip own handler
  1613. return;
  1614. }
  1615. if (handlerResult instanceof HTMLElement) {
  1616. // continue processing with new element
  1617. element = handlerResult;
  1618. icon = null; // icons not supported in this case
  1619. }
  1620. }
  1621. let translationTarget = element;
  1622. // handle icon, if template uses one
  1623. const glyphIcon = element.querySelector(':first-child');
  1624. if (glyphIcon) {
  1625. // if there is an icon, we need to provide an inner element
  1626. // to translate the message into, instead of the parent
  1627. translationTarget = document.createElement('span');
  1628. element.innerHTML = ' ';
  1629. element.prepend(glyphIcon);
  1630. element.appendChild(translationTarget);
  1631. if (icon !== null && // icon was passed
  1632. icon !== currentIcon[id] // and it differs from current icon
  1633. ) {
  1634. // remove (previous) icon
  1635. glyphIcon.classList.remove(currentIcon[id]);
  1636. // any other thing as a string (e.g. 'null') (only) removes the icon
  1637. if (typeof icon === 'string') {
  1638. // set new icon
  1639. currentIcon[id] = 'glyphicon-' + icon;
  1640. glyphIcon.classList.add(currentIcon[id]);
  1641. }
  1642. }
  1643. }
  1644. // translate and insert message
  1645. I18n._(translationTarget, ...args);
  1646. // show element
  1647. element.classList.remove('hidden');
  1648. }
  1649. /**
  1650. * display a status message
  1651. *
  1652. * This automatically passes the text to I18n for translation.
  1653. *
  1654. * @name Alert.showStatus
  1655. * @function
  1656. * @param {string|array} message string, use an array for %s/%d options
  1657. * @param {string|null} icon optional, the icon to show,
  1658. * default: leave previous icon
  1659. */
  1660. me.showStatus = function (message, icon) {
  1661. handleNotification(1, statusMessage, message, icon);
  1662. };
  1663. /**
  1664. * display a warning message
  1665. *
  1666. * This automatically passes the text to I18n for translation.
  1667. *
  1668. * @name Alert.showWarning
  1669. * @function
  1670. * @param {string|array} message string, use an array for %s/%d options
  1671. * @param {string|null} icon optional, the icon to show, default:
  1672. * leave previous icon
  1673. */
  1674. me.showWarning = function (message, icon) {
  1675. const glyphIcon = errorMessage.querySelector(':first-child');
  1676. if (glyphIcon) {
  1677. glyphIcon.classList.remove(currentIcon[3]);
  1678. glyphIcon.classList.add(currentIcon[2]);
  1679. }
  1680. handleNotification(2, errorMessage, message, icon);
  1681. };
  1682. /**
  1683. * display an error message
  1684. *
  1685. * This automatically passes the text to I18n for translation.
  1686. *
  1687. * @name Alert.showError
  1688. * @function
  1689. * @param {string|array} message string, use an array for %s/%d options
  1690. * @param {string|null} icon optional, the icon to show, default:
  1691. * leave previous icon
  1692. */
  1693. me.showError = function (message, icon) {
  1694. handleNotification(3, errorMessage, message, icon);
  1695. };
  1696. /**
  1697. * display remaining message
  1698. *
  1699. * This automatically passes the text to I18n for translation.
  1700. *
  1701. * @name Alert.showRemaining
  1702. * @function
  1703. * @param {string|array} message string, use an array for %s/%d options
  1704. */
  1705. me.showRemaining = function (message) {
  1706. handleNotification(1, remainingTime, message);
  1707. };
  1708. /**
  1709. * shows a loading message, optionally with a percentage
  1710. *
  1711. * This automatically passes all texts to the i10s module.
  1712. *
  1713. * @name Alert.showLoading
  1714. * @function
  1715. * @param {string|array|null} message optional, use an array for %s/%d options, default: 'Loading…'
  1716. * @param {string|null} icon optional, the icon to show, default: leave previous icon
  1717. */
  1718. me.showLoading = function (message, icon) {
  1719. // default message text
  1720. if (typeof message === 'undefined') {
  1721. message = 'Loading…';
  1722. }
  1723. handleNotification(0, loadingIndicator, message, icon);
  1724. // show loading status (cursor)
  1725. document.body.classList.add('loading');
  1726. };
  1727. /**
  1728. * hides the loading message
  1729. *
  1730. * @name Alert.hideLoading
  1731. * @function
  1732. */
  1733. me.hideLoading = function () {
  1734. loadingIndicator.classList.add('hidden');
  1735. // hide loading cursor
  1736. document.body.classList.remove('loading');
  1737. };
  1738. /**
  1739. * hides any status/error messages
  1740. *
  1741. * This does not include the loading message.
  1742. *
  1743. * @name Alert.hideMessages
  1744. * @function
  1745. */
  1746. me.hideMessages = function () {
  1747. statusMessage.classList.add('hidden');
  1748. errorMessage.classList.add('hidden');
  1749. };
  1750. /**
  1751. * set a custom handler, which gets all notifications.
  1752. *
  1753. * This handler gets the following arguments:
  1754. * alertType (see array), $element, args, icon
  1755. * If it returns true, the own processing will be stopped so the message
  1756. * will not be displayed. Otherwise it will continue.
  1757. * As an aditional feature it can return q jQuery element, which will
  1758. * then be used to add the message there. Icons are not supported in
  1759. * that case and will be ignored.
  1760. * Pass 'null' to reset/delete the custom handler.
  1761. * Note that there is no notification when a message is supposed to get
  1762. * hidden.
  1763. *
  1764. * @name Alert.setCustomHandler
  1765. * @function
  1766. * @param {function|null} newHandler
  1767. */
  1768. me.setCustomHandler = function (newHandler) {
  1769. customHandler = newHandler;
  1770. };
  1771. /**
  1772. * init status manager
  1773. *
  1774. * preloads jQuery elements
  1775. *
  1776. * @name Alert.init
  1777. * @function
  1778. */
  1779. me.init = function () {
  1780. // hide "no javascript" error message (guard in test environments)
  1781. const noscriptEl = document.getElementById('noscript');
  1782. if (noscriptEl) {
  1783. noscriptEl.style.display = 'none';
  1784. }
  1785. // not a reset, but first set of the elements
  1786. errorMessage = document.getElementById('errormessage');
  1787. loadingIndicator = document.getElementById('loadingindicator');
  1788. statusMessage = document.getElementById('status');
  1789. remainingTime = document.getElementById('remainingtime');
  1790. currentIcon = [
  1791. 'glyphicon-time', // loading icon
  1792. 'glyphicon-info-sign', // status icon
  1793. 'glyphicon-warning-sign', // warning icon
  1794. 'glyphicon-alert' // error icon
  1795. ];
  1796. };
  1797. return me;
  1798. })();
  1799. /**
  1800. * handles paste status/result
  1801. *
  1802. * @name PasteStatus
  1803. * @class
  1804. */
  1805. const PasteStatus = (function () {
  1806. const me = {};
  1807. let pasteSuccess,
  1808. pasteUrl,
  1809. remainingTime,
  1810. shortenButton;
  1811. /**
  1812. * forward to URL shortener
  1813. *
  1814. * @name PasteStatus.sendToShortener
  1815. * @private
  1816. * @function
  1817. */
  1818. function sendToShortener() {
  1819. if (shortenButton.classList.contains('buttondisabled')) {
  1820. return;
  1821. }
  1822. fetch(`${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`, {
  1823. method: 'GET',
  1824. headers: { 'Accept': 'text/html, application/xhtml+xml, application/xml, application/json' },
  1825. credentials: 'omit',
  1826. signal: AbortSignal.timeout(10000)
  1827. })
  1828. .then(response => {
  1829. if (!response.ok) {
  1830. throw new Error('HTTP ' + response.status);
  1831. }
  1832. return response.text();
  1833. })
  1834. .then(data => PasteStatus.extractUrl(data))
  1835. .catch(error => {
  1836. console.error('Shortener error:', error);
  1837. // we don't know why it failed, could be CORS of the external
  1838. // server not setup properly, in which case we follow old
  1839. // behavior to open it in new tab
  1840. window.open(
  1841. `${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`,
  1842. '_blank',
  1843. 'noopener, noreferrer'
  1844. );
  1845. });
  1846. }
  1847. /**
  1848. * Forces opening the document if the link does not do this automatically.
  1849. *
  1850. * This is necessary as browsers will not reload the page when it is
  1851. * already loaded (which is fake as it is set via history.pushState()).
  1852. *
  1853. * @name PasteStatus.pasteLinkClick
  1854. * @function
  1855. */
  1856. function pasteLinkClick() {
  1857. // check if location is (already) shown in URL bar
  1858. if (window.location.href === pasteUrl.href) {
  1859. // if so we need to load link by reloading the current site
  1860. window.location.reload(true);
  1861. }
  1862. }
  1863. /**
  1864. * creates a notification after a successful document upload
  1865. *
  1866. * @name PasteStatus.createPasteNotification
  1867. * @function
  1868. * @param {string} url
  1869. * @param {string} deleteUrl
  1870. */
  1871. me.createPasteNotification = function (url, deleteUrl) {
  1872. I18n._(
  1873. document.getElementById('pastelink'),
  1874. 'Your document is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit <kbd>Ctrl</kbd>+<kbd>c</kbd> to copy)</span>',
  1875. url, url
  1876. );
  1877. // save newly created element
  1878. pasteUrl = document.getElementById('pasteurl');
  1879. // and add click event
  1880. pasteUrl.addEventListener('click', pasteLinkClick);
  1881. // delete link
  1882. const deleteLink = document.getElementById('deletelink');
  1883. if (deleteLink) {
  1884. deleteLink.href = deleteUrl;
  1885. }
  1886. I18n._(document.querySelector('#deletelink span:not(.glyphicon)'), 'Delete data');
  1887. // enable shortener button
  1888. shortenButton.classList.remove('buttondisabled');
  1889. // show result
  1890. pasteSuccess.classList.remove('hidden');
  1891. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1892. Helper.selectText(pasteUrl);
  1893. };
  1894. /**
  1895. * Checks if auto-shortening is enabled and sends the link to the shortener if it is.
  1896. *
  1897. * @name PasteStatus.checkAutoShorten
  1898. * @function
  1899. */
  1900. me.checkAutoShorten = function () {
  1901. // check if auto-shortening is enabled
  1902. if (shortenButton.dataset.autoshorten === 'true') {
  1903. // if so, we send the link to the shortener
  1904. // we do not remove the button, in case shortener fails
  1905. sendToShortener();
  1906. }
  1907. }
  1908. /**
  1909. * extracts URLs from given string
  1910. *
  1911. * if at least one is found, it disables the shortener button and
  1912. * replaces the document URL
  1913. *
  1914. * @name PasteStatus.extractUrl
  1915. * @function
  1916. * @param {string} response
  1917. */
  1918. me.extractUrl = function (response) {
  1919. if (typeof response === 'object') {
  1920. response = JSON.stringify(response);
  1921. }
  1922. if (typeof response === 'string' && response.length > 0) {
  1923. const shortUrlMatcher = /https?:\/\/[^\s"<]+/g; // JSON API will have URL in quotes, XML in tags
  1924. const shortUrl = (response.match(shortUrlMatcher) || []).filter(function (urlRegExMatch) {
  1925. if (typeof URL.canParse === 'function') {
  1926. return URL.canParse(urlRegExMatch);
  1927. }
  1928. // polyfill for older browsers (< 120) & node (< 19.9 & < 18.17)
  1929. try {
  1930. return !!new URL(urlRegExMatch);
  1931. } catch (error) {
  1932. return false;
  1933. }
  1934. }).sort(function (a, b) {
  1935. return a.length - b.length; // shortest first
  1936. })[0];
  1937. if (typeof shortUrl === 'string' && shortUrl.length > 0) {
  1938. // we disable the button to avoid calling shortener again
  1939. shortenButton.classList.add('buttondisabled');
  1940. // update link
  1941. pasteUrl.textContent = shortUrl;
  1942. pasteUrl.href = shortUrl;
  1943. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1944. Helper.selectText(pasteUrl);
  1945. CopyToClipboard.setUrl(shortUrl);
  1946. return;
  1947. }
  1948. }
  1949. Alert.showError('Cannot parse response from URL shortener.');
  1950. };
  1951. /**
  1952. * shows the remaining time
  1953. *
  1954. * @name PasteStatus.showRemainingTime
  1955. * @function
  1956. * @param {Paste} paste
  1957. */
  1958. me.showRemainingTime = function (paste) {
  1959. if (paste.isBurnAfterReadingEnabled()) {
  1960. // display document "for your eyes only" if it is deleted
  1961. // the document has been deleted when the JSON with the ciphertext
  1962. // has been downloaded
  1963. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1964. remainingTime.classList.add('foryoureyesonly');
  1965. } else if (paste.getTimeToLive() > 0) {
  1966. // display document expiration
  1967. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1968. expirationLabel = [
  1969. 'This document will expire in %d ' + expiration[1] + '.',
  1970. 'This document will expire in %d ' + expiration[1] + 's.'
  1971. ];
  1972. Alert.showRemaining([expirationLabel, expiration[0]]);
  1973. remainingTime.classList.remove('foryoureyesonly');
  1974. } else {
  1975. // never expires
  1976. return;
  1977. }
  1978. // in the end, display notification
  1979. remainingTime.classList.remove('hidden');
  1980. };
  1981. /**
  1982. * hides the remaining time and successful upload notification
  1983. *
  1984. * @name PasteStatus.hideMessages
  1985. * @function
  1986. */
  1987. me.hideMessages = function () {
  1988. remainingTime.classList.add('hidden');
  1989. pasteSuccess.classList.add('hidden');
  1990. };
  1991. /**
  1992. * init status manager
  1993. *
  1994. * preloads jQuery elements
  1995. *
  1996. * @name PasteStatus.init
  1997. * @function
  1998. */
  1999. me.init = function () {
  2000. pasteSuccess = document.getElementById('pastesuccess');
  2001. // pasteUrl is saved in me.createPasteNotification() after creation
  2002. remainingTime = document.getElementById('remainingtime');
  2003. shortenButton = document.getElementById('shortenbutton');
  2004. // bind elements
  2005. if (shortenButton) {
  2006. shortenButton.addEventListener('click', sendToShortener);
  2007. }
  2008. };
  2009. return me;
  2010. })();
  2011. /**
  2012. * password prompt
  2013. *
  2014. * @name Prompt
  2015. * @class
  2016. */
  2017. const Prompt = (function () {
  2018. const me = {};
  2019. let passwordDecrypt,
  2020. passwordModal,
  2021. bootstrap5PasswordModal = null,
  2022. password = '';
  2023. /**
  2024. * submit a password in the modal dialog
  2025. *
  2026. * @name Prompt.submitPasswordModal
  2027. * @private
  2028. * @function
  2029. * @param {Event} event
  2030. */
  2031. function submitPasswordModal(event) {
  2032. event.preventDefault();
  2033. // get input
  2034. password = passwordDecrypt.value;
  2035. // hide modal
  2036. if (bootstrap5PasswordModal) {
  2037. bootstrap5PasswordModal.hide();
  2038. } else {
  2039. if (passwordModal) {
  2040. passwordModal.classList.remove('show');
  2041. passwordModal.style.display = 'none';
  2042. }
  2043. }
  2044. PasteDecrypter.run();
  2045. }
  2046. /**
  2047. * Request users confirmation to load possibly burn after reading document
  2048. *
  2049. * @name Prompt.requestLoadConfirmation
  2050. * @function
  2051. */
  2052. me.requestLoadConfirmation = function () {
  2053. const loadconfirmmodal = document.getElementById('loadconfirmmodal');
  2054. const loadconfirmOpenNow = loadconfirmmodal.querySelector('#loadconfirm-open-now');
  2055. loadconfirmOpenNow.removeEventListener('click', PasteDecrypter.run);
  2056. loadconfirmOpenNow.addEventListener('click', PasteDecrypter.run);
  2057. const loadconfirmClose = loadconfirmmodal.querySelector('.close');
  2058. loadconfirmClose.removeEventListener('click', Controller.newPaste);
  2059. loadconfirmClose.addEventListener('click', Controller.newPaste);
  2060. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2061. (new bootstrap.Modal(loadconfirmmodal)).show();
  2062. } else {
  2063. // minimal fallback: make element visible
  2064. loadconfirmmodal.classList.add('show');
  2065. }
  2066. }
  2067. /**
  2068. * ask the user for the password and set it
  2069. *
  2070. * @name Prompt.requestPassword
  2071. * @function
  2072. */
  2073. me.requestPassword = function () {
  2074. // show new bootstrap method (if available)
  2075. if (passwordModal !== null) {
  2076. if (bootstrap5PasswordModal) {
  2077. bootstrap5PasswordModal.show();
  2078. }
  2079. return;
  2080. }
  2081. PasteDecrypter.run();
  2082. };
  2083. /**
  2084. * get the cached password
  2085. *
  2086. * If you do not get a password with this function
  2087. * (returns an empty string), use requestPassword.
  2088. *
  2089. * @name Prompt.getPassword
  2090. * @function
  2091. * @return {string}
  2092. */
  2093. me.getPassword = function () {
  2094. return password;
  2095. };
  2096. /**
  2097. * resets the password to an empty string
  2098. *
  2099. * @name Prompt.reset
  2100. * @function
  2101. */
  2102. me.reset = function () {
  2103. // reset internal
  2104. password = '';
  2105. // and also reset UI
  2106. passwordDecrypt.value = '';
  2107. };
  2108. /**
  2109. * init status manager
  2110. *
  2111. * preloads jQuery elements
  2112. *
  2113. * @name Prompt.init
  2114. * @function
  2115. */
  2116. me.init = function () {
  2117. passwordDecrypt = document.getElementById('passworddecrypt');
  2118. passwordModal = document.getElementById('passwordmodal');
  2119. // bind events - handle Model password submission
  2120. if (passwordModal) {
  2121. const passwordForm = document.getElementById('passwordform');
  2122. if (passwordForm) {
  2123. passwordForm.addEventListener('submit', submitPasswordModal);
  2124. }
  2125. const disableClosingConfig = {
  2126. backdrop: 'static',
  2127. keyboard: false,
  2128. show: false
  2129. };
  2130. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip && typeof bootstrap.Modal === 'function') {
  2131. bootstrap5PasswordModal = new bootstrap.Modal(passwordModal, disableClosingConfig);
  2132. } else {
  2133. // fallback: keep modal hidden until explicitly shown
  2134. passwordModal.style.display = 'none';
  2135. }
  2136. // ensure focus when modal shown (works for bootstrap5)
  2137. passwordModal.addEventListener('shown.bs.modal', () => {
  2138. passwordDecrypt.focus();
  2139. });
  2140. }
  2141. };
  2142. return me;
  2143. })();
  2144. /**
  2145. * Manage paste/message input, and preview tab
  2146. *
  2147. * Note that the actual preview is handled by PasteViewer.
  2148. *
  2149. * @name Editor
  2150. * @class
  2151. */
  2152. const Editor = (function () {
  2153. const me = {};
  2154. let editorTabs,
  2155. messageEdit,
  2156. messageEditParent,
  2157. messagePreview,
  2158. messagePreviewParent,
  2159. messageTab,
  2160. messageTabParent,
  2161. message,
  2162. isPreview = false,
  2163. isTabSupported = true;
  2164. /**
  2165. * support input of tab character
  2166. *
  2167. * @name Editor.supportTabs
  2168. * @function
  2169. * @param {Event} event
  2170. * @this $message (but not used, so it is jQuery-free, possibly faster)
  2171. */
  2172. function supportTabs(event) {
  2173. // support disabling tab support using [Esc] and [Ctrl]+[m]
  2174. if (event.key === 'Escape' || (event.ctrlKey && event.key === 'm')) {
  2175. toggleTabSupport();
  2176. if (messageTab) messageTab.checked = isTabSupported;
  2177. event.preventDefault();
  2178. }
  2179. else if (isTabSupported && event.key === 'Tab') {
  2180. // get caret position & selection
  2181. const val = this.value,
  2182. start = this.selectionStart,
  2183. end = this.selectionEnd;
  2184. // set textarea value to: text before caret + tab + text after caret
  2185. this.value = val.substring(0, start) + '\t' + val.substring(end);
  2186. // put caret at right position again
  2187. this.selectionStart = this.selectionEnd = start + 1;
  2188. // prevent the textarea to lose focus
  2189. event.preventDefault();
  2190. }
  2191. }
  2192. /**
  2193. * toggle tab support in message textarea
  2194. *
  2195. * @name Editor.toggleTabSupport
  2196. * @private
  2197. * @function
  2198. */
  2199. function toggleTabSupport() {
  2200. isTabSupported = !isTabSupported;
  2201. }
  2202. /**
  2203. * view the Editor tab
  2204. *
  2205. * @name Editor.viewEditor
  2206. * @function
  2207. * @param {Event} event - optional
  2208. */
  2209. function viewEditor(event) {
  2210. // toggle buttons
  2211. messageEdit.classList.add('active');
  2212. messageEditParent.classList.add('active');
  2213. messagePreview.classList.remove('active');
  2214. messagePreviewParent.classList.remove('active');
  2215. messageEdit.setAttribute('aria-selected', 'true');
  2216. messagePreview.setAttribute('aria-selected', 'false');
  2217. PasteViewer.hide();
  2218. // reshow input
  2219. message.classList.remove('hidden');
  2220. messageTabParent.classList.remove('hidden');
  2221. me.focusInput();
  2222. // finish
  2223. isPreview = false;
  2224. // prevent jumping of page to top
  2225. if (typeof event !== 'undefined') {
  2226. event.preventDefault();
  2227. }
  2228. }
  2229. /**
  2230. * view the preview tab
  2231. *
  2232. * @name Editor.viewPreview
  2233. * @function
  2234. * @param {Event} event
  2235. */
  2236. function viewPreview(event) {
  2237. // toggle buttons
  2238. messageEdit.classList.remove('active');
  2239. messageEditParent.classList.remove('active');
  2240. messagePreview.classList.add('active');
  2241. messagePreviewParent.classList.add('active');
  2242. messageEdit.setAttribute('aria-selected', 'false');
  2243. messagePreview.setAttribute('aria-selected', 'true');
  2244. // hide input as now preview is shown
  2245. message.classList.add('hidden');
  2246. messageTabParent.classList.add('hidden');
  2247. // show preview
  2248. PasteViewer.setText(message.value);
  2249. if (AttachmentViewer.hasAttachmentData()) {
  2250. const attachmentsData = AttachmentViewer.getAttachmentsData();
  2251. attachmentsData.forEach(attachmentData => {
  2252. const mimeType = AttachmentViewer.getAttachmentMimeType(attachmentData);
  2253. AttachmentViewer.handleBlobAttachmentPreview(
  2254. AttachmentViewer.getAttachmentPreview(),
  2255. attachmentData, mimeType
  2256. );
  2257. });
  2258. AttachmentViewer.showAttachment();
  2259. }
  2260. PasteViewer.run();
  2261. // finish
  2262. isPreview = true;
  2263. // prevent jumping of page to top
  2264. if (typeof event !== 'undefined') {
  2265. event.preventDefault();
  2266. }
  2267. }
  2268. /**
  2269. * get the state of the preview
  2270. *
  2271. * @name Editor.isPreview
  2272. * @function
  2273. */
  2274. me.isPreview = function () {
  2275. return isPreview;
  2276. };
  2277. /**
  2278. * reset the Editor view
  2279. *
  2280. * @name Editor.resetInput
  2281. * @function
  2282. */
  2283. me.resetInput = function () {
  2284. // go back to input
  2285. if (isPreview) {
  2286. viewEditor();
  2287. }
  2288. // clear content
  2289. message.value = '';
  2290. };
  2291. /**
  2292. * shows the Editor
  2293. *
  2294. * @name Editor.show
  2295. * @function
  2296. */
  2297. me.show = function () {
  2298. message.classList.remove('hidden');
  2299. messageTabParent.classList.remove('hidden');
  2300. editorTabs.classList.remove('hidden');
  2301. };
  2302. /**
  2303. * hides the Editor
  2304. *
  2305. * @name Editor.hide
  2306. * @function
  2307. */
  2308. me.hide = function () {
  2309. message.classList.add('hidden');
  2310. messageTabParent.classList.add('hidden');
  2311. editorTabs.classList.add('hidden');
  2312. };
  2313. /**
  2314. * focuses the message input
  2315. *
  2316. * @name Editor.focusInput
  2317. * @function
  2318. */
  2319. me.focusInput = function () {
  2320. message.focus();
  2321. };
  2322. /**
  2323. * sets a new text
  2324. *
  2325. * @name Editor.setText
  2326. * @function
  2327. * @param {string} newText
  2328. */
  2329. me.setText = function (newText) {
  2330. message.value = newText;
  2331. };
  2332. /**
  2333. * returns the current text
  2334. *
  2335. * @name Editor.getText
  2336. * @function
  2337. * @return {string}
  2338. */
  2339. me.getText = function () {
  2340. return message.value;
  2341. };
  2342. /**
  2343. * init editor
  2344. *
  2345. * preloads jQuery elements
  2346. *
  2347. * @name Editor.init
  2348. * @function
  2349. */
  2350. me.init = function () {
  2351. editorTabs = document.getElementById('editorTabs');
  2352. message = document.getElementById('message');
  2353. messageTab = document.getElementById('messagetab');
  2354. messageTabParent = messageTab ? messageTab.parentElement : null;
  2355. // bind events
  2356. if (message) {
  2357. message.addEventListener('keydown', supportTabs);
  2358. }
  2359. if (messageTab) {
  2360. messageTab.addEventListener('change', toggleTabSupport);
  2361. }
  2362. // bind click events to tab switchers (a), and save parents (li)
  2363. messageEdit = document.getElementById('messageedit');
  2364. if (messageEdit) {
  2365. messageEdit.addEventListener('click', viewEditor);
  2366. messageEditParent = messageEdit.parentElement;
  2367. }
  2368. messagePreview = document.getElementById('messagepreview');
  2369. if (messagePreview) {
  2370. messagePreview.addEventListener('click', viewPreview);
  2371. messagePreviewParent = messagePreview.parentElement;
  2372. }
  2373. };
  2374. return me;
  2375. })();
  2376. /**
  2377. * (view) Parse and show document.
  2378. *
  2379. * @name PasteViewer
  2380. * @class
  2381. */
  2382. const PasteViewer = (function () {
  2383. const me = {};
  2384. let messageTabParent,
  2385. placeholder,
  2386. prettyMessage,
  2387. prettyPrintEl,
  2388. plainText,
  2389. text,
  2390. format = 'plaintext',
  2391. isDisplayed = false,
  2392. isChanged = true; // by default true as nothing was parsed yet
  2393. /**
  2394. * apply the set format on paste and displays it
  2395. *
  2396. * @name PasteViewer.parsePaste
  2397. * @private
  2398. * @function
  2399. */
  2400. function parsePaste() {
  2401. // skip parsing if no text is given
  2402. if (text === '') {
  2403. return;
  2404. }
  2405. if (format === 'markdown') {
  2406. const converter = new showdown.Converter({
  2407. strikethrough: true,
  2408. tables: true,
  2409. tablesHeaderId: true,
  2410. simplifiedAutoLink: true,
  2411. excludeTrailingPunctuationFromURLs: true
  2412. });
  2413. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2414. plainText.innerHTML = DOMPurify.sanitize(
  2415. converter.makeHtml(text),
  2416. purifyHtmlConfig
  2417. );
  2418. // add table classes from bootstrap css
  2419. plainText.querySelectorAll('table').forEach(t => {
  2420. t.classList.add('table-condensed', 'table-bordered');
  2421. });
  2422. } else {
  2423. if (format === 'syntaxhighlighting') {
  2424. // yes, this is really needed to initialize the environment
  2425. if (typeof prettyPrint === 'function') {
  2426. prettyPrint();
  2427. }
  2428. prettyPrintEl.innerHTML = prettyPrintOne(
  2429. Helper.htmlEntities(text), null, true
  2430. );
  2431. } else {
  2432. // = 'plaintext'
  2433. prettyPrintEl.textContent = text;
  2434. }
  2435. Helper.urls2links(prettyPrintEl);
  2436. prettyPrintEl.style.whiteSpace = 'pre-wrap';
  2437. prettyPrintEl.style.wordBreak = 'normal';
  2438. prettyPrintEl.classList.remove('prettyprint');
  2439. }
  2440. }
  2441. /**
  2442. * displays the document
  2443. *
  2444. * @name PasteViewer.showPaste
  2445. * @private
  2446. * @function
  2447. */
  2448. function showPaste() {
  2449. // instead of "nothing" better display a placeholder
  2450. if (text === '') {
  2451. if (placeholder) placeholder.classList.remove('hidden');
  2452. return;
  2453. }
  2454. // otherwise hide the placeholder
  2455. if (placeholder) placeholder.classList.add('hidden');
  2456. if (messageTabParent) messageTabParent.classList.add('hidden');
  2457. if (format === 'markdown') {
  2458. if (plainText) plainText.classList.remove('hidden');
  2459. if (prettyMessage) prettyMessage.classList.add('hidden');
  2460. } else {
  2461. if (plainText) plainText.classList.add('hidden');
  2462. if (prettyMessage) prettyMessage.classList.remove('hidden');
  2463. }
  2464. }
  2465. /**
  2466. * sets the format in which the text is shown
  2467. *
  2468. * @name PasteViewer.setFormat
  2469. * @function
  2470. * @param {string} newFormat the new format
  2471. */
  2472. me.setFormat = function (newFormat) {
  2473. // skip if there is no update
  2474. if (format === newFormat) {
  2475. return;
  2476. }
  2477. // needs to update display too, if we switch from or to Markdown
  2478. if (format === 'markdown' || newFormat === 'markdown') {
  2479. isDisplayed = false;
  2480. }
  2481. format = newFormat;
  2482. isChanged = true;
  2483. // update preview
  2484. if (Editor.isPreview()) {
  2485. PasteViewer.run();
  2486. }
  2487. };
  2488. /**
  2489. * returns the current format
  2490. *
  2491. * @name PasteViewer.getFormat
  2492. * @function
  2493. * @return {string}
  2494. */
  2495. me.getFormat = function () {
  2496. return format;
  2497. };
  2498. /**
  2499. * returns whether the current view is pretty printed
  2500. *
  2501. * @name PasteViewer.isPrettyPrinted
  2502. * @function
  2503. * @return {bool}
  2504. */
  2505. me.isPrettyPrinted = function () {
  2506. return $prettyPrint.hasClass('prettyprinted');
  2507. };
  2508. /**
  2509. * sets the text to show
  2510. *
  2511. * @name PasteViewer.setText
  2512. * @function
  2513. * @param {string} newText the text to show
  2514. */
  2515. me.setText = function (newText) {
  2516. if (text !== newText) {
  2517. text = newText;
  2518. isChanged = true;
  2519. }
  2520. };
  2521. /**
  2522. * gets the current cached text
  2523. *
  2524. * @name PasteViewer.getText
  2525. * @function
  2526. * @return {string}
  2527. */
  2528. me.getText = function () {
  2529. return text;
  2530. };
  2531. /**
  2532. * show/update the parsed text (preview)
  2533. *
  2534. * @name PasteViewer.run
  2535. * @function
  2536. */
  2537. me.run = function () {
  2538. if (isChanged) {
  2539. parsePaste();
  2540. isChanged = false;
  2541. }
  2542. if (!isDisplayed) {
  2543. showPaste();
  2544. isDisplayed = true;
  2545. }
  2546. };
  2547. /**
  2548. * hide parsed text (preview)
  2549. *
  2550. * @name PasteViewer.hide
  2551. * @function
  2552. */
  2553. me.hide = function () {
  2554. if (!isDisplayed) {
  2555. return;
  2556. }
  2557. if (plainText) plainText.classList.add('hidden');
  2558. if (prettyMessage) prettyMessage.classList.add('hidden');
  2559. if (placeholder) placeholder.classList.add('hidden');
  2560. AttachmentViewer.hideAttachmentPreview();
  2561. isDisplayed = false;
  2562. };
  2563. /**
  2564. * init status manager
  2565. *
  2566. * preloads jQuery elements
  2567. *
  2568. * @name PasteViewer.init
  2569. * @function
  2570. */
  2571. me.init = function () {
  2572. const messagetab = document.getElementById('messagetab');
  2573. messageTabParent = messagetab ? messagetab.parentElement : null;
  2574. placeholder = document.getElementById('placeholder');
  2575. plainText = document.getElementById('plaintext');
  2576. prettyMessage = document.getElementById('prettymessage');
  2577. prettyPrintEl = document.getElementById('prettyprint');
  2578. // get default option from template/HTML or fall back to set value
  2579. format = Model.getFormatDefault() || format;
  2580. text = '';
  2581. isDisplayed = false;
  2582. isChanged = true;
  2583. };
  2584. return me;
  2585. })();
  2586. /**
  2587. * (view) Show attachment and preview if possible
  2588. *
  2589. * @name AttachmentViewer
  2590. * @class
  2591. */
  2592. const AttachmentViewer = (function () {
  2593. const me = {};
  2594. let attachmentPreview,
  2595. attachment,
  2596. attachmentsData = [],
  2597. files,
  2598. fileInput,
  2599. dragAndDropFileNames,
  2600. dropzone;
  2601. /**
  2602. * get blob URL from string data and mime type
  2603. *
  2604. * @name AttachmentViewer.getBlobUrl
  2605. * @private
  2606. * @function
  2607. * @param {string} data - raw data of attachment
  2608. * @param {string} data - mime type of attachment
  2609. * @return {string} objectURL
  2610. */
  2611. function getBlobUrl(data, mimeType) {
  2612. // Transform into a Blob
  2613. const buf = new Uint8Array(data.length);
  2614. for (let i = 0; i < data.length; ++i) {
  2615. buf[i] = data.charCodeAt(i);
  2616. }
  2617. const blob = new window.Blob(
  2618. [buf],
  2619. {
  2620. type: mimeType
  2621. }
  2622. );
  2623. // Get blob URL
  2624. return window.URL.createObjectURL(blob);
  2625. }
  2626. /**
  2627. * sets the attachment but does not yet show it
  2628. *
  2629. * @name AttachmentViewer.setAttachment
  2630. * @function
  2631. * @param {string} attachmentData - base64-encoded data of file
  2632. * @param {string} fileName - optional, file name
  2633. */
  2634. me.setAttachment = function (attachmentData, fileName) {
  2635. // skip, if attachments got disabled
  2636. if (!attachment || !attachmentPreview) return;
  2637. // data URI format: data:[<mimeType>][;base64],<data>
  2638. const template = Model.getTemplate('attachment');
  2639. const attachmentLink = template.querySelector('a');
  2640. // position in data URI string of where data begins
  2641. const base64Start = attachmentData.indexOf(',') + 1;
  2642. const mimeType = me.getAttachmentMimeType(attachmentData);
  2643. // extract data and convert to binary
  2644. const rawData = attachmentData.substring(base64Start);
  2645. const decodedData = rawData.length > 0 ? atob(rawData) : '';
  2646. let blobUrl = getBlobUrl(decodedData, mimeType);
  2647. attachmentLink.setAttribute('href', blobUrl);
  2648. if (typeof fileName !== 'undefined') {
  2649. attachmentLink.setAttribute('download', fileName);
  2650. const fileSize = Helper.formatBytes(decodedData.length);
  2651. const spans = template.querySelectorAll('span');
  2652. const span = spans[spans.length - 1];
  2653. span.textContent += ` (${fileName}, ${fileSize})`;
  2654. }
  2655. // sanitize SVG preview
  2656. // prevents executing embedded scripts when CSP is not set and user
  2657. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2658. // in the preview by use of an img tag, which disables scripts, too
  2659. if (mimeType.match(/^image\/.*svg/i)) {
  2660. const sanitizedData = DOMPurify.sanitize(
  2661. decodedData,
  2662. purifySvgConfig
  2663. );
  2664. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2665. }
  2666. template.classList.remove('hidden');
  2667. attachment.appendChild(template);
  2668. me.handleBlobAttachmentPreview(attachmentPreview, blobUrl, mimeType);
  2669. };
  2670. /**
  2671. * displays the attachment
  2672. *
  2673. * @name AttachmentViewer.showAttachment
  2674. * @function
  2675. */
  2676. me.showAttachment = function () {
  2677. // skip, if attachments got disabled
  2678. if (!attachment || !attachmentPreview) return;
  2679. attachment.classList.remove('hidden');
  2680. if (me.hasAttachmentPreview()) {
  2681. attachmentPreview.classList.remove('hidden');
  2682. }
  2683. };
  2684. /**
  2685. * removes the attachment
  2686. *
  2687. * This automatically hides the attachment containers too, to
  2688. * prevent an inconsistent display.
  2689. *
  2690. * @name AttachmentViewer.removeAttachment
  2691. * @function
  2692. */
  2693. me.removeAttachment = function () {
  2694. if (!attachment) {
  2695. return;
  2696. }
  2697. me.hideAttachment();
  2698. me.hideAttachmentPreview();
  2699. attachment.innerHTML = '';
  2700. attachmentPreview.innerHTML = '';
  2701. dragAndDropFileNames.innerHTML = '';
  2702. AttachmentViewer.removeAttachmentData();
  2703. };
  2704. /**
  2705. * removes the attachment data
  2706. *
  2707. * This removes the data, which would be uploaded otherwise.
  2708. *
  2709. * @name AttachmentViewer.removeAttachmentData
  2710. * @function
  2711. */
  2712. me.removeAttachmentData = function () {
  2713. files = undefined;
  2714. attachmentsData = [];
  2715. };
  2716. /**
  2717. * Cleares the drag & drop data.
  2718. *
  2719. * @name AttachmentViewer.clearDragAndDrop
  2720. * @function
  2721. */
  2722. me.clearDragAndDrop = function () {
  2723. if (dragAndDropFileNames) {
  2724. dragAndDropFileNames.innerHTML = '';
  2725. }
  2726. };
  2727. /**
  2728. * Print file names added via drag & drop
  2729. *
  2730. * @name AttachmentViewer.printDragAndDropFileNames
  2731. * @private
  2732. * @function
  2733. * @param {string[]} fileNames
  2734. */
  2735. function printDragAndDropFileNames(fileNames) {
  2736. dragAndDropFileNames.innerHTML = '';
  2737. fileNames.forEach(fileName => {
  2738. const name = document.createTextNode(fileName);
  2739. dragAndDropFileNames.appendChild(name);
  2740. dragAndDropFileNames.appendChild(document.createElement('br'));
  2741. });
  2742. }
  2743. /**
  2744. * hides the attachment
  2745. *
  2746. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2747. * for that) nor will it hide the attachment link if it was moved somewhere
  2748. * else (see AttachmentViewer.moveAttachmentTo).
  2749. *
  2750. * @name AttachmentViewer.hideAttachment
  2751. * @function
  2752. */
  2753. me.hideAttachment = function () {
  2754. attachment.classList.add('hidden');
  2755. };
  2756. /**
  2757. * hides the attachment preview
  2758. *
  2759. * @name AttachmentViewer.hideAttachmentPreview
  2760. * @function
  2761. */
  2762. me.hideAttachmentPreview = function () {
  2763. if (attachmentPreview) {
  2764. attachmentPreview.classList.add('hidden');
  2765. }
  2766. };
  2767. /**
  2768. * checks if has any attachment preview
  2769. *
  2770. * @name AttachmentViewer.hasAttachmentPreview
  2771. * @function
  2772. * @return {JQuery}
  2773. */
  2774. me.hasAttachmentPreview = function () {
  2775. return attachmentPreview.children.length > 0;
  2776. }
  2777. /**
  2778. * checks if there is an attachment displayed
  2779. *
  2780. * @name AttachmentViewer.hasAttachment
  2781. * @function
  2782. */
  2783. me.hasAttachment = function () {
  2784. if (!attachment) {
  2785. return false;
  2786. }
  2787. return attachment.children.length > 0;
  2788. };
  2789. /**
  2790. * checks if there is attachment data (for preview!) available
  2791. *
  2792. * It returns true, when there is data that needs to be encrypted.
  2793. *
  2794. * @name AttachmentViewer.hasAttachmentData
  2795. * @function
  2796. */
  2797. me.hasAttachmentData = function () {
  2798. if (attachment) {
  2799. return true;
  2800. }
  2801. return false;
  2802. };
  2803. /**
  2804. * return the attachments
  2805. *
  2806. * @name AttachmentViewer.getAttachments
  2807. * @function
  2808. * @returns {array}
  2809. */
  2810. me.getAttachments = function () {
  2811. return [...attachment.querySelectorAll('a')].map(link => (
  2812. [
  2813. link.href,
  2814. link.download
  2815. ]
  2816. ));
  2817. };
  2818. /**
  2819. * Get attachment mime type
  2820. *
  2821. * @name AttachmentViewer.getAttachmentMimeType
  2822. * @function
  2823. * @param {string} attachmentData - Base64 string
  2824. */
  2825. me.getAttachmentMimeType = function (attachmentData) {
  2826. // position in data URI string of where mimeType ends
  2827. const mimeTypeEnd = attachmentData.indexOf(';');
  2828. // extract mimeType
  2829. return attachmentData.substring(5, mimeTypeEnd);
  2830. }
  2831. /**
  2832. * moves the attachment link to another element
  2833. *
  2834. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2835. *
  2836. * @name AttachmentViewer.moveAttachmentTo
  2837. * @function
  2838. * @param {HTMLElement} element - the wrapper/container element where this should be moved to
  2839. * @param {array} attachment - attachment data
  2840. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2841. */
  2842. me.moveAttachmentTo = function (element, attachment, label) {
  2843. const attachmentLink = document.createElement('a');
  2844. attachmentLink.className = 'alert-link';
  2845. attachmentLink.href = attachment[0];
  2846. attachmentLink.download = attachment[1];
  2847. // move element to new place
  2848. element.appendChild(attachmentLink);
  2849. // update text - ensuring no HTML is inserted into the text node
  2850. I18n._(attachmentLink, label, attachment[1]);
  2851. };
  2852. /**
  2853. * read files data as data URL using the FileReader API
  2854. *
  2855. * @name AttachmentViewer.readFileData
  2856. * @private
  2857. * @function
  2858. * @param {FileList[]} loadedFiles (optional) loaded files array
  2859. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2860. */
  2861. function readFileData(loadedFiles = []) {
  2862. // Clear old cache
  2863. me.removeAttachmentData();
  2864. if (typeof FileReader === 'undefined') {
  2865. // revert loading status…
  2866. me.hideAttachment();
  2867. me.hideAttachmentPreview();
  2868. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2869. return;
  2870. }
  2871. if (loadedFiles && loadedFiles.length > 0) {
  2872. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2873. printDragAndDropFileNames(fileNames);
  2874. } else {
  2875. const fileInput = document.getElementById('file');
  2876. if (fileInput && fileInput.files) {
  2877. loadedFiles = [...fileInput.files];
  2878. }
  2879. me.clearDragAndDrop();
  2880. }
  2881. if (loadedFiles.length > 0) {
  2882. files = loadedFiles;
  2883. loadedFiles.forEach((loadedFile, index) => {
  2884. const fileReader = new FileReader();
  2885. fileReader.onload = function (event) {
  2886. const dataURL = event.target.result;
  2887. if (dataURL) {
  2888. attachmentsData[index] = dataURL;
  2889. }
  2890. if (Editor.isPreview()) {
  2891. me.handleAttachmentPreview(attachmentPreview, dataURL);
  2892. attachmentPreview.classList.remove('hidden');
  2893. }
  2894. TopNav.highlightFileupload();
  2895. };
  2896. fileReader.readAsDataURL(loadedFile);
  2897. });
  2898. } else {
  2899. me.removeAttachmentData();
  2900. }
  2901. }
  2902. /**
  2903. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2904. *
  2905. * @name AttachmentViewer.handleBlobAttachmentPreview
  2906. * @function
  2907. * @argument {HTMLElement} targetElement element where the preview should be appended
  2908. * @argument {string} file as a blob URL
  2909. * @argument {string} mime type
  2910. */
  2911. me.handleBlobAttachmentPreview = function (targetElement, blobUrl, mimeType) {
  2912. const alreadyIncludesCurrentAttachment = targetElement.querySelectorAll(`[src='${blobUrl}']`).length > 0;
  2913. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  2914. if (mimeType.toLowerCase().startsWith('image/')) {
  2915. const image = document.createElement('img');
  2916. image.setAttribute('src', blobUrl);
  2917. image.setAttribute('class', 'img-thumbnail');
  2918. targetElement.appendChild(image);
  2919. } else if (mimeType.toLowerCase().startsWith('video/')) {
  2920. const video = document.createElement('video');
  2921. video.setAttribute('controls', 'true');
  2922. video.setAttribute('autoplay', 'true');
  2923. video.setAttribute('class', 'img-thumbnail');
  2924. const source = document.createElement('source');
  2925. source.setAttribute('type', mimeType);
  2926. source.setAttribute('src', blobUrl);
  2927. video.appendChild(source);
  2928. targetElement.appendChild(video);
  2929. } else if (mimeType.toLowerCase().startsWith('audio/')) {
  2930. const audio = document.createElement('audio');
  2931. audio.setAttribute('controls', 'true');
  2932. audio.setAttribute('autoplay', 'true');
  2933. const source = document.createElement('source');
  2934. source.setAttribute('type', mimeType);
  2935. source.setAttribute('src', blobUrl);
  2936. audio.appendChild(source);
  2937. targetElement.appendChild(audio);
  2938. } else if (mimeType.toLowerCase().endsWith('/pdf')) {
  2939. const embed = document.createElement('embed');
  2940. embed.setAttribute('src', blobUrl);
  2941. embed.setAttribute('type', 'application/pdf');
  2942. embed.setAttribute('class', 'pdfPreview');
  2943. // Fallback for browsers, that don't support the vh unit
  2944. embed.style.height = window.innerHeight + 'px';
  2945. targetElement.appendChild(embed);
  2946. }
  2947. }
  2948. };
  2949. /**
  2950. * attaches the file attachment drag & drop handler to the page
  2951. *
  2952. * @name AttachmentViewer.addDragDropHandler
  2953. * @private
  2954. * @function
  2955. */
  2956. function addDragDropHandler() {
  2957. if (typeof fileInput === 'undefined' || fileInput === null) {
  2958. return;
  2959. }
  2960. const handleDragEnterOrOver = function (event) {
  2961. event.stopPropagation();
  2962. event.preventDefault();
  2963. return false;
  2964. };
  2965. const handleDrop = function (event) {
  2966. event.stopPropagation();
  2967. event.preventDefault();
  2968. if (TopNav.isAttachmentReadonly()) {
  2969. return false;
  2970. }
  2971. if (fileInput) {
  2972. const files = [...event.dataTransfer.files];
  2973. //Clear the file input:
  2974. fileInput.value = '';
  2975. //Only works in Chrome:
  2976. //fileInput.files = event.dataTransfer.files;
  2977. readFileData(files);
  2978. }
  2979. };
  2980. draghover(document);
  2981. document.addEventListener('draghoverstart', function (e) {
  2982. if (TopNav.isAttachmentReadonly()) {
  2983. e.stopPropagation();
  2984. e.preventDefault();
  2985. return false;
  2986. }
  2987. // show dropzone to indicate drop support
  2988. dropzone.classList.remove('hidden');
  2989. });
  2990. document.addEventListener('draghoverend', function () {
  2991. dropzone.classList.add('hidden');
  2992. });
  2993. document.addEventListener('drop', handleDrop);
  2994. document.addEventListener('dragenter', handleDragEnterOrOver);
  2995. document.addEventListener('dragover', handleDragEnterOrOver);
  2996. fileInput.addEventListener('change', function () {
  2997. readFileData();
  2998. });
  2999. }
  3000. /**
  3001. * attaches the clipboard attachment handler to the page
  3002. *
  3003. * @name AttachmentViewer.addClipboardEventHandler
  3004. * @private
  3005. * @function
  3006. */
  3007. function addClipboardEventHandler() {
  3008. document.addEventListener('paste', (event) => {
  3009. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3010. const files = [...items]
  3011. .filter(item => item.kind === 'file')
  3012. .map(item => item.getAsFile());
  3013. if (TopNav.isAttachmentReadonly() && files.length) {
  3014. event.stopPropagation();
  3015. event.preventDefault();
  3016. return false;
  3017. }
  3018. if (files.length) {
  3019. readFileData(files);
  3020. }
  3021. });
  3022. }
  3023. /**
  3024. * getter for attachment data
  3025. *
  3026. * @name AttachmentViewer.getAttachmentsData
  3027. * @function
  3028. * @return {string[]}
  3029. */
  3030. me.getAttachmentsData = function () {
  3031. return attachmentsData;
  3032. };
  3033. /**
  3034. * getter for attachment preview
  3035. *
  3036. * @name AttachmentViewer.getAttachmentPreview
  3037. * @function
  3038. * @return {jQuery}
  3039. */
  3040. me.getAttachmentPreview = function () {
  3041. return $attachmentPreview;
  3042. };
  3043. /**
  3044. * getter for files data, returns the file list
  3045. *
  3046. * @name AttachmentViewer.getFiles
  3047. * @function
  3048. * @return {FileList[]}
  3049. */
  3050. me.getFiles = function () {
  3051. return files;
  3052. };
  3053. /**
  3054. * initiate
  3055. *
  3056. * preloads jQuery elements
  3057. *
  3058. * @name AttachmentViewer.init
  3059. * @function
  3060. */
  3061. me.init = function () {
  3062. attachment = document.getElementById('attachment');
  3063. dragAndDropFileNames = document.getElementById('dragAndDropFileName');
  3064. dropzone = document.getElementById('dropzone');
  3065. if (attachment) {
  3066. attachmentPreview = document.getElementById('attachmentPreview');
  3067. fileInput = document.getElementById('file');
  3068. addDragDropHandler();
  3069. addClipboardEventHandler();
  3070. }
  3071. }
  3072. return me;
  3073. })();
  3074. /**
  3075. * (view) Shows discussion thread and handles replies
  3076. *
  3077. * @name DiscussionViewer
  3078. * @class
  3079. */
  3080. const DiscussionViewer = (function () {
  3081. const me = {};
  3082. let commentTail,
  3083. discussion,
  3084. reply,
  3085. replyMessage,
  3086. replyNickname,
  3087. replyStatus,
  3088. commentContainer,
  3089. replyCommentId;
  3090. /**
  3091. * initializes the templates
  3092. *
  3093. * @name DiscussionViewer.initTemplates
  3094. * @private
  3095. * @function
  3096. */
  3097. function initTemplates() {
  3098. reply = Model.getTemplate('reply');
  3099. replyMessage = reply.querySelector('#replymessage');
  3100. replyNickname = reply.querySelector('#nickname');
  3101. replyStatus = reply.querySelector('#replystatus');
  3102. // cache elements
  3103. commentTail = Model.getTemplate('commenttail');
  3104. }
  3105. /**
  3106. * open the comment entry when clicking the "Reply" button of a comment
  3107. *
  3108. * @name DiscussionViewer.openReply
  3109. * @private
  3110. * @function
  3111. * @param {Event} event
  3112. */
  3113. function openReply(event) {
  3114. const source = event.target;
  3115. // show all reply buttons
  3116. commentContainer.querySelectorAll('button').forEach(btn => btn.classList.remove('hidden'));
  3117. // hide the current reply button
  3118. source.classList.add('hidden');
  3119. // clear input
  3120. replyMessage.value = '';
  3121. replyNickname.value = '';
  3122. // get comment id from source element
  3123. replyCommentId = source.parentElement.id.split('_')[1];
  3124. // move to correct position
  3125. source.after(reply);
  3126. // show
  3127. reply.classList.remove('hidden');
  3128. replyMessage.focus();
  3129. event.preventDefault();
  3130. }
  3131. /**
  3132. * custom handler for displaying notifications in own status message area
  3133. *
  3134. * @name DiscussionViewer.handleNotification
  3135. * @function
  3136. * @param {string} alertType
  3137. * @return {bool|jQuery}
  3138. */
  3139. me.handleNotification = function (alertType) {
  3140. // ignore loading messages
  3141. if (alertType === 'loading') {
  3142. return false;
  3143. }
  3144. if (alertType === 'danger') {
  3145. replyStatus.classList.remove('alert-info');
  3146. replyStatus.classList.add('alert-danger');
  3147. const replyIcon = replyStatus.querySelector(':first-child');
  3148. if (replyIcon) {
  3149. replyIcon.classList.remove('glyphicon-alert');
  3150. replyIcon.classList.add('glyphicon-info-sign');
  3151. }
  3152. } else {
  3153. replyStatus.classList.remove('alert-danger');
  3154. replyStatus.classList.add('alert-info');
  3155. const replyIcon = replyStatus.querySelector(':first-child');
  3156. if (replyIcon) {
  3157. replyIcon.classList.remove('glyphicon-info-sign');
  3158. replyIcon.classList.add('glyphicon-alert');
  3159. }
  3160. }
  3161. return replyStatus;
  3162. };
  3163. /**
  3164. * adds another comment
  3165. *
  3166. * @name DiscussionViewer.addComment
  3167. * @function
  3168. * @param {Comment} comment
  3169. * @param {string} commentText
  3170. * @param {string} nickname
  3171. */
  3172. me.addComment = function (comment, commentText, nickname) {
  3173. if (commentText === '') {
  3174. commentText = 'comment decryption failed';
  3175. }
  3176. // create new comment based on template
  3177. const commentEntry = Model.getTemplate('comment');
  3178. if (!commentEntry) {
  3179. return;
  3180. }
  3181. commentEntry.id = 'comment_' + comment.id;
  3182. const commentEntryData = commentEntry.querySelector('div.commentdata');
  3183. if (!commentEntryData) {
  3184. return;
  3185. }
  3186. // set & parse text
  3187. commentEntryData.textContent = commentText;
  3188. Helper.urls2links(commentEntryData);
  3189. // set nickname
  3190. if (nickname.length > 0) {
  3191. const nicknameElement = commentEntry.querySelector('span.nickname');
  3192. if (nicknameElement) {
  3193. nicknameElement.textContent = nickname;
  3194. }
  3195. } else {
  3196. const anonCommenter = document.createElement('em');
  3197. anonCommenter.textContent = I18n._('Anonymous');
  3198. const nicknameElement = commentEntry.querySelector('span.nickname');
  3199. if (nicknameElement) {
  3200. nicknameElement.innerHTML = '';
  3201. nicknameElement.appendChild(anonCommenter);
  3202. }
  3203. }
  3204. // set date
  3205. const created = comment.getCreated();
  3206. const commentDate = created === 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3207. const dateSpan = commentEntry.querySelector('span.commentdate');
  3208. if (dateSpan) {
  3209. dateSpan.textContent = commentDate;
  3210. dateSpan.setAttribute('title', 'CommentID: ' + comment.id);
  3211. }
  3212. // if an avatar is available, display it
  3213. const icon = comment.getIcon();
  3214. if (icon) {
  3215. const image = document.createElement('img');
  3216. image.setAttribute('src', icon);
  3217. image.setAttribute('class', 'vizhash');
  3218. const nickSpan = commentEntry.querySelector('span.nickname');
  3219. if (nickSpan) {
  3220. nickSpan.prepend(' ');
  3221. nickSpan.prepend(image);
  3222. }
  3223. }
  3224. // starting point (default value/fallback)
  3225. let place = commentContainer;
  3226. // if parent comment exists
  3227. const parentComment = document.getElementById('comment_' + comment.parentid);
  3228. if (parentComment) {
  3229. // use parent as position for new comment, so it is shifted
  3230. // to the right
  3231. place = parentComment;
  3232. }
  3233. // finally append comment
  3234. place.appendChild(commentEntry);
  3235. };
  3236. /**
  3237. * finishes the discussion area after last comment
  3238. *
  3239. * @name DiscussionViewer.finishDiscussion
  3240. * @function
  3241. */
  3242. me.finishDiscussion = function () {
  3243. // add 'add new comment' area
  3244. commentContainer.appendChild(commentTail);
  3245. // show discussions
  3246. discussion.classList.remove('hidden');
  3247. };
  3248. /**
  3249. * removes the old discussion and prepares everything for creating a new
  3250. * one.
  3251. *
  3252. * @name DiscussionViewer.prepareNewDiscussion
  3253. * @function
  3254. */
  3255. me.prepareNewDiscussion = function () {
  3256. commentContainer.innerHTML = '';
  3257. discussion.classList.add('hidden');
  3258. // (re-)init templates
  3259. initTemplates();
  3260. };
  3261. /**
  3262. * returns the users message from the reply form
  3263. *
  3264. * @name DiscussionViewer.getReplyMessage
  3265. * @function
  3266. * @return {String}
  3267. */
  3268. me.getReplyMessage = function () {
  3269. return replyMessage.value;
  3270. };
  3271. /**
  3272. * returns the users nickname (if any) from the reply form
  3273. *
  3274. * @name DiscussionViewer.getReplyNickname
  3275. * @function
  3276. * @return {String}
  3277. */
  3278. me.getReplyNickname = function () {
  3279. return replyNickname.value;
  3280. };
  3281. /**
  3282. * returns the id of the parent comment the user is replying to
  3283. *
  3284. * @name DiscussionViewer.getReplyCommentId
  3285. * @function
  3286. * @return {int|undefined}
  3287. */
  3288. me.getReplyCommentId = function () {
  3289. return replyCommentId;
  3290. };
  3291. /**
  3292. * highlights a specific comment and scrolls to it if necessary
  3293. *
  3294. * @name DiscussionViewer.highlightComment
  3295. * @function
  3296. * @param {string} commentId
  3297. * @param {bool} fadeOut - whether to fade out the comment
  3298. */
  3299. me.highlightComment = function (commentId, fadeOut) {
  3300. const comment = document.getElementById('comment_' + commentId);
  3301. // in case comment does not exist, cancel
  3302. if (!comment) {
  3303. return;
  3304. }
  3305. comment.classList.add('highlight');
  3306. const highlightComment = function () {
  3307. if (fadeOut === true) {
  3308. setTimeout(function () {
  3309. comment.classList.remove('highlight');
  3310. }, 300);
  3311. }
  3312. };
  3313. if (UiHelper.isVisible(comment)) {
  3314. return highlightComment();
  3315. }
  3316. UiHelper.scrollTo(comment, 100, 'swing', highlightComment);
  3317. };
  3318. /**
  3319. * initiate
  3320. *
  3321. * preloads jQuery elements
  3322. *
  3323. * @name DiscussionViewer.init
  3324. * @function
  3325. */
  3326. me.init = function () {
  3327. // bind events to templates (so they are later cloned)
  3328. const commentTailTemplate = document.getElementById('commenttailtemplate');
  3329. if (commentTailTemplate) {
  3330. commentTailTemplate.querySelectorAll('button').forEach(btn => btn.addEventListener('click', openReply));
  3331. }
  3332. const commentTemplate = document.getElementById('commenttemplate');
  3333. if (commentTemplate) {
  3334. commentTemplate.querySelectorAll('button').forEach(btn => btn.addEventListener('click', openReply));
  3335. }
  3336. const replyTemplate = document.getElementById('replytemplate');
  3337. if (replyTemplate) {
  3338. replyTemplate.querySelectorAll('button').forEach(btn => btn.addEventListener('click', PasteEncrypter.sendComment));
  3339. }
  3340. commentContainer = document.getElementById('commentcontainer');
  3341. discussion = document.getElementById('discussion');
  3342. };
  3343. return me;
  3344. })();
  3345. /**
  3346. * Manage top (navigation) bar
  3347. *
  3348. * @name TopNav
  3349. * @param {object} window
  3350. * @param {object} document
  3351. * @class
  3352. */
  3353. const TopNav = (function (window, document) {
  3354. const me = {};
  3355. let createButtonsDisplayed = false,
  3356. viewButtonsDisplayed = false,
  3357. burnAfterReadingDefault = false,
  3358. openDiscussionDefault = false,
  3359. attach,
  3360. burnAfterReading,
  3361. burnAfterReadingOption,
  3362. cloneButton,
  3363. customAttachment,
  3364. expiration,
  3365. fileRemoveButton,
  3366. fileWrap,
  3367. formatter,
  3368. newButton,
  3369. openDiscussion,
  3370. openDiscussionOption,
  3371. password,
  3372. passwordInput,
  3373. rawTextButton,
  3374. downloadTextButton,
  3375. qrCodeLink,
  3376. emailLink,
  3377. sendButton,
  3378. retryButton,
  3379. pasteExpiration = null,
  3380. retryButtonCallback;
  3381. /**
  3382. * set the expiration on bootstrap templates in dropdown
  3383. *
  3384. * @name TopNav.updateExpiration
  3385. * @private
  3386. * @function
  3387. * @param {Event} event
  3388. */
  3389. function updateExpiration(event) {
  3390. // get selected option
  3391. const target = event.target;
  3392. // update dropdown display and save new expiration time
  3393. const display = document.getElementById('pasteExpirationDisplay');
  3394. if (display) {
  3395. display.textContent = target.textContent;
  3396. }
  3397. pasteExpiration = target.getAttribute('data-expiration');
  3398. event.preventDefault();
  3399. }
  3400. /**
  3401. * set the format on bootstrap templates in dropdown from user interaction
  3402. *
  3403. * @name TopNav.updateFormat
  3404. * @private
  3405. * @function
  3406. * @param {Event} event
  3407. */
  3408. function updateFormat(event) {
  3409. // get selected option
  3410. const target = event.target;
  3411. // update dropdown display and save new format
  3412. const newFormat = target.getAttribute('data-format');
  3413. const display = document.getElementById('pasteFormatterDisplay');
  3414. if (display) {
  3415. display.textContent = target.textContent;
  3416. }
  3417. PasteViewer.setFormat(newFormat);
  3418. event.preventDefault();
  3419. }
  3420. /**
  3421. * when "burn after reading" is checked, disable discussion
  3422. *
  3423. * @name TopNav.changeBurnAfterReading
  3424. * @private
  3425. * @function
  3426. */
  3427. function changeBurnAfterReading() {
  3428. if (me.getBurnAfterReading()) {
  3429. openDiscussionOption.classList.add('buttondisabled');
  3430. openDiscussion.checked = false;
  3431. // if button is actually disabled, force-enable it and uncheck other button
  3432. burnAfterReadingOption.classList.remove('buttondisabled');
  3433. } else {
  3434. openDiscussionOption.classList.remove('buttondisabled');
  3435. }
  3436. }
  3437. /**
  3438. * when discussion is checked, disable "burn after reading"
  3439. *
  3440. * @name TopNav.changeOpenDiscussion
  3441. * @private
  3442. * @function
  3443. */
  3444. function changeOpenDiscussion() {
  3445. if (me.getOpenDiscussion()) {
  3446. burnAfterReadingOption.classList.add('buttondisabled');
  3447. burnAfterReading.checked = false;
  3448. // if button is actually disabled, force-enable it and uncheck other button
  3449. openDiscussionOption.classList.remove('buttondisabled');
  3450. } else {
  3451. burnAfterReadingOption.classList.remove('buttondisabled');
  3452. }
  3453. }
  3454. /**
  3455. * Clear the password input in the top navigation
  3456. *
  3457. * @name TopNav.clearPasswordInput
  3458. * @function
  3459. */
  3460. function clearPasswordInput() {
  3461. passwordInput.value = '';
  3462. }
  3463. /**
  3464. * Clear the attachment input in the top navigation.
  3465. *
  3466. * @name TopNav.clearAttachmentInput
  3467. * @function
  3468. */
  3469. function clearAttachmentInput() {
  3470. // hide UI for selected files
  3471. const inputElement = fileWrap && fileWrap.querySelector('input');
  3472. if (inputElement) {
  3473. inputElement.value = '';
  3474. }
  3475. }
  3476. /**
  3477. * return raw text
  3478. *
  3479. * @name TopNav.rawText
  3480. * @private
  3481. * @function
  3482. */
  3483. function rawText() {
  3484. TopNav.hideAllButtons();
  3485. Alert.showLoading('Showing raw text…', 'time');
  3486. let paste = PasteViewer.getText();
  3487. // push a new state to allow back navigation with browser back button
  3488. history.pushState(
  3489. { type: 'raw' },
  3490. document.title,
  3491. // recreate document URL
  3492. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3493. CryptTool.base58encode(Model.getPasteKey())
  3494. );
  3495. // we use text/html instead of text/plain to avoid a bug when
  3496. // reloading the raw text view (it reverts to type text/html)
  3497. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3498. newDoc = document.open('text/html', 'replace');
  3499. newDoc.write('<!DOCTYPE html><html><head>');
  3500. for (let i = 0; i < $head.length; ++i) {
  3501. newDoc.write($head[i].outerHTML);
  3502. }
  3503. newDoc.write(
  3504. '</head><body><pre>' +
  3505. DOMPurify.sanitize(
  3506. Helper.htmlEntities(paste),
  3507. purifyHtmlConfig
  3508. ) +
  3509. '</pre></body></html>'
  3510. );
  3511. newDoc.close();
  3512. }
  3513. /**
  3514. * download text
  3515. *
  3516. * @name TopNav.downloadText
  3517. * @private
  3518. * @function
  3519. */
  3520. function downloadText() {
  3521. const fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3522. const filename = 'document-' + Model.getPasteId() + fileFormat;
  3523. const text = PasteViewer.getText();
  3524. const element = document.createElement('a');
  3525. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3526. element.setAttribute('download', filename);
  3527. element.style.display = 'none';
  3528. document.body.appendChild(element);
  3529. element.click();
  3530. document.body.removeChild(element);
  3531. }
  3532. /**
  3533. * saves the language in a cookie and reloads the page
  3534. *
  3535. * @name TopNav.setLanguage
  3536. * @private
  3537. * @function
  3538. * @param {Event} event
  3539. */
  3540. function setLanguage(event) {
  3541. let lang = event.target.getAttribute('data-lang') || event.target.value;
  3542. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3543. window.location.reload();
  3544. event.preventDefault();
  3545. }
  3546. /**
  3547. * save the template in a cookie and reloads the page
  3548. *
  3549. * @name TopNav.setTemplate
  3550. * @private
  3551. * @function
  3552. * @param {Event} event
  3553. */
  3554. function setTemplate(event) {
  3555. let template = event.target.getAttribute('data-template') || event.target.value;
  3556. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3557. window.location.reload();
  3558. event.preventDefault();
  3559. }
  3560. /**
  3561. * hides all messages and creates a new document
  3562. *
  3563. * @name TopNav.clickNewPaste
  3564. * @private
  3565. * @function
  3566. */
  3567. function clickNewPaste() {
  3568. Controller.hideStatusMessages();
  3569. Controller.newPaste();
  3570. }
  3571. /**
  3572. * retrys some callback registered before
  3573. *
  3574. * @name TopNav.clickRetryButton
  3575. * @private
  3576. * @function
  3577. * @param {Event} event
  3578. */
  3579. function clickRetryButton(event) {
  3580. retryButtonCallback(event);
  3581. }
  3582. /**
  3583. * removes the existing attachment
  3584. *
  3585. * @name TopNav.removeAttachment
  3586. * @private
  3587. * @function
  3588. * @param {Event} event
  3589. */
  3590. function removeAttachment(event) {
  3591. // if custom attachment is used, remove it first
  3592. if (customAttachment && !customAttachment.classList.contains('hidden')) {
  3593. AttachmentViewer.removeAttachment();
  3594. customAttachment.classList.add('hidden');
  3595. fileWrap.classList.remove('hidden');
  3596. }
  3597. // in any case, remove saved attachment data
  3598. AttachmentViewer.removeAttachmentData();
  3599. clearAttachmentInput();
  3600. AttachmentViewer.clearDragAndDrop();
  3601. // pevent '#' from appearing in the URL
  3602. event.preventDefault();
  3603. }
  3604. /**
  3605. * Shows the QR code of the current document (URL).
  3606. *
  3607. * @name TopNav.displayQrCode
  3608. * @private
  3609. * @function
  3610. */
  3611. function displayQrCode() {
  3612. const qrCanvas = kjua({
  3613. render: 'canvas',
  3614. text: window.location.href
  3615. });
  3616. const qrDisplay = document.getElementById('qrcode-display');
  3617. if (qrDisplay) {
  3618. qrDisplay.innerHTML = '';
  3619. qrDisplay.appendChild(qrCanvas);
  3620. }
  3621. }
  3622. /**
  3623. * Template Email body.
  3624. *
  3625. * @name TopNav.templateEmailBody
  3626. * @private
  3627. * @param {string} expirationDateString
  3628. * @param {bool} isBurnafterreading
  3629. */
  3630. function templateEmailBody(expirationDateString, isBurnafterreading) {
  3631. const EOL = '\n';
  3632. const BULLET = ' - ';
  3633. let emailBody = '';
  3634. if (expirationDateString !== null || isBurnafterreading) {
  3635. emailBody += I18n._('Notice:');
  3636. emailBody += EOL;
  3637. if (expirationDateString !== null) {
  3638. emailBody += EOL;
  3639. emailBody += BULLET;
  3640. // avoid DOMPurify mess with forward slash in expirationDateString
  3641. emailBody += Helper.sprintf(
  3642. I18n._(
  3643. 'This link will expire after %s.',
  3644. '%s'
  3645. ),
  3646. expirationDateString
  3647. );
  3648. }
  3649. if (isBurnafterreading) {
  3650. emailBody += EOL;
  3651. emailBody += BULLET;
  3652. emailBody += I18n._(
  3653. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3654. );
  3655. }
  3656. emailBody += EOL;
  3657. emailBody += EOL;
  3658. }
  3659. emailBody += I18n._('Link:');
  3660. emailBody += EOL;
  3661. const pasteUrlElement = document.getElementById('pasteurl');
  3662. emailBody += (pasteUrlElement && pasteUrlElement.getAttribute('href')) || window.location.href; // href is tried first as it might have been shortened
  3663. return emailBody;
  3664. }
  3665. /**
  3666. * Trigger Email send.
  3667. *
  3668. * @name TopNav.triggerEmailSend
  3669. * @private
  3670. * @param {string} emailBody
  3671. */
  3672. function triggerEmailSend(emailBody) {
  3673. window.open(
  3674. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3675. '_self',
  3676. 'noopener, noreferrer'
  3677. );
  3678. }
  3679. /**
  3680. * Send Email with current document (URL).
  3681. *
  3682. * @name TopNav.sendEmail
  3683. * @private
  3684. * @function
  3685. * @param {Date|null} expirationDate date of expiration
  3686. * @param {bool} isBurnafterreading whether it is burn after reading
  3687. */
  3688. function sendEmail(expirationDate, isBurnafterreading) {
  3689. const expirationDateRoundedToSecond = new Date(expirationDate);
  3690. // round down at least 30 seconds to make up for the delay of request
  3691. expirationDateRoundedToSecond.setUTCSeconds(
  3692. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3693. );
  3694. expirationDateRoundedToSecond.setUTCSeconds(0);
  3695. const emailconfirmmodal = document.getElementById('emailconfirmmodal');
  3696. if (expirationDate !== null) {
  3697. const emailconfirmTimezoneCurrent = emailconfirmmodal.querySelector('#emailconfirm-timezone-current');
  3698. const emailconfirmTimezoneUtc = emailconfirmmodal.querySelector('#emailconfirm-timezone-utc');
  3699. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3700. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip && bootstrap.Tooltip.VERSION ?
  3701. new bootstrap.Modal(emailconfirmmodal) : null;
  3702. function sendEmailAndHideModal() {
  3703. const emailBody = templateEmailBody(
  3704. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3705. expirationDateRoundedToSecond.toLocaleString(
  3706. [], localeConfiguration
  3707. ), isBurnafterreading
  3708. );
  3709. if (bootstrap5EmailConfirmModal) {
  3710. bootstrap5EmailConfirmModal.hide();
  3711. }
  3712. triggerEmailSend(emailBody);
  3713. }
  3714. emailconfirmTimezoneCurrent.removeEventListener('click', sendEmailAndHideModal);
  3715. emailconfirmTimezoneCurrent.addEventListener('click', sendEmailAndHideModal);
  3716. emailconfirmTimezoneUtc.removeEventListener('click', sendEmailAndHideModal);
  3717. emailconfirmTimezoneUtc.addEventListener('click', () => {
  3718. localeConfiguration.timeZone = 'UTC';
  3719. sendEmailAndHideModal();
  3720. });
  3721. if (bootstrap5EmailConfirmModal) {
  3722. bootstrap5EmailConfirmModal.show();
  3723. }
  3724. } else {
  3725. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3726. }
  3727. }
  3728. /**
  3729. * Shows all navigation elements for viewing an existing document
  3730. *
  3731. * @name TopNav.showViewButtons
  3732. * @function
  3733. */
  3734. me.showViewButtons = function () {
  3735. if (viewButtonsDisplayed) {
  3736. return;
  3737. }
  3738. newButton.classList.remove('hidden');
  3739. cloneButton.classList.remove('hidden');
  3740. rawTextButton.classList.remove('hidden');
  3741. downloadTextButton.classList.remove('hidden');
  3742. qrCodeLink.classList.remove('hidden');
  3743. viewButtonsDisplayed = true;
  3744. };
  3745. /**
  3746. * Hides all navigation elements for viewing an existing document
  3747. *
  3748. * @name TopNav.hideViewButtons
  3749. * @function
  3750. */
  3751. me.hideViewButtons = function () {
  3752. if (!viewButtonsDisplayed) {
  3753. return;
  3754. }
  3755. cloneButton.classList.add('hidden');
  3756. newButton.classList.add('hidden');
  3757. rawTextButton.classList.add('hidden');
  3758. downloadTextButton.classList.add('hidden');
  3759. qrCodeLink.classList.add('hidden');
  3760. me.hideEmailButton();
  3761. viewButtonsDisplayed = false;
  3762. };
  3763. /**
  3764. * Hides all elements belonging to existing documents
  3765. *
  3766. * @name TopNav.hideAllButtons
  3767. * @function
  3768. */
  3769. me.hideAllButtons = function () {
  3770. me.hideViewButtons();
  3771. me.hideCreateButtons();
  3772. };
  3773. /**
  3774. * shows all elements needed when creating a new document
  3775. *
  3776. * @name TopNav.showCreateButtons
  3777. * @function
  3778. */
  3779. me.showCreateButtons = function () {
  3780. if (createButtonsDisplayed) {
  3781. return;
  3782. }
  3783. if (attach) {
  3784. attach.classList.remove('hidden');
  3785. }
  3786. burnAfterReadingOption.classList.remove('hidden');
  3787. expiration.classList.remove('hidden');
  3788. formatter.classList.remove('hidden');
  3789. newButton.classList.remove('hidden');
  3790. openDiscussionOption.classList.remove('hidden');
  3791. password.classList.remove('hidden');
  3792. sendButton.classList.remove('hidden');
  3793. createButtonsDisplayed = true;
  3794. };
  3795. /**
  3796. * shows all elements needed when creating a new document
  3797. *
  3798. * @name TopNav.hideCreateButtons
  3799. * @function
  3800. */
  3801. me.hideCreateButtons = function () {
  3802. if (!createButtonsDisplayed) {
  3803. return;
  3804. }
  3805. newButton.classList.add('hidden');
  3806. sendButton.classList.add('hidden');
  3807. expiration.classList.add('hidden');
  3808. formatter.classList.add('hidden');
  3809. burnAfterReadingOption.classList.add('hidden');
  3810. openDiscussionOption.classList.add('hidden');
  3811. password.classList.add('hidden');
  3812. attach.classList.add('hidden');
  3813. createButtonsDisplayed = false;
  3814. };
  3815. /**
  3816. * only shows the "new document" button
  3817. *
  3818. * @name TopNav.showNewPasteButton
  3819. * @function
  3820. */
  3821. me.showNewPasteButton = function () {
  3822. newButton.classList.remove('hidden');
  3823. };
  3824. /**
  3825. * only shows the "retry" button
  3826. *
  3827. * @name TopNav.showRetryButton
  3828. * @function
  3829. */
  3830. me.showRetryButton = function () {
  3831. retryButton.classList.remove('hidden');
  3832. }
  3833. /**
  3834. * hides the "retry" button
  3835. *
  3836. * @name TopNav.hideRetryButton
  3837. * @function
  3838. */
  3839. me.hideRetryButton = function () {
  3840. retryButton.classList.add('hidden');
  3841. }
  3842. /**
  3843. * show the "email" button
  3844. *
  3845. * @name TopNav.showEmailbutton
  3846. * @function
  3847. * @param {int|undefined} optionalRemainingTimeInSeconds
  3848. */
  3849. me.showEmailButton = function (optionalRemainingTimeInSeconds) {
  3850. try {
  3851. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3852. const expirationDate = Helper.calculateExpirationDate(
  3853. new Date(),
  3854. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3855. );
  3856. const isBurnafterreading = TopNav.getBurnAfterReading();
  3857. emailLink.classList.remove('hidden');
  3858. emailLink.removeEventListener('click', sendEmail);
  3859. emailLink.addEventListener('click', () => {
  3860. sendEmail(expirationDate, isBurnafterreading);
  3861. });
  3862. } catch (error) {
  3863. console.error(error);
  3864. Alert.showError('Cannot calculate expiration date.');
  3865. }
  3866. }
  3867. /**
  3868. * hide the "email" button
  3869. *
  3870. * @name TopNav.hideEmailButton
  3871. * @function
  3872. */
  3873. me.hideEmailButton = function () {
  3874. emailLink.classList.add('hidden');
  3875. emailLink.removeEventListener('click', sendEmail);
  3876. }
  3877. /**
  3878. * only hides the clone button
  3879. *
  3880. * @name TopNav.hideCloneButton
  3881. * @function
  3882. */
  3883. me.hideCloneButton = function () {
  3884. cloneButton.classList.add('hidden');
  3885. };
  3886. /**
  3887. * only hides the raw text button
  3888. *
  3889. * @name TopNav.hideRawButton
  3890. * @function
  3891. */
  3892. me.hideRawButton = function () {
  3893. rawTextButton.classList.add('hidden');
  3894. };
  3895. /**
  3896. * only hides the download text button
  3897. *
  3898. * @name TopNav.hideRawButton
  3899. * @function
  3900. */
  3901. me.hideDownloadButton = function () {
  3902. downloadTextButton.classList.add('hidden');
  3903. };
  3904. /**
  3905. * only hides the qr code button
  3906. *
  3907. * @name TopNav.hideQrCodeButton
  3908. * @function
  3909. */
  3910. me.hideQrCodeButton = function () {
  3911. qrCodeLink.classList.add('hidden');
  3912. }
  3913. /**
  3914. * hide irrelevant buttons when viewing burn after reading document
  3915. *
  3916. * @name TopNav.hideBurnAfterReadingButtons
  3917. * @function
  3918. */
  3919. me.hideBurnAfterReadingButtons = function () {
  3920. me.hideCloneButton();
  3921. me.hideQrCodeButton();
  3922. me.hideEmailButton();
  3923. }
  3924. /**
  3925. * hides the file selector in attachment
  3926. *
  3927. * @name TopNav.hideFileSelector
  3928. * @function
  3929. */
  3930. me.hideFileSelector = function () {
  3931. fileWrap.classList.add('hidden');
  3932. };
  3933. /**
  3934. * shows the custom attachment
  3935. *
  3936. * @name TopNav.showCustomAttachment
  3937. * @function
  3938. */
  3939. me.showCustomAttachment = function () {
  3940. if (!customAttachment) {
  3941. return;
  3942. }
  3943. customAttachment.classList.remove('hidden');
  3944. };
  3945. /**
  3946. * hides the custom attachment
  3947. *
  3948. * @name TopNav.hideCustomAttachment
  3949. * @function
  3950. */
  3951. me.hideCustomAttachment = function () {
  3952. if (customAttachment) {
  3953. customAttachment.classList.add('hidden');
  3954. }
  3955. if (fileWrap) {
  3956. fileWrap.classList.remove('hidden');
  3957. }
  3958. };
  3959. /**
  3960. * collapses the navigation bar, only if expanded
  3961. *
  3962. * @name TopNav.collapseBar
  3963. * @function
  3964. */
  3965. me.collapseBar = function () {
  3966. const navbar = document.getElementById('navbar');
  3967. if (navbar && navbar.getAttribute('aria-expanded') === 'true') {
  3968. const toggle = document.querySelector('.navbar-toggle');
  3969. if (toggle) {
  3970. toggle.click();
  3971. }
  3972. }
  3973. };
  3974. /**
  3975. * Reset the top navigation back to it's default values.
  3976. *
  3977. * @name TopNav.resetInput
  3978. * @function
  3979. */
  3980. me.resetInput = function () {
  3981. clearAttachmentInput();
  3982. clearPasswordInput();
  3983. if (burnAfterReading) {
  3984. burnAfterReading.checked = burnAfterReadingDefault;
  3985. }
  3986. if (openDiscussion) {
  3987. openDiscussion.checked = openDiscussionDefault;
  3988. }
  3989. if (openDiscussionDefault || !burnAfterReadingDefault) {
  3990. openDiscussionOption.classList.remove('buttondisabled');
  3991. }
  3992. if (burnAfterReadingDefault || !openDiscussionDefault) {
  3993. burnAfterReadingOption.classList.remove('buttondisabled');
  3994. }
  3995. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  3996. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  3997. if (pasteExpirationSelect) {
  3998. pasteExpirationSelect.querySelectorAll('option').forEach((option) => {
  3999. if (option.value === pasteExpiration) {
  4000. const display = document.getElementById('pasteExpirationDisplay');
  4001. if (display) {
  4002. display.textContent = option.textContent;
  4003. }
  4004. }
  4005. });
  4006. }
  4007. };
  4008. /**
  4009. * returns the currently set expiration time
  4010. *
  4011. * @name TopNav.getExpiration
  4012. * @function
  4013. * @return {int}
  4014. */
  4015. me.getExpiration = function () {
  4016. return pasteExpiration;
  4017. };
  4018. /**
  4019. * returns the currently selected file(s)
  4020. *
  4021. * @name TopNav.getFileList
  4022. * @function
  4023. * @return {FileList|null}
  4024. */
  4025. me.getFileList = function () {
  4026. const file = document.getElementById('file');
  4027. // if no file given, return null
  4028. if (!file || !file.files || !file.files.length) {
  4029. return null;
  4030. }
  4031. // ensure the selected file is still accessible
  4032. if (!file.files[0]) {
  4033. return null;
  4034. }
  4035. return file.files;
  4036. };
  4037. /**
  4038. * returns the state of the burn after reading checkbox
  4039. *
  4040. * @name TopNav.getBurnAfterReading
  4041. * @function
  4042. * @return {bool}
  4043. */
  4044. me.getBurnAfterReading = function () {
  4045. return burnAfterReading.checked;
  4046. };
  4047. /**
  4048. * returns the state of the discussion checkbox
  4049. *
  4050. * @name TopNav.getOpenDiscussion
  4051. * @function
  4052. * @return {bool}
  4053. */
  4054. me.getOpenDiscussion = function () {
  4055. return openDiscussion.checked;
  4056. };
  4057. /**
  4058. * returns the entered password
  4059. *
  4060. * @name TopNav.getPassword
  4061. * @function
  4062. * @return {string}
  4063. */
  4064. me.getPassword = function () {
  4065. // when password is disabled passwordInput.value will return undefined
  4066. return passwordInput && passwordInput.value || '';
  4067. };
  4068. /**
  4069. * returns the element where custom attachments can be placed
  4070. *
  4071. * Used by AttachmentViewer when an attachment is cloned here.
  4072. *
  4073. * @name TopNav.getCustomAttachment
  4074. * @function
  4075. * @return {HTMLElement}
  4076. */
  4077. me.getCustomAttachment = function () {
  4078. return customAttachment;
  4079. };
  4080. /**
  4081. * Set a function to call when the retry button is clicked.
  4082. *
  4083. * @name TopNav.setRetryCallback
  4084. * @function
  4085. * @param {function} callback
  4086. */
  4087. me.setRetryCallback = function (callback) {
  4088. retryButtonCallback = callback;
  4089. }
  4090. /**
  4091. * Highlight file upload
  4092. *
  4093. * @name TopNav.highlightFileupload
  4094. * @function
  4095. */
  4096. me.highlightFileupload = function () {
  4097. // visually indicate file uploaded
  4098. const attachDropdownToggle = attach && attach.querySelector('.dropdown-toggle');
  4099. if (attachDropdownToggle && attachDropdownToggle.getAttribute('aria-expanded') === 'false') {
  4100. if (Helper.isBootstrap5()) {
  4101. new bootstrap.Dropdown(attachDropdownToggle).toggle();
  4102. } else {
  4103. attachDropdownToggle.click();
  4104. }
  4105. }
  4106. fileWrap.classList.add('highlight');
  4107. setTimeout(function () {
  4108. fileWrap.classList.remove('highlight');
  4109. }, 300);
  4110. }
  4111. /**
  4112. * set the format on bootstrap templates in dropdown programmatically
  4113. *
  4114. * @name TopNav.setFormat
  4115. * @function
  4116. */
  4117. me.setFormat = function (format) {
  4118. if (Helper.isBootstrap5()) {
  4119. const select = formatter.querySelector('select');
  4120. if (select) {
  4121. select.value = format;
  4122. }
  4123. } else {
  4124. const formatLink = formatter.parentElement.querySelector(`a[data-format="${format}"]`);
  4125. if (formatLink) {
  4126. formatLink.click();
  4127. }
  4128. }
  4129. }
  4130. /**
  4131. * returns if attachment dropdown is readonly, not editable
  4132. *
  4133. * @name TopNav.isAttachmentReadonly
  4134. * @function
  4135. * @return {bool}
  4136. */
  4137. me.isAttachmentReadonly = function () {
  4138. return !createButtonsDisplayed || (attach && attach.classList.contains('hidden'));
  4139. }
  4140. /**
  4141. * init navigation manager
  4142. *
  4143. * preloads DOM elements
  4144. *
  4145. * @name TopNav.init
  4146. * @function
  4147. */
  4148. me.init = function () {
  4149. attach = document.getElementById('attach');
  4150. burnAfterReading = document.getElementById('burnafterreading');
  4151. burnAfterReadingOption = document.getElementById('burnafterreadingoption');
  4152. cloneButton = document.getElementById('clonebutton');
  4153. customAttachment = document.getElementById('customattachment');
  4154. expiration = document.getElementById('expiration');
  4155. fileRemoveButton = document.getElementById('fileremovebutton');
  4156. fileWrap = document.getElementById('filewrap');
  4157. formatter = document.getElementById('formatter');
  4158. newButton = document.getElementById('newbutton');
  4159. openDiscussion = document.getElementById('opendiscussion');
  4160. openDiscussionOption = document.getElementById('opendiscussionoption');
  4161. password = document.getElementById('password');
  4162. passwordInput = document.getElementById('passwordinput');
  4163. rawTextButton = document.getElementById('rawtextbutton');
  4164. downloadTextButton = document.getElementById('downloadtextbutton');
  4165. retryButton = document.getElementById('retrybutton');
  4166. sendButton = document.getElementById('sendbutton');
  4167. qrCodeLink = document.getElementById('qrcodelink');
  4168. emailLink = document.getElementById('emaillink');
  4169. // bootstrap template drop down
  4170. const languageDropdown = document.getElementById('language');
  4171. if (languageDropdown) {
  4172. languageDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4173. link.addEventListener('click', setLanguage);
  4174. });
  4175. }
  4176. // bootstrap template drop down
  4177. const templateDropdown = document.getElementById('template');
  4178. if (templateDropdown) {
  4179. templateDropdown.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4180. link.addEventListener('click', setTemplate);
  4181. });
  4182. }
  4183. // bind events
  4184. if (burnAfterReading) {
  4185. burnAfterReading.addEventListener('change', changeBurnAfterReading);
  4186. }
  4187. if (openDiscussionOption) {
  4188. openDiscussionOption.addEventListener('change', changeOpenDiscussion);
  4189. }
  4190. if (newButton) {
  4191. newButton.addEventListener('click', clickNewPaste);
  4192. }
  4193. if (sendButton) {
  4194. sendButton.addEventListener('click', PasteEncrypter.sendPaste);
  4195. }
  4196. if (cloneButton) {
  4197. cloneButton.addEventListener('click', Controller.clonePaste);
  4198. }
  4199. if (rawTextButton) {
  4200. rawTextButton.addEventListener('click', rawText);
  4201. }
  4202. if (downloadTextButton) {
  4203. downloadTextButton.addEventListener('click', downloadText);
  4204. }
  4205. if (retryButton) {
  4206. retryButton.addEventListener('click', clickRetryButton);
  4207. }
  4208. if (fileRemoveButton) {
  4209. fileRemoveButton.addEventListener('click', removeAttachment);
  4210. }
  4211. if (qrCodeLink) {
  4212. qrCodeLink.addEventListener('click', displayQrCode);
  4213. }
  4214. // bootstrap template drop downs
  4215. if (expiration) {
  4216. expiration.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4217. link.addEventListener('click', updateExpiration);
  4218. });
  4219. }
  4220. if (formatter) {
  4221. formatter.parentElement.querySelectorAll('ul.dropdown-menu li a').forEach(link => {
  4222. link.addEventListener('click', updateFormat);
  4223. });
  4224. }
  4225. // bootstrap5 & page drop downs
  4226. const pasteExpirationSelect = document.getElementById('pasteExpiration');
  4227. if (pasteExpirationSelect) {
  4228. pasteExpirationSelect.addEventListener('change', function () {
  4229. pasteExpiration = Model.getExpirationDefault();
  4230. });
  4231. }
  4232. const pasteFormatterSelect = document.getElementById('pasteFormatter');
  4233. if (pasteFormatterSelect) {
  4234. pasteFormatterSelect.addEventListener('change', function () {
  4235. PasteViewer.setFormat(Model.getFormatDefault());
  4236. });
  4237. }
  4238. // initiate default state of checkboxes
  4239. changeBurnAfterReading();
  4240. changeOpenDiscussion();
  4241. // get default values from template or fall back to set value
  4242. burnAfterReadingDefault = me.getBurnAfterReading();
  4243. openDiscussionDefault = me.getOpenDiscussion();
  4244. pasteExpiration = Model.getExpirationDefault();
  4245. createButtonsDisplayed = false;
  4246. viewButtonsDisplayed = false;
  4247. };
  4248. return me;
  4249. })(window, document);
  4250. /**
  4251. * Responsible for AJAX requests, transparently handles encryption…
  4252. *
  4253. * @name ServerInteraction
  4254. * @class
  4255. */
  4256. const ServerInteraction = (function () {
  4257. const me = {};
  4258. let successFunc = null,
  4259. failureFunc = null,
  4260. symmetricKey = null,
  4261. url,
  4262. data,
  4263. password;
  4264. /**
  4265. * public variable ('constant') for errors to prevent magic numbers
  4266. *
  4267. * @name ServerInteraction.error
  4268. * @readonly
  4269. * @enum {Object}
  4270. */
  4271. me.error = {
  4272. okay: 0,
  4273. custom: 1,
  4274. unknown: 2,
  4275. serverError: 3
  4276. };
  4277. /**
  4278. * ajaxHeaders to send in AJAX requests
  4279. *
  4280. * @name ServerInteraction.ajaxHeaders
  4281. * @private
  4282. * @readonly
  4283. * @enum {Object}
  4284. */
  4285. const ajaxHeaders = {
  4286. 'X-Requested-With': 'JSONHttpRequest',
  4287. 'Content-Type': 'application/json'
  4288. };
  4289. /**
  4290. * called after successful upload
  4291. *
  4292. * @name ServerInteraction.success
  4293. * @private
  4294. * @function
  4295. * @param {int} status
  4296. * @param {int} result - optional
  4297. */
  4298. function success(status, result) {
  4299. if (successFunc !== null) {
  4300. // add useful data to result
  4301. result.encryptionKey = symmetricKey;
  4302. successFunc(status, result);
  4303. }
  4304. }
  4305. /**
  4306. * called after a upload failure
  4307. *
  4308. * @name ServerInteraction.fail
  4309. * @private
  4310. * @function
  4311. * @param {int} status - internal code
  4312. * @param {int} result - original error code
  4313. */
  4314. function fail(status, result) {
  4315. if (failureFunc !== null) {
  4316. failureFunc(status, result);
  4317. }
  4318. }
  4319. /**
  4320. * actually uploads the data
  4321. *
  4322. * @name ServerInteraction.run
  4323. * @function
  4324. */
  4325. me.run = function () {
  4326. let isPost = Object.keys(data).length > 0,
  4327. ajaxParams = {
  4328. type: isPost ? 'POST' : 'GET',
  4329. url: url,
  4330. headers: ajaxHeaders,
  4331. dataType: 'json',
  4332. success: function (result) {
  4333. if (result.status === 0) {
  4334. success(0, result);
  4335. } else if (result.status === 1) {
  4336. fail(1, result);
  4337. } else {
  4338. fail(2, result);
  4339. }
  4340. }
  4341. };
  4342. if (isPost) {
  4343. ajaxParams.data = JSON.stringify(data);
  4344. }
  4345. $.ajax(ajaxParams).fail(function (jqXHR, textStatus, errorThrown) {
  4346. console.error(textStatus, errorThrown);
  4347. fail(3, jqXHR);
  4348. });
  4349. };
  4350. /**
  4351. * return currently set data, used in unit testing
  4352. *
  4353. * @name ServerInteraction.getData
  4354. * @function
  4355. */
  4356. me.getData = function () {
  4357. return data;
  4358. };
  4359. /**
  4360. * set success function
  4361. *
  4362. * @name ServerInteraction.setUrl
  4363. * @function
  4364. * @param {function} newUrl
  4365. */
  4366. me.setUrl = function (newUrl) {
  4367. url = newUrl;
  4368. };
  4369. /**
  4370. * sets the password to use (first value) and optionally also the
  4371. * encryption key (not recommended, it is automatically generated).
  4372. *
  4373. * Note: Call this after prepare() as prepare() resets these values.
  4374. *
  4375. * @name ServerInteraction.setCryptValues
  4376. * @function
  4377. * @param {string} newPassword
  4378. * @param {string} newKey - optional
  4379. */
  4380. me.setCryptParameters = function (newPassword, newKey) {
  4381. password = newPassword;
  4382. if (typeof newKey !== 'undefined') {
  4383. symmetricKey = newKey;
  4384. }
  4385. };
  4386. /**
  4387. * set success function
  4388. *
  4389. * @name ServerInteraction.setSuccess
  4390. * @function
  4391. * @param {function} func
  4392. */
  4393. me.setSuccess = function (func) {
  4394. successFunc = func;
  4395. };
  4396. /**
  4397. * set failure function
  4398. *
  4399. * @name ServerInteraction.setFailure
  4400. * @function
  4401. * @param {function} func
  4402. */
  4403. me.setFailure = function (func) {
  4404. failureFunc = func;
  4405. };
  4406. /**
  4407. * prepares a new upload
  4408. *
  4409. * Call this when doing a new upload to reset any data from potential
  4410. * previous uploads. Must be called before any other method of this
  4411. * module.
  4412. *
  4413. * @name ServerInteraction.prepare
  4414. * @function
  4415. * @return {object}
  4416. */
  4417. me.prepare = function () {
  4418. // entropy should already be checked!
  4419. // reset password
  4420. password = '';
  4421. // reset key, so it a new one is generated when it is used
  4422. symmetricKey = null;
  4423. // reset data
  4424. successFunc = null;
  4425. failureFunc = null;
  4426. url = Helper.baseUri();
  4427. data = {};
  4428. };
  4429. /**
  4430. * encrypts and sets the data
  4431. *
  4432. * @name ServerInteraction.setCipherMessage
  4433. * @async
  4434. * @function
  4435. * @param {object} cipherMessage
  4436. */
  4437. me.setCipherMessage = async function (cipherMessage) {
  4438. if (
  4439. symmetricKey === null ||
  4440. (typeof symmetricKey === 'string' && symmetricKey === '')
  4441. ) {
  4442. symmetricKey = CryptTool.getSymmetricKey();
  4443. }
  4444. if (!data.hasOwnProperty('adata')) {
  4445. data['adata'] = [];
  4446. }
  4447. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4448. data['v'] = 2;
  4449. data['ct'] = cipherResult[0];
  4450. data['adata'] = cipherResult[1];
  4451. };
  4452. /**
  4453. * set the additional metadata to send unencrypted
  4454. *
  4455. * @name ServerInteraction.setUnencryptedData
  4456. * @function
  4457. * @param {string} index
  4458. * @param {mixed} element
  4459. */
  4460. me.setUnencryptedData = function (index, element) {
  4461. data[index] = element;
  4462. };
  4463. /**
  4464. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4465. *
  4466. * @name ServerInteraction.parseUploadError
  4467. * @function
  4468. * @param {int} status
  4469. * @param {object} data
  4470. * @param {string} doThisThing - a human description of the action, which was tried
  4471. * @return {array}
  4472. */
  4473. me.parseUploadError = function (status, data, doThisThing) {
  4474. let errorArray;
  4475. switch (status) {
  4476. case me.error.custom:
  4477. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4478. break;
  4479. case me.error.unknown:
  4480. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4481. break;
  4482. case me.error.serverError:
  4483. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4484. break;
  4485. default:
  4486. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4487. break;
  4488. }
  4489. return errorArray;
  4490. };
  4491. return me;
  4492. })();
  4493. /**
  4494. * (controller) Responsible for encrypting document and sending it to server.
  4495. *
  4496. * Does upload, encryption is done transparently by ServerInteraction.
  4497. *
  4498. * @name PasteEncrypter
  4499. * @class
  4500. */
  4501. const PasteEncrypter = (function () {
  4502. const me = {};
  4503. /**
  4504. * called after successful document upload
  4505. *
  4506. * @name PasteEncrypter.showCreatedPaste
  4507. * @private
  4508. * @function
  4509. * @param {int} status
  4510. * @param {object} data
  4511. */
  4512. function showCreatedPaste(status, data) {
  4513. Alert.hideLoading();
  4514. Alert.hideMessages();
  4515. // show notification
  4516. const baseUri = Helper.baseUri() + '?',
  4517. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4518. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4519. PasteStatus.createPasteNotification(url, deleteUrl);
  4520. // show new URL in browser bar
  4521. history.pushState({ type: 'newpaste' }, document.title, url);
  4522. TopNav.showViewButtons();
  4523. CopyToClipboard.setUrl(url);
  4524. CopyToClipboard.showKeyboardShortcutHint();
  4525. // this cannot be grouped with showViewButtons due to remaining time calculation
  4526. TopNav.showEmailButton();
  4527. TopNav.hideRawButton();
  4528. TopNav.hideDownloadButton();
  4529. Editor.hide();
  4530. PasteStatus.checkAutoShorten();
  4531. // parse and show text
  4532. // (preparation already done in me.sendPaste())
  4533. PasteViewer.run();
  4534. }
  4535. /**
  4536. * called after successful comment upload
  4537. *
  4538. * @name PasteEncrypter.showUploadedComment
  4539. * @private
  4540. * @function
  4541. * @param {int} status
  4542. * @param {object} data
  4543. */
  4544. function showUploadedComment(status, data) {
  4545. // show success message
  4546. Alert.showStatus('Comment posted.');
  4547. // reload document
  4548. Controller.refreshPaste(function () {
  4549. // highlight sent comment
  4550. DiscussionViewer.highlightComment(data.id, true);
  4551. // reset error handler
  4552. Alert.setCustomHandler(null);
  4553. });
  4554. }
  4555. /**
  4556. * send a reply in a discussion
  4557. *
  4558. * @name PasteEncrypter.sendComment
  4559. * @async
  4560. * @function
  4561. */
  4562. me.sendComment = async function () {
  4563. Alert.hideMessages();
  4564. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4565. // UI loading state
  4566. TopNav.hideAllButtons();
  4567. Alert.showLoading('Sending comment…', 'cloud-upload');
  4568. // get data
  4569. const plainText = DiscussionViewer.getReplyMessage(),
  4570. nickname = DiscussionViewer.getReplyNickname(),
  4571. parentid = DiscussionViewer.getReplyCommentId();
  4572. // do not send if there is no data
  4573. if (plainText.length === 0) {
  4574. // revert loading status…
  4575. Alert.hideLoading();
  4576. Alert.setCustomHandler(null);
  4577. TopNav.showViewButtons();
  4578. return;
  4579. }
  4580. // prepare server interaction
  4581. ServerInteraction.prepare();
  4582. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4583. // set success/fail functions
  4584. ServerInteraction.setSuccess(showUploadedComment);
  4585. ServerInteraction.setFailure(function (status, data) {
  4586. // revert loading status…
  4587. Alert.hideLoading();
  4588. TopNav.showViewButtons();
  4589. // …show error message…
  4590. Alert.showError(
  4591. ServerInteraction.parseUploadError(status, data, 'post comment')
  4592. );
  4593. // …and reset error handler
  4594. Alert.setCustomHandler(null);
  4595. });
  4596. // fill it with unencrypted params
  4597. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4598. if (typeof parentid === 'undefined') {
  4599. // if parent id is not set, this is the top-most comment, so use
  4600. // document id as parent, as the root element of the discussion tree
  4601. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4602. } else {
  4603. ServerInteraction.setUnencryptedData('parentid', parentid);
  4604. }
  4605. // prepare cypher message
  4606. let cipherMessage = {
  4607. 'comment': plainText
  4608. };
  4609. if (nickname.length > 0) {
  4610. cipherMessage['nickname'] = nickname;
  4611. }
  4612. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4613. ServerInteraction.run();
  4614. };
  4615. /**
  4616. * sends a new document to server
  4617. *
  4618. * @name PasteEncrypter.sendPaste
  4619. * @async
  4620. * @function
  4621. */
  4622. me.sendPaste = async function () {
  4623. // hide previous (error) messages
  4624. Controller.hideStatusMessages();
  4625. // UI loading state
  4626. TopNav.hideAllButtons();
  4627. Alert.showLoading('Sending document…', 'cloud-upload');
  4628. TopNav.collapseBar();
  4629. // get data
  4630. const plainText = Editor.getText(),
  4631. format = PasteViewer.getFormat(),
  4632. // the methods may return different values if no files are attached (null, undefined or false)
  4633. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachment();
  4634. // do not send if there is no data
  4635. if (plainText.length === 0 && !files) {
  4636. // revert loading status…
  4637. Alert.hideLoading();
  4638. TopNav.showCreateButtons();
  4639. return;
  4640. }
  4641. // prepare server interaction
  4642. ServerInteraction.prepare();
  4643. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4644. // set success/fail functions
  4645. ServerInteraction.setSuccess(showCreatedPaste);
  4646. ServerInteraction.setFailure(function (status, data) {
  4647. // revert loading status…
  4648. Alert.hideLoading();
  4649. TopNav.showCreateButtons();
  4650. // show error message
  4651. Alert.showError(
  4652. ServerInteraction.parseUploadError(status, data, 'create document')
  4653. );
  4654. });
  4655. // fill it with unencrypted submitted options
  4656. ServerInteraction.setUnencryptedData('adata', [
  4657. null, format,
  4658. TopNav.getOpenDiscussion() ? 1 : 0,
  4659. TopNav.getBurnAfterReading() ? 1 : 0
  4660. ]);
  4661. ServerInteraction.setUnencryptedData('meta', { 'expire': TopNav.getExpiration() });
  4662. // prepare PasteViewer for later preview
  4663. PasteViewer.setText(plainText);
  4664. PasteViewer.setFormat(format);
  4665. // prepare cypher message
  4666. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4667. cipherMessage = {
  4668. 'paste': plainText
  4669. };
  4670. if (attachmentsData.length) {
  4671. cipherMessage['attachment'] = attachmentsData;
  4672. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map((fileInfo => fileInfo.name));
  4673. } else if (AttachmentViewer.hasAttachment()) {
  4674. // fall back to cloned part
  4675. let attachments = AttachmentViewer.getAttachments();
  4676. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4677. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4678. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment, i) => {
  4679. // we need to retrieve data from blob if browser already parsed it in memory
  4680. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4681. Alert.showStatus(
  4682. [
  4683. 'Retrieving cloned file \'%s\' from memory...',
  4684. cipherMessage['attachment_name'][i]
  4685. ],
  4686. 'copy'
  4687. );
  4688. try {
  4689. const blobData = await $.ajax({
  4690. type: 'GET',
  4691. url: attachment,
  4692. processData: false,
  4693. timeout: 10000,
  4694. dataType: 'binary',
  4695. xhrFields: {
  4696. withCredentials: false,
  4697. responseType: 'blob'
  4698. }
  4699. });
  4700. if (blobData instanceof window.Blob) {
  4701. const fileReading = new Promise(function (resolve, reject) {
  4702. const fileReader = new FileReader();
  4703. fileReader.onload = function (event) {
  4704. resolve(event.target.result);
  4705. };
  4706. fileReader.onerror = function (error) {
  4707. reject(error);
  4708. }
  4709. fileReader.readAsDataURL(blobData);
  4710. });
  4711. return await fileReading;
  4712. } else {
  4713. const error = 'Cannot process attachment data.';
  4714. Alert.showError(error);
  4715. throw new TypeError(error);
  4716. }
  4717. } catch (error) {
  4718. Alert.showError('Cannot retrieve attachment.');
  4719. throw error;
  4720. }
  4721. }
  4722. }));
  4723. }
  4724. // encrypt message
  4725. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4726. // send data
  4727. ServerInteraction.run();
  4728. };
  4729. return me;
  4730. })();
  4731. /**
  4732. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4733. *
  4734. * Only decryption, no download.
  4735. *
  4736. * @name PasteDecrypter
  4737. * @class
  4738. */
  4739. const PasteDecrypter = (function () {
  4740. const me = {};
  4741. /**
  4742. * decrypt data or prompts for password in case of failure
  4743. *
  4744. * @name PasteDecrypter.decryptOrPromptPassword
  4745. * @private
  4746. * @async
  4747. * @function
  4748. * @param {string} key
  4749. * @param {string} password - optional, may be an empty string
  4750. * @param {string} cipherdata
  4751. * @throws {string}
  4752. * @return {false|string} false, when unsuccessful or string (decrypted data)
  4753. */
  4754. async function decryptOrPromptPassword(key, password, cipherdata) {
  4755. // try decryption without password
  4756. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4757. // if it fails, request password
  4758. if (plaindata.length === 0 && password.length === 0) {
  4759. // show prompt
  4760. Prompt.requestPassword();
  4761. // Thus, we cannot do anything yet, we need to wait for the user
  4762. // input.
  4763. return false;
  4764. }
  4765. // if all tries failed, we can only return an error
  4766. if (plaindata.length === 0) {
  4767. return false;
  4768. }
  4769. return plaindata;
  4770. }
  4771. /**
  4772. * decrypt the actual document text
  4773. *
  4774. * @name PasteDecrypter.decryptPaste
  4775. * @private
  4776. * @async
  4777. * @function
  4778. * @param {Paste} paste - document data in object form
  4779. * @param {string} key
  4780. * @param {string} password
  4781. * @throws {string}
  4782. * @return {Promise}
  4783. */
  4784. async function decryptPaste(paste, key, password) {
  4785. const pastePlain = await decryptOrPromptPassword(
  4786. key, password,
  4787. paste.getCipherData()
  4788. );
  4789. if (pastePlain === false) {
  4790. if (password.length === 0) {
  4791. throw 'waiting on user to provide a password';
  4792. } else {
  4793. Alert.hideLoading();
  4794. // reset password, so it can be re-entered
  4795. Prompt.reset();
  4796. TopNav.showRetryButton();
  4797. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4798. }
  4799. }
  4800. const pasteMessage = JSON.parse(pastePlain);
  4801. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4802. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  4803. pasteMessage.attachment.forEach((attachment, key) => {
  4804. const attachment_name = pasteMessage.attachment_name[key];
  4805. AttachmentViewer.setAttachment(attachment, attachment_name);
  4806. });
  4807. } else {
  4808. // Continue to process attachment parameters as strings to ensure backward compatibility
  4809. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4810. }
  4811. AttachmentViewer.showAttachment();
  4812. }
  4813. PasteViewer.setFormat(paste.getFormat());
  4814. PasteViewer.setText(pasteMessage.paste);
  4815. PasteViewer.run();
  4816. }
  4817. /**
  4818. * decrypts all comments and shows them
  4819. *
  4820. * @name PasteDecrypter.decryptComments
  4821. * @private
  4822. * @async
  4823. * @function
  4824. * @param {Paste} paste - document data in object form
  4825. * @param {string} key
  4826. * @param {string} password
  4827. * @return {Promise}
  4828. */
  4829. async function decryptComments(paste, key, password) {
  4830. // remove potential previous discussion
  4831. DiscussionViewer.prepareNewDiscussion();
  4832. const commentDecryptionPromises = [];
  4833. // iterate over comments
  4834. for (let i = 0; i < paste.comments.length; ++i) {
  4835. const comment = new Comment(paste.comments[i]),
  4836. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4837. paste.comments[i] = comment;
  4838. commentDecryptionPromises.push(
  4839. commentPromise.then(function (commentJson) {
  4840. const commentMessage = JSON.parse(commentJson);
  4841. return [
  4842. commentMessage.comment || '',
  4843. commentMessage.nickname || ''
  4844. ];
  4845. })
  4846. );
  4847. }
  4848. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4849. for (let i = 0; i < paste.comments.length; ++i) {
  4850. if (plaintexts[i][0].length === 0) {
  4851. continue;
  4852. }
  4853. DiscussionViewer.addComment(
  4854. paste.comments[i],
  4855. plaintexts[i][0],
  4856. plaintexts[i][1]
  4857. );
  4858. }
  4859. document.addEventListener(I18n.languageLoadedEvent, function () {
  4860. const comentContainer = document.getElementById('commentcontainer');
  4861. if (!comentContainer) {
  4862. return;
  4863. }
  4864. comentContainer.querySelectorAll('img.vizhash')
  4865. .forEach(img => img.setAttribute('title', I18n._('Avatar generated from IP address')));
  4866. });
  4867. });
  4868. }
  4869. /**
  4870. * show decrypted text in the display area, including discussion (if open)
  4871. *
  4872. * @name PasteDecrypter.run
  4873. * @function
  4874. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4875. */
  4876. me.run = function (paste) {
  4877. Alert.hideMessages();
  4878. Alert.setCustomHandler(null);
  4879. Alert.showLoading('Decrypting document…', 'cloud-download');
  4880. if (typeof paste === 'undefined' || paste.type === 'click') {
  4881. // get cipher data and wait until it is available
  4882. Model.getPasteData(me.run);
  4883. return;
  4884. }
  4885. let key = Model.getPasteKey(),
  4886. password = Prompt.getPassword(),
  4887. decryptionPromises = [];
  4888. TopNav.setRetryCallback(function () {
  4889. TopNav.hideRetryButton();
  4890. me.run(paste);
  4891. });
  4892. // Clear attachments to prevent duplicates
  4893. AttachmentViewer.removeAttachment();
  4894. // decrypt paste & attachments
  4895. decryptionPromises.push(decryptPaste(paste, key, password));
  4896. // if the discussion is opened on this document, display it
  4897. if (paste.isDiscussionEnabled()) {
  4898. decryptionPromises.push(decryptComments(paste, key, password));
  4899. }
  4900. // shows the remaining time (until) deletion
  4901. PasteStatus.showRemainingTime(paste);
  4902. CopyToClipboard.showKeyboardShortcutHint();
  4903. Promise.all(decryptionPromises)
  4904. .then(() => {
  4905. Alert.hideLoading();
  4906. TopNav.showViewButtons();
  4907. // discourage cloning (it cannot really be prevented)
  4908. if (paste.isBurnAfterReadingEnabled()) {
  4909. TopNav.hideBurnAfterReadingButtons();
  4910. } else {
  4911. // we have to pass in remaining_time here
  4912. TopNav.showEmailButton(paste.getTimeToLive());
  4913. }
  4914. // only offer adding comments, after document was successfully decrypted
  4915. if (paste.isDiscussionEnabled()) {
  4916. DiscussionViewer.finishDiscussion();
  4917. }
  4918. })
  4919. .catch((err) => {
  4920. // wait for the user to type in the password,
  4921. // then PasteDecrypter.run will be called again
  4922. Alert.showError(err);
  4923. });
  4924. };
  4925. return me;
  4926. })();
  4927. /**
  4928. *
  4929. * @name CopyToClipboard
  4930. * @class
  4931. */
  4932. const CopyToClipboard = (function () {
  4933. const me = {};
  4934. let copyButton,
  4935. copyLinkButton,
  4936. copyIcon,
  4937. successIcon,
  4938. shortcutHint,
  4939. url;
  4940. /**
  4941. * Handle copy to clipboard button click
  4942. *
  4943. * @name CopyToClipboard.handleCopyButtonClick
  4944. * @private
  4945. * @function
  4946. */
  4947. function handleCopyButtonClick() {
  4948. $(copyButton).click(function () {
  4949. const text = PasteViewer.getText();
  4950. saveToClipboard(text);
  4951. toggleSuccessIcon();
  4952. showAlertMessage('Document copied to clipboard');
  4953. });
  4954. }
  4955. /**
  4956. * Handle copy link to clipboard button click
  4957. *
  4958. * @name CopyToClipboard.handleCopyLinkButtonClick
  4959. * @private
  4960. * @function
  4961. */
  4962. function handleCopyLinkButtonClick() {
  4963. $(copyLinkButton).click(function () {
  4964. saveToClipboard(url);
  4965. showAlertMessage('Link copied to clipboard');
  4966. });
  4967. }
  4968. /**
  4969. * Handle CTRL+C/CMD+C keyboard shortcut
  4970. *
  4971. * @name CopyToClipboard.handleKeyboardShortcut
  4972. * @private
  4973. * @function
  4974. */
  4975. function handleKeyboardShortcut() {
  4976. $(document).bind('copy', function () {
  4977. if (!isUserSelectedTextToCopy()) {
  4978. const text = PasteViewer.getText();
  4979. saveToClipboard(text);
  4980. showAlertMessage('Document copied to clipboard');
  4981. }
  4982. });
  4983. }
  4984. /**
  4985. * Check if user selected some text on the page to copy it
  4986. *
  4987. * @name CopyToClipboard.isUserSelectedTextToCopy
  4988. * @private
  4989. * @function
  4990. * @returns {boolean}
  4991. */
  4992. function isUserSelectedTextToCopy() {
  4993. let text = '';
  4994. if (window.getSelection) {
  4995. text = window.getSelection().toString();
  4996. } else if (document.selection && document.selection.type !== 'Control') {
  4997. text = document.selection.createRange().text;
  4998. }
  4999. return text.length > 0;
  5000. }
  5001. /**
  5002. * Save text to the clipboard
  5003. *
  5004. * @name CopyToClipboard.saveToClipboard
  5005. * @private
  5006. * @param {string} text
  5007. * @function
  5008. */
  5009. function saveToClipboard(text) {
  5010. navigator.clipboard.writeText(text);
  5011. }
  5012. /**
  5013. * Show alert message after text copy
  5014. *
  5015. * @name CopyToClipboard.showAlertMessage
  5016. * @private
  5017. * @param {string} message
  5018. * @function
  5019. */
  5020. function showAlertMessage(message) {
  5021. Alert.showStatus(message);
  5022. }
  5023. /**
  5024. * Toogle success icon after copy
  5025. *
  5026. * @name CopyToClipboard.toggleSuccessIcon
  5027. * @private
  5028. * @function
  5029. */
  5030. function toggleSuccessIcon() {
  5031. $(copyIcon).css('display', 'none');
  5032. $(successIcon).css('display', 'block');
  5033. setTimeout(function () {
  5034. $(copyIcon).css('display', 'block');
  5035. $(successIcon).css('display', 'none');
  5036. }, 1000);
  5037. }
  5038. /**
  5039. * Show keyboard shortcut hint
  5040. *
  5041. * @name CopyToClipboard.showKeyboardShortcutHint
  5042. * @function
  5043. */
  5044. me.showKeyboardShortcutHint = function () {
  5045. I18n._(
  5046. shortcutHint,
  5047. 'To copy document press on the copy button or use the clipboard shortcut <kbd>Ctrl</kbd>+<kbd>c</kbd>/<kbd>Cmd</kbd>+<kbd>c</kbd>'
  5048. );
  5049. };
  5050. /**
  5051. * Hide keyboard shortcut hint
  5052. *
  5053. * @name CopyToClipboard.showKeyboardShortcutHint
  5054. * @function
  5055. */
  5056. me.hideKeyboardShortcutHint = function () {
  5057. $(shortcutHint).html('');
  5058. };
  5059. /**
  5060. * Set document url
  5061. *
  5062. * @name CopyToClipboard.setUrl
  5063. * @param {string} newUrl
  5064. * @function
  5065. */
  5066. me.setUrl = function (newUrl) {
  5067. url = newUrl;
  5068. };
  5069. /**
  5070. * Initialize
  5071. *
  5072. * @name CopyToClipboard.init
  5073. * @function
  5074. */
  5075. me.init = function () {
  5076. copyButton = $('#prettyMessageCopyBtn');
  5077. copyLinkButton = $('#copyLink');
  5078. copyIcon = $('#copyIcon');
  5079. successIcon = $('#copySuccessIcon');
  5080. shortcutHint = $('#copyShortcutHintText');
  5081. handleCopyButtonClick();
  5082. handleCopyLinkButtonClick();
  5083. handleKeyboardShortcut();
  5084. };
  5085. return me;
  5086. })();
  5087. /**
  5088. *
  5089. * @name PasswordPeek
  5090. * @class
  5091. */
  5092. const PasswordPeek = (function () {
  5093. const me = {};
  5094. /**
  5095. * Switch between visible and hidden password
  5096. *
  5097. * @name PasswordPeek.handleRevealButtonClick
  5098. * @private
  5099. * @function
  5100. */
  5101. function handleRevealButtonClick() {
  5102. const element = $(this);
  5103. const passwordInput = element.siblings('.input-password');
  5104. const isHidden = passwordInput.attr('type') === 'password';
  5105. passwordInput.attr('type', isHidden ? 'text' : 'password');
  5106. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5107. element.attr('title', tooltip);
  5108. element.attr('aria-label', tooltip);
  5109. // handle bootstrap 5 icons: eye & eye-slash
  5110. const buttonSvg = element.find('use');
  5111. if (buttonSvg.length) {
  5112. const iconHref = buttonSvg.attr('href');
  5113. if (isHidden) {
  5114. buttonSvg.attr('href', iconHref + '-slash');
  5115. } else {
  5116. buttonSvg.attr('href', iconHref.substring(0, iconHref.length - 6));
  5117. }
  5118. return;
  5119. }
  5120. // handle bootstrap 3 icons: eye-open & eye-close
  5121. const buttonSpan = element.find('span');
  5122. if (buttonSpan.length) {
  5123. if (isHidden) {
  5124. buttonSpan.addClass('glyphicon-eye-close');
  5125. buttonSpan.removeClass('glyphicon-eye-open');
  5126. } else {
  5127. buttonSpan.addClass('glyphicon-eye-open');
  5128. buttonSpan.removeClass('glyphicon-eye-close');
  5129. }
  5130. }
  5131. }
  5132. /**
  5133. * Initialize
  5134. *
  5135. * @name PasswordPeek.init
  5136. * @function
  5137. */
  5138. me.init = function () {
  5139. const revealButton = $('.toggle-password');
  5140. revealButton.click(handleRevealButtonClick);
  5141. };
  5142. return me;
  5143. })();
  5144. /**
  5145. * (controller) main PrivateBin logic
  5146. *
  5147. * @name Controller
  5148. * @param {object} window
  5149. * @param {object} document
  5150. * @class
  5151. */
  5152. const Controller = (function (window, document) {
  5153. const me = {};
  5154. /**
  5155. * hides all status messages no matter which module showed them
  5156. *
  5157. * @name Controller.hideStatusMessages
  5158. * @function
  5159. */
  5160. me.hideStatusMessages = function () {
  5161. PasteStatus.hideMessages();
  5162. Alert.hideMessages();
  5163. CopyToClipboard.hideKeyboardShortcutHint();
  5164. };
  5165. /**
  5166. * creates a new document
  5167. *
  5168. * @name Controller.newPaste
  5169. * @function
  5170. */
  5171. me.newPaste = function () {
  5172. // Important: This *must not* run Alert.hideMessages() as previous
  5173. // errors from viewing a document should be shown.
  5174. TopNav.hideAllButtons();
  5175. Alert.showLoading('Preparing new document…', 'time');
  5176. PasteStatus.hideMessages();
  5177. PasteViewer.hide();
  5178. Editor.resetInput();
  5179. Editor.show();
  5180. Editor.focusInput();
  5181. AttachmentViewer.removeAttachment();
  5182. TopNav.resetInput();
  5183. // reset format
  5184. PasteViewer.setFormat('plaintext');
  5185. TopNav.setFormat('plaintext');
  5186. TopNav.showCreateButtons();
  5187. // newPaste could be called when user is on document clone editing view
  5188. TopNav.hideCustomAttachment();
  5189. AttachmentViewer.clearDragAndDrop();
  5190. AttachmentViewer.removeAttachmentData();
  5191. Alert.hideLoading();
  5192. // only push new state if we are coming from a different one
  5193. if (Helper.baseUri() !== window.location) {
  5194. history.pushState({ type: 'create' }, document.title, Helper.baseUri());
  5195. }
  5196. // clear discussion
  5197. DiscussionViewer.prepareNewDiscussion();
  5198. };
  5199. /**
  5200. * shows the loaded document
  5201. *
  5202. * @name Controller.showPaste
  5203. * @function
  5204. */
  5205. me.showPaste = function () {
  5206. try {
  5207. Model.getPasteKey();
  5208. } catch (err) {
  5209. console.error(err);
  5210. Alert.showError('Cannot decrypt document: Decryption key missing in URL (Did you use a redirector or an URL shortener which strips part of the URL?)');
  5211. return;
  5212. }
  5213. // check if we should request loading confirmation
  5214. if (window.location.hash.startsWith(loadConfirmPrefix)) {
  5215. Prompt.requestLoadConfirmation();
  5216. return;
  5217. }
  5218. // show proper elements on screen
  5219. PasteDecrypter.run();
  5220. };
  5221. /**
  5222. * refreshes the loaded document to show potential new data
  5223. *
  5224. * @name Controller.refreshPaste
  5225. * @function
  5226. * @param {function} callback
  5227. */
  5228. me.refreshPaste = function (callback) {
  5229. // save window position to restore it later
  5230. const orgPosition = window.scrollY;
  5231. Model.getPasteData(function (data) {
  5232. ServerInteraction.prepare();
  5233. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5234. ServerInteraction.setFailure(function (status, data) {
  5235. // revert loading status…
  5236. Alert.hideLoading();
  5237. TopNav.showViewButtons();
  5238. // show error message
  5239. Alert.showError(
  5240. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5241. );
  5242. });
  5243. ServerInteraction.setSuccess(function (status, data) {
  5244. PasteDecrypter.run(new Paste(data));
  5245. // restore position
  5246. window.scrollTo(0, orgPosition);
  5247. // NOTE: could create problems as callback may be called
  5248. // asyncronously if PasteDecrypter e.g. needs to wait for a
  5249. // password being entered
  5250. callback();
  5251. });
  5252. ServerInteraction.run();
  5253. }, false); // this false is important as it circumvents the cache
  5254. }
  5255. /**
  5256. * clone the current document
  5257. *
  5258. * @name Controller.clonePaste
  5259. * @function
  5260. */
  5261. me.clonePaste = function () {
  5262. TopNav.collapseBar();
  5263. TopNav.hideAllButtons();
  5264. // hide messages from previous document
  5265. me.hideStatusMessages();
  5266. // erase the id and the key in url
  5267. history.pushState({ type: 'clone' }, document.title, Helper.baseUri());
  5268. if (AttachmentViewer.hasAttachment()) {
  5269. const attachments = AttachmentViewer.getAttachments();
  5270. attachments.forEach(attachment => {
  5271. AttachmentViewer.moveAttachmentTo(
  5272. TopNav.getCustomAttachment(),
  5273. attachment,
  5274. 'Cloned: \'%s\''
  5275. );
  5276. });
  5277. TopNav.hideFileSelector();
  5278. AttachmentViewer.hideAttachment();
  5279. // NOTE: it also looks nice without removing the attachment
  5280. // but for a consistent display we remove it…
  5281. AttachmentViewer.hideAttachmentPreview();
  5282. TopNav.showCustomAttachment();
  5283. // show another status messages to make the user aware that the
  5284. // files were cloned too!
  5285. Alert.showStatus(
  5286. [
  5287. 'The cloned file \'%s\' was attached to this document.',
  5288. attachments.map(attachment => attachment[1]).join(', ')
  5289. ],
  5290. 'copy'
  5291. );
  5292. }
  5293. Editor.setText(PasteViewer.getText());
  5294. // also clone the format
  5295. TopNav.setFormat(PasteViewer.getFormat());
  5296. PasteViewer.hide();
  5297. Editor.show();
  5298. TopNav.showCreateButtons();
  5299. // clear discussion
  5300. DiscussionViewer.prepareNewDiscussion();
  5301. };
  5302. /**
  5303. * try initializing zlib or display a warning if it fails,
  5304. * extracted from main init to allow unit testing
  5305. *
  5306. * @name Controller.initZ
  5307. * @function
  5308. */
  5309. me.initZ = function () {
  5310. z = zlib.catch(function () {
  5311. if (document.body.dataset.compression !== 'none') {
  5312. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5313. }
  5314. });
  5315. }
  5316. /**
  5317. * application start
  5318. *
  5319. * @name Controller.init
  5320. * @function
  5321. */
  5322. me.init = function () {
  5323. // first load translations
  5324. I18n.loadTranslations();
  5325. // Add a hook to make all links open a new window
  5326. DOMPurify.addHook('afterSanitizeAttributes', function (node) {
  5327. // set all elements owning target to target=_blank
  5328. if ('target' in node && node.id !== 'pasteurl') {
  5329. node.setAttribute('target', '_blank');
  5330. }
  5331. // set non-HTML/MathML links to xlink:show=new
  5332. if (!node.hasAttribute('target')
  5333. && (node.hasAttribute('xlink:href')
  5334. || node.hasAttribute('href'))) {
  5335. node.setAttribute('xlink:show', 'new');
  5336. }
  5337. if ('rel' in node) {
  5338. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5339. }
  5340. });
  5341. // center all modals
  5342. document.querySelectorAll('.modal').forEach(modal => {
  5343. modal.addEventListener('show.bs.modal', function (e) {
  5344. e.target.style.display = 'flex';
  5345. });
  5346. });
  5347. // initialize other modules/"classes"
  5348. Alert.init();
  5349. Model.init();
  5350. AttachmentViewer.init();
  5351. DiscussionViewer.init();
  5352. Editor.init();
  5353. PasteStatus.init();
  5354. PasteViewer.init();
  5355. Prompt.init();
  5356. TopNav.init();
  5357. UiHelper.init();
  5358. CopyToClipboard.init();
  5359. PasswordPeek.init();
  5360. // check for legacy browsers before going any further
  5361. if (!Legacy.Check.getInit()) {
  5362. // Legacy check didn't complete, wait and try again
  5363. setTimeout(init, 500);
  5364. return;
  5365. }
  5366. if (!Legacy.Check.getStatus()) {
  5367. // something major is wrong, stop right away
  5368. return;
  5369. }
  5370. me.initZ();
  5371. // if delete token is passed (i.e. document has been deleted by this
  5372. // access), add an event listener for the 'new' document button in the alert
  5373. if (Model.hasDeleteToken()) {
  5374. const newFromAlert = document.getElementById('new-from-alert');
  5375. if (newFromAlert) {
  5376. newFromAlert.addEventListener('click', function () {
  5377. UiHelper.reloadHome();
  5378. });
  5379. }
  5380. return;
  5381. }
  5382. // check whether existing document needs to be shown
  5383. try {
  5384. Model.getPasteId();
  5385. } catch (e) {
  5386. // otherwise create a new document
  5387. return me.newPaste();
  5388. }
  5389. // always reload on back button to invalidate cache (protect burn after read document)
  5390. window.addEventListener('popstate', () => {
  5391. window.location.reload();
  5392. });
  5393. // display an existing document
  5394. return me.showPaste();
  5395. }
  5396. return me;
  5397. })(window, document);
  5398. return {
  5399. Helper: Helper,
  5400. I18n: I18n,
  5401. CryptTool: CryptTool,
  5402. Model: Model,
  5403. UiHelper: UiHelper,
  5404. Alert: Alert,
  5405. PasteStatus: PasteStatus,
  5406. Prompt: Prompt,
  5407. Editor: Editor,
  5408. PasteViewer: PasteViewer,
  5409. AttachmentViewer: AttachmentViewer,
  5410. DiscussionViewer: DiscussionViewer,
  5411. TopNav: TopNav,
  5412. ServerInteraction: ServerInteraction,
  5413. PasteEncrypter: PasteEncrypter,
  5414. PasteDecrypter: PasteDecrypter,
  5415. PasswordPeek: PasswordPeek,
  5416. CopyToClipboard: CopyToClipboard,
  5417. Controller: Controller
  5418. };
  5419. })();
  5420. // main application start, called when DOM is fully loaded
  5421. window.addEventListener('DOMContentLoaded', function () {
  5422. 'use strict';
  5423. // run main controller
  5424. window.PrivateBin.Controller.init();
  5425. });