privatebin.js 209 KB

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