template.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  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/modules/base"
  22. "github.com/gogits/gogs/modules/markdown"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  25. func NewFuncMap() []template.FuncMap {
  26. return []template.FuncMap{map[string]interface{}{
  27. "GoVer": func() string {
  28. return strings.Title(runtime.Version())
  29. },
  30. "UseHTTPS": func() bool {
  31. return strings.HasPrefix(setting.AppUrl, "https")
  32. },
  33. "AppName": func() string {
  34. return setting.AppName
  35. },
  36. "AppSubUrl": func() string {
  37. return setting.AppSubUrl
  38. },
  39. "AppUrl": func() string {
  40. return setting.AppUrl
  41. },
  42. "AppVer": func() string {
  43. return setting.AppVer
  44. },
  45. "AppDomain": func() string {
  46. return setting.Domain
  47. },
  48. "DisableGravatar": func() bool {
  49. return setting.DisableGravatar
  50. },
  51. "ShowFooterTemplateLoadTime": func() bool {
  52. return setting.ShowFooterTemplateLoadTime
  53. },
  54. "LoadTimes": func(startTime time.Time) string {
  55. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  56. },
  57. "AvatarLink": base.AvatarLink,
  58. "Safe": Safe,
  59. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  60. "Str2html": Str2html,
  61. "TimeSince": base.TimeSince,
  62. "RawTimeSince": base.RawTimeSince,
  63. "FileSize": base.FileSize,
  64. "Subtract": base.Subtract,
  65. "Add": func(a, b int) int {
  66. return a + b
  67. },
  68. "ActionIcon": ActionIcon,
  69. "DateFmtLong": func(t time.Time) string {
  70. return t.Format(time.RFC1123Z)
  71. },
  72. "DateFmtShort": func(t time.Time) string {
  73. return t.Format("Jan 02, 2006")
  74. },
  75. "List": List,
  76. "SubStr": func(str string, start, length int) string {
  77. if len(str) == 0 {
  78. return ""
  79. }
  80. end := start + length
  81. if length == -1 {
  82. end = len(str)
  83. }
  84. if len(str) < end {
  85. return str
  86. }
  87. return str[start:end]
  88. },
  89. "EllipsisString": base.EllipsisString,
  90. "DiffTypeToStr": DiffTypeToStr,
  91. "DiffLineTypeToStr": DiffLineTypeToStr,
  92. "Sha1": Sha1,
  93. "ShortSha": base.ShortSha,
  94. "MD5": base.EncodeMD5,
  95. "ActionContent2Commits": ActionContent2Commits,
  96. "EscapePound": EscapePound,
  97. "RenderCommitMessage": RenderCommitMessage,
  98. "ThemeColorMetaTag": func() string {
  99. return setting.UI.ThemeColorMetaTag
  100. },
  101. "FilenameIsImage": func(filename string) bool {
  102. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  103. return strings.HasPrefix(mimeType, "image/")
  104. },
  105. "TabSizeClass": func(ec *editorconfig.Editorconfig, filename string) string {
  106. if ec != nil {
  107. def := ec.GetDefinitionForFilename(filename)
  108. if def.TabWidth > 0 {
  109. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  110. }
  111. }
  112. return "tab-size-8"
  113. },
  114. }}
  115. }
  116. func Safe(raw string) template.HTML {
  117. return template.HTML(raw)
  118. }
  119. func Str2html(raw string) template.HTML {
  120. return template.HTML(markdown.Sanitizer.Sanitize(raw))
  121. }
  122. func List(l *list.List) chan interface{} {
  123. e := l.Front()
  124. c := make(chan interface{})
  125. go func() {
  126. for e != nil {
  127. c <- e.Value
  128. e = e.Next()
  129. }
  130. close(c)
  131. }()
  132. return c
  133. }
  134. func Sha1(str string) string {
  135. return base.EncodeSha1(str)
  136. }
  137. func ToUTF8WithErr(content []byte) (error, string) {
  138. charsetLabel, err := base.DetectEncoding(content)
  139. if err != nil {
  140. return err, ""
  141. } else if charsetLabel == "UTF-8" {
  142. return nil, string(content)
  143. }
  144. encoding, _ := charset.Lookup(charsetLabel)
  145. if encoding == nil {
  146. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  147. }
  148. // If there is an error, we concatenate the nicely decoded part and the
  149. // original left over. This way we won't loose data.
  150. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  151. if err != nil {
  152. result = result + string(content[n:])
  153. }
  154. return err, result
  155. }
  156. func ToUTF8(content string) string {
  157. _, res := ToUTF8WithErr([]byte(content))
  158. return res
  159. }
  160. // Replaces all prefixes 'old' in 's' with 'new'.
  161. func ReplaceLeft(s, old, new string) string {
  162. old_len, new_len, i, n := len(old), len(new), 0, 0
  163. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  164. i += old_len
  165. }
  166. // simple optimization
  167. if n == 0 {
  168. return s
  169. }
  170. // allocating space for the new string
  171. newLen := n*new_len + len(s[i:])
  172. replacement := make([]byte, newLen, newLen)
  173. j := 0
  174. for ; j < n*new_len; j += new_len {
  175. copy(replacement[j:j+new_len], new)
  176. }
  177. copy(replacement[j:], s[i:])
  178. return string(replacement)
  179. }
  180. // RenderCommitMessage renders commit message with XSS-safe and special links.
  181. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
  182. cleanMsg := template.HTMLEscapeString(msg)
  183. fullMessage := string(markdown.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  184. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  185. numLines := len(msgLines)
  186. if numLines == 0 {
  187. return template.HTML("")
  188. } else if !full {
  189. return template.HTML(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 template.HTML(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, 9: // 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 10: // Comment issue
  229. return "comment-discussion"
  230. case 11: // Merge pull request
  231. return "git-merge"
  232. case 12, 14: // Close issue or pull request
  233. return "issue-closed"
  234. case 13, 15: // Reopen issue or pull request
  235. return "issue-reopened"
  236. default:
  237. return "invalid type"
  238. }
  239. }
  240. func ActionContent2Commits(act Actioner) *models.PushCommits {
  241. push := models.NewPushCommits()
  242. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  243. log.Error(4, "json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  244. }
  245. return push
  246. }
  247. func EscapePound(str string) string {
  248. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  249. }
  250. func DiffTypeToStr(diffType int) string {
  251. diffTypes := map[int]string{
  252. 1: "add", 2: "modify", 3: "del", 4: "rename",
  253. }
  254. return diffTypes[diffType]
  255. }
  256. func DiffLineTypeToStr(diffType int) string {
  257. switch diffType {
  258. case 2:
  259. return "add"
  260. case 3:
  261. return "del"
  262. case 4:
  263. return "tag"
  264. }
  265. return "same"
  266. }