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

issue.go 49KB

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