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

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