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 40KB

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