1
0

privatebin.js 205 KB

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