privatebin.js 190 KB

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