privatebin.js 178 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656
  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.1
  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, due to missing WebAssembly support.'
  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, due to missing WebAssembly support.'
  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 attachment input in the top navigation.
  3427. *
  3428. * @name TopNav.clearAttachmentInput
  3429. * @function
  3430. */
  3431. function clearAttachmentInput()
  3432. {
  3433. // hide UI for selected files
  3434. // our up-to-date jQuery can handle it :)
  3435. $fileWrap.find('input').val('');
  3436. }
  3437. /**
  3438. * return raw text
  3439. *
  3440. * @name TopNav.rawText
  3441. * @private
  3442. * @function
  3443. */
  3444. function rawText()
  3445. {
  3446. TopNav.hideAllButtons();
  3447. Alert.showLoading('Showing raw text…', 'time');
  3448. let paste = PasteViewer.getText();
  3449. // push a new state to allow back navigation with browser back button
  3450. history.pushState(
  3451. {type: 'raw'},
  3452. document.title,
  3453. // recreate paste URL
  3454. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3455. CryptTool.base58encode(Model.getPasteKey())
  3456. );
  3457. // we use text/html instead of text/plain to avoid a bug when
  3458. // reloading the raw text view (it reverts to type text/html)
  3459. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3460. newDoc = document.open('text/html', 'replace');
  3461. newDoc.write('<!DOCTYPE html><html><head>');
  3462. for (let i = 0; i < $head.length; ++i) {
  3463. newDoc.write($head[i].outerHTML);
  3464. }
  3465. newDoc.write(
  3466. '</head><body><pre>' +
  3467. DOMPurify.sanitize(
  3468. Helper.htmlEntities(paste),
  3469. purifyHtmlConfig
  3470. ) +
  3471. '</pre></body></html>'
  3472. );
  3473. newDoc.close();
  3474. }
  3475. /**
  3476. * download text
  3477. *
  3478. * @name TopNav.downloadText
  3479. * @private
  3480. * @function
  3481. */
  3482. function downloadText()
  3483. {
  3484. var filename='paste-' + Model.getPasteId() + '.txt';
  3485. var text = PasteViewer.getText();
  3486. var element = document.createElement('a');
  3487. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3488. element.setAttribute('download', filename);
  3489. element.style.display = 'none';
  3490. document.body.appendChild(element);
  3491. element.click();
  3492. document.body.removeChild(element);
  3493. }
  3494. /**
  3495. * saves the language in a cookie and reloads the page
  3496. *
  3497. * @name TopNav.setLanguage
  3498. * @private
  3499. * @function
  3500. * @param {Event} event
  3501. */
  3502. function setLanguage(event)
  3503. {
  3504. document.cookie = 'lang=' + $(event.target).data('lang') + '; SameSite=Lax; Secure';
  3505. UiHelper.reloadHome();
  3506. event.preventDefault();
  3507. }
  3508. /**
  3509. * hides all messages and creates a new paste
  3510. *
  3511. * @name TopNav.clickNewPaste
  3512. * @private
  3513. * @function
  3514. */
  3515. function clickNewPaste()
  3516. {
  3517. Controller.hideStatusMessages();
  3518. Controller.newPaste();
  3519. }
  3520. /**
  3521. * retrys some callback registered before
  3522. *
  3523. * @name TopNav.clickRetryButton
  3524. * @private
  3525. * @function
  3526. * @param {Event} event
  3527. */
  3528. function clickRetryButton(event)
  3529. {
  3530. retryButtonCallback(event);
  3531. }
  3532. /**
  3533. * removes the existing attachment
  3534. *
  3535. * @name TopNav.removeAttachment
  3536. * @private
  3537. * @function
  3538. * @param {Event} event
  3539. */
  3540. function removeAttachment(event)
  3541. {
  3542. // if custom attachment is used, remove it first
  3543. if (!$customAttachment.hasClass('hidden')) {
  3544. AttachmentViewer.removeAttachment();
  3545. $customAttachment.addClass('hidden');
  3546. $fileWrap.removeClass('hidden');
  3547. }
  3548. // in any case, remove saved attachment data
  3549. AttachmentViewer.removeAttachmentData();
  3550. clearAttachmentInput();
  3551. AttachmentViewer.clearDragAndDrop();
  3552. // pevent '#' from appearing in the URL
  3553. event.preventDefault();
  3554. }
  3555. /**
  3556. * Shows the QR code of the current paste (URL).
  3557. *
  3558. * @name TopNav.displayQrCode
  3559. * @private
  3560. * @function
  3561. */
  3562. function displayQrCode()
  3563. {
  3564. const qrCanvas = kjua({
  3565. render: 'canvas',
  3566. text: window.location.href
  3567. });
  3568. $('#qrcode-display').html(qrCanvas);
  3569. // only necessary for bootstrap 5, other templates won't have this
  3570. if (bootstrap.Tooltip.VERSION) {
  3571. $('#qrcodemodal').modal('show');
  3572. }
  3573. }
  3574. /**
  3575. * Template Email body.
  3576. *
  3577. * @name TopNav.templateEmailBody
  3578. * @private
  3579. * @param {string} expirationDateString
  3580. * @param {bool} isBurnafterreading
  3581. */
  3582. function templateEmailBody(expirationDateString, isBurnafterreading)
  3583. {
  3584. const EOL = '\n';
  3585. const BULLET = ' - ';
  3586. let emailBody = '';
  3587. if (expirationDateString !== null || isBurnafterreading) {
  3588. emailBody += I18n._('Notice:');
  3589. emailBody += EOL;
  3590. if (expirationDateString !== null) {
  3591. emailBody += EOL;
  3592. emailBody += BULLET;
  3593. // avoid DOMPurify mess with forward slash in expirationDateString
  3594. emailBody += Helper.sprintf(
  3595. I18n._(
  3596. 'This link will expire after %s.',
  3597. '%s'
  3598. ),
  3599. expirationDateString
  3600. );
  3601. }
  3602. if (isBurnafterreading) {
  3603. emailBody += EOL;
  3604. emailBody += BULLET;
  3605. emailBody += I18n._(
  3606. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3607. );
  3608. }
  3609. emailBody += EOL;
  3610. emailBody += EOL;
  3611. }
  3612. emailBody += I18n._('Link:');
  3613. emailBody += EOL;
  3614. emailBody += $('#pasteurl').attr('href'); // might have been shortened
  3615. return emailBody;
  3616. }
  3617. /**
  3618. * Trigger Email send.
  3619. *
  3620. * @name TopNav.triggerEmailSend
  3621. * @private
  3622. * @param {string} emailBody
  3623. */
  3624. function triggerEmailSend(emailBody)
  3625. {
  3626. window.open(
  3627. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3628. '_self',
  3629. 'noopener, noreferrer'
  3630. );
  3631. }
  3632. /**
  3633. * Send Email with current paste (URL).
  3634. *
  3635. * @name TopNav.sendEmail
  3636. * @private
  3637. * @function
  3638. * @param {Date|null} expirationDate date of expiration
  3639. * @param {bool} isBurnafterreading whether it is burn after reading
  3640. */
  3641. function sendEmail(expirationDate, isBurnafterreading)
  3642. {
  3643. const expirationDateRoundedToSecond = new Date(expirationDate);
  3644. // round down at least 30 seconds to make up for the delay of request
  3645. expirationDateRoundedToSecond.setUTCSeconds(
  3646. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3647. );
  3648. expirationDateRoundedToSecond.setUTCSeconds(0);
  3649. const $emailconfirmmodal = $('#emailconfirmmodal');
  3650. if ($emailconfirmmodal.length > 0) {
  3651. if (expirationDate !== null) {
  3652. const $emailconfirmTimezoneCurrent = $emailconfirmmodal.find('#emailconfirm-timezone-current');
  3653. const $emailconfirmTimezoneUtc = $emailconfirmmodal.find('#emailconfirm-timezone-utc');
  3654. $emailconfirmTimezoneCurrent.off('click.sendEmailCurrentTimezone');
  3655. $emailconfirmTimezoneCurrent.on('click.sendEmailCurrentTimezone', () => {
  3656. const emailBody = templateEmailBody(expirationDateRoundedToSecond.toLocaleString(), isBurnafterreading);
  3657. $emailconfirmmodal.modal('hide');
  3658. triggerEmailSend(emailBody);
  3659. });
  3660. $emailconfirmTimezoneUtc.off('click.sendEmailUtcTimezone');
  3661. $emailconfirmTimezoneUtc.on('click.sendEmailUtcTimezone', () => {
  3662. const emailBody = templateEmailBody(expirationDateRoundedToSecond.toLocaleString(
  3663. undefined,
  3664. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3665. { timeZone: 'UTC', dateStyle: 'long', timeStyle: 'long' }
  3666. ), isBurnafterreading);
  3667. $emailconfirmmodal.modal('hide');
  3668. triggerEmailSend(emailBody);
  3669. });
  3670. $emailconfirmmodal.modal('show');
  3671. } else {
  3672. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3673. }
  3674. } else {
  3675. let emailBody = '';
  3676. if (expirationDate !== null) {
  3677. const expirationDateString = window.confirm(
  3678. I18n._('Recipient may become aware of your timezone, convert time to UTC?')
  3679. ) ? expirationDateRoundedToSecond.toLocaleString(
  3680. undefined,
  3681. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3682. { timeZone: 'UTC', dateStyle: 'long', timeStyle: 'long' }
  3683. ) : expirationDateRoundedToSecond.toLocaleString();
  3684. emailBody = templateEmailBody(expirationDateString, isBurnafterreading);
  3685. } else {
  3686. emailBody = templateEmailBody(null, isBurnafterreading);
  3687. }
  3688. triggerEmailSend(emailBody);
  3689. }
  3690. }
  3691. /**
  3692. * Shows all navigation elements for viewing an existing paste
  3693. *
  3694. * @name TopNav.showViewButtons
  3695. * @function
  3696. */
  3697. me.showViewButtons = function()
  3698. {
  3699. if (viewButtonsDisplayed) {
  3700. return;
  3701. }
  3702. $newButton.removeClass('hidden');
  3703. $cloneButton.removeClass('hidden');
  3704. $rawTextButton.removeClass('hidden');
  3705. $downloadTextButton.removeClass('hidden');
  3706. $qrCodeLink.removeClass('hidden');
  3707. viewButtonsDisplayed = true;
  3708. };
  3709. /**
  3710. * Hides all navigation elements for viewing an existing paste
  3711. *
  3712. * @name TopNav.hideViewButtons
  3713. * @function
  3714. */
  3715. me.hideViewButtons = function()
  3716. {
  3717. if (!viewButtonsDisplayed) {
  3718. return;
  3719. }
  3720. $cloneButton.addClass('hidden');
  3721. $newButton.addClass('hidden');
  3722. $rawTextButton.addClass('hidden');
  3723. $downloadTextButton.addClass('hidden');
  3724. $qrCodeLink.addClass('hidden');
  3725. me.hideEmailButton();
  3726. viewButtonsDisplayed = false;
  3727. };
  3728. /**
  3729. * Hides all elements belonging to existing pastes
  3730. *
  3731. * @name TopNav.hideAllButtons
  3732. * @function
  3733. */
  3734. me.hideAllButtons = function()
  3735. {
  3736. me.hideViewButtons();
  3737. me.hideCreateButtons();
  3738. };
  3739. /**
  3740. * shows all elements needed when creating a new paste
  3741. *
  3742. * @name TopNav.showCreateButtons
  3743. * @function
  3744. */
  3745. me.showCreateButtons = function()
  3746. {
  3747. if (createButtonsDisplayed) {
  3748. return;
  3749. }
  3750. $attach.removeClass('hidden');
  3751. $burnAfterReadingOption.removeClass('hidden');
  3752. $expiration.removeClass('hidden');
  3753. $formatter.removeClass('hidden');
  3754. $newButton.removeClass('hidden');
  3755. $openDiscussionOption.removeClass('hidden');
  3756. $password.removeClass('hidden');
  3757. $sendButton.removeClass('hidden');
  3758. createButtonsDisplayed = true;
  3759. };
  3760. /**
  3761. * shows all elements needed when creating a new paste
  3762. *
  3763. * @name TopNav.hideCreateButtons
  3764. * @function
  3765. */
  3766. me.hideCreateButtons = function()
  3767. {
  3768. if (!createButtonsDisplayed) {
  3769. return;
  3770. }
  3771. $newButton.addClass('hidden');
  3772. $sendButton.addClass('hidden');
  3773. $expiration.addClass('hidden');
  3774. $formatter.addClass('hidden');
  3775. $burnAfterReadingOption.addClass('hidden');
  3776. $openDiscussionOption.addClass('hidden');
  3777. $password.addClass('hidden');
  3778. $attach.addClass('hidden');
  3779. createButtonsDisplayed = false;
  3780. };
  3781. /**
  3782. * only shows the "new paste" button
  3783. *
  3784. * @name TopNav.showNewPasteButton
  3785. * @function
  3786. */
  3787. me.showNewPasteButton = function()
  3788. {
  3789. $newButton.removeClass('hidden');
  3790. };
  3791. /**
  3792. * only shows the "retry" button
  3793. *
  3794. * @name TopNav.showRetryButton
  3795. * @function
  3796. */
  3797. me.showRetryButton = function()
  3798. {
  3799. $retryButton.removeClass('hidden');
  3800. }
  3801. /**
  3802. * hides the "retry" button
  3803. *
  3804. * @name TopNav.hideRetryButton
  3805. * @function
  3806. */
  3807. me.hideRetryButton = function()
  3808. {
  3809. $retryButton.addClass('hidden');
  3810. }
  3811. /**
  3812. * show the "email" button
  3813. *
  3814. * @name TopNav.showEmailbutton
  3815. * @function
  3816. * @param {int|undefined} optionalRemainingTimeInSeconds
  3817. */
  3818. me.showEmailButton = function(optionalRemainingTimeInSeconds)
  3819. {
  3820. try {
  3821. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3822. const expirationDate = Helper.calculateExpirationDate(
  3823. new Date(),
  3824. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3825. );
  3826. const isBurnafterreading = TopNav.getBurnAfterReading();
  3827. $emailLink.removeClass('hidden');
  3828. $emailLink.off('click.sendEmail');
  3829. $emailLink.on('click.sendEmail', () => {
  3830. sendEmail(expirationDate, isBurnafterreading);
  3831. });
  3832. } catch (error) {
  3833. console.error(error);
  3834. Alert.showError('Cannot calculate expiration date.');
  3835. }
  3836. }
  3837. /**
  3838. * hide the "email" button
  3839. *
  3840. * @name TopNav.hideEmailButton
  3841. * @function
  3842. */
  3843. me.hideEmailButton = function()
  3844. {
  3845. $emailLink.addClass('hidden');
  3846. $emailLink.off('click.sendEmail');
  3847. }
  3848. /**
  3849. * only hides the clone button
  3850. *
  3851. * @name TopNav.hideCloneButton
  3852. * @function
  3853. */
  3854. me.hideCloneButton = function()
  3855. {
  3856. $cloneButton.addClass('hidden');
  3857. };
  3858. /**
  3859. * only hides the raw text button
  3860. *
  3861. * @name TopNav.hideRawButton
  3862. * @function
  3863. */
  3864. me.hideRawButton = function()
  3865. {
  3866. $rawTextButton.addClass('hidden');
  3867. };
  3868. /**
  3869. * only hides the download text button
  3870. *
  3871. * @name TopNav.hideRawButton
  3872. * @function
  3873. */
  3874. me.hideDownloadButton = function()
  3875. {
  3876. $downloadTextButton.addClass('hidden');
  3877. };
  3878. /**
  3879. * only hides the qr code button
  3880. *
  3881. * @name TopNav.hideQrCodeButton
  3882. * @function
  3883. */
  3884. me.hideQrCodeButton = function()
  3885. {
  3886. $qrCodeLink.addClass('hidden');
  3887. }
  3888. /**
  3889. * hide all irrelevant buttons when viewing burn after reading paste
  3890. *
  3891. * @name TopNav.hideBurnAfterReadingButtons
  3892. * @function
  3893. */
  3894. me.hideBurnAfterReadingButtons = function()
  3895. {
  3896. me.hideCloneButton();
  3897. me.hideQrCodeButton();
  3898. me.hideEmailButton();
  3899. }
  3900. /**
  3901. * hides the file selector in attachment
  3902. *
  3903. * @name TopNav.hideFileSelector
  3904. * @function
  3905. */
  3906. me.hideFileSelector = function()
  3907. {
  3908. $fileWrap.addClass('hidden');
  3909. };
  3910. /**
  3911. * shows the custom attachment
  3912. *
  3913. * @name TopNav.showCustomAttachment
  3914. * @function
  3915. */
  3916. me.showCustomAttachment = function()
  3917. {
  3918. $customAttachment.removeClass('hidden');
  3919. };
  3920. /**
  3921. * hides the custom attachment
  3922. *
  3923. * @name TopNav.hideCustomAttachment
  3924. * @function
  3925. */
  3926. me.hideCustomAttachment = function()
  3927. {
  3928. $customAttachment.addClass('hidden');
  3929. $fileWrap.removeClass('hidden');
  3930. };
  3931. /**
  3932. * collapses the navigation bar, only if expanded
  3933. *
  3934. * @name TopNav.collapseBar
  3935. * @function
  3936. */
  3937. me.collapseBar = function()
  3938. {
  3939. if ($('#navbar').attr('aria-expanded') === 'true') {
  3940. $('.navbar-toggle').click();
  3941. }
  3942. };
  3943. /**
  3944. * Reset the top navigation back to it's default values.
  3945. *
  3946. * @name TopNav.resetInput
  3947. * @function
  3948. */
  3949. me.resetInput = function()
  3950. {
  3951. clearAttachmentInput();
  3952. $burnAfterReading.prop('checked', burnAfterReadingDefault);
  3953. $openDiscussion.prop('checked', openDiscussionDefault);
  3954. if (openDiscussionDefault || !burnAfterReadingDefault) $openDiscussionOption.removeClass('buttondisabled');
  3955. if (burnAfterReadingDefault || !openDiscussionDefault) $burnAfterReadingOption.removeClass('buttondisabled');
  3956. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  3957. $('#pasteExpiration>option').each(function() {
  3958. const $this = $(this);
  3959. if ($this.val() === pasteExpiration) {
  3960. $('#pasteExpirationDisplay').text($this.text());
  3961. }
  3962. });
  3963. };
  3964. /**
  3965. * returns the currently set expiration time
  3966. *
  3967. * @name TopNav.getExpiration
  3968. * @function
  3969. * @return {int}
  3970. */
  3971. me.getExpiration = function()
  3972. {
  3973. return Model.getExpirationDefault() || pasteExpiration;
  3974. };
  3975. /**
  3976. * returns the currently selected file(s)
  3977. *
  3978. * @name TopNav.getFileList
  3979. * @function
  3980. * @return {FileList|null}
  3981. */
  3982. me.getFileList = function()
  3983. {
  3984. const $file = $('#file');
  3985. // if no file given, return null
  3986. if (!$file.length || !$file[0].files.length) {
  3987. return null;
  3988. }
  3989. // ensure the selected file is still accessible
  3990. if (!($file[0].files && $file[0].files[0])) {
  3991. return null;
  3992. }
  3993. return $file[0].files;
  3994. };
  3995. /**
  3996. * returns the state of the burn after reading checkbox
  3997. *
  3998. * @name TopNav.getBurnAfterReading
  3999. * @function
  4000. * @return {bool}
  4001. */
  4002. me.getBurnAfterReading = function()
  4003. {
  4004. return $burnAfterReading.prop('checked');
  4005. };
  4006. /**
  4007. * returns the state of the discussion checkbox
  4008. *
  4009. * @name TopNav.getOpenDiscussion
  4010. * @function
  4011. * @return {bool}
  4012. */
  4013. me.getOpenDiscussion = function()
  4014. {
  4015. return $openDiscussion.prop('checked');
  4016. };
  4017. /**
  4018. * returns the entered password
  4019. *
  4020. * @name TopNav.getPassword
  4021. * @function
  4022. * @return {string}
  4023. */
  4024. me.getPassword = function()
  4025. {
  4026. // when password is disabled $passwordInput.val() will return undefined
  4027. return $passwordInput.val() || '';
  4028. };
  4029. /**
  4030. * returns the element where custom attachments can be placed
  4031. *
  4032. * Used by AttachmentViewer when an attachment is cloned here.
  4033. *
  4034. * @name TopNav.getCustomAttachment
  4035. * @function
  4036. * @return {jQuery}
  4037. */
  4038. me.getCustomAttachment = function()
  4039. {
  4040. return $customAttachment;
  4041. };
  4042. /**
  4043. * Set a function to call when the retry button is clicked.
  4044. *
  4045. * @name TopNav.setRetryCallback
  4046. * @function
  4047. * @param {function} callback
  4048. */
  4049. me.setRetryCallback = function(callback)
  4050. {
  4051. retryButtonCallback = callback;
  4052. }
  4053. /**
  4054. * Highlight file upload
  4055. *
  4056. * @name TopNav.highlightFileupload
  4057. * @function
  4058. */
  4059. me.highlightFileupload = function()
  4060. {
  4061. // visually indicate file uploaded
  4062. const $attachDropdownToggle = $attach.children('.dropdown-toggle');
  4063. if ($attachDropdownToggle.attr('aria-expanded') === 'false') {
  4064. $attachDropdownToggle.click();
  4065. }
  4066. $fileWrap.addClass('highlight');
  4067. setTimeout(function () {
  4068. $fileWrap.removeClass('highlight');
  4069. }, 300);
  4070. }
  4071. /**
  4072. * set the format on bootstrap templates in dropdown programmatically
  4073. *
  4074. * @name TopNav.setFormat
  4075. * @function
  4076. */
  4077. me.setFormat = function(format)
  4078. {
  4079. $formatter.parent().find(`a[data-format="${format}"]`).click();
  4080. }
  4081. /**
  4082. * returns if attachment dropdown is readonly, not editable
  4083. *
  4084. * @name TopNav.isAttachmentReadonly
  4085. * @function
  4086. * @return {bool}
  4087. */
  4088. me.isAttachmentReadonly = function()
  4089. {
  4090. return !createButtonsDisplayed || $attach.hasClass('hidden');
  4091. }
  4092. /**
  4093. * init navigation manager
  4094. *
  4095. * preloads jQuery elements
  4096. *
  4097. * @name TopNav.init
  4098. * @function
  4099. */
  4100. me.init = function()
  4101. {
  4102. $attach = $('#attach');
  4103. $burnAfterReading = $('#burnafterreading');
  4104. $burnAfterReadingOption = $('#burnafterreadingoption');
  4105. $cloneButton = $('#clonebutton');
  4106. $customAttachment = $('#customattachment');
  4107. $expiration = $('#expiration');
  4108. $fileRemoveButton = $('#fileremovebutton');
  4109. $fileWrap = $('#filewrap');
  4110. $formatter = $('#formatter');
  4111. $newButton = $('#newbutton');
  4112. $openDiscussion = $('#opendiscussion');
  4113. $openDiscussionOption = $('#opendiscussionoption');
  4114. $password = $('#password');
  4115. $passwordInput = $('#passwordinput');
  4116. $rawTextButton = $('#rawtextbutton');
  4117. $downloadTextButton = $('#downloadtextbutton');
  4118. $retryButton = $('#retrybutton');
  4119. $sendButton = $('#sendbutton');
  4120. $qrCodeLink = $('#qrcodelink');
  4121. $emailLink = $('#emaillink');
  4122. // bootstrap template drop down
  4123. $('#language ul.dropdown-menu li a').click(setLanguage);
  4124. // page template drop down
  4125. $('#language select option').click(setLanguage);
  4126. // bind events
  4127. $burnAfterReading.change(changeBurnAfterReading);
  4128. $openDiscussionOption.change(changeOpenDiscussion);
  4129. $newButton.click(clickNewPaste);
  4130. $sendButton.click(PasteEncrypter.sendPaste);
  4131. $cloneButton.click(Controller.clonePaste);
  4132. $rawTextButton.click(rawText);
  4133. $downloadTextButton.click(downloadText);
  4134. $retryButton.click(clickRetryButton);
  4135. $fileRemoveButton.click(removeAttachment);
  4136. $qrCodeLink.click(displayQrCode);
  4137. // bootstrap template drop downs
  4138. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  4139. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  4140. $('#pasteFormatter').on('change', function() {
  4141. PasteViewer.setFormat(Model.getFormatDefault());
  4142. });
  4143. // initiate default state of checkboxes
  4144. changeBurnAfterReading();
  4145. changeOpenDiscussion();
  4146. // get default values from template or fall back to set value
  4147. burnAfterReadingDefault = me.getBurnAfterReading();
  4148. openDiscussionDefault = me.getOpenDiscussion();
  4149. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4150. createButtonsDisplayed = false;
  4151. viewButtonsDisplayed = false;
  4152. };
  4153. return me;
  4154. })(window, document);
  4155. /**
  4156. * Responsible for AJAX requests, transparently handles encryption…
  4157. *
  4158. * @name ServerInteraction
  4159. * @class
  4160. */
  4161. const ServerInteraction = (function () {
  4162. const me = {};
  4163. let successFunc = null,
  4164. failureFunc = null,
  4165. symmetricKey = null,
  4166. url,
  4167. data,
  4168. password;
  4169. /**
  4170. * public variable ('constant') for errors to prevent magic numbers
  4171. *
  4172. * @name ServerInteraction.error
  4173. * @readonly
  4174. * @enum {Object}
  4175. */
  4176. me.error = {
  4177. okay: 0,
  4178. custom: 1,
  4179. unknown: 2,
  4180. serverError: 3
  4181. };
  4182. /**
  4183. * ajaxHeaders to send in AJAX requests
  4184. *
  4185. * @name ServerInteraction.ajaxHeaders
  4186. * @private
  4187. * @readonly
  4188. * @enum {Object}
  4189. */
  4190. const ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  4191. /**
  4192. * called after successful upload
  4193. *
  4194. * @name ServerInteraction.success
  4195. * @private
  4196. * @function
  4197. * @param {int} status
  4198. * @param {int} result - optional
  4199. */
  4200. function success(status, result)
  4201. {
  4202. if (successFunc !== null) {
  4203. // add useful data to result
  4204. result.encryptionKey = symmetricKey;
  4205. successFunc(status, result);
  4206. }
  4207. }
  4208. /**
  4209. * called after a upload failure
  4210. *
  4211. * @name ServerInteraction.fail
  4212. * @private
  4213. * @function
  4214. * @param {int} status - internal code
  4215. * @param {int} result - original error code
  4216. */
  4217. function fail(status, result)
  4218. {
  4219. if (failureFunc !== null) {
  4220. failureFunc(status, result);
  4221. }
  4222. }
  4223. /**
  4224. * actually uploads the data
  4225. *
  4226. * @name ServerInteraction.run
  4227. * @function
  4228. */
  4229. me.run = function()
  4230. {
  4231. let isPost = Object.keys(data).length > 0,
  4232. ajaxParams = {
  4233. type: isPost ? 'POST' : 'GET',
  4234. url: url,
  4235. headers: ajaxHeaders,
  4236. dataType: 'json',
  4237. success: function(result) {
  4238. if (result.status === 0) {
  4239. success(0, result);
  4240. } else if (result.status === 1) {
  4241. fail(1, result);
  4242. } else {
  4243. fail(2, result);
  4244. }
  4245. }
  4246. };
  4247. if (isPost) {
  4248. ajaxParams.data = JSON.stringify(data);
  4249. }
  4250. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  4251. console.error(textStatus, errorThrown);
  4252. fail(3, jqXHR);
  4253. });
  4254. };
  4255. /**
  4256. * return currently set data, used in unit testing
  4257. *
  4258. * @name ServerInteraction.getData
  4259. * @function
  4260. */
  4261. me.getData = function()
  4262. {
  4263. return data;
  4264. };
  4265. /**
  4266. * set success function
  4267. *
  4268. * @name ServerInteraction.setUrl
  4269. * @function
  4270. * @param {function} newUrl
  4271. */
  4272. me.setUrl = function(newUrl)
  4273. {
  4274. url = newUrl;
  4275. };
  4276. /**
  4277. * sets the password to use (first value) and optionally also the
  4278. * encryption key (not recommended, it is automatically generated).
  4279. *
  4280. * Note: Call this after prepare() as prepare() resets these values.
  4281. *
  4282. * @name ServerInteraction.setCryptValues
  4283. * @function
  4284. * @param {string} newPassword
  4285. * @param {string} newKey - optional
  4286. */
  4287. me.setCryptParameters = function(newPassword, newKey)
  4288. {
  4289. password = newPassword;
  4290. if (typeof newKey !== 'undefined') {
  4291. symmetricKey = newKey;
  4292. }
  4293. };
  4294. /**
  4295. * set success function
  4296. *
  4297. * @name ServerInteraction.setSuccess
  4298. * @function
  4299. * @param {function} func
  4300. */
  4301. me.setSuccess = function(func)
  4302. {
  4303. successFunc = func;
  4304. };
  4305. /**
  4306. * set failure function
  4307. *
  4308. * @name ServerInteraction.setFailure
  4309. * @function
  4310. * @param {function} func
  4311. */
  4312. me.setFailure = function(func)
  4313. {
  4314. failureFunc = func;
  4315. };
  4316. /**
  4317. * prepares a new upload
  4318. *
  4319. * Call this when doing a new upload to reset any data from potential
  4320. * previous uploads. Must be called before any other method of this
  4321. * module.
  4322. *
  4323. * @name ServerInteraction.prepare
  4324. * @function
  4325. * @return {object}
  4326. */
  4327. me.prepare = function()
  4328. {
  4329. // entropy should already be checked!
  4330. // reset password
  4331. password = '';
  4332. // reset key, so it a new one is generated when it is used
  4333. symmetricKey = null;
  4334. // reset data
  4335. successFunc = null;
  4336. failureFunc = null;
  4337. url = Helper.baseUri();
  4338. data = {};
  4339. };
  4340. /**
  4341. * encrypts and sets the data
  4342. *
  4343. * @name ServerInteraction.setCipherMessage
  4344. * @async
  4345. * @function
  4346. * @param {object} cipherMessage
  4347. */
  4348. me.setCipherMessage = async function(cipherMessage)
  4349. {
  4350. if (
  4351. symmetricKey === null ||
  4352. (typeof symmetricKey === 'string' && symmetricKey === '')
  4353. ) {
  4354. symmetricKey = CryptTool.getSymmetricKey();
  4355. }
  4356. if (!data.hasOwnProperty('adata')) {
  4357. data['adata'] = [];
  4358. }
  4359. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4360. data['v'] = 2;
  4361. data['ct'] = cipherResult[0];
  4362. data['adata'] = cipherResult[1];
  4363. };
  4364. /**
  4365. * set the additional metadata to send unencrypted
  4366. *
  4367. * @name ServerInteraction.setUnencryptedData
  4368. * @function
  4369. * @param {string} index
  4370. * @param {mixed} element
  4371. */
  4372. me.setUnencryptedData = function(index, element)
  4373. {
  4374. data[index] = element;
  4375. };
  4376. /**
  4377. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4378. *
  4379. * @name ServerInteraction.parseUploadError
  4380. * @function
  4381. * @param {int} status
  4382. * @param {object} data
  4383. * @param {string} doThisThing - a human description of the action, which was tried
  4384. * @return {array}
  4385. */
  4386. me.parseUploadError = function(status, data, doThisThing) {
  4387. let errorArray;
  4388. switch (status) {
  4389. case me.error.custom:
  4390. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4391. break;
  4392. case me.error.unknown:
  4393. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4394. break;
  4395. case me.error.serverError:
  4396. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4397. break;
  4398. default:
  4399. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4400. break;
  4401. }
  4402. return errorArray;
  4403. };
  4404. return me;
  4405. })();
  4406. /**
  4407. * (controller) Responsible for encrypting paste and sending it to server.
  4408. *
  4409. * Does upload, encryption is done transparently by ServerInteraction.
  4410. *
  4411. * @name PasteEncrypter
  4412. * @class
  4413. */
  4414. const PasteEncrypter = (function () {
  4415. const me = {};
  4416. /**
  4417. * called after successful paste upload
  4418. *
  4419. * @name PasteEncrypter.showCreatedPaste
  4420. * @private
  4421. * @function
  4422. * @param {int} status
  4423. * @param {object} data
  4424. */
  4425. function showCreatedPaste(status, data) {
  4426. Alert.hideLoading();
  4427. Alert.hideMessages();
  4428. // show notification
  4429. const baseUri = Helper.baseUri() + '?',
  4430. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4431. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4432. PasteStatus.createPasteNotification(url, deleteUrl);
  4433. // show new URL in browser bar
  4434. history.pushState({type: 'newpaste'}, document.title, url);
  4435. TopNav.showViewButtons();
  4436. // this cannot be grouped with showViewButtons due to remaining time calculation
  4437. TopNav.showEmailButton();
  4438. TopNav.hideRawButton();
  4439. TopNav.hideDownloadButton();
  4440. Editor.hide();
  4441. // parse and show text
  4442. // (preparation already done in me.sendPaste())
  4443. PasteViewer.run();
  4444. }
  4445. /**
  4446. * called after successful comment upload
  4447. *
  4448. * @name PasteEncrypter.showUploadedComment
  4449. * @private
  4450. * @function
  4451. * @param {int} status
  4452. * @param {object} data
  4453. */
  4454. function showUploadedComment(status, data) {
  4455. // show success message
  4456. Alert.showStatus('Comment posted.');
  4457. // reload paste
  4458. Controller.refreshPaste(function () {
  4459. // highlight sent comment
  4460. DiscussionViewer.highlightComment(data.id, true);
  4461. // reset error handler
  4462. Alert.setCustomHandler(null);
  4463. });
  4464. }
  4465. /**
  4466. * send a reply in a discussion
  4467. *
  4468. * @name PasteEncrypter.sendComment
  4469. * @async
  4470. * @function
  4471. */
  4472. me.sendComment = async function()
  4473. {
  4474. Alert.hideMessages();
  4475. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4476. // UI loading state
  4477. TopNav.hideAllButtons();
  4478. Alert.showLoading('Sending comment…', 'cloud-upload');
  4479. // get data
  4480. const plainText = DiscussionViewer.getReplyMessage(),
  4481. nickname = DiscussionViewer.getReplyNickname(),
  4482. parentid = DiscussionViewer.getReplyCommentId();
  4483. // do not send if there is no data
  4484. if (plainText.length === 0) {
  4485. // revert loading status…
  4486. Alert.hideLoading();
  4487. Alert.setCustomHandler(null);
  4488. TopNav.showViewButtons();
  4489. return;
  4490. }
  4491. // prepare server interaction
  4492. ServerInteraction.prepare();
  4493. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4494. // set success/fail functions
  4495. ServerInteraction.setSuccess(showUploadedComment);
  4496. ServerInteraction.setFailure(function (status, data) {
  4497. // revert loading status…
  4498. Alert.hideLoading();
  4499. TopNav.showViewButtons();
  4500. // …show error message…
  4501. Alert.showError(
  4502. ServerInteraction.parseUploadError(status, data, 'post comment')
  4503. );
  4504. // …and reset error handler
  4505. Alert.setCustomHandler(null);
  4506. });
  4507. // fill it with unencrypted params
  4508. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4509. if (typeof parentid === 'undefined') {
  4510. // if parent id is not set, this is the top-most comment, so use
  4511. // paste id as parent, as the root element of the discussion tree
  4512. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4513. } else {
  4514. ServerInteraction.setUnencryptedData('parentid', parentid);
  4515. }
  4516. // prepare cypher message
  4517. let cipherMessage = {
  4518. 'comment': plainText
  4519. };
  4520. if (nickname.length > 0) {
  4521. cipherMessage['nickname'] = nickname;
  4522. }
  4523. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4524. ServerInteraction.run();
  4525. };
  4526. /**
  4527. * sends a new paste to server
  4528. *
  4529. * @name PasteEncrypter.sendPaste
  4530. * @async
  4531. * @function
  4532. */
  4533. me.sendPaste = async function()
  4534. {
  4535. // hide previous (error) messages
  4536. Controller.hideStatusMessages();
  4537. // UI loading state
  4538. TopNav.hideAllButtons();
  4539. Alert.showLoading('Sending paste…', 'cloud-upload');
  4540. TopNav.collapseBar();
  4541. // get data
  4542. const plainText = Editor.getText(),
  4543. format = PasteViewer.getFormat(),
  4544. // the methods may return different values if no files are attached (null, undefined or false)
  4545. files = TopNav.getFileList() || AttachmentViewer.getFile() || AttachmentViewer.hasAttachment();
  4546. // do not send if there is no data
  4547. if (plainText.length === 0 && !files) {
  4548. // revert loading status…
  4549. Alert.hideLoading();
  4550. TopNav.showCreateButtons();
  4551. return;
  4552. }
  4553. // prepare server interaction
  4554. ServerInteraction.prepare();
  4555. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4556. // set success/fail functions
  4557. ServerInteraction.setSuccess(showCreatedPaste);
  4558. ServerInteraction.setFailure(function (status, data) {
  4559. // revert loading status…
  4560. Alert.hideLoading();
  4561. TopNav.showCreateButtons();
  4562. // show error message
  4563. Alert.showError(
  4564. ServerInteraction.parseUploadError(status, data, 'create paste')
  4565. );
  4566. });
  4567. // fill it with unencrypted submitted options
  4568. ServerInteraction.setUnencryptedData('adata', [
  4569. null, format,
  4570. TopNav.getOpenDiscussion() ? 1 : 0,
  4571. TopNav.getBurnAfterReading() ? 1 : 0
  4572. ]);
  4573. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  4574. // prepare PasteViewer for later preview
  4575. PasteViewer.setText(plainText);
  4576. PasteViewer.setFormat(format);
  4577. // prepare cypher message
  4578. let file = AttachmentViewer.getAttachmentData(),
  4579. cipherMessage = {
  4580. 'paste': plainText
  4581. };
  4582. if (typeof file !== 'undefined' && file !== null) {
  4583. cipherMessage['attachment'] = file;
  4584. cipherMessage['attachment_name'] = AttachmentViewer.getFile().name;
  4585. } else if (AttachmentViewer.hasAttachment()) {
  4586. // fall back to cloned part
  4587. let attachment = AttachmentViewer.getAttachment();
  4588. cipherMessage['attachment'] = attachment[0];
  4589. cipherMessage['attachment_name'] = attachment[1];
  4590. // we need to retrieve data from blob if browser already parsed it in memory
  4591. if (typeof attachment[0] === 'string' && attachment[0].startsWith('blob:')) {
  4592. Alert.showStatus(
  4593. [
  4594. 'Retrieving cloned file \'%s\' from memory...',
  4595. attachment[1]
  4596. ],
  4597. 'copy'
  4598. );
  4599. try {
  4600. const blobData = await $.ajax({
  4601. type: 'GET',
  4602. url: `${attachment[0]}`,
  4603. processData: false,
  4604. timeout: 10000,
  4605. xhrFields: {
  4606. withCredentials: false,
  4607. responseType: 'blob'
  4608. }
  4609. });
  4610. if (blobData instanceof window.Blob) {
  4611. const fileReading = new Promise(function(resolve, reject) {
  4612. const fileReader = new FileReader();
  4613. fileReader.onload = function (event) {
  4614. resolve(event.target.result);
  4615. };
  4616. fileReader.onerror = function (error) {
  4617. reject(error);
  4618. }
  4619. fileReader.readAsDataURL(blobData);
  4620. });
  4621. cipherMessage['attachment'] = await fileReading;
  4622. } else {
  4623. const error = 'Cannot process attachment data.';
  4624. Alert.showError(error);
  4625. throw new TypeError(error);
  4626. }
  4627. } catch (error) {
  4628. console.error(error);
  4629. Alert.showError('Cannot retrieve attachment.');
  4630. throw error;
  4631. }
  4632. }
  4633. }
  4634. // encrypt message
  4635. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4636. // send data
  4637. ServerInteraction.run();
  4638. };
  4639. return me;
  4640. })();
  4641. /**
  4642. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4643. *
  4644. * Only decryption, no download.
  4645. *
  4646. * @name PasteDecrypter
  4647. * @class
  4648. */
  4649. const PasteDecrypter = (function () {
  4650. const me = {};
  4651. /**
  4652. * decrypt data or prompts for password in case of failure
  4653. *
  4654. * @name PasteDecrypter.decryptOrPromptPassword
  4655. * @private
  4656. * @async
  4657. * @function
  4658. * @param {string} key
  4659. * @param {string} password - optional, may be an empty string
  4660. * @param {string} cipherdata
  4661. * @throws {string}
  4662. * @return {false|string} false, when unsuccessful or string (decrypted data)
  4663. */
  4664. async function decryptOrPromptPassword(key, password, cipherdata)
  4665. {
  4666. // try decryption without password
  4667. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4668. // if it fails, request password
  4669. if (plaindata.length === 0 && password.length === 0) {
  4670. // show prompt
  4671. Prompt.requestPassword();
  4672. // Thus, we cannot do anything yet, we need to wait for the user
  4673. // input.
  4674. return false;
  4675. }
  4676. // if all tries failed, we can only return an error
  4677. if (plaindata.length === 0) {
  4678. return false;
  4679. }
  4680. return plaindata;
  4681. }
  4682. /**
  4683. * decrypt the actual paste text
  4684. *
  4685. * @name PasteDecrypter.decryptPaste
  4686. * @private
  4687. * @async
  4688. * @function
  4689. * @param {Paste} paste - paste data in object form
  4690. * @param {string} key
  4691. * @param {string} password
  4692. * @throws {string}
  4693. * @return {Promise}
  4694. */
  4695. async function decryptPaste(paste, key, password)
  4696. {
  4697. let pastePlain = await decryptOrPromptPassword(
  4698. key, password,
  4699. paste.getCipherData()
  4700. );
  4701. if (pastePlain === false) {
  4702. if (password.length === 0) {
  4703. throw 'waiting on user to provide a password';
  4704. } else {
  4705. Alert.hideLoading();
  4706. // reset password, so it can be re-entered
  4707. Prompt.reset();
  4708. TopNav.showRetryButton();
  4709. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4710. }
  4711. }
  4712. if (paste.v > 1) {
  4713. // version 2 paste
  4714. const pasteMessage = JSON.parse(pastePlain);
  4715. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4716. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4717. AttachmentViewer.showAttachment();
  4718. }
  4719. pastePlain = pasteMessage.paste;
  4720. } else {
  4721. // version 1 paste
  4722. if (paste.hasOwnProperty('attachment') && paste.hasOwnProperty('attachmentname')) {
  4723. Promise.all([
  4724. CryptTool.decipher(key, password, paste.attachment),
  4725. CryptTool.decipher(key, password, paste.attachmentname)
  4726. ]).then((attachment) => {
  4727. AttachmentViewer.setAttachment(attachment[0], attachment[1]);
  4728. AttachmentViewer.showAttachment();
  4729. });
  4730. }
  4731. }
  4732. PasteViewer.setFormat(paste.getFormat());
  4733. PasteViewer.setText(pastePlain);
  4734. PasteViewer.run();
  4735. }
  4736. /**
  4737. * decrypts all comments and shows them
  4738. *
  4739. * @name PasteDecrypter.decryptComments
  4740. * @private
  4741. * @async
  4742. * @function
  4743. * @param {Paste} paste - paste data in object form
  4744. * @param {string} key
  4745. * @param {string} password
  4746. * @return {Promise}
  4747. */
  4748. async function decryptComments(paste, key, password)
  4749. {
  4750. // remove potential previous discussion
  4751. DiscussionViewer.prepareNewDiscussion();
  4752. const commentDecryptionPromises = [];
  4753. // iterate over comments
  4754. for (let i = 0; i < paste.comments.length; ++i) {
  4755. const comment = new Comment(paste.comments[i]),
  4756. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4757. paste.comments[i] = comment;
  4758. if (comment.v > 1) {
  4759. // version 2 comment
  4760. commentDecryptionPromises.push(
  4761. commentPromise.then(function (commentJson) {
  4762. const commentMessage = JSON.parse(commentJson);
  4763. return [
  4764. commentMessage.comment || '',
  4765. commentMessage.nickname || ''
  4766. ];
  4767. })
  4768. );
  4769. } else {
  4770. // version 1 comment
  4771. commentDecryptionPromises.push(
  4772. Promise.all([
  4773. commentPromise,
  4774. paste.comments[i].meta.hasOwnProperty('nickname') ?
  4775. CryptTool.decipher(key, password, paste.comments[i].meta.nickname) :
  4776. Promise.resolve('')
  4777. ])
  4778. );
  4779. }
  4780. }
  4781. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4782. for (let i = 0; i < paste.comments.length; ++i) {
  4783. if (plaintexts[i][0].length === 0) {
  4784. continue;
  4785. }
  4786. DiscussionViewer.addComment(
  4787. paste.comments[i],
  4788. plaintexts[i][0],
  4789. plaintexts[i][1]
  4790. );
  4791. }
  4792. });
  4793. }
  4794. /**
  4795. * show decrypted text in the display area, including discussion (if open)
  4796. *
  4797. * @name PasteDecrypter.run
  4798. * @function
  4799. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4800. */
  4801. me.run = function(paste)
  4802. {
  4803. Alert.hideMessages();
  4804. Alert.showLoading('Decrypting paste…', 'cloud-download');
  4805. if (typeof paste === 'undefined' || paste.type === 'click') {
  4806. // get cipher data and wait until it is available
  4807. Model.getPasteData(me.run);
  4808. return;
  4809. }
  4810. let key = Model.getPasteKey(),
  4811. password = Prompt.getPassword(),
  4812. decryptionPromises = [];
  4813. TopNav.setRetryCallback(function () {
  4814. TopNav.hideRetryButton();
  4815. me.run(paste);
  4816. });
  4817. // decrypt paste & attachments
  4818. decryptionPromises.push(decryptPaste(paste, key, password));
  4819. // if the discussion is opened on this paste, display it
  4820. if (paste.isDiscussionEnabled()) {
  4821. decryptionPromises.push(decryptComments(paste, key, password));
  4822. }
  4823. // shows the remaining time (until) deletion
  4824. PasteStatus.showRemainingTime(paste);
  4825. Promise.all(decryptionPromises)
  4826. .then(() => {
  4827. Alert.hideLoading();
  4828. TopNav.showViewButtons();
  4829. // discourage cloning (it cannot really be prevented)
  4830. if (paste.isBurnAfterReadingEnabled()) {
  4831. TopNav.hideBurnAfterReadingButtons();
  4832. } else {
  4833. // we have to pass in remaining_time here
  4834. TopNav.showEmailButton(paste.getTimeToLive());
  4835. }
  4836. // only offer adding comments, after paste was successfully decrypted
  4837. if (paste.isDiscussionEnabled()) {
  4838. DiscussionViewer.finishDiscussion();
  4839. }
  4840. })
  4841. .catch((err) => {
  4842. // wait for the user to type in the password,
  4843. // then PasteDecrypter.run will be called again
  4844. Alert.showError(err);
  4845. });
  4846. };
  4847. return me;
  4848. })();
  4849. /**
  4850. * (controller) main PrivateBin logic
  4851. *
  4852. * @name Controller
  4853. * @param {object} window
  4854. * @param {object} document
  4855. * @class
  4856. */
  4857. const Controller = (function (window, document) {
  4858. const me = {};
  4859. /**
  4860. * hides all status messages no matter which module showed them
  4861. *
  4862. * @name Controller.hideStatusMessages
  4863. * @function
  4864. */
  4865. me.hideStatusMessages = function()
  4866. {
  4867. PasteStatus.hideMessages();
  4868. Alert.hideMessages();
  4869. };
  4870. /**
  4871. * creates a new paste
  4872. *
  4873. * @name Controller.newPaste
  4874. * @function
  4875. */
  4876. me.newPaste = function()
  4877. {
  4878. // Important: This *must not* run Alert.hideMessages() as previous
  4879. // errors from viewing a paste should be shown.
  4880. TopNav.hideAllButtons();
  4881. Alert.showLoading('Preparing new paste…', 'time');
  4882. PasteStatus.hideMessages();
  4883. PasteViewer.hide();
  4884. Editor.resetInput();
  4885. Editor.show();
  4886. Editor.focusInput();
  4887. AttachmentViewer.removeAttachment();
  4888. TopNav.resetInput();
  4889. TopNav.showCreateButtons();
  4890. // newPaste could be called when user is on paste clone editing view
  4891. TopNav.hideCustomAttachment();
  4892. AttachmentViewer.clearDragAndDrop();
  4893. AttachmentViewer.removeAttachmentData();
  4894. Alert.hideLoading();
  4895. // only push new state if we are coming from a different one
  4896. if (Helper.baseUri() != window.location) {
  4897. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  4898. }
  4899. // clear discussion
  4900. DiscussionViewer.prepareNewDiscussion();
  4901. };
  4902. /**
  4903. * shows the loaded paste
  4904. *
  4905. * @name Controller.showPaste
  4906. * @function
  4907. */
  4908. me.showPaste = function()
  4909. {
  4910. try {
  4911. Model.getPasteKey();
  4912. } catch (err) {
  4913. console.error(err);
  4914. // missing decryption key (or paste ID) in URL?
  4915. if (window.location.hash.length === 0) {
  4916. 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?)');
  4917. return;
  4918. }
  4919. }
  4920. // check if we should request loading confirmation
  4921. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  4922. Prompt.requestLoadConfirmation();
  4923. return;
  4924. }
  4925. // show proper elements on screen
  4926. PasteDecrypter.run();
  4927. };
  4928. /**
  4929. * refreshes the loaded paste to show potential new data
  4930. *
  4931. * @name Controller.refreshPaste
  4932. * @function
  4933. * @param {function} callback
  4934. */
  4935. me.refreshPaste = function(callback)
  4936. {
  4937. // save window position to restore it later
  4938. const orgPosition = $(window).scrollTop();
  4939. Model.getPasteData(function (data) {
  4940. ServerInteraction.prepare();
  4941. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  4942. ServerInteraction.setFailure(function (status, data) {
  4943. // revert loading status…
  4944. Alert.hideLoading();
  4945. TopNav.showViewButtons();
  4946. // show error message
  4947. Alert.showError(
  4948. ServerInteraction.parseUploadError(status, data, 'refresh display')
  4949. );
  4950. });
  4951. ServerInteraction.setSuccess(function (status, data) {
  4952. PasteDecrypter.run(new Paste(data));
  4953. // restore position
  4954. window.scrollTo(0, orgPosition);
  4955. // NOTE: could create problems as callback may be called
  4956. // asyncronously if PasteDecrypter e.g. needs to wait for a
  4957. // password being entered
  4958. callback();
  4959. });
  4960. ServerInteraction.run();
  4961. }, false); // this false is important as it circumvents the cache
  4962. }
  4963. /**
  4964. * clone the current paste
  4965. *
  4966. * @name Controller.clonePaste
  4967. * @function
  4968. */
  4969. me.clonePaste = function()
  4970. {
  4971. TopNav.collapseBar();
  4972. TopNav.hideAllButtons();
  4973. // hide messages from previous paste
  4974. me.hideStatusMessages();
  4975. // erase the id and the key in url
  4976. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  4977. if (AttachmentViewer.hasAttachment()) {
  4978. AttachmentViewer.moveAttachmentTo(
  4979. TopNav.getCustomAttachment(),
  4980. 'Cloned: \'%s\''
  4981. );
  4982. TopNav.hideFileSelector();
  4983. AttachmentViewer.hideAttachment();
  4984. // NOTE: it also looks nice without removing the attachment
  4985. // but for a consistent display we remove it…
  4986. AttachmentViewer.hideAttachmentPreview();
  4987. TopNav.showCustomAttachment();
  4988. // show another status message to make the user aware that the
  4989. // file was cloned too!
  4990. Alert.showStatus(
  4991. [
  4992. 'The cloned file \'%s\' was attached to this paste.',
  4993. AttachmentViewer.getAttachment()[1]
  4994. ],
  4995. 'copy'
  4996. );
  4997. }
  4998. Editor.setText(PasteViewer.getText());
  4999. // also clone the format
  5000. TopNav.setFormat(PasteViewer.getFormat());
  5001. PasteViewer.hide();
  5002. Editor.show();
  5003. TopNav.showCreateButtons();
  5004. // clear discussion
  5005. DiscussionViewer.prepareNewDiscussion();
  5006. };
  5007. /**
  5008. * try initializing zlib or display a warning if it fails,
  5009. * extracted from main init to allow unit testing
  5010. *
  5011. * @name Controller.initZ
  5012. * @function
  5013. */
  5014. me.initZ = function()
  5015. {
  5016. z = zlib.catch(function () {
  5017. if ($('body').data('compression') !== 'none') {
  5018. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5019. }
  5020. });
  5021. }
  5022. /**
  5023. * application start
  5024. *
  5025. * @name Controller.init
  5026. * @function
  5027. */
  5028. me.init = function()
  5029. {
  5030. // first load translations
  5031. I18n.loadTranslations();
  5032. // Add a hook to make all links open a new window
  5033. DOMPurify.addHook('afterSanitizeAttributes', function(node) {
  5034. // set all elements owning target to target=_blank
  5035. if ('target' in node && node.id !== 'pasteurl') {
  5036. node.setAttribute('target', '_blank');
  5037. }
  5038. // set non-HTML/MathML links to xlink:show=new
  5039. if (!node.hasAttribute('target')
  5040. && (node.hasAttribute('xlink:href')
  5041. || node.hasAttribute('href'))) {
  5042. node.setAttribute('xlink:show', 'new');
  5043. }
  5044. if ('rel' in node) {
  5045. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5046. }
  5047. });
  5048. // center all modals
  5049. $('.modal').on('show.bs.modal', function(e) {
  5050. $(e.target).css({
  5051. display: 'flex'
  5052. });
  5053. });
  5054. // initialize other modules/"classes"
  5055. Alert.init();
  5056. Model.init();
  5057. AttachmentViewer.init();
  5058. DiscussionViewer.init();
  5059. Editor.init();
  5060. PasteStatus.init();
  5061. PasteViewer.init();
  5062. Prompt.init();
  5063. TopNav.init();
  5064. UiHelper.init();
  5065. // check for legacy browsers before going any further
  5066. if (!Legacy.Check.getInit()) {
  5067. // Legacy check didn't complete, wait and try again
  5068. setTimeout(init, 500);
  5069. return;
  5070. }
  5071. if (!Legacy.Check.getStatus()) {
  5072. // something major is wrong, stop right away
  5073. return;
  5074. }
  5075. me.initZ();
  5076. // if delete token is passed (i.e. paste has been deleted by this
  5077. // access), there is nothing more to do
  5078. if (Model.hasDeleteToken()) {
  5079. return;
  5080. }
  5081. // check whether existing paste needs to be shown
  5082. try {
  5083. Model.getPasteId();
  5084. } catch (e) {
  5085. // otherwise create a new paste
  5086. return me.newPaste();
  5087. }
  5088. // always reload on back button to invalidate cache(protect burn after read paste)
  5089. window.addEventListener('popstate', () => {
  5090. window.location.reload();
  5091. });
  5092. // display an existing paste
  5093. return me.showPaste();
  5094. }
  5095. return me;
  5096. })(window, document);
  5097. return {
  5098. Helper: Helper,
  5099. I18n: I18n,
  5100. CryptTool: CryptTool,
  5101. Model: Model,
  5102. UiHelper: UiHelper,
  5103. Alert: Alert,
  5104. PasteStatus: PasteStatus,
  5105. Prompt: Prompt,
  5106. Editor: Editor,
  5107. PasteViewer: PasteViewer,
  5108. AttachmentViewer: AttachmentViewer,
  5109. DiscussionViewer: DiscussionViewer,
  5110. TopNav: TopNav,
  5111. ServerInteraction: ServerInteraction,
  5112. PasteEncrypter: PasteEncrypter,
  5113. PasteDecrypter: PasteDecrypter,
  5114. Controller: Controller
  5115. };
  5116. })(jQuery, RawDeflate);