privatebin.js 142 KB

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