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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  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. isAdded := false
  710. for j := range participants {
  711. if comment.Poster == participants[j] {
  712. isAdded = true
  713. break
  714. }
  715. }
  716. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  717. participants = append(participants, comment.Poster)
  718. }
  719. } else if comment.Type == models.CommentTypeLabel {
  720. if err = comment.LoadLabel(); err != nil {
  721. ctx.ServerError("LoadLabel", err)
  722. return
  723. }
  724. } else if comment.Type == models.CommentTypeMilestone {
  725. if err = comment.LoadMilestone(); err != nil {
  726. ctx.ServerError("LoadMilestone", err)
  727. return
  728. }
  729. ghostMilestone := &models.Milestone{
  730. ID: -1,
  731. Name: ctx.Tr("repo.issues.deleted_milestone"),
  732. }
  733. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  734. comment.OldMilestone = ghostMilestone
  735. }
  736. if comment.MilestoneID > 0 && comment.Milestone == nil {
  737. comment.Milestone = ghostMilestone
  738. }
  739. } else if comment.Type == models.CommentTypeAssignees {
  740. if err = comment.LoadAssigneeUser(); err != nil {
  741. ctx.ServerError("LoadAssigneeUser", err)
  742. return
  743. }
  744. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  745. if err = comment.LoadDepIssueDetails(); err != nil {
  746. ctx.ServerError("LoadDepIssueDetails", err)
  747. return
  748. }
  749. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview {
  750. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  751. ctx.ServerError("LoadReview", err)
  752. return
  753. }
  754. if comment.Review == nil {
  755. continue
  756. }
  757. if err = comment.Review.LoadAttributes(); err != nil {
  758. if !models.IsErrUserNotExist(err) {
  759. ctx.ServerError("Review.LoadAttributes", err)
  760. return
  761. }
  762. comment.Review.Reviewer = models.NewGhostUser()
  763. }
  764. if err = comment.Review.LoadCodeComments(); err != nil {
  765. ctx.ServerError("Review.LoadCodeComments", err)
  766. return
  767. }
  768. }
  769. }
  770. if issue.IsPull {
  771. pull := issue.PullRequest
  772. pull.Issue = issue
  773. canDelete := false
  774. if ctx.IsSigned {
  775. if err := pull.GetHeadRepo(); err != nil {
  776. log.Error("GetHeadRepo: %v", err)
  777. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch {
  778. perm, err := models.GetUserRepoPermission(pull.HeadRepo, ctx.User)
  779. if err != nil {
  780. ctx.ServerError("GetUserRepoPermission", err)
  781. return
  782. }
  783. if perm.CanWrite(models.UnitTypeCode) {
  784. // Check if branch is not protected
  785. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch, ctx.User); err != nil {
  786. log.Error("IsProtectedBranch: %v", err)
  787. } else if !protected {
  788. canDelete = true
  789. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup"
  790. }
  791. }
  792. }
  793. }
  794. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  795. if err != nil {
  796. ctx.ServerError("GetUnit", err)
  797. return
  798. }
  799. prConfig := prUnit.PullRequestsConfig()
  800. ctx.Data["AllowMerge"] = ctx.Repo.CanWrite(models.UnitTypeCode)
  801. if err := pull.CheckUserAllowedToMerge(ctx.User); err != nil {
  802. if !models.IsErrNotAllowedToMerge(err) {
  803. ctx.ServerError("CheckUserAllowedToMerge", err)
  804. return
  805. }
  806. ctx.Data["AllowMerge"] = false
  807. }
  808. // Check correct values and select default
  809. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  810. !prConfig.IsMergeStyleAllowed(ms) {
  811. if prConfig.AllowMerge {
  812. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  813. } else if prConfig.AllowRebase {
  814. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  815. } else if prConfig.AllowRebaseMerge {
  816. ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge
  817. } else if prConfig.AllowSquash {
  818. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  819. } else {
  820. ctx.Data["MergeStyle"] = ""
  821. }
  822. }
  823. if err = pull.LoadProtectedBranch(); err != nil {
  824. ctx.ServerError("LoadProtectedBranch", err)
  825. return
  826. }
  827. if pull.ProtectedBranch != nil {
  828. cnt := pull.ProtectedBranch.GetGrantedApprovalsCount(pull)
  829. ctx.Data["IsBlockedByApprovals"] = pull.ProtectedBranch.RequiredApprovals > 0 && cnt < pull.ProtectedBranch.RequiredApprovals
  830. ctx.Data["GrantedApprovals"] = cnt
  831. }
  832. ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
  833. ctx.Data["PullReviewersWithType"], err = models.GetReviewersByPullID(issue.ID)
  834. if err != nil {
  835. ctx.ServerError("GetReviewersByPullID", err)
  836. return
  837. }
  838. }
  839. // Get Dependencies
  840. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  841. if err != nil {
  842. ctx.ServerError("BlockedByDependencies", err)
  843. return
  844. }
  845. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  846. if err != nil {
  847. ctx.ServerError("BlockingDependencies", err)
  848. return
  849. }
  850. ctx.Data["Participants"] = participants
  851. ctx.Data["NumParticipants"] = len(participants)
  852. ctx.Data["Issue"] = issue
  853. ctx.Data["ReadOnly"] = true
  854. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  855. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
  856. ctx.Data["IsIssueWriter"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  857. ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
  858. ctx.Data["IsRepoIssuesWriter"] = ctx.IsSigned && (ctx.Repo.CanWrite(models.UnitTypeIssues) || ctx.User.IsAdmin)
  859. ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
  860. ctx.HTML(200, tplIssueView)
  861. }
  862. // GetActionIssue will return the issue which is used in the context.
  863. func GetActionIssue(ctx *context.Context) *models.Issue {
  864. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  865. if err != nil {
  866. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  867. return nil
  868. }
  869. issue.Repo = ctx.Repo.Repository
  870. checkIssueRights(ctx, issue)
  871. if ctx.Written() {
  872. return nil
  873. }
  874. if err = issue.LoadAttributes(); err != nil {
  875. ctx.ServerError("LoadAttributes", nil)
  876. return nil
  877. }
  878. return issue
  879. }
  880. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  881. if issue.IsPull && !ctx.Repo.CanRead(models.UnitTypePullRequests) ||
  882. !issue.IsPull && !ctx.Repo.CanRead(models.UnitTypeIssues) {
  883. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  884. }
  885. }
  886. func getActionIssues(ctx *context.Context) []*models.Issue {
  887. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  888. if len(commaSeparatedIssueIDs) == 0 {
  889. return nil
  890. }
  891. issueIDs := make([]int64, 0, 10)
  892. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  893. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  894. if err != nil {
  895. ctx.ServerError("ParseInt", err)
  896. return nil
  897. }
  898. issueIDs = append(issueIDs, issueID)
  899. }
  900. issues, err := models.GetIssuesByIDs(issueIDs)
  901. if err != nil {
  902. ctx.ServerError("GetIssuesByIDs", err)
  903. return nil
  904. }
  905. // Check access rights for all issues
  906. issueUnitEnabled := ctx.Repo.CanRead(models.UnitTypeIssues)
  907. prUnitEnabled := ctx.Repo.CanRead(models.UnitTypePullRequests)
  908. for _, issue := range issues {
  909. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  910. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  911. return nil
  912. }
  913. if err = issue.LoadAttributes(); err != nil {
  914. ctx.ServerError("LoadAttributes", err)
  915. return nil
  916. }
  917. }
  918. return issues
  919. }
  920. // UpdateIssueTitle change issue's title
  921. func UpdateIssueTitle(ctx *context.Context) {
  922. issue := GetActionIssue(ctx)
  923. if ctx.Written() {
  924. return
  925. }
  926. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  927. ctx.Error(403)
  928. return
  929. }
  930. title := ctx.QueryTrim("title")
  931. if len(title) == 0 {
  932. ctx.Error(204)
  933. return
  934. }
  935. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  936. ctx.ServerError("ChangeTitle", err)
  937. return
  938. }
  939. ctx.JSON(200, map[string]interface{}{
  940. "title": issue.Title,
  941. })
  942. }
  943. // UpdateIssueContent change issue's content
  944. func UpdateIssueContent(ctx *context.Context) {
  945. issue := GetActionIssue(ctx)
  946. if ctx.Written() {
  947. return
  948. }
  949. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  950. ctx.Error(403)
  951. return
  952. }
  953. content := ctx.Query("content")
  954. if err := issue.ChangeContent(ctx.User, content); err != nil {
  955. ctx.ServerError("ChangeContent", err)
  956. return
  957. }
  958. ctx.JSON(200, map[string]interface{}{
  959. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  960. })
  961. }
  962. // UpdateIssueMilestone change issue's milestone
  963. func UpdateIssueMilestone(ctx *context.Context) {
  964. issues := getActionIssues(ctx)
  965. if ctx.Written() {
  966. return
  967. }
  968. milestoneID := ctx.QueryInt64("id")
  969. for _, issue := range issues {
  970. oldMilestoneID := issue.MilestoneID
  971. if oldMilestoneID == milestoneID {
  972. continue
  973. }
  974. issue.MilestoneID = milestoneID
  975. if err := models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  976. ctx.ServerError("ChangeMilestoneAssign", err)
  977. return
  978. }
  979. }
  980. ctx.JSON(200, map[string]interface{}{
  981. "ok": true,
  982. })
  983. }
  984. // UpdateIssueAssignee change issue's assignee
  985. func UpdateIssueAssignee(ctx *context.Context) {
  986. issues := getActionIssues(ctx)
  987. if ctx.Written() {
  988. return
  989. }
  990. assigneeID := ctx.QueryInt64("id")
  991. action := ctx.Query("action")
  992. for _, issue := range issues {
  993. switch action {
  994. case "clear":
  995. if err := models.DeleteNotPassedAssignee(issue, ctx.User, []*models.User{}); err != nil {
  996. ctx.ServerError("ClearAssignees", err)
  997. return
  998. }
  999. default:
  1000. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  1001. ctx.ServerError("ChangeAssignee", err)
  1002. return
  1003. }
  1004. }
  1005. }
  1006. ctx.JSON(200, map[string]interface{}{
  1007. "ok": true,
  1008. })
  1009. }
  1010. // UpdateIssueStatus change issue's status
  1011. func UpdateIssueStatus(ctx *context.Context) {
  1012. issues := getActionIssues(ctx)
  1013. if ctx.Written() {
  1014. return
  1015. }
  1016. var isClosed bool
  1017. switch action := ctx.Query("action"); action {
  1018. case "open":
  1019. isClosed = false
  1020. case "close":
  1021. isClosed = true
  1022. default:
  1023. log.Warn("Unrecognized action: %s", action)
  1024. }
  1025. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  1026. ctx.ServerError("LoadRepositories", err)
  1027. return
  1028. }
  1029. for _, issue := range issues {
  1030. if issue.IsClosed != isClosed {
  1031. if err := issue.ChangeStatus(ctx.User, isClosed); err != nil {
  1032. if models.IsErrDependenciesLeft(err) {
  1033. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  1034. "error": "cannot close this issue because it still has open dependencies",
  1035. })
  1036. return
  1037. }
  1038. ctx.ServerError("ChangeStatus", err)
  1039. return
  1040. }
  1041. notification.NotifyIssueChangeStatus(ctx.User, issue, isClosed)
  1042. }
  1043. }
  1044. ctx.JSON(200, map[string]interface{}{
  1045. "ok": true,
  1046. })
  1047. }
  1048. // NewComment create a comment for issue
  1049. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  1050. issue := GetActionIssue(ctx)
  1051. if ctx.Written() {
  1052. return
  1053. }
  1054. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1055. if log.IsTrace() {
  1056. if ctx.IsSigned {
  1057. issueType := "issues"
  1058. if issue.IsPull {
  1059. issueType = "pulls"
  1060. }
  1061. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1062. "User in Repo has Permissions: %-+v",
  1063. ctx.User,
  1064. log.NewColoredIDValue(issue.PosterID),
  1065. issueType,
  1066. ctx.Repo.Repository,
  1067. ctx.Repo.Permission)
  1068. } else {
  1069. log.Trace("Permission Denied: Not logged in")
  1070. }
  1071. }
  1072. ctx.Error(403)
  1073. }
  1074. if issue.IsLocked && !ctx.Repo.CanWrite(models.UnitTypeIssues) && !ctx.User.IsAdmin {
  1075. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  1076. ctx.Redirect(issue.HTMLURL(), http.StatusSeeOther)
  1077. return
  1078. }
  1079. var attachments []string
  1080. if setting.AttachmentEnabled {
  1081. attachments = form.Files
  1082. }
  1083. if ctx.HasError() {
  1084. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  1085. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  1086. return
  1087. }
  1088. var comment *models.Comment
  1089. defer func() {
  1090. // Check if issue admin/poster changes the status of issue.
  1091. if (ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  1092. (form.Status == "reopen" || form.Status == "close") &&
  1093. !(issue.IsPull && issue.PullRequest.HasMerged) {
  1094. // Duplication and conflict check should apply to reopen pull request.
  1095. var pr *models.PullRequest
  1096. if form.Status == "reopen" && issue.IsPull {
  1097. pull := issue.PullRequest
  1098. var err error
  1099. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  1100. if err != nil {
  1101. if !models.IsErrPullRequestNotExist(err) {
  1102. ctx.ServerError("GetUnmergedPullRequest", err)
  1103. return
  1104. }
  1105. }
  1106. // Regenerate patch and test conflict.
  1107. if pr == nil {
  1108. if err = issue.PullRequest.UpdatePatch(); err != nil {
  1109. ctx.ServerError("UpdatePatch", err)
  1110. return
  1111. }
  1112. issue.PullRequest.AddToTaskQueue()
  1113. }
  1114. }
  1115. if pr != nil {
  1116. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  1117. } else {
  1118. isClosed := form.Status == "close"
  1119. if err := issue.ChangeStatus(ctx.User, isClosed); err != nil {
  1120. log.Error("ChangeStatus: %v", err)
  1121. if models.IsErrDependenciesLeft(err) {
  1122. if issue.IsPull {
  1123. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  1124. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1125. } else {
  1126. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  1127. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1128. }
  1129. return
  1130. }
  1131. } else {
  1132. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  1133. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  1134. return
  1135. }
  1136. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  1137. notification.NotifyIssueChangeStatus(ctx.User, issue, isClosed)
  1138. }
  1139. }
  1140. }
  1141. // Redirect to comment hashtag if there is any actual content.
  1142. typeName := "issues"
  1143. if issue.IsPull {
  1144. typeName = "pulls"
  1145. }
  1146. if comment != nil {
  1147. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  1148. } else {
  1149. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  1150. }
  1151. }()
  1152. // Fix #321: Allow empty comments, as long as we have attachments.
  1153. if len(form.Content) == 0 && len(attachments) == 0 {
  1154. return
  1155. }
  1156. comment, err := models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  1157. if err != nil {
  1158. ctx.ServerError("CreateIssueComment", err)
  1159. return
  1160. }
  1161. notification.NotifyCreateIssueComment(ctx.User, ctx.Repo.Repository, issue, comment)
  1162. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1163. }
  1164. // UpdateCommentContent change comment of issue's content
  1165. func UpdateCommentContent(ctx *context.Context) {
  1166. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1167. if err != nil {
  1168. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1169. return
  1170. }
  1171. if err := comment.LoadIssue(); err != nil {
  1172. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1173. return
  1174. }
  1175. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1176. ctx.Error(403)
  1177. return
  1178. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1179. ctx.Error(204)
  1180. return
  1181. }
  1182. oldContent := comment.Content
  1183. comment.Content = ctx.Query("content")
  1184. if len(comment.Content) == 0 {
  1185. ctx.JSON(200, map[string]interface{}{
  1186. "content": "",
  1187. })
  1188. return
  1189. }
  1190. if err = models.UpdateComment(ctx.User, comment, oldContent); err != nil {
  1191. ctx.ServerError("UpdateComment", err)
  1192. return
  1193. }
  1194. notification.NotifyUpdateComment(ctx.User, comment, oldContent)
  1195. ctx.JSON(200, map[string]interface{}{
  1196. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  1197. })
  1198. }
  1199. // DeleteComment delete comment of issue
  1200. func DeleteComment(ctx *context.Context) {
  1201. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1202. if err != nil {
  1203. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1204. return
  1205. }
  1206. if err := comment.LoadIssue(); err != nil {
  1207. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1208. return
  1209. }
  1210. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1211. ctx.Error(403)
  1212. return
  1213. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1214. ctx.Error(204)
  1215. return
  1216. }
  1217. if err = models.DeleteComment(ctx.User, comment); err != nil {
  1218. ctx.ServerError("DeleteCommentByID", err)
  1219. return
  1220. }
  1221. notification.NotifyDeleteComment(ctx.User, comment)
  1222. ctx.Status(200)
  1223. }
  1224. // ChangeIssueReaction create a reaction for issue
  1225. func ChangeIssueReaction(ctx *context.Context, form auth.ReactionForm) {
  1226. issue := GetActionIssue(ctx)
  1227. if ctx.Written() {
  1228. return
  1229. }
  1230. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1231. if log.IsTrace() {
  1232. if ctx.IsSigned {
  1233. issueType := "issues"
  1234. if issue.IsPull {
  1235. issueType = "pulls"
  1236. }
  1237. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1238. "User in Repo has Permissions: %-+v",
  1239. ctx.User,
  1240. log.NewColoredIDValue(issue.PosterID),
  1241. issueType,
  1242. ctx.Repo.Repository,
  1243. ctx.Repo.Permission)
  1244. } else {
  1245. log.Trace("Permission Denied: Not logged in")
  1246. }
  1247. }
  1248. ctx.Error(403)
  1249. return
  1250. }
  1251. if ctx.HasError() {
  1252. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1253. return
  1254. }
  1255. switch ctx.Params(":action") {
  1256. case "react":
  1257. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1258. if err != nil {
  1259. log.Info("CreateIssueReaction: %s", err)
  1260. break
  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 created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1269. case "unreact":
  1270. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1271. ctx.ServerError("DeleteIssueReaction", err)
  1272. return
  1273. }
  1274. // Reload new reactions
  1275. issue.Reactions = nil
  1276. if err := issue.LoadAttributes(); err != nil {
  1277. log.Info("issue.LoadAttributes: %s", err)
  1278. break
  1279. }
  1280. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1281. default:
  1282. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1283. return
  1284. }
  1285. if len(issue.Reactions) == 0 {
  1286. ctx.JSON(200, map[string]interface{}{
  1287. "empty": true,
  1288. "html": "",
  1289. })
  1290. return
  1291. }
  1292. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1293. "ctx": ctx.Data,
  1294. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1295. "Reactions": issue.Reactions.GroupByType(),
  1296. })
  1297. if err != nil {
  1298. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  1299. return
  1300. }
  1301. ctx.JSON(200, map[string]interface{}{
  1302. "html": html,
  1303. })
  1304. }
  1305. // ChangeCommentReaction create a reaction for comment
  1306. func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
  1307. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1308. if err != nil {
  1309. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1310. return
  1311. }
  1312. if err := comment.LoadIssue(); err != nil {
  1313. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1314. return
  1315. }
  1316. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanReadIssuesOrPulls(comment.Issue.IsPull)) {
  1317. if log.IsTrace() {
  1318. if ctx.IsSigned {
  1319. issueType := "issues"
  1320. if comment.Issue.IsPull {
  1321. issueType = "pulls"
  1322. }
  1323. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1324. "User in Repo has Permissions: %-+v",
  1325. ctx.User,
  1326. log.NewColoredIDValue(comment.Issue.PosterID),
  1327. issueType,
  1328. ctx.Repo.Repository,
  1329. ctx.Repo.Permission)
  1330. } else {
  1331. log.Trace("Permission Denied: Not logged in")
  1332. }
  1333. }
  1334. ctx.Error(403)
  1335. return
  1336. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1337. ctx.Error(204)
  1338. return
  1339. }
  1340. switch ctx.Params(":action") {
  1341. case "react":
  1342. reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Content)
  1343. if err != nil {
  1344. log.Info("CreateCommentReaction: %s", err)
  1345. break
  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 created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
  1354. case "unreact":
  1355. if err := models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Content); err != nil {
  1356. ctx.ServerError("DeleteCommentReaction", err)
  1357. return
  1358. }
  1359. // Reload new reactions
  1360. comment.Reactions = nil
  1361. if err = comment.LoadReactions(); err != nil {
  1362. log.Info("comment.LoadReactions: %s", err)
  1363. break
  1364. }
  1365. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID)
  1366. default:
  1367. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1368. return
  1369. }
  1370. if len(comment.Reactions) == 0 {
  1371. ctx.JSON(200, map[string]interface{}{
  1372. "empty": true,
  1373. "html": "",
  1374. })
  1375. return
  1376. }
  1377. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1378. "ctx": ctx.Data,
  1379. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  1380. "Reactions": comment.Reactions.GroupByType(),
  1381. })
  1382. if err != nil {
  1383. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  1384. return
  1385. }
  1386. ctx.JSON(200, map[string]interface{}{
  1387. "html": html,
  1388. })
  1389. }