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