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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "errors"
  7. "fmt"
  8. "io"
  9. "mime/multipart"
  10. "os"
  11. "path"
  12. "strings"
  13. "time"
  14. api "code.gitea.io/sdk/gitea"
  15. "github.com/Unknwon/com"
  16. "github.com/go-xorm/xorm"
  17. gouuid "github.com/satori/go.uuid"
  18. "code.gitea.io/gitea/modules/base"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. )
  22. var (
  23. errMissingIssueNumber = errors.New("No issue number specified")
  24. )
  25. // Issue represents an issue or pull request of repository.
  26. type Issue struct {
  27. ID int64 `xorm:"pk autoincr"`
  28. RepoID int64 `xorm:"INDEX UNIQUE(repo_index)"`
  29. Repo *Repository `xorm:"-"`
  30. Index int64 `xorm:"UNIQUE(repo_index)"` // Index in one repository.
  31. PosterID int64
  32. Poster *User `xorm:"-"`
  33. Title string `xorm:"name"`
  34. Content string `xorm:"TEXT"`
  35. RenderedContent string `xorm:"-"`
  36. Labels []*Label `xorm:"-"`
  37. MilestoneID int64
  38. Milestone *Milestone `xorm:"-"`
  39. Priority int
  40. AssigneeID int64
  41. Assignee *User `xorm:"-"`
  42. IsClosed bool
  43. IsRead bool `xorm:"-"`
  44. IsPull bool // Indicates whether is a pull request or not.
  45. PullRequest *PullRequest `xorm:"-"`
  46. NumComments int
  47. Deadline time.Time `xorm:"-"`
  48. DeadlineUnix int64
  49. Created time.Time `xorm:"-"`
  50. CreatedUnix int64
  51. Updated time.Time `xorm:"-"`
  52. UpdatedUnix int64
  53. Attachments []*Attachment `xorm:"-"`
  54. Comments []*Comment `xorm:"-"`
  55. }
  56. // BeforeInsert is invoked from XORM before inserting an object of this type.
  57. func (issue *Issue) BeforeInsert() {
  58. issue.CreatedUnix = time.Now().Unix()
  59. issue.UpdatedUnix = issue.CreatedUnix
  60. }
  61. // BeforeUpdate is invoked from XORM before updating this object.
  62. func (issue *Issue) BeforeUpdate() {
  63. issue.UpdatedUnix = time.Now().Unix()
  64. issue.DeadlineUnix = issue.Deadline.Unix()
  65. }
  66. // AfterSet is invoked from XORM after setting the value of a field of
  67. // this object.
  68. func (issue *Issue) AfterSet(colName string, _ xorm.Cell) {
  69. switch colName {
  70. case "deadline_unix":
  71. issue.Deadline = time.Unix(issue.DeadlineUnix, 0).Local()
  72. case "created_unix":
  73. issue.Created = time.Unix(issue.CreatedUnix, 0).Local()
  74. case "updated_unix":
  75. issue.Updated = time.Unix(issue.UpdatedUnix, 0).Local()
  76. }
  77. }
  78. func (issue *Issue) loadRepo(e Engine) (err error) {
  79. if issue.Repo == nil {
  80. issue.Repo, err = getRepositoryByID(e, issue.RepoID)
  81. if err != nil {
  82. return fmt.Errorf("getRepositoryByID [%d]: %v", issue.RepoID, err)
  83. }
  84. }
  85. return nil
  86. }
  87. func (issue *Issue) loadAttributes(e Engine) (err error) {
  88. if err := issue.loadRepo(e); err != nil {
  89. return err
  90. }
  91. if issue.Poster == nil {
  92. issue.Poster, err = getUserByID(e, issue.PosterID)
  93. if err != nil {
  94. issue.PosterID = -1
  95. issue.Poster = NewGhostUser()
  96. if !IsErrUserNotExist(err) {
  97. return fmt.Errorf("getUserByID.(poster) [%d]: %v", issue.PosterID, err)
  98. }
  99. err = nil
  100. return
  101. }
  102. }
  103. if issue.Labels == nil {
  104. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  105. if err != nil {
  106. return fmt.Errorf("getLabelsByIssueID [%d]: %v", issue.ID, err)
  107. }
  108. }
  109. if issue.Milestone == nil && issue.MilestoneID > 0 {
  110. issue.Milestone, err = getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  111. if err != nil {
  112. return fmt.Errorf("getMilestoneByRepoID [repo_id: %d, milestone_id: %d]: %v", issue.RepoID, issue.MilestoneID, err)
  113. }
  114. }
  115. if issue.Assignee == nil && issue.AssigneeID > 0 {
  116. issue.Assignee, err = getUserByID(e, issue.AssigneeID)
  117. if err != nil {
  118. return fmt.Errorf("getUserByID.(assignee) [%d]: %v", issue.AssigneeID, err)
  119. }
  120. }
  121. if issue.IsPull && issue.PullRequest == nil {
  122. // It is possible pull request is not yet created.
  123. issue.PullRequest, err = getPullRequestByIssueID(e, issue.ID)
  124. if err != nil && !IsErrPullRequestNotExist(err) {
  125. return fmt.Errorf("getPullRequestByIssueID [%d]: %v", issue.ID, err)
  126. }
  127. }
  128. if issue.Attachments == nil {
  129. issue.Attachments, err = getAttachmentsByIssueID(e, issue.ID)
  130. if err != nil {
  131. return fmt.Errorf("getAttachmentsByIssueID [%d]: %v", issue.ID, err)
  132. }
  133. }
  134. if issue.Comments == nil {
  135. issue.Comments, err = getCommentsByIssueID(e, issue.ID)
  136. if err != nil {
  137. return fmt.Errorf("getCommentsByIssueID [%d]: %v", issue.ID, err)
  138. }
  139. }
  140. return nil
  141. }
  142. // LoadAttributes loads the attribute of this issue.
  143. func (issue *Issue) LoadAttributes() error {
  144. return issue.loadAttributes(x)
  145. }
  146. // HTMLURL returns the absolute URL to this issue.
  147. func (issue *Issue) HTMLURL() string {
  148. var path string
  149. if issue.IsPull {
  150. path = "pulls"
  151. } else {
  152. path = "issues"
  153. }
  154. return fmt.Sprintf("%s/%s/%d", issue.Repo.HTMLURL(), path, issue.Index)
  155. }
  156. // DiffURL returns the absolute URL to this diff
  157. func (issue *Issue) DiffURL() string {
  158. if issue.IsPull {
  159. return fmt.Sprintf("%s/pulls/%d.diff", issue.Repo.HTMLURL(), issue.Index)
  160. }
  161. return ""
  162. }
  163. // PatchURL returns the absolute URL to this patch
  164. func (issue *Issue) PatchURL() string {
  165. if issue.IsPull {
  166. return fmt.Sprintf("%s/pulls/%d.patch", issue.Repo.HTMLURL(), issue.Index)
  167. }
  168. return ""
  169. }
  170. // State returns string representation of issue status.
  171. func (issue *Issue) State() api.StateType {
  172. if issue.IsClosed {
  173. return api.StateClosed
  174. }
  175. return api.StateOpen
  176. }
  177. // APIFormat assumes some fields assigned with values:
  178. // Required - Poster, Labels,
  179. // Optional - Milestone, Assignee, PullRequest
  180. func (issue *Issue) APIFormat() *api.Issue {
  181. apiLabels := make([]*api.Label, len(issue.Labels))
  182. for i := range issue.Labels {
  183. apiLabels[i] = issue.Labels[i].APIFormat()
  184. }
  185. apiIssue := &api.Issue{
  186. ID: issue.ID,
  187. Index: issue.Index,
  188. Poster: issue.Poster.APIFormat(),
  189. Title: issue.Title,
  190. Body: issue.Content,
  191. Labels: apiLabels,
  192. State: issue.State(),
  193. Comments: issue.NumComments,
  194. Created: issue.Created,
  195. Updated: issue.Updated,
  196. }
  197. if issue.Milestone != nil {
  198. apiIssue.Milestone = issue.Milestone.APIFormat()
  199. }
  200. if issue.Assignee != nil {
  201. apiIssue.Assignee = issue.Assignee.APIFormat()
  202. }
  203. if issue.IsPull {
  204. apiIssue.PullRequest = &api.PullRequestMeta{
  205. HasMerged: issue.PullRequest.HasMerged,
  206. }
  207. if issue.PullRequest.HasMerged {
  208. apiIssue.PullRequest.Merged = &issue.PullRequest.Merged
  209. }
  210. }
  211. return apiIssue
  212. }
  213. // HashTag returns unique hash tag for issue.
  214. func (issue *Issue) HashTag() string {
  215. return "issue-" + com.ToStr(issue.ID)
  216. }
  217. // IsPoster returns true if given user by ID is the poster.
  218. func (issue *Issue) IsPoster(uid int64) bool {
  219. return issue.PosterID == uid
  220. }
  221. func (issue *Issue) hasLabel(e Engine, labelID int64) bool {
  222. return hasIssueLabel(e, issue.ID, labelID)
  223. }
  224. // HasLabel returns true if issue has been labeled by given ID.
  225. func (issue *Issue) HasLabel(labelID int64) bool {
  226. return issue.hasLabel(x, labelID)
  227. }
  228. func (issue *Issue) sendLabelUpdatedWebhook(doer *User) {
  229. var err error
  230. if issue.IsPull {
  231. err = issue.PullRequest.LoadIssue()
  232. if err != nil {
  233. log.Error(4, "LoadIssue: %v", err)
  234. return
  235. }
  236. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  237. Action: api.HookIssueLabelUpdated,
  238. Index: issue.Index,
  239. PullRequest: issue.PullRequest.APIFormat(),
  240. Repository: issue.Repo.APIFormat(AccessModeNone),
  241. Sender: doer.APIFormat(),
  242. })
  243. }
  244. if err != nil {
  245. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  246. } else {
  247. go HookQueue.Add(issue.RepoID)
  248. }
  249. }
  250. func (issue *Issue) addLabel(e *xorm.Session, label *Label) error {
  251. return newIssueLabel(e, issue, label)
  252. }
  253. // AddLabel adds a new label to the issue.
  254. func (issue *Issue) AddLabel(doer *User, label *Label) error {
  255. if err := NewIssueLabel(issue, label); err != nil {
  256. return err
  257. }
  258. issue.sendLabelUpdatedWebhook(doer)
  259. return nil
  260. }
  261. func (issue *Issue) addLabels(e *xorm.Session, labels []*Label) error {
  262. return newIssueLabels(e, issue, labels)
  263. }
  264. // AddLabels adds a list of new labels to the issue.
  265. func (issue *Issue) AddLabels(doer *User, labels []*Label) error {
  266. if err := NewIssueLabels(issue, labels); err != nil {
  267. return err
  268. }
  269. issue.sendLabelUpdatedWebhook(doer)
  270. return nil
  271. }
  272. func (issue *Issue) getLabels(e Engine) (err error) {
  273. if len(issue.Labels) > 0 {
  274. return nil
  275. }
  276. issue.Labels, err = getLabelsByIssueID(e, issue.ID)
  277. if err != nil {
  278. return fmt.Errorf("getLabelsByIssueID: %v", err)
  279. }
  280. return nil
  281. }
  282. func (issue *Issue) removeLabel(e *xorm.Session, label *Label) error {
  283. return deleteIssueLabel(e, issue, label)
  284. }
  285. // RemoveLabel removes a label from issue by given ID.
  286. func (issue *Issue) RemoveLabel(doer *User, label *Label) error {
  287. if err := issue.loadRepo(x); err != nil {
  288. return err
  289. }
  290. if has, err := HasAccess(doer, issue.Repo, AccessModeWrite); err != nil {
  291. return err
  292. } else if !has {
  293. return ErrLabelNotExist{}
  294. }
  295. if err := DeleteIssueLabel(issue, label); err != nil {
  296. return err
  297. }
  298. issue.sendLabelUpdatedWebhook(doer)
  299. return nil
  300. }
  301. func (issue *Issue) clearLabels(e *xorm.Session) (err error) {
  302. if err = issue.getLabels(e); err != nil {
  303. return fmt.Errorf("getLabels: %v", err)
  304. }
  305. for i := range issue.Labels {
  306. if err = issue.removeLabel(e, issue.Labels[i]); err != nil {
  307. return fmt.Errorf("removeLabel: %v", err)
  308. }
  309. }
  310. return nil
  311. }
  312. // ClearLabels removes all issue labels as the given user.
  313. // Triggers appropriate WebHooks, if any.
  314. func (issue *Issue) ClearLabels(doer *User) (err error) {
  315. sess := x.NewSession()
  316. defer sessionRelease(sess)
  317. if err = sess.Begin(); err != nil {
  318. return err
  319. }
  320. if err := issue.loadRepo(sess); err != nil {
  321. return err
  322. }
  323. if has, err := hasAccess(sess, doer, issue.Repo, AccessModeWrite); err != nil {
  324. return err
  325. } else if !has {
  326. return ErrLabelNotExist{}
  327. }
  328. if err = issue.clearLabels(sess); err != nil {
  329. return err
  330. }
  331. if err = sess.Commit(); err != nil {
  332. return fmt.Errorf("Commit: %v", err)
  333. }
  334. if issue.IsPull {
  335. err = issue.PullRequest.LoadIssue()
  336. if err != nil {
  337. log.Error(4, "LoadIssue: %v", err)
  338. return
  339. }
  340. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  341. Action: api.HookIssueLabelCleared,
  342. Index: issue.Index,
  343. PullRequest: issue.PullRequest.APIFormat(),
  344. Repository: issue.Repo.APIFormat(AccessModeNone),
  345. Sender: doer.APIFormat(),
  346. })
  347. }
  348. if err != nil {
  349. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  350. } else {
  351. go HookQueue.Add(issue.RepoID)
  352. }
  353. return nil
  354. }
  355. // ReplaceLabels removes all current labels and add new labels to the issue.
  356. // Triggers appropriate WebHooks, if any.
  357. func (issue *Issue) ReplaceLabels(labels []*Label) (err error) {
  358. sess := x.NewSession()
  359. defer sessionRelease(sess)
  360. if err = sess.Begin(); err != nil {
  361. return err
  362. }
  363. if err = issue.clearLabels(sess); err != nil {
  364. return fmt.Errorf("clearLabels: %v", err)
  365. } else if err = issue.addLabels(sess, labels); err != nil {
  366. return fmt.Errorf("addLabels: %v", err)
  367. }
  368. return sess.Commit()
  369. }
  370. // GetAssignee sets the Assignee attribute of this issue.
  371. func (issue *Issue) GetAssignee() (err error) {
  372. if issue.AssigneeID == 0 || issue.Assignee != nil {
  373. return nil
  374. }
  375. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  376. if IsErrUserNotExist(err) {
  377. return nil
  378. }
  379. return err
  380. }
  381. // ReadBy sets issue to be read by given user.
  382. func (issue *Issue) ReadBy(uid int64) error {
  383. return UpdateIssueUserByRead(uid, issue.ID)
  384. }
  385. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  386. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  387. return err
  388. }
  389. // UpdateIssueCols only updates values of specific columns for given issue.
  390. func UpdateIssueCols(issue *Issue, cols ...string) error {
  391. return updateIssueCols(x, issue, cols...)
  392. }
  393. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  394. // Nothing should be performed if current status is same as target status
  395. if issue.IsClosed == isClosed {
  396. return nil
  397. }
  398. issue.IsClosed = isClosed
  399. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  400. return err
  401. } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
  402. return err
  403. }
  404. // Update issue count of labels
  405. if err = issue.getLabels(e); err != nil {
  406. return err
  407. }
  408. for idx := range issue.Labels {
  409. if issue.IsClosed {
  410. issue.Labels[idx].NumClosedIssues++
  411. } else {
  412. issue.Labels[idx].NumClosedIssues--
  413. }
  414. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  415. return err
  416. }
  417. }
  418. // Update issue count of milestone
  419. if err = changeMilestoneIssueStats(e, issue); err != nil {
  420. return err
  421. }
  422. // New action comment
  423. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  424. return err
  425. }
  426. return nil
  427. }
  428. // ChangeStatus changes issue status to open or closed.
  429. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  430. sess := x.NewSession()
  431. defer sessionRelease(sess)
  432. if err = sess.Begin(); err != nil {
  433. return err
  434. }
  435. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  436. return err
  437. }
  438. if err = sess.Commit(); err != nil {
  439. return fmt.Errorf("Commit: %v", err)
  440. }
  441. if issue.IsPull {
  442. // Merge pull request calls issue.changeStatus so we need to handle separately.
  443. issue.PullRequest.Issue = issue
  444. apiPullRequest := &api.PullRequestPayload{
  445. Index: issue.Index,
  446. PullRequest: issue.PullRequest.APIFormat(),
  447. Repository: repo.APIFormat(AccessModeNone),
  448. Sender: doer.APIFormat(),
  449. }
  450. if isClosed {
  451. apiPullRequest.Action = api.HookIssueClosed
  452. } else {
  453. apiPullRequest.Action = api.HookIssueReOpened
  454. }
  455. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  456. }
  457. if err != nil {
  458. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  459. } else {
  460. go HookQueue.Add(repo.ID)
  461. }
  462. return nil
  463. }
  464. // ChangeTitle changes the title of this issue, as the given user.
  465. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  466. oldTitle := issue.Title
  467. issue.Title = title
  468. if err = UpdateIssueCols(issue, "name"); err != nil {
  469. return fmt.Errorf("UpdateIssueCols: %v", err)
  470. }
  471. if issue.IsPull {
  472. issue.PullRequest.Issue = issue
  473. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  474. Action: api.HookIssueEdited,
  475. Index: issue.Index,
  476. Changes: &api.ChangesPayload{
  477. Title: &api.ChangesFromPayload{
  478. From: oldTitle,
  479. },
  480. },
  481. PullRequest: issue.PullRequest.APIFormat(),
  482. Repository: issue.Repo.APIFormat(AccessModeNone),
  483. Sender: doer.APIFormat(),
  484. })
  485. }
  486. if err != nil {
  487. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  488. } else {
  489. go HookQueue.Add(issue.RepoID)
  490. }
  491. return nil
  492. }
  493. // ChangeContent changes issue content, as the given user.
  494. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  495. oldContent := issue.Content
  496. issue.Content = content
  497. if err = UpdateIssueCols(issue, "content"); err != nil {
  498. return fmt.Errorf("UpdateIssueCols: %v", err)
  499. }
  500. if issue.IsPull {
  501. issue.PullRequest.Issue = issue
  502. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  503. Action: api.HookIssueEdited,
  504. Index: issue.Index,
  505. Changes: &api.ChangesPayload{
  506. Body: &api.ChangesFromPayload{
  507. From: oldContent,
  508. },
  509. },
  510. PullRequest: issue.PullRequest.APIFormat(),
  511. Repository: issue.Repo.APIFormat(AccessModeNone),
  512. Sender: doer.APIFormat(),
  513. })
  514. }
  515. if err != nil {
  516. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  517. } else {
  518. go HookQueue.Add(issue.RepoID)
  519. }
  520. return nil
  521. }
  522. // ChangeAssignee changes the Asssignee field of this issue.
  523. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  524. issue.AssigneeID = assigneeID
  525. if err = UpdateIssueUserByAssignee(issue); err != nil {
  526. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  527. }
  528. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  529. if err != nil && !IsErrUserNotExist(err) {
  530. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  531. return nil
  532. }
  533. // Error not nil here means user does not exist, which is remove assignee.
  534. isRemoveAssignee := err != nil
  535. if issue.IsPull {
  536. issue.PullRequest.Issue = issue
  537. apiPullRequest := &api.PullRequestPayload{
  538. Index: issue.Index,
  539. PullRequest: issue.PullRequest.APIFormat(),
  540. Repository: issue.Repo.APIFormat(AccessModeNone),
  541. Sender: doer.APIFormat(),
  542. }
  543. if isRemoveAssignee {
  544. apiPullRequest.Action = api.HookIssueUnassigned
  545. } else {
  546. apiPullRequest.Action = api.HookIssueAssigned
  547. }
  548. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  549. }
  550. if err != nil {
  551. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  552. } else {
  553. go HookQueue.Add(issue.RepoID)
  554. }
  555. return nil
  556. }
  557. // NewIssueOptions represents the options of a new issue.
  558. type NewIssueOptions struct {
  559. Repo *Repository
  560. Issue *Issue
  561. LableIDs []int64
  562. Attachments []string // In UUID format.
  563. IsPull bool
  564. }
  565. func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
  566. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  567. opts.Issue.Index = opts.Repo.NextIssueIndex()
  568. if opts.Issue.MilestoneID > 0 {
  569. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  570. if err != nil && !IsErrMilestoneNotExist(err) {
  571. return fmt.Errorf("getMilestoneByID: %v", err)
  572. }
  573. // Assume milestone is invalid and drop silently.
  574. opts.Issue.MilestoneID = 0
  575. if milestone != nil {
  576. opts.Issue.MilestoneID = milestone.ID
  577. opts.Issue.Milestone = milestone
  578. if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
  579. return err
  580. }
  581. }
  582. }
  583. if opts.Issue.AssigneeID > 0 {
  584. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  585. if err != nil && !IsErrUserNotExist(err) {
  586. return fmt.Errorf("getUserByID: %v", err)
  587. }
  588. // Assume assignee is invalid and drop silently.
  589. opts.Issue.AssigneeID = 0
  590. if assignee != nil {
  591. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  592. if err != nil {
  593. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  594. }
  595. if valid {
  596. opts.Issue.AssigneeID = assignee.ID
  597. opts.Issue.Assignee = assignee
  598. }
  599. }
  600. }
  601. // Milestone and assignee validation should happen before insert actual object.
  602. if _, err = e.Insert(opts.Issue); err != nil {
  603. return err
  604. }
  605. if opts.IsPull {
  606. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  607. } else {
  608. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  609. }
  610. if err != nil {
  611. return err
  612. }
  613. if len(opts.LableIDs) > 0 {
  614. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  615. // So we have to get all needed labels first.
  616. labels := make([]*Label, 0, len(opts.LableIDs))
  617. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  618. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  619. }
  620. for _, label := range labels {
  621. // Silently drop invalid labels.
  622. if label.RepoID != opts.Repo.ID {
  623. continue
  624. }
  625. if err = opts.Issue.addLabel(e, label); err != nil {
  626. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  627. }
  628. }
  629. }
  630. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  631. return err
  632. }
  633. if len(opts.Attachments) > 0 {
  634. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  635. if err != nil {
  636. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  637. }
  638. for i := 0; i < len(attachments); i++ {
  639. attachments[i].IssueID = opts.Issue.ID
  640. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  641. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  642. }
  643. }
  644. }
  645. return opts.Issue.loadAttributes(e)
  646. }
  647. // NewIssue creates new issue with labels for repository.
  648. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  649. sess := x.NewSession()
  650. defer sessionRelease(sess)
  651. if err = sess.Begin(); err != nil {
  652. return err
  653. }
  654. if err = newIssue(sess, NewIssueOptions{
  655. Repo: repo,
  656. Issue: issue,
  657. LableIDs: labelIDs,
  658. Attachments: uuids,
  659. }); err != nil {
  660. return fmt.Errorf("newIssue: %v", err)
  661. }
  662. if err = sess.Commit(); err != nil {
  663. return fmt.Errorf("Commit: %v", err)
  664. }
  665. if err = NotifyWatchers(&Action{
  666. ActUserID: issue.Poster.ID,
  667. ActUserName: issue.Poster.Name,
  668. OpType: ActionCreateIssue,
  669. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  670. RepoID: repo.ID,
  671. RepoUserName: repo.Owner.Name,
  672. RepoName: repo.Name,
  673. IsPrivate: repo.IsPrivate,
  674. }); err != nil {
  675. log.Error(4, "NotifyWatchers: %v", err)
  676. }
  677. if err = issue.MailParticipants(); err != nil {
  678. log.Error(4, "MailParticipants: %v", err)
  679. }
  680. return nil
  681. }
  682. // GetIssueByRef returns an Issue specified by a GFM reference.
  683. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  684. func GetIssueByRef(ref string) (*Issue, error) {
  685. n := strings.IndexByte(ref, byte('#'))
  686. if n == -1 {
  687. return nil, errMissingIssueNumber
  688. }
  689. index, err := com.StrTo(ref[n+1:]).Int64()
  690. if err != nil {
  691. return nil, err
  692. }
  693. repo, err := GetRepositoryByRef(ref[:n])
  694. if err != nil {
  695. return nil, err
  696. }
  697. issue, err := GetIssueByIndex(repo.ID, index)
  698. if err != nil {
  699. return nil, err
  700. }
  701. return issue, issue.LoadAttributes()
  702. }
  703. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  704. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  705. issue := &Issue{
  706. RepoID: repoID,
  707. Index: index,
  708. }
  709. has, err := x.Get(issue)
  710. if err != nil {
  711. return nil, err
  712. } else if !has {
  713. return nil, ErrIssueNotExist{0, repoID, index}
  714. }
  715. return issue, nil
  716. }
  717. // GetIssueByIndex returns issue by index in a repository.
  718. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  719. issue, err := GetRawIssueByIndex(repoID, index)
  720. if err != nil {
  721. return nil, err
  722. }
  723. return issue, issue.LoadAttributes()
  724. }
  725. func getIssueByID(e Engine, id int64) (*Issue, error) {
  726. issue := new(Issue)
  727. has, err := e.Id(id).Get(issue)
  728. if err != nil {
  729. return nil, err
  730. } else if !has {
  731. return nil, ErrIssueNotExist{id, 0, 0}
  732. }
  733. return issue, issue.LoadAttributes()
  734. }
  735. // GetIssueByID returns an issue by given ID.
  736. func GetIssueByID(id int64) (*Issue, error) {
  737. return getIssueByID(x, id)
  738. }
  739. // IssuesOptions represents options of an issue.
  740. type IssuesOptions struct {
  741. RepoID int64
  742. AssigneeID int64
  743. PosterID int64
  744. MentionedID int64
  745. MilestoneID int64
  746. RepoIDs []int64
  747. Page int
  748. IsClosed bool
  749. IsPull bool
  750. Labels string
  751. SortType string
  752. }
  753. // Issues returns a list of issues by given conditions.
  754. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  755. if opts.Page <= 0 {
  756. opts.Page = 1
  757. }
  758. sess := x.Limit(setting.UI.IssuePagingNum, (opts.Page-1)*setting.UI.IssuePagingNum)
  759. if opts.RepoID > 0 {
  760. sess.And("issue.repo_id=?", opts.RepoID)
  761. } else if len(opts.RepoIDs) > 0 {
  762. // In case repository IDs are provided but actually no repository has issue.
  763. sess.In("issue.repo_id", opts.RepoIDs)
  764. }
  765. sess.And("issue.is_closed=?", opts.IsClosed)
  766. if opts.AssigneeID > 0 {
  767. sess.And("issue.assignee_id=?", opts.AssigneeID)
  768. }
  769. if opts.PosterID > 0 {
  770. sess.And("issue.poster_id=?", opts.PosterID)
  771. }
  772. if opts.MentionedID > 0 {
  773. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  774. And("issue_user.is_mentioned = ?", true).
  775. And("issue_user.uid = ?", opts.MentionedID)
  776. }
  777. if opts.MilestoneID > 0 {
  778. sess.And("issue.milestone_id=?", opts.MilestoneID)
  779. }
  780. sess.And("issue.is_pull=?", opts.IsPull)
  781. switch opts.SortType {
  782. case "oldest":
  783. sess.Asc("issue.created_unix")
  784. case "recentupdate":
  785. sess.Desc("issue.updated_unix")
  786. case "leastupdate":
  787. sess.Asc("issue.updated_unix")
  788. case "mostcomment":
  789. sess.Desc("issue.num_comments")
  790. case "leastcomment":
  791. sess.Asc("issue.num_comments")
  792. case "priority":
  793. sess.Desc("issue.priority")
  794. default:
  795. sess.Desc("issue.created_unix")
  796. }
  797. if len(opts.Labels) > 0 && opts.Labels != "0" {
  798. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  799. if err != nil {
  800. return nil, err
  801. }
  802. if len(labelIDs) > 0 {
  803. sess.
  804. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  805. In("issue_label.label_id", labelIDs)
  806. }
  807. }
  808. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  809. if err := sess.Find(&issues); err != nil {
  810. return nil, fmt.Errorf("Find: %v", err)
  811. }
  812. // FIXME: use IssueList to improve performance.
  813. for i := range issues {
  814. if err := issues[i].LoadAttributes(); err != nil {
  815. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  816. }
  817. }
  818. return issues, nil
  819. }
  820. // .___ ____ ___
  821. // | | ______ ________ __ ____ | | \______ ___________
  822. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  823. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  824. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  825. // \/ \/ \/ \/ \/
  826. // IssueUser represents an issue-user relation.
  827. type IssueUser struct {
  828. ID int64 `xorm:"pk autoincr"`
  829. UID int64 `xorm:"INDEX"` // User ID.
  830. IssueID int64
  831. RepoID int64 `xorm:"INDEX"`
  832. MilestoneID int64
  833. IsRead bool
  834. IsAssigned bool
  835. IsMentioned bool
  836. IsPoster bool
  837. IsClosed bool
  838. }
  839. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  840. assignees, err := repo.getAssignees(e)
  841. if err != nil {
  842. return fmt.Errorf("getAssignees: %v", err)
  843. }
  844. // Poster can be anyone, append later if not one of assignees.
  845. isPosterAssignee := false
  846. // Leave a seat for poster itself to append later, but if poster is one of assignee
  847. // and just waste 1 unit is cheaper than re-allocate memory once.
  848. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  849. for _, assignee := range assignees {
  850. isPoster := assignee.ID == issue.PosterID
  851. issueUsers = append(issueUsers, &IssueUser{
  852. IssueID: issue.ID,
  853. RepoID: repo.ID,
  854. UID: assignee.ID,
  855. IsPoster: isPoster,
  856. IsAssigned: assignee.ID == issue.AssigneeID,
  857. })
  858. if !isPosterAssignee && isPoster {
  859. isPosterAssignee = true
  860. }
  861. }
  862. if !isPosterAssignee {
  863. issueUsers = append(issueUsers, &IssueUser{
  864. IssueID: issue.ID,
  865. RepoID: repo.ID,
  866. UID: issue.PosterID,
  867. IsPoster: true,
  868. })
  869. }
  870. if _, err = e.Insert(issueUsers); err != nil {
  871. return err
  872. }
  873. return nil
  874. }
  875. // NewIssueUsers adds new issue-user relations for new issue of repository.
  876. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  877. sess := x.NewSession()
  878. defer sessionRelease(sess)
  879. if err = sess.Begin(); err != nil {
  880. return err
  881. }
  882. if err = newIssueUsers(sess, repo, issue); err != nil {
  883. return err
  884. }
  885. return sess.Commit()
  886. }
  887. // PairsContains returns true when pairs list contains given issue.
  888. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  889. for i := range ius {
  890. if ius[i].IssueID == issueID &&
  891. ius[i].UID == uid {
  892. return i
  893. }
  894. }
  895. return -1
  896. }
  897. // GetIssueUsers returns issue-user pairs by given repository and user.
  898. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  899. ius := make([]*IssueUser, 0, 10)
  900. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  901. return ius, err
  902. }
  903. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  904. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  905. if len(rids) == 0 {
  906. return []*IssueUser{}, nil
  907. }
  908. ius := make([]*IssueUser, 0, 10)
  909. sess := x.
  910. Limit(20, (page-1)*20).
  911. Where("is_closed=?", isClosed).
  912. In("repo_id", rids)
  913. err := sess.Find(&ius)
  914. return ius, err
  915. }
  916. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  917. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  918. ius := make([]*IssueUser, 0, 10)
  919. sess := x.
  920. Limit(20, (page-1)*20).
  921. Where("uid=?", uid).
  922. And("is_closed=?", isClosed)
  923. if rid > 0 {
  924. sess.And("repo_id=?", rid)
  925. }
  926. switch filterMode {
  927. case FilterModeAssign:
  928. sess.And("is_assigned=?", true)
  929. case FilterModeCreate:
  930. sess.And("is_poster=?", true)
  931. default:
  932. return ius, nil
  933. }
  934. err := sess.Find(&ius)
  935. return ius, err
  936. }
  937. // UpdateIssueMentions extracts mentioned people from content and
  938. // updates issue-user relations for them.
  939. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  940. if len(mentions) == 0 {
  941. return nil
  942. }
  943. for i := range mentions {
  944. mentions[i] = strings.ToLower(mentions[i])
  945. }
  946. users := make([]*User, 0, len(mentions))
  947. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  948. return fmt.Errorf("find mentioned users: %v", err)
  949. }
  950. ids := make([]int64, 0, len(mentions))
  951. for _, user := range users {
  952. ids = append(ids, user.ID)
  953. if !user.IsOrganization() || user.NumMembers == 0 {
  954. continue
  955. }
  956. memberIDs := make([]int64, 0, user.NumMembers)
  957. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  958. if err != nil {
  959. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  960. }
  961. for _, orgUser := range orgUsers {
  962. memberIDs = append(memberIDs, orgUser.ID)
  963. }
  964. ids = append(ids, memberIDs...)
  965. }
  966. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  967. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  968. }
  969. return nil
  970. }
  971. // IssueStats represents issue statistic information.
  972. type IssueStats struct {
  973. OpenCount, ClosedCount int64
  974. AllCount int64
  975. AssignCount int64
  976. CreateCount int64
  977. MentionCount int64
  978. }
  979. // Filter modes.
  980. const (
  981. FilterModeAll = iota
  982. FilterModeAssign
  983. FilterModeCreate
  984. FilterModeMention
  985. )
  986. func parseCountResult(results []map[string][]byte) int64 {
  987. if len(results) == 0 {
  988. return 0
  989. }
  990. for _, result := range results[0] {
  991. return com.StrTo(string(result)).MustInt64()
  992. }
  993. return 0
  994. }
  995. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  996. type IssueStatsOptions struct {
  997. RepoID int64
  998. Labels string
  999. MilestoneID int64
  1000. AssigneeID int64
  1001. MentionedID int64
  1002. PosterID int64
  1003. IsPull bool
  1004. }
  1005. // GetIssueStats returns issue statistic information by given conditions.
  1006. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1007. stats := &IssueStats{}
  1008. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1009. sess := x.
  1010. Where("issue.repo_id = ?", opts.RepoID).
  1011. And("is_pull = ?", opts.IsPull)
  1012. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1013. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1014. if err != nil {
  1015. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1016. } else if len(labelIDs) > 0 {
  1017. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1018. In("label_id", labelIDs)
  1019. }
  1020. }
  1021. if opts.MilestoneID > 0 {
  1022. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1023. }
  1024. if opts.AssigneeID > 0 {
  1025. sess.And("assignee_id = ?", opts.AssigneeID)
  1026. }
  1027. if opts.PosterID > 0 {
  1028. sess.And("poster_id = ?", opts.PosterID)
  1029. }
  1030. if opts.MentionedID > 0 {
  1031. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1032. And("issue_user.uid = ?", opts.MentionedID).
  1033. And("issue_user.is_mentioned = ?", true)
  1034. }
  1035. return sess
  1036. }
  1037. stats.OpenCount, _ = countSession(opts).
  1038. And("is_closed = ?", false).
  1039. Count(&Issue{})
  1040. stats.ClosedCount, _ = countSession(opts).
  1041. And("is_closed = ?", true).
  1042. Count(&Issue{})
  1043. return stats
  1044. }
  1045. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1046. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1047. stats := &IssueStats{}
  1048. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1049. sess := x.
  1050. Where("issue.is_closed = ?", isClosed).
  1051. And("issue.is_pull = ?", isPull)
  1052. if repoID > 0 {
  1053. sess.And("repo_id = ?", repoID)
  1054. } else if len(repoIDs) > 0 {
  1055. sess.In("repo_id", repoIDs)
  1056. }
  1057. return sess
  1058. }
  1059. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1060. And("assignee_id = ?", uid).
  1061. Count(&Issue{})
  1062. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1063. And("poster_id = ?", uid).
  1064. Count(&Issue{})
  1065. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1066. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1067. switch filterMode {
  1068. case FilterModeAssign:
  1069. openCountSession.And("assignee_id = ?", uid)
  1070. closedCountSession.And("assignee_id = ?", uid)
  1071. case FilterModeCreate:
  1072. openCountSession.And("poster_id = ?", uid)
  1073. closedCountSession.And("poster_id = ?", uid)
  1074. }
  1075. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1076. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1077. return stats
  1078. }
  1079. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1080. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1081. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1082. sess := x.
  1083. Where("issue.repo_id = ?", isClosed).
  1084. And("is_pull = ?", isPull).
  1085. And("repo_id = ?", repoID)
  1086. return sess
  1087. }
  1088. openCountSession := countSession(false, isPull, repoID)
  1089. closedCountSession := countSession(true, isPull, repoID)
  1090. switch filterMode {
  1091. case FilterModeAssign:
  1092. openCountSession.And("assignee_id = ?", uid)
  1093. closedCountSession.And("assignee_id = ?", uid)
  1094. case FilterModeCreate:
  1095. openCountSession.And("poster_id = ?", uid)
  1096. closedCountSession.And("poster_id = ?", uid)
  1097. }
  1098. openResult, _ := openCountSession.Count(&Issue{})
  1099. closedResult, _ := closedCountSession.Count(&Issue{})
  1100. return openResult, closedResult
  1101. }
  1102. func updateIssue(e Engine, issue *Issue) error {
  1103. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1104. return err
  1105. }
  1106. // UpdateIssue updates all fields of given issue.
  1107. func UpdateIssue(issue *Issue) error {
  1108. return updateIssue(x, issue)
  1109. }
  1110. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1111. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1112. return err
  1113. }
  1114. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1115. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1116. return updateIssueUsersByStatus(x, issueID, isClosed)
  1117. }
  1118. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1119. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1120. return err
  1121. }
  1122. // Assignee ID equals to 0 means clear assignee.
  1123. if issue.AssigneeID > 0 {
  1124. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1125. return err
  1126. }
  1127. }
  1128. return updateIssue(e, issue)
  1129. }
  1130. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1131. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1132. sess := x.NewSession()
  1133. defer sessionRelease(sess)
  1134. if err = sess.Begin(); err != nil {
  1135. return err
  1136. }
  1137. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1138. return err
  1139. }
  1140. return sess.Commit()
  1141. }
  1142. // UpdateIssueUserByRead updates issue-user relation for reading.
  1143. func UpdateIssueUserByRead(uid, issueID int64) error {
  1144. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1145. return err
  1146. }
  1147. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1148. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1149. for _, uid := range uids {
  1150. iu := &IssueUser{
  1151. UID: uid,
  1152. IssueID: issueID,
  1153. }
  1154. has, err := e.Get(iu)
  1155. if err != nil {
  1156. return err
  1157. }
  1158. iu.IsMentioned = true
  1159. if has {
  1160. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1161. } else {
  1162. _, err = e.Insert(iu)
  1163. }
  1164. if err != nil {
  1165. return err
  1166. }
  1167. }
  1168. return nil
  1169. }
  1170. // _____ .__.__ __
  1171. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1172. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1173. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1174. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1175. // \/ \/ \/ \/ \/
  1176. // Milestone represents a milestone of repository.
  1177. type Milestone struct {
  1178. ID int64 `xorm:"pk autoincr"`
  1179. RepoID int64 `xorm:"INDEX"`
  1180. Name string
  1181. Content string `xorm:"TEXT"`
  1182. RenderedContent string `xorm:"-"`
  1183. IsClosed bool
  1184. NumIssues int
  1185. NumClosedIssues int
  1186. NumOpenIssues int `xorm:"-"`
  1187. Completeness int // Percentage(1-100).
  1188. IsOverDue bool `xorm:"-"`
  1189. DeadlineString string `xorm:"-"`
  1190. Deadline time.Time `xorm:"-"`
  1191. DeadlineUnix int64
  1192. ClosedDate time.Time `xorm:"-"`
  1193. ClosedDateUnix int64
  1194. }
  1195. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1196. func (m *Milestone) BeforeInsert() {
  1197. m.DeadlineUnix = m.Deadline.Unix()
  1198. }
  1199. // BeforeUpdate is invoked from XORM before updating this object.
  1200. func (m *Milestone) BeforeUpdate() {
  1201. if m.NumIssues > 0 {
  1202. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1203. } else {
  1204. m.Completeness = 0
  1205. }
  1206. m.DeadlineUnix = m.Deadline.Unix()
  1207. m.ClosedDateUnix = m.ClosedDate.Unix()
  1208. }
  1209. // AfterSet is invoked from XORM after setting the value of a field of
  1210. // this object.
  1211. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1212. switch colName {
  1213. case "num_closed_issues":
  1214. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1215. case "deadline_unix":
  1216. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1217. if m.Deadline.Year() == 9999 {
  1218. return
  1219. }
  1220. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1221. if time.Now().Local().After(m.Deadline) {
  1222. m.IsOverDue = true
  1223. }
  1224. case "closed_date_unix":
  1225. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1226. }
  1227. }
  1228. // State returns string representation of milestone status.
  1229. func (m *Milestone) State() api.StateType {
  1230. if m.IsClosed {
  1231. return api.StateClosed
  1232. }
  1233. return api.StateOpen
  1234. }
  1235. // APIFormat returns this Milestone in API format.
  1236. func (m *Milestone) APIFormat() *api.Milestone {
  1237. apiMilestone := &api.Milestone{
  1238. ID: m.ID,
  1239. State: m.State(),
  1240. Title: m.Name,
  1241. Description: m.Content,
  1242. OpenIssues: m.NumOpenIssues,
  1243. ClosedIssues: m.NumClosedIssues,
  1244. }
  1245. if m.IsClosed {
  1246. apiMilestone.Closed = &m.ClosedDate
  1247. }
  1248. if m.Deadline.Year() < 9999 {
  1249. apiMilestone.Deadline = &m.Deadline
  1250. }
  1251. return apiMilestone
  1252. }
  1253. // NewMilestone creates new milestone of repository.
  1254. func NewMilestone(m *Milestone) (err error) {
  1255. sess := x.NewSession()
  1256. defer sessionRelease(sess)
  1257. if err = sess.Begin(); err != nil {
  1258. return err
  1259. }
  1260. if _, err = sess.Insert(m); err != nil {
  1261. return err
  1262. }
  1263. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1264. return err
  1265. }
  1266. return sess.Commit()
  1267. }
  1268. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1269. m := &Milestone{
  1270. ID: id,
  1271. RepoID: repoID,
  1272. }
  1273. has, err := e.Get(m)
  1274. if err != nil {
  1275. return nil, err
  1276. } else if !has {
  1277. return nil, ErrMilestoneNotExist{id, repoID}
  1278. }
  1279. return m, nil
  1280. }
  1281. // GetMilestoneByRepoID returns the milestone in a repository.
  1282. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1283. return getMilestoneByRepoID(x, repoID, id)
  1284. }
  1285. // GetMilestonesByRepoID returns all milestones of a repository.
  1286. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1287. miles := make([]*Milestone, 0, 10)
  1288. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1289. }
  1290. // GetMilestones returns a list of milestones of given repository and status.
  1291. func GetMilestones(repoID int64, page int, isClosed bool) ([]*Milestone, error) {
  1292. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1293. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1294. if page > 0 {
  1295. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1296. }
  1297. return miles, sess.Find(&miles)
  1298. }
  1299. func updateMilestone(e Engine, m *Milestone) error {
  1300. _, err := e.Id(m.ID).AllCols().Update(m)
  1301. return err
  1302. }
  1303. // UpdateMilestone updates information of given milestone.
  1304. func UpdateMilestone(m *Milestone) error {
  1305. return updateMilestone(x, m)
  1306. }
  1307. func countRepoMilestones(e Engine, repoID int64) int64 {
  1308. count, _ := e.
  1309. Where("repo_id=?", repoID).
  1310. Count(new(Milestone))
  1311. return count
  1312. }
  1313. // CountRepoMilestones returns number of milestones in given repository.
  1314. func CountRepoMilestones(repoID int64) int64 {
  1315. return countRepoMilestones(x, repoID)
  1316. }
  1317. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1318. closed, _ := e.
  1319. Where("repo_id=? AND is_closed=?", repoID, true).
  1320. Count(new(Milestone))
  1321. return closed
  1322. }
  1323. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1324. func CountRepoClosedMilestones(repoID int64) int64 {
  1325. return countRepoClosedMilestones(x, repoID)
  1326. }
  1327. // MilestoneStats returns number of open and closed milestones of given repository.
  1328. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1329. open, _ = x.
  1330. Where("repo_id=? AND is_closed=?", repoID, false).
  1331. Count(new(Milestone))
  1332. return open, CountRepoClosedMilestones(repoID)
  1333. }
  1334. // ChangeMilestoneStatus changes the milestone open/closed status.
  1335. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1336. repo, err := GetRepositoryByID(m.RepoID)
  1337. if err != nil {
  1338. return err
  1339. }
  1340. sess := x.NewSession()
  1341. defer sessionRelease(sess)
  1342. if err = sess.Begin(); err != nil {
  1343. return err
  1344. }
  1345. m.IsClosed = isClosed
  1346. if err = updateMilestone(sess, m); err != nil {
  1347. return err
  1348. }
  1349. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1350. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1351. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1352. return err
  1353. }
  1354. return sess.Commit()
  1355. }
  1356. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1357. if issue.MilestoneID == 0 {
  1358. return nil
  1359. }
  1360. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1361. if err != nil {
  1362. return err
  1363. }
  1364. if issue.IsClosed {
  1365. m.NumOpenIssues--
  1366. m.NumClosedIssues++
  1367. } else {
  1368. m.NumOpenIssues++
  1369. m.NumClosedIssues--
  1370. }
  1371. return updateMilestone(e, m)
  1372. }
  1373. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1374. // for the milestone associated with the given issue.
  1375. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1376. sess := x.NewSession()
  1377. defer sessionRelease(sess)
  1378. if err = sess.Begin(); err != nil {
  1379. return err
  1380. }
  1381. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1382. return err
  1383. }
  1384. return sess.Commit()
  1385. }
  1386. func changeMilestoneAssign(e *xorm.Session, issue *Issue, oldMilestoneID int64) error {
  1387. if oldMilestoneID > 0 {
  1388. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1389. if err != nil {
  1390. return err
  1391. }
  1392. m.NumIssues--
  1393. if issue.IsClosed {
  1394. m.NumClosedIssues--
  1395. }
  1396. if err = updateMilestone(e, m); err != nil {
  1397. return err
  1398. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
  1399. return err
  1400. }
  1401. }
  1402. if issue.MilestoneID > 0 {
  1403. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1404. if err != nil {
  1405. return err
  1406. }
  1407. m.NumIssues++
  1408. if issue.IsClosed {
  1409. m.NumClosedIssues++
  1410. }
  1411. if err = updateMilestone(e, m); err != nil {
  1412. return err
  1413. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
  1414. return err
  1415. }
  1416. }
  1417. return updateIssue(e, issue)
  1418. }
  1419. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1420. func ChangeMilestoneAssign(issue *Issue, oldMilestoneID int64) (err error) {
  1421. sess := x.NewSession()
  1422. defer sess.Close()
  1423. if err = sess.Begin(); err != nil {
  1424. return err
  1425. }
  1426. if err = changeMilestoneAssign(sess, issue, oldMilestoneID); err != nil {
  1427. return err
  1428. }
  1429. return sess.Commit()
  1430. }
  1431. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1432. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1433. m, err := GetMilestoneByRepoID(repoID, id)
  1434. if err != nil {
  1435. if IsErrMilestoneNotExist(err) {
  1436. return nil
  1437. }
  1438. return err
  1439. }
  1440. repo, err := GetRepositoryByID(m.RepoID)
  1441. if err != nil {
  1442. return err
  1443. }
  1444. sess := x.NewSession()
  1445. defer sessionRelease(sess)
  1446. if err = sess.Begin(); err != nil {
  1447. return err
  1448. }
  1449. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1450. return err
  1451. }
  1452. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1453. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1454. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1455. return err
  1456. }
  1457. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1458. return err
  1459. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1460. return err
  1461. }
  1462. return sess.Commit()
  1463. }
  1464. // Attachment represent a attachment of issue/comment/release.
  1465. type Attachment struct {
  1466. ID int64 `xorm:"pk autoincr"`
  1467. UUID string `xorm:"uuid UNIQUE"`
  1468. IssueID int64 `xorm:"INDEX"`
  1469. CommentID int64
  1470. ReleaseID int64 `xorm:"INDEX"`
  1471. Name string
  1472. Created time.Time `xorm:"-"`
  1473. CreatedUnix int64
  1474. }
  1475. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1476. func (a *Attachment) BeforeInsert() {
  1477. a.CreatedUnix = time.Now().Unix()
  1478. }
  1479. // AfterSet is invoked from XORM after setting the value of a field of
  1480. // this object.
  1481. func (a *Attachment) AfterSet(colName string, _ xorm.Cell) {
  1482. switch colName {
  1483. case "created_unix":
  1484. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  1485. }
  1486. }
  1487. // AttachmentLocalPath returns where attachment is stored in local file
  1488. // system based on given UUID.
  1489. func AttachmentLocalPath(uuid string) string {
  1490. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1491. }
  1492. // LocalPath returns where attachment is stored in local file system.
  1493. func (a *Attachment) LocalPath() string {
  1494. return AttachmentLocalPath(a.UUID)
  1495. }
  1496. // NewAttachment creates a new attachment object.
  1497. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1498. attach := &Attachment{
  1499. UUID: gouuid.NewV4().String(),
  1500. Name: name,
  1501. }
  1502. localPath := attach.LocalPath()
  1503. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  1504. return nil, fmt.Errorf("MkdirAll: %v", err)
  1505. }
  1506. fw, err := os.Create(localPath)
  1507. if err != nil {
  1508. return nil, fmt.Errorf("Create: %v", err)
  1509. }
  1510. defer fw.Close()
  1511. if _, err = fw.Write(buf); err != nil {
  1512. return nil, fmt.Errorf("Write: %v", err)
  1513. } else if _, err = io.Copy(fw, file); err != nil {
  1514. return nil, fmt.Errorf("Copy: %v", err)
  1515. }
  1516. if _, err := x.Insert(attach); err != nil {
  1517. return nil, err
  1518. }
  1519. return attach, nil
  1520. }
  1521. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1522. attach := &Attachment{UUID: uuid}
  1523. has, err := x.Get(attach)
  1524. if err != nil {
  1525. return nil, err
  1526. } else if !has {
  1527. return nil, ErrAttachmentNotExist{0, uuid}
  1528. }
  1529. return attach, nil
  1530. }
  1531. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  1532. if len(uuids) == 0 {
  1533. return []*Attachment{}, nil
  1534. }
  1535. // Silently drop invalid uuids.
  1536. attachments := make([]*Attachment, 0, len(uuids))
  1537. return attachments, e.In("uuid", uuids).Find(&attachments)
  1538. }
  1539. // GetAttachmentByUUID returns attachment by given UUID.
  1540. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1541. return getAttachmentByUUID(x, uuid)
  1542. }
  1543. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  1544. attachments := make([]*Attachment, 0, 10)
  1545. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  1546. }
  1547. // GetAttachmentsByIssueID returns all attachments of an issue.
  1548. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1549. return getAttachmentsByIssueID(x, issueID)
  1550. }
  1551. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1552. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1553. attachments := make([]*Attachment, 0, 10)
  1554. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1555. }
  1556. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1557. func DeleteAttachment(a *Attachment, remove bool) error {
  1558. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1559. return err
  1560. }
  1561. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1562. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1563. for i, a := range attachments {
  1564. if remove {
  1565. if err := os.Remove(a.LocalPath()); err != nil {
  1566. return i, err
  1567. }
  1568. }
  1569. if _, err := x.Delete(a); err != nil {
  1570. return i, err
  1571. }
  1572. }
  1573. return len(attachments), nil
  1574. }
  1575. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1576. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  1577. attachments, err := GetAttachmentsByIssueID(issueID)
  1578. if err != nil {
  1579. return 0, err
  1580. }
  1581. return DeleteAttachments(attachments, remove)
  1582. }
  1583. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1584. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  1585. attachments, err := GetAttachmentsByCommentID(commentID)
  1586. if err != nil {
  1587. return 0, err
  1588. }
  1589. return DeleteAttachments(attachments, remove)
  1590. }