privatebin.js 157 KB

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