issue.go 31 KB

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