privatebin.js 167 KB

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