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

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