1
0

privatebin.js 170 KB

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