privatebin.js 190 KB

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