template.go 7.6 KB

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