privatebin.js 134 KB

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