privatebin.js 136 KB

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