1
0

issue.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260
  1. package repo
  2. import (
  3. "errors"
  4. "fmt"
  5. "net/http"
  6. "net/url"
  7. "strings"
  8. "time"
  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. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  799. c.NotFound()
  800. return
  801. } else if comment.Type != database.CommentTypeComment {
  802. c.Status(http.StatusNoContent)
  803. return
  804. }
  805. oldContent := comment.Content
  806. comment.Content = c.Query("content")
  807. if comment.Content == "" {
  808. c.JSONSuccess(map[string]any{
  809. "content": "",
  810. })
  811. return
  812. }
  813. if err = database.UpdateComment(c.User, comment, oldContent); err != nil {
  814. c.Error(err, "update comment")
  815. return
  816. }
  817. c.JSONSuccess(map[string]string{
  818. "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  819. })
  820. }
  821. func DeleteComment(c *context.Context) {
  822. comment, err := database.GetCommentByID(c.ParamsInt64(":id"))
  823. if err != nil {
  824. c.NotFoundOrError(err, "get comment by ID")
  825. return
  826. }
  827. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  828. c.NotFound()
  829. return
  830. } else if comment.Type != database.CommentTypeComment {
  831. c.Status(http.StatusNoContent)
  832. return
  833. }
  834. if err = database.DeleteCommentByID(c.User, comment.ID); err != nil {
  835. c.Error(err, "delete comment by ID")
  836. return
  837. }
  838. c.Status(http.StatusOK)
  839. }
  840. func Labels(c *context.Context) {
  841. c.Data["Title"] = c.Tr("repo.labels")
  842. c.Data["PageIsIssueList"] = true
  843. c.Data["PageIsLabels"] = true
  844. c.Data["RequireMinicolors"] = true
  845. c.Data["LabelTemplates"] = database.LabelTemplates
  846. c.Success(tmplRepoIssueLabels)
  847. }
  848. func InitializeLabels(c *context.Context, f form.InitializeLabels) {
  849. if c.HasError() {
  850. c.RawRedirect(c.Repo.MakeURL("labels"))
  851. return
  852. }
  853. list, err := database.GetLabelTemplateFile(f.TemplateName)
  854. if err != nil {
  855. c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err))
  856. c.RawRedirect(c.Repo.MakeURL("labels"))
  857. return
  858. }
  859. labels := make([]*database.Label, len(list))
  860. for i := 0; i < len(list); i++ {
  861. labels[i] = &database.Label{
  862. RepoID: c.Repo.Repository.ID,
  863. Name: list[i][0],
  864. Color: list[i][1],
  865. }
  866. }
  867. if err := database.NewLabels(labels...); err != nil {
  868. c.Error(err, "new labels")
  869. return
  870. }
  871. c.RawRedirect(c.Repo.MakeURL("labels"))
  872. }
  873. func NewLabel(c *context.Context, f form.CreateLabel) {
  874. c.Data["Title"] = c.Tr("repo.labels")
  875. c.Data["PageIsLabels"] = true
  876. if c.HasError() {
  877. c.Flash.Error(c.Data["ErrorMsg"].(string))
  878. c.RawRedirect(c.Repo.MakeURL("labels"))
  879. return
  880. }
  881. l := &database.Label{
  882. RepoID: c.Repo.Repository.ID,
  883. Name: f.Title,
  884. Color: f.Color,
  885. }
  886. if err := database.NewLabels(l); err != nil {
  887. c.Error(err, "new labels")
  888. return
  889. }
  890. c.RawRedirect(c.Repo.MakeURL("labels"))
  891. }
  892. func UpdateLabel(c *context.Context, f form.CreateLabel) {
  893. l, err := database.GetLabelByID(f.ID)
  894. if err != nil {
  895. c.NotFoundOrError(err, "get label by ID")
  896. return
  897. }
  898. l.Name = f.Title
  899. l.Color = f.Color
  900. if err := database.UpdateLabel(l); err != nil {
  901. c.Error(err, "update label")
  902. return
  903. }
  904. c.RawRedirect(c.Repo.MakeURL("labels"))
  905. }
  906. func DeleteLabel(c *context.Context) {
  907. if err := database.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  908. c.Flash.Error("DeleteLabel: " + err.Error())
  909. } else {
  910. c.Flash.Success(c.Tr("repo.issues.label_deletion_success"))
  911. }
  912. c.JSONSuccess(map[string]any{
  913. "redirect": c.Repo.MakeURL("labels"),
  914. })
  915. }
  916. func Milestones(c *context.Context) {
  917. c.Data["Title"] = c.Tr("repo.milestones")
  918. c.Data["PageIsIssueList"] = true
  919. c.Data["PageIsMilestones"] = true
  920. isShowClosed := c.Query("state") == "closed"
  921. openCount, closedCount := database.MilestoneStats(c.Repo.Repository.ID)
  922. c.Data["OpenCount"] = openCount
  923. c.Data["ClosedCount"] = closedCount
  924. page := c.QueryInt("page")
  925. if page <= 1 {
  926. page = 1
  927. }
  928. var total int
  929. if !isShowClosed {
  930. total = int(openCount)
  931. } else {
  932. total = int(closedCount)
  933. }
  934. c.Data["Page"] = paginater.New(total, conf.UI.IssuePagingNum, page, 5)
  935. miles, err := database.GetMilestones(c.Repo.Repository.ID, page, isShowClosed)
  936. if err != nil {
  937. c.Error(err, "get milestones")
  938. return
  939. }
  940. for _, m := range miles {
  941. m.NumOpenIssues = int(m.CountIssues(false, false))
  942. m.NumClosedIssues = int(m.CountIssues(true, false))
  943. if m.NumOpenIssues+m.NumClosedIssues > 0 {
  944. m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues)
  945. }
  946. m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  947. }
  948. c.Data["Milestones"] = miles
  949. if isShowClosed {
  950. c.Data["State"] = "closed"
  951. } else {
  952. c.Data["State"] = "open"
  953. }
  954. c.Data["IsShowClosed"] = isShowClosed
  955. c.Success(tmplRepoIssueMilestones)
  956. }
  957. func NewMilestone(c *context.Context) {
  958. c.Data["Title"] = c.Tr("repo.milestones.new")
  959. c.Data["PageIsIssueList"] = true
  960. c.Data["PageIsMilestones"] = true
  961. c.Data["RequireDatetimepicker"] = true
  962. c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
  963. c.Success(tmplRepoIssueMilestoneNew)
  964. }
  965. func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
  966. c.Data["Title"] = c.Tr("repo.milestones.new")
  967. c.Data["PageIsIssueList"] = true
  968. c.Data["PageIsMilestones"] = true
  969. c.Data["RequireDatetimepicker"] = true
  970. c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
  971. if c.HasError() {
  972. c.Success(tmplRepoIssueMilestoneNew)
  973. return
  974. }
  975. if f.Deadline == "" {
  976. f.Deadline = "9999-12-31"
  977. }
  978. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  979. if err != nil {
  980. c.Data["Err_Deadline"] = true
  981. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f)
  982. return
  983. }
  984. if err = database.NewMilestone(&database.Milestone{
  985. RepoID: c.Repo.Repository.ID,
  986. Name: f.Title,
  987. Content: f.Content,
  988. Deadline: deadline,
  989. }); err != nil {
  990. c.Error(err, "new milestone")
  991. return
  992. }
  993. c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title))
  994. c.RawRedirect(c.Repo.MakeURL("milestones"))
  995. }
  996. func EditMilestone(c *context.Context) {
  997. c.Data["Title"] = c.Tr("repo.milestones.edit")
  998. c.Data["PageIsMilestones"] = true
  999. c.Data["PageIsEditMilestone"] = true
  1000. c.Data["RequireDatetimepicker"] = true
  1001. c.Data["DateLang"] = conf.I18n.DateLang(c.Language())
  1002. m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1003. if err != nil {
  1004. c.NotFoundOrError(err, "get milestone by repository ID")
  1005. return
  1006. }
  1007. c.Data["title"] = m.Name
  1008. c.Data["content"] = m.Content
  1009. if len(m.DeadlineString) > 0 {
  1010. c.Data["deadline"] = m.DeadlineString
  1011. }
  1012. c.Success(tmplRepoIssueMilestoneNew)
  1013. }
  1014. func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
  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. if c.HasError() {
  1021. c.Success(tmplRepoIssueMilestoneNew)
  1022. return
  1023. }
  1024. if f.Deadline == "" {
  1025. f.Deadline = "9999-12-31"
  1026. }
  1027. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  1028. if err != nil {
  1029. c.Data["Err_Deadline"] = true
  1030. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), tmplRepoIssueMilestoneNew, &f)
  1031. return
  1032. }
  1033. m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1034. if err != nil {
  1035. c.NotFoundOrError(err, "get milestone by repository ID")
  1036. return
  1037. }
  1038. m.Name = f.Title
  1039. m.Content = f.Content
  1040. m.Deadline = deadline
  1041. if err = database.UpdateMilestone(m); err != nil {
  1042. c.Error(err, "update milestone")
  1043. return
  1044. }
  1045. c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name))
  1046. c.RawRedirect(c.Repo.MakeURL("milestones"))
  1047. }
  1048. func ChangeMilestonStatus(c *context.Context) {
  1049. m, err := database.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1050. if err != nil {
  1051. c.NotFoundOrError(err, "get milestone by repository ID")
  1052. return
  1053. }
  1054. location := url.URL{
  1055. Path: "milestones",
  1056. }
  1057. switch c.Params(":action") {
  1058. case "open":
  1059. if m.IsClosed {
  1060. if err = database.ChangeMilestoneStatus(m, false); err != nil {
  1061. c.Error(err, "change milestone status to open")
  1062. return
  1063. }
  1064. }
  1065. location.RawQuery = "state=open"
  1066. case "close":
  1067. if !m.IsClosed {
  1068. m.ClosedDate = time.Now()
  1069. if err = database.ChangeMilestoneStatus(m, true); err != nil {
  1070. c.Error(err, "change milestone status to closed")
  1071. return
  1072. }
  1073. }
  1074. location.RawQuery = "state=closed"
  1075. }
  1076. c.RawRedirect(c.Repo.MakeURL(location))
  1077. }
  1078. func DeleteMilestone(c *context.Context) {
  1079. if err := database.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  1080. c.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1081. } else {
  1082. c.Flash.Success(c.Tr("repo.milestones.deletion_success"))
  1083. }
  1084. c.JSONSuccess(map[string]any{
  1085. "redirect": c.Repo.MakeURL("milestones"),
  1086. })
  1087. }