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

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