privatebin.js 142 KB

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