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

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