template.go 6.6 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 base
  5. import (
  6. "container/list"
  7. "encoding/json"
  8. "fmt"
  9. "html/template"
  10. "runtime"
  11. "strings"
  12. "time"
  13. "golang.org/x/net/html/charset"
  14. "golang.org/x/text/transform"
  15. "github.com/gogits/chardet"
  16. "github.com/gogits/gogs/modules/setting"
  17. )
  18. func Safe(raw string) template.HTML {
  19. return template.HTML(raw)
  20. }
  21. func Str2html(raw string) template.HTML {
  22. return template.HTML(Sanitizer.Sanitize(raw))
  23. }
  24. func Range(l int) []int {
  25. return make([]int, l)
  26. }
  27. func List(l *list.List) chan interface{} {
  28. e := l.Front()
  29. c := make(chan interface{})
  30. go func() {
  31. for e != nil {
  32. c <- e.Value
  33. e = e.Next()
  34. }
  35. close(c)
  36. }()
  37. return c
  38. }
  39. func Sha1(str string) string {
  40. return EncodeSha1(str)
  41. }
  42. func ShortSha(sha1 string) string {
  43. if len(sha1) == 40 {
  44. return sha1[:10]
  45. }
  46. return sha1
  47. }
  48. func DetectEncoding(content []byte) (string, error) {
  49. detector := chardet.NewTextDetector()
  50. result, err := detector.DetectBest(content)
  51. if result.Charset != "UTF-8" && len(setting.AnsiCharset) > 0 {
  52. return setting.AnsiCharset, err
  53. }
  54. return result.Charset, err
  55. }
  56. func ToUtf8WithErr(content []byte) (error, string) {
  57. charsetLabel, err := DetectEncoding(content)
  58. if err != nil {
  59. return err, ""
  60. }
  61. if charsetLabel == "UTF-8" {
  62. return nil, string(content)
  63. }
  64. encoding, _ := charset.Lookup(charsetLabel)
  65. if encoding == nil {
  66. return fmt.Errorf("unknown char decoder %s", charsetLabel), string(content)
  67. }
  68. result, n, err := transform.String(encoding.NewDecoder(), string(content))
  69. // If there is an error, we concatenate the nicely decoded part and the
  70. // original left over. This way we won't loose data.
  71. if err != nil {
  72. result = result + string(content[n:])
  73. }
  74. return err, result
  75. }
  76. func ToUtf8(content string) string {
  77. _, res := ToUtf8WithErr([]byte(content))
  78. return res
  79. }
  80. // Replaces all prefixes 'old' in 's' with 'new'.
  81. func ReplaceLeft(s, old, new string) string {
  82. old_len, new_len, i, n := len(old), len(new), 0, 0
  83. for ; i < len(s) && strings.HasPrefix(s[i:], old); n += 1 {
  84. i += old_len
  85. }
  86. // simple optimization
  87. if n == 0 {
  88. return s
  89. }
  90. // allocating space for the new string
  91. newLen := n*new_len + len(s[i:])
  92. replacement := make([]byte, newLen, newLen)
  93. j := 0
  94. for ; j < n*new_len; j += new_len {
  95. copy(replacement[j:j+new_len], new)
  96. }
  97. copy(replacement[j:], s[i:])
  98. return string(replacement)
  99. }
  100. // RenderCommitMessage renders commit message with XSS-safe and special links.
  101. func RenderCommitMessage(msg, urlPrefix string) template.HTML {
  102. cleanMsg := template.HTMLEscapeString(msg)
  103. fullMessage := string(RenderIssueIndexPattern([]byte(cleanMsg), urlPrefix))
  104. msgLines := strings.Split(strings.TrimSpace(fullMessage), "\n")
  105. for i := range msgLines {
  106. msgLines[i] = ReplaceLeft(msgLines[i], " ", "&nbsp;")
  107. }
  108. fullMessage = strings.Join(msgLines, "<br>")
  109. return template.HTML(fullMessage)
  110. }
  111. var TemplateFuncs template.FuncMap = map[string]interface{}{
  112. "GoVer": func() string {
  113. return strings.Title(runtime.Version())
  114. },
  115. "AppName": func() string {
  116. return setting.AppName
  117. },
  118. "AppUrl": func() string {
  119. return setting.AppUrl
  120. },
  121. "AppSubUrl": func() string {
  122. return setting.AppSubUrl
  123. },
  124. "AppVer": func() string {
  125. return setting.AppVer
  126. },
  127. "AppDomain": func() string {
  128. return setting.Domain
  129. },
  130. "DisableGravatar": func() bool {
  131. return setting.DisableGravatar
  132. },
  133. "LoadTimes": func(startTime time.Time) string {
  134. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  135. },
  136. "AvatarLink": AvatarLink,
  137. "Safe": Safe,
  138. "Str2html": Str2html,
  139. "TimeSince": TimeSince,
  140. "RawTimeSince": RawTimeSince,
  141. "FileSize": FileSize,
  142. "Subtract": Subtract,
  143. "Add": func(a, b int) int {
  144. return a + b
  145. },
  146. "ActionIcon": ActionIcon,
  147. "DateFmtLong": func(t time.Time) string {
  148. return t.Format(time.RFC1123Z)
  149. },
  150. "DateFmtShort": func(t time.Time) string {
  151. return t.Format("Jan 02, 2006")
  152. },
  153. "List": List,
  154. "Mail2Domain": func(mail string) string {
  155. if !strings.Contains(mail, "@") {
  156. return "try.gogs.io"
  157. }
  158. return strings.SplitN(mail, "@", 2)[1]
  159. },
  160. "SubStr": func(str string, start, length int) string {
  161. if len(str) == 0 {
  162. return ""
  163. }
  164. end := start + length
  165. if length == -1 {
  166. end = len(str)
  167. }
  168. if len(str) < end {
  169. return str
  170. }
  171. return str[start:end]
  172. },
  173. "DiffTypeToStr": DiffTypeToStr,
  174. "DiffLineTypeToStr": DiffLineTypeToStr,
  175. "Sha1": Sha1,
  176. "ShortSha": ShortSha,
  177. "Md5": EncodeMd5,
  178. "ActionContent2Commits": ActionContent2Commits,
  179. "Oauth2Icon": Oauth2Icon,
  180. "Oauth2Name": Oauth2Name,
  181. "ToUtf8": ToUtf8,
  182. "EscapePound": func(str string) string {
  183. return strings.Replace(strings.Replace(str, "%", "%25", -1), "#", "%23", -1)
  184. },
  185. "RenderCommitMessage": RenderCommitMessage,
  186. }
  187. type Actioner interface {
  188. GetOpType() int
  189. GetActUserName() string
  190. GetActEmail() string
  191. GetRepoUserName() string
  192. GetRepoName() string
  193. GetRepoPath() string
  194. GetRepoLink() string
  195. GetBranch() string
  196. GetContent() string
  197. GetCreate() time.Time
  198. GetIssueInfos() []string
  199. }
  200. // ActionIcon accepts a int that represents action operation type
  201. // and returns a icon class name.
  202. func ActionIcon(opType int) string {
  203. switch opType {
  204. case 1, 8: // Create, transfer repository.
  205. return "repo"
  206. case 5, 9: // Commit repository.
  207. return "git-commit"
  208. case 6: // Create issue.
  209. return "issue-opened"
  210. case 10: // Comment issue.
  211. return "comment"
  212. default:
  213. return "invalid type"
  214. }
  215. }
  216. type PushCommit struct {
  217. Sha1 string
  218. Message string
  219. AuthorEmail string
  220. AuthorName string
  221. }
  222. type PushCommits struct {
  223. Len int
  224. Commits []*PushCommit
  225. CompareUrl string
  226. }
  227. func ActionContent2Commits(act Actioner) *PushCommits {
  228. var push *PushCommits
  229. if err := json.Unmarshal([]byte(act.GetContent()), &push); err != nil {
  230. return nil
  231. }
  232. return push
  233. }
  234. func DiffTypeToStr(diffType int) string {
  235. diffTypes := map[int]string{
  236. 1: "add", 2: "modify", 3: "del",
  237. }
  238. return diffTypes[diffType]
  239. }
  240. func DiffLineTypeToStr(diffType int) string {
  241. switch diffType {
  242. case 2:
  243. return "add"
  244. case 3:
  245. return "del"
  246. case 4:
  247. return "tag"
  248. }
  249. return "same"
  250. }
  251. func Oauth2Icon(t int) string {
  252. switch t {
  253. case 1:
  254. return "fa-github-square"
  255. case 2:
  256. return "fa-google-plus-square"
  257. case 3:
  258. return "fa-twitter-square"
  259. case 4:
  260. return "fa-qq"
  261. case 5:
  262. return "fa-weibo"
  263. }
  264. return ""
  265. }
  266. func Oauth2Name(t int) string {
  267. switch t {
  268. case 1:
  269. return "GitHub"
  270. case 2:
  271. return "Google+"
  272. case 3:
  273. return "Twitter"
  274. case 4:
  275. return "腾讯 QQ"
  276. case 5:
  277. return "Weibo"
  278. }
  279. return ""
  280. }