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.

1368 lines
35 KiB

10 years ago
10 years ago
10 years ago
10 years ago
8 years ago
10 years ago
10 years ago
10 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
8 years ago
10 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  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. "errors"
  7. "fmt"
  8. "sort"
  9. "strings"
  10. "time"
  11. api "code.gitea.io/sdk/gitea"
  12. "github.com/Unknwon/com"
  13. "github.com/go-xorm/xorm"
  14. "code.gitea.io/gitea/modules/base"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "code.gitea.io/gitea/modules/util"
  18. )
  19. var (
  20. errMissingIssueNumber = errors.New("No issue number specified")
  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. Title string `xorm:"name"`
  31. Content string `xorm:"TEXT"`
  32. RenderedContent string `xorm:"-"`
  33. Labels []*Label `xorm:"-"`
  34. MilestoneID int64 `xorm:"INDEX"`
  35. Milestone *Milestone `xorm:"-"`
  36. Priority int
  37. AssigneeID int64 `xorm:"INDEX"`
  38. Assignee *User `xorm:"-"`
  39. IsClosed bool `xorm:"INDEX"`
  40. IsRead bool `xorm:"-"`
  41. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  42. PullRequest *PullRequest `xorm:"-"`
  43. NumComments int
  44. Deadline time.Time `xorm:"-"`
  45. DeadlineUnix int64 `xorm:"INDEX"`
  46. Created time.Time `xorm:"-"`
  47. CreatedUnix int64 `xorm:"INDEX"`
  48. Updated time.Time `xorm:"-"`
  49. UpdatedUnix int64 `xorm:"INDEX"`
  50. Attachments []*Attachment `xorm:"-"`
  51. Comments []*Comment `xorm:"-"`
  52. }
  53. // BeforeInsert is invoked from XORM before inserting an object of this type.
  54. func (issue *Issue) BeforeInsert() {
  55. issue.CreatedUnix = time.Now().Unix()
  56. issue.UpdatedUnix = issue.CreatedUnix
  57. }
  58. // BeforeUpdate is invoked from XORM before updating this object.
  59. func (issue *Issue) BeforeUpdate() {
  60. issue.UpdatedUnix = time.Now().Unix()
  61. issue.DeadlineUnix = issue.Deadline.Unix()
  62. }
  63. // AfterSet is invoked from XORM after setting the value of a field of
  64. // this object.
  65. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  66. switch colName {
  67. case "deadline_unix":
  68. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  69. case "created_unix":
  70. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  71. case "updated_unix":
  72. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  73. }
  74. }
  75. func (issue *Issue) loadRepo(e Engine) (err error) {
  76. if issue.Repo == nil {
  77. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  78. if err != nil {
  79. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  80. }
  81. }
  82. return nil
  83. }
  84. // GetPullRequest returns the issue pull request
  85. func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) {
  86. if !issue.IsPull {
  87. return nil, fmt.Errorf("Issue is not a pull request")
  88. }
  89. pr, err = getPullRequestByIssueID(x, issue.ID)
  90. return
  91. }
  92. func (issue *Issue) loadLabels(e Engine) (err error) {
  93. if issue.Labels == nil {
  94. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  95. if err != nil {
  96. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  97. }
  98. }
  99. return nil
  100. }
  101. func (issue *Issue) loadPoster(e Engine) (err error) {
  102. if issue.Poster == nil {
  103. issue.Poster, err = getUserByID(e, issue.PosterID)
  104. if err != nil {
  105. issue.PosterID = -1
  106. issue.Poster = NewGhostUser()
  107. if !IsErrUserNotExist(err) {
  108. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  109. }
  110. err = nil
  111. return
  112. }
  113. }
  114. return
  115. }
  116. func (issue *Issue) loadAttributes(e Engine) (err error) {
  117. if err = issue.loadRepo(e); err != nil {
  118. return
  119. }
  120. if err = issue.loadPoster(e); err != nil {
  121. return
  122. }
  123. if err = issue.loadLabels(e); err != nil {
  124. return
  125. }
  126. if issue.Milestone == nil && issue.MilestoneID > 0 {
  127. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  128. if err != nil {
  129. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  130. }
  131. }
  132. if issue.Assignee == nil && issue.AssigneeID > 0 {
  133. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  134. if err != nil {
  135. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  136. }
  137. }
  138. if issue.IsPull && issue.PullRequest == nil {
  139. // It is possible pull request is not yet created.
  140. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  141. if err != nil && !IsErrPullRequestNotExist(err) {
  142. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  143. }
  144. }
  145. if issue.Attachments == nil {
  146. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  147. if err != nil {
  148. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  149. }
  150. }
  151. if issue.Comments == nil {
  152. issue.Comments, err = getCommentsByIssueID(e, issue.ID)
  153. if err != nil {
  154. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  155. }
  156. }
  157. return nil
  158. }
  159. // LoadAttributes loads the attribute of this issue.
  160. func (issue *Issue) LoadAttributes() error {
  161. return issue.loadAttributes(x)
  162. }
  163. // GetIsRead load the `IsRead` field of the issue
  164. func (issue *Issue) GetIsRead(userID int64) error {
  165. issueUser := &IssueUser{IssueID: issue.ID, UID: userID}
  166. if has, err := x.Get(issueUser); err != nil {
  167. return err
  168. } else if !has {
  169. issue.IsRead = false
  170. return nil
  171. }
  172. issue.IsRead = issueUser.IsRead
  173. return nil
  174. }
  175. // HTMLURL returns the absolute URL to this issue.
  176. func (issue *Issue) HTMLURL() string {
  177. var path string
  178. if issue.IsPull {
  179. path = "pulls"
  180. } else {
  181. path = "issues"
  182. }
  183. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  184. }
  185. // DiffURL returns the absolute URL to this diff
  186. func (issue *Issue) DiffURL() string {
  187. if issue.IsPull {
  188. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  189. }
  190. return ""
  191. }
  192. // PatchURL returns the absolute URL to this patch
  193. func (issue *Issue) PatchURL() string {
  194. if issue.IsPull {
  195. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  196. }
  197. return ""
  198. }
  199. // State returns string representation of issue status.
  200. func (issue *Issue) State() api.StateType {
  201. if issue.IsClosed {
  202. return api.StateClosed
  203. }
  204. return api.StateOpen
  205. }
  206. // APIFormat assumes some fields assigned with values:
  207. // Required - Poster, Labels,
  208. // Optional - Milestone, Assignee, PullRequest
  209. func (issue *Issue) APIFormat() *api.Issue {
  210. apiLabels := make([]*api.Label, len(issue.Labels))
  211. for i := range issue.Labels {
  212. apiLabels[i] = issue.Labels[i].APIFormat()
  213. }
  214. apiIssue := &api.Issue{
  215. ID: issue.ID,
  216. Index: issue.Index,
  217. Poster: issue.Poster.APIFormat(),
  218. Title: issue.Title,
  219. Body: issue.Content,
  220. Labels: apiLabels,
  221. State: issue.State(),
  222. Comments: issue.NumComments,
  223. Created: issue.Created,
  224. Updated: issue.Updated,
  225. }
  226. if issue.Milestone != nil {
  227. apiIssue.Milestone = issue.Milestone.APIFormat()
  228. }
  229. if issue.Assignee != nil {
  230. apiIssue.Assignee = issue.Assignee.APIFormat()
  231. }
  232. if issue.IsPull {
  233. apiIssue.PullRequest = &api.PullRequestMeta{
  234. HasMerged: issue.PullRequest.HasMerged,
  235. }
  236. if issue.PullRequest.HasMerged {
  237. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  238. }
  239. }
  240. return apiIssue
  241. }
  242. // HashTag returns unique hash tag for issue.
  243. func (issue *Issue) HashTag() string {
  244. return "issue-" + com.ToStr(issue.ID)
  245. }
  246. // IsPoster returns true if given user by ID is the poster.
  247. func (issue *Issue) IsPoster(uid int64) bool {
  248. return issue.PosterID == uid
  249. }
  250. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  251. return hasIssueLabel(e, issue.ID, labelID)
  252. }
  253. // HasLabel returns true if issue has been labeled by given ID.
  254. func (issue *Issue) HasLabel(labelID int64) bool {
  255. return issue.hasLabel(x, labelID)
  256. }
  257. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  258. var err error
  259. if issue.IsPull {
  260. err = issue.PullRequest.LoadIssue()
  261. if err != nil {
  262. log.Error(4, "LoadIssue: %v", err)
  263. return
  264. }
  265. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  266. Action: api.HookIssueLabelUpdated,
  267. Index: issue.Index,
  268. PullRequest: issue.PullRequest.APIFormat(),
  269. Repository: issue.Repo.APIFormat(AccessModeNone),
  270. Sender: doer.APIFormat(),
  271. })
  272. }
  273. if err != nil {
  274. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  275. } else {
  276. go HookQueue.Add(issue.RepoID)
  277. }
  278. }
  279. func (issue *Issue) addLabel(e *xorm.Session, label *Label, doer *User) error {
  280. return newIssueLabel(e, issue, label, doer)
  281. }
  282. // AddLabel adds a new label to the issue.
  283. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  284. if err := NewIssueLabel(issue, label, doer); err != nil {
  285. return err
  286. }
  287. issue.sendLabelUpdatedWebhook(doer)
  288. return nil
  289. }
  290. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label, doer *User) error {
  291. return newIssueLabels(e, issue, labels, doer)
  292. }
  293. // AddLabels adds a list of new labels to the issue.
  294. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  295. if err := NewIssueLabels(issue, labels, doer); err != nil {
  296. return err
  297. }
  298. issue.sendLabelUpdatedWebhook(doer)
  299. return nil
  300. }
  301. func (issue *Issue) getLabels(e Engine) (err error) {
  302. if len(issue.Labels) > 0 {
  303. return nil
  304. }
  305. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  306. if err != nil {
  307. return fmt.Errorf("getLabelsByIssueID: %v", err)
  308. }
  309. return nil
  310. }
  311. func (issue *Issue) removeLabel(e *xorm.Session, doer *User, label *Label) error {
  312. return deleteIssueLabel(e, issue, label, doer)
  313. }
  314. // RemoveLabel removes a label from issue by given ID.
  315. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  316. if err := issue.loadRepo(x); err != nil {
  317. return err
  318. }
  319. if has, err := HasAccess(doer, issue.Repo, AccessModeWrite); err != nil {
  320. return err
  321. } else if !has {
  322. return ErrLabelNotExist{}
  323. }
  324. if err := DeleteIssueLabel(issue, label, doer); err != nil {
  325. return err
  326. }
  327. issue.sendLabelUpdatedWebhook(doer)
  328. return nil
  329. }
  330. func (issue *Issue) clearLabels(e *xorm.Session, doer *User) (err error) {
  331. if err = issue.getLabels(e); err != nil {
  332. return fmt.Errorf("getLabels: %v", err)
  333. }
  334. for i := range issue.Labels {
  335. if err = issue.removeLabel(e, doer, issue.Labels[i]); err != nil {
  336. return fmt.Errorf("removeLabel: %v", err)
  337. }
  338. }
  339. return nil
  340. }
  341. // ClearLabels removes all issue labels as the given user.
  342. // Triggers appropriate WebHooks, if any.
  343. func (issue *Issue) ClearLabels(doer *User) (err error) {
  344. sess := x.NewSession()
  345. defer sessionRelease(sess)
  346. if err = sess.Begin(); err != nil {
  347. return err
  348. }
  349. if err := issue.loadRepo(sess); err != nil {
  350. return err
  351. }
  352. if has, err := hasAccess(sess, doer, issue.Repo, AccessModeWrite); err != nil {
  353. return err
  354. } else if !has {
  355. return ErrLabelNotExist{}
  356. }
  357. if err = issue.clearLabels(sess, doer); err != nil {
  358. return err
  359. }
  360. if err = sess.Commit(); err != nil {
  361. return fmt.Errorf("Commit: %v", err)
  362. }
  363. if issue.IsPull {
  364. err = issue.PullRequest.LoadIssue()
  365. if err != nil {
  366. log.Error(4, "LoadIssue: %v", err)
  367. return
  368. }
  369. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  370. Action: api.HookIssueLabelCleared,
  371. Index: issue.Index,
  372. PullRequest: issue.PullRequest.APIFormat(),
  373. Repository: issue.Repo.APIFormat(AccessModeNone),
  374. Sender: doer.APIFormat(),
  375. })
  376. }
  377. if err != nil {
  378. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  379. } else {
  380. go HookQueue.Add(issue.RepoID)
  381. }
  382. return nil
  383. }
  384. type labelSorter []*Label
  385. func (ts labelSorter) Len() int {
  386. return len([]*Label(ts))
  387. }
  388. func (ts labelSorter) Less(i, j int) bool {
  389. return []*Label(ts)[i].ID < []*Label(ts)[j].ID
  390. }
  391. func (ts labelSorter) Swap(i, j int) {
  392. []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i]
  393. }
  394. // ReplaceLabels removes all current labels and add new labels to the issue.
  395. // Triggers appropriate WebHooks, if any.
  396. func (issue *Issue) ReplaceLabels(labels []*Label, doer *User) (err error) {
  397. sess := x.NewSession()
  398. defer sessionRelease(sess)
  399. if err = sess.Begin(); err != nil {
  400. return err
  401. }
  402. if err = issue.loadLabels(sess); err != nil {
  403. return err
  404. }
  405. sort.Sort(labelSorter(labels))
  406. sort.Sort(labelSorter(issue.Labels))
  407. var toAdd, toRemove []*Label
  408. for _, l := range labels {
  409. var exist bool
  410. for _, oriLabel := range issue.Labels {
  411. if oriLabel.ID == l.ID {
  412. exist = true
  413. break
  414. }
  415. }
  416. if !exist {
  417. toAdd = append(toAdd, l)
  418. }
  419. }
  420. for _, oriLabel := range issue.Labels {
  421. var exist bool
  422. for _, l := range labels {
  423. if oriLabel.ID == l.ID {
  424. exist = true
  425. break
  426. }
  427. }
  428. if !exist {
  429. toRemove = append(toRemove, oriLabel)
  430. }
  431. }
  432. if len(toAdd) > 0 {
  433. if err = issue.addLabels(sess, toAdd, doer); err != nil {
  434. return fmt.Errorf("addLabels: %v", err)
  435. }
  436. }
  437. if len(toRemove) > 0 {
  438. for _, l := range toRemove {
  439. if err = issue.removeLabel(sess, doer, l); err != nil {
  440. return fmt.Errorf("removeLabel: %v", err)
  441. }
  442. }
  443. }
  444. return sess.Commit()
  445. }
  446. // GetAssignee sets the Assignee attribute of this issue.
  447. func (issue *Issue) GetAssignee() (err error) {
  448. if issue.AssigneeID == 0 || issue.Assignee != nil {
  449. return nil
  450. }
  451. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  452. if IsErrUserNotExist(err) {
  453. return nil
  454. }
  455. return err
  456. }
  457. // ReadBy sets issue to be read by given user.
  458. func (issue *Issue) ReadBy(userID int64) error {
  459. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  460. return err
  461. }
  462. if err := setNotificationStatusReadIfUnread(x, userID, issue.ID); err != nil {
  463. return err
  464. }
  465. return nil
  466. }
  467. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  468. if _, err := e.Id(issue.ID).Cols(cols...).Update(issue); err != nil {
  469. return err
  470. }
  471. UpdateIssueIndexer(issue)
  472. return nil
  473. }
  474. // UpdateIssueCols only updates values of specific columns for given issue.
  475. func UpdateIssueCols(issue *Issue, cols ...string) error {
  476. return updateIssueCols(x, issue, cols...)
  477. }
  478. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  479. // Nothing should be performed if current status is same as target status
  480. if issue.IsClosed == isClosed {
  481. return nil
  482. }
  483. issue.IsClosed = isClosed
  484. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  485. return err
  486. }
  487. // Update issue count of labels
  488. if err = issue.getLabels(e); err != nil {
  489. return err
  490. }
  491. for idx := range issue.Labels {
  492. if issue.IsClosed {
  493. issue.Labels[idx].NumClosedIssues++
  494. } else {
  495. issue.Labels[idx].NumClosedIssues--
  496. }
  497. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  498. return err
  499. }
  500. }
  501. // Update issue count of milestone
  502. if err = changeMilestoneIssueStats(e, issue); err != nil {
  503. return err
  504. }
  505. // New action comment
  506. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  507. return err
  508. }
  509. return nil
  510. }
  511. // ChangeStatus changes issue status to open or closed.
  512. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  513. sess := x.NewSession()
  514. defer sessionRelease(sess)
  515. if err = sess.Begin(); err != nil {
  516. return err
  517. }
  518. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  519. return err
  520. }
  521. if err = sess.Commit(); err != nil {
  522. return fmt.Errorf("Commit: %v", err)
  523. }
  524. if issue.IsPull {
  525. // Merge pull request calls issue.changeStatus so we need to handle separately.
  526. issue.PullRequest.Issue = issue
  527. apiPullRequest := &api.PullRequestPayload{
  528. Index: issue.Index,
  529. PullRequest: issue.PullRequest.APIFormat(),
  530. Repository: repo.APIFormat(AccessModeNone),
  531. Sender: doer.APIFormat(),
  532. }
  533. if isClosed {
  534. apiPullRequest.Action = api.HookIssueClosed
  535. } else {
  536. apiPullRequest.Action = api.HookIssueReOpened
  537. }
  538. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  539. }
  540. if err != nil {
  541. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  542. } else {
  543. go HookQueue.Add(repo.ID)
  544. }
  545. return nil
  546. }
  547. // ChangeTitle changes the title of this issue, as the given user.
  548. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  549. oldTitle := issue.Title
  550. issue.Title = title
  551. sess := x.NewSession()
  552. defer sess.Close()
  553. if err = sess.Begin(); err != nil {
  554. return err
  555. }
  556. if err = updateIssueCols(sess, issue, "name"); err != nil {
  557. return fmt.Errorf("updateIssueCols: %v", err)
  558. }
  559. if _, err = createChangeTitleComment(sess, doer, issue.Repo, issue, oldTitle, title); err != nil {
  560. return fmt.Errorf("createChangeTitleComment: %v", err)
  561. }
  562. if err = sess.Commit(); err != nil {
  563. return err
  564. }
  565. if issue.IsPull {
  566. issue.PullRequest.Issue = issue
  567. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  568. Action: api.HookIssueEdited,
  569. Index: issue.Index,
  570. Changes: &api.ChangesPayload{
  571. Title: &api.ChangesFromPayload{
  572. From: oldTitle,
  573. },
  574. },
  575. PullRequest: issue.PullRequest.APIFormat(),
  576. Repository: issue.Repo.APIFormat(AccessModeNone),
  577. Sender: doer.APIFormat(),
  578. })
  579. }
  580. if err != nil {
  581. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  582. } else {
  583. go HookQueue.Add(issue.RepoID)
  584. }
  585. return nil
  586. }
  587. // AddDeletePRBranchComment adds delete branch comment for pull request issue
  588. func AddDeletePRBranchComment(doer *User, repo *Repository, issueID int64, branchName string) error {
  589. issue, err := getIssueByID(x, issueID)
  590. if err != nil {
  591. return err
  592. }
  593. sess := x.NewSession()
  594. defer sess.Close()
  595. if err := sess.Begin(); err != nil {
  596. return err
  597. }
  598. if _, err := createDeleteBranchComment(sess, doer, repo, issue, branchName); err != nil {
  599. return err
  600. }
  601. return sess.Commit()
  602. }
  603. // ChangeContent changes issue content, as the given user.
  604. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  605. oldContent := issue.Content
  606. issue.Content = content
  607. if err = UpdateIssueCols(issue, "content"); err != nil {
  608. return fmt.Errorf("UpdateIssueCols: %v", err)
  609. }
  610. if issue.IsPull {
  611. issue.PullRequest.Issue = issue
  612. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  613. Action: api.HookIssueEdited,
  614. Index: issue.Index,
  615. Changes: &api.ChangesPayload{
  616. Body: &api.ChangesFromPayload{
  617. From: oldContent,
  618. },
  619. },
  620. PullRequest: issue.PullRequest.APIFormat(),
  621. Repository: issue.Repo.APIFormat(AccessModeNone),
  622. Sender: doer.APIFormat(),
  623. })
  624. }
  625. if err != nil {
  626. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  627. } else {
  628. go HookQueue.Add(issue.RepoID)
  629. }
  630. return nil
  631. }
  632. // ChangeAssignee changes the Asssignee field of this issue.
  633. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  634. var oldAssigneeID = issue.AssigneeID
  635. issue.AssigneeID = assigneeID
  636. if err = UpdateIssueUserByAssignee(issue); err != nil {
  637. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  638. }
  639. sess := x.NewSession()
  640. defer sess.Close()
  641. if err = issue.loadRepo(sess); err != nil {
  642. return fmt.Errorf("loadRepo: %v", err)
  643. }
  644. if _, err = createAssigneeComment(sess, doer, issue.Repo, issue, oldAssigneeID, assigneeID); err != nil {
  645. return fmt.Errorf("createAssigneeComment: %v", err)
  646. }
  647. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  648. if err != nil && !IsErrUserNotExist(err) {
  649. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  650. return nil
  651. }
  652. // Error not nil here means user does not exist, which is remove assignee.
  653. isRemoveAssignee := err != nil
  654. if issue.IsPull {
  655. issue.PullRequest.Issue = issue
  656. apiPullRequest := &api.PullRequestPayload{
  657. Index: issue.Index,
  658. PullRequest: issue.PullRequest.APIFormat(),
  659. Repository: issue.Repo.APIFormat(AccessModeNone),
  660. Sender: doer.APIFormat(),
  661. }
  662. if isRemoveAssignee {
  663. apiPullRequest.Action = api.HookIssueUnassigned
  664. } else {
  665. apiPullRequest.Action = api.HookIssueAssigned
  666. }
  667. if err := PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest); err != nil {
  668. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  669. return nil
  670. }
  671. }
  672. go HookQueue.Add(issue.RepoID)
  673. return nil
  674. }
  675. // NewIssueOptions represents the options of a new issue.
  676. type NewIssueOptions struct {
  677. Repo *Repository
  678. Issue *Issue
  679. LableIDs []int64
  680. Attachments []string // In UUID format.
  681. IsPull bool
  682. }
  683. func newIssue(e *xorm.Session, doer *User, opts NewIssueOptions) (err error) {
  684. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  685. opts.Issue.Index = opts.Repo.NextIssueIndex()
  686. if opts.Issue.MilestoneID > 0 {
  687. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  688. if err != nil && !IsErrMilestoneNotExist(err) {
  689. return fmt.Errorf("getMilestoneByID: %v", err)
  690. }
  691. // Assume milestone is invalid and drop silently.
  692. opts.Issue.MilestoneID = 0
  693. if milestone != nil {
  694. opts.Issue.MilestoneID = milestone.ID
  695. opts.Issue.Milestone = milestone
  696. }
  697. }
  698. if opts.Issue.AssigneeID > 0 {
  699. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  700. if err != nil && !IsErrUserNotExist(err) {
  701. return fmt.Errorf("getUserByID: %v", err)
  702. }
  703. // Assume assignee is invalid and drop silently.
  704. opts.Issue.AssigneeID = 0
  705. if assignee != nil {
  706. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  707. if err != nil {
  708. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  709. }
  710. if valid {
  711. opts.Issue.AssigneeID = assignee.ID
  712. opts.Issue.Assignee = assignee
  713. }
  714. }
  715. }
  716. // Milestone and assignee validation should happen before insert actual object.
  717. if _, err = e.Insert(opts.Issue); err != nil {
  718. return err
  719. }
  720. if opts.Issue.MilestoneID > 0 {
  721. if err = changeMilestoneAssign(e, doer, opts.Issue, -1); err != nil {
  722. return err
  723. }
  724. }
  725. if opts.Issue.AssigneeID > 0 {
  726. if err = opts.Issue.loadRepo(e); err != nil {
  727. return err
  728. }
  729. if _, err = createAssigneeComment(e, doer, opts.Issue.Repo, opts.Issue, -1, opts.Issue.AssigneeID); err != nil {
  730. return err
  731. }
  732. }
  733. if opts.IsPull {
  734. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  735. } else {
  736. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  737. }
  738. if err != nil {
  739. return err
  740. }
  741. if len(opts.LableIDs) > 0 {
  742. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  743. // So we have to get all needed labels first.
  744. labels := make([]*Label, 0, len(opts.LableIDs))
  745. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  746. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  747. }
  748. if err = opts.Issue.loadPoster(e); err != nil {
  749. return err
  750. }
  751. for _, label := range labels {
  752. // Silently drop invalid labels.
  753. if label.RepoID != opts.Repo.ID {
  754. continue
  755. }
  756. if err = opts.Issue.addLabel(e, label, opts.Issue.Poster); err != nil {
  757. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  758. }
  759. }
  760. }
  761. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  762. return err
  763. }
  764. UpdateIssueIndexer(opts.Issue)
  765. if len(opts.Attachments) > 0 {
  766. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  767. if err != nil {
  768. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  769. }
  770. for i := 0; i < len(attachments); i++ {
  771. attachments[i].IssueID = opts.Issue.ID
  772. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  773. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  774. }
  775. }
  776. }
  777. return opts.Issue.loadAttributes(e)
  778. }
  779. // NewIssue creates new issue with labels for repository.
  780. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  781. sess := x.NewSession()
  782. defer sessionRelease(sess)
  783. if err = sess.Begin(); err != nil {
  784. return err
  785. }
  786. if err = newIssue(sess, issue.Poster, NewIssueOptions{
  787. Repo: repo,
  788. Issue: issue,
  789. LableIDs: labelIDs,
  790. Attachments: uuids,
  791. }); err != nil {
  792. return fmt.Errorf("newIssue: %v", err)
  793. }
  794. if err = sess.Commit(); err != nil {
  795. return fmt.Errorf("Commit: %v", err)
  796. }
  797. if err = NotifyWatchers(&Action{
  798. ActUserID: issue.Poster.ID,
  799. ActUserName: issue.Poster.Name,
  800. OpType: ActionCreateIssue,
  801. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  802. RepoID: repo.ID,
  803. RepoUserName: repo.Owner.Name,
  804. RepoName: repo.Name,
  805. IsPrivate: repo.IsPrivate,
  806. }); err != nil {
  807. log.Error(4, "NotifyWatchers: %v", err)
  808. }
  809. if err = issue.MailParticipants(); err != nil {
  810. log.Error(4, "MailParticipants: %v", err)
  811. }
  812. return nil
  813. }
  814. // GetIssueByRef returns an Issue specified by a GFM reference.
  815. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  816. func GetIssueByRef(ref string) (*Issue, error) {
  817. n := strings.IndexByte(ref, byte('#'))
  818. if n == -1 {
  819. return nil, errMissingIssueNumber
  820. }
  821. index, err := com.StrTo(ref[n+1:]).Int64()
  822. if err != nil {
  823. return nil, err
  824. }
  825. repo, err := GetRepositoryByRef(ref[:n])
  826. if err != nil {
  827. return nil, err
  828. }
  829. issue, err := GetIssueByIndex(repo.ID, index)
  830. if err != nil {
  831. return nil, err
  832. }
  833. return issue, issue.LoadAttributes()
  834. }
  835. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  836. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  837. issue := &Issue{
  838. RepoID: repoID,
  839. Index: index,
  840. }
  841. has, err := x.Get(issue)
  842. if err != nil {
  843. return nil, err
  844. } else if !has {
  845. return nil, ErrIssueNotExist{0, repoID, index}
  846. }
  847. return issue, nil
  848. }
  849. // GetIssueByIndex returns issue by index in a repository.
  850. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  851. issue, err := GetRawIssueByIndex(repoID, index)
  852. if err != nil {
  853. return nil, err
  854. }
  855. return issue, issue.LoadAttributes()
  856. }
  857. func getIssueByID(e Engine, id int64) (*Issue, error) {
  858. issue := new(Issue)
  859. has, err := e.Id(id).Get(issue)
  860. if err != nil {
  861. return nil, err
  862. } else if !has {
  863. return nil, ErrIssueNotExist{id, 0, 0}
  864. }
  865. return issue, issue.LoadAttributes()
  866. }
  867. // GetIssueByID returns an issue by given ID.
  868. func GetIssueByID(id int64) (*Issue, error) {
  869. return getIssueByID(x, id)
  870. }
  871. // IssuesOptions represents options of an issue.
  872. type IssuesOptions struct {
  873. RepoID int64
  874. AssigneeID int64
  875. PosterID int64
  876. MentionedID int64
  877. MilestoneID int64
  878. RepoIDs []int64
  879. Page int
  880. IsClosed util.OptionalBool
  881. IsPull util.OptionalBool
  882. Labels string
  883. SortType string
  884. IssueIDs []int64
  885. }
  886. // sortIssuesSession sort an issues-related session based on the provided
  887. // sortType string
  888. func sortIssuesSession(sess *xorm.Session, sortType string) {
  889. switch sortType {
  890. case "oldest":
  891. sess.Asc("issue.created_unix")
  892. case "recentupdate":
  893. sess.Desc("issue.updated_unix")
  894. case "leastupdate":
  895. sess.Asc("issue.updated_unix")
  896. case "mostcomment":
  897. sess.Desc("issue.num_comments")
  898. case "leastcomment":
  899. sess.Asc("issue.num_comments")
  900. case "priority":
  901. sess.Desc("issue.priority")
  902. default:
  903. sess.Desc("issue.created_unix")
  904. }
  905. }
  906. // Issues returns a list of issues by given conditions.
  907. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  908. var sess *xorm.Session
  909. if opts.Page >= 0 {
  910. var start int
  911. if opts.Page == 0 {
  912. start = 0
  913. } else {
  914. start = (opts.Page - 1) * setting.UI.IssuePagingNum
  915. }
  916. sess = x.Limit(setting.UI.IssuePagingNum, start)
  917. } else {
  918. sess = x.NewSession()
  919. defer sess.Close()
  920. }
  921. if len(opts.IssueIDs) > 0 {
  922. sess.In("issue.id", opts.IssueIDs)
  923. }
  924. if opts.RepoID > 0 {
  925. sess.And("issue.repo_id=?", opts.RepoID)
  926. } else if len(opts.RepoIDs) > 0 {
  927. // In case repository IDs are provided but actually no repository has issue.
  928. sess.In("issue.repo_id", opts.RepoIDs)
  929. }
  930. switch opts.IsClosed {
  931. case util.OptionalBoolTrue:
  932. sess.And("issue.is_closed=?", true)
  933. case util.OptionalBoolFalse:
  934. sess.And("issue.is_closed=?", false)
  935. }
  936. if opts.AssigneeID > 0 {
  937. sess.And("issue.assignee_id=?", opts.AssigneeID)
  938. }
  939. if opts.PosterID > 0 {
  940. sess.And("issue.poster_id=?", opts.PosterID)
  941. }
  942. if opts.MentionedID > 0 {
  943. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  944. And("issue_user.is_mentioned = ?", true).
  945. And("issue_user.uid = ?", opts.MentionedID)
  946. }
  947. if opts.MilestoneID > 0 {
  948. sess.And("issue.milestone_id=?", opts.MilestoneID)
  949. }
  950. switch opts.IsPull {
  951. case util.OptionalBoolTrue:
  952. sess.And("issue.is_pull=?", true)
  953. case util.OptionalBoolFalse:
  954. sess.And("issue.is_pull=?", false)
  955. }
  956. sortIssuesSession(sess, opts.SortType)
  957. if len(opts.Labels) > 0 && opts.Labels != "0" {
  958. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  959. if err != nil {
  960. return nil, err
  961. }
  962. if len(labelIDs) > 0 {
  963. sess.
  964. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  965. In("issue_label.label_id", labelIDs)
  966. }
  967. }
  968. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  969. if err := sess.Find(&issues); err != nil {
  970. return nil, fmt.Errorf("Find: %v", err)
  971. }
  972. // FIXME: use IssueList to improve performance.
  973. for i := range issues {
  974. if err := issues[i].LoadAttributes(); err != nil {
  975. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  976. }
  977. }
  978. return issues, nil
  979. }
  980. // UpdateIssueMentions extracts mentioned people from content and
  981. // updates issue-user relations for them.
  982. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  983. if len(mentions) == 0 {
  984. return nil
  985. }
  986. for i := range mentions {
  987. mentions[i] = strings.ToLower(mentions[i])
  988. }
  989. users := make([]*User, 0, len(mentions))
  990. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  991. return fmt.Errorf("find mentioned users: %v", err)
  992. }
  993. ids := make([]int64, 0, len(mentions))
  994. for _, user := range users {
  995. ids = append(ids, user.ID)
  996. if !user.IsOrganization() || user.NumMembers == 0 {
  997. continue
  998. }
  999. memberIDs := make([]int64, 0, user.NumMembers)
  1000. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  1001. if err != nil {
  1002. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  1003. }
  1004. for _, orgUser := range orgUsers {
  1005. memberIDs = append(memberIDs, orgUser.ID)
  1006. }
  1007. ids = append(ids, memberIDs...)
  1008. }
  1009. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  1010. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1011. }
  1012. return nil
  1013. }
  1014. // IssueStats represents issue statistic information.
  1015. type IssueStats struct {
  1016. OpenCount, ClosedCount int64
  1017. AllCount int64
  1018. AssignCount int64
  1019. CreateCount int64
  1020. MentionCount int64
  1021. }
  1022. // Filter modes.
  1023. const (
  1024. FilterModeAll = iota
  1025. FilterModeAssign
  1026. FilterModeCreate
  1027. FilterModeMention
  1028. )
  1029. func parseCountResult(results []map[string][]byte) int64 {
  1030. if len(results) == 0 {
  1031. return 0
  1032. }
  1033. for _, result := range results[0] {
  1034. return com.StrTo(string(result)).MustInt64()
  1035. }
  1036. return 0
  1037. }
  1038. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1039. type IssueStatsOptions struct {
  1040. RepoID int64
  1041. Labels string
  1042. MilestoneID int64
  1043. AssigneeID int64
  1044. MentionedID int64
  1045. PosterID int64
  1046. IsPull bool
  1047. IssueIDs []int64
  1048. }
  1049. // GetIssueStats returns issue statistic information by given conditions.
  1050. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1051. stats := &IssueStats{}
  1052. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1053. sess := x.
  1054. Where("issue.repo_id = ?", opts.RepoID).
  1055. And("is_pull = ?", opts.IsPull)
  1056. if len(opts.IssueIDs) > 0 {
  1057. sess.In("issue.id", opts.IssueIDs)
  1058. }
  1059. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1060. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1061. if err != nil {
  1062. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1063. } else if len(labelIDs) > 0 {
  1064. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1065. In("label_id", labelIDs)
  1066. }
  1067. }
  1068. if opts.MilestoneID > 0 {
  1069. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1070. }
  1071. if opts.AssigneeID > 0 {
  1072. sess.And("assignee_id = ?", opts.AssigneeID)
  1073. }
  1074. if opts.PosterID > 0 {
  1075. sess.And("poster_id = ?", opts.PosterID)
  1076. }
  1077. if opts.MentionedID > 0 {
  1078. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1079. And("issue_user.uid = ?", opts.MentionedID).
  1080. And("issue_user.is_mentioned = ?", true)
  1081. }
  1082. return sess
  1083. }
  1084. var err error
  1085. stats.OpenCount, err = countSession(opts).
  1086. And("is_closed = ?", false).
  1087. Count(&Issue{})
  1088. if err != nil {
  1089. return nil, err
  1090. }
  1091. stats.ClosedCount, err = countSession(opts).
  1092. And("is_closed = ?", true).
  1093. Count(&Issue{})
  1094. if err != nil {
  1095. return nil, err
  1096. }
  1097. return stats, nil
  1098. }
  1099. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1100. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1101. stats := &IssueStats{}
  1102. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1103. sess := x.
  1104. Where("issue.is_closed = ?", isClosed).
  1105. And("issue.is_pull = ?", isPull)
  1106. if repoID > 0 {
  1107. sess.And("repo_id = ?", repoID)
  1108. } else if len(repoIDs) > 0 {
  1109. sess.In("repo_id", repoIDs)
  1110. }
  1111. return sess
  1112. }
  1113. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1114. And("assignee_id = ?", uid).
  1115. Count(&Issue{})
  1116. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1117. And("poster_id = ?", uid).
  1118. Count(&Issue{})
  1119. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1120. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1121. switch filterMode {
  1122. case FilterModeAssign:
  1123. openCountSession.And("assignee_id = ?", uid)
  1124. closedCountSession.And("assignee_id = ?", uid)
  1125. case FilterModeCreate:
  1126. openCountSession.And("poster_id = ?", uid)
  1127. closedCountSession.And("poster_id = ?", uid)
  1128. }
  1129. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1130. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1131. return stats
  1132. }
  1133. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1134. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1135. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1136. sess := x.
  1137. Where("is_closed = ?", isClosed).
  1138. And("is_pull = ?", isPull).
  1139. And("repo_id = ?", repoID)
  1140. return sess
  1141. }
  1142. openCountSession := countSession(false, isPull, repoID)
  1143. closedCountSession := countSession(true, isPull, repoID)
  1144. switch filterMode {
  1145. case FilterModeAssign:
  1146. openCountSession.And("assignee_id = ?", uid)
  1147. closedCountSession.And("assignee_id = ?", uid)
  1148. case FilterModeCreate:
  1149. openCountSession.And("poster_id = ?", uid)
  1150. closedCountSession.And("poster_id = ?", uid)
  1151. }
  1152. openResult, _ := openCountSession.Count(&Issue{})
  1153. closedResult, _ := closedCountSession.Count(&Issue{})
  1154. return openResult, closedResult
  1155. }
  1156. func updateIssue(e Engine, issue *Issue) error {
  1157. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1158. if err != nil {
  1159. return err
  1160. }
  1161. UpdateIssueIndexer(issue)
  1162. return nil
  1163. }
  1164. // UpdateIssue updates all fields of given issue.
  1165. func UpdateIssue(issue *Issue) error {
  1166. return updateIssue(x, issue)
  1167. }