Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

issue.go 71KB

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