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 16 kB

11 years ago
11 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 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
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
9 years ago
8 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 years ago
Better logging (#6038) (#6095) * Panic don't fatal on create new logger Fixes #5854 Signed-off-by: Andrew Thornton <art27@cantab.net> * partial broken * Update the logging infrastrcture Signed-off-by: Andrew Thornton <art27@cantab.net> * Reset the skip levels for Fatal and Error Signed-off-by: Andrew Thornton <art27@cantab.net> * broken ncsa * More log.Error fixes Signed-off-by: Andrew Thornton <art27@cantab.net> * Remove nal * set log-levels to lowercase * Make console_test test all levels * switch to lowercased levels * OK now working * Fix vetting issues * Fix lint * Fix tests * change default logging to match current gitea * Improve log testing Signed-off-by: Andrew Thornton <art27@cantab.net> * reset error skip levels to 0 * Update documentation and access logger configuration * Redirect the router log back to gitea if redirect macaron log but also allow setting the log level - i.e. TRACE * Fix broken level caching * Refactor the router log * Add Router logger * Add colorizing options * Adjust router colors * Only create logger if they will be used * update app.ini.sample * rename Attribute ColorAttribute * Change from white to green for function * Set fatal/error levels * Restore initial trace logger * Fix Trace arguments in modules/auth/auth.go * Properly handle XORMLogger * Improve admin/config page * fix fmt * Add auto-compression of old logs * Update error log levels * Remove the unnecessary skip argument from Error, Fatal and Critical * Add stacktrace support * Fix tests * Remove x/sync from vendors? * Add stderr option to console logger * Use filepath.ToSlash to protect against Windows in tests * Remove prefixed underscores from names in colors.go * Remove not implemented database logger This was removed from Gogs on 4 Mar 2016 but left in the configuration since then. * Ensure that log paths are relative to ROOT_PATH * use path.Join * rename jsonConfig to logConfig * Rename "config" to "jsonConfig" to make it clearer * Requested changes * Requested changes: XormLogger * Try to color the windows terminal If successful default to colorizing the console logs * fixup * Colorize initially too * update vendor * Colorize logs on default and remove if this is not a colorizing logger * Fix documentation * fix test * Use go-isatty to detect if on windows we are on msys or cygwin * Fix spelling mistake * Add missing vendors * More changes * Rationalise the ANSI writer protection * Adjust colors on advice from @0x5c * Make Flags a comma separated list * Move to use the windows constant for ENABLE_VIRTUAL_TERMINAL_PROCESSING * Ensure matching is done on the non-colored message - to simpify EXPRESSION
6 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
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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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. "bytes"
  7. "crypto/md5"
  8. "crypto/rand"
  9. "crypto/sha1"
  10. "encoding/base64"
  11. "encoding/hex"
  12. "fmt"
  13. "html/template"
  14. "io"
  15. "math"
  16. "net/http"
  17. "net/url"
  18. "os"
  19. "path"
  20. "path/filepath"
  21. "runtime"
  22. "strconv"
  23. "strings"
  24. "time"
  25. "unicode"
  26. "unicode/utf8"
  27. "code.gitea.io/gitea/modules/git"
  28. "code.gitea.io/gitea/modules/log"
  29. "code.gitea.io/gitea/modules/setting"
  30. "code.gitea.io/gitea/modules/util"
  31. "github.com/Unknwon/com"
  32. "github.com/Unknwon/i18n"
  33. "github.com/gogits/chardet"
  34. )
  35. // UTF8BOM is the utf-8 byte-order marker
  36. var UTF8BOM = []byte{'\xef', '\xbb', '\xbf'}
  37. // EncodeMD5 encodes string to md5 hex value.
  38. func EncodeMD5(str string) string {
  39. m := md5.New()
  40. m.Write([]byte(str))
  41. return hex.EncodeToString(m.Sum(nil))
  42. }
  43. // EncodeSha1 string to sha1 hex value.
  44. func EncodeSha1(str string) string {
  45. h := sha1.New()
  46. h.Write([]byte(str))
  47. return hex.EncodeToString(h.Sum(nil))
  48. }
  49. // ShortSha is basically just truncating.
  50. // It is DEPRECATED and will be removed in the future.
  51. func ShortSha(sha1 string) string {
  52. return TruncateString(sha1, 10)
  53. }
  54. // DetectEncoding detect the encoding of content
  55. func DetectEncoding(content []byte) (string, error) {
  56. if utf8.Valid(content) {
  57. log.Debug("Detected encoding: utf-8 (fast)")
  58. return "UTF-8", nil
  59. }
  60. textDetector := chardet.NewTextDetector()
  61. var detectContent []byte
  62. if len(content) < 1024 {
  63. // Check if original content is valid
  64. if _, err := textDetector.DetectBest(content); err != nil {
  65. return "", err
  66. }
  67. times := 1024 / len(content)
  68. detectContent = make([]byte, 0, times*len(content))
  69. for i := 0; i < times; i++ {
  70. detectContent = append(detectContent, content...)
  71. }
  72. } else {
  73. detectContent = content
  74. }
  75. result, err := textDetector.DetectBest(detectContent)
  76. if err != nil {
  77. return "", err
  78. }
  79. if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 {
  80. log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset)
  81. return setting.Repository.AnsiCharset, err
  82. }
  83. log.Debug("Detected encoding: %s", result.Charset)
  84. return result.Charset, err
  85. }
  86. // RemoveBOMIfPresent removes a UTF-8 BOM from a []byte
  87. func RemoveBOMIfPresent(content []byte) []byte {
  88. if len(content) > 2 && bytes.Equal(content[0:3], UTF8BOM) {
  89. return content[3:]
  90. }
  91. return content
  92. }
  93. // BasicAuthDecode decode basic auth string
  94. func BasicAuthDecode(encoded string) (string, string, error) {
  95. s, err := base64.StdEncoding.DecodeString(encoded)
  96. if err != nil {
  97. return "", "", err
  98. }
  99. auth := strings.SplitN(string(s), ":", 2)
  100. return auth[0], auth[1], nil
  101. }
  102. // BasicAuthEncode encode basic auth string
  103. func BasicAuthEncode(username, password string) string {
  104. return base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
  105. }
  106. // GetRandomBytesAsBase64 generates a random base64 string from n bytes
  107. func GetRandomBytesAsBase64(n int) string {
  108. bytes := make([]byte, 32)
  109. _, err := io.ReadFull(rand.Reader, bytes)
  110. if err != nil {
  111. log.Fatal("Error reading random bytes: %v", err)
  112. }
  113. return base64.RawURLEncoding.EncodeToString(bytes)
  114. }
  115. // VerifyTimeLimitCode verify time limit code
  116. func VerifyTimeLimitCode(data string, minutes int, code string) bool {
  117. if len(code) <= 18 {
  118. return false
  119. }
  120. // split code
  121. start := code[:12]
  122. lives := code[12:18]
  123. if d, err := com.StrTo(lives).Int(); err == nil {
  124. minutes = d
  125. }
  126. // right active code
  127. retCode := CreateTimeLimitCode(data, minutes, start)
  128. if retCode == code && minutes > 0 {
  129. // check time is expired or not
  130. before, _ := time.ParseInLocation("200601021504", start, time.Local)
  131. now := time.Now()
  132. if before.Add(time.Minute*time.Duration(minutes)).Unix() > now.Unix() {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. // TimeLimitCodeLength default value for time limit code
  139. const TimeLimitCodeLength = 12 + 6 + 40
  140. // CreateTimeLimitCode create a time limit code
  141. // code format: 12 length date time string + 6 minutes string + 40 sha1 encoded string
  142. func CreateTimeLimitCode(data string, minutes int, startInf interface{}) string {
  143. format := "200601021504"
  144. var start, end time.Time
  145. var startStr, endStr string
  146. if startInf == nil {
  147. // Use now time create code
  148. start = time.Now()
  149. startStr = start.Format(format)
  150. } else {
  151. // use start string create code
  152. startStr = startInf.(string)
  153. start, _ = time.ParseInLocation(format, startStr, time.Local)
  154. startStr = start.Format(format)
  155. }
  156. end = start.Add(time.Minute * time.Duration(minutes))
  157. endStr = end.Format(format)
  158. // create sha1 encode string
  159. sh := sha1.New()
  160. sh.Write([]byte(data + setting.SecretKey + startStr + endStr + com.ToStr(minutes)))
  161. encoded := hex.EncodeToString(sh.Sum(nil))
  162. code := fmt.Sprintf("%s%06d%s", startStr, minutes, encoded)
  163. return code
  164. }
  165. // HashEmail hashes email address to MD5 string.
  166. // https://en.gravatar.com/site/implement/hash/
  167. func HashEmail(email string) string {
  168. return EncodeMD5(strings.ToLower(strings.TrimSpace(email)))
  169. }
  170. // DefaultAvatarLink the default avatar link
  171. func DefaultAvatarLink() string {
  172. return setting.AppSubURL + "/img/avatar_default.png"
  173. }
  174. // DefaultAvatarSize is a sentinel value for the default avatar size, as
  175. // determined by the avatar-hosting service.
  176. const DefaultAvatarSize = -1
  177. // libravatarURL returns the URL for the given email. This function should only
  178. // be called if a federated avatar service is enabled.
  179. func libravatarURL(email string) (*url.URL, error) {
  180. urlStr, err := setting.LibravatarService.FromEmail(email)
  181. if err != nil {
  182. log.Error("LibravatarService.FromEmail(email=%s): error %v", email, err)
  183. return nil, err
  184. }
  185. u, err := url.Parse(urlStr)
  186. if err != nil {
  187. log.Error("Failed to parse libravatar url(%s): error %v", urlStr, err)
  188. return nil, err
  189. }
  190. return u, nil
  191. }
  192. // SizedAvatarLink returns a sized link to the avatar for the given email
  193. // address.
  194. func SizedAvatarLink(email string, size int) string {
  195. var avatarURL *url.URL
  196. if setting.EnableFederatedAvatar && setting.LibravatarService != nil {
  197. var err error
  198. avatarURL, err = libravatarURL(email)
  199. if err != nil {
  200. return DefaultAvatarLink()
  201. }
  202. } else if !setting.DisableGravatar {
  203. // copy GravatarSourceURL, because we will modify its Path.
  204. copyOfGravatarSourceURL := *setting.GravatarSourceURL
  205. avatarURL = &copyOfGravatarSourceURL
  206. avatarURL.Path = path.Join(avatarURL.Path, HashEmail(email))
  207. } else {
  208. return DefaultAvatarLink()
  209. }
  210. vals := avatarURL.Query()
  211. vals.Set("d", "identicon")
  212. if size != DefaultAvatarSize {
  213. vals.Set("s", strconv.Itoa(size))
  214. }
  215. avatarURL.RawQuery = vals.Encode()
  216. return avatarURL.String()
  217. }
  218. // AvatarLink returns relative avatar link to the site domain by given email,
  219. // which includes app sub-url as prefix. However, it is possible
  220. // to return full URL if user enables Gravatar-like service.
  221. func AvatarLink(email string) string {
  222. return SizedAvatarLink(email, DefaultAvatarSize)
  223. }
  224. // Seconds-based time units
  225. const (
  226. Minute = 60
  227. Hour = 60 * Minute
  228. Day = 24 * Hour
  229. Week = 7 * Day
  230. Month = 30 * Day
  231. Year = 12 * Month
  232. )
  233. func computeTimeDiff(diff int64, lang string) (int64, string) {
  234. diffStr := ""
  235. switch {
  236. case diff <= 0:
  237. diff = 0
  238. diffStr = i18n.Tr(lang, "tool.now")
  239. case diff < 2:
  240. diff = 0
  241. diffStr = i18n.Tr(lang, "tool.1s")
  242. case diff < 1*Minute:
  243. diffStr = i18n.Tr(lang, "tool.seconds", diff)
  244. diff = 0
  245. case diff < 2*Minute:
  246. diff -= 1 * Minute
  247. diffStr = i18n.Tr(lang, "tool.1m")
  248. case diff < 1*Hour:
  249. diffStr = i18n.Tr(lang, "tool.minutes", diff/Minute)
  250. diff -= diff / Minute * Minute
  251. case diff < 2*Hour:
  252. diff -= 1 * Hour
  253. diffStr = i18n.Tr(lang, "tool.1h")
  254. case diff < 1*Day:
  255. diffStr = i18n.Tr(lang, "tool.hours", diff/Hour)
  256. diff -= diff / Hour * Hour
  257. case diff < 2*Day:
  258. diff -= 1 * Day
  259. diffStr = i18n.Tr(lang, "tool.1d")
  260. case diff < 1*Week:
  261. diffStr = i18n.Tr(lang, "tool.days", diff/Day)
  262. diff -= diff / Day * Day
  263. case diff < 2*Week:
  264. diff -= 1 * Week
  265. diffStr = i18n.Tr(lang, "tool.1w")
  266. case diff < 1*Month:
  267. diffStr = i18n.Tr(lang, "tool.weeks", diff/Week)
  268. diff -= diff / Week * Week
  269. case diff < 2*Month:
  270. diff -= 1 * Month
  271. diffStr = i18n.Tr(lang, "tool.1mon")
  272. case diff < 1*Year:
  273. diffStr = i18n.Tr(lang, "tool.months", diff/Month)
  274. diff -= diff / Month * Month
  275. case diff < 2*Year:
  276. diff -= 1 * Year
  277. diffStr = i18n.Tr(lang, "tool.1y")
  278. default:
  279. diffStr = i18n.Tr(lang, "tool.years", diff/Year)
  280. diff -= (diff / Year) * Year
  281. }
  282. return diff, diffStr
  283. }
  284. // MinutesToFriendly returns a user friendly string with number of minutes
  285. // converted to hours and minutes.
  286. func MinutesToFriendly(minutes int, lang string) string {
  287. duration := time.Duration(minutes) * time.Minute
  288. return TimeSincePro(time.Now().Add(-duration), lang)
  289. }
  290. // TimeSincePro calculates the time interval and generate full user-friendly string.
  291. func TimeSincePro(then time.Time, lang string) string {
  292. return timeSincePro(then, time.Now(), lang)
  293. }
  294. func timeSincePro(then, now time.Time, lang string) string {
  295. diff := now.Unix() - then.Unix()
  296. if then.After(now) {
  297. return i18n.Tr(lang, "tool.future")
  298. }
  299. if diff == 0 {
  300. return i18n.Tr(lang, "tool.now")
  301. }
  302. var timeStr, diffStr string
  303. for {
  304. if diff == 0 {
  305. break
  306. }
  307. diff, diffStr = computeTimeDiff(diff, lang)
  308. timeStr += ", " + diffStr
  309. }
  310. return strings.TrimPrefix(timeStr, ", ")
  311. }
  312. func timeSince(then, now time.Time, lang string) string {
  313. return timeSinceUnix(then.Unix(), now.Unix(), lang)
  314. }
  315. func timeSinceUnix(then, now int64, lang string) string {
  316. lbl := "tool.ago"
  317. diff := now - then
  318. if then > now {
  319. lbl = "tool.from_now"
  320. diff = then - now
  321. }
  322. if diff <= 0 {
  323. return i18n.Tr(lang, "tool.now")
  324. }
  325. _, diffStr := computeTimeDiff(diff, lang)
  326. return i18n.Tr(lang, lbl, diffStr)
  327. }
  328. // RawTimeSince retrieves i18n key of time since t
  329. func RawTimeSince(t time.Time, lang string) string {
  330. return timeSince(t, time.Now(), lang)
  331. }
  332. // TimeSince calculates the time interval and generate user-friendly string.
  333. func TimeSince(then time.Time, lang string) template.HTML {
  334. return htmlTimeSince(then, time.Now(), lang)
  335. }
  336. func htmlTimeSince(then, now time.Time, lang string) template.HTML {
  337. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  338. then.Format(setting.TimeFormat),
  339. timeSince(then, now, lang)))
  340. }
  341. // TimeSinceUnix calculates the time interval and generate user-friendly string.
  342. func TimeSinceUnix(then util.TimeStamp, lang string) template.HTML {
  343. return htmlTimeSinceUnix(then, util.TimeStamp(time.Now().Unix()), lang)
  344. }
  345. func htmlTimeSinceUnix(then, now util.TimeStamp, lang string) template.HTML {
  346. return template.HTML(fmt.Sprintf(`<span class="time-since" title="%s">%s</span>`,
  347. then.Format(setting.TimeFormat),
  348. timeSinceUnix(int64(then), int64(now), lang)))
  349. }
  350. // Storage space size types
  351. const (
  352. Byte = 1
  353. KByte = Byte * 1024
  354. MByte = KByte * 1024
  355. GByte = MByte * 1024
  356. TByte = GByte * 1024
  357. PByte = TByte * 1024
  358. EByte = PByte * 1024
  359. )
  360. var bytesSizeTable = map[string]uint64{
  361. "b": Byte,
  362. "kb": KByte,
  363. "mb": MByte,
  364. "gb": GByte,
  365. "tb": TByte,
  366. "pb": PByte,
  367. "eb": EByte,
  368. }
  369. func logn(n, b float64) float64 {
  370. return math.Log(n) / math.Log(b)
  371. }
  372. func humanateBytes(s uint64, base float64, sizes []string) string {
  373. if s < 10 {
  374. return fmt.Sprintf("%dB", s)
  375. }
  376. e := math.Floor(logn(float64(s), base))
  377. suffix := sizes[int(e)]
  378. val := float64(s) / math.Pow(base, math.Floor(e))
  379. f := "%.0f"
  380. if val < 10 {
  381. f = "%.1f"
  382. }
  383. return fmt.Sprintf(f+"%s", val, suffix)
  384. }
  385. // FileSize calculates the file size and generate user-friendly string.
  386. func FileSize(s int64) string {
  387. sizes := []string{"B", "KB", "MB", "GB", "TB", "PB", "EB"}
  388. return humanateBytes(uint64(s), 1024, sizes)
  389. }
  390. // Subtract deals with subtraction of all types of number.
  391. func Subtract(left interface{}, right interface{}) interface{} {
  392. var rleft, rright int64
  393. var fleft, fright float64
  394. var isInt = true
  395. switch left := left.(type) {
  396. case int:
  397. rleft = int64(left)
  398. case int8:
  399. rleft = int64(left)
  400. case int16:
  401. rleft = int64(left)
  402. case int32:
  403. rleft = int64(left)
  404. case int64:
  405. rleft = left
  406. case float32:
  407. fleft = float64(left)
  408. isInt = false
  409. case float64:
  410. fleft = left
  411. isInt = false
  412. }
  413. switch right := right.(type) {
  414. case int:
  415. rright = int64(right)
  416. case int8:
  417. rright = int64(right)
  418. case int16:
  419. rright = int64(right)
  420. case int32:
  421. rright = int64(right)
  422. case int64:
  423. rright = right
  424. case float32:
  425. fright = float64(right)
  426. isInt = false
  427. case float64:
  428. fright = right
  429. isInt = false
  430. }
  431. if isInt {
  432. return rleft - rright
  433. }
  434. return fleft + float64(rleft) - (fright + float64(rright))
  435. }
  436. // EllipsisString returns a truncated short string,
  437. // it appends '...' in the end of the length of string is too large.
  438. func EllipsisString(str string, length int) string {
  439. if length <= 3 {
  440. return "..."
  441. }
  442. if len(str) <= length {
  443. return str
  444. }
  445. return str[:length-3] + "..."
  446. }
  447. // TruncateString returns a truncated string with given limit,
  448. // it returns input string if length is not reached limit.
  449. func TruncateString(str string, limit int) string {
  450. if len(str) < limit {
  451. return str
  452. }
  453. return str[:limit]
  454. }
  455. // StringsToInt64s converts a slice of string to a slice of int64.
  456. func StringsToInt64s(strs []string) ([]int64, error) {
  457. ints := make([]int64, len(strs))
  458. for i := range strs {
  459. n, err := com.StrTo(strs[i]).Int64()
  460. if err != nil {
  461. return ints, err
  462. }
  463. ints[i] = n
  464. }
  465. return ints, nil
  466. }
  467. // Int64sToStrings converts a slice of int64 to a slice of string.
  468. func Int64sToStrings(ints []int64) []string {
  469. strs := make([]string, len(ints))
  470. for i := range ints {
  471. strs[i] = strconv.FormatInt(ints[i], 10)
  472. }
  473. return strs
  474. }
  475. // Int64sToMap converts a slice of int64 to a int64 map.
  476. func Int64sToMap(ints []int64) map[int64]bool {
  477. m := make(map[int64]bool)
  478. for _, i := range ints {
  479. m[i] = true
  480. }
  481. return m
  482. }
  483. // Int64sContains returns if a int64 in a slice of int64
  484. func Int64sContains(intsSlice []int64, a int64) bool {
  485. for _, c := range intsSlice {
  486. if c == a {
  487. return true
  488. }
  489. }
  490. return false
  491. }
  492. // IsLetter reports whether the rune is a letter (category L).
  493. // https://github.com/golang/go/blob/master/src/go/scanner/scanner.go#L257
  494. func IsLetter(ch rune) bool {
  495. return 'a' <= ch && ch <= 'z' || 'A' <= ch && ch <= 'Z' || ch == '_' || ch >= 0x80 && unicode.IsLetter(ch)
  496. }
  497. // IsTextFile returns true if file content format is plain text or empty.
  498. func IsTextFile(data []byte) bool {
  499. if len(data) == 0 {
  500. return true
  501. }
  502. return strings.Index(http.DetectContentType(data), "text/") != -1
  503. }
  504. // IsImageFile detects if data is an image format
  505. func IsImageFile(data []byte) bool {
  506. return strings.Index(http.DetectContentType(data), "image/") != -1
  507. }
  508. // IsPDFFile detects if data is a pdf format
  509. func IsPDFFile(data []byte) bool {
  510. return strings.Index(http.DetectContentType(data), "application/pdf") != -1
  511. }
  512. // IsVideoFile detects if data is an video format
  513. func IsVideoFile(data []byte) bool {
  514. return strings.Index(http.DetectContentType(data), "video/") != -1
  515. }
  516. // IsAudioFile detects if data is an video format
  517. func IsAudioFile(data []byte) bool {
  518. return strings.Index(http.DetectContentType(data), "audio/") != -1
  519. }
  520. // EntryIcon returns the octicon class for displaying files/directories
  521. func EntryIcon(entry *git.TreeEntry) string {
  522. switch {
  523. case entry.IsLink():
  524. te, err := entry.FollowLink()
  525. if err != nil {
  526. log.Debug(err.Error())
  527. return "file-symlink-file"
  528. }
  529. if te.IsDir() {
  530. return "file-symlink-directory"
  531. }
  532. return "file-symlink-file"
  533. case entry.IsDir():
  534. return "file-directory"
  535. case entry.IsSubModule():
  536. return "file-submodule"
  537. }
  538. return "file-text"
  539. }
  540. // SetupGiteaRoot Sets GITEA_ROOT if it is not already set and returns the value
  541. func SetupGiteaRoot() string {
  542. giteaRoot := os.Getenv("GITEA_ROOT")
  543. if giteaRoot == "" {
  544. _, filename, _, _ := runtime.Caller(0)
  545. giteaRoot = strings.TrimSuffix(filename, "modules/base/tool.go")
  546. wd, err := os.Getwd()
  547. if err != nil {
  548. rel, err := filepath.Rel(giteaRoot, wd)
  549. if err != nil && strings.HasPrefix(filepath.ToSlash(rel), "../") {
  550. giteaRoot = wd
  551. }
  552. }
  553. if _, err := os.Stat(filepath.Join(giteaRoot, "gitea")); os.IsNotExist(err) {
  554. giteaRoot = ""
  555. } else if err := os.Setenv("GITEA_ROOT", giteaRoot); err != nil {
  556. giteaRoot = ""
  557. }
  558. }
  559. return giteaRoot
  560. }