privatebin.js 134 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467
  1. /**
  2. * PrivateBin
  3. *
  4. * a zero-knowledge paste bin
  5. *
  6. * @see {@link https://github.com/PrivateBin/PrivateBin}
  7. * @copyright 2012 Sébastien SAUVAGE ({@link http://sebsauvage.net})
  8. * @license {@link https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License}
  9. * @version 1.1.1
  10. * @name PrivateBin
  11. * @namespace
  12. */
  13. /** global: Base64 */
  14. /** global: DOMPurify */
  15. /** global: FileReader */
  16. /** global: RawDeflate */
  17. /** global: history */
  18. /** global: navigator */
  19. /** global: prettyPrint */
  20. /** global: prettyPrintOne */
  21. /** global: showdown */
  22. /** global: sjcl */
  23. /** global: kjua */
  24. // Immediately start random number generator collector.
  25. sjcl.random.startCollectors();
  26. // main application start, called when DOM is fully loaded
  27. jQuery(document).ready(function() {
  28. 'use strict';
  29. // run main controller
  30. $.PrivateBin.Controller.init();
  31. });
  32. jQuery.PrivateBin = (function($, sjcl, Base64, RawDeflate) {
  33. 'use strict';
  34. /**
  35. * static Helper methods
  36. *
  37. * @name Helper
  38. * @class
  39. */
  40. var Helper = (function () {
  41. var me = {};
  42. /**
  43. * blacklist of UserAgents (parts) known to belong to a bot
  44. *
  45. * @private
  46. * @enum {Object}
  47. * @readonly
  48. */
  49. var BadBotUA = [
  50. 'Bot',
  51. 'bot'
  52. ];
  53. /**
  54. * cache for script location
  55. *
  56. * @name Helper.baseUri
  57. * @private
  58. * @enum {string|null}
  59. */
  60. var baseUri = null;
  61. /**
  62. * converts a duration (in seconds) into human friendly approximation
  63. *
  64. * @name Helper.secondsToHuman
  65. * @function
  66. * @param {number} seconds
  67. * @return {Array}
  68. */
  69. me.secondsToHuman = function(seconds)
  70. {
  71. var v;
  72. if (seconds < 60)
  73. {
  74. v = Math.floor(seconds);
  75. return [v, 'second'];
  76. }
  77. if (seconds < 60 * 60)
  78. {
  79. v = Math.floor(seconds / 60);
  80. return [v, 'minute'];
  81. }
  82. if (seconds < 60 * 60 * 24)
  83. {
  84. v = Math.floor(seconds / (60 * 60));
  85. return [v, 'hour'];
  86. }
  87. // If less than 2 months, display in days:
  88. if (seconds < 60 * 60 * 24 * 60)
  89. {
  90. v = Math.floor(seconds / (60 * 60 * 24));
  91. return [v, 'day'];
  92. }
  93. v = Math.floor(seconds / (60 * 60 * 24 * 30));
  94. return [v, 'month'];
  95. };
  96. /**
  97. * text range selection
  98. *
  99. * @see {@link https://stackoverflow.com/questions/985272/jquery-selecting-text-in-an-element-akin-to-highlighting-with-your-mouse}
  100. * @name Helper.selectText
  101. * @function
  102. * @param {HTMLElement} element
  103. */
  104. me.selectText = function(element)
  105. {
  106. var range, selection;
  107. // MS
  108. if (document.body.createTextRange) {
  109. range = document.body.createTextRange();
  110. range.moveToElementText(element);
  111. range.select();
  112. } else if (window.getSelection) {
  113. selection = window.getSelection();
  114. range = document.createRange();
  115. range.selectNodeContents(element);
  116. selection.removeAllRanges();
  117. selection.addRange(range);
  118. }
  119. };
  120. /**
  121. * convert URLs to clickable links.
  122. * URLs to handle:
  123. * <pre>
  124. * magnet:?xt.1=urn:sha1:YNCKHTQCWBTRNJIV4WNAE52SJUQCZO5C&xt.2=urn:sha1:TXGCZQTH26NL6OUQAJJPFALHG2LTGBC7
  125. * https://example.com:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  126. * http://user:example.com@localhost:8800/zero/?6f09182b8ea51997#WtLEUO5Epj9UHAV9JFs+6pUQZp13TuspAUjnF+iM+dM=
  127. * </pre>
  128. *
  129. * @name Helper.urls2links
  130. * @function
  131. * @param {string} html
  132. * @return {string}
  133. */
  134. me.urls2links = function(html)
  135. {
  136. return html.replace(
  137. /(((http|https|ftp):\/\/[\w?=&.\/-;#@~%+*-]+(?![\w\s?&.\/;#~%"=-]*>))|((magnet):[\w?=&.\/-;#@~%+*-]+))/ig,
  138. '<a href="$1" rel="nofollow">$1</a>'
  139. );
  140. };
  141. /**
  142. * minimal sprintf emulation for %s and %d formats
  143. *
  144. * Note that this function needs the parameters in the same order as the
  145. * format strings appear in the string, contrary to the original.
  146. *
  147. * @see {@link https://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format#4795914}
  148. * @name Helper.sprintf
  149. * @function
  150. * @param {string} format
  151. * @param {...*} args - one or multiple parameters injected into format string
  152. * @return {string}
  153. */
  154. me.sprintf = function()
  155. {
  156. var args = Array.prototype.slice.call(arguments);
  157. var format = args[0],
  158. i = 1;
  159. return format.replace(/%(s|d)/g, function (m) {
  160. // m is the matched format, e.g. %s, %d
  161. var val = args[i];
  162. // A switch statement so that the formatter can be extended.
  163. switch (m)
  164. {
  165. case '%d':
  166. val = parseFloat(val);
  167. if (isNaN(val)) {
  168. val = 0;
  169. }
  170. break;
  171. default:
  172. // Default is %s
  173. }
  174. ++i;
  175. return val;
  176. });
  177. };
  178. /**
  179. * get value of cookie, if it was set, empty string otherwise
  180. *
  181. * @see {@link http://www.w3schools.com/js/js_cookies.asp}
  182. * @name Helper.getCookie
  183. * @function
  184. * @param {string} cname - may not be empty
  185. * @return {string}
  186. */
  187. me.getCookie = function(cname) {
  188. var name = cname + '=',
  189. ca = document.cookie.split(';');
  190. for (var i = 0; i < ca.length; ++i) {
  191. var c = ca[i];
  192. while (c.charAt(0) === ' ')
  193. {
  194. c = c.substring(1);
  195. }
  196. if (c.indexOf(name) === 0)
  197. {
  198. return c.substring(name.length, c.length);
  199. }
  200. }
  201. return '';
  202. };
  203. /**
  204. * get the current location (without search or hash part of the URL),
  205. * eg. https://example.com/path/?aaaa#bbbb --> https://example.com/path/
  206. *
  207. * @name Helper.baseUri
  208. * @function
  209. * @return {string}
  210. */
  211. me.baseUri = function()
  212. {
  213. // check for cached version
  214. if (baseUri !== null) {
  215. return baseUri;
  216. }
  217. baseUri = window.location.origin + window.location.pathname;
  218. return baseUri;
  219. };
  220. /**
  221. * resets state, used for unit testing
  222. *
  223. * @name Helper.reset
  224. * @function
  225. */
  226. me.reset = function()
  227. {
  228. baseUri = null;
  229. };
  230. /**
  231. * checks whether this is a bot we dislike
  232. *
  233. * @name Helper.isBadBot
  234. * @function
  235. * @return {bool}
  236. */
  237. me.isBadBot = function() {
  238. // check whether a bot user agent part can be found in the current
  239. // user agent
  240. var arrayLength = BadBotUA.length;
  241. for (var i = 0; i < arrayLength; i++) {
  242. if (navigator.userAgent.indexOf(BadBotUA) >= 0) {
  243. return true;
  244. }
  245. }
  246. return false;
  247. }
  248. return me;
  249. })();
  250. /**
  251. * internationalization module
  252. *
  253. * @name I18n
  254. * @class
  255. */
  256. var I18n = (function () {
  257. var me = {};
  258. /**
  259. * const for string of loaded language
  260. *
  261. * @name I18n.languageLoadedEvent
  262. * @private
  263. * @prop {string}
  264. * @readonly
  265. */
  266. var languageLoadedEvent = 'languageLoaded';
  267. /**
  268. * supported languages, minus the built in 'en'
  269. *
  270. * @name I18n.supportedLanguages
  271. * @private
  272. * @prop {string[]}
  273. * @readonly
  274. */
  275. var supportedLanguages = ['de', 'es', 'fr', 'it', 'no', 'pl', 'pt', 'oc', 'ru', 'sl', 'zh'];
  276. /**
  277. * built in language
  278. *
  279. * @name I18n.language
  280. * @private
  281. * @prop {string|null}
  282. */
  283. var language = null;
  284. /**
  285. * translation cache
  286. *
  287. * @name I18n.translations
  288. * @private
  289. * @enum {Object}
  290. */
  291. var translations = {};
  292. /**
  293. * translate a string, alias for I18n.translate
  294. *
  295. * @name I18n._
  296. * @function
  297. * @param {jQuery} $element - optional
  298. * @param {string} messageId
  299. * @param {...*} args - one or multiple parameters injected into placeholders
  300. * @return {string}
  301. */
  302. me._ = function()
  303. {
  304. return me.translate.apply(this, arguments);
  305. };
  306. /**
  307. * translate a string
  308. *
  309. * Optionally pass a jQuery element as the first parameter, to automatically
  310. * let the text of this element be replaced. In case the (asynchronously
  311. * loaded) language is not downloadet yet, this will make sure the string
  312. * is replaced when it is actually loaded.
  313. * So for easy translations passing the jQuery object to apply it to is
  314. * more save, especially when they are loaded in the beginning.
  315. *
  316. * @name I18n.translate
  317. * @function
  318. * @param {jQuery} $element - optional
  319. * @param {string} messageId
  320. * @param {...*} args - one or multiple parameters injected into placeholders
  321. * @return {string}
  322. */
  323. me.translate = function()
  324. {
  325. // convert parameters to array
  326. var args = Array.prototype.slice.call(arguments),
  327. messageId,
  328. $element = null;
  329. // parse arguments
  330. if (args[0] instanceof jQuery) {
  331. // optional jQuery element as first parameter
  332. $element = args[0];
  333. args.shift();
  334. }
  335. // extract messageId from arguments
  336. var usesPlurals = $.isArray(args[0]);
  337. if (usesPlurals) {
  338. // use the first plural form as messageId, otherwise the singular
  339. messageId = args[0].length > 1 ? args[0][1] : args[0][0];
  340. } else {
  341. messageId = args[0];
  342. }
  343. if (messageId.length === 0) {
  344. return messageId;
  345. }
  346. // if no translation string cannot be found (in translations object)
  347. if (!translations.hasOwnProperty(messageId) || language === null) {
  348. // if language is still loading and we have an elemt assigned
  349. if (language === null && $element !== null) {
  350. // handle the error by attaching the language loaded event
  351. var orgArguments = arguments;
  352. $(document).on(languageLoadedEvent, function () {
  353. // log to show that the previous error could be mitigated
  354. console.warn('Fix missing translation of \'' + messageId + '\' with now loaded language ' + language);
  355. // re-execute this function
  356. me.translate.apply(this, orgArguments);
  357. });
  358. // and fall back to English for now until the real language
  359. // file is loaded
  360. }
  361. // for all other languages than English for which this behaviour
  362. // is expected as it is built-in, log error
  363. if (language !== null && language !== 'en') {
  364. console.error('Missing translation for: \'' + messageId + '\' in language ' + language);
  365. // fallback to English
  366. }
  367. // save English translation (should be the same on both sides)
  368. translations[messageId] = args[0];
  369. }
  370. // lookup plural translation
  371. if (usesPlurals && $.isArray(translations[messageId])) {
  372. var n = parseInt(args[1] || 1, 10),
  373. key = me.getPluralForm(n),
  374. maxKey = translations[messageId].length - 1;
  375. if (key > maxKey) {
  376. key = maxKey;
  377. }
  378. args[0] = translations[messageId][key];
  379. args[1] = n;
  380. } else {
  381. // lookup singular translation
  382. args[0] = translations[messageId];
  383. }
  384. // format string
  385. var output = Helper.sprintf.apply(this, args);
  386. // if $element is given, apply text to element
  387. if ($element !== null) {
  388. // get last text node of element
  389. var content = $element.contents();
  390. if (content.length > 1) {
  391. content[content.length - 1].nodeValue = ' ' + output;
  392. } else {
  393. $element.text(output);
  394. }
  395. }
  396. return output;
  397. };
  398. /**
  399. * per language functions to use to determine the plural form
  400. *
  401. * @see {@link http://localization-guide.readthedocs.org/en/latest/l10n/pluralforms.html}
  402. * @name I18n.getPluralForm
  403. * @function
  404. * @param {int} n
  405. * @return {int} array key
  406. */
  407. me.getPluralForm = function(n) {
  408. switch (language)
  409. {
  410. case 'fr':
  411. case 'oc':
  412. case 'zh':
  413. return n > 1 ? 1 : 0;
  414. case 'pl':
  415. return n === 1 ? 0 : (n % 10 >= 2 && n %10 <=4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  416. case 'ru':
  417. return n % 10 === 1 && n % 100 !== 11 ? 0 : (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
  418. case 'sl':
  419. return n % 100 === 1 ? 1 : (n % 100 === 2 ? 2 : (n % 100 === 3 || n % 100 === 4 ? 3 : 0));
  420. // de, en, es, it, no, pt
  421. default:
  422. return n !== 1 ? 1 : 0;
  423. }
  424. };
  425. /**
  426. * load translations into cache
  427. *
  428. * @name I18n.loadTranslations
  429. * @function
  430. */
  431. me.loadTranslations = function()
  432. {
  433. var newLanguage = Helper.getCookie('lang');
  434. // auto-select language based on browser settings
  435. if (newLanguage.length === 0) {
  436. newLanguage = (navigator.language || navigator.userLanguage || 'en').substring(0, 2);
  437. }
  438. // if language is already used skip update
  439. if (newLanguage === language) {
  440. return;
  441. }
  442. // if language is built-in (English) skip update
  443. if (newLanguage === 'en') {
  444. language = 'en';
  445. return;
  446. }
  447. // if language is not supported, show error
  448. if (supportedLanguages.indexOf(newLanguage) === -1) {
  449. console.error('Language \'%s\' is not supported. Translation failed, fallback to English.', newLanguage);
  450. language = 'en';
  451. return;
  452. }
  453. // load strings from JSON
  454. $.getJSON('i18n/' + newLanguage + '.json', function(data) {
  455. language = newLanguage;
  456. translations = data;
  457. $(document).triggerHandler(languageLoadedEvent);
  458. }).fail(function (data, textStatus, errorMsg) {
  459. console.error('Language \'%s\' could not be loaded (%s: %s). Translation failed, fallback to English.', newLanguage, textStatus, errorMsg);
  460. language = 'en';
  461. });
  462. };
  463. /**
  464. * resets state, used for unit testing
  465. *
  466. * @name I18n.reset
  467. * @function
  468. */
  469. me.reset = function(mockLanguage, mockTranslations)
  470. {
  471. language = mockLanguage || null;
  472. translations = mockTranslations || {};
  473. };
  474. return me;
  475. })();
  476. /**
  477. * handles everything related to en/decryption
  478. *
  479. * @name CryptTool
  480. * @class
  481. */
  482. var CryptTool = (function () {
  483. var me = {};
  484. /**
  485. * compress a message (deflate compression), returns base64 encoded data
  486. *
  487. * @name CryptTool.compress
  488. * @function
  489. * @private
  490. * @param {string} message
  491. * @return {string} base64 data
  492. */
  493. function compress(message)
  494. {
  495. return Base64.toBase64( RawDeflate.deflate( Base64.utob(message) ) );
  496. }
  497. /**
  498. * decompress a message compressed with cryptToolcompress()
  499. *
  500. * @name CryptTool.decompress
  501. * @function
  502. * @private
  503. * @param {string} data - base64 data
  504. * @return {string} message
  505. */
  506. function decompress(data)
  507. {
  508. return Base64.btou( RawDeflate.inflate( Base64.fromBase64(data) ) );
  509. }
  510. /**
  511. * compress, then encrypt message with given key and password
  512. *
  513. * @name CryptTool.cipher
  514. * @function
  515. * @param {string} key
  516. * @param {string} password
  517. * @param {string} message
  518. * @return {string} data - JSON with encrypted data
  519. */
  520. me.cipher = function(key, password, message)
  521. {
  522. // Galois Counter Mode, keysize 256 bit, authentication tag 128 bit
  523. var options = {
  524. mode: 'gcm',
  525. ks: 256,
  526. ts: 128
  527. };
  528. if ((password || '').trim().length === 0) {
  529. return sjcl.encrypt(key, compress(message), options);
  530. }
  531. return sjcl.encrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), compress(message), options);
  532. };
  533. /**
  534. * decrypt message with key, then decompress
  535. *
  536. * @name CryptTool.decipher
  537. * @function
  538. * @param {string} key
  539. * @param {string} password
  540. * @param {string} data - JSON with encrypted data
  541. * @return {string} decrypted message, empty if decryption failed
  542. */
  543. me.decipher = function(key, password, data)
  544. {
  545. if (data !== undefined) {
  546. try {
  547. return decompress(sjcl.decrypt(key, data));
  548. } catch(err) {
  549. try {
  550. return decompress(sjcl.decrypt(key + sjcl.codec.hex.fromBits(sjcl.hash.sha256.hash(password)), data));
  551. } catch(e) {
  552. return '';
  553. }
  554. }
  555. }
  556. };
  557. /**
  558. * checks whether the crypt tool has collected enough entropy
  559. *
  560. * @name CryptTool.isEntropyReady
  561. * @function
  562. * @return {bool}
  563. */
  564. me.isEntropyReady = function()
  565. {
  566. return sjcl.random.isReady();
  567. };
  568. /**
  569. * add a listener function, triggered when enough entropy is available
  570. *
  571. * @name CryptTool.addEntropySeedListener
  572. * @function
  573. * @param {function} func
  574. */
  575. me.addEntropySeedListener = function(func)
  576. {
  577. sjcl.random.addEventListener('seeded', func);
  578. };
  579. /**
  580. * returns a random symmetric key
  581. *
  582. * @name CryptTool.getSymmetricKey
  583. * @function
  584. * @return {string} func
  585. */
  586. me.getSymmetricKey = function()
  587. {
  588. return sjcl.codec.base64.fromBits(sjcl.random.randomWords(8, 0), 0);
  589. };
  590. return me;
  591. })();
  592. /**
  593. * (Model) Data source (aka MVC)
  594. *
  595. * @name Model
  596. * @class
  597. */
  598. var Model = (function () {
  599. var me = {};
  600. var pasteData = null,
  601. $templates;
  602. var id = null, symmetricKey = null;
  603. /**
  604. * returns the expiration set in the HTML
  605. *
  606. * @name Model.getExpirationDefault
  607. * @function
  608. * @return string
  609. */
  610. me.getExpirationDefault = function()
  611. {
  612. return $('#pasteExpiration').val();
  613. };
  614. /**
  615. * returns the format set in the HTML
  616. *
  617. * @name Model.getFormatDefault
  618. * @function
  619. * @return string
  620. */
  621. me.getFormatDefault = function()
  622. {
  623. return $('#pasteFormatter').val();
  624. };
  625. /**
  626. * returns the paste data (including the cipher data)
  627. *
  628. * @name Model.getPasteData
  629. * @function
  630. * @param {function} callback (optional) Called when data is available
  631. * @param {function} useCache (optional) Whether to use the cache or
  632. * force a data reload. Default: true
  633. * @return string
  634. */
  635. me.getPasteData = function(callback, useCache)
  636. {
  637. // use cache if possible/allowed
  638. if (useCache !== false && pasteData !== null) {
  639. //execute callback
  640. if (typeof callback === 'function') {
  641. return callback(pasteData);
  642. }
  643. // alternatively just using inline
  644. return pasteData;
  645. }
  646. // reload data
  647. Uploader.prepare();
  648. Uploader.setUrl(Helper.baseUri() + '?' + me.getPasteId());
  649. Uploader.setFailure(function (status, data) {
  650. // revert loading status…
  651. Alert.hideLoading();
  652. TopNav.showViewButtons();
  653. // show error message
  654. Alert.showError(Uploader.parseUploadError(status, data, 'getting paste data'));
  655. });
  656. Uploader.setSuccess(function (status, data) {
  657. pasteData = data;
  658. if (typeof callback === 'function') {
  659. return callback(data);
  660. }
  661. });
  662. Uploader.run();
  663. };
  664. /**
  665. * get the pastes unique identifier from the URL,
  666. * eg. https://example.com/path/?c05354954c49a487#dfdsdgdgdfgdf returns c05354954c49a487
  667. *
  668. * @name Model.getPasteId
  669. * @function
  670. * @return {string} unique identifier
  671. * @throws {string}
  672. */
  673. me.getPasteId = function()
  674. {
  675. if (id === null) {
  676. // 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. // TODO: cannot set original $fileWrap here for security reasons…
  2002. $dragAndDropFileName.text(loadedFile.name);
  2003. }
  2004. file = loadedFile;
  2005. fileReader.onload = function (event) {
  2006. var dataURL = event.target.result;
  2007. attachmentData = dataURL;
  2008. if (Editor.isPreview()) {
  2009. me.handleAttachmentPreview($attachmentPreview, dataURL);
  2010. $attachmentPreview.removeClass('hidden');
  2011. }
  2012. };
  2013. fileReader.readAsDataURL(loadedFile);
  2014. }
  2015. /**
  2016. * handle the preview of files that can either be an image, video, audio or pdf element
  2017. *
  2018. * @name AttachmentViewer.handleAttachmentPreview
  2019. * @function
  2020. * @argument {jQuery} $targetElement where the preview should be appended.
  2021. * @argument {File Data} data of the file to be displayed.
  2022. */
  2023. me.handleAttachmentPreview = function ($targetElement, data) {
  2024. if (data) {
  2025. // source: https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()
  2026. var mimeType = data.slice(
  2027. data.indexOf('data:') + 5,
  2028. data.indexOf(';base64,')
  2029. );
  2030. attachmentHasPreview = true;
  2031. if (mimeType.match(/image\//i)) {
  2032. $targetElement.html(
  2033. $(document.createElement('img'))
  2034. .attr('src', data)
  2035. .attr('class', 'img-thumbnail')
  2036. );
  2037. } else if (mimeType.match(/video\//i)) {
  2038. $targetElement.html(
  2039. $(document.createElement('video'))
  2040. .attr('controls', 'true')
  2041. .attr('autoplay', 'true')
  2042. .attr('class', 'img-thumbnail')
  2043. .append($(document.createElement('source'))
  2044. .attr('type', mimeType)
  2045. .attr('src', data))
  2046. );
  2047. } else if (mimeType.match(/audio\//i)) {
  2048. $targetElement.html(
  2049. $(document.createElement('audio'))
  2050. .attr('controls', 'true')
  2051. .attr('autoplay', 'true')
  2052. .append($(document.createElement('source'))
  2053. .attr('type', mimeType)
  2054. .attr('src', data))
  2055. );
  2056. } else if (mimeType.match(/\/pdf/i)) {
  2057. // PDFs are only displayed if the filesize is smaller than about 1MB (after base64 encoding).
  2058. // Bigger filesizes currently cause crashes in various browsers.
  2059. // See also: https://code.google.com/p/chromium/issues/detail?id=69227
  2060. // Firefox crashes with files that are about 1.5MB
  2061. // The performance with 1MB files is bearable
  2062. if (data.length > 1398488) {
  2063. Alert.showError('File too large, to display a preview. Please download the attachment.'); //TODO: is this error really neccessary?
  2064. return;
  2065. }
  2066. // Fallback for browsers, that don't support the vh unit
  2067. var clientHeight = $(window).height();
  2068. $targetElement.html(
  2069. $(document.createElement('embed'))
  2070. .attr('src', data)
  2071. .attr('type', 'application/pdf')
  2072. .attr('class', 'pdfPreview')
  2073. .css('height', clientHeight)
  2074. );
  2075. } else {
  2076. attachmentHasPreview = false;
  2077. }
  2078. }
  2079. };
  2080. /**
  2081. * attaches the file attachment drag & drop handler to the page
  2082. *
  2083. * @name AttachmentViewer.addDragDropHandler
  2084. * @private
  2085. * @function
  2086. */
  2087. function addDragDropHandler() {
  2088. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  2089. return;
  2090. }
  2091. var ignoreDragDrop = function(event) {
  2092. event.stopPropagation();
  2093. event.preventDefault();
  2094. };
  2095. var drop = function(event) {
  2096. var evt = event.originalEvent;
  2097. evt.stopPropagation();
  2098. evt.preventDefault();
  2099. if ($fileInput) {
  2100. var file = evt.dataTransfer.files[0];
  2101. //Clear the file input:
  2102. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2103. $fileInput.unwrap();
  2104. //Only works in Chrome:
  2105. //fileInput[0].files = e.dataTransfer.files;
  2106. readFileData(file);
  2107. }
  2108. };
  2109. $(document).on('drop', drop);
  2110. $(document).on('dragenter', ignoreDragDrop);
  2111. $(document).on('dragover', ignoreDragDrop);
  2112. $fileInput.on('change', function () {
  2113. readFileData();
  2114. });
  2115. }
  2116. /**
  2117. * attaches the clipboard attachment handler to the page
  2118. *
  2119. * @name AttachmentViewer.addClipboardEventHandler
  2120. * @private
  2121. * @function
  2122. */
  2123. function addClipboardEventHandler() {
  2124. $(document).on('paste', function (event) {
  2125. var items = (event.clipboardData || event.originalEvent.clipboardData).items;
  2126. for (var i in items) {
  2127. if (items.hasOwnProperty(i)) {
  2128. var item = items[i];
  2129. if (item.kind === 'file') {
  2130. readFileData(item.getAsFile());
  2131. }
  2132. }
  2133. }
  2134. });
  2135. }
  2136. /**
  2137. * getter for attachment data
  2138. *
  2139. * @name AttachmentViewer.getAttachmentData
  2140. * @function
  2141. * @return {jQuery}
  2142. */
  2143. me.getAttachmentData = function () {
  2144. return attachmentData;
  2145. };
  2146. /**
  2147. * getter for attachment link
  2148. *
  2149. * @name AttachmentViewer.getAttachmentLink
  2150. * @function
  2151. * @return {jQuery}
  2152. */
  2153. me.getAttachmentLink = function () {
  2154. return $attachmentLink;
  2155. };
  2156. /**
  2157. * getter for attachment preview
  2158. *
  2159. * @name AttachmentViewer.getAttachmentPreview
  2160. * @function
  2161. * @return {jQuery}
  2162. */
  2163. me.getAttachmentPreview = function () {
  2164. return $attachmentPreview;
  2165. };
  2166. /**
  2167. * getter for file data, returns the file contents
  2168. *
  2169. * @name AttachmentViewer.getFile
  2170. * @function
  2171. * @return {string}
  2172. */
  2173. me.getFile = function () {
  2174. return file;
  2175. };
  2176. /**
  2177. * initiate
  2178. *
  2179. * preloads jQuery elements
  2180. *
  2181. * @name AttachmentViewer.init
  2182. * @function
  2183. */
  2184. me.init = function()
  2185. {
  2186. $attachment = $('#attachment');
  2187. if($attachment.length){
  2188. $attachmentLink = $('#attachment a');
  2189. $attachmentPreview = $('#attachmentPreview');
  2190. $dragAndDropFileName = $('#dragAndDropFileName');
  2191. $fileInput = $('#file');
  2192. addDragDropHandler();
  2193. addClipboardEventHandler();
  2194. }
  2195. }
  2196. return me;
  2197. })();
  2198. /**
  2199. * (view) Shows discussion thread and handles replies
  2200. *
  2201. * @name DiscussionViewer
  2202. * @class
  2203. */
  2204. var DiscussionViewer = (function () {
  2205. var me = {};
  2206. var $commentTail,
  2207. $discussion,
  2208. $reply,
  2209. $replyMessage,
  2210. $replyNickname,
  2211. $replyStatus,
  2212. $commentContainer;
  2213. var replyCommentId;
  2214. /**
  2215. * initializes the templates
  2216. *
  2217. * @name DiscussionViewer.initTemplates
  2218. * @private
  2219. * @function
  2220. */
  2221. function initTemplates()
  2222. {
  2223. $reply = Model.getTemplate('reply');
  2224. $replyMessage = $reply.find('#replymessage');
  2225. $replyNickname = $reply.find('#nickname');
  2226. $replyStatus = $reply.find('#replystatus');
  2227. // cache jQuery elements
  2228. $commentTail = Model.getTemplate('commenttail');
  2229. }
  2230. /**
  2231. * open the comment entry when clicking the "Reply" button of a comment
  2232. *
  2233. * @name DiscussionViewer.openReply
  2234. * @private
  2235. * @function
  2236. * @param {Event} event
  2237. */
  2238. function openReply(event)
  2239. {
  2240. var $source = $(event.target);
  2241. // clear input
  2242. $replyMessage.val('');
  2243. $replyNickname.val('');
  2244. // get comment id from source element
  2245. replyCommentId = $source.parent().prop('id').split('_')[1];
  2246. // move to correct position
  2247. $source.after($reply);
  2248. // show
  2249. $reply.removeClass('hidden');
  2250. $replyMessage.focus();
  2251. event.preventDefault();
  2252. }
  2253. /**
  2254. * custom handler for displaying notifications in own status message area
  2255. *
  2256. * @name DiscussionViewer.handleNotification
  2257. * @function
  2258. * @param {string} alertType
  2259. * @return {bool|jQuery}
  2260. */
  2261. me.handleNotification = function(alertType)
  2262. {
  2263. // ignore loading messages
  2264. if (alertType === 'loading') {
  2265. return false;
  2266. }
  2267. if (alertType === 'danger') {
  2268. $replyStatus.removeClass('alert-info');
  2269. $replyStatus.addClass('alert-danger');
  2270. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2271. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2272. } else {
  2273. $replyStatus.removeClass('alert-danger');
  2274. $replyStatus.addClass('alert-info');
  2275. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2276. $replyStatus.find(':first').addClass('glyphicon-alert');
  2277. }
  2278. return $replyStatus;
  2279. };
  2280. /**
  2281. * adds another comment
  2282. *
  2283. * @name DiscussionViewer.addComment
  2284. * @function
  2285. * @param {object} comment
  2286. * @param {string} commentText
  2287. * @param {string} nickname
  2288. */
  2289. me.addComment = function(comment, commentText, nickname)
  2290. {
  2291. if (commentText === '') {
  2292. commentText = 'comment decryption failed';
  2293. }
  2294. // create new comment based on template
  2295. var $commentEntry = Model.getTemplate('comment');
  2296. $commentEntry.prop('id', 'comment_' + comment.id);
  2297. var $commentEntryData = $commentEntry.find('div.commentdata');
  2298. // set & parse text
  2299. $commentEntryData.html(
  2300. DOMPurify.sanitize(
  2301. Helper.urls2links(commentText)
  2302. )
  2303. );
  2304. // set nickname
  2305. if (nickname.length > 0) {
  2306. $commentEntry.find('span.nickname').text(nickname);
  2307. } else {
  2308. $commentEntry.find('span.nickname').html('<i></i>');
  2309. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2310. }
  2311. // set date
  2312. $commentEntry.find('span.commentdate')
  2313. .text(' (' + (new Date(comment.meta.postdate * 1000).toLocaleString()) + ')')
  2314. .attr('title', 'CommentID: ' + comment.id);
  2315. // if an avatar is available, display it
  2316. if (comment.meta.vizhash) {
  2317. $commentEntry.find('span.nickname')
  2318. .before(
  2319. '<img src="' + comment.meta.vizhash + '" class="vizhash" /> '
  2320. );
  2321. $(document).on('languageLoaded', function () {
  2322. $commentEntry.find('img.vizhash')
  2323. .prop('title', I18n._('Avatar generated from IP address'));
  2324. });
  2325. }
  2326. // starting point (default value/fallback)
  2327. var $place = $commentContainer;
  2328. // if parent comment exists
  2329. var $parentComment = $('#comment_' + comment.parentid);
  2330. if ($parentComment.length) {
  2331. // use parent as position for new comment, so it is shifted
  2332. // to the right
  2333. $place = $parentComment;
  2334. }
  2335. // finally append comment
  2336. $place.append($commentEntry);
  2337. };
  2338. /**
  2339. * finishes the discussion area after last comment
  2340. *
  2341. * @name DiscussionViewer.finishDiscussion
  2342. * @function
  2343. */
  2344. me.finishDiscussion = function()
  2345. {
  2346. // add 'add new comment' area
  2347. $commentContainer.append($commentTail);
  2348. // show discussions
  2349. $discussion.removeClass('hidden');
  2350. };
  2351. /**
  2352. * removes the old discussion and prepares everything for creating a new
  2353. * one.
  2354. *
  2355. * @name DiscussionViewer.prepareNewDiscussion
  2356. * @function
  2357. */
  2358. me.prepareNewDiscussion = function()
  2359. {
  2360. $commentContainer.html('');
  2361. $discussion.addClass('hidden');
  2362. // (re-)init templates
  2363. initTemplates();
  2364. };
  2365. /**
  2366. * returns the users message from the reply form
  2367. *
  2368. * @name DiscussionViewer.getReplyMessage
  2369. * @function
  2370. * @return {String}
  2371. */
  2372. me.getReplyMessage = function()
  2373. {
  2374. return $replyMessage.val();
  2375. };
  2376. /**
  2377. * returns the users nickname (if any) from the reply form
  2378. *
  2379. * @name DiscussionViewer.getReplyNickname
  2380. * @function
  2381. * @return {String}
  2382. */
  2383. me.getReplyNickname = function()
  2384. {
  2385. return $replyNickname.val();
  2386. };
  2387. /**
  2388. * returns the id of the parent comment the user is replying to
  2389. *
  2390. * @name DiscussionViewer.getReplyCommentId
  2391. * @function
  2392. * @return {int|undefined}
  2393. */
  2394. me.getReplyCommentId = function()
  2395. {
  2396. return replyCommentId;
  2397. };
  2398. /**
  2399. * highlights a specific comment and scrolls to it if necessary
  2400. *
  2401. * @name DiscussionViewer.highlightComment
  2402. * @function
  2403. * @param {string} commentId
  2404. * @param {bool} fadeOut - whether to fade out the comment
  2405. */
  2406. me.highlightComment = function(commentId, fadeOut)
  2407. {
  2408. var $comment = $('#comment_' + commentId);
  2409. // in case comment does not exist, cancel
  2410. if ($comment.length === 0) {
  2411. return;
  2412. }
  2413. var highlightComment = function () {
  2414. $comment.addClass('highlight');
  2415. if (fadeOut === true) {
  2416. setTimeout(function () {
  2417. $comment.removeClass('highlight');
  2418. }, 300);
  2419. }
  2420. };
  2421. if (UiHelper.isVisible($comment)) {
  2422. return highlightComment();
  2423. }
  2424. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2425. };
  2426. /**
  2427. * initiate
  2428. *
  2429. * preloads jQuery elements
  2430. *
  2431. * @name DiscussionViewer.init
  2432. * @function
  2433. */
  2434. me.init = function()
  2435. {
  2436. // bind events to templates (so they are later cloned)
  2437. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2438. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2439. $commentContainer = $('#commentcontainer');
  2440. $discussion = $('#discussion');
  2441. };
  2442. return me;
  2443. })();
  2444. /**
  2445. * Manage top (navigation) bar
  2446. *
  2447. * @name TopNav
  2448. * @param {object} window
  2449. * @param {object} document
  2450. * @class
  2451. */
  2452. var TopNav = (function (window, document) {
  2453. var me = {};
  2454. var createButtonsDisplayed = false;
  2455. var viewButtonsDisplayed = false;
  2456. var $attach,
  2457. $burnAfterReading,
  2458. $burnAfterReadingOption,
  2459. $cloneButton,
  2460. $customAttachment,
  2461. $expiration,
  2462. $fileRemoveButton,
  2463. $fileWrap,
  2464. $formatter,
  2465. $newButton,
  2466. $openDiscussion,
  2467. $openDiscussionOption,
  2468. $password,
  2469. $passwordInput,
  2470. $rawTextButton,
  2471. $qrCodeLink,
  2472. $sendButton,
  2473. $retryButton;
  2474. var pasteExpiration = '1week',
  2475. retryButtonCallback;
  2476. /**
  2477. * set the expiration on bootstrap templates in dropdown
  2478. *
  2479. * @name TopNav.updateExpiration
  2480. * @private
  2481. * @function
  2482. * @param {Event} event
  2483. */
  2484. function updateExpiration(event)
  2485. {
  2486. // get selected option
  2487. var target = $(event.target);
  2488. // update dropdown display and save new expiration time
  2489. $('#pasteExpirationDisplay').text(target.text());
  2490. pasteExpiration = target.data('expiration');
  2491. event.preventDefault();
  2492. }
  2493. /**
  2494. * set the format on bootstrap templates in dropdown
  2495. *
  2496. * @name TopNav.updateFormat
  2497. * @private
  2498. * @function
  2499. * @param {Event} event
  2500. */
  2501. function updateFormat(event)
  2502. {
  2503. // get selected option
  2504. var $target = $(event.target);
  2505. // update dropdown display and save new format
  2506. var newFormat = $target.data('format');
  2507. $('#pasteFormatterDisplay').text($target.text());
  2508. PasteViewer.setFormat(newFormat);
  2509. // update preview
  2510. if (Editor.isPreview()) {
  2511. PasteViewer.run();
  2512. }
  2513. event.preventDefault();
  2514. }
  2515. /**
  2516. * when "burn after reading" is checked, disable discussion
  2517. *
  2518. * @name TopNav.changeBurnAfterReading
  2519. * @private
  2520. * @function
  2521. */
  2522. function changeBurnAfterReading()
  2523. {
  2524. if ($burnAfterReading.is(':checked')) {
  2525. $openDiscussionOption.addClass('buttondisabled');
  2526. $openDiscussion.prop('checked', false);
  2527. // if button is actually disabled, force-enable it and uncheck other button
  2528. $burnAfterReadingOption.removeClass('buttondisabled');
  2529. } else {
  2530. $openDiscussionOption.removeClass('buttondisabled');
  2531. }
  2532. }
  2533. /**
  2534. * when discussion is checked, disable "burn after reading"
  2535. *
  2536. * @name TopNav.changeOpenDiscussion
  2537. * @private
  2538. * @function
  2539. */
  2540. function changeOpenDiscussion()
  2541. {
  2542. if ($openDiscussion.is(':checked')) {
  2543. $burnAfterReadingOption.addClass('buttondisabled');
  2544. $burnAfterReading.prop('checked', false);
  2545. // if button is actually disabled, force-enable it and uncheck other button
  2546. $openDiscussionOption.removeClass('buttondisabled');
  2547. } else {
  2548. $burnAfterReadingOption.removeClass('buttondisabled');
  2549. }
  2550. }
  2551. /**
  2552. * return raw text
  2553. *
  2554. * @name TopNav.rawText
  2555. * @private
  2556. * @function
  2557. */
  2558. function rawText()
  2559. {
  2560. TopNav.hideAllButtons();
  2561. Alert.showLoading('Showing raw text…', 'time');
  2562. var paste = PasteViewer.getText();
  2563. // push a new state to allow back navigation with browser back button
  2564. history.pushState(
  2565. {type: 'raw'},
  2566. document.title,
  2567. // recreate paste URL
  2568. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  2569. Model.getPasteKey()
  2570. );
  2571. // we use text/html instead of text/plain to avoid a bug when
  2572. // reloading the raw text view (it reverts to type text/html)
  2573. var $head = $('head').children().not('noscript, script, link[type="text/css"]');
  2574. var newDoc = document.open('text/html', 'replace');
  2575. newDoc.write('<!DOCTYPE html><html><head>');
  2576. for (var i = 0; i < $head.length; i++) {
  2577. newDoc.write($head[i].outerHTML);
  2578. }
  2579. newDoc.write('</head><body><pre>' + DOMPurify.sanitize(paste) + '</pre></body></html>');
  2580. newDoc.close();
  2581. }
  2582. /**
  2583. * saves the language in a cookie and reloads the page
  2584. *
  2585. * @name TopNav.setLanguage
  2586. * @private
  2587. * @function
  2588. * @param {Event} event
  2589. */
  2590. function setLanguage(event)
  2591. {
  2592. document.cookie = 'lang=' + $(event.target).data('lang');
  2593. UiHelper.reloadHome();
  2594. }
  2595. /**
  2596. * hides all messages and creates a new paste
  2597. *
  2598. * @name TopNav.clickNewPaste
  2599. * @private
  2600. * @function
  2601. */
  2602. function clickNewPaste()
  2603. {
  2604. Controller.hideStatusMessages();
  2605. Controller.newPaste();
  2606. }
  2607. /**
  2608. * retrys some callback registered before
  2609. *
  2610. * @name TopNav.clickRetryButton
  2611. * @private
  2612. * @function
  2613. * @param {Event} event
  2614. */
  2615. function clickRetryButton(event)
  2616. {
  2617. retryButtonCallback(event);
  2618. }
  2619. /**
  2620. * removes the existing attachment
  2621. *
  2622. * @name TopNav.removeAttachment
  2623. * @private
  2624. * @function
  2625. * @param {Event} event
  2626. */
  2627. function removeAttachment(event)
  2628. {
  2629. // if custom attachment is used, remove it first
  2630. if (!$customAttachment.hasClass('hidden')) {
  2631. AttachmentViewer.removeAttachment();
  2632. $customAttachment.addClass('hidden');
  2633. $fileWrap.removeClass('hidden');
  2634. }
  2635. // in any case, remove saved attachment data
  2636. AttachmentViewer.removeAttachmentData();
  2637. // hide UI for selected files
  2638. // our up-to-date jQuery can handle it :)
  2639. $fileWrap.find('input').val('');
  2640. AttachmentViewer.clearDragAndDrop();
  2641. // pevent '#' from appearing in the URL
  2642. event.preventDefault();
  2643. }
  2644. /**
  2645. * Shows the QR code of the current paste (URL).
  2646. *
  2647. * @name TopNav.displayQrCode
  2648. * @private
  2649. * @function
  2650. */
  2651. function displayQrCode()
  2652. {
  2653. var qrCanvas = kjua({
  2654. render: 'canvas',
  2655. text: window.location.href
  2656. });
  2657. $('#qrcode-display').html(qrCanvas);
  2658. }
  2659. /**
  2660. * Shows all navigation elements for viewing an existing paste
  2661. *
  2662. * @name TopNav.showViewButtons
  2663. * @function
  2664. */
  2665. me.showViewButtons = function()
  2666. {
  2667. if (viewButtonsDisplayed) {
  2668. console.warn('showViewButtons: view buttons are already displayed');
  2669. return;
  2670. }
  2671. $newButton.removeClass('hidden');
  2672. $cloneButton.removeClass('hidden');
  2673. $rawTextButton.removeClass('hidden');
  2674. $qrCodeLink.removeClass('hidden');
  2675. viewButtonsDisplayed = true;
  2676. };
  2677. /**
  2678. * Hides all navigation elements for viewing an existing paste
  2679. *
  2680. * @name TopNav.hideViewButtons
  2681. * @function
  2682. */
  2683. me.hideViewButtons = function()
  2684. {
  2685. if (!viewButtonsDisplayed) {
  2686. console.warn('hideViewButtons: view buttons are already hidden');
  2687. return;
  2688. }
  2689. $cloneButton.addClass('hidden');
  2690. $newButton.addClass('hidden');
  2691. $rawTextButton.addClass('hidden');
  2692. $qrCodeLink.addClass('hidden');
  2693. viewButtonsDisplayed = false;
  2694. };
  2695. /**
  2696. * Hides all elements belonging to existing pastes
  2697. *
  2698. * @name TopNav.hideAllButtons
  2699. * @function
  2700. */
  2701. me.hideAllButtons = function()
  2702. {
  2703. me.hideViewButtons();
  2704. me.hideCreateButtons();
  2705. };
  2706. /**
  2707. * shows all elements needed when creating a new paste
  2708. *
  2709. * @name TopNav.showCreateButtons
  2710. * @function
  2711. */
  2712. me.showCreateButtons = function()
  2713. {
  2714. if (createButtonsDisplayed) {
  2715. console.warn('showCreateButtons: create buttons are already displayed');
  2716. return;
  2717. }
  2718. $attach.removeClass('hidden');
  2719. $burnAfterReadingOption.removeClass('hidden');
  2720. $expiration.removeClass('hidden');
  2721. $formatter.removeClass('hidden');
  2722. $newButton.removeClass('hidden');
  2723. $openDiscussionOption.removeClass('hidden');
  2724. $password.removeClass('hidden');
  2725. $sendButton.removeClass('hidden');
  2726. createButtonsDisplayed = true;
  2727. };
  2728. /**
  2729. * shows all elements needed when creating a new paste
  2730. *
  2731. * @name TopNav.hideCreateButtons
  2732. * @function
  2733. */
  2734. me.hideCreateButtons = function()
  2735. {
  2736. if (!createButtonsDisplayed) {
  2737. console.warn('hideCreateButtons: create buttons are already hidden');
  2738. return;
  2739. }
  2740. $newButton.addClass('hidden');
  2741. $sendButton.addClass('hidden');
  2742. $expiration.addClass('hidden');
  2743. $formatter.addClass('hidden');
  2744. $burnAfterReadingOption.addClass('hidden');
  2745. $openDiscussionOption.addClass('hidden');
  2746. $password.addClass('hidden');
  2747. $attach.addClass('hidden');
  2748. createButtonsDisplayed = false;
  2749. };
  2750. /**
  2751. * only shows the "new paste" button
  2752. *
  2753. * @name TopNav.showNewPasteButton
  2754. * @function
  2755. */
  2756. me.showNewPasteButton = function()
  2757. {
  2758. $newButton.removeClass('hidden');
  2759. };
  2760. /**
  2761. * only shows the "retry" button
  2762. *
  2763. * @name TopNav.showRetryButton
  2764. * @function
  2765. */
  2766. me.showRetryButton = function()
  2767. {
  2768. $retryButton.removeClass('hidden');
  2769. }
  2770. /**
  2771. * hides the "retry" button
  2772. *
  2773. * @name TopNav.hideRetryButton
  2774. * @function
  2775. */
  2776. me.hideRetryButton = function()
  2777. {
  2778. $retryButton.addClass('hidden');
  2779. }
  2780. /**
  2781. * only hides the clone button
  2782. *
  2783. * @name TopNav.hideCloneButton
  2784. * @function
  2785. */
  2786. me.hideCloneButton = function()
  2787. {
  2788. $cloneButton.addClass('hidden');
  2789. };
  2790. /**
  2791. * only hides the raw text button
  2792. *
  2793. * @name TopNav.hideRawButton
  2794. * @function
  2795. */
  2796. me.hideRawButton = function()
  2797. {
  2798. $rawTextButton.addClass('hidden');
  2799. };
  2800. /**
  2801. * hides the file selector in attachment
  2802. *
  2803. * @name TopNav.hideFileSelector
  2804. * @function
  2805. */
  2806. me.hideFileSelector = function()
  2807. {
  2808. $fileWrap.addClass('hidden');
  2809. };
  2810. /**
  2811. * shows the custom attachment
  2812. *
  2813. * @name TopNav.showCustomAttachment
  2814. * @function
  2815. */
  2816. me.showCustomAttachment = function()
  2817. {
  2818. $customAttachment.removeClass('hidden');
  2819. };
  2820. /**
  2821. * collapses the navigation bar, only if expanded
  2822. *
  2823. * @name TopNav.collapseBar
  2824. * @function
  2825. */
  2826. me.collapseBar = function()
  2827. {
  2828. if ($('#navbar').attr('aria-expanded') === 'true') {
  2829. $('.navbar-toggle').click();
  2830. }
  2831. };
  2832. /**
  2833. * returns the currently set expiration time
  2834. *
  2835. * @name TopNav.getExpiration
  2836. * @function
  2837. * @return {int}
  2838. */
  2839. me.getExpiration = function()
  2840. {
  2841. return pasteExpiration;
  2842. };
  2843. /**
  2844. * returns the currently selected file(s)
  2845. *
  2846. * @name TopNav.getFileList
  2847. * @function
  2848. * @return {FileList|null}
  2849. */
  2850. me.getFileList = function()
  2851. {
  2852. var $file = $('#file');
  2853. // if no file given, return null
  2854. if (!$file.length || !$file[0].files.length) {
  2855. return null;
  2856. }
  2857. // ensure the selected file is still accessible
  2858. if (!($file[0].files && $file[0].files[0])) {
  2859. return null;
  2860. }
  2861. return $file[0].files;
  2862. };
  2863. /**
  2864. * returns the state of the burn after reading checkbox
  2865. *
  2866. * @name TopNav.getExpiration
  2867. * @function
  2868. * @return {bool}
  2869. */
  2870. me.getBurnAfterReading = function()
  2871. {
  2872. return $burnAfterReading.is(':checked');
  2873. };
  2874. /**
  2875. * returns the state of the discussion checkbox
  2876. *
  2877. * @name TopNav.getOpenDiscussion
  2878. * @function
  2879. * @return {bool}
  2880. */
  2881. me.getOpenDiscussion = function()
  2882. {
  2883. return $openDiscussion.is(':checked');
  2884. };
  2885. /**
  2886. * returns the entered password
  2887. *
  2888. * @name TopNav.getPassword
  2889. * @function
  2890. * @return {string}
  2891. */
  2892. me.getPassword = function()
  2893. {
  2894. return $passwordInput.val();
  2895. };
  2896. /**
  2897. * returns the element where custom attachments can be placed
  2898. *
  2899. * Used by AttachmentViewer when an attachment is cloned here.
  2900. *
  2901. * @name TopNav.getCustomAttachment
  2902. * @function
  2903. * @return {jQuery}
  2904. */
  2905. me.getCustomAttachment = function()
  2906. {
  2907. return $customAttachment;
  2908. };
  2909. /**
  2910. * Set a function to call when the retry button is clicked.
  2911. *
  2912. * @name TopNav.setRetryCallback
  2913. * @function
  2914. * @param {function} callback
  2915. */
  2916. me.setRetryCallback = function(callback)
  2917. {
  2918. retryButtonCallback = callback;
  2919. }
  2920. /**
  2921. * init navigation manager
  2922. *
  2923. * preloads jQuery elements
  2924. *
  2925. * @name TopNav.init
  2926. * @function
  2927. */
  2928. me.init = function()
  2929. {
  2930. $attach = $('#attach');
  2931. $burnAfterReading = $('#burnafterreading');
  2932. $burnAfterReadingOption = $('#burnafterreadingoption');
  2933. $cloneButton = $('#clonebutton');
  2934. $customAttachment = $('#customattachment');
  2935. $expiration = $('#expiration');
  2936. $fileRemoveButton = $('#fileremovebutton');
  2937. $fileWrap = $('#filewrap');
  2938. $formatter = $('#formatter');
  2939. $newButton = $('#newbutton');
  2940. $openDiscussion = $('#opendiscussion');
  2941. $openDiscussionOption = $('#opendiscussionoption');
  2942. $password = $('#password');
  2943. $passwordInput = $('#passwordinput');
  2944. $rawTextButton = $('#rawtextbutton');
  2945. $retryButton = $('#retrybutton');
  2946. $sendButton = $('#sendbutton');
  2947. $qrCodeLink = $('#qrcodelink');
  2948. // bootstrap template drop down
  2949. $('#language ul.dropdown-menu li a').click(setLanguage);
  2950. // page template drop down
  2951. $('#language select option').click(setLanguage);
  2952. // bind events
  2953. $burnAfterReading.change(changeBurnAfterReading);
  2954. $openDiscussionOption.change(changeOpenDiscussion);
  2955. $newButton.click(clickNewPaste);
  2956. $sendButton.click(PasteEncrypter.sendPaste);
  2957. $cloneButton.click(Controller.clonePaste);
  2958. $rawTextButton.click(rawText);
  2959. $retryButton.click(clickRetryButton);
  2960. $fileRemoveButton.click(removeAttachment);
  2961. $qrCodeLink.click(displayQrCode);
  2962. // bootstrap template drop downs
  2963. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  2964. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  2965. // initiate default state of checkboxes
  2966. changeBurnAfterReading();
  2967. changeOpenDiscussion();
  2968. // get default value from template or fall back to set value
  2969. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  2970. createButtonsDisplayed = false;
  2971. viewButtonsDisplayed = false;
  2972. };
  2973. return me;
  2974. })(window, document);
  2975. /**
  2976. * Responsible for AJAX requests, transparently handles encryption…
  2977. *
  2978. * @name Uploader
  2979. * @class
  2980. */
  2981. var Uploader = (function () {
  2982. var me = {};
  2983. var successFunc = null,
  2984. failureFunc = null,
  2985. url,
  2986. data,
  2987. symmetricKey,
  2988. password;
  2989. /**
  2990. * public variable ('constant') for errors to prevent magic numbers
  2991. *
  2992. * @name Uploader.error
  2993. * @readonly
  2994. * @enum {Object}
  2995. */
  2996. me.error = {
  2997. okay: 0,
  2998. custom: 1,
  2999. unknown: 2,
  3000. serverError: 3
  3001. };
  3002. /**
  3003. * ajaxHeaders to send in AJAX requests
  3004. *
  3005. * @name Uploader.ajaxHeaders
  3006. * @private
  3007. * @readonly
  3008. * @enum {Object}
  3009. */
  3010. var ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  3011. /**
  3012. * called after successful upload
  3013. *
  3014. * @name Uploader.checkCryptParameters
  3015. * @private
  3016. * @function
  3017. * @throws {string}
  3018. */
  3019. function checkCryptParameters()
  3020. {
  3021. // workaround for this nasty 'bug' in ECMAScript
  3022. // see https://stackoverflow.com/questions/18808226/why-is-typeof-null-object
  3023. var typeOfKey = typeof symmetricKey;
  3024. if (symmetricKey === null) {
  3025. typeOfKey = 'null';
  3026. }
  3027. // in case of missing preparation, throw error
  3028. switch (typeOfKey) {
  3029. case 'string':
  3030. // already set, all right
  3031. return;
  3032. case 'null':
  3033. // needs to be generated auto-generate
  3034. symmetricKey = CryptTool.getSymmetricKey();
  3035. break;
  3036. default:
  3037. console.error('current invalid symmetricKey:', symmetricKey);
  3038. throw 'symmetricKey is invalid, probably the module was not prepared';
  3039. }
  3040. // password is optional
  3041. }
  3042. /**
  3043. * called after successful upload
  3044. *
  3045. * @name Uploader.success
  3046. * @private
  3047. * @function
  3048. * @param {int} status
  3049. * @param {int} result - optional
  3050. */
  3051. function success(status, result)
  3052. {
  3053. // add useful data to result
  3054. result.encryptionKey = symmetricKey;
  3055. result.requestData = data;
  3056. if (successFunc !== null) {
  3057. successFunc(status, result);
  3058. }
  3059. }
  3060. /**
  3061. * called after a upload failure
  3062. *
  3063. * @name Uploader.fail
  3064. * @private
  3065. * @function
  3066. * @param {int} status - internal code
  3067. * @param {int} result - original error code
  3068. */
  3069. function fail(status, result)
  3070. {
  3071. if (failureFunc !== null) {
  3072. failureFunc(status, result);
  3073. }
  3074. }
  3075. /**
  3076. * actually uploads the data
  3077. *
  3078. * @name Uploader.run
  3079. * @function
  3080. */
  3081. me.run = function()
  3082. {
  3083. $.ajax({
  3084. type: 'POST',
  3085. url: url,
  3086. data: data,
  3087. dataType: 'json',
  3088. headers: ajaxHeaders,
  3089. success: function(result) {
  3090. if (result.status === 0) {
  3091. success(0, result);
  3092. } else if (result.status === 1) {
  3093. fail(1, result);
  3094. } else {
  3095. fail(2, result);
  3096. }
  3097. }
  3098. })
  3099. .fail(function(jqXHR, textStatus, errorThrown) {
  3100. console.error(textStatus, errorThrown);
  3101. fail(3, jqXHR);
  3102. });
  3103. };
  3104. /**
  3105. * set success function
  3106. *
  3107. * @name Uploader.setUrl
  3108. * @function
  3109. * @param {function} newUrl
  3110. */
  3111. me.setUrl = function(newUrl)
  3112. {
  3113. url = newUrl;
  3114. };
  3115. /**
  3116. * sets the password to use (first value) and optionally also the
  3117. * encryption key (not recommend, it is automatically generated).
  3118. *
  3119. * Note: Call this after prepare() as prepare() resets these values.
  3120. *
  3121. * @name Uploader.setCryptValues
  3122. * @function
  3123. * @param {string} newPassword
  3124. * @param {string} newKey - optional
  3125. */
  3126. me.setCryptParameters = function(newPassword, newKey)
  3127. {
  3128. password = newPassword;
  3129. if (typeof newKey !== 'undefined') {
  3130. symmetricKey = newKey;
  3131. }
  3132. };
  3133. /**
  3134. * set success function
  3135. *
  3136. * @name Uploader.setSuccess
  3137. * @function
  3138. * @param {function} func
  3139. */
  3140. me.setSuccess = function(func)
  3141. {
  3142. successFunc = func;
  3143. };
  3144. /**
  3145. * set failure function
  3146. *
  3147. * @name Uploader.setFailure
  3148. * @function
  3149. * @param {function} func
  3150. */
  3151. me.setFailure = function(func)
  3152. {
  3153. failureFunc = func;
  3154. };
  3155. /**
  3156. * prepares a new upload
  3157. *
  3158. * Call this when doing a new upload to reset any data from potential
  3159. * previous uploads. Must be called before any other method of this
  3160. * module.
  3161. *
  3162. * @name Uploader.prepare
  3163. * @function
  3164. * @return {object}
  3165. */
  3166. me.prepare = function()
  3167. {
  3168. // entropy should already be checked!
  3169. // reset password
  3170. password = '';
  3171. // reset key, so it a new one is generated when it is used
  3172. symmetricKey = null;
  3173. // reset data
  3174. successFunc = null;
  3175. failureFunc = null;
  3176. url = Helper.baseUri();
  3177. data = {};
  3178. };
  3179. /**
  3180. * encrypts and sets the data
  3181. *
  3182. * @name Uploader.setData
  3183. * @function
  3184. * @param {string} index
  3185. * @param {mixed} element
  3186. */
  3187. me.setData = function(index, element)
  3188. {
  3189. checkCryptParameters();
  3190. data[index] = CryptTool.cipher(symmetricKey, password, element);
  3191. };
  3192. /**
  3193. * set the additional metadata to send unencrypted
  3194. *
  3195. * @name Uploader.setUnencryptedData
  3196. * @function
  3197. * @param {string} index
  3198. * @param {mixed} element
  3199. */
  3200. me.setUnencryptedData = function(index, element)
  3201. {
  3202. data[index] = element;
  3203. };
  3204. /**
  3205. * set the additional metadata to send unencrypted passed at once
  3206. *
  3207. * @name Uploader.setUnencryptedData
  3208. * @function
  3209. * @param {object} newData
  3210. */
  3211. me.setUnencryptedBulkData = function(newData)
  3212. {
  3213. $.extend(data, newData);
  3214. };
  3215. /**
  3216. * Helper, which parses shows a general error message based on the result of the Uploader
  3217. *
  3218. * @name Uploader.parseUploadError
  3219. * @function
  3220. * @param {int} status
  3221. * @param {object} data
  3222. * @param {string} doThisThing - a human description of the action, which was tried
  3223. * @return {array}
  3224. */
  3225. me.parseUploadError = function(status, data, doThisThing) {
  3226. var errorArray;
  3227. switch (status) {
  3228. case me.error.custom:
  3229. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  3230. break;
  3231. case me.error.unknown:
  3232. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  3233. break;
  3234. case me.error.serverError:
  3235. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  3236. break;
  3237. default:
  3238. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  3239. break;
  3240. }
  3241. return errorArray;
  3242. };
  3243. /**
  3244. * init Uploader
  3245. *
  3246. * @name Uploader.init
  3247. * @function
  3248. */
  3249. me.init = function()
  3250. {
  3251. // nothing yet
  3252. };
  3253. return me;
  3254. })();
  3255. /**
  3256. * (controller) Responsible for encrypting paste and sending it to server.
  3257. *
  3258. * Does upload, encryption is done transparently by Uploader.
  3259. *
  3260. * @name PasteEncrypter
  3261. * @class
  3262. */
  3263. var PasteEncrypter = (function () {
  3264. var me = {};
  3265. var requirementsChecked = false;
  3266. /**
  3267. * checks whether there is a suitable amount of entrophy
  3268. *
  3269. * @name PasteEncrypter.checkRequirements
  3270. * @private
  3271. * @function
  3272. * @param {function} retryCallback - the callback to execute to retry the upload
  3273. * @return {bool}
  3274. */
  3275. function checkRequirements(retryCallback) {
  3276. // skip double requirement checks
  3277. if (requirementsChecked === true) {
  3278. return true;
  3279. }
  3280. if (!CryptTool.isEntropyReady()) {
  3281. // display a message and wait
  3282. Alert.showStatus('Please move your mouse for more entropy…');
  3283. CryptTool.addEntropySeedListener(retryCallback);
  3284. return false;
  3285. }
  3286. requirementsChecked = true;
  3287. return true;
  3288. }
  3289. /**
  3290. * called after successful paste upload
  3291. *
  3292. * @name PasteEncrypter.showCreatedPaste
  3293. * @private
  3294. * @function
  3295. * @param {int} status
  3296. * @param {object} data
  3297. */
  3298. function showCreatedPaste(status, data) {
  3299. Alert.hideLoading();
  3300. var url = Helper.baseUri() + '?' + data.id + '#' + data.encryptionKey,
  3301. deleteUrl = Helper.baseUri() + '?pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  3302. Alert.hideMessages();
  3303. // show notification
  3304. PasteStatus.createPasteNotification(url, deleteUrl);
  3305. // show new URL in browser bar
  3306. history.pushState({type: 'newpaste'}, document.title, url);
  3307. TopNav.showViewButtons();
  3308. TopNav.hideRawButton();
  3309. Editor.hide();
  3310. // parse and show text
  3311. // (preparation already done in me.sendPaste())
  3312. PasteViewer.run();
  3313. }
  3314. /**
  3315. * called after successful comment upload
  3316. *
  3317. * @name PasteEncrypter.showUploadedComment
  3318. * @private
  3319. * @function
  3320. * @param {int} status
  3321. * @param {object} data
  3322. */
  3323. function showUploadedComment(status, data) {
  3324. // show success message
  3325. Alert.showStatus('Comment posted.');
  3326. // reload paste
  3327. Controller.refreshPaste(function () {
  3328. // highlight sent comment
  3329. DiscussionViewer.highlightComment(data.id, true);
  3330. // reset error handler
  3331. Alert.setCustomHandler(null);
  3332. });
  3333. }
  3334. /**
  3335. * adds attachments to the Uploader
  3336. *
  3337. * @name PasteEncrypter.encryptAttachments
  3338. * @private
  3339. * @function
  3340. * @param {function} callback - excuted when action is successful
  3341. */
  3342. function encryptAttachments(callback) {
  3343. var file = AttachmentViewer.getAttachmentData();
  3344. if (typeof file !== 'undefined' && file !== null) {
  3345. var fileName = AttachmentViewer.getFile().name;
  3346. Uploader.setData('attachment', file);
  3347. Uploader.setData('attachmentname', fileName);
  3348. // run callback
  3349. return callback();
  3350. } else if (AttachmentViewer.hasAttachment()) {
  3351. // fall back to cloned part
  3352. var attachment = AttachmentViewer.getAttachment();
  3353. Uploader.setData('attachment', attachment[0]);
  3354. Uploader.setData('attachmentname', attachment[1]);
  3355. return callback();
  3356. } else {
  3357. // if there are no attachments, this is of course still successful
  3358. return callback();
  3359. }
  3360. }
  3361. /**
  3362. * send a reply in a discussion
  3363. *
  3364. * @name PasteEncrypter.sendComment
  3365. * @function
  3366. */
  3367. me.sendComment = function()
  3368. {
  3369. Alert.hideMessages();
  3370. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3371. // UI loading state
  3372. TopNav.hideAllButtons();
  3373. Alert.showLoading('Sending comment…', 'cloud-upload');
  3374. // get data
  3375. var plainText = DiscussionViewer.getReplyMessage(),
  3376. nickname = DiscussionViewer.getReplyNickname(),
  3377. parentid = DiscussionViewer.getReplyCommentId();
  3378. // do not send if there is no data
  3379. if (plainText.length === 0) {
  3380. // revert loading status…
  3381. Alert.hideLoading();
  3382. Alert.setCustomHandler(null);
  3383. TopNav.showViewButtons();
  3384. return;
  3385. }
  3386. // check entropy
  3387. if (!checkRequirements(function () {
  3388. me.sendComment();
  3389. })) {
  3390. return; // to prevent multiple executions
  3391. }
  3392. // prepare Uploader
  3393. Uploader.prepare();
  3394. Uploader.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3395. // set success/fail functions
  3396. Uploader.setSuccess(showUploadedComment);
  3397. Uploader.setFailure(function (status, data) {
  3398. // revert loading status…
  3399. Alert.hideLoading();
  3400. TopNav.showViewButtons();
  3401. // show error message
  3402. Alert.showError(
  3403. Uploader.parseUploadError(status, data, 'post comment')
  3404. );
  3405. // reset error handler
  3406. Alert.setCustomHandler(null);
  3407. });
  3408. // fill it with unencrypted params
  3409. Uploader.setUnencryptedData('pasteid', Model.getPasteId());
  3410. if (typeof parentid === 'undefined') {
  3411. // if parent id is not set, this is the top-most comment, so use
  3412. // paste id as parent, as the root element of the discussion tree
  3413. Uploader.setUnencryptedData('parentid', Model.getPasteId());
  3414. } else {
  3415. Uploader.setUnencryptedData('parentid', parentid);
  3416. }
  3417. // encrypt data
  3418. Uploader.setData('data', plainText);
  3419. if (nickname.length > 0) {
  3420. Uploader.setData('nickname', nickname);
  3421. }
  3422. Uploader.run();
  3423. };
  3424. /**
  3425. * sends a new paste to server
  3426. *
  3427. * @name PasteEncrypter.sendPaste
  3428. * @function
  3429. */
  3430. me.sendPaste = function()
  3431. {
  3432. // hide previous (error) messages
  3433. Controller.hideStatusMessages();
  3434. // UI loading state
  3435. TopNav.hideAllButtons();
  3436. Alert.showLoading('Sending paste…', 'cloud-upload');
  3437. TopNav.collapseBar();
  3438. // get data
  3439. var plainText = Editor.getText(),
  3440. format = PasteViewer.getFormat(),
  3441. // the methods may return different values if no files are attached (null, undefined or false)
  3442. files = TopNav.getFileList() || AttachmentViewer.getFile() || AttachmentViewer.hasAttachment();
  3443. // do not send if there is no data
  3444. if (plainText.length === 0 && !files) {
  3445. // revert loading status…
  3446. Alert.hideLoading();
  3447. TopNav.showCreateButtons();
  3448. return;
  3449. }
  3450. // check entropy
  3451. if (!checkRequirements(function () {
  3452. me.sendPaste();
  3453. })) {
  3454. return; // to prevent multiple executions
  3455. }
  3456. // prepare Uploader
  3457. Uploader.prepare();
  3458. Uploader.setCryptParameters(TopNav.getPassword());
  3459. // set success/fail functions
  3460. Uploader.setSuccess(showCreatedPaste);
  3461. Uploader.setFailure(function (status, data) {
  3462. // revert loading status…
  3463. Alert.hideLoading();
  3464. TopNav.showCreateButtons();
  3465. // show error message
  3466. Alert.showError(
  3467. Uploader.parseUploadError(status, data, 'create paste')
  3468. );
  3469. });
  3470. // fill it with unencrypted submitted options
  3471. Uploader.setUnencryptedBulkData({
  3472. expire: TopNav.getExpiration(),
  3473. formatter: format,
  3474. burnafterreading: TopNav.getBurnAfterReading() ? 1 : 0,
  3475. opendiscussion: TopNav.getOpenDiscussion() ? 1 : 0
  3476. });
  3477. // prepare PasteViewer for later preview
  3478. PasteViewer.setText(plainText);
  3479. PasteViewer.setFormat(format);
  3480. // encrypt cipher data
  3481. Uploader.setData('data', plainText);
  3482. // encrypt attachments
  3483. encryptAttachments(
  3484. function () {
  3485. // send data
  3486. Uploader.run();
  3487. }
  3488. );
  3489. };
  3490. /**
  3491. * initialize
  3492. *
  3493. * @name PasteEncrypter.init
  3494. * @function
  3495. */
  3496. me.init = function()
  3497. {
  3498. // nothing yet
  3499. };
  3500. return me;
  3501. })();
  3502. /**
  3503. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3504. *
  3505. * Only decryption, no download.
  3506. *
  3507. * @name PasteDecrypter
  3508. * @class
  3509. */
  3510. var PasteDecrypter = (function () {
  3511. var me = {};
  3512. /**
  3513. * decrypt data or prompts for password in case of failure
  3514. *
  3515. * @name PasteDecrypter.decryptOrPromptPassword
  3516. * @private
  3517. * @function
  3518. * @param {string} key
  3519. * @param {string} password - optional, may be an empty string
  3520. * @param {string} cipherdata
  3521. * @throws {string}
  3522. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3523. */
  3524. function decryptOrPromptPassword(key, password, cipherdata)
  3525. {
  3526. // try decryption without password
  3527. var plaindata = CryptTool.decipher(key, password, cipherdata);
  3528. // if it fails, request password
  3529. if (plaindata.length === 0 && password.length === 0) {
  3530. // show prompt
  3531. Prompt.requestPassword();
  3532. // if password is there instantly (legacy method), re-try encryption
  3533. if (Prompt.getPassword().length !== 0) {
  3534. // recursive
  3535. // note: an infinite loop is prevented as the previous if
  3536. // clause checks whether a password is already set and ignores
  3537. // errors when a password has been passed
  3538. return decryptOrPromptPassword(key, password, cipherdata);
  3539. }
  3540. // if password could not be received yet, the new modal is used,
  3541. // which uses asyncronous event-driven methods to get the password.
  3542. // Thus, we cannot do anything yet, we need to wait for the user
  3543. // input.
  3544. return false;
  3545. }
  3546. // if all tries failed, we can only return an error
  3547. if (plaindata.length === 0) {
  3548. throw 'failed to decipher data';
  3549. }
  3550. return plaindata;
  3551. }
  3552. /**
  3553. * decrypt the actual paste text
  3554. *
  3555. * @name PasteDecrypter.decryptPaste
  3556. * @private
  3557. * @function
  3558. * @param {object} paste - paste data in object form
  3559. * @param {string} key
  3560. * @param {string} password
  3561. * @param {bool} ignoreError - ignore decryption errors iof set to true
  3562. * @return {bool} whether action was successful
  3563. * @throws {string}
  3564. */
  3565. function decryptPaste(paste, key, password, ignoreError)
  3566. {
  3567. var plaintext;
  3568. if (ignoreError === true) {
  3569. plaintext = CryptTool.decipher(key, password, paste.data);
  3570. } else {
  3571. try {
  3572. plaintext = decryptOrPromptPassword(key, password, paste.data);
  3573. } catch (err) {
  3574. throw 'failed to decipher paste text: ' + err;
  3575. }
  3576. if (plaintext === false) {
  3577. return false;
  3578. }
  3579. }
  3580. // on success show paste
  3581. PasteViewer.setFormat(paste.meta.formatter);
  3582. PasteViewer.setText(plaintext);
  3583. // trigger to show the text (attachment loaded afterwards)
  3584. PasteViewer.run();
  3585. return true;
  3586. }
  3587. /**
  3588. * decrypts any attachment
  3589. *
  3590. * @name PasteDecrypter.decryptAttachment
  3591. * @private
  3592. * @function
  3593. * @param {object} paste - paste data in object form
  3594. * @param {string} key
  3595. * @param {string} password
  3596. * @return {bool} whether action was successful
  3597. * @throws {string}
  3598. */
  3599. function decryptAttachment(paste, key, password)
  3600. {
  3601. var attachment, attachmentName;
  3602. // decrypt attachment
  3603. try {
  3604. attachment = decryptOrPromptPassword(key, password, paste.attachment);
  3605. } catch (err) {
  3606. throw 'failed to decipher attachment: ' + err;
  3607. }
  3608. if (attachment === false) {
  3609. return false;
  3610. }
  3611. // decrypt attachment name
  3612. if (paste.attachmentname) {
  3613. try {
  3614. attachmentName = decryptOrPromptPassword(key, password, paste.attachmentname);
  3615. } catch (err) {
  3616. throw 'failed to decipher attachment name: ' + err;
  3617. }
  3618. if (attachmentName === false) {
  3619. return false;
  3620. }
  3621. }
  3622. AttachmentViewer.setAttachment(attachment, attachmentName);
  3623. AttachmentViewer.showAttachment();
  3624. return true;
  3625. }
  3626. /**
  3627. * decrypts all comments and shows them
  3628. *
  3629. * @name PasteDecrypter.decryptComments
  3630. * @private
  3631. * @function
  3632. * @param {object} paste - paste data in object form
  3633. * @param {string} key
  3634. * @param {string} password
  3635. * @return {bool} whether action was successful
  3636. */
  3637. function decryptComments(paste, key, password)
  3638. {
  3639. // remove potentially previous discussion
  3640. DiscussionViewer.prepareNewDiscussion();
  3641. // iterate over comments
  3642. for (var i = 0; i < paste.comments.length; ++i) {
  3643. var comment = paste.comments[i];
  3644. DiscussionViewer.addComment(
  3645. comment,
  3646. CryptTool.decipher(key, password, comment.data),
  3647. CryptTool.decipher(key, password, comment.meta.nickname)
  3648. );
  3649. }
  3650. DiscussionViewer.finishDiscussion();
  3651. return true;
  3652. }
  3653. /**
  3654. * show decrypted text in the display area, including discussion (if open)
  3655. *
  3656. * @name PasteDecrypter.run
  3657. * @function
  3658. * @param {Object} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  3659. */
  3660. me.run = function(paste)
  3661. {
  3662. Alert.hideMessages();
  3663. Alert.showLoading('Decrypting paste…', 'cloud-download');
  3664. if (typeof paste === 'undefined') {
  3665. // get cipher data and wait until it is available
  3666. Model.getPasteData(me.run);
  3667. return;
  3668. }
  3669. var key = Model.getPasteKey(),
  3670. password = Prompt.getPassword();
  3671. if (PasteViewer.isPrettyPrinted()) {
  3672. // don't decrypt twice
  3673. return;
  3674. }
  3675. // try to decrypt the paste
  3676. try {
  3677. // decrypt attachments
  3678. if (paste.attachment) {
  3679. if (AttachmentViewer.hasAttachmentData()) {
  3680. // try to decrypt paste and if it fails (because the password is
  3681. // missing) return to let JS continue and wait for user
  3682. if (!decryptAttachment(paste, key, password)) {
  3683. return;
  3684. }
  3685. }
  3686. // ignore empty paste, as this is allowed when pasting attachments
  3687. decryptPaste(paste, key, password, true);
  3688. } else {
  3689. if (decryptPaste(paste, key, password) === false) {
  3690. return false;
  3691. }
  3692. }
  3693. // shows the remaining time (until) deletion
  3694. PasteStatus.showRemainingTime(paste.meta);
  3695. // if the discussion is opened on this paste, display it
  3696. if (paste.meta.opendiscussion) {
  3697. decryptComments(paste, key, password);
  3698. }
  3699. Alert.hideLoading();
  3700. TopNav.showViewButtons();
  3701. } catch(err) {
  3702. Alert.hideLoading();
  3703. // log and show error
  3704. console.error(err);
  3705. Alert.showError('Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.');
  3706. // reset password, so it can be re-entered and sow retry button
  3707. Prompt.reset();
  3708. TopNav.setRetryCallback(function () {
  3709. TopNav.hideRetryButton();
  3710. me.run(paste);
  3711. });
  3712. TopNav.showRetryButton();
  3713. }
  3714. };
  3715. /**
  3716. * initialize
  3717. *
  3718. * @name PasteDecrypter.init
  3719. * @function
  3720. */
  3721. me.init = function()
  3722. {
  3723. // nothing yet
  3724. };
  3725. return me;
  3726. })();
  3727. /**
  3728. * (controller) main PrivateBin logic
  3729. *
  3730. * @name Controller
  3731. * @param {object} window
  3732. * @param {object} document
  3733. * @class
  3734. */
  3735. var Controller = (function (window, document) {
  3736. var me = {};
  3737. /**
  3738. * hides all status messages no matter which module showed them
  3739. *
  3740. * @name Controller.hideStatusMessages
  3741. * @function
  3742. */
  3743. me.hideStatusMessages = function()
  3744. {
  3745. PasteStatus.hideMessages();
  3746. Alert.hideMessages();
  3747. };
  3748. /**
  3749. * creates a new paste
  3750. *
  3751. * @name Controller.newPaste
  3752. * @function
  3753. */
  3754. me.newPaste = function()
  3755. {
  3756. // Important: This *must not* run Alert.hideMessages() as previous
  3757. // errors from viewing a paste should be shown.
  3758. TopNav.hideAllButtons();
  3759. Alert.showLoading('Preparing new paste…', 'time');
  3760. PasteStatus.hideMessages();
  3761. PasteViewer.hide();
  3762. Editor.resetInput();
  3763. Editor.show();
  3764. Editor.focusInput();
  3765. AttachmentViewer.removeAttachment();
  3766. TopNav.showCreateButtons();
  3767. Alert.hideLoading();
  3768. };
  3769. /**
  3770. * shows how we much we love bots that execute JS ;)
  3771. *
  3772. * @name Controller.showBadBotMessage
  3773. * @function
  3774. */
  3775. me.showBadBotMessage = function()
  3776. {
  3777. TopNav.hideAllButtons();
  3778. Alert.showError('I love you too, bot…');
  3779. }
  3780. /**
  3781. * shows the loaded paste
  3782. *
  3783. * @name Controller.showPaste
  3784. * @function
  3785. */
  3786. me.showPaste = function()
  3787. {
  3788. try {
  3789. Model.getPasteKey();
  3790. } catch (err) {
  3791. console.error(err);
  3792. // missing decryption key (or paste ID) in URL?
  3793. if (window.location.hash.length === 0) {
  3794. 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?)');
  3795. return;
  3796. }
  3797. }
  3798. // show proper elements on screen
  3799. PasteDecrypter.run();
  3800. };
  3801. /**
  3802. * refreshes the loaded paste to show potential new data
  3803. *
  3804. * @name Controller.refreshPaste
  3805. * @function
  3806. * @param {function} callback
  3807. */
  3808. me.refreshPaste = function(callback)
  3809. {
  3810. // save window position to restore it later
  3811. var orgPosition = $(window).scrollTop();
  3812. Model.getPasteData(function (data) {
  3813. Uploader.prepare();
  3814. Uploader.setUrl(Helper.baseUri() + '?' + Model.getPasteId());
  3815. Uploader.setFailure(function (status, data) {
  3816. // revert loading status…
  3817. Alert.hideLoading();
  3818. TopNav.showViewButtons();
  3819. // show error message
  3820. Alert.showError(
  3821. Uploader.parseUploadError(status, data, 'refresh display')
  3822. );
  3823. });
  3824. Uploader.setSuccess(function (status, data) {
  3825. PasteDecrypter.run(data);
  3826. // restore position
  3827. window.scrollTo(0, orgPosition);
  3828. PasteDecrypter.run(data);
  3829. // NOTE: could create problems as callback may be called
  3830. // asyncronously if PasteDecrypter e.g. needs to wait for a
  3831. // password being entered
  3832. callback();
  3833. });
  3834. Uploader.run();
  3835. }, false); // this false is important as it circumvents the cache
  3836. }
  3837. /**
  3838. * clone the current paste
  3839. *
  3840. * @name Controller.clonePaste
  3841. * @function
  3842. */
  3843. me.clonePaste = function()
  3844. {
  3845. TopNav.collapseBar();
  3846. TopNav.hideAllButtons();
  3847. Alert.showLoading('Cloning paste…', 'transfer');
  3848. // hide messages from previous paste
  3849. me.hideStatusMessages();
  3850. // erase the id and the key in url
  3851. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  3852. if (AttachmentViewer.hasAttachment()) {
  3853. AttachmentViewer.moveAttachmentTo(
  3854. TopNav.getCustomAttachment(),
  3855. 'Cloned: \'%s\''
  3856. );
  3857. TopNav.hideFileSelector();
  3858. AttachmentViewer.hideAttachment();
  3859. // NOTE: it also looks nice without removing the attachment
  3860. // but for a consistent display we remove it…
  3861. AttachmentViewer.hideAttachmentPreview();
  3862. TopNav.showCustomAttachment();
  3863. // show another status message to make the user aware that the
  3864. // file was cloned too!
  3865. Alert.showStatus(
  3866. [
  3867. 'The cloned file \'%s\' was attached to this paste.',
  3868. AttachmentViewer.getAttachment()[1]
  3869. ],
  3870. 'copy'
  3871. );
  3872. }
  3873. Editor.setText(PasteViewer.getText());
  3874. PasteViewer.hide();
  3875. Editor.show();
  3876. Alert.hideLoading();
  3877. TopNav.showCreateButtons();
  3878. };
  3879. /**
  3880. * removes a saved paste
  3881. *
  3882. * @name Controller.removePaste
  3883. * @function
  3884. * @param {string} pasteId
  3885. * @param {string} deleteToken
  3886. * @deprecated not used anymore, de we still need it?
  3887. */
  3888. me.removePaste = function(pasteId, deleteToken) {
  3889. // unfortunately many web servers don't support DELETE (and PUT) out of the box
  3890. // so we use a POST request
  3891. Uploader.prepare();
  3892. Uploader.setUrl(Helper.baseUri() + '?' + pasteId);
  3893. Uploader.setUnencryptedData('deletetoken', deleteToken);
  3894. Uploader.setFailure(function () {
  3895. Alert.showError(
  3896. I18n._('Could not delete the paste, it was not stored in burn after reading mode.')
  3897. );
  3898. });
  3899. Uploader.run();
  3900. };
  3901. /**
  3902. * application start
  3903. *
  3904. * @name Controller.init
  3905. * @function
  3906. */
  3907. me.init = function()
  3908. {
  3909. // first load translations
  3910. I18n.loadTranslations();
  3911. DOMPurify.setConfig({SAFE_FOR_JQUERY: true});
  3912. // initialize other modules/"classes"
  3913. Alert.init();
  3914. Model.init();
  3915. AttachmentViewer.init();
  3916. DiscussionViewer.init();
  3917. Editor.init();
  3918. PasteDecrypter.init();
  3919. PasteEncrypter.init();
  3920. PasteStatus.init();
  3921. PasteViewer.init();
  3922. Prompt.init();
  3923. TopNav.init();
  3924. UiHelper.init();
  3925. Uploader.init();
  3926. // check whether existing paste needs to be shown
  3927. try {
  3928. Model.getPasteId();
  3929. } catch (e) {
  3930. // otherwise create a new paste
  3931. return me.newPaste();
  3932. }
  3933. // if delete token is passed (i.e. paste has been deleted by this access)
  3934. // there is no more stuf we need to do
  3935. if (Model.hasDeleteToken()) {
  3936. return;
  3937. }
  3938. // prevent bots from viewing a paste and potentially deleting data
  3939. // when burn-after-reading is set
  3940. // see https://github.com/elrido/ZeroBin/issues/11
  3941. if (Helper.isBadBot()) {
  3942. return me.showBadBotMessage();
  3943. }
  3944. // display an existing paste
  3945. return me.showPaste();
  3946. }
  3947. return me;
  3948. })(window, document);
  3949. return {
  3950. Helper: Helper,
  3951. I18n: I18n,
  3952. CryptTool: CryptTool,
  3953. Model: Model,
  3954. UiHelper: UiHelper,
  3955. Alert: Alert,
  3956. PasteStatus: PasteStatus,
  3957. Prompt: Prompt,
  3958. Editor: Editor,
  3959. PasteViewer: PasteViewer,
  3960. AttachmentViewer: AttachmentViewer,
  3961. DiscussionViewer: DiscussionViewer,
  3962. TopNav: TopNav,
  3963. Uploader: Uploader,
  3964. PasteEncrypter: PasteEncrypter,
  3965. PasteDecrypter: PasteDecrypter,
  3966. Controller: Controller
  3967. };
  3968. })(jQuery, sjcl, Base64, RawDeflate);