privatebin.js 154 KB

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