You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 49KB

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