privatebin.js 159 KB

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