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

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