issue.go 30 KB

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