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

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