template.go 6.8 KB

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