privatebin.js 148 KB

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