privatebin.js 200 KB

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