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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 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 user
  6. import (
  7. "bytes"
  8. "fmt"
  9. "net/http"
  10. "regexp"
  11. "sort"
  12. "strconv"
  13. "strings"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/base"
  16. "code.gitea.io/gitea/modules/context"
  17. issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
  18. "code.gitea.io/gitea/modules/log"
  19. "code.gitea.io/gitea/modules/markup/markdown"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/util"
  22. issue_service "code.gitea.io/gitea/services/issue"
  23. pull_service "code.gitea.io/gitea/services/pull"
  24. jsoniter "github.com/json-iterator/go"
  25. "github.com/keybase/go-crypto/openpgp"
  26. "github.com/keybase/go-crypto/openpgp/armor"
  27. "xorm.io/builder"
  28. )
  29. const (
  30. tplDashboard base.TplName = "user/dashboard/dashboard"
  31. tplIssues base.TplName = "user/dashboard/issues"
  32. tplMilestones base.TplName = "user/dashboard/milestones"
  33. tplProfile base.TplName = "user/profile"
  34. )
  35. // getDashboardContextUser finds out which context user dashboard is being viewed as .
  36. func getDashboardContextUser(ctx *context.Context) *models.User {
  37. ctxUser := ctx.User
  38. orgName := ctx.Params(":org")
  39. if len(orgName) > 0 {
  40. ctxUser = ctx.Org.Organization
  41. ctx.Data["Teams"] = ctx.Org.Organization.Teams
  42. }
  43. ctx.Data["ContextUser"] = ctxUser
  44. if err := ctx.User.GetOrganizations(&models.SearchOrganizationsOptions{All: true}); err != nil {
  45. ctx.ServerError("GetOrganizations", err)
  46. return nil
  47. }
  48. ctx.Data["Orgs"] = ctx.User.Orgs
  49. return ctxUser
  50. }
  51. // retrieveFeeds loads feeds for the specified user
  52. func retrieveFeeds(ctx *context.Context, options models.GetFeedsOptions) {
  53. actions, err := models.GetFeeds(options)
  54. if err != nil {
  55. ctx.ServerError("GetFeeds", err)
  56. return
  57. }
  58. userCache := map[int64]*models.User{options.RequestedUser.ID: options.RequestedUser}
  59. if ctx.User != nil {
  60. userCache[ctx.User.ID] = ctx.User
  61. }
  62. for _, act := range actions {
  63. if act.ActUser != nil {
  64. userCache[act.ActUserID] = act.ActUser
  65. }
  66. }
  67. for _, act := range actions {
  68. repoOwner, ok := userCache[act.Repo.OwnerID]
  69. if !ok {
  70. repoOwner, err = models.GetUserByID(act.Repo.OwnerID)
  71. if err != nil {
  72. if models.IsErrUserNotExist(err) {
  73. continue
  74. }
  75. ctx.ServerError("GetUserByID", err)
  76. return
  77. }
  78. userCache[repoOwner.ID] = repoOwner
  79. }
  80. act.Repo.Owner = repoOwner
  81. }
  82. ctx.Data["Feeds"] = actions
  83. }
  84. // Dashboard render the dashboard page
  85. func Dashboard(ctx *context.Context) {
  86. ctxUser := getDashboardContextUser(ctx)
  87. if ctx.Written() {
  88. return
  89. }
  90. ctx.Data["Title"] = ctxUser.DisplayName() + " - " + ctx.Tr("dashboard")
  91. ctx.Data["PageIsDashboard"] = true
  92. ctx.Data["PageIsNews"] = true
  93. ctx.Data["SearchLimit"] = setting.UI.User.RepoPagingNum
  94. if setting.Service.EnableUserHeatmap {
  95. data, err := models.GetUserHeatmapDataByUserTeam(ctxUser, ctx.Org.Team, ctx.User)
  96. if err != nil {
  97. ctx.ServerError("GetUserHeatmapDataByUserTeam", err)
  98. return
  99. }
  100. ctx.Data["HeatmapData"] = data
  101. }
  102. var err error
  103. var mirrors []*models.Repository
  104. if ctxUser.IsOrganization() {
  105. var env models.AccessibleReposEnvironment
  106. if ctx.Org.Team != nil {
  107. env = ctxUser.AccessibleTeamReposEnv(ctx.Org.Team)
  108. } else {
  109. env, err = ctxUser.AccessibleReposEnv(ctx.User.ID)
  110. if err != nil {
  111. ctx.ServerError("AccessibleReposEnv", err)
  112. return
  113. }
  114. }
  115. mirrors, err = env.MirrorRepos()
  116. if err != nil {
  117. ctx.ServerError("env.MirrorRepos", err)
  118. return
  119. }
  120. } else {
  121. mirrors, err = ctxUser.GetMirrorRepositories()
  122. if err != nil {
  123. ctx.ServerError("GetMirrorRepositories", err)
  124. return
  125. }
  126. }
  127. ctx.Data["MaxShowRepoNum"] = setting.UI.User.RepoPagingNum
  128. if err := models.MirrorRepositoryList(mirrors).LoadAttributes(); err != nil {
  129. ctx.ServerError("MirrorRepositoryList.LoadAttributes", err)
  130. return
  131. }
  132. ctx.Data["MirrorCount"] = len(mirrors)
  133. ctx.Data["Mirrors"] = mirrors
  134. retrieveFeeds(ctx, models.GetFeedsOptions{
  135. RequestedUser: ctxUser,
  136. RequestedTeam: ctx.Org.Team,
  137. Actor: ctx.User,
  138. IncludePrivate: true,
  139. OnlyPerformedBy: false,
  140. IncludeDeleted: false,
  141. Date: ctx.Query("date"),
  142. })
  143. if ctx.Written() {
  144. return
  145. }
  146. ctx.HTML(http.StatusOK, tplDashboard)
  147. }
  148. // Milestones render the user milestones page
  149. func Milestones(ctx *context.Context) {
  150. if models.UnitTypeIssues.UnitGlobalDisabled() && models.UnitTypePullRequests.UnitGlobalDisabled() {
  151. log.Debug("Milestones overview page not available as both issues and pull requests are globally disabled")
  152. ctx.Status(404)
  153. return
  154. }
  155. ctx.Data["Title"] = ctx.Tr("milestones")
  156. ctx.Data["PageIsMilestonesDashboard"] = true
  157. ctxUser := getDashboardContextUser(ctx)
  158. if ctx.Written() {
  159. return
  160. }
  161. repoOpts := models.SearchRepoOptions{
  162. Actor: ctxUser,
  163. OwnerID: ctxUser.ID,
  164. Private: true,
  165. AllPublic: false, // Include also all public repositories of users and public organisations
  166. AllLimited: false, // Include also all public repositories of limited organisations
  167. HasMilestones: util.OptionalBoolTrue, // Just needs display repos has milestones
  168. }
  169. if ctxUser.IsOrganization() && ctx.Org.Team != nil {
  170. repoOpts.TeamID = ctx.Org.Team.ID
  171. }
  172. var (
  173. userRepoCond = models.SearchRepositoryCondition(&repoOpts) // all repo condition user could visit
  174. repoCond = userRepoCond
  175. repoIDs []int64
  176. reposQuery = ctx.Query("repos")
  177. isShowClosed = ctx.Query("state") == "closed"
  178. sortType = ctx.Query("sort")
  179. page = ctx.QueryInt("page")
  180. keyword = strings.Trim(ctx.Query("q"), " ")
  181. )
  182. if page <= 1 {
  183. page = 1
  184. }
  185. if len(reposQuery) != 0 {
  186. if issueReposQueryPattern.MatchString(reposQuery) {
  187. // remove "[" and "]" from string
  188. reposQuery = reposQuery[1 : len(reposQuery)-1]
  189. //for each ID (delimiter ",") add to int to repoIDs
  190. for _, rID := range strings.Split(reposQuery, ",") {
  191. // Ensure nonempty string entries
  192. if rID != "" && rID != "0" {
  193. rIDint64, err := strconv.ParseInt(rID, 10, 64)
  194. // If the repo id specified by query is not parseable or not accessible by user, just ignore it.
  195. if err == nil {
  196. repoIDs = append(repoIDs, rIDint64)
  197. }
  198. }
  199. }
  200. if len(repoIDs) > 0 {
  201. // Don't just let repoCond = builder.In("id", repoIDs) because user may has no permission on repoIDs
  202. // But the original repoCond has a limitation
  203. repoCond = repoCond.And(builder.In("id", repoIDs))
  204. }
  205. } else {
  206. log.Warn("issueReposQueryPattern not match with query")
  207. }
  208. }
  209. counts, err := models.CountMilestonesByRepoCondAndKw(userRepoCond, keyword, isShowClosed)
  210. if err != nil {
  211. ctx.ServerError("CountMilestonesByRepoIDs", err)
  212. return
  213. }
  214. milestones, err := models.SearchMilestones(repoCond, page, isShowClosed, sortType, keyword)
  215. if err != nil {
  216. ctx.ServerError("SearchMilestones", err)
  217. return
  218. }
  219. showRepos, _, err := models.SearchRepositoryByCondition(&repoOpts, userRepoCond, false)
  220. if err != nil {
  221. ctx.ServerError("SearchRepositoryByCondition", err)
  222. return
  223. }
  224. sort.Sort(showRepos)
  225. for i := 0; i < len(milestones); {
  226. for _, repo := range showRepos {
  227. if milestones[i].RepoID == repo.ID {
  228. milestones[i].Repo = repo
  229. break
  230. }
  231. }
  232. if milestones[i].Repo == nil {
  233. log.Warn("Cannot find milestone %d 's repository %d", milestones[i].ID, milestones[i].RepoID)
  234. milestones = append(milestones[:i], milestones[i+1:]...)
  235. continue
  236. }
  237. milestones[i].RenderedContent = string(markdown.Render([]byte(milestones[i].Content), milestones[i].Repo.Link(), milestones[i].Repo.ComposeMetas()))
  238. if milestones[i].Repo.IsTimetrackerEnabled() {
  239. err := milestones[i].LoadTotalTrackedTime()
  240. if err != nil {
  241. ctx.ServerError("LoadTotalTrackedTime", err)
  242. return
  243. }
  244. }
  245. i++
  246. }
  247. milestoneStats, err := models.GetMilestonesStatsByRepoCondAndKw(repoCond, keyword)
  248. if err != nil {
  249. ctx.ServerError("GetMilestoneStats", err)
  250. return
  251. }
  252. var totalMilestoneStats *models.MilestonesStats
  253. if len(repoIDs) == 0 {
  254. totalMilestoneStats = milestoneStats
  255. } else {
  256. totalMilestoneStats, err = models.GetMilestonesStatsByRepoCondAndKw(userRepoCond, keyword)
  257. if err != nil {
  258. ctx.ServerError("GetMilestoneStats", err)
  259. return
  260. }
  261. }
  262. var pagerCount int
  263. if isShowClosed {
  264. ctx.Data["State"] = "closed"
  265. ctx.Data["Total"] = totalMilestoneStats.ClosedCount
  266. pagerCount = int(milestoneStats.ClosedCount)
  267. } else {
  268. ctx.Data["State"] = "open"
  269. ctx.Data["Total"] = totalMilestoneStats.OpenCount
  270. pagerCount = int(milestoneStats.OpenCount)
  271. }
  272. ctx.Data["Milestones"] = milestones
  273. ctx.Data["Repos"] = showRepos
  274. ctx.Data["Counts"] = counts
  275. ctx.Data["MilestoneStats"] = milestoneStats
  276. ctx.Data["SortType"] = sortType
  277. ctx.Data["Keyword"] = keyword
  278. if milestoneStats.Total() != totalMilestoneStats.Total() {
  279. ctx.Data["RepoIDs"] = repoIDs
  280. }
  281. ctx.Data["IsShowClosed"] = isShowClosed
  282. pager := context.NewPagination(pagerCount, setting.UI.IssuePagingNum, page, 5)
  283. pager.AddParam(ctx, "q", "Keyword")
  284. pager.AddParam(ctx, "repos", "RepoIDs")
  285. pager.AddParam(ctx, "sort", "SortType")
  286. pager.AddParam(ctx, "state", "State")
  287. ctx.Data["Page"] = pager
  288. ctx.HTML(http.StatusOK, tplMilestones)
  289. }
  290. // Pulls renders the user's pull request overview page
  291. func Pulls(ctx *context.Context) {
  292. if models.UnitTypePullRequests.UnitGlobalDisabled() {
  293. log.Debug("Pull request overview page not available as it is globally disabled.")
  294. ctx.Status(404)
  295. return
  296. }
  297. ctx.Data["Title"] = ctx.Tr("pull_requests")
  298. ctx.Data["PageIsPulls"] = true
  299. buildIssueOverview(ctx, models.UnitTypePullRequests)
  300. }
  301. // Issues renders the user's issues overview page
  302. func Issues(ctx *context.Context) {
  303. if models.UnitTypeIssues.UnitGlobalDisabled() {
  304. log.Debug("Issues overview page not available as it is globally disabled.")
  305. ctx.Status(404)
  306. return
  307. }
  308. ctx.Data["Title"] = ctx.Tr("issues")
  309. ctx.Data["PageIsIssues"] = true
  310. buildIssueOverview(ctx, models.UnitTypeIssues)
  311. }
  312. // Regexp for repos query
  313. var issueReposQueryPattern = regexp.MustCompile(`^\[\d+(,\d+)*,?\]$`)
  314. func buildIssueOverview(ctx *context.Context, unitType models.UnitType) {
  315. // ----------------------------------------------------
  316. // Determine user; can be either user or organization.
  317. // Return with NotFound or ServerError if unsuccessful.
  318. // ----------------------------------------------------
  319. ctxUser := getDashboardContextUser(ctx)
  320. if ctx.Written() {
  321. return
  322. }
  323. var (
  324. viewType string
  325. sortType = ctx.Query("sort")
  326. filterMode = models.FilterModeAll
  327. )
  328. // --------------------------------------------------------------------------------
  329. // Distinguish User from Organization.
  330. // Org:
  331. // - Remember pre-determined viewType string for later. Will be posted to ctx.Data.
  332. // Organization does not have view type and filter mode.
  333. // User:
  334. // - Use ctx.Query("type") to determine filterMode.
  335. // The type is set when clicking for example "assigned to me" on the overview page.
  336. // - Remember either this or a fallback. Will be posted to ctx.Data.
  337. // --------------------------------------------------------------------------------
  338. // TODO: distinguish during routing
  339. viewType = ctx.Query("type")
  340. switch viewType {
  341. case "assigned":
  342. filterMode = models.FilterModeAssign
  343. case "created_by":
  344. filterMode = models.FilterModeCreate
  345. case "mentioned":
  346. filterMode = models.FilterModeMention
  347. case "review_requested":
  348. filterMode = models.FilterModeReviewRequested
  349. case "your_repositories": // filterMode already set to All
  350. default:
  351. viewType = "your_repositories"
  352. }
  353. // --------------------------------------------------------------------------
  354. // Build opts (IssuesOptions), which contains filter information.
  355. // Will eventually be used to retrieve issues relevant for the overview page.
  356. // Note: Non-final states of opts are used in-between, namely for:
  357. // - Keyword search
  358. // - Count Issues by repo
  359. // --------------------------------------------------------------------------
  360. isPullList := unitType == models.UnitTypePullRequests
  361. opts := &models.IssuesOptions{
  362. IsPull: util.OptionalBoolOf(isPullList),
  363. SortType: sortType,
  364. IsArchived: util.OptionalBoolFalse,
  365. }
  366. // Get repository IDs where User/Org/Team has access.
  367. var team *models.Team
  368. if ctx.Org != nil {
  369. team = ctx.Org.Team
  370. }
  371. userRepoIDs, err := getActiveUserRepoIDs(ctxUser, team, unitType)
  372. if err != nil {
  373. ctx.ServerError("userRepoIDs", err)
  374. return
  375. }
  376. switch filterMode {
  377. case models.FilterModeAll:
  378. opts.RepoIDs = userRepoIDs
  379. case models.FilterModeAssign:
  380. opts.AssigneeID = ctx.User.ID
  381. case models.FilterModeCreate:
  382. opts.PosterID = ctx.User.ID
  383. case models.FilterModeMention:
  384. opts.MentionedID = ctx.User.ID
  385. case models.FilterModeReviewRequested:
  386. opts.ReviewRequestedID = ctx.User.ID
  387. }
  388. if ctxUser.IsOrganization() {
  389. opts.RepoIDs = userRepoIDs
  390. }
  391. // keyword holds the search term entered into the search field.
  392. keyword := strings.Trim(ctx.Query("q"), " ")
  393. ctx.Data["Keyword"] = keyword
  394. // Execute keyword search for issues.
  395. // USING NON-FINAL STATE OF opts FOR A QUERY.
  396. issueIDsFromSearch, err := issueIDsFromSearch(ctxUser, keyword, opts)
  397. if err != nil {
  398. ctx.ServerError("issueIDsFromSearch", err)
  399. return
  400. }
  401. // Ensure no issues are returned if a keyword was provided that didn't match any issues.
  402. var forceEmpty bool
  403. if len(issueIDsFromSearch) > 0 {
  404. opts.IssueIDs = issueIDsFromSearch
  405. } else if len(keyword) > 0 {
  406. forceEmpty = true
  407. }
  408. // Educated guess: Do or don't show closed issues.
  409. isShowClosed := ctx.Query("state") == "closed"
  410. opts.IsClosed = util.OptionalBoolOf(isShowClosed)
  411. // Filter repos and count issues in them. Count will be used later.
  412. // USING NON-FINAL STATE OF opts FOR A QUERY.
  413. var issueCountByRepo map[int64]int64
  414. if !forceEmpty {
  415. issueCountByRepo, err = models.CountIssuesByRepo(opts)
  416. if err != nil {
  417. ctx.ServerError("CountIssuesByRepo", err)
  418. return
  419. }
  420. }
  421. // Make sure page number is at least 1. Will be posted to ctx.Data.
  422. page := ctx.QueryInt("page")
  423. if page <= 1 {
  424. page = 1
  425. }
  426. opts.Page = page
  427. opts.PageSize = setting.UI.IssuePagingNum
  428. // Get IDs for labels (a filter option for issues/pulls).
  429. // Required for IssuesOptions.
  430. var labelIDs []int64
  431. selectedLabels := ctx.Query("labels")
  432. if len(selectedLabels) > 0 && selectedLabels != "0" {
  433. labelIDs, err = base.StringsToInt64s(strings.Split(selectedLabels, ","))
  434. if err != nil {
  435. ctx.ServerError("StringsToInt64s", err)
  436. return
  437. }
  438. }
  439. opts.LabelIDs = labelIDs
  440. // Parse ctx.Query("repos") and remember matched repo IDs for later.
  441. // Gets set when clicking filters on the issues overview page.
  442. repoIDs := getRepoIDs(ctx.Query("repos"))
  443. if len(repoIDs) > 0 {
  444. opts.RepoIDs = repoIDs
  445. }
  446. // ------------------------------
  447. // Get issues as defined by opts.
  448. // ------------------------------
  449. // Slice of Issues that will be displayed on the overview page
  450. // USING FINAL STATE OF opts FOR A QUERY.
  451. var issues []*models.Issue
  452. if !forceEmpty {
  453. issues, err = models.Issues(opts)
  454. if err != nil {
  455. ctx.ServerError("Issues", err)
  456. return
  457. }
  458. } else {
  459. issues = []*models.Issue{}
  460. }
  461. // ----------------------------------
  462. // Add repository pointers to Issues.
  463. // ----------------------------------
  464. // showReposMap maps repository IDs to their Repository pointers.
  465. showReposMap, err := repoIDMap(ctxUser, issueCountByRepo, unitType)
  466. if err != nil {
  467. if models.IsErrRepoNotExist(err) {
  468. ctx.NotFound("GetRepositoryByID", err)
  469. return
  470. }
  471. ctx.ServerError("repoIDMap", err)
  472. return
  473. }
  474. // a RepositoryList
  475. showRepos := models.RepositoryListOfMap(showReposMap)
  476. sort.Sort(showRepos)
  477. if err = showRepos.LoadAttributes(); err != nil {
  478. ctx.ServerError("LoadAttributes", err)
  479. return
  480. }
  481. // maps pull request IDs to their CommitStatus. Will be posted to ctx.Data.
  482. var commitStatus = make(map[int64]*models.CommitStatus, len(issues))
  483. for _, issue := range issues {
  484. issue.Repo = showReposMap[issue.RepoID]
  485. if isPullList {
  486. var statuses, _ = pull_service.GetLastCommitStatus(issue.PullRequest)
  487. commitStatus[issue.PullRequest.ID] = models.CalcCommitStatus(statuses)
  488. }
  489. }
  490. // -------------------------------
  491. // Fill stats to post to ctx.Data.
  492. // -------------------------------
  493. userIssueStatsOpts := models.UserIssueStatsOptions{
  494. UserID: ctx.User.ID,
  495. UserRepoIDs: userRepoIDs,
  496. FilterMode: filterMode,
  497. IsPull: isPullList,
  498. IsClosed: isShowClosed,
  499. IsArchived: util.OptionalBoolFalse,
  500. LabelIDs: opts.LabelIDs,
  501. }
  502. if len(repoIDs) > 0 {
  503. userIssueStatsOpts.UserRepoIDs = repoIDs
  504. }
  505. if ctxUser.IsOrganization() {
  506. userIssueStatsOpts.RepoIDs = userRepoIDs
  507. }
  508. userIssueStats, err := models.GetUserIssueStats(userIssueStatsOpts)
  509. if err != nil {
  510. ctx.ServerError("GetUserIssueStats User", err)
  511. return
  512. }
  513. var shownIssueStats *models.IssueStats
  514. if !forceEmpty {
  515. statsOpts := models.UserIssueStatsOptions{
  516. UserID: ctx.User.ID,
  517. UserRepoIDs: userRepoIDs,
  518. FilterMode: filterMode,
  519. IsPull: isPullList,
  520. IsClosed: isShowClosed,
  521. IssueIDs: issueIDsFromSearch,
  522. IsArchived: util.OptionalBoolFalse,
  523. LabelIDs: opts.LabelIDs,
  524. }
  525. if len(repoIDs) > 0 {
  526. statsOpts.RepoIDs = repoIDs
  527. } else if ctxUser.IsOrganization() {
  528. statsOpts.RepoIDs = userRepoIDs
  529. }
  530. shownIssueStats, err = models.GetUserIssueStats(statsOpts)
  531. if err != nil {
  532. ctx.ServerError("GetUserIssueStats Shown", err)
  533. return
  534. }
  535. } else {
  536. shownIssueStats = &models.IssueStats{}
  537. }
  538. var allIssueStats *models.IssueStats
  539. if !forceEmpty {
  540. allIssueStatsOpts := models.UserIssueStatsOptions{
  541. UserID: ctx.User.ID,
  542. UserRepoIDs: userRepoIDs,
  543. FilterMode: filterMode,
  544. IsPull: isPullList,
  545. IsClosed: isShowClosed,
  546. IssueIDs: issueIDsFromSearch,
  547. IsArchived: util.OptionalBoolFalse,
  548. LabelIDs: opts.LabelIDs,
  549. }
  550. if ctxUser.IsOrganization() {
  551. allIssueStatsOpts.RepoIDs = userRepoIDs
  552. }
  553. allIssueStats, err = models.GetUserIssueStats(allIssueStatsOpts)
  554. if err != nil {
  555. ctx.ServerError("GetUserIssueStats All", err)
  556. return
  557. }
  558. } else {
  559. allIssueStats = &models.IssueStats{}
  560. }
  561. // Will be posted to ctx.Data.
  562. var shownIssues int
  563. if !isShowClosed {
  564. shownIssues = int(shownIssueStats.OpenCount)
  565. ctx.Data["TotalIssueCount"] = int(allIssueStats.OpenCount)
  566. } else {
  567. shownIssues = int(shownIssueStats.ClosedCount)
  568. ctx.Data["TotalIssueCount"] = int(allIssueStats.ClosedCount)
  569. }
  570. ctx.Data["IsShowClosed"] = isShowClosed
  571. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
  572. issue_service.GetRefEndNamesAndURLs(issues, ctx.Query("RepoLink"))
  573. ctx.Data["Issues"] = issues
  574. approvalCounts, err := models.IssueList(issues).GetApprovalCounts()
  575. if err != nil {
  576. ctx.ServerError("ApprovalCounts", err)
  577. return
  578. }
  579. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  580. counts, ok := approvalCounts[issueID]
  581. if !ok || len(counts) == 0 {
  582. return 0
  583. }
  584. reviewTyp := models.ReviewTypeApprove
  585. if typ == "reject" {
  586. reviewTyp = models.ReviewTypeReject
  587. } else if typ == "waiting" {
  588. reviewTyp = models.ReviewTypeRequest
  589. }
  590. for _, count := range counts {
  591. if count.Type == reviewTyp {
  592. return count.Count
  593. }
  594. }
  595. return 0
  596. }
  597. ctx.Data["CommitStatus"] = commitStatus
  598. ctx.Data["Repos"] = showRepos
  599. ctx.Data["Counts"] = issueCountByRepo
  600. ctx.Data["IssueStats"] = userIssueStats
  601. ctx.Data["ShownIssueStats"] = shownIssueStats
  602. ctx.Data["ViewType"] = viewType
  603. ctx.Data["SortType"] = sortType
  604. ctx.Data["RepoIDs"] = repoIDs
  605. ctx.Data["IsShowClosed"] = isShowClosed
  606. ctx.Data["SelectLabels"] = selectedLabels
  607. if isShowClosed {
  608. ctx.Data["State"] = "closed"
  609. } else {
  610. ctx.Data["State"] = "open"
  611. }
  612. // Convert []int64 to string
  613. json := jsoniter.ConfigCompatibleWithStandardLibrary
  614. reposParam, _ := json.Marshal(repoIDs)
  615. ctx.Data["ReposParam"] = string(reposParam)
  616. pager := context.NewPagination(shownIssues, setting.UI.IssuePagingNum, page, 5)
  617. pager.AddParam(ctx, "q", "Keyword")
  618. pager.AddParam(ctx, "type", "ViewType")
  619. pager.AddParam(ctx, "repos", "ReposParam")
  620. pager.AddParam(ctx, "sort", "SortType")
  621. pager.AddParam(ctx, "state", "State")
  622. pager.AddParam(ctx, "labels", "SelectLabels")
  623. pager.AddParam(ctx, "milestone", "MilestoneID")
  624. pager.AddParam(ctx, "assignee", "AssigneeID")
  625. ctx.Data["Page"] = pager
  626. ctx.HTML(http.StatusOK, tplIssues)
  627. }
  628. func getRepoIDs(reposQuery string) []int64 {
  629. if len(reposQuery) == 0 || reposQuery == "[]" {
  630. return []int64{}
  631. }
  632. if !issueReposQueryPattern.MatchString(reposQuery) {
  633. log.Warn("issueReposQueryPattern does not match query")
  634. return []int64{}
  635. }
  636. var repoIDs []int64
  637. // remove "[" and "]" from string
  638. reposQuery = reposQuery[1 : len(reposQuery)-1]
  639. //for each ID (delimiter ",") add to int to repoIDs
  640. for _, rID := range strings.Split(reposQuery, ",") {
  641. // Ensure nonempty string entries
  642. if rID != "" && rID != "0" {
  643. rIDint64, err := strconv.ParseInt(rID, 10, 64)
  644. if err == nil {
  645. repoIDs = append(repoIDs, rIDint64)
  646. }
  647. }
  648. }
  649. return repoIDs
  650. }
  651. func getActiveUserRepoIDs(ctxUser *models.User, team *models.Team, unitType models.UnitType) ([]int64, error) {
  652. var userRepoIDs []int64
  653. var err error
  654. if ctxUser.IsOrganization() {
  655. userRepoIDs, err = getActiveTeamOrOrgRepoIds(ctxUser, team, unitType)
  656. if err != nil {
  657. return nil, fmt.Errorf("orgRepoIds: %v", err)
  658. }
  659. } else {
  660. userRepoIDs, err = ctxUser.GetActiveAccessRepoIDs(unitType)
  661. if err != nil {
  662. return nil, fmt.Errorf("ctxUser.GetAccessRepoIDs: %v", err)
  663. }
  664. }
  665. if len(userRepoIDs) == 0 {
  666. userRepoIDs = []int64{-1}
  667. }
  668. return userRepoIDs, nil
  669. }
  670. // getActiveTeamOrOrgRepoIds gets RepoIDs for ctxUser as Organization.
  671. // Should be called if and only if ctxUser.IsOrganization == true.
  672. func getActiveTeamOrOrgRepoIds(ctxUser *models.User, team *models.Team, unitType models.UnitType) ([]int64, error) {
  673. var orgRepoIDs []int64
  674. var err error
  675. var env models.AccessibleReposEnvironment
  676. if team != nil {
  677. env = ctxUser.AccessibleTeamReposEnv(team)
  678. } else {
  679. env, err = ctxUser.AccessibleReposEnv(ctxUser.ID)
  680. if err != nil {
  681. return nil, fmt.Errorf("AccessibleReposEnv: %v", err)
  682. }
  683. }
  684. orgRepoIDs, err = env.RepoIDs(1, ctxUser.NumRepos)
  685. if err != nil {
  686. return nil, fmt.Errorf("env.RepoIDs: %v", err)
  687. }
  688. orgRepoIDs, err = models.FilterOutRepoIdsWithoutUnitAccess(ctxUser, orgRepoIDs, unitType)
  689. if err != nil {
  690. return nil, fmt.Errorf("FilterOutRepoIdsWithoutUnitAccess: %v", err)
  691. }
  692. return orgRepoIDs, nil
  693. }
  694. func issueIDsFromSearch(ctxUser *models.User, keyword string, opts *models.IssuesOptions) ([]int64, error) {
  695. if len(keyword) == 0 {
  696. return []int64{}, nil
  697. }
  698. searchRepoIDs, err := models.GetRepoIDsForIssuesOptions(opts, ctxUser)
  699. if err != nil {
  700. return nil, fmt.Errorf("GetRepoIDsForIssuesOptions: %v", err)
  701. }
  702. issueIDsFromSearch, err := issue_indexer.SearchIssuesByKeyword(searchRepoIDs, keyword)
  703. if err != nil {
  704. return nil, fmt.Errorf("SearchIssuesByKeyword: %v", err)
  705. }
  706. return issueIDsFromSearch, nil
  707. }
  708. func repoIDMap(ctxUser *models.User, issueCountByRepo map[int64]int64, unitType models.UnitType) (map[int64]*models.Repository, error) {
  709. repoByID := make(map[int64]*models.Repository, len(issueCountByRepo))
  710. for id := range issueCountByRepo {
  711. if id <= 0 {
  712. continue
  713. }
  714. if _, ok := repoByID[id]; !ok {
  715. repo, err := models.GetRepositoryByID(id)
  716. if models.IsErrRepoNotExist(err) {
  717. return nil, err
  718. } else if err != nil {
  719. return nil, fmt.Errorf("GetRepositoryByID: [%d]%v", id, err)
  720. }
  721. repoByID[id] = repo
  722. }
  723. repo := repoByID[id]
  724. // Check if user has access to given repository.
  725. perm, err := models.GetUserRepoPermission(repo, ctxUser)
  726. if err != nil {
  727. return nil, fmt.Errorf("GetUserRepoPermission: [%d]%v", id, err)
  728. }
  729. if !perm.CanRead(unitType) {
  730. log.Debug("User created Issues in Repository which they no longer have access to: [%d]", id)
  731. }
  732. }
  733. return repoByID, nil
  734. }
  735. // ShowSSHKeys output all the ssh keys of user by uid
  736. func ShowSSHKeys(ctx *context.Context, uid int64) {
  737. keys, err := models.ListPublicKeys(uid, models.ListOptions{})
  738. if err != nil {
  739. ctx.ServerError("ListPublicKeys", err)
  740. return
  741. }
  742. var buf bytes.Buffer
  743. for i := range keys {
  744. buf.WriteString(keys[i].OmitEmail())
  745. buf.WriteString("\n")
  746. }
  747. ctx.PlainText(200, buf.Bytes())
  748. }
  749. // ShowGPGKeys output all the public GPG keys of user by uid
  750. func ShowGPGKeys(ctx *context.Context, uid int64) {
  751. keys, err := models.ListGPGKeys(uid, models.ListOptions{})
  752. if err != nil {
  753. ctx.ServerError("ListGPGKeys", err)
  754. return
  755. }
  756. entities := make([]*openpgp.Entity, 0)
  757. failedEntitiesID := make([]string, 0)
  758. for _, k := range keys {
  759. e, err := models.GPGKeyToEntity(k)
  760. if err != nil {
  761. if models.IsErrGPGKeyImportNotExist(err) {
  762. failedEntitiesID = append(failedEntitiesID, k.KeyID)
  763. continue //Skip previous import without backup of imported armored key
  764. }
  765. ctx.ServerError("ShowGPGKeys", err)
  766. return
  767. }
  768. entities = append(entities, e)
  769. }
  770. var buf bytes.Buffer
  771. headers := make(map[string]string)
  772. if len(failedEntitiesID) > 0 { //If some key need re-import to be exported
  773. headers["Note"] = fmt.Sprintf("The keys with the following IDs couldn't be exported and need to be reuploaded %s", strings.Join(failedEntitiesID, ", "))
  774. }
  775. writer, _ := armor.Encode(&buf, "PGP PUBLIC KEY BLOCK", headers)
  776. for _, e := range entities {
  777. err = e.Serialize(writer) //TODO find why key are exported with a different cipherTypeByte as original (should not be blocking but strange)
  778. if err != nil {
  779. ctx.ServerError("ShowGPGKeys", err)
  780. return
  781. }
  782. }
  783. writer.Close()
  784. ctx.PlainText(200, buf.Bytes())
  785. }
  786. // Email2User show user page via email
  787. func Email2User(ctx *context.Context) {
  788. u, err := models.GetUserByEmail(ctx.Query("email"))
  789. if err != nil {
  790. if models.IsErrUserNotExist(err) {
  791. ctx.NotFound("GetUserByEmail", err)
  792. } else {
  793. ctx.ServerError("GetUserByEmail", err)
  794. }
  795. return
  796. }
  797. ctx.Redirect(setting.AppSubURL + "/user/" + u.Name)
  798. }