template.go 6.3 KB

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