privatebin.js 166 KB

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