privatebin.js 134 KB

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