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.

tool.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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/sha1"
  8. "crypto/sha256"
  9. "encoding/base64"
  10. "encoding/hex"
  11. "fmt"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path"
  16. "path/filepath"
  17. "runtime"
  18. "strconv"
  19. "strings"
  20. "time"
  21. "unicode"
  22. "code.gitea.io/gitea/modules/git"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/setting"
  25. "github.com/dustin/go-humanize"
  26. "github.com/unknwon/com"
  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. // EncodeSha1 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. // EncodeSha256 string to sha1 hex value.
  41. func EncodeSha256(str string) string {
  42. h := sha256.New()
  43. _, _ = h.Write([]byte(str))
  44. return hex.EncodeToString(h.Sum(nil))
  45. }
  46. // ShortSha is basically just truncating.
  47. // It is DEPRECATED and will be removed in the future.
  48. func ShortSha(sha1 string) string {
  49. return TruncateString(sha1, 10)
  50. }
  51. // BasicAuthDecode decode basic auth string
  52. func BasicAuthDecode(encoded string) (string, string, error) {
  53. s, err := base64.StdEncoding.DecodeString(encoded)
  54. if err != nil {
  55. return "", "", err
  56. }
  57. auth := strings.SplitN(string(s), ":", 2)
  58. return auth[0], auth[1], nil
  59. }
  60. // BasicAuthEncode encode basic auth string
  61. func BasicAuthEncode(username, password string) string {
  62. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  63. }
  64. // VerifyTimeLimitCode verify time limit code
  65. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  66. if len(code) <= 18 {
  67. return false
  68. }
  69. // split code
  70. start := code[:12]
  71. lives := code[12:18]
  72. if d, err := com.StrTo(lives).Int(); err == nil {
  73. minutes = d
  74. }
  75. // right active code
  76. retCode := CreateTimeLimitCode(data, minutes, start)
  77. if retCode == code && minutes > 0 {
  78. // check time is expired or not
  79. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  80. now := time.Now()
  81. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  82. return true
  83. }
  84. }
  85. return false
  86. }
  87. // TimeLimitCodeLength default value for time limit code
  88. const TimeLimitCodeLength = 12 + 6 + 40
  89. // CreateTimeLimitCode create a time limit code
  90. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  91. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  92. format := "200601021504"
  93. var start, end time.Time
  94. var startStr, endStr string
  95. if startInf == nil {
  96. // Use now time create code
  97. start = time.Now()
  98. startStr = start.Format(format)
  99. } else {
  100. // use start string create code
  101. startStr = startInf.(string)
  102. start, _ = time.ParseInLocation(format, startStr, time.Local)
  103. startStr = start.Format(format)
  104. }
  105. end = start.Add(time.Minute * time.Duration(minutes))
  106. endStr = end.Format(format)
  107. // create sha1 encode string
  108. sh := sha1.New()
  109. _, _ = sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  110. encoded := hex.EncodeToString(sh.Sum(nil))
  111. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  112. return code
  113. }
  114. // HashEmail hashes email address to MD5 string.
  115. // https://en.gravatar.com/site/implement/hash/
  116. func HashEmail(email string) string {
  117. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  118. }
  119. // DefaultAvatarLink the default avatar link
  120. func DefaultAvatarLink() string {
  121. return setting.AppSubURL + "/img/avatar_default.png"
  122. }
  123. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  124. // determined by the avatar-hosting service.
  125. const DefaultAvatarSize = -1
  126. // libravatarURL returns the URL for the given email. This function should only
  127. // be called if a federated avatar service is enabled.
  128. func libravatarURL(email string) (*url.URL, error) {
  129. urlStr, err := setting.LibravatarService.FromEmail(email)
  130. if err != nil {
  131. log.Error("LibravatarService.FromEmail(email=%s): error %v", email, err)
  132. return nil, err
  133. }
  134. u, err := url.Parse(urlStr)
  135. if err != nil {
  136. log.Error("Failed to parse libravatar url(%s): error %v", urlStr, err)
  137. return nil, err
  138. }
  139. return u, nil
  140. }
  141. // SizedAvatarLink returns a sized link to the avatar for the given email
  142. // address.
  143. func SizedAvatarLink(email string, size int) string {
  144. var avatarURL *url.URL
  145. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  146. var err error
  147. avatarURL, err = libravatarURL(email)
  148. if err != nil {
  149. return DefaultAvatarLink()
  150. }
  151. } else if !setting.DisableGravatar {
  152. // copy GravatarSourceURL, because we will modify its Path.
  153. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  154. avatarURL = &copyOfGravatarSourceURL
  155. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  156. } else {
  157. return DefaultAvatarLink()
  158. }
  159. vals := avatarURL.Query()
  160. vals.Set("d", "identicon")
  161. if size != DefaultAvatarSize {
  162. vals.Set("s", strconv.Itoa(size))
  163. }
  164. avatarURL.RawQuery = vals.Encode()
  165. return avatarURL.String()
  166. }
  167. // SizedAvatarLinkWithDomain returns a sized link to the avatar for the given email
  168. // address.
  169. func SizedAvatarLinkWithDomain(email string, size int) string {
  170. var avatarURL *url.URL
  171. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  172. var err error
  173. avatarURL, err = libravatarURL(email)
  174. if err != nil {
  175. return DefaultAvatarLink()
  176. }
  177. } else if !setting.DisableGravatar {
  178. // copy GravatarSourceURL, because we will modify its Path.
  179. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  180. avatarURL = &copyOfGravatarSourceURL
  181. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  182. } else {
  183. return DefaultAvatarLink()
  184. }
  185. vals := avatarURL.Query()
  186. vals.Set("d", "identicon")
  187. if size != DefaultAvatarSize {
  188. vals.Set("s", strconv.Itoa(size))
  189. }
  190. avatarURL.RawQuery = vals.Encode()
  191. return avatarURL.String()
  192. }
  193. // FileSize calculates the file size and generate user-friendly string.
  194. func FileSize(s int64) string {
  195. return humanize.IBytes(uint64(s))
  196. }
  197. // PrettyNumber produces a string form of the given number in base 10 with
  198. // commas after every three orders of magnitud
  199. func PrettyNumber(v int64) string {
  200. return humanize.Comma(v)
  201. }
  202. // Subtract deals with subtraction of all types of number.
  203. func Subtract(left interface{}, right interface{}) interface{} {
  204. var rleft, rright int64
  205. var fleft, fright float64
  206. var isInt = true
  207. switch v := left.(type) {
  208. case int:
  209. rleft = int64(v)
  210. case int8:
  211. rleft = int64(v)
  212. case int16:
  213. rleft = int64(v)
  214. case int32:
  215. rleft = int64(v)
  216. case int64:
  217. rleft = v
  218. case float32:
  219. fleft = float64(v)
  220. isInt = false
  221. case float64:
  222. fleft = v
  223. isInt = false
  224. }
  225. switch v := right.(type) {
  226. case int:
  227. rright = int64(v)
  228. case int8:
  229. rright = int64(v)
  230. case int16:
  231. rright = int64(v)
  232. case int32:
  233. rright = int64(v)
  234. case int64:
  235. rright = v
  236. case float32:
  237. fright = float64(v)
  238. isInt = false
  239. case float64:
  240. fright = v
  241. isInt = false
  242. }
  243. if isInt {
  244. return rleft - rright
  245. }
  246. return fleft + float64(rleft) - (fright + float64(rright))
  247. }
  248. // EllipsisString returns a truncated short string,
  249. // it appends '...' in the end of the length of string is too large.
  250. func EllipsisString(str string, length int) string {
  251. if length <= 3 {
  252. return "..."
  253. }
  254. if len(str) <= length {
  255. return str
  256. }
  257. return str[:length-3] + "..."
  258. }
  259. // TruncateString returns a truncated string with given limit,
  260. // it returns input string if length is not reached limit.
  261. func TruncateString(str string, limit int) string {
  262. if len(str) < limit {
  263. return str
  264. }
  265. return str[:limit]
  266. }
  267. // StringsToInt64s converts a slice of string to a slice of int64.
  268. func StringsToInt64s(strs []string) ([]int64, error) {
  269. ints := make([]int64, len(strs))
  270. for i := range strs {
  271. n, err := com.StrTo(strs[i]).Int64()
  272. if err != nil {
  273. return ints, err
  274. }
  275. ints[i] = n
  276. }
  277. return ints, nil
  278. }
  279. // Int64sToStrings converts a slice of int64 to a slice of string.
  280. func Int64sToStrings(ints []int64) []string {
  281. strs := make([]string, len(ints))
  282. for i := range ints {
  283. strs[i] = strconv.FormatInt(ints[i], 10)
  284. }
  285. return strs
  286. }
  287. // Int64sToMap converts a slice of int64 to a int64 map.
  288. func Int64sToMap(ints []int64) map[int64]bool {
  289. m := make(map[int64]bool)
  290. for _, i := range ints {
  291. m[i] = true
  292. }
  293. return m
  294. }
  295. // Int64sContains returns if a int64 in a slice of int64
  296. func Int64sContains(intsSlice []int64, a int64) bool {
  297. for _, c := range intsSlice {
  298. if c == a {
  299. return true
  300. }
  301. }
  302. return false
  303. }
  304. // IsLetter reports whether the rune is a letter (category L).
  305. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  306. func IsLetter(ch rune) bool {
  307. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  308. }
  309. // IsTextFile returns true if file content format is plain text or empty.
  310. func IsTextFile(data []byte) bool {
  311. if len(data) == 0 {
  312. return true
  313. }
  314. return strings.Contains(http.DetectContentType(data), "text/")
  315. }
  316. // IsImageFile detects if data is an image format
  317. func IsImageFile(data []byte) bool {
  318. return strings.Contains(http.DetectContentType(data), "image/")
  319. }
  320. // IsPDFFile detects if data is a pdf format
  321. func IsPDFFile(data []byte) bool {
  322. return strings.Contains(http.DetectContentType(data), "application/pdf")
  323. }
  324. // IsVideoFile detects if data is an video format
  325. func IsVideoFile(data []byte) bool {
  326. return strings.Contains(http.DetectContentType(data), "video/")
  327. }
  328. // IsAudioFile detects if data is an video format
  329. func IsAudioFile(data []byte) bool {
  330. return strings.Contains(http.DetectContentType(data), "audio/")
  331. }
  332. // EntryIcon returns the octicon class for displaying files/directories
  333. func EntryIcon(entry *git.TreeEntry) string {
  334. switch {
  335. case entry.IsLink():
  336. te, err := entry.FollowLink()
  337. if err != nil {
  338. log.Debug(err.Error())
  339. return "file-symlink-file"
  340. }
  341. if te.IsDir() {
  342. return "file-symlink-directory"
  343. }
  344. return "file-symlink-file"
  345. case entry.IsDir():
  346. return "file-directory"
  347. case entry.IsSubModule():
  348. return "file-submodule"
  349. }
  350. return "file"
  351. }
  352. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  353. func SetupGiteaRoot() string {
  354. giteaRoot := os.Getenv("GITEA_ROOT")
  355. if giteaRoot == "" {
  356. _, filename, _, _ := runtime.Caller(0)
  357. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  358. wd, err := os.Getwd()
  359. if err != nil {
  360. rel, err := filepath.Rel(giteaRoot, wd)
  361. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  362. giteaRoot = wd
  363. }
  364. }
  365. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  366. giteaRoot = ""
  367. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  368. giteaRoot = ""
  369. }
  370. }
  371. return giteaRoot
  372. }