template.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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. "EscapePound": func(str string) string {
  94. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20").Replace(str)
  95. },
  96. "RenderCommitMessage": RenderCommitMessage,
  97. "ThemeColorMetaTag": func() string {
  98. return setting.UI.ThemeColorMetaTag
  99. },
  100. }}
  101. }
  102. func Safe(raw string) template.HTML {
  103. return template.HTML(raw)
  104. }
  105. func Str2html(raw string) template.HTML {
  106. return template.HTML(markdown.Sanitizer.Sanitize(raw))
  107. }
  108. func List(l *list.List) chan interface{} {
  109. e := l.Front()
  110. c := make(chan interface{})
  111. go func() {
  112. for e != nil {
  113. c <- e.Value
  114. e = e.Next()
  115. }
  116. close(c)
  117. }()
  118. return c
  119. }
  120. func Sha1(str string) string {
  121. return base.EncodeSha1(str)
  122. }
  123. func ToUTF8WithErr(content []byte) (error, string) {
  124. charsetLabel, err := base.DetectEncoding(content)
  125. if err != nil {
  126. return err, ""
  127. } else if charsetLabel == "UTF-8" {
  128. return nil, string(content)
  129. }
  130. encoding, _ := charset.Lookup(charsetLabel)
  131. if encoding == nil {
  132. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  133. }
  134. // If there is an error, we concatenate the nicely decoded part and the
  135. // original left over. This way we won't loose data.
  136. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  137. if err != nil {
  138. result = result + string(content[n:])
  139. }
  140. return err, result
  141. }
  142. func ToUTF8(content string) string {
  143. _, res := ToUTF8WithErr([]byte(content))
  144. return res
  145. }
  146. // Replaces all prefixes 'old' in 's' with 'new'.
  147. func ReplaceLeft(s, old, new string) string {
  148. old_len, new_len, i, n := len(old), len(new), 0, 0
  149. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  150. i += old_len
  151. }
  152. // simple optimization
  153. if n == 0 {
  154. return s
  155. }
  156. // allocating space for the new string
  157. newLen := n*new_len + len(s[i:])
  158. replacement := make([]byte, newLen, newLen)
  159. j := 0
  160. for ; j < n*new_len; j += new_len {
  161. copy(replacement[j:j+new_len], new)
  162. }
  163. copy(replacement[j:], s[i:])
  164. return string(replacement)
  165. }
  166. // RenderCommitMessage renders commit message with XSS-safe and special links.
  167. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
  168. cleanMsg := template.HTMLEscapeString(msg)
  169. fullMessage := string(markdown.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  170. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  171. numLines := len(msgLines)
  172. if numLines == 0 {
  173. return template.HTML("")
  174. } else if !full {
  175. return template.HTML(msgLines[0])
  176. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  177. // First line is a header, standalone or followed by empty line
  178. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  179. if numLines >= 2 {
  180. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  181. } else {
  182. fullMessage = header
  183. }
  184. } else {
  185. // Non-standard git message, there is no header line
  186. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  187. }
  188. return template.HTML(fullMessage)
  189. }
  190. type Actioner interface {
  191. GetOpType() int
  192. GetActUserName() string
  193. GetActEmail() string
  194. GetRepoUserName() string
  195. GetRepoName() string
  196. GetRepoPath() string
  197. GetRepoLink() string
  198. GetBranch() string
  199. GetContent() string
  200. GetCreate() time.Time
  201. GetIssueInfos() []string
  202. }
  203. // ActionIcon accepts a int that represents action operation type
  204. // and returns a icon class name.
  205. func ActionIcon(opType int) string {
  206. switch opType {
  207. case 1, 8: // Create and transfer repository
  208. return "repo"
  209. case 5, 9: // Commit repository
  210. return "git-commit"
  211. case 6: // Create issue
  212. return "issue-opened"
  213. case 7: // New pull request
  214. return "git-pull-request"
  215. case 10: // Comment issue
  216. return "comment-discussion"
  217. case 11: // Merge pull request
  218. return "git-merge"
  219. case 12, 14: // Close issue or pull request
  220. return "issue-closed"
  221. case 13, 15: // Reopen issue or pull request
  222. return "issue-reopened"
  223. default:
  224. return "invalid type"
  225. }
  226. }
  227. func ActionContent2Commits(act Actioner) *models.PushCommits {
  228. push := models.NewPushCommits()
  229. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  230. log.Error(4, "json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  231. }
  232. return push
  233. }
  234. func DiffTypeToStr(diffType int) string {
  235. diffTypes := map[int]string{
  236. 1: "add", 2: "modify", 3: "del", 4: "rename",
  237. }
  238. return diffTypes[diffType]
  239. }
  240. func DiffLineTypeToStr(diffType int) string {
  241. switch diffType {
  242. case 2:
  243. return "add"
  244. case 3:
  245. return "del"
  246. case 4:
  247. return "tag"
  248. }
  249. return "same"
  250. }