template.go 7.5 KB

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