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

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