You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1127 lines
28 KiB

10 years ago
  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/gogits/gogs/models"
  16. "github.com/gogits/gogs/modules/auth"
  17. "github.com/gogits/gogs/modules/base"
  18. "github.com/gogits/gogs/modules/log"
  19. "github.com/gogits/gogs/modules/mailer"
  20. "github.com/gogits/gogs/modules/middleware"
  21. "github.com/gogits/gogs/modules/setting"
  22. )
  23. const (
  24. ISSUES base.TplName = "repo/issue/list"
  25. ISSUE_CREATE base.TplName = "repo/issue/create"
  26. ISSUE_VIEW base.TplName = "repo/issue/view"
  27. MILESTONE base.TplName = "repo/issue/milestone"
  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 Issues(ctx *middleware.Context) {
  36. ctx.Data["Title"] = "Issues"
  37. ctx.Data["IsRepoToolbarIssues"] = true
  38. ctx.Data["IsRepoToolbarIssuesList"] = true
  39. viewType := ctx.Query("type")
  40. types := []string{"assigned", "created_by", "mentioned"}
  41. if !com.IsSliceContainsStr(types, viewType) {
  42. viewType = "all"
  43. }
  44. isShowClosed := ctx.Query("state") == "closed"
  45. if viewType != "all" && !ctx.IsSigned {
  46. ctx.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubUrl+ctx.Req.RequestURI), 0, setting.AppSubUrl)
  47. ctx.Redirect(setting.AppSubUrl + "/user/login")
  48. return
  49. }
  50. var assigneeId, posterId int64
  51. var filterMode int
  52. switch viewType {
  53. case "assigned":
  54. assigneeId = ctx.User.Id
  55. filterMode = models.FM_ASSIGN
  56. case "created_by":
  57. posterId = ctx.User.Id
  58. filterMode = models.FM_CREATE
  59. case "mentioned":
  60. filterMode = models.FM_MENTION
  61. }
  62. var mid int64
  63. midx, _ := com.StrTo(ctx.Query("milestone")).Int64()
  64. if midx > 0 {
  65. mile, err := models.GetMilestoneByIndex(ctx.Repo.Repository.Id, midx)
  66. if err != nil {
  67. ctx.Handle(500, "issue.Issues(GetMilestoneByIndex): %v", err)
  68. return
  69. }
  70. mid = mile.Id
  71. }
  72. selectLabels := ctx.Query("labels")
  73. labels, err := models.GetLabels(ctx.Repo.Repository.Id)
  74. if err != nil {
  75. ctx.Handle(500, "issue.Issues(GetLabels): %v", err)
  76. return
  77. }
  78. for _, l := range labels {
  79. l.CalOpenIssues()
  80. }
  81. ctx.Data["Labels"] = labels
  82. page, _ := com.StrTo(ctx.Query("page")).Int()
  83. // Get issues.
  84. issues, err := models.GetIssues(assigneeId, ctx.Repo.Repository.Id, posterId, mid, page,
  85. isShowClosed, selectLabels, ctx.Query("sortType"))
  86. if err != nil {
  87. ctx.Handle(500, "issue.Issues(GetIssues): %v", err)
  88. return
  89. }
  90. // Get issue-user pairs.
  91. pairs, err := models.GetIssueUserPairs(ctx.Repo.Repository.Id, posterId, isShowClosed)
  92. if err != nil {
  93. ctx.Handle(500, "issue.Issues(GetIssueUserPairs): %v", err)
  94. return
  95. }
  96. // Get posters.
  97. for i := range issues {
  98. if err = issues[i].GetLabels(); err != nil {
  99. ctx.Handle(500, "GetLabels", fmt.Errorf("[#%d]%v", issues[i].Id, err))
  100. return
  101. }
  102. idx := models.PairsContains(pairs, issues[i].Id)
  103. if filterMode == models.FM_MENTION && (idx == -1 || !pairs[idx].IsMentioned) {
  104. continue
  105. }
  106. if idx > -1 {
  107. issues[i].IsRead = pairs[idx].IsRead
  108. } else {
  109. issues[i].IsRead = true
  110. }
  111. if err = issues[i].GetPoster(); err != nil {
  112. ctx.Handle(500, "issue.Issues(GetPoster)", fmt.Errorf("[#%d]%v", issues[i].Id, err))
  113. return
  114. }
  115. }
  116. var uid int64 = -1
  117. if ctx.User != nil {
  118. uid = ctx.User.Id
  119. }
  120. issueStats := models.GetIssueStats(ctx.Repo.Repository.Id, uid, isShowClosed, filterMode)
  121. ctx.Data["IssueStats"] = issueStats
  122. ctx.Data["SelectLabels"], _ = com.StrTo(selectLabels).Int64()
  123. ctx.Data["ViewType"] = viewType
  124. ctx.Data["Issues"] = issues
  125. ctx.Data["IsShowClosed"] = isShowClosed
  126. if isShowClosed {
  127. ctx.Data["State"] = "closed"
  128. ctx.Data["ShowCount"] = issueStats.ClosedCount
  129. } else {
  130. ctx.Data["ShowCount"] = issueStats.OpenCount
  131. }
  132. ctx.HTML(200, ISSUES)
  133. }
  134. func CreateIssue(ctx *middleware.Context) {
  135. ctx.Data["Title"] = "Create issue"
  136. ctx.Data["IsRepoToolbarIssues"] = true
  137. ctx.Data["IsRepoToolbarIssuesList"] = false
  138. ctx.Data["AttachmentsEnabled"] = setting.AttachmentEnabled
  139. var err error
  140. // Get all milestones.
  141. ctx.Data["OpenMilestones"], err = models.GetMilestones(ctx.Repo.Repository.Id, false)
  142. if err != nil {
  143. ctx.Handle(500, "issue.ViewIssue(GetMilestones.1): %v", err)
  144. return
  145. }
  146. ctx.Data["ClosedMilestones"], err = models.GetMilestones(ctx.Repo.Repository.Id, true)
  147. if err != nil {
  148. ctx.Handle(500, "issue.ViewIssue(GetMilestones.2): %v", err)
  149. return
  150. }
  151. us, err := models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/"))
  152. if err != nil {
  153. ctx.Handle(500, "issue.CreateIssue(GetCollaborators)", err)
  154. return
  155. }
  156. ctx.Data["AllowedTypes"] = setting.AttachmentAllowedTypes
  157. ctx.Data["Collaborators"] = us
  158. ctx.HTML(200, ISSUE_CREATE)
  159. }
  160. func CreateIssuePost(ctx *middleware.Context, form auth.CreateIssueForm) {
  161. send := func(status int, data interface{}, err error) {
  162. if err != nil {
  163. log.Error(4, "issue.CreateIssuePost(?): %s", err)
  164. ctx.JSON(status, map[string]interface{}{
  165. "ok": false,
  166. "status": status,
  167. "error": err.Error(),
  168. })
  169. } else {
  170. ctx.JSON(status, map[string]interface{}{
  171. "ok": true,
  172. "status": status,
  173. "data": data,
  174. })
  175. }
  176. }
  177. var err error
  178. // Get all milestones.
  179. _, err = models.GetMilestones(ctx.Repo.Repository.Id, false)
  180. if err != nil {
  181. send(500, nil, err)
  182. return
  183. }
  184. _, err = models.GetMilestones(ctx.Repo.Repository.Id, true)
  185. if err != nil {
  186. send(500, nil, err)
  187. return
  188. }
  189. _, err = models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/"))
  190. if err != nil {
  191. send(500, nil, err)
  192. return
  193. }
  194. if ctx.HasError() {
  195. send(400, nil, errors.New(ctx.Flash.ErrorMsg))
  196. return
  197. }
  198. // Only collaborators can assign.
  199. if !ctx.Repo.IsOwner {
  200. form.AssigneeId = 0
  201. }
  202. issue := &models.Issue{
  203. RepoId: ctx.Repo.Repository.Id,
  204. Index: int64(ctx.Repo.Repository.NumIssues) + 1,
  205. Name: form.IssueName,
  206. PosterId: ctx.User.Id,
  207. MilestoneId: form.MilestoneId,
  208. AssigneeId: form.AssigneeId,
  209. LabelIds: form.Labels,
  210. Content: form.Content,
  211. }
  212. if err := models.NewIssue(issue); err != nil {
  213. send(500, nil, err)
  214. return
  215. } else if err := models.NewIssueUserPairs(issue.RepoId, issue.Id, ctx.Repo.Owner.Id,
  216. ctx.User.Id, form.AssigneeId, ctx.Repo.Repository.Name); err != nil {
  217. send(500, nil, err)
  218. return
  219. }
  220. if setting.AttachmentEnabled {
  221. uploadFiles(ctx, issue.Id, 0)
  222. }
  223. // Update mentions.
  224. ms := base.MentionPattern.FindAllString(issue.Content, -1)
  225. if len(ms) > 0 {
  226. for i := range ms {
  227. ms[i] = ms[i][1:]
  228. }
  229. if err := models.UpdateMentions(ms, issue.Id); err != nil {
  230. send(500, nil, err)
  231. return
  232. }
  233. }
  234. act := &models.Action{
  235. ActUserId: ctx.User.Id,
  236. ActUserName: ctx.User.Name,
  237. ActEmail: ctx.User.Email,
  238. OpType: models.CREATE_ISSUE,
  239. Content: fmt.Sprintf("%d|%s", issue.Index, issue.Name),
  240. RepoId: ctx.Repo.Repository.Id,
  241. RepoUserName: ctx.Repo.Owner.Name,
  242. RepoName: ctx.Repo.Repository.Name,
  243. RefName: ctx.Repo.BranchName,
  244. IsPrivate: ctx.Repo.Repository.IsPrivate,
  245. }
  246. // Notify watchers.
  247. if err := models.NotifyWatchers(act); err != nil {
  248. send(500, nil, err)
  249. return
  250. }
  251. // Mail watchers and mentions.
  252. if setting.Service.EnableNotifyMail {
  253. tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue)
  254. if err != nil {
  255. send(500, nil, err)
  256. return
  257. }
  258. tos = append(tos, ctx.User.LowerName)
  259. newTos := make([]string, 0, len(ms))
  260. for _, m := range ms {
  261. if com.IsSliceContainsStr(tos, m) {
  262. continue
  263. }
  264. newTos = append(newTos, m)
  265. }
  266. if err = mailer.SendIssueMentionMail(ctx.Render, ctx.User, ctx.Repo.Owner,
  267. ctx.Repo.Repository, issue, models.GetUserEmailsByNames(newTos)); err != nil {
  268. send(500, nil, err)
  269. return
  270. }
  271. }
  272. log.Trace("%d Issue created: %d", ctx.Repo.Repository.Id, issue.Id)
  273. send(200, fmt.Sprintf("%s/%s/%s/issues/%d", setting.AppSubUrl, ctx.Params(":username"), ctx.Params(":reponame"), issue.Index), nil)
  274. }
  275. func checkLabels(labels, allLabels []*models.Label) {
  276. for _, l := range labels {
  277. for _, l2 := range allLabels {
  278. if l.Id == l2.Id {
  279. l2.IsChecked = true
  280. break
  281. }
  282. }
  283. }
  284. }
  285. func ViewIssue(ctx *middleware.Context) {
  286. ctx.Data["AttachmentsEnabled"] = setting.AttachmentEnabled
  287. idx := com.StrTo(ctx.Params(":index")).MustInt64()
  288. if idx == 0 {
  289. ctx.Handle(404, "issue.ViewIssue", nil)
  290. return
  291. }
  292. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, idx)
  293. if err != nil {
  294. if err == models.ErrIssueNotExist {
  295. ctx.Handle(404, "issue.ViewIssue(GetIssueByIndex)", err)
  296. } else {
  297. ctx.Handle(500, "issue.ViewIssue(GetIssueByIndex)", err)
  298. }
  299. return
  300. }
  301. // Get labels.
  302. if err = issue.GetLabels(); err != nil {
  303. ctx.Handle(500, "issue.ViewIssue(GetLabels)", err)
  304. return
  305. }
  306. labels, err := models.GetLabels(ctx.Repo.Repository.Id)
  307. if err != nil {
  308. ctx.Handle(500, "issue.ViewIssue(GetLabels.2)", err)
  309. return
  310. }
  311. checkLabels(issue.Labels, labels)
  312. ctx.Data["Labels"] = labels
  313. // Get assigned milestone.
  314. if issue.MilestoneId > 0 {
  315. ctx.Data["Milestone"], err = models.GetMilestoneById(issue.MilestoneId)
  316. if err != nil {
  317. if err == models.ErrMilestoneNotExist {
  318. log.Warn("issue.ViewIssue(GetMilestoneById): %v", err)
  319. } else {
  320. ctx.Handle(500, "issue.ViewIssue(GetMilestoneById)", err)
  321. return
  322. }
  323. }
  324. }
  325. // Get all milestones.
  326. ctx.Data["OpenMilestones"], err = models.GetMilestones(ctx.Repo.Repository.Id, false)
  327. if err != nil {
  328. ctx.Handle(500, "issue.ViewIssue(GetMilestones.1): %v", err)
  329. return
  330. }
  331. ctx.Data["ClosedMilestones"], err = models.GetMilestones(ctx.Repo.Repository.Id, true)
  332. if err != nil {
  333. ctx.Handle(500, "issue.ViewIssue(GetMilestones.2): %v", err)
  334. return
  335. }
  336. // Get all collaborators.
  337. ctx.Data["Collaborators"], err = models.GetCollaborators(strings.TrimPrefix(ctx.Repo.RepoLink, "/"))
  338. if err != nil {
  339. ctx.Handle(500, "issue.CreateIssue(GetCollaborators)", err)
  340. return
  341. }
  342. if ctx.IsSigned {
  343. // Update issue-user.
  344. if err = models.UpdateIssueUserPairByRead(ctx.User.Id, issue.Id); err != nil {
  345. ctx.Handle(500, "issue.ViewIssue(UpdateIssueUserPairByRead): %v", err)
  346. return
  347. }
  348. }
  349. // Get poster and Assignee.
  350. if err = issue.GetPoster(); err != nil {
  351. ctx.Handle(500, "issue.ViewIssue(GetPoster): %v", err)
  352. return
  353. } else if err = issue.GetAssignee(); err != nil {
  354. ctx.Handle(500, "issue.ViewIssue(GetAssignee): %v", err)
  355. return
  356. }
  357. issue.RenderedContent = string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink))
  358. // Get comments.
  359. comments, err := models.GetIssueComments(issue.Id)
  360. if err != nil {
  361. ctx.Handle(500, "issue.ViewIssue(GetIssueComments): %v", err)
  362. return
  363. }
  364. // Get posters.
  365. for i := range comments {
  366. u, err := models.GetUserById(comments[i].PosterId)
  367. if err != nil {
  368. ctx.Handle(500, "issue.ViewIssue(GetUserById.2): %v", err)
  369. return
  370. }
  371. comments[i].Poster = u
  372. if comments[i].Type == models.COMMENT {
  373. comments[i].Content = string(base.RenderMarkdown([]byte(comments[i].Content), ctx.Repo.RepoLink))
  374. }
  375. }
  376. ctx.Data["AllowedTypes"] = setting.AttachmentAllowedTypes
  377. ctx.Data["Title"] = issue.Name
  378. ctx.Data["Issue"] = issue
  379. ctx.Data["Comments"] = comments
  380. ctx.Data["IsIssueOwner"] = ctx.Repo.IsOwner || (ctx.IsSigned && issue.PosterId == ctx.User.Id)
  381. ctx.Data["IsRepoToolbarIssues"] = true
  382. ctx.Data["IsRepoToolbarIssuesList"] = false
  383. ctx.HTML(200, ISSUE_VIEW)
  384. }
  385. func UpdateIssue(ctx *middleware.Context, form auth.CreateIssueForm) {
  386. idx := com.StrTo(ctx.Params(":index")).MustInt64()
  387. if idx <= 0 {
  388. ctx.Error(404)
  389. return
  390. }
  391. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, idx)
  392. if err != nil {
  393. if err == models.ErrIssueNotExist {
  394. ctx.Handle(404, "issue.UpdateIssue", err)
  395. } else {
  396. ctx.Handle(500, "issue.UpdateIssue(GetIssueByIndex)", err)
  397. }
  398. return
  399. }
  400. if ctx.User.Id != issue.PosterId && !ctx.Repo.IsOwner {
  401. ctx.Error(403)
  402. return
  403. }
  404. issue.Name = form.IssueName
  405. issue.MilestoneId = form.MilestoneId
  406. issue.AssigneeId = form.AssigneeId
  407. issue.LabelIds = form.Labels
  408. issue.Content = form.Content
  409. // try get content from text, ignore conflict with preview ajax
  410. if form.Content == "" {
  411. issue.Content = ctx.Query("text")
  412. }
  413. if err = models.UpdateIssue(issue); err != nil {
  414. ctx.Handle(500, "issue.UpdateIssue(UpdateIssue)", err)
  415. return
  416. }
  417. ctx.JSON(200, map[string]interface{}{
  418. "ok": true,
  419. "title": issue.Name,
  420. "content": string(base.RenderMarkdown([]byte(issue.Content), ctx.Repo.RepoLink)),
  421. })
  422. }
  423. func UpdateIssueLabel(ctx *middleware.Context) {
  424. if !ctx.Repo.IsOwner {
  425. ctx.Error(403)
  426. return
  427. }
  428. idx := com.StrTo(ctx.Params(":index")).MustInt64()
  429. if idx <= 0 {
  430. ctx.Error(404)
  431. return
  432. }
  433. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, idx)
  434. if err != nil {
  435. if err == models.ErrIssueNotExist {
  436. ctx.Handle(404, "issue.UpdateIssueLabel(GetIssueByIndex)", err)
  437. } else {
  438. ctx.Handle(500, "issue.UpdateIssueLabel(GetIssueByIndex)", err)
  439. }
  440. return
  441. }
  442. isAttach := ctx.Query("action") == "attach"
  443. labelStrId := ctx.Query("id")
  444. labelId := com.StrTo(labelStrId).MustInt64()
  445. label, err := models.GetLabelById(labelId)
  446. if err != nil {
  447. if err == models.ErrLabelNotExist {
  448. ctx.Handle(404, "issue.UpdateIssueLabel(GetLabelById)", err)
  449. } else {
  450. ctx.Handle(500, "issue.UpdateIssueLabel(GetLabelById)", err)
  451. }
  452. return
  453. }
  454. isHad := strings.Contains(issue.LabelIds, "$"+labelStrId+"|")
  455. isNeedUpdate := false
  456. if isAttach {
  457. if !isHad {
  458. issue.LabelIds += "$" + labelStrId + "|"
  459. isNeedUpdate = true
  460. }
  461. } else {
  462. if isHad {
  463. issue.LabelIds = strings.Replace(issue.LabelIds, "$"+labelStrId+"|", "", -1)
  464. isNeedUpdate = true
  465. }
  466. }
  467. if isNeedUpdate {
  468. if err = models.UpdateIssue(issue); err != nil {
  469. ctx.Handle(500, "issue.UpdateIssueLabel(UpdateIssue)", err)
  470. return
  471. }
  472. if isAttach {
  473. label.NumIssues++
  474. if issue.IsClosed {
  475. label.NumClosedIssues++
  476. }
  477. } else {
  478. label.NumIssues--
  479. if issue.IsClosed {
  480. label.NumClosedIssues--
  481. }
  482. }
  483. if err = models.UpdateLabel(label); err != nil {
  484. ctx.Handle(500, "issue.UpdateIssueLabel(UpdateLabel)", err)
  485. return
  486. }
  487. }
  488. ctx.JSON(200, map[string]interface{}{
  489. "ok": true,
  490. })
  491. }
  492. func UpdateIssueMilestone(ctx *middleware.Context) {
  493. if !ctx.Repo.IsOwner {
  494. ctx.Error(403)
  495. return
  496. }
  497. issueId := com.StrTo(ctx.Params(":index")).MustInt64()
  498. if issueId == 0 {
  499. ctx.Error(404)
  500. return
  501. }
  502. issue, err := models.GetIssueById(issueId)
  503. if err != nil {
  504. if err == models.ErrIssueNotExist {
  505. ctx.Handle(404, "issue.UpdateIssueMilestone(GetIssueById)", err)
  506. } else {
  507. ctx.Handle(500, "issue.UpdateIssueMilestone(GetIssueById)", err)
  508. }
  509. return
  510. }
  511. oldMid := issue.MilestoneId
  512. mid := com.StrTo(ctx.Query("milestoneid")).MustInt64()
  513. if oldMid == mid {
  514. ctx.JSON(200, map[string]interface{}{
  515. "ok": true,
  516. })
  517. return
  518. }
  519. // Not check for invalid milestone id and give responsibility to owners.
  520. issue.MilestoneId = mid
  521. if err = models.ChangeMilestoneAssign(oldMid, mid, issue); err != nil {
  522. ctx.Handle(500, "issue.UpdateIssueMilestone(ChangeMilestoneAssign)", err)
  523. return
  524. } else if err = models.UpdateIssue(issue); err != nil {
  525. ctx.Handle(500, "issue.UpdateIssueMilestone(UpdateIssue)", err)
  526. return
  527. }
  528. ctx.JSON(200, map[string]interface{}{
  529. "ok": true,
  530. })
  531. }
  532. func UpdateAssignee(ctx *middleware.Context) {
  533. if !ctx.Repo.IsOwner {
  534. ctx.Error(403)
  535. return
  536. }
  537. issueId := com.StrTo(ctx.Params(":index")).MustInt64()
  538. if issueId == 0 {
  539. ctx.Error(404)
  540. return
  541. }
  542. issue, err := models.GetIssueById(issueId)
  543. if err != nil {
  544. if err == models.ErrIssueNotExist {
  545. ctx.Handle(404, "GetIssueById", err)
  546. } else {
  547. ctx.Handle(500, "GetIssueById", err)
  548. }
  549. return
  550. }
  551. aid := com.StrTo(ctx.Query("assigneeid")).MustInt64()
  552. // Not check for invalid assignne id and give responsibility to owners.
  553. issue.AssigneeId = aid
  554. if err = models.UpdateIssueUserPairByAssignee(aid, issue.Id); err != nil {
  555. ctx.Handle(500, "UpdateIssueUserPairByAssignee: %v", err)
  556. return
  557. } else if err = models.UpdateIssue(issue); err != nil {
  558. ctx.Handle(500, "UpdateIssue", err)
  559. return
  560. }
  561. ctx.JSON(200, map[string]interface{}{
  562. "ok": true,
  563. })
  564. }
  565. func uploadFiles(ctx *middleware.Context, issueId, commentId int64) {
  566. if !setting.AttachmentEnabled {
  567. return
  568. }
  569. allowedTypes := strings.Split(setting.AttachmentAllowedTypes, "|")
  570. attachments := ctx.Req.MultipartForm.File["attachments"]
  571. if len(attachments) > setting.AttachmentMaxFiles {
  572. ctx.Handle(400, "issue.Comment", ErrTooManyFiles)
  573. return
  574. }
  575. for _, header := range attachments {
  576. file, err := header.Open()
  577. if err != nil {
  578. ctx.Handle(500, "issue.Comment(header.Open)", err)
  579. return
  580. }
  581. defer file.Close()
  582. buf := make([]byte, 1024)
  583. n, _ := file.Read(buf)
  584. if n > 0 {
  585. buf = buf[:n]
  586. }
  587. fileType := http.DetectContentType(buf)
  588. fmt.Println(fileType)
  589. allowed := false
  590. for _, t := range allowedTypes {
  591. t := strings.Trim(t, " ")
  592. if t == "*/*" || t == fileType {
  593. allowed = true
  594. break
  595. }
  596. }
  597. if !allowed {
  598. ctx.Handle(400, "issue.Comment", ErrFileTypeForbidden)
  599. return
  600. }
  601. out, err := ioutil.TempFile(setting.AttachmentPath, "attachment_")
  602. if err != nil {
  603. ctx.Handle(500, "ioutil.TempFile", err)
  604. return
  605. }
  606. defer out.Close()
  607. out.Write(buf)
  608. _, err = io.Copy(out, file)
  609. if err != nil {
  610. ctx.Handle(500, "io.Copy", err)
  611. return
  612. }
  613. _, err = models.CreateAttachment(issueId, commentId, header.Filename, out.Name())
  614. if err != nil {
  615. ctx.Handle(500, "CreateAttachment", err)
  616. return
  617. }
  618. }
  619. }
  620. func Comment(ctx *middleware.Context) {
  621. send := func(status int, data interface{}, err error) {
  622. if err != nil {
  623. log.Error(4, "issue.Comment(?): %s", err)
  624. ctx.JSON(status, map[string]interface{}{
  625. "ok": false,
  626. "status": status,
  627. "error": err.Error(),
  628. })
  629. } else {
  630. ctx.JSON(status, map[string]interface{}{
  631. "ok": true,
  632. "status": status,
  633. "data": data,
  634. })
  635. }
  636. }
  637. index := com.StrTo(ctx.Query("issueIndex")).MustInt64()
  638. if index == 0 {
  639. ctx.Error(404)
  640. return
  641. }
  642. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.Id, index)
  643. if err != nil {
  644. if err == models.ErrIssueNotExist {
  645. send(404, nil, err)
  646. } else {
  647. send(200, nil, err)
  648. }
  649. return
  650. }
  651. // Check if issue owner changes the status of issue.
  652. var newStatus string
  653. if ctx.Repo.IsOwner || issue.PosterId == ctx.User.Id {
  654. newStatus = ctx.Query("change_status")
  655. }
  656. if len(newStatus) > 0 {
  657. if (strings.Contains(newStatus, "Reopen") && issue.IsClosed) ||
  658. (strings.Contains(newStatus, "Close") && !issue.IsClosed) {
  659. issue.IsClosed = !issue.IsClosed
  660. if err = models.UpdateIssue(issue); err != nil {
  661. send(500, nil, err)
  662. return
  663. } else if err = models.UpdateIssueUserPairsByStatus(issue.Id, issue.IsClosed); err != nil {
  664. send(500, nil, err)
  665. return
  666. }
  667. // Change open/closed issue counter for the associated milestone
  668. if issue.MilestoneId > 0 {
  669. if err = models.ChangeMilestoneIssueStats(issue); err != nil {
  670. send(500, nil, err)
  671. }
  672. }
  673. cmtType := models.CLOSE
  674. if !issue.IsClosed {
  675. cmtType = models.REOPEN
  676. }
  677. if _, err = models.CreateComment(ctx.User.Id, ctx.Repo.Repository.Id, issue.Id, 0, 0, cmtType, "", nil); err != nil {
  678. send(200, nil, err)
  679. return
  680. }
  681. log.Trace("%s Issue(%d) status changed: %v", ctx.Req.RequestURI, issue.Id, !issue.IsClosed)
  682. }
  683. }
  684. var comment *models.Comment
  685. var ms []string
  686. content := ctx.Query("content")
  687. // Fix #321. Allow empty comments, as long as we have attachments.
  688. if len(content) > 0 || len(ctx.Req.MultipartForm.File["attachments"]) > 0 {
  689. switch ctx.Params(":action") {
  690. case "new":
  691. if comment, err = models.CreateComment(ctx.User.Id, ctx.Repo.Repository.Id, issue.Id, 0, 0, models.COMMENT, content, nil); err != nil {
  692. send(500, nil, err)
  693. return
  694. }
  695. // Update mentions.
  696. ms = base.MentionPattern.FindAllString(issue.Content, -1)
  697. if len(ms) > 0 {
  698. for i := range ms {
  699. ms[i] = ms[i][1:]
  700. }
  701. if err := models.UpdateMentions(ms, issue.Id); err != nil {
  702. send(500, nil, err)
  703. return
  704. }
  705. }
  706. log.Trace("%s Comment created: %d", ctx.Req.RequestURI, issue.Id)
  707. default:
  708. ctx.Handle(404, "issue.Comment", err)
  709. return
  710. }
  711. }
  712. if comment != nil {
  713. uploadFiles(ctx, issue.Id, comment.Id)
  714. }
  715. // Notify watchers.
  716. act := &models.Action{
  717. ActUserId: ctx.User.Id,
  718. ActUserName: ctx.User.LowerName,
  719. ActEmail: ctx.User.Email,
  720. OpType: models.COMMENT_ISSUE,
  721. Content: fmt.Sprintf("%d|%s", issue.Index, strings.Split(content, "\n")[0]),
  722. RepoId: ctx.Repo.Repository.Id,
  723. RepoUserName: ctx.Repo.Owner.LowerName,
  724. RepoName: ctx.Repo.Repository.LowerName,
  725. }
  726. if err = models.NotifyWatchers(act); err != nil {
  727. send(500, nil, err)
  728. return
  729. }
  730. // Mail watchers and mentions.
  731. if setting.Service.EnableNotifyMail {
  732. issue.Content = content
  733. tos, err := mailer.SendIssueNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue)
  734. if err != nil {
  735. send(500, nil, err)
  736. return
  737. }
  738. tos = append(tos, ctx.User.LowerName)
  739. newTos := make([]string, 0, len(ms))
  740. for _, m := range ms {
  741. if com.IsSliceContainsStr(tos, m) {
  742. continue
  743. }
  744. newTos = append(newTos, m)
  745. }
  746. if err = mailer.SendIssueMentionMail(ctx.Render, ctx.User, ctx.Repo.Owner,
  747. ctx.Repo.Repository, issue, models.GetUserEmailsByNames(newTos)); err != nil {
  748. send(500, nil, err)
  749. return
  750. }
  751. }
  752. send(200, fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, index), nil)
  753. }
  754. func NewLabel(ctx *middleware.Context, form auth.CreateLabelForm) {
  755. if ctx.HasError() {
  756. Issues(ctx)
  757. return
  758. }
  759. l := &models.Label{
  760. RepoId: ctx.Repo.Repository.Id,
  761. Name: form.Title,
  762. Color: form.Color,
  763. }
  764. if err := models.NewLabel(l); err != nil {
  765. ctx.Handle(500, "issue.NewLabel(NewLabel)", err)
  766. return
  767. }
  768. ctx.Redirect(ctx.Repo.RepoLink + "/issues")
  769. }
  770. func UpdateLabel(ctx *middleware.Context, form auth.CreateLabelForm) {
  771. id := com.StrTo(ctx.Query("id")).MustInt64()
  772. if id == 0 {
  773. ctx.Error(404)
  774. return
  775. }
  776. l := &models.Label{
  777. Id: id,
  778. Name: form.Title,
  779. Color: form.Color,
  780. }
  781. if err := models.UpdateLabel(l); err != nil {
  782. ctx.Handle(500, "issue.UpdateLabel(UpdateLabel)", err)
  783. return
  784. }
  785. ctx.Redirect(ctx.Repo.RepoLink + "/issues")
  786. }
  787. func DeleteLabel(ctx *middleware.Context) {
  788. removes := ctx.Query("remove")
  789. if len(strings.TrimSpace(removes)) == 0 {
  790. ctx.JSON(200, map[string]interface{}{
  791. "ok": true,
  792. })
  793. return
  794. }
  795. strIds := strings.Split(removes, ",")
  796. for _, strId := range strIds {
  797. if err := models.DeleteLabel(ctx.Repo.Repository.Id, strId); err != nil {
  798. ctx.Handle(500, "issue.DeleteLabel(DeleteLabel)", err)
  799. return
  800. }
  801. }
  802. ctx.JSON(200, map[string]interface{}{
  803. "ok": true,
  804. })
  805. }
  806. func Milestones(ctx *middleware.Context) {
  807. ctx.Data["Title"] = "Milestones"
  808. ctx.Data["IsRepoToolbarIssues"] = true
  809. ctx.Data["IsRepoToolbarIssuesList"] = true
  810. isShowClosed := ctx.Query("state") == "closed"
  811. miles, err := models.GetMilestones(ctx.Repo.Repository.Id, isShowClosed)
  812. if err != nil {
  813. ctx.Handle(500, "issue.Milestones(GetMilestones)", err)
  814. return
  815. }
  816. for _, m := range miles {
  817. m.RenderedContent = string(base.RenderMarkdown([]byte(m.Content), ctx.Repo.RepoLink))
  818. m.CalOpenIssues()
  819. }
  820. ctx.Data["Milestones"] = miles
  821. if isShowClosed {
  822. ctx.Data["State"] = "closed"
  823. } else {
  824. ctx.Data["State"] = "open"
  825. }
  826. ctx.HTML(200, MILESTONE)
  827. }
  828. func NewMilestone(ctx *middleware.Context) {
  829. ctx.Data["Title"] = "New Milestone"
  830. ctx.Data["IsRepoToolbarIssues"] = true
  831. ctx.Data["IsRepoToolbarIssuesList"] = true
  832. ctx.HTML(200, MILESTONE_NEW)
  833. }
  834. func NewMilestonePost(ctx *middleware.Context, form auth.CreateMilestoneForm) {
  835. ctx.Data["Title"] = "New Milestone"
  836. ctx.Data["IsRepoToolbarIssues"] = true
  837. ctx.Data["IsRepoToolbarIssuesList"] = true
  838. if ctx.HasError() {
  839. ctx.HTML(200, MILESTONE_NEW)
  840. return
  841. }
  842. var deadline time.Time
  843. var err error
  844. if len(form.Deadline) == 0 {
  845. form.Deadline = "12/31/9999"
  846. }
  847. deadline, err = time.Parse("01/02/2006", form.Deadline)
  848. if err != nil {
  849. ctx.Handle(500, "issue.NewMilestonePost(time.Parse)", err)
  850. return
  851. }
  852. mile := &models.Milestone{
  853. RepoId: ctx.Repo.Repository.Id,
  854. Index: int64(ctx.Repo.Repository.NumMilestones) + 1,
  855. Name: form.Title,
  856. Content: form.Content,
  857. Deadline: deadline,
  858. }
  859. if err = models.NewMilestone(mile); err != nil {
  860. ctx.Handle(500, "issue.NewMilestonePost(NewMilestone)", err)
  861. return
  862. }
  863. ctx.Redirect(ctx.Repo.RepoLink + "/issues/milestones")
  864. }
  865. func UpdateMilestone(ctx *middleware.Context) {
  866. ctx.Data["Title"] = "Update Milestone"
  867. ctx.Data["IsRepoToolbarIssues"] = true
  868. ctx.Data["IsRepoToolbarIssuesList"] = true
  869. idx := com.StrTo(ctx.Params(":index")).MustInt64()
  870. if idx == 0 {
  871. ctx.Handle(404, "issue.UpdateMilestone", nil)
  872. return
  873. }
  874. mile, err := models.GetMilestoneByIndex(ctx.Repo.Repository.Id, idx)
  875. if err != nil {
  876. if err == models.ErrMilestoneNotExist {
  877. ctx.Handle(404, "issue.UpdateMilestone(GetMilestoneByIndex)", err)
  878. } else {
  879. ctx.Handle(500, "issue.UpdateMilestone(GetMilestoneByIndex)", err)
  880. }
  881. return
  882. }
  883. action := ctx.Params(":action")
  884. if len(action) > 0 {
  885. switch action {
  886. case "open":
  887. if mile.IsClosed {
  888. if err = models.ChangeMilestoneStatus(mile, false); err != nil {
  889. ctx.Handle(500, "issue.UpdateMilestone(ChangeMilestoneStatus)", err)
  890. return
  891. }
  892. }
  893. case "close":
  894. if !mile.IsClosed {
  895. mile.ClosedDate = time.Now()
  896. if err = models.ChangeMilestoneStatus(mile, true); err != nil {
  897. ctx.Handle(500, "issue.UpdateMilestone(ChangeMilestoneStatus)", err)
  898. return
  899. }
  900. }
  901. case "delete":
  902. if err = models.DeleteMilestone(mile); err != nil {
  903. ctx.Handle(500, "issue.UpdateMilestone(DeleteMilestone)", err)
  904. return
  905. }
  906. }
  907. ctx.Redirect(ctx.Repo.RepoLink + "/issues/milestones")
  908. return
  909. }
  910. mile.DeadlineString = mile.Deadline.UTC().Format("01/02/2006")
  911. if mile.DeadlineString == "12/31/9999" {
  912. mile.DeadlineString = ""
  913. }
  914. ctx.Data["Milestone"] = mile
  915. ctx.HTML(200, MILESTONE_EDIT)
  916. }
  917. func UpdateMilestonePost(ctx *middleware.Context, form auth.CreateMilestoneForm) {
  918. ctx.Data["Title"] = "Update Milestone"
  919. ctx.Data["IsRepoToolbarIssues"] = true
  920. ctx.Data["IsRepoToolbarIssuesList"] = true
  921. idx := com.StrTo(ctx.Params(":index")).MustInt64()
  922. if idx == 0 {
  923. ctx.Handle(404, "issue.UpdateMilestonePost", nil)
  924. return
  925. }
  926. mile, err := models.GetMilestoneByIndex(ctx.Repo.Repository.Id, idx)
  927. if err != nil {
  928. if err == models.ErrMilestoneNotExist {
  929. ctx.Handle(404, "issue.UpdateMilestonePost(GetMilestoneByIndex)", err)
  930. } else {
  931. ctx.Handle(500, "issue.UpdateMilestonePost(GetMilestoneByIndex)", err)
  932. }
  933. return
  934. }
  935. if ctx.HasError() {
  936. ctx.HTML(200, MILESTONE_EDIT)
  937. return
  938. }
  939. var deadline time.Time
  940. if len(form.Deadline) == 0 {
  941. form.Deadline = "12/31/9999"
  942. }
  943. deadline, err = time.Parse("01/02/2006", form.Deadline)
  944. if err != nil {
  945. ctx.Handle(500, "issue.UpdateMilestonePost(time.Parse)", err)
  946. return
  947. }
  948. mile.Name = form.Title
  949. mile.Content = form.Content
  950. mile.Deadline = deadline
  951. if err = models.UpdateMilestone(mile); err != nil {
  952. ctx.Handle(500, "issue.UpdateMilestonePost(UpdateMilestone)", err)
  953. return
  954. }
  955. ctx.Redirect(ctx.Repo.RepoLink + "/issues/milestones")
  956. }
  957. func IssueGetAttachment(ctx *middleware.Context) {
  958. id := com.StrTo(ctx.Params(":id")).MustInt64()
  959. if id == 0 {
  960. ctx.Error(404)
  961. return
  962. }
  963. attachment, err := models.GetAttachmentById(id)
  964. if err != nil {
  965. ctx.Handle(404, "issue.IssueGetAttachment(models.GetAttachmentById)", err)
  966. return
  967. }
  968. // Fix #312. Attachments with , in their name are not handled correctly by Google Chrome.
  969. // We must put the name in " manually.
  970. ctx.ServeFile(attachment.Path, "\""+attachment.Name+"\"")
  971. }
  972. // testing route handler for new issue ui page
  973. // todo : move to Issue() function
  974. func Issues2(ctx *middleware.Context){
  975. ctx.HTML(200,"repo/issue2/list")
  976. }