issue.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278
  1. package repo
  2. import (
  3. "fmt"
  4. "gitote/gitote/models"
  5. "gitote/gitote/models/errors"
  6. "gitote/gitote/pkg/context"
  7. "gitote/gitote/pkg/form"
  8. "gitote/gitote/pkg/markup"
  9. "gitote/gitote/pkg/setting"
  10. "gitote/gitote/pkg/template"
  11. "gitote/gitote/pkg/tool"
  12. "io"
  13. "io/ioutil"
  14. "net/http"
  15. "net/url"
  16. "strings"
  17. "time"
  18. "github.com/Unknwon/com"
  19. "gitlab.com/yoginth/paginater"
  20. log "gopkg.in/clog.v1"
  21. )
  22. const (
  23. ISSUES = "repo/issue/list"
  24. ISSUE_NEW = "repo/issue/new"
  25. ISSUE_VIEW = "repo/issue/view"
  26. LABELS = "repo/issue/labels"
  27. MILESTONE = "repo/issue/milestones"
  28. MILESTONE_NEW = "repo/issue/milestone_new"
  29. MILESTONE_EDIT = "repo/issue/milestone_edit"
  30. ISSUE_TEMPLATE_KEY = "IssueTemplate"
  31. )
  32. var (
  33. ErrFileTypeForbidden = errors.New("File type is not allowed")
  34. ErrTooManyFiles = errors.New("Maximum number of files to upload exceeded")
  35. IssueTemplateCandidates = []string{
  36. "ISSUE_TEMPLATE.md",
  37. ".gitote/ISSUE_TEMPLATE.md",
  38. ".github/ISSUE_TEMPLATE.md",
  39. }
  40. )
  41. func MustEnableIssues(c *context.Context) {
  42. if !c.Repo.Repository.EnableIssues {
  43. c.Handle(404, "MustEnableIssues", nil)
  44. return
  45. }
  46. if c.Repo.Repository.EnableExternalTracker {
  47. c.Redirect(c.Repo.Repository.ExternalTrackerURL)
  48. return
  49. }
  50. }
  51. func MustAllowPulls(c *context.Context) {
  52. if !c.Repo.Repository.AllowsPulls() {
  53. c.Handle(404, "MustAllowPulls", nil)
  54. return
  55. }
  56. // User can send pull request if owns a forked repository.
  57. if c.IsLogged && c.User.HasForkedRepo(c.Repo.Repository.ID) {
  58. c.Repo.PullRequest.Allowed = true
  59. c.Repo.PullRequest.HeadInfo = c.User.Name + ":" + c.Repo.BranchName
  60. }
  61. }
  62. func RetrieveLabels(c *context.Context) {
  63. labels, err := models.GetLabelsByRepoID(c.Repo.Repository.ID)
  64. if err != nil {
  65. c.Handle(500, "RetrieveLabels.GetLabels", err)
  66. return
  67. }
  68. for _, l := range labels {
  69. l.CalOpenIssues()
  70. }
  71. c.Data["Labels"] = labels
  72. c.Data["NumLabels"] = len(labels)
  73. }
  74. func issues(c *context.Context, isPullList bool) {
  75. if isPullList {
  76. MustAllowPulls(c)
  77. if c.Written() {
  78. return
  79. }
  80. c.Data["Title"] = c.Tr("repo.pulls")
  81. c.Data["PageIsPullList"] = true
  82. } else {
  83. MustEnableIssues(c)
  84. if c.Written() {
  85. return
  86. }
  87. c.Data["Title"] = c.Tr("repo.issues")
  88. c.Data["PageIsIssueList"] = true
  89. }
  90. viewType := c.Query("type")
  91. sortType := c.Query("sort")
  92. types := []string{"assigned", "created_by", "mentioned"}
  93. if !com.IsSliceContainsStr(types, viewType) {
  94. viewType = "all"
  95. }
  96. keyword := c.Query("q")
  97. // Must sign in to see issues about you.
  98. if viewType != "all" && !c.IsLogged {
  99. c.SetCookie("redirect_to", "/"+url.QueryEscape(setting.AppSubURL+c.Req.RequestURI), 0, setting.AppSubURL)
  100. c.Redirect(setting.AppSubURL + "/login")
  101. return
  102. }
  103. var (
  104. assigneeID = c.QueryInt64("assignee")
  105. posterID int64
  106. )
  107. filterMode := models.FILTER_MODE_YOUR_REPOS
  108. switch viewType {
  109. case "assigned":
  110. filterMode = models.FILTER_MODE_ASSIGN
  111. assigneeID = c.User.ID
  112. case "created_by":
  113. filterMode = models.FILTER_MODE_CREATE
  114. posterID = c.User.ID
  115. case "mentioned":
  116. filterMode = models.FILTER_MODE_MENTION
  117. }
  118. var uid int64 = -1
  119. if c.IsLogged {
  120. uid = c.User.ID
  121. }
  122. repo := c.Repo.Repository
  123. selectLabels := c.Query("labels")
  124. milestoneID := c.QueryInt64("milestone")
  125. isShowClosed := c.Query("state") == "closed"
  126. issueStats := models.GetIssueStats(&models.IssueStatsOptions{
  127. RepoID: repo.ID,
  128. UserID: uid,
  129. Labels: selectLabels,
  130. MilestoneID: milestoneID,
  131. AssigneeID: assigneeID,
  132. FilterMode: filterMode,
  133. IsPull: isPullList,
  134. Keyword: keyword,
  135. })
  136. page := c.QueryInt("page")
  137. if page <= 1 {
  138. page = 1
  139. }
  140. var total int
  141. if !isShowClosed {
  142. total = int(issueStats.OpenCount)
  143. } else {
  144. total = int(issueStats.ClosedCount)
  145. }
  146. pager := paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  147. c.Data["Page"] = pager
  148. issues, err := models.Issues(&models.IssuesOptions{
  149. UserID: uid,
  150. AssigneeID: assigneeID,
  151. RepoID: repo.ID,
  152. PosterID: posterID,
  153. MilestoneID: milestoneID,
  154. Page: pager.Current(),
  155. IsClosed: isShowClosed,
  156. IsMention: filterMode == models.FILTER_MODE_MENTION,
  157. IsPull: isPullList,
  158. Labels: selectLabels,
  159. SortType: sortType,
  160. Keyword: keyword,
  161. })
  162. if err != nil {
  163. c.Handle(500, "Issues", err)
  164. return
  165. }
  166. // Get issue-user relations.
  167. pairs, err := models.GetIssueUsers(repo.ID, posterID, isShowClosed)
  168. if err != nil {
  169. c.Handle(500, "GetIssueUsers", err)
  170. return
  171. }
  172. // Get posters.
  173. for i := range issues {
  174. if !c.IsLogged {
  175. issues[i].IsRead = true
  176. continue
  177. }
  178. // Check read status.
  179. idx := models.PairsContains(pairs, issues[i].ID, c.User.ID)
  180. if idx > -1 {
  181. issues[i].IsRead = pairs[idx].IsRead
  182. } else {
  183. issues[i].IsRead = true
  184. }
  185. }
  186. c.Data["Issues"] = issues
  187. // Get milestones.
  188. c.Data["Milestones"], err = models.GetMilestonesByRepoID(repo.ID)
  189. if err != nil {
  190. c.Handle(500, "GetAllRepoMilestones", err)
  191. return
  192. }
  193. // Get assignees.
  194. c.Data["Assignees"], err = repo.GetAssignees()
  195. if err != nil {
  196. c.Handle(500, "GetAssignees", err)
  197. return
  198. }
  199. if viewType == "assigned" {
  200. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  201. }
  202. c.Data["IssueStats"] = issueStats
  203. c.Data["SelectLabels"] = com.StrTo(selectLabels).MustInt64()
  204. c.Data["ViewType"] = viewType
  205. c.Data["SortType"] = sortType
  206. c.Data["MilestoneID"] = milestoneID
  207. c.Data["AssigneeID"] = assigneeID
  208. c.Data["IsShowClosed"] = isShowClosed
  209. if isShowClosed {
  210. c.Data["State"] = "closed"
  211. } else {
  212. c.Data["State"] = "open"
  213. }
  214. c.Data["Keyword"] = keyword
  215. c.HTML(200, ISSUES)
  216. }
  217. func Issues(c *context.Context) {
  218. issues(c, false)
  219. }
  220. func Pulls(c *context.Context) {
  221. issues(c, true)
  222. }
  223. func renderAttachmentSettings(c *context.Context) {
  224. c.Data["RequireDropzone"] = true
  225. c.Data["IsAttachmentEnabled"] = setting.AttachmentEnabled
  226. c.Data["AttachmentAllowedTypes"] = setting.AttachmentAllowedTypes
  227. c.Data["AttachmentMaxSize"] = setting.AttachmentMaxSize
  228. c.Data["AttachmentMaxFiles"] = setting.AttachmentMaxFiles
  229. }
  230. func RetrieveRepoMilestonesAndAssignees(c *context.Context, repo *models.Repository) {
  231. var err error
  232. c.Data["OpenMilestones"], err = models.GetMilestones(repo.ID, -1, false)
  233. if err != nil {
  234. c.Handle(500, "GetMilestones", err)
  235. return
  236. }
  237. c.Data["ClosedMilestones"], err = models.GetMilestones(repo.ID, -1, true)
  238. if err != nil {
  239. c.Handle(500, "GetMilestones", err)
  240. return
  241. }
  242. c.Data["Assignees"], err = repo.GetAssignees()
  243. if err != nil {
  244. c.Handle(500, "GetAssignees", err)
  245. return
  246. }
  247. }
  248. func RetrieveRepoMetas(c *context.Context, repo *models.Repository) []*models.Label {
  249. if !c.Repo.IsWriter() {
  250. return nil
  251. }
  252. labels, err := models.GetLabelsByRepoID(repo.ID)
  253. if err != nil {
  254. c.Handle(500, "GetLabelsByRepoID", err)
  255. return nil
  256. }
  257. c.Data["Labels"] = labels
  258. RetrieveRepoMilestonesAndAssignees(c, repo)
  259. if c.Written() {
  260. return nil
  261. }
  262. return labels
  263. }
  264. func getFileContentFromDefaultBranch(c *context.Context, filename string) (string, bool) {
  265. var r io.Reader
  266. var bytes []byte
  267. if c.Repo.Commit == nil {
  268. var err error
  269. c.Repo.Commit, err = c.Repo.GitRepo.GetBranchCommit(c.Repo.Repository.DefaultBranch)
  270. if err != nil {
  271. return "", false
  272. }
  273. }
  274. entry, err := c.Repo.Commit.GetTreeEntryByPath(filename)
  275. if err != nil {
  276. return "", false
  277. }
  278. r, err = entry.Blob().Data()
  279. if err != nil {
  280. return "", false
  281. }
  282. bytes, err = ioutil.ReadAll(r)
  283. if err != nil {
  284. return "", false
  285. }
  286. return string(bytes), true
  287. }
  288. func setTemplateIfExists(c *context.Context, ctxDataKey string, possibleFiles []string) {
  289. for _, filename := range possibleFiles {
  290. content, found := getFileContentFromDefaultBranch(c, filename)
  291. if found {
  292. c.Data[ctxDataKey] = content
  293. return
  294. }
  295. }
  296. }
  297. func NewIssue(c *context.Context) {
  298. c.Data["Title"] = c.Tr("repo.issues.new")
  299. c.Data["PageIsIssueList"] = true
  300. c.Data["RequireHighlightJS"] = true
  301. c.Data["RequireSimpleMDE"] = true
  302. c.Data["title"] = c.Query("title")
  303. c.Data["content"] = c.Query("body")
  304. setTemplateIfExists(c, ISSUE_TEMPLATE_KEY, IssueTemplateCandidates)
  305. renderAttachmentSettings(c)
  306. RetrieveRepoMetas(c, c.Repo.Repository)
  307. if c.Written() {
  308. return
  309. }
  310. c.HTML(200, ISSUE_NEW)
  311. }
  312. func ValidateRepoMetas(c *context.Context, f form.NewIssue) ([]int64, int64, int64) {
  313. var (
  314. repo = c.Repo.Repository
  315. err error
  316. )
  317. labels := RetrieveRepoMetas(c, c.Repo.Repository)
  318. if c.Written() {
  319. return nil, 0, 0
  320. }
  321. if !c.Repo.IsWriter() {
  322. return nil, 0, 0
  323. }
  324. // Check labels.
  325. labelIDs := tool.StringsToInt64s(strings.Split(f.LabelIDs, ","))
  326. labelIDMark := tool.Int64sToMap(labelIDs)
  327. hasSelected := false
  328. for i := range labels {
  329. if labelIDMark[labels[i].ID] {
  330. labels[i].IsChecked = true
  331. hasSelected = true
  332. }
  333. }
  334. c.Data["HasSelectedLabel"] = hasSelected
  335. c.Data["label_ids"] = f.LabelIDs
  336. c.Data["Labels"] = labels
  337. // Check milestone.
  338. milestoneID := f.MilestoneID
  339. if milestoneID > 0 {
  340. c.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  341. if err != nil {
  342. c.Handle(500, "GetMilestoneByID", err)
  343. return nil, 0, 0
  344. }
  345. c.Data["milestone_id"] = milestoneID
  346. }
  347. // Check assignee.
  348. assigneeID := f.AssigneeID
  349. if assigneeID > 0 {
  350. c.Data["Assignee"], err = repo.GetAssigneeByID(assigneeID)
  351. if err != nil {
  352. c.Handle(500, "GetAssigneeByID", err)
  353. return nil, 0, 0
  354. }
  355. c.Data["assignee_id"] = assigneeID
  356. }
  357. return labelIDs, milestoneID, assigneeID
  358. }
  359. func NewIssuePost(c *context.Context, f form.NewIssue) {
  360. c.Data["Title"] = c.Tr("repo.issues.new")
  361. c.Data["PageIsIssueList"] = true
  362. c.Data["RequireHighlightJS"] = true
  363. c.Data["RequireSimpleMDE"] = true
  364. renderAttachmentSettings(c)
  365. labelIDs, milestoneID, assigneeID := ValidateRepoMetas(c, f)
  366. if c.Written() {
  367. return
  368. }
  369. if c.HasError() {
  370. c.HTML(200, ISSUE_NEW)
  371. return
  372. }
  373. var attachments []string
  374. if setting.AttachmentEnabled {
  375. attachments = f.Files
  376. }
  377. issue := &models.Issue{
  378. RepoID: c.Repo.Repository.ID,
  379. Title: f.Title,
  380. PosterID: c.User.ID,
  381. Poster: c.User,
  382. MilestoneID: milestoneID,
  383. AssigneeID: assigneeID,
  384. Content: f.Content,
  385. }
  386. if err := models.NewIssue(c.Repo.Repository, issue, labelIDs, attachments); err != nil {
  387. c.Handle(500, "NewIssue", err)
  388. return
  389. }
  390. log.Trace("Issue created: %d/%d", c.Repo.Repository.ID, issue.ID)
  391. c.Redirect(c.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  392. }
  393. func uploadAttachment(c *context.Context, allowedTypes []string) {
  394. file, header, err := c.Req.FormFile("file")
  395. if err != nil {
  396. c.Error(500, fmt.Sprintf("FormFile: %v", err))
  397. return
  398. }
  399. defer file.Close()
  400. buf := make([]byte, 1024)
  401. n, _ := file.Read(buf)
  402. if n > 0 {
  403. buf = buf[:n]
  404. }
  405. fileType := http.DetectContentType(buf)
  406. allowed := false
  407. for _, t := range allowedTypes {
  408. t := strings.Trim(t, " ")
  409. if t == "*/*" || t == fileType {
  410. allowed = true
  411. break
  412. }
  413. }
  414. if !allowed {
  415. c.Error(400, ErrFileTypeForbidden.Error())
  416. return
  417. }
  418. attach, err := models.NewAttachment(header.Filename, buf, file)
  419. if err != nil {
  420. c.Error(500, fmt.Sprintf("NewAttachment: %v", err))
  421. return
  422. }
  423. log.Trace("New attachment uploaded: %s", attach.UUID)
  424. c.JSON(200, map[string]string{
  425. "uuid": attach.UUID,
  426. })
  427. }
  428. func UploadIssueAttachment(c *context.Context) {
  429. if !setting.AttachmentEnabled {
  430. c.NotFound()
  431. return
  432. }
  433. uploadAttachment(c, strings.Split(setting.AttachmentAllowedTypes, ","))
  434. }
  435. func viewIssue(c *context.Context, isPullList bool) {
  436. c.Data["RequireHighlightJS"] = true
  437. c.Data["RequireDropzone"] = true
  438. renderAttachmentSettings(c)
  439. index := c.ParamsInt64(":index")
  440. if index <= 0 {
  441. c.NotFound()
  442. return
  443. }
  444. issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, index)
  445. if err != nil {
  446. c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  447. return
  448. }
  449. c.Data["Title"] = issue.Title
  450. // Make sure type and URL matches.
  451. if !isPullList && issue.IsPull {
  452. c.Redirect(c.Repo.RepoLink + "/pulls/" + com.ToStr(issue.Index))
  453. return
  454. } else if isPullList && !issue.IsPull {
  455. c.Redirect(c.Repo.RepoLink + "/issues/" + com.ToStr(issue.Index))
  456. return
  457. }
  458. if issue.IsPull {
  459. MustAllowPulls(c)
  460. if c.Written() {
  461. return
  462. }
  463. c.Data["PageIsPullList"] = true
  464. c.Data["PageIsPullConversation"] = true
  465. } else {
  466. MustEnableIssues(c)
  467. if c.Written() {
  468. return
  469. }
  470. c.Data["PageIsIssueList"] = true
  471. }
  472. issue.RenderedContent = string(markup.Markdown(issue.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  473. repo := c.Repo.Repository
  474. // Get more information if it's a pull request.
  475. if issue.IsPull {
  476. if issue.PullRequest.HasMerged {
  477. c.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  478. PrepareMergedViewPullInfo(c, issue)
  479. } else {
  480. PrepareViewPullInfo(c, issue)
  481. }
  482. if c.Written() {
  483. return
  484. }
  485. }
  486. // Metas.
  487. // Check labels.
  488. labelIDMark := make(map[int64]bool)
  489. for i := range issue.Labels {
  490. labelIDMark[issue.Labels[i].ID] = true
  491. }
  492. labels, err := models.GetLabelsByRepoID(repo.ID)
  493. if err != nil {
  494. c.Handle(500, "GetLabelsByRepoID", err)
  495. return
  496. }
  497. hasSelected := false
  498. for i := range labels {
  499. if labelIDMark[labels[i].ID] {
  500. labels[i].IsChecked = true
  501. hasSelected = true
  502. }
  503. }
  504. c.Data["HasSelectedLabel"] = hasSelected
  505. c.Data["Labels"] = labels
  506. // Check milestone and assignee.
  507. if c.Repo.IsWriter() {
  508. RetrieveRepoMilestonesAndAssignees(c, repo)
  509. if c.Written() {
  510. return
  511. }
  512. }
  513. if c.IsLogged {
  514. // Update issue-user.
  515. if err = issue.ReadBy(c.User.ID); err != nil {
  516. c.Handle(500, "ReadBy", err)
  517. return
  518. }
  519. }
  520. var (
  521. tag models.CommentTag
  522. ok bool
  523. marked = make(map[int64]models.CommentTag)
  524. comment *models.Comment
  525. participants = make([]*models.User, 1, 10)
  526. )
  527. // Render comments and and fetch participants.
  528. participants[0] = issue.Poster
  529. for _, comment = range issue.Comments {
  530. if comment.Type == models.COMMENT_TYPE_COMMENT {
  531. comment.RenderedContent = string(markup.Markdown(comment.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  532. // Check tag.
  533. tag, ok = marked[comment.PosterID]
  534. if ok {
  535. comment.ShowTag = tag
  536. continue
  537. }
  538. if repo.IsOwnedBy(comment.PosterID) ||
  539. (repo.Owner.IsOrganization() && repo.Owner.IsOwnedBy(comment.PosterID)) {
  540. comment.ShowTag = models.COMMENT_TAG_OWNER
  541. } else if comment.Poster.IsWriterOfRepo(repo) {
  542. comment.ShowTag = models.COMMENT_TAG_WRITER
  543. } else if comment.PosterID == issue.PosterID {
  544. comment.ShowTag = models.COMMENT_TAG_POSTER
  545. }
  546. marked[comment.PosterID] = comment.ShowTag
  547. isAdded := false
  548. for j := range participants {
  549. if comment.Poster == participants[j] {
  550. isAdded = true
  551. break
  552. }
  553. }
  554. if !isAdded && !issue.IsPoster(comment.Poster.ID) {
  555. participants = append(participants, comment.Poster)
  556. }
  557. }
  558. }
  559. if issue.IsPull && issue.PullRequest.HasMerged {
  560. pull := issue.PullRequest
  561. branchProtected := false
  562. protectBranch, err := models.GetProtectBranchOfRepoByName(pull.BaseRepoID, pull.HeadBranch)
  563. if err != nil {
  564. if !errors.IsErrBranchNotExist(err) {
  565. c.ServerError("GetProtectBranchOfRepoByName", err)
  566. return
  567. }
  568. } else {
  569. branchProtected = protectBranch.Protected
  570. }
  571. c.Data["IsPullBranchDeletable"] = pull.BaseRepoID == pull.HeadRepoID &&
  572. c.Repo.IsWriter() && c.Repo.GitRepo.IsBranchExist(pull.HeadBranch) &&
  573. !branchProtected
  574. deleteBranchUrl := template.EscapePound(c.Repo.RepoLink + "/branches/delete/" + pull.HeadBranch)
  575. c.Data["DeleteBranchLink"] = fmt.Sprintf("%s?commit=%s&redirect_to=%s", deleteBranchUrl, pull.MergedCommitID, c.Data["Link"])
  576. }
  577. c.Data["Participants"] = participants
  578. c.Data["NumParticipants"] = len(participants)
  579. c.Data["Issue"] = issue
  580. c.Data["IsIssueOwner"] = c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))
  581. c.Data["SignInLink"] = setting.AppSubURL + "/login?redirect_to=" + c.Data["Link"].(string)
  582. c.HTML(200, ISSUE_VIEW)
  583. }
  584. func ViewIssue(c *context.Context) {
  585. c.Data["PageIsIssueConversation"] = true
  586. viewIssue(c, false)
  587. }
  588. func ViewPull(c *context.Context) {
  589. viewIssue(c, true)
  590. }
  591. func getActionIssue(c *context.Context) *models.Issue {
  592. issue, err := models.GetIssueByIndex(c.Repo.Repository.ID, c.ParamsInt64(":index"))
  593. if err != nil {
  594. c.NotFoundOrServerError("GetIssueByIndex", errors.IsIssueNotExist, err)
  595. return nil
  596. }
  597. // Prevent guests accessing pull requests
  598. if !c.Repo.HasAccess() && issue.IsPull {
  599. c.NotFound()
  600. return nil
  601. }
  602. return issue
  603. }
  604. func UpdateIssueTitle(c *context.Context) {
  605. issue := getActionIssue(c)
  606. if c.Written() {
  607. return
  608. }
  609. if !c.IsLogged || (!issue.IsPoster(c.User.ID) && !c.Repo.IsWriter()) {
  610. c.Error(403)
  611. return
  612. }
  613. title := c.QueryTrim("title")
  614. if len(title) == 0 {
  615. c.Error(204)
  616. return
  617. }
  618. if err := issue.ChangeTitle(c.User, title); err != nil {
  619. c.Handle(500, "ChangeTitle", err)
  620. return
  621. }
  622. c.JSON(200, map[string]interface{}{
  623. "title": issue.Title,
  624. })
  625. }
  626. func UpdateIssueContent(c *context.Context) {
  627. issue := getActionIssue(c)
  628. if c.Written() {
  629. return
  630. }
  631. if !c.IsLogged || (c.User.ID != issue.PosterID && !c.Repo.IsWriter()) {
  632. c.Error(403)
  633. return
  634. }
  635. content := c.Query("content")
  636. if err := issue.ChangeContent(c.User, content); err != nil {
  637. c.Handle(500, "ChangeContent", err)
  638. return
  639. }
  640. c.JSON(200, map[string]string{
  641. "content": string(markup.Markdown(issue.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  642. })
  643. }
  644. func UpdateIssueLabel(c *context.Context) {
  645. issue := getActionIssue(c)
  646. if c.Written() {
  647. return
  648. }
  649. if c.Query("action") == "clear" {
  650. if err := issue.ClearLabels(c.User); err != nil {
  651. c.Handle(500, "ClearLabels", err)
  652. return
  653. }
  654. } else {
  655. isAttach := c.Query("action") == "attach"
  656. label, err := models.GetLabelOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id"))
  657. if err != nil {
  658. if models.IsErrLabelNotExist(err) {
  659. c.Error(404, "GetLabelByID")
  660. } else {
  661. c.Handle(500, "GetLabelByID", err)
  662. }
  663. return
  664. }
  665. if isAttach && !issue.HasLabel(label.ID) {
  666. if err = issue.AddLabel(c.User, label); err != nil {
  667. c.Handle(500, "AddLabel", err)
  668. return
  669. }
  670. } else if !isAttach && issue.HasLabel(label.ID) {
  671. if err = issue.RemoveLabel(c.User, label); err != nil {
  672. c.Handle(500, "RemoveLabel", err)
  673. return
  674. }
  675. }
  676. }
  677. c.JSON(200, map[string]interface{}{
  678. "ok": true,
  679. })
  680. }
  681. func UpdateIssueMilestone(c *context.Context) {
  682. issue := getActionIssue(c)
  683. if c.Written() {
  684. return
  685. }
  686. oldMilestoneID := issue.MilestoneID
  687. milestoneID := c.QueryInt64("id")
  688. if oldMilestoneID == milestoneID {
  689. c.JSON(200, map[string]interface{}{
  690. "ok": true,
  691. })
  692. return
  693. }
  694. // Not check for invalid milestone id and give responsibility to owners.
  695. issue.MilestoneID = milestoneID
  696. if err := models.ChangeMilestoneAssign(c.User, issue, oldMilestoneID); err != nil {
  697. c.Handle(500, "ChangeMilestoneAssign", err)
  698. return
  699. }
  700. c.JSON(200, map[string]interface{}{
  701. "ok": true,
  702. })
  703. }
  704. func UpdateIssueAssignee(c *context.Context) {
  705. issue := getActionIssue(c)
  706. if c.Written() {
  707. return
  708. }
  709. assigneeID := c.QueryInt64("id")
  710. if issue.AssigneeID == assigneeID {
  711. c.JSON(200, map[string]interface{}{
  712. "ok": true,
  713. })
  714. return
  715. }
  716. if err := issue.ChangeAssignee(c.User, assigneeID); err != nil {
  717. c.Handle(500, "ChangeAssignee", err)
  718. return
  719. }
  720. c.JSON(200, map[string]interface{}{
  721. "ok": true,
  722. })
  723. }
  724. func NewComment(c *context.Context, f form.CreateComment) {
  725. issue := getActionIssue(c)
  726. if c.Written() {
  727. return
  728. }
  729. var attachments []string
  730. if setting.AttachmentEnabled {
  731. attachments = f.Files
  732. }
  733. if c.HasError() {
  734. c.Flash.Error(c.Data["ErrorMsg"].(string))
  735. c.Redirect(fmt.Sprintf("%s/issues/%d", c.Repo.RepoLink, issue.Index))
  736. return
  737. }
  738. var err error
  739. var comment *models.Comment
  740. defer func() {
  741. // Check if issue admin/poster changes the status of issue.
  742. if (c.Repo.IsWriter() || (c.IsLogged && issue.IsPoster(c.User.ID))) &&
  743. (f.Status == "reopen" || f.Status == "close") &&
  744. !(issue.IsPull && issue.PullRequest.HasMerged) {
  745. // Duplication and conflict check should apply to reopen pull request.
  746. var pr *models.PullRequest
  747. if f.Status == "reopen" && issue.IsPull {
  748. pull := issue.PullRequest
  749. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch)
  750. if err != nil {
  751. if !models.IsErrPullRequestNotExist(err) {
  752. c.ServerError("GetUnmergedPullRequest", err)
  753. return
  754. }
  755. }
  756. // Regenerate patch and test conflict.
  757. if pr == nil {
  758. if err = issue.PullRequest.UpdatePatch(); err != nil {
  759. c.ServerError("UpdatePatch", err)
  760. return
  761. }
  762. issue.PullRequest.AddToTaskQueue()
  763. }
  764. }
  765. if pr != nil {
  766. c.Flash.Info(c.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  767. } else {
  768. if err = issue.ChangeStatus(c.User, c.Repo.Repository, f.Status == "close"); err != nil {
  769. log.Error(2, "ChangeStatus: %v", err)
  770. } else {
  771. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  772. }
  773. }
  774. }
  775. // Redirect to comment hashtag if there is any actual content.
  776. typeName := "issues"
  777. if issue.IsPull {
  778. typeName = "pulls"
  779. }
  780. if comment != nil {
  781. c.RawRedirect(fmt.Sprintf("%s/%s/%d#%s", c.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  782. } else {
  783. c.Redirect(fmt.Sprintf("%s/%s/%d", c.Repo.RepoLink, typeName, issue.Index))
  784. }
  785. }()
  786. // Fix #321: Allow empty comments, as long as we have attachments.
  787. if len(f.Content) == 0 && len(attachments) == 0 {
  788. return
  789. }
  790. comment, err = models.CreateIssueComment(c.User, c.Repo.Repository, issue, f.Content, attachments)
  791. if err != nil {
  792. c.ServerError("CreateIssueComment", err)
  793. return
  794. }
  795. log.Trace("Comment created: %d/%d/%d", c.Repo.Repository.ID, issue.ID, comment.ID)
  796. }
  797. func UpdateCommentContent(c *context.Context) {
  798. comment, err := models.GetCommentByID(c.ParamsInt64(":id"))
  799. if err != nil {
  800. c.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  801. return
  802. }
  803. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  804. c.Error(404)
  805. return
  806. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  807. c.Error(204)
  808. return
  809. }
  810. oldContent := comment.Content
  811. comment.Content = c.Query("content")
  812. if len(comment.Content) == 0 {
  813. c.JSON(200, map[string]interface{}{
  814. "content": "",
  815. })
  816. return
  817. }
  818. if err = models.UpdateComment(c.User, comment, oldContent); err != nil {
  819. c.Handle(500, "UpdateComment", err)
  820. return
  821. }
  822. c.JSON(200, map[string]string{
  823. "content": string(markup.Markdown(comment.Content, c.Query("context"), c.Repo.Repository.ComposeMetas())),
  824. })
  825. }
  826. func DeleteComment(c *context.Context) {
  827. comment, err := models.GetCommentByID(c.ParamsInt64(":id"))
  828. if err != nil {
  829. c.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  830. return
  831. }
  832. if c.UserID() != comment.PosterID && !c.Repo.IsAdmin() {
  833. c.Error(404)
  834. return
  835. } else if comment.Type != models.COMMENT_TYPE_COMMENT {
  836. c.Error(204)
  837. return
  838. }
  839. if err = models.DeleteCommentByID(c.User, comment.ID); err != nil {
  840. c.Handle(500, "DeleteCommentByID", err)
  841. return
  842. }
  843. c.Status(200)
  844. }
  845. func Labels(c *context.Context) {
  846. c.Data["Title"] = c.Tr("repo.labels")
  847. c.Data["PageIsIssueList"] = true
  848. c.Data["PageIsLabels"] = true
  849. c.Data["RequireMinicolors"] = true
  850. c.Data["LabelTemplates"] = models.LabelTemplates
  851. c.HTML(200, LABELS)
  852. }
  853. func InitializeLabels(c *context.Context, f form.InitializeLabels) {
  854. if c.HasError() {
  855. c.Redirect(c.Repo.RepoLink + "/labels")
  856. return
  857. }
  858. list, err := models.GetLabelTemplateFile(f.TemplateName)
  859. if err != nil {
  860. c.Flash.Error(c.Tr("repo.issues.label_templates.fail_to_load_file", f.TemplateName, err))
  861. c.Redirect(c.Repo.RepoLink + "/labels")
  862. return
  863. }
  864. labels := make([]*models.Label, len(list))
  865. for i := 0; i < len(list); i++ {
  866. labels[i] = &models.Label{
  867. RepoID: c.Repo.Repository.ID,
  868. Name: list[i][0],
  869. Color: list[i][1],
  870. }
  871. }
  872. if err := models.NewLabels(labels...); err != nil {
  873. c.Handle(500, "NewLabels", err)
  874. return
  875. }
  876. c.Redirect(c.Repo.RepoLink + "/labels")
  877. }
  878. func NewLabel(c *context.Context, f form.CreateLabel) {
  879. c.Data["Title"] = c.Tr("repo.labels")
  880. c.Data["PageIsLabels"] = true
  881. if c.HasError() {
  882. c.Flash.Error(c.Data["ErrorMsg"].(string))
  883. c.Redirect(c.Repo.RepoLink + "/labels")
  884. return
  885. }
  886. l := &models.Label{
  887. RepoID: c.Repo.Repository.ID,
  888. Name: f.Title,
  889. Color: f.Color,
  890. }
  891. if err := models.NewLabels(l); err != nil {
  892. c.Handle(500, "NewLabel", err)
  893. return
  894. }
  895. c.Redirect(c.Repo.RepoLink + "/labels")
  896. }
  897. func UpdateLabel(c *context.Context, f form.CreateLabel) {
  898. l, err := models.GetLabelByID(f.ID)
  899. if err != nil {
  900. switch {
  901. case models.IsErrLabelNotExist(err):
  902. c.Error(404)
  903. default:
  904. c.Handle(500, "UpdateLabel", err)
  905. }
  906. return
  907. }
  908. l.Name = f.Title
  909. l.Color = f.Color
  910. if err := models.UpdateLabel(l); err != nil {
  911. c.Handle(500, "UpdateLabel", err)
  912. return
  913. }
  914. c.Redirect(c.Repo.RepoLink + "/labels")
  915. }
  916. func DeleteLabel(c *context.Context) {
  917. if err := models.DeleteLabel(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  918. c.Flash.Error("DeleteLabel: " + err.Error())
  919. } else {
  920. c.Flash.Success(c.Tr("repo.issues.label_deletion_success"))
  921. }
  922. c.JSON(200, map[string]interface{}{
  923. "redirect": c.Repo.RepoLink + "/labels",
  924. })
  925. return
  926. }
  927. func Milestones(c *context.Context) {
  928. c.Data["Title"] = c.Tr("repo.milestones")
  929. c.Data["PageIsIssueList"] = true
  930. c.Data["PageIsMilestones"] = true
  931. isShowClosed := c.Query("state") == "closed"
  932. openCount, closedCount := models.MilestoneStats(c.Repo.Repository.ID)
  933. c.Data["OpenCount"] = openCount
  934. c.Data["ClosedCount"] = closedCount
  935. page := c.QueryInt("page")
  936. if page <= 1 {
  937. page = 1
  938. }
  939. var total int
  940. if !isShowClosed {
  941. total = int(openCount)
  942. } else {
  943. total = int(closedCount)
  944. }
  945. c.Data["Page"] = paginater.New(total, setting.UI.IssuePagingNum, page, 5)
  946. miles, err := models.GetMilestones(c.Repo.Repository.ID, page, isShowClosed)
  947. if err != nil {
  948. c.Handle(500, "GetMilestones", err)
  949. return
  950. }
  951. for _, m := range miles {
  952. m.NumOpenIssues = int(m.CountIssues(false, false))
  953. m.NumClosedIssues = int(m.CountIssues(true, false))
  954. if m.NumOpenIssues+m.NumClosedIssues > 0 {
  955. m.Completeness = m.NumClosedIssues * 100 / (m.NumOpenIssues + m.NumClosedIssues)
  956. }
  957. m.RenderedContent = string(markup.Markdown(m.Content, c.Repo.RepoLink, c.Repo.Repository.ComposeMetas()))
  958. }
  959. c.Data["Milestones"] = miles
  960. if isShowClosed {
  961. c.Data["State"] = "closed"
  962. } else {
  963. c.Data["State"] = "open"
  964. }
  965. c.Data["IsShowClosed"] = isShowClosed
  966. c.HTML(200, MILESTONE)
  967. }
  968. func NewMilestone(c *context.Context) {
  969. c.Data["Title"] = c.Tr("repo.milestones.new")
  970. c.Data["PageIsIssueList"] = true
  971. c.Data["PageIsMilestones"] = true
  972. c.Data["RequireDatetimepicker"] = true
  973. c.Data["DateLang"] = setting.DateLang(c.Locale.Language())
  974. c.HTML(200, MILESTONE_NEW)
  975. }
  976. func NewMilestonePost(c *context.Context, f form.CreateMilestone) {
  977. c.Data["Title"] = c.Tr("repo.milestones.new")
  978. c.Data["PageIsIssueList"] = true
  979. c.Data["PageIsMilestones"] = true
  980. c.Data["RequireDatetimepicker"] = true
  981. c.Data["DateLang"] = setting.DateLang(c.Locale.Language())
  982. if c.HasError() {
  983. c.HTML(200, MILESTONE_NEW)
  984. return
  985. }
  986. if len(f.Deadline) == 0 {
  987. f.Deadline = "9999-12-31"
  988. }
  989. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  990. if err != nil {
  991. c.Data["Err_Deadline"] = true
  992. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  993. return
  994. }
  995. if err = models.NewMilestone(&models.Milestone{
  996. RepoID: c.Repo.Repository.ID,
  997. Name: f.Title,
  998. Content: f.Content,
  999. Deadline: deadline,
  1000. }); err != nil {
  1001. c.Handle(500, "NewMilestone", err)
  1002. return
  1003. }
  1004. c.Flash.Success(c.Tr("repo.milestones.create_success", f.Title))
  1005. c.Redirect(c.Repo.RepoLink + "/milestones")
  1006. }
  1007. func EditMilestone(c *context.Context) {
  1008. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1009. c.Data["PageIsMilestones"] = true
  1010. c.Data["PageIsEditMilestone"] = true
  1011. c.Data["RequireDatetimepicker"] = true
  1012. c.Data["DateLang"] = setting.DateLang(c.Locale.Language())
  1013. m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1014. if err != nil {
  1015. if models.IsErrMilestoneNotExist(err) {
  1016. c.Handle(404, "", nil)
  1017. } else {
  1018. c.Handle(500, "GetMilestoneByRepoID", err)
  1019. }
  1020. return
  1021. }
  1022. c.Data["title"] = m.Name
  1023. c.Data["content"] = m.Content
  1024. if len(m.DeadlineString) > 0 {
  1025. c.Data["deadline"] = m.DeadlineString
  1026. }
  1027. c.HTML(200, MILESTONE_NEW)
  1028. }
  1029. func EditMilestonePost(c *context.Context, f form.CreateMilestone) {
  1030. c.Data["Title"] = c.Tr("repo.milestones.edit")
  1031. c.Data["PageIsMilestones"] = true
  1032. c.Data["PageIsEditMilestone"] = true
  1033. c.Data["RequireDatetimepicker"] = true
  1034. c.Data["DateLang"] = setting.DateLang(c.Locale.Language())
  1035. if c.HasError() {
  1036. c.HTML(200, MILESTONE_NEW)
  1037. return
  1038. }
  1039. if len(f.Deadline) == 0 {
  1040. f.Deadline = "9999-12-31"
  1041. }
  1042. deadline, err := time.ParseInLocation("2006-01-02", f.Deadline, time.Local)
  1043. if err != nil {
  1044. c.Data["Err_Deadline"] = true
  1045. c.RenderWithErr(c.Tr("repo.milestones.invalid_due_date_format"), MILESTONE_NEW, &f)
  1046. return
  1047. }
  1048. m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1049. if err != nil {
  1050. if models.IsErrMilestoneNotExist(err) {
  1051. c.Handle(404, "", nil)
  1052. } else {
  1053. c.Handle(500, "GetMilestoneByRepoID", err)
  1054. }
  1055. return
  1056. }
  1057. m.Name = f.Title
  1058. m.Content = f.Content
  1059. m.Deadline = deadline
  1060. if err = models.UpdateMilestone(m); err != nil {
  1061. c.Handle(500, "UpdateMilestone", err)
  1062. return
  1063. }
  1064. c.Flash.Success(c.Tr("repo.milestones.edit_success", m.Name))
  1065. c.Redirect(c.Repo.RepoLink + "/milestones")
  1066. }
  1067. func ChangeMilestonStatus(c *context.Context) {
  1068. m, err := models.GetMilestoneByRepoID(c.Repo.Repository.ID, c.ParamsInt64(":id"))
  1069. if err != nil {
  1070. if models.IsErrMilestoneNotExist(err) {
  1071. c.Handle(404, "", err)
  1072. } else {
  1073. c.Handle(500, "GetMilestoneByRepoID", err)
  1074. }
  1075. return
  1076. }
  1077. switch c.Params(":action") {
  1078. case "open":
  1079. if m.IsClosed {
  1080. if err = models.ChangeMilestoneStatus(m, false); err != nil {
  1081. c.Handle(500, "ChangeMilestoneStatus", err)
  1082. return
  1083. }
  1084. }
  1085. c.Redirect(c.Repo.RepoLink + "/milestones?state=open")
  1086. case "close":
  1087. if !m.IsClosed {
  1088. m.ClosedDate = time.Now()
  1089. if err = models.ChangeMilestoneStatus(m, true); err != nil {
  1090. c.Handle(500, "ChangeMilestoneStatus", err)
  1091. return
  1092. }
  1093. }
  1094. c.Redirect(c.Repo.RepoLink + "/milestones?state=closed")
  1095. default:
  1096. c.Redirect(c.Repo.RepoLink + "/milestones")
  1097. }
  1098. }
  1099. func DeleteMilestone(c *context.Context) {
  1100. if err := models.DeleteMilestoneOfRepoByID(c.Repo.Repository.ID, c.QueryInt64("id")); err != nil {
  1101. c.Flash.Error("DeleteMilestoneByRepoID: " + err.Error())
  1102. } else {
  1103. c.Flash.Success(c.Tr("repo.milestones.deletion_success"))
  1104. }
  1105. c.JSON(200, map[string]interface{}{
  1106. "redirect": c.Repo.RepoLink + "/milestones",
  1107. })
  1108. }