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.

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