template.go 7.5 KB

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