1
0

issue.go 30 KB

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