functions.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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 dict(values ...any) (map[string]any, error) {
  161. if len(values)%2 != 0 {
  162. return nil, errors.New("dict expects an even number of arguments")
  163. }
  164. dict := make(map[string]any, len(values)/2)
  165. for i := 0; i < len(values); i += 2 {
  166. key, ok := values[i].(string)
  167. if !ok {
  168. return nil, errors.New("dict keys must be strings")
  169. }
  170. dict[key] = values[i+1]
  171. }
  172. return dict, nil
  173. }
  174. func truncate(str string, max int) string {
  175. if max <= 0 {
  176. panic("truncate: max must be greater than zero")
  177. }
  178. // Template callers pass feed titles from remote content. Scanning and
  179. // allocating the entire untrusted input just to truncate it could create a
  180. // denial-of-service risk, so stop as soon as we reach the requested limit.
  181. runeCount := 0
  182. for i := range str {
  183. if runeCount == max {
  184. return str[:i] + "…"
  185. }
  186. runeCount++
  187. }
  188. return str
  189. }
  190. func isEmail(str string) bool {
  191. _, err := mail.ParseAddress(str)
  192. return err == nil
  193. }
  194. // untrustedURL validates a feed-supplied URL against the sanitizer's scheme
  195. // allowlist before exposing it to html/template. Returns "#" for unsafe URLs
  196. // (e.g. javascript:, data:) so anchors render as inert links.
  197. //
  198. // Go's built-in html/template URL filter only allows http(s), mailto, and
  199. // relative URLs — too narrow for feeds which legitimately use schemes like
  200. // magnet:, feed:, webcal:, and tel:.
  201. func untrustedURL(rawURL string) template.URL {
  202. if !sanitizer.HasValidURIScheme(rawURL) {
  203. return template.URL("#")
  204. }
  205. return template.URL(rawURL)
  206. }
  207. // Returns the duration in human readable format (hours and minutes).
  208. func duration(t time.Time) string {
  209. return durationImpl(t, time.Now())
  210. }
  211. // Accepts now argument for easy testing
  212. func durationImpl(t time.Time, now time.Time) string {
  213. if t.IsZero() {
  214. return ""
  215. }
  216. if diff := t.Sub(now); diff >= 0 {
  217. // Round to nearest second to get e.g. "14m56s" rather than "14m56.245483933s"
  218. return diff.Round(time.Second).String()
  219. }
  220. return ""
  221. }
  222. func elapsedTime(printer *locale.Printer, tz string, t time.Time) string {
  223. if t.IsZero() {
  224. return printer.Print("time_elapsed.not_yet")
  225. }
  226. now := timezone.Now(tz)
  227. t = timezone.Convert(tz, t)
  228. if now.Before(t) {
  229. return printer.Print("time_elapsed.not_yet")
  230. }
  231. diff := now.Sub(t)
  232. // Duration in seconds
  233. s := diff.Seconds()
  234. // Duration in days
  235. d := int(s / 86400)
  236. switch {
  237. case s < 60:
  238. return printer.Print("time_elapsed.now")
  239. case s < 3600:
  240. minutes := int(diff.Minutes())
  241. return printer.Plural("time_elapsed.minutes", minutes, minutes)
  242. case s < 86400:
  243. hours := int(diff.Hours())
  244. return printer.Plural("time_elapsed.hours", hours, hours)
  245. case d == 1:
  246. return printer.Print("time_elapsed.yesterday")
  247. case d < 21:
  248. return printer.Plural("time_elapsed.days", d, d)
  249. case d < 31:
  250. weeks := int(math.Round(float64(d) / 7))
  251. return printer.Plural("time_elapsed.weeks", weeks, weeks)
  252. case d < 365:
  253. months := int(math.Round(float64(d) / 30))
  254. return printer.Plural("time_elapsed.months", months, months)
  255. default:
  256. years := int(math.Round(float64(d) / 365))
  257. return printer.Plural("time_elapsed.years", years, years)
  258. }
  259. }
  260. func formatFileSize(b int64) string {
  261. const unit = 1024
  262. if b < unit {
  263. return fmt.Sprintf("%d B", b)
  264. }
  265. base := math.Log(float64(b)) / math.Log(unit)
  266. number := math.Pow(unit, base-math.Floor(base))
  267. return fmt.Sprintf("%.1f %ciB", number, "KMGTPE"[int64(base)-1])
  268. }