privatebin.js 159 KB

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