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

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