privatebin.js 128 KB

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