Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

issue.go 58KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2020 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package models
  6. import (
  7. "fmt"
  8. "regexp"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "code.gitea.io/gitea/modules/base"
  13. "code.gitea.io/gitea/modules/log"
  14. "code.gitea.io/gitea/modules/references"
  15. "code.gitea.io/gitea/modules/setting"
  16. "code.gitea.io/gitea/modules/structs"
  17. api "code.gitea.io/gitea/modules/structs"
  18. "code.gitea.io/gitea/modules/timeutil"
  19. "code.gitea.io/gitea/modules/util"
  20. "xorm.io/builder"
  21. "xorm.io/xorm"
  22. )
  23. // Issue represents an issue or pull request of repository.
  24. type Issue struct {
  25. ID int64 `xorm:"pk autoincr"`
  26. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  27. Repo *Repository `xorm:"-"`
  28. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  29. PosterID int64 `xorm:"INDEX"`
  30. Poster *User `xorm:"-"`
  31. OriginalAuthor string
  32. OriginalAuthorID int64 `xorm:"index"`
  33. Title string `xorm:"name"`
  34. Content string `xorm:"TEXT"`
  35. RenderedContent string `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64 `xorm:"INDEX"`
  38. Milestone *Milestone `xorm:"-"`
  39. Project *Project `xorm:"-"`
  40. Priority int
  41. AssigneeID int64 `xorm:"-"`
  42. Assignee *User `xorm:"-"`
  43. IsClosed bool `xorm:"INDEX"`
  44. IsRead bool `xorm:"-"`
  45. IsPull bool `xorm:"INDEX"` // Indicates whether is a pull request or not.
  46. PullRequest *PullRequest `xorm:"-"`
  47. NumComments int
  48. Ref string
  49. DeadlineUnix timeutil.TimeStamp `xorm:"INDEX"`
  50. CreatedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  51. UpdatedUnix timeutil.TimeStamp `xorm:"INDEX updated"`
  52. ClosedUnix timeutil.TimeStamp `xorm:"INDEX"`
  53. Attachments []*Attachment `xorm:"-"`
  54. Comments []*Comment `xorm:"-"`
  55. Reactions ReactionList `xorm:"-"`
  56. TotalTrackedTime int64 `xorm:"-"`
  57. Assignees []*User `xorm:"-"`
  58. // IsLocked limits commenting abilities to users on an issue
  59. // with write access
  60. IsLocked bool `xorm:"NOT NULL DEFAULT false"`
  61. // For view issue page.
  62. ShowTag CommentTag `xorm:"-"`
  63. }
  64. var (
  65. issueTasksPat *regexp.Regexp
  66. issueTasksDonePat *regexp.Regexp
  67. )
  68. const 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 fmt.Sprintf("issue-%d", 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. UpdatedAfterUnix int64
  943. UpdatedBeforeUnix int64
  944. // prioritize issues from this repo
  945. PriorityRepoID int64
  946. IsArchived util.OptionalBool
  947. }
  948. // sortIssuesSession sort an issues-related session based on the provided
  949. // sortType string
  950. func sortIssuesSession(sess *xorm.Session, sortType string, priorityRepoID int64) {
  951. switch sortType {
  952. case "oldest":
  953. sess.Asc("issue.created_unix")
  954. case "recentupdate":
  955. sess.Desc("issue.updated_unix")
  956. case "leastupdate":
  957. sess.Asc("issue.updated_unix")
  958. case "mostcomment":
  959. sess.Desc("issue.num_comments")
  960. case "leastcomment":
  961. sess.Asc("issue.num_comments")
  962. case "priority":
  963. sess.Desc("issue.priority")
  964. case "nearduedate":
  965. // 253370764800 is 01/01/9999 @ 12:00am (UTC)
  966. sess.OrderBy("CASE WHEN issue.deadline_unix = 0 THEN 253370764800 ELSE issue.deadline_unix END ASC")
  967. case "farduedate":
  968. sess.Desc("issue.deadline_unix")
  969. case "priorityrepo":
  970. sess.OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(priorityRepoID, 10) + " THEN 1 ELSE 2 END, issue.created_unix DESC")
  971. default:
  972. sess.Desc("issue.created_unix")
  973. }
  974. }
  975. func (opts *IssuesOptions) setupSession(sess *xorm.Session) {
  976. if opts.Page >= 0 && opts.PageSize > 0 {
  977. var start int
  978. if opts.Page == 0 {
  979. start = 0
  980. } else {
  981. start = (opts.Page - 1) * opts.PageSize
  982. }
  983. sess.Limit(opts.PageSize, start)
  984. }
  985. if len(opts.IssueIDs) > 0 {
  986. sess.In("issue.id", opts.IssueIDs)
  987. }
  988. if len(opts.RepoIDs) > 0 {
  989. // In case repository IDs are provided but actually no repository has issue.
  990. sess.In("issue.repo_id", opts.RepoIDs)
  991. }
  992. switch opts.IsClosed {
  993. case util.OptionalBoolTrue:
  994. sess.And("issue.is_closed=?", true)
  995. case util.OptionalBoolFalse:
  996. sess.And("issue.is_closed=?", false)
  997. }
  998. if opts.AssigneeID > 0 {
  999. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1000. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1001. }
  1002. if opts.PosterID > 0 {
  1003. sess.And("issue.poster_id=?", opts.PosterID)
  1004. }
  1005. if opts.MentionedID > 0 {
  1006. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1007. And("issue_user.is_mentioned = ?", true).
  1008. And("issue_user.uid = ?", opts.MentionedID)
  1009. }
  1010. if len(opts.MilestoneIDs) > 0 {
  1011. sess.In("issue.milestone_id", opts.MilestoneIDs)
  1012. }
  1013. if opts.UpdatedAfterUnix != 0 {
  1014. sess.And(builder.Gte{"issue.updated_unix": opts.UpdatedAfterUnix})
  1015. }
  1016. if opts.UpdatedBeforeUnix != 0 {
  1017. sess.And(builder.Lte{"issue.updated_unix": opts.UpdatedBeforeUnix})
  1018. }
  1019. if opts.ProjectID > 0 {
  1020. sess.Join("INNER", "project_issue", "issue.id = project_issue.issue_id").
  1021. And("project_issue.project_id=?", opts.ProjectID)
  1022. }
  1023. if opts.ProjectBoardID != 0 {
  1024. if opts.ProjectBoardID > 0 {
  1025. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": opts.ProjectBoardID}))
  1026. } else {
  1027. sess.In("issue.id", builder.Select("issue_id").From("project_issue").Where(builder.Eq{"project_board_id": 0}))
  1028. }
  1029. }
  1030. switch opts.IsPull {
  1031. case util.OptionalBoolTrue:
  1032. sess.And("issue.is_pull=?", true)
  1033. case util.OptionalBoolFalse:
  1034. sess.And("issue.is_pull=?", false)
  1035. }
  1036. if opts.IsArchived != util.OptionalBoolNone {
  1037. sess.Join("INNER", "repository", "issue.repo_id = repository.id").And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()})
  1038. }
  1039. if opts.LabelIDs != nil {
  1040. for i, labelID := range opts.LabelIDs {
  1041. if labelID > 0 {
  1042. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1043. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1044. } else {
  1045. sess.Where("issue.id not in (select issue_id from issue_label where label_id = ?)", -labelID)
  1046. }
  1047. }
  1048. }
  1049. if len(opts.IncludedLabelNames) > 0 {
  1050. sess.In("issue.id", BuildLabelNamesIssueIDsCondition(opts.IncludedLabelNames))
  1051. }
  1052. if len(opts.ExcludedLabelNames) > 0 {
  1053. sess.And(builder.NotIn("issue.id", BuildLabelNamesIssueIDsCondition(opts.ExcludedLabelNames)))
  1054. }
  1055. }
  1056. // CountIssuesByRepo map from repoID to number of issues matching the options
  1057. func CountIssuesByRepo(opts *IssuesOptions) (map[int64]int64, error) {
  1058. sess := x.NewSession()
  1059. defer sess.Close()
  1060. opts.setupSession(sess)
  1061. countsSlice := make([]*struct {
  1062. RepoID int64
  1063. Count int64
  1064. }, 0, 10)
  1065. if err := sess.GroupBy("issue.repo_id").
  1066. Select("issue.repo_id AS repo_id, COUNT(*) AS count").
  1067. Table("issue").
  1068. Find(&countsSlice); err != nil {
  1069. return nil, err
  1070. }
  1071. countMap := make(map[int64]int64, len(countsSlice))
  1072. for _, c := range countsSlice {
  1073. countMap[c.RepoID] = c.Count
  1074. }
  1075. return countMap, nil
  1076. }
  1077. // GetRepoIDsForIssuesOptions find all repo ids for the given options
  1078. func GetRepoIDsForIssuesOptions(opts *IssuesOptions, user *User) ([]int64, error) {
  1079. repoIDs := make([]int64, 0, 5)
  1080. sess := x.NewSession()
  1081. defer sess.Close()
  1082. opts.setupSession(sess)
  1083. accessCond := accessibleRepositoryCondition(user)
  1084. if err := sess.Where(accessCond).
  1085. Join("INNER", "repository", "`issue`.repo_id = `repository`.id").
  1086. Distinct("issue.repo_id").
  1087. Table("issue").
  1088. Find(&repoIDs); err != nil {
  1089. return nil, err
  1090. }
  1091. return repoIDs, nil
  1092. }
  1093. // Issues returns a list of issues by given conditions.
  1094. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  1095. sess := x.NewSession()
  1096. defer sess.Close()
  1097. opts.setupSession(sess)
  1098. sortIssuesSession(sess, opts.SortType, opts.PriorityRepoID)
  1099. issues := make([]*Issue, 0, opts.ListOptions.PageSize)
  1100. if err := sess.Find(&issues); err != nil {
  1101. return nil, fmt.Errorf("Find: %v", err)
  1102. }
  1103. sess.Close()
  1104. if err := IssueList(issues).LoadAttributes(); err != nil {
  1105. return nil, fmt.Errorf("LoadAttributes: %v", err)
  1106. }
  1107. return issues, nil
  1108. }
  1109. // CountIssues number return of issues by given conditions.
  1110. func CountIssues(opts *IssuesOptions) (int64, error) {
  1111. sess := x.NewSession()
  1112. defer sess.Close()
  1113. countsSlice := make([]*struct {
  1114. RepoID int64
  1115. Count int64
  1116. }, 0, 1)
  1117. sess.Select("COUNT(issue.id) AS count").Table("issue")
  1118. opts.setupSession(sess)
  1119. if err := sess.Find(&countsSlice); err != nil {
  1120. return 0, fmt.Errorf("Find: %v", err)
  1121. }
  1122. if len(countsSlice) < 1 {
  1123. return 0, fmt.Errorf("there is less than one result sql record")
  1124. }
  1125. return countsSlice[0].Count, nil
  1126. }
  1127. // GetParticipantsIDsByIssueID returns the IDs of all users who participated in comments of an issue,
  1128. // but skips joining with `user` for performance reasons.
  1129. // User permissions must be verified elsewhere if required.
  1130. func GetParticipantsIDsByIssueID(issueID int64) ([]int64, error) {
  1131. userIDs := make([]int64, 0, 5)
  1132. return userIDs, x.Table("comment").
  1133. Cols("poster_id").
  1134. Where("issue_id = ?", issueID).
  1135. And("type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1136. Distinct("poster_id").
  1137. Find(&userIDs)
  1138. }
  1139. // IsUserParticipantsOfIssue return true if user is participants of an issue
  1140. func IsUserParticipantsOfIssue(user *User, issue *Issue) bool {
  1141. userIDs, err := issue.getParticipantIDsByIssue(x)
  1142. if err != nil {
  1143. log.Error(err.Error())
  1144. return false
  1145. }
  1146. return util.IsInt64InSlice(user.ID, userIDs)
  1147. }
  1148. // UpdateIssueMentions updates issue-user relations for mentioned users.
  1149. func UpdateIssueMentions(ctx DBContext, issueID int64, mentions []*User) error {
  1150. if len(mentions) == 0 {
  1151. return nil
  1152. }
  1153. ids := make([]int64, len(mentions))
  1154. for i, u := range mentions {
  1155. ids[i] = u.ID
  1156. }
  1157. if err := UpdateIssueUsersByMentions(ctx, issueID, ids); err != nil {
  1158. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  1159. }
  1160. return nil
  1161. }
  1162. // IssueStats represents issue statistic information.
  1163. type IssueStats struct {
  1164. OpenCount, ClosedCount int64
  1165. YourRepositoriesCount int64
  1166. AssignCount int64
  1167. CreateCount int64
  1168. MentionCount int64
  1169. }
  1170. // Filter modes.
  1171. const (
  1172. FilterModeAll = iota
  1173. FilterModeAssign
  1174. FilterModeCreate
  1175. FilterModeMention
  1176. )
  1177. func parseCountResult(results []map[string][]byte) int64 {
  1178. if len(results) == 0 {
  1179. return 0
  1180. }
  1181. for _, result := range results[0] {
  1182. c, _ := strconv.ParseInt(string(result), 10, 64)
  1183. return c
  1184. }
  1185. return 0
  1186. }
  1187. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1188. type IssueStatsOptions struct {
  1189. RepoID int64
  1190. Labels string
  1191. MilestoneID int64
  1192. AssigneeID int64
  1193. MentionedID int64
  1194. PosterID int64
  1195. IsPull util.OptionalBool
  1196. IssueIDs []int64
  1197. }
  1198. // GetIssueStats returns issue statistic information by given conditions.
  1199. func GetIssueStats(opts *IssueStatsOptions) (*IssueStats, error) {
  1200. if len(opts.IssueIDs) <= maxQueryParameters {
  1201. return getIssueStatsChunk(opts, opts.IssueIDs)
  1202. }
  1203. // If too long a list of IDs is provided, we get the statistics in
  1204. // smaller chunks and get accumulates. Note: this could potentially
  1205. // get us invalid results. The alternative is to insert the list of
  1206. // ids in a temporary table and join from them.
  1207. accum := &IssueStats{}
  1208. for i := 0; i < len(opts.IssueIDs); {
  1209. chunk := i + maxQueryParameters
  1210. if chunk > len(opts.IssueIDs) {
  1211. chunk = len(opts.IssueIDs)
  1212. }
  1213. stats, err := getIssueStatsChunk(opts, opts.IssueIDs[i:chunk])
  1214. if err != nil {
  1215. return nil, err
  1216. }
  1217. accum.OpenCount += stats.OpenCount
  1218. accum.ClosedCount += stats.ClosedCount
  1219. accum.YourRepositoriesCount += stats.YourRepositoriesCount
  1220. accum.AssignCount += stats.AssignCount
  1221. accum.CreateCount += stats.CreateCount
  1222. accum.OpenCount += stats.MentionCount
  1223. i = chunk
  1224. }
  1225. return accum, nil
  1226. }
  1227. func getIssueStatsChunk(opts *IssueStatsOptions, issueIDs []int64) (*IssueStats, error) {
  1228. stats := &IssueStats{}
  1229. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1230. sess := x.
  1231. Where("issue.repo_id = ?", opts.RepoID)
  1232. if len(opts.IssueIDs) > 0 {
  1233. sess.In("issue.id", opts.IssueIDs)
  1234. }
  1235. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1236. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1237. if err != nil {
  1238. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1239. } else {
  1240. for i, labelID := range labelIDs {
  1241. if labelID > 0 {
  1242. sess.Join("INNER", fmt.Sprintf("issue_label il%d", i),
  1243. fmt.Sprintf("issue.id = il%[1]d.issue_id AND il%[1]d.label_id = %[2]d", i, labelID))
  1244. } else {
  1245. sess.Where("issue.id NOT IN (SELECT issue_id FROM issue_label WHERE label_id = ?)", -labelID)
  1246. }
  1247. }
  1248. }
  1249. }
  1250. if opts.MilestoneID > 0 {
  1251. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1252. }
  1253. if opts.AssigneeID > 0 {
  1254. sess.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1255. And("issue_assignees.assignee_id = ?", opts.AssigneeID)
  1256. }
  1257. if opts.PosterID > 0 {
  1258. sess.And("issue.poster_id = ?", opts.PosterID)
  1259. }
  1260. if opts.MentionedID > 0 {
  1261. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1262. And("issue_user.uid = ?", opts.MentionedID).
  1263. And("issue_user.is_mentioned = ?", true)
  1264. }
  1265. switch opts.IsPull {
  1266. case util.OptionalBoolTrue:
  1267. sess.And("issue.is_pull=?", true)
  1268. case util.OptionalBoolFalse:
  1269. sess.And("issue.is_pull=?", false)
  1270. }
  1271. return sess
  1272. }
  1273. var err error
  1274. stats.OpenCount, err = countSession(opts).
  1275. And("issue.is_closed = ?", false).
  1276. Count(new(Issue))
  1277. if err != nil {
  1278. return stats, err
  1279. }
  1280. stats.ClosedCount, err = countSession(opts).
  1281. And("issue.is_closed = ?", true).
  1282. Count(new(Issue))
  1283. return stats, err
  1284. }
  1285. // UserIssueStatsOptions contains parameters accepted by GetUserIssueStats.
  1286. type UserIssueStatsOptions struct {
  1287. UserID int64
  1288. RepoIDs []int64
  1289. UserRepoIDs []int64
  1290. FilterMode int
  1291. IsPull bool
  1292. IsClosed bool
  1293. IssueIDs []int64
  1294. IsArchived util.OptionalBool
  1295. LabelIDs []int64
  1296. }
  1297. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1298. func GetUserIssueStats(opts UserIssueStatsOptions) (*IssueStats, error) {
  1299. var err error
  1300. stats := &IssueStats{}
  1301. cond := builder.NewCond()
  1302. cond = cond.And(builder.Eq{"issue.is_pull": opts.IsPull})
  1303. if len(opts.RepoIDs) > 0 {
  1304. cond = cond.And(builder.In("issue.repo_id", opts.RepoIDs))
  1305. }
  1306. if len(opts.IssueIDs) > 0 {
  1307. cond = cond.And(builder.In("issue.id", opts.IssueIDs))
  1308. }
  1309. sess := func(cond builder.Cond) *xorm.Session {
  1310. s := x.Where(cond)
  1311. if len(opts.LabelIDs) > 0 {
  1312. s.Join("INNER", "issue_label", "issue_label.issue_id = issue.id").
  1313. In("issue_label.label_id", opts.LabelIDs)
  1314. }
  1315. if opts.IsArchived != util.OptionalBoolNone {
  1316. s.Join("INNER", "repository", "issue.repo_id = repository.id").
  1317. And(builder.Eq{"repository.is_archived": opts.IsArchived.IsTrue()})
  1318. }
  1319. return s
  1320. }
  1321. switch opts.FilterMode {
  1322. case FilterModeAll:
  1323. stats.OpenCount, err = sess(cond).And("issue.is_closed = ?", false).
  1324. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1325. Count(new(Issue))
  1326. if err != nil {
  1327. return nil, err
  1328. }
  1329. stats.ClosedCount, err = sess(cond).And("issue.is_closed = ?", true).
  1330. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1331. Count(new(Issue))
  1332. if err != nil {
  1333. return nil, err
  1334. }
  1335. case FilterModeAssign:
  1336. stats.OpenCount, err = sess(cond).And("issue.is_closed = ?", false).
  1337. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1338. And("issue_assignees.assignee_id = ?", opts.UserID).
  1339. Count(new(Issue))
  1340. if err != nil {
  1341. return nil, err
  1342. }
  1343. stats.ClosedCount, err = sess(cond).And("issue.is_closed = ?", true).
  1344. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1345. And("issue_assignees.assignee_id = ?", opts.UserID).
  1346. Count(new(Issue))
  1347. if err != nil {
  1348. return nil, err
  1349. }
  1350. case FilterModeCreate:
  1351. stats.OpenCount, err = sess(cond).And("issue.is_closed = ?", false).
  1352. And("issue.poster_id = ?", opts.UserID).
  1353. Count(new(Issue))
  1354. if err != nil {
  1355. return nil, err
  1356. }
  1357. stats.ClosedCount, err = sess(cond).And("issue.is_closed = ?", true).
  1358. And("issue.poster_id = ?", opts.UserID).
  1359. Count(new(Issue))
  1360. if err != nil {
  1361. return nil, err
  1362. }
  1363. case FilterModeMention:
  1364. stats.OpenCount, err = sess(cond).And("issue.is_closed = ?", false).
  1365. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1366. And("issue_user.uid = ?", opts.UserID).
  1367. Count(new(Issue))
  1368. if err != nil {
  1369. return nil, err
  1370. }
  1371. stats.ClosedCount, err = sess(cond).And("issue.is_closed = ?", true).
  1372. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1373. And("issue_user.uid = ?", opts.UserID).
  1374. Count(new(Issue))
  1375. if err != nil {
  1376. return nil, err
  1377. }
  1378. }
  1379. cond = cond.And(builder.Eq{"issue.is_closed": opts.IsClosed})
  1380. stats.AssignCount, err = sess(cond).
  1381. Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1382. And("issue_assignees.assignee_id = ?", opts.UserID).
  1383. Count(new(Issue))
  1384. if err != nil {
  1385. return nil, err
  1386. }
  1387. stats.CreateCount, err = sess(cond).
  1388. And("poster_id = ?", opts.UserID).
  1389. Count(new(Issue))
  1390. if err != nil {
  1391. return nil, err
  1392. }
  1393. stats.MentionCount, err = sess(cond).
  1394. Join("INNER", "issue_user", "issue.id = issue_user.issue_id and issue_user.is_mentioned = ?", true).
  1395. And("issue_user.uid = ?", opts.UserID).
  1396. Count(new(Issue))
  1397. if err != nil {
  1398. return nil, err
  1399. }
  1400. stats.YourRepositoriesCount, err = sess(cond).
  1401. And(builder.In("issue.repo_id", opts.UserRepoIDs)).
  1402. Count(new(Issue))
  1403. if err != nil {
  1404. return nil, err
  1405. }
  1406. return stats, nil
  1407. }
  1408. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1409. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1410. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1411. sess := x.
  1412. Where("is_closed = ?", isClosed).
  1413. And("is_pull = ?", isPull).
  1414. And("repo_id = ?", repoID)
  1415. return sess
  1416. }
  1417. openCountSession := countSession(false, isPull, repoID)
  1418. closedCountSession := countSession(true, isPull, repoID)
  1419. switch filterMode {
  1420. case FilterModeAssign:
  1421. openCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1422. And("issue_assignees.assignee_id = ?", uid)
  1423. closedCountSession.Join("INNER", "issue_assignees", "issue.id = issue_assignees.issue_id").
  1424. And("issue_assignees.assignee_id = ?", uid)
  1425. case FilterModeCreate:
  1426. openCountSession.And("poster_id = ?", uid)
  1427. closedCountSession.And("poster_id = ?", uid)
  1428. }
  1429. openResult, _ := openCountSession.Count(new(Issue))
  1430. closedResult, _ := closedCountSession.Count(new(Issue))
  1431. return openResult, closedResult
  1432. }
  1433. // SearchIssueIDsByKeyword search issues on database
  1434. func SearchIssueIDsByKeyword(kw string, repoIDs []int64, limit, start int) (int64, []int64, error) {
  1435. var repoCond = builder.In("repo_id", repoIDs)
  1436. var subQuery = builder.Select("id").From("issue").Where(repoCond)
  1437. var cond = builder.And(
  1438. repoCond,
  1439. builder.Or(
  1440. builder.Like{"name", kw},
  1441. builder.Like{"content", kw},
  1442. builder.In("id", builder.Select("issue_id").
  1443. From("comment").
  1444. Where(builder.And(
  1445. builder.Eq{"type": CommentTypeComment},
  1446. builder.In("issue_id", subQuery),
  1447. builder.Like{"content", kw},
  1448. )),
  1449. ),
  1450. ),
  1451. )
  1452. var ids = make([]int64, 0, limit)
  1453. err := x.Distinct("id").Table("issue").Where(cond).Limit(limit, start).Find(&ids)
  1454. if err != nil {
  1455. return 0, nil, err
  1456. }
  1457. total, err := x.Distinct("id").Table("issue").Where(cond).Count()
  1458. if err != nil {
  1459. return 0, nil, err
  1460. }
  1461. return total, ids, nil
  1462. }
  1463. // UpdateIssueByAPI updates all allowed fields of given issue.
  1464. // If the issue status is changed a statusChangeComment is returned
  1465. // similarly if the title is changed the titleChanged bool is set to true
  1466. func UpdateIssueByAPI(issue *Issue, doer *User) (statusChangeComment *Comment, titleChanged bool, err error) {
  1467. sess := x.NewSession()
  1468. defer sess.Close()
  1469. if err := sess.Begin(); err != nil {
  1470. return nil, false, err
  1471. }
  1472. if err := issue.loadRepo(sess); err != nil {
  1473. return nil, false, fmt.Errorf("loadRepo: %v", err)
  1474. }
  1475. // Reload the issue
  1476. currentIssue, err := getIssueByID(sess, issue.ID)
  1477. if err != nil {
  1478. return nil, false, err
  1479. }
  1480. if _, err := sess.ID(issue.ID).Cols(
  1481. "name", "content", "milestone_id", "priority",
  1482. "deadline_unix", "updated_unix", "is_locked").
  1483. Update(issue); err != nil {
  1484. return nil, false, err
  1485. }
  1486. titleChanged = currentIssue.Title != issue.Title
  1487. if titleChanged {
  1488. var opts = &CreateCommentOptions{
  1489. Type: CommentTypeChangeTitle,
  1490. Doer: doer,
  1491. Repo: issue.Repo,
  1492. Issue: issue,
  1493. OldTitle: currentIssue.Title,
  1494. NewTitle: issue.Title,
  1495. }
  1496. _, err := createComment(sess, opts)
  1497. if err != nil {
  1498. return nil, false, fmt.Errorf("createComment: %v", err)
  1499. }
  1500. }
  1501. if currentIssue.IsClosed != issue.IsClosed {
  1502. statusChangeComment, err = issue.doChangeStatus(sess, doer, false)
  1503. if err != nil {
  1504. return nil, false, err
  1505. }
  1506. }
  1507. if err := issue.addCrossReferences(sess, doer, true); err != nil {
  1508. return nil, false, err
  1509. }
  1510. return statusChangeComment, titleChanged, sess.Commit()
  1511. }
  1512. // UpdateIssueDeadline updates an issue deadline and adds comments. Setting a deadline to 0 means deleting it.
  1513. func UpdateIssueDeadline(issue *Issue, deadlineUnix timeutil.TimeStamp, doer *User) (err error) {
  1514. // if the deadline hasn't changed do nothing
  1515. if issue.DeadlineUnix == deadlineUnix {
  1516. return nil
  1517. }
  1518. sess := x.NewSession()
  1519. defer sess.Close()
  1520. if err := sess.Begin(); err != nil {
  1521. return err
  1522. }
  1523. // Update the deadline
  1524. if err = updateIssueCols(sess, &Issue{ID: issue.ID, DeadlineUnix: deadlineUnix}, "deadline_unix"); err != nil {
  1525. return err
  1526. }
  1527. // Make the comment
  1528. if _, err = createDeadlineComment(sess, doer, issue, deadlineUnix); err != nil {
  1529. return fmt.Errorf("createRemovedDueDateComment: %v", err)
  1530. }
  1531. return sess.Commit()
  1532. }
  1533. // DependencyInfo represents high level information about an issue which is a dependency of another issue.
  1534. type DependencyInfo struct {
  1535. Issue `xorm:"extends"`
  1536. Repository `xorm:"extends"`
  1537. }
  1538. // getParticipantIDsByIssue returns all userIDs who are participated in comments of an issue and issue author
  1539. func (issue *Issue) getParticipantIDsByIssue(e Engine) ([]int64, error) {
  1540. if issue == nil {
  1541. return nil, nil
  1542. }
  1543. userIDs := make([]int64, 0, 5)
  1544. if err := e.Table("comment").Cols("poster_id").
  1545. Where("`comment`.issue_id = ?", issue.ID).
  1546. And("`comment`.type in (?,?,?)", CommentTypeComment, CommentTypeCode, CommentTypeReview).
  1547. And("`user`.is_active = ?", true).
  1548. And("`user`.prohibit_login = ?", false).
  1549. Join("INNER", "`user`", "`user`.id = `comment`.poster_id").
  1550. Distinct("poster_id").
  1551. Find(&userIDs); err != nil {
  1552. return nil, fmt.Errorf("get poster IDs: %v", err)
  1553. }
  1554. if !util.IsInt64InSlice(issue.PosterID, userIDs) {
  1555. return append(userIDs, issue.PosterID), nil
  1556. }
  1557. return userIDs, nil
  1558. }
  1559. // Get Blocked By Dependencies, aka all issues this issue is blocked by.
  1560. func (issue *Issue) getBlockedByDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1561. return issueDeps, e.
  1562. Table("issue").
  1563. Join("INNER", "repository", "repository.id = issue.repo_id").
  1564. Join("INNER", "issue_dependency", "issue_dependency.dependency_id = issue.id").
  1565. Where("issue_id = ?", issue.ID).
  1566. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1567. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1568. Find(&issueDeps)
  1569. }
  1570. // Get Blocking Dependencies, aka all issues this issue blocks.
  1571. func (issue *Issue) getBlockingDependencies(e Engine) (issueDeps []*DependencyInfo, err error) {
  1572. return issueDeps, e.
  1573. Table("issue").
  1574. Join("INNER", "repository", "repository.id = issue.repo_id").
  1575. Join("INNER", "issue_dependency", "issue_dependency.issue_id = issue.id").
  1576. Where("dependency_id = ?", issue.ID).
  1577. //sort by repo id then created date, with the issues of the same repo at the beginning of the list
  1578. OrderBy("CASE WHEN issue.repo_id = " + strconv.FormatInt(issue.RepoID, 10) + " THEN 0 ELSE issue.repo_id END, issue.created_unix DESC").
  1579. Find(&issueDeps)
  1580. }
  1581. // BlockedByDependencies finds all Dependencies an issue is blocked by
  1582. func (issue *Issue) BlockedByDependencies() ([]*DependencyInfo, error) {
  1583. return issue.getBlockedByDependencies(x)
  1584. }
  1585. // BlockingDependencies returns all blocking dependencies, aka all other issues a given issue blocks
  1586. func (issue *Issue) BlockingDependencies() ([]*DependencyInfo, error) {
  1587. return issue.getBlockingDependencies(x)
  1588. }
  1589. func (issue *Issue) updateClosedNum(e Engine) (err error) {
  1590. if issue.IsPull {
  1591. _, err = e.Exec("UPDATE `repository` SET num_closed_pulls=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1592. issue.RepoID,
  1593. true,
  1594. true,
  1595. issue.RepoID,
  1596. )
  1597. } else {
  1598. _, err = e.Exec("UPDATE `repository` SET num_closed_issues=(SELECT count(*) FROM issue WHERE repo_id=? AND is_pull=? AND is_closed=?) WHERE id=?",
  1599. issue.RepoID,
  1600. false,
  1601. true,
  1602. issue.RepoID,
  1603. )
  1604. }
  1605. return
  1606. }
  1607. // FindAndUpdateIssueMentions finds users mentioned in the given content string, and saves them in the database.
  1608. func (issue *Issue) FindAndUpdateIssueMentions(ctx DBContext, doer *User, content string) (mentions []*User, err error) {
  1609. rawMentions := references.FindAllMentionsMarkdown(content)
  1610. mentions, err = issue.ResolveMentionsByVisibility(ctx, doer, rawMentions)
  1611. if err != nil {
  1612. return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
  1613. }
  1614. if err = UpdateIssueMentions(ctx, issue.ID, mentions); err != nil {
  1615. return nil, fmt.Errorf("UpdateIssueMentions [%d]: %v", issue.ID, err)
  1616. }
  1617. return
  1618. }
  1619. // ResolveMentionsByVisibility returns the users mentioned in an issue, removing those that
  1620. // don't have access to reading it. Teams are expanded into their users, but organizations are ignored.
  1621. func (issue *Issue) ResolveMentionsByVisibility(ctx DBContext, doer *User, mentions []string) (users []*User, err error) {
  1622. if len(mentions) == 0 {
  1623. return
  1624. }
  1625. if err = issue.loadRepo(ctx.e); err != nil {
  1626. return
  1627. }
  1628. resolved := make(map[string]bool, 10)
  1629. var mentionTeams []string
  1630. if err := issue.Repo.getOwner(ctx.e); err != nil {
  1631. return nil, err
  1632. }
  1633. repoOwnerIsOrg := issue.Repo.Owner.IsOrganization()
  1634. if repoOwnerIsOrg {
  1635. mentionTeams = make([]string, 0, 5)
  1636. }
  1637. resolved[doer.LowerName] = true
  1638. for _, name := range mentions {
  1639. name := strings.ToLower(name)
  1640. if _, ok := resolved[name]; ok {
  1641. continue
  1642. }
  1643. if repoOwnerIsOrg && strings.Contains(name, "/") {
  1644. names := strings.Split(name, "/")
  1645. if len(names) < 2 || names[0] != issue.Repo.Owner.LowerName {
  1646. continue
  1647. }
  1648. mentionTeams = append(mentionTeams, names[1])
  1649. resolved[name] = true
  1650. } else {
  1651. resolved[name] = false
  1652. }
  1653. }
  1654. if issue.Repo.Owner.IsOrganization() && len(mentionTeams) > 0 {
  1655. teams := make([]*Team, 0, len(mentionTeams))
  1656. if err := ctx.e.
  1657. Join("INNER", "team_repo", "team_repo.team_id = team.id").
  1658. Where("team_repo.repo_id=?", issue.Repo.ID).
  1659. In("team.lower_name", mentionTeams).
  1660. Find(&teams); err != nil {
  1661. return nil, fmt.Errorf("find mentioned teams: %v", err)
  1662. }
  1663. if len(teams) != 0 {
  1664. checked := make([]int64, 0, len(teams))
  1665. unittype := UnitTypeIssues
  1666. if issue.IsPull {
  1667. unittype = UnitTypePullRequests
  1668. }
  1669. for _, team := range teams {
  1670. if team.Authorize >= AccessModeOwner {
  1671. checked = append(checked, team.ID)
  1672. resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true
  1673. continue
  1674. }
  1675. has, err := ctx.e.Get(&TeamUnit{OrgID: issue.Repo.Owner.ID, TeamID: team.ID, Type: unittype})
  1676. if err != nil {
  1677. return nil, fmt.Errorf("get team units (%d): %v", team.ID, err)
  1678. }
  1679. if has {
  1680. checked = append(checked, team.ID)
  1681. resolved[issue.Repo.Owner.LowerName+"/"+team.LowerName] = true
  1682. }
  1683. }
  1684. if len(checked) != 0 {
  1685. teamusers := make([]*User, 0, 20)
  1686. if err := ctx.e.
  1687. Join("INNER", "team_user", "team_user.uid = `user`.id").
  1688. In("`team_user`.team_id", checked).
  1689. And("`user`.is_active = ?", true).
  1690. And("`user`.prohibit_login = ?", false).
  1691. Find(&teamusers); err != nil {
  1692. return nil, fmt.Errorf("get teams users: %v", err)
  1693. }
  1694. if len(teamusers) > 0 {
  1695. users = make([]*User, 0, len(teamusers))
  1696. for _, user := range teamusers {
  1697. if already, ok := resolved[user.LowerName]; !ok || !already {
  1698. users = append(users, user)
  1699. resolved[user.LowerName] = true
  1700. }
  1701. }
  1702. }
  1703. }
  1704. }
  1705. }
  1706. // Remove names already in the list to avoid querying the database if pending names remain
  1707. mentionUsers := make([]string, 0, len(resolved))
  1708. for name, already := range resolved {
  1709. if !already {
  1710. mentionUsers = append(mentionUsers, name)
  1711. }
  1712. }
  1713. if len(mentionUsers) == 0 {
  1714. return
  1715. }
  1716. if users == nil {
  1717. users = make([]*User, 0, len(mentionUsers))
  1718. }
  1719. unchecked := make([]*User, 0, len(mentionUsers))
  1720. if err := ctx.e.
  1721. Where("`user`.is_active = ?", true).
  1722. And("`user`.prohibit_login = ?", false).
  1723. In("`user`.lower_name", mentionUsers).
  1724. Find(&unchecked); err != nil {
  1725. return nil, fmt.Errorf("find mentioned users: %v", err)
  1726. }
  1727. for _, user := range unchecked {
  1728. if already := resolved[user.LowerName]; already || user.IsOrganization() {
  1729. continue
  1730. }
  1731. // Normal users must have read access to the referencing issue
  1732. perm, err := getUserRepoPermission(ctx.e, issue.Repo, user)
  1733. if err != nil {
  1734. return nil, fmt.Errorf("getUserRepoPermission [%d]: %v", user.ID, err)
  1735. }
  1736. if !perm.CanReadIssuesOrPulls(issue.IsPull) {
  1737. continue
  1738. }
  1739. users = append(users, user)
  1740. }
  1741. return
  1742. }
  1743. // UpdateIssuesMigrationsByType updates all migrated repositories' issues from gitServiceType to replace originalAuthorID to posterID
  1744. func UpdateIssuesMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, posterID int64) error {
  1745. _, err := x.Table("issue").
  1746. Where("repo_id IN (SELECT id FROM repository WHERE original_service_type = ?)", gitServiceType).
  1747. And("original_author_id = ?", originalAuthorID).
  1748. Update(map[string]interface{}{
  1749. "poster_id": posterID,
  1750. "original_author": "",
  1751. "original_author_id": 0,
  1752. })
  1753. return err
  1754. }
  1755. // UpdateReactionsMigrationsByType updates all migrated repositories' reactions from gitServiceType to replace originalAuthorID to posterID
  1756. func UpdateReactionsMigrationsByType(gitServiceType structs.GitServiceType, originalAuthorID string, userID int64) error {
  1757. _, err := x.Table("reaction").
  1758. Where("original_author_id = ?", originalAuthorID).
  1759. And(migratedIssueCond(gitServiceType)).
  1760. Update(map[string]interface{}{
  1761. "user_id": userID,
  1762. "original_author": "",
  1763. "original_author_id": 0,
  1764. })
  1765. return err
  1766. }
  1767. func deleteIssuesByRepoID(sess Engine, repoID int64) (attachmentPaths []string, err error) {
  1768. deleteCond := builder.Select("id").From("issue").Where(builder.Eq{"issue.repo_id": repoID})
  1769. // Delete comments and attachments
  1770. if _, err = sess.In("issue_id", deleteCond).
  1771. Delete(&Comment{}); err != nil {
  1772. return
  1773. }
  1774. // Dependencies for issues in this repository
  1775. if _, err = sess.In("issue_id", deleteCond).
  1776. Delete(&IssueDependency{}); err != nil {
  1777. return
  1778. }
  1779. // Delete dependencies for issues in other repositories
  1780. if _, err = sess.In("dependency_id", deleteCond).
  1781. Delete(&IssueDependency{}); err != nil {
  1782. return
  1783. }
  1784. if _, err = sess.In("issue_id", deleteCond).
  1785. Delete(&IssueUser{}); err != nil {
  1786. return
  1787. }
  1788. if _, err = sess.In("issue_id", deleteCond).
  1789. Delete(&Reaction{}); err != nil {
  1790. return
  1791. }
  1792. if _, err = sess.In("issue_id", deleteCond).
  1793. Delete(&IssueWatch{}); err != nil {
  1794. return
  1795. }
  1796. if _, err = sess.In("issue_id", deleteCond).
  1797. Delete(&Stopwatch{}); err != nil {
  1798. return
  1799. }
  1800. if _, err = sess.In("issue_id", deleteCond).
  1801. Delete(&TrackedTime{}); err != nil {
  1802. return
  1803. }
  1804. if _, err = sess.In("issue_id", deleteCond).
  1805. Delete(&ProjectIssue{}); err != nil {
  1806. return
  1807. }
  1808. if _, err = sess.In("dependent_issue_id", deleteCond).
  1809. Delete(&Comment{}); err != nil {
  1810. return
  1811. }
  1812. var attachments []*Attachment
  1813. if err = sess.In("issue_id", deleteCond).
  1814. Find(&attachments); err != nil {
  1815. return
  1816. }
  1817. for j := range attachments {
  1818. attachmentPaths = append(attachmentPaths, attachments[j].RelativePath())
  1819. }
  1820. if _, err = sess.In("issue_id", deleteCond).
  1821. Delete(&Attachment{}); err != nil {
  1822. return
  1823. }
  1824. if _, err = sess.Delete(&Issue{RepoID: repoID}); err != nil {
  1825. return
  1826. }
  1827. return
  1828. }