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

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