privatebin.js 121 KB

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