privatebin.js 192 KB

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