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

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