issue.go 31 KB

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