functions.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  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. "strings"
  13. "time"
  14. "miniflux.app/v2/internal/config"
  15. "miniflux.app/v2/internal/crypto"
  16. "miniflux.app/v2/internal/http/route"
  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/urllib"
  22. "github.com/gorilla/mux"
  23. )
  24. type funcMap struct {
  25. router *mux.Router
  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. "route": func(name string, args ...any) string {
  49. return route.Path(f.router, name, args...)
  50. },
  51. "safeURL": func(url string) template.URL {
  52. return template.URL(url)
  53. },
  54. "safeCSS": func(str string) template.CSS {
  55. return template.CSS(str)
  56. },
  57. "safeJS": func(str string) template.JS {
  58. return template.JS(str)
  59. },
  60. "safeHTML": func(str string) template.HTML {
  61. return template.HTML(str)
  62. },
  63. "proxyFilter": func(data string) string {
  64. return mediaproxy.RewriteDocumentWithRelativeProxyURL(f.router, data)
  65. },
  66. "proxyURL": func(link string) string {
  67. mediaProxyMode := config.Opts.MediaProxyMode()
  68. if mediaProxyMode == "all" || (mediaProxyMode != "none" && !urllib.IsHTTPS(link)) {
  69. return mediaproxy.ProxifyRelativeURL(f.router, link)
  70. }
  71. return link
  72. },
  73. "mustBeProxyfied": func(mediaType string) bool {
  74. return slices.Contains(config.Opts.MediaProxyResourceTypes(), mediaType)
  75. },
  76. "domain": urllib.Domain,
  77. "replace": func(str, old, new string) string {
  78. return strings.Replace(str, old, new, 1)
  79. },
  80. "isodate": func(ts time.Time) string {
  81. return ts.Format("2006-01-02 15:04:05")
  82. },
  83. "theme_color": model.ThemeColor,
  84. "icon": func(iconName string) template.HTML {
  85. return template.HTML(fmt.Sprintf(
  86. `<svg class="icon" aria-hidden="true"><use href="%s#icon-%s"/></svg>`,
  87. route.Path(f.router, "appIcon", "filename", "sprite.svg"),
  88. iconName,
  89. ))
  90. },
  91. "nonce": func() string {
  92. return crypto.GenerateRandomStringHex(16)
  93. },
  94. "deRef": func(i *int) int { return *i },
  95. "duration": duration,
  96. "urlEncode": url.PathEscape,
  97. "subtract": func(a, b int) int {
  98. return a - b
  99. },
  100. // These functions are overridden at runtime after parsing.
  101. "elapsed": func(timezone string, t time.Time) string {
  102. return ""
  103. },
  104. "t": func(key any, args ...any) string {
  105. return ""
  106. },
  107. "plural": func(key string, n int, args ...any) string {
  108. return ""
  109. },
  110. }
  111. }
  112. func csp(user *model.User, nonce string) string {
  113. policies := map[string]string{
  114. "default-src": "'none'",
  115. "frame-src": "*",
  116. "img-src": "* data:",
  117. "manifest-src": "'self'",
  118. "media-src": "*",
  119. "require-trusted-types-for": "'script'",
  120. "script-src": "'nonce-" + nonce + "' 'strict-dynamic'",
  121. "style-src": "'nonce-" + nonce + "'",
  122. "trusted-types": "html url",
  123. "connect-src": "'self'",
  124. }
  125. if user != nil {
  126. if user.ExternalFontHosts != "" {
  127. policies["font-src"] = user.ExternalFontHosts
  128. if user.Stylesheet != "" {
  129. policies["style-src"] += " " + user.ExternalFontHosts
  130. }
  131. }
  132. }
  133. var policy strings.Builder
  134. for key, value := range policies {
  135. policy.WriteString(key)
  136. policy.WriteString(" ")
  137. policy.WriteString(value)
  138. policy.WriteString("; ")
  139. }
  140. return `<meta http-equiv="Content-Security-Policy" content="` + policy.String() + `">`
  141. }
  142. func dict(values ...any) (map[string]any, error) {
  143. if len(values)%2 != 0 {
  144. return nil, errors.New("dict expects an even number of arguments")
  145. }
  146. dict := make(map[string]any, len(values)/2)
  147. for i := 0; i < len(values); i += 2 {
  148. key, ok := values[i].(string)
  149. if !ok {
  150. return nil, errors.New("dict keys must be strings")
  151. }
  152. dict[key] = values[i+1]
  153. }
  154. return dict, nil
  155. }
  156. func truncate(str string, max int) string {
  157. if runes := []rune(str); len(runes) > max {
  158. return string(runes[:max]) + "…"
  159. }
  160. return str
  161. }
  162. func isEmail(str string) bool {
  163. _, err := mail.ParseAddress(str)
  164. return err == nil
  165. }
  166. // Returns the duration in human readable format (hours and minutes).
  167. func duration(t time.Time) string {
  168. return durationImpl(t, time.Now())
  169. }
  170. // Accepts now argument for easy testing
  171. func durationImpl(t time.Time, now time.Time) string {
  172. if t.IsZero() {
  173. return ""
  174. }
  175. if diff := t.Sub(now); diff >= 0 {
  176. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  177. return diff.Round(time.Second).String()
  178. }
  179. return ""
  180. }
  181. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  182. if t.IsZero() {
  183. return printer.Print("time_elapsed.not_yet")
  184. }
  185. now := timezone.Now(tz)
  186. t = timezone.Convert(tz, t)
  187. if now.Before(t) {
  188. return printer.Print("time_elapsed.not_yet")
  189. }
  190. diff := now.Sub(t)
  191. // Duration in seconds
  192. s := diff.Seconds()
  193. // Duration in days
  194. d := int(s / 86400)
  195. switch {
  196. case s < 60:
  197. return printer.Print("time_elapsed.now")
  198. case s < 3600:
  199. minutes := int(diff.Minutes())
  200. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  201. case s < 86400:
  202. hours := int(diff.Hours())
  203. return printer.Plural("time_elapsed.hours", hours, hours)
  204. case d == 1:
  205. return printer.Print("time_elapsed.yesterday")
  206. case d < 21:
  207. return printer.Plural("time_elapsed.days", d, d)
  208. case d < 31:
  209. weeks := int(math.Round(float64(d) / 7))
  210. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  211. case d < 365:
  212. months := int(math.Round(float64(d) / 30))
  213. return printer.Plural("time_elapsed.months", months, months)
  214. default:
  215. years := int(math.Round(float64(d) / 365))
  216. return printer.Plural("time_elapsed.years", years, years)
  217. }
  218. }
  219. func formatFileSize(b int64) string {
  220. const unit = 1024
  221. if b < unit {
  222. return fmt.Sprintf("%d B", b)
  223. }
  224. base := math.Log(float64(b)) / math.Log(unit)
  225. number := math.Pow(unit, base-math.Floor(base))
  226. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  227. }