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.

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