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

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