privatebin.js 148 KB

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