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

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