template.go 7.6 KB

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