issue.go 47 KB

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