You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

template.go 7.7KB

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