template.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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, err := base.DetectEncoding(content)
  119. if err != nil {
  120. return err, ""
  121. }
  122. if charsetLabel == "UTF-8" {
  123. return nil, string(content)
  124. }
  125. encoding, _ := charset.Lookup(charsetLabel)
  126. if encoding == nil {
  127. return fmt.Errorf("unknown char decoder %s", charsetLabel), string(content)
  128. }
  129. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  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. if err != nil {
  133. result = result + string(content[n:])
  134. }
  135. return err, result
  136. }
  137. func ToUtf8(content string) string {
  138. _, res := ToUtf8WithErr([]byte(content))
  139. return res
  140. }
  141. // Replaces all prefixes 'old' in 's' with 'new'.
  142. func ReplaceLeft(s, old, new string) string {
  143. old_len, new_len, i, n := len(old), len(new), 0, 0
  144. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  145. i += old_len
  146. }
  147. // simple optimization
  148. if n == 0 {
  149. return s
  150. }
  151. // allocating space for the new string
  152. newLen := n*new_len + len(s[i:])
  153. replacement := make([]byte, newLen, newLen)
  154. j := 0
  155. for ; j < n*new_len; j += new_len {
  156. copy(replacement[j:j+new_len], new)
  157. }
  158. copy(replacement[j:], s[i:])
  159. return string(replacement)
  160. }
  161. // RenderCommitMessage renders commit message with XSS-safe and special links.
  162. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
  163. cleanMsg := template.HTMLEscapeString(msg)
  164. fullMessage := string(base.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  165. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  166. numLines := len(msgLines)
  167. if numLines == 0 {
  168. return template.HTML("")
  169. } else if !full {
  170. return template.HTML(msgLines[0])
  171. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  172. // First line is a header, standalone or followed by empty line
  173. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  174. if numLines >= 2 {
  175. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  176. } else {
  177. fullMessage = header
  178. }
  179. } else {
  180. // Non-standard git message, there is no header line
  181. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  182. }
  183. return template.HTML(fullMessage)
  184. }
  185. type Actioner interface {
  186. GetOpType() int
  187. GetActUserName() string
  188. GetActEmail() string
  189. GetRepoUserName() string
  190. GetRepoName() string
  191. GetRepoPath() string
  192. GetRepoLink() string
  193. GetBranch() string
  194. GetContent() string
  195. GetCreate() time.Time
  196. GetIssueInfos() []string
  197. }
  198. // ActionIcon accepts a int that represents action operation type
  199. // and returns a icon class name.
  200. func ActionIcon(opType int) string {
  201. switch opType {
  202. case 1, 8: // Create, transfer repository
  203. return "repo"
  204. case 5, 9: // Commit repository
  205. return "git-commit"
  206. case 6: // Create issue
  207. return "issue-opened"
  208. case 7: // New pull request
  209. return "git-pull-request"
  210. case 10: // Comment issue
  211. return "comment"
  212. case 11: // Merge pull request
  213. return "git-merge"
  214. default:
  215. return "invalid type"
  216. }
  217. }
  218. func ActionContent2Commits(act Actioner) *models.PushCommits {
  219. push := models.NewPushCommits()
  220. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  221. return nil
  222. }
  223. return push
  224. }
  225. func DiffTypeToStr(diffType int) string {
  226. diffTypes := map[int]string{
  227. 1: "add", 2: "modify", 3: "del", 4: "rename",
  228. }
  229. return diffTypes[diffType]
  230. }
  231. func DiffLineTypeToStr(diffType int) string {
  232. switch diffType {
  233. case 2:
  234. return "add"
  235. case 3:
  236. return "del"
  237. case 4:
  238. return "tag"
  239. }
  240. return "same"
  241. }