privatebin.js 149 KB

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