privatebin.js 184 KB

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