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

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