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.

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