privatebin.js 202 KB

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