template.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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.DisableGravatar
  56. },
  57. "ShowFooterTemplateLoadTime": func() bool {
  58. return conf.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. // FIXME: Unused function
  172. func ToUTF8(content string) string {
  173. _, res := ToUTF8WithErr([]byte(content))
  174. return res
  175. }
  176. // Replaces all prefixes 'old' in 's' with 'new'.
  177. // FIXME: Unused function
  178. func ReplaceLeft(s, old, new string) string {
  179. old_len, new_len, i, n := len(old), len(new), 0, 0
  180. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  181. i += old_len
  182. }
  183. // simple optimization
  184. if n == 0 {
  185. return s
  186. }
  187. // allocating space for the new string
  188. newLen := n*new_len + len(s[i:])
  189. replacement := make([]byte, newLen, newLen)
  190. j := 0
  191. for ; j < n*new_len; j += new_len {
  192. copy(replacement[j:j+new_len], new)
  193. }
  194. copy(replacement[j:], s[i:])
  195. return string(replacement)
  196. }
  197. // RenderCommitMessage renders commit message with special links.
  198. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  199. cleanMsg := template.HTMLEscapeString(msg)
  200. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  201. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  202. numLines := len(msgLines)
  203. if numLines == 0 {
  204. return ""
  205. } else if !full {
  206. return msgLines[0]
  207. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  208. // First line is a header, standalone or followed by empty line
  209. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  210. if numLines >= 2 {
  211. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  212. } else {
  213. fullMessage = header
  214. }
  215. } else {
  216. // Non-standard git message, there is no header line
  217. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  218. }
  219. return fullMessage
  220. }
  221. type Actioner interface {
  222. GetOpType() int
  223. GetActUserName() string
  224. GetRepoUserName() string
  225. GetRepoName() string
  226. GetRepoPath() string
  227. GetRepoLink() string
  228. GetBranch() string
  229. GetContent() string
  230. GetCreate() time.Time
  231. GetIssueInfos() []string
  232. }
  233. // ActionIcon accepts a int that represents action operation type
  234. // and returns a icon class name.
  235. func ActionIcon(opType int) string {
  236. switch opType {
  237. case 1, 8: // Create and transfer repository
  238. return "repo"
  239. case 5: // Commit repository
  240. return "git-commit"
  241. case 6: // Create issue
  242. return "issue-opened"
  243. case 7: // New pull request
  244. return "git-pull-request"
  245. case 9: // Push tag
  246. return "tag"
  247. case 10: // Comment issue
  248. return "comment-discussion"
  249. case 11: // Merge pull request
  250. return "git-merge"
  251. case 12, 14: // Close issue or pull request
  252. return "issue-closed"
  253. case 13, 15: // Reopen issue or pull request
  254. return "issue-reopened"
  255. case 16: // Create branch
  256. return "git-branch"
  257. case 17, 18: // Delete branch or tag
  258. return "alert"
  259. case 19: // Fork a repository
  260. return "repo-forked"
  261. case 20, 21, 22: // Mirror sync
  262. return "repo-clone"
  263. default:
  264. return "invalid type"
  265. }
  266. }
  267. func ActionContent2Commits(act Actioner) *db.PushCommits {
  268. push := db.NewPushCommits()
  269. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  270. log.Error("Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  271. }
  272. return push
  273. }
  274. func EscapePound(str string) string {
  275. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  276. }
  277. func DiffTypeToStr(diffType int) string {
  278. diffTypes := map[int]string{
  279. 1: "add", 2: "modify", 3: "del", 4: "rename",
  280. }
  281. return diffTypes[diffType]
  282. }
  283. func DiffLineTypeToStr(diffType int) string {
  284. switch diffType {
  285. case 2:
  286. return "add"
  287. case 3:
  288. return "del"
  289. case 4:
  290. return "tag"
  291. }
  292. return "same"
  293. }