issue.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287
  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 "unknwon.dev/clog/v2"
  16. "gogs.io/gogs/internal/conf"
  17. "gogs.io/gogs/internal/context"
  18. "gogs.io/gogs/internal/db"
  19. "gogs.io/gogs/internal/db/errors"
  20. "gogs.io/gogs/internal/form"
  21. "gogs.io/gogs/internal/markup"
  22. "gogs.io/gogs/internal/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 := db.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(conf.Server.Subpath+c.Req.RequestURI), 0, conf.Server.Subpath)
  101. c.Redirect(conf.Server.Subpath + "/user/login")
  102. return
  103. }
  104. var (
  105. assigneeID = c.QueryInt64("assignee")
  106. posterID int64
  107. )
  108. filterMode := db.FILTER_MODE_YOUR_REPOS
  109. switch viewType {
  110. case "assigned":
  111. filterMode = db.FILTER_MODE_ASSIGN
  112. assigneeID = c.User.ID
  113. case "created_by":
  114. filterMode = db.FILTER_MODE_CREATE
  115. posterID = c.User.ID
  116. case "mentioned":
  117. filterMode = db.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 := db.GetIssueStats(&db.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, conf.UI.IssuePagingNum, page, 5)
  147. c.Data["Page"] = pager
  148. issues, err := db.Issues(&db.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 == db.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 := db.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 := db.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 = db.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"] = conf.Attachment.Enabled
  224. c.Data["AttachmentAllowedTypes"] = conf.Attachment.AllowedTypes
  225. c.Data["AttachmentMaxSize"] = conf.Attachment.MaxSize
  226. c.Data["AttachmentMaxFiles"] = conf.Attachment.MaxFiles
  227. }
  228. func RetrieveRepoMilestonesAndAssignees(c *context.Context, repo *db.Repository) {
  229. var err error
  230. c.Data["OpenMilestones"], err = db.GetMilestones(repo.ID, -1, false)
  231. if err != nil {
  232. c.Handle(500, "GetMilestones", err)
  233. return
  234. }
  235. c.Data["ClosedMilestones"], err = db.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 *db.Repository) []*db.Label {
  247. if !c.Repo.IsWriter() {
  248. return nil
  249. }
  250. labels, err := db.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. c.Data["title"] = c.Query("title")
  301. c.Data["content"] = c.Query("content")
  302. setTemplateIfExists(c, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates)
  303. renderAttachmentSettings(c)
  304. RetrieveRepoMetas(c, c.Repo.Repository)
  305. if c.Written() {
  306. return
  307. }
  308. c.HTML(200, ISSUE_NEW)
  309. }
  310. func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) {
  311. var (
  312. repo = c.Repo.Repository
  313. err error
  314. )
  315. labels := RetrieveRepoMetas(c, c.Repo.Repository)
  316. if c.Written() {
  317. return nil, 0, 0
  318. }
  319. if !c.Repo.IsWriter() {
  320. return nil, 0, 0
  321. }
  322. // Check labels.
  323. labelIDs := tool.StringsToInt64s(strings.Split(f.LabelIDs, ","))
  324. labelIDMark := tool.Int64sToMap(labelIDs)
  325. hasSelected := false
  326. for i := range labels {
  327. if labelIDMark[labels[i].ID] {
  328. labels[i].IsChecked = true
  329. hasSelected = true
  330. }
  331. }
  332. c.Data["HasSelectedLabel"] = hasSelected
  333. c.Data["label_ids"] = f.LabelIDs
  334. c.Data["Labels"] = labels
  335. // Check milestone.
  336. milestoneID := f.MilestoneID
  337. if milestoneID > 0 {
  338. c.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  339. if err != nil {
  340. c.Handle(500, "GetMilestoneByID", err)
  341. return nil, 0, 0
  342. }
  343. c.Data["milestone_id"] = milestoneID
  344. }
  345. // Check assignee.
  346. assigneeID := f.AssigneeID
  347. if assigneeID > 0 {
  348. c.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID)
  349. if err != nil {
  350. c.Handle(500, "GetAssigneeByID", err)
  351. return nil, 0, 0
  352. }
  353. c.Data["assignee_id"] = assigneeID
  354. }
  355. return labelIDs, milestoneID, assigneeID
  356. }
  357. func NewIssuePost(c *context.Context, f form.NewIssue) {
  358. c.Data["Title"] = c.Tr("repo.issues.new")
  359. c.Data["PageIsIssueList"] = true
  360. c.Data["RequireHighlightJS"] = true
  361. c.Data["RequireSimpleMDE"] = true
  362. renderAttachmentSettings(c)
  363. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
  364. if c.Written() {
  365. return
  366. }
  367. if c.HasError() {
  368. c.HTML(200, ISSUE_NEW)
  369. return
  370. }
  371. var attachments []string
  372. if conf.Attachment.Enabled {
  373. attachments = f.Files
  374. }
  375. issue := &db.Issue{
  376. RepoID: c.Repo.Repository.ID,
  377. Title: f.Title,
  378. PosterID: c.User.ID,
  379. Poster: c.User,
  380. MilestoneID: milestoneID,
  381. AssigneeID: assigneeID,
  382. Content: f.Content,
  383. }
  384. if err := db.NewIssue(c.Repo.Repository, issue, labelIDs, attachments); err != nil {
  385. c.Handle(500, "NewIssue", err)
  386. return
  387. }
  388. log.Trace("Issue created: %d/%d", c.Repo.Repository.ID, issue.ID)
  389. c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index)))
  390. }
  391. func uploadAttachment(c *context.Context, allowedTypes []string) {
  392. file, header, err := c.Req.FormFile("file")
  393. if err != nil {
  394. c.Error(500, fmt.Sprintf("FormFile: %v", err))
  395. return
  396. }
  397. defer file.Close()
  398. buf := make([]byte, 1024)
  399. n, _ := file.Read(buf)
  400. if n > 0 {
  401. buf = buf[:n]
  402. }
  403. fileType := http.DetectContentType(buf)
  404. allowed := false
  405. for _, t := range allowedTypes {
  406. t := strings.Trim(t, " ")
  407. if t == "*/*" || t == fileType {
  408. allowed = true
  409. break
  410. }
  411. }
  412. if !allowed {
  413. c.Error(400, ErrFileTypeForbidden.Error())
  414. return
  415. }
  416. attach, err := db.NewAttachment(header.Filename, buf, file)
  417. if err != nil {
  418. c.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  419. return
  420. }
  421. log.Trace("New attachment uploaded: %s", attach.UUID)
  422. c.JSON(200, map[string]string{
  423. "uuid": attach.UUID,
  424. })
  425. }
  426. func UploadIssueAttachment(c *context.Context) {
  427. if !conf.Attachment.Enabled {
  428. c.NotFound()
  429. return
  430. }
  431. uploadAttachment(c, conf.Attachment.AllowedTypes)
  432. }
  433. func viewIssue(c *context.Context, isPullList bool) {
  434. c.Data["RequireHighlightJS"] = true
  435. c.Data["RequireDropzone"] = true
  436. renderAttachmentSettings(c)
  437. index := c.ParamsInt64(":index")
  438. if index <= 0 {
  439. c.NotFound()
  440. return
  441. }
  442. issue, err := db.GetIssueByIndex(c.Repo.Repository.ID, index)
  443. if err != nil {
  444. c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  445. return
  446. }
  447. c.Data["Title"] = issue.Title
  448. // Make sure type and URL matches.
  449. if !isPullList && issue.IsPull {
  450. c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("pulls/%d", issue.Index)))
  451. return
  452. } else if isPullList && !issue.IsPull {
  453. c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index)))
  454. return
  455. }
  456. if issue.IsPull {
  457. MustAllowPulls(c)
  458. if c.Written() {
  459. return
  460. }
  461. c.Data["PageIsPullList"] = true
  462. c.Data["PageIsPullConversation"] = true
  463. } else {
  464. MustEnableIssues(c)
  465. if c.Written() {
  466. return
  467. }
  468. c.Data["PageIsIssueList"] = true
  469. }
  470. issue.RenderedContent = string(markup.Markdown(issue.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  471. repo := c.Repo.Repository
  472. // Get more information if it's a pull request.
  473. if issue.IsPull {
  474. if issue.PullRequest.HasMerged {
  475. c.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  476. PrepareMergedViewPullInfo(c, issue)
  477. } else {
  478. PrepareViewPullInfo(c, issue)
  479. }
  480. if c.Written() {
  481. return
  482. }
  483. }
  484. // Metas.
  485. // Check labels.
  486. labelIDMark := make(map[int64]bool)
  487. for i := range issue.Labels {
  488. labelIDMark[issue.Labels[i].ID] = true
  489. }
  490. labels, err := db.GetLabelsByRepoID(repo.ID)
  491. if err != nil {
  492. c.Handle(500, "GetLabelsByRepoID", err)
  493. return
  494. }
  495. hasSelected := false
  496. for i := range labels {
  497. if labelIDMark[labels[i].ID] {
  498. labels[i].IsChecked = true
  499. hasSelected = true
  500. }
  501. }
  502. c.Data["HasSelectedLabel"] = hasSelected
  503. c.Data["Labels"] = labels
  504. // Check milestone and assignee.
  505. if c.Repo.IsWriter() {
  506. RetrieveRepoMilestonesAndAssignees(c, repo)
  507. if c.Written() {
  508. return
  509. }
  510. }
  511. if c.IsLogged {
  512. // Update issue-user.
  513. if err = issue.ReadBy(c.User.ID); err != nil {
  514. c.Handle(500, "ReadBy", err)
  515. return
  516. }
  517. }
  518. var (
  519. tag db.CommentTag
  520. ok bool
  521. marked = make(map[int64]db.CommentTag)
  522. comment *db.Comment
  523. participants = make([]*db.User, 1, 10)
  524. )
  525. // Render comments and and fetch participants.
  526. participants[0] = issue.Poster
  527. for _, comment = range issue.Comments {
  528. if comment.Type == db.COMMENT_TYPE_COMMENT {
  529. comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  530. // Check tag.
  531. tag, ok = marked[comment.PosterID]
  532. if ok {
  533. comment.ShowTag = tag
  534. continue
  535. }
  536. if repo.IsOwnedBy(comment.PosterID) ||
  537. (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
  538. comment.ShowTag = db.COMMENT_TAG_OWNER
  539. } else if comment.Poster.IsWriterOfRepo(repo) {
  540. comment.ShowTag = db.COMMENT_TAG_WRITER
  541. } else if comment.PosterID == issue.PosterID {
  542. comment.ShowTag = db.COMMENT_TAG_POSTER
  543. }
  544. marked[comment.PosterID] = comment.ShowTag
  545. isAdded := false
  546. for j := range participants {
  547. if comment.Poster == participants[j] {
  548. isAdded = true
  549. break
  550. }
  551. }
  552. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  553. participants = append(participants, comment.Poster)
  554. }
  555. }
  556. }
  557. if issue.IsPull && issue.PullRequest.HasMerged {
  558. pull := issue.PullRequest
  559. branchProtected := false
  560. protectBranch, err := db.GetProtectBranchOfRepoByName(pull.BaseRepoID, pull.HeadBranch)
  561. if err != nil {
  562. if !errors.IsErrBranchNotExist(err) {
  563. c.ServerError("GetProtectBranchOfRepoByName", err)
  564. return
  565. }
  566. } else {
  567. branchProtected = protectBranch.Protected
  568. }
  569. c.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID &&
  570. c.Repo.IsWriter() && c.Repo.GitRepo.IsBranchExist(pull.HeadBranch) &&
  571. !branchProtected
  572. c.Data["DeleteBranchLink"] = c.Repo.MakeURL(url.URL{
  573. Path: "branches/delete/" + pull.HeadBranch,
  574. RawQuery: fmt.Sprintf("commit=%s&redirect_to=%s", pull.MergedCommitID, c.Data["Link"]),
  575. })
  576. }
  577. c.Data["Participants"] = participants
  578. c.Data["NumParticipants"] = len(participants)
  579. c.Data["Issue"] = issue
  580. c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))
  581. c.Data["SignInLink"] = conf.Server.Subpath + "/user/login?redirect_to=" + c.Data["Link"].(string)
  582. c.HTML(200, ISSUE_VIEW)
  583. }
  584. func ViewIssue(c *context.Context) {
  585. viewIssue(c, false)
  586. }
  587. func ViewPull(c *context.Context) {
  588. viewIssue(c, true)
  589. }
  590. func getActionIssue(c *context.Context) *db.Issue {
  591. issue, err := db.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
  592. if err != nil {
  593. c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  594. return nil
  595. }
  596. // Prevent guests accessing pull requests
  597. if !c.Repo.HasAccess() && issue.IsPull {
  598. c.NotFound()
  599. return nil
  600. }
  601. return issue
  602. }
  603. func UpdateIssueTitle(c *context.Context) {
  604. issue := getActionIssue(c)
  605. if c.Written() {
  606. return
  607. }
  608. if !c.IsLogged || (!issue.IsPoster(c.User.ID) && !c.Repo.IsWriter()) {
  609. c.Error(403)
  610. return
  611. }
  612. title := c.QueryTrim("title")
  613. if len(title) == 0 {
  614. c.Error(204)
  615. return
  616. }
  617. if err := issue.ChangeTitle(c.User, title); err != nil {
  618. c.Handle(500, "ChangeTitle", err)
  619. return
  620. }
  621. c.JSON(200, map[string]interface{}{
  622. "title": issue.Title,
  623. })
  624. }
  625. func UpdateIssueContent(c *context.Context) {
  626. issue := getActionIssue(c)
  627. if c.Written() {
  628. return
  629. }
  630. if !c.IsLogged || (c.User.ID != issue.PosterID && !c.Repo.IsWriter()) {
  631. c.Error(403)
  632. return
  633. }
  634. content := c.Query("content")
  635. if err := issue.ChangeContent(c.User, content); err != nil {
  636. c.Handle(500, "ChangeContent", err)
  637. return
  638. }
  639. c.JSON(200, map[string]string{
  640. "content": string(markup.Markdown(issue.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  641. })
  642. }
  643. func UpdateIssueLabel(c *context.Context) {
  644. issue := getActionIssue(c)
  645. if c.Written() {
  646. return
  647. }
  648. if c.Query("action") == "clear" {
  649. if err := issue.ClearLabels(c.User); err != nil {
  650. c.Handle(500, "ClearLabels", err)
  651. return
  652. }
  653. } else {
  654. isAttach := c.Query("action") == "attach"
  655. label, err := db.GetLabelOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id"))
  656. if err != nil {
  657. if db.IsErrLabelNotExist(err) {
  658. c.Error(404, "GetLabelByID")
  659. } else {
  660. c.Handle(500, "GetLabelByID", err)
  661. }
  662. return
  663. }
  664. if isAttach && !issue.HasLabel(label.ID) {
  665. if err = issue.AddLabel(c.User, label); err != nil {
  666. c.Handle(500, "AddLabel", err)
  667. return
  668. }
  669. } else if !isAttach && issue.HasLabel(label.ID) {
  670. if err = issue.RemoveLabel(c.User, label); err != nil {
  671. c.Handle(500, "RemoveLabel", err)
  672. return
  673. }
  674. }
  675. }
  676. c.JSON(200, map[string]interface{}{
  677. "ok": true,
  678. })
  679. }
  680. func UpdateIssueMilestone(c *context.Context) {
  681. issue := getActionIssue(c)
  682. if c.Written() {
  683. return
  684. }
  685. oldMilestoneID := issue.MilestoneID
  686. milestoneID := c.QueryInt64("id")
  687. if oldMilestoneID == milestoneID {
  688. c.JSON(200, map[string]interface{}{
  689. "ok": true,
  690. })
  691. return
  692. }
  693. // Not check for invalid milestone id and give responsibility to owners.
  694. issue.MilestoneID = milestoneID
  695. if err := db.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil {
  696. c.Handle(500, "ChangeMilestoneAssign", err)
  697. return
  698. }
  699. c.JSON(200, map[string]interface{}{
  700. "ok": true,
  701. })
  702. }
  703. func UpdateIssueAssignee(c *context.Context) {
  704. issue := getActionIssue(c)
  705. if c.Written() {
  706. return
  707. }
  708. assigneeID := c.QueryInt64("id")
  709. if issue.AssigneeID == assigneeID {
  710. c.JSON(200, map[string]interface{}{
  711. "ok": true,
  712. })
  713. return
  714. }
  715. if err := issue.ChangeAssignee(c.User, assigneeID); err != nil {
  716. c.Handle(500, "ChangeAssignee", err)
  717. return
  718. }
  719. c.JSON(200, map[string]interface{}{
  720. "ok": true,
  721. })
  722. }
  723. func NewComment(c *context.Context, f form.CreateComment) {
  724. issue := getActionIssue(c)
  725. if c.Written() {
  726. return
  727. }
  728. var attachments []string
  729. if conf.Attachment.Enabled {
  730. attachments = f.Files
  731. }
  732. if c.HasError() {
  733. c.Flash.Error(c.Data["ErrorMsg"].(string))
  734. c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index)))
  735. return
  736. }
  737. var err error
  738. var comment *db.Comment
  739. defer func() {
  740. // Check if issue admin/poster changes the status of issue.
  741. if (c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))) &&
  742. (f.Status == "reopen" || f.Status == "close") &&
  743. !(issue.IsPull && issue.PullRequest.HasMerged) {
  744. // Duplication and conflict check should apply to reopen pull request.
  745. var pr *db.PullRequest
  746. if f.Status == "reopen" && issue.IsPull {
  747. pull := issue.PullRequest
  748. pr, err = db.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  749. if err != nil {
  750. if !db.IsErrPullRequestNotExist(err) {
  751. c.ServerError("GetUnmergedPullRequest", err)
  752. return
  753. }
  754. }
  755. // Regenerate patch and test conflict.
  756. if pr == nil {
  757. if err = issue.PullRequest.UpdatePatch(); err != nil {
  758. c.ServerError("UpdatePatch", err)
  759. return
  760. }
  761. issue.PullRequest.AddToTaskQueue()
  762. }
  763. }
  764. if pr != nil {
  765. c.Flash.Info(c.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  766. } else {
  767. if err = issue.ChangeStatus(c.User, c.Repo.Repository, f.Status == "close"); err != nil {
  768. log.Error("ChangeStatus: %v", err)
  769. } else {
  770. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  771. }
  772. }
  773. }
  774. // Redirect to comment hashtag if there is any actual content.
  775. typeName := "issues"
  776. if issue.IsPull {
  777. typeName = "pulls"
  778. }
  779. location := url.URL{
  780. Path: fmt.Sprintf("%s/%d", typeName, issue.Index),
  781. }
  782. if comment != nil {
  783. location.Fragment = comment.HashTag()
  784. }
  785. c.RawRedirect(c.Repo.MakeURL(location))
  786. }()
  787. // Fix #321: Allow empty comments, as long as we have attachments.
  788. if len(f.Content) == 0 && len(attachments) == 0 {
  789. return
  790. }
  791. comment, err = db.CreateIssueComment(c.User, c.Repo.Repository, issue, f.Content, attachments)
  792. if err != nil {
  793. c.ServerError("CreateIssueComment", err)
  794. return
  795. }
  796. log.Trace("Comment created: %d/%d/%d", c.Repo.Repository.ID, issue.ID, comment.ID)
  797. }
  798. func UpdateCommentContent(c *context.Context) {
  799. comment, err := db.GetCommentByID(c.ParamsInt64(":id"))
  800. if err != nil {
  801. c.NotFoundOrServerError("GetCommentByID", db.IsErrCommentNotExist, err)
  802. return
  803. }
  804. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  805. c.Error(404)
  806. return
  807. } else if comment.Type != db.COMMENT_TYPE_COMMENT {
  808. c.Error(204)
  809. return
  810. }
  811. oldContent := comment.Content
  812. comment.Content = c.Query("content")
  813. if len(comment.Content) == 0 {
  814. c.JSON(200, map[string]interface{}{
  815. "content": "",
  816. })
  817. return
  818. }
  819. if err = db.UpdateComment(c.User, comment, oldContent); err != nil {
  820. c.Handle(500, "UpdateComment", err)
  821. return
  822. }
  823. c.JSON(200, map[string]string{
  824. "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  825. })
  826. }
  827. func DeleteComment(c *context.Context) {
  828. comment, err := db.GetCommentByID(c.ParamsInt64(":id"))
  829. if err != nil {
  830. c.NotFoundOrServerError("GetCommentByID", db.IsErrCommentNotExist, err)
  831. return
  832. }
  833. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  834. c.Error(404)
  835. return
  836. } else if comment.Type != db.COMMENT_TYPE_COMMENT {
  837. c.Error(204)
  838. return
  839. }
  840. if err = db.DeleteCommentByID(c.User, comment.ID); err != nil {
  841. c.Handle(500, "DeleteCommentByID", err)
  842. return
  843. }
  844. c.Status(200)
  845. }
  846. func Labels(c *context.Context) {
  847. c.Data["Title"] = c.Tr("repo.labels")
  848. c.Data["PageIsIssueList"] = true
  849. c.Data["PageIsLabels"] = true
  850. c.Data["RequireMinicolors"] = true
  851. c.Data["LabelTemplates"] = db.LabelTemplates
  852. c.HTML(200, LABELS)
  853. }
  854. func InitializeLabels(c *context.Context, f form.InitializeLabels) {
  855. if c.HasError() {
  856. c.RawRedirect(c.Repo.MakeURL("labels"))
  857. return
  858. }
  859. list, err := db.GetLabelTemplateFile(f.TemplateName)
  860. if err != nil {
  861. c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err))
  862. c.RawRedirect(c.Repo.MakeURL("labels"))
  863. return
  864. }
  865. labels := make([]*db.Label, len(list))
  866. for i := 0; i < len(list); i++ {
  867. labels[i] = &db.Label{
  868. RepoID: c.Repo.Repository.ID,
  869. Name: list[i][0],
  870. Color: list[i][1],
  871. }
  872. }
  873. if err := db.NewLabels(labels...); err != nil {
  874. c.Handle(500, "NewLabels", err)
  875. return
  876. }
  877. c.RawRedirect(c.Repo.MakeURL("labels"))
  878. }
  879. func NewLabel(c *context.Context, f form.CreateLabel) {
  880. c.Data["Title"] = c.Tr("repo.labels")
  881. c.Data["PageIsLabels"] = true
  882. if c.HasError() {
  883. c.Flash.Error(c.Data["ErrorMsg"].(string))
  884. c.RawRedirect(c.Repo.MakeURL("labels"))
  885. return
  886. }
  887. l := &db.Label{
  888. RepoID: c.Repo.Repository.ID,
  889. Name: f.Title,
  890. Color: f.Color,
  891. }
  892. if err := db.NewLabels(l); err != nil {
  893. c.Handle(500, "NewLabel", err)
  894. return
  895. }
  896. c.RawRedirect(c.Repo.MakeURL("labels"))
  897. }
  898. func UpdateLabel(c *context.Context, f form.CreateLabel) {
  899. l, err := db.GetLabelByID(f.ID)
  900. if err != nil {
  901. switch {
  902. case db.IsErrLabelNotExist(err):
  903. c.Error(404)
  904. default:
  905. c.Handle(500, "UpdateLabel", err)
  906. }
  907. return
  908. }
  909. l.Name = f.Title
  910. l.Color = f.Color
  911. if err := db.UpdateLabel(l); err != nil {
  912. c.Handle(500, "UpdateLabel", err)
  913. return
  914. }
  915. c.RawRedirect(c.Repo.MakeURL("labels"))
  916. }
  917. func DeleteLabel(c *context.Context) {
  918. if err := db.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  919. c.Flash.Error("DeleteLabel: " + err.Error())
  920. } else {
  921. c.Flash.Success(c.Tr("repo.issues.label_deletion_success"))
  922. }
  923. c.JSONSuccess(map[string]interface{}{
  924. "redirect": c.Repo.MakeURL("labels"),
  925. })
  926. }
  927. func Milestones(c *context.Context) {
  928. c.Data["Title"] = c.Tr("repo.milestones")
  929. c.Data["PageIsIssueList"] = true
  930. c.Data["PageIsMilestones"] = true
  931. isShowClosed := c.Query("state") == "closed"
  932. openCount, closedCount := db.MilestoneStats(c.Repo.Repository.ID)
  933. c.Data["OpenCount"] = openCount
  934. c.Data["ClosedCount"] = closedCount
  935. page := c.QueryInt("page")
  936. if page <= 1 {
  937. page = 1
  938. }
  939. var total int
  940. if !isShowClosed {
  941. total = int(openCount)
  942. } else {
  943. total = int(closedCount)
  944. }
  945. c.Data["Page"] = paginater.New(total, conf.UI.IssuePagingNum, page, 5)
  946. miles, err := db.GetMilestones(c.Repo.Repository.ID, page, isShowClosed)
  947. if err != nil {
  948. c.Handle(500, "GetMilestones", err)
  949. return
  950. }
  951. for _, m := range miles {
  952. m.NumOpenIssues = int(m.CountIssues(false, false))
  953. m.NumClosedIssues = int(m.CountIssues(true, false))
  954. if m.NumOpenIssues+m.NumClosedIssues > 0 {
  955. m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues)
  956. }
  957. m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  958. }
  959. c.Data["Milestones"] = miles
  960. if isShowClosed {
  961. c.Data["State"] = "closed"
  962. } else {
  963. c.Data["State"] = "open"
  964. }
  965. c.Data["IsShowClosed"] = isShowClosed
  966. c.HTML(200, MILESTONE)
  967. }
  968. func NewMilestone(c *context.Context) {
  969. c.Data["Title"] = c.Tr("repo.milestones.new")
  970. c.Data["PageIsIssueList"] = true
  971. c.Data["PageIsMilestones"] = true
  972. c.Data["RequireDatetimepicker"] = true
  973. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  974. c.HTML(200, MILESTONE_NEW)
  975. }
  976. func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
  977. c.Data["Title"] = c.Tr("repo.milestones.new")
  978. c.Data["PageIsIssueList"] = true
  979. c.Data["PageIsMilestones"] = true
  980. c.Data["RequireDatetimepicker"] = true
  981. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  982. if c.HasError() {
  983. c.HTML(200, MILESTONE_NEW)
  984. return
  985. }
  986. if len(f.Deadline) == 0 {
  987. f.Deadline = "9999-12-31"
  988. }
  989. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  990. if err != nil {
  991. c.Data["Err_Deadline"] = true
  992. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  993. return
  994. }
  995. if err = db.NewMilestone(&db.Milestone{
  996. RepoID: c.Repo.Repository.ID,
  997. Name: f.Title,
  998. Content: f.Content,
  999. Deadline: deadline,
  1000. }); err != nil {
  1001. c.Handle(500, "NewMilestone", err)
  1002. return
  1003. }
  1004. c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title))
  1005. c.RawRedirect(c.Repo.MakeURL("milestones"))
  1006. }
  1007. func EditMilestone(c *context.Context) {
  1008. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1009. c.Data["PageIsMilestones"] = true
  1010. c.Data["PageIsEditMilestone"] = true
  1011. c.Data["RequireDatetimepicker"] = true
  1012. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  1013. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1014. if err != nil {
  1015. if db.IsErrMilestoneNotExist(err) {
  1016. c.Handle(404, "", nil)
  1017. } else {
  1018. c.Handle(500, "GetMilestoneByRepoID", err)
  1019. }
  1020. return
  1021. }
  1022. c.Data["title"] = m.Name
  1023. c.Data["content"] = m.Content
  1024. if len(m.DeadlineString) > 0 {
  1025. c.Data["deadline"] = m.DeadlineString
  1026. }
  1027. c.HTML(200, MILESTONE_NEW)
  1028. }
  1029. func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
  1030. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1031. c.Data["PageIsMilestones"] = true
  1032. c.Data["PageIsEditMilestone"] = true
  1033. c.Data["RequireDatetimepicker"] = true
  1034. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  1035. if c.HasError() {
  1036. c.HTML(200, MILESTONE_NEW)
  1037. return
  1038. }
  1039. if len(f.Deadline) == 0 {
  1040. f.Deadline = "9999-12-31"
  1041. }
  1042. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  1043. if err != nil {
  1044. c.Data["Err_Deadline"] = true
  1045. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  1046. return
  1047. }
  1048. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1049. if err != nil {
  1050. if db.IsErrMilestoneNotExist(err) {
  1051. c.Handle(404, "", nil)
  1052. } else {
  1053. c.Handle(500, "GetMilestoneByRepoID", err)
  1054. }
  1055. return
  1056. }
  1057. m.Name = f.Title
  1058. m.Content = f.Content
  1059. m.Deadline = deadline
  1060. if err = db.UpdateMilestone(m); err != nil {
  1061. c.Handle(500, "UpdateMilestone", err)
  1062. return
  1063. }
  1064. c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name))
  1065. c.RawRedirect(c.Repo.MakeURL("milestones"))
  1066. }
  1067. func ChangeMilestonStatus(c *context.Context) {
  1068. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1069. if err != nil {
  1070. if db.IsErrMilestoneNotExist(err) {
  1071. c.Handle(404, "", err)
  1072. } else {
  1073. c.Handle(500, "GetMilestoneByRepoID", err)
  1074. }
  1075. return
  1076. }
  1077. location := url.URL{
  1078. Path: "milestones",
  1079. }
  1080. switch c.Params(":action") {
  1081. case "open":
  1082. if m.IsClosed {
  1083. if err = db.ChangeMilestoneStatus(m, false); err != nil {
  1084. c.Handle(500, "ChangeMilestoneStatus", err)
  1085. return
  1086. }
  1087. }
  1088. location.RawQuery = "state=open"
  1089. case "close":
  1090. if !m.IsClosed {
  1091. m.ClosedDate = time.Now()
  1092. if err = db.ChangeMilestoneStatus(m, true); err != nil {
  1093. c.Handle(500, "ChangeMilestoneStatus", err)
  1094. return
  1095. }
  1096. }
  1097. location.RawQuery = "state=closed"
  1098. }
  1099. c.RawRedirect(c.Repo.MakeURL(location))
  1100. }
  1101. func DeleteMilestone(c *context.Context) {
  1102. if err := db.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.MakeURL("milestones"),
  1109. })
  1110. }