privatebin.js 166 KB

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