You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

tool.go 13 kB

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