template.go 6.3 KB

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