privatebin.js 201 KB

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