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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package repo
  5. import (
  6. "bytes"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/Unknwon/com"
  15. "github.com/Unknwon/paginater"
  16. "code.gitea.io/git"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/auth"
  19. "code.gitea.io/gitea/modules/base"
  20. "code.gitea.io/gitea/modules/context"
  21. "code.gitea.io/gitea/modules/indexer"
  22. "code.gitea.io/gitea/modules/log"
  23. "code.gitea.io/gitea/modules/markup/markdown"
  24. "code.gitea.io/gitea/modules/notification"
  25. "code.gitea.io/gitea/modules/setting"
  26. "code.gitea.io/gitea/modules/util"
  27. )
  28. const (
  29. tplIssues base.TplName = "repo/issue/list"
  30. tplIssueNew base.TplName = "repo/issue/new"
  31. tplIssueView base.TplName = "repo/issue/view"
  32. tplMilestone base.TplName = "repo/issue/milestones"
  33. tplMilestoneNew base.TplName = "repo/issue/milestone_new"
  34. tplMilestoneEdit base.TplName = "repo/issue/milestone_edit"
  35. tplReactions base.TplName = "repo/issue/view_content/reactions"
  36. issueTemplateKey = "IssueTemplate"
  37. )
  38. var (
  39. // ErrFileTypeForbidden not allowed file type error
  40. ErrFileTypeForbidden = errors.New("File type is not allowed")
  41. // ErrTooManyFiles upload too many files
  42. ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded")
  43. // IssueTemplateCandidates issue templates
  44. IssueTemplateCandidates = []string{
  45. "ISSUE_TEMPLATE.md",
  46. "issue_template.md",
  47. ".gitea/ISSUE_TEMPLATE.md",
  48. ".gitea/issue_template.md",
  49. ".github/ISSUE_TEMPLATE.md",
  50. ".github/issue_template.md",
  51. }
  52. )
  53. // MustEnableIssues check if repository enable internal issues
  54. func MustEnableIssues(ctx *context.Context) {
  55. if !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) &&
  56. !ctx.Repo.Repository.UnitEnabled(models.UnitTypeExternalTracker) {
  57. ctx.Handle(404, "MustEnableIssues", nil)
  58. return
  59. }
  60. unit, err := ctx.Repo.Repository.GetUnit(models.UnitTypeExternalTracker)
  61. if err == nil {
  62. ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL)
  63. return
  64. }
  65. }
  66. // MustAllowPulls check if repository enable pull requests
  67. func MustAllowPulls(ctx *context.Context) {
  68. if !ctx.Repo.Repository.AllowsPulls() {
  69. ctx.Handle(404, "MustAllowPulls", nil)
  70. return
  71. }
  72. // User can send pull request if owns a forked repository.
  73. if ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID) {
  74. ctx.Repo.PullRequest.Allowed = true
  75. ctx.Repo.PullRequest.HeadInfo = ctx.User.Name + ":" + ctx.Repo.BranchName
  76. }
  77. }
  78. // Issues render issues page
  79. func Issues(ctx *context.Context) {
  80. isPullList := ctx.Params(":type") == "pulls"
  81. if isPullList {
  82. MustAllowPulls(ctx)
  83. if ctx.Written() {
  84. return
  85. }
  86. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  87. ctx.Data["PageIsPullList"] = true
  88. } else {
  89. MustEnableIssues(ctx)
  90. if ctx.Written() {
  91. return
  92. }
  93. ctx.Data["Title"] = ctx.Tr("repo.issues")
  94. ctx.Data["PageIsIssueList"] = true
  95. }
  96. viewType := ctx.Query("type")
  97. sortType := ctx.Query("sort")
  98. types := []string{"all", "assigned", "created_by", "mentioned"}
  99. if !com.IsSliceContainsStr(types, viewType) {
  100. viewType = "all"
  101. }
  102. var (
  103. assigneeID = ctx.QueryInt64("assignee")
  104. posterID int64
  105. mentionedID int64
  106. forceEmpty bool
  107. )
  108. if ctx.IsSigned {
  109. switch viewType {
  110. case "created_by":
  111. posterID = ctx.User.ID
  112. case "mentioned":
  113. mentionedID = ctx.User.ID
  114. }
  115. }
  116. repo := ctx.Repo.Repository
  117. selectLabels := ctx.Query("labels")
  118. milestoneID := ctx.QueryInt64("milestone")
  119. isShowClosed := ctx.Query("state") == "closed"
  120. keyword := strings.Trim(ctx.Query("q"), " ")
  121. if bytes.Contains([]byte(keyword), []byte{0x00}) {
  122. keyword = ""
  123. }
  124. var issueIDs []int64
  125. var err error
  126. if len(keyword) > 0 {
  127. issueIDs, err = indexer.SearchIssuesByKeyword(repo.ID, keyword)
  128. if len(issueIDs) == 0 {
  129. forceEmpty = true
  130. }
  131. }
  132. var issueStats *models.IssueStats
  133. if forceEmpty {
  134. issueStats = &models.IssueStats{}
  135. } else {
  136. var err error
  137. issueStats, err = models.GetIssueStats(&models.IssueStatsOptions{
  138. RepoID: repo.ID,
  139. Labels: selectLabels,
  140. MilestoneID: milestoneID,
  141. AssigneeID: assigneeID,
  142. MentionedID: mentionedID,
  143. PosterID: posterID,
  144. IsPull: isPullList,
  145. IssueIDs: issueIDs,
  146. })
  147. if err != nil {
  148. ctx.Handle(500, "GetIssueStats", err)
  149. return
  150. }
  151. }
  152. page := ctx.QueryInt("page")
  153. if page <= 1 {
  154. page = 1
  155. }
  156. var total int
  157. if !isShowClosed {
  158. total = int(issueStats.OpenCount)
  159. } else {
  160. total = int(issueStats.ClosedCount)
  161. }
  162. pager := paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  163. ctx.Data["Page"] = pager
  164. var issues []*models.Issue
  165. if forceEmpty {
  166. issues = []*models.Issue{}
  167. } else {
  168. issues, err = models.Issues(&models.IssuesOptions{
  169. RepoIDs: []int64{repo.ID},
  170. AssigneeID: assigneeID,
  171. PosterID: posterID,
  172. MentionedID: mentionedID,
  173. MilestoneID: milestoneID,
  174. Page: pager.Current(),
  175. PageSize: setting.UI.IssuePagingNum,
  176. IsClosed: util.OptionalBoolOf(isShowClosed),
  177. IsPull: util.OptionalBoolOf(isPullList),
  178. Labels: selectLabels,
  179. SortType: sortType,
  180. IssueIDs: issueIDs,
  181. })
  182. if err != nil {
  183. ctx.Handle(500, "Issues", err)
  184. return
  185. }
  186. }
  187. // Get posters.
  188. for i := range issues {
  189. // Check read status
  190. if !ctx.IsSigned {
  191. issues[i].IsRead = true
  192. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  193. ctx.Handle(500, "GetIsRead", err)
  194. return
  195. }
  196. }
  197. ctx.Data["Issues"] = issues
  198. // Get milestones.
  199. ctx.Data["Milestones"], err = models.GetMilestonesByRepoID(repo.ID)
  200. if err != nil {
  201. ctx.Handle(500, "GetAllRepoMilestones", err)
  202. return
  203. }
  204. // Get assignees.
  205. ctx.Data["Assignees"], err = repo.GetAssignees()
  206. if err != nil {
  207. ctx.Handle(500, "GetAssignees", err)
  208. return
  209. }
  210. if ctx.QueryInt64("assignee") == 0 {
  211. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  212. }
  213. ctx.Data["IssueStats"] = issueStats
  214. ctx.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64()
  215. ctx.Data["ViewType"] = viewType
  216. ctx.Data["SortType"] = sortType
  217. ctx.Data["MilestoneID"] = milestoneID
  218. ctx.Data["AssigneeID"] = assigneeID
  219. ctx.Data["IsShowClosed"] = isShowClosed
  220. ctx.Data["Keyword"] = keyword
  221. if isShowClosed {
  222. ctx.Data["State"] = "closed"
  223. } else {
  224. ctx.Data["State"] = "open"
  225. }
  226. ctx.HTML(200, tplIssues)
  227. }
  228. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  229. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  230. var err error
  231. ctx.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false, "")
  232. if err != nil {
  233. ctx.Handle(500, "GetMilestones", err)
  234. return
  235. }
  236. ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true, "")
  237. if err != nil {
  238. ctx.Handle(500, "GetMilestones", err)
  239. return
  240. }
  241. ctx.Data["Assignees"], err = repo.GetAssignees()
  242. if err != nil {
  243. ctx.Handle(500, "GetAssignees", err)
  244. return
  245. }
  246. }
  247. // RetrieveRepoMetas find all the meta information of a repository
  248. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository) []*models.Label {
  249. if !ctx.Repo.IsWriter() {
  250. return nil
  251. }
  252. labels, err := models.GetLabelsByRepoID(repo.ID, "")
  253. if err != nil {
  254. ctx.Handle(500, "GetLabelsByRepoID", err)
  255. return nil
  256. }
  257. ctx.Data["Labels"] = labels
  258. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  259. if ctx.Written() {
  260. return nil
  261. }
  262. brs, err := ctx.Repo.GitRepo.GetBranches()
  263. if err != nil {
  264. ctx.Handle(500, "GetBranches", err)
  265. return nil
  266. }
  267. ctx.Data["Branches"] = brs
  268. return labels
  269. }
  270. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  271. var r io.Reader
  272. var bytes []byte
  273. if ctx.Repo.Commit == nil {
  274. var err error
  275. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  276. if err != nil {
  277. return "", false
  278. }
  279. }
  280. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  281. if err != nil {
  282. return "", false
  283. }
  284. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  285. return "", false
  286. }
  287. r, err = entry.Blob().Data()
  288. if err != nil {
  289. return "", false
  290. }
  291. bytes, err = ioutil.ReadAll(r)
  292. if err != nil {
  293. return "", false
  294. }
  295. return string(bytes), true
  296. }
  297. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleFiles []string) {
  298. for _, filename := range possibleFiles {
  299. content, found := getFileContentFromDefaultBranch(ctx, filename)
  300. if found {
  301. ctx.Data[ctxDataKey] = content
  302. return
  303. }
  304. }
  305. }
  306. // NewIssue render createing issue page
  307. func NewIssue(ctx *context.Context) {
  308. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  309. ctx.Data["PageIsIssueList"] = true
  310. ctx.Data["RequireHighlightJS"] = true
  311. ctx.Data["RequireSimpleMDE"] = true
  312. ctx.Data["RequireTribute"] = true
  313. setTemplateIfExists(ctx, issueTemplateKey, IssueTemplateCandidates)
  314. renderAttachmentSettings(ctx)
  315. RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  316. if ctx.Written() {
  317. return
  318. }
  319. ctx.HTML(200, tplIssueNew)
  320. }
  321. // ValidateRepoMetas check and returns repository's meta informations
  322. func ValidateRepoMetas(ctx *context.Context, form auth.CreateIssueForm) ([]int64, int64, int64) {
  323. var (
  324. repo = ctx.Repo.Repository
  325. err error
  326. )
  327. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository)
  328. if ctx.Written() {
  329. return nil, 0, 0
  330. }
  331. if !ctx.Repo.IsWriter() {
  332. return nil, 0, 0
  333. }
  334. var labelIDs []int64
  335. hasSelected := false
  336. // Check labels.
  337. if len(form.LabelIDs) > 0 {
  338. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  339. if err != nil {
  340. return nil, 0, 0
  341. }
  342. labelIDMark := base.Int64sToMap(labelIDs)
  343. for i := range labels {
  344. if labelIDMark[labels[i].ID] {
  345. labels[i].IsChecked = true
  346. hasSelected = true
  347. }
  348. }
  349. }
  350. ctx.Data["Labels"] = labels
  351. ctx.Data["HasSelectedLabel"] = hasSelected
  352. ctx.Data["label_ids"] = form.LabelIDs
  353. // Check milestone.
  354. milestoneID := form.MilestoneID
  355. if milestoneID > 0 {
  356. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  357. if err != nil {
  358. ctx.Handle(500, "GetMilestoneByID", err)
  359. return nil, 0, 0
  360. }
  361. ctx.Data["milestone_id"] = milestoneID
  362. }
  363. // Check assignee.
  364. assigneeID := form.AssigneeID
  365. if assigneeID > 0 {
  366. ctx.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID)
  367. if err != nil {
  368. ctx.Handle(500, "GetAssigneeByID", err)
  369. return nil, 0, 0
  370. }
  371. ctx.Data["assignee_id"] = assigneeID
  372. }
  373. return labelIDs, milestoneID, assigneeID
  374. }
  375. // NewIssuePost response for creating new issue
  376. func NewIssuePost(ctx *context.Context, form auth.CreateIssueForm) {
  377. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  378. ctx.Data["PageIsIssueList"] = true
  379. ctx.Data["RequireHighlightJS"] = true
  380. ctx.Data["RequireSimpleMDE"] = true
  381. ctx.Data["ReadOnly"] = false
  382. renderAttachmentSettings(ctx)
  383. var (
  384. repo = ctx.Repo.Repository
  385. attachments []string
  386. )
  387. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(ctx, form)
  388. if ctx.Written() {
  389. return
  390. }
  391. if setting.AttachmentEnabled {
  392. attachments = form.Files
  393. }
  394. if ctx.HasError() {
  395. ctx.HTML(200, tplIssueNew)
  396. return
  397. }
  398. issue := &models.Issue{
  399. RepoID: repo.ID,
  400. Title: form.Title,
  401. PosterID: ctx.User.ID,
  402. Poster: ctx.User,
  403. MilestoneID: milestoneID,
  404. AssigneeID: assigneeID,
  405. Content: form.Content,
  406. Ref: form.Ref,
  407. }
  408. if err := models.NewIssue(repo, issue, labelIDs, attachments); err != nil {
  409. ctx.Handle(500, "NewIssue", err)
  410. return
  411. }
  412. notification.Service.NotifyIssue(issue, ctx.User.ID)
  413. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  414. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  415. }
  416. // commentTag returns the CommentTag for a comment in/with the given repo, poster and issue
  417. func commentTag(repo *models.Repository, poster *models.User, issue *models.Issue) (models.CommentTag, error) {
  418. if repo.IsOwnedBy(poster.ID) {
  419. return models.CommentTagOwner, nil
  420. } else if repo.Owner.IsOrganization() {
  421. isOwner, err := repo.Owner.IsOwnedBy(poster.ID)
  422. if err != nil {
  423. return models.CommentTagNone, err
  424. } else if isOwner {
  425. return models.CommentTagOwner, nil
  426. }
  427. }
  428. if poster.IsWriterOfRepo(repo) {
  429. return models.CommentTagWriter, nil
  430. } else if poster.ID == issue.PosterID {
  431. return models.CommentTagPoster, nil
  432. }
  433. return models.CommentTagNone, nil
  434. }
  435. // ViewIssue render issue view page
  436. func ViewIssue(ctx *context.Context) {
  437. ctx.Data["RequireHighlightJS"] = true
  438. ctx.Data["RequireDropzone"] = true
  439. ctx.Data["RequireTribute"] = true
  440. renderAttachmentSettings(ctx)
  441. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  442. if err != nil {
  443. if models.IsErrIssueNotExist(err) {
  444. ctx.Handle(404, "GetIssueByIndex", err)
  445. } else {
  446. ctx.Handle(500, "GetIssueByIndex", err)
  447. }
  448. return
  449. }
  450. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  451. var iw *models.IssueWatch
  452. var exists bool
  453. if ctx.User != nil {
  454. iw, exists, err = models.GetIssueWatch(ctx.User.ID, issue.ID)
  455. if err != nil {
  456. ctx.Handle(500, "GetIssueWatch", err)
  457. return
  458. }
  459. if !exists {
  460. iw = &models.IssueWatch{
  461. UserID: ctx.User.ID,
  462. IssueID: issue.ID,
  463. IsWatching: models.IsWatching(ctx.User.ID, ctx.Repo.Repository.ID),
  464. }
  465. }
  466. }
  467. ctx.Data["IssueWatch"] = iw
  468. // Make sure type and URL matches.
  469. if ctx.Params(":type") == "issues" && issue.IsPull {
  470. ctx.Redirect(ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  471. return
  472. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  473. ctx.Redirect(ctx.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  474. return
  475. }
  476. if issue.IsPull {
  477. MustAllowPulls(ctx)
  478. if ctx.Written() {
  479. return
  480. }
  481. ctx.Data["PageIsPullList"] = true
  482. ctx.Data["PageIsPullConversation"] = true
  483. } else {
  484. MustEnableIssues(ctx)
  485. if ctx.Written() {
  486. return
  487. }
  488. ctx.Data["PageIsIssueList"] = true
  489. }
  490. issue.RenderedContent = string(markdown.Render([]byte(issue.Content), ctx.Repo.RepoLink,
  491. ctx.Repo.Repository.ComposeMetas()))
  492. repo := ctx.Repo.Repository
  493. // Get more information if it's a pull request.
  494. if issue.IsPull {
  495. if issue.PullRequest.HasMerged {
  496. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  497. PrepareMergedViewPullInfo(ctx, issue)
  498. } else {
  499. PrepareViewPullInfo(ctx, issue)
  500. }
  501. if ctx.Written() {
  502. return
  503. }
  504. }
  505. // Metas.
  506. // Check labels.
  507. labelIDMark := make(map[int64]bool)
  508. for i := range issue.Labels {
  509. labelIDMark[issue.Labels[i].ID] = true
  510. }
  511. labels, err := models.GetLabelsByRepoID(repo.ID, "")
  512. if err != nil {
  513. ctx.Handle(500, "GetLabelsByRepoID", err)
  514. return
  515. }
  516. hasSelected := false
  517. for i := range labels {
  518. if labelIDMark[labels[i].ID] {
  519. labels[i].IsChecked = true
  520. hasSelected = true
  521. }
  522. }
  523. ctx.Data["HasSelectedLabel"] = hasSelected
  524. ctx.Data["Labels"] = labels
  525. // Check milestone and assignee.
  526. if ctx.Repo.IsWriter() {
  527. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  528. if ctx.Written() {
  529. return
  530. }
  531. }
  532. if ctx.IsSigned {
  533. // Update issue-user.
  534. if err = issue.ReadBy(ctx.User.ID); err != nil {
  535. ctx.Handle(500, "ReadBy", err)
  536. return
  537. }
  538. }
  539. var (
  540. tag models.CommentTag
  541. ok bool
  542. marked = make(map[int64]models.CommentTag)
  543. comment *models.Comment
  544. participants = make([]*models.User, 1, 10)
  545. )
  546. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  547. if ctx.IsSigned {
  548. // Deal with the stopwatch
  549. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  550. if !ctx.Data["IsStopwatchRunning"].(bool) {
  551. var exists bool
  552. var sw *models.Stopwatch
  553. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  554. ctx.Handle(500, "HasUserStopwatch", err)
  555. return
  556. }
  557. ctx.Data["HasUserStopwatch"] = exists
  558. if exists {
  559. // Add warning if the user has already a stopwatch
  560. var otherIssue *models.Issue
  561. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  562. ctx.Handle(500, "GetIssueByID", err)
  563. return
  564. }
  565. // Add link to the issue of the already running stopwatch
  566. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  567. }
  568. }
  569. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  570. } else {
  571. ctx.Data["CanUseTimetracker"] = false
  572. }
  573. if ctx.Data["WorkingUsers"], err = models.TotalTimes(models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  574. ctx.Handle(500, "TotalTimes", err)
  575. return
  576. }
  577. }
  578. // Render comments and and fetch participants.
  579. participants[0] = issue.Poster
  580. for _, comment = range issue.Comments {
  581. if comment.Type == models.CommentTypeComment {
  582. comment.RenderedContent = string(markdown.Render([]byte(comment.Content), ctx.Repo.RepoLink,
  583. ctx.Repo.Repository.ComposeMetas()))
  584. // Check tag.
  585. tag, ok = marked[comment.PosterID]
  586. if ok {
  587. comment.ShowTag = tag
  588. continue
  589. }
  590. comment.ShowTag, err = commentTag(repo, comment.Poster, issue)
  591. if err != nil {
  592. ctx.Handle(500, "commentTag", err)
  593. return
  594. }
  595. marked[comment.PosterID] = comment.ShowTag
  596. isAdded := false
  597. for j := range participants {
  598. if comment.Poster == participants[j] {
  599. isAdded = true
  600. break
  601. }
  602. }
  603. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  604. participants = append(participants, comment.Poster)
  605. }
  606. } else if comment.Type == models.CommentTypeLabel {
  607. if err = comment.LoadLabel(); err != nil {
  608. ctx.Handle(500, "LoadLabel", err)
  609. return
  610. }
  611. } else if comment.Type == models.CommentTypeMilestone {
  612. if err = comment.LoadMilestone(); err != nil {
  613. ctx.Handle(500, "LoadMilestone", err)
  614. return
  615. }
  616. ghostMilestone := &models.Milestone{
  617. ID: -1,
  618. Name: ctx.Tr("repo.issues.deleted_milestone"),
  619. }
  620. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  621. comment.OldMilestone = ghostMilestone
  622. }
  623. if comment.MilestoneID > 0 && comment.Milestone == nil {
  624. comment.Milestone = ghostMilestone
  625. }
  626. } else if comment.Type == models.CommentTypeAssignees {
  627. if err = comment.LoadAssignees(); err != nil {
  628. ctx.Handle(500, "LoadAssignees", err)
  629. return
  630. }
  631. }
  632. }
  633. if issue.IsPull {
  634. pull := issue.PullRequest
  635. canDelete := false
  636. if ctx.IsSigned {
  637. if err := pull.GetHeadRepo(); err != nil {
  638. log.Error(4, "GetHeadRepo: %v", err)
  639. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch && ctx.User.IsWriterOfRepo(pull.HeadRepo) {
  640. // Check if branch is not protected
  641. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch, ctx.User); err != nil {
  642. log.Error(4, "IsProtectedBranch: %v", err)
  643. } else if !protected {
  644. canDelete = true
  645. ctx.Data["DeleteBranchLink"] = ctx.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index) + "/cleanup"
  646. }
  647. }
  648. }
  649. prUnit, err := repo.GetUnit(models.UnitTypePullRequests)
  650. if err != nil {
  651. ctx.Handle(500, "GetUnit", err)
  652. return
  653. }
  654. prConfig := prUnit.PullRequestsConfig()
  655. // Check correct values and select default
  656. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  657. !prConfig.IsMergeStyleAllowed(ms) {
  658. if prConfig.AllowMerge {
  659. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  660. } else if prConfig.AllowRebase {
  661. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  662. } else if prConfig.AllowSquash {
  663. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  664. } else {
  665. ctx.Data["MergeStyle"] = ""
  666. }
  667. }
  668. ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
  669. }
  670. ctx.Data["Participants"] = participants
  671. ctx.Data["NumParticipants"] = len(participants)
  672. ctx.Data["Issue"] = issue
  673. ctx.Data["ReadOnly"] = true
  674. ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))
  675. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  676. ctx.HTML(200, tplIssueView)
  677. }
  678. // GetActionIssue will return the issue which is used in the context.
  679. func GetActionIssue(ctx *context.Context) *models.Issue {
  680. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  681. if err != nil {
  682. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  683. return nil
  684. }
  685. checkIssueRights(ctx, issue)
  686. if ctx.Written() {
  687. return nil
  688. }
  689. if err = issue.LoadAttributes(); err != nil {
  690. ctx.Handle(500, "LoadAttributes", nil)
  691. return nil
  692. }
  693. return issue
  694. }
  695. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  696. if issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) ||
  697. !issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
  698. ctx.Handle(404, "IssueOrPullRequestUnitNotAllowed", nil)
  699. }
  700. }
  701. func getActionIssues(ctx *context.Context) []*models.Issue {
  702. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  703. if len(commaSeparatedIssueIDs) == 0 {
  704. return nil
  705. }
  706. issueIDs := make([]int64, 0, 10)
  707. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  708. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  709. if err != nil {
  710. ctx.Handle(500, "ParseInt", err)
  711. return nil
  712. }
  713. issueIDs = append(issueIDs, issueID)
  714. }
  715. issues, err := models.GetIssuesByIDs(issueIDs)
  716. if err != nil {
  717. ctx.Handle(500, "GetIssuesByIDs", err)
  718. return nil
  719. }
  720. // Check access rights for all issues
  721. issueUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues)
  722. prUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests)
  723. for _, issue := range issues {
  724. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  725. ctx.Handle(404, "IssueOrPullRequestUnitNotAllowed", nil)
  726. return nil
  727. }
  728. if err = issue.LoadAttributes(); err != nil {
  729. ctx.Handle(500, "LoadAttributes", err)
  730. return nil
  731. }
  732. }
  733. return issues
  734. }
  735. // UpdateIssueTitle change issue's title
  736. func UpdateIssueTitle(ctx *context.Context) {
  737. issue := GetActionIssue(ctx)
  738. if ctx.Written() {
  739. return
  740. }
  741. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) {
  742. ctx.Error(403)
  743. return
  744. }
  745. title := ctx.QueryTrim("title")
  746. if len(title) == 0 {
  747. ctx.Error(204)
  748. return
  749. }
  750. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  751. ctx.Handle(500, "ChangeTitle", err)
  752. return
  753. }
  754. ctx.JSON(200, map[string]interface{}{
  755. "title": issue.Title,
  756. })
  757. }
  758. // UpdateIssueContent change issue's content
  759. func UpdateIssueContent(ctx *context.Context) {
  760. issue := GetActionIssue(ctx)
  761. if ctx.Written() {
  762. return
  763. }
  764. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) {
  765. ctx.Error(403)
  766. return
  767. }
  768. content := ctx.Query("content")
  769. if err := issue.ChangeContent(ctx.User, content); err != nil {
  770. ctx.Handle(500, "ChangeContent", err)
  771. return
  772. }
  773. ctx.JSON(200, map[string]interface{}{
  774. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  775. })
  776. }
  777. // UpdateIssueMilestone change issue's milestone
  778. func UpdateIssueMilestone(ctx *context.Context) {
  779. issues := getActionIssues(ctx)
  780. if ctx.Written() {
  781. return
  782. }
  783. milestoneID := ctx.QueryInt64("id")
  784. for _, issue := range issues {
  785. oldMilestoneID := issue.MilestoneID
  786. if oldMilestoneID == milestoneID {
  787. continue
  788. }
  789. issue.MilestoneID = milestoneID
  790. if err := models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  791. ctx.Handle(500, "ChangeMilestoneAssign", err)
  792. return
  793. }
  794. }
  795. ctx.JSON(200, map[string]interface{}{
  796. "ok": true,
  797. })
  798. }
  799. // UpdateIssueAssignee change issue's assignee
  800. func UpdateIssueAssignee(ctx *context.Context) {
  801. issues := getActionIssues(ctx)
  802. if ctx.Written() {
  803. return
  804. }
  805. assigneeID := ctx.QueryInt64("id")
  806. for _, issue := range issues {
  807. if issue.AssigneeID == assigneeID {
  808. continue
  809. }
  810. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  811. ctx.Handle(500, "ChangeAssignee", err)
  812. return
  813. }
  814. }
  815. ctx.JSON(200, map[string]interface{}{
  816. "ok": true,
  817. })
  818. }
  819. // UpdateIssueStatus change issue's status
  820. func UpdateIssueStatus(ctx *context.Context) {
  821. issues := getActionIssues(ctx)
  822. if ctx.Written() {
  823. return
  824. }
  825. var isClosed bool
  826. switch action := ctx.Query("action"); action {
  827. case "open":
  828. isClosed = false
  829. case "close":
  830. isClosed = true
  831. default:
  832. log.Warn("Unrecognized action: %s", action)
  833. }
  834. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  835. ctx.Handle(500, "LoadRepositories", err)
  836. return
  837. }
  838. for _, issue := range issues {
  839. if err := issue.ChangeStatus(ctx.User, issue.Repo, isClosed); err != nil {
  840. ctx.Handle(500, "ChangeStatus", err)
  841. return
  842. }
  843. }
  844. ctx.JSON(200, map[string]interface{}{
  845. "ok": true,
  846. })
  847. }
  848. // NewComment create a comment for issue
  849. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  850. issue := GetActionIssue(ctx)
  851. if ctx.Written() {
  852. return
  853. }
  854. var attachments []string
  855. if setting.AttachmentEnabled {
  856. attachments = form.Files
  857. }
  858. if ctx.HasError() {
  859. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  860. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  861. return
  862. }
  863. var comment *models.Comment
  864. defer func() {
  865. // Check if issue admin/poster changes the status of issue.
  866. if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  867. (form.Status == "reopen" || form.Status == "close") &&
  868. !(issue.IsPull && issue.PullRequest.HasMerged) {
  869. // Duplication and conflict check should apply to reopen pull request.
  870. var pr *models.PullRequest
  871. if form.Status == "reopen" && issue.IsPull {
  872. pull := issue.PullRequest
  873. pr, err := models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  874. if err != nil {
  875. if !models.IsErrPullRequestNotExist(err) {
  876. ctx.Handle(500, "GetUnmergedPullRequest", err)
  877. return
  878. }
  879. }
  880. // Regenerate patch and test conflict.
  881. if pr == nil {
  882. if err = issue.PullRequest.UpdatePatch(); err != nil {
  883. ctx.Handle(500, "UpdatePatch", err)
  884. return
  885. }
  886. issue.PullRequest.AddToTaskQueue()
  887. }
  888. }
  889. if pr != nil {
  890. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  891. } else {
  892. if err := issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil {
  893. log.Error(4, "ChangeStatus: %v", err)
  894. } else {
  895. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  896. notification.Service.NotifyIssue(issue, ctx.User.ID)
  897. }
  898. }
  899. }
  900. // Redirect to comment hashtag if there is any actual content.
  901. typeName := "issues"
  902. if issue.IsPull {
  903. typeName = "pulls"
  904. }
  905. if comment != nil {
  906. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  907. } else {
  908. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  909. }
  910. }()
  911. // Fix #321: Allow empty comments, as long as we have attachments.
  912. if len(form.Content) == 0 && len(attachments) == 0 {
  913. return
  914. }
  915. comment, err := models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  916. if err != nil {
  917. ctx.Handle(500, "CreateIssueComment", err)
  918. return
  919. }
  920. notification.Service.NotifyIssue(issue, ctx.User.ID)
  921. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  922. }
  923. // UpdateCommentContent change comment of issue's content
  924. func UpdateCommentContent(ctx *context.Context) {
  925. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  926. if err != nil {
  927. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  928. return
  929. }
  930. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  931. ctx.Error(403)
  932. return
  933. } else if comment.Type != models.CommentTypeComment {
  934. ctx.Error(204)
  935. return
  936. }
  937. comment.Content = ctx.Query("content")
  938. if len(comment.Content) == 0 {
  939. ctx.JSON(200, map[string]interface{}{
  940. "content": "",
  941. })
  942. return
  943. }
  944. if err = models.UpdateComment(comment); err != nil {
  945. ctx.Handle(500, "UpdateComment", err)
  946. return
  947. }
  948. ctx.JSON(200, map[string]interface{}{
  949. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  950. })
  951. }
  952. // DeleteComment delete comment of issue
  953. func DeleteComment(ctx *context.Context) {
  954. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  955. if err != nil {
  956. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  957. return
  958. }
  959. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  960. ctx.Error(403)
  961. return
  962. } else if comment.Type != models.CommentTypeComment {
  963. ctx.Error(204)
  964. return
  965. }
  966. if err = models.DeleteComment(comment); err != nil {
  967. ctx.Handle(500, "DeleteCommentByID", err)
  968. return
  969. }
  970. ctx.Status(200)
  971. }
  972. // Milestones render milestones page
  973. func Milestones(ctx *context.Context) {
  974. ctx.Data["Title"] = ctx.Tr("repo.milestones")
  975. ctx.Data["PageIsIssueList"] = true
  976. ctx.Data["PageIsMilestones"] = true
  977. isShowClosed := ctx.Query("state") == "closed"
  978. openCount, closedCount, err := models.MilestoneStats(ctx.Repo.Repository.ID)
  979. if err != nil {
  980. ctx.Handle(500, "MilestoneStats", err)
  981. return
  982. }
  983. ctx.Data["OpenCount"] = openCount
  984. ctx.Data["ClosedCount"] = closedCount
  985. sortType := ctx.Query("sort")
  986. page := ctx.QueryInt("page")
  987. if page <= 1 {
  988. page = 1
  989. }
  990. var total int
  991. if !isShowClosed {
  992. total = int(openCount)
  993. } else {
  994. total = int(closedCount)
  995. }
  996. ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  997. miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed, sortType)
  998. if err != nil {
  999. ctx.Handle(500, "GetMilestones", err)
  1000. return
  1001. }
  1002. for _, m := range miles {
  1003. m.RenderedContent = string(markdown.Render([]byte(m.Content), ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()))
  1004. }
  1005. ctx.Data["Milestones"] = miles
  1006. if isShowClosed {
  1007. ctx.Data["State"] = "closed"
  1008. } else {
  1009. ctx.Data["State"] = "open"
  1010. }
  1011. ctx.Data["SortType"] = sortType
  1012. ctx.Data["IsShowClosed"] = isShowClosed
  1013. ctx.HTML(200, tplMilestone)
  1014. }
  1015. // NewMilestone render creating milestone page
  1016. func NewMilestone(ctx *context.Context) {
  1017. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1018. ctx.Data["PageIsIssueList"] = true
  1019. ctx.Data["PageIsMilestones"] = true
  1020. ctx.Data["RequireDatetimepicker"] = true
  1021. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1022. ctx.HTML(200, tplMilestoneNew)
  1023. }
  1024. // NewMilestonePost response for creating milestone
  1025. func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1026. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1027. ctx.Data["PageIsIssueList"] = true
  1028. ctx.Data["PageIsMilestones"] = true
  1029. ctx.Data["RequireDatetimepicker"] = true
  1030. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1031. if ctx.HasError() {
  1032. ctx.HTML(200, tplMilestoneNew)
  1033. return
  1034. }
  1035. if len(form.Deadline) == 0 {
  1036. form.Deadline = "9999-12-31"
  1037. }
  1038. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1039. if err != nil {
  1040. ctx.Data["Err_Deadline"] = true
  1041. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1042. return
  1043. }
  1044. if err = models.NewMilestone(&models.Milestone{
  1045. RepoID: ctx.Repo.Repository.ID,
  1046. Name: form.Title,
  1047. Content: form.Content,
  1048. DeadlineUnix: util.TimeStamp(deadline.Unix()),
  1049. }); err != nil {
  1050. ctx.Handle(500, "NewMilestone", err)
  1051. return
  1052. }
  1053. ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
  1054. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1055. }
  1056. // EditMilestone render edting milestone page
  1057. func EditMilestone(ctx *context.Context) {
  1058. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1059. ctx.Data["PageIsMilestones"] = true
  1060. ctx.Data["PageIsEditMilestone"] = true
  1061. ctx.Data["RequireDatetimepicker"] = true
  1062. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1063. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1064. if err != nil {
  1065. if models.IsErrMilestoneNotExist(err) {
  1066. ctx.Handle(404, "", nil)
  1067. } else {
  1068. ctx.Handle(500, "GetMilestoneByRepoID", err)
  1069. }
  1070. return
  1071. }
  1072. ctx.Data["title"] = m.Name
  1073. ctx.Data["content"] = m.Content
  1074. if len(m.DeadlineString) > 0 {
  1075. ctx.Data["deadline"] = m.DeadlineString
  1076. }
  1077. ctx.HTML(200, tplMilestoneNew)
  1078. }
  1079. // EditMilestonePost response for edting milestone
  1080. func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1081. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1082. ctx.Data["PageIsMilestones"] = true
  1083. ctx.Data["PageIsEditMilestone"] = true
  1084. ctx.Data["RequireDatetimepicker"] = true
  1085. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1086. if ctx.HasError() {
  1087. ctx.HTML(200, tplMilestoneNew)
  1088. return
  1089. }
  1090. if len(form.Deadline) == 0 {
  1091. form.Deadline = "9999-12-31"
  1092. }
  1093. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1094. if err != nil {
  1095. ctx.Data["Err_Deadline"] = true
  1096. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1097. return
  1098. }
  1099. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1100. if err != nil {
  1101. if models.IsErrMilestoneNotExist(err) {
  1102. ctx.Handle(404, "", nil)
  1103. } else {
  1104. ctx.Handle(500, "GetMilestoneByRepoID", err)
  1105. }
  1106. return
  1107. }
  1108. m.Name = form.Title
  1109. m.Content = form.Content
  1110. m.DeadlineUnix = util.TimeStamp(deadline.Unix())
  1111. if err = models.UpdateMilestone(m); err != nil {
  1112. ctx.Handle(500, "UpdateMilestone", err)
  1113. return
  1114. }
  1115. ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
  1116. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1117. }
  1118. // ChangeMilestonStatus response for change a milestone's status
  1119. func ChangeMilestonStatus(ctx *context.Context) {
  1120. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1121. if err != nil {
  1122. if models.IsErrMilestoneNotExist(err) {
  1123. ctx.Handle(404, "", err)
  1124. } else {
  1125. ctx.Handle(500, "GetMilestoneByRepoID", err)
  1126. }
  1127. return
  1128. }
  1129. switch ctx.Params(":action") {
  1130. case "open":
  1131. if m.IsClosed {
  1132. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1133. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1134. return
  1135. }
  1136. }
  1137. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
  1138. case "close":
  1139. if !m.IsClosed {
  1140. m.ClosedDateUnix = util.TimeStampNow()
  1141. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1142. ctx.Handle(500, "ChangeMilestoneStatus", err)
  1143. return
  1144. }
  1145. }
  1146. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
  1147. default:
  1148. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1149. }
  1150. }
  1151. // DeleteMilestone delete a milestone
  1152. func DeleteMilestone(ctx *context.Context) {
  1153. if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  1154. ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1155. } else {
  1156. ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
  1157. }
  1158. ctx.JSON(200, map[string]interface{}{
  1159. "redirect": ctx.Repo.RepoLink + "/milestones",
  1160. })
  1161. }
  1162. // ChangeIssueReaction create a reaction for issue
  1163. func ChangeIssueReaction(ctx *context.Context, form auth.ReactionForm) {
  1164. issue := GetActionIssue(ctx)
  1165. if ctx.Written() {
  1166. return
  1167. }
  1168. if ctx.HasError() {
  1169. ctx.Handle(500, "ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1170. return
  1171. }
  1172. switch ctx.Params(":action") {
  1173. case "react":
  1174. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1175. if err != nil {
  1176. log.Info("CreateIssueReaction: %s", err)
  1177. break
  1178. }
  1179. // Reload new reactions
  1180. issue.Reactions = nil
  1181. if err = issue.LoadAttributes(); err != nil {
  1182. log.Info("issue.LoadAttributes: %s", err)
  1183. break
  1184. }
  1185. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1186. case "unreact":
  1187. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1188. ctx.Handle(500, "DeleteIssueReaction", err)
  1189. return
  1190. }
  1191. // Reload new reactions
  1192. issue.Reactions = nil
  1193. if err := issue.LoadAttributes(); err != nil {
  1194. log.Info("issue.LoadAttributes: %s", err)
  1195. break
  1196. }
  1197. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1198. default:
  1199. ctx.Handle(404, fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1200. return
  1201. }
  1202. if len(issue.Reactions) == 0 {
  1203. ctx.JSON(200, map[string]interface{}{
  1204. "empty": true,
  1205. "html": "",
  1206. })
  1207. return
  1208. }
  1209. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1210. "ctx": ctx.Data,
  1211. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1212. "Reactions": issue.Reactions.GroupByType(),
  1213. })
  1214. if err != nil {
  1215. ctx.Handle(500, "ChangeIssueReaction.HTMLString", err)
  1216. return
  1217. }
  1218. ctx.JSON(200, map[string]interface{}{
  1219. "html": html,
  1220. })
  1221. }
  1222. // ChangeCommentReaction create a reaction for comment
  1223. func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
  1224. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1225. if err != nil {
  1226. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1227. return
  1228. }
  1229. issue, err := models.GetIssueByID(comment.IssueID)
  1230. checkIssueRights(ctx, issue)
  1231. if ctx.Written() {
  1232. return
  1233. }
  1234. if ctx.HasError() {
  1235. ctx.Handle(500, "ChangeCommentReaction", errors.New(ctx.GetErrMsg()))
  1236. return
  1237. }
  1238. switch ctx.Params(":action") {
  1239. case "react":
  1240. reaction, err := models.CreateCommentReaction(ctx.User, issue, comment, form.Content)
  1241. if err != nil {
  1242. log.Info("CreateCommentReaction: %s", err)
  1243. break
  1244. }
  1245. // Reload new reactions
  1246. comment.Reactions = nil
  1247. if err = comment.LoadReactions(); err != nil {
  1248. log.Info("comment.LoadReactions: %s", err)
  1249. break
  1250. }
  1251. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID, reaction.ID)
  1252. case "unreact":
  1253. if err := models.DeleteCommentReaction(ctx.User, issue, comment, form.Content); err != nil {
  1254. ctx.Handle(500, "DeleteCommentReaction", err)
  1255. return
  1256. }
  1257. // Reload new reactions
  1258. comment.Reactions = nil
  1259. if err = comment.LoadReactions(); err != nil {
  1260. log.Info("comment.LoadReactions: %s", err)
  1261. break
  1262. }
  1263. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1264. default:
  1265. ctx.Handle(404, fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1266. return
  1267. }
  1268. if len(comment.Reactions) == 0 {
  1269. ctx.JSON(200, map[string]interface{}{
  1270. "empty": true,
  1271. "html": "",
  1272. })
  1273. return
  1274. }
  1275. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1276. "ctx": ctx.Data,
  1277. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  1278. "Reactions": comment.Reactions.GroupByType(),
  1279. })
  1280. if err != nil {
  1281. ctx.Handle(500, "ChangeCommentReaction.HTMLString", err)
  1282. return
  1283. }
  1284. ctx.JSON(200, map[string]interface{}{
  1285. "html": html,
  1286. })
  1287. }