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.

tool.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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. "bytes"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "crypto/sha256"
  11. "encoding/base64"
  12. "encoding/hex"
  13. "fmt"
  14. "html/template"
  15. "io"
  16. "math"
  17. "net/http"
  18. "net/url"
  19. "os"
  20. "path"
  21. "path/filepath"
  22. "runtime"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "unicode"
  27. "unicode/utf8"
  28. "code.gitea.io/gitea/modules/git"
  29. "code.gitea.io/gitea/modules/log"
  30. "code.gitea.io/gitea/modules/setting"
  31. "code.gitea.io/gitea/modules/util"
  32. "github.com/Unknwon/com"
  33. "github.com/Unknwon/i18n"
  34. "github.com/gogits/chardet"
  35. )
  36. // UTF8BOM is the utf-8 byte-order marker
  37. var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
  38. // EncodeMD5 encodes string to md5 hex value.
  39. func EncodeMD5(str string) string {
  40. m := md5.New()
  41. _, _ = m.Write([]byte(str))
  42. return hex.EncodeToString(m.Sum(nil))
  43. }
  44. // EncodeSha1 string to sha1 hex value.
  45. func EncodeSha1(str string) string {
  46. h := sha1.New()
  47. _, _ = h.Write([]byte(str))
  48. return hex.EncodeToString(h.Sum(nil))
  49. }
  50. // EncodeSha256 string to sha1 hex value.
  51. func EncodeSha256(str string) string {
  52. h := sha256.New()
  53. _, _ = h.Write([]byte(str))
  54. return hex.EncodeToString(h.Sum(nil))
  55. }
  56. // ShortSha is basically just truncating.
  57. // It is DEPRECATED and will be removed in the future.
  58. func ShortSha(sha1 string) string {
  59. return TruncateString(sha1, 10)
  60. }
  61. // DetectEncoding detect the encoding of content
  62. func DetectEncoding(content []byte) (string, error) {
  63. if utf8.Valid(content) {
  64. log.Debug("Detected encoding: utf-8 (fast)")
  65. return "UTF-8", nil
  66. }
  67. textDetector := chardet.NewTextDetector()
  68. var detectContent []byte
  69. if len(content) < 1024 {
  70. // Check if original content is valid
  71. if _, err := textDetector.DetectBest(content); err != nil {
  72. return "", err
  73. }
  74. times := 1024 / len(content)
  75. detectContent = make([]byte, 0, times*len(content))
  76. for i := 0; i < times; i++ {
  77. detectContent = append(detectContent, content...)
  78. }
  79. } else {
  80. detectContent = content
  81. }
  82. result, err := textDetector.DetectBest(detectContent)
  83. if err != nil {
  84. return "", err
  85. }
  86. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  87. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  88. return setting.Repository.AnsiCharset, err
  89. }
  90. log.Debug("Detected encoding: %s", result.Charset)
  91. return result.Charset, err
  92. }
  93. // RemoveBOMIfPresent removes a UTF-8 BOM from a []byte
  94. func RemoveBOMIfPresent(content []byte) []byte {
  95. if len(content) > 2 && bytes.Equal(content[0:3], UTF8BOM) {
  96. return content[3:]
  97. }
  98. return content
  99. }
  100. // BasicAuthDecode decode basic auth string
  101. func BasicAuthDecode(encoded string) (string, string, error) {
  102. s, err := base64.StdEncoding.DecodeString(encoded)
  103. if err != nil {
  104. return "", "", err
  105. }
  106. auth := strings.SplitN(string(s), ":", 2)
  107. return auth[0], auth[1], nil
  108. }
  109. // BasicAuthEncode encode basic auth string
  110. func BasicAuthEncode(username, password string) string {
  111. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  112. }
  113. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  114. func GetRandomBytesAsBase64(n int) string {
  115. bytes := make([]byte, 32)
  116. _, err := io.ReadFull(rand.Reader, bytes)
  117. if err != nil {
  118. log.Fatal("Error reading random bytes: %v", err)
  119. }
  120. return base64.RawURLEncoding.EncodeToString(bytes)
  121. }
  122. // VerifyTimeLimitCode verify time limit code
  123. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  124. if len(code) <= 18 {
  125. return false
  126. }
  127. // split code
  128. start := code[:12]
  129. lives := code[12:18]
  130. if d, err := com.StrTo(lives).Int(); err == nil {
  131. minutes = d
  132. }
  133. // right active code
  134. retCode := CreateTimeLimitCode(data, minutes, start)
  135. if retCode == code && minutes > 0 {
  136. // check time is expired or not
  137. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  138. now := time.Now()
  139. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  140. return true
  141. }
  142. }
  143. return false
  144. }
  145. // TimeLimitCodeLength default value for time limit code
  146. const TimeLimitCodeLength = 12 + 6 + 40
  147. // CreateTimeLimitCode create a time limit code
  148. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  149. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  150. format := "200601021504"
  151. var start, end time.Time
  152. var startStr, endStr string
  153. if startInf == nil {
  154. // Use now time create code
  155. start = time.Now()
  156. startStr = start.Format(format)
  157. } else {
  158. // use start string create code
  159. startStr = startInf.(string)
  160. start, _ = time.ParseInLocation(format, startStr, time.Local)
  161. startStr = start.Format(format)
  162. }
  163. end = start.Add(time.Minute * time.Duration(minutes))
  164. endStr = end.Format(format)
  165. // create sha1 encode string
  166. sh := sha1.New()
  167. _, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  168. encoded := hex.EncodeToString(sh.Sum(nil))
  169. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  170. return code
  171. }
  172. // HashEmail hashes email address to MD5 string.
  173. // https://en.gravatar.com/site/implement/hash/
  174. func HashEmail(email string) string {
  175. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  176. }
  177. // DefaultAvatarLink the default avatar link
  178. func DefaultAvatarLink() string {
  179. return setting.AppSubURL + "/img/avatar_default.png"
  180. }
  181. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  182. // determined by the avatar-hosting service.
  183. const DefaultAvatarSize = -1
  184. // libravatarURL returns the URL for the given email. This function should only
  185. // be called if a federated avatar service is enabled.
  186. func libravatarURL(email string) (*url.URL, error) {
  187. urlStr, err := setting.LibravatarService.FromEmail(email)
  188. if err != nil {
  189. log.Error("LibravatarService.FromEmail(email=%s): error %v", email, err)
  190. return nil, err
  191. }
  192. u, err := url.Parse(urlStr)
  193. if err != nil {
  194. log.Error("Failed to parse libravatar url(%s): error %v", urlStr, err)
  195. return nil, err
  196. }
  197. return u, nil
  198. }
  199. // SizedAvatarLink returns a sized link to the avatar for the given email
  200. // address.
  201. func SizedAvatarLink(email string, size int) string {
  202. var avatarURL *url.URL
  203. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  204. var err error
  205. avatarURL, err = libravatarURL(email)
  206. if err != nil {
  207. return DefaultAvatarLink()
  208. }
  209. } else if !setting.DisableGravatar {
  210. // copy GravatarSourceURL, because we will modify its Path.
  211. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  212. avatarURL = &copyOfGravatarSourceURL
  213. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  214. } else {
  215. return DefaultAvatarLink()
  216. }
  217. vals := avatarURL.Query()
  218. vals.Set("d", "identicon")
  219. if size != DefaultAvatarSize {
  220. vals.Set("s", strconv.Itoa(size))
  221. }
  222. avatarURL.RawQuery = vals.Encode()
  223. return avatarURL.String()
  224. }
  225. // AvatarLink returns relative avatar link to the site domain by given email,
  226. // which includes app sub-url as prefix. However, it is possible
  227. // to return full URL if user enables Gravatar-like service.
  228. func AvatarLink(email string) string {
  229. return SizedAvatarLink(email, DefaultAvatarSize)
  230. }
  231. // Seconds-based time units
  232. const (
  233. Minute = 60
  234. Hour = 60 * Minute
  235. Day = 24 * Hour
  236. Week = 7 * Day
  237. Month = 30 * Day
  238. Year = 12 * Month
  239. )
  240. func computeTimeDiff(diff int64, lang string) (int64, string) {
  241. diffStr := ""
  242. switch {
  243. case diff <= 0:
  244. diff = 0
  245. diffStr = i18n.Tr(lang, "tool.now")
  246. case diff < 2:
  247. diff = 0
  248. diffStr = i18n.Tr(lang, "tool.1s")
  249. case diff < 1*Minute:
  250. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  251. diff = 0
  252. case diff < 2*Minute:
  253. diff -= 1 * Minute
  254. diffStr = i18n.Tr(lang, "tool.1m")
  255. case diff < 1*Hour:
  256. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  257. diff -= diff / Minute * Minute
  258. case diff < 2*Hour:
  259. diff -= 1 * Hour
  260. diffStr = i18n.Tr(lang, "tool.1h")
  261. case diff < 1*Day:
  262. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  263. diff -= diff / Hour * Hour
  264. case diff < 2*Day:
  265. diff -= 1 * Day
  266. diffStr = i18n.Tr(lang, "tool.1d")
  267. case diff < 1*Week:
  268. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  269. diff -= diff / Day * Day
  270. case diff < 2*Week:
  271. diff -= 1 * Week
  272. diffStr = i18n.Tr(lang, "tool.1w")
  273. case diff < 1*Month:
  274. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  275. diff -= diff / Week * Week
  276. case diff < 2*Month:
  277. diff -= 1 * Month
  278. diffStr = i18n.Tr(lang, "tool.1mon")
  279. case diff < 1*Year:
  280. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  281. diff -= diff / Month * Month
  282. case diff < 2*Year:
  283. diff -= 1 * Year
  284. diffStr = i18n.Tr(lang, "tool.1y")
  285. default:
  286. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  287. diff -= (diff / Year) * Year
  288. }
  289. return diff, diffStr
  290. }
  291. // MinutesToFriendly returns a user friendly string with number of minutes
  292. // converted to hours and minutes.
  293. func MinutesToFriendly(minutes int, lang string) string {
  294. duration := time.Duration(minutes) * time.Minute
  295. return TimeSincePro(time.Now().Add(-duration), lang)
  296. }
  297. // TimeSincePro calculates the time interval and generate full user-friendly string.
  298. func TimeSincePro(then time.Time, lang string) string {
  299. return timeSincePro(then, time.Now(), lang)
  300. }
  301. func timeSincePro(then, now time.Time, lang string) string {
  302. diff := now.Unix() - then.Unix()
  303. if then.After(now) {
  304. return i18n.Tr(lang, "tool.future")
  305. }
  306. if diff == 0 {
  307. return i18n.Tr(lang, "tool.now")
  308. }
  309. var timeStr, diffStr string
  310. for {
  311. if diff == 0 {
  312. break
  313. }
  314. diff, diffStr = computeTimeDiff(diff, lang)
  315. timeStr += ", " + diffStr
  316. }
  317. return strings.TrimPrefix(timeStr, ", ")
  318. }
  319. func timeSince(then, now time.Time, lang string) string {
  320. return timeSinceUnix(then.Unix(), now.Unix(), lang)
  321. }
  322. func timeSinceUnix(then, now int64, lang string) string {
  323. lbl := "tool.ago"
  324. diff := now - then
  325. if then > now {
  326. lbl = "tool.from_now"
  327. diff = then - now
  328. }
  329. if diff <= 0 {
  330. return i18n.Tr(lang, "tool.now")
  331. }
  332. _, diffStr := computeTimeDiff(diff, lang)
  333. return i18n.Tr(lang, lbl, diffStr)
  334. }
  335. // RawTimeSince retrieves i18n key of time since t
  336. func RawTimeSince(t time.Time, lang string) string {
  337. return timeSince(t, time.Now(), lang)
  338. }
  339. // TimeSince calculates the time interval and generate user-friendly string.
  340. func TimeSince(then time.Time, lang string) template.HTML {
  341. return htmlTimeSince(then, time.Now(), lang)
  342. }
  343. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  344. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  345. then.Format(setting.TimeFormat),
  346. timeSince(then, now, lang)))
  347. }
  348. // TimeSinceUnix calculates the time interval and generate user-friendly string.
  349. func TimeSinceUnix(then util.TimeStamp, lang string) template.HTML {
  350. return htmlTimeSinceUnix(then, util.TimeStamp(time.Now().Unix()), lang)
  351. }
  352. func htmlTimeSinceUnix(then, now util.TimeStamp, lang string) template.HTML {
  353. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  354. then.Format(setting.TimeFormat),
  355. timeSinceUnix(int64(then), int64(now), lang)))
  356. }
  357. // Storage space size types
  358. const (
  359. Byte = 1
  360. KByte = Byte * 1024
  361. MByte = KByte * 1024
  362. GByte = MByte * 1024
  363. TByte = GByte * 1024
  364. PByte = TByte * 1024
  365. EByte = PByte * 1024
  366. )
  367. func logn(n, b float64) float64 {
  368. return math.Log(n) / math.Log(b)
  369. }
  370. func humanateBytes(s uint64, base float64, sizes []string) string {
  371. if s < 10 {
  372. return fmt.Sprintf("%dB", s)
  373. }
  374. e := math.Floor(logn(float64(s), base))
  375. suffix := sizes[int(e)]
  376. val := float64(s) / math.Pow(base, math.Floor(e))
  377. f := "%.0f"
  378. if val < 10 {
  379. f = "%.1f"
  380. }
  381. return fmt.Sprintf(f+"%s", val, suffix)
  382. }
  383. // FileSize calculates the file size and generate user-friendly string.
  384. func FileSize(s int64) string {
  385. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  386. return humanateBytes(uint64(s), 1024, sizes)
  387. }
  388. // Subtract deals with subtraction of all types of number.
  389. func Subtract(left interface{}, right interface{}) interface{} {
  390. var rleft, rright int64
  391. var fleft, fright float64
  392. var isInt = true
  393. switch v := left.(type) {
  394. case int:
  395. rleft = int64(v)
  396. case int8:
  397. rleft = int64(v)
  398. case int16:
  399. rleft = int64(v)
  400. case int32:
  401. rleft = int64(v)
  402. case int64:
  403. rleft = v
  404. case float32:
  405. fleft = float64(v)
  406. isInt = false
  407. case float64:
  408. fleft = v
  409. isInt = false
  410. }
  411. switch v := right.(type) {
  412. case int:
  413. rright = int64(v)
  414. case int8:
  415. rright = int64(v)
  416. case int16:
  417. rright = int64(v)
  418. case int32:
  419. rright = int64(v)
  420. case int64:
  421. rright = v
  422. case float32:
  423. fright = float64(v)
  424. isInt = false
  425. case float64:
  426. fright = v
  427. isInt = false
  428. }
  429. if isInt {
  430. return rleft - rright
  431. }
  432. return fleft + float64(rleft) - (fright + float64(rright))
  433. }
  434. // EllipsisString returns a truncated short string,
  435. // it appends '...' in the end of the length of string is too large.
  436. func EllipsisString(str string, length int) string {
  437. if length <= 3 {
  438. return "..."
  439. }
  440. if len(str) <= length {
  441. return str
  442. }
  443. return str[:length-3] + "..."
  444. }
  445. // TruncateString returns a truncated string with given limit,
  446. // it returns input string if length is not reached limit.
  447. func TruncateString(str string, limit int) string {
  448. if len(str) < limit {
  449. return str
  450. }
  451. return str[:limit]
  452. }
  453. // StringsToInt64s converts a slice of string to a slice of int64.
  454. func StringsToInt64s(strs []string) ([]int64, error) {
  455. ints := make([]int64, len(strs))
  456. for i := range strs {
  457. n, err := com.StrTo(strs[i]).Int64()
  458. if err != nil {
  459. return ints, err
  460. }
  461. ints[i] = n
  462. }
  463. return ints, nil
  464. }
  465. // Int64sToStrings converts a slice of int64 to a slice of string.
  466. func Int64sToStrings(ints []int64) []string {
  467. strs := make([]string, len(ints))
  468. for i := range ints {
  469. strs[i] = strconv.FormatInt(ints[i], 10)
  470. }
  471. return strs
  472. }
  473. // Int64sToMap converts a slice of int64 to a int64 map.
  474. func Int64sToMap(ints []int64) map[int64]bool {
  475. m := make(map[int64]bool)
  476. for _, i := range ints {
  477. m[i] = true
  478. }
  479. return m
  480. }
  481. // Int64sContains returns if a int64 in a slice of int64
  482. func Int64sContains(intsSlice []int64, a int64) bool {
  483. for _, c := range intsSlice {
  484. if c == a {
  485. return true
  486. }
  487. }
  488. return false
  489. }
  490. // IsLetter reports whether the rune is a letter (category L).
  491. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  492. func IsLetter(ch rune) bool {
  493. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  494. }
  495. // IsTextFile returns true if file content format is plain text or empty.
  496. func IsTextFile(data []byte) bool {
  497. if len(data) == 0 {
  498. return true
  499. }
  500. return strings.Contains(http.DetectContentType(data), "text/")
  501. }
  502. // IsImageFile detects if data is an image format
  503. func IsImageFile(data []byte) bool {
  504. return strings.Contains(http.DetectContentType(data), "image/")
  505. }
  506. // IsPDFFile detects if data is a pdf format
  507. func IsPDFFile(data []byte) bool {
  508. return strings.Contains(http.DetectContentType(data), "application/pdf")
  509. }
  510. // IsVideoFile detects if data is an video format
  511. func IsVideoFile(data []byte) bool {
  512. return strings.Contains(http.DetectContentType(data), "video/")
  513. }
  514. // IsAudioFile detects if data is an video format
  515. func IsAudioFile(data []byte) bool {
  516. return strings.Contains(http.DetectContentType(data), "audio/")
  517. }
  518. // EntryIcon returns the octicon class for displaying files/directories
  519. func EntryIcon(entry *git.TreeEntry) string {
  520. switch {
  521. case entry.IsLink():
  522. te, err := entry.FollowLink()
  523. if err != nil {
  524. log.Debug(err.Error())
  525. return "file-symlink-file"
  526. }
  527. if te.IsDir() {
  528. return "file-symlink-directory"
  529. }
  530. return "file-symlink-file"
  531. case entry.IsDir():
  532. return "file-directory"
  533. case entry.IsSubModule():
  534. return "file-submodule"
  535. }
  536. return "file-text"
  537. }
  538. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  539. func SetupGiteaRoot() string {
  540. giteaRoot := os.Getenv("GITEA_ROOT")
  541. if giteaRoot == "" {
  542. _, filename, _, _ := runtime.Caller(0)
  543. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  544. wd, err := os.Getwd()
  545. if err != nil {
  546. rel, err := filepath.Rel(giteaRoot, wd)
  547. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  548. giteaRoot = wd
  549. }
  550. }
  551. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  552. giteaRoot = ""
  553. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  554. giteaRoot = ""
  555. }
  556. }
  557. return giteaRoot
  558. }