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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  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(userID int64) error {
  383. if err := UpdateIssueUserByRead(userID, issue.ID); err != nil {
  384. return err
  385. }
  386. if err := setNotificationStatusRead(x, userID, issue.ID); err != nil {
  387. return err
  388. }
  389. return nil
  390. }
  391. func updateIssueCols(e Engine, issue *Issue, cols ...string) error {
  392. _, err := e.Id(issue.ID).Cols(cols...).Update(issue)
  393. return err
  394. }
  395. // UpdateIssueCols only updates values of specific columns for given issue.
  396. func UpdateIssueCols(issue *Issue, cols ...string) error {
  397. return updateIssueCols(x, issue, cols...)
  398. }
  399. func (issue *Issue) changeStatus(e *xorm.Session, doer *User, repo *Repository, isClosed bool) (err error) {
  400. // Nothing should be performed if current status is same as target status
  401. if issue.IsClosed == isClosed {
  402. return nil
  403. }
  404. issue.IsClosed = isClosed
  405. if err = updateIssueCols(e, issue, "is_closed"); err != nil {
  406. return err
  407. } else if err = updateIssueUsersByStatus(e, issue.ID, isClosed); err != nil {
  408. return err
  409. }
  410. // Update issue count of labels
  411. if err = issue.getLabels(e); err != nil {
  412. return err
  413. }
  414. for idx := range issue.Labels {
  415. if issue.IsClosed {
  416. issue.Labels[idx].NumClosedIssues++
  417. } else {
  418. issue.Labels[idx].NumClosedIssues--
  419. }
  420. if err = updateLabel(e, issue.Labels[idx]); err != nil {
  421. return err
  422. }
  423. }
  424. // Update issue count of milestone
  425. if err = changeMilestoneIssueStats(e, issue); err != nil {
  426. return err
  427. }
  428. // New action comment
  429. if _, err = createStatusComment(e, doer, repo, issue); err != nil {
  430. return err
  431. }
  432. return nil
  433. }
  434. // ChangeStatus changes issue status to open or closed.
  435. func (issue *Issue) ChangeStatus(doer *User, repo *Repository, isClosed bool) (err error) {
  436. sess := x.NewSession()
  437. defer sessionRelease(sess)
  438. if err = sess.Begin(); err != nil {
  439. return err
  440. }
  441. if err = issue.changeStatus(sess, doer, repo, isClosed); err != nil {
  442. return err
  443. }
  444. if err = sess.Commit(); err != nil {
  445. return fmt.Errorf("Commit: %v", err)
  446. }
  447. if issue.IsPull {
  448. // Merge pull request calls issue.changeStatus so we need to handle separately.
  449. issue.PullRequest.Issue = issue
  450. apiPullRequest := &api.PullRequestPayload{
  451. Index: issue.Index,
  452. PullRequest: issue.PullRequest.APIFormat(),
  453. Repository: repo.APIFormat(AccessModeNone),
  454. Sender: doer.APIFormat(),
  455. }
  456. if isClosed {
  457. apiPullRequest.Action = api.HookIssueClosed
  458. } else {
  459. apiPullRequest.Action = api.HookIssueReOpened
  460. }
  461. err = PrepareWebhooks(repo, HookEventPullRequest, apiPullRequest)
  462. }
  463. if err != nil {
  464. log.Error(4, "PrepareWebhooks [is_pull: %v, is_closed: %v]: %v", issue.IsPull, isClosed, err)
  465. } else {
  466. go HookQueue.Add(repo.ID)
  467. }
  468. return nil
  469. }
  470. // ChangeTitle changes the title of this issue, as the given user.
  471. func (issue *Issue) ChangeTitle(doer *User, title string) (err error) {
  472. oldTitle := issue.Title
  473. issue.Title = title
  474. if err = UpdateIssueCols(issue, "name"); err != nil {
  475. return fmt.Errorf("UpdateIssueCols: %v", err)
  476. }
  477. if issue.IsPull {
  478. issue.PullRequest.Issue = issue
  479. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  480. Action: api.HookIssueEdited,
  481. Index: issue.Index,
  482. Changes: &api.ChangesPayload{
  483. Title: &api.ChangesFromPayload{
  484. From: oldTitle,
  485. },
  486. },
  487. PullRequest: issue.PullRequest.APIFormat(),
  488. Repository: issue.Repo.APIFormat(AccessModeNone),
  489. Sender: doer.APIFormat(),
  490. })
  491. }
  492. if err != nil {
  493. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  494. } else {
  495. go HookQueue.Add(issue.RepoID)
  496. }
  497. return nil
  498. }
  499. // ChangeContent changes issue content, as the given user.
  500. func (issue *Issue) ChangeContent(doer *User, content string) (err error) {
  501. oldContent := issue.Content
  502. issue.Content = content
  503. if err = UpdateIssueCols(issue, "content"); err != nil {
  504. return fmt.Errorf("UpdateIssueCols: %v", err)
  505. }
  506. if issue.IsPull {
  507. issue.PullRequest.Issue = issue
  508. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, &api.PullRequestPayload{
  509. Action: api.HookIssueEdited,
  510. Index: issue.Index,
  511. Changes: &api.ChangesPayload{
  512. Body: &api.ChangesFromPayload{
  513. From: oldContent,
  514. },
  515. },
  516. PullRequest: issue.PullRequest.APIFormat(),
  517. Repository: issue.Repo.APIFormat(AccessModeNone),
  518. Sender: doer.APIFormat(),
  519. })
  520. }
  521. if err != nil {
  522. log.Error(4, "PrepareWebhooks [is_pull: %v]: %v", issue.IsPull, err)
  523. } else {
  524. go HookQueue.Add(issue.RepoID)
  525. }
  526. return nil
  527. }
  528. // ChangeAssignee changes the Asssignee field of this issue.
  529. func (issue *Issue) ChangeAssignee(doer *User, assigneeID int64) (err error) {
  530. issue.AssigneeID = assigneeID
  531. if err = UpdateIssueUserByAssignee(issue); err != nil {
  532. return fmt.Errorf("UpdateIssueUserByAssignee: %v", err)
  533. }
  534. issue.Assignee, err = GetUserByID(issue.AssigneeID)
  535. if err != nil && !IsErrUserNotExist(err) {
  536. log.Error(4, "GetUserByID [assignee_id: %v]: %v", issue.AssigneeID, err)
  537. return nil
  538. }
  539. // Error not nil here means user does not exist, which is remove assignee.
  540. isRemoveAssignee := err != nil
  541. if issue.IsPull {
  542. issue.PullRequest.Issue = issue
  543. apiPullRequest := &api.PullRequestPayload{
  544. Index: issue.Index,
  545. PullRequest: issue.PullRequest.APIFormat(),
  546. Repository: issue.Repo.APIFormat(AccessModeNone),
  547. Sender: doer.APIFormat(),
  548. }
  549. if isRemoveAssignee {
  550. apiPullRequest.Action = api.HookIssueUnassigned
  551. } else {
  552. apiPullRequest.Action = api.HookIssueAssigned
  553. }
  554. err = PrepareWebhooks(issue.Repo, HookEventPullRequest, apiPullRequest)
  555. }
  556. if err != nil {
  557. log.Error(4, "PrepareWebhooks [is_pull: %v, remove_assignee: %v]: %v", issue.IsPull, isRemoveAssignee, err)
  558. } else {
  559. go HookQueue.Add(issue.RepoID)
  560. }
  561. return nil
  562. }
  563. // NewIssueOptions represents the options of a new issue.
  564. type NewIssueOptions struct {
  565. Repo *Repository
  566. Issue *Issue
  567. LableIDs []int64
  568. Attachments []string // In UUID format.
  569. IsPull bool
  570. }
  571. func newIssue(e *xorm.Session, opts NewIssueOptions) (err error) {
  572. opts.Issue.Title = strings.TrimSpace(opts.Issue.Title)
  573. opts.Issue.Index = opts.Repo.NextIssueIndex()
  574. if opts.Issue.MilestoneID > 0 {
  575. milestone, err := getMilestoneByRepoID(e, opts.Issue.RepoID, opts.Issue.MilestoneID)
  576. if err != nil && !IsErrMilestoneNotExist(err) {
  577. return fmt.Errorf("getMilestoneByID: %v", err)
  578. }
  579. // Assume milestone is invalid and drop silently.
  580. opts.Issue.MilestoneID = 0
  581. if milestone != nil {
  582. opts.Issue.MilestoneID = milestone.ID
  583. opts.Issue.Milestone = milestone
  584. if err = changeMilestoneAssign(e, opts.Issue, -1); err != nil {
  585. return err
  586. }
  587. }
  588. }
  589. if opts.Issue.AssigneeID > 0 {
  590. assignee, err := getUserByID(e, opts.Issue.AssigneeID)
  591. if err != nil && !IsErrUserNotExist(err) {
  592. return fmt.Errorf("getUserByID: %v", err)
  593. }
  594. // Assume assignee is invalid and drop silently.
  595. opts.Issue.AssigneeID = 0
  596. if assignee != nil {
  597. valid, err := hasAccess(e, assignee, opts.Repo, AccessModeWrite)
  598. if err != nil {
  599. return fmt.Errorf("hasAccess [user_id: %d, repo_id: %d]: %v", assignee.ID, opts.Repo.ID, err)
  600. }
  601. if valid {
  602. opts.Issue.AssigneeID = assignee.ID
  603. opts.Issue.Assignee = assignee
  604. }
  605. }
  606. }
  607. // Milestone and assignee validation should happen before insert actual object.
  608. if _, err = e.Insert(opts.Issue); err != nil {
  609. return err
  610. }
  611. if opts.IsPull {
  612. _, err = e.Exec("UPDATE `repository` SET num_pulls = num_pulls + 1 WHERE id = ?", opts.Issue.RepoID)
  613. } else {
  614. _, err = e.Exec("UPDATE `repository` SET num_issues = num_issues + 1 WHERE id = ?", opts.Issue.RepoID)
  615. }
  616. if err != nil {
  617. return err
  618. }
  619. if len(opts.LableIDs) > 0 {
  620. // During the session, SQLite3 driver cannot handle retrieve objects after update something.
  621. // So we have to get all needed labels first.
  622. labels := make([]*Label, 0, len(opts.LableIDs))
  623. if err = e.In("id", opts.LableIDs).Find(&labels); err != nil {
  624. return fmt.Errorf("find all labels [label_ids: %v]: %v", opts.LableIDs, err)
  625. }
  626. for _, label := range labels {
  627. // Silently drop invalid labels.
  628. if label.RepoID != opts.Repo.ID {
  629. continue
  630. }
  631. if err = opts.Issue.addLabel(e, label); err != nil {
  632. return fmt.Errorf("addLabel [id: %d]: %v", label.ID, err)
  633. }
  634. }
  635. }
  636. if err = newIssueUsers(e, opts.Repo, opts.Issue); err != nil {
  637. return err
  638. }
  639. if len(opts.Attachments) > 0 {
  640. attachments, err := getAttachmentsByUUIDs(e, opts.Attachments)
  641. if err != nil {
  642. return fmt.Errorf("getAttachmentsByUUIDs [uuids: %v]: %v", opts.Attachments, err)
  643. }
  644. for i := 0; i < len(attachments); i++ {
  645. attachments[i].IssueID = opts.Issue.ID
  646. if _, err = e.Id(attachments[i].ID).Update(attachments[i]); err != nil {
  647. return fmt.Errorf("update attachment [id: %d]: %v", attachments[i].ID, err)
  648. }
  649. }
  650. }
  651. return opts.Issue.loadAttributes(e)
  652. }
  653. // NewIssue creates new issue with labels for repository.
  654. func NewIssue(repo *Repository, issue *Issue, labelIDs []int64, uuids []string) (err error) {
  655. sess := x.NewSession()
  656. defer sessionRelease(sess)
  657. if err = sess.Begin(); err != nil {
  658. return err
  659. }
  660. if err = newIssue(sess, NewIssueOptions{
  661. Repo: repo,
  662. Issue: issue,
  663. LableIDs: labelIDs,
  664. Attachments: uuids,
  665. }); err != nil {
  666. return fmt.Errorf("newIssue: %v", err)
  667. }
  668. if err = sess.Commit(); err != nil {
  669. return fmt.Errorf("Commit: %v", err)
  670. }
  671. if err = NotifyWatchers(&Action{
  672. ActUserID: issue.Poster.ID,
  673. ActUserName: issue.Poster.Name,
  674. OpType: ActionCreateIssue,
  675. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Title),
  676. RepoID: repo.ID,
  677. RepoUserName: repo.Owner.Name,
  678. RepoName: repo.Name,
  679. IsPrivate: repo.IsPrivate,
  680. }); err != nil {
  681. log.Error(4, "NotifyWatchers: %v", err)
  682. }
  683. if err = issue.MailParticipants(); err != nil {
  684. log.Error(4, "MailParticipants: %v", err)
  685. }
  686. return nil
  687. }
  688. // GetIssueByRef returns an Issue specified by a GFM reference.
  689. // See https://help.github.com/articles/writing-on-github#references for more information on the syntax.
  690. func GetIssueByRef(ref string) (*Issue, error) {
  691. n := strings.IndexByte(ref, byte('#'))
  692. if n == -1 {
  693. return nil, errMissingIssueNumber
  694. }
  695. index, err := com.StrTo(ref[n+1:]).Int64()
  696. if err != nil {
  697. return nil, err
  698. }
  699. repo, err := GetRepositoryByRef(ref[:n])
  700. if err != nil {
  701. return nil, err
  702. }
  703. issue, err := GetIssueByIndex(repo.ID, index)
  704. if err != nil {
  705. return nil, err
  706. }
  707. return issue, issue.LoadAttributes()
  708. }
  709. // GetRawIssueByIndex returns raw issue without loading attributes by index in a repository.
  710. func GetRawIssueByIndex(repoID, index int64) (*Issue, error) {
  711. issue := &Issue{
  712. RepoID: repoID,
  713. Index: index,
  714. }
  715. has, err := x.Get(issue)
  716. if err != nil {
  717. return nil, err
  718. } else if !has {
  719. return nil, ErrIssueNotExist{0, repoID, index}
  720. }
  721. return issue, nil
  722. }
  723. // GetIssueByIndex returns issue by index in a repository.
  724. func GetIssueByIndex(repoID, index int64) (*Issue, error) {
  725. issue, err := GetRawIssueByIndex(repoID, index)
  726. if err != nil {
  727. return nil, err
  728. }
  729. return issue, issue.LoadAttributes()
  730. }
  731. func getIssueByID(e Engine, id int64) (*Issue, error) {
  732. issue := new(Issue)
  733. has, err := e.Id(id).Get(issue)
  734. if err != nil {
  735. return nil, err
  736. } else if !has {
  737. return nil, ErrIssueNotExist{id, 0, 0}
  738. }
  739. return issue, issue.LoadAttributes()
  740. }
  741. // GetIssueByID returns an issue by given ID.
  742. func GetIssueByID(id int64) (*Issue, error) {
  743. return getIssueByID(x, id)
  744. }
  745. // IssuesOptions represents options of an issue.
  746. type IssuesOptions struct {
  747. RepoID int64
  748. AssigneeID int64
  749. PosterID int64
  750. MentionedID int64
  751. MilestoneID int64
  752. RepoIDs []int64
  753. Page int
  754. IsClosed bool
  755. IsPull bool
  756. Labels string
  757. SortType string
  758. }
  759. // sortIssuesSession sort an issues-related session based on the provided
  760. // sortType string
  761. func sortIssuesSession(sess *xorm.Session, sortType string) {
  762. switch sortType {
  763. case "oldest":
  764. sess.Asc("issue.created_unix")
  765. case "recentupdate":
  766. sess.Desc("issue.updated_unix")
  767. case "leastupdate":
  768. sess.Asc("issue.updated_unix")
  769. case "mostcomment":
  770. sess.Desc("issue.num_comments")
  771. case "leastcomment":
  772. sess.Asc("issue.num_comments")
  773. case "priority":
  774. sess.Desc("issue.priority")
  775. default:
  776. sess.Desc("issue.created_unix")
  777. }
  778. }
  779. // Issues returns a list of issues by given conditions.
  780. func Issues(opts *IssuesOptions) ([]*Issue, error) {
  781. if opts.Page <= 0 {
  782. opts.Page = 1
  783. }
  784. sess := x.Limit(setting.UI.IssuePagingNum, (opts.Page-1)*setting.UI.IssuePagingNum)
  785. if opts.RepoID > 0 {
  786. sess.And("issue.repo_id=?", opts.RepoID)
  787. } else if len(opts.RepoIDs) > 0 {
  788. // In case repository IDs are provided but actually no repository has issue.
  789. sess.In("issue.repo_id", opts.RepoIDs)
  790. }
  791. sess.And("issue.is_closed=?", opts.IsClosed)
  792. if opts.AssigneeID > 0 {
  793. sess.And("issue.assignee_id=?", opts.AssigneeID)
  794. }
  795. if opts.PosterID > 0 {
  796. sess.And("issue.poster_id=?", opts.PosterID)
  797. }
  798. if opts.MentionedID > 0 {
  799. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  800. And("issue_user.is_mentioned = ?", true).
  801. And("issue_user.uid = ?", opts.MentionedID)
  802. }
  803. if opts.MilestoneID > 0 {
  804. sess.And("issue.milestone_id=?", opts.MilestoneID)
  805. }
  806. sess.And("issue.is_pull=?", opts.IsPull)
  807. sortIssuesSession(sess, opts.SortType)
  808. if len(opts.Labels) > 0 && opts.Labels != "0" {
  809. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  810. if err != nil {
  811. return nil, err
  812. }
  813. if len(labelIDs) > 0 {
  814. sess.
  815. Join("INNER", "issue_label", "issue.id = issue_label.issue_id").
  816. In("issue_label.label_id", labelIDs)
  817. }
  818. }
  819. issues := make([]*Issue, 0, setting.UI.IssuePagingNum)
  820. if err := sess.Find(&issues); err != nil {
  821. return nil, fmt.Errorf("Find: %v", err)
  822. }
  823. // FIXME: use IssueList to improve performance.
  824. for i := range issues {
  825. if err := issues[i].LoadAttributes(); err != nil {
  826. return nil, fmt.Errorf("LoadAttributes [%d]: %v", issues[i].ID, err)
  827. }
  828. }
  829. return issues, nil
  830. }
  831. // .___ ____ ___
  832. // | | ______ ________ __ ____ | | \______ ___________
  833. // | |/ ___// ___/ | \_/ __ \| | / ___// __ \_ __ \
  834. // | |\___ \ \___ \| | /\ ___/| | /\___ \\ ___/| | \/
  835. // |___/____ >____ >____/ \___ >______//____ >\___ >__|
  836. // \/ \/ \/ \/ \/
  837. // IssueUser represents an issue-user relation.
  838. type IssueUser struct {
  839. ID int64 `xorm:"pk autoincr"`
  840. UID int64 `xorm:"INDEX"` // User ID.
  841. IssueID int64
  842. RepoID int64 `xorm:"INDEX"`
  843. MilestoneID int64
  844. IsRead bool
  845. IsAssigned bool
  846. IsMentioned bool
  847. IsPoster bool
  848. IsClosed bool
  849. }
  850. func newIssueUsers(e *xorm.Session, repo *Repository, issue *Issue) error {
  851. assignees, err := repo.getAssignees(e)
  852. if err != nil {
  853. return fmt.Errorf("getAssignees: %v", err)
  854. }
  855. // Poster can be anyone, append later if not one of assignees.
  856. isPosterAssignee := false
  857. // Leave a seat for poster itself to append later, but if poster is one of assignee
  858. // and just waste 1 unit is cheaper than re-allocate memory once.
  859. issueUsers := make([]*IssueUser, 0, len(assignees)+1)
  860. for _, assignee := range assignees {
  861. isPoster := assignee.ID == issue.PosterID
  862. issueUsers = append(issueUsers, &IssueUser{
  863. IssueID: issue.ID,
  864. RepoID: repo.ID,
  865. UID: assignee.ID,
  866. IsPoster: isPoster,
  867. IsAssigned: assignee.ID == issue.AssigneeID,
  868. })
  869. if !isPosterAssignee && isPoster {
  870. isPosterAssignee = true
  871. }
  872. }
  873. if !isPosterAssignee {
  874. issueUsers = append(issueUsers, &IssueUser{
  875. IssueID: issue.ID,
  876. RepoID: repo.ID,
  877. UID: issue.PosterID,
  878. IsPoster: true,
  879. })
  880. }
  881. if _, err = e.Insert(issueUsers); err != nil {
  882. return err
  883. }
  884. return nil
  885. }
  886. // NewIssueUsers adds new issue-user relations for new issue of repository.
  887. func NewIssueUsers(repo *Repository, issue *Issue) (err error) {
  888. sess := x.NewSession()
  889. defer sessionRelease(sess)
  890. if err = sess.Begin(); err != nil {
  891. return err
  892. }
  893. if err = newIssueUsers(sess, repo, issue); err != nil {
  894. return err
  895. }
  896. return sess.Commit()
  897. }
  898. // PairsContains returns true when pairs list contains given issue.
  899. func PairsContains(ius []*IssueUser, issueID, uid int64) int {
  900. for i := range ius {
  901. if ius[i].IssueID == issueID &&
  902. ius[i].UID == uid {
  903. return i
  904. }
  905. }
  906. return -1
  907. }
  908. // GetIssueUsers returns issue-user pairs by given repository and user.
  909. func GetIssueUsers(rid, uid int64, isClosed bool) ([]*IssueUser, error) {
  910. ius := make([]*IssueUser, 0, 10)
  911. err := x.Where("is_closed=?", isClosed).Find(&ius, &IssueUser{RepoID: rid, UID: uid})
  912. return ius, err
  913. }
  914. // GetIssueUserPairsByRepoIds returns issue-user pairs by given repository IDs.
  915. func GetIssueUserPairsByRepoIds(rids []int64, isClosed bool, page int) ([]*IssueUser, error) {
  916. if len(rids) == 0 {
  917. return []*IssueUser{}, nil
  918. }
  919. ius := make([]*IssueUser, 0, 10)
  920. sess := x.
  921. Limit(20, (page-1)*20).
  922. Where("is_closed=?", isClosed).
  923. In("repo_id", rids)
  924. err := sess.Find(&ius)
  925. return ius, err
  926. }
  927. // GetIssueUserPairsByMode returns issue-user pairs by given repository and user.
  928. func GetIssueUserPairsByMode(uid, rid int64, isClosed bool, page, filterMode int) ([]*IssueUser, error) {
  929. ius := make([]*IssueUser, 0, 10)
  930. sess := x.
  931. Limit(20, (page-1)*20).
  932. Where("uid=?", uid).
  933. And("is_closed=?", isClosed)
  934. if rid > 0 {
  935. sess.And("repo_id=?", rid)
  936. }
  937. switch filterMode {
  938. case FilterModeAssign:
  939. sess.And("is_assigned=?", true)
  940. case FilterModeCreate:
  941. sess.And("is_poster=?", true)
  942. default:
  943. return ius, nil
  944. }
  945. err := sess.Find(&ius)
  946. return ius, err
  947. }
  948. // UpdateIssueMentions extracts mentioned people from content and
  949. // updates issue-user relations for them.
  950. func UpdateIssueMentions(e Engine, issueID int64, mentions []string) error {
  951. if len(mentions) == 0 {
  952. return nil
  953. }
  954. for i := range mentions {
  955. mentions[i] = strings.ToLower(mentions[i])
  956. }
  957. users := make([]*User, 0, len(mentions))
  958. if err := e.In("lower_name", mentions).Asc("lower_name").Find(&users); err != nil {
  959. return fmt.Errorf("find mentioned users: %v", err)
  960. }
  961. ids := make([]int64, 0, len(mentions))
  962. for _, user := range users {
  963. ids = append(ids, user.ID)
  964. if !user.IsOrganization() || user.NumMembers == 0 {
  965. continue
  966. }
  967. memberIDs := make([]int64, 0, user.NumMembers)
  968. orgUsers, err := GetOrgUsersByOrgID(user.ID)
  969. if err != nil {
  970. return fmt.Errorf("GetOrgUsersByOrgID [%d]: %v", user.ID, err)
  971. }
  972. for _, orgUser := range orgUsers {
  973. memberIDs = append(memberIDs, orgUser.ID)
  974. }
  975. ids = append(ids, memberIDs...)
  976. }
  977. if err := UpdateIssueUsersByMentions(e, issueID, ids); err != nil {
  978. return fmt.Errorf("UpdateIssueUsersByMentions: %v", err)
  979. }
  980. return nil
  981. }
  982. // IssueStats represents issue statistic information.
  983. type IssueStats struct {
  984. OpenCount, ClosedCount int64
  985. AllCount int64
  986. AssignCount int64
  987. CreateCount int64
  988. MentionCount int64
  989. }
  990. // Filter modes.
  991. const (
  992. FilterModeAll = iota
  993. FilterModeAssign
  994. FilterModeCreate
  995. FilterModeMention
  996. )
  997. func parseCountResult(results []map[string][]byte) int64 {
  998. if len(results) == 0 {
  999. return 0
  1000. }
  1001. for _, result := range results[0] {
  1002. return com.StrTo(string(result)).MustInt64()
  1003. }
  1004. return 0
  1005. }
  1006. // IssueStatsOptions contains parameters accepted by GetIssueStats.
  1007. type IssueStatsOptions struct {
  1008. RepoID int64
  1009. Labels string
  1010. MilestoneID int64
  1011. AssigneeID int64
  1012. MentionedID int64
  1013. PosterID int64
  1014. IsPull bool
  1015. }
  1016. // GetIssueStats returns issue statistic information by given conditions.
  1017. func GetIssueStats(opts *IssueStatsOptions) *IssueStats {
  1018. stats := &IssueStats{}
  1019. countSession := func(opts *IssueStatsOptions) *xorm.Session {
  1020. sess := x.
  1021. Where("issue.repo_id = ?", opts.RepoID).
  1022. And("is_pull = ?", opts.IsPull)
  1023. if len(opts.Labels) > 0 && opts.Labels != "0" {
  1024. labelIDs, err := base.StringsToInt64s(strings.Split(opts.Labels, ","))
  1025. if err != nil {
  1026. log.Warn("Malformed Labels argument: %s", opts.Labels)
  1027. } else if len(labelIDs) > 0 {
  1028. sess.Join("INNER", "issue_label", "issue.id = issue_id").
  1029. In("label_id", labelIDs)
  1030. }
  1031. }
  1032. if opts.MilestoneID > 0 {
  1033. sess.And("issue.milestone_id = ?", opts.MilestoneID)
  1034. }
  1035. if opts.AssigneeID > 0 {
  1036. sess.And("assignee_id = ?", opts.AssigneeID)
  1037. }
  1038. if opts.PosterID > 0 {
  1039. sess.And("poster_id = ?", opts.PosterID)
  1040. }
  1041. if opts.MentionedID > 0 {
  1042. sess.Join("INNER", "issue_user", "issue.id = issue_user.issue_id").
  1043. And("issue_user.uid = ?", opts.MentionedID).
  1044. And("issue_user.is_mentioned = ?", true)
  1045. }
  1046. return sess
  1047. }
  1048. stats.OpenCount, _ = countSession(opts).
  1049. And("is_closed = ?", false).
  1050. Count(&Issue{})
  1051. stats.ClosedCount, _ = countSession(opts).
  1052. And("is_closed = ?", true).
  1053. Count(&Issue{})
  1054. return stats
  1055. }
  1056. // GetUserIssueStats returns issue statistic information for dashboard by given conditions.
  1057. func GetUserIssueStats(repoID, uid int64, repoIDs []int64, filterMode int, isPull bool) *IssueStats {
  1058. stats := &IssueStats{}
  1059. countSession := func(isClosed, isPull bool, repoID int64, repoIDs []int64) *xorm.Session {
  1060. sess := x.
  1061. Where("issue.is_closed = ?", isClosed).
  1062. And("issue.is_pull = ?", isPull)
  1063. if repoID > 0 {
  1064. sess.And("repo_id = ?", repoID)
  1065. } else if len(repoIDs) > 0 {
  1066. sess.In("repo_id", repoIDs)
  1067. }
  1068. return sess
  1069. }
  1070. stats.AssignCount, _ = countSession(false, isPull, repoID, repoIDs).
  1071. And("assignee_id = ?", uid).
  1072. Count(&Issue{})
  1073. stats.CreateCount, _ = countSession(false, isPull, repoID, repoIDs).
  1074. And("poster_id = ?", uid).
  1075. Count(&Issue{})
  1076. openCountSession := countSession(false, isPull, repoID, repoIDs)
  1077. closedCountSession := countSession(true, isPull, repoID, repoIDs)
  1078. switch filterMode {
  1079. case FilterModeAssign:
  1080. openCountSession.And("assignee_id = ?", uid)
  1081. closedCountSession.And("assignee_id = ?", uid)
  1082. case FilterModeCreate:
  1083. openCountSession.And("poster_id = ?", uid)
  1084. closedCountSession.And("poster_id = ?", uid)
  1085. }
  1086. stats.OpenCount, _ = openCountSession.Count(&Issue{})
  1087. stats.ClosedCount, _ = closedCountSession.Count(&Issue{})
  1088. return stats
  1089. }
  1090. // GetRepoIssueStats returns number of open and closed repository issues by given filter mode.
  1091. func GetRepoIssueStats(repoID, uid int64, filterMode int, isPull bool) (numOpen int64, numClosed int64) {
  1092. countSession := func(isClosed, isPull bool, repoID int64) *xorm.Session {
  1093. sess := x.
  1094. Where("issue.repo_id = ?", isClosed).
  1095. And("is_pull = ?", isPull).
  1096. And("repo_id = ?", repoID)
  1097. return sess
  1098. }
  1099. openCountSession := countSession(false, isPull, repoID)
  1100. closedCountSession := countSession(true, isPull, repoID)
  1101. switch filterMode {
  1102. case FilterModeAssign:
  1103. openCountSession.And("assignee_id = ?", uid)
  1104. closedCountSession.And("assignee_id = ?", uid)
  1105. case FilterModeCreate:
  1106. openCountSession.And("poster_id = ?", uid)
  1107. closedCountSession.And("poster_id = ?", uid)
  1108. }
  1109. openResult, _ := openCountSession.Count(&Issue{})
  1110. closedResult, _ := closedCountSession.Count(&Issue{})
  1111. return openResult, closedResult
  1112. }
  1113. func updateIssue(e Engine, issue *Issue) error {
  1114. _, err := e.Id(issue.ID).AllCols().Update(issue)
  1115. return err
  1116. }
  1117. // UpdateIssue updates all fields of given issue.
  1118. func UpdateIssue(issue *Issue) error {
  1119. return updateIssue(x, issue)
  1120. }
  1121. func updateIssueUsersByStatus(e Engine, issueID int64, isClosed bool) error {
  1122. _, err := e.Exec("UPDATE `issue_user` SET is_closed=? WHERE issue_id=?", isClosed, issueID)
  1123. return err
  1124. }
  1125. // UpdateIssueUsersByStatus updates issue-user relations by issue status.
  1126. func UpdateIssueUsersByStatus(issueID int64, isClosed bool) error {
  1127. return updateIssueUsersByStatus(x, issueID, isClosed)
  1128. }
  1129. func updateIssueUserByAssignee(e *xorm.Session, issue *Issue) (err error) {
  1130. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE issue_id = ?", false, issue.ID); err != nil {
  1131. return err
  1132. }
  1133. // Assignee ID equals to 0 means clear assignee.
  1134. if issue.AssigneeID > 0 {
  1135. if _, err = e.Exec("UPDATE `issue_user` SET is_assigned = ? WHERE uid = ? AND issue_id = ?", true, issue.AssigneeID, issue.ID); err != nil {
  1136. return err
  1137. }
  1138. }
  1139. return updateIssue(e, issue)
  1140. }
  1141. // UpdateIssueUserByAssignee updates issue-user relation for assignee.
  1142. func UpdateIssueUserByAssignee(issue *Issue) (err error) {
  1143. sess := x.NewSession()
  1144. defer sessionRelease(sess)
  1145. if err = sess.Begin(); err != nil {
  1146. return err
  1147. }
  1148. if err = updateIssueUserByAssignee(sess, issue); err != nil {
  1149. return err
  1150. }
  1151. return sess.Commit()
  1152. }
  1153. // UpdateIssueUserByRead updates issue-user relation for reading.
  1154. func UpdateIssueUserByRead(uid, issueID int64) error {
  1155. _, err := x.Exec("UPDATE `issue_user` SET is_read=? WHERE uid=? AND issue_id=?", true, uid, issueID)
  1156. return err
  1157. }
  1158. // UpdateIssueUsersByMentions updates issue-user pairs by mentioning.
  1159. func UpdateIssueUsersByMentions(e Engine, issueID int64, uids []int64) error {
  1160. for _, uid := range uids {
  1161. iu := &IssueUser{
  1162. UID: uid,
  1163. IssueID: issueID,
  1164. }
  1165. has, err := e.Get(iu)
  1166. if err != nil {
  1167. return err
  1168. }
  1169. iu.IsMentioned = true
  1170. if has {
  1171. _, err = e.Id(iu.ID).AllCols().Update(iu)
  1172. } else {
  1173. _, err = e.Insert(iu)
  1174. }
  1175. if err != nil {
  1176. return err
  1177. }
  1178. }
  1179. return nil
  1180. }
  1181. // _____ .__.__ __
  1182. // / \ |__| | ____ _______/ |_ ____ ____ ____
  1183. // / \ / \| | | _/ __ \ / ___/\ __\/ _ \ / \_/ __ \
  1184. // / Y \ | |_\ ___/ \___ \ | | ( <_> ) | \ ___/
  1185. // \____|__ /__|____/\___ >____ > |__| \____/|___| /\___ >
  1186. // \/ \/ \/ \/ \/
  1187. // Milestone represents a milestone of repository.
  1188. type Milestone struct {
  1189. ID int64 `xorm:"pk autoincr"`
  1190. RepoID int64 `xorm:"INDEX"`
  1191. Name string
  1192. Content string `xorm:"TEXT"`
  1193. RenderedContent string `xorm:"-"`
  1194. IsClosed bool
  1195. NumIssues int
  1196. NumClosedIssues int
  1197. NumOpenIssues int `xorm:"-"`
  1198. Completeness int // Percentage(1-100).
  1199. IsOverDue bool `xorm:"-"`
  1200. DeadlineString string `xorm:"-"`
  1201. Deadline time.Time `xorm:"-"`
  1202. DeadlineUnix int64
  1203. ClosedDate time.Time `xorm:"-"`
  1204. ClosedDateUnix int64
  1205. }
  1206. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1207. func (m *Milestone) BeforeInsert() {
  1208. m.DeadlineUnix = m.Deadline.Unix()
  1209. }
  1210. // BeforeUpdate is invoked from XORM before updating this object.
  1211. func (m *Milestone) BeforeUpdate() {
  1212. if m.NumIssues > 0 {
  1213. m.Completeness = m.NumClosedIssues * 100 / m.NumIssues
  1214. } else {
  1215. m.Completeness = 0
  1216. }
  1217. m.DeadlineUnix = m.Deadline.Unix()
  1218. m.ClosedDateUnix = m.ClosedDate.Unix()
  1219. }
  1220. // AfterSet is invoked from XORM after setting the value of a field of
  1221. // this object.
  1222. func (m *Milestone) AfterSet(colName string, _ xorm.Cell) {
  1223. switch colName {
  1224. case "num_closed_issues":
  1225. m.NumOpenIssues = m.NumIssues - m.NumClosedIssues
  1226. case "deadline_unix":
  1227. m.Deadline = time.Unix(m.DeadlineUnix, 0).Local()
  1228. if m.Deadline.Year() == 9999 {
  1229. return
  1230. }
  1231. m.DeadlineString = m.Deadline.Format("2006-01-02")
  1232. if time.Now().Local().After(m.Deadline) {
  1233. m.IsOverDue = true
  1234. }
  1235. case "closed_date_unix":
  1236. m.ClosedDate = time.Unix(m.ClosedDateUnix, 0).Local()
  1237. }
  1238. }
  1239. // State returns string representation of milestone status.
  1240. func (m *Milestone) State() api.StateType {
  1241. if m.IsClosed {
  1242. return api.StateClosed
  1243. }
  1244. return api.StateOpen
  1245. }
  1246. // APIFormat returns this Milestone in API format.
  1247. func (m *Milestone) APIFormat() *api.Milestone {
  1248. apiMilestone := &api.Milestone{
  1249. ID: m.ID,
  1250. State: m.State(),
  1251. Title: m.Name,
  1252. Description: m.Content,
  1253. OpenIssues: m.NumOpenIssues,
  1254. ClosedIssues: m.NumClosedIssues,
  1255. }
  1256. if m.IsClosed {
  1257. apiMilestone.Closed = &m.ClosedDate
  1258. }
  1259. if m.Deadline.Year() < 9999 {
  1260. apiMilestone.Deadline = &m.Deadline
  1261. }
  1262. return apiMilestone
  1263. }
  1264. // NewMilestone creates new milestone of repository.
  1265. func NewMilestone(m *Milestone) (err error) {
  1266. sess := x.NewSession()
  1267. defer sessionRelease(sess)
  1268. if err = sess.Begin(); err != nil {
  1269. return err
  1270. }
  1271. if _, err = sess.Insert(m); err != nil {
  1272. return err
  1273. }
  1274. if _, err = sess.Exec("UPDATE `repository` SET num_milestones = num_milestones + 1 WHERE id = ?", m.RepoID); err != nil {
  1275. return err
  1276. }
  1277. return sess.Commit()
  1278. }
  1279. func getMilestoneByRepoID(e Engine, repoID, id int64) (*Milestone, error) {
  1280. m := &Milestone{
  1281. ID: id,
  1282. RepoID: repoID,
  1283. }
  1284. has, err := e.Get(m)
  1285. if err != nil {
  1286. return nil, err
  1287. } else if !has {
  1288. return nil, ErrMilestoneNotExist{id, repoID}
  1289. }
  1290. return m, nil
  1291. }
  1292. // GetMilestoneByRepoID returns the milestone in a repository.
  1293. func GetMilestoneByRepoID(repoID, id int64) (*Milestone, error) {
  1294. return getMilestoneByRepoID(x, repoID, id)
  1295. }
  1296. // GetMilestonesByRepoID returns all milestones of a repository.
  1297. func GetMilestonesByRepoID(repoID int64) ([]*Milestone, error) {
  1298. miles := make([]*Milestone, 0, 10)
  1299. return miles, x.Where("repo_id = ?", repoID).Find(&miles)
  1300. }
  1301. // GetMilestones returns a list of milestones of given repository and status.
  1302. func GetMilestones(repoID int64, page int, isClosed bool, sortType string) ([]*Milestone, error) {
  1303. miles := make([]*Milestone, 0, setting.UI.IssuePagingNum)
  1304. sess := x.Where("repo_id = ? AND is_closed = ?", repoID, isClosed)
  1305. if page > 0 {
  1306. sess = sess.Limit(setting.UI.IssuePagingNum, (page-1)*setting.UI.IssuePagingNum)
  1307. }
  1308. switch sortType {
  1309. case "furthestduedate":
  1310. sess.Desc("deadline_unix")
  1311. case "leastcomplete":
  1312. sess.Asc("completeness")
  1313. case "mostcomplete":
  1314. sess.Desc("completeness")
  1315. case "leastissues":
  1316. sess.Asc("num_issues")
  1317. case "mostissues":
  1318. sess.Desc("num_issues")
  1319. default:
  1320. sess.Asc("deadline_unix")
  1321. }
  1322. return miles, sess.Find(&miles)
  1323. }
  1324. func updateMilestone(e Engine, m *Milestone) error {
  1325. _, err := e.Id(m.ID).AllCols().Update(m)
  1326. return err
  1327. }
  1328. // UpdateMilestone updates information of given milestone.
  1329. func UpdateMilestone(m *Milestone) error {
  1330. return updateMilestone(x, m)
  1331. }
  1332. func countRepoMilestones(e Engine, repoID int64) int64 {
  1333. count, _ := e.
  1334. Where("repo_id=?", repoID).
  1335. Count(new(Milestone))
  1336. return count
  1337. }
  1338. // CountRepoMilestones returns number of milestones in given repository.
  1339. func CountRepoMilestones(repoID int64) int64 {
  1340. return countRepoMilestones(x, repoID)
  1341. }
  1342. func countRepoClosedMilestones(e Engine, repoID int64) int64 {
  1343. closed, _ := e.
  1344. Where("repo_id=? AND is_closed=?", repoID, true).
  1345. Count(new(Milestone))
  1346. return closed
  1347. }
  1348. // CountRepoClosedMilestones returns number of closed milestones in given repository.
  1349. func CountRepoClosedMilestones(repoID int64) int64 {
  1350. return countRepoClosedMilestones(x, repoID)
  1351. }
  1352. // MilestoneStats returns number of open and closed milestones of given repository.
  1353. func MilestoneStats(repoID int64) (open int64, closed int64) {
  1354. open, _ = x.
  1355. Where("repo_id=? AND is_closed=?", repoID, false).
  1356. Count(new(Milestone))
  1357. return open, CountRepoClosedMilestones(repoID)
  1358. }
  1359. // ChangeMilestoneStatus changes the milestone open/closed status.
  1360. func ChangeMilestoneStatus(m *Milestone, isClosed bool) (err error) {
  1361. repo, err := GetRepositoryByID(m.RepoID)
  1362. if err != nil {
  1363. return err
  1364. }
  1365. sess := x.NewSession()
  1366. defer sessionRelease(sess)
  1367. if err = sess.Begin(); err != nil {
  1368. return err
  1369. }
  1370. m.IsClosed = isClosed
  1371. if err = updateMilestone(sess, m); err != nil {
  1372. return err
  1373. }
  1374. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1375. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1376. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1377. return err
  1378. }
  1379. return sess.Commit()
  1380. }
  1381. func changeMilestoneIssueStats(e *xorm.Session, issue *Issue) error {
  1382. if issue.MilestoneID == 0 {
  1383. return nil
  1384. }
  1385. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1386. if err != nil {
  1387. return err
  1388. }
  1389. if issue.IsClosed {
  1390. m.NumOpenIssues--
  1391. m.NumClosedIssues++
  1392. } else {
  1393. m.NumOpenIssues++
  1394. m.NumClosedIssues--
  1395. }
  1396. return updateMilestone(e, m)
  1397. }
  1398. // ChangeMilestoneIssueStats updates the open/closed issues counter and progress
  1399. // for the milestone associated with the given issue.
  1400. func ChangeMilestoneIssueStats(issue *Issue) (err error) {
  1401. sess := x.NewSession()
  1402. defer sessionRelease(sess)
  1403. if err = sess.Begin(); err != nil {
  1404. return err
  1405. }
  1406. if err = changeMilestoneIssueStats(sess, issue); err != nil {
  1407. return err
  1408. }
  1409. return sess.Commit()
  1410. }
  1411. func changeMilestoneAssign(e *xorm.Session, issue *Issue, oldMilestoneID int64) error {
  1412. if oldMilestoneID > 0 {
  1413. m, err := getMilestoneByRepoID(e, issue.RepoID, oldMilestoneID)
  1414. if err != nil {
  1415. return err
  1416. }
  1417. m.NumIssues--
  1418. if issue.IsClosed {
  1419. m.NumClosedIssues--
  1420. }
  1421. if err = updateMilestone(e, m); err != nil {
  1422. return err
  1423. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE issue_id = ?", issue.ID); err != nil {
  1424. return err
  1425. }
  1426. }
  1427. if issue.MilestoneID > 0 {
  1428. m, err := getMilestoneByRepoID(e, issue.RepoID, issue.MilestoneID)
  1429. if err != nil {
  1430. return err
  1431. }
  1432. m.NumIssues++
  1433. if issue.IsClosed {
  1434. m.NumClosedIssues++
  1435. }
  1436. if err = updateMilestone(e, m); err != nil {
  1437. return err
  1438. } else if _, err = e.Exec("UPDATE `issue_user` SET milestone_id = ? WHERE issue_id = ?", m.ID, issue.ID); err != nil {
  1439. return err
  1440. }
  1441. }
  1442. return updateIssue(e, issue)
  1443. }
  1444. // ChangeMilestoneAssign changes assignment of milestone for issue.
  1445. func ChangeMilestoneAssign(issue *Issue, oldMilestoneID int64) (err error) {
  1446. sess := x.NewSession()
  1447. defer sess.Close()
  1448. if err = sess.Begin(); err != nil {
  1449. return err
  1450. }
  1451. if err = changeMilestoneAssign(sess, issue, oldMilestoneID); err != nil {
  1452. return err
  1453. }
  1454. return sess.Commit()
  1455. }
  1456. // DeleteMilestoneByRepoID deletes a milestone from a repository.
  1457. func DeleteMilestoneByRepoID(repoID, id int64) error {
  1458. m, err := GetMilestoneByRepoID(repoID, id)
  1459. if err != nil {
  1460. if IsErrMilestoneNotExist(err) {
  1461. return nil
  1462. }
  1463. return err
  1464. }
  1465. repo, err := GetRepositoryByID(m.RepoID)
  1466. if err != nil {
  1467. return err
  1468. }
  1469. sess := x.NewSession()
  1470. defer sessionRelease(sess)
  1471. if err = sess.Begin(); err != nil {
  1472. return err
  1473. }
  1474. if _, err = sess.Id(m.ID).Delete(new(Milestone)); err != nil {
  1475. return err
  1476. }
  1477. repo.NumMilestones = int(countRepoMilestones(sess, repo.ID))
  1478. repo.NumClosedMilestones = int(countRepoClosedMilestones(sess, repo.ID))
  1479. if _, err = sess.Id(repo.ID).AllCols().Update(repo); err != nil {
  1480. return err
  1481. }
  1482. if _, err = sess.Exec("UPDATE `issue` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1483. return err
  1484. } else if _, err = sess.Exec("UPDATE `issue_user` SET milestone_id = 0 WHERE milestone_id = ?", m.ID); err != nil {
  1485. return err
  1486. }
  1487. return sess.Commit()
  1488. }
  1489. // Attachment represent a attachment of issue/comment/release.
  1490. type Attachment struct {
  1491. ID int64 `xorm:"pk autoincr"`
  1492. UUID string `xorm:"uuid UNIQUE"`
  1493. IssueID int64 `xorm:"INDEX"`
  1494. CommentID int64
  1495. ReleaseID int64 `xorm:"INDEX"`
  1496. Name string
  1497. Created time.Time `xorm:"-"`
  1498. CreatedUnix int64
  1499. }
  1500. // BeforeInsert is invoked from XORM before inserting an object of this type.
  1501. func (a *Attachment) BeforeInsert() {
  1502. a.CreatedUnix = time.Now().Unix()
  1503. }
  1504. // AfterSet is invoked from XORM after setting the value of a field of
  1505. // this object.
  1506. func (a *Attachment) AfterSet(colName string, _ xorm.Cell) {
  1507. switch colName {
  1508. case "created_unix":
  1509. a.Created = time.Unix(a.CreatedUnix, 0).Local()
  1510. }
  1511. }
  1512. // AttachmentLocalPath returns where attachment is stored in local file
  1513. // system based on given UUID.
  1514. func AttachmentLocalPath(uuid string) string {
  1515. return path.Join(setting.AttachmentPath, uuid[0:1], uuid[1:2], uuid)
  1516. }
  1517. // LocalPath returns where attachment is stored in local file system.
  1518. func (a *Attachment) LocalPath() string {
  1519. return AttachmentLocalPath(a.UUID)
  1520. }
  1521. // NewAttachment creates a new attachment object.
  1522. func NewAttachment(name string, buf []byte, file multipart.File) (_ *Attachment, err error) {
  1523. attach := &Attachment{
  1524. UUID: gouuid.NewV4().String(),
  1525. Name: name,
  1526. }
  1527. localPath := attach.LocalPath()
  1528. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  1529. return nil, fmt.Errorf("MkdirAll: %v", err)
  1530. }
  1531. fw, err := os.Create(localPath)
  1532. if err != nil {
  1533. return nil, fmt.Errorf("Create: %v", err)
  1534. }
  1535. defer fw.Close()
  1536. if _, err = fw.Write(buf); err != nil {
  1537. return nil, fmt.Errorf("Write: %v", err)
  1538. } else if _, err = io.Copy(fw, file); err != nil {
  1539. return nil, fmt.Errorf("Copy: %v", err)
  1540. }
  1541. if _, err := x.Insert(attach); err != nil {
  1542. return nil, err
  1543. }
  1544. return attach, nil
  1545. }
  1546. func getAttachmentByUUID(e Engine, uuid string) (*Attachment, error) {
  1547. attach := &Attachment{UUID: uuid}
  1548. has, err := x.Get(attach)
  1549. if err != nil {
  1550. return nil, err
  1551. } else if !has {
  1552. return nil, ErrAttachmentNotExist{0, uuid}
  1553. }
  1554. return attach, nil
  1555. }
  1556. func getAttachmentsByUUIDs(e Engine, uuids []string) ([]*Attachment, error) {
  1557. if len(uuids) == 0 {
  1558. return []*Attachment{}, nil
  1559. }
  1560. // Silently drop invalid uuids.
  1561. attachments := make([]*Attachment, 0, len(uuids))
  1562. return attachments, e.In("uuid", uuids).Find(&attachments)
  1563. }
  1564. // GetAttachmentByUUID returns attachment by given UUID.
  1565. func GetAttachmentByUUID(uuid string) (*Attachment, error) {
  1566. return getAttachmentByUUID(x, uuid)
  1567. }
  1568. func getAttachmentsByIssueID(e Engine, issueID int64) ([]*Attachment, error) {
  1569. attachments := make([]*Attachment, 0, 10)
  1570. return attachments, e.Where("issue_id = ? AND comment_id = 0", issueID).Find(&attachments)
  1571. }
  1572. // GetAttachmentsByIssueID returns all attachments of an issue.
  1573. func GetAttachmentsByIssueID(issueID int64) ([]*Attachment, error) {
  1574. return getAttachmentsByIssueID(x, issueID)
  1575. }
  1576. // GetAttachmentsByCommentID returns all attachments if comment by given ID.
  1577. func GetAttachmentsByCommentID(commentID int64) ([]*Attachment, error) {
  1578. attachments := make([]*Attachment, 0, 10)
  1579. return attachments, x.Where("comment_id=?", commentID).Find(&attachments)
  1580. }
  1581. // DeleteAttachment deletes the given attachment and optionally the associated file.
  1582. func DeleteAttachment(a *Attachment, remove bool) error {
  1583. _, err := DeleteAttachments([]*Attachment{a}, remove)
  1584. return err
  1585. }
  1586. // DeleteAttachments deletes the given attachments and optionally the associated files.
  1587. func DeleteAttachments(attachments []*Attachment, remove bool) (int, error) {
  1588. for i, a := range attachments {
  1589. if remove {
  1590. if err := os.Remove(a.LocalPath()); err != nil {
  1591. return i, err
  1592. }
  1593. }
  1594. if _, err := x.Delete(a); err != nil {
  1595. return i, err
  1596. }
  1597. }
  1598. return len(attachments), nil
  1599. }
  1600. // DeleteAttachmentsByIssue deletes all attachments associated with the given issue.
  1601. func DeleteAttachmentsByIssue(issueID int64, remove bool) (int, error) {
  1602. attachments, err := GetAttachmentsByIssueID(issueID)
  1603. if err != nil {
  1604. return 0, err
  1605. }
  1606. return DeleteAttachments(attachments, remove)
  1607. }
  1608. // DeleteAttachmentsByComment deletes all attachments associated with the given comment.
  1609. func DeleteAttachmentsByComment(commentID int64, remove bool) (int, error) {
  1610. attachments, err := GetAttachmentsByCommentID(commentID)
  1611. if err != nil {
  1612. return 0, err
  1613. }
  1614. return DeleteAttachments(attachments, remove)
  1615. }