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

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