1
0

privatebin.js 149 KB

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