privatebin.js 128 KB

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