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.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  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.NotFound("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.NotFound("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", "your_repositories", "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.ServerError("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.ServerError("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.ServerError("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.ServerError("GetAllRepoMilestones", err)
  202. return
  203. }
  204. // Get assignees.
  205. ctx.Data["Assignees"], err = repo.GetAssignees()
  206. if err != nil {
  207. ctx.ServerError("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.ServerError("GetMilestones", err)
  234. return
  235. }
  236. ctx.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true, "")
  237. if err != nil {
  238. ctx.ServerError("GetMilestones", err)
  239. return
  240. }
  241. ctx.Data["Assignees"], err = repo.GetAssignees()
  242. if err != nil {
  243. ctx.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.NotFound("GetIssueByIndex", err)
  445. } else {
  446. ctx.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("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.ServerError("LoadLabel", err)
  609. return
  610. }
  611. } else if comment.Type == models.CommentTypeMilestone {
  612. if err = comment.LoadMilestone(); err != nil {
  613. ctx.ServerError("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.ServerError("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.ServerError("GetUnit", err)
  652. return
  653. }
  654. prConfig := prUnit.PullRequestsConfig()
  655. ctx.Data["AllowMerge"] = ctx.Data["IsRepositoryWriter"]
  656. if err := pull.CheckUserAllowedToMerge(ctx.User); err != nil {
  657. if !models.IsErrNotAllowedToMerge(err) {
  658. ctx.ServerError("CheckUserAllowedToMerge", err)
  659. return
  660. }
  661. ctx.Data["AllowMerge"] = false
  662. }
  663. // Check correct values and select default
  664. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  665. !prConfig.IsMergeStyleAllowed(ms) {
  666. if prConfig.AllowMerge {
  667. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  668. } else if prConfig.AllowRebase {
  669. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  670. } else if prConfig.AllowSquash {
  671. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  672. } else {
  673. ctx.Data["MergeStyle"] = ""
  674. }
  675. }
  676. ctx.Data["IsPullBranchDeletable"] = canDelete && pull.HeadRepo != nil && git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch)
  677. }
  678. ctx.Data["Participants"] = participants
  679. ctx.Data["NumParticipants"] = len(participants)
  680. ctx.Data["Issue"] = issue
  681. ctx.Data["ReadOnly"] = true
  682. ctx.Data["IsIssueOwner"] = ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))
  683. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + ctx.Data["Link"].(string)
  684. ctx.HTML(200, tplIssueView)
  685. }
  686. // GetActionIssue will return the issue which is used in the context.
  687. func GetActionIssue(ctx *context.Context) *models.Issue {
  688. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  689. if err != nil {
  690. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  691. return nil
  692. }
  693. checkIssueRights(ctx, issue)
  694. if ctx.Written() {
  695. return nil
  696. }
  697. if err = issue.LoadAttributes(); err != nil {
  698. ctx.ServerError("LoadAttributes", nil)
  699. return nil
  700. }
  701. return issue
  702. }
  703. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  704. if issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests) ||
  705. !issue.IsPull && !ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues) {
  706. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  707. }
  708. }
  709. func getActionIssues(ctx *context.Context) []*models.Issue {
  710. commaSeparatedIssueIDs := ctx.Query("issue_ids")
  711. if len(commaSeparatedIssueIDs) == 0 {
  712. return nil
  713. }
  714. issueIDs := make([]int64, 0, 10)
  715. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  716. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  717. if err != nil {
  718. ctx.ServerError("ParseInt", err)
  719. return nil
  720. }
  721. issueIDs = append(issueIDs, issueID)
  722. }
  723. issues, err := models.GetIssuesByIDs(issueIDs)
  724. if err != nil {
  725. ctx.ServerError("GetIssuesByIDs", err)
  726. return nil
  727. }
  728. // Check access rights for all issues
  729. issueUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypeIssues)
  730. prUnitEnabled := ctx.Repo.Repository.UnitEnabled(models.UnitTypePullRequests)
  731. for _, issue := range issues {
  732. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  733. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  734. return nil
  735. }
  736. if err = issue.LoadAttributes(); err != nil {
  737. ctx.ServerError("LoadAttributes", err)
  738. return nil
  739. }
  740. }
  741. return issues
  742. }
  743. // UpdateIssueTitle change issue's title
  744. func UpdateIssueTitle(ctx *context.Context) {
  745. issue := GetActionIssue(ctx)
  746. if ctx.Written() {
  747. return
  748. }
  749. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.IsWriter()) {
  750. ctx.Error(403)
  751. return
  752. }
  753. title := ctx.QueryTrim("title")
  754. if len(title) == 0 {
  755. ctx.Error(204)
  756. return
  757. }
  758. if err := issue.ChangeTitle(ctx.User, title); err != nil {
  759. ctx.ServerError("ChangeTitle", err)
  760. return
  761. }
  762. ctx.JSON(200, map[string]interface{}{
  763. "title": issue.Title,
  764. })
  765. }
  766. // UpdateIssueContent change issue's content
  767. func UpdateIssueContent(ctx *context.Context) {
  768. issue := GetActionIssue(ctx)
  769. if ctx.Written() {
  770. return
  771. }
  772. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.IsWriter()) {
  773. ctx.Error(403)
  774. return
  775. }
  776. content := ctx.Query("content")
  777. if err := issue.ChangeContent(ctx.User, content); err != nil {
  778. ctx.ServerError("ChangeContent", err)
  779. return
  780. }
  781. ctx.JSON(200, map[string]interface{}{
  782. "content": string(markdown.Render([]byte(issue.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  783. })
  784. }
  785. // UpdateIssueMilestone change issue's milestone
  786. func UpdateIssueMilestone(ctx *context.Context) {
  787. issues := getActionIssues(ctx)
  788. if ctx.Written() {
  789. return
  790. }
  791. milestoneID := ctx.QueryInt64("id")
  792. for _, issue := range issues {
  793. oldMilestoneID := issue.MilestoneID
  794. if oldMilestoneID == milestoneID {
  795. continue
  796. }
  797. issue.MilestoneID = milestoneID
  798. if err := models.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  799. ctx.ServerError("ChangeMilestoneAssign", err)
  800. return
  801. }
  802. }
  803. ctx.JSON(200, map[string]interface{}{
  804. "ok": true,
  805. })
  806. }
  807. // UpdateIssueAssignee change issue's assignee
  808. func UpdateIssueAssignee(ctx *context.Context) {
  809. issues := getActionIssues(ctx)
  810. if ctx.Written() {
  811. return
  812. }
  813. assigneeID := ctx.QueryInt64("id")
  814. for _, issue := range issues {
  815. if issue.AssigneeID == assigneeID {
  816. continue
  817. }
  818. if err := issue.ChangeAssignee(ctx.User, assigneeID); err != nil {
  819. ctx.ServerError("ChangeAssignee", err)
  820. return
  821. }
  822. }
  823. ctx.JSON(200, map[string]interface{}{
  824. "ok": true,
  825. })
  826. }
  827. // UpdateIssueStatus change issue's status
  828. func UpdateIssueStatus(ctx *context.Context) {
  829. issues := getActionIssues(ctx)
  830. if ctx.Written() {
  831. return
  832. }
  833. var isClosed bool
  834. switch action := ctx.Query("action"); action {
  835. case "open":
  836. isClosed = false
  837. case "close":
  838. isClosed = true
  839. default:
  840. log.Warn("Unrecognized action: %s", action)
  841. }
  842. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  843. ctx.ServerError("LoadRepositories", err)
  844. return
  845. }
  846. for _, issue := range issues {
  847. if err := issue.ChangeStatus(ctx.User, issue.Repo, isClosed); err != nil {
  848. ctx.ServerError("ChangeStatus", err)
  849. return
  850. }
  851. }
  852. ctx.JSON(200, map[string]interface{}{
  853. "ok": true,
  854. })
  855. }
  856. // NewComment create a comment for issue
  857. func NewComment(ctx *context.Context, form auth.CreateCommentForm) {
  858. issue := GetActionIssue(ctx)
  859. if ctx.Written() {
  860. return
  861. }
  862. var attachments []string
  863. if setting.AttachmentEnabled {
  864. attachments = form.Files
  865. }
  866. if ctx.HasError() {
  867. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  868. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index))
  869. return
  870. }
  871. var comment *models.Comment
  872. defer func() {
  873. // Check if issue admin/poster changes the status of issue.
  874. if (ctx.Repo.IsWriter() || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  875. (form.Status == "reopen" || form.Status == "close") &&
  876. !(issue.IsPull && issue.PullRequest.HasMerged) {
  877. // Duplication and conflict check should apply to reopen pull request.
  878. var pr *models.PullRequest
  879. if form.Status == "reopen" && issue.IsPull {
  880. pull := issue.PullRequest
  881. pr, err := models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  882. if err != nil {
  883. if !models.IsErrPullRequestNotExist(err) {
  884. ctx.ServerError("GetUnmergedPullRequest", err)
  885. return
  886. }
  887. }
  888. // Regenerate patch and test conflict.
  889. if pr == nil {
  890. if err = issue.PullRequest.UpdatePatch(); err != nil {
  891. ctx.ServerError("UpdatePatch", err)
  892. return
  893. }
  894. issue.PullRequest.AddToTaskQueue()
  895. }
  896. }
  897. if pr != nil {
  898. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  899. } else {
  900. if err := issue.ChangeStatus(ctx.User, ctx.Repo.Repository, form.Status == "close"); err != nil {
  901. log.Error(4, "ChangeStatus: %v", err)
  902. } else {
  903. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  904. notification.Service.NotifyIssue(issue, ctx.User.ID)
  905. }
  906. }
  907. }
  908. // Redirect to comment hashtag if there is any actual content.
  909. typeName := "issues"
  910. if issue.IsPull {
  911. typeName = "pulls"
  912. }
  913. if comment != nil {
  914. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  915. } else {
  916. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  917. }
  918. }()
  919. // Fix #321: Allow empty comments, as long as we have attachments.
  920. if len(form.Content) == 0 && len(attachments) == 0 {
  921. return
  922. }
  923. comment, err := models.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  924. if err != nil {
  925. ctx.ServerError("CreateIssueComment", err)
  926. return
  927. }
  928. notification.Service.NotifyIssue(issue, ctx.User.ID)
  929. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  930. }
  931. // UpdateCommentContent change comment of issue's content
  932. func UpdateCommentContent(ctx *context.Context) {
  933. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  934. if err != nil {
  935. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  936. return
  937. }
  938. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  939. ctx.Error(403)
  940. return
  941. } else if comment.Type != models.CommentTypeComment {
  942. ctx.Error(204)
  943. return
  944. }
  945. comment.Content = ctx.Query("content")
  946. if len(comment.Content) == 0 {
  947. ctx.JSON(200, map[string]interface{}{
  948. "content": "",
  949. })
  950. return
  951. }
  952. if err = models.UpdateComment(comment); err != nil {
  953. ctx.ServerError("UpdateComment", err)
  954. return
  955. }
  956. ctx.JSON(200, map[string]interface{}{
  957. "content": string(markdown.Render([]byte(comment.Content), ctx.Query("context"), ctx.Repo.Repository.ComposeMetas())),
  958. })
  959. }
  960. // DeleteComment delete comment of issue
  961. func DeleteComment(ctx *context.Context) {
  962. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  963. if err != nil {
  964. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  965. return
  966. }
  967. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.IsAdmin()) {
  968. ctx.Error(403)
  969. return
  970. } else if comment.Type != models.CommentTypeComment {
  971. ctx.Error(204)
  972. return
  973. }
  974. if err = models.DeleteComment(comment); err != nil {
  975. ctx.ServerError("DeleteCommentByID", err)
  976. return
  977. }
  978. ctx.Status(200)
  979. }
  980. // Milestones render milestones page
  981. func Milestones(ctx *context.Context) {
  982. ctx.Data["Title"] = ctx.Tr("repo.milestones")
  983. ctx.Data["PageIsIssueList"] = true
  984. ctx.Data["PageIsMilestones"] = true
  985. isShowClosed := ctx.Query("state") == "closed"
  986. openCount, closedCount, err := models.MilestoneStats(ctx.Repo.Repository.ID)
  987. if err != nil {
  988. ctx.ServerError("MilestoneStats", err)
  989. return
  990. }
  991. ctx.Data["OpenCount"] = openCount
  992. ctx.Data["ClosedCount"] = closedCount
  993. sortType := ctx.Query("sort")
  994. page := ctx.QueryInt("page")
  995. if page <= 1 {
  996. page = 1
  997. }
  998. var total int
  999. if !isShowClosed {
  1000. total = int(openCount)
  1001. } else {
  1002. total = int(closedCount)
  1003. }
  1004. ctx.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  1005. miles, err := models.GetMilestones(ctx.Repo.Repository.ID, page, isShowClosed, sortType)
  1006. if err != nil {
  1007. ctx.ServerError("GetMilestones", err)
  1008. return
  1009. }
  1010. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  1011. if miles.LoadTotalTrackedTimes(); err != nil {
  1012. ctx.ServerError("LoadTotalTrackedTimes", err)
  1013. return
  1014. }
  1015. }
  1016. for _, m := range miles {
  1017. m.RenderedContent = string(markdown.Render([]byte(m.Content), ctx.Repo.RepoLink, ctx.Repo.Repository.ComposeMetas()))
  1018. }
  1019. ctx.Data["Milestones"] = miles
  1020. if isShowClosed {
  1021. ctx.Data["State"] = "closed"
  1022. } else {
  1023. ctx.Data["State"] = "open"
  1024. }
  1025. ctx.Data["SortType"] = sortType
  1026. ctx.Data["IsShowClosed"] = isShowClosed
  1027. ctx.HTML(200, tplMilestone)
  1028. }
  1029. // NewMilestone render creating milestone page
  1030. func NewMilestone(ctx *context.Context) {
  1031. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1032. ctx.Data["PageIsIssueList"] = true
  1033. ctx.Data["PageIsMilestones"] = true
  1034. ctx.Data["RequireDatetimepicker"] = true
  1035. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1036. ctx.HTML(200, tplMilestoneNew)
  1037. }
  1038. // NewMilestonePost response for creating milestone
  1039. func NewMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1040. ctx.Data["Title"] = ctx.Tr("repo.milestones.new")
  1041. ctx.Data["PageIsIssueList"] = true
  1042. ctx.Data["PageIsMilestones"] = true
  1043. ctx.Data["RequireDatetimepicker"] = true
  1044. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1045. if ctx.HasError() {
  1046. ctx.HTML(200, tplMilestoneNew)
  1047. return
  1048. }
  1049. if len(form.Deadline) == 0 {
  1050. form.Deadline = "9999-12-31"
  1051. }
  1052. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1053. if err != nil {
  1054. ctx.Data["Err_Deadline"] = true
  1055. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1056. return
  1057. }
  1058. if err = models.NewMilestone(&models.Milestone{
  1059. RepoID: ctx.Repo.Repository.ID,
  1060. Name: form.Title,
  1061. Content: form.Content,
  1062. DeadlineUnix: util.TimeStamp(deadline.Unix()),
  1063. }); err != nil {
  1064. ctx.ServerError("NewMilestone", err)
  1065. return
  1066. }
  1067. ctx.Flash.Success(ctx.Tr("repo.milestones.create_success", form.Title))
  1068. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1069. }
  1070. // EditMilestone render edting milestone page
  1071. func EditMilestone(ctx *context.Context) {
  1072. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1073. ctx.Data["PageIsMilestones"] = true
  1074. ctx.Data["PageIsEditMilestone"] = true
  1075. ctx.Data["RequireDatetimepicker"] = true
  1076. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1077. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1078. if err != nil {
  1079. if models.IsErrMilestoneNotExist(err) {
  1080. ctx.NotFound("", nil)
  1081. } else {
  1082. ctx.ServerError("GetMilestoneByRepoID", err)
  1083. }
  1084. return
  1085. }
  1086. ctx.Data["title"] = m.Name
  1087. ctx.Data["content"] = m.Content
  1088. if len(m.DeadlineString) > 0 {
  1089. ctx.Data["deadline"] = m.DeadlineString
  1090. }
  1091. ctx.HTML(200, tplMilestoneNew)
  1092. }
  1093. // EditMilestonePost response for edting milestone
  1094. func EditMilestonePost(ctx *context.Context, form auth.CreateMilestoneForm) {
  1095. ctx.Data["Title"] = ctx.Tr("repo.milestones.edit")
  1096. ctx.Data["PageIsMilestones"] = true
  1097. ctx.Data["PageIsEditMilestone"] = true
  1098. ctx.Data["RequireDatetimepicker"] = true
  1099. ctx.Data["DateLang"] = setting.DateLang(ctx.Locale.Language())
  1100. if ctx.HasError() {
  1101. ctx.HTML(200, tplMilestoneNew)
  1102. return
  1103. }
  1104. if len(form.Deadline) == 0 {
  1105. form.Deadline = "9999-12-31"
  1106. }
  1107. deadline, err := time.ParseInLocation("2006-01-02", form.Deadline, time.Local)
  1108. if err != nil {
  1109. ctx.Data["Err_Deadline"] = true
  1110. ctx.RenderWithErr(ctx.Tr("repo.milestones.invalid_due_date_format"), tplMilestoneNew, &form)
  1111. return
  1112. }
  1113. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1114. if err != nil {
  1115. if models.IsErrMilestoneNotExist(err) {
  1116. ctx.NotFound("", nil)
  1117. } else {
  1118. ctx.ServerError("GetMilestoneByRepoID", err)
  1119. }
  1120. return
  1121. }
  1122. m.Name = form.Title
  1123. m.Content = form.Content
  1124. m.DeadlineUnix = util.TimeStamp(deadline.Unix())
  1125. if err = models.UpdateMilestone(m); err != nil {
  1126. ctx.ServerError("UpdateMilestone", err)
  1127. return
  1128. }
  1129. ctx.Flash.Success(ctx.Tr("repo.milestones.edit_success", m.Name))
  1130. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1131. }
  1132. // ChangeMilestonStatus response for change a milestone's status
  1133. func ChangeMilestonStatus(ctx *context.Context) {
  1134. m, err := models.GetMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.ParamsInt64(":id"))
  1135. if err != nil {
  1136. if models.IsErrMilestoneNotExist(err) {
  1137. ctx.NotFound("", err)
  1138. } else {
  1139. ctx.ServerError("GetMilestoneByRepoID", err)
  1140. }
  1141. return
  1142. }
  1143. switch ctx.Params(":action") {
  1144. case "open":
  1145. if m.IsClosed {
  1146. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1147. ctx.ServerError("ChangeMilestoneStatus", err)
  1148. return
  1149. }
  1150. }
  1151. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=open")
  1152. case "close":
  1153. if !m.IsClosed {
  1154. m.ClosedDateUnix = util.TimeStampNow()
  1155. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1156. ctx.ServerError("ChangeMilestoneStatus", err)
  1157. return
  1158. }
  1159. }
  1160. ctx.Redirect(ctx.Repo.RepoLink + "/milestones?state=closed")
  1161. default:
  1162. ctx.Redirect(ctx.Repo.RepoLink + "/milestones")
  1163. }
  1164. }
  1165. // DeleteMilestone delete a milestone
  1166. func DeleteMilestone(ctx *context.Context) {
  1167. if err := models.DeleteMilestoneByRepoID(ctx.Repo.Repository.ID, ctx.QueryInt64("id")); err != nil {
  1168. ctx.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1169. } else {
  1170. ctx.Flash.Success(ctx.Tr("repo.milestones.deletion_success"))
  1171. }
  1172. ctx.JSON(200, map[string]interface{}{
  1173. "redirect": ctx.Repo.RepoLink + "/milestones",
  1174. })
  1175. }
  1176. // ChangeIssueReaction create a reaction for issue
  1177. func ChangeIssueReaction(ctx *context.Context, form auth.ReactionForm) {
  1178. issue := GetActionIssue(ctx)
  1179. if ctx.Written() {
  1180. return
  1181. }
  1182. if ctx.HasError() {
  1183. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  1184. return
  1185. }
  1186. switch ctx.Params(":action") {
  1187. case "react":
  1188. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  1189. if err != nil {
  1190. log.Info("CreateIssueReaction: %s", err)
  1191. break
  1192. }
  1193. // Reload new reactions
  1194. issue.Reactions = nil
  1195. if err = issue.LoadAttributes(); err != nil {
  1196. log.Info("issue.LoadAttributes: %s", err)
  1197. break
  1198. }
  1199. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  1200. case "unreact":
  1201. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  1202. ctx.ServerError("DeleteIssueReaction", err)
  1203. return
  1204. }
  1205. // Reload new reactions
  1206. issue.Reactions = nil
  1207. if err := issue.LoadAttributes(); err != nil {
  1208. log.Info("issue.LoadAttributes: %s", err)
  1209. break
  1210. }
  1211. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  1212. default:
  1213. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1214. return
  1215. }
  1216. if len(issue.Reactions) == 0 {
  1217. ctx.JSON(200, map[string]interface{}{
  1218. "empty": true,
  1219. "html": "",
  1220. })
  1221. return
  1222. }
  1223. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1224. "ctx": ctx.Data,
  1225. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  1226. "Reactions": issue.Reactions.GroupByType(),
  1227. })
  1228. if err != nil {
  1229. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  1230. return
  1231. }
  1232. ctx.JSON(200, map[string]interface{}{
  1233. "html": html,
  1234. })
  1235. }
  1236. // ChangeCommentReaction create a reaction for comment
  1237. func ChangeCommentReaction(ctx *context.Context, form auth.ReactionForm) {
  1238. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1239. if err != nil {
  1240. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1241. return
  1242. }
  1243. issue, err := models.GetIssueByID(comment.IssueID)
  1244. checkIssueRights(ctx, issue)
  1245. if ctx.Written() {
  1246. return
  1247. }
  1248. if ctx.HasError() {
  1249. ctx.ServerError("ChangeCommentReaction", errors.New(ctx.GetErrMsg()))
  1250. return
  1251. }
  1252. switch ctx.Params(":action") {
  1253. case "react":
  1254. reaction, err := models.CreateCommentReaction(ctx.User, issue, comment, form.Content)
  1255. if err != nil {
  1256. log.Info("CreateCommentReaction: %s", err)
  1257. break
  1258. }
  1259. // Reload new reactions
  1260. comment.Reactions = nil
  1261. if err = comment.LoadReactions(); err != nil {
  1262. log.Info("comment.LoadReactions: %s", err)
  1263. break
  1264. }
  1265. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID, reaction.ID)
  1266. case "unreact":
  1267. if err := models.DeleteCommentReaction(ctx.User, issue, comment, form.Content); err != nil {
  1268. ctx.ServerError("DeleteCommentReaction", err)
  1269. return
  1270. }
  1271. // Reload new reactions
  1272. comment.Reactions = nil
  1273. if err = comment.LoadReactions(); err != nil {
  1274. log.Info("comment.LoadReactions: %s", err)
  1275. break
  1276. }
  1277. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1278. default:
  1279. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  1280. return
  1281. }
  1282. if len(comment.Reactions) == 0 {
  1283. ctx.JSON(200, map[string]interface{}{
  1284. "empty": true,
  1285. "html": "",
  1286. })
  1287. return
  1288. }
  1289. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  1290. "ctx": ctx.Data,
  1291. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  1292. "Reactions": comment.Reactions.GroupByType(),
  1293. })
  1294. if err != nil {
  1295. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  1296. return
  1297. }
  1298. ctx.JSON(200, map[string]interface{}{
  1299. "html": html,
  1300. })
  1301. }