template.go 7.9 KB

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