issue.go 31 KB

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