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.

1846 lines
47 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
9 years ago
9 years ago
9 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
9 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
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. gouuid "github.com/satori/go.uuid"
  18. "github.com/gogits/gogs/modules/base"
  19. "github.com/gogits/gogs/modules/log"
  20. "github.com/gogits/gogs/modules/setting"
  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: ACTION_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. func UpdateMentions(userNames []string, issueId int64) error {
  574. for i := range userNames {
  575. userNames[i] = strings.ToLower(userNames[i])
  576. }
  577. users := make([]*User, 0, len(userNames))
  578. if err := x.Where("lower_name IN (?)", strings.Join(userNames, "\",\"")).OrderBy("lower_name ASC").Find(&users); err != nil {
  579. return err
  580. }
  581. ids := make([]int64, 0, len(userNames))
  582. for _, user := range users {
  583. ids = append(ids, user.Id)
  584. if !user.IsOrganization() {
  585. continue
  586. }
  587. if user.NumMembers == 0 {
  588. continue
  589. }
  590. tempIds := make([]int64, 0, user.NumMembers)
  591. orgUsers, err := GetOrgUsersByOrgId(user.Id)
  592. if err != nil {
  593. return err
  594. }
  595. for _, orgUser := range orgUsers {
  596. tempIds = append(tempIds, orgUser.ID)
  597. }
  598. ids = append(ids, tempIds...)
  599. }
  600. if err := UpdateIssueUsersByMentions(ids, issueId); err != nil {
  601. return err
  602. }
  603. return nil
  604. }
  605. // IssueStats represents issue statistic information.
  606. type IssueStats struct {
  607. OpenCount, ClosedCount int64
  608. AllCount int64
  609. AssignCount int64
  610. CreateCount int64
  611. MentionCount int64
  612. }
  613. // Filter modes.
  614. const (
  615. FM_ALL = iota
  616. FM_ASSIGN
  617. FM_CREATE
  618. FM_MENTION
  619. )
  620. func parseCountResult(results []map[string][]byte) int64 {
  621. if len(results) == 0 {
  622. return 0
  623. }
  624. for _, result := range results[0] {
  625. return com.StrTo(string(result)).MustInt64()
  626. }
  627. return 0
  628. }
  629. type IssueStatsOptions struct {
  630. RepoID int64
  631. UserID int64
  632. LabelID int64
  633. MilestoneID int64
  634. AssigneeID int64
  635. FilterMode int
  636. IsPull bool
  637. }
  638. // GetIssueStats returns issue statistic information by given conditions.
  639. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  640. stats := &IssueStats{}
  641. queryStr := "SELECT COUNT(*) FROM `issue` "
  642. if opts.LabelID > 0 {
  643. queryStr += "INNER JOIN `issue_label` ON `issue`.id=`issue_label`.issue_id AND `issue_label`.label_id=" + com.ToStr(opts.LabelID)
  644. }
  645. baseCond := " WHERE issue.repo_id=" + com.ToStr(opts.RepoID) + " AND issue.is_closed=?"
  646. if opts.MilestoneID > 0 {
  647. baseCond += " AND issue.milestone_id=" + com.ToStr(opts.MilestoneID)
  648. }
  649. if opts.AssigneeID > 0 {
  650. baseCond += " AND assignee_id=" + com.ToStr(opts.AssigneeID)
  651. }
  652. baseCond += " AND issue.is_pull=?"
  653. switch opts.FilterMode {
  654. case FM_ALL, FM_ASSIGN:
  655. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull)
  656. stats.OpenCount = parseCountResult(results)
  657. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull)
  658. stats.ClosedCount = parseCountResult(results)
  659. case FM_CREATE:
  660. baseCond += " AND poster_id=?"
  661. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID)
  662. stats.OpenCount = parseCountResult(results)
  663. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID)
  664. stats.ClosedCount = parseCountResult(results)
  665. case FM_MENTION:
  666. queryStr += " INNER JOIN `issue_user` ON `issue`.id=`issue_user`.issue_id"
  667. baseCond += " AND `issue_user`.uid=? AND `issue_user`.is_mentioned=?"
  668. results, _ := x.Query(queryStr+baseCond, false, opts.IsPull, opts.UserID, true)
  669. stats.OpenCount = parseCountResult(results)
  670. results, _ = x.Query(queryStr+baseCond, true, opts.IsPull, opts.UserID, true)
  671. stats.ClosedCount = parseCountResult(results)
  672. }
  673. return stats
  674. }
  675. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  676. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  677. stats := &IssueStats{}
  678. queryStr := "SELECT COUNT(*) FROM `issue` "
  679. baseCond := " WHERE issue.is_closed=?"
  680. if repoID > 0 || len(repoIDs) == 0 {
  681. baseCond += " AND issue.repo_id=" + com.ToStr(repoID)
  682. } else {
  683. baseCond += " AND issue.repo_id IN (" + strings.Join(base.Int64sToStrings(repoIDs), ",") + ")"
  684. }
  685. if isPull {
  686. baseCond += " AND issue.is_pull=1"
  687. } else {
  688. baseCond += " AND issue.is_pull=0"
  689. }
  690. results, _ := x.Query(queryStr+baseCond+" AND assignee_id=?", false, uid)
  691. stats.AssignCount = parseCountResult(results)
  692. results, _ = x.Query(queryStr+baseCond+" AND poster_id=?", false, uid)
  693. stats.CreateCount = parseCountResult(results)
  694. switch filterMode {
  695. case FM_ASSIGN:
  696. baseCond += " AND assignee_id=" + com.ToStr(uid)
  697. case FM_CREATE:
  698. baseCond += " AND poster_id=" + com.ToStr(uid)
  699. }
  700. results, _ = x.Query(queryStr+baseCond, false)
  701. stats.OpenCount = parseCountResult(results)
  702. results, _ = x.Query(queryStr+baseCond, true)
  703. stats.ClosedCount = parseCountResult(results)
  704. return stats
  705. }
  706. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  707. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  708. queryStr := "SELECT COUNT(*) FROM `issue` "
  709. baseCond := " WHERE issue.repo_id=? AND issue.is_closed=?"
  710. if isPull {
  711. baseCond += " AND issue.is_pull=1"
  712. } else {
  713. baseCond += " AND issue.is_pull=0"
  714. }
  715. switch filterMode {
  716. case FM_ASSIGN:
  717. baseCond += " AND assignee_id=" + com.ToStr(uid)
  718. case FM_CREATE:
  719. baseCond += " AND poster_id=" + com.ToStr(uid)
  720. }
  721. results, _ := x.Query(queryStr+baseCond, repoID, false)
  722. numOpen = parseCountResult(results)
  723. results, _ = x.Query(queryStr+baseCond, repoID, true)
  724. numClosed = parseCountResult(results)
  725. return numOpen, numClosed
  726. }
  727. func updateIssue(e Engine, issue *Issue) error {
  728. _, err := e.Id(issue.ID).AllCols().Update(issue)
  729. return err
  730. }
  731. // UpdateIssue updates all fields of given issue.
  732. func UpdateIssue(issue *Issue) error {
  733. return updateIssue(x, issue)
  734. }
  735. // updateIssueCols updates specific fields of given issue.
  736. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  737. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  738. return err
  739. }
  740. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  741. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  742. return err
  743. }
  744. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  745. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  746. return updateIssueUsersByStatus(x, issueID, isClosed)
  747. }
  748. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  749. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE issue_id=?", false, issue.ID); err != nil {
  750. return err
  751. }
  752. // Assignee ID equals to 0 means clear assignee.
  753. if issue.AssigneeID > 0 {
  754. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned=? WHERE uid=? AND issue_id=?", true, issue.AssigneeID, issue.ID); err != nil {
  755. return err
  756. }
  757. }
  758. return updateIssue(e, issue)
  759. }
  760. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  761. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  762. sess := x.NewSession()
  763. defer sessionRelease(sess)
  764. if err = sess.Begin(); err != nil {
  765. return err
  766. }
  767. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  768. return err
  769. }
  770. return sess.Commit()
  771. }
  772. // UpdateIssueUserByRead updates issue-user relation for reading.
  773. func UpdateIssueUserByRead(uid, issueID int64) error {
  774. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  775. return err
  776. }
  777. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  778. func UpdateIssueUsersByMentions(uids []int64, iid int64) error {
  779. for _, uid := range uids {
  780. iu := &IssueUser{UID: uid, IssueID: iid}
  781. has, err := x.Get(iu)
  782. if err != nil {
  783. return err
  784. }
  785. iu.IsMentioned = true
  786. if has {
  787. _, err = x.Id(iu.ID).AllCols().Update(iu)
  788. } else {
  789. _, err = x.Insert(iu)
  790. }
  791. if err != nil {
  792. return err
  793. }
  794. }
  795. return nil
  796. }
  797. // .____ ___. .__
  798. // | | _____ \_ |__ ____ | |
  799. // | | \__ \ | __ \_/ __ \| |
  800. // | |___ / __ \| \_\ \ ___/| |__
  801. // |_______ (____ /___ /\___ >____/
  802. // \/ \/ \/ \/
  803. // Label represents a label of repository for issues.
  804. type Label struct {
  805. ID int64 `xorm:"pk autoincr"`
  806. RepoID int64 `xorm:"INDEX"`
  807. Name string
  808. Color string `xorm:"VARCHAR(7)"`
  809. NumIssues int
  810. NumClosedIssues int
  811. NumOpenIssues int `xorm:"-"`
  812. IsChecked bool `xorm:"-"`
  813. }
  814. // CalOpenIssues calculates the open issues of label.
  815. func (m *Label) CalOpenIssues() {
  816. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  817. }
  818. // NewLabel creates new label of repository.
  819. func NewLabel(l *Label) error {
  820. _, err := x.Insert(l)
  821. return err
  822. }
  823. func getLabelByID(e Engine, id int64) (*Label, error) {
  824. if id <= 0 {
  825. return nil, ErrLabelNotExist{id}
  826. }
  827. l := &Label{ID: id}
  828. has, err := x.Get(l)
  829. if err != nil {
  830. return nil, err
  831. } else if !has {
  832. return nil, ErrLabelNotExist{l.ID}
  833. }
  834. return l, nil
  835. }
  836. // GetLabelByID returns a label by given ID.
  837. func GetLabelByID(id int64) (*Label, error) {
  838. return getLabelByID(x, id)
  839. }
  840. // GetLabelsByRepoID returns all labels that belong to given repository by ID.
  841. func GetLabelsByRepoID(repoID int64) ([]*Label, error) {
  842. labels := make([]*Label, 0, 10)
  843. return labels, x.Where("repo_id=?", repoID).Find(&labels)
  844. }
  845. func getLabelsByIssueID(e Engine, issueID int64) ([]*Label, error) {
  846. issueLabels, err := getIssueLabels(e, issueID)
  847. if err != nil {
  848. return nil, fmt.Errorf("getIssueLabels: %v", err)
  849. }
  850. var label *Label
  851. labels := make([]*Label, 0, len(issueLabels))
  852. for idx := range issueLabels {
  853. label, err = getLabelByID(e, issueLabels[idx].LabelID)
  854. if err != nil && !IsErrLabelNotExist(err) {
  855. return nil, fmt.Errorf("getLabelByID: %v", err)
  856. }
  857. labels = append(labels, label)
  858. }
  859. return labels, nil
  860. }
  861. // GetLabelsByIssueID returns all labels that belong to given issue by ID.
  862. func GetLabelsByIssueID(issueID int64) ([]*Label, error) {
  863. return getLabelsByIssueID(x, issueID)
  864. }
  865. func updateLabel(e Engine, l *Label) error {
  866. _, err := e.Id(l.ID).AllCols().Update(l)
  867. return err
  868. }
  869. // UpdateLabel updates label information.
  870. func UpdateLabel(l *Label) error {
  871. return updateLabel(x, l)
  872. }
  873. // DeleteLabel delete a label of given repository.
  874. func DeleteLabel(repoID, labelID int64) error {
  875. l, err := GetLabelByID(labelID)
  876. if err != nil {
  877. if IsErrLabelNotExist(err) {
  878. return nil
  879. }
  880. return err
  881. }
  882. sess := x.NewSession()
  883. defer sessionRelease(sess)
  884. if err = sess.Begin(); err != nil {
  885. return err
  886. }
  887. if _, err = x.Where("label_id=?", labelID).Delete(new(IssueLabel)); err != nil {
  888. return err
  889. } else if _, err = sess.Delete(l); err != nil {
  890. return err
  891. }
  892. return sess.Commit()
  893. }
  894. // .___ .____ ___. .__
  895. // | | ______ ________ __ ____ | | _____ \_ |__ ____ | |
  896. // | |/ ___// ___/ | \_/ __ \| | \__ \ | __ \_/ __ \| |
  897. // | |\___ \ \___ \| | /\ ___/| |___ / __ \| \_\ \ ___/| |__
  898. // |___/____ >____ >____/ \___ >_______ (____ /___ /\___ >____/
  899. // \/ \/ \/ \/ \/ \/ \/
  900. // IssueLabel represetns an issue-lable relation.
  901. type IssueLabel struct {
  902. ID int64 `xorm:"pk autoincr"`
  903. IssueID int64 `xorm:"UNIQUE(s)"`
  904. LabelID int64 `xorm:"UNIQUE(s)"`
  905. }
  906. func hasIssueLabel(e Engine, issueID, labelID int64) bool {
  907. has, _ := e.Where("issue_id=? AND label_id=?", issueID, labelID).Get(new(IssueLabel))
  908. return has
  909. }
  910. // HasIssueLabel returns true if issue has been labeled.
  911. func HasIssueLabel(issueID, labelID int64) bool {
  912. return hasIssueLabel(x, issueID, labelID)
  913. }
  914. func newIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  915. if _, err = e.Insert(&IssueLabel{
  916. IssueID: issue.ID,
  917. LabelID: label.ID,
  918. }); err != nil {
  919. return err
  920. }
  921. label.NumIssues++
  922. if issue.IsClosed {
  923. label.NumClosedIssues++
  924. }
  925. return updateLabel(e, label)
  926. }
  927. // NewIssueLabel creates a new issue-label relation.
  928. func NewIssueLabel(issue *Issue, label *Label) (err error) {
  929. sess := x.NewSession()
  930. defer sessionRelease(sess)
  931. if err = sess.Begin(); err != nil {
  932. return err
  933. }
  934. if err = newIssueLabel(sess, issue, label); err != nil {
  935. return err
  936. }
  937. return sess.Commit()
  938. }
  939. func getIssueLabels(e Engine, issueID int64) ([]*IssueLabel, error) {
  940. issueLabels := make([]*IssueLabel, 0, 10)
  941. return issueLabels, e.Where("issue_id=?", issueID).Asc("label_id").Find(&issueLabels)
  942. }
  943. // GetIssueLabels returns all issue-label relations of given issue by ID.
  944. func GetIssueLabels(issueID int64) ([]*IssueLabel, error) {
  945. return getIssueLabels(x, issueID)
  946. }
  947. func deleteIssueLabel(e *xorm.Session, issue *Issue, label *Label) (err error) {
  948. if _, err = e.Delete(&IssueLabel{
  949. IssueID: issue.ID,
  950. LabelID: label.ID,
  951. }); err != nil {
  952. return err
  953. }
  954. label.NumIssues--
  955. if issue.IsClosed {
  956. label.NumClosedIssues--
  957. }
  958. return updateLabel(e, label)
  959. }
  960. // DeleteIssueLabel deletes issue-label relation.
  961. func DeleteIssueLabel(issue *Issue, label *Label) (err error) {
  962. sess := x.NewSession()
  963. defer sessionRelease(sess)
  964. if err = sess.Begin(); err != nil {
  965. return err
  966. }
  967. if err = deleteIssueLabel(sess, issue, label); err != nil {
  968. return err
  969. }
  970. return sess.Commit()
  971. }
  972. // _____ .__.__ __
  973. // / \ |__| | ____ _______/ |_ ____ ____ ____
  974. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  975. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  976. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  977. // \/ \/ \/ \/ \/
  978. // Milestone represents a milestone of repository.
  979. type Milestone struct {
  980. ID int64 `xorm:"pk autoincr"`
  981. RepoID int64 `xorm:"INDEX"`
  982. Name string
  983. Content string `xorm:"TEXT"`
  984. RenderedContent string `xorm:"-"`
  985. IsClosed bool
  986. NumIssues int
  987. NumClosedIssues int
  988. NumOpenIssues int `xorm:"-"`
  989. Completeness int // Percentage(1-100).
  990. Deadline time.Time
  991. DeadlineString string `xorm:"-"`
  992. IsOverDue bool `xorm:"-"`
  993. ClosedDate time.Time
  994. }
  995. func (m *Milestone) BeforeUpdate() {
  996. if m.NumIssues > 0 {
  997. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  998. } else {
  999. m.Completeness = 0
  1000. }
  1001. }
  1002. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1003. if colName == "deadline" {
  1004. if m.Deadline.Year() == 9999 {
  1005. return
  1006. }
  1007. m.Deadline = regulateTimeZone(m.Deadline)
  1008. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1009. if time.Now().After(m.Deadline) {
  1010. m.IsOverDue = true
  1011. }
  1012. }
  1013. }
  1014. // CalOpenIssues calculates the open issues of milestone.
  1015. func (m *Milestone) CalOpenIssues() {
  1016. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1017. }
  1018. // NewMilestone creates new milestone of repository.
  1019. func NewMilestone(m *Milestone) (err error) {
  1020. sess := x.NewSession()
  1021. defer sessionRelease(sess)
  1022. if err = sess.Begin(); err != nil {
  1023. return err
  1024. }
  1025. if _, err = sess.Insert(m); err != nil {
  1026. return err
  1027. }
  1028. if _, err = sess.Exec("UPDATE `repository` SET num_milestones=num_milestones+1 WHERE id=?", m.RepoID); err != nil {
  1029. return err
  1030. }
  1031. return sess.Commit()
  1032. }
  1033. func getMilestoneByID(e Engine, id int64) (*Milestone, error) {
  1034. m := &Milestone{ID: id}
  1035. has, err := e.Get(m)
  1036. if err != nil {
  1037. return nil, err
  1038. } else if !has {
  1039. return nil, ErrMilestoneNotExist{id, 0}
  1040. }
  1041. return m, nil
  1042. }
  1043. // GetMilestoneByID returns the milestone of given ID.
  1044. func GetMilestoneByID(id int64) (*Milestone, error) {
  1045. return getMilestoneByID(x, id)
  1046. }
  1047. // GetRepoMilestoneByID returns the milestone of given ID and repository.
  1048. func GetRepoMilestoneByID(repoID, milestoneID int64) (*Milestone, error) {
  1049. m := &Milestone{ID: milestoneID, RepoID: repoID}
  1050. has, err := x.Get(m)
  1051. if err != nil {
  1052. return nil, err
  1053. } else if !has {
  1054. return nil, ErrMilestoneNotExist{milestoneID, repoID}
  1055. }
  1056. return m, nil
  1057. }
  1058. // GetAllRepoMilestones returns all milestones of given repository.
  1059. func GetAllRepoMilestones(repoID int64) ([]*Milestone, error) {
  1060. miles := make([]*Milestone, 0, 10)
  1061. return miles, x.Where("repo_id=?", repoID).Find(&miles)
  1062. }
  1063. // GetMilestones returns a list of milestones of given repository and status.
  1064. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1065. miles := make([]*Milestone, 0, setting.IssuePagingNum)
  1066. sess := x.Where("repo_id=? AND is_closed=?", repoID, isClosed)
  1067. if page > 0 {
  1068. sess = sess.Limit(setting.IssuePagingNum, (page-1)*setting.IssuePagingNum)
  1069. }
  1070. return miles, sess.Find(&miles)
  1071. }
  1072. func updateMilestone(e Engine, m *Milestone) error {
  1073. _, err := e.Id(m.ID).AllCols().Update(m)
  1074. return err
  1075. }
  1076. // UpdateMilestone updates information of given milestone.
  1077. func UpdateMilestone(m *Milestone) error {
  1078. return updateMilestone(x, m)
  1079. }
  1080. func countRepoMilestones(e Engine, repoID int64) int64 {
  1081. count, _ := e.Where("repo_id=?", repoID).Count(new(Milestone))
  1082. return count
  1083. }
  1084. // CountRepoMilestones returns number of milestones in given repository.
  1085. func CountRepoMilestones(repoID int64) int64 {
  1086. return countRepoMilestones(x, repoID)
  1087. }
  1088. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1089. closed, _ := e.Where("repo_id=? AND is_closed=?", repoID, true).Count(new(Milestone))
  1090. return closed
  1091. }
  1092. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1093. func CountRepoClosedMilestones(repoID int64) int64 {
  1094. return countRepoClosedMilestones(x, repoID)
  1095. }
  1096. // MilestoneStats returns number of open and closed milestones of given repository.
  1097. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1098. open, _ = x.Where("repo_id=? AND is_closed=?", repoID, false).Count(new(Milestone))
  1099. return open, CountRepoClosedMilestones(repoID)
  1100. }
  1101. // ChangeMilestoneStatus changes the milestone open/closed status.
  1102. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1103. repo, err := GetRepositoryByID(m.RepoID)
  1104. if err != nil {
  1105. return err
  1106. }
  1107. sess := x.NewSession()
  1108. defer sessionRelease(sess)
  1109. if err = sess.Begin(); err != nil {
  1110. return err
  1111. }
  1112. m.IsClosed = isClosed
  1113. if err = updateMilestone(sess, m); err != nil {
  1114. return err
  1115. }
  1116. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1117. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1118. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1119. return err
  1120. }
  1121. return sess.Commit()
  1122. }
  1123. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1124. if issue.MilestoneID == 0 {
  1125. return nil
  1126. }
  1127. m, err := getMilestoneByID(e, issue.MilestoneID)
  1128. if err != nil {
  1129. return err
  1130. }
  1131. if issue.IsClosed {
  1132. m.NumOpenIssues--
  1133. m.NumClosedIssues++
  1134. } else {
  1135. m.NumOpenIssues++
  1136. m.NumClosedIssues--
  1137. }
  1138. return updateMilestone(e, m)
  1139. }
  1140. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1141. // for the milestone associated with the given issue.
  1142. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1143. sess := x.NewSession()
  1144. defer sessionRelease(sess)
  1145. if err = sess.Begin(); err != nil {
  1146. return err
  1147. }
  1148. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1149. return err
  1150. }
  1151. return sess.Commit()
  1152. }
  1153. func changeMilestoneAssign(e *xorm.Session, oldMid int64, issue *Issue) error {
  1154. if oldMid > 0 {
  1155. m, err := getMilestoneByID(e, oldMid)
  1156. if err != nil {
  1157. return err
  1158. }
  1159. m.NumIssues--
  1160. if issue.IsClosed {
  1161. m.NumClosedIssues--
  1162. }
  1163. if err = updateMilestone(e, m); err != nil {
  1164. return err
  1165. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE issue_id=?", issue.ID); err != nil {
  1166. return err
  1167. }
  1168. }
  1169. if issue.MilestoneID > 0 {
  1170. m, err := getMilestoneByID(e, issue.MilestoneID)
  1171. if err != nil {
  1172. return err
  1173. }
  1174. m.NumIssues++
  1175. if issue.IsClosed {
  1176. m.NumClosedIssues++
  1177. }
  1178. if m.NumIssues == 0 {
  1179. return ErrWrongIssueCounter
  1180. }
  1181. if err = updateMilestone(e, m); err != nil {
  1182. return err
  1183. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id=? WHERE issue_id=?", m.ID, issue.ID); err != nil {
  1184. return err
  1185. }
  1186. }
  1187. return updateIssue(e, issue)
  1188. }
  1189. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1190. func ChangeMilestoneAssign(oldMid int64, issue *Issue) (err error) {
  1191. sess := x.NewSession()
  1192. defer sess.Close()
  1193. if err = sess.Begin(); err != nil {
  1194. return err
  1195. }
  1196. if err = changeMilestoneAssign(sess, oldMid, issue); err != nil {
  1197. return err
  1198. }
  1199. return sess.Commit()
  1200. }
  1201. // DeleteMilestoneByID deletes a milestone by given ID.
  1202. func DeleteMilestoneByID(id int64) error {
  1203. m, err := GetMilestoneByID(id)
  1204. if err != nil {
  1205. if IsErrMilestoneNotExist(err) {
  1206. return nil
  1207. }
  1208. return err
  1209. }
  1210. repo, err := GetRepositoryByID(m.RepoID)
  1211. if err != nil {
  1212. return err
  1213. }
  1214. sess := x.NewSession()
  1215. defer sessionRelease(sess)
  1216. if err = sess.Begin(); err != nil {
  1217. return err
  1218. }
  1219. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1220. return err
  1221. }
  1222. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1223. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1224. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1225. return err
  1226. }
  1227. if _, err = sess.Exec("UPDATE `issue` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1228. return err
  1229. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id=0 WHERE milestone_id=?", m.ID); err != nil {
  1230. return err
  1231. }
  1232. return sess.Commit()
  1233. }
  1234. // _________ __
  1235. // \_ ___ \ ____ _____ _____ ____ _____/ |_
  1236. // / \ \/ / _ \ / \ / \_/ __ \ / \ __\
  1237. // \ \___( <_> ) Y Y \ Y Y \ ___/| | \ |
  1238. // \______ /\____/|__|_| /__|_| /\___ >___| /__|
  1239. // \/ \/ \/ \/ \/
  1240. // CommentType defines whether a comment is just a simple comment, an action (like close) or a reference.
  1241. type CommentType int
  1242. const (
  1243. // Plain comment, can be associated with a commit (CommitId > 0) and a line (Line > 0)
  1244. COMMENT_TYPE_COMMENT CommentType = iota
  1245. COMMENT_TYPE_REOPEN
  1246. COMMENT_TYPE_CLOSE
  1247. // References.
  1248. COMMENT_TYPE_ISSUE_REF
  1249. // Reference from a commit (not part of a pull request)
  1250. COMMENT_TYPE_COMMIT_REF
  1251. // Reference from a comment
  1252. COMMENT_TYPE_COMMENT_REF
  1253. // Reference from a pull request
  1254. COMMENT_TYPE_PULL_REF
  1255. )
  1256. type CommentTag int
  1257. const (
  1258. COMMENT_TAG_NONE CommentTag = iota
  1259. COMMENT_TAG_POSTER
  1260. COMMENT_TAG_ADMIN
  1261. COMMENT_TAG_OWNER
  1262. )
  1263. // Comment represents a comment in commit and issue page.
  1264. type Comment struct {
  1265. ID int64 `xorm:"pk autoincr"`
  1266. Type CommentType
  1267. PosterID int64
  1268. Poster *User `xorm:"-"`
  1269. IssueID int64 `xorm:"INDEX"`
  1270. CommitID int64
  1271. Line int64
  1272. Content string `xorm:"TEXT"`
  1273. RenderedContent string `xorm:"-"`
  1274. Created time.Time `xorm:"CREATED"`
  1275. // Reference issue in commit message
  1276. CommitSHA string `xorm:"VARCHAR(40)"`
  1277. Attachments []*Attachment `xorm:"-"`
  1278. // For view issue page.
  1279. ShowTag CommentTag `xorm:"-"`
  1280. }
  1281. func (c *Comment) AfterSet(colName string, _ xorm.Cell) {
  1282. var err error
  1283. switch colName {
  1284. case "id":
  1285. c.Attachments, err = GetAttachmentsByCommentID(c.ID)
  1286. if err != nil {
  1287. log.Error(3, "GetAttachmentsByCommentID[%d]: %v", c.ID, err)
  1288. }
  1289. case "poster_id":
  1290. c.Poster, err = GetUserByID(c.PosterID)
  1291. if err != nil {
  1292. if IsErrUserNotExist(err) {
  1293. c.PosterID = -1
  1294. c.Poster = NewFakeUser()
  1295. } else {
  1296. log.Error(3, "GetUserByID[%d]: %v", c.ID, err)
  1297. }
  1298. }
  1299. case "created":
  1300. c.Created = regulateTimeZone(c.Created)
  1301. }
  1302. }
  1303. func (c *Comment) AfterDelete() {
  1304. _, err := DeleteAttachmentsByComment(c.ID, true)
  1305. if err != nil {
  1306. log.Info("Could not delete files for comment %d on issue #%d: %s", c.ID, c.IssueID, err)
  1307. }
  1308. }
  1309. // HashTag returns unique hash tag for comment.
  1310. func (c *Comment) HashTag() string {
  1311. return "issuecomment-" + com.ToStr(c.ID)
  1312. }
  1313. // EventTag returns unique event hash tag for comment.
  1314. func (c *Comment) EventTag() string {
  1315. return "event-" + com.ToStr(c.ID)
  1316. }
  1317. func createComment(e *xorm.Session, u *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, uuids []string) (_ *Comment, err error) {
  1318. comment := &Comment{
  1319. PosterID: u.Id,
  1320. Type: cmtType,
  1321. IssueID: issue.ID,
  1322. CommitID: commitID,
  1323. Line: line,
  1324. Content: content,
  1325. CommitSHA: commitSHA,
  1326. }
  1327. if _, err = e.Insert(comment); err != nil {
  1328. return nil, err
  1329. }
  1330. // Compose comment action, could be plain comment, close or reopen issue.
  1331. // This object will be used to notify watchers in the end of function.
  1332. act := &Action{
  1333. ActUserID: u.Id,
  1334. ActUserName: u.Name,
  1335. ActEmail: u.Email,
  1336. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  1337. RepoID: repo.ID,
  1338. RepoUserName: repo.Owner.Name,
  1339. RepoName: repo.Name,
  1340. IsPrivate: repo.IsPrivate,
  1341. }
  1342. // Check comment type.
  1343. switch cmtType {
  1344. case COMMENT_TYPE_COMMENT:
  1345. act.OpType = ACTION_COMMENT_ISSUE
  1346. if _, err = e.Exec("UPDATE `issue` SET num_comments=num_comments+1 WHERE id=?", issue.ID); err != nil {
  1347. return nil, err
  1348. }
  1349. // Check attachments.
  1350. attachments := make([]*Attachment, 0, len(uuids))
  1351. for _, uuid := range uuids {
  1352. attach, err := getAttachmentByUUID(e, uuid)
  1353. if err != nil {
  1354. if IsErrAttachmentNotExist(err) {
  1355. continue
  1356. }
  1357. return nil, fmt.Errorf("getAttachmentByUUID[%s]: %v", uuid, err)
  1358. }
  1359. attachments = append(attachments, attach)
  1360. }
  1361. for i := range attachments {
  1362. attachments[i].IssueID = issue.ID
  1363. attachments[i].CommentID = comment.ID
  1364. // No assign value could be 0, so ignore AllCols().
  1365. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  1366. return nil, fmt.Errorf("update attachment[%d]: %v", attachments[i].ID, err)
  1367. }
  1368. }
  1369. case COMMENT_TYPE_REOPEN:
  1370. act.OpType = ACTION_REOPEN_ISSUE
  1371. if issue.IsPull {
  1372. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls-1 WHERE id=?", repo.ID)
  1373. } else {
  1374. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues-1 WHERE id=?", repo.ID)
  1375. }
  1376. if err != nil {
  1377. return nil, err
  1378. }
  1379. case COMMENT_TYPE_CLOSE:
  1380. act.OpType = ACTION_CLOSE_ISSUE
  1381. if issue.IsPull {
  1382. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=num_closed_pulls+1 WHERE id=?", repo.ID)
  1383. } else {
  1384. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=num_closed_issues+1 WHERE id=?", repo.ID)
  1385. }
  1386. if err != nil {
  1387. return nil, err
  1388. }
  1389. }
  1390. // Notify watchers for whatever action comes in.
  1391. if err = notifyWatchers(e, act); err != nil {
  1392. return nil, fmt.Errorf("notifyWatchers: %v", err)
  1393. }
  1394. return comment, nil
  1395. }
  1396. func createStatusComment(e *xorm.Session, doer *User, repo *Repository, issue *Issue) (*Comment, error) {
  1397. cmtType := COMMENT_TYPE_CLOSE
  1398. if !issue.IsClosed {
  1399. cmtType = COMMENT_TYPE_REOPEN
  1400. }
  1401. return createComment(e, doer, repo, issue, 0, 0, cmtType, "", "", nil)
  1402. }
  1403. // CreateComment creates comment of issue or commit.
  1404. func CreateComment(doer *User, repo *Repository, issue *Issue, commitID, line int64, cmtType CommentType, content, commitSHA string, attachments []string) (comment *Comment, err error) {
  1405. sess := x.NewSession()
  1406. defer sessionRelease(sess)
  1407. if err = sess.Begin(); err != nil {
  1408. return nil, err
  1409. }
  1410. comment, err = createComment(sess, doer, repo, issue, commitID, line, cmtType, content, commitSHA, attachments)
  1411. if err != nil {
  1412. return nil, err
  1413. }
  1414. return comment, sess.Commit()
  1415. }
  1416. // CreateIssueComment creates a plain issue comment.
  1417. func CreateIssueComment(doer *User, repo *Repository, issue *Issue, content string, attachments []string) (*Comment, error) {
  1418. return CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMENT, content, "", attachments)
  1419. }
  1420. // CreateRefComment creates a commit reference comment to issue.
  1421. func CreateRefComment(doer *User, repo *Repository, issue *Issue, content, commitSHA string) error {
  1422. if len(commitSHA) == 0 {
  1423. return fmt.Errorf("cannot create reference with empty commit SHA")
  1424. }
  1425. // Check if same reference from same commit has already existed.
  1426. has, err := x.Get(&Comment{
  1427. Type: COMMENT_TYPE_COMMIT_REF,
  1428. IssueID: issue.ID,
  1429. CommitSHA: commitSHA,
  1430. })
  1431. if err != nil {
  1432. return fmt.Errorf("check reference comment: %v", err)
  1433. } else if has {
  1434. return nil
  1435. }
  1436. _, err = CreateComment(doer, repo, issue, 0, 0, COMMENT_TYPE_COMMIT_REF, content, commitSHA, nil)
  1437. return err
  1438. }
  1439. // GetCommentByID returns the comment by given ID.
  1440. func GetCommentByID(id int64) (*Comment, error) {
  1441. c := new(Comment)
  1442. has, err := x.Id(id).Get(c)
  1443. if err != nil {
  1444. return nil, err
  1445. } else if !has {
  1446. return nil, ErrCommentNotExist{id}
  1447. }
  1448. return c, nil
  1449. }
  1450. // GetCommentsByIssueID returns all comments of issue by given ID.
  1451. func GetCommentsByIssueID(issueID int64) ([]*Comment, error) {
  1452. comments := make([]*Comment, 0, 10)
  1453. return comments, x.Where("issue_id=?", issueID).Asc("created").Find(&comments)
  1454. }
  1455. // UpdateComment updates information of comment.
  1456. func UpdateComment(c *Comment) error {
  1457. _, err := x.Id(c.ID).AllCols().Update(c)
  1458. return err
  1459. }
  1460. // Attachment represent a attachment of issue/comment/release.
  1461. type Attachment struct {
  1462. ID int64 `xorm:"pk autoincr"`
  1463. UUID string `xorm:"uuid UNIQUE"`
  1464. IssueID int64 `xorm:"INDEX"`
  1465. CommentID int64
  1466. ReleaseID int64 `xorm:"INDEX"`
  1467. Name string
  1468. Created time.Time `xorm:"CREATED"`
  1469. }
  1470. // AttachmentLocalPath returns where attachment is stored in local file system based on given UUID.
  1471. func AttachmentLocalPath(uuid string) string {
  1472. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1473. }
  1474. // LocalPath returns where attachment is stored in local file system.
  1475. func (attach *Attachment) LocalPath() string {
  1476. return AttachmentLocalPath(attach.UUID)
  1477. }
  1478. // NewAttachment creates a new attachment object.
  1479. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1480. attach := &Attachment{
  1481. UUID: gouuid.NewV4().String(),
  1482. Name: name,
  1483. }
  1484. if err = os.MkdirAll(path.Dir(attach.LocalPath()), os.ModePerm); err != nil {
  1485. return nil, fmt.Errorf("MkdirAll: %v", err)
  1486. }
  1487. fw, err := os.Create(attach.LocalPath())
  1488. if err != nil {
  1489. return nil, fmt.Errorf("Create: %v", err)
  1490. }
  1491. defer fw.Close()
  1492. if _, err = fw.Write(buf); err != nil {
  1493. return nil, fmt.Errorf("Write: %v", err)
  1494. } else if _, err = io.Copy(fw, file); err != nil {
  1495. return nil, fmt.Errorf("Copy: %v", err)
  1496. }
  1497. sess := x.NewSession()
  1498. defer sessionRelease(sess)
  1499. if err := sess.Begin(); err != nil {
  1500. return nil, err
  1501. }
  1502. if _, err := sess.Insert(attach); err != nil {
  1503. return nil, err
  1504. }
  1505. return attach, sess.Commit()
  1506. }
  1507. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1508. attach := &Attachment{UUID: uuid}
  1509. has, err := x.Get(attach)
  1510. if err != nil {
  1511. return nil, err
  1512. } else if !has {
  1513. return nil, ErrAttachmentNotExist{0, uuid}
  1514. }
  1515. return attach, nil
  1516. }
  1517. // GetAttachmentByUUID returns attachment by given UUID.
  1518. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1519. return getAttachmentByUUID(x, uuid)
  1520. }
  1521. // GetAttachmentsByIssueID returns all attachments for given issue by ID.
  1522. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1523. attachments := make([]*Attachment, 0, 10)
  1524. return attachments, x.Where("issue_id=? AND comment_id=0", issueID).Find(&attachments)
  1525. }
  1526. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1527. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1528. attachments := make([]*Attachment, 0, 10)
  1529. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1530. }
  1531. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1532. func DeleteAttachment(a *Attachment, remove bool) error {
  1533. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1534. return err
  1535. }
  1536. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1537. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1538. for i, a := range attachments {
  1539. if remove {
  1540. if err := os.Remove(a.LocalPath()); err != nil {
  1541. return i, err
  1542. }
  1543. }
  1544. if _, err := x.Delete(a.ID); err != nil {
  1545. return i, err
  1546. }
  1547. }
  1548. return len(attachments), nil
  1549. }
  1550. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1551. func DeleteAttachmentsByIssue(issueId int64, remove bool) (int, error) {
  1552. attachments, err := GetAttachmentsByIssueID(issueId)
  1553. if err != nil {
  1554. return 0, err
  1555. }
  1556. return DeleteAttachments(attachments, remove)
  1557. }
  1558. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1559. func DeleteAttachmentsByComment(commentId int64, remove bool) (int, error) {
  1560. attachments, err := GetAttachmentsByCommentID(commentId)
  1561. if err != nil {
  1562. return 0, err
  1563. }
  1564. return DeleteAttachments(attachments, remove)
  1565. }