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

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