privatebin.js 135 KB

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