You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 69KB

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