privatebin.js 117 KB

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