privatebin.js 140 KB

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