tool.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  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 tool
  5. import (
  6. "crypto/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "math/big"
  14. "strings"
  15. "time"
  16. "unicode"
  17. "unicode/utf8"
  18. "github.com/unknwon/com"
  19. "github.com/unknwon/i18n"
  20. log "unknwon.dev/clog/v2"
  21. "github.com/gogs/chardet"
  22. "gogs.io/gogs/internal/conf"
  23. )
  24. // MD5Bytes encodes string to MD5 bytes.
  25. // TODO: Move to hashutil.MD5Bytes.
  26. func MD5Bytes(str string) []byte {
  27. m := md5.New()
  28. _, _ = m.Write([]byte(str))
  29. return m.Sum(nil)
  30. }
  31. // MD5 encodes string to MD5 hex value.
  32. // TODO: Move to hashutil.MD5.
  33. func MD5(str string) string {
  34. return hex.EncodeToString(MD5Bytes(str))
  35. }
  36. // SHA1 encodes string to SHA1 hex value.
  37. // TODO: Move to hashutil.SHA1.
  38. func SHA1(str string) string {
  39. h := sha1.New()
  40. _, _ = h.Write([]byte(str))
  41. return hex.EncodeToString(h.Sum(nil))
  42. }
  43. // ShortSHA1 truncates SHA1 string length to at most 10.
  44. func ShortSHA1(sha1 string) string {
  45. if len(sha1) > 10 {
  46. return sha1[:10]
  47. }
  48. return sha1
  49. }
  50. // DetectEncoding returns best guess of encoding of given content.
  51. func DetectEncoding(content []byte) (string, error) {
  52. if utf8.Valid(content) {
  53. log.Trace("Detected encoding: UTF-8 (fast)")
  54. return "UTF-8", nil
  55. }
  56. result, err := chardet.NewTextDetector().DetectBest(content)
  57. if result.Charset != "UTF-8" && len(conf.Repository.ANSICharset) > 0 {
  58. log.Trace("Using default ANSICharset: %s", conf.Repository.ANSICharset)
  59. return conf.Repository.ANSICharset, err
  60. }
  61. log.Trace("Detected encoding: %s", result.Charset)
  62. return result.Charset, err
  63. }
  64. // BasicAuthDecode decodes username and password portions of HTTP Basic Authentication
  65. // from encoded content.
  66. func BasicAuthDecode(encoded string) (string, string, error) {
  67. s, err := base64.StdEncoding.DecodeString(encoded)
  68. if err != nil {
  69. return "", "", err
  70. }
  71. auth := strings.SplitN(string(s), ":", 2)
  72. return auth[0], auth[1], nil
  73. }
  74. // BasicAuthEncode encodes username and password in HTTP Basic Authentication format.
  75. func BasicAuthEncode(username, password string) string {
  76. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  77. }
  78. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  79. // RandomString returns generated random string in given length of characters.
  80. // It also returns possible error during generation.
  81. func RandomString(n int) (string, error) {
  82. buffer := make([]byte, n)
  83. max := big.NewInt(int64(len(alphanum)))
  84. for i := 0; i < n; i++ {
  85. index, err := randomInt(max)
  86. if err != nil {
  87. return "", err
  88. }
  89. buffer[i] = alphanum[index]
  90. }
  91. return string(buffer), nil
  92. }
  93. func randomInt(max *big.Int) (int, error) {
  94. rand, err := rand.Int(rand.Reader, max)
  95. if err != nil {
  96. return 0, err
  97. }
  98. return int(rand.Int64()), nil
  99. }
  100. // verify time limit code
  101. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  102. if len(code) <= 18 {
  103. return false
  104. }
  105. // split code
  106. start := code[:12]
  107. lives := code[12:18]
  108. if d, err := com.StrTo(lives).Int(); err == nil {
  109. minutes = d
  110. }
  111. // right active code
  112. retCode := CreateTimeLimitCode(data, minutes, start)
  113. if retCode == code && minutes > 0 {
  114. // check time is expired or not
  115. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  116. now := time.Now()
  117. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  118. return true
  119. }
  120. }
  121. return false
  122. }
  123. const TIME_LIMIT_CODE_LENGTH = 12 + 6 + 40
  124. // CreateTimeLimitCode generates a time limit code based on given input data.
  125. // Format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  126. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  127. format := "200601021504"
  128. var start, end time.Time
  129. var startStr, endStr string
  130. if startInf == nil {
  131. // Use now time create code
  132. start = time.Now()
  133. startStr = start.Format(format)
  134. } else {
  135. // use start string create code
  136. startStr = startInf.(string)
  137. start, _ = time.ParseInLocation(format, startStr, time.Local)
  138. startStr = start.Format(format)
  139. }
  140. end = start.Add(time.Minute * time.Duration(minutes))
  141. endStr = end.Format(format)
  142. // create sha1 encode string
  143. sh := sha1.New()
  144. _, _ = sh.Write([]byte(data + conf.Security.SecretKey + startStr + endStr + com.ToStr(minutes)))
  145. encoded := hex.EncodeToString(sh.Sum(nil))
  146. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  147. return code
  148. }
  149. // HashEmail hashes email address to MD5 string.
  150. // https://en.gravatar.com/site/implement/hash/
  151. func HashEmail(email string) string {
  152. email = strings.ToLower(strings.TrimSpace(email))
  153. h := md5.New()
  154. _, _ = h.Write([]byte(email))
  155. return hex.EncodeToString(h.Sum(nil))
  156. }
  157. // AvatarLink returns relative avatar link to the site domain by given email,
  158. // which includes app sub-url as prefix. However, it is possible
  159. // to return full URL if user enables Gravatar-like service.
  160. func AvatarLink(email string) (url string) {
  161. if conf.Picture.EnableFederatedAvatar && conf.Picture.LibravatarService != nil &&
  162. strings.Contains(email, "@") {
  163. var err error
  164. url, err = conf.Picture.LibravatarService.FromEmail(email)
  165. if err != nil {
  166. log.Warn("AvatarLink.LibravatarService.FromEmail [%s]: %v", email, err)
  167. }
  168. }
  169. if len(url) == 0 && !conf.Picture.DisableGravatar {
  170. url = conf.Picture.GravatarSource + HashEmail(email) + "?d=identicon"
  171. }
  172. if len(url) == 0 {
  173. url = conf.Server.Subpath + "/img/avatar_default.png"
  174. }
  175. return url
  176. }
  177. // AppendAvatarSize appends avatar size query parameter to the URL in the correct format.
  178. func AppendAvatarSize(url string, size int) string {
  179. if strings.Contains(url, "?") {
  180. return url + "&s=" + com.ToStr(size)
  181. }
  182. return url + "?s=" + com.ToStr(size)
  183. }
  184. // Seconds-based time units
  185. const (
  186. Minute = 60
  187. Hour = 60 * Minute
  188. Day = 24 * Hour
  189. Week = 7 * Day
  190. Month = 30 * Day
  191. Year = 12 * Month
  192. )
  193. func computeTimeDiff(diff int64) (int64, string) {
  194. diffStr := ""
  195. switch {
  196. case diff <= 0:
  197. diff = 0
  198. diffStr = "now"
  199. case diff < 2:
  200. diff = 0
  201. diffStr = "1 second"
  202. case diff < 1*Minute:
  203. diffStr = fmt.Sprintf("%d seconds", diff)
  204. diff = 0
  205. case diff < 2*Minute:
  206. diff -= 1 * Minute
  207. diffStr = "1 minute"
  208. case diff < 1*Hour:
  209. diffStr = fmt.Sprintf("%d minutes", diff/Minute)
  210. diff -= diff / Minute * Minute
  211. case diff < 2*Hour:
  212. diff -= 1 * Hour
  213. diffStr = "1 hour"
  214. case diff < 1*Day:
  215. diffStr = fmt.Sprintf("%d hours", diff/Hour)
  216. diff -= diff / Hour * Hour
  217. case diff < 2*Day:
  218. diff -= 1 * Day
  219. diffStr = "1 day"
  220. case diff < 1*Week:
  221. diffStr = fmt.Sprintf("%d days", diff/Day)
  222. diff -= diff / Day * Day
  223. case diff < 2*Week:
  224. diff -= 1 * Week
  225. diffStr = "1 week"
  226. case diff < 1*Month:
  227. diffStr = fmt.Sprintf("%d weeks", diff/Week)
  228. diff -= diff / Week * Week
  229. case diff < 2*Month:
  230. diff -= 1 * Month
  231. diffStr = "1 month"
  232. case diff < 1*Year:
  233. diffStr = fmt.Sprintf("%d months", diff/Month)
  234. diff -= diff / Month * Month
  235. case diff < 2*Year:
  236. diff -= 1 * Year
  237. diffStr = "1 year"
  238. default:
  239. diffStr = fmt.Sprintf("%d years", diff/Year)
  240. diff = 0
  241. }
  242. return diff, diffStr
  243. }
  244. // TimeSincePro calculates the time interval and generate full user-friendly string.
  245. func TimeSincePro(then time.Time) string {
  246. now := time.Now()
  247. diff := now.Unix() - then.Unix()
  248. if then.After(now) {
  249. return "future"
  250. }
  251. var timeStr, diffStr string
  252. for {
  253. if diff == 0 {
  254. break
  255. }
  256. diff, diffStr = computeTimeDiff(diff)
  257. timeStr += ", " + diffStr
  258. }
  259. return strings.TrimPrefix(timeStr, ", ")
  260. }
  261. func timeSince(then time.Time, lang string) string {
  262. now := time.Now()
  263. lbl := i18n.Tr(lang, "tool.ago")
  264. diff := now.Unix() - then.Unix()
  265. if then.After(now) {
  266. lbl = i18n.Tr(lang, "tool.from_now")
  267. diff = then.Unix() - now.Unix()
  268. }
  269. switch {
  270. case diff <= 0:
  271. return i18n.Tr(lang, "tool.now")
  272. case diff <= 2:
  273. return i18n.Tr(lang, "tool.1s", lbl)
  274. case diff < 1*Minute:
  275. return i18n.Tr(lang, "tool.seconds", diff, lbl)
  276. case diff < 2*Minute:
  277. return i18n.Tr(lang, "tool.1m", lbl)
  278. case diff < 1*Hour:
  279. return i18n.Tr(lang, "tool.minutes", diff/Minute, lbl)
  280. case diff < 2*Hour:
  281. return i18n.Tr(lang, "tool.1h", lbl)
  282. case diff < 1*Day:
  283. return i18n.Tr(lang, "tool.hours", diff/Hour, lbl)
  284. case diff < 2*Day:
  285. return i18n.Tr(lang, "tool.1d", lbl)
  286. case diff < 1*Week:
  287. return i18n.Tr(lang, "tool.days", diff/Day, lbl)
  288. case diff < 2*Week:
  289. return i18n.Tr(lang, "tool.1w", lbl)
  290. case diff < 1*Month:
  291. return i18n.Tr(lang, "tool.weeks", diff/Week, lbl)
  292. case diff < 2*Month:
  293. return i18n.Tr(lang, "tool.1mon", lbl)
  294. case diff < 1*Year:
  295. return i18n.Tr(lang, "tool.months", diff/Month, lbl)
  296. case diff < 2*Year:
  297. return i18n.Tr(lang, "tool.1y", lbl)
  298. default:
  299. return i18n.Tr(lang, "tool.years", diff/Year, lbl)
  300. }
  301. }
  302. func RawTimeSince(t time.Time, lang string) string {
  303. return timeSince(t, lang)
  304. }
  305. // TimeSince calculates the time interval and generate user-friendly string.
  306. func TimeSince(t time.Time, lang string) template.HTML {
  307. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`, t.Format(conf.Time.FormatLayout), timeSince(t, lang)))
  308. }
  309. // Subtract deals with subtraction of all types of number.
  310. func Subtract(left interface{}, right interface{}) interface{} {
  311. var rleft, rright int64
  312. var fleft, fright float64
  313. var isInt = true
  314. switch left := left.(type) {
  315. case int:
  316. rleft = int64(left)
  317. case int8:
  318. rleft = int64(left)
  319. case int16:
  320. rleft = int64(left)
  321. case int32:
  322. rleft = int64(left)
  323. case int64:
  324. rleft = left
  325. case float32:
  326. fleft = float64(left)
  327. isInt = false
  328. case float64:
  329. fleft = left
  330. isInt = false
  331. }
  332. switch right := right.(type) {
  333. case int:
  334. rright = int64(right)
  335. case int8:
  336. rright = int64(right)
  337. case int16:
  338. rright = int64(right)
  339. case int32:
  340. rright = int64(right)
  341. case int64:
  342. rright = right
  343. case float32:
  344. fright = float64(left.(float32))
  345. isInt = false
  346. case float64:
  347. fleft = left.(float64)
  348. isInt = false
  349. }
  350. if isInt {
  351. return rleft - rright
  352. } else {
  353. return fleft + float64(rleft) - (fright + float64(rright))
  354. }
  355. }
  356. // EllipsisString returns a truncated short string,
  357. // it appends '...' in the end of the length of string is too large.
  358. func EllipsisString(str string, length int) string {
  359. if len(str) < length {
  360. return str
  361. }
  362. return str[:length-3] + "..."
  363. }
  364. // TruncateString returns a truncated string with given limit,
  365. // it returns input string if length is not reached limit.
  366. func TruncateString(str string, limit int) string {
  367. if len(str) < limit {
  368. return str
  369. }
  370. return str[:limit]
  371. }
  372. // StringsToInt64s converts a slice of string to a slice of int64.
  373. func StringsToInt64s(strs []string) []int64 {
  374. ints := make([]int64, len(strs))
  375. for i := range strs {
  376. ints[i] = com.StrTo(strs[i]).MustInt64()
  377. }
  378. return ints
  379. }
  380. // Int64sToStrings converts a slice of int64 to a slice of string.
  381. func Int64sToStrings(ints []int64) []string {
  382. strs := make([]string, len(ints))
  383. for i := range ints {
  384. strs[i] = com.ToStr(ints[i])
  385. }
  386. return strs
  387. }
  388. // Int64sToMap converts a slice of int64 to a int64 map.
  389. func Int64sToMap(ints []int64) map[int64]bool {
  390. m := make(map[int64]bool)
  391. for _, i := range ints {
  392. m[i] = true
  393. }
  394. return m
  395. }
  396. // IsLetter reports whether the rune is a letter (category L).
  397. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  398. func IsLetter(ch rune) bool {
  399. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  400. }