privatebin.js 158 KB

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