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

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