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.

issue.go 45KB

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