privatebin.js 192 KB

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