issue.go 30 KB

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