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

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