tool.go 12 KB

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