privatebin.js 174 KB

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