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

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