privatebin.js 158 KB

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