issue.go 31 KB

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