privatebin.js 154 KB

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