issue.go 30 KB

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