issue.go 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226
  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. file, header, err := ctx.Req.FormFile("file")
  389. if err != nil {
  390. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  391. return
  392. }
  393. defer file.Close()
  394. buf := make([]byte, 1024)
  395. n, _ := file.Read(buf)
  396. if n > 0 {
  397. buf = buf[:n]
  398. }
  399. fileType := http.DetectContentType(buf)
  400. allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
  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["RequireDropzone"] = true
  426. renderAttachmentSettings(ctx)
  427. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  428. if err != nil {
  429. if models.IsErrIssueNotExist(err) {
  430. ctx.Handle(404, "GetIssueByIndex", err)
  431. } else {
  432. ctx.Handle(500, "GetIssueByIndex", err)
  433. }
  434. return
  435. }
  436. ctx.Data["Title"] = issue.Title
  437. // Make sure type and URL matches.
  438. if ctx.Params(":type") == "issues" && issue.IsPull {
  439. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  440. return
  441. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  442. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  443. return
  444. }
  445. if issue.IsPull {
  446. MustAllowPulls(ctx)
  447. if ctx.Written() {
  448. return
  449. }
  450. ctx.Data["PageIsPullList"] = true
  451. ctx.Data["PageIsPullConversation"] = true
  452. } else {
  453. MustEnableIssues(ctx)
  454. if ctx.Written() {
  455. return
  456. }
  457. ctx.Data["PageIsIssueList"] = true
  458. }
  459. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  460. ctx.Repo.Repository.ComposeMetas()))
  461. repo := ctx.Repo.Repository
  462. // Get more information if it's a pull request.
  463. if issue.IsPull {
  464. if issue.PullRequest.HasMerged {
  465. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  466. PrepareMergedViewPullInfo(ctx, issue)
  467. } else {
  468. PrepareViewPullInfo(ctx, issue)
  469. }
  470. if ctx.Written() {
  471. return
  472. }
  473. }
  474. // Metas.
  475. // Check labels.
  476. labelIDMark := make(map[int64]bool)
  477. for i := range issue.Labels {
  478. labelIDMark[issue.Labels[i].ID] = true
  479. }
  480. labels, err := models.GetLabelsByRepoID(repo.ID)
  481. if err != nil {
  482. ctx.Handle(500, "GetLabelsByRepoID", err)
  483. return
  484. }
  485. hasSelected := false
  486. for i := range labels {
  487. if labelIDMark[labels[i].ID] {
  488. labels[i].IsChecked = true
  489. hasSelected = true
  490. }
  491. }
  492. ctx.Data["HasSelectedLabel"] = hasSelected
  493. ctx.Data["Labels"] = labels
  494. // Check milestone and assignee.
  495. if ctx.Repo.IsWriter() {
  496. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  497. if ctx.Written() {
  498. return
  499. }
  500. }
  501. if ctx.IsSigned {
  502. // Update issue-user.
  503. if err = issue.ReadBy(ctx.User.ID); err != nil {
  504. ctx.Handle(500, "ReadBy", err)
  505. return
  506. }
  507. }
  508. var (
  509. tag models.CommentTag
  510. ok bool
  511. marked = make(map[int64]models.CommentTag)
  512. comment *models.Comment
  513. participants = make([]*models.User, 1, 10)
  514. )
  515. // Render comments and and fetch participants.
  516. participants[0] = issue.Poster
  517. for _, comment = range issue.Comments {
  518. if comment.Type == models.COMMENT_TYPE_COMMENT {
  519. comment.RenderedContent = string(markdown.Render([]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.IsWriterOfRepo(repo) {
  531. comment.ShowTag = models.COMMENT_TAG_WRITER
  532. } else if comment.PosterID == issue.PosterID {
  533. comment.ShowTag = models.COMMENT_TAG_POSTER
  534. }
  535. marked[comment.PosterID] = comment.ShowTag
  536. isAdded := false
  537. for j := range participants {
  538. if comment.Poster == participants[j] {
  539. isAdded = true
  540. break
  541. }
  542. }
  543. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  544. participants = append(participants, comment.Poster)
  545. }
  546. }
  547. }
  548. ctx.Data["Participants"] = participants
  549. ctx.Data["NumParticipants"] = len(participants)
  550. ctx.Data["Issue"] = issue
  551. ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))
  552. ctx.Data["SignInLink"] = setting.AppSubUrl + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  553. ctx.HTML(200, ISSUE_VIEW)
  554. }
  555. func getActionIssue(ctx *context.Context) *models.Issue {
  556. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  557. if err != nil {
  558. if models.IsErrIssueNotExist(err) {
  559. ctx.Error(404, "GetIssueByIndex")
  560. } else {
  561. ctx.Handle(500, "GetIssueByIndex", err)
  562. }
  563. return nil
  564. }
  565. return issue
  566. }
  567. func UpdateIssueTitle(ctx *context.Context) {
  568. issue := getActionIssue(ctx)
  569. if ctx.Written() {
  570. return
  571. }
  572. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) {
  573. ctx.Error(403)
  574. return
  575. }
  576. title := ctx.QueryTrim("title")
  577. if len(title) == 0 {
  578. ctx.Error(204)
  579. return
  580. }
  581. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  582. ctx.Handle(500, "ChangeTitle", err)
  583. return
  584. }
  585. ctx.JSON(200, map[string]interface{}{
  586. "title": issue.Title,
  587. })
  588. }
  589. func UpdateIssueContent(ctx *context.Context) {
  590. issue := getActionIssue(ctx)
  591. if ctx.Written() {
  592. return
  593. }
  594. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) {
  595. ctx.Error(403)
  596. return
  597. }
  598. content := ctx.Query("content")
  599. if err := issue.ChangeContent(ctx.User, content); err != nil {
  600. ctx.Handle(500, "ChangeContent", err)
  601. return
  602. }
  603. ctx.JSON(200, map[string]interface{}{
  604. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  605. })
  606. }
  607. func UpdateIssueLabel(ctx *context.Context) {
  608. issue := getActionIssue(ctx)
  609. if ctx.Written() {
  610. return
  611. }
  612. if ctx.Query("action") == "clear" {
  613. if err := issue.ClearLabels(ctx.User); err != nil {
  614. ctx.Handle(500, "ClearLabels", err)
  615. return
  616. }
  617. } else {
  618. isAttach := ctx.Query("action") == "attach"
  619. label, err := models.GetLabelByID(ctx.QueryInt64("id"))
  620. if err != nil {
  621. if models.IsErrLabelNotExist(err) {
  622. ctx.Error(404, "GetLabelByID")
  623. } else {
  624. ctx.Handle(500, "GetLabelByID", err)
  625. }
  626. return
  627. }
  628. if isAttach && !issue.HasLabel(label.ID) {
  629. if err = issue.AddLabel(ctx.User, label); err != nil {
  630. ctx.Handle(500, "AddLabel", err)
  631. return
  632. }
  633. } else if !isAttach && issue.HasLabel(label.ID) {
  634. if err = issue.RemoveLabel(ctx.User, label); err != nil {
  635. ctx.Handle(500, "RemoveLabel", err)
  636. return
  637. }
  638. }
  639. }
  640. ctx.JSON(200, map[string]interface{}{
  641. "ok": true,
  642. })
  643. }
  644. func UpdateIssueMilestone(ctx *context.Context) {
  645. issue := getActionIssue(ctx)
  646. if ctx.Written() {
  647. return
  648. }
  649. oldMilestoneID := issue.MilestoneID
  650. milestoneID := ctx.QueryInt64("id")
  651. if oldMilestoneID == milestoneID {
  652. ctx.JSON(200, map[string]interface{}{
  653. "ok": true,
  654. })
  655. return
  656. }
  657. // Not check for invalid milestone id and give responsibility to owners.
  658. issue.MilestoneID = milestoneID
  659. if err := models.ChangeMilestoneAssign(issue, oldMilestoneID); err != nil {
  660. ctx.Handle(500, "ChangeMilestoneAssign", err)
  661. return
  662. }
  663. ctx.JSON(200, map[string]interface{}{
  664. "ok": true,
  665. })
  666. }
  667. func UpdateIssueAssignee(ctx *context.Context) {
  668. issue := getActionIssue(ctx)
  669. if ctx.Written() {
  670. return
  671. }
  672. assigneeID := ctx.QueryInt64("id")
  673. if issue.AssigneeID == assigneeID {
  674. ctx.JSON(200, map[string]interface{}{
  675. "ok": true,
  676. })
  677. return
  678. }
  679. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  680. ctx.Handle(500, "ChangeAssignee", err)
  681. return
  682. }
  683. ctx.JSON(200, map[string]interface{}{
  684. "ok": true,
  685. })
  686. }
  687. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  688. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  689. if err != nil {
  690. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  691. return
  692. }
  693. var attachments []string
  694. if setting.AttachmentEnabled {
  695. attachments = form.Files
  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.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  706. (form.Status == "reopen" || form.Status == "close") &&
  707. !(issue.IsPull && issue.PullRequest.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.PullRequest.UpdatePatch(); err != nil {
  722. ctx.Handle(500, "UpdatePatch", err)
  723. return
  724. }
  725. issue.PullRequest.AddToTaskQueue()
  726. }
  727. }
  728. if pr != nil {
  729. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  730. } else {
  731. if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil {
  732. log.Error(4, "ChangeStatus: %v", err)
  733. } else {
  734. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  735. }
  736. }
  737. }
  738. // Redirect to comment hashtag if there is any actual content.
  739. typeName := "issues"
  740. if issue.IsPull {
  741. typeName = "pulls"
  742. }
  743. if comment != nil {
  744. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  745. } else {
  746. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  747. }
  748. }()
  749. // Fix #321: Allow empty comments, as long as we have attachments.
  750. if len(form.Content) == 0 && len(attachments) == 0 {
  751. return
  752. }
  753. comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  754. if err != nil {
  755. ctx.Handle(500, "CreateIssueComment", err)
  756. return
  757. }
  758. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  759. }
  760. func UpdateCommentContent(ctx *context.Context) {
  761. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  762. if err != nil {
  763. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  764. return
  765. }
  766. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  767. ctx.Error(403)
  768. return
  769. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  770. ctx.Error(204)
  771. return
  772. }
  773. comment.Content = ctx.Query("content")
  774. if len(comment.Content) == 0 {
  775. ctx.JSON(200, map[string]interface{}{
  776. "content": "",
  777. })
  778. return
  779. }
  780. if err = models.UpdateComment(comment); err != nil {
  781. ctx.Handle(500, "UpdateComment", err)
  782. return
  783. }
  784. ctx.JSON(200, map[string]interface{}{
  785. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  786. })
  787. }
  788. func DeleteComment(ctx *context.Context) {
  789. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  790. if err != nil {
  791. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  792. return
  793. }
  794. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  795. ctx.Error(403)
  796. return
  797. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  798. ctx.Error(204)
  799. return
  800. }
  801. if err = models.DeleteCommentByID(comment.ID); err != nil {
  802. ctx.Handle(500, "DeleteCommentByID", err)
  803. return
  804. }
  805. ctx.Status(200)
  806. }
  807. func Labels(ctx *context.Context) {
  808. ctx.Data["Title"] = ctx.Tr("repo.labels")
  809. ctx.Data["PageIsIssueList"] = true
  810. ctx.Data["PageIsLabels"] = true
  811. ctx.Data["RequireMinicolors"] = true
  812. ctx.Data["LabelTemplates"] = models.LabelTemplates
  813. ctx.HTML(200, LABELS)
  814. }
  815. func InitializeLabels(ctx *context.Context, form auth.InitializeLabelsForm) {
  816. if ctx.HasError() {
  817. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  818. return
  819. }
  820. list, err := models.GetLabelTemplateFile(form.TemplateName)
  821. if err != nil {
  822. ctx.Flash.Error(ctx.Tr("repo.issues.label_templates.fail_to_load_file", form.TemplateName, err))
  823. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  824. return
  825. }
  826. labels := make([]*models.Label, len(list))
  827. for i := 0; i < len(list); i++ {
  828. labels[i] = &models.Label{
  829. RepoID: ctx.Repo.Repository.ID,
  830. Name: list[i][0],
  831. Color: list[i][1],
  832. }
  833. }
  834. if err := models.NewLabels(labels...); err != nil {
  835. ctx.Handle(500, "NewLabels", err)
  836. return
  837. }
  838. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  839. }
  840. func NewLabel(ctx *context.Context, form auth.CreateLabelForm) {
  841. ctx.Data["Title"] = ctx.Tr("repo.labels")
  842. ctx.Data["PageIsLabels"] = true
  843. if ctx.HasError() {
  844. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  845. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  846. return
  847. }
  848. l := &models.Label{
  849. RepoID: ctx.Repo.Repository.ID,
  850. Name: form.Title,
  851. Color: form.Color,
  852. }
  853. if err := models.NewLabels(l); err != nil {
  854. ctx.Handle(500, "NewLabel", err)
  855. return
  856. }
  857. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  858. }
  859. func UpdateLabel(ctx *context.Context, form auth.CreateLabelForm) {
  860. l, err := models.GetLabelByID(form.ID)
  861. if err != nil {
  862. switch {
  863. case models.IsErrLabelNotExist(err):
  864. ctx.Error(404)
  865. default:
  866. ctx.Handle(500, "UpdateLabel", err)
  867. }
  868. return
  869. }
  870. l.Name = form.Title
  871. l.Color = form.Color
  872. if err := models.UpdateLabel(l); err != nil {
  873. ctx.Handle(500, "UpdateLabel", err)
  874. return
  875. }
  876. ctx.Redirect(ctx.Repo.RepoLink + "/labels")
  877. }
  878. func DeleteLabel(ctx *context.Context) {
  879. if err := models.DeleteLabel(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  880. ctx.Flash.Error("DeleteLabel: " + err.Error())
  881. } else {
  882. ctx.Flash.Success(ctx.Tr("repo.issues.label_deletion_success"))
  883. }
  884. ctx.JSON(200, map[string]interface{}{
  885. "redirect": ctx.Repo.RepoLink + "/labels",
  886. })
  887. return
  888. }
  889. func Milestones(ctx *context.Context) {
  890. ctx.Data["Title"] = ctx.Tr("repo.milestones")
  891. ctx.Data["PageIsIssueList"] = true
  892. ctx.Data["PageIsMilestones"] = true
  893. isShowClosed := ctx.Query("state") == "closed"
  894. openCount, closedCount := models.MilestoneStats(ctx.Repo.Repository.ID)
  895. ctx.Data["OpenCount"] = openCount
  896. ctx.Data["ClosedCount"] = closedCount
  897. page := ctx.QueryInt("page")
  898. if page <= 1 {
  899. page = 1
  900. }
  901. var total int
  902. if !isShowClosed {
  903. total = int(openCount)
  904. } else {
  905. total = int(closedCount)
  906. }
  907. ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  908. miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed)
  909. if err != nil {
  910. ctx.Handle(500, "GetMilestones", err)
  911. return
  912. }
  913. for _, m := range miles {
  914. m.RenderedContent = string(markdown.Render([]byte(m.Content), ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()))
  915. }
  916. ctx.Data["Milestones"] = miles
  917. if isShowClosed {
  918. ctx.Data["State"] = "closed"
  919. } else {
  920. ctx.Data["State"] = "open"
  921. }
  922. ctx.Data["IsShowClosed"] = isShowClosed
  923. ctx.HTML(200, MILESTONE)
  924. }
  925. func NewMilestone(ctx *context.Context) {
  926. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  927. ctx.Data["PageIsIssueList"] = true
  928. ctx.Data["PageIsMilestones"] = true
  929. ctx.Data["RequireDatetimepicker"] = true
  930. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  931. ctx.HTML(200, MILESTONE_NEW)
  932. }
  933. func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  934. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  935. ctx.Data["PageIsIssueList"] = true
  936. ctx.Data["PageIsMilestones"] = true
  937. ctx.Data["RequireDatetimepicker"] = true
  938. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  939. if ctx.HasError() {
  940. ctx.HTML(200, MILESTONE_NEW)
  941. return
  942. }
  943. if len(form.Deadline) == 0 {
  944. form.Deadline = "9999-12-31"
  945. }
  946. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  947. if err != nil {
  948. ctx.Data["Err_Deadline"] = true
  949. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form)
  950. return
  951. }
  952. if err = models.NewMilestone(&models.Milestone{
  953. RepoID: ctx.Repo.Repository.ID,
  954. Name: form.Title,
  955. Content: form.Content,
  956. Deadline: deadline,
  957. }); err != nil {
  958. ctx.Handle(500, "NewMilestone", err)
  959. return
  960. }
  961. ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
  962. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  963. }
  964. func EditMilestone(ctx *context.Context) {
  965. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  966. ctx.Data["PageIsMilestones"] = true
  967. ctx.Data["PageIsEditMilestone"] = true
  968. ctx.Data["RequireDatetimepicker"] = true
  969. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  970. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  971. if err != nil {
  972. if models.IsErrMilestoneNotExist(err) {
  973. ctx.Handle(404, "", nil)
  974. } else {
  975. ctx.Handle(500, "GetMilestoneByRepoID", err)
  976. }
  977. return
  978. }
  979. ctx.Data["title"] = m.Name
  980. ctx.Data["content"] = m.Content
  981. if len(m.DeadlineString) > 0 {
  982. ctx.Data["deadline"] = m.DeadlineString
  983. }
  984. ctx.HTML(200, MILESTONE_NEW)
  985. }
  986. func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  987. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  988. ctx.Data["PageIsMilestones"] = true
  989. ctx.Data["PageIsEditMilestone"] = true
  990. ctx.Data["RequireDatetimepicker"] = true
  991. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  992. if ctx.HasError() {
  993. ctx.HTML(200, MILESTONE_NEW)
  994. return
  995. }
  996. if len(form.Deadline) == 0 {
  997. form.Deadline = "9999-12-31"
  998. }
  999. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1000. if err != nil {
  1001. ctx.Data["Err_Deadline"] = true
  1002. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &form)
  1003. return
  1004. }
  1005. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1006. if err != nil {
  1007. if models.IsErrMilestoneNotExist(err) {
  1008. ctx.Handle(404, "", nil)
  1009. } else {
  1010. ctx.Handle(500, "GetMilestoneByRepoID", err)
  1011. }
  1012. return
  1013. }
  1014. m.Name = form.Title
  1015. m.Content = form.Content
  1016. m.Deadline = deadline
  1017. if err = models.UpdateMilestone(m); err != nil {
  1018. ctx.Handle(500, "UpdateMilestone", err)
  1019. return
  1020. }
  1021. ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
  1022. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1023. }
  1024. func ChangeMilestonStatus(ctx *context.Context) {
  1025. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1026. if err != nil {
  1027. if models.IsErrMilestoneNotExist(err) {
  1028. ctx.Handle(404, "", err)
  1029. } else {
  1030. ctx.Handle(500, "GetMilestoneByRepoID", err)
  1031. }
  1032. return
  1033. }
  1034. switch ctx.Params(":action") {
  1035. case "open":
  1036. if m.IsClosed {
  1037. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1038. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1039. return
  1040. }
  1041. }
  1042. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
  1043. case "close":
  1044. if !m.IsClosed {
  1045. m.ClosedDate = time.Now()
  1046. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1047. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1048. return
  1049. }
  1050. }
  1051. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
  1052. default:
  1053. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1054. }
  1055. }
  1056. func DeleteMilestone(ctx *context.Context) {
  1057. if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  1058. ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1059. } else {
  1060. ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
  1061. }
  1062. ctx.JSON(200, map[string]interface{}{
  1063. "redirect": ctx.Repo.RepoLink + "/milestones",
  1064. })
  1065. }