privatebin.js 188 KB

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