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

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