You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

issue.go 39KB

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