1// Copyright 2014 The Gogs Authors. All rights reserved. 2// Copyright 2020 The Gitea Authors. All rights reserved. 3// Use of this source code is governed by a MIT-style 4// license that can be found in the LICENSE file. 5 6package models 7 8import ( 9 "context" 10 "fmt" 11 "regexp" 12 "sort" 13 "strconv" 14 "strings" 15 16 "code.gitea.io/gitea/models/db" 17 "code.gitea.io/gitea/models/issues" 18 "code.gitea.io/gitea/models/perm" 19 repo_model "code.gitea.io/gitea/models/repo" 20 "code.gitea.io/gitea/models/unit" 21 user_model "code.gitea.io/gitea/models/user" 22 "code.gitea.io/gitea/modules/base" 23 "code.gitea.io/gitea/modules/git" 24 "code.gitea.io/gitea/modules/log" 25 "code.gitea.io/gitea/modules/references" 26 api "code.gitea.io/gitea/modules/structs" 27 "code.gitea.io/gitea/modules/timeutil" 28 "code.gitea.io/gitea/modules/util" 29 30 "xorm.io/builder" 31 "xorm.io/xorm" 32) 33 34// Issue represents an issue or pull request of repository. 35type Issue struct { 36 ID int64 `xorm:"pk autoincr"` 37 RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"` 38 Repo *repo_model.Repository `xorm:"-"` 39 Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository. 40 PosterID int64 `xorm:"INDEX"` 41 Poster *user_model.User `xorm:"-"` 42 OriginalAuthor string 43 OriginalAuthorID int64 `xorm:"index"` 44 Title string `xorm:"name"` 45 Content string `xorm:"LONGTEXT"` 46 RenderedContent string `xorm:"-"` 47 Labels []*Label `xorm:"-"` 48 MilestoneID int64 `xorm:"INDEX"` 49 Milestone *Milestone `xorm:"-"` 50 Project *Project `xorm:"-"` 51 Priority int 52 AssigneeID int64 `xorm:"-"` 53 Assignee *user_model.User `xorm:"-"` 54 IsClosed bool `xorm:"INDEX"` 55 IsRead bool `xorm:"-"` 56 IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not. 57 PullRequest *PullRequest `xorm:"-"` 58 NumComments int 59 Ref string 60 61 DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"` 62 63 CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"` 64 UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"` 65 ClosedUnix timeutil.TimeStamp `xorm:"INDEX"` 66 67 Attachments []*repo_model.Attachment `xorm:"-"` 68 Comments []*Comment `xorm:"-"` 69 Reactions ReactionList `xorm:"-"` 70 TotalTrackedTime int64 `xorm:"-"` 71 Assignees []*user_model.User `xorm:"-"` 72 73 // IsLocked limits commenting abilities to users on an issue 74 // with write access 75 IsLocked bool `xorm:"NOT NULL DEFAULT false"` 76 77 // For view issue page. 78 ShowRole RoleDescriptor `xorm:"-"` 79} 80 81var ( 82 issueTasksPat *regexp.Regexp 83 issueTasksDonePat *regexp.Regexp 84) 85 86const ( 87 issueTasksRegexpStr = `(^\s*[-*]\s\[[\sxX]\]\s.)|(\n\s*[-*]\s\[[\sxX]\]\s.)` 88 issueTasksDoneRegexpStr = `(^\s*[-*]\s\[[xX]\]\s.)|(\n\s*[-*]\s\[[xX]\]\s.)` 89) 90 91// IssueIndex represents the issue index table 92type IssueIndex db.ResourceIndex 93 94func init() { 95 issueTasksPat = regexp.MustCompile(issueTasksRegexpStr) 96 issueTasksDonePat = regexp.MustCompile(issueTasksDoneRegexpStr) 97 98 db.RegisterModel(new(Issue)) 99 db.RegisterModel(new(IssueIndex)) 100} 101 102func (issue *Issue) loadTotalTimes(e db.Engine) (err error) { 103 opts := FindTrackedTimesOptions{IssueID: issue.ID} 104 issue.TotalTrackedTime, err = opts.toSession(e).SumInt(&TrackedTime{}, "time") 105 if err != nil { 106 return err 107 } 108 return nil 109} 110 111// IsOverdue checks if the issue is overdue 112func (issue *Issue) IsOverdue() bool { 113 if issue.IsClosed { 114 return issue.ClosedUnix >= issue.DeadlineUnix 115 } 116 return timeutil.TimeStampNow() >= issue.DeadlineUnix 117} 118 119// LoadRepo loads issue's repository 120func (issue *Issue) LoadRepo() error { 121 return issue.loadRepo(db.DefaultContext) 122} 123 124func (issue *Issue) loadRepo(ctx context.Context) (err error) { 125 if issue.Repo == nil { 126 issue.Repo, err = repo_model.GetRepositoryByIDCtx(ctx, issue.RepoID) 127 if err != nil { 128 return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err) 129 } 130 } 131 return nil 132} 133 134// IsTimetrackerEnabled returns true if the repo enables timetracking 135func (issue *Issue) IsTimetrackerEnabled() bool { 136 return issue.isTimetrackerEnabled(db.DefaultContext) 137} 138 139func (issue *Issue) isTimetrackerEnabled(ctx context.Context) bool { 140 if err := issue.loadRepo(ctx); err != nil { 141 log.Error(fmt.Sprintf("loadRepo: %v", err)) 142 return false 143 } 144 return issue.Repo.IsTimetrackerEnabledCtx(ctx) 145} 146 147// GetPullRequest returns the issue pull request 148func (issue *Issue) GetPullRequest() (pr *PullRequest, err error) { 149 if !issue.IsPull { 150 return nil, fmt.Errorf("Issue is not a pull request") 151 } 152 153 pr, err = getPullRequestByIssueID(db.GetEngine(db.DefaultContext), issue.ID) 154 if err != nil { 155 return nil, err 156 } 157 pr.Issue = issue 158 return 159} 160 161// LoadLabels loads labels 162func (issue *Issue) LoadLabels() error { 163 return issue.loadLabels(db.GetEngine(db.DefaultContext)) 164} 165 166func (issue *Issue) loadLabels(e db.Engine) (err error) { 167 if issue.Labels == nil { 168 issue.Labels, err = getLabelsByIssueID(e, issue.ID) 169 if err != nil { 170 return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err) 171 } 172 } 173 return nil 174} 175 176// LoadPoster loads poster 177func (issue *Issue) LoadPoster() error { 178 return issue.loadPoster(db.GetEngine(db.DefaultContext)) 179} 180 181func (issue *Issue) loadPoster(e db.Engine) (err error) { 182 if issue.Poster == nil { 183 issue.Poster, err = user_model.GetUserByIDEngine(e, issue.PosterID) 184 if err != nil { 185 issue.PosterID = -1 186 issue.Poster = user_model.NewGhostUser() 187 if !user_model.IsErrUserNotExist(err) { 188 return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err) 189 } 190 err = nil 191 return 192 } 193 } 194 return 195} 196 197func (issue *Issue) loadPullRequest(e db.Engine) (err error) { 198 if issue.IsPull && issue.PullRequest == nil { 199 issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID) 200 if err != nil { 201 if IsErrPullRequestNotExist(err) { 202 return err 203 } 204 return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err) 205 } 206 issue.PullRequest.Issue = issue 207 } 208 return nil 209} 210 211// LoadPullRequest loads pull request info 212func (issue *Issue) LoadPullRequest() error { 213 return issue.loadPullRequest(db.GetEngine(db.DefaultContext)) 214} 215 216func (issue *Issue) loadComments(e db.Engine) (err error) { 217 return issue.loadCommentsByType(e, CommentTypeUnknown) 218} 219 220// LoadDiscussComments loads discuss comments 221func (issue *Issue) LoadDiscussComments() error { 222 return issue.loadCommentsByType(db.GetEngine(db.DefaultContext), CommentTypeComment) 223} 224 225func (issue *Issue) loadCommentsByType(e db.Engine, tp CommentType) (err error) { 226 if issue.Comments != nil { 227 return nil 228 } 229 issue.Comments, err = findComments(e, &FindCommentsOptions{ 230 IssueID: issue.ID, 231 Type: tp, 232 }) 233 return err 234} 235 236func (issue *Issue) loadReactions(ctx context.Context) (err error) { 237 if issue.Reactions != nil { 238 return nil 239 } 240 e := db.GetEngine(ctx) 241 reactions, _, err := findReactions(e, FindReactionsOptions{ 242 IssueID: issue.ID, 243 }) 244 if err != nil { 245 return err 246 } 247 if err = issue.loadRepo(ctx); err != nil { 248 return err 249 } 250 // Load reaction user data 251 if _, err := ReactionList(reactions).loadUsers(e, issue.Repo); err != nil { 252 return err 253 } 254 255 // Cache comments to map 256 comments := make(map[int64]*Comment) 257 for _, comment := range issue.Comments { 258 comments[comment.ID] = comment 259 } 260 // Add reactions either to issue or comment 261 for _, react := range reactions { 262 if react.CommentID == 0 { 263 issue.Reactions = append(issue.Reactions, react) 264 } else if comment, ok := comments[react.CommentID]; ok { 265 comment.Reactions = append(comment.Reactions, react) 266 } 267 } 268 return nil 269} 270 271func (issue *Issue) loadMilestone(e db.Engine) (err error) { 272 if (issue.Milestone == nil || issue.Milestone.ID != issue.MilestoneID) && issue.MilestoneID > 0 { 273 issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID) 274 if err != nil && !IsErrMilestoneNotExist(err) { 275 return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err) 276 } 277 } 278 return nil 279} 280 281func (issue *Issue) loadAttributes(ctx context.Context) (err error) { 282 e := db.GetEngine(ctx) 283 if err = issue.loadRepo(ctx); err != nil { 284 return 285 } 286 287 if err = issue.loadPoster(e); err != nil { 288 return 289 } 290 291 if err = issue.loadLabels(e); err != nil { 292 return 293 } 294 295 if err = issue.loadMilestone(e); err != nil { 296 return 297 } 298 299 if err = issue.loadProject(e); err != nil { 300 return 301 } 302 303 if err = issue.loadAssignees(e); err != nil { 304 return 305 } 306 307 if err = issue.loadPullRequest(e); err != nil && !IsErrPullRequestNotExist(err) { 308 // It is possible pull request is not yet created. 309 return err 310 } 311 312 if issue.Attachments == nil { 313 issue.Attachments, err = repo_model.GetAttachmentsByIssueIDCtx(ctx, issue.ID) 314 if err != nil { 315 return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err) 316 } 317 } 318 319 if err = issue.loadComments(e); err != nil { 320 return err 321 } 322 323 if err = CommentList(issue.Comments).loadAttributes(ctx); err != nil { 324 return err 325 } 326 if issue.isTimetrackerEnabled(ctx) { 327 if err = issue.loadTotalTimes(e); err != nil { 328 return err 329 } 330 } 331 332 return issue.loadReactions(ctx) 333} 334 335// LoadAttributes loads the attribute of this issue. 336func (issue *Issue) LoadAttributes() error { 337 return issue.loadAttributes(db.DefaultContext) 338} 339 340// LoadMilestone load milestone of this issue. 341func (issue *Issue) LoadMilestone() error { 342 return issue.loadMilestone(db.GetEngine(db.DefaultContext)) 343} 344 345// GetIsRead load the `IsRead` field of the issue 346func (issue *Issue) GetIsRead(userID int64) error { 347 issueUser := &IssueUser{IssueID: issue.ID, UID: userID} 348 if has, err := db.GetEngine(db.DefaultContext).Get(issueUser); err != nil { 349 return err 350 } else if !has { 351 issue.IsRead = false 352 return nil 353 } 354 issue.IsRead = issueUser.IsRead 355 return nil 356} 357 358// APIURL returns the absolute APIURL to this issue. 359func (issue *Issue) APIURL() string { 360 if issue.Repo == nil { 361 err := issue.LoadRepo() 362 if err != nil { 363 log.Error("Issue[%d].APIURL(): %v", issue.ID, err) 364 return "" 365 } 366 } 367 return fmt.Sprintf("%s/issues/%d", issue.Repo.APIURL(), issue.Index) 368} 369 370// HTMLURL returns the absolute URL to this issue. 371func (issue *Issue) HTMLURL() string { 372 var path string 373 if issue.IsPull { 374 path = "pulls" 375 } else { 376 path = "issues" 377 } 378 return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index) 379} 380 381// Link returns the Link URL to this issue. 382func (issue *Issue) Link() string { 383 var path string 384 if issue.IsPull { 385 path = "pulls" 386 } else { 387 path = "issues" 388 } 389 return fmt.Sprintf("%s/%s/%d", issue.Repo.Link(), path, issue.Index) 390} 391 392// DiffURL returns the absolute URL to this diff 393func (issue *Issue) DiffURL() string { 394 if issue.IsPull { 395 return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index) 396 } 397 return "" 398} 399 400// PatchURL returns the absolute URL to this patch 401func (issue *Issue) PatchURL() string { 402 if issue.IsPull { 403 return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index) 404 } 405 return "" 406} 407 408// State returns string representation of issue status. 409func (issue *Issue) State() api.StateType { 410 if issue.IsClosed { 411 return api.StateClosed 412 } 413 return api.StateOpen 414} 415 416// HashTag returns unique hash tag for issue. 417func (issue *Issue) HashTag() string { 418 return fmt.Sprintf("issue-%d", issue.ID) 419} 420 421// IsPoster returns true if given user by ID is the poster. 422func (issue *Issue) IsPoster(uid int64) bool { 423 return issue.OriginalAuthorID == 0 && issue.PosterID == uid 424} 425 426func (issue *Issue) hasLabel(e db.Engine, labelID int64) bool { 427 return hasIssueLabel(e, issue.ID, labelID) 428} 429 430// HasLabel returns true if issue has been labeled by given ID. 431func (issue *Issue) HasLabel(labelID int64) bool { 432 return issue.hasLabel(db.GetEngine(db.DefaultContext), labelID) 433} 434 435func (issue *Issue) addLabel(ctx context.Context, label *Label, doer *user_model.User) error { 436 return newIssueLabel(ctx, issue, label, doer) 437} 438 439func (issue *Issue) addLabels(ctx context.Context, labels []*Label, doer *user_model.User) error { 440 return newIssueLabels(ctx, issue, labels, doer) 441} 442 443func (issue *Issue) getLabels(e db.Engine) (err error) { 444 if len(issue.Labels) > 0 { 445 return nil 446 } 447 448 issue.Labels, err = getLabelsByIssueID(e, issue.ID) 449 if err != nil { 450 return fmt.Errorf("getLabelsByIssueID: %v", err) 451 } 452 return nil 453} 454 455func (issue *Issue) removeLabel(ctx context.Context, doer *user_model.User, label *Label) error { 456 return deleteIssueLabel(ctx, issue, label, doer) 457} 458 459func (issue *Issue) clearLabels(ctx context.Context, doer *user_model.User) (err error) { 460 if err = issue.getLabels(db.GetEngine(ctx)); err != nil { 461 return fmt.Errorf("getLabels: %v", err) 462 } 463 464 for i := range issue.Labels { 465 if err = issue.removeLabel(ctx, doer, issue.Labels[i]); err != nil { 466 return fmt.Errorf("removeLabel: %v", err) 467 } 468 } 469 470 return nil 471} 472 473// ClearLabels removes all issue labels as the given user. 474// Triggers appropriate WebHooks, if any. 475func (issue *Issue) ClearLabels(doer *user_model.User) (err error) { 476 ctx, committer, err := db.TxContext() 477 if err != nil { 478 return err 479 } 480 defer committer.Close() 481 482 if err := issue.loadRepo(ctx); err != nil { 483 return err 484 } else if err = issue.loadPullRequest(db.GetEngine(ctx)); err != nil { 485 return err 486 } 487 488 perm, err := getUserRepoPermission(ctx, issue.Repo, doer) 489 if err != nil { 490 return err 491 } 492 if !perm.CanWriteIssuesOrPulls(issue.IsPull) { 493 return ErrRepoLabelNotExist{} 494 } 495 496 if err = issue.clearLabels(ctx, doer); err != nil { 497 return err 498 } 499 500 if err = committer.Commit(); err != nil { 501 return fmt.Errorf("Commit: %v", err) 502 } 503 504 return nil 505} 506 507type labelSorter []*Label 508 509func (ts labelSorter) Len() int { 510 return len([]*Label(ts)) 511} 512 513func (ts labelSorter) Less(i, j int) bool { 514 return []*Label(ts)[i].ID < []*Label(ts)[j].ID 515} 516 517func (ts labelSorter) Swap(i, j int) { 518 []*Label(ts)[i], []*Label(ts)[j] = []*Label(ts)[j], []*Label(ts)[i] 519} 520 521// ReplaceLabels removes all current labels and add new labels to the issue. 522// Triggers appropriate WebHooks, if any. 523func (issue *Issue) ReplaceLabels(labels []*Label, doer *user_model.User) (err error) { 524 ctx, committer, err := db.TxContext() 525 if err != nil { 526 return err 527 } 528 defer committer.Close() 529 530 if err = issue.loadRepo(ctx); err != nil { 531 return err 532 } 533 534 if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { 535 return err 536 } 537 538 sort.Sort(labelSorter(labels)) 539 sort.Sort(labelSorter(issue.Labels)) 540 541 var toAdd, toRemove []*Label 542 543 addIndex, removeIndex := 0, 0 544 for addIndex < len(labels) && removeIndex < len(issue.Labels) { 545 addLabel := labels[addIndex] 546 removeLabel := issue.Labels[removeIndex] 547 if addLabel.ID == removeLabel.ID { 548 // Silently drop invalid labels 549 if removeLabel.RepoID != issue.RepoID && removeLabel.OrgID != issue.Repo.OwnerID { 550 toRemove = append(toRemove, removeLabel) 551 } 552 553 addIndex++ 554 removeIndex++ 555 } else if addLabel.ID < removeLabel.ID { 556 // Only add if the label is valid 557 if addLabel.RepoID == issue.RepoID || addLabel.OrgID == issue.Repo.OwnerID { 558 toAdd = append(toAdd, addLabel) 559 } 560 addIndex++ 561 } else { 562 toRemove = append(toRemove, removeLabel) 563 removeIndex++ 564 } 565 } 566 toAdd = append(toAdd, labels[addIndex:]...) 567 toRemove = append(toRemove, issue.Labels[removeIndex:]...) 568 569 if len(toAdd) > 0 { 570 if err = issue.addLabels(ctx, toAdd, doer); err != nil { 571 return fmt.Errorf("addLabels: %v", err) 572 } 573 } 574 575 for _, l := range toRemove { 576 if err = issue.removeLabel(ctx, doer, l); err != nil { 577 return fmt.Errorf("removeLabel: %v", err) 578 } 579 } 580 581 issue.Labels = nil 582 if err = issue.loadLabels(db.GetEngine(ctx)); err != nil { 583 return err 584 } 585 586 return committer.Commit() 587} 588 589// ReadBy sets issue to be read by given user. 590func (issue *Issue) ReadBy(userID int64) error { 591 if err := UpdateIssueUserByRead(userID, issue.ID); err != nil { 592 return err 593 } 594 595 return setIssueNotificationStatusReadIfUnread(db.GetEngine(db.DefaultContext), userID, issue.ID) 596} 597 598func updateIssueCols(ctx context.Context, issue *Issue, cols ...string) error { 599 if _, err := db.GetEngine(ctx).ID(issue.ID).Cols(cols...).Update(issue); err != nil { 600 return err 601 } 602 return nil 603} 604 605func (issue *Issue) changeStatus(ctx context.Context, doer *user_model.User, isClosed, isMergePull bool) (*Comment, error) { 606 // Reload the issue 607 currentIssue, err := getIssueByID(db.GetEngine(ctx), issue.ID) 608 if err != nil { 609 return nil, err 610 } 611 612 // Nothing should be performed if current status is same as target status 613 if currentIssue.IsClosed == isClosed { 614 if !issue.IsPull { 615 return nil, ErrIssueWasClosed{ 616 ID: issue.ID, 617 } 618 } 619 return nil, ErrPullWasClosed{ 620 ID: issue.ID, 621 } 622 } 623 624 issue.IsClosed = isClosed 625 return issue.doChangeStatus(ctx, doer, isMergePull) 626} 627 628func (issue *Issue) doChangeStatus(ctx context.Context, doer *user_model.User, isMergePull bool) (*Comment, error) { 629 e := db.GetEngine(ctx) 630 // Check for open dependencies 631 if issue.IsClosed && issue.Repo.IsDependenciesEnabledCtx(ctx) { 632 // only check if dependencies are enabled and we're about to close an issue, otherwise reopening an issue would fail when there are unsatisfied dependencies 633 noDeps, err := issueNoDependenciesLeft(e, issue) 634 if err != nil { 635 return nil, err 636 } 637 638 if !noDeps { 639 return nil, ErrDependenciesLeft{issue.ID} 640 } 641 } 642 643 if issue.IsClosed { 644 issue.ClosedUnix = timeutil.TimeStampNow() 645 } else { 646 issue.ClosedUnix = 0 647 } 648 649 if err := updateIssueCols(ctx, issue, "is_closed", "closed_unix"); err != nil { 650 return nil, err 651 } 652 653 // Update issue count of labels 654 if err := issue.getLabels(e); err != nil { 655 return nil, err 656 } 657 for idx := range issue.Labels { 658 if err := updateLabelCols(e, issue.Labels[idx], "num_issues", "num_closed_issue"); err != nil { 659 return nil, err 660 } 661 } 662 663 // Update issue count of milestone 664 if issue.MilestoneID > 0 { 665 if err := updateMilestoneCounters(ctx, issue.MilestoneID); err != nil { 666 return nil, err 667 } 668 } 669 670 if err := issue.updateClosedNum(ctx); err != nil { 671 return nil, err 672 } 673 674 // New action comment 675 cmtType := CommentTypeClose 676 if !issue.IsClosed { 677 cmtType = CommentTypeReopen 678 } else if isMergePull { 679 cmtType = CommentTypeMergePull 680 } 681 682 return createComment(ctx, &CreateCommentOptions{ 683 Type: cmtType, 684 Doer: doer, 685 Repo: issue.Repo, 686 Issue: issue, 687 }) 688} 689 690// ChangeStatus changes issue status to open or closed. 691func (issue *Issue) ChangeStatus(doer *user_model.User, isClosed bool) (*Comment, error) { 692 ctx, committer, err := db.TxContext() 693 if err != nil { 694 return nil, err 695 } 696 defer committer.Close() 697 698 if err := issue.loadRepo(ctx); err != nil { 699 return nil, err 700 } 701 if err := issue.loadPoster(db.GetEngine(ctx)); err != nil { 702 return nil, err 703 } 704 705 comment, err := issue.changeStatus(ctx, doer, isClosed, false) 706 if err != nil { 707 return nil, err 708 } 709 710 if err = committer.Commit(); err != nil { 711 return nil, fmt.Errorf("Commit: %v", err) 712 } 713 714 return comment, nil 715} 716 717// ChangeTitle changes the title of this issue, as the given user. 718func (issue *Issue) ChangeTitle(doer *user_model.User, oldTitle string) (err error) { 719 ctx, committer, err := db.TxContext() 720 if err != nil { 721 return err 722 } 723 defer committer.Close() 724 725 if err = updateIssueCols(ctx, issue, "name"); err != nil { 726 return fmt.Errorf("updateIssueCols: %v", err) 727 } 728 729 if err = issue.loadRepo(ctx); err != nil { 730 return fmt.Errorf("loadRepo: %v", err) 731 } 732 733 opts := &CreateCommentOptions{ 734 Type: CommentTypeChangeTitle, 735 Doer: doer, 736 Repo: issue.Repo, 737 Issue: issue, 738 OldTitle: oldTitle, 739 NewTitle: issue.Title, 740 } 741 if _, err = createComment(ctx, opts); err != nil { 742 return fmt.Errorf("createComment: %v", err) 743 } 744 if err = issue.addCrossReferences(ctx, doer, true); err != nil { 745 return err 746 } 747 748 return committer.Commit() 749} 750 751// ChangeRef changes the branch of this issue, as the given user. 752func (issue *Issue) ChangeRef(doer *user_model.User, oldRef string) (err error) { 753 ctx, committer, err := db.TxContext() 754 if err != nil { 755 return err 756 } 757 defer committer.Close() 758 759 if err = updateIssueCols(ctx, issue, "ref"); err != nil { 760 return fmt.Errorf("updateIssueCols: %v", err) 761 } 762 763 if err = issue.loadRepo(ctx); err != nil { 764 return fmt.Errorf("loadRepo: %v", err) 765 } 766 oldRefFriendly := strings.TrimPrefix(oldRef, git.BranchPrefix) 767 newRefFriendly := strings.TrimPrefix(issue.Ref, git.BranchPrefix) 768 769 opts := &CreateCommentOptions{ 770 Type: CommentTypeChangeIssueRef, 771 Doer: doer, 772 Repo: issue.Repo, 773 Issue: issue, 774 OldRef: oldRefFriendly, 775 NewRef: newRefFriendly, 776 } 777 if _, err = createComment(ctx, opts); err != nil { 778 return fmt.Errorf("createComment: %v", err) 779 } 780 781 return committer.Commit() 782} 783 784// AddDeletePRBranchComment adds delete branch comment for pull request issue 785func AddDeletePRBranchComment(doer *user_model.User, repo *repo_model.Repository, issueID int64, branchName string) error { 786 issue, err := getIssueByID(db.GetEngine(db.DefaultContext), issueID) 787 if err != nil { 788 return err 789 } 790 ctx, committer, err := db.TxContext() 791 if err != nil { 792 return err 793 } 794 defer committer.Close() 795 opts := &CreateCommentOptions{ 796 Type: CommentTypeDeleteBranch, 797 Doer: doer, 798 Repo: repo, 799 Issue: issue, 800 OldRef: branchName, 801 } 802 if _, err = createComment(ctx, opts); err != nil { 803 return err 804 } 805 806 return committer.Commit() 807} 808 809// UpdateAttachments update attachments by UUIDs for the issue 810func (issue *Issue) UpdateAttachments(uuids []string) (err error) { 811 ctx, committer, err := db.TxContext() 812 if err != nil { 813 return err 814 } 815 defer committer.Close() 816 attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, uuids) 817 if err != nil { 818 return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", uuids, err) 819 } 820 for i := 0; i < len(attachments); i++ { 821 attachments[i].IssueID = issue.ID 822 if err := repo_model.UpdateAttachmentCtx(ctx, attachments[i]); err != nil { 823 return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) 824 } 825 } 826 return committer.Commit() 827} 828 829// ChangeContent changes issue content, as the given user. 830func (issue *Issue) ChangeContent(doer *user_model.User, content string) (err error) { 831 ctx, committer, err := db.TxContext() 832 if err != nil { 833 return err 834 } 835 defer committer.Close() 836 837 hasContentHistory, err := issues.HasIssueContentHistory(ctx, issue.ID, 0) 838 if err != nil { 839 return fmt.Errorf("HasIssueContentHistory: %v", err) 840 } 841 if !hasContentHistory { 842 if err = issues.SaveIssueContentHistory(db.GetEngine(ctx), issue.PosterID, issue.ID, 0, 843 issue.CreatedUnix, issue.Content, true); err != nil { 844 return fmt.Errorf("SaveIssueContentHistory: %v", err) 845 } 846 } 847 848 issue.Content = content 849 850 if err = updateIssueCols(ctx, issue, "content"); err != nil { 851 return fmt.Errorf("UpdateIssueCols: %v", err) 852 } 853 854 if err = issues.SaveIssueContentHistory(db.GetEngine(ctx), doer.ID, issue.ID, 0, 855 timeutil.TimeStampNow(), issue.Content, false); err != nil { 856 return fmt.Errorf("SaveIssueContentHistory: %v", err) 857 } 858 859 if err = issue.addCrossReferences(ctx, doer, true); err != nil { 860 return fmt.Errorf("addCrossReferences: %v", err) 861 } 862 863 return committer.Commit() 864} 865 866// GetTasks returns the amount of tasks in the issues content 867func (issue *Issue) GetTasks() int { 868 return len(issueTasksPat.FindAllStringIndex(issue.Content, -1)) 869} 870 871// GetTasksDone returns the amount of completed tasks in the issues content 872func (issue *Issue) GetTasksDone() int { 873 return len(issueTasksDonePat.FindAllStringIndex(issue.Content, -1)) 874} 875 876// GetLastEventTimestamp returns the last user visible event timestamp, either the creation of this issue or the close. 877func (issue *Issue) GetLastEventTimestamp() timeutil.TimeStamp { 878 if issue.IsClosed { 879 return issue.ClosedUnix 880 } 881 return issue.CreatedUnix 882} 883 884// GetLastEventLabel returns the localization label for the current issue. 885func (issue *Issue) GetLastEventLabel() string { 886 if issue.IsClosed { 887 if issue.IsPull && issue.PullRequest.HasMerged { 888 return "repo.pulls.merged_by" 889 } 890 return "repo.issues.closed_by" 891 } 892 return "repo.issues.opened_by" 893} 894 895// GetLastComment return last comment for the current issue. 896func (issue *Issue) GetLastComment() (*Comment, error) { 897 var c Comment 898 exist, err := db.GetEngine(db.DefaultContext).Where("type = ?", CommentTypeComment). 899 And("issue_id = ?", issue.ID).Desc("created_unix").Get(&c) 900 if err != nil { 901 return nil, err 902 } 903 if !exist { 904 return nil, nil 905 } 906 return &c, nil 907} 908 909// GetLastEventLabelFake returns the localization label for the current issue without providing a link in the username. 910func (issue *Issue) GetLastEventLabelFake() string { 911 if issue.IsClosed { 912 if issue.IsPull && issue.PullRequest.HasMerged { 913 return "repo.pulls.merged_by_fake" 914 } 915 return "repo.issues.closed_by_fake" 916 } 917 return "repo.issues.opened_by_fake" 918} 919 920// NewIssueOptions represents the options of a new issue. 921type NewIssueOptions struct { 922 Repo *repo_model.Repository 923 Issue *Issue 924 LabelIDs []int64 925 Attachments []string // In UUID format. 926 IsPull bool 927} 928 929func newIssue(ctx context.Context, doer *user_model.User, opts NewIssueOptions) (err error) { 930 e := db.GetEngine(ctx) 931 opts.Issue.Title = strings.TrimSpace(opts.Issue.Title) 932 933 if opts.Issue.MilestoneID > 0 { 934 milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID) 935 if err != nil && !IsErrMilestoneNotExist(err) { 936 return fmt.Errorf("getMilestoneByID: %v", err) 937 } 938 939 // Assume milestone is invalid and drop silently. 940 opts.Issue.MilestoneID = 0 941 if milestone != nil { 942 opts.Issue.MilestoneID = milestone.ID 943 opts.Issue.Milestone = milestone 944 } 945 } 946 947 if opts.Issue.Index <= 0 { 948 return fmt.Errorf("no issue index provided") 949 } 950 if opts.Issue.ID > 0 { 951 return fmt.Errorf("issue exist") 952 } 953 954 if _, err := e.Insert(opts.Issue); err != nil { 955 return err 956 } 957 958 if opts.Issue.MilestoneID > 0 { 959 if err := updateMilestoneCounters(ctx, opts.Issue.MilestoneID); err != nil { 960 return err 961 } 962 963 opts := &CreateCommentOptions{ 964 Type: CommentTypeMilestone, 965 Doer: doer, 966 Repo: opts.Repo, 967 Issue: opts.Issue, 968 OldMilestoneID: 0, 969 MilestoneID: opts.Issue.MilestoneID, 970 } 971 if _, err = createComment(ctx, opts); err != nil { 972 return err 973 } 974 } 975 976 if opts.IsPull { 977 _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID) 978 } else { 979 _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID) 980 } 981 if err != nil { 982 return err 983 } 984 985 if len(opts.LabelIDs) > 0 { 986 // During the session, SQLite3 driver cannot handle retrieve objects after update something. 987 // So we have to get all needed labels first. 988 labels := make([]*Label, 0, len(opts.LabelIDs)) 989 if err = e.In("id", opts.LabelIDs).Find(&labels); err != nil { 990 return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LabelIDs, err) 991 } 992 993 if err = opts.Issue.loadPoster(e); err != nil { 994 return err 995 } 996 997 for _, label := range labels { 998 // Silently drop invalid labels. 999 if label.RepoID != opts.Repo.ID && label.OrgID != opts.Repo.OwnerID { 1000 continue 1001 } 1002 1003 if err = opts.Issue.addLabel(ctx, label, opts.Issue.Poster); err != nil { 1004 return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err) 1005 } 1006 } 1007 } 1008 1009 if err = newIssueUsers(ctx, opts.Repo, opts.Issue); err != nil { 1010 return err 1011 } 1012 1013 if len(opts.Attachments) > 0 { 1014 attachments, err := repo_model.GetAttachmentsByUUIDs(ctx, opts.Attachments) 1015 if err != nil { 1016 return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err) 1017 } 1018 1019 for i := 0; i < len(attachments); i++ { 1020 attachments[i].IssueID = opts.Issue.ID 1021 if _, err = e.ID(attachments[i].ID).Update(attachments[i]); err != nil { 1022 return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err) 1023 } 1024 } 1025 } 1026 if err = opts.Issue.loadAttributes(ctx); err != nil { 1027 return err 1028 } 1029 1030 return opts.Issue.addCrossReferences(ctx, doer, false) 1031} 1032 1033// RecalculateIssueIndexForRepo create issue_index for repo if not exist and 1034// update it based on highest index of existing issues assigned to a repo 1035func RecalculateIssueIndexForRepo(repoID int64) error { 1036 ctx, committer, err := db.TxContext() 1037 if err != nil { 1038 return err 1039 } 1040 defer committer.Close() 1041 1042 if err := db.UpsertResourceIndex(db.GetEngine(ctx), "issue_index", repoID); err != nil { 1043 return err 1044 } 1045 1046 var max int64 1047 if _, err := db.GetEngine(ctx).Select(" MAX(`index`)").Table("issue").Where("repo_id=?", repoID).Get(&max); err != nil { 1048 return err 1049 } 1050 1051 if _, err := db.GetEngine(ctx).Exec("UPDATE `issue_index` SET max_index=? WHERE group_id=?", max, repoID); err != nil { 1052 return err 1053 } 1054 1055 return committer.Commit() 1056} 1057 1058// NewIssue creates new issue with labels for repository. 1059func NewIssue(repo *repo_model.Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) { 1060 idx, err := db.GetNextResourceIndex("issue_index", repo.ID) 1061 if err != nil { 1062 return fmt.Errorf("generate issue index failed: %v", err) 1063 } 1064 1065 issue.Index = idx 1066 1067 ctx, committer, err := db.TxContext() 1068 if err != nil { 1069 return err 1070 } 1071 defer committer.Close() 1072 1073 if err = newIssue(ctx, issue.Poster, NewIssueOptions{ 1074 Repo: repo, 1075 Issue: issue, 1076 LabelIDs: labelIDs, 1077 Attachments: uuids, 1078 }); err != nil { 1079 if IsErrUserDoesNotHaveAccessToRepo(err) || IsErrNewIssueInsert(err) { 1080 return err 1081 } 1082 return fmt.Errorf("newIssue: %v", err) 1083 } 1084 1085 if err = committer.Commit(); err != nil { 1086 return fmt.Errorf("Commit: %v", err) 1087 } 1088 1089 return nil 1090} 1091 1092// GetIssueByIndex returns raw issue without loading attributes by index in a repository. 1093func GetIssueByIndex(repoID, index int64) (*Issue, error) { 1094 if index < 1 { 1095 return nil, ErrIssueNotExist{} 1096 } 1097 issue := &Issue{ 1098 RepoID: repoID, 1099 Index: index, 1100 } 1101 has, err := db.GetEngine(db.DefaultContext).Get(issue) 1102 if err != nil { 1103 return nil, err 1104 } else if !has { 1105 return nil, ErrIssueNotExist{0, repoID, index} 1106 } 1107 return issue, nil 1108} 1109 1110// GetIssueWithAttrsByIndex returns issue by index in a repository. 1111func GetIssueWithAttrsByIndex(repoID, index int64) (*Issue, error) { 1112 issue, err := GetIssueByIndex(repoID, index) 1113 if err != nil { 1114 return nil, err 1115 } 1116 return issue, issue.LoadAttributes() 1117} 1118 1119func getIssueByID(e db.Engine, id int64) (*Issue, error) { 1120 issue := new(Issue) 1121 has, err := e.ID(id).Get(issue) 1122 if err != nil { 1123 return nil, err 1124 } else if !has { 1125 return nil, ErrIssueNotExist{id, 0, 0} 1126 } 1127 return issue, nil 1128} 1129 1130// GetIssueWithAttrsByID returns an issue with attributes by given ID. 1131func GetIssueWithAttrsByID(id int64) (*Issue, error) { 1132 issue, err := getIssueByID(db.GetEngine(db.DefaultContext), id) 1133 if err != nil { 1134 return nil, err 1135 } 1136 return issue, issue.loadAttributes(db.DefaultContext) 1137} 1138 1139// GetIssueByID returns an issue by given ID. 1140func GetIssueByID(id int64) (*Issue, error) { 1141 return getIssueByID(db.GetEngine(db.DefaultContext), id) 1142} 1143 1144func getIssuesByIDs(e db.Engine, issueIDs []int64) ([]*Issue, error) { 1145 issues := make([]*Issue, 0, 10) 1146 return issues, e.In("id", issueIDs).Find(&issues) 1147} 1148 1149func getIssueIDsByRepoID(e db.Engine, repoID int64) ([]int64, error) { 1150 ids := make([]int64, 0, 10) 1151 err := e.Table("issue").Cols("id").Where("repo_id = ?", repoID).Find(&ids) 1152 return ids, err 1153} 1154 1155// GetIssueIDsByRepoID returns all issue ids by repo id 1156func GetIssueIDsByRepoID(repoID int64) ([]int64, error) { 1157 return getIssueIDsByRepoID(db.GetEngine(db.DefaultContext), repoID) 1158} 1159 1160// GetIssuesByIDs return issues with the given IDs. 1161func GetIssuesByIDs(issueIDs []int64) ([]*Issue, error) { 1162 return getIssuesByIDs(db.GetEngine(db.DefaultContext), issueIDs) 1163} 1164 1165// IssuesOptions represents options of an issue. 1166type IssuesOptions struct { 1167 db.ListOptions 1168 RepoIDs []int64 // include all repos if empty 1169 AssigneeID int64 1170 PosterID int64 1171 MentionedID int64 1172 ReviewRequestedID int64 1173 MilestoneIDs []int64 1174 ProjectID int64 1175 ProjectBoardID int64 1176 IsClosed util.OptionalBool 1177 IsPull util.OptionalBool 1178 LabelIDs []int64 1179 IncludedLabelNames []string 1180 ExcludedLabelNames []string 1181 IncludeMilestones []string 1182 SortType string 1183 IssueIDs []int64 1184 UpdatedAfterUnix int64 1185 UpdatedBeforeUnix int64 1186 // prioritize issues from this repo 1187 PriorityRepoID int64 1188 IsArchived util.OptionalBool 1189 Org *Organization // issues permission scope 1190 Team *Team // issues permission scope 1191 User *user_model.User // issues permission scope 1192} 1193 1194// sortIssuesSession sort an issues-related session based on the provided 1195// sortType string 1196func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) { 1197 switch sortType { 1198 case "oldest": 1199 sess.Asc("issue.created_unix").Asc("issue.id") 1200 case "recentupdate": 1201 sess.Desc("issue.updated_unix").Desc("issue.created_unix").Desc("issue.id") 1202 case "leastupdate": 1203 sess.Asc("issue.updated_unix").Asc("issue.created_unix").Asc("issue.id") 1204 case "mostcomment": 1205 sess.Desc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id") 1206 case "leastcomment": 1207 sess.Asc("issue.num_comments").Desc("issue.created_unix").Desc("issue.id") 1208 case "priority": 1209 sess.Desc("issue.priority").Desc("issue.created_unix").Desc("issue.id") 1210 case "nearduedate": 1211 // 253370764800 is 01/01/9999 @ 12:00am (UTC) 1212 sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id"). 1213 OrderBy("CASE " + 1214 "WHEN issue.deadline_unix = 0 AND (milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL) THEN 253370764800 " + 1215 "WHEN milestone.deadline_unix = 0 OR milestone.deadline_unix IS NULL THEN issue.deadline_unix " + 1216 "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " + 1217 "ELSE issue.deadline_unix END ASC"). 1218 Desc("issue.created_unix"). 1219 Desc("issue.id") 1220 case "farduedate": 1221 sess.Join("LEFT", "milestone", "issue.milestone_id = milestone.id"). 1222 OrderBy("CASE " + 1223 "WHEN milestone.deadline_unix IS NULL THEN issue.deadline_unix " + 1224 "WHEN milestone.deadline_unix < issue.deadline_unix OR issue.deadline_unix = 0 THEN milestone.deadline_unix " + 1225 "ELSE issue.deadline_unix END DESC"). 1226 Desc("issue.created_unix"). 1227 Desc("issue.id") 1228 case "priorityrepo": 1229 sess.OrderBy("CASE " + 1230 "WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 " + 1231 "ELSE 2 END ASC"). 1232 Desc("issue.created_unix"). 1233 Desc("issue.id") 1234 case "project-column-sorting": 1235 sess.Asc("project_issue.sorting").Desc("issue.created_unix").Desc("issue.id") 1236 default: 1237 sess.Desc("issue.created_unix").Desc("issue.id") 1238 } 1239} 1240 1241func (opts *IssuesOptions) setupSession(sess *xorm.Session) { 1242 if opts.Page >= 0 && opts.PageSize > 0 { 1243 var start int 1244 if opts.Page == 0 { 1245 start = 0 1246 } else { 1247 start = (opts.Page - 1) * opts.PageSize 1248 } 1249 sess.Limit(opts.PageSize, start) 1250 } 1251 1252 if len(opts.IssueIDs) > 0 { 1253 sess.In("issue.id", opts.IssueIDs) 1254 } 1255 1256 if len(opts.RepoIDs) > 0 { 1257 applyReposCondition(sess, opts.RepoIDs) 1258 } 1259 1260 switch opts.IsClosed { 1261 case util.OptionalBoolTrue: 1262 sess.And("issue.is_closed=?", true) 1263 case util.OptionalBoolFalse: 1264 sess.And("issue.is_closed=?", false) 1265 } 1266 1267 if opts.AssigneeID > 0 { 1268 applyAssigneeCondition(sess, opts.AssigneeID) 1269 } 1270 1271 if opts.PosterID > 0 { 1272 applyPosterCondition(sess, opts.PosterID) 1273 } 1274 1275 if opts.MentionedID > 0 { 1276 applyMentionedCondition(sess, opts.MentionedID) 1277 } 1278 1279 if opts.ReviewRequestedID > 0 { 1280 applyReviewRequestedCondition(sess, opts.ReviewRequestedID) 1281 } 1282 1283 if len(opts.MilestoneIDs) > 0 { 1284 sess.In("issue.milestone_id", opts.MilestoneIDs) 1285 } 1286 1287 if opts.UpdatedAfterUnix != 0 { 1288 sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix}) 1289 } 1290 if opts.UpdatedBeforeUnix != 0 { 1291 sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix}) 1292 } 1293 1294 if opts.ProjectID > 0 { 1295 sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id"). 1296 And("project_issue.project_id=?", opts.ProjectID) 1297 } 1298 1299 if opts.ProjectBoardID != 0 { 1300 if opts.ProjectBoardID > 0 { 1301 sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID})) 1302 } else { 1303 sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0})) 1304 } 1305 } 1306 1307 switch opts.IsPull { 1308 case util.OptionalBoolTrue: 1309 sess.And("issue.is_pull=?", true) 1310 case util.OptionalBoolFalse: 1311 sess.And("issue.is_pull=?", false) 1312 } 1313 1314 if opts.IsArchived != util.OptionalBoolNone { 1315 sess.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()}) 1316 } 1317 1318 if opts.LabelIDs != nil { 1319 for i, labelID := range opts.LabelIDs { 1320 if labelID > 0 { 1321 sess.Join("INNER", fmt.Sprintf("issue_label il%d", i), 1322 fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID)) 1323 } else { 1324 sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID) 1325 } 1326 } 1327 } 1328 1329 if len(opts.IncludedLabelNames) > 0 { 1330 sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames)) 1331 } 1332 1333 if len(opts.ExcludedLabelNames) > 0 { 1334 sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames))) 1335 } 1336 1337 if len(opts.IncludeMilestones) > 0 { 1338 sess.In("issue.milestone_id", 1339 builder.Select("id"). 1340 From("milestone"). 1341 Where(builder.In("name", opts.IncludeMilestones))) 1342 } 1343 1344 if opts.User != nil { 1345 sess.And( 1346 issuePullAccessibleRepoCond("issue.repo_id", opts.User.ID, opts.Org, opts.Team, opts.IsPull.IsTrue()), 1347 ) 1348 } 1349} 1350 1351// issuePullAccessibleRepoCond userID must not be zero, this condition require join repository table 1352func issuePullAccessibleRepoCond(repoIDstr string, userID int64, org *Organization, team *Team, isPull bool) builder.Cond { 1353 cond := builder.NewCond() 1354 unitType := unit.TypeIssues 1355 if isPull { 1356 unitType = unit.TypePullRequests 1357 } 1358 if org != nil { 1359 if team != nil { 1360 cond = cond.And(teamUnitsRepoCond(repoIDstr, userID, org.ID, team.ID, unitType)) // special team member repos 1361 } else { 1362 cond = cond.And( 1363 builder.Or( 1364 userOrgUnitRepoCond(repoIDstr, userID, org.ID, unitType), // team member repos 1365 userOrgPublicUnitRepoCond(userID, org.ID), // user org public non-member repos, TODO: check repo has issues 1366 ), 1367 ) 1368 } 1369 } else { 1370 cond = cond.And( 1371 builder.Or( 1372 userOwnedRepoCond(userID), // owned repos 1373 userCollaborationRepoCond(repoIDstr, userID), // collaboration repos 1374 userAssignedRepoCond(repoIDstr, userID), // user has been assigned accessible public repos 1375 userMentionedRepoCond(repoIDstr, userID), // user has been mentioned accessible public repos 1376 userCreateIssueRepoCond(repoIDstr, userID, isPull), // user has created issue/pr accessible public repos 1377 ), 1378 ) 1379 } 1380 return cond 1381} 1382 1383func applyReposCondition(sess *xorm.Session, repoIDs []int64) *xorm.Session { 1384 return sess.In("issue.repo_id", repoIDs) 1385} 1386 1387func applyAssigneeCondition(sess *xorm.Session, assigneeID int64) *xorm.Session { 1388 return sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id"). 1389 And("issue_assignees.assignee_id = ?", assigneeID) 1390} 1391 1392func applyPosterCondition(sess *xorm.Session, posterID int64) *xorm.Session { 1393 return sess.And("issue.poster_id=?", posterID) 1394} 1395 1396func applyMentionedCondition(sess *xorm.Session, mentionedID int64) *xorm.Session { 1397 return sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id"). 1398 And("issue_user.is_mentioned = ?", true). 1399 And("issue_user.uid = ?", mentionedID) 1400} 1401 1402func applyReviewRequestedCondition(sess *xorm.Session, reviewRequestedID int64) *xorm.Session { 1403 return sess.Join("INNER", []string{"review", "r"}, "issue.id = r.issue_id"). 1404 And("issue.poster_id <> ?", reviewRequestedID). 1405 And("r.type = ?", ReviewTypeRequest). 1406 And("r.reviewer_id = ? and r.id in (select max(id) from review where issue_id = r.issue_id and reviewer_id = r.reviewer_id and type in (?, ?, ?))"+ 1407 " or r.reviewer_team_id in (select team_id from team_user where uid = ?)", 1408 reviewRequestedID, ReviewTypeApprove, ReviewTypeReject, ReviewTypeRequest, reviewRequestedID) 1409} 1410 1411// CountIssuesByRepo map from repoID to number of issues matching the options 1412func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) { 1413 e := db.GetEngine(db.DefaultContext) 1414 1415 sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") 1416 1417 opts.setupSession(sess) 1418 1419 countsSlice := make([]*struct { 1420 RepoID int64 1421 Count int64 1422 }, 0, 10) 1423 if err := sess.GroupBy("issue.repo_id"). 1424 Select("issue.repo_id AS repo_id, COUNT(*) AS count"). 1425 Table("issue"). 1426 Find(&countsSlice); err != nil { 1427 return nil, err 1428 } 1429 1430 countMap := make(map[int64]int64, len(countsSlice)) 1431 for _, c := range countsSlice { 1432 countMap[c.RepoID] = c.Count 1433 } 1434 return countMap, nil 1435} 1436 1437// GetRepoIDsForIssuesOptions find all repo ids for the given options 1438func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *user_model.User) ([]int64, error) { 1439 repoIDs := make([]int64, 0, 5) 1440 e := db.GetEngine(db.DefaultContext) 1441 1442 sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") 1443 1444 opts.setupSession(sess) 1445 1446 accessCond := accessibleRepositoryCondition(user) 1447 if err := sess.Where(accessCond). 1448 Distinct("issue.repo_id"). 1449 Table("issue"). 1450 Find(&repoIDs); err != nil { 1451 return nil, err 1452 } 1453 1454 return repoIDs, nil 1455} 1456 1457// Issues returns a list of issues by given conditions. 1458func Issues(opts *IssuesOptions) ([]*Issue, error) { 1459 e := db.GetEngine(db.DefaultContext) 1460 1461 sess := e.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") 1462 opts.setupSession(sess) 1463 sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID) 1464 1465 issues := make([]*Issue, 0, opts.ListOptions.PageSize) 1466 if err := sess.Find(&issues); err != nil { 1467 return nil, fmt.Errorf("Find: %v", err) 1468 } 1469 sess.Close() 1470 1471 if err := IssueList(issues).LoadAttributes(); err != nil { 1472 return nil, fmt.Errorf("LoadAttributes: %v", err) 1473 } 1474 1475 return issues, nil 1476} 1477 1478// CountIssues number return of issues by given conditions. 1479func CountIssues(opts *IssuesOptions) (int64, error) { 1480 e := db.GetEngine(db.DefaultContext) 1481 1482 countsSlice := make([]*struct { 1483 RepoID int64 1484 Count int64 1485 }, 0, 1) 1486 1487 sess := e.Select("COUNT(issue.id) AS count").Table("issue") 1488 sess.Join("INNER", "repository", "`issue`.repo_id = `repository`.id") 1489 opts.setupSession(sess) 1490 if err := sess.Find(&countsSlice); err != nil { 1491 return 0, fmt.Errorf("Find: %v", err) 1492 } 1493 if len(countsSlice) < 1 { 1494 return 0, fmt.Errorf("there is less than one result sql record") 1495 } 1496 return countsSlice[0].Count, nil 1497} 1498 1499// GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue, 1500// but skips joining with `user` for performance reasons. 1501// User permissions must be verified elsewhere if required. 1502func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) { 1503 userIDs := make([]int64, 0, 5) 1504 return userIDs, db.GetEngine(db.DefaultContext).Table("comment"). 1505 Cols("poster_id"). 1506 Where("issue_id = ?", issueID). 1507 And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). 1508 Distinct("poster_id"). 1509 Find(&userIDs) 1510} 1511 1512// IsUserParticipantsOfIssue return true if user is participants of an issue 1513func IsUserParticipantsOfIssue(user *user_model.User, issue *Issue) bool { 1514 userIDs, err := issue.getParticipantIDsByIssue(db.GetEngine(db.DefaultContext)) 1515 if err != nil { 1516 log.Error(err.Error()) 1517 return false 1518 } 1519 return util.IsInt64InSlice(user.ID, userIDs) 1520} 1521 1522// UpdateIssueMentions updates issue-user relations for mentioned users. 1523func UpdateIssueMentions(ctx context.Context, issueID int64, mentions []*user_model.User) error { 1524 if len(mentions) == 0 { 1525 return nil 1526 } 1527 ids := make([]int64, len(mentions)) 1528 for i, u := range mentions { 1529 ids[i] = u.ID 1530 } 1531 if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil { 1532 return fmt.Errorf("UpdateIssueUsersByMentions: %v", err) 1533 } 1534 return nil 1535} 1536 1537// IssueStats represents issue statistic information. 1538type IssueStats struct { 1539 OpenCount, ClosedCount int64 1540 YourRepositoriesCount int64 1541 AssignCount int64 1542 CreateCount int64 1543 MentionCount int64 1544 ReviewRequestedCount int64 1545} 1546 1547// Filter modes. 1548const ( 1549 FilterModeAll = iota 1550 FilterModeAssign 1551 FilterModeCreate 1552 FilterModeMention 1553 FilterModeReviewRequested 1554 FilterModeYourRepositories 1555) 1556 1557func parseCountResult(results []map[string][]byte) int64 { 1558 if len(results) == 0 { 1559 return 0 1560 } 1561 for _, result := range results[0] { 1562 c, _ := strconv.ParseInt(string(result), 10, 64) 1563 return c 1564 } 1565 return 0 1566} 1567 1568// IssueStatsOptions contains parameters accepted by GetIssueStats. 1569type IssueStatsOptions struct { 1570 RepoID int64 1571 Labels string 1572 MilestoneID int64 1573 AssigneeID int64 1574 MentionedID int64 1575 PosterID int64 1576 ReviewRequestedID int64 1577 IsPull util.OptionalBool 1578 IssueIDs []int64 1579} 1580 1581const ( 1582 // When queries are broken down in parts because of the number 1583 // of parameters, attempt to break by this amount 1584 maxQueryParameters = 300 1585) 1586 1587// GetIssueStats returns issue statistic information by given conditions. 1588func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) { 1589 if len(opts.IssueIDs) <= maxQueryParameters { 1590 return getIssueStatsChunk(opts, opts.IssueIDs) 1591 } 1592 1593 // If too long a list of IDs is provided, we get the statistics in 1594 // smaller chunks and get accumulates. Note: this could potentially 1595 // get us invalid results. The alternative is to insert the list of 1596 // ids in a temporary table and join from them. 1597 accum := &IssueStats{} 1598 for i := 0; i < len(opts.IssueIDs); { 1599 chunk := i + maxQueryParameters 1600 if chunk > len(opts.IssueIDs) { 1601 chunk = len(opts.IssueIDs) 1602 } 1603 stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk]) 1604 if err != nil { 1605 return nil, err 1606 } 1607 accum.OpenCount += stats.OpenCount 1608 accum.ClosedCount += stats.ClosedCount 1609 accum.YourRepositoriesCount += stats.YourRepositoriesCount 1610 accum.AssignCount += stats.AssignCount 1611 accum.CreateCount += stats.CreateCount 1612 accum.OpenCount += stats.MentionCount 1613 accum.ReviewRequestedCount += stats.ReviewRequestedCount 1614 i = chunk 1615 } 1616 return accum, nil 1617} 1618 1619func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) { 1620 stats := &IssueStats{} 1621 1622 countSession := func(opts *IssueStatsOptions, issueIDs []int64) *xorm.Session { 1623 sess := db.GetEngine(db.DefaultContext). 1624 Where("issue.repo_id = ?", opts.RepoID) 1625 1626 if len(issueIDs) > 0 { 1627 sess.In("issue.id", issueIDs) 1628 } 1629 1630 if len(opts.Labels) > 0 && opts.Labels != "0" { 1631 labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ",")) 1632 if err != nil { 1633 log.Warn("Malformed Labels argument: %s", opts.Labels) 1634 } else { 1635 for i, labelID := range labelIDs { 1636 if labelID > 0 { 1637 sess.Join("INNER", fmt.Sprintf("issue_label il%d", i), 1638 fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID)) 1639 } else { 1640 sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID) 1641 } 1642 } 1643 } 1644 } 1645 1646 if opts.MilestoneID > 0 { 1647 sess.And("issue.milestone_id = ?", opts.MilestoneID) 1648 } 1649 1650 if opts.AssigneeID > 0 { 1651 applyAssigneeCondition(sess, opts.AssigneeID) 1652 } 1653 1654 if opts.PosterID > 0 { 1655 applyPosterCondition(sess, opts.PosterID) 1656 } 1657 1658 if opts.MentionedID > 0 { 1659 applyMentionedCondition(sess, opts.MentionedID) 1660 } 1661 1662 if opts.ReviewRequestedID > 0 { 1663 applyReviewRequestedCondition(sess, opts.ReviewRequestedID) 1664 } 1665 1666 switch opts.IsPull { 1667 case util.OptionalBoolTrue: 1668 sess.And("issue.is_pull=?", true) 1669 case util.OptionalBoolFalse: 1670 sess.And("issue.is_pull=?", false) 1671 } 1672 1673 return sess 1674 } 1675 1676 var err error 1677 stats.OpenCount, err = countSession(opts, issueIDs). 1678 And("issue.is_closed = ?", false). 1679 Count(new(Issue)) 1680 if err != nil { 1681 return stats, err 1682 } 1683 stats.ClosedCount, err = countSession(opts, issueIDs). 1684 And("issue.is_closed = ?", true). 1685 Count(new(Issue)) 1686 return stats, err 1687} 1688 1689// UserIssueStatsOptions contains parameters accepted by GetUserIssueStats. 1690type UserIssueStatsOptions struct { 1691 UserID int64 1692 RepoIDs []int64 1693 FilterMode int 1694 IsPull bool 1695 IsClosed bool 1696 IssueIDs []int64 1697 IsArchived util.OptionalBool 1698 LabelIDs []int64 1699 RepoCond builder.Cond 1700 Org *Organization 1701 Team *Team 1702} 1703 1704// GetUserIssueStats returns issue statistic information for dashboard by given conditions. 1705func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) { 1706 var err error 1707 stats := &IssueStats{} 1708 1709 cond := builder.NewCond() 1710 cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull}) 1711 if len(opts.RepoIDs) > 0 { 1712 cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs)) 1713 } 1714 if len(opts.IssueIDs) > 0 { 1715 cond = cond.And(builder.In("issue.id", opts.IssueIDs)) 1716 } 1717 if opts.RepoCond != nil { 1718 cond = cond.And(opts.RepoCond) 1719 } 1720 1721 if opts.UserID > 0 { 1722 cond = cond.And(issuePullAccessibleRepoCond("issue.repo_id", opts.UserID, opts.Org, opts.Team, opts.IsPull)) 1723 } 1724 1725 sess := func(cond builder.Cond) *xorm.Session { 1726 s := db.GetEngine(db.DefaultContext).Where(cond) 1727 if len(opts.LabelIDs) > 0 { 1728 s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id"). 1729 In("issue_label.label_id", opts.LabelIDs) 1730 } 1731 if opts.UserID > 0 || opts.IsArchived != util.OptionalBoolNone { 1732 s.Join("INNER", "repository", "issue.repo_id = repository.id") 1733 if opts.IsArchived != util.OptionalBoolNone { 1734 s.And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()}) 1735 } 1736 } 1737 return s 1738 } 1739 1740 switch opts.FilterMode { 1741 case FilterModeAll, FilterModeYourRepositories: 1742 stats.OpenCount, err = sess(cond). 1743 And("issue.is_closed = ?", false). 1744 Count(new(Issue)) 1745 if err != nil { 1746 return nil, err 1747 } 1748 stats.ClosedCount, err = sess(cond). 1749 And("issue.is_closed = ?", true). 1750 Count(new(Issue)) 1751 if err != nil { 1752 return nil, err 1753 } 1754 case FilterModeAssign: 1755 stats.OpenCount, err = applyAssigneeCondition(sess(cond), opts.UserID). 1756 And("issue.is_closed = ?", false). 1757 Count(new(Issue)) 1758 if err != nil { 1759 return nil, err 1760 } 1761 stats.ClosedCount, err = applyAssigneeCondition(sess(cond), opts.UserID). 1762 And("issue.is_closed = ?", true). 1763 Count(new(Issue)) 1764 if err != nil { 1765 return nil, err 1766 } 1767 case FilterModeCreate: 1768 stats.OpenCount, err = applyPosterCondition(sess(cond), opts.UserID). 1769 And("issue.is_closed = ?", false). 1770 Count(new(Issue)) 1771 if err != nil { 1772 return nil, err 1773 } 1774 stats.ClosedCount, err = applyPosterCondition(sess(cond), opts.UserID). 1775 And("issue.is_closed = ?", true). 1776 Count(new(Issue)) 1777 if err != nil { 1778 return nil, err 1779 } 1780 case FilterModeMention: 1781 stats.OpenCount, err = applyMentionedCondition(sess(cond), opts.UserID). 1782 And("issue.is_closed = ?", false). 1783 Count(new(Issue)) 1784 if err != nil { 1785 return nil, err 1786 } 1787 stats.ClosedCount, err = applyMentionedCondition(sess(cond), opts.UserID). 1788 And("issue.is_closed = ?", true). 1789 Count(new(Issue)) 1790 if err != nil { 1791 return nil, err 1792 } 1793 case FilterModeReviewRequested: 1794 stats.OpenCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID). 1795 And("issue.is_closed = ?", false). 1796 Count(new(Issue)) 1797 if err != nil { 1798 return nil, err 1799 } 1800 stats.ClosedCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID). 1801 And("issue.is_closed = ?", true). 1802 Count(new(Issue)) 1803 if err != nil { 1804 return nil, err 1805 } 1806 } 1807 1808 cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed}) 1809 stats.AssignCount, err = applyAssigneeCondition(sess(cond), opts.UserID).Count(new(Issue)) 1810 if err != nil { 1811 return nil, err 1812 } 1813 1814 stats.CreateCount, err = applyPosterCondition(sess(cond), opts.UserID).Count(new(Issue)) 1815 if err != nil { 1816 return nil, err 1817 } 1818 1819 stats.MentionCount, err = applyMentionedCondition(sess(cond), opts.UserID).Count(new(Issue)) 1820 if err != nil { 1821 return nil, err 1822 } 1823 1824 stats.YourRepositoriesCount, err = sess(cond).Count(new(Issue)) 1825 if err != nil { 1826 return nil, err 1827 } 1828 1829 stats.ReviewRequestedCount, err = applyReviewRequestedCondition(sess(cond), opts.UserID).Count(new(Issue)) 1830 if err != nil { 1831 return nil, err 1832 } 1833 1834 return stats, nil 1835} 1836 1837// GetRepoIssueStats returns number of open and closed repository issues by given filter mode. 1838func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen, numClosed int64) { 1839 countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session { 1840 sess := db.GetEngine(db.DefaultContext). 1841 Where("is_closed = ?", isClosed). 1842 And("is_pull = ?", isPull). 1843 And("repo_id = ?", repoID) 1844 1845 return sess 1846 } 1847 1848 openCountSession := countSession(false, isPull, repoID) 1849 closedCountSession := countSession(true, isPull, repoID) 1850 1851 switch filterMode { 1852 case FilterModeAssign: 1853 applyAssigneeCondition(openCountSession, uid) 1854 applyAssigneeCondition(closedCountSession, uid) 1855 case FilterModeCreate: 1856 applyPosterCondition(openCountSession, uid) 1857 applyPosterCondition(closedCountSession, uid) 1858 } 1859 1860 openResult, _ := openCountSession.Count(new(Issue)) 1861 closedResult, _ := closedCountSession.Count(new(Issue)) 1862 1863 return openResult, closedResult 1864} 1865 1866// SearchIssueIDsByKeyword search issues on database 1867func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) { 1868 repoCond := builder.In("repo_id", repoIDs) 1869 subQuery := builder.Select("id").From("issue").Where(repoCond) 1870 kw = strings.ToUpper(kw) 1871 cond := builder.And( 1872 repoCond, 1873 builder.Or( 1874 builder.Like{"UPPER(name)", kw}, 1875 builder.Like{"UPPER(content)", kw}, 1876 builder.In("id", builder.Select("issue_id"). 1877 From("comment"). 1878 Where(builder.And( 1879 builder.Eq{"type": CommentTypeComment}, 1880 builder.In("issue_id", subQuery), 1881 builder.Like{"UPPER(content)", kw}, 1882 )), 1883 ), 1884 ), 1885 ) 1886 1887 ids := make([]int64, 0, limit) 1888 res := make([]struct { 1889 ID int64 1890 UpdatedUnix int64 1891 }, 0, limit) 1892 err := db.GetEngine(db.DefaultContext).Distinct("id", "updated_unix").Table("issue").Where(cond). 1893 OrderBy("`updated_unix` DESC").Limit(limit, start). 1894 Find(&res) 1895 if err != nil { 1896 return 0, nil, err 1897 } 1898 for _, r := range res { 1899 ids = append(ids, r.ID) 1900 } 1901 1902 total, err := db.GetEngine(db.DefaultContext).Distinct("id").Table("issue").Where(cond).Count() 1903 if err != nil { 1904 return 0, nil, err 1905 } 1906 1907 return total, ids, nil 1908} 1909 1910// UpdateIssueByAPI updates all allowed fields of given issue. 1911// If the issue status is changed a statusChangeComment is returned 1912// similarly if the title is changed the titleChanged bool is set to true 1913func UpdateIssueByAPI(issue *Issue, doer *user_model.User) (statusChangeComment *Comment, titleChanged bool, err error) { 1914 ctx, committer, err := db.TxContext() 1915 if err != nil { 1916 return nil, false, err 1917 } 1918 defer committer.Close() 1919 sess := db.GetEngine(ctx) 1920 1921 if err := issue.loadRepo(ctx); err != nil { 1922 return nil, false, fmt.Errorf("loadRepo: %v", err) 1923 } 1924 1925 // Reload the issue 1926 currentIssue, err := getIssueByID(sess, issue.ID) 1927 if err != nil { 1928 return nil, false, err 1929 } 1930 1931 if _, err := sess.ID(issue.ID).Cols( 1932 "name", "content", "milestone_id", "priority", 1933 "deadline_unix", "updated_unix", "is_locked"). 1934 Update(issue); err != nil { 1935 return nil, false, err 1936 } 1937 1938 titleChanged = currentIssue.Title != issue.Title 1939 if titleChanged { 1940 opts := &CreateCommentOptions{ 1941 Type: CommentTypeChangeTitle, 1942 Doer: doer, 1943 Repo: issue.Repo, 1944 Issue: issue, 1945 OldTitle: currentIssue.Title, 1946 NewTitle: issue.Title, 1947 } 1948 _, err := createComment(ctx, opts) 1949 if err != nil { 1950 return nil, false, fmt.Errorf("createComment: %v", err) 1951 } 1952 } 1953 1954 if currentIssue.IsClosed != issue.IsClosed { 1955 statusChangeComment, err = issue.doChangeStatus(ctx, doer, false) 1956 if err != nil { 1957 return nil, false, err 1958 } 1959 } 1960 1961 if err := issue.addCrossReferences(ctx, doer, true); err != nil { 1962 return nil, false, err 1963 } 1964 return statusChangeComment, titleChanged, committer.Commit() 1965} 1966 1967// UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it. 1968func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *user_model.User) (err error) { 1969 // if the deadline hasn't changed do nothing 1970 if issue.DeadlineUnix == deadlineUnix { 1971 return nil 1972 } 1973 ctx, committer, err := db.TxContext() 1974 if err != nil { 1975 return err 1976 } 1977 defer committer.Close() 1978 1979 // Update the deadline 1980 if err = updateIssueCols(ctx, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil { 1981 return err 1982 } 1983 1984 // Make the comment 1985 if _, err = createDeadlineComment(ctx, doer, issue, deadlineUnix); err != nil { 1986 return fmt.Errorf("createRemovedDueDateComment: %v", err) 1987 } 1988 1989 return committer.Commit() 1990} 1991 1992// DependencyInfo represents high level information about an issue which is a dependency of another issue. 1993type DependencyInfo struct { 1994 Issue `xorm:"extends"` 1995 repo_model.Repository `xorm:"extends"` 1996} 1997 1998// getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author 1999func (issue *Issue) getParticipantIDsByIssue(e db.Engine) ([]int64, error) { 2000 if issue == nil { 2001 return nil, nil 2002 } 2003 userIDs := make([]int64, 0, 5) 2004 if err := e.Table("comment").Cols("poster_id"). 2005 Where("`comment`.issue_id = ?", issue.ID). 2006 And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview). 2007 And("`user`.is_active = ?", true). 2008 And("`user`.prohibit_login = ?", false). 2009 Join("INNER", "`user`", "`user`.id = `comment`.poster_id"). 2010 Distinct("poster_id"). 2011 Find(&userIDs); err != nil { 2012 return nil, fmt.Errorf("get poster IDs: %v", err) 2013 } 2014 if !util.IsInt64InSlice(issue.PosterID, userIDs) { 2015 return append(userIDs, issue.PosterID), nil 2016 } 2017 return userIDs, nil 2018} 2019 2020// Get Blocked By Dependencies, aka all issues this issue is blocked by. 2021func (issue *Issue) getBlockedByDependencies(e db.Engine) (issueDeps []*DependencyInfo, err error) { 2022 err = e. 2023 Table("issue"). 2024 Join("INNER", "repository", "repository.id = issue.repo_id"). 2025 Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id"). 2026 Where("issue_id = ?", issue.ID). 2027 // sort by repo id then created date, with the issues of the same repo at the beginning of the list 2028 OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC"). 2029 Find(&issueDeps) 2030 2031 for _, depInfo := range issueDeps { 2032 depInfo.Issue.Repo = &depInfo.Repository 2033 } 2034 2035 return issueDeps, err 2036} 2037 2038// Get Blocking Dependencies, aka all issues this issue blocks. 2039func (issue *Issue) getBlockingDependencies(e db.Engine) (issueDeps []*DependencyInfo, err error) { 2040 err = e. 2041 Table("issue"). 2042 Join("INNER", "repository", "repository.id = issue.repo_id"). 2043 Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id"). 2044 Where("dependency_id = ?", issue.ID). 2045 // sort by repo id then created date, with the issues of the same repo at the beginning of the list 2046 OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC"). 2047 Find(&issueDeps) 2048 2049 for _, depInfo := range issueDeps { 2050 depInfo.Issue.Repo = &depInfo.Repository 2051 } 2052 2053 return issueDeps, err 2054} 2055 2056// BlockedByDependencies finds all Dependencies an issue is blocked by 2057func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) { 2058 return issue.getBlockedByDependencies(db.GetEngine(db.DefaultContext)) 2059} 2060 2061// BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks 2062func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) { 2063 return issue.getBlockingDependencies(db.GetEngine(db.DefaultContext)) 2064} 2065 2066func (issue *Issue) updateClosedNum(ctx context.Context) (err error) { 2067 if issue.IsPull { 2068 err = repoStatsCorrectNumClosed(ctx, issue.RepoID, true, "num_closed_pulls") 2069 } else { 2070 err = repoStatsCorrectNumClosed(ctx, issue.RepoID, false, "num_closed_issues") 2071 } 2072 return 2073} 2074 2075// FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database. 2076func (issue *Issue) FindAndUpdateIssueMentions(ctx context.Context, doer *user_model.User, content string) (mentions []*user_model.User, err error) { 2077 rawMentions := references.FindAllMentionsMarkdown(content) 2078 mentions, err = issue.ResolveMentionsByVisibility(ctx, doer, rawMentions) 2079 if err != nil { 2080 return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err) 2081 } 2082 if err = UpdateIssueMentions(ctx, issue.ID, mentions); err != nil { 2083 return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err) 2084 } 2085 return 2086} 2087 2088// ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that 2089// don't have access to reading it. Teams are expanded into their users, but organizations are ignored. 2090func (issue *Issue) ResolveMentionsByVisibility(ctx context.Context, doer *user_model.User, mentions []string) (users []*user_model.User, err error) { 2091 if len(mentions) == 0 { 2092 return 2093 } 2094 if err = issue.loadRepo(ctx); err != nil { 2095 return 2096 } 2097 2098 resolved := make(map[string]bool, 10) 2099 var mentionTeams []string 2100 2101 if err := issue.Repo.GetOwner(ctx); err != nil { 2102 return nil, err 2103 } 2104 2105 repoOwnerIsOrg := issue.Repo.Owner.IsOrganization() 2106 if repoOwnerIsOrg { 2107 mentionTeams = make([]string, 0, 5) 2108 } 2109 2110 resolved[doer.LowerName] = true 2111 for _, name := range mentions { 2112 name := strings.ToLower(name) 2113 if _, ok := resolved[name]; ok { 2114 continue 2115 } 2116 if repoOwnerIsOrg && strings.Contains(name, "/") { 2117 names := strings.Split(name, "/") 2118 if len(names) < 2 || names[0] != issue.Repo.Owner.LowerName { 2119 continue 2120 } 2121 mentionTeams = append(mentionTeams, names[1]) 2122 resolved[name] = true 2123 } else { 2124 resolved[name] = false 2125 } 2126 } 2127 2128 if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 { 2129 teams := make([]*Team, 0, len(mentionTeams)) 2130 if err := db.GetEngine(ctx). 2131 Join("INNER", "team_repo", "team_repo.team_id = team.id"). 2132 Where("team_repo.repo_id=?", issue.Repo.ID). 2133 In("team.lower_name", mentionTeams). 2134 Find(&teams); err != nil { 2135 return nil, fmt.Errorf("find mentioned teams: %v", err) 2136 } 2137 if len(teams) != 0 { 2138 checked := make([]int64, 0, len(teams)) 2139 unittype := unit.TypeIssues 2140 if issue.IsPull { 2141 unittype = unit.TypePullRequests 2142 } 2143 for _, team := range teams { 2144 if team.AccessMode >= perm.AccessModeAdmin { 2145 checked = append(checked, team.ID) 2146 resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true 2147 continue 2148 } 2149 has, err := db.GetEngine(ctx).Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype}) 2150 if err != nil { 2151 return nil, fmt.Errorf("get team units (%d): %v", team.ID, err) 2152 } 2153 if has { 2154 checked = append(checked, team.ID) 2155 resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true 2156 } 2157 } 2158 if len(checked) != 0 { 2159 teamusers := make([]*user_model.User, 0, 20) 2160 if err := db.GetEngine(ctx). 2161 Join("INNER", "team_user", "team_user.uid = `user`.id"). 2162 In("`team_user`.team_id", checked). 2163 And("`user`.is_active = ?", true). 2164 And("`user`.prohibit_login = ?", false). 2165 Find(&teamusers); err != nil { 2166 return nil, fmt.Errorf("get teams users: %v", err) 2167 } 2168 if len(teamusers) > 0 { 2169 users = make([]*user_model.User, 0, len(teamusers)) 2170 for _, user := range teamusers { 2171 if already, ok := resolved[user.LowerName]; !ok || !already { 2172 users = append(users, user) 2173 resolved[user.LowerName] = true 2174 } 2175 } 2176 } 2177 } 2178 } 2179 } 2180 2181 // Remove names already in the list to avoid querying the database if pending names remain 2182 mentionUsers := make([]string, 0, len(resolved)) 2183 for name, already := range resolved { 2184 if !already { 2185 mentionUsers = append(mentionUsers, name) 2186 } 2187 } 2188 if len(mentionUsers) == 0 { 2189 return 2190 } 2191 2192 if users == nil { 2193 users = make([]*user_model.User, 0, len(mentionUsers)) 2194 } 2195 2196 unchecked := make([]*user_model.User, 0, len(mentionUsers)) 2197 if err := db.GetEngine(ctx). 2198 Where("`user`.is_active = ?", true). 2199 And("`user`.prohibit_login = ?", false). 2200 In("`user`.lower_name", mentionUsers). 2201 Find(&unchecked); err != nil { 2202 return nil, fmt.Errorf("find mentioned users: %v", err) 2203 } 2204 for _, user := range unchecked { 2205 if already := resolved[user.LowerName]; already || user.IsOrganization() { 2206 continue 2207 } 2208 // Normal users must have read access to the referencing issue 2209 perm, err := getUserRepoPermission(ctx, issue.Repo, user) 2210 if err != nil { 2211 return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err) 2212 } 2213 if !perm.CanReadIssuesOrPulls(issue.IsPull) { 2214 continue 2215 } 2216 users = append(users, user) 2217 } 2218 2219 return 2220} 2221 2222// UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID 2223func UpdateIssuesMigrationsByType(gitServiceType api.GitServiceType, originalAuthorID string, posterID int64) error { 2224 _, err := db.GetEngine(db.DefaultContext).Table("issue"). 2225 Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType). 2226 And("original_author_id = ?", originalAuthorID). 2227 Update(map[string]interface{}{ 2228 "poster_id": posterID, 2229 "original_author": "", 2230 "original_author_id": 0, 2231 }) 2232 return err 2233} 2234 2235// UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID 2236func UpdateReactionsMigrationsByType(gitServiceType api.GitServiceType, originalAuthorID string, userID int64) error { 2237 _, err := db.GetEngine(db.DefaultContext).Table("reaction"). 2238 Where("original_author_id = ?", originalAuthorID). 2239 And(migratedIssueCond(gitServiceType)). 2240 Update(map[string]interface{}{ 2241 "user_id": userID, 2242 "original_author": "", 2243 "original_author_id": 0, 2244 }) 2245 return err 2246} 2247 2248func deleteIssuesByRepoID(sess db.Engine, repoID int64) (attachmentPaths []string, err error) { 2249 deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID}) 2250 2251 // Delete content histories 2252 if _, err = sess.In("issue_id", deleteCond). 2253 Delete(&issues.ContentHistory{}); err != nil { 2254 return 2255 } 2256 2257 // Delete comments and attachments 2258 if _, err = sess.In("issue_id", deleteCond). 2259 Delete(&Comment{}); err != nil { 2260 return 2261 } 2262 2263 // Dependencies for issues in this repository 2264 if _, err = sess.In("issue_id", deleteCond). 2265 Delete(&IssueDependency{}); err != nil { 2266 return 2267 } 2268 2269 // Delete dependencies for issues in other repositories 2270 if _, err = sess.In("dependency_id", deleteCond). 2271 Delete(&IssueDependency{}); err != nil { 2272 return 2273 } 2274 2275 if _, err = sess.In("issue_id", deleteCond). 2276 Delete(&IssueUser{}); err != nil { 2277 return 2278 } 2279 2280 if _, err = sess.In("issue_id", deleteCond). 2281 Delete(&Reaction{}); err != nil { 2282 return 2283 } 2284 2285 if _, err = sess.In("issue_id", deleteCond). 2286 Delete(&IssueWatch{}); err != nil { 2287 return 2288 } 2289 2290 if _, err = sess.In("issue_id", deleteCond). 2291 Delete(&Stopwatch{}); err != nil { 2292 return 2293 } 2294 2295 if _, err = sess.In("issue_id", deleteCond). 2296 Delete(&TrackedTime{}); err != nil { 2297 return 2298 } 2299 2300 if _, err = sess.In("issue_id", deleteCond). 2301 Delete(&ProjectIssue{}); err != nil { 2302 return 2303 } 2304 2305 if _, err = sess.In("dependent_issue_id", deleteCond). 2306 Delete(&Comment{}); err != nil { 2307 return 2308 } 2309 2310 var attachments []*repo_model.Attachment 2311 if err = sess.In("issue_id", deleteCond). 2312 Find(&attachments); err != nil { 2313 return 2314 } 2315 2316 for j := range attachments { 2317 attachmentPaths = append(attachmentPaths, attachments[j].RelativePath()) 2318 } 2319 2320 if _, err = sess.In("issue_id", deleteCond). 2321 Delete(&repo_model.Attachment{}); err != nil { 2322 return 2323 } 2324 2325 if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil { 2326 return 2327 } 2328 2329 return 2330} 2331