functions.go 7.5 KB

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