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