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