functions.go 8.0 KB

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