issue.go 29 KB

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