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

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