選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

issue.go 50KB

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