issue.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  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.Handle(404, "MustEnableIssues", nil)
  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.Handle(404, "MustAllowPulls", nil)
  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.Handle(500, "RetrieveLabels.GetLabels", err)
  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.Handle(500, "Issues", err)
  161. return
  162. }
  163. // Get issue-user relations.
  164. pairs, err := db.GetIssueUsers(repo.ID, posterID, isShowClosed)
  165. if err != nil {
  166. c.Handle(500, "GetIssueUsers", err)
  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.Handle(500, "GetAllRepoMilestones", err)
  188. return
  189. }
  190. // Get assignees.
  191. c.Data["Assignees"], err = repo.GetAssignees()
  192. if err != nil {
  193. c.Handle(500, "GetAssignees", err)
  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.HTML(200, 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.Handle(500, "GetMilestones", err)
  231. return
  232. }
  233. c.Data["ClosedMilestones"], err = db.GetMilestones(repo.ID, -1, true)
  234. if err != nil {
  235. c.Handle(500, "GetMilestones", err)
  236. return
  237. }
  238. c.Data["Assignees"], err = repo.GetAssignees()
  239. if err != nil {
  240. c.Handle(500, "GetAssignees", err)
  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.Handle(500, "GetLabelsByRepoID", err)
  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.HTML(200, 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.Handle(500, "GetMilestoneByID", err)
  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.Handle(500, "GetAssigneeByID", err)
  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.HTML(200, 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.Handle(500, "NewIssue", err)
  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(500, fmt.Sprintf("FormFile: %v", err))
  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.Error(400, ErrFileTypeForbidden.Error())
  406. return
  407. }
  408. attach, err := db.NewAttachment(header.Filename, buf, file)
  409. if err != nil {
  410. c.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  411. return
  412. }
  413. log.Trace("New attachment uploaded: %s", attach.UUID)
  414. c.JSON(200, 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.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  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.Handle(500, "GetLabelsByRepoID", err)
  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.Handle(500, "ReadBy", err)
  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 !errors.IsErrBranchNotExist(err) {
  555. c.ServerError("GetProtectBranchOfRepoByName", err)
  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.HTML(200, 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.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  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.Error(403)
  602. return
  603. }
  604. title := c.QueryTrim("title")
  605. if len(title) == 0 {
  606. c.Error(204)
  607. return
  608. }
  609. if err := issue.ChangeTitle(c.User, title); err != nil {
  610. c.Handle(500, "ChangeTitle", err)
  611. return
  612. }
  613. c.JSON(200, 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.Error(403)
  624. return
  625. }
  626. content := c.Query("content")
  627. if err := issue.ChangeContent(c.User, content); err != nil {
  628. c.Handle(500, "ChangeContent", err)
  629. return
  630. }
  631. c.JSON(200, 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.Handle(500, "ClearLabels", err)
  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. if db.IsErrLabelNotExist(err) {
  650. c.Error(404, "GetLabelByID")
  651. } else {
  652. c.Handle(500, "GetLabelByID", err)
  653. }
  654. return
  655. }
  656. if isAttach && !issue.HasLabel(label.ID) {
  657. if err = issue.AddLabel(c.User, label); err != nil {
  658. c.Handle(500, "AddLabel", err)
  659. return
  660. }
  661. } else if !isAttach && issue.HasLabel(label.ID) {
  662. if err = issue.RemoveLabel(c.User, label); err != nil {
  663. c.Handle(500, "RemoveLabel", err)
  664. return
  665. }
  666. }
  667. }
  668. c.JSON(200, map[string]interface{}{
  669. "ok": true,
  670. })
  671. }
  672. func UpdateIssueMilestone(c *context.Context) {
  673. issue := getActionIssue(c)
  674. if c.Written() {
  675. return
  676. }
  677. oldMilestoneID := issue.MilestoneID
  678. milestoneID := c.QueryInt64("id")
  679. if oldMilestoneID == milestoneID {
  680. c.JSON(200, map[string]interface{}{
  681. "ok": true,
  682. })
  683. return
  684. }
  685. // Not check for invalid milestone id and give responsibility to owners.
  686. issue.MilestoneID = milestoneID
  687. if err := db.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil {
  688. c.Handle(500, "ChangeMilestoneAssign", err)
  689. return
  690. }
  691. c.JSON(200, map[string]interface{}{
  692. "ok": true,
  693. })
  694. }
  695. func UpdateIssueAssignee(c *context.Context) {
  696. issue := getActionIssue(c)
  697. if c.Written() {
  698. return
  699. }
  700. assigneeID := c.QueryInt64("id")
  701. if issue.AssigneeID == assigneeID {
  702. c.JSON(200, map[string]interface{}{
  703. "ok": true,
  704. })
  705. return
  706. }
  707. if err := issue.ChangeAssignee(c.User, assigneeID); err != nil {
  708. c.Handle(500, "ChangeAssignee", err)
  709. return
  710. }
  711. c.JSON(200, map[string]interface{}{
  712. "ok": true,
  713. })
  714. }
  715. func NewComment(c *context.Context, f form.CreateComment) {
  716. issue := getActionIssue(c)
  717. if c.Written() {
  718. return
  719. }
  720. var attachments []string
  721. if conf.Attachment.Enabled {
  722. attachments = f.Files
  723. }
  724. if c.HasError() {
  725. c.Flash.Error(c.Data["ErrorMsg"].(string))
  726. c.RawRedirect(c.Repo.MakeURL(fmt.Sprintf("issues/%d", issue.Index)))
  727. return
  728. }
  729. var err error
  730. var comment *db.Comment
  731. defer func() {
  732. // Check if issue admin/poster changes the status of issue.
  733. if (c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))) &&
  734. (f.Status == "reopen" || f.Status == "close") &&
  735. !(issue.IsPull && issue.PullRequest.HasMerged) {
  736. // Duplication and conflict check should apply to reopen pull request.
  737. var pr *db.PullRequest
  738. if f.Status == "reopen" && issue.IsPull {
  739. pull := issue.PullRequest
  740. pr, err = db.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  741. if err != nil {
  742. if !db.IsErrPullRequestNotExist(err) {
  743. c.ServerError("GetUnmergedPullRequest", err)
  744. return
  745. }
  746. }
  747. // Regenerate patch and test conflict.
  748. if pr == nil {
  749. if err = issue.PullRequest.UpdatePatch(); err != nil {
  750. c.ServerError("UpdatePatch", err)
  751. return
  752. }
  753. issue.PullRequest.AddToTaskQueue()
  754. }
  755. }
  756. if pr != nil {
  757. c.Flash.Info(c.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  758. } else {
  759. if err = issue.ChangeStatus(c.User, c.Repo.Repository, f.Status == "close"); err != nil {
  760. log.Error("ChangeStatus: %v", err)
  761. } else {
  762. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  763. }
  764. }
  765. }
  766. // Redirect to comment hashtag if there is any actual content.
  767. typeName := "issues"
  768. if issue.IsPull {
  769. typeName = "pulls"
  770. }
  771. location := url.URL{
  772. Path: fmt.Sprintf("%s/%d", typeName, issue.Index),
  773. }
  774. if comment != nil {
  775. location.Fragment = comment.HashTag()
  776. }
  777. c.RawRedirect(c.Repo.MakeURL(location))
  778. }()
  779. // Fix #321: Allow empty comments, as long as we have attachments.
  780. if len(f.Content) == 0 && len(attachments) == 0 {
  781. return
  782. }
  783. comment, err = db.CreateIssueComment(c.User, c.Repo.Repository, issue, f.Content, attachments)
  784. if err != nil {
  785. c.ServerError("CreateIssueComment", err)
  786. return
  787. }
  788. log.Trace("Comment created: %d/%d/%d", c.Repo.Repository.ID, issue.ID, comment.ID)
  789. }
  790. func UpdateCommentContent(c *context.Context) {
  791. comment, err := db.GetCommentByID(c.ParamsInt64(":id"))
  792. if err != nil {
  793. c.NotFoundOrServerError("GetCommentByID", db.IsErrCommentNotExist, err)
  794. return
  795. }
  796. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  797. c.Error(404)
  798. return
  799. } else if comment.Type != db.COMMENT_TYPE_COMMENT {
  800. c.Error(204)
  801. return
  802. }
  803. oldContent := comment.Content
  804. comment.Content = c.Query("content")
  805. if len(comment.Content) == 0 {
  806. c.JSON(200, map[string]interface{}{
  807. "content": "",
  808. })
  809. return
  810. }
  811. if err = db.UpdateComment(c.User, comment, oldContent); err != nil {
  812. c.Handle(500, "UpdateComment", err)
  813. return
  814. }
  815. c.JSON(200, map[string]string{
  816. "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  817. })
  818. }
  819. func DeleteComment(c *context.Context) {
  820. comment, err := db.GetCommentByID(c.ParamsInt64(":id"))
  821. if err != nil {
  822. c.NotFoundOrServerError("GetCommentByID", db.IsErrCommentNotExist, err)
  823. return
  824. }
  825. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  826. c.Error(404)
  827. return
  828. } else if comment.Type != db.COMMENT_TYPE_COMMENT {
  829. c.Error(204)
  830. return
  831. }
  832. if err = db.DeleteCommentByID(c.User, comment.ID); err != nil {
  833. c.Handle(500, "DeleteCommentByID", err)
  834. return
  835. }
  836. c.Status(200)
  837. }
  838. func Labels(c *context.Context) {
  839. c.Data["Title"] = c.Tr("repo.labels")
  840. c.Data["PageIsIssueList"] = true
  841. c.Data["PageIsLabels"] = true
  842. c.Data["RequireMinicolors"] = true
  843. c.Data["LabelTemplates"] = db.LabelTemplates
  844. c.HTML(200, LABELS)
  845. }
  846. func InitializeLabels(c *context.Context, f form.InitializeLabels) {
  847. if c.HasError() {
  848. c.RawRedirect(c.Repo.MakeURL("labels"))
  849. return
  850. }
  851. list, err := db.GetLabelTemplateFile(f.TemplateName)
  852. if err != nil {
  853. c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err))
  854. c.RawRedirect(c.Repo.MakeURL("labels"))
  855. return
  856. }
  857. labels := make([]*db.Label, len(list))
  858. for i := 0; i < len(list); i++ {
  859. labels[i] = &db.Label{
  860. RepoID: c.Repo.Repository.ID,
  861. Name: list[i][0],
  862. Color: list[i][1],
  863. }
  864. }
  865. if err := db.NewLabels(labels...); err != nil {
  866. c.Handle(500, "NewLabels", err)
  867. return
  868. }
  869. c.RawRedirect(c.Repo.MakeURL("labels"))
  870. }
  871. func NewLabel(c *context.Context, f form.CreateLabel) {
  872. c.Data["Title"] = c.Tr("repo.labels")
  873. c.Data["PageIsLabels"] = true
  874. if c.HasError() {
  875. c.Flash.Error(c.Data["ErrorMsg"].(string))
  876. c.RawRedirect(c.Repo.MakeURL("labels"))
  877. return
  878. }
  879. l := &db.Label{
  880. RepoID: c.Repo.Repository.ID,
  881. Name: f.Title,
  882. Color: f.Color,
  883. }
  884. if err := db.NewLabels(l); err != nil {
  885. c.Handle(500, "NewLabel", err)
  886. return
  887. }
  888. c.RawRedirect(c.Repo.MakeURL("labels"))
  889. }
  890. func UpdateLabel(c *context.Context, f form.CreateLabel) {
  891. l, err := db.GetLabelByID(f.ID)
  892. if err != nil {
  893. switch {
  894. case db.IsErrLabelNotExist(err):
  895. c.Error(404)
  896. default:
  897. c.Handle(500, "UpdateLabel", err)
  898. }
  899. return
  900. }
  901. l.Name = f.Title
  902. l.Color = f.Color
  903. if err := db.UpdateLabel(l); err != nil {
  904. c.Handle(500, "UpdateLabel", err)
  905. return
  906. }
  907. c.RawRedirect(c.Repo.MakeURL("labels"))
  908. }
  909. func DeleteLabel(c *context.Context) {
  910. if err := db.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  911. c.Flash.Error("DeleteLabel: " + err.Error())
  912. } else {
  913. c.Flash.Success(c.Tr("repo.issues.label_deletion_success"))
  914. }
  915. c.JSONSuccess(map[string]interface{}{
  916. "redirect": c.Repo.MakeURL("labels"),
  917. })
  918. }
  919. func Milestones(c *context.Context) {
  920. c.Data["Title"] = c.Tr("repo.milestones")
  921. c.Data["PageIsIssueList"] = true
  922. c.Data["PageIsMilestones"] = true
  923. isShowClosed := c.Query("state") == "closed"
  924. openCount, closedCount := db.MilestoneStats(c.Repo.Repository.ID)
  925. c.Data["OpenCount"] = openCount
  926. c.Data["ClosedCount"] = closedCount
  927. page := c.QueryInt("page")
  928. if page <= 1 {
  929. page = 1
  930. }
  931. var total int
  932. if !isShowClosed {
  933. total = int(openCount)
  934. } else {
  935. total = int(closedCount)
  936. }
  937. c.Data["Page"] = paginater.New(total, conf.UI.IssuePagingNum, page, 5)
  938. miles, err := db.GetMilestones(c.Repo.Repository.ID, page, isShowClosed)
  939. if err != nil {
  940. c.Handle(500, "GetMilestones", err)
  941. return
  942. }
  943. for _, m := range miles {
  944. m.NumOpenIssues = int(m.CountIssues(false, false))
  945. m.NumClosedIssues = int(m.CountIssues(true, false))
  946. if m.NumOpenIssues+m.NumClosedIssues > 0 {
  947. m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues)
  948. }
  949. m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  950. }
  951. c.Data["Milestones"] = miles
  952. if isShowClosed {
  953. c.Data["State"] = "closed"
  954. } else {
  955. c.Data["State"] = "open"
  956. }
  957. c.Data["IsShowClosed"] = isShowClosed
  958. c.HTML(200, MILESTONE)
  959. }
  960. func NewMilestone(c *context.Context) {
  961. c.Data["Title"] = c.Tr("repo.milestones.new")
  962. c.Data["PageIsIssueList"] = true
  963. c.Data["PageIsMilestones"] = true
  964. c.Data["RequireDatetimepicker"] = true
  965. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  966. c.HTML(200, MILESTONE_NEW)
  967. }
  968. func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
  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. if c.HasError() {
  975. c.HTML(200, MILESTONE_NEW)
  976. return
  977. }
  978. if len(f.Deadline) == 0 {
  979. f.Deadline = "9999-12-31"
  980. }
  981. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  982. if err != nil {
  983. c.Data["Err_Deadline"] = true
  984. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  985. return
  986. }
  987. if err = db.NewMilestone(&db.Milestone{
  988. RepoID: c.Repo.Repository.ID,
  989. Name: f.Title,
  990. Content: f.Content,
  991. Deadline: deadline,
  992. }); err != nil {
  993. c.Handle(500, "NewMilestone", err)
  994. return
  995. }
  996. c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title))
  997. c.RawRedirect(c.Repo.MakeURL("milestones"))
  998. }
  999. func EditMilestone(c *context.Context) {
  1000. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1001. c.Data["PageIsMilestones"] = true
  1002. c.Data["PageIsEditMilestone"] = true
  1003. c.Data["RequireDatetimepicker"] = true
  1004. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  1005. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1006. if err != nil {
  1007. if db.IsErrMilestoneNotExist(err) {
  1008. c.Handle(404, "", nil)
  1009. } else {
  1010. c.Handle(500, "GetMilestoneByRepoID", err)
  1011. }
  1012. return
  1013. }
  1014. c.Data["title"] = m.Name
  1015. c.Data["content"] = m.Content
  1016. if len(m.DeadlineString) > 0 {
  1017. c.Data["deadline"] = m.DeadlineString
  1018. }
  1019. c.HTML(200, MILESTONE_NEW)
  1020. }
  1021. func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
  1022. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1023. c.Data["PageIsMilestones"] = true
  1024. c.Data["PageIsEditMilestone"] = true
  1025. c.Data["RequireDatetimepicker"] = true
  1026. c.Data["DateLang"] = conf.I18n.DateLang(c.Locale.Language())
  1027. if c.HasError() {
  1028. c.HTML(200, MILESTONE_NEW)
  1029. return
  1030. }
  1031. if len(f.Deadline) == 0 {
  1032. f.Deadline = "9999-12-31"
  1033. }
  1034. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  1035. if err != nil {
  1036. c.Data["Err_Deadline"] = true
  1037. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  1038. return
  1039. }
  1040. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1041. if err != nil {
  1042. if db.IsErrMilestoneNotExist(err) {
  1043. c.Handle(404, "", nil)
  1044. } else {
  1045. c.Handle(500, "GetMilestoneByRepoID", err)
  1046. }
  1047. return
  1048. }
  1049. m.Name = f.Title
  1050. m.Content = f.Content
  1051. m.Deadline = deadline
  1052. if err = db.UpdateMilestone(m); err != nil {
  1053. c.Handle(500, "UpdateMilestone", err)
  1054. return
  1055. }
  1056. c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name))
  1057. c.RawRedirect(c.Repo.MakeURL("milestones"))
  1058. }
  1059. func ChangeMilestonStatus(c *context.Context) {
  1060. m, err := db.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1061. if err != nil {
  1062. if db.IsErrMilestoneNotExist(err) {
  1063. c.Handle(404, "", err)
  1064. } else {
  1065. c.Handle(500, "GetMilestoneByRepoID", err)
  1066. }
  1067. return
  1068. }
  1069. location := url.URL{
  1070. Path: "milestones",
  1071. }
  1072. switch c.Params(":action") {
  1073. case "open":
  1074. if m.IsClosed {
  1075. if err = db.ChangeMilestoneStatus(m, false); err != nil {
  1076. c.Handle(500, "ChangeMilestoneStatus", err)
  1077. return
  1078. }
  1079. }
  1080. location.RawQuery = "state=open"
  1081. case "close":
  1082. if !m.IsClosed {
  1083. m.ClosedDate = time.Now()
  1084. if err = db.ChangeMilestoneStatus(m, true); err != nil {
  1085. c.Handle(500, "ChangeMilestoneStatus", err)
  1086. return
  1087. }
  1088. }
  1089. location.RawQuery = "state=closed"
  1090. }
  1091. c.RawRedirect(c.Repo.MakeURL(location))
  1092. }
  1093. func DeleteMilestone(c *context.Context) {
  1094. if err := db.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  1095. c.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1096. } else {
  1097. c.Flash.Success(c.Tr("repo.milestones.deletion_success"))
  1098. }
  1099. c.JSON(200, map[string]interface{}{
  1100. "redirect": c.Repo.MakeURL("milestones"),
  1101. })
  1102. }