1
0

privatebin.js 178 KB

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