issue.go 29 KB

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