privatebin.js 140 KB

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