template.go 7.4 KB

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