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.

324 lines
8.3 KiB

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