issue.go 30 KB

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