issue.go 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  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 repo
  5. import (
  6. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. "time"
  12. "github.com/Unknwon/com"
  13. "github.com/Unknwon/paginater"
  14. "github.com/gogits/gogs/models"
  15. "github.com/gogits/gogs/modules/auth"
  16. "github.com/gogits/gogs/modules/base"
  17. "github.com/gogits/gogs/modules/log"
  18. "github.com/gogits/gogs/modules/mailer"
  19. "github.com/gogits/gogs/modules/middleware"
  20. "github.com/gogits/gogs/modules/setting"
  21. )
  22. const (
  23. ISSUES base.TplName = "repo/issue/list"
  24. ISSUE_NEW base.TplName = "repo/issue/new"
  25. ISSUE_VIEW base.TplName = "repo/issue/view"
  26. LABELS base.TplName = "repo/issue/labels"
  27. MILESTONE base.TplName = "repo/issue/milestones"
  28. MILESTONE_NEW base.TplName = "repo/issue/milestone_new"
  29. MILESTONE_EDIT base.TplName = "repo/issue/milestone_edit"
  30. )
  31. var (
  32. ErrFileTypeForbidden = errors.New("File type is not allowed")
  33. ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded")
  34. )
  35. func MustEnableIssues(ctx *middleware.Context) {
  36. if !ctx.Repo.Repository.EnableIssues {
  37. ctx.Handle(404, "MustEnableIssues", nil)
  38. }
  39. }
  40. func MustEnablePulls(ctx *middleware.Context) {
  41. if !ctx.Repo.Repository.EnablePulls {
  42. ctx.Handle(404, "MustEnablePulls", nil)
  43. }
  44. ctx.Data["HasForkedRepo"] = ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)
  45. }
  46. func RetrieveLabels(ctx *middleware.Context) {
  47. labels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID)
  48. if err != nil {
  49. ctx.Handle(500, "RetrieveLabels.GetLabels: %v", err)
  50. return
  51. }
  52. for _, l := range labels {
  53. l.CalOpenIssues()
  54. }
  55. ctx.Data["Labels"] = labels
  56. ctx.Data["NumLabels"] = len(labels)
  57. }
  58. func Issues(ctx *middleware.Context) {
  59. isPullList := ctx.Params(":type") == "pulls"
  60. if isPullList {
  61. MustEnablePulls(ctx)
  62. if ctx.Written() {
  63. return
  64. }
  65. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  66. ctx.Data["PageIsPullList"] = true
  67. } else {
  68. MustEnableIssues(ctx)
  69. if ctx.Written() {
  70. return
  71. }
  72. ctx.Data["Title"] = ctx.Tr("repo.issues")
  73. ctx.Data["PageIsIssueList"] = true
  74. }
  75. viewType := ctx.Query("type")
  76. sortType := ctx.Query("sort")
  77. types := []string{"assigned", "created_by", "mentioned"}
  78. if !com.IsSliceContainsStr(types, viewType) {
  79. viewType = "all"
  80. }
  81. // Must sign in to see issues about you.
  82. if viewType != "all" && !ctx.IsSigned {
  83. ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  84. ctx.Redirect(setting.AppSubUrl + "/user/login")
  85. return
  86. }
  87. var (
  88. assigneeID = ctx.QueryInt64("assignee")
  89. posterID int64
  90. )
  91. filterMode := models.FM_ALL
  92. switch viewType {
  93. case "assigned":
  94. filterMode = models.FM_ASSIGN
  95. assigneeID = ctx.User.Id
  96. case "created_by":
  97. filterMode = models.FM_CREATE
  98. posterID = ctx.User.Id
  99. case "mentioned":
  100. filterMode = models.FM_MENTION
  101. }
  102. var uid int64 = -1
  103. if ctx.IsSigned {
  104. uid = ctx.User.Id
  105. }
  106. repo := ctx.Repo.Repository
  107. selectLabels := ctx.Query("labels")
  108. milestoneID := ctx.QueryInt64("milestone")
  109. isShowClosed := ctx.Query("state") == "closed"
  110. issueStats := models.GetIssueStats(&models.IssueStatsOptions{
  111. RepoID: repo.ID,
  112. UserID: uid,
  113. LabelID: com.StrTo(selectLabels).MustInt64(),
  114. MilestoneID: milestoneID,
  115. AssigneeID: assigneeID,
  116. FilterMode: filterMode,
  117. IsPull: isPullList,
  118. })
  119. page := ctx.QueryInt("page")
  120. if page <= 1 {
  121. page = 1
  122. }
  123. var total int
  124. if !isShowClosed {
  125. total = int(issueStats.OpenCount)
  126. } else {
  127. total = int(issueStats.ClosedCount)
  128. }
  129. pager := paginater.New(total, setting.IssuePagingNum, page, 5)
  130. ctx.Data["Page"] = pager
  131. // Get issues.
  132. issues, err := models.Issues(&models.IssuesOptions{
  133. UserID: uid,
  134. AssigneeID: assigneeID,
  135. RepoID: repo.ID,
  136. PosterID: posterID,
  137. MilestoneID: milestoneID,
  138. Page: pager.Current(),
  139. IsClosed: isShowClosed,
  140. IsMention: filterMode == models.FM_MENTION,
  141. IsPull: isPullList,
  142. Labels: selectLabels,
  143. SortType: sortType,
  144. })
  145. if err != nil {
  146. ctx.Handle(500, "Issues: %v", err)
  147. return
  148. }
  149. // Get issue-user relations.
  150. pairs, err := models.GetIssueUsers(repo.ID, posterID, isShowClosed)
  151. if err != nil {
  152. ctx.Handle(500, "GetIssueUsers: %v", err)
  153. return
  154. }
  155. // Get posters.
  156. for i := range issues {
  157. if err = issues[i].GetPoster(); err != nil {
  158. ctx.Handle(500, "GetPoster", fmt.Errorf("[#%d]%v", issues[i].ID, err))
  159. return
  160. }
  161. if err = issues[i].GetLabels(); err != nil {
  162. ctx.Handle(500, "GetLabels", fmt.Errorf("[#%d]%v", issues[i].ID, err))
  163. return
  164. }
  165. if !ctx.IsSigned {
  166. issues[i].IsRead = true
  167. continue
  168. }
  169. // Check read status.
  170. idx := models.PairsContains(pairs, issues[i].ID, ctx.User.Id)
  171. if idx > -1 {
  172. issues[i].IsRead = pairs[idx].IsRead
  173. } else {
  174. issues[i].IsRead = true
  175. }
  176. }
  177. ctx.Data["Issues"] = issues
  178. // Get milestones.
  179. ctx.Data["Milestones"], err = models.GetAllRepoMilestones(repo.ID)
  180. if err != nil {
  181. ctx.Handle(500, "GetAllRepoMilestones: %v", err)
  182. return
  183. }
  184. // Get assignees.
  185. ctx.Data["Assignees"], err = repo.GetAssignees()
  186. if err != nil {
  187. ctx.Handle(500, "GetAssignees: %v", err)
  188. return
  189. }
  190. ctx.Data["IssueStats"] = issueStats
  191. ctx.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64()
  192. ctx.Data["ViewType"] = viewType
  193. ctx.Data["SortType"] = sortType
  194. ctx.Data["MilestoneID"] = milestoneID
  195. ctx.Data["AssigneeID"] = assigneeID
  196. ctx.Data["IsShowClosed"] = isShowClosed
  197. if isShowClosed {
  198. ctx.Data["State"] = "closed"
  199. } else {
  200. ctx.Data["State"] = "open"
  201. }
  202. ctx.HTML(200, ISSUES)
  203. }
  204. func renderAttachmentSettings(ctx *middleware.Context) {
  205. ctx.Data["RequireDropzone"] = true
  206. ctx.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled
  207. ctx.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes
  208. ctx.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize
  209. ctx.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles
  210. }
  211. func RetrieveRepoMilestonesAndAssignees(ctx *middleware.Context, repo *models.Repository) {
  212. var err error
  213. ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false)
  214. if err != nil {
  215. ctx.Handle(500, "GetMilestones: %v", err)
  216. return
  217. }
  218. ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true)
  219. if err != nil {
  220. ctx.Handle(500, "GetMilestones: %v", err)
  221. return
  222. }
  223. ctx.Data["Assignees"], err = repo.GetAssignees()
  224. if err != nil {
  225. ctx.Handle(500, "GetAssignees: %v", err)
  226. return
  227. }
  228. }
  229. func RetrieveRepoMetas(ctx *middleware.Context, repo *models.Repository) []*models.Label {
  230. if !ctx.Repo.IsAdmin() {
  231. return nil
  232. }
  233. labels, err := models.GetLabelsByRepoID(repo.ID)
  234. if err != nil {
  235. ctx.Handle(500, "GetLabelsByRepoID: %v", err)
  236. return nil
  237. }
  238. ctx.Data["Labels"] = labels
  239. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  240. if ctx.Written() {
  241. return nil
  242. }
  243. return labels
  244. }
  245. func NewIssue(ctx *middleware.Context) {
  246. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  247. ctx.Data["PageIsIssueList"] = true
  248. renderAttachmentSettings(ctx)
  249. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  250. if ctx.Written() {
  251. return
  252. }
  253. ctx.HTML(200, ISSUE_NEW)
  254. }
  255. func ValidateRepoMetas(ctx *middleware.Context, form auth.CreateIssueForm) ([]int64, int64, int64) {
  256. var (
  257. repo = ctx.Repo.Repository
  258. err error
  259. )
  260. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  261. if ctx.Written() {
  262. return nil, 0, 0
  263. }
  264. if !ctx.Repo.IsAdmin() {
  265. return nil, 0, 0
  266. }
  267. // Check labels.
  268. labelIDs := base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  269. labelIDMark := base.Int64sToMap(labelIDs)
  270. hasSelected := false
  271. for i := range labels {
  272. if labelIDMark[labels[i].ID] {
  273. labels[i].IsChecked = true
  274. hasSelected = true
  275. }
  276. }
  277. ctx.Data["HasSelectedLabel"] = hasSelected
  278. ctx.Data["label_ids"] = form.LabelIDs
  279. ctx.Data["Labels"] = labels
  280. // Check milestone.
  281. milestoneID := form.MilestoneID
  282. if milestoneID > 0 {
  283. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  284. if err != nil {
  285. ctx.Handle(500, "GetMilestoneByID: %v", err)
  286. return nil, 0, 0
  287. }
  288. ctx.Data["milestone_id"] = milestoneID
  289. }
  290. // Check assignee.
  291. assigneeID := form.AssigneeID
  292. if assigneeID > 0 {
  293. ctx.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID)
  294. if err != nil {
  295. ctx.Handle(500, "GetAssigneeByID: %v", err)
  296. return nil, 0, 0
  297. }
  298. ctx.Data["assignee_id"] = assigneeID
  299. }
  300. return labelIDs, milestoneID, assigneeID
  301. }
  302. func notifyWatchersAndMentions(ctx *middleware.Context, issue *models.Issue) {
  303. // Update mentions
  304. mentions := base.MentionPattern.FindAllString(issue.Content, -1)
  305. if len(mentions) > 0 {
  306. for i := range mentions {
  307. mentions[i] = strings.TrimSpace(mentions[i])[1:]
  308. }
  309. if err := models.UpdateMentions(mentions, issue.ID); err != nil {
  310. ctx.Handle(500, "UpdateMentions", err)
  311. return
  312. }
  313. }
  314. repo := ctx.Repo.Repository
  315. // Mail watchers and mentions.
  316. if setting.Service.EnableNotifyMail {
  317. tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, repo, issue)
  318. if err != nil {
  319. ctx.Handle(500, "SendIssueNotifyMail", err)
  320. return
  321. }
  322. tos = append(tos, ctx.User.LowerName)
  323. newTos := make([]string, 0, len(mentions))
  324. for _, m := range mentions {
  325. if com.IsSliceContainsStr(tos, m) {
  326. continue
  327. }
  328. newTos = append(newTos, m)
  329. }
  330. if err = mailer.SendIssueMentionMail(ctx.Render, ctx.User, ctx.Repo.Owner,
  331. repo, issue, models.GetUserEmailsByNames(newTos)); err != nil {
  332. ctx.Handle(500, "SendIssueMentionMail", err)
  333. return
  334. }
  335. }
  336. }
  337. func NewIssuePost(ctx *middleware.Context, form auth.CreateIssueForm) {
  338. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  339. ctx.Data["PageIsIssueList"] = true
  340. renderAttachmentSettings(ctx)
  341. var (
  342. repo = ctx.Repo.Repository
  343. attachments []string
  344. )
  345. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form)
  346. if ctx.Written() {
  347. return
  348. }
  349. if setting.AttachmentEnabled {
  350. attachments = form.Attachments
  351. }
  352. if ctx.HasError() {
  353. ctx.HTML(200, ISSUE_NEW)
  354. return
  355. }
  356. issue := &models.Issue{
  357. RepoID: ctx.Repo.Repository.ID,
  358. Index: repo.NextIssueIndex(),
  359. Name: strings.TrimSpace(form.Title),
  360. PosterID: ctx.User.Id,
  361. Poster: ctx.User,
  362. MilestoneID: milestoneID,
  363. AssigneeID: assigneeID,
  364. Content: form.Content,
  365. }
  366. if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil {
  367. ctx.Handle(500, "NewIssue", err)
  368. return
  369. }
  370. notifyWatchersAndMentions(ctx, issue)
  371. if ctx.Written() {
  372. return
  373. }
  374. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  375. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  376. }
  377. func UploadIssueAttachment(ctx *middleware.Context) {
  378. if !setting.AttachmentEnabled {
  379. ctx.Error(404, "attachment is not enabled")
  380. return
  381. }
  382. allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
  383. file, header, err := ctx.Req.FormFile("file")
  384. if err != nil {
  385. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  386. return
  387. }
  388. defer file.Close()
  389. buf := make([]byte, 1024)
  390. n, _ := file.Read(buf)
  391. if n > 0 {
  392. buf = buf[:n]
  393. }
  394. fileType := http.DetectContentType(buf)
  395. allowed := false
  396. for _, t := range allowedTypes {
  397. t := strings.Trim(t, " ")
  398. if t == "*/*" || t == fileType {
  399. allowed = true
  400. break
  401. }
  402. }
  403. if !allowed {
  404. ctx.Error(400, ErrFileTypeForbidden.Error())
  405. return
  406. }
  407. attach, err := models.NewAttachment(header.Filename, buf, file)
  408. if err != nil {
  409. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  410. return
  411. }
  412. log.Trace("New attachment uploaded: %s", attach.UUID)
  413. ctx.JSON(200, map[string]string{
  414. "uuid": attach.UUID,
  415. })
  416. }
  417. func ViewIssue(ctx *middleware.Context) {
  418. ctx.Data["RequireDropzone"] = true
  419. renderAttachmentSettings(ctx)
  420. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  421. if err != nil {
  422. if models.IsErrIssueNotExist(err) {
  423. ctx.Handle(404, "GetIssueByIndex", err)
  424. } else {
  425. ctx.Handle(500, "GetIssueByIndex", err)
  426. }
  427. return
  428. }
  429. ctx.Data["Title"] = issue.Name
  430. // Make sure type and URL matches.
  431. if ctx.Params(":type") == "issues" && issue.IsPull {
  432. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  433. return
  434. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  435. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  436. return
  437. }
  438. if issue.IsPull {
  439. if err = issue.GetPullRequest(); err != nil {
  440. ctx.Handle(500, "GetPullRequest", err)
  441. return
  442. }
  443. ctx.Data["PageIsPullList"] = true
  444. ctx.Data["PageIsPullConversation"] = true
  445. ctx.Data["HasForkedRepo"] = ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)
  446. } else {
  447. MustEnableIssues(ctx)
  448. if ctx.Written() {
  449. return
  450. }
  451. ctx.Data["PageIsIssueList"] = true
  452. }
  453. if err = issue.GetPoster(); err != nil {
  454. ctx.Handle(500, "GetPoster", err)
  455. return
  456. }
  457. issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink,
  458. ctx.Repo.Repository.ComposeMetas()))
  459. repo := ctx.Repo.Repository
  460. // Get more information if it's a pull request.
  461. if issue.IsPull {
  462. if issue.HasMerged {
  463. ctx.Data["DisableStatusChange"] = issue.HasMerged
  464. PrepareMergedViewPullInfo(ctx, issue)
  465. } else {
  466. PrepareViewPullInfo(ctx, issue)
  467. }
  468. if ctx.Written() {
  469. return
  470. }
  471. }
  472. // Metas.
  473. // Check labels.
  474. if err = issue.GetLabels(); err != nil {
  475. ctx.Handle(500, "GetLabels", err)
  476. return
  477. }
  478. labelIDMark := make(map[int64]bool)
  479. for i := range issue.Labels {
  480. labelIDMark[issue.Labels[i].ID] = true
  481. }
  482. labels, err := models.GetLabelsByRepoID(repo.ID)
  483. if err != nil {
  484. ctx.Handle(500, "GetLabelsByRepoID: %v", err)
  485. return
  486. }
  487. hasSelected := false
  488. for i := range labels {
  489. if labelIDMark[labels[i].ID] {
  490. labels[i].IsChecked = true
  491. hasSelected = true
  492. }
  493. }
  494. ctx.Data["HasSelectedLabel"] = hasSelected
  495. ctx.Data["Labels"] = labels
  496. // Check milestone and assignee.
  497. if ctx.Repo.IsAdmin() {
  498. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  499. if ctx.Written() {
  500. return
  501. }
  502. }
  503. if ctx.IsSigned {
  504. // Update issue-user.
  505. if err = issue.ReadBy(ctx.User.Id); err != nil {
  506. ctx.Handle(500, "ReadBy", err)
  507. return
  508. }
  509. }
  510. var (
  511. tag models.CommentTag
  512. ok bool
  513. marked = make(map[int64]models.CommentTag)
  514. comment *models.Comment
  515. )
  516. // Render comments.
  517. for _, comment = range issue.Comments {
  518. if comment.Type == models.COMMENT_TYPE_COMMENT {
  519. comment.RenderedContent = string(base.RenderMarkdown([]byte(comment.Content), ctx.Repo.RepoLink,
  520. ctx.Repo.Repository.ComposeMetas()))
  521. // Check tag.
  522. tag, ok = marked[comment.PosterID]
  523. if ok {
  524. comment.ShowTag = tag
  525. continue
  526. }
  527. if repo.IsOwnedBy(comment.PosterID) ||
  528. (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
  529. comment.ShowTag = models.COMMENT_TAG_OWNER
  530. } else if comment.Poster.IsAdminOfRepo(repo) {
  531. comment.ShowTag = models.COMMENT_TAG_ADMIN
  532. } else if comment.PosterID == issue.PosterID {
  533. comment.ShowTag = models.COMMENT_TAG_POSTER
  534. }
  535. marked[comment.PosterID] = comment.ShowTag
  536. }
  537. }
  538. ctx.Data["Issue"] = issue
  539. ctx.Data["IsIssueOwner"] = ctx.Repo.IsAdmin() || (ctx.IsSigned && issue.IsPoster(ctx.User.Id))
  540. ctx.Data["SignInLink"] = setting.AppSubUrl + "/user/login"
  541. ctx.HTML(200, ISSUE_VIEW)
  542. }
  543. func getActionIssue(ctx *middleware.Context) *models.Issue {
  544. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  545. if err != nil {
  546. if models.IsErrIssueNotExist(err) {
  547. ctx.Error(404, "GetIssueByIndex")
  548. } else {
  549. ctx.Handle(500, "GetIssueByIndex", err)
  550. }
  551. return nil
  552. }
  553. return issue
  554. }
  555. func UpdateIssueTitle(ctx *middleware.Context) {
  556. issue := getActionIssue(ctx)
  557. if ctx.Written() {
  558. return
  559. }
  560. if !ctx.IsSigned || (ctx.User.Id != issue.PosterID && !ctx.Repo.IsAdmin()) {
  561. ctx.Error(403)
  562. return
  563. }
  564. issue.Name = ctx.QueryTrim("title")
  565. if len(issue.Name) == 0 {
  566. ctx.Error(204)
  567. return
  568. }
  569. if err := models.UpdateIssue(issue); err != nil {
  570. ctx.Handle(500, "UpdateIssue", err)
  571. return
  572. }
  573. ctx.JSON(200, map[string]interface{}{
  574. "title": issue.Name,
  575. })
  576. }
  577. func UpdateIssueContent(ctx *middleware.Context) {
  578. issue := getActionIssue(ctx)
  579. if ctx.Written() {
  580. return
  581. }
  582. if !ctx.IsSigned || (ctx.User.Id != issue.PosterID && !ctx.Repo.IsAdmin()) {
  583. ctx.Error(403)
  584. return
  585. }
  586. issue.Content = ctx.Query("content")
  587. if err := models.UpdateIssue(issue); err != nil {
  588. ctx.Handle(500, "UpdateIssue", err)
  589. return
  590. }
  591. ctx.JSON(200, map[string]interface{}{
  592. "content": string(base.RenderMarkdown([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  593. })
  594. }
  595. func UpdateIssueLabel(ctx *middleware.Context) {
  596. issue := getActionIssue(ctx)
  597. if ctx.Written() {
  598. return
  599. }
  600. if ctx.Query("action") == "clear" {
  601. if err := issue.ClearLabels(); err != nil {
  602. ctx.Handle(500, "ClearLabels", err)
  603. return
  604. }
  605. } else {
  606. isAttach := ctx.Query("action") == "attach"
  607. label, err := models.GetLabelByID(ctx.QueryInt64("id"))
  608. if err != nil {
  609. if models.IsErrLabelNotExist(err) {
  610. ctx.Error(404, "GetLabelByID")
  611. } else {
  612. ctx.Handle(500, "GetLabelByID", err)
  613. }
  614. return
  615. }
  616. if isAttach && !issue.HasLabel(label.ID) {
  617. if err = issue.AddLabel(label); err != nil {
  618. ctx.Handle(500, "AddLabel", err)
  619. return
  620. }
  621. } else if !isAttach && issue.HasLabel(label.ID) {
  622. if err = issue.RemoveLabel(label); err != nil {
  623. ctx.Handle(500, "RemoveLabel", err)
  624. return
  625. }
  626. }
  627. }
  628. ctx.JSON(200, map[string]interface{}{
  629. "ok": true,
  630. })
  631. }
  632. func UpdateIssueMilestone(ctx *middleware.Context) {
  633. issue := getActionIssue(ctx)
  634. if ctx.Written() {
  635. return
  636. }
  637. oldMid := issue.MilestoneID
  638. mid := ctx.QueryInt64("id")
  639. if oldMid == mid {
  640. ctx.JSON(200, map[string]interface{}{
  641. "ok": true,
  642. })
  643. return
  644. }
  645. // Not check for invalid milestone id and give responsibility to owners.
  646. issue.MilestoneID = mid
  647. if err := models.ChangeMilestoneAssign(oldMid, issue); err != nil {
  648. ctx.Handle(500, "ChangeMilestoneAssign", err)
  649. return
  650. }
  651. ctx.JSON(200, map[string]interface{}{
  652. "ok": true,
  653. })
  654. }
  655. func UpdateIssueAssignee(ctx *middleware.Context) {
  656. issue := getActionIssue(ctx)
  657. if ctx.Written() {
  658. return
  659. }
  660. aid := ctx.QueryInt64("id")
  661. if issue.AssigneeID == aid {
  662. ctx.JSON(200, map[string]interface{}{
  663. "ok": true,
  664. })
  665. return
  666. }
  667. // Not check for invalid assignee id and give responsibility to owners.
  668. issue.AssigneeID = aid
  669. if err := models.UpdateIssueUserByAssignee(issue); err != nil {
  670. ctx.Handle(500, "UpdateIssueUserByAssignee: %v", err)
  671. return
  672. }
  673. ctx.JSON(200, map[string]interface{}{
  674. "ok": true,
  675. })
  676. }
  677. func NewComment(ctx *middleware.Context, form auth.CreateCommentForm) {
  678. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  679. if err != nil {
  680. if models.IsErrIssueNotExist(err) {
  681. ctx.Handle(404, "GetIssueByIndex", err)
  682. } else {
  683. ctx.Handle(500, "GetIssueByIndex", err)
  684. }
  685. return
  686. }
  687. if issue.IsPull {
  688. if err = issue.GetPullRequest(); err != nil {
  689. ctx.Handle(500, "GetPullRequest", err)
  690. return
  691. }
  692. }
  693. var attachments []string
  694. if setting.AttachmentEnabled {
  695. attachments = form.Attachments
  696. }
  697. if ctx.HasError() {
  698. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  699. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  700. return
  701. }
  702. var comment *models.Comment
  703. defer func() {
  704. // Check if issue admin/poster changes the status of issue.
  705. if (ctx.Repo.IsAdmin() || (ctx.IsSigned && issue.IsPoster(ctx.User.Id))) &&
  706. (form.Status == "reopen" || form.Status == "close") &&
  707. !(issue.IsPull && issue.HasMerged) {
  708. // Duplication and conflict check should apply to reopen pull request.
  709. var pr *models.PullRequest
  710. if form.Status == "reopen" && issue.IsPull {
  711. pull := issue.PullRequest
  712. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  713. if err != nil {
  714. if !models.IsErrPullRequestNotExist(err) {
  715. ctx.Handle(500, "GetUnmergedPullRequest", err)
  716. return
  717. }
  718. }
  719. // Regenerate patch and test conflict.
  720. if pr == nil {
  721. if err = issue.UpdatePatch(); err != nil {
  722. ctx.Handle(500, "UpdatePatch", err)
  723. return
  724. }
  725. issue.AddToTaskQueue()
  726. }
  727. }
  728. if pr != nil {
  729. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  730. } else {
  731. issue.Repo = ctx.Repo.Repository
  732. if err = issue.ChangeStatus(ctx.User, form.Status == "close"); err != nil {
  733. log.Error(4, "ChangeStatus: %v", err)
  734. } else {
  735. log.Trace("Issue[%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  736. }
  737. }
  738. }
  739. // Redirect to comment hashtag if there is any actual content.
  740. typeName := "issues"
  741. if issue.IsPull {
  742. typeName = "pulls"
  743. }
  744. if comment != nil {
  745. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  746. } else {
  747. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  748. }
  749. }()
  750. // Fix #321: Allow empty comments, as long as we have attachments.
  751. if len(form.Content) == 0 && len(attachments) == 0 {
  752. return
  753. }
  754. comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  755. if err != nil {
  756. ctx.Handle(500, "CreateIssueComment", err)
  757. return
  758. }
  759. notifyWatchersAndMentions(ctx, &models.Issue{
  760. ID: issue.ID,
  761. Index: issue.Index,
  762. Name: issue.Name,
  763. Content: form.Content,
  764. })
  765. if ctx.Written() {
  766. return
  767. }
  768. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  769. }
  770. func UpdateCommentContent(ctx *middleware.Context) {
  771. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  772. if err != nil {
  773. if models.IsErrCommentNotExist(err) {
  774. ctx.Error(404, "GetCommentByID")
  775. } else {
  776. ctx.Handle(500, "GetCommentByID", err)
  777. }
  778. return
  779. }
  780. if !ctx.IsSigned || (ctx.User.Id != comment.PosterID && !ctx.Repo.IsAdmin()) {
  781. ctx.Error(403)
  782. return
  783. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  784. ctx.Error(204)
  785. return
  786. }
  787. comment.Content = ctx.Query("content")
  788. if len(comment.Content) == 0 {
  789. ctx.JSON(200, map[string]interface{}{
  790. "content": "",
  791. })
  792. return
  793. }
  794. if err := models.UpdateComment(comment); err != nil {
  795. ctx.Handle(500, "UpdateComment", err)
  796. return
  797. }
  798. ctx.JSON(200, map[string]interface{}{
  799. "content": string(base.RenderMarkdown([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  800. })
  801. }
  802. func Labels(ctx *middleware.Context) {
  803. ctx.Data["Title"] = ctx.Tr("repo.labels")
  804. ctx.Data["PageIsIssueList"] = true
  805. ctx.Data["PageIsLabels"] = true
  806. ctx.Data["RequireMinicolors"] = true
  807. ctx.HTML(200, LABELS)
  808. }
  809. func NewLabel(ctx *middleware.Context, form auth.CreateLabelForm) {
  810. ctx.Data["Title"] = ctx.Tr("repo.labels")
  811. ctx.Data["PageIsLabels"] = true
  812. if ctx.HasError() {
  813. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  814. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  815. return
  816. }
  817. l := &models.Label{
  818. RepoID: ctx.Repo.Repository.ID,
  819. Name: form.Title,
  820. Color: form.Color,
  821. }
  822. if err := models.NewLabel(l); err != nil {
  823. ctx.Handle(500, "NewLabel", err)
  824. return
  825. }
  826. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  827. }
  828. func UpdateLabel(ctx *middleware.Context, form auth.CreateLabelForm) {
  829. l, err := models.GetLabelByID(form.ID)
  830. if err != nil {
  831. switch {
  832. case models.IsErrLabelNotExist(err):
  833. ctx.Error(404)
  834. default:
  835. ctx.Handle(500, "UpdateLabel", err)
  836. }
  837. return
  838. }
  839. fmt.Println(form.Title, form.Color)
  840. l.Name = form.Title
  841. l.Color = form.Color
  842. if err := models.UpdateLabel(l); err != nil {
  843. ctx.Handle(500, "UpdateLabel", err)
  844. return
  845. }
  846. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  847. }
  848. func DeleteLabel(ctx *middleware.Context) {
  849. if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  850. ctx.Flash.Error("DeleteLabel: " + err.Error())
  851. } else {
  852. ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success"))
  853. }
  854. ctx.JSON(200, map[string]interface{}{
  855. "redirect": ctx.Repo.RepoLink + "/labels",
  856. })
  857. return
  858. }
  859. func Milestones(ctx *middleware.Context) {
  860. ctx.Data["Title"] = ctx.Tr("repo.milestones")
  861. ctx.Data["PageIsIssueList"] = true
  862. ctx.Data["PageIsMilestones"] = true
  863. isShowClosed := ctx.Query("state") == "closed"
  864. openCount, closedCount := models.MilestoneStats(ctx.Repo.Repository.ID)
  865. ctx.Data["OpenCount"] = openCount
  866. ctx.Data["ClosedCount"] = closedCount
  867. page := ctx.QueryInt("page")
  868. if page <= 1 {
  869. page = 1
  870. }
  871. var total int
  872. if !isShowClosed {
  873. total = int(openCount)
  874. } else {
  875. total = int(closedCount)
  876. }
  877. ctx.Data["Page"] = paginater.New(total, setting.IssuePagingNum, page, 5)
  878. miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed)
  879. if err != nil {
  880. ctx.Handle(500, "GetMilestones", err)
  881. return
  882. }
  883. for _, m := range miles {
  884. m.RenderedContent = string(base.RenderMarkdown([]byte(m.Content), ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()))
  885. m.CalOpenIssues()
  886. }
  887. ctx.Data["Milestones"] = miles
  888. if isShowClosed {
  889. ctx.Data["State"] = "closed"
  890. } else {
  891. ctx.Data["State"] = "open"
  892. }
  893. ctx.Data["IsShowClosed"] = isShowClosed
  894. ctx.HTML(200, MILESTONE)
  895. }
  896. func NewMilestone(ctx *middleware.Context) {
  897. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  898. ctx.Data["PageIsIssueList"] = true
  899. ctx.Data["PageIsMilestones"] = true
  900. ctx.Data["RequireDatetimepicker"] = true
  901. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  902. ctx.HTML(200, MILESTONE_NEW)
  903. }
  904. func NewMilestonePost(ctx *middleware.Context, form auth.CreateMilestoneForm) {
  905. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  906. ctx.Data["PageIsIssueList"] = true
  907. ctx.Data["PageIsMilestones"] = true
  908. ctx.Data["RequireDatetimepicker"] = true
  909. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  910. if ctx.HasError() {
  911. ctx.HTML(200, MILESTONE_NEW)
  912. return
  913. }
  914. if len(form.Deadline) == 0 {
  915. form.Deadline = "9999-12-31"
  916. }
  917. deadline, err := time.Parse("2006-01-02", form.Deadline)
  918. if err != nil {
  919. ctx.Data["Err_Deadline"] = true
  920. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form)
  921. return
  922. }
  923. if err = models.NewMilestone(&models.Milestone{
  924. RepoID: ctx.Repo.Repository.ID,
  925. Name: form.Title,
  926. Content: form.Content,
  927. Deadline: deadline,
  928. }); err != nil {
  929. ctx.Handle(500, "NewMilestone", err)
  930. return
  931. }
  932. ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
  933. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  934. }
  935. func EditMilestone(ctx *middleware.Context) {
  936. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  937. ctx.Data["PageIsMilestones"] = true
  938. ctx.Data["PageIsEditMilestone"] = true
  939. ctx.Data["RequireDatetimepicker"] = true
  940. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  941. m, err := models.GetMilestoneByID(ctx.ParamsInt64(":id"))
  942. if err != nil {
  943. if models.IsErrMilestoneNotExist(err) {
  944. ctx.Handle(404, "GetMilestoneByID", nil)
  945. } else {
  946. ctx.Handle(500, "GetMilestoneByID", err)
  947. }
  948. return
  949. }
  950. ctx.Data["title"] = m.Name
  951. ctx.Data["content"] = m.Content
  952. if len(m.DeadlineString) > 0 {
  953. ctx.Data["deadline"] = m.DeadlineString
  954. }
  955. ctx.HTML(200, MILESTONE_NEW)
  956. }
  957. func EditMilestonePost(ctx *middleware.Context, form auth.CreateMilestoneForm) {
  958. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  959. ctx.Data["PageIsMilestones"] = true
  960. ctx.Data["PageIsEditMilestone"] = true
  961. ctx.Data["RequireDatetimepicker"] = true
  962. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  963. if ctx.HasError() {
  964. ctx.HTML(200, MILESTONE_NEW)
  965. return
  966. }
  967. if len(form.Deadline) == 0 {
  968. form.Deadline = "9999-12-31"
  969. }
  970. deadline, err := time.Parse("2006-01-02", form.Deadline)
  971. if err != nil {
  972. ctx.Data["Err_Deadline"] = true
  973. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form)
  974. return
  975. }
  976. m, err := models.GetMilestoneByID(ctx.ParamsInt64(":id"))
  977. if err != nil {
  978. if models.IsErrMilestoneNotExist(err) {
  979. ctx.Handle(404, "GetMilestoneByID", nil)
  980. } else {
  981. ctx.Handle(500, "GetMilestoneByID", err)
  982. }
  983. return
  984. }
  985. m.Name = form.Title
  986. m.Content = form.Content
  987. m.Deadline = deadline
  988. if err = models.UpdateMilestone(m); err != nil {
  989. ctx.Handle(500, "UpdateMilestone", err)
  990. return
  991. }
  992. ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
  993. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  994. }
  995. func ChangeMilestonStatus(ctx *middleware.Context) {
  996. m, err := models.GetMilestoneByID(ctx.ParamsInt64(":id"))
  997. if err != nil {
  998. if models.IsErrMilestoneNotExist(err) {
  999. ctx.Handle(404, "GetMilestoneByID", err)
  1000. } else {
  1001. ctx.Handle(500, "GetMilestoneByID", err)
  1002. }
  1003. return
  1004. }
  1005. switch ctx.Params(":action") {
  1006. case "open":
  1007. if m.IsClosed {
  1008. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1009. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1010. return
  1011. }
  1012. }
  1013. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
  1014. case "close":
  1015. if !m.IsClosed {
  1016. m.ClosedDate = time.Now()
  1017. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1018. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1019. return
  1020. }
  1021. }
  1022. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
  1023. default:
  1024. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1025. }
  1026. }
  1027. func DeleteMilestone(ctx *middleware.Context) {
  1028. if err := models.DeleteMilestoneByID(ctx.QueryInt64("id")); err != nil {
  1029. ctx.Flash.Error("DeleteMilestoneByID: " + err.Error())
  1030. } else {
  1031. ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
  1032. }
  1033. ctx.JSON(200, map[string]interface{}{
  1034. "redirect": ctx.Repo.RepoLink + "/milestones",
  1035. })
  1036. }