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