privatebin.js 179 KB

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