privatebin.js 149 KB

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