1
0

privatebin.js 174 KB

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