privatebin.js 120 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017
  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 returs 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. // set sanitized and linked text
  1525. var sanitizedLinkedText = DOMPurify.sanitize(Helper.urls2links(text));
  1526. $plainText.html(sanitizedLinkedText);
  1527. $prettyPrint.html(sanitizedLinkedText);
  1528. switch (format) {
  1529. case 'markdown':
  1530. var converter = new showdown.Converter({
  1531. strikethrough: true,
  1532. tables: true,
  1533. tablesHeaderId: true
  1534. });
  1535. // let showdown convert the HTML and sanitize HTML *afterwards*!
  1536. $plainText.html(
  1537. DOMPurify.sanitize(converter.makeHtml(text))
  1538. );
  1539. // add table classes from bootstrap css
  1540. $plainText.find('table').addClass('table-condensed table-bordered');
  1541. break;
  1542. case 'syntaxhighlighting':
  1543. // yes, this is really needed to initialize the environment
  1544. if (typeof prettyPrint === 'function')
  1545. {
  1546. prettyPrint();
  1547. }
  1548. $prettyPrint.html(
  1549. DOMPurify.sanitize(
  1550. prettyPrintOne(Helper.urls2links(text), null, true)
  1551. )
  1552. );
  1553. // fall through, as the rest is the same
  1554. default: // = 'plaintext'
  1555. $prettyPrint.css('white-space', 'pre-wrap');
  1556. $prettyPrint.css('word-break', 'normal');
  1557. $prettyPrint.removeClass('prettyprint');
  1558. }
  1559. }
  1560. /**
  1561. * displays the paste
  1562. *
  1563. * @name PasteViewer.showPaste
  1564. * @private
  1565. * @function
  1566. */
  1567. function showPaste()
  1568. {
  1569. // instead of "nothing" better display a placeholder
  1570. if (text === '') {
  1571. $placeholder.removeClass('hidden')
  1572. return;
  1573. }
  1574. // otherwise hide the placeholder
  1575. $placeholder.addClass('hidden')
  1576. switch (format) {
  1577. case 'markdown':
  1578. $plainText.removeClass('hidden');
  1579. $prettyMessage.addClass('hidden');
  1580. break;
  1581. default:
  1582. $plainText.addClass('hidden');
  1583. $prettyMessage.removeClass('hidden');
  1584. break;
  1585. }
  1586. }
  1587. /**
  1588. * sets the format in which the text is shown
  1589. *
  1590. * @name PasteViewer.setFormat
  1591. * @function
  1592. * @param {string} newFormat the new format
  1593. */
  1594. me.setFormat = function(newFormat)
  1595. {
  1596. // skip if there is no update
  1597. if (format === newFormat) {
  1598. return;
  1599. }
  1600. // needs to update display too, if we switch from or to Markdown
  1601. if (format === 'markdown' || newFormat === 'markdown') {
  1602. isDisplayed = false;
  1603. }
  1604. format = newFormat;
  1605. isChanged = true;
  1606. }
  1607. /**
  1608. * returns the current format
  1609. *
  1610. * @name PasteViewer.getFormat
  1611. * @function
  1612. * @return {string}
  1613. */
  1614. me.getFormat = function()
  1615. {
  1616. return format;
  1617. }
  1618. /**
  1619. * returns whether the current view is pretty printed
  1620. *
  1621. * @name PasteViewer.isPrettyPrinted
  1622. * @function
  1623. * @return {bool}
  1624. */
  1625. me.isPrettyPrinted = function()
  1626. {
  1627. return $prettyPrint.hasClass('prettyprinted');
  1628. }
  1629. /**
  1630. * sets the text to show
  1631. *
  1632. * @name PasteViewer.setText
  1633. * @function
  1634. * @param {string} newText the text to show
  1635. */
  1636. me.setText = function(newText)
  1637. {
  1638. // escape HTML entities
  1639. newText = $('<div />').text(newText).html();
  1640. if (text !== newText) {
  1641. text = newText;
  1642. isChanged = true;
  1643. }
  1644. }
  1645. /**
  1646. * gets the current cached text
  1647. *
  1648. * @name PasteViewer.getText
  1649. * @function
  1650. * @return {string}
  1651. */
  1652. me.getText = function()
  1653. {
  1654. return text;
  1655. }
  1656. /**
  1657. * show/update the parsed text (preview)
  1658. *
  1659. * @name PasteViewer.run
  1660. * @function
  1661. */
  1662. me.run = function()
  1663. {
  1664. if (isChanged) {
  1665. parsePaste();
  1666. isChanged = false;
  1667. }
  1668. if (!isDisplayed) {
  1669. showPaste();
  1670. isDisplayed = true;
  1671. }
  1672. }
  1673. /**
  1674. * hide parsed text (preview)
  1675. *
  1676. * @name PasteViewer.hide
  1677. * @function
  1678. */
  1679. me.hide = function()
  1680. {
  1681. if (!isDisplayed) {
  1682. console.warn('PasteViewer was called to hide the parsed view, but it is already hidden.');
  1683. }
  1684. $plainText.addClass('hidden');
  1685. $prettyMessage.addClass('hidden');
  1686. $placeholder.addClass('hidden');
  1687. isDisplayed = false;
  1688. }
  1689. /**
  1690. * init status manager
  1691. *
  1692. * preloads jQuery elements
  1693. *
  1694. * @name PasteViewer.init
  1695. * @function
  1696. */
  1697. me.init = function()
  1698. {
  1699. $placeholder = $('#placeholder');
  1700. $plainText = $('#plaintext');
  1701. $prettyMessage = $('#prettymessage');
  1702. $prettyPrint = $('#prettyprint');
  1703. // check requirements
  1704. if (typeof prettyPrintOne !== 'function') {
  1705. Alert.showError([
  1706. 'The library %s is not available. This may cause display errors.',
  1707. 'pretty print'
  1708. ]);
  1709. }
  1710. if (typeof showdown !== 'object') {
  1711. Alert.showError([
  1712. 'The library %s is not available. This may cause display errors.',
  1713. 'showdown'
  1714. ]);
  1715. }
  1716. // get default option from template/HTML or fall back to set value
  1717. format = Model.getFormatDefault() || format;
  1718. text = '';
  1719. isDisplayed = false;
  1720. isChanged = true;
  1721. }
  1722. return me;
  1723. })();
  1724. /**
  1725. * (view) Show attachment and preview if possible
  1726. *
  1727. * @name AttachmentViewer
  1728. * @class
  1729. */
  1730. var AttachmentViewer = (function () {
  1731. var me = {};
  1732. var $attachmentLink,
  1733. $attachmentPreview,
  1734. $attachment;
  1735. var attachmentHasPreview = false;
  1736. /**
  1737. * sets the attachment but does not yet show it
  1738. *
  1739. * @name AttachmentViewer.setAttachment
  1740. * @function
  1741. * @param {string} attachmentData - base64-encoded data of file
  1742. * @param {string} fileName - optional, file name
  1743. */
  1744. me.setAttachment = function(attachmentData, fileName)
  1745. {
  1746. var imagePrefix = 'data:image/';
  1747. $attachmentLink.attr('href', attachmentData);
  1748. if (typeof fileName !== 'undefined') {
  1749. $attachmentLink.attr('download', fileName);
  1750. }
  1751. // if the attachment is an image, display it
  1752. if (attachmentData.substring(0, imagePrefix.length) === imagePrefix) {
  1753. $attachmentPreview.html(
  1754. $(document.createElement('img'))
  1755. .attr('src', attachmentData)
  1756. .attr('class', 'img-thumbnail')
  1757. );
  1758. attachmentHasPreview = true;
  1759. }
  1760. }
  1761. /**
  1762. * displays the attachment
  1763. *
  1764. * @name AttachmentViewer.showAttachment
  1765. * @function
  1766. */
  1767. me.showAttachment = function()
  1768. {
  1769. $attachment.removeClass('hidden');
  1770. if (attachmentHasPreview) {
  1771. $attachmentPreview.removeClass('hidden');
  1772. }
  1773. }
  1774. /**
  1775. * removes the attachment
  1776. *
  1777. * This automatically hides the attachment containers to, to
  1778. * prevent an inconsistent display.
  1779. *
  1780. * @name AttachmentViewer.removeAttachment
  1781. * @function
  1782. */
  1783. me.removeAttachment = function()
  1784. {
  1785. me.hideAttachment();
  1786. me.hideAttachmentPreview();
  1787. $attachmentLink.prop('href', '');
  1788. $attachmentLink.prop('download', '');
  1789. $attachmentPreview.html('');
  1790. }
  1791. /**
  1792. * hides the attachment
  1793. *
  1794. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  1795. * for that) nor will it hide the attachment link if it was moved somewhere
  1796. * else (see AttachmentViewer.moveAttachmentTo).
  1797. *
  1798. * @name AttachmentViewer.hideAttachment
  1799. * @function
  1800. */
  1801. me.hideAttachment = function()
  1802. {
  1803. $attachment.addClass('hidden');
  1804. }
  1805. /**
  1806. * hides the attachment preview
  1807. *
  1808. * @name AttachmentViewer.hideAttachmentPreview
  1809. * @function
  1810. */
  1811. me.hideAttachmentPreview = function()
  1812. {
  1813. $attachmentPreview.addClass('hidden');
  1814. }
  1815. /**
  1816. * checks if there is an attachment
  1817. *
  1818. * @name AttachmentViewer.hasAttachment
  1819. * @function
  1820. */
  1821. me.hasAttachment = function()
  1822. {
  1823. var link = $attachmentLink.prop('href');
  1824. return (typeof link !== 'undefined' && link !== '')
  1825. }
  1826. /**
  1827. * return the attachment
  1828. *
  1829. * @name AttachmentViewer.getAttachment
  1830. * @function
  1831. * @returns {array}
  1832. */
  1833. me.getAttachment = function()
  1834. {
  1835. return [
  1836. $attachmentLink.prop('href'),
  1837. $attachmentLink.prop('download')
  1838. ];
  1839. }
  1840. /**
  1841. * moves the attachment link to another element
  1842. *
  1843. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  1844. *
  1845. * @name AttachmentViewer.moveAttachmentTo
  1846. * @function
  1847. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  1848. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  1849. */
  1850. me.moveAttachmentTo = function($element, label)
  1851. {
  1852. // move elemement to new place
  1853. $attachmentLink.appendTo($element);
  1854. // update text
  1855. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  1856. }
  1857. /**
  1858. * initiate
  1859. *
  1860. * preloads jQuery elements
  1861. *
  1862. * @name AttachmentViewer.init
  1863. * @function
  1864. */
  1865. me.init = function()
  1866. {
  1867. $attachment = $('#attachment');
  1868. $attachmentLink = $('#attachment a');
  1869. $attachmentPreview = $('#attachmentPreview');
  1870. attachmentHasPreview = false;
  1871. }
  1872. return me;
  1873. })();
  1874. /**
  1875. * (view) Shows discussion thread and handles replies
  1876. *
  1877. * @name DiscussionViewer
  1878. * @class
  1879. */
  1880. var DiscussionViewer = (function () {
  1881. var me = {};
  1882. var $commentTail,
  1883. $discussion,
  1884. $reply,
  1885. $replyMessage,
  1886. $replyNickname,
  1887. $replyStatus,
  1888. $commentContainer;
  1889. var replyCommentId;
  1890. /**
  1891. * initializes the templates
  1892. *
  1893. * @name DiscussionViewer.initTemplates
  1894. * @private
  1895. * @function
  1896. */
  1897. function initTemplates()
  1898. {
  1899. $reply = Model.getTemplate('reply');
  1900. $replyMessage = $reply.find('#replymessage');
  1901. $replyNickname = $reply.find('#nickname');
  1902. $replyStatus = $reply.find('#replystatus');
  1903. // cache jQuery elements
  1904. $commentTail = Model.getTemplate('commenttail');
  1905. }
  1906. /**
  1907. * open the comment entry when clicking the "Reply" button of a comment
  1908. *
  1909. * @name DiscussionViewer.openReply
  1910. * @private
  1911. * @function
  1912. * @param {Event} event
  1913. */
  1914. function openReply(event)
  1915. {
  1916. var $source = $(event.target);
  1917. // clear input
  1918. $replyMessage.val('');
  1919. $replyNickname.val('');
  1920. // get comment id from source element
  1921. replyCommentId = $source.parent().prop('id').split('_')[1];
  1922. // move to correct position
  1923. $source.after($reply);
  1924. // show
  1925. $reply.removeClass('hidden');
  1926. $replyMessage.focus();
  1927. event.preventDefault();
  1928. }
  1929. /**
  1930. * custom handler for displaying notifications in own status message area
  1931. *
  1932. * @name DiscussionViewer.handleNotification
  1933. * @function
  1934. * @param {string} alertType
  1935. * @param {jQuery} $element
  1936. * @param {string|array} args
  1937. * @param {string|null} icon
  1938. * @return {bool|jQuery}
  1939. */
  1940. me.handleNotification = function(alertType, $element, args, icon)
  1941. {
  1942. // ignore loading messages
  1943. if (alertType === 'loading') {
  1944. return false;
  1945. }
  1946. if (alertType === 'danger') {
  1947. $replyStatus.removeClass('alert-info');
  1948. $replyStatus.addClass('alert-danger');
  1949. $replyStatus.find(':first').removeClass('glyphicon-alert');
  1950. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  1951. } else {
  1952. $replyStatus.removeClass('alert-danger');
  1953. $replyStatus.addClass('alert-info');
  1954. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  1955. $replyStatus.find(':first').addClass('glyphicon-alert');
  1956. }
  1957. return $replyStatus;
  1958. }
  1959. /**
  1960. * adds another comment
  1961. *
  1962. * @name DiscussionViewer.addComment
  1963. * @function
  1964. * @param {object} comment
  1965. * @param {string} commentText
  1966. * @param {jQuery} $place - optional, tries to find the best position otherwise
  1967. */
  1968. me.addComment = function(comment, commentText, nickname, $place)
  1969. {
  1970. if (typeof $place === 'undefined') {
  1971. // starting point (default value/fallback)
  1972. $place = $commentContainer;
  1973. // if parent comment exists
  1974. var $parentComment = $('#comment_' + comment.parentid);
  1975. if ($parentComment.length) {
  1976. // use parent as position for noew comment, so it shifted
  1977. // to the right
  1978. $place = $parentComment;
  1979. }
  1980. }
  1981. if (commentText === '') {
  1982. commentText = 'comment decryption failed';
  1983. }
  1984. // create new comment based on template
  1985. var $commentEntry = Model.getTemplate('comment');
  1986. $commentEntry.prop('id', 'comment_' + comment.id);
  1987. var $commentEntryData = $commentEntry.find('div.commentdata');
  1988. // set & parse text
  1989. $commentEntryData.html(
  1990. DOMPurify.sanitize(
  1991. Helper.urls2links(commentText)
  1992. )
  1993. );
  1994. // set nickname
  1995. if (nickname.length > 0) {
  1996. $commentEntry.find('span.nickname').text(nickname);
  1997. } else {
  1998. $commentEntry.find('span.nickname').html('<i></i>');
  1999. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2000. }
  2001. // set date
  2002. $commentEntry.find('span.commentdate')
  2003. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2004. .attr('title', 'CommentID: ' + comment.id);
  2005. // if an avatar is available, display it
  2006. if (comment.meta.vizhash) {
  2007. $commentEntry.find('span.nickname')
  2008. .before(
  2009. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2010. );
  2011. $(document).on('languageLoaded', function () {
  2012. $commentEntry.find('img.vizhash')
  2013. .prop('title', I18n._('Avatar generated from IP address'));
  2014. });
  2015. }
  2016. // finally append comment
  2017. $place.append($commentEntry);
  2018. }
  2019. /**
  2020. * finishes the discussion area after last comment
  2021. *
  2022. * @name DiscussionViewer.finishDiscussion
  2023. * @function
  2024. */
  2025. me.finishDiscussion = function()
  2026. {
  2027. // add 'add new comment' area
  2028. $commentContainer.append($commentTail);
  2029. // show discussions
  2030. $discussion.removeClass('hidden');
  2031. }
  2032. /**
  2033. * shows the discussion area
  2034. *
  2035. * @name DiscussionViewer.showDiscussion
  2036. * @function
  2037. */
  2038. me.showDiscussion = function()
  2039. {
  2040. $discussion.removeClass('hidden');
  2041. }
  2042. /**
  2043. * removes the old discussion and prepares everything for creating a new
  2044. * one.
  2045. *
  2046. * @name DiscussionViewer.prepareNewDiscussion
  2047. * @function
  2048. */
  2049. me.prepareNewDiscussion = function()
  2050. {
  2051. $commentContainer.html('');
  2052. $discussion.addClass('hidden');
  2053. // (re-)init templates
  2054. initTemplates();
  2055. }
  2056. /**
  2057. * returns the users message from the reply form
  2058. *
  2059. * @name DiscussionViewer.getReplyMessage
  2060. * @function
  2061. * @return {String}
  2062. */
  2063. me.getReplyMessage = function()
  2064. {
  2065. return $replyMessage.val();
  2066. }
  2067. /**
  2068. * returns the users nickname (if any) from the reply form
  2069. *
  2070. * @name DiscussionViewer.getReplyNickname
  2071. * @function
  2072. * @return {String}
  2073. */
  2074. me.getReplyNickname = function()
  2075. {
  2076. return $replyNickname.val();
  2077. }
  2078. /**
  2079. * returns the id of the parent comment the user is replying to
  2080. *
  2081. * @name DiscussionViewer.getReplyCommentId
  2082. * @function
  2083. * @return {int|undefined}
  2084. */
  2085. me.getReplyCommentId = function()
  2086. {
  2087. return replyCommentId;
  2088. }
  2089. /**
  2090. * highlights a specific comment and scrolls to it if necessary
  2091. *
  2092. * @name DiscussionViewer.highlightComment
  2093. * @function
  2094. * @param {string} commentId
  2095. * @param {bool} fadeOut - whether to fade out the comment
  2096. */
  2097. me.highlightComment = function(commentId, fadeOut)
  2098. {
  2099. var $comment = $('#comment_' + commentId);
  2100. // in case comment does not exist, cancel
  2101. if ($comment.length === 0) {
  2102. return;
  2103. }
  2104. var highlightComment = function () {
  2105. $comment.addClass('highlight');
  2106. if (fadeOut === true) {
  2107. setTimeout(function () {
  2108. $comment.removeClass('highlight');
  2109. }, 300);
  2110. }
  2111. }
  2112. if (UiHelper.isVisible($comment)) {
  2113. return highlightComment();
  2114. }
  2115. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2116. }
  2117. /**
  2118. * initiate
  2119. *
  2120. * preloads jQuery elements
  2121. *
  2122. * @name DiscussionViewer.init
  2123. * @function
  2124. */
  2125. me.init = function()
  2126. {
  2127. // bind events to templates (so they are later cloned)
  2128. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2129. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2130. $commentContainer = $('#commentcontainer');
  2131. $discussion = $('#discussion');
  2132. }
  2133. return me;
  2134. })();
  2135. /**
  2136. * Manage top (navigation) bar
  2137. *
  2138. * @name TopNav
  2139. * @param {object} window
  2140. * @param {object} document
  2141. * @class
  2142. */
  2143. var TopNav = (function (window, document) {
  2144. var me = {};
  2145. var createButtonsDisplayed = false;
  2146. var viewButtonsDisplayed = false;
  2147. var $attach,
  2148. $burnAfterReading,
  2149. $burnAfterReadingOption,
  2150. $cloneButton,
  2151. $customAttachment,
  2152. $expiration,
  2153. $fileRemoveButton,
  2154. $fileWrap,
  2155. $formatter,
  2156. $newButton,
  2157. $openDiscussion,
  2158. $openDiscussionOption,
  2159. $password,
  2160. $passwordInput,
  2161. $rawTextButton,
  2162. $qrCodeLink,
  2163. $sendButton;
  2164. var pasteExpiration = '1week';
  2165. /**
  2166. * set the expiration on bootstrap templates in dropdown
  2167. *
  2168. * @name TopNav.updateExpiration
  2169. * @private
  2170. * @function
  2171. * @param {Event} event
  2172. */
  2173. function updateExpiration(event)
  2174. {
  2175. // get selected option
  2176. var target = $(event.target);
  2177. // update dropdown display and save new expiration time
  2178. $('#pasteExpirationDisplay').text(target.text());
  2179. pasteExpiration = target.data('expiration');
  2180. event.preventDefault();
  2181. }
  2182. /**
  2183. * set the format on bootstrap templates in dropdown
  2184. *
  2185. * @name TopNav.updateFormat
  2186. * @private
  2187. * @function
  2188. * @param {Event} event
  2189. */
  2190. function updateFormat(event)
  2191. {
  2192. // get selected option
  2193. var $target = $(event.target);
  2194. // update dropdown display and save new format
  2195. var newFormat = $target.data('format');
  2196. $('#pasteFormatterDisplay').text($target.text());
  2197. PasteViewer.setFormat(newFormat);
  2198. // update preview
  2199. if (Editor.isPreview()) {
  2200. PasteViewer.run();
  2201. }
  2202. event.preventDefault();
  2203. }
  2204. /**
  2205. * when "burn after reading" is checked, disable discussion
  2206. *
  2207. * @name TopNav.changeBurnAfterReading
  2208. * @private
  2209. * @function
  2210. */
  2211. function changeBurnAfterReading()
  2212. {
  2213. if ($burnAfterReading.is(':checked')) {
  2214. $openDiscussionOption.addClass('buttondisabled');
  2215. $openDiscussion.prop('checked', false);
  2216. // if button is actually disabled, force-enable it and uncheck other button
  2217. $burnAfterReadingOption.removeClass('buttondisabled');
  2218. } else {
  2219. $openDiscussionOption.removeClass('buttondisabled');
  2220. }
  2221. }
  2222. /**
  2223. * when discussion is checked, disable "burn after reading"
  2224. *
  2225. * @name TopNav.changeOpenDiscussion
  2226. * @private
  2227. * @function
  2228. */
  2229. function changeOpenDiscussion()
  2230. {
  2231. if ($openDiscussion.is(':checked')) {
  2232. $burnAfterReadingOption.addClass('buttondisabled');
  2233. $burnAfterReading.prop('checked', false);
  2234. // if button is actually disabled, force-enable it and uncheck other button
  2235. $openDiscussionOption.removeClass('buttondisabled');
  2236. } else {
  2237. $burnAfterReadingOption.removeClass('buttondisabled');
  2238. }
  2239. }
  2240. /**
  2241. * return raw text
  2242. *
  2243. * @name TopNav.rawText
  2244. * @private
  2245. * @function
  2246. * @param {Event} event
  2247. */
  2248. function rawText(event)
  2249. {
  2250. TopNav.hideAllButtons();
  2251. Alert.showLoading('Showing raw text…', 0, 'time');
  2252. var paste = PasteViewer.getText();
  2253. // push a new state to allow back navigation with browser back button
  2254. history.pushState(
  2255. {type: 'raw'},
  2256. document.title,
  2257. // recreate paste URL
  2258. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2259. Model.getPasteKey()
  2260. );
  2261. // we use text/html instead of text/plain to avoid a bug when
  2262. // reloading the raw text view (it reverts to type text/html)
  2263. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2264. var newDoc = document.open('text/html', 'replace');
  2265. newDoc.write('<!DOCTYPE html><html><head>');
  2266. for (var i = 0; i < $head.length; i++) {
  2267. newDoc.write($head[i].outerHTML);
  2268. }
  2269. newDoc.write('</head><body><pre>' + DOMPurify.sanitize(paste) + '</pre></body></html>');
  2270. newDoc.close();
  2271. }
  2272. /**
  2273. * saves the language in a cookie and reloads the page
  2274. *
  2275. * @name TopNav.setLanguage
  2276. * @private
  2277. * @function
  2278. * @param {Event} event
  2279. */
  2280. function setLanguage(event)
  2281. {
  2282. document.cookie = 'lang=' + $(event.target).data('lang');
  2283. UiHelper.reloadHome();
  2284. }
  2285. /**
  2286. * hides all messages and creates a new paste
  2287. *
  2288. * @name TopNav.clickNewPaste
  2289. * @private
  2290. * @function
  2291. * @param {Event} event
  2292. */
  2293. function clickNewPaste(event)
  2294. {
  2295. Controller.hideStatusMessages();
  2296. Controller.newPaste();
  2297. }
  2298. /**
  2299. * removes the existing attachment
  2300. *
  2301. * @name TopNav.removeAttachment
  2302. * @private
  2303. * @function
  2304. * @param {Event} event
  2305. */
  2306. function removeAttachment(event)
  2307. {
  2308. // if custom attachment is used, remove it first
  2309. if (!$customAttachment.hasClass('hidden')) {
  2310. AttachmentViewer.removeAttachment();
  2311. $customAttachment.addClass('hidden');
  2312. $fileWrap.removeClass('hidden');
  2313. }
  2314. // our up-to-date jQuery can handle it :)
  2315. $fileWrap.find('input').val('');
  2316. // pevent '#' from appearing in the URL
  2317. event.preventDefault();
  2318. }
  2319. /**
  2320. * Shows the QR code of the current paste (URL).
  2321. *
  2322. * @name TopNav.displayQrCode
  2323. * @function
  2324. * @param {Event} event
  2325. */
  2326. function displayQrCode(event)
  2327. {
  2328. var qrCanvas = kjua({
  2329. render: 'canvas',
  2330. text: window.location.href
  2331. });
  2332. $('#qrcode-display').html(qrCanvas);
  2333. }
  2334. /**
  2335. * Shows all elements belonging to viwing an existing pastes
  2336. *
  2337. * @name TopNav.showViewButtons
  2338. * @function
  2339. */
  2340. me.showViewButtons = function()
  2341. {
  2342. if (viewButtonsDisplayed) {
  2343. console.warn('showViewButtons: view buttons are already displayed');
  2344. return;
  2345. }
  2346. $newButton.removeClass('hidden');
  2347. $cloneButton.removeClass('hidden');
  2348. $rawTextButton.removeClass('hidden');
  2349. $qrCodeLink.removeClass('hidden');
  2350. viewButtonsDisplayed = true;
  2351. }
  2352. /**
  2353. * Hides all elements belonging to existing pastes
  2354. *
  2355. * @name TopNav.hideViewButtons
  2356. * @function
  2357. */
  2358. me.hideViewButtons = function()
  2359. {
  2360. if (!viewButtonsDisplayed) {
  2361. console.warn('hideViewButtons: view buttons are already hidden');
  2362. return;
  2363. }
  2364. $newButton.addClass('hidden');
  2365. $cloneButton.addClass('hidden');
  2366. $rawTextButton.addClass('hidden');
  2367. $qrCodeLink.addClass('hidden');
  2368. viewButtonsDisplayed = false;
  2369. }
  2370. /**
  2371. * Hides all elements belonging to existing pastes
  2372. *
  2373. * @name TopNav.hideAllButtons
  2374. * @function
  2375. */
  2376. me.hideAllButtons = function()
  2377. {
  2378. me.hideViewButtons();
  2379. me.hideCreateButtons();
  2380. }
  2381. /**
  2382. * shows all elements needed when creating a new paste
  2383. *
  2384. * @name TopNav.showCreateButtons
  2385. * @function
  2386. */
  2387. me.showCreateButtons = function()
  2388. {
  2389. if (createButtonsDisplayed) {
  2390. console.warn('showCreateButtons: create buttons are already displayed');
  2391. return;
  2392. }
  2393. $sendButton.removeClass('hidden');
  2394. $expiration.removeClass('hidden');
  2395. $formatter.removeClass('hidden');
  2396. $burnAfterReadingOption.removeClass('hidden');
  2397. $openDiscussionOption.removeClass('hidden');
  2398. $newButton.removeClass('hidden');
  2399. $password.removeClass('hidden');
  2400. $attach.removeClass('hidden');
  2401. createButtonsDisplayed = true;
  2402. }
  2403. /**
  2404. * shows all elements needed when creating a new paste
  2405. *
  2406. * @name TopNav.hideCreateButtons
  2407. * @function
  2408. */
  2409. me.hideCreateButtons = function()
  2410. {
  2411. if (!createButtonsDisplayed) {
  2412. console.warn('hideCreateButtons: create buttons are already hidden');
  2413. return;
  2414. }
  2415. $newButton.addClass('hidden');
  2416. $sendButton.addClass('hidden');
  2417. $expiration.addClass('hidden');
  2418. $formatter.addClass('hidden');
  2419. $burnAfterReadingOption.addClass('hidden');
  2420. $openDiscussionOption.addClass('hidden');
  2421. $password.addClass('hidden');
  2422. $attach.addClass('hidden');
  2423. createButtonsDisplayed = false;
  2424. }
  2425. /**
  2426. * only shows the "new paste" button
  2427. *
  2428. * @name TopNav.showNewPasteButton
  2429. * @function
  2430. */
  2431. me.showNewPasteButton = function()
  2432. {
  2433. $newButton.removeClass('hidden');
  2434. }
  2435. /**
  2436. * only hides the clone button
  2437. *
  2438. * @name TopNav.hideCloneButton
  2439. * @function
  2440. */
  2441. me.hideCloneButton = function()
  2442. {
  2443. $cloneButton.addClass('hidden');
  2444. }
  2445. /**
  2446. * only hides the raw text button
  2447. *
  2448. * @name TopNav.hideRawButton
  2449. * @function
  2450. */
  2451. me.hideRawButton = function()
  2452. {
  2453. $rawTextButton.addClass('hidden');
  2454. }
  2455. /**
  2456. * hides the file selector in attachment
  2457. *
  2458. * @name TopNav.hideFileSelector
  2459. * @function
  2460. */
  2461. me.hideFileSelector = function()
  2462. {
  2463. $fileWrap.addClass('hidden');
  2464. }
  2465. /**
  2466. * shows the custom attachment
  2467. *
  2468. * @name TopNav.showCustomAttachment
  2469. * @function
  2470. */
  2471. me.showCustomAttachment = function()
  2472. {
  2473. $customAttachment.removeClass('hidden');
  2474. }
  2475. /**
  2476. * collapses the navigation bar if nedded
  2477. *
  2478. * @name TopNav.collapseBar
  2479. * @function
  2480. */
  2481. me.collapseBar = function()
  2482. {
  2483. var $bar = $('.navbar-toggle');
  2484. // check if bar is expanded
  2485. if ($bar.hasClass('collapse in')) {
  2486. // if so, toggle it
  2487. $bar.click();
  2488. }
  2489. }
  2490. /**
  2491. * returns the currently set expiration time
  2492. *
  2493. * @name TopNav.getExpiration
  2494. * @function
  2495. * @return {int}
  2496. */
  2497. me.getExpiration = function()
  2498. {
  2499. return pasteExpiration;
  2500. }
  2501. /**
  2502. * returns the currently selected file(s)
  2503. *
  2504. * @name TopNav.getFileList
  2505. * @function
  2506. * @return {FileList|null}
  2507. */
  2508. me.getFileList = function()
  2509. {
  2510. var $file = $('#file');
  2511. // if no file given, return null
  2512. if (!$file.length || !$file[0].files.length) {
  2513. return null;
  2514. }
  2515. // @TODO is this really necessary
  2516. if (!($file[0].files && $file[0].files[0])) {
  2517. return null;
  2518. }
  2519. return $file[0].files;
  2520. }
  2521. /**
  2522. * returns the state of the burn after reading checkbox
  2523. *
  2524. * @name TopNav.getExpiration
  2525. * @function
  2526. * @return {bool}
  2527. */
  2528. me.getBurnAfterReading = function()
  2529. {
  2530. return $burnAfterReading.is(':checked');
  2531. }
  2532. /**
  2533. * returns the state of the discussion checkbox
  2534. *
  2535. * @name TopNav.getOpenDiscussion
  2536. * @function
  2537. * @return {bool}
  2538. */
  2539. me.getOpenDiscussion = function()
  2540. {
  2541. return $openDiscussion.is(':checked');
  2542. }
  2543. /**
  2544. * returns the entered password
  2545. *
  2546. * @name TopNav.getPassword
  2547. * @function
  2548. * @return {string}
  2549. */
  2550. me.getPassword = function()
  2551. {
  2552. return $passwordInput.val();
  2553. }
  2554. /**
  2555. * returns the element where custom attachments can be placed
  2556. *
  2557. * Used by AttachmentViewer when an attachment is cloned here.
  2558. *
  2559. * @name TopNav.getCustomAttachment
  2560. * @function
  2561. * @return {jQuery}
  2562. */
  2563. me.getCustomAttachment = function()
  2564. {
  2565. return $customAttachment;
  2566. }
  2567. /**
  2568. * init navigation manager
  2569. *
  2570. * preloads jQuery elements
  2571. *
  2572. * @name TopNav.init
  2573. * @function
  2574. */
  2575. me.init = function()
  2576. {
  2577. $attach = $('#attach');
  2578. $burnAfterReading = $('#burnafterreading');
  2579. $burnAfterReadingOption = $('#burnafterreadingoption');
  2580. $cloneButton = $('#clonebutton');
  2581. $customAttachment = $('#customattachment');
  2582. $expiration = $('#expiration');
  2583. $fileRemoveButton = $('#fileremovebutton');
  2584. $fileWrap = $('#filewrap');
  2585. $formatter = $('#formatter');
  2586. $newButton = $('#newbutton');
  2587. $openDiscussion = $('#opendiscussion');
  2588. $openDiscussionOption = $('#opendiscussionoption');
  2589. $password = $('#password');
  2590. $passwordInput = $('#passwordinput');
  2591. $rawTextButton = $('#rawtextbutton');
  2592. $sendButton = $('#sendbutton');
  2593. $qrCodeLink = $('#qrcodelink');
  2594. // bootstrap template drop down
  2595. $('#language ul.dropdown-menu li a').click(setLanguage);
  2596. // page template drop down
  2597. $('#language select option').click(setLanguage);
  2598. // bind events
  2599. $burnAfterReading.change(changeBurnAfterReading);
  2600. $openDiscussionOption.change(changeOpenDiscussion);
  2601. $newButton.click(clickNewPaste);
  2602. $sendButton.click(PasteEncrypter.sendPaste);
  2603. $cloneButton.click(Controller.clonePaste);
  2604. $rawTextButton.click(rawText);
  2605. $fileRemoveButton.click(removeAttachment);
  2606. $qrCodeLink.click(displayQrCode);
  2607. // bootstrap template drop downs
  2608. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2609. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2610. // initiate default state of checkboxes
  2611. changeBurnAfterReading();
  2612. changeOpenDiscussion();
  2613. // get default value from template or fall back to set value
  2614. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2615. }
  2616. return me;
  2617. })(window, document);
  2618. /**
  2619. * Responsible for AJAX requests, transparently handles encryption…
  2620. *
  2621. * @name Uploader
  2622. * @class
  2623. */
  2624. var Uploader = (function () {
  2625. var me = {};
  2626. var successFunc = null,
  2627. failureFunc = null,
  2628. url,
  2629. data,
  2630. symmetricKey,
  2631. password;
  2632. /**
  2633. * public variable ('constant') for errors to prevent magic numbers
  2634. *
  2635. * @name Uploader.error
  2636. * @readonly
  2637. * @enum {Object}
  2638. */
  2639. me.error = {
  2640. okay: 0,
  2641. custom: 1,
  2642. unknown: 2,
  2643. serverError: 3
  2644. };
  2645. /**
  2646. * ajaxHeaders to send in AJAX requests
  2647. *
  2648. * @name Uploader.ajaxHeaders
  2649. * @private
  2650. * @readonly
  2651. * @enum {Object}
  2652. */
  2653. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  2654. /**
  2655. * called after successful upload
  2656. *
  2657. * @name Uploader.checkCryptParameters
  2658. * @private
  2659. * @function
  2660. * @throws {string}
  2661. */
  2662. function checkCryptParameters()
  2663. {
  2664. // workaround for this nasty 'bug' in ECMAScript
  2665. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  2666. var typeOfKey = typeof symmetricKey;
  2667. if (symmetricKey === null) {
  2668. typeOfKey = 'null';
  2669. }
  2670. // in case of missing preparation, throw error
  2671. switch (typeOfKey) {
  2672. case 'string':
  2673. // already set, all right
  2674. return;
  2675. case 'null':
  2676. // needs to be generated auto-generate
  2677. symmetricKey = CryptTool.getSymmetricKey();
  2678. break;
  2679. default:
  2680. console.error('current invalid symmetricKey:', symmetricKey);
  2681. throw 'symmetricKey is invalid, probably the module was not prepared';
  2682. }
  2683. // password is optional
  2684. }
  2685. /**
  2686. * called after successful upload
  2687. *
  2688. * @name Uploader.success
  2689. * @private
  2690. * @function
  2691. * @param {int} status
  2692. * @param {int} result - optional
  2693. */
  2694. function success(status, result)
  2695. {
  2696. // add useful data to result
  2697. result.encryptionKey = symmetricKey;
  2698. result.requestData = data;
  2699. if (successFunc !== null) {
  2700. successFunc(status, result);
  2701. }
  2702. }
  2703. /**
  2704. * called after a upload failure
  2705. *
  2706. * @name Uploader.fail
  2707. * @private
  2708. * @function
  2709. * @param {int} status - internal code
  2710. * @param {int} result - original error code
  2711. */
  2712. function fail(status, result)
  2713. {
  2714. if (failureFunc !== null) {
  2715. failureFunc(status, result);
  2716. }
  2717. }
  2718. /**
  2719. * actually uploads the data
  2720. *
  2721. * @name Uploader.run
  2722. * @function
  2723. */
  2724. me.run = function()
  2725. {
  2726. $.ajax({
  2727. type: 'POST',
  2728. url: url,
  2729. data: data,
  2730. dataType: 'json',
  2731. headers: ajaxHeaders,
  2732. success: function(result) {
  2733. if (result.status === 0) {
  2734. success(0, result);
  2735. } else if (result.status === 1) {
  2736. fail(1, result);
  2737. } else {
  2738. fail(2, result);
  2739. }
  2740. }
  2741. })
  2742. .fail(function(jqXHR, textStatus, errorThrown) {
  2743. console.error(textStatus, errorThrown);
  2744. fail(3, jqXHR);
  2745. });
  2746. }
  2747. /**
  2748. * set success function
  2749. *
  2750. * @name Uploader.setUrl
  2751. * @function
  2752. * @param {function} newUrl
  2753. */
  2754. me.setUrl = function(newUrl)
  2755. {
  2756. url = newUrl;
  2757. }
  2758. /**
  2759. * sets the password to use (first value) and optionally also the
  2760. * encryption key (not recommend, it is automatically generated).
  2761. *
  2762. * Note: Call this after prepare() as prepare() resets these values.
  2763. *
  2764. * @name Uploader.setCryptValues
  2765. * @function
  2766. * @param {string} newPassword
  2767. * @param {string} newKey - optional
  2768. */
  2769. me.setCryptParameters = function(newPassword, newKey)
  2770. {
  2771. password = newPassword;
  2772. if (typeof newKey !== 'undefined') {
  2773. symmetricKey = newKey;
  2774. }
  2775. }
  2776. /**
  2777. * set success function
  2778. *
  2779. * @name Uploader.setSuccess
  2780. * @function
  2781. * @param {function} func
  2782. */
  2783. me.setSuccess = function(func)
  2784. {
  2785. successFunc = func;
  2786. }
  2787. /**
  2788. * set failure function
  2789. *
  2790. * @name Uploader.setFailure
  2791. * @function
  2792. * @param {function} func
  2793. */
  2794. me.setFailure = function(func)
  2795. {
  2796. failureFunc = func;
  2797. }
  2798. /**
  2799. * prepares a new upload
  2800. *
  2801. * Call this when doing a new upload to reset any data from potential
  2802. * previous uploads. Must be called before any other method of this
  2803. * module.
  2804. *
  2805. * @name Uploader.prepare
  2806. * @function
  2807. * @return {object}
  2808. */
  2809. me.prepare = function()
  2810. {
  2811. // entropy should already be checked!
  2812. // reset password
  2813. password = '';
  2814. // reset key, so it a new one is generated when it is used
  2815. symmetricKey = null;
  2816. // reset data
  2817. successFunc = null;
  2818. failureFunc = null;
  2819. url = Helper.baseUri();
  2820. data = {};
  2821. }
  2822. /**
  2823. * encrypts and sets the data
  2824. *
  2825. * @name Uploader.setData
  2826. * @function
  2827. * @param {string} index
  2828. * @param {mixed} element
  2829. */
  2830. me.setData = function(index, element)
  2831. {
  2832. checkCryptParameters();
  2833. data[index] = CryptTool.cipher(symmetricKey, password, element);
  2834. }
  2835. /**
  2836. * set the additional metadata to send unencrypted
  2837. *
  2838. * @name Uploader.setUnencryptedData
  2839. * @function
  2840. * @param {string} index
  2841. * @param {mixed} element
  2842. */
  2843. me.setUnencryptedData = function(index, element)
  2844. {
  2845. data[index] = element;
  2846. }
  2847. /**
  2848. * set the additional metadata to send unencrypted passed at once
  2849. *
  2850. * @name Uploader.setUnencryptedData
  2851. * @function
  2852. * @param {object} newData
  2853. */
  2854. me.setUnencryptedBulkData = function(newData)
  2855. {
  2856. $.extend(data, newData);
  2857. }
  2858. /**
  2859. * Helper, which parses shows a general error message based on the result of the Uploader
  2860. *
  2861. * @name Uploader.parseUploadError
  2862. * @function
  2863. * @param {int} status
  2864. * @param {object} data
  2865. * @param {string} doThisThing - a human description of the action, which was tried
  2866. * @return {array}
  2867. */
  2868. me.parseUploadError = function(status, data, doThisThing) {
  2869. var errorArray;
  2870. switch (status) {
  2871. case me.error['custom']:
  2872. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  2873. break;
  2874. case me.error['unknown']:
  2875. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  2876. break;
  2877. case me.error['serverError']:
  2878. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  2879. break;
  2880. default:
  2881. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  2882. break;
  2883. }
  2884. return errorArray;
  2885. }
  2886. /**
  2887. * init Uploader
  2888. *
  2889. * @name Uploader.init
  2890. * @function
  2891. */
  2892. me.init = function()
  2893. {
  2894. // nothing yet
  2895. }
  2896. return me;
  2897. })();
  2898. /**
  2899. * (controller) Responsible for encrypting paste and sending it to server.
  2900. *
  2901. * Does upload, encryption is done transparently by Uploader.
  2902. *
  2903. * @name PasteEncrypter
  2904. * @class
  2905. */
  2906. var PasteEncrypter = (function () {
  2907. var me = {};
  2908. var requirementsChecked = false;
  2909. /**
  2910. * checks whether there is a suitable amount of entrophy
  2911. *
  2912. * @name PasteEncrypter.checkRequirements
  2913. * @private
  2914. * @function
  2915. * @param {function} retryCallback - the callback to execute to retry the upload
  2916. * @return {bool}
  2917. */
  2918. function checkRequirements(retryCallback) {
  2919. // skip double requirement checks
  2920. if (requirementsChecked === true) {
  2921. return true;
  2922. }
  2923. if (!CryptTool.isEntropyReady()) {
  2924. // display a message and wait
  2925. Alert.showStatus('Please move your mouse for more entropy…');
  2926. CryptTool.addEntropySeedListener(retryCallback);
  2927. return false;
  2928. }
  2929. requirementsChecked = true;
  2930. return true;
  2931. }
  2932. /**
  2933. * called after successful paste upload
  2934. *
  2935. * @name PasteEncrypter.showCreatedPaste
  2936. * @private
  2937. * @function
  2938. * @param {int} status
  2939. * @param {object} data
  2940. */
  2941. function showCreatedPaste(status, data) {
  2942. Alert.hideLoading();
  2943. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  2944. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  2945. Alert.hideMessages();
  2946. // show notification
  2947. PasteStatus.createPasteNotification(url, deleteUrl)
  2948. // show new URL in browser bar
  2949. history.pushState({type: 'newpaste'}, document.title, url);
  2950. TopNav.showViewButtons();
  2951. TopNav.hideRawButton();
  2952. Editor.hide();
  2953. // parse and show text
  2954. // (preparation already done in me.sendPaste())
  2955. PasteViewer.run();
  2956. }
  2957. /**
  2958. * called after successful comment upload
  2959. *
  2960. * @name PasteEncrypter.showUploadedComment
  2961. * @private
  2962. * @function
  2963. * @param {int} status
  2964. * @param {object} data
  2965. */
  2966. function showUploadedComment(status, data) {
  2967. // show success message
  2968. // Alert.showStatus('Comment posted.');
  2969. // reload paste
  2970. Controller.refreshPaste(function () {
  2971. // highlight sent comment
  2972. DiscussionViewer.highlightComment(data.id, true);
  2973. // reset error handler
  2974. Alert.setCustomHandler(null);
  2975. });
  2976. }
  2977. /**
  2978. * adds attachments to the Uploader
  2979. *
  2980. * @name PasteEncrypter.encryptAttachments
  2981. * @private
  2982. * @function
  2983. * @param {File|null|undefined} file - optional, falls back to cloned attachment
  2984. * @param {function} callback - excuted when action is successful
  2985. */
  2986. function encryptAttachments(file, callback) {
  2987. if (typeof file !== 'undefined' && file !== null) {
  2988. // check file reader requirements for upload
  2989. if (typeof FileReader === 'undefined') {
  2990. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2991. // cancels process as it does not execute callback
  2992. return;
  2993. }
  2994. var reader = new FileReader();
  2995. // closure to capture the file information
  2996. reader.onload = function(event) {
  2997. Uploader.setData('attachment', event.target.result);
  2998. Uploader.setData('attachmentname', file.name);
  2999. // run callback
  3000. return callback();
  3001. }
  3002. // actually read first file
  3003. reader.readAsDataURL(file);
  3004. } else if (AttachmentViewer.hasAttachment()) {
  3005. // fall back to cloned part
  3006. var attachment = AttachmentViewer.getAttachment();
  3007. Uploader.setData('attachment', attachment[0]);
  3008. Uploader.setData('attachmentname', attachment[1]);
  3009. return callback();
  3010. } else {
  3011. // if there are no attachments, this is of course still successful
  3012. return callback();
  3013. }
  3014. }
  3015. /**
  3016. * send a reply in a discussion
  3017. *
  3018. * @name PasteEncrypter.sendComment
  3019. * @function
  3020. */
  3021. me.sendComment = function()
  3022. {
  3023. Alert.hideMessages();
  3024. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3025. // UI loading state
  3026. TopNav.hideAllButtons();
  3027. Alert.showLoading('Sending comment…', 0, 'cloud-upload');
  3028. // get data
  3029. var plainText = DiscussionViewer.getReplyMessage(),
  3030. nickname = DiscussionViewer.getReplyNickname(),
  3031. parentid = DiscussionViewer.getReplyCommentId();
  3032. // do not send if there is no data
  3033. if (plainText.length === 0) {
  3034. // revert loading status…
  3035. Alert.hideLoading();
  3036. Alert.setCustomHandler(null);
  3037. TopNav.showViewButtons();
  3038. return;
  3039. }
  3040. // check entropy
  3041. if (!checkRequirements(function () {
  3042. me.sendComment();
  3043. })) {
  3044. return; // to prevent multiple executions
  3045. }
  3046. Alert.showLoading(null, 10);
  3047. // prepare Uploader
  3048. Uploader.prepare();
  3049. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3050. // set success/fail functions
  3051. Uploader.setSuccess(showUploadedComment);
  3052. Uploader.setFailure(function (status, data) {
  3053. // revert loading status…
  3054. Alert.hideLoading();
  3055. TopNav.showViewButtons();
  3056. // show error message
  3057. Alert.showError(Uploader.parseUploadError(status, data, 'post comment'));
  3058. // reset error handler
  3059. Alert.setCustomHandler(null);
  3060. });
  3061. // fill it with unencrypted params
  3062. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3063. if (typeof parentid === 'undefined') {
  3064. // if parent id is not set, this is the top-most comment, so use
  3065. // paste id as parent @TODO is this really good?
  3066. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3067. } else {
  3068. Uploader.setUnencryptedData('parentid', parentid);
  3069. }
  3070. // encrypt data
  3071. Uploader.setData('data', plainText);
  3072. if (nickname.length > 0) {
  3073. Uploader.setData('nickname', nickname);
  3074. }
  3075. Uploader.run();
  3076. }
  3077. /**
  3078. * sends a new paste to server
  3079. *
  3080. * @name PasteEncrypter.sendPaste
  3081. * @function
  3082. */
  3083. me.sendPaste = function()
  3084. {
  3085. // hide previous (error) messages
  3086. Controller.hideStatusMessages();
  3087. // UI loading state
  3088. TopNav.hideAllButtons();
  3089. Alert.showLoading('Sending paste…', 0, 'cloud-upload');
  3090. TopNav.collapseBar();
  3091. // get data
  3092. var plainText = Editor.getText(),
  3093. format = PasteViewer.getFormat(),
  3094. files = TopNav.getFileList();
  3095. // do not send if there is no data
  3096. if (plainText.length === 0 && files === null) {
  3097. // revert loading status…
  3098. Alert.hideLoading();
  3099. TopNav.showCreateButtons();
  3100. return;
  3101. }
  3102. Alert.showLoading(null, 10);
  3103. // check entropy
  3104. if (!checkRequirements(function () {
  3105. me.sendPaste();
  3106. })) {
  3107. return; // to prevent multiple executions
  3108. }
  3109. // prepare Uploader
  3110. Uploader.prepare();
  3111. Uploader.setCryptParameters(TopNav.getPassword());
  3112. // set success/fail functions
  3113. Uploader.setSuccess(showCreatedPaste);
  3114. Uploader.setFailure(function (status, data) {
  3115. // revert loading status…
  3116. Alert.hideLoading();
  3117. TopNav.showCreateButtons();
  3118. // show error message
  3119. Alert.showError(Uploader.parseUploadError(status, data, 'create paste'));
  3120. });
  3121. // fill it with unencrypted submitted options
  3122. Uploader.setUnencryptedBulkData({
  3123. expire: TopNav.getExpiration(),
  3124. formatter: format,
  3125. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3126. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3127. });
  3128. // prepare PasteViewer for later preview
  3129. PasteViewer.setText(plainText);
  3130. PasteViewer.setFormat(format);
  3131. // encrypt cipher data
  3132. Uploader.setData('data', plainText);
  3133. // encrypt attachments
  3134. encryptAttachments(
  3135. files === null ? null : files[0],
  3136. function () {
  3137. // send data
  3138. Uploader.run();
  3139. }
  3140. );
  3141. }
  3142. /**
  3143. * initialize
  3144. *
  3145. * @name PasteEncrypter.init
  3146. * @function
  3147. */
  3148. me.init = function()
  3149. {
  3150. // nothing yet
  3151. }
  3152. return me;
  3153. })();
  3154. /**
  3155. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3156. *
  3157. * Only decryption, no download.
  3158. *
  3159. * @name PasteDecrypter
  3160. * @class
  3161. */
  3162. var PasteDecrypter = (function () {
  3163. var me = {};
  3164. /**
  3165. * decrypt data or prompts for password in cvase of failure
  3166. *
  3167. * @name PasteDecrypter.decryptOrPromptPassword
  3168. * @private
  3169. * @function
  3170. * @param {string} key
  3171. * @param {string} password - optional, may be an empty string
  3172. * @param {string} cipherdata
  3173. * @throws {string}
  3174. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3175. */
  3176. function decryptOrPromptPassword(key, password, cipherdata)
  3177. {
  3178. // try decryption without password
  3179. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3180. // if it fails, request password
  3181. if (plaindata.length === 0 && password.length === 0) {
  3182. // try to get cached password first
  3183. password = Prompt.getPassword();
  3184. // if password is there, re-try
  3185. if (password.length === 0) {
  3186. password = Prompt.requestPassword();
  3187. }
  3188. // recursive
  3189. // note: an infinite loop is prevented as the previous if
  3190. // clause checks whether a password is already set and ignores
  3191. // errors when a password has been passed
  3192. return decryptOrPromptPassword.apply(key, password, cipherdata);
  3193. }
  3194. // if all tries failed, we can only return an error
  3195. if (plaindata.length === 0) {
  3196. throw 'failed to decipher data';
  3197. }
  3198. return plaindata;
  3199. }
  3200. /**
  3201. * decrypt the actual paste text
  3202. *
  3203. * @name PasteDecrypter.decryptOrPromptPassword
  3204. * @private
  3205. * @function
  3206. * @param {object} paste - paste data in object form
  3207. * @param {string} key
  3208. * @param {string} password
  3209. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3210. * @return {bool} whether action was successful
  3211. * @throws {string}
  3212. */
  3213. function decryptPaste(paste, key, password, ignoreError)
  3214. {
  3215. var plaintext
  3216. if (ignoreError === true) {
  3217. plaintext = CryptTool.decipher(key, password, paste.data);
  3218. } else {
  3219. try {
  3220. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3221. } catch (err) {
  3222. throw 'failed to decipher paste text: ' + err
  3223. }
  3224. if (plaintext === false) {
  3225. return false;
  3226. }
  3227. }
  3228. // on success show paste
  3229. PasteViewer.setFormat(paste.meta.formatter);
  3230. PasteViewer.setText(plaintext);
  3231. // trigger to show the text (attachment loaded afterwards)
  3232. PasteViewer.run();
  3233. return true;
  3234. }
  3235. /**
  3236. * decrypts any attachment
  3237. *
  3238. * @name PasteDecrypter.decryptAttachment
  3239. * @private
  3240. * @function
  3241. * @param {object} paste - paste data in object form
  3242. * @param {string} key
  3243. * @param {string} password
  3244. * @return {bool} whether action was successful
  3245. * @throws {string}
  3246. */
  3247. function decryptAttachment(paste, key, password)
  3248. {
  3249. // decrypt attachment
  3250. try {
  3251. var attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3252. } catch (err) {
  3253. throw 'failed to decipher attachment: ' + err
  3254. }
  3255. if (attachment === false) {
  3256. return false;
  3257. }
  3258. // decrypt attachment name
  3259. var attachmentName;
  3260. if (paste.attachmentname) {
  3261. try {
  3262. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3263. } catch (err) {
  3264. throw 'failed to decipher attachment name: ' + err
  3265. }
  3266. if (attachmentName === false) {
  3267. return false;
  3268. }
  3269. }
  3270. AttachmentViewer.setAttachment(attachment, attachmentName);
  3271. AttachmentViewer.showAttachment();
  3272. return true;
  3273. }
  3274. /**
  3275. * decrypts all comments and shows them
  3276. *
  3277. * @name PasteDecrypter.decryptComments
  3278. * @private
  3279. * @function
  3280. * @param {object} paste - paste data in object form
  3281. * @param {string} key
  3282. * @param {string} password
  3283. * @return {bool} whether action was successful
  3284. */
  3285. function decryptComments(paste, key, password)
  3286. {
  3287. // remove potentially previous discussion
  3288. DiscussionViewer.prepareNewDiscussion();
  3289. // iterate over comments
  3290. for (var i = 0; i < paste.comments.length; ++i) {
  3291. var comment = paste.comments[i];
  3292. DiscussionViewer.addComment(
  3293. comment,
  3294. CryptTool.decipher(key, password, comment.data),
  3295. CryptTool.decipher(key, password, comment.meta.nickname)
  3296. );
  3297. }
  3298. DiscussionViewer.finishDiscussion();
  3299. DiscussionViewer.showDiscussion();
  3300. return true;
  3301. }
  3302. /**
  3303. * show decrypted text in the display area, including discussion (if open)
  3304. *
  3305. * @name PasteDecrypter.run
  3306. * @function
  3307. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3308. */
  3309. me.run = function(paste)
  3310. {
  3311. Alert.hideMessages();
  3312. Alert.showLoading('Decrypting paste…', 0, 'cloud-download'); // @TODO icon maybe rotation-lock, but needs full Glyphicons
  3313. if (typeof paste === 'undefined') {
  3314. paste = $.parseJSON(Model.getCipherData());
  3315. }
  3316. var key = Model.getPasteKey(),
  3317. password = Prompt.getPassword();
  3318. if (PasteViewer.isPrettyPrinted()) {
  3319. console.error('Too pretty! (don\'t know why this check)'); //@TODO
  3320. return;
  3321. }
  3322. // try to decrypt the paste
  3323. try {
  3324. // decrypt attachments
  3325. if (paste.attachment) {
  3326. // try to decrypt paste and if it fails (because the password is
  3327. // missing) return to let JS continue and wait for user
  3328. if (!decryptAttachment(paste, key, password)) {
  3329. return;
  3330. }
  3331. // ignore empty paste, as this is allowed when pasting attachments
  3332. decryptPaste(paste, key, password, true);
  3333. } else {
  3334. decryptPaste(paste, key, password);
  3335. }
  3336. // shows the remaining time (until) deletion
  3337. PasteStatus.showRemainingTime(paste.meta);
  3338. // if the discussion is opened on this paste, display it
  3339. if (paste.meta.opendiscussion) {
  3340. decryptComments(paste, key, password);
  3341. }
  3342. Alert.hideLoading();
  3343. TopNav.showViewButtons();
  3344. } catch(err) {
  3345. Alert.hideLoading();
  3346. // log and show error
  3347. console.error(err);
  3348. Alert.showError('Could not decrypt data (Wrong key?)');
  3349. }
  3350. }
  3351. /**
  3352. * initialize
  3353. *
  3354. * @name PasteDecrypter.init
  3355. * @function
  3356. */
  3357. me.init = function()
  3358. {
  3359. // nothing yet
  3360. }
  3361. return me;
  3362. })();
  3363. /**
  3364. * (controller) main PrivateBin logic
  3365. *
  3366. * @name Controller
  3367. * @param {object} window
  3368. * @param {object} document
  3369. * @class
  3370. */
  3371. var Controller = (function (window, document) {
  3372. var me = {};
  3373. /**
  3374. * hides all status messages no matter which module showed them
  3375. *
  3376. * @name Controller.hideStatusMessages
  3377. * @function
  3378. */
  3379. me.hideStatusMessages = function()
  3380. {
  3381. PasteStatus.hideMessages();
  3382. Alert.hideMessages();
  3383. }
  3384. /**
  3385. * creates a new paste
  3386. *
  3387. * @name Controller.newPaste
  3388. * @function
  3389. */
  3390. me.newPaste = function()
  3391. {
  3392. // Important: This *must not* run Alert.hideMessages() as previous
  3393. // errors from viewing a paste should be shown.
  3394. TopNav.hideAllButtons();
  3395. Alert.showLoading('Preparing new paste…', 0, 'time');
  3396. PasteStatus.hideMessages();
  3397. PasteViewer.hide();
  3398. Editor.resetInput();
  3399. Editor.show();
  3400. Editor.focusInput();
  3401. TopNav.showCreateButtons();
  3402. Alert.hideLoading();
  3403. }
  3404. /**
  3405. * shows the loaded paste
  3406. *
  3407. * @name Controller.showPaste
  3408. * @function
  3409. */
  3410. me.showPaste = function()
  3411. {
  3412. try {
  3413. Model.getPasteId();
  3414. Model.getPasteKey();
  3415. } catch (err) {
  3416. console.error(err);
  3417. // missing decryption key (or paste ID) in URL?
  3418. if (window.location.hash.length === 0) {
  3419. 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?)');
  3420. // @TODO adjust error message as it is less specific now, probably include thrown exception for a detailed error
  3421. return;
  3422. }
  3423. }
  3424. // show proper elements on screen
  3425. PasteDecrypter.run();
  3426. }
  3427. /**
  3428. * refreshes the loaded paste to show potential new data
  3429. *
  3430. * @name Controller.refreshPaste
  3431. * @function
  3432. * @param {function} callback
  3433. */
  3434. me.refreshPaste = function(callback)
  3435. {
  3436. // save window position to restore it later
  3437. var orgPosition = $(window).scrollTop();
  3438. Uploader.prepare();
  3439. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3440. Uploader.setFailure(function (status, data) {
  3441. // revert loading status…
  3442. Alert.hideLoading();
  3443. TopNav.showViewButtons();
  3444. // show error message
  3445. Alert.showError(Uploader.parseUploadError(status, data, 'refresh display'));
  3446. })
  3447. Uploader.setSuccess(function (status, data) {
  3448. PasteDecrypter.run(data);
  3449. // restore position
  3450. window.scrollTo(0, orgPosition);
  3451. callback();
  3452. })
  3453. Uploader.run();
  3454. }
  3455. /**
  3456. * clone the current paste
  3457. *
  3458. * @name Controller.clonePaste
  3459. * @function
  3460. * @param {Event} event
  3461. */
  3462. me.clonePaste = function(event)
  3463. {
  3464. TopNav.collapseBar();
  3465. TopNav.hideAllButtons();
  3466. Alert.showLoading('Cloning paste…', 0, 'transfer');
  3467. // hide messages from previous paste
  3468. me.hideStatusMessages();
  3469. // erase the id and the key in url
  3470. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3471. if (AttachmentViewer.hasAttachment()) {
  3472. AttachmentViewer.moveAttachmentTo(
  3473. TopNav.getCustomAttachment(),
  3474. 'Cloned: \'%s\''
  3475. );
  3476. TopNav.hideFileSelector();
  3477. AttachmentViewer.hideAttachment();
  3478. // NOTE: it also looks nice without removing the attachment
  3479. // but for a consistent display we remove it…
  3480. AttachmentViewer.hideAttachmentPreview();
  3481. TopNav.showCustomAttachment();
  3482. // show another status message to make the user aware that the
  3483. // file was cloned too!
  3484. Alert.showStatus(
  3485. [
  3486. 'The cloned file \'%s\' was attached to this paste.',
  3487. AttachmentViewer.getAttachment()[1]
  3488. ], 'copy', true, true);
  3489. }
  3490. Editor.setText(PasteViewer.getText())
  3491. PasteViewer.hide();
  3492. Editor.show();
  3493. Alert.hideLoading();
  3494. TopNav.showCreateButtons();
  3495. }
  3496. /**
  3497. * removes a saved paste
  3498. *
  3499. * @name Controller.removePaste
  3500. * @function
  3501. * @param {string} pasteId
  3502. * @param {string} deleteToken
  3503. */
  3504. me.removePaste = function(pasteId, deleteToken) {
  3505. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3506. // so we use a POST request
  3507. Uploader.prepare();
  3508. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3509. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3510. Uploader.setFailure(function () {
  3511. Alert.showError(I18n._('Could not delete the paste, it was not stored in burn after reading mode.'));
  3512. })
  3513. Uploader.run();
  3514. }
  3515. /**
  3516. * application start
  3517. *
  3518. * @name Controller.init
  3519. * @function
  3520. */
  3521. me.init = function()
  3522. {
  3523. // first load translations
  3524. I18n.loadTranslations();
  3525. DOMPurify.setConfig({SAFE_FOR_JQUERY: true});
  3526. // initialize other modules/"classes"
  3527. Alert.init();
  3528. Model.init();
  3529. AttachmentViewer.init();
  3530. DiscussionViewer.init();
  3531. Editor.init();
  3532. PasteDecrypter.init();
  3533. PasteEncrypter.init();
  3534. PasteStatus.init();
  3535. PasteViewer.init();
  3536. Prompt.init();
  3537. TopNav.init();
  3538. UiHelper.init();
  3539. Uploader.init();
  3540. // display an existing paste
  3541. if (Model.hasCipherData()) {
  3542. return me.showPaste();
  3543. }
  3544. // otherwise create a new paste
  3545. me.newPaste();
  3546. }
  3547. return me;
  3548. })(window, document);
  3549. return {
  3550. Helper: Helper,
  3551. I18n: I18n,
  3552. CryptTool: CryptTool,
  3553. Model: Model,
  3554. UiHelper: UiHelper,
  3555. Alert: Alert,
  3556. PasteStatus: PasteStatus,
  3557. Prompt: Prompt,
  3558. Editor: Editor,
  3559. PasteViewer: PasteViewer,
  3560. AttachmentViewer: AttachmentViewer,
  3561. DiscussionViewer: DiscussionViewer,
  3562. TopNav: TopNav,
  3563. Uploader: Uploader,
  3564. PasteEncrypter: PasteEncrypter,
  3565. PasteDecrypter: PasteDecrypter,
  3566. Controller: Controller
  3567. };
  3568. }(jQuery, sjcl, Base64, RawDeflate);