template.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. "fmt"
  8. "html/template"
  9. "mime"
  10. "path/filepath"
  11. "runtime"
  12. "strings"
  13. "time"
  14. "github.com/json-iterator/go"
  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. "gogs.io/gogs/internal/db"
  21. "gogs.io/gogs/internal/markup"
  22. "gogs.io/gogs/internal/setting"
  23. "gogs.io/gogs/internal/tool"
  24. )
  25. // TODO: only initialize map once and save to a local variable to reduce copies.
  26. func NewFuncMap() []template.FuncMap {
  27. return []template.FuncMap{map[string]interface{}{
  28. "GoVer": func() string {
  29. return strings.Title(runtime.Version())
  30. },
  31. "Year": func() int {
  32. return time.Now().Year()
  33. },
  34. "UseHTTPS": func() bool {
  35. return strings.HasPrefix(setting.AppURL, "https")
  36. },
  37. "AppName": func() string {
  38. return setting.AppName
  39. },
  40. "AppSubURL": func() string {
  41. return setting.AppSubURL
  42. },
  43. "AppURL": func() string {
  44. return setting.AppURL
  45. },
  46. "AppVer": func() string {
  47. return setting.AppVer
  48. },
  49. "AppDomain": func() string {
  50. return setting.Domain
  51. },
  52. "DisableGravatar": func() bool {
  53. return setting.DisableGravatar
  54. },
  55. "ShowFooterTemplateLoadTime": func() bool {
  56. return setting.ShowFooterTemplateLoadTime
  57. },
  58. "LoadTimes": func(startTime time.Time) string {
  59. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  60. },
  61. "AvatarLink": tool.AvatarLink,
  62. "AppendAvatarSize": tool.AppendAvatarSize,
  63. "Safe": Safe,
  64. "Sanitize": bluemonday.UGCPolicy().Sanitize,
  65. "Str2HTML": Str2HTML,
  66. "NewLine2br": NewLine2br,
  67. "TimeSince": tool.TimeSince,
  68. "RawTimeSince": tool.RawTimeSince,
  69. "FileSize": tool.FileSize,
  70. "Subtract": tool.Subtract,
  71. "Add": func(a, b int) int {
  72. return a + b
  73. },
  74. "ActionIcon": ActionIcon,
  75. "DateFmtLong": func(t time.Time) string {
  76. return t.Format(time.RFC1123Z)
  77. },
  78. "DateFmtShort": func(t time.Time) string {
  79. return t.Format("Jan 02, 2006")
  80. },
  81. "List": List,
  82. "SubStr": func(str string, start, length int) string {
  83. if len(str) == 0 {
  84. return ""
  85. }
  86. end := start + length
  87. if length == -1 {
  88. end = len(str)
  89. }
  90. if len(str) < end {
  91. return str
  92. }
  93. return str[start:end]
  94. },
  95. "Join": strings.Join,
  96. "EllipsisString": tool.EllipsisString,
  97. "DiffTypeToStr": DiffTypeToStr,
  98. "DiffLineTypeToStr": DiffLineTypeToStr,
  99. "Sha1": Sha1,
  100. "ShortSHA1": tool.ShortSHA1,
  101. "MD5": tool.MD5,
  102. "ActionContent2Commits": ActionContent2Commits,
  103. "EscapePound": EscapePound,
  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. }}
  122. }
  123. func Safe(raw string) template.HTML {
  124. return template.HTML(raw)
  125. }
  126. func Str2HTML(raw string) template.HTML {
  127. return template.HTML(markup.Sanitize(raw))
  128. }
  129. // NewLine2br simply replaces "\n" to "<br>".
  130. func NewLine2br(raw string) string {
  131. return strings.Replace(raw, "\n", "<br>", -1)
  132. }
  133. func List(l *list.List) chan interface{} {
  134. e := l.Front()
  135. c := make(chan interface{})
  136. go func() {
  137. for e != nil {
  138. c <- e.Value
  139. e = e.Next()
  140. }
  141. close(c)
  142. }()
  143. return c
  144. }
  145. func Sha1(str string) string {
  146. return tool.SHA1(str)
  147. }
  148. func ToUTF8WithErr(content []byte) (error, string) {
  149. charsetLabel, err := tool.DetectEncoding(content)
  150. if err != nil {
  151. return err, ""
  152. } else if charsetLabel == "UTF-8" {
  153. return nil, string(content)
  154. }
  155. encoding, _ := charset.Lookup(charsetLabel)
  156. if encoding == nil {
  157. return fmt.Errorf("Unknown encoding: %s", charsetLabel), string(content)
  158. }
  159. // If there is an error, we concatenate the nicely decoded part and the
  160. // original left over. This way we won't loose data.
  161. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  162. if err != nil {
  163. result = result + string(content[n:])
  164. }
  165. return err, result
  166. }
  167. // FIXME: Unused function
  168. func ToUTF8(content string) string {
  169. _, res := ToUTF8WithErr([]byte(content))
  170. return res
  171. }
  172. // Replaces all prefixes 'old' in 's' with 'new'.
  173. // FIXME: Unused function
  174. func ReplaceLeft(s, old, new string) string {
  175. old_len, new_len, i, n := len(old), len(new), 0, 0
  176. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  177. i += old_len
  178. }
  179. // simple optimization
  180. if n == 0 {
  181. return s
  182. }
  183. // allocating space for the new string
  184. newLen := n*new_len + len(s[i:])
  185. replacement := make([]byte, newLen, newLen)
  186. j := 0
  187. for ; j < n*new_len; j += new_len {
  188. copy(replacement[j:j+new_len], new)
  189. }
  190. copy(replacement[j:], s[i:])
  191. return string(replacement)
  192. }
  193. // RenderCommitMessage renders commit message with special links.
  194. func RenderCommitMessage(full bool, msg, urlPrefix string, metas map[string]string) string {
  195. cleanMsg := template.HTMLEscapeString(msg)
  196. fullMessage := string(markup.RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix, metas))
  197. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  198. numLines := len(msgLines)
  199. if numLines == 0 {
  200. return ""
  201. } else if !full {
  202. return msgLines[0]
  203. } else if numLines == 1 || (numLines >= 2 && len(msgLines[1]) == 0) {
  204. // First line is a header, standalone or followed by empty line
  205. header := fmt.Sprintf("<h3>%s</h3>", msgLines[0])
  206. if numLines >= 2 {
  207. fullMessage = header + fmt.Sprintf("\n<pre>%s</pre>", strings.Join(msgLines[2:], "\n"))
  208. } else {
  209. fullMessage = header
  210. }
  211. } else {
  212. // Non-standard git message, there is no header line
  213. fullMessage = fmt.Sprintf("<h4>%s</h4>", strings.Join(msgLines, "<br>"))
  214. }
  215. return fullMessage
  216. }
  217. type Actioner interface {
  218. GetOpType() int
  219. GetActUserName() string
  220. GetRepoUserName() string
  221. GetRepoName() string
  222. GetRepoPath() string
  223. GetRepoLink() string
  224. GetBranch() string
  225. GetContent() string
  226. GetCreate() time.Time
  227. GetIssueInfos() []string
  228. }
  229. // ActionIcon accepts a int that represents action operation type
  230. // and returns a icon class name.
  231. func ActionIcon(opType int) string {
  232. switch opType {
  233. case 1, 8: // Create and transfer repository
  234. return "repo"
  235. case 5: // Commit repository
  236. return "git-commit"
  237. case 6: // Create issue
  238. return "issue-opened"
  239. case 7: // New pull request
  240. return "git-pull-request"
  241. case 9: // Push tag
  242. return "tag"
  243. case 10: // Comment issue
  244. return "comment-discussion"
  245. case 11: // Merge pull request
  246. return "git-merge"
  247. case 12, 14: // Close issue or pull request
  248. return "issue-closed"
  249. case 13, 15: // Reopen issue or pull request
  250. return "issue-reopened"
  251. case 16: // Create branch
  252. return "git-branch"
  253. case 17, 18: // Delete branch or tag
  254. return "alert"
  255. case 19: // Fork a repository
  256. return "repo-forked"
  257. case 20, 21, 22: // Mirror sync
  258. return "repo-clone"
  259. default:
  260. return "invalid type"
  261. }
  262. }
  263. func ActionContent2Commits(act Actioner) *db.PushCommits {
  264. push := db.NewPushCommits()
  265. if err := jsoniter.Unmarshal([]byte(act.GetContent()), push); err != nil {
  266. log.Error(4, "Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  267. }
  268. return push
  269. }
  270. func EscapePound(str string) string {
  271. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  272. }
  273. func DiffTypeToStr(diffType int) string {
  274. diffTypes := map[int]string{
  275. 1: "add", 2: "modify", 3: "del", 4: "rename",
  276. }
  277. return diffTypes[diffType]
  278. }
  279. func DiffLineTypeToStr(diffType int) string {
  280. switch diffType {
  281. case 2:
  282. return "add"
  283. case 3:
  284. return "del"
  285. case 4:
  286. return "tag"
  287. }
  288. return "same"
  289. }