privatebin.js 132 KB

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