privatebin.js 175 KB

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