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

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