privatebin.js 143 KB

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