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.

setting.go 24 kB

Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
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
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 years ago
Feature: Timetracking (#2211) * Added comment's hashtag to url for mail notifications. * Added explanation to return statement + documentation. * Replacing in-line link generation with HTMLURL. (+gofmt) * Replaced action-based model with nil-based model. (+gofmt) * Replaced mailIssueActionToParticipants with mailIssueCommentToParticipants. * Updating comment for mailIssueCommentToParticipants * Added link to comment in "Dashboard" * Deleting feed entry if a comment is going to be deleted * Added migration * Added improved migration to add a CommentID column to action. * Added improved links to comments in feed entries. * Fixes #1956 by filtering for deleted comments that are referenced in actions. * Introducing "IsDeleted" column to action. * Adding design draft (not functional) * Adding database models for stopwatches and trackedtimes * See go-gitea/gitea#967 * Adding design draft (not functional) * Adding translations and improving design * Implementing stopwatch (for timetracking) * Make UI functional * Add hints in timeline for time tracking events * Implementing timetracking feature * Adding "Add time manual" option * Improved stopwatch * Created report of total spent time by user * Only showing total time spent if theire is something to show. * Adding license headers. * Improved error handling for "Add Time Manual" * Adding @sapks 's changes, refactoring * Adding API for feature tracking * Adding unit test * Adding DISABLE/ENABLE option to Repository settings page * Improving translations * Applying @sapk 's changes * Removing repo_unit and using IssuesSetting for disabling/enabling timetracker * Adding DEFAULT_ENABLE_TIMETRACKER to config, installation and admin menu * Improving documentation * Fixing vendor/ folder * Changing timtracking routes by adding subgroups /times and /times/stopwatch (Proposed by @lafriks ) * Restricting write access to timetracking based on the repo settings (Proposed by @lafriks ) * Fixed minor permissions bug. * Adding CanUseTimetracker and IsTimetrackerEnabled in ctx.Repo * Allow assignees and authors to track there time too. * Fixed some build-time-errors + logical errors. * Removing unused Get...ByID functions * Moving IsTimetrackerEnabled from context.Repository to models.Repository * Adding a seperate file for issue related repo functions * Adding license headers * Fixed GetUserByParams return 404 * Moving /users/:username/times to /repos/:username/:reponame/times/:username for security reasons * Adding /repos/:username/times to get all tracked times of the repo * Updating sdk-dependency * Updating swagger.v1.json * Adding warning if user has already a running stopwatch (auto-timetracker) * Replacing GetTrackedTimesBy... with GetTrackedTimes(options FindTrackedTimesOptions) * Changing code.gitea.io/sdk back to code.gitea.io/sdk * Correcting spelling mistake * Updating vendor.json * Changing GET stopwatch/toggle to POST stopwatch/toggle * Changing GET stopwatch/cancel to POST stopwatch/cancel * Added migration for stopwatches/timetracking * Fixed some access bugs for read-only users * Added default allow only contributors to track time value to config * Fixed migration by chaging x.Iterate to x.Find * Resorted imports * Moved Add Time Manually form to repo_form.go * Removed "Seconds" field from Add Time Manually * Resorted imports * Improved permission checking * Fixed some bugs * Added integration test * gofmt * Adding integration test by @lafriks * Added created_unix to comment fixtures * Using last event instead of a fixed event * Adding another integration test by @lafriks * Fixing bug Timetracker enabled causing error 500 at sidebar.tpl * Fixed a refactoring bug that resulted in hiding "HasUserStopwatch" warning. * Returning TrackedTime instead of AddTimeOption at AddTime. * Updating SDK from go-gitea/go-sdk#69 * Resetting Go-SDK back to default repository * Fixing test-vendor by changing ini back to original repository * Adding "tags" to swagger spec * govendor sync * Removed duplicate * Formatting templates * Adding IsTimetrackingEnabled checks to API * Improving translations / english texts * Improving documentation * Updating swagger spec * Fixing integration test caused be translation-changes * Removed encoding issues in local_en-US.ini. * "Added" copyright line * Moved unit.IssuesConfig().EnableTimetracker into a != nil check * Removed some other encoding issues in local_en-US.ini * Improved javascript by checking if data-context exists * Replaced manual comment creation with CreateComment * Removed unnecessary code * Improved error checking * Small cosmetic changes * Replaced int>string>duration parsing with int>duration parsing * Fixed encoding issues * Removed unused imports Signed-off-by: Jonas Franz <info@jonasfranz.software>
7 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
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
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
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
Repository avatars (#6986) * Repository avatars - first variant of code from old work for gogs - add migration 87 - add new option in app.ini - add en-US locale string - add new class in repository.less * Add changed index.css, remove unused template name * Update en-us doc about configuration options * Add comments to new functions, add new option to docker app.ini * Add comment for lint * Remove variable, not needed * Fix formatting * Update swagger api template * Check if avatar exists * Fix avatar link/path checks * Typo * TEXT column can't have a default value * Fixes: - remove old avatar file on upload - use ID in name of avatar file - users may upload same files - add simple tests * Fix fmt check * Generate PNG instead of "static" GIF * More informative comment * Fix error message * Update avatar upload checks: - add file size check - add new option - update config docs - add new string to en-us locale * Fixes: - use FileHEader field for check file size - add new test - upload big image * Fix formatting * Update comments * Update log message * Removed wrong style - not needed * Use Sync2 to migrate * Update repos list view - bigger avatar - fix html blocks alignment * A little adjust avatar size * Use small icons for explore/repo list * Use new cool avatar preparation func by @lafriks * Missing changes for new function * Remove unused import, move imports * Missed new option definition in app.ini Add file size check in user/profile avatar upload * Use smaller field length for Avatar * Use session to update repo DB data, update DeleteAvatar - use session too * Fix err variable definition * As suggested @lafriks - return as soon as possible, code readability
6 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "errors"
  8. "fmt"
  9. "io/ioutil"
  10. "net/url"
  11. "regexp"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/timeutil"
  22. "code.gitea.io/gitea/modules/validation"
  23. "code.gitea.io/gitea/routers/utils"
  24. "github.com/Unknwon/com"
  25. "mvdan.cc/xurls/v2"
  26. )
  27. const (
  28. tplSettingsOptions base.TplName = "repo/settings/options"
  29. tplCollaboration base.TplName = "repo/settings/collaboration"
  30. tplBranches base.TplName = "repo/settings/branches"
  31. tplGithooks base.TplName = "repo/settings/githooks"
  32. tplGithookEdit base.TplName = "repo/settings/githook_edit"
  33. tplDeployKeys base.TplName = "repo/settings/deploy_keys"
  34. tplProtectedBranch base.TplName = "repo/settings/protected_branch"
  35. )
  36. var validFormAddress *regexp.Regexp
  37. // Settings show a repository's settings page
  38. func Settings(ctx *context.Context) {
  39. ctx.Data["Title"] = ctx.Tr("repo.settings")
  40. ctx.Data["PageIsSettingsOptions"] = true
  41. ctx.Data["ForcePrivate"] = setting.Repository.ForcePrivate
  42. ctx.HTML(200, tplSettingsOptions)
  43. }
  44. // SettingsPost response for changes of a repository
  45. func SettingsPost(ctx *context.Context, form auth.RepoSettingForm) {
  46. ctx.Data["Title"] = ctx.Tr("repo.settings")
  47. ctx.Data["PageIsSettingsOptions"] = true
  48. repo := ctx.Repo.Repository
  49. switch ctx.Query("action") {
  50. case "update":
  51. if ctx.HasError() {
  52. ctx.HTML(200, tplSettingsOptions)
  53. return
  54. }
  55. isNameChanged := false
  56. oldRepoName := repo.Name
  57. newRepoName := form.RepoName
  58. // Check if repository name has been changed.
  59. if repo.LowerName != strings.ToLower(newRepoName) {
  60. isNameChanged = true
  61. if err := models.ChangeRepositoryName(ctx.Repo.Owner, repo.Name, newRepoName); err != nil {
  62. ctx.Data["Err_RepoName"] = true
  63. switch {
  64. case models.IsErrRepoAlreadyExist(err):
  65. ctx.RenderWithErr(ctx.Tr("form.repo_name_been_taken"), tplSettingsOptions, &form)
  66. case models.IsErrNameReserved(err):
  67. ctx.RenderWithErr(ctx.Tr("repo.form.name_reserved", err.(models.ErrNameReserved).Name), tplSettingsOptions, &form)
  68. case models.IsErrNamePatternNotAllowed(err):
  69. ctx.RenderWithErr(ctx.Tr("repo.form.name_pattern_not_allowed", err.(models.ErrNamePatternNotAllowed).Pattern), tplSettingsOptions, &form)
  70. default:
  71. ctx.ServerError("ChangeRepositoryName", err)
  72. }
  73. return
  74. }
  75. err := models.NewRepoRedirect(ctx.Repo.Owner.ID, repo.ID, repo.Name, newRepoName)
  76. if err != nil {
  77. ctx.ServerError("NewRepoRedirect", err)
  78. return
  79. }
  80. log.Trace("Repository name changed: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newRepoName)
  81. }
  82. // In case it's just a case change.
  83. repo.Name = newRepoName
  84. repo.LowerName = strings.ToLower(newRepoName)
  85. repo.Description = form.Description
  86. repo.Website = form.Website
  87. // Visibility of forked repository is forced sync with base repository.
  88. if repo.IsFork {
  89. form.Private = repo.BaseRepo.IsPrivate
  90. }
  91. visibilityChanged := repo.IsPrivate != form.Private
  92. // when ForcePrivate enabled, you could change public repo to private, but only admin users can change private to public
  93. if visibilityChanged && setting.Repository.ForcePrivate && !form.Private && !ctx.User.IsAdmin {
  94. ctx.ServerError("Force Private enabled", errors.New("cannot change private repository to public"))
  95. return
  96. }
  97. repo.IsPrivate = form.Private
  98. if err := models.UpdateRepository(repo, visibilityChanged); err != nil {
  99. ctx.ServerError("UpdateRepository", err)
  100. return
  101. }
  102. log.Trace("Repository basic settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  103. if isNameChanged {
  104. if err := models.RenameRepoAction(ctx.User, oldRepoName, repo); err != nil {
  105. log.Error("RenameRepoAction: %v", err)
  106. }
  107. }
  108. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  109. ctx.Redirect(repo.Link() + "/settings")
  110. case "mirror":
  111. if !repo.IsMirror {
  112. ctx.NotFound("", nil)
  113. return
  114. }
  115. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  116. // as an error on the UI for this action
  117. ctx.Data["Err_RepoName"] = nil
  118. interval, err := time.ParseDuration(form.Interval)
  119. if err != nil || (interval != 0 && interval < setting.Mirror.MinInterval) {
  120. ctx.Data["Err_Interval"] = true
  121. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  122. } else {
  123. ctx.Repo.Mirror.EnablePrune = form.EnablePrune
  124. ctx.Repo.Mirror.Interval = interval
  125. if interval != 0 {
  126. ctx.Repo.Mirror.NextUpdateUnix = timeutil.TimeStampNow().AddDuration(interval)
  127. } else {
  128. ctx.Repo.Mirror.NextUpdateUnix = 0
  129. }
  130. if err := models.UpdateMirror(ctx.Repo.Mirror); err != nil {
  131. ctx.Data["Err_Interval"] = true
  132. ctx.RenderWithErr(ctx.Tr("repo.mirror_interval_invalid"), tplSettingsOptions, &form)
  133. return
  134. }
  135. }
  136. // Validate the form.MirrorAddress
  137. u, err := url.Parse(form.MirrorAddress)
  138. if err != nil {
  139. ctx.Data["Err_MirrorAddress"] = true
  140. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  141. return
  142. }
  143. if u.Opaque != "" || !(u.Scheme == "http" || u.Scheme == "https" || u.Scheme == "git") {
  144. ctx.Data["Err_MirrorAddress"] = true
  145. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_protocol_invalid"), tplSettingsOptions, &form)
  146. return
  147. }
  148. // Now use xurls
  149. address := validFormAddress.FindString(form.MirrorAddress)
  150. if address != form.MirrorAddress && form.MirrorAddress != "" {
  151. ctx.Data["Err_MirrorAddress"] = true
  152. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  153. return
  154. }
  155. if u.EscapedPath() == "" || u.Host == "" || !u.IsAbs() {
  156. ctx.Data["Err_MirrorAddress"] = true
  157. ctx.RenderWithErr(ctx.Tr("repo.mirror_address_url_invalid"), tplSettingsOptions, &form)
  158. return
  159. }
  160. address = u.String()
  161. if err := ctx.Repo.Mirror.SaveAddress(address); err != nil {
  162. ctx.ServerError("SaveAddress", err)
  163. return
  164. }
  165. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  166. ctx.Redirect(repo.Link() + "/settings")
  167. case "mirror-sync":
  168. if !repo.IsMirror {
  169. ctx.NotFound("", nil)
  170. return
  171. }
  172. go models.MirrorQueue.Add(repo.ID)
  173. ctx.Flash.Info(ctx.Tr("repo.settings.mirror_sync_in_progress"))
  174. ctx.Redirect(repo.Link() + "/settings")
  175. case "advanced":
  176. var units []models.RepoUnit
  177. // This section doesn't require repo_name/RepoName to be set in the form, don't show it
  178. // as an error on the UI for this action
  179. ctx.Data["Err_RepoName"] = nil
  180. for _, tp := range models.MustRepoUnits {
  181. units = append(units, models.RepoUnit{
  182. RepoID: repo.ID,
  183. Type: tp,
  184. Config: new(models.UnitConfig),
  185. })
  186. }
  187. if form.EnableWiki {
  188. if form.EnableExternalWiki {
  189. if !validation.IsValidExternalURL(form.ExternalWikiURL) {
  190. ctx.Flash.Error(ctx.Tr("repo.settings.external_wiki_url_error"))
  191. ctx.Redirect(repo.Link() + "/settings")
  192. return
  193. }
  194. units = append(units, models.RepoUnit{
  195. RepoID: repo.ID,
  196. Type: models.UnitTypeExternalWiki,
  197. Config: &models.ExternalWikiConfig{
  198. ExternalWikiURL: form.ExternalWikiURL,
  199. },
  200. })
  201. } else {
  202. units = append(units, models.RepoUnit{
  203. RepoID: repo.ID,
  204. Type: models.UnitTypeWiki,
  205. Config: new(models.UnitConfig),
  206. })
  207. }
  208. }
  209. if form.EnableIssues {
  210. if form.EnableExternalTracker {
  211. if !validation.IsValidExternalURL(form.ExternalTrackerURL) {
  212. ctx.Flash.Error(ctx.Tr("repo.settings.external_tracker_url_error"))
  213. ctx.Redirect(repo.Link() + "/settings")
  214. return
  215. }
  216. if len(form.TrackerURLFormat) != 0 && !validation.IsValidExternalTrackerURLFormat(form.TrackerURLFormat) {
  217. ctx.Flash.Error(ctx.Tr("repo.settings.tracker_url_format_error"))
  218. ctx.Redirect(repo.Link() + "/settings")
  219. return
  220. }
  221. units = append(units, models.RepoUnit{
  222. RepoID: repo.ID,
  223. Type: models.UnitTypeExternalTracker,
  224. Config: &models.ExternalTrackerConfig{
  225. ExternalTrackerURL: form.ExternalTrackerURL,
  226. ExternalTrackerFormat: form.TrackerURLFormat,
  227. ExternalTrackerStyle: form.TrackerIssueStyle,
  228. },
  229. })
  230. } else {
  231. units = append(units, models.RepoUnit{
  232. RepoID: repo.ID,
  233. Type: models.UnitTypeIssues,
  234. Config: &models.IssuesConfig{
  235. EnableTimetracker: form.EnableTimetracker,
  236. AllowOnlyContributorsToTrackTime: form.AllowOnlyContributorsToTrackTime,
  237. EnableDependencies: form.EnableIssueDependencies,
  238. },
  239. })
  240. }
  241. }
  242. if form.EnablePulls {
  243. units = append(units, models.RepoUnit{
  244. RepoID: repo.ID,
  245. Type: models.UnitTypePullRequests,
  246. Config: &models.PullRequestsConfig{
  247. IgnoreWhitespaceConflicts: form.PullsIgnoreWhitespace,
  248. AllowMerge: form.PullsAllowMerge,
  249. AllowRebase: form.PullsAllowRebase,
  250. AllowRebaseMerge: form.PullsAllowRebaseMerge,
  251. AllowSquash: form.PullsAllowSquash,
  252. },
  253. })
  254. }
  255. if err := models.UpdateRepositoryUnits(repo, units); err != nil {
  256. ctx.ServerError("UpdateRepositoryUnits", err)
  257. return
  258. }
  259. log.Trace("Repository advanced settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  260. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  261. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  262. case "admin":
  263. if !ctx.User.IsAdmin {
  264. ctx.Error(403)
  265. return
  266. }
  267. if repo.IsFsckEnabled != form.EnableHealthCheck {
  268. repo.IsFsckEnabled = form.EnableHealthCheck
  269. }
  270. if repo.CloseIssuesViaCommitInAnyBranch != form.EnableCloseIssuesViaCommitInAnyBranch {
  271. repo.CloseIssuesViaCommitInAnyBranch = form.EnableCloseIssuesViaCommitInAnyBranch
  272. }
  273. if err := models.UpdateRepository(repo, false); err != nil {
  274. ctx.ServerError("UpdateRepository", err)
  275. return
  276. }
  277. log.Trace("Repository admin settings updated: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  278. ctx.Flash.Success(ctx.Tr("repo.settings.update_settings_success"))
  279. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  280. case "convert":
  281. if !ctx.Repo.IsOwner() {
  282. ctx.Error(404)
  283. return
  284. }
  285. if repo.Name != form.RepoName {
  286. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  287. return
  288. }
  289. if !repo.IsMirror {
  290. ctx.Error(404)
  291. return
  292. }
  293. repo.IsMirror = false
  294. if _, err := models.CleanUpMigrateInfo(repo); err != nil {
  295. ctx.ServerError("CleanUpMigrateInfo", err)
  296. return
  297. } else if err = models.DeleteMirrorByRepoID(ctx.Repo.Repository.ID); err != nil {
  298. ctx.ServerError("DeleteMirrorByRepoID", err)
  299. return
  300. }
  301. log.Trace("Repository converted from mirror to regular: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  302. ctx.Flash.Success(ctx.Tr("repo.settings.convert_succeed"))
  303. ctx.Redirect(setting.AppSubURL + "/" + ctx.Repo.Owner.Name + "/" + repo.Name)
  304. case "transfer":
  305. if !ctx.Repo.IsOwner() {
  306. ctx.Error(404)
  307. return
  308. }
  309. if repo.Name != form.RepoName {
  310. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  311. return
  312. }
  313. newOwner := ctx.Query("new_owner_name")
  314. isExist, err := models.IsUserExist(0, newOwner)
  315. if err != nil {
  316. ctx.ServerError("IsUserExist", err)
  317. return
  318. } else if !isExist {
  319. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_owner_name"), tplSettingsOptions, nil)
  320. return
  321. }
  322. oldOwnerID := ctx.Repo.Owner.ID
  323. if err = models.TransferOwnership(ctx.User, newOwner, repo); err != nil {
  324. if models.IsErrRepoAlreadyExist(err) {
  325. ctx.RenderWithErr(ctx.Tr("repo.settings.new_owner_has_same_repo"), tplSettingsOptions, nil)
  326. } else {
  327. ctx.ServerError("TransferOwnership", err)
  328. }
  329. return
  330. }
  331. err = models.NewRepoRedirect(oldOwnerID, repo.ID, repo.Name, repo.Name)
  332. if err != nil {
  333. ctx.ServerError("NewRepoRedirect", err)
  334. return
  335. }
  336. log.Trace("Repository transferred: %s/%s -> %s", ctx.Repo.Owner.Name, repo.Name, newOwner)
  337. ctx.Flash.Success(ctx.Tr("repo.settings.transfer_succeed"))
  338. ctx.Redirect(setting.AppSubURL + "/" + newOwner + "/" + repo.Name)
  339. case "delete":
  340. if !ctx.Repo.IsOwner() {
  341. ctx.Error(404)
  342. return
  343. }
  344. if repo.Name != form.RepoName {
  345. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  346. return
  347. }
  348. if err := models.DeleteRepository(ctx.User, ctx.Repo.Owner.ID, repo.ID); err != nil {
  349. ctx.ServerError("DeleteRepository", err)
  350. return
  351. }
  352. log.Trace("Repository deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  353. ctx.Flash.Success(ctx.Tr("repo.settings.deletion_success"))
  354. ctx.Redirect(ctx.Repo.Owner.DashboardLink())
  355. case "delete-wiki":
  356. if !ctx.Repo.IsOwner() {
  357. ctx.Error(404)
  358. return
  359. }
  360. if repo.Name != form.RepoName {
  361. ctx.RenderWithErr(ctx.Tr("form.enterred_invalid_repo_name"), tplSettingsOptions, nil)
  362. return
  363. }
  364. err := repo.DeleteWiki()
  365. if err != nil {
  366. log.Error("Delete Wiki: %v", err.Error())
  367. }
  368. log.Trace("Repository wiki deleted: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  369. ctx.Flash.Success(ctx.Tr("repo.settings.wiki_deletion_success"))
  370. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  371. case "archive":
  372. if !ctx.Repo.IsOwner() {
  373. ctx.Error(403)
  374. return
  375. }
  376. if repo.IsMirror {
  377. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error_ismirror"))
  378. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  379. return
  380. }
  381. if err := repo.SetArchiveRepoState(true); err != nil {
  382. log.Error("Tried to archive a repo: %s", err)
  383. ctx.Flash.Error(ctx.Tr("repo.settings.archive.error"))
  384. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  385. return
  386. }
  387. ctx.Flash.Success(ctx.Tr("repo.settings.archive.success"))
  388. log.Trace("Repository was archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  389. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  390. case "unarchive":
  391. if !ctx.Repo.IsOwner() {
  392. ctx.Error(403)
  393. return
  394. }
  395. if err := repo.SetArchiveRepoState(false); err != nil {
  396. log.Error("Tried to unarchive a repo: %s", err)
  397. ctx.Flash.Error(ctx.Tr("repo.settings.unarchive.error"))
  398. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  399. return
  400. }
  401. ctx.Flash.Success(ctx.Tr("repo.settings.unarchive.success"))
  402. log.Trace("Repository was un-archived: %s/%s", ctx.Repo.Owner.Name, repo.Name)
  403. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  404. default:
  405. ctx.NotFound("", nil)
  406. }
  407. }
  408. // Collaboration render a repository's collaboration page
  409. func Collaboration(ctx *context.Context) {
  410. ctx.Data["Title"] = ctx.Tr("repo.settings")
  411. ctx.Data["PageIsSettingsCollaboration"] = true
  412. users, err := ctx.Repo.Repository.GetCollaborators()
  413. if err != nil {
  414. ctx.ServerError("GetCollaborators", err)
  415. return
  416. }
  417. ctx.Data["Collaborators"] = users
  418. ctx.HTML(200, tplCollaboration)
  419. }
  420. // CollaborationPost response for actions for a collaboration of a repository
  421. func CollaborationPost(ctx *context.Context) {
  422. name := utils.RemoveUsernameParameterSuffix(strings.ToLower(ctx.Query("collaborator")))
  423. if len(name) == 0 || ctx.Repo.Owner.LowerName == name {
  424. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  425. return
  426. }
  427. u, err := models.GetUserByName(name)
  428. if err != nil {
  429. if models.IsErrUserNotExist(err) {
  430. ctx.Flash.Error(ctx.Tr("form.user_not_exist"))
  431. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  432. } else {
  433. ctx.ServerError("GetUserByName", err)
  434. }
  435. return
  436. }
  437. if !u.IsActive {
  438. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_inactive_user"))
  439. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  440. return
  441. }
  442. // Organization is not allowed to be added as a collaborator.
  443. if u.IsOrganization() {
  444. ctx.Flash.Error(ctx.Tr("repo.settings.org_not_allowed_to_be_collaborator"))
  445. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  446. return
  447. }
  448. if got, err := ctx.Repo.Repository.IsCollaborator(u.ID); err == nil && got {
  449. ctx.Flash.Error(ctx.Tr("repo.settings.add_collaborator_duplicate"))
  450. ctx.Redirect(ctx.Repo.RepoLink + "/settings/collaboration")
  451. return
  452. }
  453. if err = ctx.Repo.Repository.AddCollaborator(u); err != nil {
  454. ctx.ServerError("AddCollaborator", err)
  455. return
  456. }
  457. if setting.Service.EnableNotifyMail {
  458. models.SendCollaboratorMail(u, ctx.User, ctx.Repo.Repository)
  459. }
  460. ctx.Flash.Success(ctx.Tr("repo.settings.add_collaborator_success"))
  461. ctx.Redirect(setting.AppSubURL + ctx.Req.URL.Path)
  462. }
  463. // ChangeCollaborationAccessMode response for changing access of a collaboration
  464. func ChangeCollaborationAccessMode(ctx *context.Context) {
  465. if err := ctx.Repo.Repository.ChangeCollaborationAccessMode(
  466. ctx.QueryInt64("uid"),
  467. models.AccessMode(ctx.QueryInt("mode"))); err != nil {
  468. log.Error("ChangeCollaborationAccessMode: %v", err)
  469. }
  470. }
  471. // DeleteCollaboration delete a collaboration for a repository
  472. func DeleteCollaboration(ctx *context.Context) {
  473. if err := ctx.Repo.Repository.DeleteCollaboration(ctx.QueryInt64("id")); err != nil {
  474. ctx.Flash.Error("DeleteCollaboration: " + err.Error())
  475. } else {
  476. ctx.Flash.Success(ctx.Tr("repo.settings.remove_collaborator_success"))
  477. }
  478. ctx.JSON(200, map[string]interface{}{
  479. "redirect": ctx.Repo.RepoLink + "/settings/collaboration",
  480. })
  481. }
  482. // parseOwnerAndRepo get repos by owner
  483. func parseOwnerAndRepo(ctx *context.Context) (*models.User, *models.Repository) {
  484. owner, err := models.GetUserByName(ctx.Params(":username"))
  485. if err != nil {
  486. if models.IsErrUserNotExist(err) {
  487. ctx.NotFound("GetUserByName", err)
  488. } else {
  489. ctx.ServerError("GetUserByName", err)
  490. }
  491. return nil, nil
  492. }
  493. repo, err := models.GetRepositoryByName(owner.ID, ctx.Params(":reponame"))
  494. if err != nil {
  495. if models.IsErrRepoNotExist(err) {
  496. ctx.NotFound("GetRepositoryByName", err)
  497. } else {
  498. ctx.ServerError("GetRepositoryByName", err)
  499. }
  500. return nil, nil
  501. }
  502. return owner, repo
  503. }
  504. // GitHooks hooks of a repository
  505. func GitHooks(ctx *context.Context) {
  506. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  507. ctx.Data["PageIsSettingsGitHooks"] = true
  508. hooks, err := ctx.Repo.GitRepo.Hooks()
  509. if err != nil {
  510. ctx.ServerError("Hooks", err)
  511. return
  512. }
  513. ctx.Data["Hooks"] = hooks
  514. ctx.HTML(200, tplGithooks)
  515. }
  516. // GitHooksEdit render for editing a hook of repository page
  517. func GitHooksEdit(ctx *context.Context) {
  518. ctx.Data["Title"] = ctx.Tr("repo.settings.githooks")
  519. ctx.Data["PageIsSettingsGitHooks"] = true
  520. name := ctx.Params(":name")
  521. hook, err := ctx.Repo.GitRepo.GetHook(name)
  522. if err != nil {
  523. if err == git.ErrNotValidHook {
  524. ctx.NotFound("GetHook", err)
  525. } else {
  526. ctx.ServerError("GetHook", err)
  527. }
  528. return
  529. }
  530. ctx.Data["Hook"] = hook
  531. ctx.HTML(200, tplGithookEdit)
  532. }
  533. // GitHooksEditPost response for editing a git hook of a repository
  534. func GitHooksEditPost(ctx *context.Context) {
  535. name := ctx.Params(":name")
  536. hook, err := ctx.Repo.GitRepo.GetHook(name)
  537. if err != nil {
  538. if err == git.ErrNotValidHook {
  539. ctx.NotFound("GetHook", err)
  540. } else {
  541. ctx.ServerError("GetHook", err)
  542. }
  543. return
  544. }
  545. hook.Content = ctx.Query("content")
  546. if err = hook.Update(); err != nil {
  547. ctx.ServerError("hook.Update", err)
  548. return
  549. }
  550. ctx.Redirect(ctx.Repo.RepoLink + "/settings/hooks/git")
  551. }
  552. // DeployKeys render the deploy keys list of a repository page
  553. func DeployKeys(ctx *context.Context) {
  554. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  555. ctx.Data["PageIsSettingsKeys"] = true
  556. ctx.Data["DisableSSH"] = setting.SSH.Disabled
  557. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  558. if err != nil {
  559. ctx.ServerError("ListDeployKeys", err)
  560. return
  561. }
  562. ctx.Data["Deploykeys"] = keys
  563. ctx.HTML(200, tplDeployKeys)
  564. }
  565. // DeployKeysPost response for adding a deploy key of a repository
  566. func DeployKeysPost(ctx *context.Context, form auth.AddKeyForm) {
  567. ctx.Data["Title"] = ctx.Tr("repo.settings.deploy_keys")
  568. ctx.Data["PageIsSettingsKeys"] = true
  569. keys, err := models.ListDeployKeys(ctx.Repo.Repository.ID)
  570. if err != nil {
  571. ctx.ServerError("ListDeployKeys", err)
  572. return
  573. }
  574. ctx.Data["Deploykeys"] = keys
  575. if ctx.HasError() {
  576. ctx.HTML(200, tplDeployKeys)
  577. return
  578. }
  579. content, err := models.CheckPublicKeyString(form.Content)
  580. if err != nil {
  581. if models.IsErrSSHDisabled(err) {
  582. ctx.Flash.Info(ctx.Tr("settings.ssh_disabled"))
  583. } else if models.IsErrKeyUnableVerify(err) {
  584. ctx.Flash.Info(ctx.Tr("form.unable_verify_ssh_key"))
  585. } else {
  586. ctx.Data["HasError"] = true
  587. ctx.Data["Err_Content"] = true
  588. ctx.Flash.Error(ctx.Tr("form.invalid_ssh_key", err.Error()))
  589. }
  590. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  591. return
  592. }
  593. key, err := models.AddDeployKey(ctx.Repo.Repository.ID, form.Title, content, !form.IsWritable)
  594. if err != nil {
  595. ctx.Data["HasError"] = true
  596. switch {
  597. case models.IsErrDeployKeyAlreadyExist(err):
  598. ctx.Data["Err_Content"] = true
  599. ctx.RenderWithErr(ctx.Tr("repo.settings.key_been_used"), tplDeployKeys, &form)
  600. case models.IsErrKeyAlreadyExist(err):
  601. ctx.Data["Err_Content"] = true
  602. ctx.RenderWithErr(ctx.Tr("settings.ssh_key_been_used"), tplDeployKeys, &form)
  603. case models.IsErrKeyNameAlreadyUsed(err):
  604. ctx.Data["Err_Title"] = true
  605. ctx.RenderWithErr(ctx.Tr("repo.settings.key_name_used"), tplDeployKeys, &form)
  606. default:
  607. ctx.ServerError("AddDeployKey", err)
  608. }
  609. return
  610. }
  611. log.Trace("Deploy key added: %d", ctx.Repo.Repository.ID)
  612. ctx.Flash.Success(ctx.Tr("repo.settings.add_key_success", key.Name))
  613. ctx.Redirect(ctx.Repo.RepoLink + "/settings/keys")
  614. }
  615. // DeleteDeployKey response for deleting a deploy key
  616. func DeleteDeployKey(ctx *context.Context) {
  617. if err := models.DeleteDeployKey(ctx.User, ctx.QueryInt64("id")); err != nil {
  618. ctx.Flash.Error("DeleteDeployKey: " + err.Error())
  619. } else {
  620. ctx.Flash.Success(ctx.Tr("repo.settings.deploy_key_deletion_success"))
  621. }
  622. ctx.JSON(200, map[string]interface{}{
  623. "redirect": ctx.Repo.RepoLink + "/settings/keys",
  624. })
  625. }
  626. func init() {
  627. var err error
  628. validFormAddress, err = xurls.StrictMatchingScheme(`(https?)|(git)://`)
  629. if err != nil {
  630. panic(err)
  631. }
  632. }
  633. // UpdateAvatarSetting update repo's avatar
  634. func UpdateAvatarSetting(ctx *context.Context, form auth.AvatarForm) error {
  635. ctxRepo := ctx.Repo.Repository
  636. if form.Avatar == nil {
  637. // No avatar is uploaded and we not removing it here.
  638. // No random avatar generated here.
  639. // Just exit, no action.
  640. if !com.IsFile(ctxRepo.CustomAvatarPath()) {
  641. log.Trace("No avatar was uploaded for repo: %d. Default icon will appear instead.", ctxRepo.ID)
  642. }
  643. return nil
  644. }
  645. r, err := form.Avatar.Open()
  646. if err != nil {
  647. return fmt.Errorf("Avatar.Open: %v", err)
  648. }
  649. defer r.Close()
  650. if form.Avatar.Size > setting.AvatarMaxFileSize {
  651. return errors.New(ctx.Tr("settings.uploaded_avatar_is_too_big"))
  652. }
  653. data, err := ioutil.ReadAll(r)
  654. if err != nil {
  655. return fmt.Errorf("ioutil.ReadAll: %v", err)
  656. }
  657. if !base.IsImageFile(data) {
  658. return errors.New(ctx.Tr("settings.uploaded_avatar_not_a_image"))
  659. }
  660. if err = ctxRepo.UploadAvatar(data); err != nil {
  661. return fmt.Errorf("UploadAvatar: %v", err)
  662. }
  663. return nil
  664. }
  665. // SettingsAvatar save new POSTed repository avatar
  666. func SettingsAvatar(ctx *context.Context, form auth.AvatarForm) {
  667. form.Source = auth.AvatarLocal
  668. if err := UpdateAvatarSetting(ctx, form); err != nil {
  669. ctx.Flash.Error(err.Error())
  670. } else {
  671. ctx.Flash.Success(ctx.Tr("repo.settings.update_avatar_success"))
  672. }
  673. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  674. }
  675. // SettingsDeleteAvatar delete repository avatar
  676. func SettingsDeleteAvatar(ctx *context.Context) {
  677. if err := ctx.Repo.Repository.DeleteAvatar(); err != nil {
  678. ctx.Flash.Error(fmt.Sprintf("DeleteAvatar: %v", err))
  679. }
  680. ctx.Redirect(ctx.Repo.RepoLink + "/settings")
  681. }