functions.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package template // import "miniflux.app/v2/internal/template"
  4. import (
  5. "errors"
  6. "fmt"
  7. "html/template"
  8. "math"
  9. "net/mail"
  10. "net/url"
  11. "slices"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "miniflux.app/v2/internal/config"
  16. "miniflux.app/v2/internal/locale"
  17. "miniflux.app/v2/internal/mediaproxy"
  18. "miniflux.app/v2/internal/model"
  19. "miniflux.app/v2/internal/reader/sanitizer"
  20. "miniflux.app/v2/internal/timezone"
  21. "miniflux.app/v2/internal/ui/static"
  22. "miniflux.app/v2/internal/urllib"
  23. )
  24. type funcMap struct {
  25. basePath string
  26. iconPaths map[string]string
  27. }
  28. // Map returns a map of template functions that are compiled during template parsing.
  29. func (f *funcMap) Map() template.FuncMap {
  30. // Pre-compute every icon URL once, as iconPath is called a lot during pages rendering.
  31. f.iconPaths = make(map[string]string, len(static.BinaryBundles))
  32. for filename, bundle := range static.BinaryBundles {
  33. f.iconPaths[filename] = f.basePath + "/icon/" + bundle.Checksum + "/" + filename
  34. }
  35. return template.FuncMap{
  36. "contains": strings.Contains,
  37. "startsWith": strings.HasPrefix,
  38. "formatFileSize": formatFileSize,
  39. "dict": dict,
  40. "truncate": truncate,
  41. "isEmail": isEmail,
  42. "baseURL": config.Opts.BaseURL,
  43. "apiEnabled": config.Opts.HasAPI,
  44. "rootURL": config.Opts.RootURL,
  45. "disableLocalAuth": config.Opts.DisableLocalAuth,
  46. "webAuthnEnabled": config.Opts.WebAuthn,
  47. "oidcProviderName": config.Opts.OAuth2OIDCProviderName,
  48. "hasOAuth2Provider": func(provider string) bool {
  49. return config.Opts.OAuth2Provider() == provider
  50. },
  51. "hasAuthProxy": func() bool {
  52. return config.Opts.AuthProxyHeader() != ""
  53. },
  54. "routePath": func(format string, args ...any) string {
  55. if len(args) > 0 {
  56. return f.basePath + fmt.Sprintf(format, args...)
  57. }
  58. return f.basePath + format
  59. },
  60. "untrustedURL": untrustedURL,
  61. "safeCSS": func(str string) template.CSS {
  62. return template.CSS(str)
  63. },
  64. "safeJS": func(str string) template.JS {
  65. return template.JS(str)
  66. },
  67. "safeHTML": func(str string) template.HTML {
  68. return template.HTML(str)
  69. },
  70. "proxyFilter": mediaproxy.RewriteDocumentWithRelativeProxyURL,
  71. "proxyURL": func(link string) string {
  72. mediaProxyMode := config.Opts.MediaProxyMode()
  73. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  74. return mediaproxy.ProxifyRelativeURL(link)
  75. }
  76. return link
  77. },
  78. "mustBeProxyfied": func(mediaType string) bool {
  79. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  80. },
  81. "domain": urllib.Domain,
  82. "replace": func(str, old, new string) string {
  83. return strings.Replace(str, old, new, 1)
  84. },
  85. "isodate": func(ts time.Time) string {
  86. return ts.Format("2006-01-02 15:04:05")
  87. },
  88. "theme_color": model.ThemeColor,
  89. "iconPath": f.iconPath,
  90. "icon": f.iconFunc(),
  91. "deRef": func(i *int) int { return *i },
  92. "duration": duration,
  93. "urlEncode": url.PathEscape,
  94. "subtract": func(a, b int) int {
  95. return a - b
  96. },
  97. "queryString": func(params map[string]any) string {
  98. if len(params) == 0 {
  99. return ""
  100. }
  101. values := url.Values{}
  102. for key, value := range params {
  103. switch v := value.(type) {
  104. case string:
  105. if v != "" {
  106. values.Set(key, v)
  107. }
  108. case int:
  109. if v != 0 {
  110. values.Set(key, strconv.Itoa(v))
  111. }
  112. case int64:
  113. if v != 0 {
  114. values.Set(key, strconv.FormatInt(v, 10))
  115. }
  116. case bool:
  117. if v {
  118. values.Set(key, "1")
  119. }
  120. default:
  121. if value != nil {
  122. str := fmt.Sprint(value)
  123. if str != "" {
  124. values.Set(key, str)
  125. }
  126. }
  127. }
  128. }
  129. encoded := values.Encode()
  130. if encoded == "" {
  131. return ""
  132. }
  133. return "?" + encoded
  134. },
  135. // These functions are overridden at runtime after parsing.
  136. "elapsed": func(timezone string, t time.Time) string {
  137. return ""
  138. },
  139. "t": func(key any, args ...any) string {
  140. return ""
  141. },
  142. "plural": func(key string, n int, args ...any) string {
  143. return ""
  144. },
  145. }
  146. }
  147. func (f *funcMap) iconPath(filename string) string {
  148. return f.iconPaths[filename]
  149. }
  150. func (f *funcMap) iconFunc() func(string) template.HTML {
  151. // Concatenation is used instead of fmt.Sprintf,
  152. // as it's much faster, and this function is called
  153. // a bunch of times per feed item on the main page.
  154. prefix := `<svg class="icon" aria-hidden="true"><use href="` + f.iconPath("sprite.svg") + `#icon-`
  155. const suffix = `"/></svg>`
  156. return func(iconName string) template.HTML {
  157. return template.HTML(prefix + iconName + suffix)
  158. }
  159. }
  160. func CSPPolicy(user *model.User, nonce string) string {
  161. policies := map[string]string{
  162. "default-src": "'none'",
  163. "frame-src": "*",
  164. "img-src": "* data:",
  165. "manifest-src": "'self'",
  166. "media-src": "*",
  167. "require-trusted-types-for": "'script'",
  168. "script-src": "'nonce-" + nonce + "' 'strict-dynamic'",
  169. "style-src": "'nonce-" + nonce + "'",
  170. "trusted-types": "html url",
  171. "connect-src": "'self'",
  172. }
  173. if user != nil {
  174. if user.ExternalFontHosts != "" {
  175. policies["font-src"] = user.ExternalFontHosts
  176. if user.Stylesheet != "" {
  177. policies["style-src"] += " " + user.ExternalFontHosts
  178. }
  179. }
  180. }
  181. var policy strings.Builder
  182. policy.Grow(350)
  183. for key, value := range policies {
  184. policy.WriteString(key)
  185. policy.WriteString(" ")
  186. policy.WriteString(value)
  187. policy.WriteString("; ")
  188. }
  189. return policy.String()
  190. }
  191. func dict(values ...any) (map[string]any, error) {
  192. if len(values)%2 != 0 {
  193. return nil, errors.New("dict expects an even number of arguments")
  194. }
  195. dict := make(map[string]any, len(values)/2)
  196. for i := 0; i < len(values); i += 2 {
  197. key, ok := values[i].(string)
  198. if !ok {
  199. return nil, errors.New("dict keys must be strings")
  200. }
  201. dict[key] = values[i+1]
  202. }
  203. return dict, nil
  204. }
  205. func truncate(str string, max int) string {
  206. if max <= 0 {
  207. panic("truncate: max must be greater than zero")
  208. }
  209. // Template callers pass feed titles from remote content. Scanning and
  210. // allocating the entire untrusted input just to truncate it could create a
  211. // denial-of-service risk, so stop as soon as we reach the requested limit.
  212. runeCount := 0
  213. for i := range str {
  214. if runeCount == max {
  215. return str[:i] + "…"
  216. }
  217. runeCount++
  218. }
  219. return str
  220. }
  221. func isEmail(str string) bool {
  222. _, err := mail.ParseAddress(str)
  223. return err == nil
  224. }
  225. // untrustedURL validates a feed-supplied URL against the sanitizer's scheme
  226. // allowlist before exposing it to html/template. Returns "#" for unsafe URLs
  227. // (e.g. javascript:, data:) so anchors render as inert links.
  228. //
  229. // Go's built-in html/template URL filter only allows http(s), mailto, and
  230. // relative URLs — too narrow for feeds which legitimately use schemes like
  231. // magnet:, feed:, webcal:, and tel:.
  232. func untrustedURL(rawURL string) template.URL {
  233. if !sanitizer.HasValidURIScheme(rawURL) {
  234. return template.URL("#")
  235. }
  236. return template.URL(rawURL)
  237. }
  238. // Returns the duration in human readable format (hours and minutes).
  239. func duration(t time.Time) string {
  240. return durationImpl(t, time.Now())
  241. }
  242. // Accepts now argument for easy testing
  243. func durationImpl(t time.Time, now time.Time) string {
  244. if t.IsZero() {
  245. return ""
  246. }
  247. if diff := t.Sub(now); diff >= 0 {
  248. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  249. return diff.Round(time.Second).String()
  250. }
  251. return ""
  252. }
  253. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  254. if t.IsZero() {
  255. return printer.Print("time_elapsed.not_yet")
  256. }
  257. now := timezone.Now(tz)
  258. t = timezone.Convert(tz, t)
  259. if now.Before(t) {
  260. return printer.Print("time_elapsed.not_yet")
  261. }
  262. diff := now.Sub(t)
  263. // Duration in seconds
  264. s := diff.Seconds()
  265. // Duration in days
  266. d := int(s / 86400)
  267. switch {
  268. case s < 60:
  269. return printer.Print("time_elapsed.now")
  270. case s < 3600:
  271. minutes := int(diff.Minutes())
  272. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  273. case s < 86400:
  274. hours := int(diff.Hours())
  275. return printer.Plural("time_elapsed.hours", hours, hours)
  276. case d == 1:
  277. return printer.Print("time_elapsed.yesterday")
  278. case d < 21:
  279. return printer.Plural("time_elapsed.days", d, d)
  280. case d < 31:
  281. weeks := int(math.Round(float64(d) / 7))
  282. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  283. case d < 365:
  284. months := int(math.Round(float64(d) / 30))
  285. return printer.Plural("time_elapsed.months", months, months)
  286. default:
  287. years := int(math.Round(float64(d) / 365))
  288. return printer.Plural("time_elapsed.years", years, years)
  289. }
  290. }
  291. func formatFileSize(b int64) string {
  292. const unit = 1024
  293. if b < unit {
  294. return fmt.Sprintf("%d B", b)
  295. }
  296. base := math.Log(float64(b)) / math.Log(unit)
  297. number := math.Pow(unit, base-math.Floor(base))
  298. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  299. }