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.

1800 lines
46 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
9 years ago
9 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. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "mime/multipart"
  11. "os"
  12. "path"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/setting"
  20. gouuid "github.com/gogits/gogs/modules/uuid"
  21. )
  22. var (
  23. ErrWrongIssueCounter = errors.New("Invalid number of issues for this milestone")
  24. ErrAttachmentNotLinked = errors.New("Attachment does not belong to this issue")
  25. ErrMissingIssueNumber = errors.New("No issue number specified")
  26. )
  27. // Issue represents an issue or pull request of repository.
  28. type Issue struct {
  29. ID int64 `xorm:"pk autoincr"`
  30. RepoID int64 `xorm:"INDEX"`
  31. Index int64 // Index in one repository.
  32. Name string
  33. Repo *Repository `xorm:"-"`
  34. PosterID int64
  35. Poster *User `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64
  38. Milestone *Milestone `xorm:"-"`
  39. AssigneeID int64
  40. Assignee *User `xorm:"-"`
  41. IsRead bool `xorm:"-"`
  42. IsPull bool // Indicates whether is a pull request or not.
  43. *PullRequest `xorm:"-"`
  44. IsClosed bool
  45. Content string `xorm:"TEXT"`
  46. RenderedContent string `xorm:"-"`
  47. Priority int
  48. NumComments int
  49. Deadline time.Time
  50. Created time.Time `xorm:"CREATED"`
  51. Updated time.Time `xorm:"UPDATED"`
  52. Attachments []*Attachment `xorm:"-"`
  53. Comments []*Comment `xorm:"-"`
  54. }
  55. func (i *Issue) AfterSet(colName string, _ xorm.Cell) {
  56. var err error
  57. switch colName {
  58. case "id":
  59. i.Attachments, err = GetAttachmentsByIssueID(i.ID)
  60. if err != nil {
  61. log.Error(3, "GetAttachmentsByIssueID[%d]: %v", i.ID, err)
  62. }
  63. i.Comments, err = GetCommentsByIssueID(i.ID)
  64. if err != nil {
  65. log.Error(3, "GetCommentsByIssueID[%d]: %v", i.ID, err)
  66. }
  67. case "milestone_id":
  68. if i.MilestoneID == 0 {
  69. return
  70. }
  71. i.Milestone, err = GetMilestoneByID(i.MilestoneID)
  72. if err != nil {
  73. log.Error(3, "GetMilestoneById[%d]: %v", i.ID, err)
  74. }
  75. case "assignee_id":
  76. if i.AssigneeID == 0 {
  77. return
  78. }
  79. i.Assignee, err = GetUserByID(i.AssigneeID)
  80. if err != nil {
  81. log.Error(3, "GetUserByID[%d]: %v", i.ID, err)
  82. }
  83. case "created":
  84. i.Created = regulateTimeZone(i.Created)
  85. }
  86. }
  87. // HashTag returns unique hash tag for issue.
  88. func (i *Issue) HashTag() string {
  89. return "issue-" + com.ToStr(i.ID)
  90. }
  91. // IsPoster returns true if given user by ID is the poster.
  92. func (i *Issue) IsPoster(uid int64) bool {
  93. return i.PosterID == uid
  94. }
  95. func (i *Issue) GetPoster() (err error) {
  96. i.Poster, err = GetUserByID(i.PosterID)
  97. if IsErrUserNotExist(err) {
  98. i.PosterID = -1
  99. i.Poster = NewFakeUser()
  100. return nil
  101. }
  102. return err
  103. }
  104. func (i *Issue) hasLabel(e Engine, labelID int64) bool {
  105. return hasIssueLabel(e, i.ID, labelID)
  106. }
  107. // HasLabel returns true if issue has been labeled by given ID.
  108. func (i *Issue) HasLabel(labelID int64) bool {
  109. return i.hasLabel(x, labelID)
  110. }
  111. func (i *Issue) addLabel(e *xorm.Session, label *Label) error {
  112. return newIssueLabel(e, i, label)
  113. }
  114. // AddLabel adds new label to issue by given ID.
  115. func (i *Issue) AddLabel(label *Label) (err error) {
  116. sess := x.NewSession()
  117. defer sessionRelease(sess)
  118. if err = sess.Begin(); err != nil {
  119. return err
  120. }
  121. if err = i.addLabel(sess, label); err != nil {
  122. return err
  123. }
  124. return sess.Commit()
  125. }
  126. func (i *Issue) getLabels(e Engine) (err error) {
  127. if len(i.Labels) > 0 {
  128. return nil
  129. }
  130. i.Labels, err = getLabelsByIssueID(e, i.ID)
  131. if err != nil {
  132. return fmt.Errorf("getLabelsByIssueID: %v", err)
  133. }
  134. return nil
  135. }
  136. // GetLabels retrieves all labels of issue and assign to corresponding field.
  137. func (i *Issue) GetLabels() error {
  138. return i.getLabels(x)
  139. }
  140. func (i *Issue) removeLabel(e *xorm.Session, label *Label) error {
  141. return deleteIssueLabel(e, i, label)
  142. }
  143. // RemoveLabel removes a label from issue by given ID.
  144. func (i *Issue) RemoveLabel(label *Label) (err error) {
  145. sess := x.NewSession()
  146. defer sessionRelease(sess)
  147. if err = sess.Begin(); err != nil {
  148. return err
  149. }
  150. if err = i.removeLabel(sess, label); err != nil {
  151. return err
  152. }
  153. return sess.Commit()
  154. }
  155. func (i *Issue) ClearLabels() (err error) {
  156. sess := x.NewSession()
  157. defer sessionRelease(sess)
  158. if err = sess.Begin(); err != nil {
  159. return err
  160. }
  161. if err = i.getLabels(sess); err != nil {
  162. return err
  163. }
  164. for idx := range i.Labels {
  165. if err = i.removeLabel(sess, i.Labels[idx]); err != nil {
  166. return err
  167. }
  168. }
  169. return sess.Commit()
  170. }
  171. func (i *Issue) GetAssignee() (err error) {
  172. if i.AssigneeID == 0 || i.Assignee != nil {
  173. return nil
  174. }
  175. i.Assignee, err = GetUserByID(i.AssigneeID)
  176. if IsErrUserNotExist(err) {
  177. return nil
  178. }
  179. return err
  180. }
  181. // ReadBy sets issue to be read by given user.
  182. func (i *Issue) ReadBy(uid int64) error {
  183. return UpdateIssueUserByRead(uid, i.ID)
  184. }
  185. func (i *Issue) changeStatus(e *xorm.Session, doer *User, isClosed bool) (err error) {
  186. if i.IsClosed == isClosed {
  187. return nil
  188. }
  189. i.IsClosed = isClosed
  190. if err = updateIssueCols(e, i, "is_closed"); err != nil {
  191. return err
  192. } else if err = updateIssueUsersByStatus(e, i.ID, isClosed); err != nil {
  193. return err
  194. }
  195. // Update labels.
  196. if err = i.getLabels(e); err != nil {
  197. return err
  198. }
  199. for idx := range i.Labels {
  200. if i.IsClosed {
  201. i.Labels[idx].NumClosedIssues++
  202. } else {
  203. i.Labels[idx].NumClosedIssues--
  204. }
  205. if err = updateLabel(e, i.Labels[idx]); err != nil {
  206. return err
  207. }
  208. }
  209. // Update milestone.
  210. if err = changeMilestoneIssueStats(e, i); err != nil {
  211. return err
  212. }
  213. // New action comment.
  214. if _, err = createStatusComment(e, doer, i.Repo, i); err != nil {
  215. return err
  216. }
  217. return nil
  218. }
  219. // ChangeStatus changes issue status to open/closed.
  220. func (i *Issue) ChangeStatus(doer *User, isClosed bool) (err error) {
  221. sess := x.NewSession()
  222. defer sessionRelease(sess)
  223. if err = sess.Begin(); err != nil {
  224. return err
  225. }
  226. if err = i.changeStatus(sess, doer, isClosed); err != nil {
  227. return err
  228. }
  229. return sess.Commit()
  230. }
  231. func (i *Issue) GetPullRequest() (err error) {
  232. if i.PullRequest != nil {
  233. return nil
  234. }
  235. i.PullRequest, err = GetPullRequestByIssueID(i.ID)
  236. return err
  237. }
  238. // It's caller's responsibility to create action.
  239. func newIssue(e *xorm.Session, repo *Repository, issue *Issue, labelIDs []int64, uuids []string, isPull bool) (err error) {
  240. if _, err = e.Insert(issue); err != nil {
  241. return err
  242. }
  243. if isPull {
  244. _, err = e.Exec("UPDATE `repository` SET num_pulls=num_pulls+1 WHERE id=?", issue.RepoID)
  245. } else {
  246. _, err = e.Exec("UPDATE `repository` SET num_issues=num_issues+1 WHERE id=?", issue.RepoID)
  247. }
  248. if err != nil {
  249. return err
  250. }
  251. var label *Label
  252. for _, id := range labelIDs {
  253. if id == 0 {
  254. continue
  255. }
  256. label, err = getLabelByID(e, id)
  257. if err != nil {
  258. return err
  259. }
  260. if err = issue.addLabel(e, label); err != nil {
  261. return fmt.Errorf("addLabel: %v", err)
  262. }
  263. }
  264. if issue.MilestoneID > 0 {
  265. if err = changeMilestoneAssign(e, 0, issue); err != nil {
  266. return err
  267. }
  268. }
  269. if err = newIssueUsers(e, repo, issue); err != nil {
  270. return err
  271. }
  272. // Check attachments.
  273. attachments := make([]*Attachment, 0, len(uuids))
  274. for _, uuid := range uuids {
  275. attach, err := getAttachmentByUUID(e, uuid)
  276. if err != nil {
  277. if IsErrAttachmentNotExist(err) {
  278. continue
  279. }
  280. return fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  281. }
  282. attachments = append(attachments, attach)
  283. }
  284. for i := range attachments {
  285. attachments[i].IssueID = issue.ID
  286. // No assign value could be 0, so ignore AllCols().
  287. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  288. return fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  289. }
  290. }
  291. return nil
  292. }
  293. // NewIssue creates new issue with labels for repository.
  294. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  295. sess := x.NewSession()
  296. defer sessionRelease(sess)
  297. if err = sess.Begin(); err != nil {
  298. return err
  299. }
  300. if err = newIssue(sess, repo, issue, labelIDs, uuids, false); err != nil {
  301. return fmt.Errorf("newIssue: %v", err)
  302. }
  303. // Notify watchers.
  304. act := &Action{
  305. ActUserID: issue.Poster.Id,
  306. ActUserName: issue.Poster.Name,
  307. ActEmail: issue.Poster.Email,
  308. OpType: CREATE_ISSUE,
  309. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  310. RepoID: repo.ID,
  311. RepoUserName: repo.Owner.Name,
  312. RepoName: repo.Name,
  313. IsPrivate: repo.IsPrivate,
  314. }
  315. if err = notifyWatchers(sess, act); err != nil {
  316. return err
  317. }
  318. return sess.Commit()
  319. }
  320. // GetIssueByRef returns an Issue specified by a GFM reference.
  321. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  322. func GetIssueByRef(ref string) (*Issue, error) {
  323. n := strings.IndexByte(ref, byte('#'))
  324. if n == -1 {
  325. return nil, ErrMissingIssueNumber
  326. }
  327. index, err := com.StrTo(ref[n+1:]).Int64()
  328. if err != nil {
  329. return nil, err
  330. }
  331. repo, err := GetRepositoryByRef(ref[:n])
  332. if err != nil {
  333. return nil, err
  334. }
  335. issue, err := GetIssueByIndex(repo.ID, index)
  336. if err != nil {
  337. return nil, err
  338. }
  339. issue.Repo = repo
  340. return issue, nil
  341. }
  342. // GetIssueByIndex returns issue by given index in repository.
  343. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  344. issue := &Issue{
  345. RepoID: repoID,
  346. Index: index,
  347. }
  348. has, err := x.Get(issue)
  349. if err != nil {
  350. return nil, err
  351. } else if !has {
  352. return nil, ErrIssueNotExist{0, repoID, index}
  353. }
  354. return issue, nil
  355. }
  356. // GetIssueByID returns an issue by given ID.
  357. func GetIssueByID(id int64) (*Issue, error) {
  358. issue := new(Issue)
  359. has, err := x.Id(id).Get(issue)
  360. if err != nil {
  361. return nil, err
  362. } else if !has {
  363. return nil, ErrIssueNotExist{id, 0, 0}
  364. }
  365. return issue, nil
  366. }
  367. type IssuesOptions struct {
  368. UserID int64
  369. AssigneeID int64
  370. RepoID int64
  371. PosterID int64
  372. MilestoneID int64
  373. RepoIDs []int64
  374. Page int
  375. IsClosed bool
  376. IsMention bool
  377. IsPull bool
  378. Labels string
  379. SortType string
  380. }
  381. // Issues returns a list of issues by given conditions.
  382. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  383. sess := x.Limit(setting.IssuePagingNum, (opts.Page-1)*setting.IssuePagingNum)
  384. if opts.RepoID > 0 {
  385. sess.Where("issue.repo_id=?", opts.RepoID).And("issue.is_closed=?", opts.IsClosed)
  386. } else if opts.RepoIDs != nil {
  387. // In case repository IDs are provided but actually no repository has issue.
  388. if len(opts.RepoIDs) == 0 {
  389. return make([]*Issue, 0), nil
  390. }
  391. sess.Where("issue.repo_id IN ("+strings.Join(base.Int64sToStrings(opts.RepoIDs), ",")+")").And("issue.is_closed=?", opts.IsClosed)
  392. } else {
  393. sess.Where("issue.is_closed=?", opts.IsClosed)
  394. }
  395. if opts.AssigneeID > 0 {
  396. sess.And("issue.assignee_id=?", opts.AssigneeID)
  397. } else if opts.PosterID > 0 {
  398. sess.And("issue.poster_id=?", opts.PosterID)
  399. }
  400. if opts.MilestoneID > 0 {
  401. sess.And("issue.milestone_id=?", opts.MilestoneID)
  402. }
  403. sess.And("issue.is_pull=?", opts.IsPull)
  404. switch opts.SortType {
  405. case "oldest":
  406. sess.Asc("created")
  407. case "recentupdate":
  408. sess.Desc("updated")
  409. case "leastupdate":
  410. sess.Asc("updated")
  411. case "mostcomment":
  412. sess.Desc("num_comments")
  413. case "leastcomment":
  414. sess.Asc("num_comments")
  415. case "priority":
  416. sess.Desc("priority")
  417. default:
  418. sess.Desc("created")
  419. }
  420. labelIDs := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  421. if len(labelIDs) > 0 {
  422. validJoin := false
  423. queryStr := "issue.id=issue_label.issue_id"
  424. for _, id := range labelIDs {
  425. if id == 0 {
  426. continue
  427. }
  428. validJoin = true
  429. queryStr += " AND issue_label.label_id=" + com.ToStr(id)
  430. }
  431. if validJoin {
  432. sess.Join("INNER", "issue_label", queryStr)
  433. }
  434. }
  435. if opts.IsMention {
  436. queryStr := "issue.id=issue_user.issue_id AND issue_user.is_mentioned=1"
  437. if opts.UserID > 0 {
  438. queryStr += " AND issue_user.uid=" + com.ToStr(opts.UserID)
  439. }
  440. sess.Join("INNER", "issue_user", queryStr)
  441. }
  442. issues := make([]*Issue, 0, setting.IssuePagingNum)
  443. return issues, sess.Find(&issues)
  444. }
  445. type IssueStatus int
  446. const (
  447. IS_OPEN = iota + 1
  448. IS_CLOSE
  449. )
  450. // GetIssueCountByPoster returns number of issues of repository by poster.
  451. func GetIssueCountByPoster(uid, rid int64, isClosed bool) int64 {
  452. count, _ := x.Where("repo_id=?", rid).And("poster_id=?", uid).And("is_closed=?", isClosed).Count(new(Issue))
  453. return count
  454. }
  455. // .___ ____ ___
  456. // | | ______ ________ __ ____ | | \______ ___________
  457. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  458. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  459. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  460. // \/ \/ \/ \/ \/
  461. // IssueUser represents an issue-user relation.
  462. type IssueUser struct {
  463. ID int64 `xorm:"pk autoincr"`
  464. UID int64 `xorm:"INDEX"` // User ID.
  465. IssueID int64
  466. RepoID int64 `xorm:"INDEX"`
  467. MilestoneID int64
  468. IsRead bool
  469. IsAssigned bool
  470. IsMentioned bool
  471. IsPoster bool
  472. IsClosed bool
  473. }
  474. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  475. users, err := repo.GetAssignees()
  476. if err != nil {
  477. return err
  478. }
  479. iu := &IssueUser{
  480. IssueID: issue.ID,
  481. RepoID: repo.ID,
  482. }
  483. // Poster can be anyone.
  484. isNeedAddPoster := true
  485. for _, u := range users {
  486. iu.ID = 0
  487. iu.UID = u.Id
  488. iu.IsPoster = iu.UID == issue.PosterID
  489. if isNeedAddPoster && iu.IsPoster {
  490. isNeedAddPoster = false
  491. }
  492. iu.IsAssigned = iu.UID == issue.AssigneeID
  493. if _, err = e.Insert(iu); err != nil {
  494. return err
  495. }
  496. }
  497. if isNeedAddPoster {
  498. iu.ID = 0
  499. iu.UID = issue.PosterID
  500. iu.IsPoster = true
  501. if _, err = e.Insert(iu); err != nil {
  502. return err
  503. }
  504. }
  505. return nil
  506. }
  507. // NewIssueUsers adds new issue-user relations for new issue of repository.
  508. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  509. sess := x.NewSession()
  510. defer sessionRelease(sess)
  511. if err = sess.Begin(); err != nil {
  512. return err
  513. }
  514. if err = newIssueUsers(sess, repo, issue); err != nil {
  515. return err
  516. }
  517. return sess.Commit()
  518. }
  519. // PairsContains returns true when pairs list contains given issue.
  520. func PairsContains(ius []*IssueUser, issueId, uid int64) int {
  521. for i := range ius {
  522. if ius[i].IssueID == issueId &&
  523. ius[i].UID == uid {
  524. return i
  525. }
  526. }
  527. return -1
  528. }
  529. // GetIssueUsers returns issue-user pairs by given repository and user.
  530. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  531. ius := make([]*IssueUser, 0, 10)
  532. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  533. return ius, err
  534. }
  535. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  536. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  537. if len(rids) == 0 {
  538. return []*IssueUser{}, nil
  539. }
  540. buf := bytes.NewBufferString("")
  541. for _, rid := range rids {
  542. buf.WriteString("repo_id=")
  543. buf.WriteString(com.ToStr(rid))
  544. buf.WriteString(" OR ")
  545. }
  546. cond := strings.TrimSuffix(buf.String(), " OR ")
  547. ius := make([]*IssueUser, 0, 10)
  548. sess := x.Limit(20, (page-1)*20).Where("is_closed=?", isClosed)
  549. if len(cond) > 0 {
  550. sess.And(cond)
  551. }
  552. err := sess.Find(&ius)
  553. return ius, err
  554. }
  555. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  556. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  557. ius := make([]*IssueUser, 0, 10)
  558. sess := x.Limit(20, (page-1)*20).Where("uid=?", uid).And("is_closed=?", isClosed)
  559. if rid > 0 {
  560. sess.And("repo_id=?", rid)
  561. }
  562. switch filterMode {
  563. case FM_ASSIGN:
  564. sess.And("is_assigned=?", true)
  565. case FM_CREATE:
  566. sess.And("is_poster=?", true)
  567. default:
  568. return ius, nil
  569. }
  570. err := sess.Find(&ius)
  571. return ius, err
  572. }
  573. // IssueStats represents issue statistic information.
  574. type IssueStats struct {
  575. OpenCount, ClosedCount int64
  576. AllCount int64
  577. AssignCount int64
  578. CreateCount int64
  579. MentionCount int64
  580. }
  581. // Filter modes.
  582. const (
  583. FM_ALL = iota
  584. FM_ASSIGN
  585. FM_CREATE
  586. FM_MENTION
  587. )
  588. func parseCountResult(results []map[string][]byte) int64 {
  589. if len(results) == 0 {
  590. return 0
  591. }
  592. for _, result := range results[0] {
  593. return com.StrTo(string(result)).MustInt64()
  594. }
  595. return 0
  596. }
  597. type IssueStatsOptions struct {
  598. RepoID int64
  599. UserID int64
  600. LabelID int64
  601. MilestoneID int64
  602. AssigneeID int64
  603. FilterMode int
  604. IsPull bool
  605. }
  606. // GetIssueStats returns issue statistic information by given conditions.
  607. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  608. stats := &IssueStats{}
  609. queryStr := "SELECT COUNT(*) FROM `issue` "
  610. if opts.LabelID > 0 {
  611. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(opts.LabelID)
  612. }
  613. baseCond := " WHERE issue.repo_id=" + com.ToStr(opts.RepoID) + " AND issue.is_closed=?"
  614. if opts.MilestoneID > 0 {
  615. baseCond += " AND issue.milestone_id=" + com.ToStr(opts.MilestoneID)
  616. }
  617. if opts.AssigneeID > 0 {
  618. baseCond += " AND assignee_id=" + com.ToStr(opts.AssigneeID)
  619. }
  620. if opts.IsPull {
  621. baseCond += " AND issue.is_pull=1"
  622. } else {
  623. baseCond += " AND issue.is_pull=0"
  624. }
  625. switch opts.FilterMode {
  626. case FM_ALL, FM_ASSIGN:
  627. results, _ := x.Query(queryStr+baseCond, false)
  628. stats.OpenCount = parseCountResult(results)
  629. results, _ = x.Query(queryStr+baseCond, true)
  630. stats.ClosedCount = parseCountResult(results)
  631. case FM_CREATE:
  632. baseCond += " AND poster_id=?"
  633. results, _ := x.Query(queryStr+baseCond, false, opts.UserID)
  634. stats.OpenCount = parseCountResult(results)
  635. results, _ = x.Query(queryStr+baseCond, true, opts.UserID)
  636. stats.ClosedCount = parseCountResult(results)
  637. case FM_MENTION:
  638. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  639. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  640. results, _ := x.Query(queryStr+baseCond, false, opts.UserID, true)
  641. stats.OpenCount = parseCountResult(results)
  642. results, _ = x.Query(queryStr+baseCond, true, opts.UserID, true)
  643. stats.ClosedCount = parseCountResult(results)
  644. }
  645. return stats
  646. }
  647. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  648. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  649. stats := &IssueStats{}
  650. queryStr := "SELECT COUNT(*) FROM `issue` "
  651. baseCond := " WHERE issue.is_closed=?"
  652. if repoID > 0 || len(repoIDs) == 0 {
  653. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  654. } else {
  655. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  656. }
  657. if isPull {
  658. baseCond += " AND issue.is_pull=1"
  659. } else {
  660. baseCond += " AND issue.is_pull=0"
  661. }
  662. results, _ := x.Query(queryStr+baseCond+" AND assignee_id=?", false, uid)
  663. stats.AssignCount = parseCountResult(results)
  664. results, _ = x.Query(queryStr+baseCond+" AND poster_id=?", false, uid)
  665. stats.CreateCount = parseCountResult(results)
  666. switch filterMode {
  667. case FM_ASSIGN:
  668. baseCond += " AND assignee_id=" + com.ToStr(uid)
  669. case FM_CREATE:
  670. baseCond += " AND poster_id=" + com.ToStr(uid)
  671. }
  672. results, _ = x.Query(queryStr+baseCond, false)
  673. stats.OpenCount = parseCountResult(results)
  674. results, _ = x.Query(queryStr+baseCond, true)
  675. stats.ClosedCount = parseCountResult(results)
  676. return stats
  677. }
  678. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  679. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  680. queryStr := "SELECT COUNT(*) FROM `issue` "
  681. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  682. if isPull {
  683. baseCond += " AND issue.is_pull=1"
  684. } else {
  685. baseCond += " AND issue.is_pull=0"
  686. }
  687. switch filterMode {
  688. case FM_ASSIGN:
  689. baseCond += " AND assignee_id=" + com.ToStr(uid)
  690. case FM_CREATE:
  691. baseCond += " AND poster_id=" + com.ToStr(uid)
  692. }
  693. results, _ := x.Query(queryStr+baseCond, repoID, false)
  694. numOpen = parseCountResult(results)
  695. results, _ = x.Query(queryStr+baseCond, repoID, true)
  696. numClosed = parseCountResult(results)
  697. return numOpen, numClosed
  698. }
  699. func updateIssue(e Engine, issue *Issue) error {
  700. _, err := e.Id(issue.ID).AllCols().Update(issue)
  701. return err
  702. }
  703. // UpdateIssue updates all fields of given issue.
  704. func UpdateIssue(issue *Issue) error {
  705. return updateIssue(x, issue)
  706. }
  707. // updateIssueCols updates specific fields of given issue.
  708. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  709. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  710. return err
  711. }
  712. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  713. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  714. return err
  715. }
  716. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  717. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  718. return updateIssueUsersByStatus(x, issueID, isClosed)
  719. }
  720. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  721. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  722. return err
  723. }
  724. // Assignee ID equals to 0 means clear assignee.
  725. if issue.AssigneeID > 0 {
  726. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  727. return err
  728. }
  729. }
  730. return updateIssue(e, issue)
  731. }
  732. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  733. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  734. sess := x.NewSession()
  735. defer sessionRelease(sess)
  736. if err = sess.Begin(); err != nil {
  737. return err
  738. }
  739. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  740. return err
  741. }
  742. return sess.Commit()
  743. }
  744. // UpdateIssueUserByRead updates issue-user relation for reading.
  745. func UpdateIssueUserByRead(uid, issueID int64) error {
  746. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  747. return err
  748. }
  749. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  750. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  751. for _, uid := range uids {
  752. iu := &IssueUser{UID: uid, IssueID: iid}
  753. has, err := x.Get(iu)
  754. if err != nil {
  755. return err
  756. }
  757. iu.IsMentioned = true
  758. if has {
  759. _, err = x.Id(iu.ID).AllCols().Update(iu)
  760. } else {
  761. _, err = x.Insert(iu)
  762. }
  763. if err != nil {
  764. return err
  765. }
  766. }
  767. return nil
  768. }
  769. // .____ ___. .__
  770. // | | _____ \_ |__ ____ | |
  771. // | | \__ \ | __ \_/ __ \| |
  772. // | |___ / __ \| \_\ \ ___/| |__
  773. // |_______ (____ /___ /\___ >____/
  774. // \/ \/ \/ \/
  775. // Label represents a label of repository for issues.
  776. type Label struct {
  777. ID int64 `xorm:"pk autoincr"`
  778. RepoID int64 `xorm:"INDEX"`
  779. Name string
  780. Color string `xorm:"VARCHAR(7)"`
  781. NumIssues int
  782. NumClosedIssues int
  783. NumOpenIssues int `xorm:"-"`
  784. IsChecked bool `xorm:"-"`
  785. }
  786. // CalOpenIssues calculates the open issues of label.
  787. func (m *Label) CalOpenIssues() {
  788. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  789. }
  790. // NewLabel creates new label of repository.
  791. func NewLabel(l *Label) error {
  792. _, err := x.Insert(l)
  793. return err
  794. }
  795. func getLabelByID(e Engine, id int64) (*Label, error) {
  796. if id <= 0 {
  797. return nil, ErrLabelNotExist{id}
  798. }
  799. l := &Label{ID: id}
  800. has, err := x.Get(l)
  801. if err != nil {
  802. return nil, err
  803. } else if !has {
  804. return nil, ErrLabelNotExist{l.ID}
  805. }
  806. return l, nil
  807. }
  808. // GetLabelByID returns a label by given ID.
  809. func GetLabelByID(id int64) (*Label, error) {
  810. return getLabelByID(x, id)
  811. }
  812. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  813. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  814. labels := make([]*Label, 0, 10)
  815. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  816. }
  817. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  818. issueLabels, err := getIssueLabels(e, issueID)
  819. if err != nil {
  820. return nil, fmt.Errorf("getIssueLabels: %v", err)
  821. }
  822. var label *Label
  823. labels := make([]*Label, 0, len(issueLabels))
  824. for idx := range issueLabels {
  825. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  826. if err != nil && !IsErrLabelNotExist(err) {
  827. return nil, fmt.Errorf("getLabelByID: %v", err)
  828. }
  829. labels = append(labels, label)
  830. }
  831. return labels, nil
  832. }
  833. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  834. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  835. return getLabelsByIssueID(x, issueID)
  836. }
  837. func updateLabel(e Engine, l *Label) error {
  838. _, err := e.Id(l.ID).AllCols().Update(l)
  839. return err
  840. }
  841. // UpdateLabel updates label information.
  842. func UpdateLabel(l *Label) error {
  843. return updateLabel(x, l)
  844. }
  845. // DeleteLabel delete a label of given repository.
  846. func DeleteLabel(repoID, labelID int64) error {
  847. l, err := GetLabelByID(labelID)
  848. if err != nil {
  849. if IsErrLabelNotExist(err) {
  850. return nil
  851. }
  852. return err
  853. }
  854. sess := x.NewSession()
  855. defer sessionRelease(sess)
  856. if err = sess.Begin(); err != nil {
  857. return err
  858. }
  859. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  860. return err
  861. } else if _, err = sess.Delete(l); err != nil {
  862. return err
  863. }
  864. return sess.Commit()
  865. }
  866. // .___ .____ ___. .__
  867. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  868. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  869. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  870. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  871. // \/ \/ \/ \/ \/ \/ \/
  872. // IssueLabel represetns an issue-lable relation.
  873. type IssueLabel struct {
  874. ID int64 `xorm:"pk autoincr"`
  875. IssueID int64 `xorm:"UNIQUE(s)"`
  876. LabelID int64 `xorm:"UNIQUE(s)"`
  877. }
  878. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  879. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  880. return has
  881. }
  882. // HasIssueLabel returns true if issue has been labeled.
  883. func HasIssueLabel(issueID, labelID int64) bool {
  884. return hasIssueLabel(x, issueID, labelID)
  885. }
  886. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  887. if _, err = e.Insert(&IssueLabel{
  888. IssueID: issue.ID,
  889. LabelID: label.ID,
  890. }); err != nil {
  891. return err
  892. }
  893. label.NumIssues++
  894. if issue.IsClosed {
  895. label.NumClosedIssues++
  896. }
  897. return updateLabel(e, label)
  898. }
  899. // NewIssueLabel creates a new issue-label relation.
  900. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  901. sess := x.NewSession()
  902. defer sessionRelease(sess)
  903. if err = sess.Begin(); err != nil {
  904. return err
  905. }
  906. if err = newIssueLabel(sess, issue, label); err != nil {
  907. return err
  908. }
  909. return sess.Commit()
  910. }
  911. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  912. issueLabels := make([]*IssueLabel, 0, 10)
  913. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  914. }
  915. // GetIssueLabels returns all issue-label relations of given issue by ID.
  916. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  917. return getIssueLabels(x, issueID)
  918. }
  919. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  920. if _, err = e.Delete(&IssueLabel{
  921. IssueID: issue.ID,
  922. LabelID: label.ID,
  923. }); err != nil {
  924. return err
  925. }
  926. label.NumIssues--
  927. if issue.IsClosed {
  928. label.NumClosedIssues--
  929. }
  930. return updateLabel(e, label)
  931. }
  932. // DeleteIssueLabel deletes issue-label relation.
  933. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  934. sess := x.NewSession()
  935. defer sessionRelease(sess)
  936. if err = sess.Begin(); err != nil {
  937. return err
  938. }
  939. if err = deleteIssueLabel(sess, issue, label); err != nil {
  940. return err
  941. }
  942. return sess.Commit()
  943. }
  944. // _____ .__.__ __
  945. // / \ |__| | ____ _______/ |_ ____ ____ ____
  946. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  947. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  948. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  949. // \/ \/ \/ \/ \/
  950. // Milestone represents a milestone of repository.
  951. type Milestone struct {
  952. ID int64 `xorm:"pk autoincr"`
  953. RepoID int64 `xorm:"INDEX"`
  954. Name string
  955. Content string `xorm:"TEXT"`
  956. RenderedContent string `xorm:"-"`
  957. IsClosed bool
  958. NumIssues int
  959. NumClosedIssues int
  960. NumOpenIssues int `xorm:"-"`
  961. Completeness int // Percentage(1-100).
  962. Deadline time.Time
  963. DeadlineString string `xorm:"-"`
  964. IsOverDue bool `xorm:"-"`
  965. ClosedDate time.Time
  966. }
  967. func (m *Milestone) BeforeUpdate() {
  968. if m.NumIssues > 0 {
  969. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  970. } else {
  971. m.Completeness = 0
  972. }
  973. }
  974. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  975. if colName == "deadline" {
  976. if m.Deadline.Year() == 9999 {
  977. return
  978. }
  979. m.DeadlineString = m.Deadline.Format("2006-01-02")
  980. if time.Now().After(m.Deadline) {
  981. m.IsOverDue = true
  982. }
  983. }
  984. }
  985. // CalOpenIssues calculates the open issues of milestone.
  986. func (m *Milestone) CalOpenIssues() {
  987. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  988. }
  989. // NewMilestone creates new milestone of repository.
  990. func NewMilestone(m *Milestone) (err error) {
  991. sess := x.NewSession()
  992. defer sessionRelease(sess)
  993. if err = sess.Begin(); err != nil {
  994. return err
  995. }
  996. if _, err = sess.Insert(m); err != nil {
  997. return err
  998. }
  999. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1000. return err
  1001. }
  1002. return sess.Commit()
  1003. }
  1004. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1005. m := &Milestone{ID: id}
  1006. has, err := e.Get(m)
  1007. if err != nil {
  1008. return nil, err
  1009. } else if !has {
  1010. return nil, ErrMilestoneNotExist{id, 0}
  1011. }
  1012. return m, nil
  1013. }
  1014. // GetMilestoneByID returns the milestone of given ID.
  1015. func GetMilestoneByID(id int64) (*Milestone, error) {
  1016. return getMilestoneByID(x, id)
  1017. }
  1018. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1019. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1020. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1021. has, err := x.Get(m)
  1022. if err != nil {
  1023. return nil, err
  1024. } else if !has {
  1025. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1026. }
  1027. return m, nil
  1028. }
  1029. // GetAllRepoMilestones returns all milestones of given repository.
  1030. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1031. miles := make([]*Milestone, 0, 10)
  1032. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1033. }
  1034. // GetMilestones returns a list of milestones of given repository and status.
  1035. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1036. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1037. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1038. if page > 0 {
  1039. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1040. }
  1041. return miles, sess.Find(&miles)
  1042. }
  1043. func updateMilestone(e Engine, m *Milestone) error {
  1044. _, err := e.Id(m.ID).AllCols().Update(m)
  1045. return err
  1046. }
  1047. // UpdateMilestone updates information of given milestone.
  1048. func UpdateMilestone(m *Milestone) error {
  1049. return updateMilestone(x, m)
  1050. }
  1051. func countRepoMilestones(e Engine, repoID int64) int64 {
  1052. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1053. return count
  1054. }
  1055. // CountRepoMilestones returns number of milestones in given repository.
  1056. func CountRepoMilestones(repoID int64) int64 {
  1057. return countRepoMilestones(x, repoID)
  1058. }
  1059. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1060. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1061. return closed
  1062. }
  1063. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1064. func CountRepoClosedMilestones(repoID int64) int64 {
  1065. return countRepoClosedMilestones(x, repoID)
  1066. }
  1067. // MilestoneStats returns number of open and closed milestones of given repository.
  1068. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1069. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1070. return open, CountRepoClosedMilestones(repoID)
  1071. }
  1072. // ChangeMilestoneStatus changes the milestone open/closed status.
  1073. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1074. repo, err := GetRepositoryByID(m.RepoID)
  1075. if err != nil {
  1076. return err
  1077. }
  1078. sess := x.NewSession()
  1079. defer sessionRelease(sess)
  1080. if err = sess.Begin(); err != nil {
  1081. return err
  1082. }
  1083. m.IsClosed = isClosed
  1084. if err = updateMilestone(sess, m); err != nil {
  1085. return err
  1086. }
  1087. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1088. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1089. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1090. return err
  1091. }
  1092. return sess.Commit()
  1093. }
  1094. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1095. if issue.MilestoneID == 0 {
  1096. return nil
  1097. }
  1098. m, err := getMilestoneByID(e, issue.MilestoneID)
  1099. if err != nil {
  1100. return err
  1101. }
  1102. if issue.IsClosed {
  1103. m.NumOpenIssues--
  1104. m.NumClosedIssues++
  1105. } else {
  1106. m.NumOpenIssues++
  1107. m.NumClosedIssues--
  1108. }
  1109. return updateMilestone(e, m)
  1110. }
  1111. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1112. // for the milestone associated witht the given issue.
  1113. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1114. sess := x.NewSession()
  1115. defer sessionRelease(sess)
  1116. if err = sess.Begin(); err != nil {
  1117. return err
  1118. }
  1119. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1120. return err
  1121. }
  1122. return sess.Commit()
  1123. }
  1124. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1125. if oldMid > 0 {
  1126. m, err := getMilestoneByID(e, oldMid)
  1127. if err != nil {
  1128. return err
  1129. }
  1130. m.NumIssues--
  1131. if issue.IsClosed {
  1132. m.NumClosedIssues--
  1133. }
  1134. if err = updateMilestone(e, m); err != nil {
  1135. return err
  1136. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1137. return err
  1138. }
  1139. }
  1140. if issue.MilestoneID > 0 {
  1141. m, err := getMilestoneByID(e, issue.MilestoneID)
  1142. if err != nil {
  1143. return err
  1144. }
  1145. m.NumIssues++
  1146. if issue.IsClosed {
  1147. m.NumClosedIssues++
  1148. }
  1149. if m.NumIssues == 0 {
  1150. return ErrWrongIssueCounter
  1151. }
  1152. if err = updateMilestone(e, m); err != nil {
  1153. return err
  1154. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1155. return err
  1156. }
  1157. }
  1158. return updateIssue(e, issue)
  1159. }
  1160. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1161. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1162. sess := x.NewSession()
  1163. defer sess.Close()
  1164. if err = sess.Begin(); err != nil {
  1165. return err
  1166. }
  1167. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1168. return err
  1169. }
  1170. return sess.Commit()
  1171. }
  1172. // DeleteMilestoneByID deletes a milestone by given ID.
  1173. func DeleteMilestoneByID(mid int64) error {
  1174. m, err := GetMilestoneByID(mid)
  1175. if err != nil {
  1176. if IsErrMilestoneNotExist(err) {
  1177. return nil
  1178. }
  1179. return err
  1180. }
  1181. repo, err := GetRepositoryByID(m.RepoID)
  1182. if err != nil {
  1183. return err
  1184. }
  1185. sess := x.NewSession()
  1186. defer sessionRelease(sess)
  1187. if err = sess.Begin(); err != nil {
  1188. return err
  1189. }
  1190. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1191. return err
  1192. }
  1193. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1194. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1195. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1196. return err
  1197. }
  1198. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1199. return err
  1200. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1201. return err
  1202. }
  1203. return sess.Commit()
  1204. }
  1205. // _________ __
  1206. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1207. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1208. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1209. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1210. // \/ \/ \/ \/ \/
  1211. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1212. type CommentType int
  1213. const (
  1214. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1215. COMMENT_TYPE_COMMENT CommentType = iota
  1216. COMMENT_TYPE_REOPEN
  1217. COMMENT_TYPE_CLOSE
  1218. // References.
  1219. COMMENT_TYPE_ISSUE_REF
  1220. // Reference from a commit (not part of a pull request)
  1221. COMMENT_TYPE_COMMIT_REF
  1222. // Reference from a comment
  1223. COMMENT_TYPE_COMMENT_REF
  1224. // Reference from a pull request
  1225. COMMENT_TYPE_PULL_REF
  1226. )
  1227. type CommentTag int
  1228. const (
  1229. COMMENT_TAG_NONE CommentTag = iota
  1230. COMMENT_TAG_POSTER
  1231. COMMENT_TAG_ADMIN
  1232. COMMENT_TAG_OWNER
  1233. )
  1234. // Comment represents a comment in commit and issue page.
  1235. type Comment struct {
  1236. ID int64 `xorm:"pk autoincr"`
  1237. Type CommentType
  1238. PosterID int64
  1239. Poster *User `xorm:"-"`
  1240. IssueID int64 `xorm:"INDEX"`
  1241. CommitID int64
  1242. Line int64
  1243. Content string `xorm:"TEXT"`
  1244. RenderedContent string `xorm:"-"`
  1245. Created time.Time `xorm:"CREATED"`
  1246. // Reference issue in commit message
  1247. CommitSHA string `xorm:"VARCHAR(40)"`
  1248. Attachments []*Attachment `xorm:"-"`
  1249. // For view issue page.
  1250. ShowTag CommentTag `xorm:"-"`
  1251. }
  1252. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1253. var err error
  1254. switch colName {
  1255. case "id":
  1256. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1257. if err != nil {
  1258. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1259. }
  1260. case "poster_id":
  1261. c.Poster, err = GetUserByID(c.PosterID)
  1262. if err != nil {
  1263. if IsErrUserNotExist(err) {
  1264. c.PosterID = -1
  1265. c.Poster = NewFakeUser()
  1266. } else {
  1267. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1268. }
  1269. }
  1270. case "created":
  1271. c.Created = regulateTimeZone(c.Created)
  1272. }
  1273. }
  1274. func (c *Comment) AfterDelete() {
  1275. _, err := DeleteAttachmentsByComment(c.ID, true)
  1276. if err != nil {
  1277. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1278. }
  1279. }
  1280. // HashTag returns unique hash tag for comment.
  1281. func (c *Comment) HashTag() string {
  1282. return "issuecomment-" + com.ToStr(c.ID)
  1283. }
  1284. // EventTag returns unique event hash tag for comment.
  1285. func (c *Comment) EventTag() string {
  1286. return "event-" + com.ToStr(c.ID)
  1287. }
  1288. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, uuids []string) (_ *Comment, err error) {
  1289. comment := &Comment{
  1290. PosterID: u.Id,
  1291. Type: cmtType,
  1292. IssueID: issue.ID,
  1293. CommitID: commitID,
  1294. Line: line,
  1295. Content: content,
  1296. CommitSHA: commitSHA,
  1297. }
  1298. if _, err = e.Insert(comment); err != nil {
  1299. return nil, err
  1300. }
  1301. // Check comment type.
  1302. switch cmtType {
  1303. case COMMENT_TYPE_COMMENT:
  1304. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1305. return nil, err
  1306. }
  1307. // Check attachments.
  1308. attachments := make([]*Attachment, 0, len(uuids))
  1309. for _, uuid := range uuids {
  1310. attach, err := getAttachmentByUUID(e, uuid)
  1311. if err != nil {
  1312. if IsErrAttachmentNotExist(err) {
  1313. continue
  1314. }
  1315. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1316. }
  1317. attachments = append(attachments, attach)
  1318. }
  1319. for i := range attachments {
  1320. attachments[i].IssueID = issue.ID
  1321. attachments[i].CommentID = comment.ID
  1322. // No assign value could be 0, so ignore AllCols().
  1323. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1324. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1325. }
  1326. }
  1327. // Notify watchers.
  1328. act := &Action{
  1329. ActUserID: u.Id,
  1330. ActUserName: u.LowerName,
  1331. ActEmail: u.Email,
  1332. OpType: COMMENT_ISSUE,
  1333. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1334. RepoID: repo.ID,
  1335. RepoUserName: repo.Owner.LowerName,
  1336. RepoName: repo.LowerName,
  1337. IsPrivate: repo.IsPrivate,
  1338. }
  1339. if err = notifyWatchers(e, act); err != nil {
  1340. return nil, err
  1341. }
  1342. case COMMENT_TYPE_REOPEN:
  1343. if issue.IsPull {
  1344. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", repo.ID)
  1345. } else {
  1346. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID)
  1347. }
  1348. if err != nil {
  1349. return nil, err
  1350. }
  1351. case COMMENT_TYPE_CLOSE:
  1352. if issue.IsPull {
  1353. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", repo.ID)
  1354. } else {
  1355. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID)
  1356. }
  1357. if err != nil {
  1358. return nil, err
  1359. }
  1360. }
  1361. return comment, nil
  1362. }
  1363. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1364. cmtType := COMMENT_TYPE_CLOSE
  1365. if !issue.IsClosed {
  1366. cmtType = COMMENT_TYPE_REOPEN
  1367. }
  1368. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", "", nil)
  1369. }
  1370. // CreateComment creates comment of issue or commit.
  1371. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, attachments []string) (comment *Comment, err error) {
  1372. sess := x.NewSession()
  1373. defer sessionRelease(sess)
  1374. if err = sess.Begin(); err != nil {
  1375. return nil, err
  1376. }
  1377. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, commitSHA, attachments)
  1378. if err != nil {
  1379. return nil, err
  1380. }
  1381. return comment, sess.Commit()
  1382. }
  1383. // CreateIssueComment creates a plain issue comment.
  1384. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1385. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, "", attachments)
  1386. }
  1387. // CreateRefComment creates a commit reference comment to issue.
  1388. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  1389. if len(commitSHA) == 0 {
  1390. return fmt.Errorf("cannot create reference with empty commit SHA")
  1391. }
  1392. // Check if same reference from same commit has already existed.
  1393. has, err := x.Get(&Comment{
  1394. Type: COMMENT_TYPE_COMMIT_REF,
  1395. IssueID: issue.ID,
  1396. CommitSHA: commitSHA,
  1397. })
  1398. if err != nil {
  1399. return fmt.Errorf("check reference comment: %v", err)
  1400. } else if has {
  1401. return nil
  1402. }
  1403. _, err = CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, content, commitSHA, nil)
  1404. return err
  1405. }
  1406. // GetCommentByID returns the comment by given ID.
  1407. func GetCommentByID(id int64) (*Comment, error) {
  1408. c := new(Comment)
  1409. has, err := x.Id(id).Get(c)
  1410. if err != nil {
  1411. return nil, err
  1412. } else if !has {
  1413. return nil, ErrCommentNotExist{id}
  1414. }
  1415. return c, nil
  1416. }
  1417. // GetCommentsByIssueID returns all comments of issue by given ID.
  1418. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1419. comments := make([]*Comment, 0, 10)
  1420. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1421. }
  1422. // UpdateComment updates information of comment.
  1423. func UpdateComment(c *Comment) error {
  1424. _, err := x.Id(c.ID).AllCols().Update(c)
  1425. return err
  1426. }
  1427. // Attachment represent a attachment of issue/comment/release.
  1428. type Attachment struct {
  1429. ID int64 `xorm:"pk autoincr"`
  1430. UUID string `xorm:"uuid UNIQUE"`
  1431. IssueID int64 `xorm:"INDEX"`
  1432. CommentID int64
  1433. ReleaseID int64 `xorm:"INDEX"`
  1434. Name string
  1435. Created time.Time `xorm:"CREATED"`
  1436. }
  1437. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1438. func AttachmentLocalPath(uuid string) string {
  1439. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1440. }
  1441. // LocalPath returns where attachment is stored in local file system.
  1442. func (attach *Attachment) LocalPath() string {
  1443. return AttachmentLocalPath(attach.UUID)
  1444. }
  1445. // NewAttachment creates a new attachment object.
  1446. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1447. attach := &Attachment{
  1448. UUID: gouuid.NewV4().String(),
  1449. Name: name,
  1450. }
  1451. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1452. return nil, fmt.Errorf("MkdirAll: %v", err)
  1453. }
  1454. fw, err := os.Create(attach.LocalPath())
  1455. if err != nil {
  1456. return nil, fmt.Errorf("Create: %v", err)
  1457. }
  1458. defer fw.Close()
  1459. if _, err = fw.Write(buf); err != nil {
  1460. return nil, fmt.Errorf("Write: %v", err)
  1461. } else if _, err = io.Copy(fw, file); err != nil {
  1462. return nil, fmt.Errorf("Copy: %v", err)
  1463. }
  1464. sess := x.NewSession()
  1465. defer sessionRelease(sess)
  1466. if err := sess.Begin(); err != nil {
  1467. return nil, err
  1468. }
  1469. if _, err := sess.Insert(attach); err != nil {
  1470. return nil, err
  1471. }
  1472. return attach, sess.Commit()
  1473. }
  1474. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1475. attach := &Attachment{UUID: uuid}
  1476. has, err := x.Get(attach)
  1477. if err != nil {
  1478. return nil, err
  1479. } else if !has {
  1480. return nil, ErrAttachmentNotExist{0, uuid}
  1481. }
  1482. return attach, nil
  1483. }
  1484. // GetAttachmentByUUID returns attachment by given UUID.
  1485. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1486. return getAttachmentByUUID(x, uuid)
  1487. }
  1488. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1489. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1490. attachments := make([]*Attachment, 0, 10)
  1491. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1492. }
  1493. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1494. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1495. attachments := make([]*Attachment, 0, 10)
  1496. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1497. }
  1498. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1499. func DeleteAttachment(a *Attachment, remove bool) error {
  1500. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1501. return err
  1502. }
  1503. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1504. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1505. for i, a := range attachments {
  1506. if remove {
  1507. if err := os.Remove(a.LocalPath()); err != nil {
  1508. return i, err
  1509. }
  1510. }
  1511. if _, err := x.Delete(a.ID); err != nil {
  1512. return i, err
  1513. }
  1514. }
  1515. return len(attachments), nil
  1516. }
  1517. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1518. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1519. attachments, err := GetAttachmentsByIssueID(issueId)
  1520. if err != nil {
  1521. return 0, err
  1522. }
  1523. return DeleteAttachments(attachments, remove)
  1524. }
  1525. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1526. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1527. attachments, err := GetAttachmentsByCommentID(commentId)
  1528. if err != nil {
  1529. return 0, err
  1530. }
  1531. return DeleteAttachments(attachments, remove)
  1532. }