privatebin.js 204 KB

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