privatebin.js 170 KB

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