privatebin.js 121 KB

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