1
0

privatebin.js 141 KB

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