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

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