You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 59KB

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