gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package templates
  5. import (
  6. "fmt"
  7. "html/template"
  8. "net/url"
  9. "strconv"
  10. "strings"
  11. "time"
  12. user_model "code.gitea.io/gitea/models/user"
  13. "code.gitea.io/gitea/modules/base"
  14. "code.gitea.io/gitea/modules/htmlutil"
  15. "code.gitea.io/gitea/modules/markup"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/svg"
  18. "code.gitea.io/gitea/modules/templates/eval"
  19. "code.gitea.io/gitea/modules/util"
  20. "code.gitea.io/gitea/services/gitdiff"
  21. "code.gitea.io/gitea/services/webtheme"
  22. )
  23. // NewFuncMap returns functions for injecting to templates
  24. func NewFuncMap() template.FuncMap {
  25. return map[string]any{
  26. "ctx": func() any { return nil }, // template context function
  27. "DumpVar": dumpVar,
  28. "NIL": func() any { return nil },
  29. // -----------------------------------------------------------------
  30. // html/template related functions
  31. "dict": dict, // it's lowercase because this name has been widely used. Our other functions should have uppercase names.
  32. "Iif": iif,
  33. "Eval": evalTokens,
  34. "HTMLFormat": htmlFormat,
  35. "QueryEscape": queryEscape,
  36. "QueryBuild": QueryBuild,
  37. "SanitizeHTML": SanitizeHTML,
  38. "URLJoin": util.URLJoin,
  39. "DotEscape": dotEscape,
  40. "PathEscape": url.PathEscape,
  41. "PathEscapeSegments": util.PathEscapeSegments,
  42. // utils
  43. "StringUtils": NewStringUtils,
  44. "SliceUtils": NewSliceUtils,
  45. "JsonUtils": NewJsonUtils,
  46. "DateUtils": NewDateUtils,
  47. // -----------------------------------------------------------------
  48. // svg / avatar / icon / color
  49. "svg": svg.RenderHTML,
  50. "MigrationIcon": migrationIcon,
  51. "ActionIcon": actionIcon,
  52. "SortArrow": sortArrow,
  53. "ContrastColor": util.ContrastColor,
  54. // -----------------------------------------------------------------
  55. // time / number / format
  56. "FileSize": base.FileSize,
  57. "CountFmt": countFmt,
  58. "Sec2Hour": util.SecToHours,
  59. "TimeEstimateString": timeEstimateString,
  60. "LoadTimes": func(startTime time.Time) string {
  61. return strconv.FormatInt(time.Since(startTime).Nanoseconds()/1e6, 10) + "ms"
  62. },
  63. // -----------------------------------------------------------------
  64. // setting
  65. "AppName": func() string {
  66. return setting.AppName
  67. },
  68. "AppSubUrl": func() string {
  69. return setting.AppSubURL
  70. },
  71. "AssetUrlPrefix": func() string {
  72. return setting.StaticURLPrefix + "/assets"
  73. },
  74. "AppUrl": func() string {
  75. // The usage of AppUrl should be avoided as much as possible,
  76. // because the AppURL(ROOT_URL) may not match user's visiting site and the ROOT_URL in app.ini may be incorrect.
  77. // And it's difficult for Gitea to guess absolute URL correctly with zero configuration,
  78. // because Gitea doesn't know whether the scheme is HTTP or HTTPS unless the reverse proxy could tell Gitea.
  79. return setting.AppURL
  80. },
  81. "AppVer": func() string {
  82. return setting.AppVer
  83. },
  84. "AppDomain": func() string { // documented in mail-templates.md
  85. return setting.Domain
  86. },
  87. "AssetVersion": func() string {
  88. return setting.AssetVersion
  89. },
  90. "DefaultShowFullName": func() bool {
  91. return setting.UI.DefaultShowFullName
  92. },
  93. "ShowFooterTemplateLoadTime": func() bool {
  94. return setting.Other.ShowFooterTemplateLoadTime
  95. },
  96. "ShowFooterPoweredBy": func() bool {
  97. return setting.Other.ShowFooterPoweredBy
  98. },
  99. "AllowedReactions": func() []string {
  100. return setting.UI.Reactions
  101. },
  102. "CustomEmojis": func() map[string]string {
  103. return setting.UI.CustomEmojisMap
  104. },
  105. "MetaAuthor": func() string {
  106. return setting.UI.Meta.Author
  107. },
  108. "MetaDescription": func() string {
  109. return setting.UI.Meta.Description
  110. },
  111. "MetaKeywords": func() string {
  112. return setting.UI.Meta.Keywords
  113. },
  114. "EnableTimetracking": func() bool {
  115. return setting.Service.EnableTimetracking
  116. },
  117. "DisableWebhooks": func() bool {
  118. return setting.DisableWebhooks
  119. },
  120. "UserThemeName": userThemeName,
  121. "NotificationSettings": func() map[string]any {
  122. return map[string]any{
  123. "MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
  124. "TimeoutStep": int(setting.UI.Notification.TimeoutStep / time.Millisecond),
  125. "MaxTimeout": int(setting.UI.Notification.MaxTimeout / time.Millisecond),
  126. "EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond),
  127. }
  128. },
  129. "MermaidMaxSourceCharacters": func() int {
  130. return setting.MermaidMaxSourceCharacters
  131. },
  132. // -----------------------------------------------------------------
  133. // render
  134. "RenderCodeBlock": renderCodeBlock,
  135. "ReactionToEmoji": reactionToEmoji,
  136. // -----------------------------------------------------------------
  137. // misc
  138. "ShortSha": base.ShortSha,
  139. "ActionContent2Commits": ActionContent2Commits,
  140. "IsMultilineCommitMessage": isMultilineCommitMessage,
  141. "CommentMustAsDiff": gitdiff.CommentMustAsDiff,
  142. "MirrorRemoteAddress": mirrorRemoteAddress,
  143. "FilenameIsImage": filenameIsImage,
  144. "TabSizeClass": tabSizeClass,
  145. }
  146. }
  147. // SanitizeHTML sanitizes the input by default sanitization rules.
  148. func SanitizeHTML(s string) template.HTML {
  149. return markup.Sanitize(s)
  150. }
  151. func htmlFormat(s any, args ...any) template.HTML {
  152. if len(args) == 0 {
  153. // to prevent developers from calling "HTMLFormat $userInput" by mistake which will lead to XSS
  154. panic("missing arguments for HTMLFormat")
  155. }
  156. switch v := s.(type) {
  157. case string:
  158. return htmlutil.HTMLFormat(template.HTML(v), args...)
  159. case template.HTML:
  160. return htmlutil.HTMLFormat(v, args...)
  161. }
  162. panic(fmt.Sprintf("unexpected type %T", s))
  163. }
  164. func queryEscape(s string) template.URL {
  165. return template.URL(url.QueryEscape(s))
  166. }
  167. // dotEscape wraps a dots in names with ZWJ [U+200D] in order to prevent auto-linkers from detecting these as urls
  168. func dotEscape(raw string) string {
  169. return strings.ReplaceAll(raw, ".", "\u200d.\u200d")
  170. }
  171. // iif is an "inline-if", similar util.Iif[T] but templates need the non-generic version,
  172. // and it could be simply used as "{{iif expr trueVal}}" (omit the falseVal).
  173. func iif(condition any, vals ...any) any {
  174. if isTemplateTruthy(condition) {
  175. return vals[0]
  176. } else if len(vals) > 1 {
  177. return vals[1]
  178. }
  179. return nil
  180. }
  181. func isTemplateTruthy(v any) bool {
  182. truth, _ := template.IsTrue(v)
  183. return truth
  184. }
  185. // evalTokens evaluates the expression by tokens and returns the result, see the comment of eval.Expr for details.
  186. // To use this helper function in templates, pass each token as a separate parameter.
  187. //
  188. // {{ $int64 := Eval $var "+" 1 }}
  189. // {{ $float64 := Eval $var "+" 1.0 }}
  190. //
  191. // Golang's template supports comparable int types, so the int64 result can be used in later statements like {{if lt $int64 10}}
  192. func evalTokens(tokens ...any) (any, error) {
  193. n, err := eval.Expr(tokens...)
  194. return n.Value, err
  195. }
  196. func userThemeName(user *user_model.User) string {
  197. if user == nil || user.Theme == "" {
  198. return setting.UI.DefaultTheme
  199. }
  200. if webtheme.IsThemeAvailable(user.Theme) {
  201. return user.Theme
  202. }
  203. return setting.UI.DefaultTheme
  204. }
  205. func isQueryParamEmpty(v any) bool {
  206. return v == nil || v == false || v == 0 || v == int64(0) || v == ""
  207. }
  208. // QueryBuild builds a query string from a list of key-value pairs.
  209. // It omits the nil, false, zero int/int64 and empty string values,
  210. // because they are default empty values for "ctx.FormXxx" calls.
  211. // If 0 or false need to be included, use string values: "0" and "false".
  212. // Build rules:
  213. // * Even parameters: always build as query string: a=b&c=d
  214. // * Odd parameters:
  215. // * * {"/anything", param-pairs...} => "/?param-paris"
  216. // * * {"anything?old-params", new-param-pairs...} => "anything?old-params&new-param-paris"
  217. // * * Otherwise: {"old&params", new-param-pairs...} => "old&params&new-param-paris"
  218. // * * Other behaviors are undefined yet.
  219. func QueryBuild(a ...any) template.URL {
  220. var reqPath, s string
  221. hasTrailingSep := false
  222. if len(a)%2 == 1 {
  223. if v, ok := a[0].(string); ok {
  224. s = v
  225. } else if v, ok := a[0].(template.URL); ok {
  226. s = string(v)
  227. } else {
  228. panic("QueryBuild: invalid argument")
  229. }
  230. hasTrailingSep = s != "&" && strings.HasSuffix(s, "&")
  231. if strings.HasPrefix(s, "/") || strings.Contains(s, "?") {
  232. if s1, s2, ok := strings.Cut(s, "?"); ok {
  233. reqPath = s1 + "?"
  234. s = s2
  235. } else {
  236. reqPath += s + "?"
  237. s = ""
  238. }
  239. }
  240. }
  241. for i := len(a) % 2; i < len(a); i += 2 {
  242. k, ok := a[i].(string)
  243. if !ok {
  244. panic("QueryBuild: invalid argument")
  245. }
  246. var v string
  247. if va, ok := a[i+1].(string); ok {
  248. v = va
  249. } else if a[i+1] != nil {
  250. if !isQueryParamEmpty(a[i+1]) {
  251. v = fmt.Sprint(a[i+1])
  252. }
  253. }
  254. // pos1 to pos2 is the "k=v&" part, "&" is optional
  255. pos1 := strings.Index(s, "&"+k+"=")
  256. if pos1 != -1 {
  257. pos1++
  258. } else if strings.HasPrefix(s, k+"=") {
  259. pos1 = 0
  260. }
  261. pos2 := len(s)
  262. if pos1 == -1 {
  263. pos1 = len(s)
  264. } else {
  265. pos2 = pos1 + 1
  266. for pos2 < len(s) && s[pos2-1] != '&' {
  267. pos2++
  268. }
  269. }
  270. if v != "" {
  271. sep := ""
  272. hasPrefixSep := pos1 == 0 || (pos1 <= len(s) && s[pos1-1] == '&')
  273. if !hasPrefixSep {
  274. sep = "&"
  275. }
  276. s = s[:pos1] + sep + k + "=" + url.QueryEscape(v) + "&" + s[pos2:]
  277. } else {
  278. s = s[:pos1] + s[pos2:]
  279. }
  280. }
  281. if s != "" && s[len(s)-1] == '&' && !hasTrailingSep {
  282. s = s[:len(s)-1]
  283. }
  284. if reqPath != "" {
  285. if s == "" {
  286. s = reqPath
  287. if s != "?" {
  288. s = s[:len(s)-1]
  289. }
  290. } else {
  291. if s[0] == '&' {
  292. s = s[1:]
  293. }
  294. s = reqPath + s
  295. }
  296. }
  297. return template.URL(s)
  298. }