選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

helper.go 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  1. // Copyright 2018 The Gitea Authors. All rights reserved.
  2. // Copyright 2014 The Gogs Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package templates
  6. import (
  7. "bytes"
  8. "container/list"
  9. "encoding/json"
  10. "errors"
  11. "fmt"
  12. "html"
  13. "html/template"
  14. "mime"
  15. "net/url"
  16. "path/filepath"
  17. "reflect"
  18. "regexp"
  19. "runtime"
  20. "strings"
  21. texttmpl "text/template"
  22. "time"
  23. "unicode"
  24. "code.gitea.io/gitea/models"
  25. "code.gitea.io/gitea/modules/base"
  26. "code.gitea.io/gitea/modules/emoji"
  27. "code.gitea.io/gitea/modules/log"
  28. "code.gitea.io/gitea/modules/markup"
  29. "code.gitea.io/gitea/modules/repository"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/svg"
  32. "code.gitea.io/gitea/modules/timeutil"
  33. "code.gitea.io/gitea/modules/util"
  34. "code.gitea.io/gitea/services/gitdiff"
  35. mirror_service "code.gitea.io/gitea/services/mirror"
  36. "github.com/editorconfig/editorconfig-core-go/v2"
  37. jsoniter "github.com/json-iterator/go"
  38. )
  39. // Used from static.go && dynamic.go
  40. var mailSubjectSplit = regexp.MustCompile(`(?m)^-{3,}[\s]*$`)
  41. // NewFuncMap returns functions for injecting to templates
  42. func NewFuncMap() []template.FuncMap {
  43. jsonED := jsoniter.ConfigCompatibleWithStandardLibrary
  44. return []template.FuncMap{map[string]interface{}{
  45. "GoVer": func() string {
  46. return strings.Title(runtime.Version())
  47. },
  48. "UseHTTPS": func() bool {
  49. return strings.HasPrefix(setting.AppURL, "https")
  50. },
  51. "AppName": func() string {
  52. return setting.AppName
  53. },
  54. "AppSubUrl": func() string {
  55. return setting.AppSubURL
  56. },
  57. "AssetUrlPrefix": func() string {
  58. return setting.StaticURLPrefix + "/assets"
  59. },
  60. "AppUrl": func() string {
  61. return setting.AppURL
  62. },
  63. "AppVer": func() string {
  64. return setting.AppVer
  65. },
  66. "AppBuiltWith": func() string {
  67. return setting.AppBuiltWith
  68. },
  69. "AppDomain": func() string {
  70. return setting.Domain
  71. },
  72. "DisableGravatar": func() bool {
  73. return setting.DisableGravatar
  74. },
  75. "DefaultShowFullName": func() bool {
  76. return setting.UI.DefaultShowFullName
  77. },
  78. "ShowFooterTemplateLoadTime": func() bool {
  79. return setting.ShowFooterTemplateLoadTime
  80. },
  81. "LoadTimes": func(startTime time.Time) string {
  82. return fmt.Sprint(time.Since(startTime).Nanoseconds()/1e6) + "ms"
  83. },
  84. "AllowedReactions": func() []string {
  85. return setting.UI.Reactions
  86. },
  87. "Safe": Safe,
  88. "SafeJS": SafeJS,
  89. "JSEscape": JSEscape,
  90. "Str2html": Str2html,
  91. "TimeSince": timeutil.TimeSince,
  92. "TimeSinceUnix": timeutil.TimeSinceUnix,
  93. "RawTimeSince": timeutil.RawTimeSince,
  94. "FileSize": base.FileSize,
  95. "PrettyNumber": base.PrettyNumber,
  96. "Subtract": base.Subtract,
  97. "EntryIcon": base.EntryIcon,
  98. "MigrationIcon": MigrationIcon,
  99. "Add": func(a ...int) int {
  100. sum := 0
  101. for _, val := range a {
  102. sum += val
  103. }
  104. return sum
  105. },
  106. "Mul": func(a ...int) int {
  107. sum := 1
  108. for _, val := range a {
  109. sum *= val
  110. }
  111. return sum
  112. },
  113. "ActionIcon": ActionIcon,
  114. "DateFmtLong": func(t time.Time) string {
  115. return t.Format(time.RFC1123Z)
  116. },
  117. "DateFmtShort": func(t time.Time) string {
  118. return t.Format("Jan 02, 2006")
  119. },
  120. "SizeFmt": base.FileSize,
  121. "CountFmt": base.FormatNumberSI,
  122. "List": List,
  123. "SubStr": func(str string, start, length int) string {
  124. if len(str) == 0 {
  125. return ""
  126. }
  127. end := start + length
  128. if length == -1 {
  129. end = len(str)
  130. }
  131. if len(str) < end {
  132. return str
  133. }
  134. return str[start:end]
  135. },
  136. "EllipsisString": base.EllipsisString,
  137. "DiffTypeToStr": DiffTypeToStr,
  138. "DiffLineTypeToStr": DiffLineTypeToStr,
  139. "Sha1": Sha1,
  140. "ShortSha": base.ShortSha,
  141. "MD5": base.EncodeMD5,
  142. "ActionContent2Commits": ActionContent2Commits,
  143. "PathEscape": url.PathEscape,
  144. "EscapePound": func(str string) string {
  145. return strings.NewReplacer("%", "%25", "#", "%23", " ", "%20", "?", "%3F").Replace(str)
  146. },
  147. "PathEscapeSegments": util.PathEscapeSegments,
  148. "URLJoin": util.URLJoin,
  149. "RenderCommitMessage": RenderCommitMessage,
  150. "RenderCommitMessageLink": RenderCommitMessageLink,
  151. "RenderCommitMessageLinkSubject": RenderCommitMessageLinkSubject,
  152. "RenderCommitBody": RenderCommitBody,
  153. "RenderIssueTitle": RenderIssueTitle,
  154. "RenderEmoji": RenderEmoji,
  155. "RenderEmojiPlain": emoji.ReplaceAliases,
  156. "ReactionToEmoji": ReactionToEmoji,
  157. "RenderNote": RenderNote,
  158. "IsMultilineCommitMessage": IsMultilineCommitMessage,
  159. "ThemeColorMetaTag": func() string {
  160. return setting.UI.ThemeColorMetaTag
  161. },
  162. "MetaAuthor": func() string {
  163. return setting.UI.Meta.Author
  164. },
  165. "MetaDescription": func() string {
  166. return setting.UI.Meta.Description
  167. },
  168. "MetaKeywords": func() string {
  169. return setting.UI.Meta.Keywords
  170. },
  171. "UseServiceWorker": func() bool {
  172. return setting.UI.UseServiceWorker
  173. },
  174. "EnableTimetracking": func() bool {
  175. return setting.Service.EnableTimetracking
  176. },
  177. "FilenameIsImage": func(filename string) bool {
  178. mimeType := mime.TypeByExtension(filepath.Ext(filename))
  179. return strings.HasPrefix(mimeType, "image/")
  180. },
  181. "TabSizeClass": func(ec interface{}, filename string) string {
  182. var (
  183. value *editorconfig.Editorconfig
  184. ok bool
  185. )
  186. if ec != nil {
  187. if value, ok = ec.(*editorconfig.Editorconfig); !ok || value == nil {
  188. return "tab-size-8"
  189. }
  190. def, err := value.GetDefinitionForFilename(filename)
  191. if err != nil {
  192. log.Error("tab size class: getting definition for filename: %v", err)
  193. return "tab-size-8"
  194. }
  195. if def.TabWidth > 0 {
  196. return fmt.Sprintf("tab-size-%d", def.TabWidth)
  197. }
  198. }
  199. return "tab-size-8"
  200. },
  201. "SubJumpablePath": func(str string) []string {
  202. var path []string
  203. index := strings.LastIndex(str, "/")
  204. if index != -1 && index != len(str) {
  205. path = append(path, str[0:index+1], str[index+1:])
  206. } else {
  207. path = append(path, str)
  208. }
  209. return path
  210. },
  211. "DiffStatsWidth": func(adds int, dels int) string {
  212. return fmt.Sprintf("%f", float64(adds)/(float64(adds)+float64(dels))*100)
  213. },
  214. "Json": func(in interface{}) string {
  215. out, err := jsonED.Marshal(in)
  216. if err != nil {
  217. return ""
  218. }
  219. return string(out)
  220. },
  221. "JsonPrettyPrint": func(in string) string {
  222. var out bytes.Buffer
  223. err := json.Indent(&out, []byte(in), "", " ")
  224. if err != nil {
  225. return ""
  226. }
  227. return out.String()
  228. },
  229. "DisableGitHooks": func() bool {
  230. return setting.DisableGitHooks
  231. },
  232. "DisableWebhooks": func() bool {
  233. return setting.DisableWebhooks
  234. },
  235. "DisableImportLocal": func() bool {
  236. return !setting.ImportLocalPaths
  237. },
  238. "TrN": TrN,
  239. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  240. if len(values)%2 != 0 {
  241. return nil, errors.New("invalid dict call")
  242. }
  243. dict := make(map[string]interface{}, len(values)/2)
  244. for i := 0; i < len(values); i += 2 {
  245. key, ok := values[i].(string)
  246. if !ok {
  247. return nil, errors.New("dict keys must be strings")
  248. }
  249. dict[key] = values[i+1]
  250. }
  251. return dict, nil
  252. },
  253. "Printf": fmt.Sprintf,
  254. "Escape": Escape,
  255. "Sec2Time": models.SecToTime,
  256. "ParseDeadline": func(deadline string) []string {
  257. return strings.Split(deadline, "|")
  258. },
  259. "DefaultTheme": func() string {
  260. return setting.UI.DefaultTheme
  261. },
  262. // pass key-value pairs to a partial template which receives them as a dict
  263. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  264. if len(values) == 0 {
  265. return nil, errors.New("invalid dict call")
  266. }
  267. dict := make(map[string]interface{})
  268. return util.MergeInto(dict, values...)
  269. },
  270. /* like dict but merge key-value pairs into the first dict and return it */
  271. "mergeinto": func(root map[string]interface{}, values ...interface{}) (map[string]interface{}, error) {
  272. if len(values) == 0 {
  273. return nil, errors.New("invalid mergeinto call")
  274. }
  275. dict := make(map[string]interface{})
  276. for key, value := range root {
  277. dict[key] = value
  278. }
  279. return util.MergeInto(dict, values...)
  280. },
  281. "percentage": func(n int, values ...int) float32 {
  282. var sum = 0
  283. for i := 0; i < len(values); i++ {
  284. sum += values[i]
  285. }
  286. return float32(n) * 100 / float32(sum)
  287. },
  288. "CommentMustAsDiff": gitdiff.CommentMustAsDiff,
  289. "MirrorAddress": mirror_service.Address,
  290. "MirrorFullAddress": mirror_service.AddressNoCredentials,
  291. "MirrorUserName": mirror_service.Username,
  292. "MirrorPassword": mirror_service.Password,
  293. "CommitType": func(commit interface{}) string {
  294. switch commit.(type) {
  295. case models.SignCommitWithStatuses:
  296. return "SignCommitWithStatuses"
  297. case models.SignCommit:
  298. return "SignCommit"
  299. case models.UserCommit:
  300. return "UserCommit"
  301. default:
  302. return ""
  303. }
  304. },
  305. "NotificationSettings": func() map[string]interface{} {
  306. return map[string]interface{}{
  307. "MinTimeout": int(setting.UI.Notification.MinTimeout / time.Millisecond),
  308. "TimeoutStep": int(setting.UI.Notification.TimeoutStep / time.Millisecond),
  309. "MaxTimeout": int(setting.UI.Notification.MaxTimeout / time.Millisecond),
  310. "EventSourceUpdateTime": int(setting.UI.Notification.EventSourceUpdateTime / time.Millisecond),
  311. }
  312. },
  313. "containGeneric": func(arr interface{}, v interface{}) bool {
  314. arrV := reflect.ValueOf(arr)
  315. if arrV.Kind() == reflect.String && reflect.ValueOf(v).Kind() == reflect.String {
  316. return strings.Contains(arr.(string), v.(string))
  317. }
  318. if arrV.Kind() == reflect.Slice {
  319. for i := 0; i < arrV.Len(); i++ {
  320. iV := arrV.Index(i)
  321. if !iV.CanInterface() {
  322. continue
  323. }
  324. if iV.Interface() == v {
  325. return true
  326. }
  327. }
  328. }
  329. return false
  330. },
  331. "contain": func(s []int64, id int64) bool {
  332. for i := 0; i < len(s); i++ {
  333. if s[i] == id {
  334. return true
  335. }
  336. }
  337. return false
  338. },
  339. "svg": SVG,
  340. "avatar": Avatar,
  341. "avatarHTML": AvatarHTML,
  342. "avatarByAction": AvatarByAction,
  343. "avatarByEmail": AvatarByEmail,
  344. "repoAvatar": RepoAvatar,
  345. "SortArrow": func(normSort, revSort, urlSort string, isDefault bool) template.HTML {
  346. // if needed
  347. if len(normSort) == 0 || len(urlSort) == 0 {
  348. return ""
  349. }
  350. if len(urlSort) == 0 && isDefault {
  351. // if sort is sorted as default add arrow tho this table header
  352. if isDefault {
  353. return SVG("octicon-triangle-down", 16)
  354. }
  355. } else {
  356. // if sort arg is in url test if it correlates with column header sort arguments
  357. if urlSort == normSort {
  358. // the table is sorted with this header normal
  359. return SVG("octicon-triangle-down", 16)
  360. } else if urlSort == revSort {
  361. // the table is sorted with this header reverse
  362. return SVG("octicon-triangle-up", 16)
  363. }
  364. }
  365. // the table is NOT sorted with this header
  366. return ""
  367. },
  368. "RenderLabels": func(labels []*models.Label) template.HTML {
  369. html := `<span class="labels-list">`
  370. for _, label := range labels {
  371. // Protect against nil value in labels - shouldn't happen but would cause a panic if so
  372. if label == nil {
  373. continue
  374. }
  375. html += fmt.Sprintf("<div class='ui label' style='color: %s; background-color: %s'>%s</div> ",
  376. label.ForegroundColor(), label.Color, RenderEmoji(label.Name))
  377. }
  378. html += "</span>"
  379. return template.HTML(html)
  380. },
  381. }}
  382. }
  383. // NewTextFuncMap returns functions for injecting to text templates
  384. // It's a subset of those used for HTML and other templates
  385. func NewTextFuncMap() []texttmpl.FuncMap {
  386. return []texttmpl.FuncMap{map[string]interface{}{
  387. "GoVer": func() string {
  388. return strings.Title(runtime.Version())
  389. },
  390. "AppName": func() string {
  391. return setting.AppName
  392. },
  393. "AppSubUrl": func() string {
  394. return setting.AppSubURL
  395. },
  396. "AppUrl": func() string {
  397. return setting.AppURL
  398. },
  399. "AppVer": func() string {
  400. return setting.AppVer
  401. },
  402. "AppBuiltWith": func() string {
  403. return setting.AppBuiltWith
  404. },
  405. "AppDomain": func() string {
  406. return setting.Domain
  407. },
  408. "TimeSince": timeutil.TimeSince,
  409. "TimeSinceUnix": timeutil.TimeSinceUnix,
  410. "RawTimeSince": timeutil.RawTimeSince,
  411. "DateFmtLong": func(t time.Time) string {
  412. return t.Format(time.RFC1123Z)
  413. },
  414. "DateFmtShort": func(t time.Time) string {
  415. return t.Format("Jan 02, 2006")
  416. },
  417. "List": List,
  418. "SubStr": func(str string, start, length int) string {
  419. if len(str) == 0 {
  420. return ""
  421. }
  422. end := start + length
  423. if length == -1 {
  424. end = len(str)
  425. }
  426. if len(str) < end {
  427. return str
  428. }
  429. return str[start:end]
  430. },
  431. "EllipsisString": base.EllipsisString,
  432. "URLJoin": util.URLJoin,
  433. "Dict": func(values ...interface{}) (map[string]interface{}, error) {
  434. if len(values)%2 != 0 {
  435. return nil, errors.New("invalid dict call")
  436. }
  437. dict := make(map[string]interface{}, len(values)/2)
  438. for i := 0; i < len(values); i += 2 {
  439. key, ok := values[i].(string)
  440. if !ok {
  441. return nil, errors.New("dict keys must be strings")
  442. }
  443. dict[key] = values[i+1]
  444. }
  445. return dict, nil
  446. },
  447. "Printf": fmt.Sprintf,
  448. "Escape": Escape,
  449. "Sec2Time": models.SecToTime,
  450. "ParseDeadline": func(deadline string) []string {
  451. return strings.Split(deadline, "|")
  452. },
  453. "dict": func(values ...interface{}) (map[string]interface{}, error) {
  454. if len(values) == 0 {
  455. return nil, errors.New("invalid dict call")
  456. }
  457. dict := make(map[string]interface{})
  458. for i := 0; i < len(values); i++ {
  459. switch key := values[i].(type) {
  460. case string:
  461. i++
  462. if i == len(values) {
  463. return nil, errors.New("specify the key for non array values")
  464. }
  465. dict[key] = values[i]
  466. case map[string]interface{}:
  467. m := values[i].(map[string]interface{})
  468. for i, v := range m {
  469. dict[i] = v
  470. }
  471. default:
  472. return nil, errors.New("dict values must be maps")
  473. }
  474. }
  475. return dict, nil
  476. },
  477. "percentage": func(n int, values ...int) float32 {
  478. var sum = 0
  479. for i := 0; i < len(values); i++ {
  480. sum += values[i]
  481. }
  482. return float32(n) * 100 / float32(sum)
  483. },
  484. "Add": func(a ...int) int {
  485. sum := 0
  486. for _, val := range a {
  487. sum += val
  488. }
  489. return sum
  490. },
  491. "Mul": func(a ...int) int {
  492. sum := 1
  493. for _, val := range a {
  494. sum *= val
  495. }
  496. return sum
  497. },
  498. }}
  499. }
  500. var widthRe = regexp.MustCompile(`width="[0-9]+?"`)
  501. var heightRe = regexp.MustCompile(`height="[0-9]+?"`)
  502. func parseOthers(defaultSize int, defaultClass string, others ...interface{}) (int, string) {
  503. size := defaultSize
  504. if len(others) > 0 && others[0].(int) != 0 {
  505. size = others[0].(int)
  506. }
  507. class := defaultClass
  508. if len(others) > 1 && others[1].(string) != "" {
  509. if defaultClass == "" {
  510. class = others[1].(string)
  511. } else {
  512. class = defaultClass + " " + others[1].(string)
  513. }
  514. }
  515. return size, class
  516. }
  517. // AvatarHTML creates the HTML for an avatar
  518. func AvatarHTML(src string, size int, class string, name string) template.HTML {
  519. sizeStr := fmt.Sprintf(`%d`, size)
  520. if name == "" {
  521. name = "avatar"
  522. }
  523. return template.HTML(`<img class="` + class + `" src="` + src + `" title="` + html.EscapeString(name) + `" width="` + sizeStr + `" height="` + sizeStr + `"/>`)
  524. }
  525. // SVG render icons - arguments icon name (string), size (int), class (string)
  526. func SVG(icon string, others ...interface{}) template.HTML {
  527. size, class := parseOthers(16, "", others...)
  528. if svgStr, ok := svg.SVGs[icon]; ok {
  529. if size != 16 {
  530. svgStr = widthRe.ReplaceAllString(svgStr, fmt.Sprintf(`width="%d"`, size))
  531. svgStr = heightRe.ReplaceAllString(svgStr, fmt.Sprintf(`height="%d"`, size))
  532. }
  533. if class != "" {
  534. svgStr = strings.Replace(svgStr, `class="`, fmt.Sprintf(`class="%s `, class), 1)
  535. }
  536. return template.HTML(svgStr)
  537. }
  538. return template.HTML("")
  539. }
  540. // Avatar renders user avatars. args: user, size (int), class (string)
  541. func Avatar(item interface{}, others ...interface{}) template.HTML {
  542. size, class := parseOthers(models.DefaultAvatarPixelSize, "ui avatar image", others...)
  543. if user, ok := item.(*models.User); ok {
  544. src := user.RealSizedAvatarLink(size * models.AvatarRenderedSizeFactor)
  545. if src != "" {
  546. return AvatarHTML(src, size, class, user.DisplayName())
  547. }
  548. }
  549. if user, ok := item.(*models.Collaborator); ok {
  550. src := user.RealSizedAvatarLink(size * models.AvatarRenderedSizeFactor)
  551. if src != "" {
  552. return AvatarHTML(src, size, class, user.DisplayName())
  553. }
  554. }
  555. return template.HTML("")
  556. }
  557. // AvatarByAction renders user avatars from action. args: action, size (int), class (string)
  558. func AvatarByAction(action *models.Action, others ...interface{}) template.HTML {
  559. action.LoadActUser()
  560. return Avatar(action.ActUser, others...)
  561. }
  562. // RepoAvatar renders repo avatars. args: repo, size(int), class (string)
  563. func RepoAvatar(repo *models.Repository, others ...interface{}) template.HTML {
  564. size, class := parseOthers(models.DefaultAvatarPixelSize, "ui avatar image", others...)
  565. src := repo.RelAvatarLink()
  566. if src != "" {
  567. return AvatarHTML(src, size, class, repo.FullName())
  568. }
  569. return template.HTML("")
  570. }
  571. // AvatarByEmail renders avatars by email address. args: email, name, size (int), class (string)
  572. func AvatarByEmail(email string, name string, others ...interface{}) template.HTML {
  573. size, class := parseOthers(models.DefaultAvatarPixelSize, "ui avatar image", others...)
  574. src := models.SizedAvatarLink(email, size*models.AvatarRenderedSizeFactor)
  575. if src != "" {
  576. return AvatarHTML(src, size, class, name)
  577. }
  578. return template.HTML("")
  579. }
  580. // Safe render raw as HTML
  581. func Safe(raw string) template.HTML {
  582. return template.HTML(raw)
  583. }
  584. // SafeJS renders raw as JS
  585. func SafeJS(raw string) template.JS {
  586. return template.JS(raw)
  587. }
  588. // Str2html render Markdown text to HTML
  589. func Str2html(raw string) template.HTML {
  590. return template.HTML(markup.Sanitize(raw))
  591. }
  592. // Escape escapes a HTML string
  593. func Escape(raw string) string {
  594. return html.EscapeString(raw)
  595. }
  596. // JSEscape escapes a JS string
  597. func JSEscape(raw string) string {
  598. return template.JSEscapeString(raw)
  599. }
  600. // List traversings the list
  601. func List(l *list.List) chan interface{} {
  602. e := l.Front()
  603. c := make(chan interface{})
  604. go func() {
  605. for e != nil {
  606. c <- e.Value
  607. e = e.Next()
  608. }
  609. close(c)
  610. }()
  611. return c
  612. }
  613. // Sha1 returns sha1 sum of string
  614. func Sha1(str string) string {
  615. return base.EncodeSha1(str)
  616. }
  617. // RenderCommitMessage renders commit message with XSS-safe and special links.
  618. func RenderCommitMessage(msg, urlPrefix string, metas map[string]string) template.HTML {
  619. return RenderCommitMessageLink(msg, urlPrefix, "", metas)
  620. }
  621. // RenderCommitMessageLink renders commit message as a XXS-safe link to the provided
  622. // default url, handling for special links.
  623. func RenderCommitMessageLink(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  624. cleanMsg := template.HTMLEscapeString(msg)
  625. // we can safely assume that it will not return any error, since there
  626. // shouldn't be any special HTML.
  627. fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
  628. URLPrefix: urlPrefix,
  629. DefaultLink: urlDefault,
  630. Metas: metas,
  631. }, cleanMsg)
  632. if err != nil {
  633. log.Error("RenderCommitMessage: %v", err)
  634. return ""
  635. }
  636. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  637. if len(msgLines) == 0 {
  638. return template.HTML("")
  639. }
  640. return template.HTML(msgLines[0])
  641. }
  642. // RenderCommitMessageLinkSubject renders commit message as a XXS-safe link to
  643. // the provided default url, handling for special links without email to links.
  644. func RenderCommitMessageLinkSubject(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  645. msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
  646. lineEnd := strings.IndexByte(msgLine, '\n')
  647. if lineEnd > 0 {
  648. msgLine = msgLine[:lineEnd]
  649. }
  650. msgLine = strings.TrimRightFunc(msgLine, unicode.IsSpace)
  651. if len(msgLine) == 0 {
  652. return template.HTML("")
  653. }
  654. // we can safely assume that it will not return any error, since there
  655. // shouldn't be any special HTML.
  656. renderedMessage, err := markup.RenderCommitMessageSubject(&markup.RenderContext{
  657. URLPrefix: urlPrefix,
  658. DefaultLink: urlDefault,
  659. Metas: metas,
  660. }, template.HTMLEscapeString(msgLine))
  661. if err != nil {
  662. log.Error("RenderCommitMessageSubject: %v", err)
  663. return template.HTML("")
  664. }
  665. return template.HTML(renderedMessage)
  666. }
  667. // RenderCommitBody extracts the body of a commit message without its title.
  668. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  669. msgLine := strings.TrimRightFunc(msg, unicode.IsSpace)
  670. lineEnd := strings.IndexByte(msgLine, '\n')
  671. if lineEnd > 0 {
  672. msgLine = msgLine[lineEnd+1:]
  673. } else {
  674. return template.HTML("")
  675. }
  676. msgLine = strings.TrimLeftFunc(msgLine, unicode.IsSpace)
  677. if len(msgLine) == 0 {
  678. return template.HTML("")
  679. }
  680. renderedMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
  681. URLPrefix: urlPrefix,
  682. Metas: metas,
  683. }, template.HTMLEscapeString(msgLine))
  684. if err != nil {
  685. log.Error("RenderCommitMessage: %v", err)
  686. return ""
  687. }
  688. return template.HTML(renderedMessage)
  689. }
  690. // RenderIssueTitle renders issue/pull title with defined post processors
  691. func RenderIssueTitle(text, urlPrefix string, metas map[string]string) template.HTML {
  692. renderedText, err := markup.RenderIssueTitle(&markup.RenderContext{
  693. URLPrefix: urlPrefix,
  694. Metas: metas,
  695. }, template.HTMLEscapeString(text))
  696. if err != nil {
  697. log.Error("RenderIssueTitle: %v", err)
  698. return template.HTML("")
  699. }
  700. return template.HTML(renderedText)
  701. }
  702. // RenderEmoji renders html text with emoji post processors
  703. func RenderEmoji(text string) template.HTML {
  704. renderedText, err := markup.RenderEmoji(template.HTMLEscapeString(text))
  705. if err != nil {
  706. log.Error("RenderEmoji: %v", err)
  707. return template.HTML("")
  708. }
  709. return template.HTML(renderedText)
  710. }
  711. //ReactionToEmoji renders emoji for use in reactions
  712. func ReactionToEmoji(reaction string) template.HTML {
  713. val := emoji.FromCode(reaction)
  714. if val != nil {
  715. return template.HTML(val.Emoji)
  716. }
  717. val = emoji.FromAlias(reaction)
  718. if val != nil {
  719. return template.HTML(val.Emoji)
  720. }
  721. return template.HTML(fmt.Sprintf(`<img alt=":%s:" src="%s/img/emoji/%s.png"></img>`, reaction, setting.StaticURLPrefix, reaction))
  722. }
  723. // RenderNote renders the contents of a git-notes file as a commit message.
  724. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  725. cleanMsg := template.HTMLEscapeString(msg)
  726. fullMessage, err := markup.RenderCommitMessage(&markup.RenderContext{
  727. URLPrefix: urlPrefix,
  728. Metas: metas,
  729. }, cleanMsg)
  730. if err != nil {
  731. log.Error("RenderNote: %v", err)
  732. return ""
  733. }
  734. return template.HTML(string(fullMessage))
  735. }
  736. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  737. func IsMultilineCommitMessage(msg string) bool {
  738. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  739. }
  740. // Actioner describes an action
  741. type Actioner interface {
  742. GetOpType() models.ActionType
  743. GetActUserName() string
  744. GetRepoUserName() string
  745. GetRepoName() string
  746. GetRepoPath() string
  747. GetRepoLink() string
  748. GetBranch() string
  749. GetContent() string
  750. GetCreate() time.Time
  751. GetIssueInfos() []string
  752. }
  753. // ActionIcon accepts an action operation type and returns an icon class name.
  754. func ActionIcon(opType models.ActionType) string {
  755. switch opType {
  756. case models.ActionCreateRepo, models.ActionTransferRepo:
  757. return "repo"
  758. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  759. return "git-commit"
  760. case models.ActionCreateIssue:
  761. return "issue-opened"
  762. case models.ActionCreatePullRequest:
  763. return "git-pull-request"
  764. case models.ActionCommentIssue, models.ActionCommentPull:
  765. return "comment-discussion"
  766. case models.ActionMergePullRequest:
  767. return "git-merge"
  768. case models.ActionCloseIssue, models.ActionClosePullRequest:
  769. return "issue-closed"
  770. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  771. return "issue-reopened"
  772. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  773. return "mirror"
  774. case models.ActionApprovePullRequest:
  775. return "check"
  776. case models.ActionRejectPullRequest:
  777. return "diff"
  778. case models.ActionPublishRelease:
  779. return "tag"
  780. case models.ActionPullReviewDismissed:
  781. return "x"
  782. default:
  783. return "question"
  784. }
  785. }
  786. // ActionContent2Commits converts action content to push commits
  787. func ActionContent2Commits(act Actioner) *repository.PushCommits {
  788. push := repository.NewPushCommits()
  789. if act == nil || act.GetContent() == "" {
  790. return push
  791. }
  792. json := jsoniter.ConfigCompatibleWithStandardLibrary
  793. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  794. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  795. }
  796. return push
  797. }
  798. // DiffTypeToStr returns diff type name
  799. func DiffTypeToStr(diffType int) string {
  800. diffTypes := map[int]string{
  801. 1: "add", 2: "modify", 3: "del", 4: "rename", 5: "copy",
  802. }
  803. return diffTypes[diffType]
  804. }
  805. // DiffLineTypeToStr returns diff line type name
  806. func DiffLineTypeToStr(diffType int) string {
  807. switch diffType {
  808. case 2:
  809. return "add"
  810. case 3:
  811. return "del"
  812. case 4:
  813. return "tag"
  814. }
  815. return "same"
  816. }
  817. // Language specific rules for translating plural texts
  818. var trNLangRules = map[string]func(int64) int{
  819. "en-US": func(cnt int64) int {
  820. if cnt == 1 {
  821. return 0
  822. }
  823. return 1
  824. },
  825. "lv-LV": func(cnt int64) int {
  826. if cnt%10 == 1 && cnt%100 != 11 {
  827. return 0
  828. }
  829. return 1
  830. },
  831. "ru-RU": func(cnt int64) int {
  832. if cnt%10 == 1 && cnt%100 != 11 {
  833. return 0
  834. }
  835. return 1
  836. },
  837. "zh-CN": func(cnt int64) int {
  838. return 0
  839. },
  840. "zh-HK": func(cnt int64) int {
  841. return 0
  842. },
  843. "zh-TW": func(cnt int64) int {
  844. return 0
  845. },
  846. "fr-FR": func(cnt int64) int {
  847. if cnt > -2 && cnt < 2 {
  848. return 0
  849. }
  850. return 1
  851. },
  852. }
  853. // TrN returns key to be used for plural text translation
  854. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  855. var c int64
  856. if t, ok := cnt.(int); ok {
  857. c = int64(t)
  858. } else if t, ok := cnt.(int16); ok {
  859. c = int64(t)
  860. } else if t, ok := cnt.(int32); ok {
  861. c = int64(t)
  862. } else if t, ok := cnt.(int64); ok {
  863. c = t
  864. } else {
  865. return keyN
  866. }
  867. ruleFunc, ok := trNLangRules[lang]
  868. if !ok {
  869. ruleFunc = trNLangRules["en-US"]
  870. }
  871. if ruleFunc(c) == 0 {
  872. return key1
  873. }
  874. return keyN
  875. }
  876. // MigrationIcon returns a Font Awesome name matching the service an issue/comment was migrated from
  877. func MigrationIcon(hostname string) string {
  878. switch hostname {
  879. case "github.com":
  880. return "fa-github"
  881. default:
  882. return "fa-git-alt"
  883. }
  884. }
  885. func buildSubjectBodyTemplate(stpl *texttmpl.Template, btpl *template.Template, name string, content []byte) {
  886. // Split template into subject and body
  887. var subjectContent []byte
  888. bodyContent := content
  889. loc := mailSubjectSplit.FindIndex(content)
  890. if loc != nil {
  891. subjectContent = content[0:loc[0]]
  892. bodyContent = content[loc[1]:]
  893. }
  894. if _, err := stpl.New(name).
  895. Parse(string(subjectContent)); err != nil {
  896. log.Warn("Failed to parse template [%s/subject]: %v", name, err)
  897. }
  898. if _, err := btpl.New(name).
  899. Parse(string(bodyContent)); err != nil {
  900. log.Warn("Failed to parse template [%s/body]: %v", name, err)
  901. }
  902. }