privatebin.js 189 KB

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