privatebin.js 132 KB

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