privatebin.js 177 KB

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