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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002
  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"
  22. "code.gitea.io/gitea/modules/markup/markdown"
  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. pull_service "code.gitea.io/gitea/services/pull"
  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.CanWriteIssuesOrPulls(issue.IsPull) && !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([]int64{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 mileIDs []int64
  170. if milestoneID > 0 {
  171. mileIDs = []int64{milestoneID}
  172. }
  173. var issues []*models.Issue
  174. if forceEmpty {
  175. issues = []*models.Issue{}
  176. } else {
  177. issues, err = models.Issues(&models.IssuesOptions{
  178. ListOptions: models.ListOptions{
  179. Page: pager.Paginater.Current(),
  180. PageSize: setting.UI.IssuePagingNum,
  181. },
  182. RepoIDs: []int64{repo.ID},
  183. AssigneeID: assigneeID,
  184. PosterID: posterID,
  185. MentionedID: mentionedID,
  186. MilestoneIDs: mileIDs,
  187. IsClosed: util.OptionalBoolOf(isShowClosed),
  188. IsPull: isPullOption,
  189. LabelIDs: labelIDs,
  190. SortType: sortType,
  191. IssueIDs: issueIDs,
  192. })
  193. if err != nil {
  194. ctx.ServerError("Issues", err)
  195. return
  196. }
  197. }
  198. approvalCounts, err := models.IssueList(issues).GetApprovalCounts()
  199. if err != nil {
  200. ctx.ServerError("ApprovalCounts", err)
  201. return
  202. }
  203. var commitStatus = make(map[int64]*models.CommitStatus, len(issues))
  204. // Get posters.
  205. for i := range issues {
  206. // Check read status
  207. if !ctx.IsSigned {
  208. issues[i].IsRead = true
  209. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  210. ctx.ServerError("GetIsRead", err)
  211. return
  212. }
  213. if issues[i].IsPull {
  214. if err := issues[i].LoadPullRequest(); err != nil {
  215. ctx.ServerError("LoadPullRequest", err)
  216. return
  217. }
  218. commitStatus[issues[i].PullRequest.ID], _ = pull_service.GetLastCommitStatus(issues[i].PullRequest)
  219. }
  220. }
  221. ctx.Data["Issues"] = issues
  222. ctx.Data["CommitStatus"] = commitStatus
  223. // Get assignees.
  224. ctx.Data["Assignees"], err = repo.GetAssignees()
  225. if err != nil {
  226. ctx.ServerError("GetAssignees", err)
  227. return
  228. }
  229. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  230. if err != nil {
  231. ctx.ServerError("GetLabelsByRepoID", err)
  232. return
  233. }
  234. if repo.Owner.IsOrganization() {
  235. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  236. if err != nil {
  237. ctx.ServerError("GetLabelsByOrgID", err)
  238. return
  239. }
  240. ctx.Data["OrgLabels"] = orgLabels
  241. labels = append(labels, orgLabels...)
  242. }
  243. for _, l := range labels {
  244. l.LoadSelectedLabelsAfterClick(labelIDs)
  245. }
  246. ctx.Data["Labels"] = labels
  247. ctx.Data["NumLabels"] = len(labels)
  248. if ctx.QueryInt64("assignee") == 0 {
  249. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  250. }
  251. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
  252. issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
  253. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  254. counts, ok := approvalCounts[issueID]
  255. if !ok || len(counts) == 0 {
  256. return 0
  257. }
  258. reviewTyp := models.ReviewTypeApprove
  259. if typ == "reject" {
  260. reviewTyp = models.ReviewTypeReject
  261. } else if typ == "waiting" {
  262. reviewTyp = models.ReviewTypeRequest
  263. }
  264. for _, count := range counts {
  265. if count.Type == reviewTyp {
  266. return count.Count
  267. }
  268. }
  269. return 0
  270. }
  271. ctx.Data["IssueStats"] = issueStats
  272. ctx.Data["SelLabelIDs"] = labelIDs
  273. ctx.Data["SelectLabels"] = selectLabels
  274. ctx.Data["ViewType"] = viewType
  275. ctx.Data["SortType"] = sortType
  276. ctx.Data["MilestoneID"] = milestoneID
  277. ctx.Data["AssigneeID"] = assigneeID
  278. ctx.Data["IsShowClosed"] = isShowClosed
  279. ctx.Data["Keyword"] = keyword
  280. if isShowClosed {
  281. ctx.Data["State"] = "closed"
  282. } else {
  283. ctx.Data["State"] = "open"
  284. }
  285. pager.AddParam(ctx, "q", "Keyword")
  286. pager.AddParam(ctx, "type", "ViewType")
  287. pager.AddParam(ctx, "sort", "SortType")
  288. pager.AddParam(ctx, "state", "State")
  289. pager.AddParam(ctx, "labels", "SelectLabels")
  290. pager.AddParam(ctx, "milestone", "MilestoneID")
  291. pager.AddParam(ctx, "assignee", "AssigneeID")
  292. ctx.Data["Page"] = pager
  293. }
  294. // Issues render issues page
  295. func Issues(ctx *context.Context) {
  296. isPullList := ctx.Params(":type") == "pulls"
  297. if isPullList {
  298. MustAllowPulls(ctx)
  299. if ctx.Written() {
  300. return
  301. }
  302. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  303. ctx.Data["PageIsPullList"] = true
  304. } else {
  305. MustEnableIssues(ctx)
  306. if ctx.Written() {
  307. return
  308. }
  309. ctx.Data["Title"] = ctx.Tr("repo.issues")
  310. ctx.Data["PageIsIssueList"] = true
  311. }
  312. issues(ctx, ctx.QueryInt64("milestone"), util.OptionalBoolOf(isPullList))
  313. var err error
  314. // Get milestones.
  315. ctx.Data["Milestones"], err = models.GetMilestonesByRepoID(ctx.Repo.Repository.ID, api.StateType(ctx.Query("state")), models.ListOptions{})
  316. if err != nil {
  317. ctx.ServerError("GetAllRepoMilestones", err)
  318. return
  319. }
  320. ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList)
  321. ctx.HTML(200, tplIssues)
  322. }
  323. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  324. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  325. var err error
  326. ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false, "")
  327. if err != nil {
  328. ctx.ServerError("GetMilestones", err)
  329. return
  330. }
  331. ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true, "")
  332. if err != nil {
  333. ctx.ServerError("GetMilestones", err)
  334. return
  335. }
  336. ctx.Data["Assignees"], err = repo.GetAssignees()
  337. if err != nil {
  338. ctx.ServerError("GetAssignees", err)
  339. return
  340. }
  341. }
  342. // RetrieveRepoReviewers find all reviewers of a repository
  343. func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issuePosterID int64) {
  344. var err error
  345. ctx.Data["Reviewers"], err = repo.GetReviewers(ctx.User.ID, issuePosterID)
  346. if err != nil {
  347. ctx.ServerError("GetReviewers", err)
  348. return
  349. }
  350. }
  351. // RetrieveRepoMetas find all the meta information of a repository
  352. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository, isPull bool) []*models.Label {
  353. if !ctx.Repo.CanWriteIssuesOrPulls(isPull) {
  354. return nil
  355. }
  356. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  357. if err != nil {
  358. ctx.ServerError("GetLabelsByRepoID", err)
  359. return nil
  360. }
  361. ctx.Data["Labels"] = labels
  362. if repo.Owner.IsOrganization() {
  363. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  364. if err != nil {
  365. return nil
  366. }
  367. ctx.Data["OrgLabels"] = orgLabels
  368. labels = append(labels, orgLabels...)
  369. }
  370. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  371. if ctx.Written() {
  372. return nil
  373. }
  374. brs, err := ctx.Repo.GitRepo.GetBranches()
  375. if err != nil {
  376. ctx.ServerError("GetBranches", err)
  377. return nil
  378. }
  379. ctx.Data["Branches"] = brs
  380. // Contains true if the user can create issue dependencies
  381. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, isPull)
  382. return labels
  383. }
  384. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  385. var bytes []byte
  386. if ctx.Repo.Commit == nil {
  387. var err error
  388. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  389. if err != nil {
  390. return "", false
  391. }
  392. }
  393. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  394. if err != nil {
  395. return "", false
  396. }
  397. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  398. return "", false
  399. }
  400. r, err := entry.Blob().DataAsync()
  401. if err != nil {
  402. return "", false
  403. }
  404. defer r.Close()
  405. bytes, err = ioutil.ReadAll(r)
  406. if err != nil {
  407. return "", false
  408. }
  409. return string(bytes), true
  410. }
  411. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) {
  412. for _, filename := range possibleFiles {
  413. content, found := getFileContentFromDefaultBranch(ctx, filename)
  414. if found {
  415. ctx.Data[ctxDataKey] = content
  416. return
  417. }
  418. }
  419. }
  420. // NewIssue render creating issue page
  421. func NewIssue(ctx *context.Context) {
  422. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  423. ctx.Data["PageIsIssueList"] = true
  424. ctx.Data["RequireHighlightJS"] = true
  425. ctx.Data["RequireSimpleMDE"] = true
  426. ctx.Data["RequireTribute"] = true
  427. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  428. body := ctx.Query("body")
  429. ctx.Data["BodyQuery"] = body
  430. milestoneID := ctx.QueryInt64("milestone")
  431. if milestoneID > 0 {
  432. milestone, err := models.GetMilestoneByID(milestoneID)
  433. if err != nil {
  434. log.Error("GetMilestoneByID: %d: %v", milestoneID, err)
  435. } else {
  436. ctx.Data["milestone_id"] = milestoneID
  437. ctx.Data["Milestone"] = milestone
  438. }
  439. }
  440. setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates)
  441. renderAttachmentSettings(ctx)
  442. RetrieveRepoMetas(ctx, ctx.Repo.Repository, false)
  443. if ctx.Written() {
  444. return
  445. }
  446. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  447. ctx.HTML(200, tplIssueNew)
  448. }
  449. // ValidateRepoMetas check and returns repository's meta informations
  450. func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm, isPull bool) ([]int64, []int64, int64) {
  451. var (
  452. repo = ctx.Repo.Repository
  453. err error
  454. )
  455. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository, isPull)
  456. if ctx.Written() {
  457. return nil, nil, 0
  458. }
  459. var labelIDs []int64
  460. hasSelected := false
  461. // Check labels.
  462. if len(form.LabelIDs) > 0 {
  463. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  464. if err != nil {
  465. return nil, nil, 0
  466. }
  467. labelIDMark := base.Int64sToMap(labelIDs)
  468. for i := range labels {
  469. if labelIDMark[labels[i].ID] {
  470. labels[i].IsChecked = true
  471. hasSelected = true
  472. }
  473. }
  474. }
  475. ctx.Data["Labels"] = labels
  476. ctx.Data["HasSelectedLabel"] = hasSelected
  477. ctx.Data["label_ids"] = form.LabelIDs
  478. // Check milestone.
  479. milestoneID := form.MilestoneID
  480. if milestoneID > 0 {
  481. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  482. if err != nil {
  483. ctx.ServerError("GetMilestoneByID", err)
  484. return nil, nil, 0
  485. }
  486. ctx.Data["milestone_id"] = milestoneID
  487. }
  488. // Check assignees
  489. var assigneeIDs []int64
  490. if len(form.AssigneeIDs) > 0 {
  491. assigneeIDs, err = base.StringsToInt64s(strings.Split(form.AssigneeIDs, ","))
  492. if err != nil {
  493. return nil, nil, 0
  494. }
  495. // Check if the passed assignees actually exists and is assignable
  496. for _, aID := range assigneeIDs {
  497. assignee, err := models.GetUserByID(aID)
  498. if err != nil {
  499. ctx.ServerError("GetUserByID", err)
  500. return nil, nil, 0
  501. }
  502. valid, err := models.CanBeAssigned(assignee, repo, isPull)
  503. if err != nil {
  504. ctx.ServerError("canBeAssigned", err)
  505. return nil, nil, 0
  506. }
  507. if !valid {
  508. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  509. return nil, nil, 0
  510. }
  511. }
  512. }
  513. // Keep the old assignee id thingy for compatibility reasons
  514. if form.AssigneeID > 0 {
  515. assigneeIDs = append(assigneeIDs, form.AssigneeID)
  516. }
  517. return labelIDs, assigneeIDs, milestoneID
  518. }
  519. // NewIssuePost response for creating new issue
  520. func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
  521. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  522. ctx.Data["PageIsIssueList"] = true
  523. ctx.Data["RequireHighlightJS"] = true
  524. ctx.Data["RequireSimpleMDE"] = true
  525. ctx.Data["ReadOnly"] = false
  526. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  527. renderAttachmentSettings(ctx)
  528. var (
  529. repo = ctx.Repo.Repository
  530. attachments []string
  531. )
  532. labelIDs, assigneeIDs, milestoneID := ValidateRepoMetas(ctx, form, false)
  533. if ctx.Written() {
  534. return
  535. }
  536. if setting.AttachmentEnabled {
  537. attachments = form.Files
  538. }
  539. if ctx.HasError() {
  540. ctx.HTML(200, tplIssueNew)
  541. return
  542. }
  543. if util.IsEmptyString(form.Title) {
  544. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplIssueNew, form)
  545. return
  546. }
  547. issue := &models.Issue{
  548. RepoID: repo.ID,
  549. Title: form.Title,
  550. PosterID: ctx.User.ID,
  551. Poster: ctx.User,
  552. MilestoneID: milestoneID,
  553. Content: form.Content,
  554. Ref: form.Ref,
  555. }
  556. if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil {
  557. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  558. ctx.Error(400, "UserDoesNotHaveAccessToRepo", err.Error())
  559. return
  560. }
  561. ctx.ServerError("NewIssue", err)
  562. return
  563. }
  564. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  565. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  566. }
  567. // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
  568. func commentTag(repo *models.Repository, poster *models.User, issue *models.Issue) (models.CommentTag, error) {
  569. perm, err := models.GetUserRepoPermission(repo, poster)
  570. if err != nil {
  571. return models.CommentTagNone, err
  572. }
  573. if perm.IsOwner() {
  574. return models.CommentTagOwner, nil
  575. } else if poster.ID == issue.PosterID {
  576. return models.CommentTagPoster, nil
  577. } else if perm.CanWrite(models.UnitTypeCode) {
  578. return models.CommentTagWriter, nil
  579. }
  580. return models.CommentTagNone, nil
  581. }
  582. func getBranchData(ctx *context.Context, issue *models.Issue) {
  583. ctx.Data["BaseBranch"] = nil
  584. ctx.Data["HeadBranch"] = nil
  585. ctx.Data["HeadUserName"] = nil
  586. ctx.Data["BaseName"] = ctx.Repo.Repository.OwnerName
  587. if issue.IsPull {
  588. pull := issue.PullRequest
  589. ctx.Data["BaseBranch"] = pull.BaseBranch
  590. ctx.Data["HeadBranch"] = pull.HeadBranch
  591. ctx.Data["HeadUserName"] = pull.MustHeadUserName()
  592. }
  593. }
  594. // ViewIssue render issue view page
  595. func ViewIssue(ctx *context.Context) {
  596. if ctx.Params(":type") == "issues" {
  597. // If issue was requested we check if repo has external tracker and redirect
  598. extIssueUnit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  599. if err == nil && extIssueUnit != nil {
  600. if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
  601. metas := ctx.Repo.Repository.ComposeMetas()
  602. metas["index"] = ctx.Params(":index")
  603. ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas))
  604. return
  605. }
  606. } else if err != nil && !models.IsErrUnitTypeNotExist(err) {
  607. ctx.ServerError("GetUnit", err)
  608. return
  609. }
  610. }
  611. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  612. if err != nil {
  613. if models.IsErrIssueNotExist(err) {
  614. ctx.NotFound("GetIssueByIndex", err)
  615. } else {
  616. ctx.ServerError("GetIssueByIndex", err)
  617. }
  618. return
  619. }
  620. // Make sure type and URL matches.
  621. if ctx.Params(":type") == "issues" && issue.IsPull {
  622. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  623. return
  624. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  625. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  626. return
  627. }
  628. if issue.IsPull {
  629. MustAllowPulls(ctx)
  630. if ctx.Written() {
  631. return
  632. }
  633. ctx.Data["PageIsPullList"] = true
  634. ctx.Data["PageIsPullConversation"] = true
  635. } else {
  636. MustEnableIssues(ctx)
  637. if ctx.Written() {
  638. return
  639. }
  640. ctx.Data["PageIsIssueList"] = true
  641. }
  642. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  643. ctx.Data["IssueType"] = "pulls"
  644. } else if !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) {
  645. ctx.Data["IssueType"] = "issues"
  646. } else {
  647. ctx.Data["IssueType"] = "all"
  648. }
  649. ctx.Data["RequireHighlightJS"] = true
  650. ctx.Data["RequireTribute"] = true
  651. ctx.Data["RequireSimpleMDE"] = true
  652. renderAttachmentSettings(ctx)
  653. if err = issue.LoadAttributes(); err != nil {
  654. ctx.ServerError("LoadAttributes", err)
  655. return
  656. }
  657. if err = filterXRefComments(ctx, issue); err != nil {
  658. ctx.ServerError("filterXRefComments", err)
  659. return
  660. }
  661. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  662. iw := new(models.IssueWatch)
  663. if ctx.User != nil {
  664. iw.UserID = ctx.User.ID
  665. iw.IssueID = issue.ID
  666. iw.IsWatching, err = models.CheckIssueWatch(ctx.User, issue)
  667. if err != nil {
  668. ctx.InternalServerError(err)
  669. return
  670. }
  671. }
  672. ctx.Data["IssueWatch"] = iw
  673. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  674. ctx.Repo.Repository.ComposeMetas()))
  675. repo := ctx.Repo.Repository
  676. // Get more information if it's a pull request.
  677. if issue.IsPull {
  678. if issue.PullRequest.HasMerged {
  679. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  680. PrepareMergedViewPullInfo(ctx, issue)
  681. } else {
  682. PrepareViewPullInfo(ctx, issue)
  683. ctx.Data["DisableStatusChange"] = ctx.Data["IsPullRequestBroken"] == true && issue.IsClosed
  684. }
  685. if ctx.Written() {
  686. return
  687. }
  688. }
  689. // Metas.
  690. // Check labels.
  691. labelIDMark := make(map[int64]bool)
  692. for i := range issue.Labels {
  693. labelIDMark[issue.Labels[i].ID] = true
  694. }
  695. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  696. if err != nil {
  697. ctx.ServerError("GetLabelsByRepoID", err)
  698. return
  699. }
  700. ctx.Data["Labels"] = labels
  701. if repo.Owner.IsOrganization() {
  702. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.Query("sort"), models.ListOptions{})
  703. if err != nil {
  704. ctx.ServerError("GetLabelsByOrgID", err)
  705. return
  706. }
  707. ctx.Data["OrgLabels"] = orgLabels
  708. labels = append(labels, orgLabels...)
  709. }
  710. hasSelected := false
  711. for i := range labels {
  712. if labelIDMark[labels[i].ID] {
  713. labels[i].IsChecked = true
  714. hasSelected = true
  715. }
  716. }
  717. ctx.Data["HasSelectedLabel"] = hasSelected
  718. // Check milestone and assignee.
  719. if ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
  720. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  721. if ctx.Written() {
  722. return
  723. }
  724. }
  725. if issue.IsPull {
  726. canChooseReviewer := ctx.Repo.CanWrite(models.UnitTypePullRequests)
  727. if !canChooseReviewer && ctx.User != nil && ctx.IsSigned {
  728. canChooseReviewer, err = models.IsOfficialReviewer(issue, ctx.User)
  729. if err != nil {
  730. ctx.ServerError("IsOfficialReviewer", err)
  731. return
  732. }
  733. }
  734. if canChooseReviewer {
  735. RetrieveRepoReviewers(ctx, repo, issue.PosterID)
  736. ctx.Data["CanChooseReviewer"] = true
  737. } else {
  738. ctx.Data["CanChooseReviewer"] = false
  739. }
  740. if ctx.Written() {
  741. return
  742. }
  743. }
  744. if ctx.IsSigned {
  745. // Update issue-user.
  746. if err = issue.ReadBy(ctx.User.ID); err != nil {
  747. ctx.ServerError("ReadBy", err)
  748. return
  749. }
  750. }
  751. var (
  752. tag models.CommentTag
  753. ok bool
  754. marked = make(map[int64]models.CommentTag)
  755. comment *models.Comment
  756. participants = make([]*models.User, 1, 10)
  757. )
  758. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  759. if ctx.IsSigned {
  760. // Deal with the stopwatch
  761. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  762. if !ctx.Data["IsStopwatchRunning"].(bool) {
  763. var exists bool
  764. var sw *models.Stopwatch
  765. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  766. ctx.ServerError("HasUserStopwatch", err)
  767. return
  768. }
  769. ctx.Data["HasUserStopwatch"] = exists
  770. if exists {
  771. // Add warning if the user has already a stopwatch
  772. var otherIssue *models.Issue
  773. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  774. ctx.ServerError("GetIssueByID", err)
  775. return
  776. }
  777. if err = otherIssue.LoadRepo(); err != nil {
  778. ctx.ServerError("LoadRepo", err)
  779. return
  780. }
  781. // Add link to the issue of the already running stopwatch
  782. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  783. }
  784. }
  785. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  786. } else {
  787. ctx.Data["CanUseTimetracker"] = false
  788. }
  789. if ctx.Data["WorkingUsers"], err = models.TotalTimes(models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  790. ctx.ServerError("TotalTimes", err)
  791. return
  792. }
  793. }
  794. // Check if the user can use the dependencies
  795. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, issue.IsPull)
  796. // check if dependencies can be created across repositories
  797. ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies
  798. // Render comments and and fetch participants.
  799. participants[0] = issue.Poster
  800. for _, comment = range issue.Comments {
  801. comment.Issue = issue
  802. if err := comment.LoadPoster(); err != nil {
  803. ctx.ServerError("LoadPoster", err)
  804. return
  805. }
  806. if comment.Type == models.CommentTypeComment {
  807. if err := comment.LoadAttachments(); err != nil {
  808. ctx.ServerError("LoadAttachments", err)
  809. return
  810. }
  811. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  812. ctx.Repo.Repository.ComposeMetas()))
  813. // Check tag.
  814. tag, ok = marked[comment.PosterID]
  815. if ok {
  816. comment.ShowTag = tag
  817. continue
  818. }
  819. comment.ShowTag, err = commentTag(repo, comment.Poster, issue)
  820. if err != nil {
  821. ctx.ServerError("commentTag", err)
  822. return
  823. }
  824. marked[comment.PosterID] = comment.ShowTag
  825. participants = addParticipant(comment.Poster, participants)
  826. } else if comment.Type == models.CommentTypeLabel {
  827. if err = comment.LoadLabel(); err != nil {
  828. ctx.ServerError("LoadLabel", err)
  829. return
  830. }
  831. } else if comment.Type == models.CommentTypeMilestone {
  832. if err = comment.LoadMilestone(); err != nil {
  833. ctx.ServerError("LoadMilestone", err)
  834. return
  835. }
  836. ghostMilestone := &models.Milestone{
  837. ID: -1,
  838. Name: ctx.Tr("repo.issues.deleted_milestone"),
  839. }
  840. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  841. comment.OldMilestone = ghostMilestone
  842. }
  843. if comment.MilestoneID > 0 && comment.Milestone == nil {
  844. comment.Milestone = ghostMilestone
  845. }
  846. } else if comment.Type == models.CommentTypeAssignees || comment.Type == models.CommentTypeReviewRequest {
  847. if err = comment.LoadAssigneeUser(); err != nil {
  848. ctx.ServerError("LoadAssigneeUser", err)
  849. return
  850. }
  851. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  852. if err = comment.LoadDepIssueDetails(); err != nil {
  853. ctx.ServerError("LoadDepIssueDetails", err)
  854. return
  855. }
  856. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview {
  857. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  858. ctx.Repo.Repository.ComposeMetas()))
  859. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  860. ctx.ServerError("LoadReview", err)
  861. return
  862. }
  863. participants = addParticipant(comment.Poster, participants)
  864. if comment.Review == nil {
  865. continue
  866. }
  867. if err = comment.Review.LoadAttributes(); err != nil {
  868. if !models.IsErrUserNotExist(err) {
  869. ctx.ServerError("Review.LoadAttributes", err)
  870. return
  871. }
  872. comment.Review.Reviewer = models.NewGhostUser()
  873. }
  874. if err = comment.Review.LoadCodeComments(); err != nil {
  875. ctx.ServerError("Review.LoadCodeComments", err)
  876. return
  877. }
  878. if err = comment.LoadResolveDoer(); err != nil {
  879. ctx.ServerError("LoadResolveDoer", err)
  880. return
  881. }
  882. }
  883. }
  884. getBranchData(ctx, issue)
  885. if issue.IsPull {
  886. pull := issue.PullRequest
  887. pull.Issue = issue
  888. canDelete := false
  889. ctx.Data["AllowMerge"] = false
  890. if ctx.IsSigned {
  891. if err := pull.LoadHeadRepo(); err != nil {
  892. log.Error("LoadHeadRepo: %v", err)
  893. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch {
  894. perm, err := models.GetUserRepoPermission(pull.HeadRepo, ctx.User)
  895. if err != nil {
  896. ctx.ServerError("GetUserRepoPermission", err)
  897. return
  898. }
  899. if perm.CanWrite(models.UnitTypeCode) {
  900. // Check if branch is not protected
  901. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch, ctx.User); err != nil {
  902. log.Error("IsProtectedBranch: %v", err)
  903. } else if !protected {
  904. canDelete = true
  905. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup"
  906. }
  907. }
  908. }
  909. if err := pull.LoadBaseRepo(); err != nil {
  910. log.Error("LoadBaseRepo: %v", err)
  911. }
  912. perm, err := models.GetUserRepoPermission(pull.BaseRepo, ctx.User)
  913. if err != nil {
  914. ctx.ServerError("GetUserRepoPermission", err)
  915. return
  916. }
  917. ctx.Data["AllowMerge"], err = pull_service.IsUserAllowedToMerge(pull, perm, ctx.User)
  918. if err != nil {
  919. ctx.ServerError("IsUserAllowedToMerge", err)
  920. return
  921. }
  922. if ctx.Data["CanMarkConversation"], err = models.CanMarkConversation(issue, ctx.User); err != nil {
  923. ctx.ServerError("CanMarkConversation", err)
  924. return
  925. }
  926. }
  927. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  928. if err != nil {
  929. ctx.ServerError("GetUnit", err)
  930. return
  931. }
  932. prConfig := prUnit.PullRequestsConfig()
  933. // Check correct values and select default
  934. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  935. !prConfig.IsMergeStyleAllowed(ms) {
  936. if prConfig.AllowMerge {
  937. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  938. } else if prConfig.AllowRebase {
  939. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  940. } else if prConfig.AllowRebaseMerge {
  941. ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge
  942. } else if prConfig.AllowSquash {
  943. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  944. } else {
  945. ctx.Data["MergeStyle"] = ""
  946. }
  947. }
  948. if err = pull.LoadProtectedBranch(); err != nil {
  949. ctx.ServerError("LoadProtectedBranch", err)
  950. return
  951. }
  952. if pull.ProtectedBranch != nil {
  953. cnt := pull.ProtectedBranch.GetGrantedApprovalsCount(pull)
  954. ctx.Data["IsBlockedByApprovals"] = !pull.ProtectedBranch.HasEnoughApprovals(pull)
  955. ctx.Data["IsBlockedByRejection"] = pull.ProtectedBranch.MergeBlockedByRejectedReview(pull)
  956. ctx.Data["IsBlockedByOutdatedBranch"] = pull.ProtectedBranch.MergeBlockedByOutdatedBranch(pull)
  957. ctx.Data["GrantedApprovals"] = cnt
  958. ctx.Data["RequireSigned"] = pull.ProtectedBranch.RequireSignedCommits
  959. }
  960. ctx.Data["WillSign"] = false
  961. if ctx.User != nil {
  962. sign, key, err := pull.SignMerge(ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName())
  963. ctx.Data["WillSign"] = sign
  964. ctx.Data["SigningKey"] = key
  965. if err != nil {
  966. if models.IsErrWontSign(err) {
  967. ctx.Data["WontSignReason"] = err.(*models.ErrWontSign).Reason
  968. } else {
  969. ctx.Data["WontSignReason"] = "error"
  970. log.Error("Error whilst checking if could sign pr %d in repo %s. Error: %v", pull.ID, pull.BaseRepo.FullName(), err)
  971. }
  972. }
  973. }
  974. ctx.Data["IsPullBranchDeletable"] = canDelete &&
  975. pull.HeadRepo != nil &&
  976. git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch) &&
  977. (!pull.HasMerged || ctx.Data["HeadBranchCommitID"] == ctx.Data["PullHeadCommitID"])
  978. ctx.Data["PullReviewers"], err = models.GetReviewersByIssueID(issue.ID)
  979. if err != nil {
  980. ctx.ServerError("GetReviewersByIssueID", err)
  981. return
  982. }
  983. }
  984. // Get Dependencies
  985. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  986. if err != nil {
  987. ctx.ServerError("BlockedByDependencies", err)
  988. return
  989. }
  990. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  991. if err != nil {
  992. ctx.ServerError("BlockingDependencies", err)
  993. return
  994. }
  995. ctx.Data["Participants"] = participants
  996. ctx.Data["NumParticipants"] = len(participants)
  997. ctx.Data["Issue"] = issue
  998. ctx.Data["ReadOnly"] = true
  999. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  1000. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
  1001. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  1002. ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
  1003. ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
  1004. ctx.Data["RefEndName"] = git.RefEndName(issue.Ref)
  1005. ctx.HTML(200, tplIssueView)
  1006. }
  1007. // GetActionIssue will return the issue which is used in the context.
  1008. func GetActionIssue(ctx *context.Context) *models.Issue {
  1009. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1010. if err != nil {
  1011. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  1012. return nil
  1013. }
  1014. issue.Repo = ctx.Repo.Repository
  1015. checkIssueRights(ctx, issue)
  1016. if ctx.Written() {
  1017. return nil
  1018. }
  1019. if err = issue.LoadAttributes(); err != nil {
  1020. ctx.ServerError("LoadAttributes", nil)
  1021. return nil
  1022. }
  1023. return issue
  1024. }
  1025. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  1026. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) ||
  1027. !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  1028. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1029. }
  1030. }
  1031. func getActionIssues(ctx *context.Context) []*models.Issue {
  1032. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  1033. if len(commaSeparatedIssueIDs) == 0 {
  1034. return nil
  1035. }
  1036. issueIDs := make([]int64, 0, 10)
  1037. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  1038. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  1039. if err != nil {
  1040. ctx.ServerError("ParseInt", err)
  1041. return nil
  1042. }
  1043. issueIDs = append(issueIDs, issueID)
  1044. }
  1045. issues, err := models.GetIssuesByIDs(issueIDs)
  1046. if err != nil {
  1047. ctx.ServerError("GetIssuesByIDs", err)
  1048. return nil
  1049. }
  1050. // Check access rights for all issues
  1051. issueUnitEnabled := ctx.Repo.CanRead(models.UnitTypeIssues)
  1052. prUnitEnabled := ctx.Repo.CanRead(models.UnitTypePullRequests)
  1053. for _, issue := range issues {
  1054. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  1055. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1056. return nil
  1057. }
  1058. if err = issue.LoadAttributes(); err != nil {
  1059. ctx.ServerError("LoadAttributes", err)
  1060. return nil
  1061. }
  1062. }
  1063. return issues
  1064. }
  1065. // UpdateIssueTitle change issue's title
  1066. func UpdateIssueTitle(ctx *context.Context) {
  1067. issue := GetActionIssue(ctx)
  1068. if ctx.Written() {
  1069. return
  1070. }
  1071. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1072. ctx.Error(403)
  1073. return
  1074. }
  1075. title := ctx.QueryTrim("title")
  1076. if len(title) == 0 {
  1077. ctx.Error(204)
  1078. return
  1079. }
  1080. if err := issue_service.ChangeTitle(issue, ctx.User, title); err != nil {
  1081. ctx.ServerError("ChangeTitle", err)
  1082. return
  1083. }
  1084. ctx.JSON(200, map[string]interface{}{
  1085. "title": issue.Title,
  1086. })
  1087. }
  1088. // UpdateIssueContent change issue's content
  1089. func UpdateIssueContent(ctx *context.Context) {
  1090. issue := GetActionIssue(ctx)
  1091. if ctx.Written() {
  1092. return
  1093. }
  1094. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1095. ctx.Error(403)
  1096. return
  1097. }
  1098. content := ctx.Query("content")
  1099. if err := issue_service.ChangeContent(issue, ctx.User, content); err != nil {
  1100. ctx.ServerError("ChangeContent", err)
  1101. return
  1102. }
  1103. files := ctx.QueryStrings("files[]")
  1104. if err := updateAttachments(issue, files); err != nil {
  1105. ctx.ServerError("UpdateAttachments", err)
  1106. }
  1107. ctx.JSON(200, map[string]interface{}{
  1108. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1109. "attachments": attachmentsHTML(ctx, issue.Attachments),
  1110. })
  1111. }
  1112. // UpdateIssueMilestone change issue's milestone
  1113. func UpdateIssueMilestone(ctx *context.Context) {
  1114. issues := getActionIssues(ctx)
  1115. if ctx.Written() {
  1116. return
  1117. }
  1118. milestoneID := ctx.QueryInt64("id")
  1119. for _, issue := range issues {
  1120. oldMilestoneID := issue.MilestoneID
  1121. if oldMilestoneID == milestoneID {
  1122. continue
  1123. }
  1124. issue.MilestoneID = milestoneID
  1125. if err := issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  1126. ctx.ServerError("ChangeMilestoneAssign", err)
  1127. return
  1128. }
  1129. }
  1130. ctx.JSON(200, map[string]interface{}{
  1131. "ok": true,
  1132. })
  1133. }
  1134. // UpdateIssueAssignee change issue's or pull's assignee
  1135. func UpdateIssueAssignee(ctx *context.Context) {
  1136. issues := getActionIssues(ctx)
  1137. if ctx.Written() {
  1138. return
  1139. }
  1140. assigneeID := ctx.QueryInt64("id")
  1141. action := ctx.Query("action")
  1142. for _, issue := range issues {
  1143. switch action {
  1144. case "clear":
  1145. if err := issue_service.DeleteNotPassedAssignee(issue, ctx.User, []*models.User{}); err != nil {
  1146. ctx.ServerError("ClearAssignees", err)
  1147. return
  1148. }
  1149. default:
  1150. assignee, err := models.GetUserByID(assigneeID)
  1151. if err != nil {
  1152. ctx.ServerError("GetUserByID", err)
  1153. return
  1154. }
  1155. valid, err := models.CanBeAssigned(assignee, issue.Repo, issue.IsPull)
  1156. if err != nil {
  1157. ctx.ServerError("canBeAssigned", err)
  1158. return
  1159. }
  1160. if !valid {
  1161. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: issue.Repo.Name})
  1162. return
  1163. }
  1164. _, _, err = issue_service.ToggleAssignee(issue, ctx.User, assigneeID)
  1165. if err != nil {
  1166. ctx.ServerError("ToggleAssignee", err)
  1167. return
  1168. }
  1169. }
  1170. }
  1171. ctx.JSON(200, map[string]interface{}{
  1172. "ok": true,
  1173. })
  1174. }
  1175. func isLegalReviewRequest(reviewer, doer *models.User, isAdd bool, issue *models.Issue) error {
  1176. if reviewer.IsOrganization() {
  1177. return fmt.Errorf("Organization can't be added as reviewer [user_id: %d, repo_id: %d]", reviewer.ID, issue.PullRequest.BaseRepo.ID)
  1178. }
  1179. if doer.IsOrganization() {
  1180. return fmt.Errorf("Organization can't be doer to add reviewer [user_id: %d, repo_id: %d]", doer.ID, issue.PullRequest.BaseRepo.ID)
  1181. }
  1182. permReviewer, err := models.GetUserRepoPermission(issue.Repo, reviewer)
  1183. if err != nil {
  1184. return err
  1185. }
  1186. permDoer, err := models.GetUserRepoPermission(issue.Repo, doer)
  1187. if err != nil {
  1188. return err
  1189. }
  1190. lastreview, err := models.GetReviewerByIssueIDAndUserID(issue.ID, reviewer.ID)
  1191. if err != nil {
  1192. return err
  1193. }
  1194. var pemResult bool
  1195. if isAdd {
  1196. pemResult = permReviewer.CanAccessAny(models.AccessModeRead, models.UnitTypePullRequests)
  1197. if !pemResult {
  1198. return fmt.Errorf("Reviewer can't read [user_id: %d, repo_name: %s]", reviewer.ID, issue.Repo.Name)
  1199. }
  1200. if doer.ID == issue.PosterID && lastreview != nil && lastreview.Type != models.ReviewTypeRequest {
  1201. return nil
  1202. }
  1203. pemResult = permDoer.CanAccessAny(models.AccessModeWrite, models.UnitTypePullRequests)
  1204. if !pemResult {
  1205. pemResult, err = models.IsOfficialReviewer(issue, doer)
  1206. if err != nil {
  1207. return err
  1208. }
  1209. if !pemResult {
  1210. return fmt.Errorf("Doer can't choose reviewer [user_id: %d, repo_name: %s, issue_id: %d]", doer.ID, issue.Repo.Name, issue.ID)
  1211. }
  1212. }
  1213. if doer.ID == reviewer.ID {
  1214. return fmt.Errorf("doer can't be reviewer [user_id: %d, repo_name: %s]", doer.ID, issue.Repo.Name)
  1215. }
  1216. if reviewer.ID == issue.PosterID {
  1217. return fmt.Errorf("poster of pr can't be reviewer [user_id: %d, repo_name: %s]", reviewer.ID, issue.Repo.Name)
  1218. }
  1219. } else {
  1220. if lastreview.Type == models.ReviewTypeRequest && lastreview.ReviewerID == doer.ID {
  1221. return nil
  1222. }
  1223. pemResult = permDoer.IsAdmin()
  1224. if !pemResult {
  1225. return fmt.Errorf("Doer is not admin [user_id: %d, repo_name: %s]", doer.ID, issue.Repo.Name)
  1226. }
  1227. }
  1228. return nil
  1229. }
  1230. // updatePullReviewRequest change pull's request reviewers
  1231. func updatePullReviewRequest(ctx *context.Context) {
  1232. issues := getActionIssues(ctx)
  1233. if ctx.Written() {
  1234. return
  1235. }
  1236. reviewID := ctx.QueryInt64("id")
  1237. event := ctx.Query("is_add")
  1238. if event != "add" && event != "remove" {
  1239. ctx.ServerError("updatePullReviewRequest", fmt.Errorf("is_add should not be \"%s\"", event))
  1240. return
  1241. }
  1242. for _, issue := range issues {
  1243. if issue.IsPull {
  1244. reviewer, err := models.GetUserByID(reviewID)
  1245. if err != nil {
  1246. ctx.ServerError("GetUserByID", err)
  1247. return
  1248. }
  1249. err = isLegalReviewRequest(reviewer, ctx.User, event == "add", issue)
  1250. if err != nil {
  1251. ctx.ServerError("isLegalRequestReview", err)
  1252. return
  1253. }
  1254. err = issue_service.ReviewRequest(issue, ctx.User, reviewer, event == "add")
  1255. if err != nil {
  1256. ctx.ServerError("ReviewRequest", err)
  1257. return
  1258. }
  1259. } else {
  1260. ctx.ServerError("updatePullReviewRequest", fmt.Errorf("%d in %d is not Pull Request", issue.ID, issue.Repo.ID))
  1261. }
  1262. }
  1263. ctx.JSON(200, map[string]interface{}{
  1264. "ok": true,
  1265. })
  1266. }
  1267. // UpdatePullReviewRequest add or remove review request
  1268. func UpdatePullReviewRequest(ctx *context.Context) {
  1269. updatePullReviewRequest(ctx)
  1270. }
  1271. // UpdateIssueStatus change issue's status
  1272. func UpdateIssueStatus(ctx *context.Context) {
  1273. issues := getActionIssues(ctx)
  1274. if ctx.Written() {
  1275. return
  1276. }
  1277. var isClosed bool
  1278. switch action := ctx.Query("action"); action {
  1279. case "open":
  1280. isClosed = false
  1281. case "close":
  1282. isClosed = true
  1283. default:
  1284. log.Warn("Unrecognized action: %s", action)
  1285. }
  1286. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  1287. ctx.ServerError("LoadRepositories", err)
  1288. return
  1289. }
  1290. for _, issue := range issues {
  1291. if issue.IsClosed != isClosed {
  1292. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1293. if models.IsErrDependenciesLeft(err) {
  1294. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  1295. "error": "cannot close this issue because it still has open dependencies",
  1296. })
  1297. return
  1298. }
  1299. ctx.ServerError("ChangeStatus", err)
  1300. return
  1301. }
  1302. }
  1303. }
  1304. ctx.JSON(200, map[string]interface{}{
  1305. "ok": true,
  1306. })
  1307. }
  1308. // NewComment create a comment for issue
  1309. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  1310. issue := GetActionIssue(ctx)
  1311. if ctx.Written() {
  1312. return
  1313. }
  1314. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1315. if log.IsTrace() {
  1316. if ctx.IsSigned {
  1317. issueType := "issues"
  1318. if issue.IsPull {
  1319. issueType = "pulls"
  1320. }
  1321. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1322. "User in Repo has Permissions: %-+v",
  1323. ctx.User,
  1324. log.NewColoredIDValue(issue.PosterID),
  1325. issueType,
  1326. ctx.Repo.Repository,
  1327. ctx.Repo.Permission)
  1328. } else {
  1329. log.Trace("Permission Denied: Not logged in")
  1330. }
  1331. }
  1332. ctx.Error(403)
  1333. return
  1334. }
  1335. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  1336. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  1337. ctx.Redirect(issue.HTMLURL(), http.StatusSeeOther)
  1338. return
  1339. }
  1340. var attachments []string
  1341. if setting.AttachmentEnabled {
  1342. attachments = form.Files
  1343. }
  1344. if ctx.HasError() {
  1345. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  1346. ctx.Redirect(issue.HTMLURL())
  1347. return
  1348. }
  1349. var comment *models.Comment
  1350. defer func() {
  1351. // Check if issue admin/poster changes the status of issue.
  1352. if (ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  1353. (form.Status == "reopen" || form.Status == "close") &&
  1354. !(issue.IsPull && issue.PullRequest.HasMerged) {
  1355. // Duplication and conflict check should apply to reopen pull request.
  1356. var pr *models.PullRequest
  1357. if form.Status == "reopen" && issue.IsPull {
  1358. pull := issue.PullRequest
  1359. var err error
  1360. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  1361. if err != nil {
  1362. if !models.IsErrPullRequestNotExist(err) {
  1363. ctx.ServerError("GetUnmergedPullRequest", err)
  1364. return
  1365. }
  1366. }
  1367. // Regenerate patch and test conflict.
  1368. if pr == nil {
  1369. pull_service.AddToTaskQueue(issue.PullRequest)
  1370. }
  1371. }
  1372. if pr != nil {
  1373. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  1374. } else {
  1375. isClosed := form.Status == "close"
  1376. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1377. log.Error("ChangeStatus: %v", err)
  1378. if models.IsErrDependenciesLeft(err) {
  1379. if issue.IsPull {
  1380. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  1381. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1382. } else {
  1383. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  1384. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1385. }
  1386. return
  1387. }
  1388. } else {
  1389. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  1390. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  1391. return
  1392. }
  1393. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  1394. }
  1395. }
  1396. }
  1397. // Redirect to comment hashtag if there is any actual content.
  1398. typeName := "issues"
  1399. if issue.IsPull {
  1400. typeName = "pulls"
  1401. }
  1402. if comment != nil {
  1403. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  1404. } else {
  1405. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  1406. }
  1407. }()
  1408. // Fix #321: Allow empty comments, as long as we have attachments.
  1409. if len(form.Content) == 0 && len(attachments) == 0 {
  1410. return
  1411. }
  1412. comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  1413. if err != nil {
  1414. ctx.ServerError("CreateIssueComment", err)
  1415. return
  1416. }
  1417. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1418. }
  1419. // UpdateCommentContent change comment of issue's content
  1420. func UpdateCommentContent(ctx *context.Context) {
  1421. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1422. if err != nil {
  1423. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1424. return
  1425. }
  1426. if err := comment.LoadIssue(); err != nil {
  1427. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1428. return
  1429. }
  1430. if comment.Type == models.CommentTypeComment {
  1431. if err := comment.LoadAttachments(); err != nil {
  1432. ctx.ServerError("LoadAttachments", err)
  1433. return
  1434. }
  1435. }
  1436. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1437. ctx.Error(403)
  1438. return
  1439. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1440. ctx.Error(204)
  1441. return
  1442. }
  1443. oldContent := comment.Content
  1444. comment.Content = ctx.Query("content")
  1445. if len(comment.Content) == 0 {
  1446. ctx.JSON(200, map[string]interface{}{
  1447. "content": "",
  1448. })
  1449. return
  1450. }
  1451. if err = comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil {
  1452. ctx.ServerError("UpdateComment", err)
  1453. return
  1454. }
  1455. files := ctx.QueryStrings("files[]")
  1456. if err := updateAttachments(comment, files); err != nil {
  1457. ctx.ServerError("UpdateAttachments", err)
  1458. }
  1459. ctx.JSON(200, map[string]interface{}{
  1460. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1461. "attachments": attachmentsHTML(ctx, comment.Attachments),
  1462. })
  1463. }
  1464. // DeleteComment delete comment of issue
  1465. func DeleteComment(ctx *context.Context) {
  1466. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1467. if err != nil {
  1468. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1469. return
  1470. }
  1471. if err := comment.LoadIssue(); err != nil {
  1472. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1473. return
  1474. }
  1475. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1476. ctx.Error(403)
  1477. return
  1478. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1479. ctx.Error(204)
  1480. return
  1481. }
  1482. if err = comment_service.DeleteComment(comment, ctx.User); err != nil {
  1483. ctx.ServerError("DeleteCommentByID", err)
  1484. return
  1485. }
  1486. ctx.Status(200)
  1487. }
  1488. // ChangeIssueReaction create a reaction for issue
  1489. func ChangeIssueReaction(ctx *context.Context, form auth.ReactionForm) {
  1490. issue := GetActionIssue(ctx)
  1491. if ctx.Written() {
  1492. return
  1493. }
  1494. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1495. if log.IsTrace() {
  1496. if ctx.IsSigned {
  1497. issueType := "issues"
  1498. if issue.IsPull {
  1499. issueType = "pulls"
  1500. }
  1501. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1502. "User in Repo has Permissions: %-+v",
  1503. ctx.User,
  1504. log.NewColoredIDValue(issue.PosterID),
  1505. issueType,
  1506. ctx.Repo.Repository,
  1507. ctx.Repo.Permission)
  1508. } else {
  1509. log.Trace("Permission Denied: Not logged in")
  1510. }
  1511. }
  1512. ctx.Error(403)
  1513. return
  1514. }
  1515. if ctx.HasError() {
  1516. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1517. return
  1518. }
  1519. switch ctx.Params(":action") {
  1520. case "react":
  1521. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1522. if err != nil {
  1523. if models.IsErrForbiddenIssueReaction(err) {
  1524. ctx.ServerError("ChangeIssueReaction", err)
  1525. return
  1526. }
  1527. log.Info("CreateIssueReaction: %s", err)
  1528. break
  1529. }
  1530. // Reload new reactions
  1531. issue.Reactions = nil
  1532. if err = issue.LoadAttributes(); err != nil {
  1533. log.Info("issue.LoadAttributes: %s", err)
  1534. break
  1535. }
  1536. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1537. case "unreact":
  1538. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1539. ctx.ServerError("DeleteIssueReaction", err)
  1540. return
  1541. }
  1542. // Reload new reactions
  1543. issue.Reactions = nil
  1544. if err := issue.LoadAttributes(); err != nil {
  1545. log.Info("issue.LoadAttributes: %s", err)
  1546. break
  1547. }
  1548. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1549. default:
  1550. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1551. return
  1552. }
  1553. if len(issue.Reactions) == 0 {
  1554. ctx.JSON(200, map[string]interface{}{
  1555. "empty": true,
  1556. "html": "",
  1557. })
  1558. return
  1559. }
  1560. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1561. "ctx": ctx.Data,
  1562. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1563. "Reactions": issue.Reactions.GroupByType(),
  1564. })
  1565. if err != nil {
  1566. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  1567. return
  1568. }
  1569. ctx.JSON(200, map[string]interface{}{
  1570. "html": html,
  1571. })
  1572. }
  1573. // ChangeCommentReaction create a reaction for comment
  1574. func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
  1575. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1576. if err != nil {
  1577. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1578. return
  1579. }
  1580. if err := comment.LoadIssue(); err != nil {
  1581. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1582. return
  1583. }
  1584. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanReadIssuesOrPulls(comment.Issue.IsPull)) {
  1585. if log.IsTrace() {
  1586. if ctx.IsSigned {
  1587. issueType := "issues"
  1588. if comment.Issue.IsPull {
  1589. issueType = "pulls"
  1590. }
  1591. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1592. "User in Repo has Permissions: %-+v",
  1593. ctx.User,
  1594. log.NewColoredIDValue(comment.Issue.PosterID),
  1595. issueType,
  1596. ctx.Repo.Repository,
  1597. ctx.Repo.Permission)
  1598. } else {
  1599. log.Trace("Permission Denied: Not logged in")
  1600. }
  1601. }
  1602. ctx.Error(403)
  1603. return
  1604. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1605. ctx.Error(204)
  1606. return
  1607. }
  1608. switch ctx.Params(":action") {
  1609. case "react":
  1610. reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Content)
  1611. if err != nil {
  1612. if models.IsErrForbiddenIssueReaction(err) {
  1613. ctx.ServerError("ChangeIssueReaction", err)
  1614. return
  1615. }
  1616. log.Info("CreateCommentReaction: %s", err)
  1617. break
  1618. }
  1619. // Reload new reactions
  1620. comment.Reactions = nil
  1621. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  1622. log.Info("comment.LoadReactions: %s", err)
  1623. break
  1624. }
  1625. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
  1626. case "unreact":
  1627. if err := models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Content); err != nil {
  1628. ctx.ServerError("DeleteCommentReaction", err)
  1629. return
  1630. }
  1631. // Reload new reactions
  1632. comment.Reactions = nil
  1633. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  1634. log.Info("comment.LoadReactions: %s", err)
  1635. break
  1636. }
  1637. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID)
  1638. default:
  1639. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1640. return
  1641. }
  1642. if len(comment.Reactions) == 0 {
  1643. ctx.JSON(200, map[string]interface{}{
  1644. "empty": true,
  1645. "html": "",
  1646. })
  1647. return
  1648. }
  1649. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1650. "ctx": ctx.Data,
  1651. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  1652. "Reactions": comment.Reactions.GroupByType(),
  1653. })
  1654. if err != nil {
  1655. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  1656. return
  1657. }
  1658. ctx.JSON(200, map[string]interface{}{
  1659. "html": html,
  1660. })
  1661. }
  1662. func addParticipant(poster *models.User, participants []*models.User) []*models.User {
  1663. for _, part := range participants {
  1664. if poster.ID == part.ID {
  1665. return participants
  1666. }
  1667. }
  1668. return append(participants, poster)
  1669. }
  1670. func filterXRefComments(ctx *context.Context, issue *models.Issue) error {
  1671. // Remove comments that the user has no permissions to see
  1672. for i := 0; i < len(issue.Comments); {
  1673. c := issue.Comments[i]
  1674. if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 {
  1675. var err error
  1676. // Set RefRepo for description in template
  1677. c.RefRepo, err = models.GetRepositoryByID(c.RefRepoID)
  1678. if err != nil {
  1679. return err
  1680. }
  1681. perm, err := models.GetUserRepoPermission(c.RefRepo, ctx.User)
  1682. if err != nil {
  1683. return err
  1684. }
  1685. if !perm.CanReadIssuesOrPulls(c.RefIsPull) {
  1686. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  1687. continue
  1688. }
  1689. }
  1690. i++
  1691. }
  1692. return nil
  1693. }
  1694. // GetIssueAttachments returns attachments for the issue
  1695. func GetIssueAttachments(ctx *context.Context) {
  1696. issue := GetActionIssue(ctx)
  1697. var attachments = make([]*api.Attachment, len(issue.Attachments))
  1698. for i := 0; i < len(issue.Attachments); i++ {
  1699. attachments[i] = issue.Attachments[i].APIFormat()
  1700. }
  1701. ctx.JSON(200, attachments)
  1702. }
  1703. // GetCommentAttachments returns attachments for the comment
  1704. func GetCommentAttachments(ctx *context.Context) {
  1705. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1706. if err != nil {
  1707. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1708. return
  1709. }
  1710. var attachments = make([]*api.Attachment, 0)
  1711. if comment.Type == models.CommentTypeComment {
  1712. if err := comment.LoadAttachments(); err != nil {
  1713. ctx.ServerError("LoadAttachments", err)
  1714. return
  1715. }
  1716. for i := 0; i < len(comment.Attachments); i++ {
  1717. attachments = append(attachments, comment.Attachments[i].APIFormat())
  1718. }
  1719. }
  1720. ctx.JSON(200, attachments)
  1721. }
  1722. func updateAttachments(item interface{}, files []string) error {
  1723. var attachments []*models.Attachment
  1724. switch content := item.(type) {
  1725. case *models.Issue:
  1726. attachments = content.Attachments
  1727. case *models.Comment:
  1728. attachments = content.Attachments
  1729. default:
  1730. return fmt.Errorf("Unknow Type")
  1731. }
  1732. for i := 0; i < len(attachments); i++ {
  1733. if util.IsStringInSlice(attachments[i].UUID, files) {
  1734. continue
  1735. }
  1736. if err := models.DeleteAttachment(attachments[i], true); err != nil {
  1737. return err
  1738. }
  1739. }
  1740. var err error
  1741. if len(files) > 0 {
  1742. switch content := item.(type) {
  1743. case *models.Issue:
  1744. err = content.UpdateAttachments(files)
  1745. case *models.Comment:
  1746. err = content.UpdateAttachments(files)
  1747. default:
  1748. return fmt.Errorf("Unknow Type")
  1749. }
  1750. if err != nil {
  1751. return err
  1752. }
  1753. }
  1754. switch content := item.(type) {
  1755. case *models.Issue:
  1756. content.Attachments, err = models.GetAttachmentsByIssueID(content.ID)
  1757. case *models.Comment:
  1758. content.Attachments, err = models.GetAttachmentsByCommentID(content.ID)
  1759. default:
  1760. return fmt.Errorf("Unknow Type")
  1761. }
  1762. return err
  1763. }
  1764. func attachmentsHTML(ctx *context.Context, attachments []*models.Attachment) string {
  1765. attachHTML, err := ctx.HTMLString(string(tplAttachment), map[string]interface{}{
  1766. "ctx": ctx.Data,
  1767. "Attachments": attachments,
  1768. })
  1769. if err != nil {
  1770. ctx.ServerError("attachmentsHTML.HTMLString", err)
  1771. return ""
  1772. }
  1773. return attachHTML
  1774. }