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.

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