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

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