issue.go 29 KB

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