privatebin.js 178 KB

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