Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

tool.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  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. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "io"
  14. "math"
  15. "math/big"
  16. "net/http"
  17. "strconv"
  18. "strings"
  19. "time"
  20. "unicode"
  21. "unicode/utf8"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/setting"
  24. "github.com/Unknwon/com"
  25. "github.com/Unknwon/i18n"
  26. "github.com/gogits/chardet"
  27. )
  28. // EncodeMD5 encodes string to md5 hex value.
  29. func EncodeMD5(str string) string {
  30. m := md5.New()
  31. m.Write([]byte(str))
  32. return hex.EncodeToString(m.Sum(nil))
  33. }
  34. // EncodeSha1 string to sha1 hex value.
  35. func EncodeSha1(str string) string {
  36. h := sha1.New()
  37. h.Write([]byte(str))
  38. return hex.EncodeToString(h.Sum(nil))
  39. }
  40. // ShortSha is basically just truncating.
  41. // It is DEPRECATED and will be removed in the future.
  42. func ShortSha(sha1 string) string {
  43. return TruncateString(sha1, 10)
  44. }
  45. // DetectEncoding detect the encoding of content
  46. func DetectEncoding(content []byte) (string, error) {
  47. if utf8.Valid(content) {
  48. log.Debug("Detected encoding: utf-8 (fast)")
  49. return "UTF-8", nil
  50. }
  51. result, err := chardet.NewTextDetector().DetectBest(content)
  52. if err != nil {
  53. return "", err
  54. }
  55. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  56. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  57. return setting.Repository.AnsiCharset, err
  58. }
  59. log.Debug("Detected encoding: %s", result.Charset)
  60. return result.Charset, err
  61. }
  62. // BasicAuthDecode decode basic auth string
  63. func BasicAuthDecode(encoded string) (string, string, error) {
  64. s, err := base64.StdEncoding.DecodeString(encoded)
  65. if err != nil {
  66. return "", "", err
  67. }
  68. auth := strings.SplitN(string(s), ":", 2)
  69. return auth[0], auth[1], nil
  70. }
  71. // BasicAuthEncode encode basic auth string
  72. func BasicAuthEncode(username, password string) string {
  73. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  74. }
  75. // GetRandomString generate random string by specify chars.
  76. func GetRandomString(n int) (string, error) {
  77. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  78. buffer := make([]byte, n)
  79. max := big.NewInt(int64(len(alphanum)))
  80. for i := 0; i < n; i++ {
  81. index, err := randomInt(max)
  82. if err != nil {
  83. return "", err
  84. }
  85. buffer[i] = alphanum[index]
  86. }
  87. return string(buffer), nil
  88. }
  89. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  90. func GetRandomBytesAsBase64(n int) string {
  91. bytes := make([]byte, 32)
  92. _, err := io.ReadFull(rand.Reader, bytes)
  93. if err != nil {
  94. log.Fatal(4, "Error reading random bytes: %v", err)
  95. }
  96. return base64.RawURLEncoding.EncodeToString(bytes)
  97. }
  98. func randomInt(max *big.Int) (int, error) {
  99. rand, err := rand.Int(rand.Reader, max)
  100. if err != nil {
  101. return 0, err
  102. }
  103. return int(rand.Int64()), nil
  104. }
  105. // VerifyTimeLimitCode verify time limit code
  106. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  107. if len(code) <= 18 {
  108. return false
  109. }
  110. // split code
  111. start := code[:12]
  112. lives := code[12:18]
  113. if d, err := com.StrTo(lives).Int(); err == nil {
  114. minutes = d
  115. }
  116. // right active code
  117. retCode := CreateTimeLimitCode(data, minutes, start)
  118. if retCode == code && minutes > 0 {
  119. // check time is expired or not
  120. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  121. now := time.Now()
  122. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  123. return true
  124. }
  125. }
  126. return false
  127. }
  128. // TimeLimitCodeLength default value for time limit code
  129. const TimeLimitCodeLength = 12 + 6 + 40
  130. // CreateTimeLimitCode create a time limit code
  131. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  132. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  133. format := "200601021504"
  134. var start, end time.Time
  135. var startStr, endStr string
  136. if startInf == nil {
  137. // Use now time create code
  138. start = time.Now()
  139. startStr = start.Format(format)
  140. } else {
  141. // use start string create code
  142. startStr = startInf.(string)
  143. start, _ = time.ParseInLocation(format, startStr, time.Local)
  144. startStr = start.Format(format)
  145. }
  146. end = start.Add(time.Minute * time.Duration(minutes))
  147. endStr = end.Format(format)
  148. // create sha1 encode string
  149. sh := sha1.New()
  150. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  151. encoded := hex.EncodeToString(sh.Sum(nil))
  152. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  153. return code
  154. }
  155. // HashEmail hashes email address to MD5 string.
  156. // https://en.gravatar.com/site/implement/hash/
  157. func HashEmail(email string) string {
  158. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  159. }
  160. // DefaultAvatarLink the default avatar link
  161. func DefaultAvatarLink() string {
  162. return setting.AppSubURL + "/img/avatar_default.png"
  163. }
  164. // AvatarLink returns relative avatar link to the site domain by given email,
  165. // which includes app sub-url as prefix. However, it is possible
  166. // to return full URL if user enables Gravatar-like service.
  167. func AvatarLink(email string) string {
  168. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  169. url, err := setting.LibravatarService.FromEmail(email)
  170. if err != nil {
  171. log.Error(4, "LibravatarService.FromEmail(email=%s): error %v", email, err)
  172. return DefaultAvatarLink()
  173. }
  174. return url
  175. }
  176. if !setting.DisableGravatar {
  177. return setting.GravatarSource + HashEmail(email)
  178. }
  179. return DefaultAvatarLink()
  180. }
  181. // Seconds-based time units
  182. const (
  183. Minute = 60
  184. Hour = 60 * Minute
  185. Day = 24 * Hour
  186. Week = 7 * Day
  187. Month = 30 * Day
  188. Year = 12 * Month
  189. )
  190. func computeTimeDiff(diff int64, lang string) (int64, string) {
  191. diffStr := ""
  192. switch {
  193. case diff <= 0:
  194. diff = 0
  195. diffStr = i18n.Tr(lang, "tool.now")
  196. case diff < 2:
  197. diff = 0
  198. diffStr = i18n.Tr(lang, "tool.1s")
  199. case diff < 1*Minute:
  200. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  201. diff = 0
  202. case diff < 2*Minute:
  203. diff -= 1 * Minute
  204. diffStr = i18n.Tr(lang, "tool.1m")
  205. case diff < 1*Hour:
  206. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  207. diff -= diff / Minute * Minute
  208. case diff < 2*Hour:
  209. diff -= 1 * Hour
  210. diffStr = i18n.Tr(lang, "tool.1h")
  211. case diff < 1*Day:
  212. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  213. diff -= diff / Hour * Hour
  214. case diff < 2*Day:
  215. diff -= 1 * Day
  216. diffStr = i18n.Tr(lang, "tool.1d")
  217. case diff < 1*Week:
  218. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  219. diff -= diff / Day * Day
  220. case diff < 2*Week:
  221. diff -= 1 * Week
  222. diffStr = i18n.Tr(lang, "tool.1w")
  223. case diff < 1*Month:
  224. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  225. diff -= diff / Week * Week
  226. case diff < 2*Month:
  227. diff -= 1 * Month
  228. diffStr = i18n.Tr(lang, "tool.1mon")
  229. case diff < 1*Year:
  230. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  231. diff -= diff / Month * Month
  232. case diff < 2*Year:
  233. diff -= 1 * Year
  234. diffStr = i18n.Tr(lang, "tool.1y")
  235. default:
  236. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  237. diff -= (diff / Year) * Year
  238. }
  239. return diff, diffStr
  240. }
  241. // MinutesToFriendly returns a user friendly string with number of minutes
  242. // converted to hours and minutes.
  243. func MinutesToFriendly(minutes int, lang string) string {
  244. duration := time.Duration(minutes) * time.Minute
  245. return TimeSincePro(time.Now().Add(-duration), lang)
  246. }
  247. // TimeSincePro calculates the time interval and generate full user-friendly string.
  248. func TimeSincePro(then time.Time, lang string) string {
  249. return timeSincePro(then, time.Now(), lang)
  250. }
  251. func timeSincePro(then, now time.Time, lang string) string {
  252. diff := now.Unix() - then.Unix()
  253. if then.After(now) {
  254. return i18n.Tr(lang, "tool.future")
  255. }
  256. if diff == 0 {
  257. return i18n.Tr(lang, "tool.now")
  258. }
  259. var timeStr, diffStr string
  260. for {
  261. if diff == 0 {
  262. break
  263. }
  264. diff, diffStr = computeTimeDiff(diff, lang)
  265. timeStr += ", " + diffStr
  266. }
  267. return strings.TrimPrefix(timeStr, ", ")
  268. }
  269. func timeSince(then, now time.Time, lang string) string {
  270. lbl := "tool.ago"
  271. diff := now.Unix() - then.Unix()
  272. if then.After(now) {
  273. lbl = "tool.from_now"
  274. diff = then.Unix() - now.Unix()
  275. }
  276. if diff <= 0 {
  277. return i18n.Tr(lang, "tool.now")
  278. }
  279. _, diffStr := computeTimeDiff(diff, lang)
  280. return i18n.Tr(lang, lbl, diffStr)
  281. }
  282. // RawTimeSince retrieves i18n key of time since t
  283. func RawTimeSince(t time.Time, lang string) string {
  284. return timeSince(t, time.Now(), lang)
  285. }
  286. // TimeSince calculates the time interval and generate user-friendly string.
  287. func TimeSince(then time.Time, lang string) template.HTML {
  288. return htmlTimeSince(then, time.Now(), lang)
  289. }
  290. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  291. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  292. then.Format(setting.TimeFormat),
  293. timeSince(then, now, lang)))
  294. }
  295. // Storage space size types
  296. const (
  297. Byte = 1
  298. KByte = Byte * 1024
  299. MByte = KByte * 1024
  300. GByte = MByte * 1024
  301. TByte = GByte * 1024
  302. PByte = TByte * 1024
  303. EByte = PByte * 1024
  304. )
  305. var bytesSizeTable = map[string]uint64{
  306. "b": Byte,
  307. "kb": KByte,
  308. "mb": MByte,
  309. "gb": GByte,
  310. "tb": TByte,
  311. "pb": PByte,
  312. "eb": EByte,
  313. }
  314. func logn(n, b float64) float64 {
  315. return math.Log(n) / math.Log(b)
  316. }
  317. func humanateBytes(s uint64, base float64, sizes []string) string {
  318. if s < 10 {
  319. return fmt.Sprintf("%dB", s)
  320. }
  321. e := math.Floor(logn(float64(s), base))
  322. suffix := sizes[int(e)]
  323. val := float64(s) / math.Pow(base, math.Floor(e))
  324. f := "%.0f"
  325. if val < 10 {
  326. f = "%.1f"
  327. }
  328. return fmt.Sprintf(f+"%s", val, suffix)
  329. }
  330. // FileSize calculates the file size and generate user-friendly string.
  331. func FileSize(s int64) string {
  332. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  333. return humanateBytes(uint64(s), 1024, sizes)
  334. }
  335. // Subtract deals with subtraction of all types of number.
  336. func Subtract(left interface{}, right interface{}) interface{} {
  337. var rleft, rright int64
  338. var fleft, fright float64
  339. var isInt = true
  340. switch left.(type) {
  341. case int:
  342. rleft = int64(left.(int))
  343. case int8:
  344. rleft = int64(left.(int8))
  345. case int16:
  346. rleft = int64(left.(int16))
  347. case int32:
  348. rleft = int64(left.(int32))
  349. case int64:
  350. rleft = left.(int64)
  351. case float32:
  352. fleft = float64(left.(float32))
  353. isInt = false
  354. case float64:
  355. fleft = left.(float64)
  356. isInt = false
  357. }
  358. switch right.(type) {
  359. case int:
  360. rright = int64(right.(int))
  361. case int8:
  362. rright = int64(right.(int8))
  363. case int16:
  364. rright = int64(right.(int16))
  365. case int32:
  366. rright = int64(right.(int32))
  367. case int64:
  368. rright = right.(int64)
  369. case float32:
  370. fright = float64(right.(float32))
  371. isInt = false
  372. case float64:
  373. fright = right.(float64)
  374. isInt = false
  375. }
  376. if isInt {
  377. return rleft - rright
  378. }
  379. return fleft + float64(rleft) - (fright + float64(rright))
  380. }
  381. // EllipsisString returns a truncated short string,
  382. // it appends '...' in the end of the length of string is too large.
  383. func EllipsisString(str string, length int) string {
  384. if length <= 3 {
  385. return "..."
  386. }
  387. if len(str) <= length {
  388. return str
  389. }
  390. return str[:length-3] + "..."
  391. }
  392. // TruncateString returns a truncated string with given limit,
  393. // it returns input string if length is not reached limit.
  394. func TruncateString(str string, limit int) string {
  395. if len(str) < limit {
  396. return str
  397. }
  398. return str[:limit]
  399. }
  400. // StringsToInt64s converts a slice of string to a slice of int64.
  401. func StringsToInt64s(strs []string) ([]int64, error) {
  402. ints := make([]int64, len(strs))
  403. for i := range strs {
  404. n, err := com.StrTo(strs[i]).Int64()
  405. if err != nil {
  406. return ints, err
  407. }
  408. ints[i] = n
  409. }
  410. return ints, nil
  411. }
  412. // Int64sToStrings converts a slice of int64 to a slice of string.
  413. func Int64sToStrings(ints []int64) []string {
  414. strs := make([]string, len(ints))
  415. for i := range ints {
  416. strs[i] = strconv.FormatInt(ints[i], 10)
  417. }
  418. return strs
  419. }
  420. // Int64sToMap converts a slice of int64 to a int64 map.
  421. func Int64sToMap(ints []int64) map[int64]bool {
  422. m := make(map[int64]bool)
  423. for _, i := range ints {
  424. m[i] = true
  425. }
  426. return m
  427. }
  428. // Int64sContains returns if a int64 in a slice of int64
  429. func Int64sContains(intsSlice []int64, a int64) bool {
  430. for _, c := range intsSlice {
  431. if c == a {
  432. return true
  433. }
  434. }
  435. return false
  436. }
  437. // IsLetter reports whether the rune is a letter (category L).
  438. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  439. func IsLetter(ch rune) bool {
  440. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  441. }
  442. // IsTextFile returns true if file content format is plain text or empty.
  443. func IsTextFile(data []byte) bool {
  444. if len(data) == 0 {
  445. return true
  446. }
  447. return strings.Index(http.DetectContentType(data), "text/") != -1
  448. }
  449. // IsImageFile detects if data is an image format
  450. func IsImageFile(data []byte) bool {
  451. return strings.Index(http.DetectContentType(data), "image/") != -1
  452. }
  453. // IsPDFFile detects if data is a pdf format
  454. func IsPDFFile(data []byte) bool {
  455. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  456. }
  457. // IsVideoFile detects if data is an video format
  458. func IsVideoFile(data []byte) bool {
  459. return strings.Index(http.DetectContentType(data), "video/") != -1
  460. }