privatebin.js 187 KB

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