privatebin.js 153 KB

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