tool.go 13 KB

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