Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

issue.go 51KB

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