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

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