privatebin.js 192 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094
  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({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.classList.add('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 (guard in test environments)
  1855. const noscriptEl = document.getElementById('noscript');
  1856. if (noscriptEl) {
  1857. noscriptEl.style.display = 'none';
  1858. }
  1859. // not a reset, but first set of the elements
  1860. errorMessage = document.getElementById('errormessage');
  1861. loadingIndicator = document.getElementById('loadingindicator');
  1862. statusMessage = document.getElementById('status');
  1863. remainingTime = document.getElementById('remainingtime');
  1864. currentIcon = [
  1865. 'glyphicon-time', // loading icon
  1866. 'glyphicon-info-sign', // status icon
  1867. 'glyphicon-warning-sign', // warning icon
  1868. 'glyphicon-alert' // error icon
  1869. ];
  1870. };
  1871. return me;
  1872. })();
  1873. /**
  1874. * handles paste status/result
  1875. *
  1876. * @name PasteStatus
  1877. * @class
  1878. */
  1879. const PasteStatus = (function () {
  1880. const me = {};
  1881. let pasteSuccess,
  1882. pasteUrl,
  1883. remainingTime,
  1884. shortenButton;
  1885. /**
  1886. * forward to URL shortener
  1887. *
  1888. * @name PasteStatus.sendToShortener
  1889. * @private
  1890. * @function
  1891. */
  1892. function sendToShortener()
  1893. {
  1894. if (shortenButton.classList.contains('buttondisabled')) {
  1895. return;
  1896. }
  1897. fetch(`${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`, {
  1898. method: 'GET',
  1899. headers: {'Accept': 'text/html, application/xhtml+xml, application/xml, application/json'},
  1900. credentials: 'omit',
  1901. signal: AbortSignal.timeout(10000)
  1902. })
  1903. .then(response => {
  1904. if (!response.ok) {
  1905. throw new Error('HTTP ' + response.status);
  1906. }
  1907. return response.text();
  1908. })
  1909. .then(data => PasteStatus.extractUrl(data))
  1910. .catch(error => {
  1911. console.error('Shortener error:', error);
  1912. // we don't know why it failed, could be CORS of the external
  1913. // server not setup properly, in which case we follow old
  1914. // behavior to open it in new tab
  1915. window.open(
  1916. `${shortenButton.dataset.shortener}${encodeURIComponent(pasteUrl.href)}`,
  1917. '_blank',
  1918. 'noopener, noreferrer'
  1919. );
  1920. });
  1921. }
  1922. /**
  1923. * Forces opening the document if the link does not do this automatically.
  1924. *
  1925. * This is necessary as browsers will not reload the page when it is
  1926. * already loaded (which is fake as it is set via history.pushState()).
  1927. *
  1928. * @name PasteStatus.pasteLinkClick
  1929. * @function
  1930. */
  1931. function pasteLinkClick()
  1932. {
  1933. // check if location is (already) shown in URL bar
  1934. if (window.location.href === pasteUrl.href) {
  1935. // if so we need to load link by reloading the current site
  1936. window.location.reload(true);
  1937. }
  1938. }
  1939. /**
  1940. * creates a notification after a successful document upload
  1941. *
  1942. * @name PasteStatus.createPasteNotification
  1943. * @function
  1944. * @param {string} url
  1945. * @param {string} deleteUrl
  1946. */
  1947. me.createPasteNotification = function(url, deleteUrl)
  1948. {
  1949. I18n._(
  1950. document.getElementById('pastelink'),
  1951. 'Your document is <a id="pasteurl" href="%s">%s</a> <span id="copyhint">(Hit <kbd>Ctrl</kbd>+<kbd>c</kbd> to copy)</span>',
  1952. url, url
  1953. );
  1954. // save newly created element
  1955. pasteUrl = document.getElementById('pasteurl');
  1956. // and add click event
  1957. pasteUrl.addEventListener('click', pasteLinkClick);
  1958. // delete link
  1959. document.getElementById('deletelink').href = deleteUrl;
  1960. I18n._(document.querySelector('#deletelink span:not(.glyphicon)'), 'Delete data');
  1961. // enable shortener button
  1962. shortenButton.classList.remove('buttondisabled');
  1963. // show result
  1964. pasteSuccess.classList.remove('hidden');
  1965. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1966. Helper.selectText(pasteUrl);
  1967. };
  1968. /**
  1969. * Checks if auto-shortening is enabled and sends the link to the shortener if it is.
  1970. *
  1971. * @name PasteStatus.checkAutoShorten
  1972. * @function
  1973. */
  1974. me.checkAutoShorten = function() {
  1975. // check if auto-shortening is enabled
  1976. if (shortenButton.dataset.autoshorten === 'true') {
  1977. // if so, we send the link to the shortener
  1978. // we do not remove the button, in case shortener fails
  1979. sendToShortener();
  1980. }
  1981. }
  1982. /**
  1983. * extracts URLs from given string
  1984. *
  1985. * if at least one is found, it disables the shortener button and
  1986. * replaces the document URL
  1987. *
  1988. * @name PasteStatus.extractUrl
  1989. * @function
  1990. * @param {string} response
  1991. */
  1992. me.extractUrl = function(response)
  1993. {
  1994. if (typeof response === 'object') {
  1995. response = JSON.stringify(response);
  1996. }
  1997. if (typeof response === 'string' && response.length > 0) {
  1998. const shortUrlMatcher = /https?:\/\/[^\s"<]+/g; // JSON API will have URL in quotes, XML in tags
  1999. const shortUrl = (response.match(shortUrlMatcher) || []).filter(function(urlRegExMatch) {
  2000. if (typeof URL.canParse === 'function') {
  2001. return URL.canParse(urlRegExMatch);
  2002. }
  2003. // polyfill for older browsers (< 120) & node (< 19.9 & < 18.17)
  2004. try {
  2005. return !!new URL(urlRegExMatch);
  2006. } catch (error) {
  2007. return false;
  2008. }
  2009. }).sort(function(a, b) {
  2010. return a.length - b.length; // shortest first
  2011. })[0];
  2012. if (typeof shortUrl === 'string' && shortUrl.length > 0) {
  2013. // we disable the button to avoid calling shortener again
  2014. shortenButton.classList.add('buttondisabled');
  2015. // update link
  2016. pasteUrl.textContent = shortUrl;
  2017. pasteUrl.href = shortUrl;
  2018. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  2019. Helper.selectText(pasteUrl);
  2020. CopyToClipboard.setUrl(shortUrl);
  2021. return;
  2022. }
  2023. }
  2024. Alert.showError('Cannot parse response from URL shortener.');
  2025. };
  2026. /**
  2027. * shows the remaining time
  2028. *
  2029. * @name PasteStatus.showRemainingTime
  2030. * @function
  2031. * @param {Paste} paste
  2032. */
  2033. me.showRemainingTime = function(paste)
  2034. {
  2035. if (paste.isBurnAfterReadingEnabled()) {
  2036. // display document "for your eyes only" if it is deleted
  2037. // the document has been deleted when the JSON with the ciphertext
  2038. // has been downloaded
  2039. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  2040. remainingTime.classList.add('foryoureyesonly');
  2041. } else if (paste.getTimeToLive() > 0) {
  2042. // display document expiration
  2043. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  2044. expirationLabel = [
  2045. 'This document will expire in %d ' + expiration[1] + '.',
  2046. 'This document will expire in %d ' + expiration[1] + 's.'
  2047. ];
  2048. Alert.showRemaining([expirationLabel, expiration[0]]);
  2049. remainingTime.classList.remove('foryoureyesonly');
  2050. } else {
  2051. // never expires
  2052. return;
  2053. }
  2054. // in the end, display notification
  2055. remainingTime.classList.remove('hidden');
  2056. };
  2057. /**
  2058. * hides the remaining time and successful upload notification
  2059. *
  2060. * @name PasteStatus.hideMessages
  2061. * @function
  2062. */
  2063. me.hideMessages = function()
  2064. {
  2065. remainingTime.classList.add('hidden');
  2066. pasteSuccess.classList.add('hidden');
  2067. };
  2068. /**
  2069. * init status manager
  2070. *
  2071. * preloads jQuery elements
  2072. *
  2073. * @name PasteStatus.init
  2074. * @function
  2075. */
  2076. me.init = function()
  2077. {
  2078. pasteSuccess = document.getElementById('pastesuccess');
  2079. // pasteUrl is saved in me.createPasteNotification() after creation
  2080. remainingTime = document.getElementById('remainingtime');
  2081. shortenButton = document.getElementById('shortenbutton');
  2082. // bind elements
  2083. shortenButton.addEventListener('click', sendToShortener);
  2084. };
  2085. return me;
  2086. })();
  2087. /**
  2088. * password prompt
  2089. *
  2090. * @name Prompt
  2091. * @class
  2092. */
  2093. const Prompt = (function () {
  2094. const me = {};
  2095. let passwordDecrypt,
  2096. passwordModal,
  2097. bootstrap5PasswordModal = null,
  2098. password = '';
  2099. /**
  2100. * submit a password in the modal dialog
  2101. *
  2102. * @name Prompt.submitPasswordModal
  2103. * @private
  2104. * @function
  2105. * @param {Event} event
  2106. */
  2107. function submitPasswordModal(event)
  2108. {
  2109. event.preventDefault();
  2110. // get input
  2111. password = passwordDecrypt.value;
  2112. // hide modal
  2113. if (bootstrap5PasswordModal) {
  2114. bootstrap5PasswordModal.hide();
  2115. } else {
  2116. $passwordModal.modal('hide');
  2117. }
  2118. PasteDecrypter.run();
  2119. }
  2120. /**
  2121. * Request users confirmation to load possibly burn after reading document
  2122. *
  2123. * @name Prompt.requestLoadConfirmation
  2124. * @function
  2125. */
  2126. me.requestLoadConfirmation = function()
  2127. {
  2128. const loadconfirmmodal = document.getElementById('loadconfirmmodal');
  2129. const loadconfirmOpenNow = loadconfirmmodal.querySelector('#loadconfirm-open-now');
  2130. loadconfirmOpenNow.removeEventListener('click', PasteDecrypter.run);
  2131. loadconfirmOpenNow.addEventListener('click', PasteDecrypter.run);
  2132. const loadconfirmClose = loadconfirmmodal.querySelector('.close');
  2133. loadconfirmClose.removeEventListener('click', Controller.newPaste);
  2134. loadconfirmClose.addEventListener('click', Controller.newPaste);
  2135. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION) {
  2136. (new bootstrap.Modal(loadconfirmmodal)).show();
  2137. } else {
  2138. $(loadconfirmmodal).modal('show');
  2139. }
  2140. }
  2141. /**
  2142. * ask the user for the password and set it
  2143. *
  2144. * @name Prompt.requestPassword
  2145. * @function
  2146. */
  2147. me.requestPassword = function()
  2148. {
  2149. // show new bootstrap method (if available)
  2150. if ($passwordModal.length !== 0) {
  2151. if (bootstrap5PasswordModal) {
  2152. bootstrap5PasswordModal.show();
  2153. } else {
  2154. $passwordModal.modal('show');
  2155. }
  2156. return;
  2157. }
  2158. PasteDecrypter.run();
  2159. };
  2160. /**
  2161. * get the cached password
  2162. *
  2163. * If you do not get a password with this function
  2164. * (returns an empty string), use requestPassword.
  2165. *
  2166. * @name Prompt.getPassword
  2167. * @function
  2168. * @return {string}
  2169. */
  2170. me.getPassword = function()
  2171. {
  2172. return password;
  2173. };
  2174. /**
  2175. * resets the password to an empty string
  2176. *
  2177. * @name Prompt.reset
  2178. * @function
  2179. */
  2180. me.reset = function()
  2181. {
  2182. // reset internal
  2183. password = '';
  2184. // and also reset UI
  2185. $passwordDecrypt.val('');
  2186. };
  2187. /**
  2188. * init status manager
  2189. *
  2190. * preloads jQuery elements
  2191. *
  2192. * @name Prompt.init
  2193. * @function
  2194. */
  2195. me.init = function()
  2196. {
  2197. passwordDecrypt = document.getElementById('passworddecrypt');
  2198. passwordModal = $('#passwordmodal');
  2199. // bind events - handle Model password submission
  2200. if (passwordModal.length !== 0) {
  2201. document.getElementById('passwordform').addEventListener('submit', submitPasswordModal);
  2202. const disableClosingConfig = {
  2203. backdrop: 'static',
  2204. keyboard: false,
  2205. show: false
  2206. };
  2207. if (typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION) {
  2208. bootstrap5PasswordModal = new bootstrap.Modal(passwordModal[0], disableClosingConfig);
  2209. } else {
  2210. passwordModal.modal(disableClosingConfig);
  2211. }
  2212. passwordModal.on('shown.bs.modal', () => {
  2213. passwordDecrypt.focus();
  2214. });
  2215. }
  2216. };
  2217. return me;
  2218. })();
  2219. /**
  2220. * Manage paste/message input, and preview tab
  2221. *
  2222. * Note that the actual preview is handled by PasteViewer.
  2223. *
  2224. * @name Editor
  2225. * @class
  2226. */
  2227. const Editor = (function () {
  2228. const me = {};
  2229. let $editorTabs,
  2230. $messageEdit,
  2231. $messageEditParent,
  2232. $messagePreview,
  2233. $messagePreviewParent,
  2234. $messageTab,
  2235. $messageTabParent,
  2236. message,
  2237. isPreview = false,
  2238. isTabSupported = true;
  2239. /**
  2240. * support input of tab character
  2241. *
  2242. * @name Editor.supportTabs
  2243. * @function
  2244. * @param {Event} event
  2245. * @this $message (but not used, so it is jQuery-free, possibly faster)
  2246. */
  2247. function supportTabs(event)
  2248. {
  2249. // support disabling tab support using [Esc] and [Ctrl]+[m]
  2250. if (event.key === 'Escape' || (event.ctrlKey && event.key === 'm')) {
  2251. toggleTabSupport();
  2252. $messageTab[0].checked = isTabSupported;
  2253. event.preventDefault();
  2254. }
  2255. else if (isTabSupported && event.key === 'Tab') {
  2256. // get caret position & selection
  2257. const val = this.value,
  2258. start = this.selectionStart,
  2259. end = this.selectionEnd;
  2260. // set textarea value to: text before caret + tab + text after caret
  2261. this.value = val.substring(0, start) + '\t' + val.substring(end);
  2262. // put caret at right position again
  2263. this.selectionStart = this.selectionEnd = start + 1;
  2264. // prevent the textarea to lose focus
  2265. event.preventDefault();
  2266. }
  2267. }
  2268. /**
  2269. * toggle tab support in message textarea
  2270. *
  2271. * @name Editor.toggleTabSupport
  2272. * @private
  2273. * @function
  2274. */
  2275. function toggleTabSupport()
  2276. {
  2277. isTabSupported = !isTabSupported;
  2278. }
  2279. /**
  2280. * view the Editor tab
  2281. *
  2282. * @name Editor.viewEditor
  2283. * @function
  2284. * @param {Event} event - optional
  2285. */
  2286. function viewEditor(event)
  2287. {
  2288. // toggle buttons
  2289. $messageEdit.addClass('active');
  2290. $messageEditParent.addClass('active');
  2291. $messagePreview.removeClass('active');
  2292. $messagePreviewParent.removeClass('active');
  2293. $messageEdit.attr('aria-selected','true');
  2294. $messagePreview.attr('aria-selected','false');
  2295. PasteViewer.hide();
  2296. // reshow input
  2297. $message.removeClass('hidden');
  2298. $messageTabParent.removeClass('hidden');
  2299. me.focusInput();
  2300. // finish
  2301. isPreview = false;
  2302. // prevent jumping of page to top
  2303. if (typeof event !== 'undefined') {
  2304. event.preventDefault();
  2305. }
  2306. }
  2307. /**
  2308. * view the preview tab
  2309. *
  2310. * @name Editor.viewPreview
  2311. * @function
  2312. * @param {Event} event
  2313. */
  2314. function viewPreview(event)
  2315. {
  2316. // toggle buttons
  2317. $messageEdit.removeClass('active');
  2318. $messageEditParent.removeClass('active');
  2319. $messagePreview.addClass('active');
  2320. $messagePreviewParent.addClass('active');
  2321. $messageEdit.attr('aria-selected','false');
  2322. $messagePreview.attr('aria-selected','true');
  2323. // hide input as now preview is shown
  2324. $message.addClass('hidden');
  2325. $messageTabParent.addClass('hidden');
  2326. // show preview
  2327. PasteViewer.setText($message.val());
  2328. if (AttachmentViewer.hasAttachmentData()) {
  2329. const attachmentsData = AttachmentViewer.getAttachmentsData();
  2330. attachmentsData.forEach(attachmentData => {
  2331. const mimeType = AttachmentViewer.getAttachmentMimeType(attachmentData);
  2332. AttachmentViewer.handleBlobAttachmentPreview(
  2333. AttachmentViewer.getAttachmentPreview(),
  2334. attachmentData, mimeType
  2335. );
  2336. });
  2337. AttachmentViewer.showAttachment();
  2338. }
  2339. PasteViewer.run();
  2340. // finish
  2341. isPreview = true;
  2342. // prevent jumping of page to top
  2343. if (typeof event !== 'undefined') {
  2344. event.preventDefault();
  2345. }
  2346. }
  2347. /**
  2348. * get the state of the preview
  2349. *
  2350. * @name Editor.isPreview
  2351. * @function
  2352. */
  2353. me.isPreview = function()
  2354. {
  2355. return isPreview;
  2356. };
  2357. /**
  2358. * reset the Editor view
  2359. *
  2360. * @name Editor.resetInput
  2361. * @function
  2362. */
  2363. me.resetInput = function()
  2364. {
  2365. // go back to input
  2366. if (isPreview) {
  2367. viewEditor();
  2368. }
  2369. // clear content
  2370. $message.val('');
  2371. };
  2372. /**
  2373. * shows the Editor
  2374. *
  2375. * @name Editor.show
  2376. * @function
  2377. */
  2378. me.show = function()
  2379. {
  2380. $message.removeClass('hidden');
  2381. $messageTabParent.removeClass('hidden');
  2382. $editorTabs.removeClass('hidden');
  2383. };
  2384. /**
  2385. * hides the Editor
  2386. *
  2387. * @name Editor.hide
  2388. * @function
  2389. */
  2390. me.hide = function()
  2391. {
  2392. $message.addClass('hidden');
  2393. $messageTabParent.addClass('hidden');
  2394. $editorTabs.addClass('hidden');
  2395. };
  2396. /**
  2397. * focuses the message input
  2398. *
  2399. * @name Editor.focusInput
  2400. * @function
  2401. */
  2402. me.focusInput = function()
  2403. {
  2404. $message.focus();
  2405. };
  2406. /**
  2407. * sets a new text
  2408. *
  2409. * @name Editor.setText
  2410. * @function
  2411. * @param {string} newText
  2412. */
  2413. me.setText = function(newText)
  2414. {
  2415. $message.val(newText);
  2416. };
  2417. /**
  2418. * returns the current text
  2419. *
  2420. * @name Editor.getText
  2421. * @function
  2422. * @return {string}
  2423. */
  2424. me.getText = function()
  2425. {
  2426. return $message.val();
  2427. };
  2428. /**
  2429. * init editor
  2430. *
  2431. * preloads jQuery elements
  2432. *
  2433. * @name Editor.init
  2434. * @function
  2435. */
  2436. me.init = function()
  2437. {
  2438. $editorTabs = $('#editorTabs');
  2439. $message = $('#message');
  2440. $messageTab = $('#messagetab');
  2441. $messageTabParent = $messageTab.parent();
  2442. // bind events
  2443. $message.keydown(supportTabs);
  2444. $messageTab.change(toggleTabSupport);
  2445. // bind click events to tab switchers (a), and save parents (li)
  2446. $messageEdit = $('#messageedit').click(viewEditor);
  2447. $messageEditParent = $messageEdit.parent();
  2448. $messagePreview = $('#messagepreview').click(viewPreview);
  2449. $messagePreviewParent = $messagePreview.parent();
  2450. };
  2451. return me;
  2452. })();
  2453. /**
  2454. * (view) Parse and show document.
  2455. *
  2456. * @name PasteViewer
  2457. * @class
  2458. */
  2459. const PasteViewer = (function () {
  2460. const me = {};
  2461. let $messageTabParent,
  2462. $placeholder,
  2463. $prettyMessage,
  2464. $prettyPrint,
  2465. $plainText,
  2466. text,
  2467. format = 'plaintext',
  2468. isDisplayed = false,
  2469. isChanged = true; // by default true as nothing was parsed yet
  2470. /**
  2471. * apply the set format on paste and displays it
  2472. *
  2473. * @name PasteViewer.parsePaste
  2474. * @private
  2475. * @function
  2476. */
  2477. function parsePaste()
  2478. {
  2479. // skip parsing if no text is given
  2480. if (text === '') {
  2481. return;
  2482. }
  2483. if (format === 'markdown') {
  2484. const converter = new showdown.Converter({
  2485. strikethrough: true,
  2486. tables: true,
  2487. tablesHeaderId: true,
  2488. simplifiedAutoLink: true,
  2489. excludeTrailingPunctuationFromURLs: true
  2490. });
  2491. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2492. $plainText.html(
  2493. DOMPurify.sanitize(
  2494. converter.makeHtml(text),
  2495. purifyHtmlConfig
  2496. )
  2497. );
  2498. // add table classes from bootstrap css
  2499. $plainText.find('table').addClass('table-condensed table-bordered');
  2500. } else {
  2501. if (format === 'syntaxhighlighting') {
  2502. // yes, this is really needed to initialize the environment
  2503. if (typeof prettyPrint === 'function')
  2504. {
  2505. prettyPrint();
  2506. }
  2507. $prettyPrint.html(
  2508. prettyPrintOne(
  2509. Helper.htmlEntities(text), null, true
  2510. )
  2511. );
  2512. } else {
  2513. // = 'plaintext'
  2514. $prettyPrint.text(text);
  2515. }
  2516. Helper.urls2links($prettyPrint);
  2517. $prettyPrint.css('white-space', 'pre-wrap');
  2518. $prettyPrint.css('word-break', 'normal');
  2519. $prettyPrint.removeClass('prettyprint');
  2520. }
  2521. }
  2522. /**
  2523. * displays the document
  2524. *
  2525. * @name PasteViewer.showPaste
  2526. * @private
  2527. * @function
  2528. */
  2529. function showPaste()
  2530. {
  2531. // instead of "nothing" better display a placeholder
  2532. if (text === '') {
  2533. $placeholder.removeClass('hidden');
  2534. return;
  2535. }
  2536. // otherwise hide the placeholder
  2537. $placeholder.addClass('hidden');
  2538. $messageTabParent.addClass('hidden');
  2539. if (format === 'markdown') {
  2540. $plainText.removeClass('hidden');
  2541. $prettyMessage.addClass('hidden');
  2542. } else {
  2543. $plainText.addClass('hidden');
  2544. $prettyMessage.removeClass('hidden');
  2545. }
  2546. }
  2547. /**
  2548. * sets the format in which the text is shown
  2549. *
  2550. * @name PasteViewer.setFormat
  2551. * @function
  2552. * @param {string} newFormat the new format
  2553. */
  2554. me.setFormat = function(newFormat)
  2555. {
  2556. // skip if there is no update
  2557. if (format === newFormat) {
  2558. return;
  2559. }
  2560. // needs to update display too, if we switch from or to Markdown
  2561. if (format === 'markdown' || newFormat === 'markdown') {
  2562. isDisplayed = false;
  2563. }
  2564. format = newFormat;
  2565. isChanged = true;
  2566. // update preview
  2567. if (Editor.isPreview()) {
  2568. PasteViewer.run();
  2569. }
  2570. };
  2571. /**
  2572. * returns the current format
  2573. *
  2574. * @name PasteViewer.getFormat
  2575. * @function
  2576. * @return {string}
  2577. */
  2578. me.getFormat = function()
  2579. {
  2580. return format;
  2581. };
  2582. /**
  2583. * returns whether the current view is pretty printed
  2584. *
  2585. * @name PasteViewer.isPrettyPrinted
  2586. * @function
  2587. * @return {bool}
  2588. */
  2589. me.isPrettyPrinted = function()
  2590. {
  2591. return $prettyPrint.hasClass('prettyprinted');
  2592. };
  2593. /**
  2594. * sets the text to show
  2595. *
  2596. * @name PasteViewer.setText
  2597. * @function
  2598. * @param {string} newText the text to show
  2599. */
  2600. me.setText = function(newText)
  2601. {
  2602. if (text !== newText) {
  2603. text = newText;
  2604. isChanged = true;
  2605. }
  2606. };
  2607. /**
  2608. * gets the current cached text
  2609. *
  2610. * @name PasteViewer.getText
  2611. * @function
  2612. * @return {string}
  2613. */
  2614. me.getText = function()
  2615. {
  2616. return text;
  2617. };
  2618. /**
  2619. * show/update the parsed text (preview)
  2620. *
  2621. * @name PasteViewer.run
  2622. * @function
  2623. */
  2624. me.run = function()
  2625. {
  2626. if (isChanged) {
  2627. parsePaste();
  2628. isChanged = false;
  2629. }
  2630. if (!isDisplayed) {
  2631. showPaste();
  2632. isDisplayed = true;
  2633. }
  2634. };
  2635. /**
  2636. * hide parsed text (preview)
  2637. *
  2638. * @name PasteViewer.hide
  2639. * @function
  2640. */
  2641. me.hide = function()
  2642. {
  2643. if (!isDisplayed) {
  2644. return;
  2645. }
  2646. $plainText.addClass('hidden');
  2647. $prettyMessage.addClass('hidden');
  2648. $placeholder.addClass('hidden');
  2649. AttachmentViewer.hideAttachmentPreview();
  2650. isDisplayed = false;
  2651. };
  2652. /**
  2653. * init status manager
  2654. *
  2655. * preloads jQuery elements
  2656. *
  2657. * @name PasteViewer.init
  2658. * @function
  2659. */
  2660. me.init = function()
  2661. {
  2662. $messageTabParent = $('#messagetab').parent();
  2663. $placeholder = $('#placeholder');
  2664. $plainText = $('#plaintext');
  2665. $prettyMessage = $('#prettymessage');
  2666. $prettyPrint = $('#prettyprint');
  2667. // get default option from template/HTML or fall back to set value
  2668. format = Model.getFormatDefault() || format;
  2669. text = '';
  2670. isDisplayed = false;
  2671. isChanged = true;
  2672. };
  2673. return me;
  2674. })();
  2675. /**
  2676. * (view) Show attachment and preview if possible
  2677. *
  2678. * @name AttachmentViewer
  2679. * @class
  2680. */
  2681. const AttachmentViewer = (function () {
  2682. const me = {};
  2683. let attachmentPreview,
  2684. attachment,
  2685. attachmentsData = [],
  2686. files,
  2687. fileInput,
  2688. dragAndDropFileNames,
  2689. dropzone;
  2690. /**
  2691. * get blob URL from string data and mime type
  2692. *
  2693. * @name AttachmentViewer.getBlobUrl
  2694. * @private
  2695. * @function
  2696. * @param {string} data - raw data of attachment
  2697. * @param {string} data - mime type of attachment
  2698. * @return {string} objectURL
  2699. */
  2700. function getBlobUrl(data, mimeType)
  2701. {
  2702. // Transform into a Blob
  2703. const buf = new Uint8Array(data.length);
  2704. for (let i = 0; i < data.length; ++i) {
  2705. buf[i] = data.charCodeAt(i);
  2706. }
  2707. const blob = new window.Blob(
  2708. [buf],
  2709. {
  2710. type: mimeType
  2711. }
  2712. );
  2713. // Get blob URL
  2714. return window.URL.createObjectURL(blob);
  2715. }
  2716. /**
  2717. * sets the attachment but does not yet show it
  2718. *
  2719. * @name AttachmentViewer.setAttachment
  2720. * @function
  2721. * @param {string} attachmentData - base64-encoded data of file
  2722. * @param {string} fileName - optional, file name
  2723. */
  2724. me.setAttachment = function(attachmentData, fileName)
  2725. {
  2726. // skip, if attachments got disabled
  2727. if (!attachment || !attachmentPreview) return;
  2728. // data URI format: data:[<mimeType>][;base64],<data>
  2729. const template = Model.getTemplate('attachment');
  2730. const attachmentLink = template.querySelector('a');
  2731. // position in data URI string of where data begins
  2732. const base64Start = attachmentData.indexOf(',') + 1;
  2733. const mimeType = me.getAttachmentMimeType(attachmentData);
  2734. // extract data and convert to binary
  2735. const rawData = attachmentData.substring(base64Start);
  2736. const decodedData = rawData.length > 0 ? atob(rawData) : '';
  2737. let blobUrl = getBlobUrl(decodedData, mimeType);
  2738. attachmentLink.setAttribute('href', blobUrl);
  2739. if (typeof fileName !== 'undefined') {
  2740. attachmentLink.setAttribute('download', fileName);
  2741. const fileSize = Helper.formatBytes(decodedData.length);
  2742. const spans = template.querySelectorAll('span');
  2743. const span = spans[spans.length - 1];
  2744. span.textContent += ` (${fileName}, ${fileSize})`;
  2745. }
  2746. // sanitize SVG preview
  2747. // prevents executing embedded scripts when CSP is not set and user
  2748. // right-clicks/long-taps and opens the SVG in a new tab - prevented
  2749. // in the preview by use of an img tag, which disables scripts, too
  2750. if (mimeType.match(/^image\/.*svg/i)) {
  2751. const sanitizedData = DOMPurify.sanitize(
  2752. decodedData,
  2753. purifySvgConfig
  2754. );
  2755. blobUrl = getBlobUrl(sanitizedData, mimeType);
  2756. }
  2757. template.classList.remove('hidden');
  2758. attachment.appendChild(template);
  2759. me.handleBlobAttachmentPreview(attachmentPreview, blobUrl, mimeType);
  2760. };
  2761. /**
  2762. * displays the attachment
  2763. *
  2764. * @name AttachmentViewer.showAttachment
  2765. * @function
  2766. */
  2767. me.showAttachment = function()
  2768. {
  2769. // skip, if attachments got disabled
  2770. if (!attachment || !attachmentPreview) return;
  2771. attachment.classList.remove('hidden');
  2772. if (me.hasAttachmentPreview()) {
  2773. attachmentPreview.classList.remove('hidden');
  2774. }
  2775. };
  2776. /**
  2777. * removes the attachment
  2778. *
  2779. * This automatically hides the attachment containers too, to
  2780. * prevent an inconsistent display.
  2781. *
  2782. * @name AttachmentViewer.removeAttachment
  2783. * @function
  2784. */
  2785. me.removeAttachment = function()
  2786. {
  2787. if (!attachment) {
  2788. return;
  2789. }
  2790. me.hideAttachment();
  2791. me.hideAttachmentPreview();
  2792. attachment.innerHTML = '';
  2793. attachmentPreview.innerHTML = '';
  2794. dragAndDropFileNames.innerHTML = '';
  2795. AttachmentViewer.removeAttachmentData();
  2796. };
  2797. /**
  2798. * removes the attachment data
  2799. *
  2800. * This removes the data, which would be uploaded otherwise.
  2801. *
  2802. * @name AttachmentViewer.removeAttachmentData
  2803. * @function
  2804. */
  2805. me.removeAttachmentData = function()
  2806. {
  2807. files = undefined;
  2808. attachmentsData = [];
  2809. };
  2810. /**
  2811. * Cleares the drag & drop data.
  2812. *
  2813. * @name AttachmentViewer.clearDragAndDrop
  2814. * @function
  2815. */
  2816. me.clearDragAndDrop = function()
  2817. {
  2818. $dragAndDropFileNames.html('');
  2819. };
  2820. /**
  2821. * Print file names added via drag & drop
  2822. *
  2823. * @name AttachmentViewer.printDragAndDropFileNames
  2824. * @private
  2825. * @function
  2826. * @param {string[]} fileNames
  2827. */
  2828. function printDragAndDropFileNames(fileNames) {
  2829. $dragAndDropFileNames.empty();
  2830. fileNames.forEach(fileName => {
  2831. const name = document.createTextNode(fileName);
  2832. $dragAndDropFileNames[0].appendChild(name);
  2833. $dragAndDropFileNames[0].appendChild(document.createElement('br'));
  2834. });
  2835. }
  2836. /**
  2837. * hides the attachment
  2838. *
  2839. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2840. * for that) nor will it hide the attachment link if it was moved somewhere
  2841. * else (see AttachmentViewer.moveAttachmentTo).
  2842. *
  2843. * @name AttachmentViewer.hideAttachment
  2844. * @function
  2845. */
  2846. me.hideAttachment = function()
  2847. {
  2848. attachment.classList.add('hidden');
  2849. };
  2850. /**
  2851. * hides the attachment preview
  2852. *
  2853. * @name AttachmentViewer.hideAttachmentPreview
  2854. * @function
  2855. */
  2856. me.hideAttachmentPreview = function()
  2857. {
  2858. if (attachmentPreview) {
  2859. attachmentPreview.classList.add('hidden');
  2860. }
  2861. };
  2862. /**
  2863. * checks if has any attachment preview
  2864. *
  2865. * @name AttachmentViewer.hasAttachmentPreview
  2866. * @function
  2867. * @return {JQuery}
  2868. */
  2869. me.hasAttachmentPreview = function()
  2870. {
  2871. return attachmentPreview.children.length > 0;
  2872. }
  2873. /**
  2874. * checks if there is an attachment displayed
  2875. *
  2876. * @name AttachmentViewer.hasAttachment
  2877. * @function
  2878. */
  2879. me.hasAttachment = function()
  2880. {
  2881. if (!attachment) {
  2882. return false;
  2883. }
  2884. return attachment.children.length > 0;
  2885. };
  2886. /**
  2887. * checks if there is attachment data (for preview!) available
  2888. *
  2889. * It returns true, when there is data that needs to be encrypted.
  2890. *
  2891. * @name AttachmentViewer.hasAttachmentData
  2892. * @function
  2893. */
  2894. me.hasAttachmentData = function()
  2895. {
  2896. if (attachment) {
  2897. return true;
  2898. }
  2899. return false;
  2900. };
  2901. /**
  2902. * return the attachments
  2903. *
  2904. * @name AttachmentViewer.getAttachments
  2905. * @function
  2906. * @returns {array}
  2907. */
  2908. me.getAttachments = function()
  2909. {
  2910. return [...attachment.querySelectorAll('a')].map(link => (
  2911. [
  2912. link.href,
  2913. link.download
  2914. ]
  2915. ));
  2916. };
  2917. /**
  2918. * Get attachment mime type
  2919. *
  2920. * @name AttachmentViewer.getAttachmentMimeType
  2921. * @function
  2922. * @param {string} attachmentData - Base64 string
  2923. */
  2924. me.getAttachmentMimeType = function(attachmentData)
  2925. {
  2926. // position in data URI string of where mimeType ends
  2927. const mimeTypeEnd = attachmentData.indexOf(';');
  2928. // extract mimeType
  2929. return attachmentData.substring(5, mimeTypeEnd);
  2930. }
  2931. /**
  2932. * moves the attachment link to another element
  2933. *
  2934. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2935. *
  2936. * @name AttachmentViewer.moveAttachmentTo
  2937. * @function
  2938. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2939. * @param {array} attachment - attachment data
  2940. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2941. */
  2942. me.moveAttachmentTo = function($element, attachment, label)
  2943. {
  2944. const attachmentLink = $(document.createElement('a'))
  2945. .addClass('alert-link')
  2946. .prop('href', attachment[0])
  2947. .prop('download', attachment[1]);
  2948. // move elemement to new place
  2949. attachmentLink.appendTo($element);
  2950. // update text - ensuring no HTML is inserted into the text node
  2951. I18n._(attachmentLink, label, attachment[1]);
  2952. };
  2953. /**
  2954. * read files data as data URL using the FileReader API
  2955. *
  2956. * @name AttachmentViewer.readFileData
  2957. * @private
  2958. * @function
  2959. * @param {FileList[]} loadedFiles (optional) loaded files array
  2960. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2961. */
  2962. function readFileData(loadedFiles = []) {
  2963. // Clear old cache
  2964. me.removeAttachmentData();
  2965. if (typeof FileReader === 'undefined') {
  2966. // revert loading status…
  2967. me.hideAttachment();
  2968. me.hideAttachmentPreview();
  2969. Alert.showWarning('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2970. return;
  2971. }
  2972. if (loadedFiles && loadedFiles.length > 0) {
  2973. const fileNames = loadedFiles.map((loadedFile => loadedFile.name));
  2974. printDragAndDropFileNames(fileNames);
  2975. } else {
  2976. loadedFiles = [...$fileInput[0].files];
  2977. me.clearDragAndDrop();
  2978. }
  2979. if (loadedFiles.length > 0) {
  2980. files = loadedFiles;
  2981. loadedFiles.forEach((loadedFile, index) => {
  2982. const fileReader = new FileReader();
  2983. fileReader.onload = function (event) {
  2984. const dataURL = event.target.result;
  2985. if (dataURL) {
  2986. attachmentsData[index] = dataURL;
  2987. }
  2988. if (Editor.isPreview()) {
  2989. me.handleAttachmentPreview(attachmentPreview, dataURL);
  2990. attachmentPreview.classList.remove('hidden');
  2991. }
  2992. TopNav.highlightFileupload();
  2993. };
  2994. fileReader.readAsDataURL(loadedFile);
  2995. });
  2996. } else {
  2997. me.removeAttachmentData();
  2998. }
  2999. }
  3000. /**
  3001. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  3002. *
  3003. * @name AttachmentViewer.handleBlobAttachmentPreview
  3004. * @function
  3005. * @argument {HTMLElement} targetElement element where the preview should be appended
  3006. * @argument {string} file as a blob URL
  3007. * @argument {string} mime type
  3008. */
  3009. me.handleBlobAttachmentPreview = function (targetElement, blobUrl, mimeType) {
  3010. const alreadyIncludesCurrentAttachment = targetElement.querySelectorAll(`[src='${blobUrl}']`).length > 0;
  3011. if (blobUrl && !alreadyIncludesCurrentAttachment) {
  3012. if (mimeType.toLowerCase().startsWith('image/')) {
  3013. const image = document.createElement('img');
  3014. image.setAttribute('src', blobUrl);
  3015. image.setAttribute('class', 'img-thumbnail');
  3016. targetElement.appendChild(image);
  3017. } else if (mimeType.toLowerCase().startsWith('video/')) {
  3018. const video = document.createElement('video');
  3019. video.setAttribute('controls', 'true');
  3020. video.setAttribute('autoplay', 'true');
  3021. video.setAttribute('class', 'img-thumbnail');
  3022. const source = document.createElement('source');
  3023. source.setAttribute('type', mimeType);
  3024. source.setAttribute('src', blobUrl);
  3025. video.appendChild(source);
  3026. targetElement.appendChild(video);
  3027. } else if (mimeType.toLowerCase().startsWith('audio/')) {
  3028. const audio = document.createElement('audio');
  3029. audio.setAttribute('controls', 'true');
  3030. audio.setAttribute('autoplay', 'true');
  3031. const source = document.createElement('source');
  3032. source.setAttribute('type', mimeType);
  3033. source.setAttribute('src', blobUrl);
  3034. audio.appendChild(source);
  3035. targetElement.appendChild(audio);
  3036. } else if (mimeType.toLowerCase().endsWith('/pdf')) {
  3037. const embed = document.createElement('embed');
  3038. embed.setAttribute('src', blobUrl);
  3039. embed.setAttribute('type', 'application/pdf');
  3040. embed.setAttribute('class', 'pdfPreview');
  3041. // Fallback for browsers, that don't support the vh unit
  3042. embed.style.height = window.innerHeight + 'px';
  3043. targetElement.appendChild(embed);
  3044. }
  3045. }
  3046. };
  3047. /**
  3048. * attaches the file attachment drag & drop handler to the page
  3049. *
  3050. * @name AttachmentViewer.addDragDropHandler
  3051. * @private
  3052. * @function
  3053. */
  3054. function addDragDropHandler() {
  3055. if (typeof fileInput === 'undefined' || fileInput === null) {
  3056. return;
  3057. }
  3058. const handleDragEnterOrOver = function(event) {
  3059. event.stopPropagation();
  3060. event.preventDefault();
  3061. return false;
  3062. };
  3063. const handleDrop = function(event) {
  3064. event.stopPropagation();
  3065. event.preventDefault();
  3066. if (TopNav.isAttachmentReadonly()) {
  3067. return false;
  3068. }
  3069. if (fileInput) {
  3070. const files = [...event.dataTransfer.files];
  3071. //Clear the file input:
  3072. fileInput.value = '';
  3073. //Only works in Chrome:
  3074. //fileInput.files = event.dataTransfer.files;
  3075. readFileData(files);
  3076. }
  3077. };
  3078. draghover(document);
  3079. document.addEventListener('draghoverstart', function(e) {
  3080. if (TopNav.isAttachmentReadonly()) {
  3081. e.stopPropagation();
  3082. e.preventDefault();
  3083. return false;
  3084. }
  3085. // show dropzone to indicate drop support
  3086. dropzone.classList.remove('hidden');
  3087. });
  3088. document.addEventListener('draghoverend', function() {
  3089. dropzone.classList.add('hidden');
  3090. });
  3091. document.addEventListener('drop', handleDrop);
  3092. document.addEventListener('dragenter', handleDragEnterOrOver);
  3093. document.addEventListener('dragover', handleDragEnterOrOver);
  3094. fileInput.addEventListener('change', function () {
  3095. readFileData();
  3096. });
  3097. }
  3098. /**
  3099. * attaches the clipboard attachment handler to the page
  3100. *
  3101. * @name AttachmentViewer.addClipboardEventHandler
  3102. * @private
  3103. * @function
  3104. */
  3105. function addClipboardEventHandler() {
  3106. document.addEventListener('paste', (event) => {
  3107. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  3108. const files = [...items]
  3109. .filter(item => item.kind === 'file')
  3110. .map(item => item.getAsFile());
  3111. if (TopNav.isAttachmentReadonly() && files.length) {
  3112. event.stopPropagation();
  3113. event.preventDefault();
  3114. return false;
  3115. }
  3116. if (files.length) {
  3117. readFileData(files);
  3118. }
  3119. });
  3120. }
  3121. /**
  3122. * getter for attachment data
  3123. *
  3124. * @name AttachmentViewer.getAttachmentsData
  3125. * @function
  3126. * @return {string[]}
  3127. */
  3128. me.getAttachmentsData = function () {
  3129. return attachmentsData;
  3130. };
  3131. /**
  3132. * getter for attachment preview
  3133. *
  3134. * @name AttachmentViewer.getAttachmentPreview
  3135. * @function
  3136. * @return {jQuery}
  3137. */
  3138. me.getAttachmentPreview = function () {
  3139. return $attachmentPreview;
  3140. };
  3141. /**
  3142. * getter for files data, returns the file list
  3143. *
  3144. * @name AttachmentViewer.getFiles
  3145. * @function
  3146. * @return {FileList[]}
  3147. */
  3148. me.getFiles = function () {
  3149. return files;
  3150. };
  3151. /**
  3152. * initiate
  3153. *
  3154. * preloads jQuery elements
  3155. *
  3156. * @name AttachmentViewer.init
  3157. * @function
  3158. */
  3159. me.init = function()
  3160. {
  3161. attachment = document.getElementById('attachment');
  3162. dragAndDropFileNames = document.getElementById('dragAndDropFileName');
  3163. dropzone = document.getElementById('dropzone');
  3164. if(attachment) {
  3165. attachmentPreview = document.getElementById('attachmentPreview');
  3166. fileInput = document.getElementById('file');
  3167. addDragDropHandler();
  3168. addClipboardEventHandler();
  3169. }
  3170. }
  3171. return me;
  3172. })();
  3173. /**
  3174. * (view) Shows discussion thread and handles replies
  3175. *
  3176. * @name DiscussionViewer
  3177. * @class
  3178. */
  3179. const DiscussionViewer = (function () {
  3180. const me = {};
  3181. let commentTail,
  3182. discussion,
  3183. reply,
  3184. replyMessage,
  3185. replyNickname,
  3186. replyStatus,
  3187. commentContainer,
  3188. replyCommentId;
  3189. /**
  3190. * initializes the templates
  3191. *
  3192. * @name DiscussionViewer.initTemplates
  3193. * @private
  3194. * @function
  3195. */
  3196. function initTemplates()
  3197. {
  3198. reply = Model.getTemplate('reply');
  3199. replyMessage = reply.querySelector('#replymessage');
  3200. replyNickname = reply.querySelector('#nickname');
  3201. replyStatus = reply.querySelector('#replystatus');
  3202. // cache elements
  3203. commentTail = Model.getTemplate('commenttail');
  3204. }
  3205. /**
  3206. * open the comment entry when clicking the "Reply" button of a comment
  3207. *
  3208. * @name DiscussionViewer.openReply
  3209. * @private
  3210. * @function
  3211. * @param {Event} event
  3212. */
  3213. function openReply(event)
  3214. {
  3215. const source = event.target;
  3216. // show all reply buttons
  3217. commentContainer.querySelectorAll('button').forEach(btn => btn.classList.remove('hidden'));
  3218. // hide the current reply button
  3219. source.classList.add('hidden');
  3220. // clear input
  3221. replyMessage.value = '';
  3222. replyNickname.value = '';
  3223. // get comment id from source element
  3224. replyCommentId = source.parentElement.id.split('_')[1];
  3225. // move to correct position
  3226. source.after(reply);
  3227. // show
  3228. reply.classList.remove('hidden');
  3229. replyMessage.focus();
  3230. event.preventDefault();
  3231. }
  3232. /**
  3233. * custom handler for displaying notifications in own status message area
  3234. *
  3235. * @name DiscussionViewer.handleNotification
  3236. * @function
  3237. * @param {string} alertType
  3238. * @return {bool|jQuery}
  3239. */
  3240. me.handleNotification = function(alertType)
  3241. {
  3242. // ignore loading messages
  3243. if (alertType === 'loading') {
  3244. return false;
  3245. }
  3246. if (alertType === 'danger') {
  3247. replyStatus.classList.remove('alert-info');
  3248. replyStatus.classList.add('alert-danger');
  3249. replyStatus.querySelector(':first-child').classList.remove('glyphicon-alert');
  3250. replyStatus.querySelector(':first-child').classList.add('glyphicon-info-sign');
  3251. } else {
  3252. replyStatus.classList.remove('alert-danger');
  3253. replyStatus.classList.add('alert-info');
  3254. replyStatus.querySelector(':first-child').classList.remove('glyphicon-info-sign');
  3255. replyStatus.querySelector(':first-child').classList.add('glyphicon-alert');
  3256. }
  3257. return replyStatus;
  3258. };
  3259. /**
  3260. * adds another comment
  3261. *
  3262. * @name DiscussionViewer.addComment
  3263. * @function
  3264. * @param {Comment} comment
  3265. * @param {string} commentText
  3266. * @param {string} nickname
  3267. */
  3268. me.addComment = function(comment, commentText, nickname)
  3269. {
  3270. if (commentText === '') {
  3271. commentText = 'comment decryption failed';
  3272. }
  3273. // create new comment based on template
  3274. const commentEntry = Model.getTemplate('comment');
  3275. commentEntry.id = 'comment_' + comment.id;
  3276. const commentEntryData = commentEntry.querySelector('div.commentdata');
  3277. // set & parse text
  3278. commentEntryData.textContent = commentText;
  3279. Helper.urls2links(commentEntryData);
  3280. // set nickname
  3281. if (nickname.length > 0) {
  3282. commentEntry.querySelector('span.nickname').textContent = nickname;
  3283. } else {
  3284. const anonCommenter = document.createElement('em');
  3285. anonCommenter.textContent = I18n._('Anonymous');
  3286. commentEntry.querySelector('span.nickname').innerHTML = '';
  3287. commentEntry.querySelector('span.nickname').appendChild(anonCommenter);
  3288. }
  3289. // set date
  3290. const created = comment.getCreated();
  3291. const commentDate = created === 0 ? '' : ' (' + (new Date(created * 1000).toLocaleString()) + ')';
  3292. const dateSpan = commentEntry.querySelector('span.commentdate');
  3293. dateSpan.textContent = commentDate;
  3294. dateSpan.setAttribute('title', 'CommentID: ' + comment.id);
  3295. // if an avatar is available, display it
  3296. const icon = comment.getIcon();
  3297. if (icon) {
  3298. const image = document.createElement('img');
  3299. image.setAttribute('src', icon);
  3300. image.setAttribute('class', 'vizhash');
  3301. const nickSpan = commentEntry.querySelector('span.nickname');
  3302. nickSpan.prepend(' ');
  3303. nickSpan.prepend(image);
  3304. }
  3305. // starting point (default value/fallback)
  3306. let place = commentContainer;
  3307. // if parent comment exists
  3308. const parentComment = document.getElementById('comment_' + comment.parentid);
  3309. if (parentComment) {
  3310. // use parent as position for new comment, so it is shifted
  3311. // to the right
  3312. place = parentComment;
  3313. }
  3314. // finally append comment
  3315. place.appendChild(commentEntry);
  3316. };
  3317. /**
  3318. * finishes the discussion area after last comment
  3319. *
  3320. * @name DiscussionViewer.finishDiscussion
  3321. * @function
  3322. */
  3323. me.finishDiscussion = function()
  3324. {
  3325. // add 'add new comment' area
  3326. commentContainer.appendChild(commentTail);
  3327. // show discussions
  3328. discussion.classList.remove('hidden');
  3329. };
  3330. /**
  3331. * removes the old discussion and prepares everything for creating a new
  3332. * one.
  3333. *
  3334. * @name DiscussionViewer.prepareNewDiscussion
  3335. * @function
  3336. */
  3337. me.prepareNewDiscussion = function()
  3338. {
  3339. commentContainer.innerHTML = '';
  3340. discussion.classList.add('hidden');
  3341. // (re-)init templates
  3342. initTemplates();
  3343. };
  3344. /**
  3345. * returns the users message from the reply form
  3346. *
  3347. * @name DiscussionViewer.getReplyMessage
  3348. * @function
  3349. * @return {String}
  3350. */
  3351. me.getReplyMessage = function()
  3352. {
  3353. return $replyMessage.val();
  3354. };
  3355. /**
  3356. * returns the users nickname (if any) from the reply form
  3357. *
  3358. * @name DiscussionViewer.getReplyNickname
  3359. * @function
  3360. * @return {String}
  3361. */
  3362. me.getReplyNickname = function()
  3363. {
  3364. return $replyNickname.val();
  3365. };
  3366. /**
  3367. * returns the id of the parent comment the user is replying to
  3368. *
  3369. * @name DiscussionViewer.getReplyCommentId
  3370. * @function
  3371. * @return {int|undefined}
  3372. */
  3373. me.getReplyCommentId = function()
  3374. {
  3375. return replyCommentId;
  3376. };
  3377. /**
  3378. * highlights a specific comment and scrolls to it if necessary
  3379. *
  3380. * @name DiscussionViewer.highlightComment
  3381. * @function
  3382. * @param {string} commentId
  3383. * @param {bool} fadeOut - whether to fade out the comment
  3384. */
  3385. me.highlightComment = function(commentId, fadeOut)
  3386. {
  3387. const comment = document.getElementById('comment_' + commentId);
  3388. // in case comment does not exist, cancel
  3389. if (!comment) {
  3390. return;
  3391. }
  3392. comment.classList.add('highlight');
  3393. const highlightComment = function () {
  3394. if (fadeOut === true) {
  3395. setTimeout(function () {
  3396. comment.classList.remove('highlight');
  3397. }, 300);
  3398. }
  3399. };
  3400. if (UiHelper.isVisible(comment)) {
  3401. return highlightComment();
  3402. }
  3403. UiHelper.scrollTo(comment, 100, 'swing', highlightComment);
  3404. };
  3405. /**
  3406. * initiate
  3407. *
  3408. * preloads jQuery elements
  3409. *
  3410. * @name DiscussionViewer.init
  3411. * @function
  3412. */
  3413. me.init = function()
  3414. {
  3415. // bind events to templates (so they are later cloned)
  3416. document.getElementById('commenttailtemplate').querySelectorAll('button').forEach(btn => btn.addEventListener('click', openReply));
  3417. document.getElementById('commenttemplate').querySelectorAll('button').forEach(btn => btn.addEventListener('click', openReply));
  3418. document.getElementById('replytemplate').querySelectorAll('button').forEach(btn => btn.addEventListener('click', PasteEncrypter.sendComment));
  3419. commentContainer = document.getElementById('commentcontainer');
  3420. discussion = document.getElementById('discussion');
  3421. };
  3422. return me;
  3423. })();
  3424. /**
  3425. * Manage top (navigation) bar
  3426. *
  3427. * @name TopNav
  3428. * @param {object} window
  3429. * @param {object} document
  3430. * @class
  3431. */
  3432. const TopNav = (function (window, document) {
  3433. const me = {};
  3434. let createButtonsDisplayed = false,
  3435. viewButtonsDisplayed = false,
  3436. burnAfterReadingDefault = false,
  3437. openDiscussionDefault = false,
  3438. $attach,
  3439. $burnAfterReading,
  3440. $burnAfterReadingOption,
  3441. $cloneButton,
  3442. $customAttachment,
  3443. $expiration,
  3444. $fileRemoveButton,
  3445. $fileWrap,
  3446. $formatter,
  3447. $newButton,
  3448. $openDiscussion,
  3449. $openDiscussionOption,
  3450. $password,
  3451. $passwordInput,
  3452. $rawTextButton,
  3453. $downloadTextButton,
  3454. $qrCodeLink,
  3455. $emailLink,
  3456. $sendButton,
  3457. $retryButton,
  3458. pasteExpiration = null,
  3459. retryButtonCallback;
  3460. /**
  3461. * set the expiration on bootstrap templates in dropdown
  3462. *
  3463. * @name TopNav.updateExpiration
  3464. * @private
  3465. * @function
  3466. * @param {Event} event
  3467. */
  3468. function updateExpiration(event)
  3469. {
  3470. // get selected option
  3471. const target = $(event.target);
  3472. // update dropdown display and save new expiration time
  3473. $('#pasteExpirationDisplay').text(target.text());
  3474. pasteExpiration = target.data('expiration');
  3475. event.preventDefault();
  3476. }
  3477. /**
  3478. * set the format on bootstrap templates in dropdown from user interaction
  3479. *
  3480. * @name TopNav.updateFormat
  3481. * @private
  3482. * @function
  3483. * @param {Event} event
  3484. */
  3485. function updateFormat(event)
  3486. {
  3487. // get selected option
  3488. const $target = $(event.target);
  3489. // update dropdown display and save new format
  3490. const newFormat = $target.data('format');
  3491. $('#pasteFormatterDisplay').text($target.text());
  3492. PasteViewer.setFormat(newFormat);
  3493. event.preventDefault();
  3494. }
  3495. /**
  3496. * when "burn after reading" is checked, disable discussion
  3497. *
  3498. * @name TopNav.changeBurnAfterReading
  3499. * @private
  3500. * @function
  3501. */
  3502. function changeBurnAfterReading()
  3503. {
  3504. if (me.getBurnAfterReading()) {
  3505. $openDiscussionOption.addClass('buttondisabled');
  3506. $openDiscussion.prop('checked', false);
  3507. // if button is actually disabled, force-enable it and uncheck other button
  3508. $burnAfterReadingOption.removeClass('buttondisabled');
  3509. } else {
  3510. $openDiscussionOption.removeClass('buttondisabled');
  3511. }
  3512. }
  3513. /**
  3514. * when discussion is checked, disable "burn after reading"
  3515. *
  3516. * @name TopNav.changeOpenDiscussion
  3517. * @private
  3518. * @function
  3519. */
  3520. function changeOpenDiscussion()
  3521. {
  3522. if (me.getOpenDiscussion()) {
  3523. $burnAfterReadingOption.addClass('buttondisabled');
  3524. $burnAfterReading.prop('checked', false);
  3525. // if button is actually disabled, force-enable it and uncheck other button
  3526. $openDiscussionOption.removeClass('buttondisabled');
  3527. } else {
  3528. $burnAfterReadingOption.removeClass('buttondisabled');
  3529. }
  3530. }
  3531. /**
  3532. * Clear the password input in the top navigation
  3533. *
  3534. * @name TopNav.clearPasswordInput
  3535. * @function
  3536. */
  3537. function clearPasswordInput()
  3538. {
  3539. $passwordInput.val('');
  3540. }
  3541. /**
  3542. * Clear the attachment input in the top navigation.
  3543. *
  3544. * @name TopNav.clearAttachmentInput
  3545. * @function
  3546. */
  3547. function clearAttachmentInput()
  3548. {
  3549. // hide UI for selected files
  3550. // our up-to-date jQuery can handle it :)
  3551. $fileWrap.find('input').val('');
  3552. }
  3553. /**
  3554. * return raw text
  3555. *
  3556. * @name TopNav.rawText
  3557. * @private
  3558. * @function
  3559. */
  3560. function rawText()
  3561. {
  3562. TopNav.hideAllButtons();
  3563. Alert.showLoading('Showing raw text…', 'time');
  3564. let paste = PasteViewer.getText();
  3565. // push a new state to allow back navigation with browser back button
  3566. history.pushState(
  3567. {type: 'raw'},
  3568. document.title,
  3569. // recreate document URL
  3570. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3571. CryptTool.base58encode(Model.getPasteKey())
  3572. );
  3573. // we use text/html instead of text/plain to avoid a bug when
  3574. // reloading the raw text view (it reverts to type text/html)
  3575. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3576. newDoc = document.open('text/html', 'replace');
  3577. newDoc.write('<!DOCTYPE html><html><head>');
  3578. for (let i = 0; i < $head.length; ++i) {
  3579. newDoc.write($head[i].outerHTML);
  3580. }
  3581. newDoc.write(
  3582. '</head><body><pre>' +
  3583. DOMPurify.sanitize(
  3584. Helper.htmlEntities(paste),
  3585. purifyHtmlConfig
  3586. ) +
  3587. '</pre></body></html>'
  3588. );
  3589. newDoc.close();
  3590. }
  3591. /**
  3592. * download text
  3593. *
  3594. * @name TopNav.downloadText
  3595. * @private
  3596. * @function
  3597. */
  3598. function downloadText()
  3599. {
  3600. const fileFormat = PasteViewer.getFormat() === 'markdown' ? '.md' : '.txt';
  3601. const filename = 'document-' + Model.getPasteId() + fileFormat;
  3602. const text = PasteViewer.getText();
  3603. const element = document.createElement('a');
  3604. element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  3605. element.setAttribute('download', filename);
  3606. element.style.display = 'none';
  3607. document.body.appendChild(element);
  3608. element.click();
  3609. document.body.removeChild(element);
  3610. }
  3611. /**
  3612. * saves the language in a cookie and reloads the page
  3613. *
  3614. * @name TopNav.setLanguage
  3615. * @private
  3616. * @function
  3617. * @param {Event} event
  3618. */
  3619. function setLanguage(event)
  3620. {
  3621. let lang = $(event.target).data('lang') || event.target.value;
  3622. document.cookie = 'lang=' + lang + '; SameSite=Lax; Secure';
  3623. window.location.reload();
  3624. event.preventDefault();
  3625. }
  3626. /**
  3627. * save the template in a cookie and reloads the page
  3628. *
  3629. * @name TopNav.setTemplate
  3630. * @private
  3631. * @function
  3632. * @param {Event} event
  3633. */
  3634. function setTemplate(event)
  3635. {
  3636. let template = $(event.target).data('template') || event.target.value;
  3637. document.cookie = 'template=' + template + '; SameSite=Lax; Secure';
  3638. window.location.reload();
  3639. event.preventDefault();
  3640. }
  3641. /**
  3642. * hides all messages and creates a new document
  3643. *
  3644. * @name TopNav.clickNewPaste
  3645. * @private
  3646. * @function
  3647. */
  3648. function clickNewPaste()
  3649. {
  3650. Controller.hideStatusMessages();
  3651. Controller.newPaste();
  3652. }
  3653. /**
  3654. * retrys some callback registered before
  3655. *
  3656. * @name TopNav.clickRetryButton
  3657. * @private
  3658. * @function
  3659. * @param {Event} event
  3660. */
  3661. function clickRetryButton(event)
  3662. {
  3663. retryButtonCallback(event);
  3664. }
  3665. /**
  3666. * removes the existing attachment
  3667. *
  3668. * @name TopNav.removeAttachment
  3669. * @private
  3670. * @function
  3671. * @param {Event} event
  3672. */
  3673. function removeAttachment(event)
  3674. {
  3675. // if custom attachment is used, remove it first
  3676. if (!$customAttachment.hasClass('hidden')) {
  3677. AttachmentViewer.removeAttachment();
  3678. $customAttachment.addClass('hidden');
  3679. $fileWrap.removeClass('hidden');
  3680. }
  3681. // in any case, remove saved attachment data
  3682. AttachmentViewer.removeAttachmentData();
  3683. clearAttachmentInput();
  3684. AttachmentViewer.clearDragAndDrop();
  3685. // pevent '#' from appearing in the URL
  3686. event.preventDefault();
  3687. }
  3688. /**
  3689. * Shows the QR code of the current document (URL).
  3690. *
  3691. * @name TopNav.displayQrCode
  3692. * @private
  3693. * @function
  3694. */
  3695. function displayQrCode()
  3696. {
  3697. const qrCanvas = kjua({
  3698. render: 'canvas',
  3699. text: window.location.href
  3700. });
  3701. $('#qrcode-display').html(qrCanvas);
  3702. }
  3703. /**
  3704. * Template Email body.
  3705. *
  3706. * @name TopNav.templateEmailBody
  3707. * @private
  3708. * @param {string} expirationDateString
  3709. * @param {bool} isBurnafterreading
  3710. */
  3711. function templateEmailBody(expirationDateString, isBurnafterreading)
  3712. {
  3713. const EOL = '\n';
  3714. const BULLET = ' - ';
  3715. let emailBody = '';
  3716. if (expirationDateString !== null || isBurnafterreading) {
  3717. emailBody += I18n._('Notice:');
  3718. emailBody += EOL;
  3719. if (expirationDateString !== null) {
  3720. emailBody += EOL;
  3721. emailBody += BULLET;
  3722. // avoid DOMPurify mess with forward slash in expirationDateString
  3723. emailBody += Helper.sprintf(
  3724. I18n._(
  3725. 'This link will expire after %s.',
  3726. '%s'
  3727. ),
  3728. expirationDateString
  3729. );
  3730. }
  3731. if (isBurnafterreading) {
  3732. emailBody += EOL;
  3733. emailBody += BULLET;
  3734. emailBody += I18n._(
  3735. 'This link can only be accessed once, do not use back or refresh button in your browser.'
  3736. );
  3737. }
  3738. emailBody += EOL;
  3739. emailBody += EOL;
  3740. }
  3741. emailBody += I18n._('Link:');
  3742. emailBody += EOL;
  3743. emailBody += $('#pasteurl').attr('href') || window.location.href; // href is tried first as it might have been shortened
  3744. return emailBody;
  3745. }
  3746. /**
  3747. * Trigger Email send.
  3748. *
  3749. * @name TopNav.triggerEmailSend
  3750. * @private
  3751. * @param {string} emailBody
  3752. */
  3753. function triggerEmailSend(emailBody)
  3754. {
  3755. window.open(
  3756. `mailto:?body=${encodeURIComponent(emailBody)}`,
  3757. '_self',
  3758. 'noopener, noreferrer'
  3759. );
  3760. }
  3761. /**
  3762. * Send Email with current document (URL).
  3763. *
  3764. * @name TopNav.sendEmail
  3765. * @private
  3766. * @function
  3767. * @param {Date|null} expirationDate date of expiration
  3768. * @param {bool} isBurnafterreading whether it is burn after reading
  3769. */
  3770. function sendEmail(expirationDate, isBurnafterreading)
  3771. {
  3772. const expirationDateRoundedToSecond = new Date(expirationDate);
  3773. // round down at least 30 seconds to make up for the delay of request
  3774. expirationDateRoundedToSecond.setUTCSeconds(
  3775. expirationDateRoundedToSecond.getUTCSeconds() - 30
  3776. );
  3777. expirationDateRoundedToSecond.setUTCSeconds(0);
  3778. const $emailconfirmmodal = $('#emailconfirmmodal');
  3779. if (expirationDate !== null) {
  3780. const $emailconfirmTimezoneCurrent = $emailconfirmmodal.find('#emailconfirm-timezone-current');
  3781. const $emailconfirmTimezoneUtc = $emailconfirmmodal.find('#emailconfirm-timezone-utc');
  3782. let localeConfiguration = { dateStyle: 'long', timeStyle: 'long' };
  3783. const bootstrap5EmailConfirmModal = typeof bootstrap !== 'undefined' && bootstrap.Tooltip.VERSION ?
  3784. new bootstrap.Modal($emailconfirmmodal[0]) : null;
  3785. function sendEmailAndHideModal() {
  3786. const emailBody = templateEmailBody(
  3787. // we don't use Date.prototype.toUTCString() because we would like to avoid GMT
  3788. expirationDateRoundedToSecond.toLocaleString(
  3789. [], localeConfiguration
  3790. ), isBurnafterreading
  3791. );
  3792. if (bootstrap5EmailConfirmModal) {
  3793. bootstrap5EmailConfirmModal.hide();
  3794. } else {
  3795. $emailconfirmmodal.modal('hide');
  3796. }
  3797. triggerEmailSend(emailBody);
  3798. }
  3799. $emailconfirmTimezoneCurrent.off('click.sendEmailCurrentTimezone');
  3800. $emailconfirmTimezoneCurrent.on('click.sendEmailCurrentTimezone', sendEmailAndHideModal);
  3801. $emailconfirmTimezoneUtc.off('click.sendEmailUtcTimezone');
  3802. $emailconfirmTimezoneUtc.on('click.sendEmailUtcTimezone', () => {
  3803. localeConfiguration.timeZone = 'UTC';
  3804. sendEmailAndHideModal();
  3805. });
  3806. if (bootstrap5EmailConfirmModal) {
  3807. bootstrap5EmailConfirmModal.show();
  3808. } else {
  3809. $emailconfirmmodal.modal('show');
  3810. }
  3811. } else {
  3812. triggerEmailSend(templateEmailBody(null, isBurnafterreading));
  3813. }
  3814. }
  3815. /**
  3816. * Shows all navigation elements for viewing an existing document
  3817. *
  3818. * @name TopNav.showViewButtons
  3819. * @function
  3820. */
  3821. me.showViewButtons = function()
  3822. {
  3823. if (viewButtonsDisplayed) {
  3824. return;
  3825. }
  3826. $newButton.removeClass('hidden');
  3827. $cloneButton.removeClass('hidden');
  3828. $rawTextButton.removeClass('hidden');
  3829. $downloadTextButton.removeClass('hidden');
  3830. $qrCodeLink.removeClass('hidden');
  3831. viewButtonsDisplayed = true;
  3832. };
  3833. /**
  3834. * Hides all navigation elements for viewing an existing document
  3835. *
  3836. * @name TopNav.hideViewButtons
  3837. * @function
  3838. */
  3839. me.hideViewButtons = function()
  3840. {
  3841. if (!viewButtonsDisplayed) {
  3842. return;
  3843. }
  3844. $cloneButton.addClass('hidden');
  3845. $newButton.addClass('hidden');
  3846. $rawTextButton.addClass('hidden');
  3847. $downloadTextButton.addClass('hidden');
  3848. $qrCodeLink.addClass('hidden');
  3849. me.hideEmailButton();
  3850. viewButtonsDisplayed = false;
  3851. };
  3852. /**
  3853. * Hides all elements belonging to existing documents
  3854. *
  3855. * @name TopNav.hideAllButtons
  3856. * @function
  3857. */
  3858. me.hideAllButtons = function()
  3859. {
  3860. me.hideViewButtons();
  3861. me.hideCreateButtons();
  3862. };
  3863. /**
  3864. * shows all elements needed when creating a new document
  3865. *
  3866. * @name TopNav.showCreateButtons
  3867. * @function
  3868. */
  3869. me.showCreateButtons = function()
  3870. {
  3871. if (createButtonsDisplayed) {
  3872. return;
  3873. }
  3874. $attach.removeClass('hidden');
  3875. $burnAfterReadingOption.removeClass('hidden');
  3876. $expiration.removeClass('hidden');
  3877. $formatter.removeClass('hidden');
  3878. $newButton.removeClass('hidden');
  3879. $openDiscussionOption.removeClass('hidden');
  3880. $password.removeClass('hidden');
  3881. $sendButton.removeClass('hidden');
  3882. createButtonsDisplayed = true;
  3883. };
  3884. /**
  3885. * shows all elements needed when creating a new document
  3886. *
  3887. * @name TopNav.hideCreateButtons
  3888. * @function
  3889. */
  3890. me.hideCreateButtons = function()
  3891. {
  3892. if (!createButtonsDisplayed) {
  3893. return;
  3894. }
  3895. $newButton.addClass('hidden');
  3896. $sendButton.addClass('hidden');
  3897. $expiration.addClass('hidden');
  3898. $formatter.addClass('hidden');
  3899. $burnAfterReadingOption.addClass('hidden');
  3900. $openDiscussionOption.addClass('hidden');
  3901. $password.addClass('hidden');
  3902. $attach.addClass('hidden');
  3903. createButtonsDisplayed = false;
  3904. };
  3905. /**
  3906. * only shows the "new document" button
  3907. *
  3908. * @name TopNav.showNewPasteButton
  3909. * @function
  3910. */
  3911. me.showNewPasteButton = function()
  3912. {
  3913. $newButton.removeClass('hidden');
  3914. };
  3915. /**
  3916. * only shows the "retry" button
  3917. *
  3918. * @name TopNav.showRetryButton
  3919. * @function
  3920. */
  3921. me.showRetryButton = function()
  3922. {
  3923. $retryButton.removeClass('hidden');
  3924. }
  3925. /**
  3926. * hides the "retry" button
  3927. *
  3928. * @name TopNav.hideRetryButton
  3929. * @function
  3930. */
  3931. me.hideRetryButton = function()
  3932. {
  3933. $retryButton.addClass('hidden');
  3934. }
  3935. /**
  3936. * show the "email" button
  3937. *
  3938. * @name TopNav.showEmailbutton
  3939. * @function
  3940. * @param {int|undefined} optionalRemainingTimeInSeconds
  3941. */
  3942. me.showEmailButton = function(optionalRemainingTimeInSeconds)
  3943. {
  3944. try {
  3945. // we cache expiration date in closure to avoid inaccurate expiration datetime
  3946. const expirationDate = Helper.calculateExpirationDate(
  3947. new Date(),
  3948. typeof optionalRemainingTimeInSeconds === 'number' ? optionalRemainingTimeInSeconds : TopNav.getExpiration()
  3949. );
  3950. const isBurnafterreading = TopNav.getBurnAfterReading();
  3951. $emailLink.removeClass('hidden');
  3952. $emailLink.off('click.sendEmail');
  3953. $emailLink.on('click.sendEmail', () => {
  3954. sendEmail(expirationDate, isBurnafterreading);
  3955. });
  3956. } catch (error) {
  3957. console.error(error);
  3958. Alert.showError('Cannot calculate expiration date.');
  3959. }
  3960. }
  3961. /**
  3962. * hide the "email" button
  3963. *
  3964. * @name TopNav.hideEmailButton
  3965. * @function
  3966. */
  3967. me.hideEmailButton = function()
  3968. {
  3969. $emailLink.addClass('hidden');
  3970. $emailLink.off('click.sendEmail');
  3971. }
  3972. /**
  3973. * only hides the clone button
  3974. *
  3975. * @name TopNav.hideCloneButton
  3976. * @function
  3977. */
  3978. me.hideCloneButton = function()
  3979. {
  3980. $cloneButton.addClass('hidden');
  3981. };
  3982. /**
  3983. * only hides the raw text button
  3984. *
  3985. * @name TopNav.hideRawButton
  3986. * @function
  3987. */
  3988. me.hideRawButton = function()
  3989. {
  3990. $rawTextButton.addClass('hidden');
  3991. };
  3992. /**
  3993. * only hides the download text button
  3994. *
  3995. * @name TopNav.hideRawButton
  3996. * @function
  3997. */
  3998. me.hideDownloadButton = function()
  3999. {
  4000. $downloadTextButton.addClass('hidden');
  4001. };
  4002. /**
  4003. * only hides the qr code button
  4004. *
  4005. * @name TopNav.hideQrCodeButton
  4006. * @function
  4007. */
  4008. me.hideQrCodeButton = function()
  4009. {
  4010. $qrCodeLink.addClass('hidden');
  4011. }
  4012. /**
  4013. * hide irrelevant buttons when viewing burn after reading document
  4014. *
  4015. * @name TopNav.hideBurnAfterReadingButtons
  4016. * @function
  4017. */
  4018. me.hideBurnAfterReadingButtons = function()
  4019. {
  4020. me.hideCloneButton();
  4021. me.hideQrCodeButton();
  4022. me.hideEmailButton();
  4023. }
  4024. /**
  4025. * hides the file selector in attachment
  4026. *
  4027. * @name TopNav.hideFileSelector
  4028. * @function
  4029. */
  4030. me.hideFileSelector = function()
  4031. {
  4032. $fileWrap.addClass('hidden');
  4033. };
  4034. /**
  4035. * shows the custom attachment
  4036. *
  4037. * @name TopNav.showCustomAttachment
  4038. * @function
  4039. */
  4040. me.showCustomAttachment = function()
  4041. {
  4042. $customAttachment.removeClass('hidden');
  4043. };
  4044. /**
  4045. * hides the custom attachment
  4046. *
  4047. * @name TopNav.hideCustomAttachment
  4048. * @function
  4049. */
  4050. me.hideCustomAttachment = function()
  4051. {
  4052. $customAttachment.addClass('hidden');
  4053. $fileWrap.removeClass('hidden');
  4054. };
  4055. /**
  4056. * collapses the navigation bar, only if expanded
  4057. *
  4058. * @name TopNav.collapseBar
  4059. * @function
  4060. */
  4061. me.collapseBar = function()
  4062. {
  4063. if ($('#navbar').attr('aria-expanded') === 'true') {
  4064. $('.navbar-toggle').click();
  4065. }
  4066. };
  4067. /**
  4068. * Reset the top navigation back to it's default values.
  4069. *
  4070. * @name TopNav.resetInput
  4071. * @function
  4072. */
  4073. me.resetInput = function()
  4074. {
  4075. clearAttachmentInput();
  4076. clearPasswordInput();
  4077. $burnAfterReading.prop('checked', burnAfterReadingDefault);
  4078. $openDiscussion.prop('checked', openDiscussionDefault);
  4079. if (openDiscussionDefault || !burnAfterReadingDefault) $openDiscussionOption.removeClass('buttondisabled');
  4080. if (burnAfterReadingDefault || !openDiscussionDefault) $burnAfterReadingOption.removeClass('buttondisabled');
  4081. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  4082. $('#pasteExpiration>option').each(function() {
  4083. const $this = $(this);
  4084. if ($this.val() === pasteExpiration) {
  4085. $('#pasteExpirationDisplay').text($this.text());
  4086. }
  4087. });
  4088. };
  4089. /**
  4090. * returns the currently set expiration time
  4091. *
  4092. * @name TopNav.getExpiration
  4093. * @function
  4094. * @return {int}
  4095. */
  4096. me.getExpiration = function()
  4097. {
  4098. return pasteExpiration;
  4099. };
  4100. /**
  4101. * returns the currently selected file(s)
  4102. *
  4103. * @name TopNav.getFileList
  4104. * @function
  4105. * @return {FileList|null}
  4106. */
  4107. me.getFileList = function()
  4108. {
  4109. const $file = $('#file');
  4110. // if no file given, return null
  4111. if (!$file.length || !$file[0].files.length) {
  4112. return null;
  4113. }
  4114. // ensure the selected file is still accessible
  4115. if (!($file[0].files && $file[0].files[0])) {
  4116. return null;
  4117. }
  4118. return $file[0].files;
  4119. };
  4120. /**
  4121. * returns the state of the burn after reading checkbox
  4122. *
  4123. * @name TopNav.getBurnAfterReading
  4124. * @function
  4125. * @return {bool}
  4126. */
  4127. me.getBurnAfterReading = function()
  4128. {
  4129. return $burnAfterReading.prop('checked');
  4130. };
  4131. /**
  4132. * returns the state of the discussion checkbox
  4133. *
  4134. * @name TopNav.getOpenDiscussion
  4135. * @function
  4136. * @return {bool}
  4137. */
  4138. me.getOpenDiscussion = function()
  4139. {
  4140. return $openDiscussion.prop('checked');
  4141. };
  4142. /**
  4143. * returns the entered password
  4144. *
  4145. * @name TopNav.getPassword
  4146. * @function
  4147. * @return {string}
  4148. */
  4149. me.getPassword = function()
  4150. {
  4151. // when password is disabled $passwordInput.val() will return undefined
  4152. return $passwordInput.val() || '';
  4153. };
  4154. /**
  4155. * returns the element where custom attachments can be placed
  4156. *
  4157. * Used by AttachmentViewer when an attachment is cloned here.
  4158. *
  4159. * @name TopNav.getCustomAttachment
  4160. * @function
  4161. * @return {jQuery}
  4162. */
  4163. me.getCustomAttachment = function()
  4164. {
  4165. return $customAttachment;
  4166. };
  4167. /**
  4168. * Set a function to call when the retry button is clicked.
  4169. *
  4170. * @name TopNav.setRetryCallback
  4171. * @function
  4172. * @param {function} callback
  4173. */
  4174. me.setRetryCallback = function(callback)
  4175. {
  4176. retryButtonCallback = callback;
  4177. }
  4178. /**
  4179. * Highlight file upload
  4180. *
  4181. * @name TopNav.highlightFileupload
  4182. * @function
  4183. */
  4184. me.highlightFileupload = function()
  4185. {
  4186. // visually indicate file uploaded
  4187. const $attachDropdownToggle = $attach.children('.dropdown-toggle');
  4188. if ($attachDropdownToggle.attr('aria-expanded') === 'false') {
  4189. if (Helper.isBootstrap5()) {
  4190. new bootstrap.Dropdown($attachDropdownToggle).toggle();
  4191. } else {
  4192. $attachDropdownToggle.click();
  4193. }
  4194. }
  4195. $fileWrap.addClass('highlight');
  4196. setTimeout(function () {
  4197. $fileWrap.removeClass('highlight');
  4198. }, 300);
  4199. }
  4200. /**
  4201. * set the format on bootstrap templates in dropdown programmatically
  4202. *
  4203. * @name TopNav.setFormat
  4204. * @function
  4205. */
  4206. me.setFormat = function(format)
  4207. {
  4208. if (Helper.isBootstrap5()) {
  4209. $formatter.find('select').val(format);
  4210. } else {
  4211. $formatter.parent().find(`a[data-format="${format}"]`).click();
  4212. }
  4213. }
  4214. /**
  4215. * returns if attachment dropdown is readonly, not editable
  4216. *
  4217. * @name TopNav.isAttachmentReadonly
  4218. * @function
  4219. * @return {bool}
  4220. */
  4221. me.isAttachmentReadonly = function()
  4222. {
  4223. return !createButtonsDisplayed || $attach.hasClass('hidden');
  4224. }
  4225. /**
  4226. * init navigation manager
  4227. *
  4228. * preloads jQuery elements
  4229. *
  4230. * @name TopNav.init
  4231. * @function
  4232. */
  4233. me.init = function()
  4234. {
  4235. $attach = $('#attach');
  4236. $burnAfterReading = $('#burnafterreading');
  4237. $burnAfterReadingOption = $('#burnafterreadingoption');
  4238. $cloneButton = $('#clonebutton');
  4239. $customAttachment = $('#customattachment');
  4240. $expiration = $('#expiration');
  4241. $fileRemoveButton = $('#fileremovebutton');
  4242. $fileWrap = $('#filewrap');
  4243. $formatter = $('#formatter');
  4244. $newButton = $('#newbutton');
  4245. $openDiscussion = $('#opendiscussion');
  4246. $openDiscussionOption = $('#opendiscussionoption');
  4247. $password = $('#password');
  4248. $passwordInput = $('#passwordinput');
  4249. $rawTextButton = $('#rawtextbutton');
  4250. $downloadTextButton = $('#downloadtextbutton');
  4251. $retryButton = $('#retrybutton');
  4252. $sendButton = $('#sendbutton');
  4253. $qrCodeLink = $('#qrcodelink');
  4254. $emailLink = $('#emaillink');
  4255. // bootstrap template drop down
  4256. $('#language ul.dropdown-menu li a').click(setLanguage);
  4257. // bootstrap template drop down
  4258. $('#template ul.dropdown-menu li a').click(setTemplate);
  4259. // bind events
  4260. $burnAfterReading.change(changeBurnAfterReading);
  4261. $openDiscussionOption.change(changeOpenDiscussion);
  4262. $newButton.click(clickNewPaste);
  4263. $sendButton.click(PasteEncrypter.sendPaste);
  4264. $cloneButton.click(Controller.clonePaste);
  4265. $rawTextButton.click(rawText);
  4266. $downloadTextButton.click(downloadText);
  4267. $retryButton.click(clickRetryButton);
  4268. $fileRemoveButton.click(removeAttachment);
  4269. $qrCodeLink.click(displayQrCode);
  4270. // bootstrap template drop downs
  4271. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  4272. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  4273. // bootstrap5 & page drop downs
  4274. $('#pasteExpiration').on('change', function() {
  4275. pasteExpiration = Model.getExpirationDefault();
  4276. });
  4277. $('#pasteFormatter').on('change', function() {
  4278. PasteViewer.setFormat(Model.getFormatDefault());
  4279. });
  4280. // initiate default state of checkboxes
  4281. changeBurnAfterReading();
  4282. changeOpenDiscussion();
  4283. // get default values from template or fall back to set value
  4284. burnAfterReadingDefault = me.getBurnAfterReading();
  4285. openDiscussionDefault = me.getOpenDiscussion();
  4286. pasteExpiration = Model.getExpirationDefault();
  4287. createButtonsDisplayed = false;
  4288. viewButtonsDisplayed = false;
  4289. };
  4290. return me;
  4291. })(window, document);
  4292. /**
  4293. * Responsible for AJAX requests, transparently handles encryption…
  4294. *
  4295. * @name ServerInteraction
  4296. * @class
  4297. */
  4298. const ServerInteraction = (function () {
  4299. const me = {};
  4300. let successFunc = null,
  4301. failureFunc = null,
  4302. symmetricKey = null,
  4303. url,
  4304. data,
  4305. password;
  4306. /**
  4307. * public variable ('constant') for errors to prevent magic numbers
  4308. *
  4309. * @name ServerInteraction.error
  4310. * @readonly
  4311. * @enum {Object}
  4312. */
  4313. me.error = {
  4314. okay: 0,
  4315. custom: 1,
  4316. unknown: 2,
  4317. serverError: 3
  4318. };
  4319. /**
  4320. * ajaxHeaders to send in AJAX requests
  4321. *
  4322. * @name ServerInteraction.ajaxHeaders
  4323. * @private
  4324. * @readonly
  4325. * @enum {Object}
  4326. */
  4327. const ajaxHeaders = {
  4328. 'X-Requested-With': 'JSONHttpRequest',
  4329. 'Content-Type': 'application/json'
  4330. };
  4331. /**
  4332. * called after successful upload
  4333. *
  4334. * @name ServerInteraction.success
  4335. * @private
  4336. * @function
  4337. * @param {int} status
  4338. * @param {int} result - optional
  4339. */
  4340. function success(status, result)
  4341. {
  4342. if (successFunc !== null) {
  4343. // add useful data to result
  4344. result.encryptionKey = symmetricKey;
  4345. successFunc(status, result);
  4346. }
  4347. }
  4348. /**
  4349. * called after a upload failure
  4350. *
  4351. * @name ServerInteraction.fail
  4352. * @private
  4353. * @function
  4354. * @param {int} status - internal code
  4355. * @param {int} result - original error code
  4356. */
  4357. function fail(status, result)
  4358. {
  4359. if (failureFunc !== null) {
  4360. failureFunc(status, result);
  4361. }
  4362. }
  4363. /**
  4364. * actually uploads the data
  4365. *
  4366. * @name ServerInteraction.run
  4367. * @function
  4368. */
  4369. me.run = function()
  4370. {
  4371. let isPost = Object.keys(data).length > 0,
  4372. ajaxParams = {
  4373. type: isPost ? 'POST' : 'GET',
  4374. url: url,
  4375. headers: ajaxHeaders,
  4376. dataType: 'json',
  4377. success: function(result) {
  4378. if (result.status === 0) {
  4379. success(0, result);
  4380. } else if (result.status === 1) {
  4381. fail(1, result);
  4382. } else {
  4383. fail(2, result);
  4384. }
  4385. }
  4386. };
  4387. if (isPost) {
  4388. ajaxParams.data = JSON.stringify(data);
  4389. }
  4390. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  4391. console.error(textStatus, errorThrown);
  4392. fail(3, jqXHR);
  4393. });
  4394. };
  4395. /**
  4396. * return currently set data, used in unit testing
  4397. *
  4398. * @name ServerInteraction.getData
  4399. * @function
  4400. */
  4401. me.getData = function()
  4402. {
  4403. return data;
  4404. };
  4405. /**
  4406. * set success function
  4407. *
  4408. * @name ServerInteraction.setUrl
  4409. * @function
  4410. * @param {function} newUrl
  4411. */
  4412. me.setUrl = function(newUrl)
  4413. {
  4414. url = newUrl;
  4415. };
  4416. /**
  4417. * sets the password to use (first value) and optionally also the
  4418. * encryption key (not recommended, it is automatically generated).
  4419. *
  4420. * Note: Call this after prepare() as prepare() resets these values.
  4421. *
  4422. * @name ServerInteraction.setCryptValues
  4423. * @function
  4424. * @param {string} newPassword
  4425. * @param {string} newKey - optional
  4426. */
  4427. me.setCryptParameters = function(newPassword, newKey)
  4428. {
  4429. password = newPassword;
  4430. if (typeof newKey !== 'undefined') {
  4431. symmetricKey = newKey;
  4432. }
  4433. };
  4434. /**
  4435. * set success function
  4436. *
  4437. * @name ServerInteraction.setSuccess
  4438. * @function
  4439. * @param {function} func
  4440. */
  4441. me.setSuccess = function(func)
  4442. {
  4443. successFunc = func;
  4444. };
  4445. /**
  4446. * set failure function
  4447. *
  4448. * @name ServerInteraction.setFailure
  4449. * @function
  4450. * @param {function} func
  4451. */
  4452. me.setFailure = function(func)
  4453. {
  4454. failureFunc = func;
  4455. };
  4456. /**
  4457. * prepares a new upload
  4458. *
  4459. * Call this when doing a new upload to reset any data from potential
  4460. * previous uploads. Must be called before any other method of this
  4461. * module.
  4462. *
  4463. * @name ServerInteraction.prepare
  4464. * @function
  4465. * @return {object}
  4466. */
  4467. me.prepare = function()
  4468. {
  4469. // entropy should already be checked!
  4470. // reset password
  4471. password = '';
  4472. // reset key, so it a new one is generated when it is used
  4473. symmetricKey = null;
  4474. // reset data
  4475. successFunc = null;
  4476. failureFunc = null;
  4477. url = Helper.baseUri();
  4478. data = {};
  4479. };
  4480. /**
  4481. * encrypts and sets the data
  4482. *
  4483. * @name ServerInteraction.setCipherMessage
  4484. * @async
  4485. * @function
  4486. * @param {object} cipherMessage
  4487. */
  4488. me.setCipherMessage = async function(cipherMessage)
  4489. {
  4490. if (
  4491. symmetricKey === null ||
  4492. (typeof symmetricKey === 'string' && symmetricKey === '')
  4493. ) {
  4494. symmetricKey = CryptTool.getSymmetricKey();
  4495. }
  4496. if (!data.hasOwnProperty('adata')) {
  4497. data['adata'] = [];
  4498. }
  4499. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  4500. data['v'] = 2;
  4501. data['ct'] = cipherResult[0];
  4502. data['adata'] = cipherResult[1];
  4503. };
  4504. /**
  4505. * set the additional metadata to send unencrypted
  4506. *
  4507. * @name ServerInteraction.setUnencryptedData
  4508. * @function
  4509. * @param {string} index
  4510. * @param {mixed} element
  4511. */
  4512. me.setUnencryptedData = function(index, element)
  4513. {
  4514. data[index] = element;
  4515. };
  4516. /**
  4517. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  4518. *
  4519. * @name ServerInteraction.parseUploadError
  4520. * @function
  4521. * @param {int} status
  4522. * @param {object} data
  4523. * @param {string} doThisThing - a human description of the action, which was tried
  4524. * @return {array}
  4525. */
  4526. me.parseUploadError = function(status, data, doThisThing) {
  4527. let errorArray;
  4528. switch (status) {
  4529. case me.error.custom:
  4530. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  4531. break;
  4532. case me.error.unknown:
  4533. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  4534. break;
  4535. case me.error.serverError:
  4536. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  4537. break;
  4538. default:
  4539. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  4540. break;
  4541. }
  4542. return errorArray;
  4543. };
  4544. return me;
  4545. })();
  4546. /**
  4547. * (controller) Responsible for encrypting document and sending it to server.
  4548. *
  4549. * Does upload, encryption is done transparently by ServerInteraction.
  4550. *
  4551. * @name PasteEncrypter
  4552. * @class
  4553. */
  4554. const PasteEncrypter = (function () {
  4555. const me = {};
  4556. /**
  4557. * called after successful document upload
  4558. *
  4559. * @name PasteEncrypter.showCreatedPaste
  4560. * @private
  4561. * @function
  4562. * @param {int} status
  4563. * @param {object} data
  4564. */
  4565. function showCreatedPaste(status, data) {
  4566. Alert.hideLoading();
  4567. Alert.hideMessages();
  4568. // show notification
  4569. const baseUri = Helper.baseUri() + '?',
  4570. url = baseUri + data.id + (TopNav.getBurnAfterReading() ? loadConfirmPrefix : '#') + CryptTool.base58encode(data.encryptionKey),
  4571. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  4572. PasteStatus.createPasteNotification(url, deleteUrl);
  4573. // show new URL in browser bar
  4574. history.pushState({type: 'newpaste'}, document.title, url);
  4575. TopNav.showViewButtons();
  4576. CopyToClipboard.setUrl(url);
  4577. CopyToClipboard.showKeyboardShortcutHint();
  4578. // this cannot be grouped with showViewButtons due to remaining time calculation
  4579. TopNav.showEmailButton();
  4580. TopNav.hideRawButton();
  4581. TopNav.hideDownloadButton();
  4582. Editor.hide();
  4583. PasteStatus.checkAutoShorten();
  4584. // parse and show text
  4585. // (preparation already done in me.sendPaste())
  4586. PasteViewer.run();
  4587. }
  4588. /**
  4589. * called after successful comment upload
  4590. *
  4591. * @name PasteEncrypter.showUploadedComment
  4592. * @private
  4593. * @function
  4594. * @param {int} status
  4595. * @param {object} data
  4596. */
  4597. function showUploadedComment(status, data) {
  4598. // show success message
  4599. Alert.showStatus('Comment posted.');
  4600. // reload document
  4601. Controller.refreshPaste(function () {
  4602. // highlight sent comment
  4603. DiscussionViewer.highlightComment(data.id, true);
  4604. // reset error handler
  4605. Alert.setCustomHandler(null);
  4606. });
  4607. }
  4608. /**
  4609. * send a reply in a discussion
  4610. *
  4611. * @name PasteEncrypter.sendComment
  4612. * @async
  4613. * @function
  4614. */
  4615. me.sendComment = async function()
  4616. {
  4617. Alert.hideMessages();
  4618. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  4619. // UI loading state
  4620. TopNav.hideAllButtons();
  4621. Alert.showLoading('Sending comment…', 'cloud-upload');
  4622. // get data
  4623. const plainText = DiscussionViewer.getReplyMessage(),
  4624. nickname = DiscussionViewer.getReplyNickname(),
  4625. parentid = DiscussionViewer.getReplyCommentId();
  4626. // do not send if there is no data
  4627. if (plainText.length === 0) {
  4628. // revert loading status…
  4629. Alert.hideLoading();
  4630. Alert.setCustomHandler(null);
  4631. TopNav.showViewButtons();
  4632. return;
  4633. }
  4634. // prepare server interaction
  4635. ServerInteraction.prepare();
  4636. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  4637. // set success/fail functions
  4638. ServerInteraction.setSuccess(showUploadedComment);
  4639. ServerInteraction.setFailure(function (status, data) {
  4640. // revert loading status…
  4641. Alert.hideLoading();
  4642. TopNav.showViewButtons();
  4643. // …show error message…
  4644. Alert.showError(
  4645. ServerInteraction.parseUploadError(status, data, 'post comment')
  4646. );
  4647. // …and reset error handler
  4648. Alert.setCustomHandler(null);
  4649. });
  4650. // fill it with unencrypted params
  4651. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  4652. if (typeof parentid === 'undefined') {
  4653. // if parent id is not set, this is the top-most comment, so use
  4654. // document id as parent, as the root element of the discussion tree
  4655. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  4656. } else {
  4657. ServerInteraction.setUnencryptedData('parentid', parentid);
  4658. }
  4659. // prepare cypher message
  4660. let cipherMessage = {
  4661. 'comment': plainText
  4662. };
  4663. if (nickname.length > 0) {
  4664. cipherMessage['nickname'] = nickname;
  4665. }
  4666. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4667. ServerInteraction.run();
  4668. };
  4669. /**
  4670. * sends a new document to server
  4671. *
  4672. * @name PasteEncrypter.sendPaste
  4673. * @async
  4674. * @function
  4675. */
  4676. me.sendPaste = async function()
  4677. {
  4678. // hide previous (error) messages
  4679. Controller.hideStatusMessages();
  4680. // UI loading state
  4681. TopNav.hideAllButtons();
  4682. Alert.showLoading('Sending document…', 'cloud-upload');
  4683. TopNav.collapseBar();
  4684. // get data
  4685. const plainText = Editor.getText(),
  4686. format = PasteViewer.getFormat(),
  4687. // the methods may return different values if no files are attached (null, undefined or false)
  4688. files = TopNav.getFileList() || AttachmentViewer.getFiles() || AttachmentViewer.hasAttachment();
  4689. // do not send if there is no data
  4690. if (plainText.length === 0 && !files) {
  4691. // revert loading status…
  4692. Alert.hideLoading();
  4693. TopNav.showCreateButtons();
  4694. return;
  4695. }
  4696. // prepare server interaction
  4697. ServerInteraction.prepare();
  4698. ServerInteraction.setCryptParameters(TopNav.getPassword());
  4699. // set success/fail functions
  4700. ServerInteraction.setSuccess(showCreatedPaste);
  4701. ServerInteraction.setFailure(function (status, data) {
  4702. // revert loading status…
  4703. Alert.hideLoading();
  4704. TopNav.showCreateButtons();
  4705. // show error message
  4706. Alert.showError(
  4707. ServerInteraction.parseUploadError(status, data, 'create document')
  4708. );
  4709. });
  4710. // fill it with unencrypted submitted options
  4711. ServerInteraction.setUnencryptedData('adata', [
  4712. null, format,
  4713. TopNav.getOpenDiscussion() ? 1 : 0,
  4714. TopNav.getBurnAfterReading() ? 1 : 0
  4715. ]);
  4716. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  4717. // prepare PasteViewer for later preview
  4718. PasteViewer.setText(plainText);
  4719. PasteViewer.setFormat(format);
  4720. // prepare cypher message
  4721. let attachmentsData = AttachmentViewer.getAttachmentsData(),
  4722. cipherMessage = {
  4723. 'paste': plainText
  4724. };
  4725. if (attachmentsData.length) {
  4726. cipherMessage['attachment'] = attachmentsData;
  4727. cipherMessage['attachment_name'] = AttachmentViewer.getFiles().map((fileInfo => fileInfo.name));
  4728. } else if (AttachmentViewer.hasAttachment()) {
  4729. // fall back to cloned part
  4730. let attachments = AttachmentViewer.getAttachments();
  4731. cipherMessage['attachment'] = attachments.map(attachment => attachment[0]);
  4732. cipherMessage['attachment_name'] = attachments.map(attachment => attachment[1]);
  4733. cipherMessage['attachment'] = await Promise.all(cipherMessage['attachment'].map(async (attachment, i) => {
  4734. // we need to retrieve data from blob if browser already parsed it in memory
  4735. if (typeof attachment === 'string' && attachment.startsWith('blob:')) {
  4736. Alert.showStatus(
  4737. [
  4738. 'Retrieving cloned file \'%s\' from memory...',
  4739. cipherMessage['attachment_name'][i]
  4740. ],
  4741. 'copy'
  4742. );
  4743. try {
  4744. const blobData = await $.ajax({
  4745. type: 'GET',
  4746. url: attachment,
  4747. processData: false,
  4748. timeout: 10000,
  4749. dataType: 'binary',
  4750. xhrFields: {
  4751. withCredentials: false,
  4752. responseType: 'blob'
  4753. }
  4754. });
  4755. if (blobData instanceof window.Blob) {
  4756. const fileReading = new Promise(function(resolve, reject) {
  4757. const fileReader = new FileReader();
  4758. fileReader.onload = function (event) {
  4759. resolve(event.target.result);
  4760. };
  4761. fileReader.onerror = function (error) {
  4762. reject(error);
  4763. }
  4764. fileReader.readAsDataURL(blobData);
  4765. });
  4766. return await fileReading;
  4767. } else {
  4768. const error = 'Cannot process attachment data.';
  4769. Alert.showError(error);
  4770. throw new TypeError(error);
  4771. }
  4772. } catch (error) {
  4773. Alert.showError('Cannot retrieve attachment.');
  4774. throw error;
  4775. }
  4776. }
  4777. }));
  4778. }
  4779. // encrypt message
  4780. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  4781. // send data
  4782. ServerInteraction.run();
  4783. };
  4784. return me;
  4785. })();
  4786. /**
  4787. * (controller) Responsible for decrypting cipherdata and passing data to view.
  4788. *
  4789. * Only decryption, no download.
  4790. *
  4791. * @name PasteDecrypter
  4792. * @class
  4793. */
  4794. const PasteDecrypter = (function () {
  4795. const me = {};
  4796. /**
  4797. * decrypt data or prompts for password in case of failure
  4798. *
  4799. * @name PasteDecrypter.decryptOrPromptPassword
  4800. * @private
  4801. * @async
  4802. * @function
  4803. * @param {string} key
  4804. * @param {string} password - optional, may be an empty string
  4805. * @param {string} cipherdata
  4806. * @throws {string}
  4807. * @return {false|string} false, when unsuccessful or string (decrypted data)
  4808. */
  4809. async function decryptOrPromptPassword(key, password, cipherdata)
  4810. {
  4811. // try decryption without password
  4812. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  4813. // if it fails, request password
  4814. if (plaindata.length === 0 && password.length === 0) {
  4815. // show prompt
  4816. Prompt.requestPassword();
  4817. // Thus, we cannot do anything yet, we need to wait for the user
  4818. // input.
  4819. return false;
  4820. }
  4821. // if all tries failed, we can only return an error
  4822. if (plaindata.length === 0) {
  4823. return false;
  4824. }
  4825. return plaindata;
  4826. }
  4827. /**
  4828. * decrypt the actual document text
  4829. *
  4830. * @name PasteDecrypter.decryptPaste
  4831. * @private
  4832. * @async
  4833. * @function
  4834. * @param {Paste} paste - document data in object form
  4835. * @param {string} key
  4836. * @param {string} password
  4837. * @throws {string}
  4838. * @return {Promise}
  4839. */
  4840. async function decryptPaste(paste, key, password)
  4841. {
  4842. const pastePlain = await decryptOrPromptPassword(
  4843. key, password,
  4844. paste.getCipherData()
  4845. );
  4846. if (pastePlain === false) {
  4847. if (password.length === 0) {
  4848. throw 'waiting on user to provide a password';
  4849. } else {
  4850. Alert.hideLoading();
  4851. // reset password, so it can be re-entered
  4852. Prompt.reset();
  4853. TopNav.showRetryButton();
  4854. throw 'Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.';
  4855. }
  4856. }
  4857. const pasteMessage = JSON.parse(pastePlain);
  4858. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  4859. if (Array.isArray(pasteMessage.attachment) && Array.isArray(pasteMessage.attachment_name)) {
  4860. pasteMessage.attachment.forEach((attachment, key) => {
  4861. const attachment_name = pasteMessage.attachment_name[key];
  4862. AttachmentViewer.setAttachment(attachment, attachment_name);
  4863. });
  4864. } else {
  4865. // Continue to process attachment parameters as strings to ensure backward compatibility
  4866. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  4867. }
  4868. AttachmentViewer.showAttachment();
  4869. }
  4870. PasteViewer.setFormat(paste.getFormat());
  4871. PasteViewer.setText(pasteMessage.paste);
  4872. PasteViewer.run();
  4873. }
  4874. /**
  4875. * decrypts all comments and shows them
  4876. *
  4877. * @name PasteDecrypter.decryptComments
  4878. * @private
  4879. * @async
  4880. * @function
  4881. * @param {Paste} paste - document data in object form
  4882. * @param {string} key
  4883. * @param {string} password
  4884. * @return {Promise}
  4885. */
  4886. async function decryptComments(paste, key, password)
  4887. {
  4888. // remove potential previous discussion
  4889. DiscussionViewer.prepareNewDiscussion();
  4890. const commentDecryptionPromises = [];
  4891. // iterate over comments
  4892. for (let i = 0; i < paste.comments.length; ++i) {
  4893. const comment = new Comment(paste.comments[i]),
  4894. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  4895. paste.comments[i] = comment;
  4896. commentDecryptionPromises.push(
  4897. commentPromise.then(function (commentJson) {
  4898. const commentMessage = JSON.parse(commentJson);
  4899. return [
  4900. commentMessage.comment || '',
  4901. commentMessage.nickname || ''
  4902. ];
  4903. })
  4904. );
  4905. }
  4906. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4907. for (let i = 0; i < paste.comments.length; ++i) {
  4908. if (plaintexts[i][0].length === 0) {
  4909. continue;
  4910. }
  4911. DiscussionViewer.addComment(
  4912. paste.comments[i],
  4913. plaintexts[i][0],
  4914. plaintexts[i][1]
  4915. );
  4916. }
  4917. $(document).on('languageLoaded', function () {
  4918. $('#commentcontainer').find('img.vizhash')
  4919. .prop('title', I18n._('Avatar generated from IP address'));
  4920. });
  4921. });
  4922. }
  4923. /**
  4924. * show decrypted text in the display area, including discussion (if open)
  4925. *
  4926. * @name PasteDecrypter.run
  4927. * @function
  4928. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4929. */
  4930. me.run = function(paste)
  4931. {
  4932. Alert.hideMessages();
  4933. Alert.setCustomHandler(null);
  4934. Alert.showLoading('Decrypting document…', 'cloud-download');
  4935. if (typeof paste === 'undefined' || paste.type === 'click') {
  4936. // get cipher data and wait until it is available
  4937. Model.getPasteData(me.run);
  4938. return;
  4939. }
  4940. let key = Model.getPasteKey(),
  4941. password = Prompt.getPassword(),
  4942. decryptionPromises = [];
  4943. TopNav.setRetryCallback(function () {
  4944. TopNav.hideRetryButton();
  4945. me.run(paste);
  4946. });
  4947. // Clear attachments to prevent duplicates
  4948. AttachmentViewer.removeAttachment();
  4949. // decrypt paste & attachments
  4950. decryptionPromises.push(decryptPaste(paste, key, password));
  4951. // if the discussion is opened on this document, display it
  4952. if (paste.isDiscussionEnabled()) {
  4953. decryptionPromises.push(decryptComments(paste, key, password));
  4954. }
  4955. // shows the remaining time (until) deletion
  4956. PasteStatus.showRemainingTime(paste);
  4957. CopyToClipboard.showKeyboardShortcutHint();
  4958. Promise.all(decryptionPromises)
  4959. .then(() => {
  4960. Alert.hideLoading();
  4961. TopNav.showViewButtons();
  4962. // discourage cloning (it cannot really be prevented)
  4963. if (paste.isBurnAfterReadingEnabled()) {
  4964. TopNav.hideBurnAfterReadingButtons();
  4965. } else {
  4966. // we have to pass in remaining_time here
  4967. TopNav.showEmailButton(paste.getTimeToLive());
  4968. }
  4969. // only offer adding comments, after document was successfully decrypted
  4970. if (paste.isDiscussionEnabled()) {
  4971. DiscussionViewer.finishDiscussion();
  4972. }
  4973. })
  4974. .catch((err) => {
  4975. // wait for the user to type in the password,
  4976. // then PasteDecrypter.run will be called again
  4977. Alert.showError(err);
  4978. });
  4979. };
  4980. return me;
  4981. })();
  4982. /**
  4983. *
  4984. * @name CopyToClipboard
  4985. * @class
  4986. */
  4987. const CopyToClipboard = (function () {
  4988. const me = {};
  4989. let copyButton,
  4990. copyLinkButton,
  4991. copyIcon,
  4992. successIcon,
  4993. shortcutHint,
  4994. url;
  4995. /**
  4996. * Handle copy to clipboard button click
  4997. *
  4998. * @name CopyToClipboard.handleCopyButtonClick
  4999. * @private
  5000. * @function
  5001. */
  5002. function handleCopyButtonClick() {
  5003. $(copyButton).click(function() {
  5004. const text = PasteViewer.getText();
  5005. saveToClipboard(text);
  5006. toggleSuccessIcon();
  5007. showAlertMessage('Document copied to clipboard');
  5008. });
  5009. }
  5010. /**
  5011. * Handle copy link to clipboard button click
  5012. *
  5013. * @name CopyToClipboard.handleCopyLinkButtonClick
  5014. * @private
  5015. * @function
  5016. */
  5017. function handleCopyLinkButtonClick() {
  5018. $(copyLinkButton).click(function () {
  5019. saveToClipboard(url);
  5020. showAlertMessage('Link copied to clipboard');
  5021. });
  5022. }
  5023. /**
  5024. * Handle CTRL+C/CMD+C keyboard shortcut
  5025. *
  5026. * @name CopyToClipboard.handleKeyboardShortcut
  5027. * @private
  5028. * @function
  5029. */
  5030. function handleKeyboardShortcut() {
  5031. $(document).bind('copy', function () {
  5032. if (!isUserSelectedTextToCopy()) {
  5033. const text = PasteViewer.getText();
  5034. saveToClipboard(text);
  5035. showAlertMessage('Document copied to clipboard');
  5036. }
  5037. });
  5038. }
  5039. /**
  5040. * Check if user selected some text on the page to copy it
  5041. *
  5042. * @name CopyToClipboard.isUserSelectedTextToCopy
  5043. * @private
  5044. * @function
  5045. * @returns {boolean}
  5046. */
  5047. function isUserSelectedTextToCopy() {
  5048. let text = '';
  5049. if (window.getSelection) {
  5050. text = window.getSelection().toString();
  5051. } else if (document.selection && document.selection.type !== 'Control') {
  5052. text = document.selection.createRange().text;
  5053. }
  5054. return text.length > 0;
  5055. }
  5056. /**
  5057. * Save text to the clipboard
  5058. *
  5059. * @name CopyToClipboard.saveToClipboard
  5060. * @private
  5061. * @param {string} text
  5062. * @function
  5063. */
  5064. function saveToClipboard(text) {
  5065. navigator.clipboard.writeText(text);
  5066. }
  5067. /**
  5068. * Show alert message after text copy
  5069. *
  5070. * @name CopyToClipboard.showAlertMessage
  5071. * @private
  5072. * @param {string} message
  5073. * @function
  5074. */
  5075. function showAlertMessage(message) {
  5076. Alert.showStatus(message);
  5077. }
  5078. /**
  5079. * Toogle success icon after copy
  5080. *
  5081. * @name CopyToClipboard.toggleSuccessIcon
  5082. * @private
  5083. * @function
  5084. */
  5085. function toggleSuccessIcon() {
  5086. $(copyIcon).css('display', 'none');
  5087. $(successIcon).css('display', 'block');
  5088. setTimeout(function() {
  5089. $(copyIcon).css('display', 'block');
  5090. $(successIcon).css('display', 'none');
  5091. }, 1000);
  5092. }
  5093. /**
  5094. * Show keyboard shortcut hint
  5095. *
  5096. * @name CopyToClipboard.showKeyboardShortcutHint
  5097. * @function
  5098. */
  5099. me.showKeyboardShortcutHint = function () {
  5100. I18n._(
  5101. shortcutHint,
  5102. '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>'
  5103. );
  5104. };
  5105. /**
  5106. * Hide keyboard shortcut hint
  5107. *
  5108. * @name CopyToClipboard.showKeyboardShortcutHint
  5109. * @function
  5110. */
  5111. me.hideKeyboardShortcutHint = function () {
  5112. $(shortcutHint).html('');
  5113. };
  5114. /**
  5115. * Set document url
  5116. *
  5117. * @name CopyToClipboard.setUrl
  5118. * @param {string} newUrl
  5119. * @function
  5120. */
  5121. me.setUrl = function (newUrl) {
  5122. url = newUrl;
  5123. };
  5124. /**
  5125. * Initialize
  5126. *
  5127. * @name CopyToClipboard.init
  5128. * @function
  5129. */
  5130. me.init = function() {
  5131. copyButton = $('#prettyMessageCopyBtn');
  5132. copyLinkButton = $('#copyLink');
  5133. copyIcon = $('#copyIcon');
  5134. successIcon = $('#copySuccessIcon');
  5135. shortcutHint = $('#copyShortcutHintText');
  5136. handleCopyButtonClick();
  5137. handleCopyLinkButtonClick();
  5138. handleKeyboardShortcut();
  5139. };
  5140. return me;
  5141. })();
  5142. /**
  5143. *
  5144. * @name PasswordPeek
  5145. * @class
  5146. */
  5147. const PasswordPeek = (function () {
  5148. const me = {};
  5149. /**
  5150. * Switch between visible and hidden password
  5151. *
  5152. * @name PasswordPeek.handleRevealButtonClick
  5153. * @private
  5154. * @function
  5155. */
  5156. function handleRevealButtonClick() {
  5157. const element = $(this);
  5158. const passwordInput = element.siblings('.input-password');
  5159. const isHidden = passwordInput.attr('type') === 'password';
  5160. passwordInput.attr('type', isHidden ? 'text' : 'password');
  5161. const tooltip = I18n._(isHidden ? 'Hide password' : 'Show password');
  5162. element.attr('title', tooltip);
  5163. element.attr('aria-label', tooltip);
  5164. // handle bootstrap 5 icons: eye & eye-slash
  5165. const buttonSvg = element.find('use');
  5166. if (buttonSvg.length) {
  5167. const iconHref = buttonSvg.attr('href');
  5168. if (isHidden) {
  5169. buttonSvg.attr('href', iconHref + '-slash');
  5170. } else {
  5171. buttonSvg.attr('href', iconHref.substring(0, iconHref.length - 6));
  5172. }
  5173. return;
  5174. }
  5175. // handle bootstrap 3 icons: eye-open & eye-close
  5176. const buttonSpan = element.find('span');
  5177. if (buttonSpan.length) {
  5178. if (isHidden) {
  5179. buttonSpan.addClass('glyphicon-eye-close');
  5180. buttonSpan.removeClass('glyphicon-eye-open');
  5181. } else {
  5182. buttonSpan.addClass('glyphicon-eye-open');
  5183. buttonSpan.removeClass('glyphicon-eye-close');
  5184. }
  5185. }
  5186. }
  5187. /**
  5188. * Initialize
  5189. *
  5190. * @name PasswordPeek.init
  5191. * @function
  5192. */
  5193. me.init = function() {
  5194. const revealButton = $('.toggle-password');
  5195. revealButton.click(handleRevealButtonClick);
  5196. };
  5197. return me;
  5198. })();
  5199. /**
  5200. * (controller) main PrivateBin logic
  5201. *
  5202. * @name Controller
  5203. * @param {object} window
  5204. * @param {object} document
  5205. * @class
  5206. */
  5207. const Controller = (function (window, document) {
  5208. const me = {};
  5209. /**
  5210. * hides all status messages no matter which module showed them
  5211. *
  5212. * @name Controller.hideStatusMessages
  5213. * @function
  5214. */
  5215. me.hideStatusMessages = function()
  5216. {
  5217. PasteStatus.hideMessages();
  5218. Alert.hideMessages();
  5219. CopyToClipboard.hideKeyboardShortcutHint();
  5220. };
  5221. /**
  5222. * creates a new document
  5223. *
  5224. * @name Controller.newPaste
  5225. * @function
  5226. */
  5227. me.newPaste = function()
  5228. {
  5229. // Important: This *must not* run Alert.hideMessages() as previous
  5230. // errors from viewing a document should be shown.
  5231. TopNav.hideAllButtons();
  5232. Alert.showLoading('Preparing new document…', 'time');
  5233. PasteStatus.hideMessages();
  5234. PasteViewer.hide();
  5235. Editor.resetInput();
  5236. Editor.show();
  5237. Editor.focusInput();
  5238. AttachmentViewer.removeAttachment();
  5239. TopNav.resetInput();
  5240. // reset format
  5241. PasteViewer.setFormat('plaintext');
  5242. TopNav.setFormat('plaintext');
  5243. TopNav.showCreateButtons();
  5244. // newPaste could be called when user is on document clone editing view
  5245. TopNav.hideCustomAttachment();
  5246. AttachmentViewer.clearDragAndDrop();
  5247. AttachmentViewer.removeAttachmentData();
  5248. Alert.hideLoading();
  5249. // only push new state if we are coming from a different one
  5250. if (Helper.baseUri() !== window.location) {
  5251. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  5252. }
  5253. // clear discussion
  5254. DiscussionViewer.prepareNewDiscussion();
  5255. };
  5256. /**
  5257. * shows the loaded document
  5258. *
  5259. * @name Controller.showPaste
  5260. * @function
  5261. */
  5262. me.showPaste = function()
  5263. {
  5264. try {
  5265. Model.getPasteKey();
  5266. } catch (err) {
  5267. console.error(err);
  5268. 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?)');
  5269. return;
  5270. }
  5271. // check if we should request loading confirmation
  5272. if(window.location.hash.startsWith(loadConfirmPrefix)) {
  5273. Prompt.requestLoadConfirmation();
  5274. return;
  5275. }
  5276. // show proper elements on screen
  5277. PasteDecrypter.run();
  5278. };
  5279. /**
  5280. * refreshes the loaded document to show potential new data
  5281. *
  5282. * @name Controller.refreshPaste
  5283. * @function
  5284. * @param {function} callback
  5285. */
  5286. me.refreshPaste = function(callback)
  5287. {
  5288. // save window position to restore it later
  5289. const orgPosition = window.scrollY;
  5290. Model.getPasteData(function (data) {
  5291. ServerInteraction.prepare();
  5292. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  5293. ServerInteraction.setFailure(function (status, data) {
  5294. // revert loading status…
  5295. Alert.hideLoading();
  5296. TopNav.showViewButtons();
  5297. // show error message
  5298. Alert.showError(
  5299. ServerInteraction.parseUploadError(status, data, 'refresh display')
  5300. );
  5301. });
  5302. ServerInteraction.setSuccess(function (status, data) {
  5303. PasteDecrypter.run(new Paste(data));
  5304. // restore position
  5305. window.scrollTo(0, orgPosition);
  5306. // NOTE: could create problems as callback may be called
  5307. // asyncronously if PasteDecrypter e.g. needs to wait for a
  5308. // password being entered
  5309. callback();
  5310. });
  5311. ServerInteraction.run();
  5312. }, false); // this false is important as it circumvents the cache
  5313. }
  5314. /**
  5315. * clone the current document
  5316. *
  5317. * @name Controller.clonePaste
  5318. * @function
  5319. */
  5320. me.clonePaste = function()
  5321. {
  5322. TopNav.collapseBar();
  5323. TopNav.hideAllButtons();
  5324. // hide messages from previous document
  5325. me.hideStatusMessages();
  5326. // erase the id and the key in url
  5327. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  5328. if (AttachmentViewer.hasAttachment()) {
  5329. const attachments = AttachmentViewer.getAttachments();
  5330. attachments.forEach(attachment => {
  5331. AttachmentViewer.moveAttachmentTo(
  5332. TopNav.getCustomAttachment(),
  5333. attachment,
  5334. 'Cloned: \'%s\''
  5335. );
  5336. });
  5337. TopNav.hideFileSelector();
  5338. AttachmentViewer.hideAttachment();
  5339. // NOTE: it also looks nice without removing the attachment
  5340. // but for a consistent display we remove it…
  5341. AttachmentViewer.hideAttachmentPreview();
  5342. TopNav.showCustomAttachment();
  5343. // show another status messages to make the user aware that the
  5344. // files were cloned too!
  5345. Alert.showStatus(
  5346. [
  5347. 'The cloned file \'%s\' was attached to this document.',
  5348. attachments.map(attachment => attachment[1]).join(', ')
  5349. ],
  5350. 'copy'
  5351. );
  5352. }
  5353. Editor.setText(PasteViewer.getText());
  5354. // also clone the format
  5355. TopNav.setFormat(PasteViewer.getFormat());
  5356. PasteViewer.hide();
  5357. Editor.show();
  5358. TopNav.showCreateButtons();
  5359. // clear discussion
  5360. DiscussionViewer.prepareNewDiscussion();
  5361. };
  5362. /**
  5363. * try initializing zlib or display a warning if it fails,
  5364. * extracted from main init to allow unit testing
  5365. *
  5366. * @name Controller.initZ
  5367. * @function
  5368. */
  5369. me.initZ = function()
  5370. {
  5371. z = zlib.catch(function () {
  5372. if (document.body.dataset.compression !== 'none') {
  5373. Alert.showWarning('Your browser doesn\'t support WebAssembly, used for zlib compression. You can create uncompressed documents, but can\'t read compressed ones.');
  5374. }
  5375. });
  5376. }
  5377. /**
  5378. * application start
  5379. *
  5380. * @name Controller.init
  5381. * @function
  5382. */
  5383. me.init = function()
  5384. {
  5385. // first load translations
  5386. I18n.loadTranslations();
  5387. // Add a hook to make all links open a new window
  5388. DOMPurify.addHook('afterSanitizeAttributes', function(node) {
  5389. // set all elements owning target to target=_blank
  5390. if ('target' in node && node.id !== 'pasteurl') {
  5391. node.setAttribute('target', '_blank');
  5392. }
  5393. // set non-HTML/MathML links to xlink:show=new
  5394. if (!node.hasAttribute('target')
  5395. && (node.hasAttribute('xlink:href')
  5396. || node.hasAttribute('href'))) {
  5397. node.setAttribute('xlink:show', 'new');
  5398. }
  5399. if ('rel' in node) {
  5400. node.setAttribute('rel', 'nofollow noopener noreferrer');
  5401. }
  5402. });
  5403. // center all modals
  5404. $('.modal').on('show.bs.modal', function(e) {
  5405. $(e.target).css({
  5406. display: 'flex'
  5407. });
  5408. });
  5409. // initialize other modules/"classes"
  5410. Alert.init();
  5411. Model.init();
  5412. AttachmentViewer.init();
  5413. DiscussionViewer.init();
  5414. Editor.init();
  5415. PasteStatus.init();
  5416. PasteViewer.init();
  5417. Prompt.init();
  5418. TopNav.init();
  5419. UiHelper.init();
  5420. CopyToClipboard.init();
  5421. PasswordPeek.init();
  5422. // check for legacy browsers before going any further
  5423. if (!Legacy.Check.getInit()) {
  5424. // Legacy check didn't complete, wait and try again
  5425. setTimeout(init, 500);
  5426. return;
  5427. }
  5428. if (!Legacy.Check.getStatus()) {
  5429. // something major is wrong, stop right away
  5430. return;
  5431. }
  5432. me.initZ();
  5433. // if delete token is passed (i.e. document has been deleted by this
  5434. // access), add an event listener for the 'new' document button in the alert
  5435. if (Model.hasDeleteToken()) {
  5436. $('#new-from-alert').on('click', function () {
  5437. UiHelper.reloadHome();
  5438. });
  5439. return;
  5440. }
  5441. // check whether existing document needs to be shown
  5442. try {
  5443. Model.getPasteId();
  5444. } catch (e) {
  5445. // otherwise create a new document
  5446. return me.newPaste();
  5447. }
  5448. // always reload on back button to invalidate cache (protect burn after read document)
  5449. window.addEventListener('popstate', () => {
  5450. window.location.reload();
  5451. });
  5452. // display an existing document
  5453. return me.showPaste();
  5454. }
  5455. return me;
  5456. })(window, document);
  5457. return {
  5458. Helper: Helper,
  5459. I18n: I18n,
  5460. CryptTool: CryptTool,
  5461. Model: Model,
  5462. UiHelper: UiHelper,
  5463. Alert: Alert,
  5464. PasteStatus: PasteStatus,
  5465. Prompt: Prompt,
  5466. Editor: Editor,
  5467. PasteViewer: PasteViewer,
  5468. AttachmentViewer: AttachmentViewer,
  5469. DiscussionViewer: DiscussionViewer,
  5470. TopNav: TopNav,
  5471. ServerInteraction: ServerInteraction,
  5472. PasteEncrypter: PasteEncrypter,
  5473. PasteDecrypter: PasteDecrypter,
  5474. PasswordPeek: PasswordPeek,
  5475. CopyToClipboard: CopyToClipboard,
  5476. Controller: Controller
  5477. };
  5478. })();
  5479. // for compatibility with tests and existing code
  5480. if (typeof jQuery !== 'undefined') {
  5481. jQuery.PrivateBin = window.PrivateBin;
  5482. }