issue.go 30 KB

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