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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602
  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. "path"
  13. "strconv"
  14. "strings"
  15. "code.gitea.io/gitea/models"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/context"
  18. "code.gitea.io/gitea/modules/convert"
  19. "code.gitea.io/gitea/modules/git"
  20. issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
  21. "code.gitea.io/gitea/modules/log"
  22. "code.gitea.io/gitea/modules/markup"
  23. "code.gitea.io/gitea/modules/markup/markdown"
  24. "code.gitea.io/gitea/modules/setting"
  25. api "code.gitea.io/gitea/modules/structs"
  26. "code.gitea.io/gitea/modules/upload"
  27. "code.gitea.io/gitea/modules/util"
  28. "code.gitea.io/gitea/modules/web"
  29. comment_service "code.gitea.io/gitea/services/comments"
  30. "code.gitea.io/gitea/services/forms"
  31. issue_service "code.gitea.io/gitea/services/issue"
  32. pull_service "code.gitea.io/gitea/services/pull"
  33. "github.com/unknwon/com"
  34. )
  35. const (
  36. tplAttachment base.TplName = "repo/issue/view_content/attachments"
  37. tplIssues base.TplName = "repo/issue/list"
  38. tplIssueNew base.TplName = "repo/issue/new"
  39. tplIssueChoose base.TplName = "repo/issue/choose"
  40. tplIssueView base.TplName = "repo/issue/view"
  41. tplReactions base.TplName = "repo/issue/view_content/reactions"
  42. issueTemplateKey = "IssueTemplate"
  43. issueTemplateTitleKey = "IssueTemplateTitle"
  44. )
  45. var (
  46. // IssueTemplateCandidates issue templates
  47. IssueTemplateCandidates = []string{
  48. "ISSUE_TEMPLATE.md",
  49. "issue_template.md",
  50. ".gitea/ISSUE_TEMPLATE.md",
  51. ".gitea/issue_template.md",
  52. ".github/ISSUE_TEMPLATE.md",
  53. ".github/issue_template.md",
  54. }
  55. )
  56. // MustAllowUserComment checks to make sure if an issue is locked.
  57. // If locked and user has permissions to write to the repository,
  58. // then the comment is allowed, else it is blocked
  59. func MustAllowUserComment(ctx *context.Context) {
  60. issue := GetActionIssue(ctx)
  61. if ctx.Written() {
  62. return
  63. }
  64. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  65. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  66. ctx.Redirect(issue.HTMLURL())
  67. return
  68. }
  69. }
  70. // MustEnableIssues check if repository enable internal issues
  71. func MustEnableIssues(ctx *context.Context) {
  72. if !ctx.Repo.CanRead(models.UnitTypeIssues) &&
  73. !ctx.Repo.CanRead(models.UnitTypeExternalTracker) {
  74. ctx.NotFound("MustEnableIssues", nil)
  75. return
  76. }
  77. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  78. if err == nil {
  79. ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL)
  80. return
  81. }
  82. }
  83. // MustAllowPulls check if repository enable pull requests and user have right to do that
  84. func MustAllowPulls(ctx *context.Context) {
  85. if !ctx.Repo.Repository.CanEnablePulls() || !ctx.Repo.CanRead(models.UnitTypePullRequests) {
  86. ctx.NotFound("MustAllowPulls", nil)
  87. return
  88. }
  89. // User can send pull request if owns a forked repository.
  90. if ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID) {
  91. ctx.Repo.PullRequest.Allowed = true
  92. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  93. }
  94. }
  95. func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption util.OptionalBool) {
  96. var err error
  97. viewType := ctx.FormString("type")
  98. sortType := ctx.FormString("sort")
  99. types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned", "review_requested"}
  100. if !util.IsStringInSlice(viewType, types, true) {
  101. viewType = "all"
  102. }
  103. var (
  104. assigneeID = ctx.FormInt64("assignee")
  105. posterID int64
  106. mentionedID int64
  107. reviewRequestedID int64
  108. forceEmpty bool
  109. )
  110. if ctx.IsSigned {
  111. switch viewType {
  112. case "created_by":
  113. posterID = ctx.User.ID
  114. case "mentioned":
  115. mentionedID = ctx.User.ID
  116. case "assigned":
  117. assigneeID = ctx.User.ID
  118. case "review_requested":
  119. reviewRequestedID = ctx.User.ID
  120. }
  121. }
  122. repo := ctx.Repo.Repository
  123. var labelIDs []int64
  124. selectLabels := ctx.FormString("labels")
  125. if len(selectLabels) > 0 && selectLabels != "0" {
  126. labelIDs, err = base.StringsToInt64s(strings.Split(selectLabels, ","))
  127. if err != nil {
  128. ctx.ServerError("StringsToInt64s", err)
  129. return
  130. }
  131. }
  132. keyword := strings.Trim(ctx.FormString("q"), " ")
  133. if bytes.Contains([]byte(keyword), []byte{0x00}) {
  134. keyword = ""
  135. }
  136. var issueIDs []int64
  137. if len(keyword) > 0 {
  138. issueIDs, err = issue_indexer.SearchIssuesByKeyword([]int64{repo.ID}, keyword)
  139. if err != nil {
  140. ctx.ServerError("issueIndexer.Search", err)
  141. return
  142. }
  143. if len(issueIDs) == 0 {
  144. forceEmpty = true
  145. }
  146. }
  147. var issueStats *models.IssueStats
  148. if forceEmpty {
  149. issueStats = &models.IssueStats{}
  150. } else {
  151. issueStats, err = models.GetIssueStats(&models.IssueStatsOptions{
  152. RepoID: repo.ID,
  153. Labels: selectLabels,
  154. MilestoneID: milestoneID,
  155. AssigneeID: assigneeID,
  156. MentionedID: mentionedID,
  157. PosterID: posterID,
  158. ReviewRequestedID: reviewRequestedID,
  159. IsPull: isPullOption,
  160. IssueIDs: issueIDs,
  161. })
  162. if err != nil {
  163. ctx.ServerError("GetIssueStats", err)
  164. return
  165. }
  166. }
  167. isShowClosed := ctx.FormString("state") == "closed"
  168. // if open issues are zero and close don't, use closed as default
  169. if len(ctx.FormString("state")) == 0 && issueStats.OpenCount == 0 && issueStats.ClosedCount != 0 {
  170. isShowClosed = true
  171. }
  172. page := ctx.FormInt("page")
  173. if page <= 1 {
  174. page = 1
  175. }
  176. var total int
  177. if !isShowClosed {
  178. total = int(issueStats.OpenCount)
  179. } else {
  180. total = int(issueStats.ClosedCount)
  181. }
  182. pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
  183. var mileIDs []int64
  184. if milestoneID > 0 {
  185. mileIDs = []int64{milestoneID}
  186. }
  187. var issues []*models.Issue
  188. if forceEmpty {
  189. issues = []*models.Issue{}
  190. } else {
  191. issues, err = models.Issues(&models.IssuesOptions{
  192. ListOptions: models.ListOptions{
  193. Page: pager.Paginater.Current(),
  194. PageSize: setting.UI.IssuePagingNum,
  195. },
  196. RepoIDs: []int64{repo.ID},
  197. AssigneeID: assigneeID,
  198. PosterID: posterID,
  199. MentionedID: mentionedID,
  200. ReviewRequestedID: reviewRequestedID,
  201. MilestoneIDs: mileIDs,
  202. ProjectID: projectID,
  203. IsClosed: util.OptionalBoolOf(isShowClosed),
  204. IsPull: isPullOption,
  205. LabelIDs: labelIDs,
  206. SortType: sortType,
  207. IssueIDs: issueIDs,
  208. })
  209. if err != nil {
  210. ctx.ServerError("Issues", err)
  211. return
  212. }
  213. }
  214. var issueList = models.IssueList(issues)
  215. approvalCounts, err := issueList.GetApprovalCounts()
  216. if err != nil {
  217. ctx.ServerError("ApprovalCounts", err)
  218. return
  219. }
  220. // Get posters.
  221. for i := range issues {
  222. // Check read status
  223. if !ctx.IsSigned {
  224. issues[i].IsRead = true
  225. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  226. ctx.ServerError("GetIsRead", err)
  227. return
  228. }
  229. }
  230. commitStatus, err := pull_service.GetIssuesLastCommitStatus(issues)
  231. if err != nil {
  232. ctx.ServerError("GetIssuesLastCommitStatus", err)
  233. return
  234. }
  235. ctx.Data["Issues"] = issues
  236. ctx.Data["CommitStatus"] = commitStatus
  237. // Get assignees.
  238. ctx.Data["Assignees"], err = repo.GetAssignees()
  239. if err != nil {
  240. ctx.ServerError("GetAssignees", err)
  241. return
  242. }
  243. handleTeamMentions(ctx)
  244. if ctx.Written() {
  245. return
  246. }
  247. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  248. if err != nil {
  249. ctx.ServerError("GetLabelsByRepoID", err)
  250. return
  251. }
  252. if repo.Owner.IsOrganization() {
  253. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), models.ListOptions{})
  254. if err != nil {
  255. ctx.ServerError("GetLabelsByOrgID", err)
  256. return
  257. }
  258. ctx.Data["OrgLabels"] = orgLabels
  259. labels = append(labels, orgLabels...)
  260. }
  261. for _, l := range labels {
  262. l.LoadSelectedLabelsAfterClick(labelIDs)
  263. }
  264. ctx.Data["Labels"] = labels
  265. ctx.Data["NumLabels"] = len(labels)
  266. if ctx.FormInt64("assignee") == 0 {
  267. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  268. }
  269. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
  270. issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
  271. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  272. counts, ok := approvalCounts[issueID]
  273. if !ok || len(counts) == 0 {
  274. return 0
  275. }
  276. reviewTyp := models.ReviewTypeApprove
  277. if typ == "reject" {
  278. reviewTyp = models.ReviewTypeReject
  279. } else if typ == "waiting" {
  280. reviewTyp = models.ReviewTypeRequest
  281. }
  282. for _, count := range counts {
  283. if count.Type == reviewTyp {
  284. return count.Count
  285. }
  286. }
  287. return 0
  288. }
  289. ctx.Data["IssueStats"] = issueStats
  290. ctx.Data["SelLabelIDs"] = labelIDs
  291. ctx.Data["SelectLabels"] = selectLabels
  292. ctx.Data["ViewType"] = viewType
  293. ctx.Data["SortType"] = sortType
  294. ctx.Data["MilestoneID"] = milestoneID
  295. ctx.Data["AssigneeID"] = assigneeID
  296. ctx.Data["IsShowClosed"] = isShowClosed
  297. ctx.Data["Keyword"] = keyword
  298. if isShowClosed {
  299. ctx.Data["State"] = "closed"
  300. } else {
  301. ctx.Data["State"] = "open"
  302. }
  303. pager.AddParam(ctx, "q", "Keyword")
  304. pager.AddParam(ctx, "type", "ViewType")
  305. pager.AddParam(ctx, "sort", "SortType")
  306. pager.AddParam(ctx, "state", "State")
  307. pager.AddParam(ctx, "labels", "SelectLabels")
  308. pager.AddParam(ctx, "milestone", "MilestoneID")
  309. pager.AddParam(ctx, "assignee", "AssigneeID")
  310. ctx.Data["Page"] = pager
  311. }
  312. // Issues render issues page
  313. func Issues(ctx *context.Context) {
  314. isPullList := ctx.Params(":type") == "pulls"
  315. if isPullList {
  316. MustAllowPulls(ctx)
  317. if ctx.Written() {
  318. return
  319. }
  320. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  321. ctx.Data["PageIsPullList"] = true
  322. } else {
  323. MustEnableIssues(ctx)
  324. if ctx.Written() {
  325. return
  326. }
  327. ctx.Data["Title"] = ctx.Tr("repo.issues")
  328. ctx.Data["PageIsIssueList"] = true
  329. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  330. }
  331. issues(ctx, ctx.FormInt64("milestone"), ctx.FormInt64("project"), util.OptionalBoolOf(isPullList))
  332. if ctx.Written() {
  333. return
  334. }
  335. var err error
  336. // Get milestones
  337. ctx.Data["Milestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  338. RepoID: ctx.Repo.Repository.ID,
  339. State: api.StateType(ctx.FormString("state")),
  340. })
  341. if err != nil {
  342. ctx.ServerError("GetAllRepoMilestones", err)
  343. return
  344. }
  345. ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList)
  346. ctx.HTML(http.StatusOK, tplIssues)
  347. }
  348. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  349. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  350. var err error
  351. ctx.Data["OpenMilestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  352. RepoID: repo.ID,
  353. State: api.StateOpen,
  354. })
  355. if err != nil {
  356. ctx.ServerError("GetMilestones", err)
  357. return
  358. }
  359. ctx.Data["ClosedMilestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  360. RepoID: repo.ID,
  361. State: api.StateClosed,
  362. })
  363. if err != nil {
  364. ctx.ServerError("GetMilestones", err)
  365. return
  366. }
  367. ctx.Data["Assignees"], err = repo.GetAssignees()
  368. if err != nil {
  369. ctx.ServerError("GetAssignees", err)
  370. return
  371. }
  372. handleTeamMentions(ctx)
  373. if ctx.Written() {
  374. return
  375. }
  376. }
  377. func retrieveProjects(ctx *context.Context, repo *models.Repository) {
  378. var err error
  379. ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  380. RepoID: repo.ID,
  381. Page: -1,
  382. IsClosed: util.OptionalBoolFalse,
  383. Type: models.ProjectTypeRepository,
  384. })
  385. if err != nil {
  386. ctx.ServerError("GetProjects", err)
  387. return
  388. }
  389. ctx.Data["ClosedProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  390. RepoID: repo.ID,
  391. Page: -1,
  392. IsClosed: util.OptionalBoolTrue,
  393. Type: models.ProjectTypeRepository,
  394. })
  395. if err != nil {
  396. ctx.ServerError("GetProjects", err)
  397. return
  398. }
  399. }
  400. // repoReviewerSelection items to bee shown
  401. type repoReviewerSelection struct {
  402. IsTeam bool
  403. Team *models.Team
  404. User *models.User
  405. Review *models.Review
  406. CanChange bool
  407. Checked bool
  408. ItemID int64
  409. }
  410. // RetrieveRepoReviewers find all reviewers of a repository
  411. func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue *models.Issue, canChooseReviewer bool) {
  412. ctx.Data["CanChooseReviewer"] = canChooseReviewer
  413. originalAuthorReviews, err := models.GetReviewersFromOriginalAuthorsByIssueID(issue.ID)
  414. if err != nil {
  415. ctx.ServerError("GetReviewersFromOriginalAuthorsByIssueID", err)
  416. return
  417. }
  418. ctx.Data["OriginalReviews"] = originalAuthorReviews
  419. reviews, err := models.GetReviewersByIssueID(issue.ID)
  420. if err != nil {
  421. ctx.ServerError("GetReviewersByIssueID", err)
  422. return
  423. }
  424. if len(reviews) == 0 && !canChooseReviewer {
  425. return
  426. }
  427. var (
  428. pullReviews []*repoReviewerSelection
  429. reviewersResult []*repoReviewerSelection
  430. teamReviewersResult []*repoReviewerSelection
  431. teamReviewers []*models.Team
  432. reviewers []*models.User
  433. )
  434. if canChooseReviewer {
  435. posterID := issue.PosterID
  436. if issue.OriginalAuthorID > 0 {
  437. posterID = 0
  438. }
  439. reviewers, err = repo.GetReviewers(ctx.User.ID, posterID)
  440. if err != nil {
  441. ctx.ServerError("GetReviewers", err)
  442. return
  443. }
  444. teamReviewers, err = repo.GetReviewerTeams()
  445. if err != nil {
  446. ctx.ServerError("GetReviewerTeams", err)
  447. return
  448. }
  449. if len(reviewers) > 0 {
  450. reviewersResult = make([]*repoReviewerSelection, 0, len(reviewers))
  451. }
  452. if len(teamReviewers) > 0 {
  453. teamReviewersResult = make([]*repoReviewerSelection, 0, len(teamReviewers))
  454. }
  455. }
  456. pullReviews = make([]*repoReviewerSelection, 0, len(reviews))
  457. for _, review := range reviews {
  458. tmp := &repoReviewerSelection{
  459. Checked: review.Type == models.ReviewTypeRequest,
  460. Review: review,
  461. ItemID: review.ReviewerID,
  462. }
  463. if review.ReviewerTeamID > 0 {
  464. tmp.IsTeam = true
  465. tmp.ItemID = -review.ReviewerTeamID
  466. }
  467. if ctx.Repo.IsAdmin() {
  468. // Admin can dismiss or re-request any review requests
  469. tmp.CanChange = true
  470. } else if ctx.User != nil && ctx.User.ID == review.ReviewerID && review.Type == models.ReviewTypeRequest {
  471. // A user can refuse review requests
  472. tmp.CanChange = true
  473. } else if (canChooseReviewer || (ctx.User != nil && ctx.User.ID == issue.PosterID)) && review.Type != models.ReviewTypeRequest &&
  474. ctx.User.ID != review.ReviewerID {
  475. // The poster of the PR, a manager, or official reviewers can re-request review from other reviewers
  476. tmp.CanChange = true
  477. }
  478. pullReviews = append(pullReviews, tmp)
  479. if canChooseReviewer {
  480. if tmp.IsTeam {
  481. teamReviewersResult = append(teamReviewersResult, tmp)
  482. } else {
  483. reviewersResult = append(reviewersResult, tmp)
  484. }
  485. }
  486. }
  487. if len(pullReviews) > 0 {
  488. // Drop all non-existing users and teams from the reviews
  489. currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews))
  490. for _, item := range pullReviews {
  491. if item.Review.ReviewerID > 0 {
  492. if err = item.Review.LoadReviewer(); err != nil {
  493. if models.IsErrUserNotExist(err) {
  494. continue
  495. }
  496. ctx.ServerError("LoadReviewer", err)
  497. return
  498. }
  499. item.User = item.Review.Reviewer
  500. } else if item.Review.ReviewerTeamID > 0 {
  501. if err = item.Review.LoadReviewerTeam(); err != nil {
  502. if models.IsErrTeamNotExist(err) {
  503. continue
  504. }
  505. ctx.ServerError("LoadReviewerTeam", err)
  506. return
  507. }
  508. item.Team = item.Review.ReviewerTeam
  509. } else {
  510. continue
  511. }
  512. currentPullReviewers = append(currentPullReviewers, item)
  513. }
  514. ctx.Data["PullReviewers"] = currentPullReviewers
  515. }
  516. if canChooseReviewer && reviewersResult != nil {
  517. preadded := len(reviewersResult)
  518. for _, reviewer := range reviewers {
  519. found := false
  520. reviewAddLoop:
  521. for _, tmp := range reviewersResult[:preadded] {
  522. if tmp.ItemID == reviewer.ID {
  523. tmp.User = reviewer
  524. found = true
  525. break reviewAddLoop
  526. }
  527. }
  528. if found {
  529. continue
  530. }
  531. reviewersResult = append(reviewersResult, &repoReviewerSelection{
  532. IsTeam: false,
  533. CanChange: true,
  534. User: reviewer,
  535. ItemID: reviewer.ID,
  536. })
  537. }
  538. ctx.Data["Reviewers"] = reviewersResult
  539. }
  540. if canChooseReviewer && teamReviewersResult != nil {
  541. preadded := len(teamReviewersResult)
  542. for _, team := range teamReviewers {
  543. found := false
  544. teamReviewAddLoop:
  545. for _, tmp := range teamReviewersResult[:preadded] {
  546. if tmp.ItemID == -team.ID {
  547. tmp.Team = team
  548. found = true
  549. break teamReviewAddLoop
  550. }
  551. }
  552. if found {
  553. continue
  554. }
  555. teamReviewersResult = append(teamReviewersResult, &repoReviewerSelection{
  556. IsTeam: true,
  557. CanChange: true,
  558. Team: team,
  559. ItemID: -team.ID,
  560. })
  561. }
  562. ctx.Data["TeamReviewers"] = teamReviewersResult
  563. }
  564. }
  565. // RetrieveRepoMetas find all the meta information of a repository
  566. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository, isPull bool) []*models.Label {
  567. if !ctx.Repo.CanWriteIssuesOrPulls(isPull) {
  568. return nil
  569. }
  570. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  571. if err != nil {
  572. ctx.ServerError("GetLabelsByRepoID", err)
  573. return nil
  574. }
  575. ctx.Data["Labels"] = labels
  576. if repo.Owner.IsOrganization() {
  577. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), models.ListOptions{})
  578. if err != nil {
  579. return nil
  580. }
  581. ctx.Data["OrgLabels"] = orgLabels
  582. labels = append(labels, orgLabels...)
  583. }
  584. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  585. if ctx.Written() {
  586. return nil
  587. }
  588. retrieveProjects(ctx, repo)
  589. if ctx.Written() {
  590. return nil
  591. }
  592. brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  593. if err != nil {
  594. ctx.ServerError("GetBranches", err)
  595. return nil
  596. }
  597. ctx.Data["Branches"] = brs
  598. // Contains true if the user can create issue dependencies
  599. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, isPull)
  600. return labels
  601. }
  602. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  603. var bytes []byte
  604. if ctx.Repo.Commit == nil {
  605. var err error
  606. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  607. if err != nil {
  608. return "", false
  609. }
  610. }
  611. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  612. if err != nil {
  613. return "", false
  614. }
  615. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  616. return "", false
  617. }
  618. r, err := entry.Blob().DataAsync()
  619. if err != nil {
  620. return "", false
  621. }
  622. defer r.Close()
  623. bytes, err = ioutil.ReadAll(r)
  624. if err != nil {
  625. return "", false
  626. }
  627. return string(bytes), true
  628. }
  629. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs []string, possibleFiles []string) {
  630. templateCandidates := make([]string, 0, len(possibleFiles))
  631. if ctx.FormString("template") != "" {
  632. for _, dirName := range possibleDirs {
  633. templateCandidates = append(templateCandidates, path.Join(dirName, ctx.FormString("template")))
  634. }
  635. }
  636. templateCandidates = append(templateCandidates, possibleFiles...) // Append files to the end because they should be fallback
  637. for _, filename := range templateCandidates {
  638. templateContent, found := getFileContentFromDefaultBranch(ctx, filename)
  639. if found {
  640. var meta api.IssueTemplate
  641. templateBody, err := markdown.ExtractMetadata(templateContent, &meta)
  642. if err != nil {
  643. log.Debug("could not extract metadata from %s [%s]: %v", filename, ctx.Repo.Repository.FullName(), err)
  644. ctx.Data[ctxDataKey] = templateContent
  645. return
  646. }
  647. ctx.Data[issueTemplateTitleKey] = meta.Title
  648. ctx.Data[ctxDataKey] = templateBody
  649. labelIDs := make([]string, 0, len(meta.Labels))
  650. if repoLabels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, "", models.ListOptions{}); err == nil {
  651. ctx.Data["Labels"] = repoLabels
  652. if ctx.Repo.Owner.IsOrganization() {
  653. if orgLabels, err := models.GetLabelsByOrgID(ctx.Repo.Owner.ID, ctx.FormString("sort"), models.ListOptions{}); err == nil {
  654. ctx.Data["OrgLabels"] = orgLabels
  655. repoLabels = append(repoLabels, orgLabels...)
  656. }
  657. }
  658. for _, metaLabel := range meta.Labels {
  659. for _, repoLabel := range repoLabels {
  660. if strings.EqualFold(repoLabel.Name, metaLabel) {
  661. repoLabel.IsChecked = true
  662. labelIDs = append(labelIDs, fmt.Sprintf("%d", repoLabel.ID))
  663. break
  664. }
  665. }
  666. }
  667. }
  668. ctx.Data["HasSelectedLabel"] = len(labelIDs) > 0
  669. ctx.Data["label_ids"] = strings.Join(labelIDs, ",")
  670. return
  671. }
  672. }
  673. }
  674. // NewIssue render creating issue page
  675. func NewIssue(ctx *context.Context) {
  676. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  677. ctx.Data["PageIsIssueList"] = true
  678. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  679. ctx.Data["RequireHighlightJS"] = true
  680. ctx.Data["RequireSimpleMDE"] = true
  681. ctx.Data["RequireTribute"] = true
  682. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  683. title := ctx.FormString("title")
  684. ctx.Data["TitleQuery"] = title
  685. body := ctx.FormString("body")
  686. ctx.Data["BodyQuery"] = body
  687. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(models.UnitTypeProjects)
  688. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  689. upload.AddUploadContext(ctx, "comment")
  690. milestoneID := ctx.FormInt64("milestone")
  691. if milestoneID > 0 {
  692. milestone, err := models.GetMilestoneByID(milestoneID)
  693. if err != nil {
  694. log.Error("GetMilestoneByID: %d: %v", milestoneID, err)
  695. } else {
  696. ctx.Data["milestone_id"] = milestoneID
  697. ctx.Data["Milestone"] = milestone
  698. }
  699. }
  700. projectID := ctx.FormInt64("project")
  701. if projectID > 0 {
  702. project, err := models.GetProjectByID(projectID)
  703. if err != nil {
  704. log.Error("GetProjectByID: %d: %v", projectID, err)
  705. } else if project.RepoID != ctx.Repo.Repository.ID {
  706. log.Error("GetProjectByID: %d: %v", projectID, fmt.Errorf("project[%d] not in repo [%d]", project.ID, ctx.Repo.Repository.ID))
  707. } else {
  708. ctx.Data["project_id"] = projectID
  709. ctx.Data["Project"] = project
  710. }
  711. }
  712. RetrieveRepoMetas(ctx, ctx.Repo.Repository, false)
  713. setTemplateIfExists(ctx, issueTemplateKey, context.IssueTemplateDirCandidates, IssueTemplateCandidates)
  714. if ctx.Written() {
  715. return
  716. }
  717. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeIssues)
  718. ctx.HTML(http.StatusOK, tplIssueNew)
  719. }
  720. // NewIssueChooseTemplate render creating issue from template page
  721. func NewIssueChooseTemplate(ctx *context.Context) {
  722. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  723. ctx.Data["PageIsIssueList"] = true
  724. ctx.Data["milestone"] = ctx.FormInt64("milestone")
  725. issueTemplates := ctx.IssueTemplatesFromDefaultBranch()
  726. ctx.Data["NewIssueChooseTemplate"] = len(issueTemplates) > 0
  727. ctx.Data["IssueTemplates"] = issueTemplates
  728. ctx.HTML(http.StatusOK, tplIssueChoose)
  729. }
  730. // ValidateRepoMetas check and returns repository's meta information
  731. func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull bool) ([]int64, []int64, int64, int64) {
  732. var (
  733. repo = ctx.Repo.Repository
  734. err error
  735. )
  736. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository, isPull)
  737. if ctx.Written() {
  738. return nil, nil, 0, 0
  739. }
  740. var labelIDs []int64
  741. hasSelected := false
  742. // Check labels.
  743. if len(form.LabelIDs) > 0 {
  744. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  745. if err != nil {
  746. return nil, nil, 0, 0
  747. }
  748. labelIDMark := base.Int64sToMap(labelIDs)
  749. for i := range labels {
  750. if labelIDMark[labels[i].ID] {
  751. labels[i].IsChecked = true
  752. hasSelected = true
  753. }
  754. }
  755. }
  756. ctx.Data["Labels"] = labels
  757. ctx.Data["HasSelectedLabel"] = hasSelected
  758. ctx.Data["label_ids"] = form.LabelIDs
  759. // Check milestone.
  760. milestoneID := form.MilestoneID
  761. if milestoneID > 0 {
  762. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  763. if err != nil {
  764. ctx.ServerError("GetMilestoneByID", err)
  765. return nil, nil, 0, 0
  766. }
  767. ctx.Data["milestone_id"] = milestoneID
  768. }
  769. if form.ProjectID > 0 {
  770. p, err := models.GetProjectByID(form.ProjectID)
  771. if err != nil {
  772. ctx.ServerError("GetProjectByID", err)
  773. return nil, nil, 0, 0
  774. }
  775. if p.RepoID != ctx.Repo.Repository.ID {
  776. ctx.NotFound("", nil)
  777. return nil, nil, 0, 0
  778. }
  779. ctx.Data["Project"] = p
  780. ctx.Data["project_id"] = form.ProjectID
  781. }
  782. // Check assignees
  783. var assigneeIDs []int64
  784. if len(form.AssigneeIDs) > 0 {
  785. assigneeIDs, err = base.StringsToInt64s(strings.Split(form.AssigneeIDs, ","))
  786. if err != nil {
  787. return nil, nil, 0, 0
  788. }
  789. // Check if the passed assignees actually exists and is assignable
  790. for _, aID := range assigneeIDs {
  791. assignee, err := models.GetUserByID(aID)
  792. if err != nil {
  793. ctx.ServerError("GetUserByID", err)
  794. return nil, nil, 0, 0
  795. }
  796. valid, err := models.CanBeAssigned(assignee, repo, isPull)
  797. if err != nil {
  798. ctx.ServerError("CanBeAssigned", err)
  799. return nil, nil, 0, 0
  800. }
  801. if !valid {
  802. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  803. return nil, nil, 0, 0
  804. }
  805. }
  806. }
  807. // Keep the old assignee id thingy for compatibility reasons
  808. if form.AssigneeID > 0 {
  809. assigneeIDs = append(assigneeIDs, form.AssigneeID)
  810. }
  811. return labelIDs, assigneeIDs, milestoneID, form.ProjectID
  812. }
  813. // NewIssuePost response for creating new issue
  814. func NewIssuePost(ctx *context.Context) {
  815. form := web.GetForm(ctx).(*forms.CreateIssueForm)
  816. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  817. ctx.Data["PageIsIssueList"] = true
  818. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  819. ctx.Data["RequireHighlightJS"] = true
  820. ctx.Data["RequireSimpleMDE"] = true
  821. ctx.Data["ReadOnly"] = false
  822. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  823. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  824. upload.AddUploadContext(ctx, "comment")
  825. var (
  826. repo = ctx.Repo.Repository
  827. attachments []string
  828. )
  829. labelIDs, assigneeIDs, milestoneID, projectID := ValidateRepoMetas(ctx, *form, false)
  830. if ctx.Written() {
  831. return
  832. }
  833. if setting.Attachment.Enabled {
  834. attachments = form.Files
  835. }
  836. if ctx.HasError() {
  837. ctx.HTML(http.StatusOK, tplIssueNew)
  838. return
  839. }
  840. if util.IsEmptyString(form.Title) {
  841. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplIssueNew, form)
  842. return
  843. }
  844. issue := &models.Issue{
  845. RepoID: repo.ID,
  846. Title: form.Title,
  847. PosterID: ctx.User.ID,
  848. Poster: ctx.User,
  849. MilestoneID: milestoneID,
  850. Content: form.Content,
  851. Ref: form.Ref,
  852. }
  853. if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil {
  854. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  855. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
  856. return
  857. }
  858. ctx.ServerError("NewIssue", err)
  859. return
  860. }
  861. if projectID > 0 {
  862. if err := models.ChangeProjectAssign(issue, ctx.User, projectID); err != nil {
  863. ctx.ServerError("ChangeProjectAssign", err)
  864. return
  865. }
  866. }
  867. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  868. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
  869. }
  870. // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
  871. func commentTag(repo *models.Repository, poster *models.User, issue *models.Issue) (models.CommentTag, error) {
  872. perm, err := models.GetUserRepoPermission(repo, poster)
  873. if err != nil {
  874. return models.CommentTagNone, err
  875. }
  876. if perm.IsOwner() {
  877. if !poster.IsAdmin {
  878. return models.CommentTagOwner, nil
  879. }
  880. ok, err := models.IsUserRealRepoAdmin(repo, poster)
  881. if err != nil {
  882. return models.CommentTagNone, err
  883. }
  884. if ok {
  885. return models.CommentTagOwner, nil
  886. }
  887. if ok, err = repo.IsCollaborator(poster.ID); ok && err == nil {
  888. return models.CommentTagWriter, nil
  889. }
  890. return models.CommentTagNone, err
  891. }
  892. if perm.CanWrite(models.UnitTypeCode) {
  893. return models.CommentTagWriter, nil
  894. }
  895. return models.CommentTagNone, nil
  896. }
  897. func getBranchData(ctx *context.Context, issue *models.Issue) {
  898. ctx.Data["BaseBranch"] = nil
  899. ctx.Data["HeadBranch"] = nil
  900. ctx.Data["HeadUserName"] = nil
  901. ctx.Data["BaseName"] = ctx.Repo.Repository.OwnerName
  902. if issue.IsPull {
  903. pull := issue.PullRequest
  904. ctx.Data["BaseBranch"] = pull.BaseBranch
  905. ctx.Data["HeadBranch"] = pull.HeadBranch
  906. ctx.Data["HeadUserName"] = pull.MustHeadUserName()
  907. }
  908. }
  909. // ViewIssue render issue view page
  910. func ViewIssue(ctx *context.Context) {
  911. if ctx.Params(":type") == "issues" {
  912. // If issue was requested we check if repo has external tracker and redirect
  913. extIssueUnit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  914. if err == nil && extIssueUnit != nil {
  915. if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
  916. metas := ctx.Repo.Repository.ComposeMetas()
  917. metas["index"] = ctx.Params(":index")
  918. ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas))
  919. return
  920. }
  921. } else if err != nil && !models.IsErrUnitTypeNotExist(err) {
  922. ctx.ServerError("GetUnit", err)
  923. return
  924. }
  925. }
  926. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  927. if err != nil {
  928. if models.IsErrIssueNotExist(err) {
  929. ctx.NotFound("GetIssueByIndex", err)
  930. } else {
  931. ctx.ServerError("GetIssueByIndex", err)
  932. }
  933. return
  934. }
  935. // Make sure type and URL matches.
  936. if ctx.Params(":type") == "issues" && issue.IsPull {
  937. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index))
  938. return
  939. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  940. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + fmt.Sprint(issue.Index))
  941. return
  942. }
  943. if issue.IsPull {
  944. MustAllowPulls(ctx)
  945. if ctx.Written() {
  946. return
  947. }
  948. ctx.Data["PageIsPullList"] = true
  949. ctx.Data["PageIsPullConversation"] = true
  950. } else {
  951. MustEnableIssues(ctx)
  952. if ctx.Written() {
  953. return
  954. }
  955. ctx.Data["PageIsIssueList"] = true
  956. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  957. }
  958. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  959. ctx.Data["IssueType"] = "pulls"
  960. } else if !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) {
  961. ctx.Data["IssueType"] = "issues"
  962. } else {
  963. ctx.Data["IssueType"] = "all"
  964. }
  965. ctx.Data["RequireHighlightJS"] = true
  966. ctx.Data["RequireTribute"] = true
  967. ctx.Data["RequireSimpleMDE"] = true
  968. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(models.UnitTypeProjects)
  969. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  970. upload.AddUploadContext(ctx, "comment")
  971. if err = issue.LoadAttributes(); err != nil {
  972. ctx.ServerError("LoadAttributes", err)
  973. return
  974. }
  975. if err = filterXRefComments(ctx, issue); err != nil {
  976. ctx.ServerError("filterXRefComments", err)
  977. return
  978. }
  979. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  980. iw := new(models.IssueWatch)
  981. if ctx.User != nil {
  982. iw.UserID = ctx.User.ID
  983. iw.IssueID = issue.ID
  984. iw.IsWatching, err = models.CheckIssueWatch(ctx.User, issue)
  985. if err != nil {
  986. ctx.ServerError("CheckIssueWatch", err)
  987. return
  988. }
  989. }
  990. ctx.Data["IssueWatch"] = iw
  991. issue.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  992. URLPrefix: ctx.Repo.RepoLink,
  993. Metas: ctx.Repo.Repository.ComposeMetas(),
  994. GitRepo: ctx.Repo.GitRepo,
  995. }, issue.Content)
  996. if err != nil {
  997. ctx.ServerError("RenderString", err)
  998. return
  999. }
  1000. repo := ctx.Repo.Repository
  1001. // Get more information if it's a pull request.
  1002. if issue.IsPull {
  1003. if issue.PullRequest.HasMerged {
  1004. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  1005. PrepareMergedViewPullInfo(ctx, issue)
  1006. } else {
  1007. PrepareViewPullInfo(ctx, issue)
  1008. ctx.Data["DisableStatusChange"] = ctx.Data["IsPullRequestBroken"] == true && issue.IsClosed
  1009. }
  1010. if ctx.Written() {
  1011. return
  1012. }
  1013. }
  1014. // Metas.
  1015. // Check labels.
  1016. labelIDMark := make(map[int64]bool)
  1017. for i := range issue.Labels {
  1018. labelIDMark[issue.Labels[i].ID] = true
  1019. }
  1020. labels, err := models.GetLabelsByRepoID(repo.ID, "", models.ListOptions{})
  1021. if err != nil {
  1022. ctx.ServerError("GetLabelsByRepoID", err)
  1023. return
  1024. }
  1025. ctx.Data["Labels"] = labels
  1026. if repo.Owner.IsOrganization() {
  1027. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), models.ListOptions{})
  1028. if err != nil {
  1029. ctx.ServerError("GetLabelsByOrgID", err)
  1030. return
  1031. }
  1032. ctx.Data["OrgLabels"] = orgLabels
  1033. labels = append(labels, orgLabels...)
  1034. }
  1035. hasSelected := false
  1036. for i := range labels {
  1037. if labelIDMark[labels[i].ID] {
  1038. labels[i].IsChecked = true
  1039. hasSelected = true
  1040. }
  1041. }
  1042. ctx.Data["HasSelectedLabel"] = hasSelected
  1043. // Check milestone and assignee.
  1044. if ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
  1045. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  1046. retrieveProjects(ctx, repo)
  1047. if ctx.Written() {
  1048. return
  1049. }
  1050. }
  1051. if issue.IsPull {
  1052. canChooseReviewer := ctx.Repo.CanWrite(models.UnitTypePullRequests)
  1053. if !canChooseReviewer && ctx.User != nil && ctx.IsSigned {
  1054. canChooseReviewer, err = models.IsOfficialReviewer(issue, ctx.User)
  1055. if err != nil {
  1056. ctx.ServerError("IsOfficialReviewer", err)
  1057. return
  1058. }
  1059. }
  1060. RetrieveRepoReviewers(ctx, repo, issue, canChooseReviewer)
  1061. if ctx.Written() {
  1062. return
  1063. }
  1064. }
  1065. if ctx.IsSigned {
  1066. // Update issue-user.
  1067. if err = issue.ReadBy(ctx.User.ID); err != nil {
  1068. ctx.ServerError("ReadBy", err)
  1069. return
  1070. }
  1071. }
  1072. var (
  1073. tag models.CommentTag
  1074. ok bool
  1075. marked = make(map[int64]models.CommentTag)
  1076. comment *models.Comment
  1077. participants = make([]*models.User, 1, 10)
  1078. )
  1079. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  1080. if ctx.IsSigned {
  1081. // Deal with the stopwatch
  1082. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  1083. if !ctx.Data["IsStopwatchRunning"].(bool) {
  1084. var exists bool
  1085. var sw *models.Stopwatch
  1086. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  1087. ctx.ServerError("HasUserStopwatch", err)
  1088. return
  1089. }
  1090. ctx.Data["HasUserStopwatch"] = exists
  1091. if exists {
  1092. // Add warning if the user has already a stopwatch
  1093. var otherIssue *models.Issue
  1094. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  1095. ctx.ServerError("GetIssueByID", err)
  1096. return
  1097. }
  1098. if err = otherIssue.LoadRepo(); err != nil {
  1099. ctx.ServerError("LoadRepo", err)
  1100. return
  1101. }
  1102. // Add link to the issue of the already running stopwatch
  1103. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  1104. }
  1105. }
  1106. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  1107. } else {
  1108. ctx.Data["CanUseTimetracker"] = false
  1109. }
  1110. if ctx.Data["WorkingUsers"], err = models.TotalTimes(&models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  1111. ctx.ServerError("TotalTimes", err)
  1112. return
  1113. }
  1114. }
  1115. // Check if the user can use the dependencies
  1116. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, issue.IsPull)
  1117. // check if dependencies can be created across repositories
  1118. ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies
  1119. if issue.ShowTag, err = commentTag(repo, issue.Poster, issue); err != nil {
  1120. ctx.ServerError("commentTag", err)
  1121. return
  1122. }
  1123. marked[issue.PosterID] = issue.ShowTag
  1124. // Render comments and and fetch participants.
  1125. participants[0] = issue.Poster
  1126. for _, comment = range issue.Comments {
  1127. comment.Issue = issue
  1128. if err := comment.LoadPoster(); err != nil {
  1129. ctx.ServerError("LoadPoster", err)
  1130. return
  1131. }
  1132. if comment.Type == models.CommentTypeComment {
  1133. if err := comment.LoadAttachments(); err != nil {
  1134. ctx.ServerError("LoadAttachments", err)
  1135. return
  1136. }
  1137. comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  1138. URLPrefix: ctx.Repo.RepoLink,
  1139. Metas: ctx.Repo.Repository.ComposeMetas(),
  1140. GitRepo: ctx.Repo.GitRepo,
  1141. }, comment.Content)
  1142. if err != nil {
  1143. ctx.ServerError("RenderString", err)
  1144. return
  1145. }
  1146. // Check tag.
  1147. tag, ok = marked[comment.PosterID]
  1148. if ok {
  1149. comment.ShowTag = tag
  1150. continue
  1151. }
  1152. comment.ShowTag, err = commentTag(repo, comment.Poster, issue)
  1153. if err != nil {
  1154. ctx.ServerError("commentTag", err)
  1155. return
  1156. }
  1157. marked[comment.PosterID] = comment.ShowTag
  1158. participants = addParticipant(comment.Poster, participants)
  1159. } else if comment.Type == models.CommentTypeLabel {
  1160. if err = comment.LoadLabel(); err != nil {
  1161. ctx.ServerError("LoadLabel", err)
  1162. return
  1163. }
  1164. } else if comment.Type == models.CommentTypeMilestone {
  1165. if err = comment.LoadMilestone(); err != nil {
  1166. ctx.ServerError("LoadMilestone", err)
  1167. return
  1168. }
  1169. ghostMilestone := &models.Milestone{
  1170. ID: -1,
  1171. Name: ctx.Tr("repo.issues.deleted_milestone"),
  1172. }
  1173. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  1174. comment.OldMilestone = ghostMilestone
  1175. }
  1176. if comment.MilestoneID > 0 && comment.Milestone == nil {
  1177. comment.Milestone = ghostMilestone
  1178. }
  1179. } else if comment.Type == models.CommentTypeProject {
  1180. if err = comment.LoadProject(); err != nil {
  1181. ctx.ServerError("LoadProject", err)
  1182. return
  1183. }
  1184. ghostProject := &models.Project{
  1185. ID: -1,
  1186. Title: ctx.Tr("repo.issues.deleted_project"),
  1187. }
  1188. if comment.OldProjectID > 0 && comment.OldProject == nil {
  1189. comment.OldProject = ghostProject
  1190. }
  1191. if comment.ProjectID > 0 && comment.Project == nil {
  1192. comment.Project = ghostProject
  1193. }
  1194. } else if comment.Type == models.CommentTypeAssignees || comment.Type == models.CommentTypeReviewRequest {
  1195. if err = comment.LoadAssigneeUserAndTeam(); err != nil {
  1196. ctx.ServerError("LoadAssigneeUserAndTeam", err)
  1197. return
  1198. }
  1199. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  1200. if err = comment.LoadDepIssueDetails(); err != nil {
  1201. if !models.IsErrIssueNotExist(err) {
  1202. ctx.ServerError("LoadDepIssueDetails", err)
  1203. return
  1204. }
  1205. }
  1206. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview || comment.Type == models.CommentTypeDismissReview {
  1207. comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  1208. URLPrefix: ctx.Repo.RepoLink,
  1209. Metas: ctx.Repo.Repository.ComposeMetas(),
  1210. GitRepo: ctx.Repo.GitRepo,
  1211. }, comment.Content)
  1212. if err != nil {
  1213. ctx.ServerError("RenderString", err)
  1214. return
  1215. }
  1216. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  1217. ctx.ServerError("LoadReview", err)
  1218. return
  1219. }
  1220. participants = addParticipant(comment.Poster, participants)
  1221. if comment.Review == nil {
  1222. continue
  1223. }
  1224. if err = comment.Review.LoadAttributes(); err != nil {
  1225. if !models.IsErrUserNotExist(err) {
  1226. ctx.ServerError("Review.LoadAttributes", err)
  1227. return
  1228. }
  1229. comment.Review.Reviewer = models.NewGhostUser()
  1230. }
  1231. if err = comment.Review.LoadCodeComments(); err != nil {
  1232. ctx.ServerError("Review.LoadCodeComments", err)
  1233. return
  1234. }
  1235. for _, codeComments := range comment.Review.CodeComments {
  1236. for _, lineComments := range codeComments {
  1237. for _, c := range lineComments {
  1238. // Check tag.
  1239. tag, ok = marked[c.PosterID]
  1240. if ok {
  1241. c.ShowTag = tag
  1242. continue
  1243. }
  1244. c.ShowTag, err = commentTag(repo, c.Poster, issue)
  1245. if err != nil {
  1246. ctx.ServerError("commentTag", err)
  1247. return
  1248. }
  1249. marked[c.PosterID] = c.ShowTag
  1250. participants = addParticipant(c.Poster, participants)
  1251. }
  1252. }
  1253. }
  1254. if err = comment.LoadResolveDoer(); err != nil {
  1255. ctx.ServerError("LoadResolveDoer", err)
  1256. return
  1257. }
  1258. } else if comment.Type == models.CommentTypePullPush {
  1259. participants = addParticipant(comment.Poster, participants)
  1260. if err = comment.LoadPushCommits(); err != nil {
  1261. ctx.ServerError("LoadPushCommits", err)
  1262. return
  1263. }
  1264. } else if comment.Type == models.CommentTypeAddTimeManual ||
  1265. comment.Type == models.CommentTypeStopTracking {
  1266. // drop error since times could be pruned from DB..
  1267. _ = comment.LoadTime()
  1268. }
  1269. }
  1270. // Combine multiple label assignments into a single comment
  1271. combineLabelComments(issue)
  1272. getBranchData(ctx, issue)
  1273. if issue.IsPull {
  1274. pull := issue.PullRequest
  1275. pull.Issue = issue
  1276. canDelete := false
  1277. ctx.Data["AllowMerge"] = false
  1278. if ctx.IsSigned {
  1279. if err := pull.LoadHeadRepo(); err != nil {
  1280. log.Error("LoadHeadRepo: %v", err)
  1281. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch {
  1282. perm, err := models.GetUserRepoPermission(pull.HeadRepo, ctx.User)
  1283. if err != nil {
  1284. ctx.ServerError("GetUserRepoPermission", err)
  1285. return
  1286. }
  1287. if perm.CanWrite(models.UnitTypeCode) {
  1288. // Check if branch is not protected
  1289. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch); err != nil {
  1290. log.Error("IsProtectedBranch: %v", err)
  1291. } else if !protected {
  1292. canDelete = true
  1293. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + fmt.Sprint(issue.Index) + "/cleanup"
  1294. }
  1295. }
  1296. }
  1297. if err := pull.LoadBaseRepo(); err != nil {
  1298. log.Error("LoadBaseRepo: %v", err)
  1299. }
  1300. perm, err := models.GetUserRepoPermission(pull.BaseRepo, ctx.User)
  1301. if err != nil {
  1302. ctx.ServerError("GetUserRepoPermission", err)
  1303. return
  1304. }
  1305. ctx.Data["AllowMerge"], err = pull_service.IsUserAllowedToMerge(pull, perm, ctx.User)
  1306. if err != nil {
  1307. ctx.ServerError("IsUserAllowedToMerge", err)
  1308. return
  1309. }
  1310. if ctx.Data["CanMarkConversation"], err = models.CanMarkConversation(issue, ctx.User); err != nil {
  1311. ctx.ServerError("CanMarkConversation", err)
  1312. return
  1313. }
  1314. }
  1315. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  1316. if err != nil {
  1317. ctx.ServerError("GetUnit", err)
  1318. return
  1319. }
  1320. prConfig := prUnit.PullRequestsConfig()
  1321. // Check correct values and select default
  1322. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  1323. !prConfig.IsMergeStyleAllowed(ms) {
  1324. defaultMergeStyle := prConfig.GetDefaultMergeStyle()
  1325. if prConfig.IsMergeStyleAllowed(defaultMergeStyle) && !ok {
  1326. ctx.Data["MergeStyle"] = defaultMergeStyle
  1327. } else if prConfig.AllowMerge {
  1328. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  1329. } else if prConfig.AllowRebase {
  1330. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  1331. } else if prConfig.AllowRebaseMerge {
  1332. ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge
  1333. } else if prConfig.AllowSquash {
  1334. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  1335. } else if prConfig.AllowManualMerge {
  1336. ctx.Data["MergeStyle"] = models.MergeStyleManuallyMerged
  1337. } else {
  1338. ctx.Data["MergeStyle"] = ""
  1339. }
  1340. }
  1341. if err = pull.LoadProtectedBranch(); err != nil {
  1342. ctx.ServerError("LoadProtectedBranch", err)
  1343. return
  1344. }
  1345. if pull.ProtectedBranch != nil {
  1346. cnt := pull.ProtectedBranch.GetGrantedApprovalsCount(pull)
  1347. ctx.Data["IsBlockedByApprovals"] = !pull.ProtectedBranch.HasEnoughApprovals(pull)
  1348. ctx.Data["IsBlockedByRejection"] = pull.ProtectedBranch.MergeBlockedByRejectedReview(pull)
  1349. ctx.Data["IsBlockedByOfficialReviewRequests"] = pull.ProtectedBranch.MergeBlockedByOfficialReviewRequests(pull)
  1350. ctx.Data["IsBlockedByOutdatedBranch"] = pull.ProtectedBranch.MergeBlockedByOutdatedBranch(pull)
  1351. ctx.Data["GrantedApprovals"] = cnt
  1352. ctx.Data["RequireSigned"] = pull.ProtectedBranch.RequireSignedCommits
  1353. ctx.Data["ChangedProtectedFiles"] = pull.ChangedProtectedFiles
  1354. ctx.Data["IsBlockedByChangedProtectedFiles"] = len(pull.ChangedProtectedFiles) != 0
  1355. ctx.Data["ChangedProtectedFilesNum"] = len(pull.ChangedProtectedFiles)
  1356. }
  1357. ctx.Data["WillSign"] = false
  1358. if ctx.User != nil {
  1359. sign, key, _, err := pull.SignMerge(ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName())
  1360. ctx.Data["WillSign"] = sign
  1361. ctx.Data["SigningKey"] = key
  1362. if err != nil {
  1363. if models.IsErrWontSign(err) {
  1364. ctx.Data["WontSignReason"] = err.(*models.ErrWontSign).Reason
  1365. } else {
  1366. ctx.Data["WontSignReason"] = "error"
  1367. log.Error("Error whilst checking if could sign pr %d in repo %s. Error: %v", pull.ID, pull.BaseRepo.FullName(), err)
  1368. }
  1369. }
  1370. } else {
  1371. ctx.Data["WontSignReason"] = "not_signed_in"
  1372. }
  1373. ctx.Data["IsPullBranchDeletable"] = canDelete &&
  1374. pull.HeadRepo != nil &&
  1375. git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch) &&
  1376. (!pull.HasMerged || ctx.Data["HeadBranchCommitID"] == ctx.Data["PullHeadCommitID"])
  1377. stillCanManualMerge := func() bool {
  1378. if pull.HasMerged || issue.IsClosed || !ctx.IsSigned {
  1379. return false
  1380. }
  1381. if pull.CanAutoMerge() || pull.IsWorkInProgress() || pull.IsChecking() {
  1382. return false
  1383. }
  1384. if (ctx.User.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge {
  1385. return true
  1386. }
  1387. return false
  1388. }
  1389. ctx.Data["StillCanManualMerge"] = stillCanManualMerge()
  1390. }
  1391. // Get Dependencies
  1392. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  1393. if err != nil {
  1394. ctx.ServerError("BlockedByDependencies", err)
  1395. return
  1396. }
  1397. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  1398. if err != nil {
  1399. ctx.ServerError("BlockingDependencies", err)
  1400. return
  1401. }
  1402. ctx.Data["Participants"] = participants
  1403. ctx.Data["NumParticipants"] = len(participants)
  1404. ctx.Data["Issue"] = issue
  1405. ctx.Data["ReadOnly"] = false
  1406. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  1407. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
  1408. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  1409. ctx.Data["HasProjectsWritePermission"] = ctx.Repo.CanWrite(models.UnitTypeProjects)
  1410. ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
  1411. ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
  1412. ctx.Data["RefEndName"] = git.RefEndName(issue.Ref)
  1413. ctx.HTML(http.StatusOK, tplIssueView)
  1414. }
  1415. // GetActionIssue will return the issue which is used in the context.
  1416. func GetActionIssue(ctx *context.Context) *models.Issue {
  1417. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1418. if err != nil {
  1419. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  1420. return nil
  1421. }
  1422. issue.Repo = ctx.Repo.Repository
  1423. checkIssueRights(ctx, issue)
  1424. if ctx.Written() {
  1425. return nil
  1426. }
  1427. if err = issue.LoadAttributes(); err != nil {
  1428. ctx.ServerError("LoadAttributes", nil)
  1429. return nil
  1430. }
  1431. return issue
  1432. }
  1433. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  1434. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) ||
  1435. !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  1436. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1437. }
  1438. }
  1439. func getActionIssues(ctx *context.Context) []*models.Issue {
  1440. commaSeparatedIssueIDs := ctx.FormString("issue_ids")
  1441. if len(commaSeparatedIssueIDs) == 0 {
  1442. return nil
  1443. }
  1444. issueIDs := make([]int64, 0, 10)
  1445. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  1446. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  1447. if err != nil {
  1448. ctx.ServerError("ParseInt", err)
  1449. return nil
  1450. }
  1451. issueIDs = append(issueIDs, issueID)
  1452. }
  1453. issues, err := models.GetIssuesByIDs(issueIDs)
  1454. if err != nil {
  1455. ctx.ServerError("GetIssuesByIDs", err)
  1456. return nil
  1457. }
  1458. // Check access rights for all issues
  1459. issueUnitEnabled := ctx.Repo.CanRead(models.UnitTypeIssues)
  1460. prUnitEnabled := ctx.Repo.CanRead(models.UnitTypePullRequests)
  1461. for _, issue := range issues {
  1462. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  1463. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1464. return nil
  1465. }
  1466. if err = issue.LoadAttributes(); err != nil {
  1467. ctx.ServerError("LoadAttributes", err)
  1468. return nil
  1469. }
  1470. }
  1471. return issues
  1472. }
  1473. // UpdateIssueTitle change issue's title
  1474. func UpdateIssueTitle(ctx *context.Context) {
  1475. issue := GetActionIssue(ctx)
  1476. if ctx.Written() {
  1477. return
  1478. }
  1479. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1480. ctx.Error(http.StatusForbidden)
  1481. return
  1482. }
  1483. title := ctx.FormTrim("title")
  1484. if len(title) == 0 {
  1485. ctx.Error(http.StatusNoContent)
  1486. return
  1487. }
  1488. if err := issue_service.ChangeTitle(issue, ctx.User, title); err != nil {
  1489. ctx.ServerError("ChangeTitle", err)
  1490. return
  1491. }
  1492. ctx.JSON(http.StatusOK, map[string]interface{}{
  1493. "title": issue.Title,
  1494. })
  1495. }
  1496. // UpdateIssueRef change issue's ref (branch)
  1497. func UpdateIssueRef(ctx *context.Context) {
  1498. issue := GetActionIssue(ctx)
  1499. if ctx.Written() {
  1500. return
  1501. }
  1502. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) || issue.IsPull {
  1503. ctx.Error(http.StatusForbidden)
  1504. return
  1505. }
  1506. ref := ctx.FormTrim("ref")
  1507. if err := issue_service.ChangeIssueRef(issue, ctx.User, ref); err != nil {
  1508. ctx.ServerError("ChangeRef", err)
  1509. return
  1510. }
  1511. ctx.JSON(http.StatusOK, map[string]interface{}{
  1512. "ref": ref,
  1513. })
  1514. }
  1515. // UpdateIssueContent change issue's content
  1516. func UpdateIssueContent(ctx *context.Context) {
  1517. issue := GetActionIssue(ctx)
  1518. if ctx.Written() {
  1519. return
  1520. }
  1521. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1522. ctx.Error(http.StatusForbidden)
  1523. return
  1524. }
  1525. if err := issue_service.ChangeContent(issue, ctx.User, ctx.Req.FormValue("content")); err != nil {
  1526. ctx.ServerError("ChangeContent", err)
  1527. return
  1528. }
  1529. if err := updateAttachments(issue, ctx.FormStrings("files[]")); err != nil {
  1530. ctx.ServerError("UpdateAttachments", err)
  1531. return
  1532. }
  1533. content, err := markdown.RenderString(&markup.RenderContext{
  1534. URLPrefix: ctx.FormString("context"),
  1535. Metas: ctx.Repo.Repository.ComposeMetas(),
  1536. GitRepo: ctx.Repo.GitRepo,
  1537. }, issue.Content)
  1538. if err != nil {
  1539. ctx.ServerError("RenderString", err)
  1540. return
  1541. }
  1542. ctx.JSON(http.StatusOK, map[string]interface{}{
  1543. "content": content,
  1544. "attachments": attachmentsHTML(ctx, issue.Attachments, issue.Content),
  1545. })
  1546. }
  1547. // UpdateIssueMilestone change issue's milestone
  1548. func UpdateIssueMilestone(ctx *context.Context) {
  1549. issues := getActionIssues(ctx)
  1550. if ctx.Written() {
  1551. return
  1552. }
  1553. milestoneID := ctx.FormInt64("id")
  1554. for _, issue := range issues {
  1555. oldMilestoneID := issue.MilestoneID
  1556. if oldMilestoneID == milestoneID {
  1557. continue
  1558. }
  1559. issue.MilestoneID = milestoneID
  1560. if err := issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  1561. ctx.ServerError("ChangeMilestoneAssign", err)
  1562. return
  1563. }
  1564. }
  1565. ctx.JSON(http.StatusOK, map[string]interface{}{
  1566. "ok": true,
  1567. })
  1568. }
  1569. // UpdateIssueAssignee change issue's or pull's assignee
  1570. func UpdateIssueAssignee(ctx *context.Context) {
  1571. issues := getActionIssues(ctx)
  1572. if ctx.Written() {
  1573. return
  1574. }
  1575. assigneeID := ctx.FormInt64("id")
  1576. action := ctx.FormString("action")
  1577. for _, issue := range issues {
  1578. switch action {
  1579. case "clear":
  1580. if err := issue_service.DeleteNotPassedAssignee(issue, ctx.User, []*models.User{}); err != nil {
  1581. ctx.ServerError("ClearAssignees", err)
  1582. return
  1583. }
  1584. default:
  1585. assignee, err := models.GetUserByID(assigneeID)
  1586. if err != nil {
  1587. ctx.ServerError("GetUserByID", err)
  1588. return
  1589. }
  1590. valid, err := models.CanBeAssigned(assignee, issue.Repo, issue.IsPull)
  1591. if err != nil {
  1592. ctx.ServerError("canBeAssigned", err)
  1593. return
  1594. }
  1595. if !valid {
  1596. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: issue.Repo.Name})
  1597. return
  1598. }
  1599. _, _, err = issue_service.ToggleAssignee(issue, ctx.User, assigneeID)
  1600. if err != nil {
  1601. ctx.ServerError("ToggleAssignee", err)
  1602. return
  1603. }
  1604. }
  1605. }
  1606. ctx.JSON(http.StatusOK, map[string]interface{}{
  1607. "ok": true,
  1608. })
  1609. }
  1610. // UpdatePullReviewRequest add or remove review request
  1611. func UpdatePullReviewRequest(ctx *context.Context) {
  1612. issues := getActionIssues(ctx)
  1613. if ctx.Written() {
  1614. return
  1615. }
  1616. reviewID := ctx.FormInt64("id")
  1617. action := ctx.FormString("action")
  1618. // TODO: Not support 'clear' now
  1619. if action != "attach" && action != "detach" {
  1620. ctx.Status(403)
  1621. return
  1622. }
  1623. for _, issue := range issues {
  1624. if err := issue.LoadRepo(); err != nil {
  1625. ctx.ServerError("issue.LoadRepo", err)
  1626. return
  1627. }
  1628. if !issue.IsPull {
  1629. log.Warn(
  1630. "UpdatePullReviewRequest: refusing to add review request for non-PR issue %-v#%d",
  1631. issue.Repo, issue.Index,
  1632. )
  1633. ctx.Status(403)
  1634. return
  1635. }
  1636. if reviewID < 0 {
  1637. // negative reviewIDs represent team requests
  1638. if err := issue.Repo.GetOwner(); err != nil {
  1639. ctx.ServerError("issue.Repo.GetOwner", err)
  1640. return
  1641. }
  1642. if !issue.Repo.Owner.IsOrganization() {
  1643. log.Warn(
  1644. "UpdatePullReviewRequest: refusing to add team review request for %s#%d owned by non organization UID[%d]",
  1645. issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1646. )
  1647. ctx.Status(403)
  1648. return
  1649. }
  1650. team, err := models.GetTeamByID(-reviewID)
  1651. if err != nil {
  1652. ctx.ServerError("models.GetTeamByID", err)
  1653. return
  1654. }
  1655. if team.OrgID != issue.Repo.OwnerID {
  1656. log.Warn(
  1657. "UpdatePullReviewRequest: refusing to add team review request for UID[%d] team %s to %s#%d owned by UID[%d]",
  1658. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID)
  1659. ctx.Status(403)
  1660. return
  1661. }
  1662. err = issue_service.IsValidTeamReviewRequest(team, ctx.User, action == "attach", issue)
  1663. if err != nil {
  1664. if models.IsErrNotValidReviewRequest(err) {
  1665. log.Warn(
  1666. "UpdatePullReviewRequest: refusing to add invalid team review request for UID[%d] team %s to %s#%d owned by UID[%d]: Error: %v",
  1667. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1668. err,
  1669. )
  1670. ctx.Status(403)
  1671. return
  1672. }
  1673. ctx.ServerError("IsValidTeamReviewRequest", err)
  1674. return
  1675. }
  1676. _, err = issue_service.TeamReviewRequest(issue, ctx.User, team, action == "attach")
  1677. if err != nil {
  1678. ctx.ServerError("TeamReviewRequest", err)
  1679. return
  1680. }
  1681. continue
  1682. }
  1683. reviewer, err := models.GetUserByID(reviewID)
  1684. if err != nil {
  1685. if models.IsErrUserNotExist(err) {
  1686. log.Warn(
  1687. "UpdatePullReviewRequest: requested reviewer [%d] for %-v to %-v#%d is not exist: Error: %v",
  1688. reviewID, issue.Repo, issue.Index,
  1689. err,
  1690. )
  1691. ctx.Status(403)
  1692. return
  1693. }
  1694. ctx.ServerError("GetUserByID", err)
  1695. return
  1696. }
  1697. err = issue_service.IsValidReviewRequest(reviewer, ctx.User, action == "attach", issue, nil)
  1698. if err != nil {
  1699. if models.IsErrNotValidReviewRequest(err) {
  1700. log.Warn(
  1701. "UpdatePullReviewRequest: refusing to add invalid review request for %-v to %-v#%d: Error: %v",
  1702. reviewer, issue.Repo, issue.Index,
  1703. err,
  1704. )
  1705. ctx.Status(403)
  1706. return
  1707. }
  1708. ctx.ServerError("isValidReviewRequest", err)
  1709. return
  1710. }
  1711. _, err = issue_service.ReviewRequest(issue, ctx.User, reviewer, action == "attach")
  1712. if err != nil {
  1713. ctx.ServerError("ReviewRequest", err)
  1714. return
  1715. }
  1716. }
  1717. ctx.JSON(http.StatusOK, map[string]interface{}{
  1718. "ok": true,
  1719. })
  1720. }
  1721. // UpdateIssueStatus change issue's status
  1722. func UpdateIssueStatus(ctx *context.Context) {
  1723. issues := getActionIssues(ctx)
  1724. if ctx.Written() {
  1725. return
  1726. }
  1727. var isClosed bool
  1728. switch action := ctx.FormString("action"); action {
  1729. case "open":
  1730. isClosed = false
  1731. case "close":
  1732. isClosed = true
  1733. default:
  1734. log.Warn("Unrecognized action: %s", action)
  1735. }
  1736. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  1737. ctx.ServerError("LoadRepositories", err)
  1738. return
  1739. }
  1740. for _, issue := range issues {
  1741. if issue.IsClosed != isClosed {
  1742. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1743. if models.IsErrDependenciesLeft(err) {
  1744. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  1745. "error": "cannot close this issue because it still has open dependencies",
  1746. })
  1747. return
  1748. }
  1749. ctx.ServerError("ChangeStatus", err)
  1750. return
  1751. }
  1752. }
  1753. }
  1754. ctx.JSON(http.StatusOK, map[string]interface{}{
  1755. "ok": true,
  1756. })
  1757. }
  1758. // NewComment create a comment for issue
  1759. func NewComment(ctx *context.Context) {
  1760. form := web.GetForm(ctx).(*forms.CreateCommentForm)
  1761. issue := GetActionIssue(ctx)
  1762. if ctx.Written() {
  1763. return
  1764. }
  1765. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1766. if log.IsTrace() {
  1767. if ctx.IsSigned {
  1768. issueType := "issues"
  1769. if issue.IsPull {
  1770. issueType = "pulls"
  1771. }
  1772. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1773. "User in Repo has Permissions: %-+v",
  1774. ctx.User,
  1775. log.NewColoredIDValue(issue.PosterID),
  1776. issueType,
  1777. ctx.Repo.Repository,
  1778. ctx.Repo.Permission)
  1779. } else {
  1780. log.Trace("Permission Denied: Not logged in")
  1781. }
  1782. }
  1783. ctx.Error(http.StatusForbidden)
  1784. return
  1785. }
  1786. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  1787. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  1788. ctx.Redirect(issue.HTMLURL(), http.StatusSeeOther)
  1789. return
  1790. }
  1791. var attachments []string
  1792. if setting.Attachment.Enabled {
  1793. attachments = form.Files
  1794. }
  1795. if ctx.HasError() {
  1796. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  1797. ctx.Redirect(issue.HTMLURL())
  1798. return
  1799. }
  1800. var comment *models.Comment
  1801. defer func() {
  1802. // Check if issue admin/poster changes the status of issue.
  1803. if (ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  1804. (form.Status == "reopen" || form.Status == "close") &&
  1805. !(issue.IsPull && issue.PullRequest.HasMerged) {
  1806. // Duplication and conflict check should apply to reopen pull request.
  1807. var pr *models.PullRequest
  1808. if form.Status == "reopen" && issue.IsPull {
  1809. pull := issue.PullRequest
  1810. var err error
  1811. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow)
  1812. if err != nil {
  1813. if !models.IsErrPullRequestNotExist(err) {
  1814. ctx.ServerError("GetUnmergedPullRequest", err)
  1815. return
  1816. }
  1817. }
  1818. // Regenerate patch and test conflict.
  1819. if pr == nil {
  1820. issue.PullRequest.HeadCommitID = ""
  1821. pull_service.AddToTaskQueue(issue.PullRequest)
  1822. }
  1823. }
  1824. if pr != nil {
  1825. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  1826. } else {
  1827. isClosed := form.Status == "close"
  1828. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1829. log.Error("ChangeStatus: %v", err)
  1830. if models.IsErrDependenciesLeft(err) {
  1831. if issue.IsPull {
  1832. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  1833. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1834. } else {
  1835. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  1836. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1837. }
  1838. return
  1839. }
  1840. } else {
  1841. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  1842. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  1843. return
  1844. }
  1845. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  1846. }
  1847. }
  1848. }
  1849. // Redirect to comment hashtag if there is any actual content.
  1850. typeName := "issues"
  1851. if issue.IsPull {
  1852. typeName = "pulls"
  1853. }
  1854. if comment != nil {
  1855. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  1856. } else {
  1857. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  1858. }
  1859. }()
  1860. // Fix #321: Allow empty comments, as long as we have attachments.
  1861. if len(form.Content) == 0 && len(attachments) == 0 {
  1862. return
  1863. }
  1864. comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  1865. if err != nil {
  1866. ctx.ServerError("CreateIssueComment", err)
  1867. return
  1868. }
  1869. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1870. }
  1871. // UpdateCommentContent change comment of issue's content
  1872. func UpdateCommentContent(ctx *context.Context) {
  1873. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1874. if err != nil {
  1875. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1876. return
  1877. }
  1878. if err := comment.LoadIssue(); err != nil {
  1879. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1880. return
  1881. }
  1882. if comment.Type == models.CommentTypeComment {
  1883. if err := comment.LoadAttachments(); err != nil {
  1884. ctx.ServerError("LoadAttachments", err)
  1885. return
  1886. }
  1887. }
  1888. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1889. ctx.Error(http.StatusForbidden)
  1890. return
  1891. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1892. ctx.Error(http.StatusNoContent)
  1893. return
  1894. }
  1895. oldContent := comment.Content
  1896. comment.Content = ctx.FormString("content")
  1897. if len(comment.Content) == 0 {
  1898. ctx.JSON(http.StatusOK, map[string]interface{}{
  1899. "content": "",
  1900. })
  1901. return
  1902. }
  1903. if err = comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil {
  1904. ctx.ServerError("UpdateComment", err)
  1905. return
  1906. }
  1907. if err := updateAttachments(comment, ctx.FormStrings("files[]")); err != nil {
  1908. ctx.ServerError("UpdateAttachments", err)
  1909. return
  1910. }
  1911. content, err := markdown.RenderString(&markup.RenderContext{
  1912. URLPrefix: ctx.FormString("context"),
  1913. Metas: ctx.Repo.Repository.ComposeMetas(),
  1914. GitRepo: ctx.Repo.GitRepo,
  1915. }, comment.Content)
  1916. if err != nil {
  1917. ctx.ServerError("RenderString", err)
  1918. return
  1919. }
  1920. ctx.JSON(http.StatusOK, map[string]interface{}{
  1921. "content": content,
  1922. "attachments": attachmentsHTML(ctx, comment.Attachments, comment.Content),
  1923. })
  1924. }
  1925. // DeleteComment delete comment of issue
  1926. func DeleteComment(ctx *context.Context) {
  1927. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1928. if err != nil {
  1929. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1930. return
  1931. }
  1932. if err := comment.LoadIssue(); err != nil {
  1933. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1934. return
  1935. }
  1936. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1937. ctx.Error(http.StatusForbidden)
  1938. return
  1939. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1940. ctx.Error(http.StatusNoContent)
  1941. return
  1942. }
  1943. if err = comment_service.DeleteComment(ctx.User, comment); err != nil {
  1944. ctx.ServerError("DeleteCommentByID", err)
  1945. return
  1946. }
  1947. ctx.Status(200)
  1948. }
  1949. // ChangeIssueReaction create a reaction for issue
  1950. func ChangeIssueReaction(ctx *context.Context) {
  1951. form := web.GetForm(ctx).(*forms.ReactionForm)
  1952. issue := GetActionIssue(ctx)
  1953. if ctx.Written() {
  1954. return
  1955. }
  1956. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1957. if log.IsTrace() {
  1958. if ctx.IsSigned {
  1959. issueType := "issues"
  1960. if issue.IsPull {
  1961. issueType = "pulls"
  1962. }
  1963. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1964. "User in Repo has Permissions: %-+v",
  1965. ctx.User,
  1966. log.NewColoredIDValue(issue.PosterID),
  1967. issueType,
  1968. ctx.Repo.Repository,
  1969. ctx.Repo.Permission)
  1970. } else {
  1971. log.Trace("Permission Denied: Not logged in")
  1972. }
  1973. }
  1974. ctx.Error(http.StatusForbidden)
  1975. return
  1976. }
  1977. if ctx.HasError() {
  1978. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1979. return
  1980. }
  1981. switch ctx.Params(":action") {
  1982. case "react":
  1983. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1984. if err != nil {
  1985. if models.IsErrForbiddenIssueReaction(err) {
  1986. ctx.ServerError("ChangeIssueReaction", err)
  1987. return
  1988. }
  1989. log.Info("CreateIssueReaction: %s", err)
  1990. break
  1991. }
  1992. // Reload new reactions
  1993. issue.Reactions = nil
  1994. if err = issue.LoadAttributes(); err != nil {
  1995. log.Info("issue.LoadAttributes: %s", err)
  1996. break
  1997. }
  1998. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1999. case "unreact":
  2000. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  2001. ctx.ServerError("DeleteIssueReaction", err)
  2002. return
  2003. }
  2004. // Reload new reactions
  2005. issue.Reactions = nil
  2006. if err := issue.LoadAttributes(); err != nil {
  2007. log.Info("issue.LoadAttributes: %s", err)
  2008. break
  2009. }
  2010. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  2011. default:
  2012. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  2013. return
  2014. }
  2015. if len(issue.Reactions) == 0 {
  2016. ctx.JSON(http.StatusOK, map[string]interface{}{
  2017. "empty": true,
  2018. "html": "",
  2019. })
  2020. return
  2021. }
  2022. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  2023. "ctx": ctx.Data,
  2024. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  2025. "Reactions": issue.Reactions.GroupByType(),
  2026. })
  2027. if err != nil {
  2028. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  2029. return
  2030. }
  2031. ctx.JSON(http.StatusOK, map[string]interface{}{
  2032. "html": html,
  2033. })
  2034. }
  2035. // ChangeCommentReaction create a reaction for comment
  2036. func ChangeCommentReaction(ctx *context.Context) {
  2037. form := web.GetForm(ctx).(*forms.ReactionForm)
  2038. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  2039. if err != nil {
  2040. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2041. return
  2042. }
  2043. if err := comment.LoadIssue(); err != nil {
  2044. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  2045. return
  2046. }
  2047. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanReadIssuesOrPulls(comment.Issue.IsPull)) {
  2048. if log.IsTrace() {
  2049. if ctx.IsSigned {
  2050. issueType := "issues"
  2051. if comment.Issue.IsPull {
  2052. issueType = "pulls"
  2053. }
  2054. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  2055. "User in Repo has Permissions: %-+v",
  2056. ctx.User,
  2057. log.NewColoredIDValue(comment.Issue.PosterID),
  2058. issueType,
  2059. ctx.Repo.Repository,
  2060. ctx.Repo.Permission)
  2061. } else {
  2062. log.Trace("Permission Denied: Not logged in")
  2063. }
  2064. }
  2065. ctx.Error(http.StatusForbidden)
  2066. return
  2067. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  2068. ctx.Error(http.StatusNoContent)
  2069. return
  2070. }
  2071. switch ctx.Params(":action") {
  2072. case "react":
  2073. reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Content)
  2074. if err != nil {
  2075. if models.IsErrForbiddenIssueReaction(err) {
  2076. ctx.ServerError("ChangeIssueReaction", err)
  2077. return
  2078. }
  2079. log.Info("CreateCommentReaction: %s", err)
  2080. break
  2081. }
  2082. // Reload new reactions
  2083. comment.Reactions = nil
  2084. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2085. log.Info("comment.LoadReactions: %s", err)
  2086. break
  2087. }
  2088. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
  2089. case "unreact":
  2090. if err := models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Content); err != nil {
  2091. ctx.ServerError("DeleteCommentReaction", err)
  2092. return
  2093. }
  2094. // Reload new reactions
  2095. comment.Reactions = nil
  2096. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2097. log.Info("comment.LoadReactions: %s", err)
  2098. break
  2099. }
  2100. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID)
  2101. default:
  2102. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  2103. return
  2104. }
  2105. if len(comment.Reactions) == 0 {
  2106. ctx.JSON(http.StatusOK, map[string]interface{}{
  2107. "empty": true,
  2108. "html": "",
  2109. })
  2110. return
  2111. }
  2112. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  2113. "ctx": ctx.Data,
  2114. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  2115. "Reactions": comment.Reactions.GroupByType(),
  2116. })
  2117. if err != nil {
  2118. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  2119. return
  2120. }
  2121. ctx.JSON(http.StatusOK, map[string]interface{}{
  2122. "html": html,
  2123. })
  2124. }
  2125. func addParticipant(poster *models.User, participants []*models.User) []*models.User {
  2126. for _, part := range participants {
  2127. if poster.ID == part.ID {
  2128. return participants
  2129. }
  2130. }
  2131. return append(participants, poster)
  2132. }
  2133. func filterXRefComments(ctx *context.Context, issue *models.Issue) error {
  2134. // Remove comments that the user has no permissions to see
  2135. for i := 0; i < len(issue.Comments); {
  2136. c := issue.Comments[i]
  2137. if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 {
  2138. var err error
  2139. // Set RefRepo for description in template
  2140. c.RefRepo, err = models.GetRepositoryByID(c.RefRepoID)
  2141. if err != nil {
  2142. return err
  2143. }
  2144. perm, err := models.GetUserRepoPermission(c.RefRepo, ctx.User)
  2145. if err != nil {
  2146. return err
  2147. }
  2148. if !perm.CanReadIssuesOrPulls(c.RefIsPull) {
  2149. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2150. continue
  2151. }
  2152. }
  2153. i++
  2154. }
  2155. return nil
  2156. }
  2157. // GetIssueAttachments returns attachments for the issue
  2158. func GetIssueAttachments(ctx *context.Context) {
  2159. issue := GetActionIssue(ctx)
  2160. var attachments = make([]*api.Attachment, len(issue.Attachments))
  2161. for i := 0; i < len(issue.Attachments); i++ {
  2162. attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i])
  2163. }
  2164. ctx.JSON(http.StatusOK, attachments)
  2165. }
  2166. // GetCommentAttachments returns attachments for the comment
  2167. func GetCommentAttachments(ctx *context.Context) {
  2168. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  2169. if err != nil {
  2170. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2171. return
  2172. }
  2173. var attachments = make([]*api.Attachment, 0)
  2174. if comment.Type == models.CommentTypeComment {
  2175. if err := comment.LoadAttachments(); err != nil {
  2176. ctx.ServerError("LoadAttachments", err)
  2177. return
  2178. }
  2179. for i := 0; i < len(comment.Attachments); i++ {
  2180. attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i]))
  2181. }
  2182. }
  2183. ctx.JSON(http.StatusOK, attachments)
  2184. }
  2185. func updateAttachments(item interface{}, files []string) error {
  2186. var attachments []*models.Attachment
  2187. switch content := item.(type) {
  2188. case *models.Issue:
  2189. attachments = content.Attachments
  2190. case *models.Comment:
  2191. attachments = content.Attachments
  2192. default:
  2193. return fmt.Errorf("Unknown Type: %T", content)
  2194. }
  2195. for i := 0; i < len(attachments); i++ {
  2196. if util.IsStringInSlice(attachments[i].UUID, files) {
  2197. continue
  2198. }
  2199. if err := models.DeleteAttachment(attachments[i], true); err != nil {
  2200. return err
  2201. }
  2202. }
  2203. var err error
  2204. if len(files) > 0 {
  2205. switch content := item.(type) {
  2206. case *models.Issue:
  2207. err = content.UpdateAttachments(files)
  2208. case *models.Comment:
  2209. err = content.UpdateAttachments(files)
  2210. default:
  2211. return fmt.Errorf("Unknown Type: %T", content)
  2212. }
  2213. if err != nil {
  2214. return err
  2215. }
  2216. }
  2217. switch content := item.(type) {
  2218. case *models.Issue:
  2219. content.Attachments, err = models.GetAttachmentsByIssueID(content.ID)
  2220. case *models.Comment:
  2221. content.Attachments, err = models.GetAttachmentsByCommentID(content.ID)
  2222. default:
  2223. return fmt.Errorf("Unknown Type: %T", content)
  2224. }
  2225. return err
  2226. }
  2227. func attachmentsHTML(ctx *context.Context, attachments []*models.Attachment, content string) string {
  2228. attachHTML, err := ctx.HTMLString(string(tplAttachment), map[string]interface{}{
  2229. "ctx": ctx.Data,
  2230. "Attachments": attachments,
  2231. "Content": content,
  2232. })
  2233. if err != nil {
  2234. ctx.ServerError("attachmentsHTML.HTMLString", err)
  2235. return ""
  2236. }
  2237. return attachHTML
  2238. }
  2239. // combineLabelComments combine the nearby label comments as one.
  2240. func combineLabelComments(issue *models.Issue) {
  2241. var prev, cur *models.Comment
  2242. for i := 0; i < len(issue.Comments); i++ {
  2243. cur = issue.Comments[i]
  2244. if i > 0 {
  2245. prev = issue.Comments[i-1]
  2246. }
  2247. if i == 0 || cur.Type != models.CommentTypeLabel ||
  2248. (prev != nil && prev.PosterID != cur.PosterID) ||
  2249. (prev != nil && cur.CreatedUnix-prev.CreatedUnix >= 60) {
  2250. if cur.Type == models.CommentTypeLabel && cur.Label != nil {
  2251. if cur.Content != "1" {
  2252. cur.RemovedLabels = append(cur.RemovedLabels, cur.Label)
  2253. } else {
  2254. cur.AddedLabels = append(cur.AddedLabels, cur.Label)
  2255. }
  2256. }
  2257. continue
  2258. }
  2259. if cur.Label != nil { // now cur MUST be label comment
  2260. if prev.Type == models.CommentTypeLabel { // we can combine them only prev is a label comment
  2261. if cur.Content != "1" {
  2262. prev.RemovedLabels = append(prev.RemovedLabels, cur.Label)
  2263. } else {
  2264. prev.AddedLabels = append(prev.AddedLabels, cur.Label)
  2265. }
  2266. prev.CreatedUnix = cur.CreatedUnix
  2267. // remove the current comment since it has been combined to prev comment
  2268. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2269. i--
  2270. } else { // if prev is not a label comment, start a new group
  2271. if cur.Content != "1" {
  2272. cur.RemovedLabels = append(cur.RemovedLabels, cur.Label)
  2273. } else {
  2274. cur.AddedLabels = append(cur.AddedLabels, cur.Label)
  2275. }
  2276. }
  2277. }
  2278. }
  2279. }
  2280. // get all teams that current user can mention
  2281. func handleTeamMentions(ctx *context.Context) {
  2282. if ctx.User == nil || !ctx.Repo.Owner.IsOrganization() {
  2283. return
  2284. }
  2285. isAdmin := false
  2286. var err error
  2287. // Admin has super access.
  2288. if ctx.User.IsAdmin {
  2289. isAdmin = true
  2290. } else {
  2291. isAdmin, err = ctx.Repo.Owner.IsOwnedBy(ctx.User.ID)
  2292. if err != nil {
  2293. ctx.ServerError("IsOwnedBy", err)
  2294. return
  2295. }
  2296. }
  2297. if isAdmin {
  2298. if err := ctx.Repo.Owner.LoadTeams(); err != nil {
  2299. ctx.ServerError("LoadTeams", err)
  2300. return
  2301. }
  2302. } else {
  2303. ctx.Repo.Owner.Teams, err = ctx.Repo.Owner.GetUserTeams(ctx.User.ID)
  2304. if err != nil {
  2305. ctx.ServerError("GetUserTeams", err)
  2306. return
  2307. }
  2308. }
  2309. ctx.Data["MentionableTeams"] = ctx.Repo.Owner.Teams
  2310. ctx.Data["MentionableTeamsOrg"] = ctx.Repo.Owner.Name
  2311. ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.RelAvatarLink()
  2312. }