template.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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. "github.com/gogs/git-module"
  21. "github.com/G-Node/gogs/internal/conf"
  22. "github.com/G-Node/gogs/internal/cryptoutil"
  23. "github.com/G-Node/gogs/internal/db"
  24. "github.com/G-Node/gogs/internal/gitutil"
  25. "github.com/G-Node/gogs/internal/markup"
  26. "github.com/G-Node/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]interface{}{
  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. "Str2JS": Str2JS,
  75. "NewLine2br": NewLine2br,
  76. "TimeSince": tool.TimeSince,
  77. "RawTimeSince": tool.RawTimeSince,
  78. "FileSize": tool.FileSize,
  79. "Subtract": tool.Subtract,
  80. "Add": func(a, b int) int {
  81. return a + b
  82. },
  83. "ActionIcon": ActionIcon,
  84. "DateFmtLong": func(t time.Time) string {
  85. return t.Format(time.RFC1123Z)
  86. },
  87. "DateFmtShort": func(t time.Time) string {
  88. return t.Format("Jan 02, 2006")
  89. },
  90. "SubStr": func(str string, start, length int) string {
  91. if len(str) == 0 {
  92. return ""
  93. }
  94. end := start + length
  95. if length == -1 {
  96. end = len(str)
  97. }
  98. if len(str) < end {
  99. return str
  100. }
  101. return str[start:end]
  102. },
  103. "Join": strings.Join,
  104. "EllipsisString": tool.EllipsisString,
  105. "DiffFileTypeToStr": DiffFileTypeToStr,
  106. "DiffLineTypeToStr": DiffLineTypeToStr,
  107. "Sha1": Sha1,
  108. "ShortSHA1": tool.ShortSHA1,
  109. "ActionContent2Commits": ActionContent2Commits,
  110. "EscapePound": EscapePound,
  111. "RenderCommitMessage": RenderCommitMessage,
  112. "ThemeColorMetaTag": func() string {
  113. return conf.UI.ThemeColorMetaTag
  114. },
  115. "FilenameIsImage": func(filename string) bool {
  116. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  117. return strings.HasPrefix(mimeType, "image/")
  118. },
  119. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  120. if ec != nil {
  121. def, err := ec.GetDefinitionForFilename(filename)
  122. if err == nil && def.TabWidth > 0 {
  123. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  124. }
  125. }
  126. return "tab-size-8"
  127. },
  128. "InferSubmoduleURL": gitutil.InferSubmoduleURL,
  129. }}
  130. })
  131. return funcMap
  132. }
  133. func Safe(raw string) template.HTML {
  134. return template.HTML(raw)
  135. }
  136. func Str2HTML(raw string) template.HTML {
  137. return template.HTML(markup.Sanitize(raw))
  138. }
  139. // NewLine2br simply replaces "\n" to "<br>".
  140. func NewLine2br(raw string) string {
  141. return strings.Replace(raw, "\n", "<br>", -1)
  142. }
  143. func Str2JS(raw string) template.JS {
  144. return template.JS(raw)
  145. }
  146. func List(l *list.List) chan interface{} {
  147. e := l.Front()
  148. c := make(chan interface{})
  149. go func() {
  150. for e != nil {
  151. c <- e.Value
  152. e = e.Next()
  153. }
  154. close(c)
  155. }()
  156. return c
  157. }
  158. func Sha1(str string) string {
  159. return cryptoutil.SHA1(str)
  160. }
  161. func ToUTF8WithErr(content []byte) (error, string) {
  162. charsetLabel, err := tool.DetectEncoding(content)
  163. if err != nil {
  164. return err, ""
  165. } else if charsetLabel == "UTF-8" {
  166. return nil, string(content)
  167. }
  168. encoding, _ := charset.Lookup(charsetLabel)
  169. if encoding == nil {
  170. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  171. }
  172. // If there is an error, we concatenate the nicely decoded part and the
  173. // original left over. This way we won't loose data.
  174. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  175. if err != nil {
  176. result = result + string(content[n:])
  177. }
  178. return err, result
  179. }
  180. // RenderCommitMessage renders commit message with special links.
  181. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  182. cleanMsg := template.HTMLEscapeString(msg)
  183. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  184. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  185. numLines := len(msgLines)
  186. if numLines == 0 {
  187. return ""
  188. } else if !full {
  189. return msgLines[0]
  190. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  191. // First line is a header, standalone or followed by empty line
  192. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  193. if numLines >= 2 {
  194. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  195. } else {
  196. fullMessage = header
  197. }
  198. } else {
  199. // Non-standard git message, there is no header line
  200. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  201. }
  202. return fullMessage
  203. }
  204. type Actioner interface {
  205. GetOpType() int
  206. GetActUserName() string
  207. GetRepoUserName() string
  208. GetRepoName() string
  209. GetRepoPath() string
  210. GetRepoLink() string
  211. GetBranch() string
  212. GetContent() string
  213. GetCreate() time.Time
  214. GetIssueInfos() []string
  215. }
  216. // ActionIcon accepts a int that represents action operation type
  217. // and returns a icon class name.
  218. func ActionIcon(opType int) string {
  219. switch opType {
  220. case 1, 8: // Create and transfer repository
  221. return "repo"
  222. case 5: // Commit repository
  223. return "git-commit"
  224. case 6: // Create issue
  225. return "issue-opened"
  226. case 7: // New pull request
  227. return "git-pull-request"
  228. case 9: // Push tag
  229. return "tag"
  230. case 10: // Comment issue
  231. return "comment-discussion"
  232. case 11: // Merge pull request
  233. return "git-merge"
  234. case 12, 14: // Close issue or pull request
  235. return "issue-closed"
  236. case 13, 15: // Reopen issue or pull request
  237. return "issue-reopened"
  238. case 16: // Create branch
  239. return "git-branch"
  240. case 17, 18: // Delete branch or tag
  241. return "alert"
  242. case 19: // Fork a repository
  243. return "repo-forked"
  244. case 20, 21, 22: // Mirror sync
  245. return "repo-clone"
  246. default:
  247. return "invalid type"
  248. }
  249. }
  250. func ActionContent2Commits(act Actioner) *db.PushCommits {
  251. push := db.NewPushCommits()
  252. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  253. log.Error("Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  254. }
  255. return push
  256. }
  257. // TODO(unknwon): Use url.Escape.
  258. func EscapePound(str string) string {
  259. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  260. }
  261. func DiffFileTypeToStr(typ git.DiffFileType) string {
  262. return map[git.DiffFileType]string{
  263. git.DiffFileAdd: "add",
  264. git.DiffFileChange: "modify",
  265. git.DiffFileDelete: "del",
  266. git.DiffFileRename: "rename",
  267. }[typ]
  268. }
  269. func DiffLineTypeToStr(typ git.DiffLineType) string {
  270. switch typ {
  271. case git.DiffLineAdd:
  272. return "add"
  273. case git.DiffLineDelete:
  274. return "del"
  275. case git.DiffLineSection:
  276. return "tag"
  277. }
  278. return "same"
  279. }