issue.go 30 KB

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