template.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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. "github.com/microcosm-cc/bluemonday"
  16. "golang.org/x/net/html/charset"
  17. "golang.org/x/text/transform"
  18. log "gopkg.in/clog.v1"
  19. "gopkg.in/editorconfig/editorconfig-core-go.v1"
  20. "github.com/gogits/gogs/models"
  21. "github.com/gogits/gogs/modules/base"
  22. "github.com/gogits/gogs/modules/markdown"
  23. "github.com/gogits/gogs/modules/setting"
  24. )
  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. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  60. "Str2html": Str2html,
  61. "TimeSince": base.TimeSince,
  62. "RawTimeSince": base.RawTimeSince,
  63. "FileSize": base.FileSize,
  64. "Subtract": base.Subtract,
  65. "Add": func(a, b int) int {
  66. return a + b
  67. },
  68. "ActionIcon": ActionIcon,
  69. "DateFmtLong": func(t time.Time) string {
  70. return t.Format(time.RFC1123Z)
  71. },
  72. "DateFmtShort": func(t time.Time) string {
  73. return t.Format("Jan 02, 2006")
  74. },
  75. "List": List,
  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. "Join": strings.Join,
  90. "EllipsisString": base.EllipsisString,
  91. "DiffTypeToStr": DiffTypeToStr,
  92. "DiffLineTypeToStr": DiffLineTypeToStr,
  93. "Sha1": Sha1,
  94. "ShortSha": base.ShortSha,
  95. "MD5": base.EncodeMD5,
  96. "ActionContent2Commits": ActionContent2Commits,
  97. "EscapePound": EscapePound,
  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. func Safe(raw string) template.HTML {
  118. return template.HTML(raw)
  119. }
  120. func Str2html(raw string) template.HTML {
  121. return template.HTML(markdown.Sanitizer.Sanitize(raw))
  122. }
  123. func List(l *list.List) chan interface{} {
  124. e := l.Front()
  125. c := make(chan interface{})
  126. go func() {
  127. for e != nil {
  128. c <- e.Value
  129. e = e.Next()
  130. }
  131. close(c)
  132. }()
  133. return c
  134. }
  135. func Sha1(str string) string {
  136. return base.EncodeSha1(str)
  137. }
  138. func ToUTF8WithErr(content []byte) (error, string) {
  139. charsetLabel, err := base.DetectEncoding(content)
  140. if err != nil {
  141. return err, ""
  142. } else if charsetLabel == "UTF-8" {
  143. return nil, string(content)
  144. }
  145. encoding, _ := charset.Lookup(charsetLabel)
  146. if encoding == nil {
  147. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  148. }
  149. // If there is an error, we concatenate the nicely decoded part and the
  150. // original left over. This way we won't loose data.
  151. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  152. if err != nil {
  153. result = result + string(content[n:])
  154. }
  155. return err, result
  156. }
  157. func ToUTF8(content string) string {
  158. _, res := ToUTF8WithErr([]byte(content))
  159. return res
  160. }
  161. // Replaces all prefixes 'old' in 's' with 'new'.
  162. func ReplaceLeft(s, old, new string) string {
  163. old_len, new_len, i, n := len(old), len(new), 0, 0
  164. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  165. i += old_len
  166. }
  167. // simple optimization
  168. if n == 0 {
  169. return s
  170. }
  171. // allocating space for the new string
  172. newLen := n*new_len + len(s[i:])
  173. replacement := make([]byte, newLen, newLen)
  174. j := 0
  175. for ; j < n*new_len; j += new_len {
  176. copy(replacement[j:j+new_len], new)
  177. }
  178. copy(replacement[j:], s[i:])
  179. return string(replacement)
  180. }
  181. // RenderCommitMessage renders commit message with XSS-safe and special links.
  182. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) template.HTML {
  183. cleanMsg := template.HTMLEscapeString(msg)
  184. fullMessage := string(markdown.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  185. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  186. numLines := len(msgLines)
  187. if numLines == 0 {
  188. return template.HTML("")
  189. } else if !full {
  190. return template.HTML(msgLines[0])
  191. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  192. // First line is a header, standalone or followed by empty line
  193. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  194. if numLines >= 2 {
  195. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  196. } else {
  197. fullMessage = header
  198. }
  199. } else {
  200. // Non-standard git message, there is no header line
  201. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  202. }
  203. return template.HTML(fullMessage)
  204. }
  205. type Actioner interface {
  206. GetOpType() int
  207. GetActUserName() string
  208. GetRepoUserName() string
  209. GetRepoName() string
  210. GetRepoPath() string
  211. GetRepoLink() string
  212. GetBranch() string
  213. GetContent() string
  214. GetCreate() time.Time
  215. GetIssueInfos() []string
  216. }
  217. // ActionIcon accepts a int that represents action operation type
  218. // and returns a icon class name.
  219. func ActionIcon(opType int) string {
  220. switch opType {
  221. case 1, 8: // Create and transfer repository
  222. return "repo"
  223. case 5: // Commit repository
  224. return "git-commit"
  225. case 6: // Create issue
  226. return "issue-opened"
  227. case 7: // New pull request
  228. return "git-pull-request"
  229. case 9: // Push tag
  230. return "tag"
  231. case 10: // Comment issue
  232. return "comment-discussion"
  233. case 11: // Merge pull request
  234. return "git-merge"
  235. case 12, 14: // Close issue or pull request
  236. return "issue-closed"
  237. case 13, 15: // Reopen issue or pull request
  238. return "issue-reopened"
  239. case 16: // Create branch
  240. return "git-branch"
  241. case 17, 18: // Delete branch or tag
  242. return "alert"
  243. case 19: // Fork a repository
  244. return "repo-forked"
  245. default:
  246. return "invalid type"
  247. }
  248. }
  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. func EscapePound(str string) string {
  257. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  258. }
  259. func DiffTypeToStr(diffType int) string {
  260. diffTypes := map[int]string{
  261. 1: "add", 2: "modify", 3: "del", 4: "rename",
  262. }
  263. return diffTypes[diffType]
  264. }
  265. func DiffLineTypeToStr(diffType int) string {
  266. switch diffType {
  267. case 2:
  268. return "add"
  269. case 3:
  270. return "del"
  271. case 4:
  272. return "tag"
  273. }
  274. return "same"
  275. }