privatebin.js 205 KB

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