privatebin.js 151 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936
  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. // enable shortener button
  1667. $shortenButton.removeClass('buttondisabled');
  1668. // show result
  1669. $pasteSuccess.removeClass('hidden');
  1670. // we pre-select the link so that the user only has to [Ctrl]+[c] the link
  1671. Helper.selectText($pasteUrl[0]);
  1672. };
  1673. /**
  1674. * shows the remaining time
  1675. *
  1676. * @name PasteStatus.showRemainingTime
  1677. * @function
  1678. * @param {Paste} paste
  1679. */
  1680. me.showRemainingTime = function(paste)
  1681. {
  1682. if (paste.isBurnAfterReadingEnabled()) {
  1683. // display paste "for your eyes only" if it is deleted
  1684. // the paste has been deleted when the JSON with the ciphertext
  1685. // has been downloaded
  1686. Alert.showRemaining('FOR YOUR EYES ONLY. Don\'t close this window, this message can\'t be displayed again.');
  1687. $remainingTime.addClass('foryoureyesonly');
  1688. // discourage cloning (it cannot really be prevented)
  1689. TopNav.hideCloneButton();
  1690. } else if (paste.getTimeToLive() > 0) {
  1691. // display paste expiration
  1692. let expiration = Helper.secondsToHuman(paste.getTimeToLive()),
  1693. expirationLabel = [
  1694. 'This document will expire in %d ' + expiration[1] + '.',
  1695. 'This document will expire in %d ' + expiration[1] + 's.'
  1696. ];
  1697. Alert.showRemaining([expirationLabel, expiration[0]]);
  1698. $remainingTime.removeClass('foryoureyesonly');
  1699. } else {
  1700. // never expires
  1701. return;
  1702. }
  1703. // in the end, display notification
  1704. $remainingTime.removeClass('hidden');
  1705. };
  1706. /**
  1707. * hides the remaining time and successful upload notification
  1708. *
  1709. * @name PasteStatus.hideMessages
  1710. * @function
  1711. */
  1712. me.hideMessages = function()
  1713. {
  1714. $remainingTime.addClass('hidden');
  1715. $pasteSuccess.addClass('hidden');
  1716. };
  1717. /**
  1718. * init status manager
  1719. *
  1720. * preloads jQuery elements
  1721. *
  1722. * @name PasteStatus.init
  1723. * @function
  1724. */
  1725. me.init = function()
  1726. {
  1727. $pasteSuccess = $('#pastesuccess');
  1728. // $pasteUrl is saved in me.createPasteNotification() after creation
  1729. $remainingTime = $('#remainingtime');
  1730. $shortenButton = $('#shortenbutton');
  1731. // bind elements
  1732. $shortenButton.click(sendToShortener);
  1733. };
  1734. return me;
  1735. })();
  1736. /**
  1737. * password prompt
  1738. *
  1739. * @name Prompt
  1740. * @class
  1741. */
  1742. const Prompt = (function () {
  1743. const me = {};
  1744. let $passwordDecrypt,
  1745. $passwordForm,
  1746. $passwordModal,
  1747. password = '';
  1748. /**
  1749. * submit a password in the modal dialog
  1750. *
  1751. * @name Prompt.submitPasswordModal
  1752. * @private
  1753. * @function
  1754. * @param {Event} event
  1755. */
  1756. function submitPasswordModal(event)
  1757. {
  1758. event.preventDefault();
  1759. // get input
  1760. password = $passwordDecrypt.val();
  1761. // hide modal
  1762. $passwordModal.modal('hide');
  1763. PasteDecrypter.run();
  1764. }
  1765. /**
  1766. * ask the user for the password and set it
  1767. *
  1768. * @name Prompt.requestPassword
  1769. * @function
  1770. */
  1771. me.requestPassword = function()
  1772. {
  1773. // show new bootstrap method (if available)
  1774. if ($passwordModal.length !== 0) {
  1775. $passwordModal.modal({
  1776. backdrop: 'static',
  1777. keyboard: false
  1778. });
  1779. return;
  1780. }
  1781. // fallback to old method for page template
  1782. password = prompt(I18n._('Please enter the password for this paste:'), '');
  1783. if (password === null) {
  1784. throw 'password prompt canceled';
  1785. }
  1786. if (password.length === 0) {
  1787. // recurse…
  1788. return me.requestPassword();
  1789. }
  1790. PasteDecrypter.run();
  1791. };
  1792. /**
  1793. * get the cached password
  1794. *
  1795. * If you do not get a password with this function
  1796. * (returns an empty string), use requestPassword.
  1797. *
  1798. * @name Prompt.getPassword
  1799. * @function
  1800. * @return {string}
  1801. */
  1802. me.getPassword = function()
  1803. {
  1804. return password;
  1805. };
  1806. /**
  1807. * resets the password to an empty string
  1808. *
  1809. * @name Prompt.reset
  1810. * @function
  1811. */
  1812. me.reset = function()
  1813. {
  1814. // reset internal
  1815. password = '';
  1816. // and also reset UI
  1817. $passwordDecrypt.val('');
  1818. }
  1819. /**
  1820. * init status manager
  1821. *
  1822. * preloads jQuery elements
  1823. *
  1824. * @name Prompt.init
  1825. * @function
  1826. */
  1827. me.init = function()
  1828. {
  1829. $passwordDecrypt = $('#passworddecrypt');
  1830. $passwordForm = $('#passwordform');
  1831. $passwordModal = $('#passwordmodal');
  1832. // bind events
  1833. // focus password input when it is shown
  1834. $passwordModal.on('shown.bs.Model', function () {
  1835. $passwordDecrypt.focus();
  1836. });
  1837. // handle Model password submission
  1838. $passwordForm.submit(submitPasswordModal);
  1839. };
  1840. return me;
  1841. })();
  1842. /**
  1843. * Manage paste/message input, and preview tab
  1844. *
  1845. * Note that the actual preview is handled by PasteViewer.
  1846. *
  1847. * @name Editor
  1848. * @class
  1849. */
  1850. const Editor = (function () {
  1851. const me = {};
  1852. let $editorTabs,
  1853. $messageEdit,
  1854. $messagePreview,
  1855. $message,
  1856. isPreview = false;
  1857. /**
  1858. * support input of tab character
  1859. *
  1860. * @name Editor.supportTabs
  1861. * @function
  1862. * @param {Event} event
  1863. * @this $message (but not used, so it is jQuery-free, possibly faster)
  1864. */
  1865. function supportTabs(event)
  1866. {
  1867. const keyCode = event.keyCode || event.which;
  1868. // tab was pressed
  1869. if (keyCode === 9) {
  1870. // get caret position & selection
  1871. const val = this.value,
  1872. start = this.selectionStart,
  1873. end = this.selectionEnd;
  1874. // set textarea value to: text before caret + tab + text after caret
  1875. this.value = val.substring(0, start) + '\t' + val.substring(end);
  1876. // put caret at right position again
  1877. this.selectionStart = this.selectionEnd = start + 1;
  1878. // prevent the textarea to lose focus
  1879. event.preventDefault();
  1880. }
  1881. }
  1882. /**
  1883. * view the Editor tab
  1884. *
  1885. * @name Editor.viewEditor
  1886. * @function
  1887. * @param {Event} event - optional
  1888. */
  1889. function viewEditor(event)
  1890. {
  1891. // toggle buttons
  1892. $messageEdit.addClass('active');
  1893. $messagePreview.removeClass('active');
  1894. PasteViewer.hide();
  1895. // reshow input
  1896. $message.removeClass('hidden');
  1897. me.focusInput();
  1898. // finish
  1899. isPreview = false;
  1900. // prevent jumping of page to top
  1901. if (typeof event !== 'undefined') {
  1902. event.preventDefault();
  1903. }
  1904. }
  1905. /**
  1906. * view the preview tab
  1907. *
  1908. * @name Editor.viewPreview
  1909. * @function
  1910. * @param {Event} event
  1911. */
  1912. function viewPreview(event)
  1913. {
  1914. // toggle buttons
  1915. $messageEdit.removeClass('active');
  1916. $messagePreview.addClass('active');
  1917. // hide input as now preview is shown
  1918. $message.addClass('hidden');
  1919. // show preview
  1920. PasteViewer.setText($message.val());
  1921. if (AttachmentViewer.hasAttachmentData()) {
  1922. const attachment = AttachmentViewer.getAttachment();
  1923. AttachmentViewer.handleBlobAttachmentPreview(
  1924. AttachmentViewer.getAttachmentPreview(),
  1925. attachment[0], attachment[1]
  1926. );
  1927. }
  1928. PasteViewer.run();
  1929. // finish
  1930. isPreview = true;
  1931. // prevent jumping of page to top
  1932. if (typeof event !== 'undefined') {
  1933. event.preventDefault();
  1934. }
  1935. }
  1936. /**
  1937. * get the state of the preview
  1938. *
  1939. * @name Editor.isPreview
  1940. * @function
  1941. */
  1942. me.isPreview = function()
  1943. {
  1944. return isPreview;
  1945. };
  1946. /**
  1947. * reset the Editor view
  1948. *
  1949. * @name Editor.resetInput
  1950. * @function
  1951. */
  1952. me.resetInput = function()
  1953. {
  1954. // go back to input
  1955. if (isPreview) {
  1956. viewEditor();
  1957. }
  1958. // clear content
  1959. $message.val('');
  1960. };
  1961. /**
  1962. * shows the Editor
  1963. *
  1964. * @name Editor.show
  1965. * @function
  1966. */
  1967. me.show = function()
  1968. {
  1969. $message.removeClass('hidden');
  1970. $editorTabs.removeClass('hidden');
  1971. };
  1972. /**
  1973. * hides the Editor
  1974. *
  1975. * @name Editor.reset
  1976. * @function
  1977. */
  1978. me.hide = function()
  1979. {
  1980. $message.addClass('hidden');
  1981. $editorTabs.addClass('hidden');
  1982. };
  1983. /**
  1984. * focuses the message input
  1985. *
  1986. * @name Editor.focusInput
  1987. * @function
  1988. */
  1989. me.focusInput = function()
  1990. {
  1991. $message.focus();
  1992. };
  1993. /**
  1994. * sets a new text
  1995. *
  1996. * @name Editor.setText
  1997. * @function
  1998. * @param {string} newText
  1999. */
  2000. me.setText = function(newText)
  2001. {
  2002. $message.val(newText);
  2003. };
  2004. /**
  2005. * returns the current text
  2006. *
  2007. * @name Editor.getText
  2008. * @function
  2009. * @return {string}
  2010. */
  2011. me.getText = function()
  2012. {
  2013. return $message.val();
  2014. };
  2015. /**
  2016. * init status manager
  2017. *
  2018. * preloads jQuery elements
  2019. *
  2020. * @name Editor.init
  2021. * @function
  2022. */
  2023. me.init = function()
  2024. {
  2025. $editorTabs = $('#editorTabs');
  2026. $message = $('#message');
  2027. // bind events
  2028. $message.keydown(supportTabs);
  2029. // bind click events to tab switchers (a), but save parent of them
  2030. // (li)
  2031. $messageEdit = $('#messageedit').click(viewEditor).parent();
  2032. $messagePreview = $('#messagepreview').click(viewPreview).parent();
  2033. };
  2034. return me;
  2035. })();
  2036. /**
  2037. * (view) Parse and show paste.
  2038. *
  2039. * @name PasteViewer
  2040. * @class
  2041. */
  2042. const PasteViewer = (function () {
  2043. const me = {};
  2044. let $placeholder,
  2045. $prettyMessage,
  2046. $prettyPrint,
  2047. $plainText,
  2048. text,
  2049. format = 'plaintext',
  2050. isDisplayed = false,
  2051. isChanged = true; // by default true as nothing was parsed yet
  2052. /**
  2053. * apply the set format on paste and displays it
  2054. *
  2055. * @name PasteViewer.parsePaste
  2056. * @private
  2057. * @function
  2058. */
  2059. function parsePaste()
  2060. {
  2061. // skip parsing if no text is given
  2062. if (text === '') {
  2063. return;
  2064. }
  2065. // escape HTML entities, link URLs, sanitize
  2066. const escapedLinkedText = Helper.urls2links(
  2067. $('<div />').text(text).html()
  2068. ),
  2069. sanitizedLinkedText = DOMPurify.sanitize(escapedLinkedText);
  2070. $plainText.html(sanitizedLinkedText);
  2071. $prettyPrint.html(sanitizedLinkedText);
  2072. switch (format) {
  2073. case 'markdown':
  2074. const converter = new showdown.Converter({
  2075. strikethrough: true,
  2076. tables: true,
  2077. tablesHeaderId: true,
  2078. simplifiedAutoLink: true,
  2079. excludeTrailingPunctuationFromURLs: true
  2080. });
  2081. // let showdown convert the HTML and sanitize HTML *afterwards*!
  2082. $plainText.html(
  2083. DOMPurify.sanitize(
  2084. converter.makeHtml(text)
  2085. )
  2086. );
  2087. // add table classes from bootstrap css
  2088. $plainText.find('table').addClass('table-condensed table-bordered');
  2089. break;
  2090. case 'syntaxhighlighting':
  2091. // yes, this is really needed to initialize the environment
  2092. if (typeof prettyPrint === 'function')
  2093. {
  2094. prettyPrint();
  2095. }
  2096. $prettyPrint.html(
  2097. DOMPurify.sanitize(
  2098. prettyPrintOne(escapedLinkedText, null, true)
  2099. )
  2100. );
  2101. // fall through, as the rest is the same
  2102. default: // = 'plaintext'
  2103. $prettyPrint.css('white-space', 'pre-wrap');
  2104. $prettyPrint.css('word-break', 'normal');
  2105. $prettyPrint.removeClass('prettyprint');
  2106. }
  2107. }
  2108. /**
  2109. * displays the paste
  2110. *
  2111. * @name PasteViewer.showPaste
  2112. * @private
  2113. * @function
  2114. */
  2115. function showPaste()
  2116. {
  2117. // instead of "nothing" better display a placeholder
  2118. if (text === '') {
  2119. $placeholder.removeClass('hidden');
  2120. return;
  2121. }
  2122. // otherwise hide the placeholder
  2123. $placeholder.addClass('hidden');
  2124. switch (format) {
  2125. case 'markdown':
  2126. $plainText.removeClass('hidden');
  2127. $prettyMessage.addClass('hidden');
  2128. break;
  2129. default:
  2130. $plainText.addClass('hidden');
  2131. $prettyMessage.removeClass('hidden');
  2132. break;
  2133. }
  2134. }
  2135. /**
  2136. * sets the format in which the text is shown
  2137. *
  2138. * @name PasteViewer.setFormat
  2139. * @function
  2140. * @param {string} newFormat the new format
  2141. */
  2142. me.setFormat = function(newFormat)
  2143. {
  2144. // skip if there is no update
  2145. if (format === newFormat) {
  2146. return;
  2147. }
  2148. // needs to update display too, if we switch from or to Markdown
  2149. if (format === 'markdown' || newFormat === 'markdown') {
  2150. isDisplayed = false;
  2151. }
  2152. format = newFormat;
  2153. isChanged = true;
  2154. };
  2155. /**
  2156. * returns the current format
  2157. *
  2158. * @name PasteViewer.getFormat
  2159. * @function
  2160. * @return {string}
  2161. */
  2162. me.getFormat = function()
  2163. {
  2164. return format;
  2165. };
  2166. /**
  2167. * returns whether the current view is pretty printed
  2168. *
  2169. * @name PasteViewer.isPrettyPrinted
  2170. * @function
  2171. * @return {bool}
  2172. */
  2173. me.isPrettyPrinted = function()
  2174. {
  2175. return $prettyPrint.hasClass('prettyprinted');
  2176. };
  2177. /**
  2178. * sets the text to show
  2179. *
  2180. * @name PasteViewer.setText
  2181. * @function
  2182. * @param {string} newText the text to show
  2183. */
  2184. me.setText = function(newText)
  2185. {
  2186. if (text !== newText) {
  2187. text = newText;
  2188. isChanged = true;
  2189. }
  2190. };
  2191. /**
  2192. * gets the current cached text
  2193. *
  2194. * @name PasteViewer.getText
  2195. * @function
  2196. * @return {string}
  2197. */
  2198. me.getText = function()
  2199. {
  2200. return text;
  2201. };
  2202. /**
  2203. * show/update the parsed text (preview)
  2204. *
  2205. * @name PasteViewer.run
  2206. * @function
  2207. */
  2208. me.run = function()
  2209. {
  2210. if (isChanged) {
  2211. parsePaste();
  2212. isChanged = false;
  2213. }
  2214. if (!isDisplayed) {
  2215. showPaste();
  2216. isDisplayed = true;
  2217. }
  2218. };
  2219. /**
  2220. * hide parsed text (preview)
  2221. *
  2222. * @name PasteViewer.hide
  2223. * @function
  2224. */
  2225. me.hide = function()
  2226. {
  2227. if (!isDisplayed) {
  2228. return;
  2229. }
  2230. $plainText.addClass('hidden');
  2231. $prettyMessage.addClass('hidden');
  2232. $placeholder.addClass('hidden');
  2233. AttachmentViewer.hideAttachmentPreview();
  2234. isDisplayed = false;
  2235. };
  2236. /**
  2237. * init status manager
  2238. *
  2239. * preloads jQuery elements
  2240. *
  2241. * @name PasteViewer.init
  2242. * @function
  2243. */
  2244. me.init = function()
  2245. {
  2246. $placeholder = $('#placeholder');
  2247. $plainText = $('#plaintext');
  2248. $prettyMessage = $('#prettymessage');
  2249. $prettyPrint = $('#prettyprint');
  2250. // get default option from template/HTML or fall back to set value
  2251. format = Model.getFormatDefault() || format;
  2252. text = '';
  2253. isDisplayed = false;
  2254. isChanged = true;
  2255. };
  2256. return me;
  2257. })();
  2258. /**
  2259. * (view) Show attachment and preview if possible
  2260. *
  2261. * @name AttachmentViewer
  2262. * @class
  2263. */
  2264. const AttachmentViewer = (function () {
  2265. const me = {};
  2266. let $attachmentLink,
  2267. $attachmentPreview,
  2268. $attachment,
  2269. attachmentData,
  2270. file,
  2271. $fileInput,
  2272. $dragAndDropFileName,
  2273. attachmentHasPreview = false;
  2274. /**
  2275. * sets the attachment but does not yet show it
  2276. *
  2277. * @name AttachmentViewer.setAttachment
  2278. * @function
  2279. * @param {string} attachmentData - base64-encoded data of file
  2280. * @param {string} fileName - optional, file name
  2281. */
  2282. me.setAttachment = function(attachmentData, fileName)
  2283. {
  2284. // data URI format: data:[<mediaType>][;base64],<data>
  2285. // position in data URI string of where data begins
  2286. const base64Start = attachmentData.indexOf(',') + 1;
  2287. // position in data URI string of where mediaType ends
  2288. const mediaTypeEnd = attachmentData.indexOf(';');
  2289. // extract mediaType
  2290. const mediaType = attachmentData.substring(5, mediaTypeEnd);
  2291. // extract data and convert to binary
  2292. const decodedData = atob(attachmentData.substring(base64Start));
  2293. // Transform into a Blob
  2294. const buf = new Uint8Array(decodedData.length);
  2295. for (let i = 0; i < decodedData.length; ++i) {
  2296. buf[i] = decodedData.charCodeAt(i);
  2297. }
  2298. const blob = new window.Blob([ buf ], { type: mediaType });
  2299. // Get Blob URL
  2300. const blobUrl = window.URL.createObjectURL(blob);
  2301. // IE does not support setting a data URI on an a element
  2302. // Using msSaveBlob to download
  2303. if (window.Blob && navigator.msSaveBlob) {
  2304. $attachmentLink.off('click').on('click', function () {
  2305. navigator.msSaveBlob(blob, fileName);
  2306. });
  2307. } else {
  2308. $attachmentLink.attr('href', blobUrl);
  2309. }
  2310. if (typeof fileName !== 'undefined') {
  2311. $attachmentLink.attr('download', fileName);
  2312. }
  2313. me.handleBlobAttachmentPreview($attachmentPreview, blobUrl, mediaType);
  2314. };
  2315. /**
  2316. * displays the attachment
  2317. *
  2318. * @name AttachmentViewer.showAttachment
  2319. * @function
  2320. */
  2321. me.showAttachment = function()
  2322. {
  2323. $attachment.removeClass('hidden');
  2324. if (attachmentHasPreview) {
  2325. $attachmentPreview.removeClass('hidden');
  2326. }
  2327. };
  2328. /**
  2329. * removes the attachment
  2330. *
  2331. * This automatically hides the attachment containers too, to
  2332. * prevent an inconsistent display.
  2333. *
  2334. * @name AttachmentViewer.removeAttachment
  2335. * @function
  2336. */
  2337. me.removeAttachment = function()
  2338. {
  2339. if (!$attachment.length) {
  2340. return;
  2341. }
  2342. me.hideAttachment();
  2343. me.hideAttachmentPreview();
  2344. $attachmentLink.removeAttr('href');
  2345. $attachmentLink.removeAttr('download');
  2346. $attachmentLink.off('click');
  2347. $attachmentPreview.html('');
  2348. AttachmentViewer.removeAttachmentData();
  2349. };
  2350. /**
  2351. * removes the attachment data
  2352. *
  2353. * This removes the data, which would be uploaded otherwise.
  2354. *
  2355. * @name AttachmentViewer.removeAttachmentData
  2356. * @function
  2357. */
  2358. me.removeAttachmentData = function()
  2359. {
  2360. file = undefined;
  2361. attachmentData = undefined;
  2362. };
  2363. /**
  2364. * Cleares the drag & drop data.
  2365. *
  2366. * @name AttachmentViewer.clearDragAndDrop
  2367. * @function
  2368. */
  2369. me.clearDragAndDrop = function()
  2370. {
  2371. $dragAndDropFileName.text('');
  2372. };
  2373. /**
  2374. * hides the attachment
  2375. *
  2376. * This will not hide the preview (see AttachmentViewer.hideAttachmentPreview
  2377. * for that) nor will it hide the attachment link if it was moved somewhere
  2378. * else (see AttachmentViewer.moveAttachmentTo).
  2379. *
  2380. * @name AttachmentViewer.hideAttachment
  2381. * @function
  2382. */
  2383. me.hideAttachment = function()
  2384. {
  2385. $attachment.addClass('hidden');
  2386. };
  2387. /**
  2388. * hides the attachment preview
  2389. *
  2390. * @name AttachmentViewer.hideAttachmentPreview
  2391. * @function
  2392. */
  2393. me.hideAttachmentPreview = function()
  2394. {
  2395. if ($attachmentPreview) {
  2396. $attachmentPreview.addClass('hidden');
  2397. }
  2398. };
  2399. /**
  2400. * checks if there is an attachment displayed
  2401. *
  2402. * @name AttachmentViewer.hasAttachment
  2403. * @function
  2404. */
  2405. me.hasAttachment = function()
  2406. {
  2407. if (!$attachment.length) {
  2408. return false;
  2409. }
  2410. const link = $attachmentLink.prop('href');
  2411. return (typeof link !== 'undefined' && link !== '');
  2412. };
  2413. /**
  2414. * checks if there is attachment data (for preview!) available
  2415. *
  2416. * It returns true, when there is data that needs to be encrypted.
  2417. *
  2418. * @name AttachmentViewer.hasAttachmentData
  2419. * @function
  2420. */
  2421. me.hasAttachmentData = function()
  2422. {
  2423. if ($attachment.length) {
  2424. return true;
  2425. }
  2426. return false;
  2427. };
  2428. /**
  2429. * return the attachment
  2430. *
  2431. * @name AttachmentViewer.getAttachment
  2432. * @function
  2433. * @returns {array}
  2434. */
  2435. me.getAttachment = function()
  2436. {
  2437. return [
  2438. $attachmentLink.prop('href'),
  2439. $attachmentLink.prop('download')
  2440. ];
  2441. };
  2442. /**
  2443. * moves the attachment link to another element
  2444. *
  2445. * It is advisable to hide the attachment afterwards (AttachmentViewer.hideAttachment)
  2446. *
  2447. * @name AttachmentViewer.moveAttachmentTo
  2448. * @function
  2449. * @param {jQuery} $element - the wrapper/container element where this should be moved to
  2450. * @param {string} label - the text to show (%s will be replaced with the file name), will automatically be translated
  2451. */
  2452. me.moveAttachmentTo = function($element, label)
  2453. {
  2454. // move elemement to new place
  2455. $attachmentLink.appendTo($element);
  2456. // update text
  2457. I18n._($attachmentLink, label, $attachmentLink.attr('download'));
  2458. };
  2459. /**
  2460. * read file data as data URL using the FileReader API
  2461. *
  2462. * @name AttachmentViewer.readFileData
  2463. * @private
  2464. * @function
  2465. * @param {object} loadedFile (optional) loaded file object
  2466. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/FileReader#readAsDataURL()}
  2467. */
  2468. function readFileData(loadedFile) {
  2469. if (typeof FileReader === 'undefined') {
  2470. // revert loading status…
  2471. me.hideAttachment();
  2472. me.hideAttachmentPreview();
  2473. Alert.showError('Your browser does not support uploading encrypted files. Please use a newer browser.');
  2474. return;
  2475. }
  2476. const fileReader = new FileReader();
  2477. if (loadedFile === undefined) {
  2478. loadedFile = $fileInput[0].files[0];
  2479. $dragAndDropFileName.text('');
  2480. } else {
  2481. $dragAndDropFileName.text(loadedFile.name);
  2482. }
  2483. file = loadedFile;
  2484. fileReader.onload = function (event) {
  2485. const dataURL = event.target.result;
  2486. attachmentData = dataURL;
  2487. if (Editor.isPreview()) {
  2488. me.setAttachment(dataURL, loadedFile.name || '');
  2489. $attachmentPreview.removeClass('hidden');
  2490. }
  2491. };
  2492. fileReader.readAsDataURL(loadedFile);
  2493. }
  2494. /**
  2495. * handle the preview of files decoded to blob that can either be an image, video, audio or pdf element
  2496. *
  2497. * @name AttachmentViewer.handleBlobAttachmentPreview
  2498. * @function
  2499. * @argument {jQuery} $targetElement element where the preview should be appended
  2500. * @argument {string} file as a blob URL
  2501. * @argument {string} mime type
  2502. */
  2503. me.handleBlobAttachmentPreview = function ($targetElement, blobUrl, mimeType) {
  2504. if (blobUrl) {
  2505. attachmentHasPreview = true;
  2506. if (mimeType.match(/image\//i)) {
  2507. $targetElement.html(
  2508. $(document.createElement('img'))
  2509. .attr('src', blobUrl)
  2510. .attr('class', 'img-thumbnail')
  2511. );
  2512. } else if (mimeType.match(/video\//i)) {
  2513. $targetElement.html(
  2514. $(document.createElement('video'))
  2515. .attr('controls', 'true')
  2516. .attr('autoplay', 'true')
  2517. .attr('class', 'img-thumbnail')
  2518. .append($(document.createElement('source'))
  2519. .attr('type', mimeType)
  2520. .attr('src', blobUrl))
  2521. );
  2522. } else if (mimeType.match(/audio\//i)) {
  2523. $targetElement.html(
  2524. $(document.createElement('audio'))
  2525. .attr('controls', 'true')
  2526. .attr('autoplay', 'true')
  2527. .append($(document.createElement('source'))
  2528. .attr('type', mimeType)
  2529. .attr('src', blobUrl))
  2530. );
  2531. } else if (mimeType.match(/\/pdf/i)) {
  2532. // Fallback for browsers, that don't support the vh unit
  2533. var clientHeight = $(window).height();
  2534. $targetElement.html(
  2535. $(document.createElement('embed'))
  2536. .attr('src', blobUrl)
  2537. .attr('type', 'application/pdf')
  2538. .attr('class', 'pdfPreview')
  2539. .css('height', clientHeight)
  2540. );
  2541. } else {
  2542. attachmentHasPreview = false;
  2543. }
  2544. }
  2545. };
  2546. /**
  2547. * attaches the file attachment drag & drop handler to the page
  2548. *
  2549. * @name AttachmentViewer.addDragDropHandler
  2550. * @private
  2551. * @function
  2552. */
  2553. function addDragDropHandler() {
  2554. if (typeof $fileInput === 'undefined' || $fileInput.length === 0) {
  2555. return;
  2556. }
  2557. const ignoreDragDrop = function(event) {
  2558. event.stopPropagation();
  2559. event.preventDefault();
  2560. };
  2561. const drop = function(event) {
  2562. const evt = event.originalEvent;
  2563. evt.stopPropagation();
  2564. evt.preventDefault();
  2565. if ($fileInput) {
  2566. const file = evt.dataTransfer.files[0];
  2567. //Clear the file input:
  2568. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2569. $fileInput.unwrap();
  2570. //Only works in Chrome:
  2571. //fileInput[0].files = e.dataTransfer.files;
  2572. readFileData(file);
  2573. }
  2574. };
  2575. $(document).on('drop', drop);
  2576. $(document).on('dragenter', ignoreDragDrop);
  2577. $(document).on('dragover', ignoreDragDrop);
  2578. $fileInput.on('change', function () {
  2579. readFileData();
  2580. });
  2581. }
  2582. /**
  2583. * attaches the clipboard attachment handler to the page
  2584. *
  2585. * @name AttachmentViewer.addClipboardEventHandler
  2586. * @private
  2587. * @function
  2588. */
  2589. function addClipboardEventHandler() {
  2590. $(document).on('paste', function (event) {
  2591. const items = (event.clipboardData || event.originalEvent.clipboardData).items;
  2592. for (let i = 0; i < items.length; ++i) {
  2593. if (items[i].kind === 'file') {
  2594. //Clear the file input:
  2595. $fileInput.wrap('<form>').closest('form').get(0).reset();
  2596. $fileInput.unwrap();
  2597. readFileData(items[i].getAsFile());
  2598. }
  2599. }
  2600. });
  2601. }
  2602. /**
  2603. * getter for attachment data
  2604. *
  2605. * @name AttachmentViewer.getAttachmentData
  2606. * @function
  2607. * @return {jQuery}
  2608. */
  2609. me.getAttachmentData = function () {
  2610. return attachmentData;
  2611. };
  2612. /**
  2613. * getter for attachment link
  2614. *
  2615. * @name AttachmentViewer.getAttachmentLink
  2616. * @function
  2617. * @return {jQuery}
  2618. */
  2619. me.getAttachmentLink = function () {
  2620. return $attachmentLink;
  2621. };
  2622. /**
  2623. * getter for attachment preview
  2624. *
  2625. * @name AttachmentViewer.getAttachmentPreview
  2626. * @function
  2627. * @return {jQuery}
  2628. */
  2629. me.getAttachmentPreview = function () {
  2630. return $attachmentPreview;
  2631. };
  2632. /**
  2633. * getter for file data, returns the file contents
  2634. *
  2635. * @name AttachmentViewer.getFile
  2636. * @function
  2637. * @return {string}
  2638. */
  2639. me.getFile = function () {
  2640. return file;
  2641. };
  2642. /**
  2643. * initiate
  2644. *
  2645. * preloads jQuery elements
  2646. *
  2647. * @name AttachmentViewer.init
  2648. * @function
  2649. */
  2650. me.init = function()
  2651. {
  2652. $attachment = $('#attachment');
  2653. if($attachment.length){
  2654. $attachmentLink = $('#attachment a');
  2655. $attachmentPreview = $('#attachmentPreview');
  2656. $dragAndDropFileName = $('#dragAndDropFileName');
  2657. $fileInput = $('#file');
  2658. addDragDropHandler();
  2659. addClipboardEventHandler();
  2660. }
  2661. }
  2662. return me;
  2663. })();
  2664. /**
  2665. * (view) Shows discussion thread and handles replies
  2666. *
  2667. * @name DiscussionViewer
  2668. * @class
  2669. */
  2670. const DiscussionViewer = (function () {
  2671. const me = {};
  2672. let $commentTail,
  2673. $discussion,
  2674. $reply,
  2675. $replyMessage,
  2676. $replyNickname,
  2677. $replyStatus,
  2678. $commentContainer,
  2679. replyCommentId;
  2680. /**
  2681. * initializes the templates
  2682. *
  2683. * @name DiscussionViewer.initTemplates
  2684. * @private
  2685. * @function
  2686. */
  2687. function initTemplates()
  2688. {
  2689. $reply = Model.getTemplate('reply');
  2690. $replyMessage = $reply.find('#replymessage');
  2691. $replyNickname = $reply.find('#nickname');
  2692. $replyStatus = $reply.find('#replystatus');
  2693. // cache jQuery elements
  2694. $commentTail = Model.getTemplate('commenttail');
  2695. }
  2696. /**
  2697. * open the comment entry when clicking the "Reply" button of a comment
  2698. *
  2699. * @name DiscussionViewer.openReply
  2700. * @private
  2701. * @function
  2702. * @param {Event} event
  2703. */
  2704. function openReply(event)
  2705. {
  2706. const $source = $(event.target);
  2707. // clear input
  2708. $replyMessage.val('');
  2709. $replyNickname.val('');
  2710. // get comment id from source element
  2711. replyCommentId = $source.parent().prop('id').split('_')[1];
  2712. // move to correct position
  2713. $source.after($reply);
  2714. // show
  2715. $reply.removeClass('hidden');
  2716. $replyMessage.focus();
  2717. event.preventDefault();
  2718. }
  2719. /**
  2720. * custom handler for displaying notifications in own status message area
  2721. *
  2722. * @name DiscussionViewer.handleNotification
  2723. * @function
  2724. * @param {string} alertType
  2725. * @return {bool|jQuery}
  2726. */
  2727. me.handleNotification = function(alertType)
  2728. {
  2729. // ignore loading messages
  2730. if (alertType === 'loading') {
  2731. return false;
  2732. }
  2733. if (alertType === 'danger') {
  2734. $replyStatus.removeClass('alert-info');
  2735. $replyStatus.addClass('alert-danger');
  2736. $replyStatus.find(':first').removeClass('glyphicon-alert');
  2737. $replyStatus.find(':first').addClass('glyphicon-info-sign');
  2738. } else {
  2739. $replyStatus.removeClass('alert-danger');
  2740. $replyStatus.addClass('alert-info');
  2741. $replyStatus.find(':first').removeClass('glyphicon-info-sign');
  2742. $replyStatus.find(':first').addClass('glyphicon-alert');
  2743. }
  2744. return $replyStatus;
  2745. };
  2746. /**
  2747. * adds another comment
  2748. *
  2749. * @name DiscussionViewer.addComment
  2750. * @function
  2751. * @param {Comment} comment
  2752. * @param {string} commentText
  2753. * @param {string} nickname
  2754. */
  2755. me.addComment = function(comment, commentText, nickname)
  2756. {
  2757. if (commentText === '') {
  2758. commentText = 'comment decryption failed';
  2759. }
  2760. // create new comment based on template
  2761. const $commentEntry = Model.getTemplate('comment');
  2762. $commentEntry.prop('id', 'comment_' + comment.id);
  2763. const $commentEntryData = $commentEntry.find('div.commentdata');
  2764. // set & parse text
  2765. $commentEntryData.html(
  2766. DOMPurify.sanitize(
  2767. Helper.urls2links(commentText)
  2768. )
  2769. );
  2770. // set nickname
  2771. if (nickname.length > 0) {
  2772. $commentEntry.find('span.nickname').text(nickname);
  2773. } else {
  2774. $commentEntry.find('span.nickname').html('<i></i>');
  2775. I18n._($commentEntry.find('span.nickname i'), 'Anonymous');
  2776. }
  2777. // set date
  2778. $commentEntry.find('span.commentdate')
  2779. .text(' (' + (new Date(comment.getCreated() * 1000).toLocaleString()) + ')')
  2780. .attr('title', 'CommentID: ' + comment.id);
  2781. // if an avatar is available, display it
  2782. const icon = comment.getIcon();
  2783. if (icon) {
  2784. $commentEntry.find('span.nickname')
  2785. .before(
  2786. '<img src="' + icon + '" class="vizhash" /> '
  2787. );
  2788. $(document).on('languageLoaded', function () {
  2789. $commentEntry.find('img.vizhash')
  2790. .prop('title', I18n._('Avatar generated from IP address'));
  2791. });
  2792. }
  2793. // starting point (default value/fallback)
  2794. let $place = $commentContainer;
  2795. // if parent comment exists
  2796. const $parentComment = $('#comment_' + comment.parentid);
  2797. if ($parentComment.length) {
  2798. // use parent as position for new comment, so it is shifted
  2799. // to the right
  2800. $place = $parentComment;
  2801. }
  2802. // finally append comment
  2803. $place.append($commentEntry);
  2804. };
  2805. /**
  2806. * finishes the discussion area after last comment
  2807. *
  2808. * @name DiscussionViewer.finishDiscussion
  2809. * @function
  2810. */
  2811. me.finishDiscussion = function()
  2812. {
  2813. // add 'add new comment' area
  2814. $commentContainer.append($commentTail);
  2815. // show discussions
  2816. $discussion.removeClass('hidden');
  2817. };
  2818. /**
  2819. * removes the old discussion and prepares everything for creating a new
  2820. * one.
  2821. *
  2822. * @name DiscussionViewer.prepareNewDiscussion
  2823. * @function
  2824. */
  2825. me.prepareNewDiscussion = function()
  2826. {
  2827. $commentContainer.html('');
  2828. $discussion.addClass('hidden');
  2829. // (re-)init templates
  2830. initTemplates();
  2831. };
  2832. /**
  2833. * returns the users message from the reply form
  2834. *
  2835. * @name DiscussionViewer.getReplyMessage
  2836. * @function
  2837. * @return {String}
  2838. */
  2839. me.getReplyMessage = function()
  2840. {
  2841. return $replyMessage.val();
  2842. };
  2843. /**
  2844. * returns the users nickname (if any) from the reply form
  2845. *
  2846. * @name DiscussionViewer.getReplyNickname
  2847. * @function
  2848. * @return {String}
  2849. */
  2850. me.getReplyNickname = function()
  2851. {
  2852. return $replyNickname.val();
  2853. };
  2854. /**
  2855. * returns the id of the parent comment the user is replying to
  2856. *
  2857. * @name DiscussionViewer.getReplyCommentId
  2858. * @function
  2859. * @return {int|undefined}
  2860. */
  2861. me.getReplyCommentId = function()
  2862. {
  2863. return replyCommentId;
  2864. };
  2865. /**
  2866. * highlights a specific comment and scrolls to it if necessary
  2867. *
  2868. * @name DiscussionViewer.highlightComment
  2869. * @function
  2870. * @param {string} commentId
  2871. * @param {bool} fadeOut - whether to fade out the comment
  2872. */
  2873. me.highlightComment = function(commentId, fadeOut)
  2874. {
  2875. const $comment = $('#comment_' + commentId);
  2876. // in case comment does not exist, cancel
  2877. if ($comment.length === 0) {
  2878. return;
  2879. }
  2880. $comment.addClass('highlight');
  2881. const highlightComment = function () {
  2882. if (fadeOut === true) {
  2883. setTimeout(function () {
  2884. $comment.removeClass('highlight');
  2885. }, 300);
  2886. }
  2887. };
  2888. if (UiHelper.isVisible($comment)) {
  2889. return highlightComment();
  2890. }
  2891. UiHelper.scrollTo($comment, 100, 'swing', highlightComment);
  2892. };
  2893. /**
  2894. * initiate
  2895. *
  2896. * preloads jQuery elements
  2897. *
  2898. * @name DiscussionViewer.init
  2899. * @function
  2900. */
  2901. me.init = function()
  2902. {
  2903. // bind events to templates (so they are later cloned)
  2904. $('#commenttailtemplate, #commenttemplate').find('button').on('click', openReply);
  2905. $('#replytemplate').find('button').on('click', PasteEncrypter.sendComment);
  2906. $commentContainer = $('#commentcontainer');
  2907. $discussion = $('#discussion');
  2908. };
  2909. return me;
  2910. })();
  2911. /**
  2912. * Manage top (navigation) bar
  2913. *
  2914. * @name TopNav
  2915. * @param {object} window
  2916. * @param {object} document
  2917. * @class
  2918. */
  2919. const TopNav = (function (window, document) {
  2920. const me = {};
  2921. let createButtonsDisplayed = false,
  2922. viewButtonsDisplayed = false,
  2923. $attach,
  2924. $burnAfterReading,
  2925. $burnAfterReadingOption,
  2926. $cloneButton,
  2927. $customAttachment,
  2928. $expiration,
  2929. $fileRemoveButton,
  2930. $fileWrap,
  2931. $formatter,
  2932. $newButton,
  2933. $openDiscussion,
  2934. $openDiscussionOption,
  2935. $password,
  2936. $passwordInput,
  2937. $rawTextButton,
  2938. $qrCodeLink,
  2939. $sendButton,
  2940. $retryButton,
  2941. pasteExpiration = '1week',
  2942. retryButtonCallback;
  2943. /**
  2944. * set the expiration on bootstrap templates in dropdown
  2945. *
  2946. * @name TopNav.updateExpiration
  2947. * @private
  2948. * @function
  2949. * @param {Event} event
  2950. */
  2951. function updateExpiration(event)
  2952. {
  2953. // get selected option
  2954. const target = $(event.target);
  2955. // update dropdown display and save new expiration time
  2956. $('#pasteExpirationDisplay').text(target.text());
  2957. pasteExpiration = target.data('expiration');
  2958. event.preventDefault();
  2959. }
  2960. /**
  2961. * set the format on bootstrap templates in dropdown
  2962. *
  2963. * @name TopNav.updateFormat
  2964. * @private
  2965. * @function
  2966. * @param {Event} event
  2967. */
  2968. function updateFormat(event)
  2969. {
  2970. // get selected option
  2971. const $target = $(event.target);
  2972. // update dropdown display and save new format
  2973. const newFormat = $target.data('format');
  2974. $('#pasteFormatterDisplay').text($target.text());
  2975. PasteViewer.setFormat(newFormat);
  2976. // update preview
  2977. if (Editor.isPreview()) {
  2978. PasteViewer.run();
  2979. }
  2980. event.preventDefault();
  2981. }
  2982. /**
  2983. * when "burn after reading" is checked, disable discussion
  2984. *
  2985. * @name TopNav.changeBurnAfterReading
  2986. * @private
  2987. * @function
  2988. */
  2989. function changeBurnAfterReading()
  2990. {
  2991. if ($burnAfterReading.is(':checked')) {
  2992. $openDiscussionOption.addClass('buttondisabled');
  2993. $openDiscussion.prop('checked', false);
  2994. // if button is actually disabled, force-enable it and uncheck other button
  2995. $burnAfterReadingOption.removeClass('buttondisabled');
  2996. } else {
  2997. $openDiscussionOption.removeClass('buttondisabled');
  2998. }
  2999. }
  3000. /**
  3001. * when discussion is checked, disable "burn after reading"
  3002. *
  3003. * @name TopNav.changeOpenDiscussion
  3004. * @private
  3005. * @function
  3006. */
  3007. function changeOpenDiscussion()
  3008. {
  3009. if ($openDiscussion.is(':checked')) {
  3010. $burnAfterReadingOption.addClass('buttondisabled');
  3011. $burnAfterReading.prop('checked', false);
  3012. // if button is actually disabled, force-enable it and uncheck other button
  3013. $openDiscussionOption.removeClass('buttondisabled');
  3014. } else {
  3015. $burnAfterReadingOption.removeClass('buttondisabled');
  3016. }
  3017. }
  3018. /**
  3019. * return raw text
  3020. *
  3021. * @name TopNav.rawText
  3022. * @private
  3023. * @function
  3024. */
  3025. function rawText()
  3026. {
  3027. TopNav.hideAllButtons();
  3028. Alert.showLoading('Showing raw text…', 'time');
  3029. let paste = PasteViewer.getText();
  3030. // push a new state to allow back navigation with browser back button
  3031. history.pushState(
  3032. {type: 'raw'},
  3033. document.title,
  3034. // recreate paste URL
  3035. Helper.baseUri() + '?' + Model.getPasteId() + '#' +
  3036. CryptTool.base58encode(Model.getPasteKey())
  3037. );
  3038. // we use text/html instead of text/plain to avoid a bug when
  3039. // reloading the raw text view (it reverts to type text/html)
  3040. const $head = $('head').children().not('noscript, script, link[type="text/css"]'),
  3041. newDoc = document.open('text/html', 'replace');
  3042. newDoc.write('<!DOCTYPE html><html><head>');
  3043. for (let i = 0; i < $head.length; ++i) {
  3044. newDoc.write($head[i].outerHTML);
  3045. }
  3046. newDoc.write('</head><body><pre>' + DOMPurify.sanitize($('<div />').text(paste).html()) + '</pre></body></html>');
  3047. newDoc.close();
  3048. }
  3049. /**
  3050. * saves the language in a cookie and reloads the page
  3051. *
  3052. * @name TopNav.setLanguage
  3053. * @private
  3054. * @function
  3055. * @param {Event} event
  3056. */
  3057. function setLanguage(event)
  3058. {
  3059. document.cookie = 'lang=' + $(event.target).data('lang');
  3060. UiHelper.reloadHome();
  3061. }
  3062. /**
  3063. * hides all messages and creates a new paste
  3064. *
  3065. * @name TopNav.clickNewPaste
  3066. * @private
  3067. * @function
  3068. */
  3069. function clickNewPaste()
  3070. {
  3071. Controller.hideStatusMessages();
  3072. Controller.newPaste();
  3073. }
  3074. /**
  3075. * retrys some callback registered before
  3076. *
  3077. * @name TopNav.clickRetryButton
  3078. * @private
  3079. * @function
  3080. * @param {Event} event
  3081. */
  3082. function clickRetryButton(event)
  3083. {
  3084. retryButtonCallback(event);
  3085. }
  3086. /**
  3087. * removes the existing attachment
  3088. *
  3089. * @name TopNav.removeAttachment
  3090. * @private
  3091. * @function
  3092. * @param {Event} event
  3093. */
  3094. function removeAttachment(event)
  3095. {
  3096. // if custom attachment is used, remove it first
  3097. if (!$customAttachment.hasClass('hidden')) {
  3098. AttachmentViewer.removeAttachment();
  3099. $customAttachment.addClass('hidden');
  3100. $fileWrap.removeClass('hidden');
  3101. }
  3102. // in any case, remove saved attachment data
  3103. AttachmentViewer.removeAttachmentData();
  3104. // hide UI for selected files
  3105. // our up-to-date jQuery can handle it :)
  3106. $fileWrap.find('input').val('');
  3107. AttachmentViewer.clearDragAndDrop();
  3108. // pevent '#' from appearing in the URL
  3109. event.preventDefault();
  3110. }
  3111. /**
  3112. * Shows the QR code of the current paste (URL).
  3113. *
  3114. * @name TopNav.displayQrCode
  3115. * @private
  3116. * @function
  3117. */
  3118. function displayQrCode()
  3119. {
  3120. const qrCanvas = kjua({
  3121. render: 'canvas',
  3122. text: window.location.href
  3123. });
  3124. $('#qrcode-display').html(qrCanvas);
  3125. }
  3126. /**
  3127. * Shows all navigation elements for viewing an existing paste
  3128. *
  3129. * @name TopNav.showViewButtons
  3130. * @function
  3131. */
  3132. me.showViewButtons = function()
  3133. {
  3134. if (viewButtonsDisplayed) {
  3135. return;
  3136. }
  3137. $newButton.removeClass('hidden');
  3138. $cloneButton.removeClass('hidden');
  3139. $rawTextButton.removeClass('hidden');
  3140. $qrCodeLink.removeClass('hidden');
  3141. viewButtonsDisplayed = true;
  3142. };
  3143. /**
  3144. * Hides all navigation elements for viewing an existing paste
  3145. *
  3146. * @name TopNav.hideViewButtons
  3147. * @function
  3148. */
  3149. me.hideViewButtons = function()
  3150. {
  3151. if (!viewButtonsDisplayed) {
  3152. return;
  3153. }
  3154. $cloneButton.addClass('hidden');
  3155. $newButton.addClass('hidden');
  3156. $rawTextButton.addClass('hidden');
  3157. $qrCodeLink.addClass('hidden');
  3158. viewButtonsDisplayed = false;
  3159. };
  3160. /**
  3161. * Hides all elements belonging to existing pastes
  3162. *
  3163. * @name TopNav.hideAllButtons
  3164. * @function
  3165. */
  3166. me.hideAllButtons = function()
  3167. {
  3168. me.hideViewButtons();
  3169. me.hideCreateButtons();
  3170. };
  3171. /**
  3172. * shows all elements needed when creating a new paste
  3173. *
  3174. * @name TopNav.showCreateButtons
  3175. * @function
  3176. */
  3177. me.showCreateButtons = function()
  3178. {
  3179. if (createButtonsDisplayed) {
  3180. return;
  3181. }
  3182. $attach.removeClass('hidden');
  3183. $burnAfterReadingOption.removeClass('hidden');
  3184. $expiration.removeClass('hidden');
  3185. $formatter.removeClass('hidden');
  3186. $newButton.removeClass('hidden');
  3187. $openDiscussionOption.removeClass('hidden');
  3188. $password.removeClass('hidden');
  3189. $sendButton.removeClass('hidden');
  3190. createButtonsDisplayed = true;
  3191. };
  3192. /**
  3193. * shows all elements needed when creating a new paste
  3194. *
  3195. * @name TopNav.hideCreateButtons
  3196. * @function
  3197. */
  3198. me.hideCreateButtons = function()
  3199. {
  3200. if (!createButtonsDisplayed) {
  3201. return;
  3202. }
  3203. $newButton.addClass('hidden');
  3204. $sendButton.addClass('hidden');
  3205. $expiration.addClass('hidden');
  3206. $formatter.addClass('hidden');
  3207. $burnAfterReadingOption.addClass('hidden');
  3208. $openDiscussionOption.addClass('hidden');
  3209. $password.addClass('hidden');
  3210. $attach.addClass('hidden');
  3211. createButtonsDisplayed = false;
  3212. };
  3213. /**
  3214. * only shows the "new paste" button
  3215. *
  3216. * @name TopNav.showNewPasteButton
  3217. * @function
  3218. */
  3219. me.showNewPasteButton = function()
  3220. {
  3221. $newButton.removeClass('hidden');
  3222. };
  3223. /**
  3224. * only shows the "retry" button
  3225. *
  3226. * @name TopNav.showRetryButton
  3227. * @function
  3228. */
  3229. me.showRetryButton = function()
  3230. {
  3231. $retryButton.removeClass('hidden');
  3232. }
  3233. /**
  3234. * hides the "retry" button
  3235. *
  3236. * @name TopNav.hideRetryButton
  3237. * @function
  3238. */
  3239. me.hideRetryButton = function()
  3240. {
  3241. $retryButton.addClass('hidden');
  3242. }
  3243. /**
  3244. * only hides the clone button
  3245. *
  3246. * @name TopNav.hideCloneButton
  3247. * @function
  3248. */
  3249. me.hideCloneButton = function()
  3250. {
  3251. $cloneButton.addClass('hidden');
  3252. };
  3253. /**
  3254. * only hides the raw text button
  3255. *
  3256. * @name TopNav.hideRawButton
  3257. * @function
  3258. */
  3259. me.hideRawButton = function()
  3260. {
  3261. $rawTextButton.addClass('hidden');
  3262. };
  3263. /**
  3264. * hides the file selector in attachment
  3265. *
  3266. * @name TopNav.hideFileSelector
  3267. * @function
  3268. */
  3269. me.hideFileSelector = function()
  3270. {
  3271. $fileWrap.addClass('hidden');
  3272. };
  3273. /**
  3274. * shows the custom attachment
  3275. *
  3276. * @name TopNav.showCustomAttachment
  3277. * @function
  3278. */
  3279. me.showCustomAttachment = function()
  3280. {
  3281. $customAttachment.removeClass('hidden');
  3282. };
  3283. /**
  3284. * collapses the navigation bar, only if expanded
  3285. *
  3286. * @name TopNav.collapseBar
  3287. * @function
  3288. */
  3289. me.collapseBar = function()
  3290. {
  3291. if ($('#navbar').attr('aria-expanded') === 'true') {
  3292. $('.navbar-toggle').click();
  3293. }
  3294. };
  3295. /**
  3296. * returns the currently set expiration time
  3297. *
  3298. * @name TopNav.getExpiration
  3299. * @function
  3300. * @return {int}
  3301. */
  3302. me.getExpiration = function()
  3303. {
  3304. return pasteExpiration;
  3305. };
  3306. /**
  3307. * returns the currently selected file(s)
  3308. *
  3309. * @name TopNav.getFileList
  3310. * @function
  3311. * @return {FileList|null}
  3312. */
  3313. me.getFileList = function()
  3314. {
  3315. const $file = $('#file');
  3316. // if no file given, return null
  3317. if (!$file.length || !$file[0].files.length) {
  3318. return null;
  3319. }
  3320. // ensure the selected file is still accessible
  3321. if (!($file[0].files && $file[0].files[0])) {
  3322. return null;
  3323. }
  3324. return $file[0].files;
  3325. };
  3326. /**
  3327. * returns the state of the burn after reading checkbox
  3328. *
  3329. * @name TopNav.getExpiration
  3330. * @function
  3331. * @return {bool}
  3332. */
  3333. me.getBurnAfterReading = function()
  3334. {
  3335. return $burnAfterReading.is(':checked');
  3336. };
  3337. /**
  3338. * returns the state of the discussion checkbox
  3339. *
  3340. * @name TopNav.getOpenDiscussion
  3341. * @function
  3342. * @return {bool}
  3343. */
  3344. me.getOpenDiscussion = function()
  3345. {
  3346. return $openDiscussion.is(':checked');
  3347. };
  3348. /**
  3349. * returns the entered password
  3350. *
  3351. * @name TopNav.getPassword
  3352. * @function
  3353. * @return {string}
  3354. */
  3355. me.getPassword = function()
  3356. {
  3357. return $passwordInput.val();
  3358. };
  3359. /**
  3360. * returns the element where custom attachments can be placed
  3361. *
  3362. * Used by AttachmentViewer when an attachment is cloned here.
  3363. *
  3364. * @name TopNav.getCustomAttachment
  3365. * @function
  3366. * @return {jQuery}
  3367. */
  3368. me.getCustomAttachment = function()
  3369. {
  3370. return $customAttachment;
  3371. };
  3372. /**
  3373. * Set a function to call when the retry button is clicked.
  3374. *
  3375. * @name TopNav.setRetryCallback
  3376. * @function
  3377. * @param {function} callback
  3378. */
  3379. me.setRetryCallback = function(callback)
  3380. {
  3381. retryButtonCallback = callback;
  3382. }
  3383. /**
  3384. * init navigation manager
  3385. *
  3386. * preloads jQuery elements
  3387. *
  3388. * @name TopNav.init
  3389. * @function
  3390. */
  3391. me.init = function()
  3392. {
  3393. $attach = $('#attach');
  3394. $burnAfterReading = $('#burnafterreading');
  3395. $burnAfterReadingOption = $('#burnafterreadingoption');
  3396. $cloneButton = $('#clonebutton');
  3397. $customAttachment = $('#customattachment');
  3398. $expiration = $('#expiration');
  3399. $fileRemoveButton = $('#fileremovebutton');
  3400. $fileWrap = $('#filewrap');
  3401. $formatter = $('#formatter');
  3402. $newButton = $('#newbutton');
  3403. $openDiscussion = $('#opendiscussion');
  3404. $openDiscussionOption = $('#opendiscussionoption');
  3405. $password = $('#password');
  3406. $passwordInput = $('#passwordinput');
  3407. $rawTextButton = $('#rawtextbutton');
  3408. $retryButton = $('#retrybutton');
  3409. $sendButton = $('#sendbutton');
  3410. $qrCodeLink = $('#qrcodelink');
  3411. // bootstrap template drop down
  3412. $('#language ul.dropdown-menu li a').click(setLanguage);
  3413. // page template drop down
  3414. $('#language select option').click(setLanguage);
  3415. // bind events
  3416. $burnAfterReading.change(changeBurnAfterReading);
  3417. $openDiscussionOption.change(changeOpenDiscussion);
  3418. $newButton.click(clickNewPaste);
  3419. $sendButton.click(PasteEncrypter.sendPaste);
  3420. $cloneButton.click(Controller.clonePaste);
  3421. $rawTextButton.click(rawText);
  3422. $retryButton.click(clickRetryButton);
  3423. $fileRemoveButton.click(removeAttachment);
  3424. $qrCodeLink.click(displayQrCode);
  3425. // bootstrap template drop downs
  3426. $('ul.dropdown-menu li a', $('#expiration').parent()).click(updateExpiration);
  3427. $('ul.dropdown-menu li a', $('#formatter').parent()).click(updateFormat);
  3428. // initiate default state of checkboxes
  3429. changeBurnAfterReading();
  3430. changeOpenDiscussion();
  3431. // get default value from template or fall back to set value
  3432. pasteExpiration = Model.getExpirationDefault() || pasteExpiration;
  3433. createButtonsDisplayed = false;
  3434. viewButtonsDisplayed = false;
  3435. };
  3436. return me;
  3437. })(window, document);
  3438. /**
  3439. * Responsible for AJAX requests, transparently handles encryption…
  3440. *
  3441. * @name ServerInteraction
  3442. * @class
  3443. */
  3444. const ServerInteraction = (function () {
  3445. const me = {};
  3446. let successFunc = null,
  3447. failureFunc = null,
  3448. symmetricKey = null,
  3449. url,
  3450. data,
  3451. password;
  3452. /**
  3453. * public variable ('constant') for errors to prevent magic numbers
  3454. *
  3455. * @name ServerInteraction.error
  3456. * @readonly
  3457. * @enum {Object}
  3458. */
  3459. me.error = {
  3460. okay: 0,
  3461. custom: 1,
  3462. unknown: 2,
  3463. serverError: 3
  3464. };
  3465. /**
  3466. * ajaxHeaders to send in AJAX requests
  3467. *
  3468. * @name ServerInteraction.ajaxHeaders
  3469. * @private
  3470. * @readonly
  3471. * @enum {Object}
  3472. */
  3473. const ajaxHeaders = {'X-Requested-With': 'JSONHttpRequest'};
  3474. /**
  3475. * called after successful upload
  3476. *
  3477. * @name ServerInteraction.success
  3478. * @private
  3479. * @function
  3480. * @param {int} status
  3481. * @param {int} result - optional
  3482. */
  3483. function success(status, result)
  3484. {
  3485. if (successFunc !== null) {
  3486. // add useful data to result
  3487. result.encryptionKey = symmetricKey;
  3488. successFunc(status, result);
  3489. }
  3490. }
  3491. /**
  3492. * called after a upload failure
  3493. *
  3494. * @name ServerInteraction.fail
  3495. * @private
  3496. * @function
  3497. * @param {int} status - internal code
  3498. * @param {int} result - original error code
  3499. */
  3500. function fail(status, result)
  3501. {
  3502. if (failureFunc !== null) {
  3503. failureFunc(status, result);
  3504. }
  3505. }
  3506. /**
  3507. * actually uploads the data
  3508. *
  3509. * @name ServerInteraction.run
  3510. * @function
  3511. */
  3512. me.run = function()
  3513. {
  3514. let isPost = Object.keys(data).length > 0,
  3515. ajaxParams = {
  3516. type: isPost ? 'POST' : 'GET',
  3517. url: url,
  3518. headers: ajaxHeaders,
  3519. dataType: 'json',
  3520. success: function(result) {
  3521. if (result.status === 0) {
  3522. success(0, result);
  3523. } else if (result.status === 1) {
  3524. fail(1, result);
  3525. } else {
  3526. fail(2, result);
  3527. }
  3528. }
  3529. };
  3530. if (isPost) {
  3531. ajaxParams.data = JSON.stringify(data);
  3532. }
  3533. $.ajax(ajaxParams).fail(function(jqXHR, textStatus, errorThrown) {
  3534. console.error(textStatus, errorThrown);
  3535. fail(3, jqXHR);
  3536. });
  3537. };
  3538. /**
  3539. * return currently set data, used in unit testing
  3540. *
  3541. * @name ServerInteraction.getData
  3542. * @function
  3543. */
  3544. me.getData = function()
  3545. {
  3546. return data;
  3547. };
  3548. /**
  3549. * set success function
  3550. *
  3551. * @name ServerInteraction.setUrl
  3552. * @function
  3553. * @param {function} newUrl
  3554. */
  3555. me.setUrl = function(newUrl)
  3556. {
  3557. url = newUrl;
  3558. };
  3559. /**
  3560. * sets the password to use (first value) and optionally also the
  3561. * encryption key (not recommended, it is automatically generated).
  3562. *
  3563. * Note: Call this after prepare() as prepare() resets these values.
  3564. *
  3565. * @name ServerInteraction.setCryptValues
  3566. * @function
  3567. * @param {string} newPassword
  3568. * @param {string} newKey - optional
  3569. */
  3570. me.setCryptParameters = function(newPassword, newKey)
  3571. {
  3572. password = newPassword;
  3573. if (typeof newKey !== 'undefined') {
  3574. symmetricKey = newKey;
  3575. }
  3576. };
  3577. /**
  3578. * set success function
  3579. *
  3580. * @name ServerInteraction.setSuccess
  3581. * @function
  3582. * @param {function} func
  3583. */
  3584. me.setSuccess = function(func)
  3585. {
  3586. successFunc = func;
  3587. };
  3588. /**
  3589. * set failure function
  3590. *
  3591. * @name ServerInteraction.setFailure
  3592. * @function
  3593. * @param {function} func
  3594. */
  3595. me.setFailure = function(func)
  3596. {
  3597. failureFunc = func;
  3598. };
  3599. /**
  3600. * prepares a new upload
  3601. *
  3602. * Call this when doing a new upload to reset any data from potential
  3603. * previous uploads. Must be called before any other method of this
  3604. * module.
  3605. *
  3606. * @name ServerInteraction.prepare
  3607. * @function
  3608. * @return {object}
  3609. */
  3610. me.prepare = function()
  3611. {
  3612. // entropy should already be checked!
  3613. // reset password
  3614. password = '';
  3615. // reset key, so it a new one is generated when it is used
  3616. symmetricKey = null;
  3617. // reset data
  3618. successFunc = null;
  3619. failureFunc = null;
  3620. url = Helper.baseUri();
  3621. data = {};
  3622. };
  3623. /**
  3624. * encrypts and sets the data
  3625. *
  3626. * @name ServerInteraction.setCipherMessage
  3627. * @async
  3628. * @function
  3629. * @param {object} cipherMessage
  3630. */
  3631. me.setCipherMessage = async function(cipherMessage)
  3632. {
  3633. if (
  3634. symmetricKey === null ||
  3635. (typeof symmetricKey === 'string' && symmetricKey === '')
  3636. ) {
  3637. symmetricKey = CryptTool.getSymmetricKey();
  3638. }
  3639. if (!data.hasOwnProperty('adata')) {
  3640. data['adata'] = [];
  3641. }
  3642. let cipherResult = await CryptTool.cipher(symmetricKey, password, JSON.stringify(cipherMessage), data['adata']);
  3643. data['v'] = 2;
  3644. data['ct'] = cipherResult[0];
  3645. data['adata'] = cipherResult[1];
  3646. };
  3647. /**
  3648. * set the additional metadata to send unencrypted
  3649. *
  3650. * @name ServerInteraction.setUnencryptedData
  3651. * @function
  3652. * @param {string} index
  3653. * @param {mixed} element
  3654. */
  3655. me.setUnencryptedData = function(index, element)
  3656. {
  3657. data[index] = element;
  3658. };
  3659. /**
  3660. * Helper, which parses shows a general error message based on the result of the ServerInteraction
  3661. *
  3662. * @name ServerInteraction.parseUploadError
  3663. * @function
  3664. * @param {int} status
  3665. * @param {object} data
  3666. * @param {string} doThisThing - a human description of the action, which was tried
  3667. * @return {array}
  3668. */
  3669. me.parseUploadError = function(status, data, doThisThing) {
  3670. let errorArray;
  3671. switch (status) {
  3672. case me.error.custom:
  3673. errorArray = ['Could not ' + doThisThing + ': %s', data.message];
  3674. break;
  3675. case me.error.unknown:
  3676. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown status')];
  3677. break;
  3678. case me.error.serverError:
  3679. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('server error or not responding')];
  3680. break;
  3681. default:
  3682. errorArray = ['Could not ' + doThisThing + ': %s', I18n._('unknown error')];
  3683. break;
  3684. }
  3685. return errorArray;
  3686. };
  3687. return me;
  3688. })();
  3689. /**
  3690. * (controller) Responsible for encrypting paste and sending it to server.
  3691. *
  3692. * Does upload, encryption is done transparently by ServerInteraction.
  3693. *
  3694. * @name PasteEncrypter
  3695. * @class
  3696. */
  3697. const PasteEncrypter = (function () {
  3698. const me = {};
  3699. let requirementsChecked = false;
  3700. /**
  3701. * called after successful paste upload
  3702. *
  3703. * @name PasteEncrypter.showCreatedPaste
  3704. * @private
  3705. * @function
  3706. * @param {int} status
  3707. * @param {object} data
  3708. */
  3709. function showCreatedPaste(status, data) {
  3710. Alert.hideLoading();
  3711. Alert.hideMessages();
  3712. // show notification
  3713. const baseUri = Helper.baseUri() + '?',
  3714. url = baseUri + data.id + '#' + CryptTool.base58encode(data.encryptionKey),
  3715. deleteUrl = baseUri + 'pasteid=' + data.id + '&deletetoken=' + data.deletetoken;
  3716. PasteStatus.createPasteNotification(url, deleteUrl);
  3717. // show new URL in browser bar
  3718. history.pushState({type: 'newpaste'}, document.title, url);
  3719. TopNav.showViewButtons();
  3720. TopNav.hideRawButton();
  3721. Editor.hide();
  3722. // parse and show text
  3723. // (preparation already done in me.sendPaste())
  3724. PasteViewer.run();
  3725. }
  3726. /**
  3727. * called after successful comment upload
  3728. *
  3729. * @name PasteEncrypter.showUploadedComment
  3730. * @private
  3731. * @function
  3732. * @param {int} status
  3733. * @param {object} data
  3734. */
  3735. function showUploadedComment(status, data) {
  3736. // show success message
  3737. Alert.showStatus('Comment posted.');
  3738. // reload paste
  3739. Controller.refreshPaste(function () {
  3740. // highlight sent comment
  3741. DiscussionViewer.highlightComment(data.id, true);
  3742. // reset error handler
  3743. Alert.setCustomHandler(null);
  3744. });
  3745. }
  3746. /**
  3747. * send a reply in a discussion
  3748. *
  3749. * @name PasteEncrypter.sendComment
  3750. * @async
  3751. * @function
  3752. */
  3753. me.sendComment = async function()
  3754. {
  3755. Alert.hideMessages();
  3756. Alert.setCustomHandler(DiscussionViewer.handleNotification);
  3757. // UI loading state
  3758. TopNav.hideAllButtons();
  3759. Alert.showLoading('Sending comment…', 'cloud-upload');
  3760. // get data
  3761. const plainText = DiscussionViewer.getReplyMessage(),
  3762. nickname = DiscussionViewer.getReplyNickname(),
  3763. parentid = DiscussionViewer.getReplyCommentId();
  3764. // do not send if there is no data
  3765. if (plainText.length === 0) {
  3766. // revert loading status…
  3767. Alert.hideLoading();
  3768. Alert.setCustomHandler(null);
  3769. TopNav.showViewButtons();
  3770. return;
  3771. }
  3772. // prepare server interaction
  3773. ServerInteraction.prepare();
  3774. ServerInteraction.setCryptParameters(Prompt.getPassword(), Model.getPasteKey());
  3775. // set success/fail functions
  3776. ServerInteraction.setSuccess(showUploadedComment);
  3777. ServerInteraction.setFailure(function (status, data) {
  3778. // revert loading status…
  3779. Alert.hideLoading();
  3780. TopNav.showViewButtons();
  3781. // …show error message…
  3782. Alert.showError(
  3783. ServerInteraction.parseUploadError(status, data, 'post comment')
  3784. );
  3785. // …and reset error handler
  3786. Alert.setCustomHandler(null);
  3787. });
  3788. // fill it with unencrypted params
  3789. ServerInteraction.setUnencryptedData('pasteid', Model.getPasteId());
  3790. if (typeof parentid === 'undefined') {
  3791. // if parent id is not set, this is the top-most comment, so use
  3792. // paste id as parent, as the root element of the discussion tree
  3793. ServerInteraction.setUnencryptedData('parentid', Model.getPasteId());
  3794. } else {
  3795. ServerInteraction.setUnencryptedData('parentid', parentid);
  3796. }
  3797. // prepare cypher message
  3798. let cipherMessage = {
  3799. 'comment': plainText
  3800. };
  3801. if (nickname.length > 0) {
  3802. cipherMessage['nickname'] = nickname;
  3803. }
  3804. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3805. ServerInteraction.run();
  3806. };
  3807. /**
  3808. * sends a new paste to server
  3809. *
  3810. * @name PasteEncrypter.sendPaste
  3811. * @async
  3812. * @function
  3813. */
  3814. me.sendPaste = async function()
  3815. {
  3816. // hide previous (error) messages
  3817. Controller.hideStatusMessages();
  3818. // UI loading state
  3819. TopNav.hideAllButtons();
  3820. Alert.showLoading('Sending paste…', 'cloud-upload');
  3821. TopNav.collapseBar();
  3822. // get data
  3823. const plainText = Editor.getText(),
  3824. format = PasteViewer.getFormat(),
  3825. // the methods may return different values if no files are attached (null, undefined or false)
  3826. files = TopNav.getFileList() || AttachmentViewer.getFile() || AttachmentViewer.hasAttachment();
  3827. // do not send if there is no data
  3828. if (plainText.length === 0 && !files) {
  3829. // revert loading status…
  3830. Alert.hideLoading();
  3831. TopNav.showCreateButtons();
  3832. return;
  3833. }
  3834. // prepare server interaction
  3835. ServerInteraction.prepare();
  3836. ServerInteraction.setCryptParameters(TopNav.getPassword());
  3837. // set success/fail functions
  3838. ServerInteraction.setSuccess(showCreatedPaste);
  3839. ServerInteraction.setFailure(function (status, data) {
  3840. // revert loading status…
  3841. Alert.hideLoading();
  3842. TopNav.showCreateButtons();
  3843. // show error message
  3844. Alert.showError(
  3845. ServerInteraction.parseUploadError(status, data, 'create paste')
  3846. );
  3847. });
  3848. // fill it with unencrypted submitted options
  3849. ServerInteraction.setUnencryptedData('adata', [
  3850. null, format,
  3851. TopNav.getOpenDiscussion() ? 1 : 0,
  3852. TopNav.getBurnAfterReading() ? 1 : 0
  3853. ]);
  3854. ServerInteraction.setUnencryptedData('meta', {'expire': TopNav.getExpiration()});
  3855. // prepare PasteViewer for later preview
  3856. PasteViewer.setText(plainText);
  3857. PasteViewer.setFormat(format);
  3858. // prepare cypher message
  3859. let file = AttachmentViewer.getAttachmentData(),
  3860. cipherMessage = {
  3861. 'paste': plainText
  3862. };
  3863. if (typeof file !== 'undefined' && file !== null) {
  3864. cipherMessage['attachment'] = file;
  3865. cipherMessage['attachment_name'] = AttachmentViewer.getFile().name;
  3866. } else if (AttachmentViewer.hasAttachment()) {
  3867. // fall back to cloned part
  3868. let attachment = AttachmentViewer.getAttachment();
  3869. cipherMessage['attachment'] = attachment[0];
  3870. cipherMessage['attachment_name'] = attachment[1];
  3871. }
  3872. // encrypt message
  3873. await ServerInteraction.setCipherMessage(cipherMessage).catch(Alert.showError);
  3874. // send data
  3875. ServerInteraction.run();
  3876. };
  3877. return me;
  3878. })();
  3879. /**
  3880. * (controller) Responsible for decrypting cipherdata and passing data to view.
  3881. *
  3882. * Only decryption, no download.
  3883. *
  3884. * @name PasteDecrypter
  3885. * @class
  3886. */
  3887. const PasteDecrypter = (function () {
  3888. const me = {};
  3889. /**
  3890. * decrypt data or prompts for password in case of failure
  3891. *
  3892. * @name PasteDecrypter.decryptOrPromptPassword
  3893. * @private
  3894. * @async
  3895. * @function
  3896. * @param {string} key
  3897. * @param {string} password - optional, may be an empty string
  3898. * @param {string} cipherdata
  3899. * @throws {string}
  3900. * @return {false|string} false, when unsuccessful or string (decrypted data)
  3901. */
  3902. async function decryptOrPromptPassword(key, password, cipherdata)
  3903. {
  3904. // try decryption without password
  3905. const plaindata = await CryptTool.decipher(key, password, cipherdata);
  3906. // if it fails, request password
  3907. if (plaindata.length === 0 && password.length === 0) {
  3908. // show prompt
  3909. Prompt.requestPassword();
  3910. // Thus, we cannot do anything yet, we need to wait for the user
  3911. // input.
  3912. return false;
  3913. }
  3914. // if all tries failed, we can only return an error
  3915. if (plaindata.length === 0) {
  3916. throw 'failed to decipher data';
  3917. }
  3918. return plaindata;
  3919. }
  3920. /**
  3921. * decrypt the actual paste text
  3922. *
  3923. * @name PasteDecrypter.decryptPaste
  3924. * @private
  3925. * @async
  3926. * @function
  3927. * @param {Paste} paste - paste data in object form
  3928. * @param {string} key
  3929. * @param {string} password
  3930. * @throws {string}
  3931. * @return {Promise}
  3932. */
  3933. async function decryptPaste(paste, key, password)
  3934. {
  3935. let pastePlain = await decryptOrPromptPassword(
  3936. key, password,
  3937. paste.getCipherData()
  3938. );
  3939. if (pastePlain === false) {
  3940. if (password.length === 0) {
  3941. throw 'waiting on user to provide a password';
  3942. } else {
  3943. displayDecryptionError('failed to decipher paste text: Incorrect password?');
  3944. throw 'waiting on user to provide correct password';
  3945. }
  3946. }
  3947. let format = '',
  3948. text = '';
  3949. if (paste.v > 1) {
  3950. // version 2 paste
  3951. const pasteMessage = JSON.parse(pastePlain);
  3952. if (pasteMessage.hasOwnProperty('attachment') && pasteMessage.hasOwnProperty('attachment_name')) {
  3953. AttachmentViewer.setAttachment(pasteMessage.attachment, pasteMessage.attachment_name);
  3954. AttachmentViewer.showAttachment();
  3955. }
  3956. pastePlain = pasteMessage.paste;
  3957. } else {
  3958. // version 1 paste
  3959. if (paste.hasOwnProperty('attachment') && paste.hasOwnProperty('attachmentname')) {
  3960. Promise.all([
  3961. CryptTool.decipher(key, password, paste.attachment),
  3962. CryptTool.decipher(key, password, paste.attachmentname)
  3963. ]).then((attachment) => {
  3964. AttachmentViewer.setAttachment(attachment[0], attachment[1]);
  3965. AttachmentViewer.showAttachment();
  3966. });
  3967. }
  3968. }
  3969. PasteViewer.setFormat(paste.getFormat());
  3970. PasteViewer.setText(pastePlain);
  3971. PasteViewer.run();
  3972. }
  3973. /**
  3974. * decrypts all comments and shows them
  3975. *
  3976. * @name PasteDecrypter.decryptComments
  3977. * @private
  3978. * @async
  3979. * @function
  3980. * @param {Paste} paste - paste data in object form
  3981. * @param {string} key
  3982. * @param {string} password
  3983. * @return {Promise}
  3984. */
  3985. async function decryptComments(paste, key, password)
  3986. {
  3987. // remove potential previous discussion
  3988. DiscussionViewer.prepareNewDiscussion();
  3989. const commentDecryptionPromises = [];
  3990. // iterate over comments
  3991. for (let i = 0; i < paste.comments.length; ++i) {
  3992. const comment = new Comment(paste.comments[i]),
  3993. commentPromise = CryptTool.decipher(key, password, comment.getCipherData());
  3994. paste.comments[i] = comment;
  3995. if (comment.v > 1) {
  3996. // version 2 comment
  3997. commentDecryptionPromises.push(
  3998. commentPromise.then(function (commentJson) {
  3999. const commentMessage = JSON.parse(commentJson);
  4000. return [
  4001. commentMessage.comment || '',
  4002. commentMessage.nickname || ''
  4003. ];
  4004. })
  4005. );
  4006. } else {
  4007. // version 1 comment
  4008. commentDecryptionPromises.push(
  4009. Promise.all([
  4010. commentPromise,
  4011. paste.comments[i].meta.hasOwnProperty('nickname') ?
  4012. CryptTool.decipher(key, password, paste.comments[i].meta.nickname) :
  4013. Promise.resolve('')
  4014. ])
  4015. );
  4016. }
  4017. }
  4018. return Promise.all(commentDecryptionPromises).then(function (plaintexts) {
  4019. for (let i = 0; i < paste.comments.length; ++i) {
  4020. if (plaintexts[i][0].length === 0) {
  4021. continue;
  4022. }
  4023. DiscussionViewer.addComment(
  4024. paste.comments[i],
  4025. plaintexts[i][0],
  4026. plaintexts[i][1]
  4027. );
  4028. }
  4029. DiscussionViewer.finishDiscussion();
  4030. });
  4031. }
  4032. /**
  4033. * displays and logs decryption errors
  4034. *
  4035. * @name PasteDecrypter.displayDecryptionError
  4036. * @private
  4037. * @function
  4038. * @param {string} message
  4039. */
  4040. function displayDecryptionError(message)
  4041. {
  4042. Alert.hideLoading();
  4043. // log detailed error, but display generic translation
  4044. console.error(message);
  4045. Alert.showError('Could not decrypt data. Did you enter a wrong password? Retry with the button at the top.');
  4046. // reset password, so it can be re-entered
  4047. Prompt.reset();
  4048. TopNav.showRetryButton();
  4049. }
  4050. /**
  4051. * show decrypted text in the display area, including discussion (if open)
  4052. *
  4053. * @name PasteDecrypter.run
  4054. * @function
  4055. * @param {Paste} [paste] - (optional) object including comments to display (items = array with keys ('data','meta'))
  4056. */
  4057. me.run = function(paste)
  4058. {
  4059. Alert.hideMessages();
  4060. Alert.showLoading('Decrypting paste…', 'cloud-download');
  4061. if (typeof paste === 'undefined') {
  4062. // get cipher data and wait until it is available
  4063. Model.getPasteData(me.run);
  4064. return;
  4065. }
  4066. let key = Model.getPasteKey(),
  4067. password = Prompt.getPassword(),
  4068. decryptionPromises = [];
  4069. TopNav.setRetryCallback(function () {
  4070. TopNav.hideRetryButton();
  4071. me.run(paste);
  4072. });
  4073. // decrypt paste & attachments
  4074. decryptionPromises.push(decryptPaste(paste, key, password));
  4075. // if the discussion is opened on this paste, display it
  4076. if (paste.isDiscussionEnabled()) {
  4077. decryptionPromises.push(decryptComments(paste, key, password));
  4078. }
  4079. // shows the remaining time (until) deletion
  4080. PasteStatus.showRemainingTime(paste);
  4081. Promise.all(decryptionPromises)
  4082. .then(() => {
  4083. Alert.hideLoading();
  4084. TopNav.showViewButtons();
  4085. })
  4086. .catch((err) => {
  4087. // wait for the user to type in the password,
  4088. // then PasteDecrypter.run will be called again
  4089. console.error(err);
  4090. });
  4091. };
  4092. return me;
  4093. })();
  4094. /**
  4095. * initial (security) check
  4096. *
  4097. * @name InitialCheck
  4098. * @param {object} window
  4099. * @param {object} document
  4100. * @class
  4101. */
  4102. var InitialCheck = (function () {
  4103. var me = {};
  4104. /**
  4105. * blacklist of UserAgents (parts) known to belong to a bot
  4106. *
  4107. * @private
  4108. * @enum {Array}
  4109. * @readonly
  4110. */
  4111. const badBotUA = [
  4112. 'Bot',
  4113. 'bot'
  4114. ];
  4115. /**
  4116. * check if the connection is insecure
  4117. *
  4118. * @private
  4119. * @name InitialCheck.isInsecureConnection
  4120. * @function
  4121. * @return {bool}
  4122. */
  4123. function isInsecureConnection()
  4124. {
  4125. // use .isSecureContext if available
  4126. if (window.isSecureContext === true || window.isSecureContext === false) {
  4127. return !window.isSecureContext;
  4128. }
  4129. const url = new URL(window.location);
  4130. // HTTP is obviously insecure
  4131. if (url.protocol !== 'http:') {
  4132. return false;
  4133. }
  4134. // filter out actually secure connections over HTTP
  4135. for (const tld of ['.onion', '.i2p']) {
  4136. if (url.hostname.endsWith(tld)) {
  4137. return false;
  4138. }
  4139. }
  4140. // whitelist localhost for development
  4141. for (const hostname of ['localhost', '127.0.0.1', '[::1]']) {
  4142. if (url.hostname === hostname) {
  4143. return false;
  4144. }
  4145. }
  4146. // totally INSECURE http protocol!
  4147. return true;
  4148. }
  4149. /**
  4150. * checks whether this is a bot we dislike
  4151. *
  4152. * @private
  4153. * @name InitialCheck.isBadBot
  4154. * @function
  4155. * @return {bool}
  4156. */
  4157. function isBadBot() {
  4158. // check whether a bot user agent part can be found in the current
  4159. // user agent
  4160. for (const UAfragment of badBotUA) {
  4161. if (navigator.userAgent.indexOf(UAfragment) >= 0) {
  4162. return true;
  4163. }
  4164. }
  4165. return false;
  4166. }
  4167. /**
  4168. * checks whether this is an unsupported browser, via feature detection
  4169. *
  4170. * @private
  4171. * @name InitialCheck.isOldBrowser
  4172. * @function
  4173. * @return {bool}
  4174. */
  4175. function isOldBrowser() {
  4176. // webcrypto support
  4177. if (typeof window.crypto !== 'object') {
  4178. return true;
  4179. }
  4180. if (typeof WebAssembly !== 'object' && typeof WebAssembly.instantiate !== 'function') {
  4181. return true;
  4182. }
  4183. try {
  4184. // [\0, 'a', 's', 'm', (uint_32) 1] - smallest valid wasm module
  4185. const module = new WebAssembly.Module(Uint8Array.of(0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00));
  4186. if (
  4187. !(
  4188. module instanceof WebAssembly.Module &&
  4189. new WebAssembly.Instance(module) instanceof WebAssembly.Instance
  4190. )
  4191. ) {
  4192. return true;
  4193. }
  4194. } catch (e) {
  4195. return true;
  4196. }
  4197. // not checking for async/await, ES6, Promise or Uint8Array support,
  4198. // as most browsers introduced these earlier then webassembly and webcrypto:
  4199. // https://github.com/PrivateBin/PrivateBin/pull/431#issuecomment-493129359
  4200. return false;
  4201. }
  4202. /**
  4203. * init on application start, returns an all-clear signal
  4204. *
  4205. * @name InitialCheck.init
  4206. * @function
  4207. * @return {bool}
  4208. */
  4209. me.init = function()
  4210. {
  4211. // prevent bots from viewing a paste and potentially deleting data
  4212. // when burn-after-reading is set
  4213. if (isBadBot()) {
  4214. Alert.showError('I love you too, bot…');
  4215. return false;
  4216. }
  4217. if (isOldBrowser()) {
  4218. // some browsers (Chrome based ones) would have webcrypto support if using HTTPS
  4219. if (isInsecureConnection()) {
  4220. 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)]);
  4221. }
  4222. $('#oldnotice').removeClass('hidden');
  4223. return false;
  4224. }
  4225. if (isInsecureConnection()) {
  4226. $('#httpnotice').removeClass('hidden');
  4227. }
  4228. return true;
  4229. }
  4230. return me;
  4231. })();
  4232. /**
  4233. * (controller) main PrivateBin logic
  4234. *
  4235. * @name Controller
  4236. * @param {object} window
  4237. * @param {object} document
  4238. * @class
  4239. */
  4240. const Controller = (function (window, document) {
  4241. const me = {};
  4242. /**
  4243. * hides all status messages no matter which module showed them
  4244. *
  4245. * @name Controller.hideStatusMessages
  4246. * @function
  4247. */
  4248. me.hideStatusMessages = function()
  4249. {
  4250. PasteStatus.hideMessages();
  4251. Alert.hideMessages();
  4252. };
  4253. /**
  4254. * creates a new paste
  4255. *
  4256. * @name Controller.newPaste
  4257. * @function
  4258. */
  4259. me.newPaste = function()
  4260. {
  4261. // Important: This *must not* run Alert.hideMessages() as previous
  4262. // errors from viewing a paste should be shown.
  4263. TopNav.hideAllButtons();
  4264. Alert.showLoading('Preparing new paste…', 'time');
  4265. PasteStatus.hideMessages();
  4266. PasteViewer.hide();
  4267. Editor.resetInput();
  4268. Editor.show();
  4269. Editor.focusInput();
  4270. AttachmentViewer.removeAttachment();
  4271. TopNav.showCreateButtons();
  4272. Alert.hideLoading();
  4273. history.pushState({type: 'create'}, document.title, Helper.baseUri());
  4274. // clear discussion
  4275. DiscussionViewer.prepareNewDiscussion();
  4276. };
  4277. /**
  4278. * shows the loaded paste
  4279. *
  4280. * @name Controller.showPaste
  4281. * @function
  4282. */
  4283. me.showPaste = function()
  4284. {
  4285. try {
  4286. Model.getPasteKey();
  4287. } catch (err) {
  4288. console.error(err);
  4289. // missing decryption key (or paste ID) in URL?
  4290. if (window.location.hash.length === 0) {
  4291. 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?)');
  4292. return;
  4293. }
  4294. }
  4295. // show proper elements on screen
  4296. PasteDecrypter.run();
  4297. };
  4298. /**
  4299. * refreshes the loaded paste to show potential new data
  4300. *
  4301. * @name Controller.refreshPaste
  4302. * @function
  4303. * @param {function} callback
  4304. */
  4305. me.refreshPaste = function(callback)
  4306. {
  4307. // save window position to restore it later
  4308. const orgPosition = $(window).scrollTop();
  4309. Model.getPasteData(function (data) {
  4310. ServerInteraction.prepare();
  4311. ServerInteraction.setUrl(Helper.baseUri() + '?pasteid=' + Model.getPasteId());
  4312. ServerInteraction.setFailure(function (status, data) {
  4313. // revert loading status…
  4314. Alert.hideLoading();
  4315. TopNav.showViewButtons();
  4316. // show error message
  4317. Alert.showError(
  4318. ServerInteraction.parseUploadError(status, data, 'refresh display')
  4319. );
  4320. });
  4321. ServerInteraction.setSuccess(function (status, data) {
  4322. PasteDecrypter.run(new Paste(data));
  4323. // restore position
  4324. window.scrollTo(0, orgPosition);
  4325. // NOTE: could create problems as callback may be called
  4326. // asyncronously if PasteDecrypter e.g. needs to wait for a
  4327. // password being entered
  4328. callback();
  4329. });
  4330. ServerInteraction.run();
  4331. }, false); // this false is important as it circumvents the cache
  4332. }
  4333. /**
  4334. * clone the current paste
  4335. *
  4336. * @name Controller.clonePaste
  4337. * @function
  4338. */
  4339. me.clonePaste = function()
  4340. {
  4341. TopNav.collapseBar();
  4342. TopNav.hideAllButtons();
  4343. // hide messages from previous paste
  4344. me.hideStatusMessages();
  4345. // erase the id and the key in url
  4346. history.pushState({type: 'clone'}, document.title, Helper.baseUri());
  4347. if (AttachmentViewer.hasAttachment()) {
  4348. AttachmentViewer.moveAttachmentTo(
  4349. TopNav.getCustomAttachment(),
  4350. 'Cloned: \'%s\''
  4351. );
  4352. TopNav.hideFileSelector();
  4353. AttachmentViewer.hideAttachment();
  4354. // NOTE: it also looks nice without removing the attachment
  4355. // but for a consistent display we remove it…
  4356. AttachmentViewer.hideAttachmentPreview();
  4357. TopNav.showCustomAttachment();
  4358. // show another status message to make the user aware that the
  4359. // file was cloned too!
  4360. Alert.showStatus(
  4361. [
  4362. 'The cloned file \'%s\' was attached to this paste.',
  4363. AttachmentViewer.getAttachment()[1]
  4364. ],
  4365. 'copy'
  4366. );
  4367. }
  4368. Editor.setText(PasteViewer.getText());
  4369. PasteViewer.hide();
  4370. Editor.show();
  4371. TopNav.showCreateButtons();
  4372. // clear discussion
  4373. DiscussionViewer.prepareNewDiscussion();
  4374. };
  4375. /**
  4376. * application start
  4377. *
  4378. * @name Controller.init
  4379. * @function
  4380. */
  4381. me.init = async function()
  4382. {
  4383. // first load translations
  4384. I18n.loadTranslations();
  4385. DOMPurify.setConfig({SAFE_FOR_JQUERY: true});
  4386. // initialize other modules/"classes"
  4387. Alert.init();
  4388. Model.init();
  4389. AttachmentViewer.init();
  4390. DiscussionViewer.init();
  4391. Editor.init();
  4392. PasteStatus.init();
  4393. PasteViewer.init();
  4394. Prompt.init();
  4395. TopNav.init();
  4396. UiHelper.init();
  4397. z = (await zlib);
  4398. if (!InitialCheck.init()) {
  4399. // something major is wrong, stop right away
  4400. return;
  4401. }
  4402. // check whether existing paste needs to be shown
  4403. try {
  4404. Model.getPasteId();
  4405. } catch (e) {
  4406. // otherwise create a new paste
  4407. return me.newPaste();
  4408. }
  4409. // if delete token is passed (i.e. paste has been deleted by this
  4410. // access), there is nothing more to do
  4411. if (Model.hasDeleteToken()) {
  4412. return;
  4413. }
  4414. // display an existing paste
  4415. return me.showPaste();
  4416. }
  4417. return me;
  4418. })(window, document);
  4419. return {
  4420. Helper: Helper,
  4421. I18n: I18n,
  4422. CryptTool: CryptTool,
  4423. Model: Model,
  4424. UiHelper: UiHelper,
  4425. Alert: Alert,
  4426. PasteStatus: PasteStatus,
  4427. Prompt: Prompt,
  4428. Editor: Editor,
  4429. PasteViewer: PasteViewer,
  4430. AttachmentViewer: AttachmentViewer,
  4431. DiscussionViewer: DiscussionViewer,
  4432. TopNav: TopNav,
  4433. ServerInteraction: ServerInteraction,
  4434. PasteEncrypter: PasteEncrypter,
  4435. PasteDecrypter: PasteDecrypter,
  4436. InitialCheck: InitialCheck,
  4437. Controller: Controller
  4438. };
  4439. })(jQuery, RawDeflate);