privatebin.js 172 KB

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