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 51KB

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