privatebin.js 142 KB

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