issue.go 30 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.CreateIssue) ([]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.CreateIssue) {
  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. var (
  357. repo = ctx.Repo.Repository
  358. attachments []string
  359. )
  360. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, f)
  361. if ctx.Written() {
  362. return
  363. }
  364. if setting.AttachmentEnabled {
  365. attachments = f.Files
  366. }
  367. if ctx.HasError() {
  368. ctx.HTML(200, ISSUE_NEW)
  369. return
  370. }
  371. issue := &models.Issue{
  372. RepoID: repo.ID,
  373. Title: f.Title,
  374. PosterID: ctx.User.ID,
  375. Poster: ctx.User,
  376. MilestoneID: milestoneID,
  377. AssigneeID: assigneeID,
  378. Content: f.Content,
  379. }
  380. if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil {
  381. ctx.Handle(500, "NewIssue", err)
  382. return
  383. }
  384. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  385. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  386. }
  387. func UploadIssueAttachment(ctx *context.Context) {
  388. if !setting.AttachmentEnabled {
  389. ctx.Error(404, "attachment is not enabled")
  390. return
  391. }
  392. file, header, err := ctx.Req.FormFile("file")
  393. if err != nil {
  394. ctx.Error(500, fmt.Sprintf("FormFile: %v", err))
  395. return
  396. }
  397. defer file.Close()
  398. buf := make([]byte, 1024)
  399. n, _ := file.Read(buf)
  400. if n > 0 {
  401. buf = buf[:n]
  402. }
  403. fileType := http.DetectContentType(buf)
  404. allowedTypes := strings.Split(setting.AttachmentAllowedTypes, ",")
  405. allowed := false
  406. for _, t := range allowedTypes {
  407. t := strings.Trim(t, " ")
  408. if t == "*/*" || t == fileType {
  409. allowed = true
  410. break
  411. }
  412. }
  413. if !allowed {
  414. ctx.Error(400, ErrFileTypeForbidden.Error())
  415. return
  416. }
  417. attach, err := models.NewAttachment(header.Filename, buf, file)
  418. if err != nil {
  419. ctx.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  420. return
  421. }
  422. log.Trace("New attachment uploaded: %s", attach.UUID)
  423. ctx.JSON(200, map[string]string{
  424. "uuid": attach.UUID,
  425. })
  426. }
  427. func ViewIssue(ctx *context.Context) {
  428. ctx.Data["RequireHighlightJS"] = true
  429. ctx.Data["RequireDropzone"] = true
  430. renderAttachmentSettings(ctx)
  431. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  432. if err != nil {
  433. if models.IsErrIssueNotExist(err) {
  434. ctx.Handle(404, "GetIssueByIndex", err)
  435. } else {
  436. ctx.Handle(500, "GetIssueByIndex", err)
  437. }
  438. return
  439. }
  440. ctx.Data["Title"] = issue.Title
  441. // Make sure type and URL matches.
  442. if ctx.Params(":type") == "issues" && issue.IsPull {
  443. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  444. return
  445. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  446. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  447. return
  448. }
  449. if issue.IsPull {
  450. MustAllowPulls(ctx)
  451. if ctx.Written() {
  452. return
  453. }
  454. ctx.Data["PageIsPullList"] = true
  455. ctx.Data["PageIsPullConversation"] = true
  456. } else {
  457. MustEnableIssues(ctx)
  458. if ctx.Written() {
  459. return
  460. }
  461. ctx.Data["PageIsIssueList"] = true
  462. }
  463. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  464. ctx.Repo.Repository.ComposeMetas()))
  465. repo := ctx.Repo.Repository
  466. // Get more information if it's a pull request.
  467. if issue.IsPull {
  468. if issue.PullRequest.HasMerged {
  469. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  470. PrepareMergedViewPullInfo(ctx, issue)
  471. } else {
  472. PrepareViewPullInfo(ctx, issue)
  473. }
  474. if ctx.Written() {
  475. return
  476. }
  477. }
  478. // Metas.
  479. // Check labels.
  480. labelIDMark := make(map[int64]bool)
  481. for i := range issue.Labels {
  482. labelIDMark[issue.Labels[i].ID] = true
  483. }
  484. labels, err := models.GetLabelsByRepoID(repo.ID)
  485. if err != nil {
  486. ctx.Handle(500, "GetLabelsByRepoID", err)
  487. return
  488. }
  489. hasSelected := false
  490. for i := range labels {
  491. if labelIDMark[labels[i].ID] {
  492. labels[i].IsChecked = true
  493. hasSelected = true
  494. }
  495. }
  496. ctx.Data["HasSelectedLabel"] = hasSelected
  497. ctx.Data["Labels"] = labels
  498. // Check milestone and assignee.
  499. if ctx.Repo.IsWriter() {
  500. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  501. if ctx.Written() {
  502. return
  503. }
  504. }
  505. if ctx.IsSigned {
  506. // Update issue-user.
  507. if err = issue.ReadBy(ctx.User.ID); err != nil {
  508. ctx.Handle(500, "ReadBy", err)
  509. return
  510. }
  511. }
  512. var (
  513. tag models.CommentTag
  514. ok bool
  515. marked = make(map[int64]models.CommentTag)
  516. comment *models.Comment
  517. participants = make([]*models.User, 1, 10)
  518. )
  519. // Render comments and and fetch participants.
  520. participants[0] = issue.Poster
  521. for _, comment = range issue.Comments {
  522. if comment.Type == models.COMMENT_TYPE_COMMENT {
  523. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  524. ctx.Repo.Repository.ComposeMetas()))
  525. // Check tag.
  526. tag, ok = marked[comment.PosterID]
  527. if ok {
  528. comment.ShowTag = tag
  529. continue
  530. }
  531. if repo.IsOwnedBy(comment.PosterID) ||
  532. (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
  533. comment.ShowTag = models.COMMENT_TAG_OWNER
  534. } else if comment.Poster.IsWriterOfRepo(repo) {
  535. comment.ShowTag = models.COMMENT_TAG_WRITER
  536. } else if comment.PosterID == issue.PosterID {
  537. comment.ShowTag = models.COMMENT_TAG_POSTER
  538. }
  539. marked[comment.PosterID] = comment.ShowTag
  540. isAdded := false
  541. for j := range participants {
  542. if comment.Poster == participants[j] {
  543. isAdded = true
  544. break
  545. }
  546. }
  547. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  548. participants = append(participants, comment.Poster)
  549. }
  550. }
  551. }
  552. if issue.IsPull && issue.PullRequest.HasMerged {
  553. pull := issue.PullRequest
  554. ctx.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID &&
  555. ctx.Repo.IsWriter() && ctx.Repo.GitRepo.IsBranchExist(pull.HeadBranch)
  556. deleteBranchUrl := ctx.Repo.RepoLink + "/branches/delete/" + pull.HeadBranch
  557. ctx.Data["DeleteBranchLink"] = fmt.Sprintf("%s?commit=%s&redirect_to=%s", deleteBranchUrl, pull.MergedCommitID, ctx.Data["Link"])
  558. }
  559. ctx.Data["Participants"] = participants
  560. ctx.Data["NumParticipants"] = len(participants)
  561. ctx.Data["Issue"] = issue
  562. ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))
  563. ctx.Data["SignInLink"] = setting.AppSubUrl + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  564. ctx.HTML(200, ISSUE_VIEW)
  565. }
  566. func getActionIssue(ctx *context.Context) *models.Issue {
  567. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  568. if err != nil {
  569. if models.IsErrIssueNotExist(err) {
  570. ctx.Error(404, "GetIssueByIndex")
  571. } else {
  572. ctx.Handle(500, "GetIssueByIndex", err)
  573. }
  574. return nil
  575. }
  576. return issue
  577. }
  578. func UpdateIssueTitle(ctx *context.Context) {
  579. issue := getActionIssue(ctx)
  580. if ctx.Written() {
  581. return
  582. }
  583. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) {
  584. ctx.Error(403)
  585. return
  586. }
  587. title := ctx.QueryTrim("title")
  588. if len(title) == 0 {
  589. ctx.Error(204)
  590. return
  591. }
  592. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  593. ctx.Handle(500, "ChangeTitle", err)
  594. return
  595. }
  596. ctx.JSON(200, map[string]interface{}{
  597. "title": issue.Title,
  598. })
  599. }
  600. func UpdateIssueContent(ctx *context.Context) {
  601. issue := getActionIssue(ctx)
  602. if ctx.Written() {
  603. return
  604. }
  605. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) {
  606. ctx.Error(403)
  607. return
  608. }
  609. content := ctx.Query("content")
  610. if err := issue.ChangeContent(ctx.User, content); err != nil {
  611. ctx.Handle(500, "ChangeContent", err)
  612. return
  613. }
  614. ctx.JSON(200, map[string]interface{}{
  615. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  616. })
  617. }
  618. func UpdateIssueLabel(ctx *context.Context) {
  619. issue := getActionIssue(ctx)
  620. if ctx.Written() {
  621. return
  622. }
  623. if ctx.Query("action") == "clear" {
  624. if err := issue.ClearLabels(ctx.User); err != nil {
  625. ctx.Handle(500, "ClearLabels", err)
  626. return
  627. }
  628. } else {
  629. isAttach := ctx.Query("action") == "attach"
  630. label, err := models.GetLabelOfRepoByID(ctx.Repo.Repository.ID, ctx.QueryInt64("id"))
  631. if err != nil {
  632. if models.IsErrLabelNotExist(err) {
  633. ctx.Error(404, "GetLabelByID")
  634. } else {
  635. ctx.Handle(500, "GetLabelByID", err)
  636. }
  637. return
  638. }
  639. if isAttach && !issue.HasLabel(label.ID) {
  640. if err = issue.AddLabel(ctx.User, label); err != nil {
  641. ctx.Handle(500, "AddLabel", err)
  642. return
  643. }
  644. } else if !isAttach && issue.HasLabel(label.ID) {
  645. if err = issue.RemoveLabel(ctx.User, label); err != nil {
  646. ctx.Handle(500, "RemoveLabel", err)
  647. return
  648. }
  649. }
  650. }
  651. ctx.JSON(200, map[string]interface{}{
  652. "ok": true,
  653. })
  654. }
  655. func UpdateIssueMilestone(ctx *context.Context) {
  656. issue := getActionIssue(ctx)
  657. if ctx.Written() {
  658. return
  659. }
  660. oldMilestoneID := issue.MilestoneID
  661. milestoneID := ctx.QueryInt64("id")
  662. if oldMilestoneID == milestoneID {
  663. ctx.JSON(200, map[string]interface{}{
  664. "ok": true,
  665. })
  666. return
  667. }
  668. // Not check for invalid milestone id and give responsibility to owners.
  669. issue.MilestoneID = milestoneID
  670. if err := models.ChangeMilestoneAssign(issue, oldMilestoneID); err != nil {
  671. ctx.Handle(500, "ChangeMilestoneAssign", err)
  672. return
  673. }
  674. ctx.JSON(200, map[string]interface{}{
  675. "ok": true,
  676. })
  677. }
  678. func UpdateIssueAssignee(ctx *context.Context) {
  679. issue := getActionIssue(ctx)
  680. if ctx.Written() {
  681. return
  682. }
  683. assigneeID := ctx.QueryInt64("id")
  684. if issue.AssigneeID == assigneeID {
  685. ctx.JSON(200, map[string]interface{}{
  686. "ok": true,
  687. })
  688. return
  689. }
  690. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  691. ctx.Handle(500, "ChangeAssignee", err)
  692. return
  693. }
  694. ctx.JSON(200, map[string]interface{}{
  695. "ok": true,
  696. })
  697. }
  698. func NewComment(ctx *context.Context, f form.CreateComment) {
  699. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  700. if err != nil {
  701. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  702. return
  703. }
  704. var attachments []string
  705. if setting.AttachmentEnabled {
  706. attachments = f.Files
  707. }
  708. if ctx.HasError() {
  709. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  710. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  711. return
  712. }
  713. var comment *models.Comment
  714. defer func() {
  715. // Check if issue admin/poster changes the status of issue.
  716. if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  717. (f.Status == "reopen" || f.Status == "close") &&
  718. !(issue.IsPull && issue.PullRequest.HasMerged) {
  719. // Duplication and conflict check should apply to reopen pull request.
  720. var pr *models.PullRequest
  721. if f.Status == "reopen" && issue.IsPull {
  722. pull := issue.PullRequest
  723. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  724. if err != nil {
  725. if !models.IsErrPullRequestNotExist(err) {
  726. ctx.Handle(500, "GetUnmergedPullRequest", err)
  727. return
  728. }
  729. }
  730. // Regenerate patch and test conflict.
  731. if pr == nil {
  732. if err = issue.PullRequest.UpdatePatch(); err != nil {
  733. ctx.Handle(500, "UpdatePatch", err)
  734. return
  735. }
  736. issue.PullRequest.AddToTaskQueue()
  737. }
  738. }
  739. if pr != nil {
  740. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  741. } else {
  742. if err = issue.ChangeStatus(ctx.User, ctx.Repo.Repository, f.Status == "close"); err != nil {
  743. log.Error(4, "ChangeStatus: %v", err)
  744. } else {
  745. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  746. }
  747. }
  748. }
  749. // Redirect to comment hashtag if there is any actual content.
  750. typeName := "issues"
  751. if issue.IsPull {
  752. typeName = "pulls"
  753. }
  754. if comment != nil {
  755. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  756. } else {
  757. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  758. }
  759. }()
  760. // Fix #321: Allow empty comments, as long as we have attachments.
  761. if len(f.Content) == 0 && len(attachments) == 0 {
  762. return
  763. }
  764. comment, err = models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, f.Content, attachments)
  765. if err != nil {
  766. ctx.Handle(500, "CreateIssueComment", err)
  767. return
  768. }
  769. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  770. }
  771. func UpdateCommentContent(ctx *context.Context) {
  772. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  773. if err != nil {
  774. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  775. return
  776. }
  777. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  778. ctx.Error(403)
  779. return
  780. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  781. ctx.Error(204)
  782. return
  783. }
  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(comment); 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(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. }