Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

issue.go 41KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543
  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. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "net/http"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/Unknwon/com"
  16. "github.com/Unknwon/paginater"
  17. "code.gitea.io/git"
  18. "code.gitea.io/gitea/models"
  19. "code.gitea.io/gitea/modules/auth"
  20. "code.gitea.io/gitea/modules/base"
  21. "code.gitea.io/gitea/modules/context"
  22. "code.gitea.io/gitea/modules/indexer"
  23. "code.gitea.io/gitea/modules/log"
  24. "code.gitea.io/gitea/modules/markup/markdown"
  25. "code.gitea.io/gitea/modules/notification"
  26. "code.gitea.io/gitea/modules/setting"
  27. "code.gitea.io/gitea/modules/util"
  28. )
  29. const (
  30. tplIssues base.TplName = "repo/issue/list"
  31. tplIssueNew base.TplName = "repo/issue/new"
  32. tplIssueView base.TplName = "repo/issue/view"
  33. tplMilestone base.TplName = "repo/issue/milestones"
  34. tplMilestoneNew base.TplName = "repo/issue/milestone_new"
  35. tplMilestoneEdit base.TplName = "repo/issue/milestone_edit"
  36. tplReactions base.TplName = "repo/issue/view_content/reactions"
  37. issueTemplateKey = "IssueTemplate"
  38. )
  39. var (
  40. // ErrFileTypeForbidden not allowed file type error
  41. ErrFileTypeForbidden = errors.New("File type is not allowed")
  42. // ErrTooManyFiles upload too many files
  43. ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded")
  44. // IssueTemplateCandidates issue templates
  45. IssueTemplateCandidates = []string{
  46. "ISSUE_TEMPLATE.md",
  47. "issue_template.md",
  48. ".gitea/ISSUE_TEMPLATE.md",
  49. ".gitea/issue_template.md",
  50. ".github/ISSUE_TEMPLATE.md",
  51. ".github/issue_template.md",
  52. }
  53. )
  54. // MustEnableIssues check if repository enable internal issues
  55. func MustEnableIssues(ctx *context.Context) {
  56. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) &&
  57. !ctx.Repo.Repository.UnitEnabled(models.UnitTypeExternalTracker) {
  58. ctx.NotFound("MustEnableIssues", nil)
  59. return
  60. }
  61. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  62. if err == nil {
  63. ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL)
  64. return
  65. }
  66. }
  67. // MustAllowPulls check if repository enable pull requests
  68. func MustAllowPulls(ctx *context.Context) {
  69. if !ctx.Repo.Repository.AllowsPulls() {
  70. ctx.NotFound("MustAllowPulls", nil)
  71. return
  72. }
  73. // User can send pull request if owns a forked repository.
  74. if ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID) {
  75. ctx.Repo.PullRequest.Allowed = true
  76. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  77. }
  78. }
  79. // Issues render issues page
  80. func Issues(ctx *context.Context) {
  81. isPullList := ctx.Params(":type") == "pulls"
  82. if isPullList {
  83. MustAllowPulls(ctx)
  84. if ctx.Written() {
  85. return
  86. }
  87. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  88. ctx.Data["PageIsPullList"] = true
  89. } else {
  90. MustEnableIssues(ctx)
  91. if ctx.Written() {
  92. return
  93. }
  94. ctx.Data["Title"] = ctx.Tr("repo.issues")
  95. ctx.Data["PageIsIssueList"] = true
  96. }
  97. viewType := ctx.Query("type")
  98. sortType := ctx.Query("sort")
  99. types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned"}
  100. if !com.IsSliceContainsStr(types, viewType) {
  101. viewType = "all"
  102. }
  103. var (
  104. assigneeID = ctx.QueryInt64("assignee")
  105. posterID int64
  106. mentionedID int64
  107. forceEmpty bool
  108. )
  109. if ctx.IsSigned {
  110. switch viewType {
  111. case "created_by":
  112. posterID = ctx.User.ID
  113. case "mentioned":
  114. mentionedID = ctx.User.ID
  115. }
  116. }
  117. repo := ctx.Repo.Repository
  118. selectLabels := ctx.Query("labels")
  119. milestoneID := ctx.QueryInt64("milestone")
  120. isShowClosed := ctx.Query("state") == "closed"
  121. keyword := strings.Trim(ctx.Query("q"), " ")
  122. if bytes.Contains([]byte(keyword), []byte{0x00}) {
  123. keyword = ""
  124. }
  125. var issueIDs []int64
  126. var err error
  127. if len(keyword) > 0 {
  128. issueIDs, err = indexer.SearchIssuesByKeyword(repo.ID, keyword)
  129. if len(issueIDs) == 0 {
  130. forceEmpty = true
  131. }
  132. }
  133. var issueStats *models.IssueStats
  134. if forceEmpty {
  135. issueStats = &models.IssueStats{}
  136. } else {
  137. var err error
  138. issueStats, err = models.GetIssueStats(&models.IssueStatsOptions{
  139. RepoID: repo.ID,
  140. Labels: selectLabels,
  141. MilestoneID: milestoneID,
  142. AssigneeID: assigneeID,
  143. MentionedID: mentionedID,
  144. PosterID: posterID,
  145. IsPull: isPullList,
  146. IssueIDs: issueIDs,
  147. })
  148. if err != nil {
  149. ctx.ServerError("GetIssueStats", err)
  150. return
  151. }
  152. }
  153. page := ctx.QueryInt("page")
  154. if page <= 1 {
  155. page = 1
  156. }
  157. var total int
  158. if !isShowClosed {
  159. total = int(issueStats.OpenCount)
  160. } else {
  161. total = int(issueStats.ClosedCount)
  162. }
  163. pager := paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  164. ctx.Data["Page"] = pager
  165. var issues []*models.Issue
  166. if forceEmpty {
  167. issues = []*models.Issue{}
  168. } else {
  169. issues, err = models.Issues(&models.IssuesOptions{
  170. RepoIDs: []int64{repo.ID},
  171. AssigneeID: assigneeID,
  172. PosterID: posterID,
  173. MentionedID: mentionedID,
  174. MilestoneID: milestoneID,
  175. Page: pager.Current(),
  176. PageSize: setting.UI.IssuePagingNum,
  177. IsClosed: util.OptionalBoolOf(isShowClosed),
  178. IsPull: util.OptionalBoolOf(isPullList),
  179. Labels: selectLabels,
  180. SortType: sortType,
  181. IssueIDs: issueIDs,
  182. })
  183. if err != nil {
  184. ctx.ServerError("Issues", err)
  185. return
  186. }
  187. }
  188. // Get posters.
  189. for i := range issues {
  190. // Check read status
  191. if !ctx.IsSigned {
  192. issues[i].IsRead = true
  193. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  194. ctx.ServerError("GetIsRead", err)
  195. return
  196. }
  197. }
  198. ctx.Data["Issues"] = issues
  199. // Get milestones.
  200. ctx.Data["Milestones"], err = models.GetMilestonesByRepoID(repo.ID)
  201. if err != nil {
  202. ctx.ServerError("GetAllRepoMilestones", err)
  203. return
  204. }
  205. // Get assignees.
  206. ctx.Data["Assignees"], err = repo.GetAssignees()
  207. if err != nil {
  208. ctx.ServerError("GetAssignees", err)
  209. return
  210. }
  211. if ctx.QueryInt64("assignee") == 0 {
  212. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  213. }
  214. ctx.Data["IssueStats"] = issueStats
  215. ctx.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64()
  216. ctx.Data["ViewType"] = viewType
  217. ctx.Data["SortType"] = sortType
  218. ctx.Data["MilestoneID"] = milestoneID
  219. ctx.Data["AssigneeID"] = assigneeID
  220. ctx.Data["IsShowClosed"] = isShowClosed
  221. ctx.Data["Keyword"] = keyword
  222. if isShowClosed {
  223. ctx.Data["State"] = "closed"
  224. } else {
  225. ctx.Data["State"] = "open"
  226. }
  227. ctx.HTML(200, tplIssues)
  228. }
  229. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  230. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  231. var err error
  232. ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false, "")
  233. if err != nil {
  234. ctx.ServerError("GetMilestones", err)
  235. return
  236. }
  237. ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true, "")
  238. if err != nil {
  239. ctx.ServerError("GetMilestones", err)
  240. return
  241. }
  242. ctx.Data["Assignees"], err = repo.GetAssignees()
  243. if err != nil {
  244. ctx.ServerError("GetAssignees", err)
  245. return
  246. }
  247. }
  248. // RetrieveRepoMetas find all the meta information of a repository
  249. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository) []*models.Label {
  250. if !ctx.Repo.IsWriter() {
  251. return nil
  252. }
  253. labels, err := models.GetLabelsByRepoID(repo.ID, "")
  254. if err != nil {
  255. ctx.ServerError("GetLabelsByRepoID", err)
  256. return nil
  257. }
  258. ctx.Data["Labels"] = labels
  259. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  260. if ctx.Written() {
  261. return nil
  262. }
  263. brs, err := ctx.Repo.GitRepo.GetBranches()
  264. if err != nil {
  265. ctx.ServerError("GetBranches", err)
  266. return nil
  267. }
  268. ctx.Data["Branches"] = brs
  269. // Contains true if the user can create issue dependencies
  270. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User)
  271. return labels
  272. }
  273. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  274. var r io.Reader
  275. var bytes []byte
  276. if ctx.Repo.Commit == nil {
  277. var err error
  278. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  279. if err != nil {
  280. return "", false
  281. }
  282. }
  283. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  284. if err != nil {
  285. return "", false
  286. }
  287. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  288. return "", false
  289. }
  290. r, err = entry.Blob().Data()
  291. if err != nil {
  292. return "", false
  293. }
  294. bytes, err = ioutil.ReadAll(r)
  295. if err != nil {
  296. return "", false
  297. }
  298. return string(bytes), true
  299. }
  300. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) {
  301. for _, filename := range possibleFiles {
  302. content, found := getFileContentFromDefaultBranch(ctx, filename)
  303. if found {
  304. ctx.Data[ctxDataKey] = content
  305. return
  306. }
  307. }
  308. }
  309. // NewIssue render createing issue page
  310. func NewIssue(ctx *context.Context) {
  311. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  312. ctx.Data["PageIsIssueList"] = true
  313. ctx.Data["RequireHighlightJS"] = true
  314. ctx.Data["RequireSimpleMDE"] = true
  315. ctx.Data["RequireTribute"] = true
  316. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  317. setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates)
  318. renderAttachmentSettings(ctx)
  319. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  320. if ctx.Written() {
  321. return
  322. }
  323. ctx.HTML(200, tplIssueNew)
  324. }
  325. // ValidateRepoMetas check and returns repository's meta informations
  326. func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64, []int64, int64) {
  327. var (
  328. repo = ctx.Repo.Repository
  329. err error
  330. )
  331. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  332. if ctx.Written() {
  333. return nil, nil, 0
  334. }
  335. if !ctx.Repo.IsWriter() {
  336. return nil, nil, 0
  337. }
  338. var labelIDs []int64
  339. hasSelected := false
  340. // Check labels.
  341. if len(form.LabelIDs) > 0 {
  342. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  343. if err != nil {
  344. return nil, nil, 0
  345. }
  346. labelIDMark := base.Int64sToMap(labelIDs)
  347. for i := range labels {
  348. if labelIDMark[labels[i].ID] {
  349. labels[i].IsChecked = true
  350. hasSelected = true
  351. }
  352. }
  353. }
  354. ctx.Data["Labels"] = labels
  355. ctx.Data["HasSelectedLabel"] = hasSelected
  356. ctx.Data["label_ids"] = form.LabelIDs
  357. // Check milestone.
  358. milestoneID := form.MilestoneID
  359. if milestoneID > 0 {
  360. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  361. if err != nil {
  362. ctx.ServerError("GetMilestoneByID", err)
  363. return nil, nil, 0
  364. }
  365. ctx.Data["milestone_id"] = milestoneID
  366. }
  367. // Check assignees
  368. var assigneeIDs []int64
  369. if len(form.AssigneeIDs) > 0 {
  370. assigneeIDs, err = base.StringsToInt64s(strings.Split(form.AssigneeIDs, ","))
  371. if err != nil {
  372. return nil, nil, 0
  373. }
  374. // Check if the passed assignees actually exists and has write access to the repo
  375. for _, aID := range assigneeIDs {
  376. _, err = repo.GetUserIfHasWriteAccess(aID)
  377. if err != nil {
  378. ctx.ServerError("GetUserIfHasWriteAccess", err)
  379. return nil, nil, 0
  380. }
  381. }
  382. }
  383. // Keep the old assignee id thingy for compatibility reasons
  384. if form.AssigneeID > 0 {
  385. assigneeIDs = append(assigneeIDs, form.AssigneeID)
  386. }
  387. return labelIDs, assigneeIDs, milestoneID
  388. }
  389. // NewIssuePost response for creating new issue
  390. func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
  391. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  392. ctx.Data["PageIsIssueList"] = true
  393. ctx.Data["RequireHighlightJS"] = true
  394. ctx.Data["RequireSimpleMDE"] = true
  395. ctx.Data["ReadOnly"] = false
  396. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  397. renderAttachmentSettings(ctx)
  398. var (
  399. repo = ctx.Repo.Repository
  400. attachments []string
  401. )
  402. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form)
  403. if ctx.Written() {
  404. return
  405. }
  406. if setting.AttachmentEnabled {
  407. attachments = form.Files
  408. }
  409. if ctx.HasError() {
  410. ctx.HTML(200, tplIssueNew)
  411. return
  412. }
  413. issue := &models.Issue{
  414. RepoID: repo.ID,
  415. Title: form.Title,
  416. PosterID: ctx.User.ID,
  417. Poster: ctx.User,
  418. MilestoneID: milestoneID,
  419. Content: form.Content,
  420. Ref: form.Ref,
  421. }
  422. if err := models.NewIssue(repo, issue, labelIDs, assigneeIDs, attachments); err != nil {
  423. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  424. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  425. return
  426. }
  427. ctx.ServerError("NewIssue", err)
  428. return
  429. }
  430. notification.Service.NotifyIssue(issue, ctx.User.ID)
  431. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  432. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  433. }
  434. // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
  435. func commentTag(repo *models.Repository, poster *models.User, issue *models.Issue) (models.CommentTag, error) {
  436. if repo.IsOwnedBy(poster.ID) {
  437. return models.CommentTagOwner, nil
  438. } else if repo.Owner.IsOrganization() {
  439. isOwner, err := repo.Owner.IsOwnedBy(poster.ID)
  440. if err != nil {
  441. return models.CommentTagNone, err
  442. } else if isOwner {
  443. return models.CommentTagOwner, nil
  444. }
  445. }
  446. if poster.IsWriterOfRepo(repo) {
  447. return models.CommentTagWriter, nil
  448. } else if poster.ID == issue.PosterID {
  449. return models.CommentTagPoster, nil
  450. }
  451. return models.CommentTagNone, nil
  452. }
  453. // ViewIssue render issue view page
  454. func ViewIssue(ctx *context.Context) {
  455. ctx.Data["RequireHighlightJS"] = true
  456. ctx.Data["RequireDropzone"] = true
  457. ctx.Data["RequireTribute"] = true
  458. renderAttachmentSettings(ctx)
  459. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  460. if err != nil {
  461. if models.IsErrIssueNotExist(err) {
  462. ctx.NotFound("GetIssueByIndex", err)
  463. } else {
  464. ctx.ServerError("GetIssueByIndex", err)
  465. }
  466. return
  467. }
  468. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  469. var iw *models.IssueWatch
  470. var exists bool
  471. if ctx.User != nil {
  472. iw, exists, err = models.GetIssueWatch(ctx.User.ID, issue.ID)
  473. if err != nil {
  474. ctx.ServerError("GetIssueWatch", err)
  475. return
  476. }
  477. if !exists {
  478. iw = &models.IssueWatch{
  479. UserID: ctx.User.ID,
  480. IssueID: issue.ID,
  481. IsWatching: models.IsWatching(ctx.User.ID, ctx.Repo.Repository.ID),
  482. }
  483. }
  484. }
  485. ctx.Data["IssueWatch"] = iw
  486. // Make sure type and URL matches.
  487. if ctx.Params(":type") == "issues" && issue.IsPull {
  488. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  489. return
  490. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  491. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  492. return
  493. }
  494. if issue.IsPull {
  495. MustAllowPulls(ctx)
  496. if ctx.Written() {
  497. return
  498. }
  499. ctx.Data["PageIsPullList"] = true
  500. ctx.Data["PageIsPullConversation"] = true
  501. } else {
  502. MustEnableIssues(ctx)
  503. if ctx.Written() {
  504. return
  505. }
  506. ctx.Data["PageIsIssueList"] = true
  507. }
  508. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  509. ctx.Repo.Repository.ComposeMetas()))
  510. repo := ctx.Repo.Repository
  511. // Get more information if it's a pull request.
  512. if issue.IsPull {
  513. if issue.PullRequest.HasMerged {
  514. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  515. PrepareMergedViewPullInfo(ctx, issue)
  516. } else {
  517. PrepareViewPullInfo(ctx, issue)
  518. }
  519. if ctx.Written() {
  520. return
  521. }
  522. }
  523. // Metas.
  524. // Check labels.
  525. labelIDMark := make(map[int64]bool)
  526. for i := range issue.Labels {
  527. labelIDMark[issue.Labels[i].ID] = true
  528. }
  529. labels, err := models.GetLabelsByRepoID(repo.ID, "")
  530. if err != nil {
  531. ctx.ServerError("GetLabelsByRepoID", err)
  532. return
  533. }
  534. hasSelected := false
  535. for i := range labels {
  536. if labelIDMark[labels[i].ID] {
  537. labels[i].IsChecked = true
  538. hasSelected = true
  539. }
  540. }
  541. ctx.Data["HasSelectedLabel"] = hasSelected
  542. ctx.Data["Labels"] = labels
  543. // Check milestone and assignee.
  544. if ctx.Repo.IsWriter() {
  545. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  546. if ctx.Written() {
  547. return
  548. }
  549. }
  550. if ctx.IsSigned {
  551. // Update issue-user.
  552. if err = issue.ReadBy(ctx.User.ID); err != nil {
  553. ctx.ServerError("ReadBy", err)
  554. return
  555. }
  556. }
  557. var (
  558. tag models.CommentTag
  559. ok bool
  560. marked = make(map[int64]models.CommentTag)
  561. comment *models.Comment
  562. participants = make([]*models.User, 1, 10)
  563. )
  564. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  565. if ctx.IsSigned {
  566. // Deal with the stopwatch
  567. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  568. if !ctx.Data["IsStopwatchRunning"].(bool) {
  569. var exists bool
  570. var sw *models.Stopwatch
  571. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  572. ctx.ServerError("HasUserStopwatch", err)
  573. return
  574. }
  575. ctx.Data["HasUserStopwatch"] = exists
  576. if exists {
  577. // Add warning if the user has already a stopwatch
  578. var otherIssue *models.Issue
  579. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  580. ctx.ServerError("GetIssueByID", err)
  581. return
  582. }
  583. // Add link to the issue of the already running stopwatch
  584. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  585. }
  586. }
  587. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  588. } else {
  589. ctx.Data["CanUseTimetracker"] = false
  590. }
  591. if ctx.Data["WorkingUsers"], err = models.TotalTimes(models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  592. ctx.ServerError("TotalTimes", err)
  593. return
  594. }
  595. }
  596. // Check if the user can use the dependencies
  597. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User)
  598. // Render comments and and fetch participants.
  599. participants[0] = issue.Poster
  600. for _, comment = range issue.Comments {
  601. if comment.Type == models.CommentTypeComment {
  602. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  603. ctx.Repo.Repository.ComposeMetas()))
  604. // Check tag.
  605. tag, ok = marked[comment.PosterID]
  606. if ok {
  607. comment.ShowTag = tag
  608. continue
  609. }
  610. comment.ShowTag, err = commentTag(repo, comment.Poster, issue)
  611. if err != nil {
  612. ctx.ServerError("commentTag", err)
  613. return
  614. }
  615. marked[comment.PosterID] = comment.ShowTag
  616. isAdded := false
  617. for j := range participants {
  618. if comment.Poster == participants[j] {
  619. isAdded = true
  620. break
  621. }
  622. }
  623. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  624. participants = append(participants, comment.Poster)
  625. }
  626. } else if comment.Type == models.CommentTypeLabel {
  627. if err = comment.LoadLabel(); err != nil {
  628. ctx.ServerError("LoadLabel", err)
  629. return
  630. }
  631. } else if comment.Type == models.CommentTypeMilestone {
  632. if err = comment.LoadMilestone(); err != nil {
  633. ctx.ServerError("LoadMilestone", err)
  634. return
  635. }
  636. ghostMilestone := &models.Milestone{
  637. ID: -1,
  638. Name: ctx.Tr("repo.issues.deleted_milestone"),
  639. }
  640. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  641. comment.OldMilestone = ghostMilestone
  642. }
  643. if comment.MilestoneID > 0 && comment.Milestone == nil {
  644. comment.Milestone = ghostMilestone
  645. }
  646. } else if comment.Type == models.CommentTypeAssignees {
  647. if err = comment.LoadAssigneeUser(); err != nil {
  648. ctx.ServerError("LoadAssigneeUser", err)
  649. return
  650. }
  651. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  652. if err = comment.LoadDepIssueDetails(); err != nil {
  653. ctx.ServerError("LoadDepIssueDetails", err)
  654. return
  655. }
  656. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview {
  657. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  658. ctx.ServerError("LoadReview", err)
  659. return
  660. }
  661. if comment.Review == nil {
  662. continue
  663. }
  664. if err = comment.Review.LoadAttributes(); err != nil {
  665. ctx.ServerError("Review.LoadAttributes", err)
  666. return
  667. }
  668. if err = comment.Review.LoadCodeComments(); err != nil {
  669. ctx.ServerError("Review.LoadCodeComments", err)
  670. return
  671. }
  672. }
  673. }
  674. if issue.IsPull {
  675. pull := issue.PullRequest
  676. canDelete := false
  677. if ctx.IsSigned {
  678. if err := pull.GetHeadRepo(); err != nil {
  679. log.Error(4, "GetHeadRepo: %v", err)
  680. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch && ctx.User.IsWriterOfRepo(pull.HeadRepo) {
  681. // Check if branch is not protected
  682. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch, ctx.User); err != nil {
  683. log.Error(4, "IsProtectedBranch: %v", err)
  684. } else if !protected {
  685. canDelete = true
  686. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup"
  687. }
  688. }
  689. }
  690. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  691. if err != nil {
  692. ctx.ServerError("GetUnit", err)
  693. return
  694. }
  695. prConfig := prUnit.PullRequestsConfig()
  696. ctx.Data["AllowMerge"] = ctx.Data["IsRepositoryWriter"]
  697. if err := pull.CheckUserAllowedToMerge(ctx.User); err != nil {
  698. if !models.IsErrNotAllowedToMerge(err) {
  699. ctx.ServerError("CheckUserAllowedToMerge", err)
  700. return
  701. }
  702. ctx.Data["AllowMerge"] = false
  703. }
  704. // Check correct values and select default
  705. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  706. !prConfig.IsMergeStyleAllowed(ms) {
  707. if prConfig.AllowMerge {
  708. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  709. } else if prConfig.AllowRebase {
  710. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  711. } else if prConfig.AllowSquash {
  712. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  713. } else {
  714. ctx.Data["MergeStyle"] = ""
  715. }
  716. }
  717. ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
  718. }
  719. // Get Dependencies
  720. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  721. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  722. ctx.Data["Participants"] = participants
  723. ctx.Data["NumParticipants"] = len(participants)
  724. ctx.Data["Issue"] = issue
  725. ctx.Data["ReadOnly"] = true
  726. ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))
  727. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  728. ctx.HTML(200, tplIssueView)
  729. }
  730. // GetActionIssue will return the issue which is used in the context.
  731. func GetActionIssue(ctx *context.Context) *models.Issue {
  732. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  733. if err != nil {
  734. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  735. return nil
  736. }
  737. checkIssueRights(ctx, issue)
  738. if ctx.Written() {
  739. return nil
  740. }
  741. if err = issue.LoadAttributes(); err != nil {
  742. ctx.ServerError("LoadAttributes", nil)
  743. return nil
  744. }
  745. return issue
  746. }
  747. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  748. if issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) ||
  749. !issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
  750. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  751. }
  752. }
  753. func getActionIssues(ctx *context.Context) []*models.Issue {
  754. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  755. if len(commaSeparatedIssueIDs) == 0 {
  756. return nil
  757. }
  758. issueIDs := make([]int64, 0, 10)
  759. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  760. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  761. if err != nil {
  762. ctx.ServerError("ParseInt", err)
  763. return nil
  764. }
  765. issueIDs = append(issueIDs, issueID)
  766. }
  767. issues, err := models.GetIssuesByIDs(issueIDs)
  768. if err != nil {
  769. ctx.ServerError("GetIssuesByIDs", err)
  770. return nil
  771. }
  772. // Check access rights for all issues
  773. issueUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues)
  774. prUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests)
  775. for _, issue := range issues {
  776. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  777. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  778. return nil
  779. }
  780. if err = issue.LoadAttributes(); err != nil {
  781. ctx.ServerError("LoadAttributes", err)
  782. return nil
  783. }
  784. }
  785. return issues
  786. }
  787. // UpdateIssueTitle change issue's title
  788. func UpdateIssueTitle(ctx *context.Context) {
  789. issue := GetActionIssue(ctx)
  790. if ctx.Written() {
  791. return
  792. }
  793. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) {
  794. ctx.Error(403)
  795. return
  796. }
  797. title := ctx.QueryTrim("title")
  798. if len(title) == 0 {
  799. ctx.Error(204)
  800. return
  801. }
  802. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  803. ctx.ServerError("ChangeTitle", err)
  804. return
  805. }
  806. ctx.JSON(200, map[string]interface{}{
  807. "title": issue.Title,
  808. })
  809. }
  810. // UpdateIssueContent change issue's content
  811. func UpdateIssueContent(ctx *context.Context) {
  812. issue := GetActionIssue(ctx)
  813. if ctx.Written() {
  814. return
  815. }
  816. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) {
  817. ctx.Error(403)
  818. return
  819. }
  820. content := ctx.Query("content")
  821. if err := issue.ChangeContent(ctx.User, content); err != nil {
  822. ctx.ServerError("ChangeContent", err)
  823. return
  824. }
  825. ctx.JSON(200, map[string]interface{}{
  826. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  827. })
  828. }
  829. // UpdateIssueMilestone change issue's milestone
  830. func UpdateIssueMilestone(ctx *context.Context) {
  831. issues := getActionIssues(ctx)
  832. if ctx.Written() {
  833. return
  834. }
  835. milestoneID := ctx.QueryInt64("id")
  836. for _, issue := range issues {
  837. oldMilestoneID := issue.MilestoneID
  838. if oldMilestoneID == milestoneID {
  839. continue
  840. }
  841. issue.MilestoneID = milestoneID
  842. if err := models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  843. ctx.ServerError("ChangeMilestoneAssign", err)
  844. return
  845. }
  846. }
  847. ctx.JSON(200, map[string]interface{}{
  848. "ok": true,
  849. })
  850. }
  851. // UpdateIssueAssignee change issue's assignee
  852. func UpdateIssueAssignee(ctx *context.Context) {
  853. issues := getActionIssues(ctx)
  854. if ctx.Written() {
  855. return
  856. }
  857. assigneeID := ctx.QueryInt64("id")
  858. action := ctx.Query("action")
  859. for _, issue := range issues {
  860. switch action {
  861. case "clear":
  862. if err := models.DeleteNotPassedAssignee(issue, ctx.User, []*models.User{}); err != nil {
  863. ctx.ServerError("ClearAssignees", err)
  864. return
  865. }
  866. default:
  867. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  868. ctx.ServerError("ChangeAssignee", err)
  869. return
  870. }
  871. }
  872. }
  873. ctx.JSON(200, map[string]interface{}{
  874. "ok": true,
  875. })
  876. }
  877. // UpdateIssueStatus change issue's status
  878. func UpdateIssueStatus(ctx *context.Context) {
  879. issues := getActionIssues(ctx)
  880. if ctx.Written() {
  881. return
  882. }
  883. var isClosed bool
  884. switch action := ctx.Query("action"); action {
  885. case "open":
  886. isClosed = false
  887. case "close":
  888. isClosed = true
  889. default:
  890. log.Warn("Unrecognized action: %s", action)
  891. }
  892. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  893. ctx.ServerError("LoadRepositories", err)
  894. return
  895. }
  896. for _, issue := range issues {
  897. if err := issue.ChangeStatus(ctx.User, issue.Repo, isClosed); err != nil {
  898. if models.IsErrDependenciesLeft(err) {
  899. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  900. "error": "cannot close this issue because it still has open dependencies",
  901. })
  902. return
  903. }
  904. ctx.ServerError("ChangeStatus", err)
  905. return
  906. }
  907. }
  908. ctx.JSON(200, map[string]interface{}{
  909. "ok": true,
  910. })
  911. }
  912. // NewComment create a comment for issue
  913. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  914. issue := GetActionIssue(ctx)
  915. if ctx.Written() {
  916. return
  917. }
  918. var attachments []string
  919. if setting.AttachmentEnabled {
  920. attachments = form.Files
  921. }
  922. if ctx.HasError() {
  923. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  924. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  925. return
  926. }
  927. var comment *models.Comment
  928. defer func() {
  929. // Check if issue admin/poster changes the status of issue.
  930. if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  931. (form.Status == "reopen" || form.Status == "close") &&
  932. !(issue.IsPull && issue.PullRequest.HasMerged) {
  933. // Duplication and conflict check should apply to reopen pull request.
  934. var pr *models.PullRequest
  935. if form.Status == "reopen" && issue.IsPull {
  936. pull := issue.PullRequest
  937. pr, err := models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  938. if err != nil {
  939. if !models.IsErrPullRequestNotExist(err) {
  940. ctx.ServerError("GetUnmergedPullRequest", err)
  941. return
  942. }
  943. }
  944. // Regenerate patch and test conflict.
  945. if pr == nil {
  946. if err = issue.PullRequest.UpdatePatch(); err != nil {
  947. ctx.ServerError("UpdatePatch", err)
  948. return
  949. }
  950. issue.PullRequest.AddToTaskQueue()
  951. }
  952. }
  953. if pr != nil {
  954. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  955. } else {
  956. if err := issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil {
  957. log.Error(4, "ChangeStatus: %v", err)
  958. if models.IsErrDependenciesLeft(err) {
  959. if issue.IsPull {
  960. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  961. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  962. } else {
  963. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  964. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  965. }
  966. return
  967. }
  968. } else {
  969. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  970. notification.Service.NotifyIssue(issue, ctx.User.ID)
  971. }
  972. }
  973. }
  974. // Redirect to comment hashtag if there is any actual content.
  975. typeName := "issues"
  976. if issue.IsPull {
  977. typeName = "pulls"
  978. }
  979. if comment != nil {
  980. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  981. } else {
  982. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  983. }
  984. }()
  985. // Fix #321: Allow empty comments, as long as we have attachments.
  986. if len(form.Content) == 0 && len(attachments) == 0 {
  987. return
  988. }
  989. comment, err := models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  990. if err != nil {
  991. ctx.ServerError("CreateIssueComment", err)
  992. return
  993. }
  994. notification.Service.NotifyIssue(issue, ctx.User.ID)
  995. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  996. }
  997. // UpdateCommentContent change comment of issue's content
  998. func UpdateCommentContent(ctx *context.Context) {
  999. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1000. if err != nil {
  1001. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1002. return
  1003. }
  1004. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  1005. ctx.Error(403)
  1006. return
  1007. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1008. ctx.Error(204)
  1009. return
  1010. }
  1011. oldContent := comment.Content
  1012. comment.Content = ctx.Query("content")
  1013. if len(comment.Content) == 0 {
  1014. ctx.JSON(200, map[string]interface{}{
  1015. "content": "",
  1016. })
  1017. return
  1018. }
  1019. if err = models.UpdateComment(ctx.User, comment, oldContent); err != nil {
  1020. ctx.ServerError("UpdateComment", err)
  1021. return
  1022. }
  1023. ctx.JSON(200, map[string]interface{}{
  1024. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1025. })
  1026. }
  1027. // DeleteComment delete comment of issue
  1028. func DeleteComment(ctx *context.Context) {
  1029. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1030. if err != nil {
  1031. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1032. return
  1033. }
  1034. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  1035. ctx.Error(403)
  1036. return
  1037. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1038. ctx.Error(204)
  1039. return
  1040. }
  1041. if err = models.DeleteComment(ctx.User, comment); err != nil {
  1042. ctx.ServerError("DeleteCommentByID", err)
  1043. return
  1044. }
  1045. ctx.Status(200)
  1046. }
  1047. // Milestones render milestones page
  1048. func Milestones(ctx *context.Context) {
  1049. ctx.Data["Title"] = ctx.Tr("repo.milestones")
  1050. ctx.Data["PageIsIssueList"] = true
  1051. ctx.Data["PageIsMilestones"] = true
  1052. isShowClosed := ctx.Query("state") == "closed"
  1053. openCount, closedCount, err := models.MilestoneStats(ctx.Repo.Repository.ID)
  1054. if err != nil {
  1055. ctx.ServerError("MilestoneStats", err)
  1056. return
  1057. }
  1058. ctx.Data["OpenCount"] = openCount
  1059. ctx.Data["ClosedCount"] = closedCount
  1060. sortType := ctx.Query("sort")
  1061. page := ctx.QueryInt("page")
  1062. if page <= 1 {
  1063. page = 1
  1064. }
  1065. var total int
  1066. if !isShowClosed {
  1067. total = int(openCount)
  1068. } else {
  1069. total = int(closedCount)
  1070. }
  1071. ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  1072. miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed, sortType)
  1073. if err != nil {
  1074. ctx.ServerError("GetMilestones", err)
  1075. return
  1076. }
  1077. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  1078. if miles.LoadTotalTrackedTimes(); err != nil {
  1079. ctx.ServerError("LoadTotalTrackedTimes", err)
  1080. return
  1081. }
  1082. }
  1083. for _, m := range miles {
  1084. m.RenderedContent = string(markdown.Render([]byte(m.Content), ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()))
  1085. }
  1086. ctx.Data["Milestones"] = miles
  1087. if isShowClosed {
  1088. ctx.Data["State"] = "closed"
  1089. } else {
  1090. ctx.Data["State"] = "open"
  1091. }
  1092. ctx.Data["SortType"] = sortType
  1093. ctx.Data["IsShowClosed"] = isShowClosed
  1094. ctx.HTML(200, tplMilestone)
  1095. }
  1096. // NewMilestone render creating milestone page
  1097. func NewMilestone(ctx *context.Context) {
  1098. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1099. ctx.Data["PageIsIssueList"] = true
  1100. ctx.Data["PageIsMilestones"] = true
  1101. ctx.Data["RequireDatetimepicker"] = true
  1102. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1103. ctx.HTML(200, tplMilestoneNew)
  1104. }
  1105. // NewMilestonePost response for creating milestone
  1106. func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1107. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1108. ctx.Data["PageIsIssueList"] = true
  1109. ctx.Data["PageIsMilestones"] = true
  1110. ctx.Data["RequireDatetimepicker"] = true
  1111. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1112. if ctx.HasError() {
  1113. ctx.HTML(200, tplMilestoneNew)
  1114. return
  1115. }
  1116. if len(form.Deadline) == 0 {
  1117. form.Deadline = "9999-12-31"
  1118. }
  1119. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1120. if err != nil {
  1121. ctx.Data["Err_Deadline"] = true
  1122. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1123. return
  1124. }
  1125. if err = models.NewMilestone(&models.Milestone{
  1126. RepoID: ctx.Repo.Repository.ID,
  1127. Name: form.Title,
  1128. Content: form.Content,
  1129. DeadlineUnix: util.TimeStamp(deadline.Unix()),
  1130. }); err != nil {
  1131. ctx.ServerError("NewMilestone", err)
  1132. return
  1133. }
  1134. ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
  1135. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1136. }
  1137. // EditMilestone render edting milestone page
  1138. func EditMilestone(ctx *context.Context) {
  1139. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1140. ctx.Data["PageIsMilestones"] = true
  1141. ctx.Data["PageIsEditMilestone"] = true
  1142. ctx.Data["RequireDatetimepicker"] = true
  1143. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1144. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1145. if err != nil {
  1146. if models.IsErrMilestoneNotExist(err) {
  1147. ctx.NotFound("", nil)
  1148. } else {
  1149. ctx.ServerError("GetMilestoneByRepoID", err)
  1150. }
  1151. return
  1152. }
  1153. ctx.Data["title"] = m.Name
  1154. ctx.Data["content"] = m.Content
  1155. if len(m.DeadlineString) > 0 {
  1156. ctx.Data["deadline"] = m.DeadlineString
  1157. }
  1158. ctx.HTML(200, tplMilestoneNew)
  1159. }
  1160. // EditMilestonePost response for edting milestone
  1161. func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1162. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1163. ctx.Data["PageIsMilestones"] = true
  1164. ctx.Data["PageIsEditMilestone"] = true
  1165. ctx.Data["RequireDatetimepicker"] = true
  1166. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1167. if ctx.HasError() {
  1168. ctx.HTML(200, tplMilestoneNew)
  1169. return
  1170. }
  1171. if len(form.Deadline) == 0 {
  1172. form.Deadline = "9999-12-31"
  1173. }
  1174. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1175. if err != nil {
  1176. ctx.Data["Err_Deadline"] = true
  1177. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1178. return
  1179. }
  1180. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1181. if err != nil {
  1182. if models.IsErrMilestoneNotExist(err) {
  1183. ctx.NotFound("", nil)
  1184. } else {
  1185. ctx.ServerError("GetMilestoneByRepoID", err)
  1186. }
  1187. return
  1188. }
  1189. m.Name = form.Title
  1190. m.Content = form.Content
  1191. m.DeadlineUnix = util.TimeStamp(deadline.Unix())
  1192. if err = models.UpdateMilestone(m); err != nil {
  1193. ctx.ServerError("UpdateMilestone", err)
  1194. return
  1195. }
  1196. ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
  1197. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1198. }
  1199. // ChangeMilestonStatus response for change a milestone's status
  1200. func ChangeMilestonStatus(ctx *context.Context) {
  1201. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1202. if err != nil {
  1203. if models.IsErrMilestoneNotExist(err) {
  1204. ctx.NotFound("", err)
  1205. } else {
  1206. ctx.ServerError("GetMilestoneByRepoID", err)
  1207. }
  1208. return
  1209. }
  1210. switch ctx.Params(":action") {
  1211. case "open":
  1212. if m.IsClosed {
  1213. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1214. ctx.ServerError("ChangeMilestoneStatus", err)
  1215. return
  1216. }
  1217. }
  1218. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
  1219. case "close":
  1220. if !m.IsClosed {
  1221. m.ClosedDateUnix = util.TimeStampNow()
  1222. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1223. ctx.ServerError("ChangeMilestoneStatus", err)
  1224. return
  1225. }
  1226. }
  1227. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
  1228. default:
  1229. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1230. }
  1231. }
  1232. // DeleteMilestone delete a milestone
  1233. func DeleteMilestone(ctx *context.Context) {
  1234. if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  1235. ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1236. } else {
  1237. ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
  1238. }
  1239. ctx.JSON(200, map[string]interface{}{
  1240. "redirect": ctx.Repo.RepoLink + "/milestones",
  1241. })
  1242. }
  1243. // ChangeIssueReaction create a reaction for issue
  1244. func ChangeIssueReaction(ctx *context.Context, form auth.ReactionForm) {
  1245. issue := GetActionIssue(ctx)
  1246. if ctx.Written() {
  1247. return
  1248. }
  1249. if ctx.HasError() {
  1250. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1251. return
  1252. }
  1253. switch ctx.Params(":action") {
  1254. case "react":
  1255. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1256. if err != nil {
  1257. log.Info("CreateIssueReaction: %s", err)
  1258. break
  1259. }
  1260. // Reload new reactions
  1261. issue.Reactions = nil
  1262. if err = issue.LoadAttributes(); err != nil {
  1263. log.Info("issue.LoadAttributes: %s", err)
  1264. break
  1265. }
  1266. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1267. case "unreact":
  1268. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1269. ctx.ServerError("DeleteIssueReaction", err)
  1270. return
  1271. }
  1272. // Reload new reactions
  1273. issue.Reactions = nil
  1274. if err := issue.LoadAttributes(); err != nil {
  1275. log.Info("issue.LoadAttributes: %s", err)
  1276. break
  1277. }
  1278. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1279. default:
  1280. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1281. return
  1282. }
  1283. if len(issue.Reactions) == 0 {
  1284. ctx.JSON(200, map[string]interface{}{
  1285. "empty": true,
  1286. "html": "",
  1287. })
  1288. return
  1289. }
  1290. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1291. "ctx": ctx.Data,
  1292. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1293. "Reactions": issue.Reactions.GroupByType(),
  1294. })
  1295. if err != nil {
  1296. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  1297. return
  1298. }
  1299. ctx.JSON(200, map[string]interface{}{
  1300. "html": html,
  1301. })
  1302. }
  1303. // ChangeCommentReaction create a reaction for comment
  1304. func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
  1305. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1306. if err != nil {
  1307. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1308. return
  1309. }
  1310. issue, err := models.GetIssueByID(comment.IssueID)
  1311. checkIssueRights(ctx, issue)
  1312. if ctx.Written() {
  1313. return
  1314. }
  1315. if ctx.HasError() {
  1316. ctx.ServerError("ChangeCommentReaction", errors.New(ctx.GetErrMsg()))
  1317. return
  1318. }
  1319. switch ctx.Params(":action") {
  1320. case "react":
  1321. reaction, err := models.CreateCommentReaction(ctx.User, issue, comment, form.Content)
  1322. if err != nil {
  1323. log.Info("CreateCommentReaction: %s", err)
  1324. break
  1325. }
  1326. // Reload new reactions
  1327. comment.Reactions = nil
  1328. if err = comment.LoadReactions(); err != nil {
  1329. log.Info("comment.LoadReactions: %s", err)
  1330. break
  1331. }
  1332. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID, reaction.ID)
  1333. case "unreact":
  1334. if err := models.DeleteCommentReaction(ctx.User, issue, comment, form.Content); err != nil {
  1335. ctx.ServerError("DeleteCommentReaction", err)
  1336. return
  1337. }
  1338. // Reload new reactions
  1339. comment.Reactions = nil
  1340. if err = comment.LoadReactions(); err != nil {
  1341. log.Info("comment.LoadReactions: %s", err)
  1342. break
  1343. }
  1344. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1345. default:
  1346. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1347. return
  1348. }
  1349. if len(comment.Reactions) == 0 {
  1350. ctx.JSON(200, map[string]interface{}{
  1351. "empty": true,
  1352. "html": "",
  1353. })
  1354. return
  1355. }
  1356. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1357. "ctx": ctx.Data,
  1358. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  1359. "Reactions": comment.Reactions.GroupByType(),
  1360. })
  1361. if err != nil {
  1362. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  1363. return
  1364. }
  1365. ctx.JSON(200, map[string]interface{}{
  1366. "html": html,
  1367. })
  1368. }