privatebin.js 191 KB

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