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

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