privatebin.js 151 KB

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