1
0

template.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package template
  5. import (
  6. "fmt"
  7. "html/template"
  8. "mime"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "time"
  13. "github.com/editorconfig/editorconfig-core-go/v2"
  14. jsoniter "github.com/json-iterator/go"
  15. "github.com/microcosm-cc/bluemonday"
  16. "golang.org/x/net/html/charset"
  17. "golang.org/x/text/transform"
  18. log "unknwon.dev/clog/v2"
  19. "github.com/gogs/git-module"
  20. "gogs.io/gogs/internal/conf"
  21. "gogs.io/gogs/internal/cryptoutil"
  22. "gogs.io/gogs/internal/database"
  23. "gogs.io/gogs/internal/gitutil"
  24. "gogs.io/gogs/internal/markup"
  25. "gogs.io/gogs/internal/strutil"
  26. "gogs.io/gogs/internal/tool"
  27. )
  28. var (
  29. funcMap []template.FuncMap
  30. funcMapOnce sync.Once
  31. )
  32. // FuncMap returns a list of user-defined template functions.
  33. func FuncMap() []template.FuncMap {
  34. funcMapOnce.Do(func() {
  35. funcMap = []template.FuncMap{map[string]any{
  36. "BuildCommit": func() string {
  37. return conf.BuildCommit
  38. },
  39. "Year": func() int {
  40. return time.Now().Year()
  41. },
  42. "UseHTTPS": func() bool {
  43. return conf.Server.URL.Scheme == "https"
  44. },
  45. "AppName": func() string {
  46. return conf.App.BrandName
  47. },
  48. "AppSubURL": func() string {
  49. return conf.Server.Subpath
  50. },
  51. "AppURL": func() string {
  52. return conf.Server.ExternalURL
  53. },
  54. "AppVer": func() string {
  55. return conf.App.Version
  56. },
  57. "AppDomain": func() string {
  58. return conf.Server.Domain
  59. },
  60. "DisableGravatar": func() bool {
  61. return conf.Picture.DisableGravatar
  62. },
  63. "ShowFooterTemplateLoadTime": func() bool {
  64. return conf.Other.ShowFooterTemplateLoadTime
  65. },
  66. "LoadTimes": func(startTime time.Time) string {
  67. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  68. },
  69. "AvatarLink": tool.AvatarLink,
  70. "AppendAvatarSize": tool.AppendAvatarSize,
  71. "Safe": Safe,
  72. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  73. "Str2HTML": Str2HTML,
  74. "NewLine2br": NewLine2br,
  75. "TimeSince": tool.TimeSince,
  76. "RawTimeSince": tool.RawTimeSince,
  77. "FileSize": tool.FileSize,
  78. "Subtract": tool.Subtract,
  79. "Add": func(a, b int) int {
  80. return a + b
  81. },
  82. "ActionIcon": ActionIcon,
  83. "DateFmtLong": func(t time.Time) string {
  84. return t.Format(time.RFC1123Z)
  85. },
  86. "DateFmtShort": func(t time.Time) string {
  87. return t.Format("Jan 02, 2006")
  88. },
  89. "SubStr": func(str string, start, length int) string {
  90. if str == "" {
  91. return ""
  92. }
  93. end := start + length
  94. if length == -1 {
  95. end = len(str)
  96. }
  97. if len(str) < end {
  98. return str
  99. }
  100. return str[start:end]
  101. },
  102. "Join": strings.Join,
  103. "EllipsisString": strutil.Ellipsis,
  104. "DiffFileTypeToStr": DiffFileTypeToStr,
  105. "DiffLineTypeToStr": DiffLineTypeToStr,
  106. "Sha1": Sha1,
  107. "ShortSHA1": tool.ShortSHA1,
  108. "ActionContent2Commits": ActionContent2Commits,
  109. "EscapePound": EscapePound,
  110. "RenderCommitMessage": RenderCommitMessage,
  111. "ThemeColorMetaTag": func() string {
  112. return conf.UI.ThemeColorMetaTag
  113. },
  114. "FilenameIsImage": func(filename string) bool {
  115. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  116. return strings.HasPrefix(mimeType, "image/")
  117. },
  118. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  119. if ec != nil {
  120. def, err := ec.GetDefinitionForFilename(filename)
  121. if err == nil && def.TabWidth > 0 {
  122. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  123. }
  124. }
  125. return "tab-size-8"
  126. },
  127. "InferSubmoduleURL": gitutil.InferSubmoduleURL,
  128. }}
  129. })
  130. return funcMap
  131. }
  132. func Safe(raw string) template.HTML {
  133. return template.HTML(raw)
  134. }
  135. func Str2HTML(raw string) template.HTML {
  136. return template.HTML(markup.Sanitize(raw))
  137. }
  138. // NewLine2br simply replaces "\n" to "<br>".
  139. func NewLine2br(raw string) string {
  140. return strings.ReplaceAll(raw, "\n", "<br>")
  141. }
  142. func Sha1(str string) string {
  143. return cryptoutil.SHA1(str)
  144. }
  145. func ToUTF8WithErr(content []byte) (error, string) {
  146. charsetLabel, err := tool.DetectEncoding(content)
  147. if err != nil {
  148. return err, ""
  149. } else if charsetLabel == "UTF-8" {
  150. return nil, string(content)
  151. }
  152. encoding, _ := charset.Lookup(charsetLabel)
  153. if encoding == nil {
  154. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  155. }
  156. // If there is an error, we concatenate the nicely decoded part and the
  157. // original left over. This way we won't loose data.
  158. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  159. if err != nil {
  160. result = result + string(content[n:])
  161. }
  162. return err, result
  163. }
  164. // RenderCommitMessage renders commit message with special links.
  165. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  166. cleanMsg := template.HTMLEscapeString(msg)
  167. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  168. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  169. numLines := len(msgLines)
  170. if numLines == 0 {
  171. return ""
  172. } else if !full {
  173. return msgLines[0]
  174. } else if numLines == 1 || (numLines >= 2 && msgLines[1] == "") {
  175. // First line is a header, standalone or followed by empty line
  176. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  177. if numLines >= 2 {
  178. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  179. } else {
  180. fullMessage = header
  181. }
  182. } else {
  183. // Non-standard git message, there is no header line
  184. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  185. }
  186. return fullMessage
  187. }
  188. type Actioner interface {
  189. GetOpType() int
  190. GetActUserName() string
  191. GetRepoUserName() string
  192. GetRepoName() string
  193. GetRepoPath() string
  194. GetRepoLink() string
  195. GetBranch() string
  196. GetContent() string
  197. GetCreate() time.Time
  198. GetIssueInfos() []string
  199. }
  200. // ActionIcon accepts a int that represents action operation type
  201. // and returns a icon class name.
  202. func ActionIcon(opType int) string {
  203. switch opType {
  204. case 1, 8: // Create and transfer repository
  205. return "repo"
  206. case 5: // Commit repository
  207. return "git-commit"
  208. case 6: // Create issue
  209. return "issue-opened"
  210. case 7: // New pull request
  211. return "git-pull-request"
  212. case 9: // Push tag
  213. return "tag"
  214. case 10: // Comment issue
  215. return "comment-discussion"
  216. case 11: // Merge pull request
  217. return "git-merge"
  218. case 12, 14: // Close issue or pull request
  219. return "issue-closed"
  220. case 13, 15: // Reopen issue or pull request
  221. return "issue-reopened"
  222. case 16: // Create branch
  223. return "git-branch"
  224. case 17, 18: // Delete branch or tag
  225. return "alert"
  226. case 19: // Fork a repository
  227. return "repo-forked"
  228. case 20, 21, 22: // Mirror sync
  229. return "repo-clone"
  230. default:
  231. return "invalid type"
  232. }
  233. }
  234. func ActionContent2Commits(act Actioner) *database.PushCommits {
  235. push := database.NewPushCommits()
  236. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  237. log.Error("Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  238. }
  239. return push
  240. }
  241. // TODO(unknwon): Use url.Escape.
  242. func EscapePound(str string) string {
  243. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  244. }
  245. func DiffFileTypeToStr(typ git.DiffFileType) string {
  246. return map[git.DiffFileType]string{
  247. git.DiffFileAdd: "add",
  248. git.DiffFileChange: "modify",
  249. git.DiffFileDelete: "del",
  250. git.DiffFileRename: "rename",
  251. }[typ]
  252. }
  253. func DiffLineTypeToStr(typ git.DiffLineType) string {
  254. switch typ {
  255. case git.DiffLineAdd:
  256. return "add"
  257. case git.DiffLineDelete:
  258. return "del"
  259. case git.DiffLineSection:
  260. return "tag"
  261. }
  262. return "same"
  263. }