privatebin.js 119 KB

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