1
0

privatebin.js 170 KB

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