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

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