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

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