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.

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