1
0

privatebin.js 203 KB

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