privatebin.js 187 KB

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