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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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/hmac"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "hash"
  14. "html/template"
  15. "math"
  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 result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  53. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  54. return setting.Repository.AnsiCharset, err
  55. }
  56. log.Debug("Detected encoding: %s", result.Charset)
  57. return result.Charset, err
  58. }
  59. // BasicAuthDecode decode basic auth string
  60. func BasicAuthDecode(encoded string) (string, string, error) {
  61. s, err := base64.StdEncoding.DecodeString(encoded)
  62. if err != nil {
  63. return "", "", err
  64. }
  65. auth := strings.SplitN(string(s), ":", 2)
  66. return auth[0], auth[1], nil
  67. }
  68. // BasicAuthEncode encode basic auth string
  69. func BasicAuthEncode(username, password string) string {
  70. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  71. }
  72. // GetRandomString generate random string by specify chars.
  73. func GetRandomString(n int, alphabets ...byte) string {
  74. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  75. var bytes = make([]byte, n)
  76. rand.Read(bytes)
  77. for i, b := range bytes {
  78. if len(alphabets) == 0 {
  79. bytes[i] = alphanum[b%byte(len(alphanum))]
  80. } else {
  81. bytes[i] = alphabets[b%byte(len(alphabets))]
  82. }
  83. }
  84. return string(bytes)
  85. }
  86. // PBKDF2 http://code.google.com/p/go/source/browse/pbkdf2/pbkdf2.go?repo=crypto
  87. // FIXME: use https://godoc.org/golang.org/x/crypto/pbkdf2?
  88. func PBKDF2(password, salt []byte, iter, keyLen int, h func() hash.Hash) []byte {
  89. prf := hmac.New(h, password)
  90. hashLen := prf.Size()
  91. numBlocks := (keyLen + hashLen - 1) / hashLen
  92. var buf [4]byte
  93. dk := make([]byte, 0, numBlocks*hashLen)
  94. U := make([]byte, hashLen)
  95. for block := 1; block <= numBlocks; block++ {
  96. // N.B.: || means concatenation, ^ means XOR
  97. // for each block T_i = U_1 ^ U_2 ^ ... ^ U_iter
  98. // U_1 = PRF(password, salt || uint(i))
  99. prf.Reset()
  100. prf.Write(salt)
  101. buf[0] = byte(block >> 24)
  102. buf[1] = byte(block >> 16)
  103. buf[2] = byte(block >> 8)
  104. buf[3] = byte(block)
  105. prf.Write(buf[:4])
  106. dk = prf.Sum(dk)
  107. T := dk[len(dk)-hashLen:]
  108. copy(U, T)
  109. // U_n = PRF(password, U_(n-1))
  110. for n := 2; n <= iter; n++ {
  111. prf.Reset()
  112. prf.Write(U)
  113. U = U[:0]
  114. U = prf.Sum(U)
  115. for x := range U {
  116. T[x] ^= U[x]
  117. }
  118. }
  119. }
  120. return dk[:keyLen]
  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. // AvatarLink returns relative avatar link to the site domain by given email,
  178. // which includes app sub-url as prefix. However, it is possible
  179. // to return full URL if user enables Gravatar-like service.
  180. func AvatarLink(email string) string {
  181. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  182. // TODO: This doesn't check any error. AvatarLink should return (string, error)
  183. url, _ := setting.LibravatarService.FromEmail(email)
  184. return url
  185. }
  186. if !setting.DisableGravatar {
  187. return setting.GravatarSource + HashEmail(email)
  188. }
  189. return setting.AppSubURL + "/img/avatar_default.png"
  190. }
  191. // Seconds-based time units
  192. const (
  193. Minute = 60
  194. Hour = 60 * Minute
  195. Day = 24 * Hour
  196. Week = 7 * Day
  197. Month = 30 * Day
  198. Year = 12 * Month
  199. )
  200. func computeTimeDiff(diff int64) (int64, string) {
  201. diffStr := ""
  202. switch {
  203. case diff <= 0:
  204. diff = 0
  205. diffStr = "now"
  206. case diff < 2:
  207. diff = 0
  208. diffStr = "1 second"
  209. case diff < 1*Minute:
  210. diffStr = fmt.Sprintf("%d seconds", diff)
  211. diff = 0
  212. case diff < 2*Minute:
  213. diff -= 1 * Minute
  214. diffStr = "1 minute"
  215. case diff < 1*Hour:
  216. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  217. diff -= diff / Minute * Minute
  218. case diff < 2*Hour:
  219. diff -= 1 * Hour
  220. diffStr = "1 hour"
  221. case diff < 1*Day:
  222. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  223. diff -= diff / Hour * Hour
  224. case diff < 2*Day:
  225. diff -= 1 * Day
  226. diffStr = "1 day"
  227. case diff < 1*Week:
  228. diffStr = fmt.Sprintf("%d days", diff/Day)
  229. diff -= diff / Day * Day
  230. case diff < 2*Week:
  231. diff -= 1 * Week
  232. diffStr = "1 week"
  233. case diff < 1*Month:
  234. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  235. diff -= diff / Week * Week
  236. case diff < 2*Month:
  237. diff -= 1 * Month
  238. diffStr = "1 month"
  239. case diff < 1*Year:
  240. diffStr = fmt.Sprintf("%d months", diff/Month)
  241. diff -= diff / Month * Month
  242. case diff < 2*Year:
  243. diff -= 1 * Year
  244. diffStr = "1 year"
  245. default:
  246. diffStr = fmt.Sprintf("%d years", diff/Year)
  247. diff = 0
  248. }
  249. return diff, diffStr
  250. }
  251. // TimeSincePro calculates the time interval and generate full user-friendly string.
  252. func TimeSincePro(then time.Time) string {
  253. now := time.Now()
  254. diff := now.Unix() - then.Unix()
  255. if then.After(now) {
  256. return "future"
  257. }
  258. var timeStr, diffStr string
  259. for {
  260. if diff == 0 {
  261. break
  262. }
  263. diff, diffStr = computeTimeDiff(diff)
  264. timeStr += ", " + diffStr
  265. }
  266. return strings.TrimPrefix(timeStr, ", ")
  267. }
  268. func timeSince(then time.Time, lang string) string {
  269. now := time.Now()
  270. lbl := i18n.Tr(lang, "tool.ago")
  271. diff := now.Unix() - then.Unix()
  272. if then.After(now) {
  273. lbl = i18n.Tr(lang, "tool.from_now")
  274. diff = then.Unix() - now.Unix()
  275. }
  276. switch {
  277. case diff <= 0:
  278. return i18n.Tr(lang, "tool.now")
  279. case diff <= 2:
  280. return i18n.Tr(lang, "tool.1s", lbl)
  281. case diff < 1*Minute:
  282. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  283. case diff < 2*Minute:
  284. return i18n.Tr(lang, "tool.1m", lbl)
  285. case diff < 1*Hour:
  286. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  287. case diff < 2*Hour:
  288. return i18n.Tr(lang, "tool.1h", lbl)
  289. case diff < 1*Day:
  290. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  291. case diff < 2*Day:
  292. return i18n.Tr(lang, "tool.1d", lbl)
  293. case diff < 1*Week:
  294. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  295. case diff < 2*Week:
  296. return i18n.Tr(lang, "tool.1w", lbl)
  297. case diff < 1*Month:
  298. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  299. case diff < 2*Month:
  300. return i18n.Tr(lang, "tool.1mon", lbl)
  301. case diff < 1*Year:
  302. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  303. case diff < 2*Year:
  304. return i18n.Tr(lang, "tool.1y", lbl)
  305. default:
  306. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  307. }
  308. }
  309. // RawTimeSince retrieves i18n key of time since t
  310. func RawTimeSince(t time.Time, lang string) string {
  311. return timeSince(t, lang)
  312. }
  313. // TimeSince calculates the time interval and generate user-friendly string.
  314. func TimeSince(t time.Time, lang string) template.HTML {
  315. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(setting.TimeFormat), timeSince(t, lang)))
  316. }
  317. // Storage space size types
  318. const (
  319. Byte = 1
  320. KByte = Byte * 1024
  321. MByte = KByte * 1024
  322. GByte = MByte * 1024
  323. TByte = GByte * 1024
  324. PByte = TByte * 1024
  325. EByte = PByte * 1024
  326. )
  327. var bytesSizeTable = map[string]uint64{
  328. "b": Byte,
  329. "kb": KByte,
  330. "mb": MByte,
  331. "gb": GByte,
  332. "tb": TByte,
  333. "pb": PByte,
  334. "eb": EByte,
  335. }
  336. func logn(n, b float64) float64 {
  337. return math.Log(n) / math.Log(b)
  338. }
  339. func humanateBytes(s uint64, base float64, sizes []string) string {
  340. if s < 10 {
  341. return fmt.Sprintf("%dB", s)
  342. }
  343. e := math.Floor(logn(float64(s), base))
  344. suffix := sizes[int(e)]
  345. val := float64(s) / math.Pow(base, math.Floor(e))
  346. f := "%.0f"
  347. if val < 10 {
  348. f = "%.1f"
  349. }
  350. return fmt.Sprintf(f+"%s", val, suffix)
  351. }
  352. // FileSize calculates the file size and generate user-friendly string.
  353. func FileSize(s int64) string {
  354. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  355. return humanateBytes(uint64(s), 1024, sizes)
  356. }
  357. // Subtract deals with subtraction of all types of number.
  358. func Subtract(left interface{}, right interface{}) interface{} {
  359. var rleft, rright int64
  360. var fleft, fright float64
  361. var isInt = true
  362. switch left.(type) {
  363. case int:
  364. rleft = int64(left.(int))
  365. case int8:
  366. rleft = int64(left.(int8))
  367. case int16:
  368. rleft = int64(left.(int16))
  369. case int32:
  370. rleft = int64(left.(int32))
  371. case int64:
  372. rleft = left.(int64)
  373. case float32:
  374. fleft = float64(left.(float32))
  375. isInt = false
  376. case float64:
  377. fleft = left.(float64)
  378. isInt = false
  379. }
  380. switch right.(type) {
  381. case int:
  382. rright = int64(right.(int))
  383. case int8:
  384. rright = int64(right.(int8))
  385. case int16:
  386. rright = int64(right.(int16))
  387. case int32:
  388. rright = int64(right.(int32))
  389. case int64:
  390. rright = right.(int64)
  391. case float32:
  392. fright = float64(left.(float32))
  393. isInt = false
  394. case float64:
  395. fleft = left.(float64)
  396. isInt = false
  397. }
  398. if isInt {
  399. return rleft - rright
  400. }
  401. return fleft + float64(rleft) - (fright + float64(rright))
  402. }
  403. // EllipsisString returns a truncated short string,
  404. // it appends '...' in the end of the length of string is too large.
  405. func EllipsisString(str string, length int) string {
  406. if length <= 3 {
  407. return "..."
  408. }
  409. if len(str) <= length {
  410. return str
  411. }
  412. return str[:length-3] + "..."
  413. }
  414. // TruncateString returns a truncated string with given limit,
  415. // it returns input string if length is not reached limit.
  416. func TruncateString(str string, limit int) string {
  417. if len(str) < limit {
  418. return str
  419. }
  420. return str[:limit]
  421. }
  422. // StringsToInt64s converts a slice of string to a slice of int64.
  423. func StringsToInt64s(strs []string) []int64 {
  424. ints := make([]int64, len(strs))
  425. for i := range strs {
  426. ints[i] = com.StrTo(strs[i]).MustInt64()
  427. }
  428. return ints
  429. }
  430. // Int64sToStrings converts a slice of int64 to a slice of string.
  431. func Int64sToStrings(ints []int64) []string {
  432. strs := make([]string, len(ints))
  433. for i := range ints {
  434. strs[i] = strconv.FormatInt(ints[i], 10)
  435. }
  436. return strs
  437. }
  438. // Int64sToMap converts a slice of int64 to a int64 map.
  439. func Int64sToMap(ints []int64) map[int64]bool {
  440. m := make(map[int64]bool)
  441. for _, i := range ints {
  442. m[i] = true
  443. }
  444. return m
  445. }
  446. // IsLetter reports whether the rune is a letter (category L).
  447. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  448. func IsLetter(ch rune) bool {
  449. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  450. }
  451. // IsTextFile returns true if file content format is plain text or empty.
  452. func IsTextFile(data []byte) bool {
  453. if len(data) == 0 {
  454. return true
  455. }
  456. return strings.Index(http.DetectContentType(data), "text/") != -1
  457. }
  458. // IsImageFile detectes if data is an image format
  459. func IsImageFile(data []byte) bool {
  460. return strings.Index(http.DetectContentType(data), "image/") != -1
  461. }
  462. // IsPDFFile detectes if data is a pdf format
  463. func IsPDFFile(data []byte) bool {
  464. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  465. }