本站源代码
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.

1788 lines
48KB

  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 models
  5. import (
  6. "fmt"
  7. "path"
  8. "regexp"
  9. "sort"
  10. "strings"
  11. "code.gitea.io/gitea/modules/base"
  12. "code.gitea.io/gitea/modules/log"
  13. "code.gitea.io/gitea/modules/setting"
  14. "code.gitea.io/gitea/modules/structs"
  15. api "code.gitea.io/gitea/modules/structs"
  16. "code.gitea.io/gitea/modules/timeutil"
  17. "code.gitea.io/gitea/modules/util"
  18. "github.com/unknwon/com"
  19. "xorm.io/builder"
  20. "xorm.io/xorm"
  21. )
  22. // Issue represents an issue or pull request of repository.
  23. type Issue struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  26. Repo *Repository `xorm:"-"`
  27. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  28. PosterID int64 `xorm:"INDEX"`
  29. Poster *User `xorm:"-"`
  30. OriginalAuthor string
  31. OriginalAuthorID int64 `xorm:"index"`
  32. Title string `xorm:"name"`
  33. Content string `xorm:"TEXT"`
  34. RenderedContent string `xorm:"-"`
  35. Labels []*Label `xorm:"-"`
  36. MilestoneID int64 `xorm:"INDEX"`
  37. Milestone *Milestone `xorm:"-"`
  38. Priority int
  39. AssigneeID int64 `xorm:"-"`
  40. Assignee *User `xorm:"-"`
  41. IsClosed bool `xorm:"INDEX"`
  42. IsRead bool `xorm:"-"`
  43. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  44. PullRequest *PullRequest `xorm:"-"`
  45. NumComments int
  46. Ref string
  47. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  48. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  49. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  50. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  51. Attachments []*Attachment `xorm:"-"`
  52. Comments []*Comment `xorm:"-"`
  53. Reactions ReactionList `xorm:"-"`
  54. TotalTrackedTime int64 `xorm:"-"`
  55. Assignees []*User `xorm:"-"`
  56. // IsLocked limits commenting abilities to users on an issue
  57. // with write access
  58. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  59. }
  60. var (
  61. issueTasksPat *regexp.Regexp
  62. issueTasksDonePat *regexp.Regexp
  63. )
  64. const issueTasksRegexpStr = `(^\s*[-*]\s\[[\sx]\]\s.)|(\n\s*[-*]\s\[[\sx]\]\s.)`
  65. const issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[x]\]\s.)|(\n\s*[-*]\s\[[x]\]\s.)`
  66. const issueMaxDupIndexAttempts = 3
  67. func init() {
  68. issueTasksPat = regexp.MustCompile(issueTasksRegexpStr)
  69. issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr)
  70. }
  71. func (issue *Issue) loadTotalTimes(e Engine) (err error) {
  72. opts := FindTrackedTimesOptions{IssueID: issue.ID}
  73. issue.TotalTrackedTime, err = opts.ToSession(e).SumInt(&TrackedTime{}, "time")
  74. if err != nil {
  75. return err
  76. }
  77. return nil
  78. }
  79. // IsOverdue checks if the issue is overdue
  80. func (issue *Issue) IsOverdue() bool {
  81. return timeutil.TimeStampNow() >= issue.DeadlineUnix
  82. }
  83. // LoadRepo loads issue's repository
  84. func (issue *Issue) LoadRepo() error {
  85. return issue.loadRepo(x)
  86. }
  87. func (issue *Issue) loadRepo(e Engine) (err error) {
  88. if issue.Repo == nil {
  89. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  90. if err != nil {
  91. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  92. }
  93. }
  94. return nil
  95. }
  96. // IsTimetrackerEnabled returns true if the repo enables timetracking
  97. func (issue *Issue) IsTimetrackerEnabled() bool {
  98. return issue.isTimetrackerEnabled(x)
  99. }
  100. func (issue *Issue) isTimetrackerEnabled(e Engine) bool {
  101. if err := issue.loadRepo(e); err != nil {
  102. log.Error(fmt.Sprintf("loadRepo: %v", err))
  103. return false
  104. }
  105. return issue.Repo.IsTimetrackerEnabled()
  106. }
  107. // GetPullRequest returns the issue pull request
  108. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  109. if !issue.IsPull {
  110. return nil, fmt.Errorf("Issue is not a pull request")
  111. }
  112. pr, err = getPullRequestByIssueID(x, issue.ID)
  113. if err != nil {
  114. return nil, err
  115. }
  116. pr.Issue = issue
  117. return
  118. }
  119. func (issue *Issue) loadLabels(e Engine) (err error) {
  120. if issue.Labels == nil {
  121. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  122. if err != nil {
  123. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  124. }
  125. }
  126. return nil
  127. }
  128. // LoadPoster loads poster
  129. func (issue *Issue) LoadPoster() error {
  130. return issue.loadPoster(x)
  131. }
  132. func (issue *Issue) loadPoster(e Engine) (err error) {
  133. if issue.Poster == nil {
  134. issue.Poster, err = getUserByID(e, issue.PosterID)
  135. if err != nil {
  136. issue.PosterID = -1
  137. issue.Poster = NewGhostUser()
  138. if !IsErrUserNotExist(err) {
  139. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  140. }
  141. err = nil
  142. return
  143. }
  144. }
  145. return
  146. }
  147. func (issue *Issue) loadPullRequest(e Engine) (err error) {
  148. if issue.IsPull && issue.PullRequest == nil {
  149. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  150. if err != nil {
  151. if IsErrPullRequestNotExist(err) {
  152. return err
  153. }
  154. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  155. }
  156. issue.PullRequest.Issue = issue
  157. }
  158. return nil
  159. }
  160. // LoadPullRequest loads pull request info
  161. func (issue *Issue) LoadPullRequest() error {
  162. return issue.loadPullRequest(x)
  163. }
  164. func (issue *Issue) loadComments(e Engine) (err error) {
  165. return issue.loadCommentsByType(e, CommentTypeUnknown)
  166. }
  167. // LoadDiscussComments loads discuss comments
  168. func (issue *Issue) LoadDiscussComments() error {
  169. return issue.loadCommentsByType(x, CommentTypeComment)
  170. }
  171. func (issue *Issue) loadCommentsByType(e Engine, tp CommentType) (err error) {
  172. if issue.Comments != nil {
  173. return nil
  174. }
  175. issue.Comments, err = findComments(e, FindCommentsOptions{
  176. IssueID: issue.ID,
  177. Type: tp,
  178. })
  179. return err
  180. }
  181. func (issue *Issue) loadReactions(e Engine) (err error) {
  182. if issue.Reactions != nil {
  183. return nil
  184. }
  185. reactions, err := findReactions(e, FindReactionsOptions{
  186. IssueID: issue.ID,
  187. })
  188. if err != nil {
  189. return err
  190. }
  191. // Load reaction user data
  192. if _, err := ReactionList(reactions).loadUsers(e); err != nil {
  193. return err
  194. }
  195. // Cache comments to map
  196. comments := make(map[int64]*Comment)
  197. for _, comment := range issue.Comments {
  198. comments[comment.ID] = comment
  199. }
  200. // Add reactions either to issue or comment
  201. for _, react := range reactions {
  202. if react.CommentID == 0 {
  203. issue.Reactions = append(issue.Reactions, react)
  204. } else if comment, ok := comments[react.CommentID]; ok {
  205. comment.Reactions = append(comment.Reactions, react)
  206. }
  207. }
  208. return nil
  209. }
  210. func (issue *Issue) loadAttributes(e Engine) (err error) {
  211. if err = issue.loadRepo(e); err != nil {
  212. return
  213. }
  214. if err = issue.loadPoster(e); err != nil {
  215. return
  216. }
  217. if err = issue.loadLabels(e); err != nil {
  218. return
  219. }
  220. if issue.Milestone == nil && issue.MilestoneID > 0 {
  221. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  222. if err != nil && !IsErrMilestoneNotExist(err) {
  223. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  224. }
  225. }
  226. if err = issue.loadAssignees(e); err != nil {
  227. return
  228. }
  229. if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) {
  230. // It is possible pull request is not yet created.
  231. return err
  232. }
  233. if issue.Attachments == nil {
  234. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  235. if err != nil {
  236. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  237. }
  238. }
  239. if err = issue.loadComments(e); err != nil {
  240. return err
  241. }
  242. if err = CommentList(issue.Comments).loadAttributes(e); err != nil {
  243. return err
  244. }
  245. if issue.isTimetrackerEnabled(e) {
  246. if err = issue.loadTotalTimes(e); err != nil {
  247. return err
  248. }
  249. }
  250. return issue.loadReactions(e)
  251. }
  252. // LoadAttributes loads the attribute of this issue.
  253. func (issue *Issue) LoadAttributes() error {
  254. return issue.loadAttributes(x)
  255. }
  256. // GetIsRead load the `IsRead` field of the issue
  257. func (issue *Issue) GetIsRead(userID int64) error {
  258. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  259. if has, err := x.Get(issueUser); err != nil {
  260. return err
  261. } else if !has {
  262. issue.IsRead = false
  263. return nil
  264. }
  265. issue.IsRead = issueUser.IsRead
  266. return nil
  267. }
  268. // APIURL returns the absolute APIURL to this issue.
  269. func (issue *Issue) APIURL() string {
  270. return issue.Repo.APIURL() + "/" + path.Join("issues", fmt.Sprint(issue.Index))
  271. }
  272. // HTMLURL returns the absolute URL to this issue.
  273. func (issue *Issue) HTMLURL() string {
  274. var path string
  275. if issue.IsPull {
  276. path = "pulls"
  277. } else {
  278. path = "issues"
  279. }
  280. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  281. }
  282. // DiffURL returns the absolute URL to this diff
  283. func (issue *Issue) DiffURL() string {
  284. if issue.IsPull {
  285. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  286. }
  287. return ""
  288. }
  289. // PatchURL returns the absolute URL to this patch
  290. func (issue *Issue) PatchURL() string {
  291. if issue.IsPull {
  292. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  293. }
  294. return ""
  295. }
  296. // State returns string representation of issue status.
  297. func (issue *Issue) State() api.StateType {
  298. if issue.IsClosed {
  299. return api.StateClosed
  300. }
  301. return api.StateOpen
  302. }
  303. // APIFormat assumes some fields assigned with values:
  304. // Required - Poster, Labels,
  305. // Optional - Milestone, Assignee, PullRequest
  306. func (issue *Issue) APIFormat() *api.Issue {
  307. return issue.apiFormat(x)
  308. }
  309. func (issue *Issue) apiFormat(e Engine) *api.Issue {
  310. issue.loadLabels(e)
  311. apiLabels := make([]*api.Label, len(issue.Labels))
  312. for i := range issue.Labels {
  313. apiLabels[i] = issue.Labels[i].APIFormat()
  314. }
  315. issue.loadPoster(e)
  316. issue.loadRepo(e)
  317. apiIssue := &api.Issue{
  318. ID: issue.ID,
  319. URL: issue.APIURL(),
  320. Index: issue.Index,
  321. Poster: issue.Poster.APIFormat(),
  322. Title: issue.Title,
  323. Body: issue.Content,
  324. Labels: apiLabels,
  325. State: issue.State(),
  326. Comments: issue.NumComments,
  327. Created: issue.CreatedUnix.AsTime(),
  328. Updated: issue.UpdatedUnix.AsTime(),
  329. }
  330. if issue.ClosedUnix != 0 {
  331. apiIssue.Closed = issue.ClosedUnix.AsTimePtr()
  332. }
  333. if issue.Milestone != nil {
  334. apiIssue.Milestone = issue.Milestone.APIFormat()
  335. }
  336. issue.loadAssignees(e)
  337. if len(issue.Assignees) > 0 {
  338. for _, assignee := range issue.Assignees {
  339. apiIssue.Assignees = append(apiIssue.Assignees, assignee.APIFormat())
  340. }
  341. apiIssue.Assignee = issue.Assignees[0].APIFormat() // For compatibility, we're keeping the first assignee as `apiIssue.Assignee`
  342. }
  343. if issue.IsPull {
  344. issue.loadPullRequest(e)
  345. apiIssue.PullRequest = &api.PullRequestMeta{
  346. HasMerged: issue.PullRequest.HasMerged,
  347. }
  348. if issue.PullRequest.HasMerged {
  349. apiIssue.PullRequest.Merged = issue.PullRequest.MergedUnix.AsTimePtr()
  350. }
  351. }
  352. if issue.DeadlineUnix != 0 {
  353. apiIssue.Deadline = issue.DeadlineUnix.AsTimePtr()
  354. }
  355. return apiIssue
  356. }
  357. // HashTag returns unique hash tag for issue.
  358. func (issue *Issue) HashTag() string {
  359. return "issue-" + com.ToStr(issue.ID)
  360. }
  361. // IsPoster returns true if given user by ID is the poster.
  362. func (issue *Issue) IsPoster(uid int64) bool {
  363. return issue.PosterID == uid
  364. }
  365. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  366. return hasIssueLabel(e, issue.ID, labelID)
  367. }
  368. // HasLabel returns true if issue has been labeled by given ID.
  369. func (issue *Issue) HasLabel(labelID int64) bool {
  370. return issue.hasLabel(x, labelID)
  371. }
  372. // ReplyReference returns tokenized address to use for email reply headers
  373. func (issue *Issue) ReplyReference() string {
  374. var path string
  375. if issue.IsPull {
  376. path = "pulls"
  377. } else {
  378. path = "issues"
  379. }
  380. return fmt.Sprintf("%s/%s/%d@%s", issue.Repo.FullName(), path, issue.Index, setting.Domain)
  381. }
  382. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  383. return newIssueLabel(e, issue, label, doer)
  384. }
  385. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  386. return newIssueLabels(e, issue, labels, doer)
  387. }
  388. func (issue *Issue) getLabels(e Engine) (err error) {
  389. if len(issue.Labels) > 0 {
  390. return nil
  391. }
  392. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  393. if err != nil {
  394. return fmt.Errorf("getLabelsByIssueID: %v", err)
  395. }
  396. return nil
  397. }
  398. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  399. return deleteIssueLabel(e, issue, label, doer)
  400. }
  401. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  402. if err = issue.getLabels(e); err != nil {
  403. return fmt.Errorf("getLabels: %v", err)
  404. }
  405. for i := range issue.Labels {
  406. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  407. return fmt.Errorf("removeLabel: %v", err)
  408. }
  409. }
  410. return nil
  411. }
  412. // ClearLabels removes all issue labels as the given user.
  413. // Triggers appropriate WebHooks, if any.
  414. func (issue *Issue) ClearLabels(doer *User) (err error) {
  415. sess := x.NewSession()
  416. defer sess.Close()
  417. if err = sess.Begin(); err != nil {
  418. return err
  419. }
  420. if err := issue.loadRepo(sess); err != nil {
  421. return err
  422. } else if err = issue.loadPullRequest(sess); err != nil {
  423. return err
  424. }
  425. perm, err := getUserRepoPermission(sess, issue.Repo, doer)
  426. if err != nil {
  427. return err
  428. }
  429. if !perm.CanWriteIssuesOrPulls(issue.IsPull) {
  430. return ErrLabelNotExist{}
  431. }
  432. if err = issue.clearLabels(sess, doer); err != nil {
  433. return err
  434. }
  435. if err = sess.Commit(); err != nil {
  436. return fmt.Errorf("Commit: %v", err)
  437. }
  438. return nil
  439. }
  440. type labelSorter []*Label
  441. func (ts labelSorter) Len() int {
  442. return len([]*Label(ts))
  443. }
  444. func (ts labelSorter) Less(i, j int) bool {
  445. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  446. }
  447. func (ts labelSorter) Swap(i, j int) {
  448. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  449. }
  450. // ReplaceLabels removes all current labels and add new labels to the issue.
  451. // Triggers appropriate WebHooks, if any.
  452. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  453. sess := x.NewSession()
  454. defer sess.Close()
  455. if err = sess.Begin(); err != nil {
  456. return err
  457. }
  458. if err = issue.loadLabels(sess); err != nil {
  459. return err
  460. }
  461. sort.Sort(labelSorter(labels))
  462. sort.Sort(labelSorter(issue.Labels))
  463. var toAdd, toRemove []*Label
  464. addIndex, removeIndex := 0, 0
  465. for addIndex < len(labels) && removeIndex < len(issue.Labels) {
  466. addLabel := labels[addIndex]
  467. removeLabel := issue.Labels[removeIndex]
  468. if addLabel.ID == removeLabel.ID {
  469. addIndex++
  470. removeIndex++
  471. } else if addLabel.ID < removeLabel.ID {
  472. toAdd = append(toAdd, addLabel)
  473. addIndex++
  474. } else {
  475. toRemove = append(toRemove, removeLabel)
  476. removeIndex++
  477. }
  478. }
  479. toAdd = append(toAdd, labels[addIndex:]...)
  480. toRemove = append(toRemove, issue.Labels[removeIndex:]...)
  481. if len(toAdd) > 0 {
  482. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  483. return fmt.Errorf("addLabels: %v", err)
  484. }
  485. }
  486. for _, l := range toRemove {
  487. if err = issue.removeLabel(sess, doer, l); err != nil {
  488. return fmt.Errorf("removeLabel: %v", err)
  489. }
  490. }
  491. return sess.Commit()
  492. }
  493. // ReadBy sets issue to be read by given user.
  494. func (issue *Issue) ReadBy(userID int64) error {
  495. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  496. return err
  497. }
  498. return setNotificationStatusReadIfUnread(x, userID, issue.ID)
  499. }
  500. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  501. if _, err := e.ID(issue.ID).Cols(cols...).Update(issue); err != nil {
  502. return err
  503. }
  504. return nil
  505. }
  506. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  507. // Reload the issue
  508. currentIssue, err := getIssueByID(e, issue.ID)
  509. if err != nil {
  510. return err
  511. }
  512. // Nothing should be performed if current status is same as target status
  513. if currentIssue.IsClosed == isClosed {
  514. return nil
  515. }
  516. // Check for open dependencies
  517. if isClosed && issue.Repo.isDependenciesEnabled(e) {
  518. // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies
  519. noDeps, err := issueNoDependenciesLeft(e, issue)
  520. if err != nil {
  521. return err
  522. }
  523. if !noDeps {
  524. return ErrDependenciesLeft{issue.ID}
  525. }
  526. }
  527. issue.IsClosed = isClosed
  528. if isClosed {
  529. issue.ClosedUnix = timeutil.TimeStampNow()
  530. } else {
  531. issue.ClosedUnix = 0
  532. }
  533. if err = updateIssueCols(e, issue, "is_closed", "closed_unix"); err != nil {
  534. return err
  535. }
  536. // Update issue count of labels
  537. if err = issue.getLabels(e); err != nil {
  538. return err
  539. }
  540. for idx := range issue.Labels {
  541. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  542. return err
  543. }
  544. }
  545. // Update issue count of milestone
  546. if err := updateMilestoneClosedNum(e, issue.MilestoneID); err != nil {
  547. return err
  548. }
  549. // New action comment
  550. if _, err = createStatusComment(e, doer, issue); err != nil {
  551. return err
  552. }
  553. return nil
  554. }
  555. // ChangeStatus changes issue status to open or closed.
  556. func (issue *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  557. sess := x.NewSession()
  558. defer sess.Close()
  559. if err = sess.Begin(); err != nil {
  560. return err
  561. }
  562. if err = issue.loadRepo(sess); err != nil {
  563. return err
  564. }
  565. if err = issue.loadPoster(sess); err != nil {
  566. return err
  567. }
  568. if err = issue.changeStatus(sess, doer, isClosed); err != nil {
  569. return err
  570. }
  571. if err = sess.Commit(); err != nil {
  572. return fmt.Errorf("Commit: %v", err)
  573. }
  574. return nil
  575. }
  576. // ChangeTitle changes the title of this issue, as the given user.
  577. func (issue *Issue) ChangeTitle(doer *User, oldTitle string) (err error) {
  578. sess := x.NewSession()
  579. defer sess.Close()
  580. if err = sess.Begin(); err != nil {
  581. return err
  582. }
  583. if err = updateIssueCols(sess, issue, "name"); err != nil {
  584. return fmt.Errorf("updateIssueCols: %v", err)
  585. }
  586. if err = issue.loadRepo(sess); err != nil {
  587. return fmt.Errorf("loadRepo: %v", err)
  588. }
  589. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, issue.Title); err != nil {
  590. return fmt.Errorf("createChangeTitleComment: %v", err)
  591. }
  592. if err = issue.neuterCrossReferences(sess); err != nil {
  593. return err
  594. }
  595. if err = issue.addCrossReferences(sess, doer); err != nil {
  596. return err
  597. }
  598. return sess.Commit()
  599. }
  600. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  601. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  602. issue, err := getIssueByID(x, issueID)
  603. if err != nil {
  604. return err
  605. }
  606. sess := x.NewSession()
  607. defer sess.Close()
  608. if err := sess.Begin(); err != nil {
  609. return err
  610. }
  611. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  612. return err
  613. }
  614. return sess.Commit()
  615. }
  616. // UpdateAttachments update attachments by UUIDs for the issue
  617. func (issue *Issue) UpdateAttachments(uuids []string) (err error) {
  618. sess := x.NewSession()
  619. defer sess.Close()
  620. if err = sess.Begin(); err != nil {
  621. return err
  622. }
  623. attachments, err := getAttachmentsByUUIDs(sess, uuids)
  624. if err != nil {
  625. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err)
  626. }
  627. for i := 0; i < len(attachments); i++ {
  628. attachments[i].IssueID = issue.ID
  629. if err := updateAttachment(sess, attachments[i]); err != nil {
  630. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  631. }
  632. }
  633. return sess.Commit()
  634. }
  635. // ChangeContent changes issue content, as the given user.
  636. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  637. oldContent := issue.Content
  638. issue.Content = content
  639. sess := x.NewSession()
  640. defer sess.Close()
  641. if err = sess.Begin(); err != nil {
  642. return err
  643. }
  644. if err = updateIssueCols(sess, issue, "content"); err != nil {
  645. return fmt.Errorf("UpdateIssueCols: %v", err)
  646. }
  647. if err = issue.neuterCrossReferences(sess); err != nil {
  648. return err
  649. }
  650. if err = issue.addCrossReferences(sess, doer); err != nil {
  651. return err
  652. }
  653. if err = sess.Commit(); err != nil {
  654. return err
  655. }
  656. sess.Close()
  657. mode, _ := AccessLevel(issue.Poster, issue.Repo)
  658. if issue.IsPull {
  659. issue.PullRequest.Issue = issue
  660. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  661. Action: api.HookIssueEdited,
  662. Index: issue.Index,
  663. Changes: &api.ChangesPayload{
  664. Body: &api.ChangesFromPayload{
  665. From: oldContent,
  666. },
  667. },
  668. PullRequest: issue.PullRequest.APIFormat(),
  669. Repository: issue.Repo.APIFormat(mode),
  670. Sender: doer.APIFormat(),
  671. })
  672. } else {
  673. err = PrepareWebhooks(issue.Repo, HookEventIssues, &api.IssuePayload{
  674. Action: api.HookIssueEdited,
  675. Index: issue.Index,
  676. Changes: &api.ChangesPayload{
  677. Body: &api.ChangesFromPayload{
  678. From: oldContent,
  679. },
  680. },
  681. Issue: issue.APIFormat(),
  682. Repository: issue.Repo.APIFormat(mode),
  683. Sender: doer.APIFormat(),
  684. })
  685. }
  686. if err != nil {
  687. log.Error("PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  688. } else {
  689. go HookQueue.Add(issue.RepoID)
  690. }
  691. return nil
  692. }
  693. // GetTasks returns the amount of tasks in the issues content
  694. func (issue *Issue) GetTasks() int {
  695. return len(issueTasksPat.FindAllStringIndex(issue.Content, -1))
  696. }
  697. // GetTasksDone returns the amount of completed tasks in the issues content
  698. func (issue *Issue) GetTasksDone() int {
  699. return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1))
  700. }
  701. // GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close.
  702. func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp {
  703. if issue.IsClosed {
  704. return issue.ClosedUnix
  705. }
  706. return issue.CreatedUnix
  707. }
  708. // GetLastEventLabel returns the localization label for the current issue.
  709. func (issue *Issue) GetLastEventLabel() string {
  710. if issue.IsClosed {
  711. if issue.IsPull && issue.PullRequest.HasMerged {
  712. return "repo.pulls.merged_by"
  713. }
  714. return "repo.issues.closed_by"
  715. }
  716. return "repo.issues.opened_by"
  717. }
  718. // GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username.
  719. func (issue *Issue) GetLastEventLabelFake() string {
  720. if issue.IsClosed {
  721. if issue.IsPull && issue.PullRequest.HasMerged {
  722. return "repo.pulls.merged_by_fake"
  723. }
  724. return "repo.issues.closed_by_fake"
  725. }
  726. return "repo.issues.opened_by_fake"
  727. }
  728. // NewIssueOptions represents the options of a new issue.
  729. type NewIssueOptions struct {
  730. Repo *Repository
  731. Issue *Issue
  732. LabelIDs []int64
  733. Attachments []string // In UUID format.
  734. IsPull bool
  735. }
  736. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  737. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  738. if opts.Issue.MilestoneID > 0 {
  739. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  740. if err != nil && !IsErrMilestoneNotExist(err) {
  741. return fmt.Errorf("getMilestoneByID: %v", err)
  742. }
  743. // Assume milestone is invalid and drop silently.
  744. opts.Issue.MilestoneID = 0
  745. if milestone != nil {
  746. opts.Issue.MilestoneID = milestone.ID
  747. opts.Issue.Milestone = milestone
  748. }
  749. }
  750. // Milestone validation should happen before insert actual object.
  751. if _, err := e.SetExpr("`index`", "coalesce(MAX(`index`),0)+1").
  752. Where("repo_id=?", opts.Issue.RepoID).
  753. Insert(opts.Issue); err != nil {
  754. return ErrNewIssueInsert{err}
  755. }
  756. inserted, err := getIssueByID(e, opts.Issue.ID)
  757. if err != nil {
  758. return err
  759. }
  760. // Patch Index with the value calculated by the database
  761. opts.Issue.Index = inserted.Index
  762. if opts.Issue.MilestoneID > 0 {
  763. if _, err = e.Exec("UPDATE `milestone` SET num_issues=num_issues+1 WHERE id=?", opts.Issue.MilestoneID); err != nil {
  764. return err
  765. }
  766. if _, err = createMilestoneComment(e, doer, opts.Repo, opts.Issue, 0, opts.Issue.MilestoneID); err != nil {
  767. return err
  768. }
  769. }
  770. if opts.IsPull {
  771. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  772. } else {
  773. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  774. }
  775. if err != nil {
  776. return err
  777. }
  778. if len(opts.LabelIDs) > 0 {
  779. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  780. // So we have to get all needed labels first.
  781. labels := make([]*Label, 0, len(opts.LabelIDs))
  782. if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil {
  783. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err)
  784. }
  785. if err = opts.Issue.loadPoster(e); err != nil {
  786. return err
  787. }
  788. for _, label := range labels {
  789. // Silently drop invalid labels.
  790. if label.RepoID != opts.Repo.ID {
  791. continue
  792. }
  793. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  794. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  795. }
  796. }
  797. }
  798. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  799. return err
  800. }
  801. if len(opts.Attachments) > 0 {
  802. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  803. if err != nil {
  804. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  805. }
  806. for i := 0; i < len(attachments); i++ {
  807. attachments[i].IssueID = opts.Issue.ID
  808. if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil {
  809. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  810. }
  811. }
  812. }
  813. if err = opts.Issue.loadAttributes(e); err != nil {
  814. return err
  815. }
  816. return opts.Issue.addCrossReferences(e, doer)
  817. }
  818. // NewIssue creates new issue with labels for repository.
  819. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  820. // Retry several times in case INSERT fails due to duplicate key for (repo_id, index); see #7887
  821. i := 0
  822. for {
  823. if err = newIssueAttempt(repo, issue, labelIDs, uuids); err == nil {
  824. return nil
  825. }
  826. if !IsErrNewIssueInsert(err) {
  827. return err
  828. }
  829. if i++; i == issueMaxDupIndexAttempts {
  830. break
  831. }
  832. log.Error("NewIssue: error attempting to insert the new issue; will retry. Original error: %v", err)
  833. }
  834. return fmt.Errorf("NewIssue: too many errors attempting to insert the new issue. Last error was: %v", err)
  835. }
  836. func newIssueAttempt(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  837. sess := x.NewSession()
  838. defer sess.Close()
  839. if err = sess.Begin(); err != nil {
  840. return err
  841. }
  842. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  843. Repo: repo,
  844. Issue: issue,
  845. LabelIDs: labelIDs,
  846. Attachments: uuids,
  847. }); err != nil {
  848. if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) {
  849. return err
  850. }
  851. return fmt.Errorf("newIssue: %v", err)
  852. }
  853. if err = sess.Commit(); err != nil {
  854. return fmt.Errorf("Commit: %v", err)
  855. }
  856. return nil
  857. }
  858. // GetIssueByIndex returns raw issue without loading attributes by index in a repository.
  859. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  860. issue := &Issue{
  861. RepoID: repoID,
  862. Index: index,
  863. }
  864. has, err := x.Get(issue)
  865. if err != nil {
  866. return nil, err
  867. } else if !has {
  868. return nil, ErrIssueNotExist{0, repoID, index}
  869. }
  870. return issue, nil
  871. }
  872. // GetIssueWithAttrsByIndex returns issue by index in a repository.
  873. func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) {
  874. issue, err := GetIssueByIndex(repoID, index)
  875. if err != nil {
  876. return nil, err
  877. }
  878. return issue, issue.LoadAttributes()
  879. }
  880. func getIssueByID(e Engine, id int64) (*Issue, error) {
  881. issue := new(Issue)
  882. has, err := e.ID(id).Get(issue)
  883. if err != nil {
  884. return nil, err
  885. } else if !has {
  886. return nil, ErrIssueNotExist{id, 0, 0}
  887. }
  888. return issue, nil
  889. }
  890. // GetIssueWithAttrsByID returns an issue with attributes by given ID.
  891. func GetIssueWithAttrsByID(id int64) (*Issue, error) {
  892. issue, err := getIssueByID(x, id)
  893. if err != nil {
  894. return nil, err
  895. }
  896. return issue, issue.loadAttributes(x)
  897. }
  898. // GetIssueByID returns an issue by given ID.
  899. func GetIssueByID(id int64) (*Issue, error) {
  900. return getIssueByID(x, id)
  901. }
  902. func getIssuesByIDs(e Engine, issueIDs []int64) ([]*Issue, error) {
  903. issues := make([]*Issue, 0, 10)
  904. return issues, e.In("id", issueIDs).Find(&issues)
  905. }
  906. func getIssueIDsByRepoID(e Engine, repoID int64) ([]int64, error) {
  907. var ids = make([]int64, 0, 10)
  908. err := e.Table("issue").Where("repo_id = ?", repoID).Find(&ids)
  909. return ids, err
  910. }
  911. // GetIssueIDsByRepoID returns all issue ids by repo id
  912. func GetIssueIDsByRepoID(repoID int64) ([]int64, error) {
  913. return getIssueIDsByRepoID(x, repoID)
  914. }
  915. // GetIssuesByIDs return issues with the given IDs.
  916. func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) {
  917. return getIssuesByIDs(x, issueIDs)
  918. }
  919. // IssuesOptions represents options of an issue.
  920. type IssuesOptions struct {
  921. RepoIDs []int64 // include all repos if empty
  922. AssigneeID int64
  923. PosterID int64
  924. MentionedID int64
  925. MilestoneID int64
  926. Page int
  927. PageSize int
  928. IsClosed util.OptionalBool
  929. IsPull util.OptionalBool
  930. LabelIDs []int64
  931. SortType string
  932. IssueIDs []int64
  933. }
  934. // sortIssuesSession sort an issues-related session based on the provided
  935. // sortType string
  936. func sortIssuesSession(sess *xorm.Session, sortType string) {
  937. switch sortType {
  938. case "oldest":
  939. sess.Asc("issue.created_unix")
  940. case "recentupdate":
  941. sess.Desc("issue.updated_unix")
  942. case "leastupdate":
  943. sess.Asc("issue.updated_unix")
  944. case "mostcomment":
  945. sess.Desc("issue.num_comments")
  946. case "leastcomment":
  947. sess.Asc("issue.num_comments")
  948. case "priority":
  949. sess.Desc("issue.priority")
  950. case "nearduedate":
  951. sess.Asc("issue.deadline_unix")
  952. case "farduedate":
  953. sess.Desc("issue.deadline_unix")
  954. default:
  955. sess.Desc("issue.created_unix")
  956. }
  957. }
  958. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  959. if opts.Page >= 0 && opts.PageSize > 0 {
  960. var start int
  961. if opts.Page == 0 {
  962. start = 0
  963. } else {
  964. start = (opts.Page - 1) * opts.PageSize
  965. }
  966. sess.Limit(opts.PageSize, start)
  967. }
  968. if len(opts.IssueIDs) > 0 {
  969. sess.In("issue.id", opts.IssueIDs)
  970. }
  971. if len(opts.RepoIDs) > 0 {
  972. // In case repository IDs are provided but actually no repository has issue.
  973. sess.In("issue.repo_id", opts.RepoIDs)
  974. }
  975. switch opts.IsClosed {
  976. case util.OptionalBoolTrue:
  977. sess.And("issue.is_closed=?", true)
  978. case util.OptionalBoolFalse:
  979. sess.And("issue.is_closed=?", false)
  980. }
  981. if opts.AssigneeID > 0 {
  982. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  983. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  984. }
  985. if opts.PosterID > 0 {
  986. sess.And("issue.poster_id=?", opts.PosterID)
  987. }
  988. if opts.MentionedID > 0 {
  989. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  990. And("issue_user.is_mentioned = ?", true).
  991. And("issue_user.uid = ?", opts.MentionedID)
  992. }
  993. if opts.MilestoneID > 0 {
  994. sess.And("issue.milestone_id=?", opts.MilestoneID)
  995. }
  996. switch opts.IsPull {
  997. case util.OptionalBoolTrue:
  998. sess.And("issue.is_pull=?", true)
  999. case util.OptionalBoolFalse:
  1000. sess.And("issue.is_pull=?", false)
  1001. }
  1002. if opts.LabelIDs != nil {
  1003. for i, labelID := range opts.LabelIDs {
  1004. if labelID > 0 {
  1005. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1006. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1007. } else {
  1008. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1009. }
  1010. }
  1011. }
  1012. }
  1013. // CountIssuesByRepo map from repoID to number of issues matching the options
  1014. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1015. sess := x.NewSession()
  1016. defer sess.Close()
  1017. opts.setupSession(sess)
  1018. countsSlice := make([]*struct {
  1019. RepoID int64
  1020. Count int64
  1021. }, 0, 10)
  1022. if err := sess.GroupBy("issue.repo_id").
  1023. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1024. Table("issue").
  1025. Find(&countsSlice); err != nil {
  1026. return nil, err
  1027. }
  1028. countMap := make(map[int64]int64, len(countsSlice))
  1029. for _, c := range countsSlice {
  1030. countMap[c.RepoID] = c.Count
  1031. }
  1032. return countMap, nil
  1033. }
  1034. // Issues returns a list of issues by given conditions.
  1035. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1036. sess := x.NewSession()
  1037. defer sess.Close()
  1038. opts.setupSession(sess)
  1039. sortIssuesSession(sess, opts.SortType)
  1040. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  1041. if err := sess.Find(&issues); err != nil {
  1042. return nil, fmt.Errorf("Find: %v", err)
  1043. }
  1044. sess.Close()
  1045. if err := IssueList(issues).LoadAttributes(); err != nil {
  1046. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1047. }
  1048. return issues, nil
  1049. }
  1050. // GetParticipantsByIssueID returns all users who are participated in comments of an issue.
  1051. func GetParticipantsByIssueID(issueID int64) ([]*User, error) {
  1052. return getParticipantsByIssueID(x, issueID)
  1053. }
  1054. func getParticipantsByIssueID(e Engine, issueID int64) ([]*User, error) {
  1055. userIDs := make([]int64, 0, 5)
  1056. if err := e.Table("comment").Cols("poster_id").
  1057. Where("`comment`.issue_id = ?", issueID).
  1058. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1059. And("`user`.is_active = ?", true).
  1060. And("`user`.prohibit_login = ?", false).
  1061. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1062. Distinct("poster_id").
  1063. Find(&userIDs); err != nil {
  1064. return nil, fmt.Errorf("get poster IDs: %v", err)
  1065. }
  1066. if len(userIDs) == 0 {
  1067. return nil, nil
  1068. }
  1069. users := make([]*User, 0, len(userIDs))
  1070. return users, e.In("id", userIDs).Find(&users)
  1071. }
  1072. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1073. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1074. if len(mentions) == 0 {
  1075. return nil
  1076. }
  1077. ids := make([]int64, len(mentions))
  1078. for i, u := range mentions {
  1079. ids[i] = u.ID
  1080. }
  1081. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1082. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1083. }
  1084. return nil
  1085. }
  1086. // IssueStats represents issue statistic information.
  1087. type IssueStats struct {
  1088. OpenCount, ClosedCount int64
  1089. YourRepositoriesCount int64
  1090. AssignCount int64
  1091. CreateCount int64
  1092. MentionCount int64
  1093. }
  1094. // Filter modes.
  1095. const (
  1096. FilterModeAll = iota
  1097. FilterModeAssign
  1098. FilterModeCreate
  1099. FilterModeMention
  1100. )
  1101. func parseCountResult(results []map[string][]byte) int64 {
  1102. if len(results) == 0 {
  1103. return 0
  1104. }
  1105. for _, result := range results[0] {
  1106. return com.StrTo(string(result)).MustInt64()
  1107. }
  1108. return 0
  1109. }
  1110. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1111. type IssueStatsOptions struct {
  1112. RepoID int64
  1113. Labels string
  1114. MilestoneID int64
  1115. AssigneeID int64
  1116. MentionedID int64
  1117. PosterID int64
  1118. IsPull util.OptionalBool
  1119. IssueIDs []int64
  1120. }
  1121. // GetIssueStats returns issue statistic information by given conditions.
  1122. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1123. stats := &IssueStats{}
  1124. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1125. sess := x.
  1126. Where("issue.repo_id = ?", opts.RepoID)
  1127. if len(opts.IssueIDs) > 0 {
  1128. sess.In("issue.id", opts.IssueIDs)
  1129. }
  1130. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1131. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1132. if err != nil {
  1133. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1134. } else {
  1135. for i, labelID := range labelIDs {
  1136. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1137. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1138. }
  1139. }
  1140. }
  1141. if opts.MilestoneID > 0 {
  1142. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1143. }
  1144. if opts.AssigneeID > 0 {
  1145. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1146. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1147. }
  1148. if opts.PosterID > 0 {
  1149. sess.And("issue.poster_id = ?", opts.PosterID)
  1150. }
  1151. if opts.MentionedID > 0 {
  1152. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1153. And("issue_user.uid = ?", opts.MentionedID).
  1154. And("issue_user.is_mentioned = ?", true)
  1155. }
  1156. switch opts.IsPull {
  1157. case util.OptionalBoolTrue:
  1158. sess.And("issue.is_pull=?", true)
  1159. case util.OptionalBoolFalse:
  1160. sess.And("issue.is_pull=?", false)
  1161. }
  1162. return sess
  1163. }
  1164. var err error
  1165. stats.OpenCount, err = countSession(opts).
  1166. And("issue.is_closed = ?", false).
  1167. Count(new(Issue))
  1168. if err != nil {
  1169. return stats, err
  1170. }
  1171. stats.ClosedCount, err = countSession(opts).
  1172. And("issue.is_closed = ?", true).
  1173. Count(new(Issue))
  1174. return stats, err
  1175. }
  1176. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1177. type UserIssueStatsOptions struct {
  1178. UserID int64
  1179. RepoID int64
  1180. UserRepoIDs []int64
  1181. FilterMode int
  1182. IsPull bool
  1183. IsClosed bool
  1184. }
  1185. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1186. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1187. var err error
  1188. stats := &IssueStats{}
  1189. cond := builder.NewCond()
  1190. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1191. if opts.RepoID > 0 {
  1192. cond = cond.And(builder.Eq{"issue.repo_id": opts.RepoID})
  1193. }
  1194. switch opts.FilterMode {
  1195. case FilterModeAll:
  1196. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1197. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1198. Count(new(Issue))
  1199. if err != nil {
  1200. return nil, err
  1201. }
  1202. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1203. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1204. Count(new(Issue))
  1205. if err != nil {
  1206. return nil, err
  1207. }
  1208. case FilterModeAssign:
  1209. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1210. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1211. And("issue_assignees.assignee_id = ?", opts.UserID).
  1212. Count(new(Issue))
  1213. if err != nil {
  1214. return nil, err
  1215. }
  1216. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1217. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1218. And("issue_assignees.assignee_id = ?", opts.UserID).
  1219. Count(new(Issue))
  1220. if err != nil {
  1221. return nil, err
  1222. }
  1223. case FilterModeCreate:
  1224. stats.OpenCount, err = x.Where(cond).And("is_closed = ?", false).
  1225. And("poster_id = ?", opts.UserID).
  1226. Count(new(Issue))
  1227. if err != nil {
  1228. return nil, err
  1229. }
  1230. stats.ClosedCount, err = x.Where(cond).And("is_closed = ?", true).
  1231. And("poster_id = ?", opts.UserID).
  1232. Count(new(Issue))
  1233. if err != nil {
  1234. return nil, err
  1235. }
  1236. case FilterModeMention:
  1237. stats.OpenCount, err = x.Where(cond).And("issue.is_closed = ?", false).
  1238. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1239. And("issue_user.uid = ?", opts.UserID).
  1240. Count(new(Issue))
  1241. if err != nil {
  1242. return nil, err
  1243. }
  1244. stats.ClosedCount, err = x.Where(cond).And("issue.is_closed = ?", true).
  1245. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1246. And("issue_user.uid = ?", opts.UserID).
  1247. Count(new(Issue))
  1248. if err != nil {
  1249. return nil, err
  1250. }
  1251. }
  1252. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1253. stats.AssignCount, err = x.Where(cond).
  1254. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1255. And("issue_assignees.assignee_id = ?", opts.UserID).
  1256. Count(new(Issue))
  1257. if err != nil {
  1258. return nil, err
  1259. }
  1260. stats.CreateCount, err = x.Where(cond).
  1261. And("poster_id = ?", opts.UserID).
  1262. Count(new(Issue))
  1263. if err != nil {
  1264. return nil, err
  1265. }
  1266. stats.MentionCount, err = x.Where(cond).
  1267. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1268. And("issue_user.uid = ?", opts.UserID).
  1269. Count(new(Issue))
  1270. if err != nil {
  1271. return nil, err
  1272. }
  1273. stats.YourRepositoriesCount, err = x.Where(cond).
  1274. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1275. Count(new(Issue))
  1276. if err != nil {
  1277. return nil, err
  1278. }
  1279. return stats, nil
  1280. }
  1281. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1282. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1283. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1284. sess := x.
  1285. Where("is_closed = ?", isClosed).
  1286. And("is_pull = ?", isPull).
  1287. And("repo_id = ?", repoID)
  1288. return sess
  1289. }
  1290. openCountSession := countSession(false, isPull, repoID)
  1291. closedCountSession := countSession(true, isPull, repoID)
  1292. switch filterMode {
  1293. case FilterModeAssign:
  1294. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1295. And("issue_assignees.assignee_id = ?", uid)
  1296. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1297. And("issue_assignees.assignee_id = ?", uid)
  1298. case FilterModeCreate:
  1299. openCountSession.And("poster_id = ?", uid)
  1300. closedCountSession.And("poster_id = ?", uid)
  1301. }
  1302. openResult, _ := openCountSession.Count(new(Issue))
  1303. closedResult, _ := closedCountSession.Count(new(Issue))
  1304. return openResult, closedResult
  1305. }
  1306. // SearchIssueIDsByKeyword search issues on database
  1307. func SearchIssueIDsByKeyword(kw string, repoID int64, limit, start int) (int64, []int64, error) {
  1308. var repoCond = builder.Eq{"repo_id": repoID}
  1309. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1310. var cond = builder.And(
  1311. repoCond,
  1312. builder.Or(
  1313. builder.Like{"name", kw},
  1314. builder.Like{"content", kw},
  1315. builder.In("id", builder.Select("issue_id").
  1316. From("comment").
  1317. Where(builder.And(
  1318. builder.Eq{"type": CommentTypeComment},
  1319. builder.In("issue_id", subQuery),
  1320. builder.Like{"content", kw},
  1321. )),
  1322. ),
  1323. ),
  1324. )
  1325. var ids = make([]int64, 0, limit)
  1326. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1327. if err != nil {
  1328. return 0, nil, err
  1329. }
  1330. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1331. if err != nil {
  1332. return 0, nil, err
  1333. }
  1334. return total, ids, nil
  1335. }
  1336. func updateIssue(e Engine, issue *Issue) error {
  1337. _, err := e.ID(issue.ID).AllCols().Update(issue)
  1338. if err != nil {
  1339. return err
  1340. }
  1341. return nil
  1342. }
  1343. // UpdateIssue updates all fields of given issue.
  1344. func UpdateIssue(issue *Issue) error {
  1345. sess := x.NewSession()
  1346. defer sess.Close()
  1347. if err := sess.Begin(); err != nil {
  1348. return err
  1349. }
  1350. if err := updateIssue(sess, issue); err != nil {
  1351. return err
  1352. }
  1353. if err := issue.neuterCrossReferences(sess); err != nil {
  1354. return err
  1355. }
  1356. if err := issue.loadPoster(sess); err != nil {
  1357. return err
  1358. }
  1359. if err := issue.addCrossReferences(sess, issue.Poster); err != nil {
  1360. return err
  1361. }
  1362. return sess.Commit()
  1363. }
  1364. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1365. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1366. // if the deadline hasn't changed do nothing
  1367. if issue.DeadlineUnix == deadlineUnix {
  1368. return nil
  1369. }
  1370. sess := x.NewSession()
  1371. defer sess.Close()
  1372. if err := sess.Begin(); err != nil {
  1373. return err
  1374. }
  1375. // Update the deadline
  1376. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1377. return err
  1378. }
  1379. // Make the comment
  1380. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1381. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1382. }
  1383. return sess.Commit()
  1384. }
  1385. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1386. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*Issue, err error) {
  1387. return issueDeps, e.
  1388. Table("issue_dependency").
  1389. Select("issue.*").
  1390. Join("INNER", "issue", "issue.id = issue_dependency.dependency_id").
  1391. Where("issue_id = ?", issue.ID).
  1392. Find(&issueDeps)
  1393. }
  1394. // Get Blocking Dependencies, aka all issues this issue blocks.
  1395. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*Issue, err error) {
  1396. return issueDeps, e.
  1397. Table("issue_dependency").
  1398. Select("issue.*").
  1399. Join("INNER", "issue", "issue.id = issue_dependency.issue_id").
  1400. Where("dependency_id = ?", issue.ID).
  1401. Find(&issueDeps)
  1402. }
  1403. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1404. func (issue *Issue) BlockedByDependencies() ([]*Issue, error) {
  1405. return issue.getBlockedByDependencies(x)
  1406. }
  1407. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1408. func (issue *Issue) BlockingDependencies() ([]*Issue, error) {
  1409. return issue.getBlockingDependencies(x)
  1410. }
  1411. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1412. if issue.IsPull {
  1413. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1414. issue.RepoID,
  1415. true,
  1416. true,
  1417. issue.RepoID,
  1418. )
  1419. } else {
  1420. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1421. issue.RepoID,
  1422. false,
  1423. true,
  1424. issue.RepoID,
  1425. )
  1426. }
  1427. return
  1428. }
  1429. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1430. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1431. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1432. if len(mentions) == 0 {
  1433. return
  1434. }
  1435. if err = issue.loadRepo(ctx.e); err != nil {
  1436. return
  1437. }
  1438. resolved := make(map[string]bool, 20)
  1439. names := make([]string, 0, 20)
  1440. resolved[doer.LowerName] = true
  1441. for _, name := range mentions {
  1442. name := strings.ToLower(name)
  1443. if _, ok := resolved[name]; ok {
  1444. continue
  1445. }
  1446. resolved[name] = false
  1447. names = append(names, name)
  1448. }
  1449. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1450. return nil, err
  1451. }
  1452. if issue.Repo.Owner.IsOrganization() {
  1453. // Since there can be users with names that match the name of a team,
  1454. // if the team exists and can read the issue, the team takes precedence.
  1455. teams := make([]*Team, 0, len(names))
  1456. if err := ctx.e.
  1457. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1458. Where("team_repo.repo_id=?", issue.Repo.ID).
  1459. In("team.lower_name", names).
  1460. Find(&teams); err != nil {
  1461. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1462. }
  1463. if len(teams) != 0 {
  1464. checked := make([]int64, 0, len(teams))
  1465. unittype := UnitTypeIssues
  1466. if issue.IsPull {
  1467. unittype = UnitTypePullRequests
  1468. }
  1469. for _, team := range teams {
  1470. if team.Authorize >= AccessModeOwner {
  1471. checked = append(checked, team.ID)
  1472. resolved[team.LowerName] = true
  1473. continue
  1474. }
  1475. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1476. if err != nil {
  1477. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1478. }
  1479. if has {
  1480. checked = append(checked, team.ID)
  1481. resolved[team.LowerName] = true
  1482. }
  1483. }
  1484. if len(checked) != 0 {
  1485. teamusers := make([]*User, 0, 20)
  1486. if err := ctx.e.
  1487. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1488. In("`team_user`.team_id", checked).
  1489. And("`user`.is_active = ?", true).
  1490. And("`user`.prohibit_login = ?", false).
  1491. Find(&teamusers); err != nil {
  1492. return nil, fmt.Errorf("get teams users: %v", err)
  1493. }
  1494. if len(teamusers) > 0 {
  1495. users = make([]*User, 0, len(teamusers))
  1496. for _, user := range teamusers {
  1497. if already, ok := resolved[user.LowerName]; !ok || !already {
  1498. users = append(users, user)
  1499. resolved[user.LowerName] = true
  1500. }
  1501. }
  1502. }
  1503. }
  1504. }
  1505. // Remove names already in the list to avoid querying the database if pending names remain
  1506. names = make([]string, 0, len(resolved))
  1507. for name, already := range resolved {
  1508. if !already {
  1509. names = append(names, name)
  1510. }
  1511. }
  1512. if len(names) == 0 {
  1513. return
  1514. }
  1515. }
  1516. unchecked := make([]*User, 0, len(names))
  1517. if err := ctx.e.
  1518. Where("`user`.is_active = ?", true).
  1519. And("`user`.prohibit_login = ?", false).
  1520. In("`user`.lower_name", names).
  1521. Find(&unchecked); err != nil {
  1522. return nil, fmt.Errorf("find mentioned users: %v", err)
  1523. }
  1524. for _, user := range unchecked {
  1525. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1526. continue
  1527. }
  1528. // Normal users must have read access to the referencing issue
  1529. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1530. if err != nil {
  1531. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1532. }
  1533. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1534. continue
  1535. }
  1536. users = append(users, user)
  1537. }
  1538. return
  1539. }
  1540. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1541. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1542. _, err := x.Table("issue").
  1543. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1544. And("original_author_id = ?", originalAuthorID).
  1545. Update(map[string]interface{}{
  1546. "poster_id": posterID,
  1547. "original_author": "",
  1548. "original_author_id": 0,
  1549. })
  1550. return err
  1551. }
上海开阖软件有限公司 沪ICP备12045867号-1