template.go 7.1 KB

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