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

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