privatebin.js 158 KB

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