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