privatebin.js 197 KB

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