privatebin.js 177 KB

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