privatebin.js 121 KB

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