privatebin.js 133 KB

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