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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  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/md5"
  7. "crypto/rand"
  8. "crypto/sha1"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "html/template"
  13. "io"
  14. "math"
  15. "net/http"
  16. "net/url"
  17. "path"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "unicode"
  22. "unicode/utf8"
  23. "code.gitea.io/git"
  24. "code.gitea.io/gitea/modules/log"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/util"
  27. "github.com/Unknwon/com"
  28. "github.com/Unknwon/i18n"
  29. "github.com/gogits/chardet"
  30. )
  31. // EncodeMD5 encodes string to md5 hex value.
  32. func EncodeMD5(str string) string {
  33. m := md5.New()
  34. m.Write([]byte(str))
  35. return hex.EncodeToString(m.Sum(nil))
  36. }
  37. // EncodeSha1 string to sha1 hex value.
  38. func EncodeSha1(str string) string {
  39. h := sha1.New()
  40. h.Write([]byte(str))
  41. return hex.EncodeToString(h.Sum(nil))
  42. }
  43. // ShortSha is basically just truncating.
  44. // It is DEPRECATED and will be removed in the future.
  45. func ShortSha(sha1 string) string {
  46. return TruncateString(sha1, 10)
  47. }
  48. // DetectEncoding detect the encoding of content
  49. func DetectEncoding(content []byte) (string, error) {
  50. if utf8.Valid(content) {
  51. log.Debug("Detected encoding: utf-8 (fast)")
  52. return "UTF-8", nil
  53. }
  54. textDetector := chardet.NewTextDetector()
  55. var detectContent []byte
  56. if len(content) < 1024 {
  57. // Check if original content is valid
  58. if _, err := textDetector.DetectBest(content); err != nil {
  59. return "", err
  60. }
  61. times := 1024 / len(content)
  62. detectContent = make([]byte, 0, times*len(content))
  63. for i := 0; i < times; i++ {
  64. detectContent = append(detectContent, content...)
  65. }
  66. } else {
  67. detectContent = content
  68. }
  69. result, err := textDetector.DetectBest(detectContent)
  70. if err != nil {
  71. return "", err
  72. }
  73. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  74. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  75. return setting.Repository.AnsiCharset, err
  76. }
  77. log.Debug("Detected encoding: %s", result.Charset)
  78. return result.Charset, err
  79. }
  80. // BasicAuthDecode decode basic auth string
  81. func BasicAuthDecode(encoded string) (string, string, error) {
  82. s, err := base64.StdEncoding.DecodeString(encoded)
  83. if err != nil {
  84. return "", "", err
  85. }
  86. auth := strings.SplitN(string(s), ":", 2)
  87. return auth[0], auth[1], nil
  88. }
  89. // BasicAuthEncode encode basic auth string
  90. func BasicAuthEncode(username, password string) string {
  91. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  92. }
  93. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  94. func GetRandomBytesAsBase64(n int) string {
  95. bytes := make([]byte, 32)
  96. _, err := io.ReadFull(rand.Reader, bytes)
  97. if err != nil {
  98. log.Fatal(4, "Error reading random bytes: %v", err)
  99. }
  100. return base64.RawURLEncoding.EncodeToString(bytes)
  101. }
  102. // VerifyTimeLimitCode verify time limit code
  103. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  104. if len(code) <= 18 {
  105. return false
  106. }
  107. // split code
  108. start := code[:12]
  109. lives := code[12:18]
  110. if d, err := com.StrTo(lives).Int(); err == nil {
  111. minutes = d
  112. }
  113. // right active code
  114. retCode := CreateTimeLimitCode(data, minutes, start)
  115. if retCode == code && minutes > 0 {
  116. // check time is expired or not
  117. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  118. now := time.Now()
  119. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  120. return true
  121. }
  122. }
  123. return false
  124. }
  125. // TimeLimitCodeLength default value for time limit code
  126. const TimeLimitCodeLength = 12 + 6 + 40
  127. // CreateTimeLimitCode create a time limit code
  128. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  129. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  130. format := "200601021504"
  131. var start, end time.Time
  132. var startStr, endStr string
  133. if startInf == nil {
  134. // Use now time create code
  135. start = time.Now()
  136. startStr = start.Format(format)
  137. } else {
  138. // use start string create code
  139. startStr = startInf.(string)
  140. start, _ = time.ParseInLocation(format, startStr, time.Local)
  141. startStr = start.Format(format)
  142. }
  143. end = start.Add(time.Minute * time.Duration(minutes))
  144. endStr = end.Format(format)
  145. // create sha1 encode string
  146. sh := sha1.New()
  147. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  148. encoded := hex.EncodeToString(sh.Sum(nil))
  149. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  150. return code
  151. }
  152. // HashEmail hashes email address to MD5 string.
  153. // https://en.gravatar.com/site/implement/hash/
  154. func HashEmail(email string) string {
  155. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  156. }
  157. // DefaultAvatarLink the default avatar link
  158. func DefaultAvatarLink() string {
  159. return setting.AppSubURL + "/img/avatar_default.png"
  160. }
  161. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  162. // determined by the avatar-hosting service.
  163. const DefaultAvatarSize = -1
  164. // libravatarURL returns the URL for the given email. This function should only
  165. // be called if a federated avatar service is enabled.
  166. func libravatarURL(email string) (*url.URL, error) {
  167. urlStr, err := setting.LibravatarService.FromEmail(email)
  168. if err != nil {
  169. log.Error(4, "LibravatarService.FromEmail(email=%s): error %v", email, err)
  170. return nil, err
  171. }
  172. u, err := url.Parse(urlStr)
  173. if err != nil {
  174. log.Error(4, "Failed to parse libravatar url(%s): error %v", urlStr, err)
  175. return nil, err
  176. }
  177. return u, nil
  178. }
  179. // SizedAvatarLink returns a sized link to the avatar for the given email
  180. // address.
  181. func SizedAvatarLink(email string, size int) string {
  182. var avatarURL *url.URL
  183. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  184. var err error
  185. avatarURL, err = libravatarURL(email)
  186. if err != nil {
  187. return DefaultAvatarLink()
  188. }
  189. } else if !setting.DisableGravatar {
  190. // copy GravatarSourceURL, because we will modify its Path.
  191. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  192. avatarURL = &copyOfGravatarSourceURL
  193. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  194. } else {
  195. return DefaultAvatarLink()
  196. }
  197. vals := avatarURL.Query()
  198. vals.Set("d", "identicon")
  199. if size != DefaultAvatarSize {
  200. vals.Set("s", strconv.Itoa(size))
  201. }
  202. avatarURL.RawQuery = vals.Encode()
  203. return avatarURL.String()
  204. }
  205. // AvatarLink returns relative avatar link to the site domain by given email,
  206. // which includes app sub-url as prefix. However, it is possible
  207. // to return full URL if user enables Gravatar-like service.
  208. func AvatarLink(email string) string {
  209. return SizedAvatarLink(email, DefaultAvatarSize)
  210. }
  211. // Seconds-based time units
  212. const (
  213. Minute = 60
  214. Hour = 60 * Minute
  215. Day = 24 * Hour
  216. Week = 7 * Day
  217. Month = 30 * Day
  218. Year = 12 * Month
  219. )
  220. func computeTimeDiff(diff int64, lang string) (int64, string) {
  221. diffStr := ""
  222. switch {
  223. case diff <= 0:
  224. diff = 0
  225. diffStr = i18n.Tr(lang, "tool.now")
  226. case diff < 2:
  227. diff = 0
  228. diffStr = i18n.Tr(lang, "tool.1s")
  229. case diff < 1*Minute:
  230. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  231. diff = 0
  232. case diff < 2*Minute:
  233. diff -= 1 * Minute
  234. diffStr = i18n.Tr(lang, "tool.1m")
  235. case diff < 1*Hour:
  236. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  237. diff -= diff / Minute * Minute
  238. case diff < 2*Hour:
  239. diff -= 1 * Hour
  240. diffStr = i18n.Tr(lang, "tool.1h")
  241. case diff < 1*Day:
  242. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  243. diff -= diff / Hour * Hour
  244. case diff < 2*Day:
  245. diff -= 1 * Day
  246. diffStr = i18n.Tr(lang, "tool.1d")
  247. case diff < 1*Week:
  248. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  249. diff -= diff / Day * Day
  250. case diff < 2*Week:
  251. diff -= 1 * Week
  252. diffStr = i18n.Tr(lang, "tool.1w")
  253. case diff < 1*Month:
  254. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  255. diff -= diff / Week * Week
  256. case diff < 2*Month:
  257. diff -= 1 * Month
  258. diffStr = i18n.Tr(lang, "tool.1mon")
  259. case diff < 1*Year:
  260. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  261. diff -= diff / Month * Month
  262. case diff < 2*Year:
  263. diff -= 1 * Year
  264. diffStr = i18n.Tr(lang, "tool.1y")
  265. default:
  266. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  267. diff -= (diff / Year) * Year
  268. }
  269. return diff, diffStr
  270. }
  271. // MinutesToFriendly returns a user friendly string with number of minutes
  272. // converted to hours and minutes.
  273. func MinutesToFriendly(minutes int, lang string) string {
  274. duration := time.Duration(minutes) * time.Minute
  275. return TimeSincePro(time.Now().Add(-duration), lang)
  276. }
  277. // TimeSincePro calculates the time interval and generate full user-friendly string.
  278. func TimeSincePro(then time.Time, lang string) string {
  279. return timeSincePro(then, time.Now(), lang)
  280. }
  281. func timeSincePro(then, now time.Time, lang string) string {
  282. diff := now.Unix() - then.Unix()
  283. if then.After(now) {
  284. return i18n.Tr(lang, "tool.future")
  285. }
  286. if diff == 0 {
  287. return i18n.Tr(lang, "tool.now")
  288. }
  289. var timeStr, diffStr string
  290. for {
  291. if diff == 0 {
  292. break
  293. }
  294. diff, diffStr = computeTimeDiff(diff, lang)
  295. timeStr += ", " + diffStr
  296. }
  297. return strings.TrimPrefix(timeStr, ", ")
  298. }
  299. func timeSince(then, now time.Time, lang string) string {
  300. return timeSinceUnix(then.Unix(), now.Unix(), lang)
  301. }
  302. func timeSinceUnix(then, now int64, lang string) string {
  303. lbl := "tool.ago"
  304. diff := now - then
  305. if then > now {
  306. lbl = "tool.from_now"
  307. diff = then - now
  308. }
  309. if diff <= 0 {
  310. return i18n.Tr(lang, "tool.now")
  311. }
  312. _, diffStr := computeTimeDiff(diff, lang)
  313. return i18n.Tr(lang, lbl, diffStr)
  314. }
  315. // RawTimeSince retrieves i18n key of time since t
  316. func RawTimeSince(t time.Time, lang string) string {
  317. return timeSince(t, time.Now(), lang)
  318. }
  319. // TimeSince calculates the time interval and generate user-friendly string.
  320. func TimeSince(then time.Time, lang string) template.HTML {
  321. return htmlTimeSince(then, time.Now(), lang)
  322. }
  323. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  324. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  325. then.Format(setting.TimeFormat),
  326. timeSince(then, now, lang)))
  327. }
  328. // TimeSinceUnix calculates the time interval and generate user-friendly string.
  329. func TimeSinceUnix(then util.TimeStamp, lang string) template.HTML {
  330. return htmlTimeSinceUnix(then, util.TimeStamp(time.Now().Unix()), lang)
  331. }
  332. func htmlTimeSinceUnix(then, now util.TimeStamp, lang string) template.HTML {
  333. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  334. then.Format(setting.TimeFormat),
  335. timeSinceUnix(int64(then), int64(now), lang)))
  336. }
  337. // Storage space size types
  338. const (
  339. Byte = 1
  340. KByte = Byte * 1024
  341. MByte = KByte * 1024
  342. GByte = MByte * 1024
  343. TByte = GByte * 1024
  344. PByte = TByte * 1024
  345. EByte = PByte * 1024
  346. )
  347. var bytesSizeTable = map[string]uint64{
  348. "b": Byte,
  349. "kb": KByte,
  350. "mb": MByte,
  351. "gb": GByte,
  352. "tb": TByte,
  353. "pb": PByte,
  354. "eb": EByte,
  355. }
  356. func logn(n, b float64) float64 {
  357. return math.Log(n) / math.Log(b)
  358. }
  359. func humanateBytes(s uint64, base float64, sizes []string) string {
  360. if s < 10 {
  361. return fmt.Sprintf("%dB", s)
  362. }
  363. e := math.Floor(logn(float64(s), base))
  364. suffix := sizes[int(e)]
  365. val := float64(s) / math.Pow(base, math.Floor(e))
  366. f := "%.0f"
  367. if val < 10 {
  368. f = "%.1f"
  369. }
  370. return fmt.Sprintf(f+"%s", val, suffix)
  371. }
  372. // FileSize calculates the file size and generate user-friendly string.
  373. func FileSize(s int64) string {
  374. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  375. return humanateBytes(uint64(s), 1024, sizes)
  376. }
  377. // Subtract deals with subtraction of all types of number.
  378. func Subtract(left interface{}, right interface{}) interface{} {
  379. var rleft, rright int64
  380. var fleft, fright float64
  381. var isInt = true
  382. switch left := left.(type) {
  383. case int:
  384. rleft = int64(left)
  385. case int8:
  386. rleft = int64(left)
  387. case int16:
  388. rleft = int64(left)
  389. case int32:
  390. rleft = int64(left)
  391. case int64:
  392. rleft = left
  393. case float32:
  394. fleft = float64(left)
  395. isInt = false
  396. case float64:
  397. fleft = left
  398. isInt = false
  399. }
  400. switch right := right.(type) {
  401. case int:
  402. rright = int64(right)
  403. case int8:
  404. rright = int64(right)
  405. case int16:
  406. rright = int64(right)
  407. case int32:
  408. rright = int64(right)
  409. case int64:
  410. rright = right
  411. case float32:
  412. fright = float64(right)
  413. isInt = false
  414. case float64:
  415. fright = right
  416. isInt = false
  417. }
  418. if isInt {
  419. return rleft - rright
  420. }
  421. return fleft + float64(rleft) - (fright + float64(rright))
  422. }
  423. // EllipsisString returns a truncated short string,
  424. // it appends '...' in the end of the length of string is too large.
  425. func EllipsisString(str string, length int) string {
  426. if length <= 3 {
  427. return "..."
  428. }
  429. if len(str) <= length {
  430. return str
  431. }
  432. return str[:length-3] + "..."
  433. }
  434. // TruncateString returns a truncated string with given limit,
  435. // it returns input string if length is not reached limit.
  436. func TruncateString(str string, limit int) string {
  437. if len(str) < limit {
  438. return str
  439. }
  440. return str[:limit]
  441. }
  442. // StringsToInt64s converts a slice of string to a slice of int64.
  443. func StringsToInt64s(strs []string) ([]int64, error) {
  444. ints := make([]int64, len(strs))
  445. for i := range strs {
  446. n, err := com.StrTo(strs[i]).Int64()
  447. if err != nil {
  448. return ints, err
  449. }
  450. ints[i] = n
  451. }
  452. return ints, nil
  453. }
  454. // Int64sToStrings converts a slice of int64 to a slice of string.
  455. func Int64sToStrings(ints []int64) []string {
  456. strs := make([]string, len(ints))
  457. for i := range ints {
  458. strs[i] = strconv.FormatInt(ints[i], 10)
  459. }
  460. return strs
  461. }
  462. // Int64sToMap converts a slice of int64 to a int64 map.
  463. func Int64sToMap(ints []int64) map[int64]bool {
  464. m := make(map[int64]bool)
  465. for _, i := range ints {
  466. m[i] = true
  467. }
  468. return m
  469. }
  470. // Int64sContains returns if a int64 in a slice of int64
  471. func Int64sContains(intsSlice []int64, a int64) bool {
  472. for _, c := range intsSlice {
  473. if c == a {
  474. return true
  475. }
  476. }
  477. return false
  478. }
  479. // IsLetter reports whether the rune is a letter (category L).
  480. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  481. func IsLetter(ch rune) bool {
  482. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  483. }
  484. // IsTextFile returns true if file content format is plain text or empty.
  485. func IsTextFile(data []byte) bool {
  486. if len(data) == 0 {
  487. return true
  488. }
  489. return strings.Index(http.DetectContentType(data), "text/") != -1
  490. }
  491. // IsImageFile detects if data is an image format
  492. func IsImageFile(data []byte) bool {
  493. return strings.Index(http.DetectContentType(data), "image/") != -1
  494. }
  495. // IsPDFFile detects if data is a pdf format
  496. func IsPDFFile(data []byte) bool {
  497. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  498. }
  499. // IsVideoFile detects if data is an video format
  500. func IsVideoFile(data []byte) bool {
  501. return strings.Index(http.DetectContentType(data), "video/") != -1
  502. }
  503. // IsAudioFile detects if data is an video format
  504. func IsAudioFile(data []byte) bool {
  505. return strings.Index(http.DetectContentType(data), "audio/") != -1
  506. }
  507. // EntryIcon returns the octicon class for displaying files/directories
  508. func EntryIcon(entry *git.TreeEntry) string {
  509. switch {
  510. case entry.IsLink():
  511. te, err := entry.FollowLink()
  512. if err != nil {
  513. log.Debug(err.Error())
  514. return "file-symlink-file"
  515. }
  516. if te.IsDir() {
  517. return "file-symlink-directory"
  518. }
  519. return "file-symlink-file"
  520. case entry.IsDir():
  521. return "file-directory"
  522. case entry.IsSubModule():
  523. return "file-submodule"
  524. }
  525. return "file-text"
  526. }