You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

helper.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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. "StaticUrlPrefix": func() string {
  58. return setting.StaticURLPrefix
  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([]byte(cleanMsg), urlPrefix, urlDefault, metas)
  628. if err != nil {
  629. log.Error("RenderCommitMessage: %v", err)
  630. return ""
  631. }
  632. msgLines := strings.Split(strings.TrimSpace(string(fullMessage)), "\n")
  633. if len(msgLines) == 0 {
  634. return template.HTML("")
  635. }
  636. return template.HTML(msgLines[0])
  637. }
  638. // RenderCommitMessageLinkSubject renders commit message as a XXS-safe link to
  639. // the provided default url, handling for special links without email to links.
  640. func RenderCommitMessageLinkSubject(msg, urlPrefix, urlDefault string, metas map[string]string) template.HTML {
  641. msgLine := strings.TrimLeftFunc(msg, unicode.IsSpace)
  642. lineEnd := strings.IndexByte(msgLine, '\n')
  643. if lineEnd > 0 {
  644. msgLine = msgLine[:lineEnd]
  645. }
  646. msgLine = strings.TrimRightFunc(msgLine, unicode.IsSpace)
  647. if len(msgLine) == 0 {
  648. return template.HTML("")
  649. }
  650. // we can safely assume that it will not return any error, since there
  651. // shouldn't be any special HTML.
  652. renderedMessage, err := markup.RenderCommitMessageSubject([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, urlDefault, metas)
  653. if err != nil {
  654. log.Error("RenderCommitMessageSubject: %v", err)
  655. return template.HTML("")
  656. }
  657. return template.HTML(renderedMessage)
  658. }
  659. // RenderCommitBody extracts the body of a commit message without its title.
  660. func RenderCommitBody(msg, urlPrefix string, metas map[string]string) template.HTML {
  661. msgLine := strings.TrimRightFunc(msg, unicode.IsSpace)
  662. lineEnd := strings.IndexByte(msgLine, '\n')
  663. if lineEnd > 0 {
  664. msgLine = msgLine[lineEnd+1:]
  665. } else {
  666. return template.HTML("")
  667. }
  668. msgLine = strings.TrimLeftFunc(msgLine, unicode.IsSpace)
  669. if len(msgLine) == 0 {
  670. return template.HTML("")
  671. }
  672. renderedMessage, err := markup.RenderCommitMessage([]byte(template.HTMLEscapeString(msgLine)), urlPrefix, "", metas)
  673. if err != nil {
  674. log.Error("RenderCommitMessage: %v", err)
  675. return ""
  676. }
  677. return template.HTML(renderedMessage)
  678. }
  679. // RenderIssueTitle renders issue/pull title with defined post processors
  680. func RenderIssueTitle(text, urlPrefix string, metas map[string]string) template.HTML {
  681. renderedText, err := markup.RenderIssueTitle([]byte(template.HTMLEscapeString(text)), urlPrefix, metas)
  682. if err != nil {
  683. log.Error("RenderIssueTitle: %v", err)
  684. return template.HTML("")
  685. }
  686. return template.HTML(renderedText)
  687. }
  688. // RenderEmoji renders html text with emoji post processors
  689. func RenderEmoji(text string) template.HTML {
  690. renderedText, err := markup.RenderEmoji([]byte(template.HTMLEscapeString(text)))
  691. if err != nil {
  692. log.Error("RenderEmoji: %v", err)
  693. return template.HTML("")
  694. }
  695. return template.HTML(renderedText)
  696. }
  697. //ReactionToEmoji renders emoji for use in reactions
  698. func ReactionToEmoji(reaction string) template.HTML {
  699. val := emoji.FromCode(reaction)
  700. if val != nil {
  701. return template.HTML(val.Emoji)
  702. }
  703. val = emoji.FromAlias(reaction)
  704. if val != nil {
  705. return template.HTML(val.Emoji)
  706. }
  707. return template.HTML(fmt.Sprintf(`<img alt=":%s:" src="%s/img/emoji/%s.png"></img>`, reaction, setting.StaticURLPrefix, reaction))
  708. }
  709. // RenderNote renders the contents of a git-notes file as a commit message.
  710. func RenderNote(msg, urlPrefix string, metas map[string]string) template.HTML {
  711. cleanMsg := template.HTMLEscapeString(msg)
  712. fullMessage, err := markup.RenderCommitMessage([]byte(cleanMsg), urlPrefix, "", metas)
  713. if err != nil {
  714. log.Error("RenderNote: %v", err)
  715. return ""
  716. }
  717. return template.HTML(string(fullMessage))
  718. }
  719. // IsMultilineCommitMessage checks to see if a commit message contains multiple lines.
  720. func IsMultilineCommitMessage(msg string) bool {
  721. return strings.Count(strings.TrimSpace(msg), "\n") >= 1
  722. }
  723. // Actioner describes an action
  724. type Actioner interface {
  725. GetOpType() models.ActionType
  726. GetActUserName() string
  727. GetRepoUserName() string
  728. GetRepoName() string
  729. GetRepoPath() string
  730. GetRepoLink() string
  731. GetBranch() string
  732. GetContent() string
  733. GetCreate() time.Time
  734. GetIssueInfos() []string
  735. }
  736. // ActionIcon accepts an action operation type and returns an icon class name.
  737. func ActionIcon(opType models.ActionType) string {
  738. switch opType {
  739. case models.ActionCreateRepo, models.ActionTransferRepo:
  740. return "repo"
  741. case models.ActionCommitRepo, models.ActionPushTag, models.ActionDeleteTag, models.ActionDeleteBranch:
  742. return "git-commit"
  743. case models.ActionCreateIssue:
  744. return "issue-opened"
  745. case models.ActionCreatePullRequest:
  746. return "git-pull-request"
  747. case models.ActionCommentIssue, models.ActionCommentPull:
  748. return "comment-discussion"
  749. case models.ActionMergePullRequest:
  750. return "git-merge"
  751. case models.ActionCloseIssue, models.ActionClosePullRequest:
  752. return "issue-closed"
  753. case models.ActionReopenIssue, models.ActionReopenPullRequest:
  754. return "issue-reopened"
  755. case models.ActionMirrorSyncPush, models.ActionMirrorSyncCreate, models.ActionMirrorSyncDelete:
  756. return "mirror"
  757. case models.ActionApprovePullRequest:
  758. return "check"
  759. case models.ActionRejectPullRequest:
  760. return "diff"
  761. case models.ActionPublishRelease:
  762. return "tag"
  763. case models.ActionPullReviewDismissed:
  764. return "x"
  765. default:
  766. return "question"
  767. }
  768. }
  769. // ActionContent2Commits converts action content to push commits
  770. func ActionContent2Commits(act Actioner) *repository.PushCommits {
  771. push := repository.NewPushCommits()
  772. if act == nil || act.GetContent() == "" {
  773. return push
  774. }
  775. json := jsoniter.ConfigCompatibleWithStandardLibrary
  776. if err := json.Unmarshal([]byte(act.GetContent()), push); err != nil {
  777. log.Error("json.Unmarshal:\n%s\nERROR: %v", act.GetContent(), err)
  778. }
  779. return push
  780. }
  781. // DiffTypeToStr returns diff type name
  782. func DiffTypeToStr(diffType int) string {
  783. diffTypes := map[int]string{
  784. 1: "add", 2: "modify", 3: "del", 4: "rename", 5: "copy",
  785. }
  786. return diffTypes[diffType]
  787. }
  788. // DiffLineTypeToStr returns diff line type name
  789. func DiffLineTypeToStr(diffType int) string {
  790. switch diffType {
  791. case 2:
  792. return "add"
  793. case 3:
  794. return "del"
  795. case 4:
  796. return "tag"
  797. }
  798. return "same"
  799. }
  800. // Language specific rules for translating plural texts
  801. var trNLangRules = map[string]func(int64) int{
  802. "en-US": func(cnt int64) int {
  803. if cnt == 1 {
  804. return 0
  805. }
  806. return 1
  807. },
  808. "lv-LV": func(cnt int64) int {
  809. if cnt%10 == 1 && cnt%100 != 11 {
  810. return 0
  811. }
  812. return 1
  813. },
  814. "ru-RU": func(cnt int64) int {
  815. if cnt%10 == 1 && cnt%100 != 11 {
  816. return 0
  817. }
  818. return 1
  819. },
  820. "zh-CN": func(cnt int64) int {
  821. return 0
  822. },
  823. "zh-HK": func(cnt int64) int {
  824. return 0
  825. },
  826. "zh-TW": func(cnt int64) int {
  827. return 0
  828. },
  829. "fr-FR": func(cnt int64) int {
  830. if cnt > -2 && cnt < 2 {
  831. return 0
  832. }
  833. return 1
  834. },
  835. }
  836. // TrN returns key to be used for plural text translation
  837. func TrN(lang string, cnt interface{}, key1, keyN string) string {
  838. var c int64
  839. if t, ok := cnt.(int); ok {
  840. c = int64(t)
  841. } else if t, ok := cnt.(int16); ok {
  842. c = int64(t)
  843. } else if t, ok := cnt.(int32); ok {
  844. c = int64(t)
  845. } else if t, ok := cnt.(int64); ok {
  846. c = t
  847. } else {
  848. return keyN
  849. }
  850. ruleFunc, ok := trNLangRules[lang]
  851. if !ok {
  852. ruleFunc = trNLangRules["en-US"]
  853. }
  854. if ruleFunc(c) == 0 {
  855. return key1
  856. }
  857. return keyN
  858. }
  859. // MigrationIcon returns a Font Awesome name matching the service an issue/comment was migrated from
  860. func MigrationIcon(hostname string) string {
  861. switch hostname {
  862. case "github.com":
  863. return "fa-github"
  864. default:
  865. return "fa-git-alt"
  866. }
  867. }
  868. func buildSubjectBodyTemplate(stpl *texttmpl.Template, btpl *template.Template, name string, content []byte) {
  869. // Split template into subject and body
  870. var subjectContent []byte
  871. bodyContent := content
  872. loc := mailSubjectSplit.FindIndex(content)
  873. if loc != nil {
  874. subjectContent = content[0:loc[0]]
  875. bodyContent = content[loc[1]:]
  876. }
  877. if _, err := stpl.New(name).
  878. Parse(string(subjectContent)); err != nil {
  879. log.Warn("Failed to parse template [%s/subject]: %v", name, err)
  880. }
  881. if _, err := btpl.New(name).
  882. Parse(string(bodyContent)); err != nil {
  883. log.Warn("Failed to parse template [%s/body]: %v", name, err)
  884. }
  885. }