template.go 7.2 KB

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