privatebin.js 120 KB

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