issue.go 31 KB

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