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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2018 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package repo
  6. import (
  7. "bytes"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "net/http"
  12. "net/url"
  13. "path"
  14. "strconv"
  15. "strings"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/models/db"
  18. repo_model "code.gitea.io/gitea/models/repo"
  19. "code.gitea.io/gitea/models/unit"
  20. user_model "code.gitea.io/gitea/models/user"
  21. "code.gitea.io/gitea/modules/base"
  22. "code.gitea.io/gitea/modules/context"
  23. "code.gitea.io/gitea/modules/convert"
  24. "code.gitea.io/gitea/modules/git"
  25. issue_indexer "code.gitea.io/gitea/modules/indexer/issues"
  26. "code.gitea.io/gitea/modules/log"
  27. "code.gitea.io/gitea/modules/markup"
  28. "code.gitea.io/gitea/modules/markup/markdown"
  29. "code.gitea.io/gitea/modules/setting"
  30. api "code.gitea.io/gitea/modules/structs"
  31. "code.gitea.io/gitea/modules/upload"
  32. "code.gitea.io/gitea/modules/util"
  33. "code.gitea.io/gitea/modules/web"
  34. comment_service "code.gitea.io/gitea/services/comments"
  35. "code.gitea.io/gitea/services/forms"
  36. issue_service "code.gitea.io/gitea/services/issue"
  37. pull_service "code.gitea.io/gitea/services/pull"
  38. "github.com/unknwon/com"
  39. )
  40. const (
  41. tplAttachment base.TplName = "repo/issue/view_content/attachments"
  42. tplIssues base.TplName = "repo/issue/list"
  43. tplIssueNew base.TplName = "repo/issue/new"
  44. tplIssueChoose base.TplName = "repo/issue/choose"
  45. tplIssueView base.TplName = "repo/issue/view"
  46. tplReactions base.TplName = "repo/issue/view_content/reactions"
  47. issueTemplateKey = "IssueTemplate"
  48. issueTemplateTitleKey = "IssueTemplateTitle"
  49. )
  50. var (
  51. // IssueTemplateCandidates issue templates
  52. IssueTemplateCandidates = []string{
  53. "ISSUE_TEMPLATE.md",
  54. "issue_template.md",
  55. ".gitea/ISSUE_TEMPLATE.md",
  56. ".gitea/issue_template.md",
  57. ".github/ISSUE_TEMPLATE.md",
  58. ".github/issue_template.md",
  59. }
  60. )
  61. // MustAllowUserComment checks to make sure if an issue is locked.
  62. // If locked and user has permissions to write to the repository,
  63. // then the comment is allowed, else it is blocked
  64. func MustAllowUserComment(ctx *context.Context) {
  65. issue := GetActionIssue(ctx)
  66. if ctx.Written() {
  67. return
  68. }
  69. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  70. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  71. ctx.Redirect(issue.HTMLURL())
  72. return
  73. }
  74. }
  75. // MustEnableIssues check if repository enable internal issues
  76. func MustEnableIssues(ctx *context.Context) {
  77. if !ctx.Repo.CanRead(unit.TypeIssues) &&
  78. !ctx.Repo.CanRead(unit.TypeExternalTracker) {
  79. ctx.NotFound("MustEnableIssues", nil)
  80. return
  81. }
  82. unit, err := ctx.Repo.Repository.GetUnit(unit.TypeExternalTracker)
  83. if err == nil {
  84. ctx.Redirect(unit.ExternalTrackerConfig().ExternalTrackerURL)
  85. return
  86. }
  87. }
  88. // MustAllowPulls check if repository enable pull requests and user have right to do that
  89. func MustAllowPulls(ctx *context.Context) {
  90. if !ctx.Repo.Repository.CanEnablePulls() || !ctx.Repo.CanRead(unit.TypePullRequests) {
  91. ctx.NotFound("MustAllowPulls", nil)
  92. return
  93. }
  94. // User can send pull request if owns a forked repository.
  95. if ctx.IsSigned && models.HasForkedRepo(ctx.User.ID, ctx.Repo.Repository.ID) {
  96. ctx.Repo.PullRequest.Allowed = true
  97. ctx.Repo.PullRequest.HeadInfoSubURL = url.PathEscape(ctx.User.Name) + ":" + util.PathEscapeSegments(ctx.Repo.BranchName)
  98. }
  99. }
  100. func issues(ctx *context.Context, milestoneID, projectID int64, isPullOption util.OptionalBool) {
  101. var err error
  102. viewType := ctx.FormString("type")
  103. sortType := ctx.FormString("sort")
  104. types := []string{"all", "your_repositories", "assigned", "created_by", "mentioned", "review_requested"}
  105. if !util.IsStringInSlice(viewType, types, true) {
  106. viewType = "all"
  107. }
  108. var (
  109. assigneeID = ctx.FormInt64("assignee")
  110. posterID int64
  111. mentionedID int64
  112. reviewRequestedID int64
  113. forceEmpty bool
  114. )
  115. if ctx.IsSigned {
  116. switch viewType {
  117. case "created_by":
  118. posterID = ctx.User.ID
  119. case "mentioned":
  120. mentionedID = ctx.User.ID
  121. case "assigned":
  122. assigneeID = ctx.User.ID
  123. case "review_requested":
  124. reviewRequestedID = ctx.User.ID
  125. }
  126. }
  127. repo := ctx.Repo.Repository
  128. var labelIDs []int64
  129. selectLabels := ctx.FormString("labels")
  130. if len(selectLabels) > 0 && selectLabels != "0" {
  131. labelIDs, err = base.StringsToInt64s(strings.Split(selectLabels, ","))
  132. if err != nil {
  133. ctx.ServerError("StringsToInt64s", err)
  134. return
  135. }
  136. }
  137. keyword := strings.Trim(ctx.FormString("q"), " ")
  138. if bytes.Contains([]byte(keyword), []byte{0x00}) {
  139. keyword = ""
  140. }
  141. var issueIDs []int64
  142. if len(keyword) > 0 {
  143. issueIDs, err = issue_indexer.SearchIssuesByKeyword([]int64{repo.ID}, keyword)
  144. if err != nil {
  145. ctx.ServerError("issueIndexer.Search", err)
  146. return
  147. }
  148. if len(issueIDs) == 0 {
  149. forceEmpty = true
  150. }
  151. }
  152. var issueStats *models.IssueStats
  153. if forceEmpty {
  154. issueStats = &models.IssueStats{}
  155. } else {
  156. issueStats, err = models.GetIssueStats(&models.IssueStatsOptions{
  157. RepoID: repo.ID,
  158. Labels: selectLabels,
  159. MilestoneID: milestoneID,
  160. AssigneeID: assigneeID,
  161. MentionedID: mentionedID,
  162. PosterID: posterID,
  163. ReviewRequestedID: reviewRequestedID,
  164. IsPull: isPullOption,
  165. IssueIDs: issueIDs,
  166. })
  167. if err != nil {
  168. ctx.ServerError("GetIssueStats", err)
  169. return
  170. }
  171. }
  172. isShowClosed := ctx.FormString("state") == "closed"
  173. // if open issues are zero and close don't, use closed as default
  174. if len(ctx.FormString("state")) == 0 && issueStats.OpenCount == 0 && issueStats.ClosedCount != 0 {
  175. isShowClosed = true
  176. }
  177. page := ctx.FormInt("page")
  178. if page <= 1 {
  179. page = 1
  180. }
  181. var total int
  182. if !isShowClosed {
  183. total = int(issueStats.OpenCount)
  184. } else {
  185. total = int(issueStats.ClosedCount)
  186. }
  187. pager := context.NewPagination(total, setting.UI.IssuePagingNum, page, 5)
  188. var mileIDs []int64
  189. if milestoneID > 0 {
  190. mileIDs = []int64{milestoneID}
  191. }
  192. var issues []*models.Issue
  193. if forceEmpty {
  194. issues = []*models.Issue{}
  195. } else {
  196. issues, err = models.Issues(&models.IssuesOptions{
  197. ListOptions: db.ListOptions{
  198. Page: pager.Paginater.Current(),
  199. PageSize: setting.UI.IssuePagingNum,
  200. },
  201. RepoIDs: []int64{repo.ID},
  202. AssigneeID: assigneeID,
  203. PosterID: posterID,
  204. MentionedID: mentionedID,
  205. ReviewRequestedID: reviewRequestedID,
  206. MilestoneIDs: mileIDs,
  207. ProjectID: projectID,
  208. IsClosed: util.OptionalBoolOf(isShowClosed),
  209. IsPull: isPullOption,
  210. LabelIDs: labelIDs,
  211. SortType: sortType,
  212. IssueIDs: issueIDs,
  213. })
  214. if err != nil {
  215. ctx.ServerError("Issues", err)
  216. return
  217. }
  218. }
  219. var issueList = models.IssueList(issues)
  220. approvalCounts, err := issueList.GetApprovalCounts()
  221. if err != nil {
  222. ctx.ServerError("ApprovalCounts", err)
  223. return
  224. }
  225. // Get posters.
  226. for i := range issues {
  227. // Check read status
  228. if !ctx.IsSigned {
  229. issues[i].IsRead = true
  230. } else if err = issues[i].GetIsRead(ctx.User.ID); err != nil {
  231. ctx.ServerError("GetIsRead", err)
  232. return
  233. }
  234. }
  235. commitStatus, err := pull_service.GetIssuesLastCommitStatus(issues)
  236. if err != nil {
  237. ctx.ServerError("GetIssuesLastCommitStatus", err)
  238. return
  239. }
  240. ctx.Data["Issues"] = issues
  241. ctx.Data["CommitStatus"] = commitStatus
  242. // Get assignees.
  243. ctx.Data["Assignees"], err = repo.GetAssignees()
  244. if err != nil {
  245. ctx.ServerError("GetAssignees", err)
  246. return
  247. }
  248. handleTeamMentions(ctx)
  249. if ctx.Written() {
  250. return
  251. }
  252. labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
  253. if err != nil {
  254. ctx.ServerError("GetLabelsByRepoID", err)
  255. return
  256. }
  257. if repo.Owner.IsOrganization() {
  258. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
  259. if err != nil {
  260. ctx.ServerError("GetLabelsByOrgID", err)
  261. return
  262. }
  263. ctx.Data["OrgLabels"] = orgLabels
  264. labels = append(labels, orgLabels...)
  265. }
  266. for _, l := range labels {
  267. l.LoadSelectedLabelsAfterClick(labelIDs)
  268. }
  269. ctx.Data["Labels"] = labels
  270. ctx.Data["NumLabels"] = len(labels)
  271. if ctx.FormInt64("assignee") == 0 {
  272. assigneeID = 0 // Reset ID to prevent unexpected selection of assignee.
  273. }
  274. ctx.Data["IssueRefEndNames"], ctx.Data["IssueRefURLs"] =
  275. issue_service.GetRefEndNamesAndURLs(issues, ctx.Repo.RepoLink)
  276. ctx.Data["ApprovalCounts"] = func(issueID int64, typ string) int64 {
  277. counts, ok := approvalCounts[issueID]
  278. if !ok || len(counts) == 0 {
  279. return 0
  280. }
  281. reviewTyp := models.ReviewTypeApprove
  282. if typ == "reject" {
  283. reviewTyp = models.ReviewTypeReject
  284. } else if typ == "waiting" {
  285. reviewTyp = models.ReviewTypeRequest
  286. }
  287. for _, count := range counts {
  288. if count.Type == reviewTyp {
  289. return count.Count
  290. }
  291. }
  292. return 0
  293. }
  294. if ctx.Repo.CanWriteIssuesOrPulls(ctx.Params(":type") == "pulls") {
  295. projects, _, err := models.GetProjects(models.ProjectSearchOptions{
  296. RepoID: repo.ID,
  297. Type: models.ProjectTypeRepository,
  298. IsClosed: util.OptionalBoolOf(isShowClosed),
  299. })
  300. if err != nil {
  301. ctx.ServerError("GetProjects", err)
  302. return
  303. }
  304. ctx.Data["Projects"] = projects
  305. }
  306. ctx.Data["IssueStats"] = issueStats
  307. ctx.Data["SelLabelIDs"] = labelIDs
  308. ctx.Data["SelectLabels"] = selectLabels
  309. ctx.Data["ViewType"] = viewType
  310. ctx.Data["SortType"] = sortType
  311. ctx.Data["MilestoneID"] = milestoneID
  312. ctx.Data["AssigneeID"] = assigneeID
  313. ctx.Data["IsShowClosed"] = isShowClosed
  314. ctx.Data["Keyword"] = keyword
  315. if isShowClosed {
  316. ctx.Data["State"] = "closed"
  317. } else {
  318. ctx.Data["State"] = "open"
  319. }
  320. pager.AddParam(ctx, "q", "Keyword")
  321. pager.AddParam(ctx, "type", "ViewType")
  322. pager.AddParam(ctx, "sort", "SortType")
  323. pager.AddParam(ctx, "state", "State")
  324. pager.AddParam(ctx, "labels", "SelectLabels")
  325. pager.AddParam(ctx, "milestone", "MilestoneID")
  326. pager.AddParam(ctx, "assignee", "AssigneeID")
  327. ctx.Data["Page"] = pager
  328. }
  329. // Issues render issues page
  330. func Issues(ctx *context.Context) {
  331. isPullList := ctx.Params(":type") == "pulls"
  332. if isPullList {
  333. MustAllowPulls(ctx)
  334. if ctx.Written() {
  335. return
  336. }
  337. ctx.Data["Title"] = ctx.Tr("repo.pulls")
  338. ctx.Data["PageIsPullList"] = true
  339. } else {
  340. MustEnableIssues(ctx)
  341. if ctx.Written() {
  342. return
  343. }
  344. ctx.Data["Title"] = ctx.Tr("repo.issues")
  345. ctx.Data["PageIsIssueList"] = true
  346. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  347. }
  348. issues(ctx, ctx.FormInt64("milestone"), ctx.FormInt64("project"), util.OptionalBoolOf(isPullList))
  349. if ctx.Written() {
  350. return
  351. }
  352. var err error
  353. // Get milestones
  354. ctx.Data["Milestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  355. RepoID: ctx.Repo.Repository.ID,
  356. State: api.StateType(ctx.FormString("state")),
  357. })
  358. if err != nil {
  359. ctx.ServerError("GetAllRepoMilestones", err)
  360. return
  361. }
  362. ctx.Data["CanWriteIssuesOrPulls"] = ctx.Repo.CanWriteIssuesOrPulls(isPullList)
  363. ctx.HTML(http.StatusOK, tplIssues)
  364. }
  365. // RetrieveRepoMilestonesAndAssignees find all the milestones and assignees of a repository
  366. func RetrieveRepoMilestonesAndAssignees(ctx *context.Context, repo *models.Repository) {
  367. var err error
  368. ctx.Data["OpenMilestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  369. RepoID: repo.ID,
  370. State: api.StateOpen,
  371. })
  372. if err != nil {
  373. ctx.ServerError("GetMilestones", err)
  374. return
  375. }
  376. ctx.Data["ClosedMilestones"], _, err = models.GetMilestones(models.GetMilestonesOption{
  377. RepoID: repo.ID,
  378. State: api.StateClosed,
  379. })
  380. if err != nil {
  381. ctx.ServerError("GetMilestones", err)
  382. return
  383. }
  384. ctx.Data["Assignees"], err = repo.GetAssignees()
  385. if err != nil {
  386. ctx.ServerError("GetAssignees", err)
  387. return
  388. }
  389. handleTeamMentions(ctx)
  390. }
  391. func retrieveProjects(ctx *context.Context, repo *models.Repository) {
  392. var err error
  393. ctx.Data["OpenProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  394. RepoID: repo.ID,
  395. Page: -1,
  396. IsClosed: util.OptionalBoolFalse,
  397. Type: models.ProjectTypeRepository,
  398. })
  399. if err != nil {
  400. ctx.ServerError("GetProjects", err)
  401. return
  402. }
  403. ctx.Data["ClosedProjects"], _, err = models.GetProjects(models.ProjectSearchOptions{
  404. RepoID: repo.ID,
  405. Page: -1,
  406. IsClosed: util.OptionalBoolTrue,
  407. Type: models.ProjectTypeRepository,
  408. })
  409. if err != nil {
  410. ctx.ServerError("GetProjects", err)
  411. return
  412. }
  413. }
  414. // repoReviewerSelection items to bee shown
  415. type repoReviewerSelection struct {
  416. IsTeam bool
  417. Team *models.Team
  418. User *user_model.User
  419. Review *models.Review
  420. CanChange bool
  421. Checked bool
  422. ItemID int64
  423. }
  424. // RetrieveRepoReviewers find all reviewers of a repository
  425. func RetrieveRepoReviewers(ctx *context.Context, repo *models.Repository, issue *models.Issue, canChooseReviewer bool) {
  426. ctx.Data["CanChooseReviewer"] = canChooseReviewer
  427. originalAuthorReviews, err := models.GetReviewersFromOriginalAuthorsByIssueID(issue.ID)
  428. if err != nil {
  429. ctx.ServerError("GetReviewersFromOriginalAuthorsByIssueID", err)
  430. return
  431. }
  432. ctx.Data["OriginalReviews"] = originalAuthorReviews
  433. reviews, err := models.GetReviewersByIssueID(issue.ID)
  434. if err != nil {
  435. ctx.ServerError("GetReviewersByIssueID", err)
  436. return
  437. }
  438. if len(reviews) == 0 && !canChooseReviewer {
  439. return
  440. }
  441. var (
  442. pullReviews []*repoReviewerSelection
  443. reviewersResult []*repoReviewerSelection
  444. teamReviewersResult []*repoReviewerSelection
  445. teamReviewers []*models.Team
  446. reviewers []*user_model.User
  447. )
  448. if canChooseReviewer {
  449. posterID := issue.PosterID
  450. if issue.OriginalAuthorID > 0 {
  451. posterID = 0
  452. }
  453. reviewers, err = repo.GetReviewers(ctx.User.ID, posterID)
  454. if err != nil {
  455. ctx.ServerError("GetReviewers", err)
  456. return
  457. }
  458. teamReviewers, err = repo.GetReviewerTeams()
  459. if err != nil {
  460. ctx.ServerError("GetReviewerTeams", err)
  461. return
  462. }
  463. if len(reviewers) > 0 {
  464. reviewersResult = make([]*repoReviewerSelection, 0, len(reviewers))
  465. }
  466. if len(teamReviewers) > 0 {
  467. teamReviewersResult = make([]*repoReviewerSelection, 0, len(teamReviewers))
  468. }
  469. }
  470. pullReviews = make([]*repoReviewerSelection, 0, len(reviews))
  471. for _, review := range reviews {
  472. tmp := &repoReviewerSelection{
  473. Checked: review.Type == models.ReviewTypeRequest,
  474. Review: review,
  475. ItemID: review.ReviewerID,
  476. }
  477. if review.ReviewerTeamID > 0 {
  478. tmp.IsTeam = true
  479. tmp.ItemID = -review.ReviewerTeamID
  480. }
  481. if ctx.Repo.IsAdmin() {
  482. // Admin can dismiss or re-request any review requests
  483. tmp.CanChange = true
  484. } else if ctx.User != nil && ctx.User.ID == review.ReviewerID && review.Type == models.ReviewTypeRequest {
  485. // A user can refuse review requests
  486. tmp.CanChange = true
  487. } else if (canChooseReviewer || (ctx.User != nil && ctx.User.ID == issue.PosterID)) && review.Type != models.ReviewTypeRequest &&
  488. ctx.User.ID != review.ReviewerID {
  489. // The poster of the PR, a manager, or official reviewers can re-request review from other reviewers
  490. tmp.CanChange = true
  491. }
  492. pullReviews = append(pullReviews, tmp)
  493. if canChooseReviewer {
  494. if tmp.IsTeam {
  495. teamReviewersResult = append(teamReviewersResult, tmp)
  496. } else {
  497. reviewersResult = append(reviewersResult, tmp)
  498. }
  499. }
  500. }
  501. if len(pullReviews) > 0 {
  502. // Drop all non-existing users and teams from the reviews
  503. currentPullReviewers := make([]*repoReviewerSelection, 0, len(pullReviews))
  504. for _, item := range pullReviews {
  505. if item.Review.ReviewerID > 0 {
  506. if err = item.Review.LoadReviewer(); err != nil {
  507. if user_model.IsErrUserNotExist(err) {
  508. continue
  509. }
  510. ctx.ServerError("LoadReviewer", err)
  511. return
  512. }
  513. item.User = item.Review.Reviewer
  514. } else if item.Review.ReviewerTeamID > 0 {
  515. if err = item.Review.LoadReviewerTeam(); err != nil {
  516. if models.IsErrTeamNotExist(err) {
  517. continue
  518. }
  519. ctx.ServerError("LoadReviewerTeam", err)
  520. return
  521. }
  522. item.Team = item.Review.ReviewerTeam
  523. } else {
  524. continue
  525. }
  526. currentPullReviewers = append(currentPullReviewers, item)
  527. }
  528. ctx.Data["PullReviewers"] = currentPullReviewers
  529. }
  530. if canChooseReviewer && reviewersResult != nil {
  531. preadded := len(reviewersResult)
  532. for _, reviewer := range reviewers {
  533. found := false
  534. reviewAddLoop:
  535. for _, tmp := range reviewersResult[:preadded] {
  536. if tmp.ItemID == reviewer.ID {
  537. tmp.User = reviewer
  538. found = true
  539. break reviewAddLoop
  540. }
  541. }
  542. if found {
  543. continue
  544. }
  545. reviewersResult = append(reviewersResult, &repoReviewerSelection{
  546. IsTeam: false,
  547. CanChange: true,
  548. User: reviewer,
  549. ItemID: reviewer.ID,
  550. })
  551. }
  552. ctx.Data["Reviewers"] = reviewersResult
  553. }
  554. if canChooseReviewer && teamReviewersResult != nil {
  555. preadded := len(teamReviewersResult)
  556. for _, team := range teamReviewers {
  557. found := false
  558. teamReviewAddLoop:
  559. for _, tmp := range teamReviewersResult[:preadded] {
  560. if tmp.ItemID == -team.ID {
  561. tmp.Team = team
  562. found = true
  563. break teamReviewAddLoop
  564. }
  565. }
  566. if found {
  567. continue
  568. }
  569. teamReviewersResult = append(teamReviewersResult, &repoReviewerSelection{
  570. IsTeam: true,
  571. CanChange: true,
  572. Team: team,
  573. ItemID: -team.ID,
  574. })
  575. }
  576. ctx.Data["TeamReviewers"] = teamReviewersResult
  577. }
  578. }
  579. // RetrieveRepoMetas find all the meta information of a repository
  580. func RetrieveRepoMetas(ctx *context.Context, repo *models.Repository, isPull bool) []*models.Label {
  581. if !ctx.Repo.CanWriteIssuesOrPulls(isPull) {
  582. return nil
  583. }
  584. labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
  585. if err != nil {
  586. ctx.ServerError("GetLabelsByRepoID", err)
  587. return nil
  588. }
  589. ctx.Data["Labels"] = labels
  590. if repo.Owner.IsOrganization() {
  591. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
  592. if err != nil {
  593. return nil
  594. }
  595. ctx.Data["OrgLabels"] = orgLabels
  596. labels = append(labels, orgLabels...)
  597. }
  598. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  599. if ctx.Written() {
  600. return nil
  601. }
  602. retrieveProjects(ctx, repo)
  603. if ctx.Written() {
  604. return nil
  605. }
  606. brs, _, err := ctx.Repo.GitRepo.GetBranches(0, 0)
  607. if err != nil {
  608. ctx.ServerError("GetBranches", err)
  609. return nil
  610. }
  611. ctx.Data["Branches"] = brs
  612. // Contains true if the user can create issue dependencies
  613. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, isPull)
  614. return labels
  615. }
  616. func getFileContentFromDefaultBranch(ctx *context.Context, filename string) (string, bool) {
  617. var bytes []byte
  618. if ctx.Repo.Commit == nil {
  619. var err error
  620. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(ctx.Repo.Repository.DefaultBranch)
  621. if err != nil {
  622. return "", false
  623. }
  624. }
  625. entry, err := ctx.Repo.Commit.GetTreeEntryByPath(filename)
  626. if err != nil {
  627. return "", false
  628. }
  629. if entry.Blob().Size() >= setting.UI.MaxDisplayFileSize {
  630. return "", false
  631. }
  632. r, err := entry.Blob().DataAsync()
  633. if err != nil {
  634. return "", false
  635. }
  636. defer r.Close()
  637. bytes, err = io.ReadAll(r)
  638. if err != nil {
  639. return "", false
  640. }
  641. return string(bytes), true
  642. }
  643. func setTemplateIfExists(ctx *context.Context, ctxDataKey string, possibleDirs []string, possibleFiles []string) {
  644. templateCandidates := make([]string, 0, len(possibleFiles))
  645. if ctx.FormString("template") != "" {
  646. for _, dirName := range possibleDirs {
  647. templateCandidates = append(templateCandidates, path.Join(dirName, ctx.FormString("template")))
  648. }
  649. }
  650. templateCandidates = append(templateCandidates, possibleFiles...) // Append files to the end because they should be fallback
  651. for _, filename := range templateCandidates {
  652. templateContent, found := getFileContentFromDefaultBranch(ctx, filename)
  653. if found {
  654. var meta api.IssueTemplate
  655. templateBody, err := markdown.ExtractMetadata(templateContent, &meta)
  656. if err != nil {
  657. log.Debug("could not extract metadata from %s [%s]: %v", filename, ctx.Repo.Repository.FullName(), err)
  658. ctx.Data[ctxDataKey] = templateContent
  659. return
  660. }
  661. ctx.Data[issueTemplateTitleKey] = meta.Title
  662. ctx.Data[ctxDataKey] = templateBody
  663. labelIDs := make([]string, 0, len(meta.Labels))
  664. if repoLabels, err := models.GetLabelsByRepoID(ctx.Repo.Repository.ID, "", db.ListOptions{}); err == nil {
  665. ctx.Data["Labels"] = repoLabels
  666. if ctx.Repo.Owner.IsOrganization() {
  667. if orgLabels, err := models.GetLabelsByOrgID(ctx.Repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{}); err == nil {
  668. ctx.Data["OrgLabels"] = orgLabels
  669. repoLabels = append(repoLabels, orgLabels...)
  670. }
  671. }
  672. for _, metaLabel := range meta.Labels {
  673. for _, repoLabel := range repoLabels {
  674. if strings.EqualFold(repoLabel.Name, metaLabel) {
  675. repoLabel.IsChecked = true
  676. labelIDs = append(labelIDs, strconv.FormatInt(repoLabel.ID, 10))
  677. break
  678. }
  679. }
  680. }
  681. }
  682. ctx.Data["HasSelectedLabel"] = len(labelIDs) > 0
  683. ctx.Data["label_ids"] = strings.Join(labelIDs, ",")
  684. return
  685. }
  686. }
  687. }
  688. // NewIssue render creating issue page
  689. func NewIssue(ctx *context.Context) {
  690. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  691. ctx.Data["PageIsIssueList"] = true
  692. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  693. ctx.Data["RequireHighlightJS"] = true
  694. ctx.Data["RequireSimpleMDE"] = true
  695. ctx.Data["RequireTribute"] = true
  696. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  697. title := ctx.FormString("title")
  698. ctx.Data["TitleQuery"] = title
  699. body := ctx.FormString("body")
  700. ctx.Data["BodyQuery"] = body
  701. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(unit.TypeProjects)
  702. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  703. upload.AddUploadContext(ctx, "comment")
  704. milestoneID := ctx.FormInt64("milestone")
  705. if milestoneID > 0 {
  706. milestone, err := models.GetMilestoneByID(milestoneID)
  707. if err != nil {
  708. log.Error("GetMilestoneByID: %d: %v", milestoneID, err)
  709. } else {
  710. ctx.Data["milestone_id"] = milestoneID
  711. ctx.Data["Milestone"] = milestone
  712. }
  713. }
  714. projectID := ctx.FormInt64("project")
  715. if projectID > 0 {
  716. project, err := models.GetProjectByID(projectID)
  717. if err != nil {
  718. log.Error("GetProjectByID: %d: %v", projectID, err)
  719. } else if project.RepoID != ctx.Repo.Repository.ID {
  720. log.Error("GetProjectByID: %d: %v", projectID, fmt.Errorf("project[%d] not in repo [%d]", project.ID, ctx.Repo.Repository.ID))
  721. } else {
  722. ctx.Data["project_id"] = projectID
  723. ctx.Data["Project"] = project
  724. }
  725. if len(ctx.Req.URL.Query().Get("project")) > 0 {
  726. ctx.Data["redirect_after_creation"] = "project"
  727. }
  728. }
  729. RetrieveRepoMetas(ctx, ctx.Repo.Repository, false)
  730. setTemplateIfExists(ctx, issueTemplateKey, context.IssueTemplateDirCandidates, IssueTemplateCandidates)
  731. if ctx.Written() {
  732. return
  733. }
  734. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWrite(unit.TypeIssues)
  735. ctx.HTML(http.StatusOK, tplIssueNew)
  736. }
  737. // NewIssueChooseTemplate render creating issue from template page
  738. func NewIssueChooseTemplate(ctx *context.Context) {
  739. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  740. ctx.Data["PageIsIssueList"] = true
  741. ctx.Data["milestone"] = ctx.FormInt64("milestone")
  742. issueTemplates := ctx.IssueTemplatesFromDefaultBranch()
  743. ctx.Data["NewIssueChooseTemplate"] = len(issueTemplates) > 0
  744. ctx.Data["IssueTemplates"] = issueTemplates
  745. ctx.HTML(http.StatusOK, tplIssueChoose)
  746. }
  747. // ValidateRepoMetas check and returns repository's meta information
  748. func ValidateRepoMetas(ctx *context.Context, form forms.CreateIssueForm, isPull bool) ([]int64, []int64, int64, int64) {
  749. var (
  750. repo = ctx.Repo.Repository
  751. err error
  752. )
  753. labels := RetrieveRepoMetas(ctx, ctx.Repo.Repository, isPull)
  754. if ctx.Written() {
  755. return nil, nil, 0, 0
  756. }
  757. var labelIDs []int64
  758. hasSelected := false
  759. // Check labels.
  760. if len(form.LabelIDs) > 0 {
  761. labelIDs, err = base.StringsToInt64s(strings.Split(form.LabelIDs, ","))
  762. if err != nil {
  763. return nil, nil, 0, 0
  764. }
  765. labelIDMark := base.Int64sToMap(labelIDs)
  766. for i := range labels {
  767. if labelIDMark[labels[i].ID] {
  768. labels[i].IsChecked = true
  769. hasSelected = true
  770. }
  771. }
  772. }
  773. ctx.Data["Labels"] = labels
  774. ctx.Data["HasSelectedLabel"] = hasSelected
  775. ctx.Data["label_ids"] = form.LabelIDs
  776. // Check milestone.
  777. milestoneID := form.MilestoneID
  778. if milestoneID > 0 {
  779. ctx.Data["Milestone"], err = repo.GetMilestoneByID(milestoneID)
  780. if err != nil {
  781. ctx.ServerError("GetMilestoneByID", err)
  782. return nil, nil, 0, 0
  783. }
  784. ctx.Data["milestone_id"] = milestoneID
  785. }
  786. if form.ProjectID > 0 {
  787. p, err := models.GetProjectByID(form.ProjectID)
  788. if err != nil {
  789. ctx.ServerError("GetProjectByID", err)
  790. return nil, nil, 0, 0
  791. }
  792. if p.RepoID != ctx.Repo.Repository.ID {
  793. ctx.NotFound("", nil)
  794. return nil, nil, 0, 0
  795. }
  796. ctx.Data["Project"] = p
  797. ctx.Data["project_id"] = form.ProjectID
  798. }
  799. // Check assignees
  800. var assigneeIDs []int64
  801. if len(form.AssigneeIDs) > 0 {
  802. assigneeIDs, err = base.StringsToInt64s(strings.Split(form.AssigneeIDs, ","))
  803. if err != nil {
  804. return nil, nil, 0, 0
  805. }
  806. // Check if the passed assignees actually exists and is assignable
  807. for _, aID := range assigneeIDs {
  808. assignee, err := user_model.GetUserByID(aID)
  809. if err != nil {
  810. ctx.ServerError("GetUserByID", err)
  811. return nil, nil, 0, 0
  812. }
  813. valid, err := models.CanBeAssigned(assignee, repo, isPull)
  814. if err != nil {
  815. ctx.ServerError("CanBeAssigned", err)
  816. return nil, nil, 0, 0
  817. }
  818. if !valid {
  819. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: aID, RepoName: repo.Name})
  820. return nil, nil, 0, 0
  821. }
  822. }
  823. }
  824. // Keep the old assignee id thingy for compatibility reasons
  825. if form.AssigneeID > 0 {
  826. assigneeIDs = append(assigneeIDs, form.AssigneeID)
  827. }
  828. return labelIDs, assigneeIDs, milestoneID, form.ProjectID
  829. }
  830. // NewIssuePost response for creating new issue
  831. func NewIssuePost(ctx *context.Context) {
  832. form := web.GetForm(ctx).(*forms.CreateIssueForm)
  833. ctx.Data["Title"] = ctx.Tr("repo.issues.new")
  834. ctx.Data["PageIsIssueList"] = true
  835. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  836. ctx.Data["RequireHighlightJS"] = true
  837. ctx.Data["RequireSimpleMDE"] = true
  838. ctx.Data["PullRequestWorkInProgressPrefixes"] = setting.Repository.PullRequest.WorkInProgressPrefixes
  839. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  840. upload.AddUploadContext(ctx, "comment")
  841. var (
  842. repo = ctx.Repo.Repository
  843. attachments []string
  844. )
  845. labelIDs, assigneeIDs, milestoneID, projectID := ValidateRepoMetas(ctx, *form, false)
  846. if ctx.Written() {
  847. return
  848. }
  849. if setting.Attachment.Enabled {
  850. attachments = form.Files
  851. }
  852. if ctx.HasError() {
  853. ctx.HTML(http.StatusOK, tplIssueNew)
  854. return
  855. }
  856. if util.IsEmptyString(form.Title) {
  857. ctx.RenderWithErr(ctx.Tr("repo.issues.new.title_empty"), tplIssueNew, form)
  858. return
  859. }
  860. issue := &models.Issue{
  861. RepoID: repo.ID,
  862. Repo: repo,
  863. Title: form.Title,
  864. PosterID: ctx.User.ID,
  865. Poster: ctx.User,
  866. MilestoneID: milestoneID,
  867. Content: form.Content,
  868. Ref: form.Ref,
  869. }
  870. if err := issue_service.NewIssue(repo, issue, labelIDs, attachments, assigneeIDs); err != nil {
  871. if models.IsErrUserDoesNotHaveAccessToRepo(err) {
  872. ctx.Error(http.StatusBadRequest, "UserDoesNotHaveAccessToRepo", err.Error())
  873. return
  874. }
  875. ctx.ServerError("NewIssue", err)
  876. return
  877. }
  878. if projectID > 0 {
  879. if err := models.ChangeProjectAssign(issue, ctx.User, projectID); err != nil {
  880. ctx.ServerError("ChangeProjectAssign", err)
  881. return
  882. }
  883. }
  884. log.Trace("Issue created: %d/%d", repo.ID, issue.ID)
  885. if ctx.FormString("redirect_after_creation") == "project" {
  886. ctx.Redirect(ctx.Repo.RepoLink + "/projects/" + strconv.FormatInt(form.ProjectID, 10))
  887. } else {
  888. ctx.Redirect(issue.Link())
  889. }
  890. }
  891. // roleDescriptor returns the Role Decriptor for a comment in/with the given repo, poster and issue
  892. func roleDescriptor(repo *models.Repository, poster *user_model.User, issue *models.Issue) (models.RoleDescriptor, error) {
  893. perm, err := models.GetUserRepoPermission(repo, poster)
  894. if err != nil {
  895. return models.RoleDescriptorNone, err
  896. }
  897. // By default the poster has no roles on the comment.
  898. roleDescriptor := models.RoleDescriptorNone
  899. // Check if the poster is owner of the repo.
  900. if perm.IsOwner() {
  901. // If the poster isn't a admin, enable the owner role.
  902. if !poster.IsAdmin {
  903. roleDescriptor = roleDescriptor.WithRole(models.RoleDescriptorOwner)
  904. } else {
  905. // Otherwise check if poster is the real repo admin.
  906. ok, err := models.IsUserRealRepoAdmin(repo, poster)
  907. if err != nil {
  908. return models.RoleDescriptorNone, err
  909. }
  910. if ok {
  911. roleDescriptor = roleDescriptor.WithRole(models.RoleDescriptorOwner)
  912. }
  913. }
  914. }
  915. // Is the poster can write issues or pulls to the repo, enable the Writer role.
  916. // Only enable this if the poster doesn't have the owner role already.
  917. if !roleDescriptor.HasRole("Owner") && perm.CanWriteIssuesOrPulls(issue.IsPull) {
  918. roleDescriptor = roleDescriptor.WithRole(models.RoleDescriptorWriter)
  919. }
  920. // If the poster is the actual poster of the issue, enable Poster role.
  921. if issue.IsPoster(poster.ID) {
  922. roleDescriptor = roleDescriptor.WithRole(models.RoleDescriptorPoster)
  923. }
  924. return roleDescriptor, nil
  925. }
  926. func getBranchData(ctx *context.Context, issue *models.Issue) {
  927. ctx.Data["BaseBranch"] = nil
  928. ctx.Data["HeadBranch"] = nil
  929. ctx.Data["HeadUserName"] = nil
  930. ctx.Data["BaseName"] = ctx.Repo.Repository.OwnerName
  931. if issue.IsPull {
  932. pull := issue.PullRequest
  933. ctx.Data["BaseBranch"] = pull.BaseBranch
  934. ctx.Data["HeadBranch"] = pull.HeadBranch
  935. ctx.Data["HeadUserName"] = pull.MustHeadUserName()
  936. }
  937. }
  938. // ViewIssue render issue view page
  939. func ViewIssue(ctx *context.Context) {
  940. if ctx.Params(":type") == "issues" {
  941. // If issue was requested we check if repo has external tracker and redirect
  942. extIssueUnit, err := ctx.Repo.Repository.GetUnit(unit.TypeExternalTracker)
  943. if err == nil && extIssueUnit != nil {
  944. if extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == markup.IssueNameStyleNumeric || extIssueUnit.ExternalTrackerConfig().ExternalTrackerStyle == "" {
  945. metas := ctx.Repo.Repository.ComposeMetas()
  946. metas["index"] = ctx.Params(":index")
  947. ctx.Redirect(com.Expand(extIssueUnit.ExternalTrackerConfig().ExternalTrackerFormat, metas))
  948. return
  949. }
  950. } else if err != nil && !models.IsErrUnitTypeNotExist(err) {
  951. ctx.ServerError("GetUnit", err)
  952. return
  953. }
  954. }
  955. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  956. if err != nil {
  957. if models.IsErrIssueNotExist(err) {
  958. ctx.NotFound("GetIssueByIndex", err)
  959. } else {
  960. ctx.ServerError("GetIssueByIndex", err)
  961. }
  962. return
  963. }
  964. if issue.Repo == nil {
  965. issue.Repo = ctx.Repo.Repository
  966. }
  967. // Make sure type and URL matches.
  968. if ctx.Params(":type") == "issues" && issue.IsPull {
  969. ctx.Redirect(issue.Link())
  970. return
  971. } else if ctx.Params(":type") == "pulls" && !issue.IsPull {
  972. ctx.Redirect(issue.Link())
  973. return
  974. }
  975. if issue.IsPull {
  976. MustAllowPulls(ctx)
  977. if ctx.Written() {
  978. return
  979. }
  980. ctx.Data["PageIsPullList"] = true
  981. ctx.Data["PageIsPullConversation"] = true
  982. } else {
  983. MustEnableIssues(ctx)
  984. if ctx.Written() {
  985. return
  986. }
  987. ctx.Data["PageIsIssueList"] = true
  988. ctx.Data["NewIssueChooseTemplate"] = len(ctx.IssueTemplatesFromDefaultBranch()) > 0
  989. }
  990. if issue.IsPull && !ctx.Repo.CanRead(unit.TypeIssues) {
  991. ctx.Data["IssueType"] = "pulls"
  992. } else if !issue.IsPull && !ctx.Repo.CanRead(unit.TypePullRequests) {
  993. ctx.Data["IssueType"] = "issues"
  994. } else {
  995. ctx.Data["IssueType"] = "all"
  996. }
  997. ctx.Data["RequireHighlightJS"] = true
  998. ctx.Data["RequireTribute"] = true
  999. ctx.Data["RequireSimpleMDE"] = true
  1000. ctx.Data["IsProjectsEnabled"] = ctx.Repo.CanRead(unit.TypeProjects)
  1001. ctx.Data["IsAttachmentEnabled"] = setting.Attachment.Enabled
  1002. upload.AddUploadContext(ctx, "comment")
  1003. if err = issue.LoadAttributes(); err != nil {
  1004. ctx.ServerError("LoadAttributes", err)
  1005. return
  1006. }
  1007. if err = filterXRefComments(ctx, issue); err != nil {
  1008. ctx.ServerError("filterXRefComments", err)
  1009. return
  1010. }
  1011. ctx.Data["Title"] = fmt.Sprintf("#%d - %s", issue.Index, issue.Title)
  1012. iw := new(models.IssueWatch)
  1013. if ctx.User != nil {
  1014. iw.UserID = ctx.User.ID
  1015. iw.IssueID = issue.ID
  1016. iw.IsWatching, err = models.CheckIssueWatch(ctx.User, issue)
  1017. if err != nil {
  1018. ctx.ServerError("CheckIssueWatch", err)
  1019. return
  1020. }
  1021. }
  1022. ctx.Data["IssueWatch"] = iw
  1023. issue.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  1024. URLPrefix: ctx.Repo.RepoLink,
  1025. Metas: ctx.Repo.Repository.ComposeMetas(),
  1026. GitRepo: ctx.Repo.GitRepo,
  1027. Ctx: ctx,
  1028. }, issue.Content)
  1029. if err != nil {
  1030. ctx.ServerError("RenderString", err)
  1031. return
  1032. }
  1033. repo := ctx.Repo.Repository
  1034. // Get more information if it's a pull request.
  1035. if issue.IsPull {
  1036. if issue.PullRequest.HasMerged {
  1037. ctx.Data["DisableStatusChange"] = issue.PullRequest.HasMerged
  1038. PrepareMergedViewPullInfo(ctx, issue)
  1039. } else {
  1040. PrepareViewPullInfo(ctx, issue)
  1041. ctx.Data["DisableStatusChange"] = ctx.Data["IsPullRequestBroken"] == true && issue.IsClosed
  1042. }
  1043. if ctx.Written() {
  1044. return
  1045. }
  1046. }
  1047. // Metas.
  1048. // Check labels.
  1049. labelIDMark := make(map[int64]bool)
  1050. for i := range issue.Labels {
  1051. labelIDMark[issue.Labels[i].ID] = true
  1052. }
  1053. labels, err := models.GetLabelsByRepoID(repo.ID, "", db.ListOptions{})
  1054. if err != nil {
  1055. ctx.ServerError("GetLabelsByRepoID", err)
  1056. return
  1057. }
  1058. ctx.Data["Labels"] = labels
  1059. if repo.Owner.IsOrganization() {
  1060. orgLabels, err := models.GetLabelsByOrgID(repo.Owner.ID, ctx.FormString("sort"), db.ListOptions{})
  1061. if err != nil {
  1062. ctx.ServerError("GetLabelsByOrgID", err)
  1063. return
  1064. }
  1065. ctx.Data["OrgLabels"] = orgLabels
  1066. labels = append(labels, orgLabels...)
  1067. }
  1068. hasSelected := false
  1069. for i := range labels {
  1070. if labelIDMark[labels[i].ID] {
  1071. labels[i].IsChecked = true
  1072. hasSelected = true
  1073. }
  1074. }
  1075. ctx.Data["HasSelectedLabel"] = hasSelected
  1076. // Check milestone and assignee.
  1077. if ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) {
  1078. RetrieveRepoMilestonesAndAssignees(ctx, repo)
  1079. retrieveProjects(ctx, repo)
  1080. if ctx.Written() {
  1081. return
  1082. }
  1083. }
  1084. if issue.IsPull {
  1085. canChooseReviewer := ctx.Repo.CanWrite(unit.TypePullRequests)
  1086. if !canChooseReviewer && ctx.User != nil && ctx.IsSigned {
  1087. canChooseReviewer, err = models.IsOfficialReviewer(issue, ctx.User)
  1088. if err != nil {
  1089. ctx.ServerError("IsOfficialReviewer", err)
  1090. return
  1091. }
  1092. }
  1093. RetrieveRepoReviewers(ctx, repo, issue, canChooseReviewer)
  1094. if ctx.Written() {
  1095. return
  1096. }
  1097. }
  1098. if ctx.IsSigned {
  1099. // Update issue-user.
  1100. if err = issue.ReadBy(ctx.User.ID); err != nil {
  1101. ctx.ServerError("ReadBy", err)
  1102. return
  1103. }
  1104. }
  1105. var (
  1106. role models.RoleDescriptor
  1107. ok bool
  1108. marked = make(map[int64]models.RoleDescriptor)
  1109. comment *models.Comment
  1110. participants = make([]*user_model.User, 1, 10)
  1111. )
  1112. if ctx.Repo.Repository.IsTimetrackerEnabled() {
  1113. if ctx.IsSigned {
  1114. // Deal with the stopwatch
  1115. ctx.Data["IsStopwatchRunning"] = models.StopwatchExists(ctx.User.ID, issue.ID)
  1116. if !ctx.Data["IsStopwatchRunning"].(bool) {
  1117. var exists bool
  1118. var sw *models.Stopwatch
  1119. if exists, sw, err = models.HasUserStopwatch(ctx.User.ID); err != nil {
  1120. ctx.ServerError("HasUserStopwatch", err)
  1121. return
  1122. }
  1123. ctx.Data["HasUserStopwatch"] = exists
  1124. if exists {
  1125. // Add warning if the user has already a stopwatch
  1126. var otherIssue *models.Issue
  1127. if otherIssue, err = models.GetIssueByID(sw.IssueID); err != nil {
  1128. ctx.ServerError("GetIssueByID", err)
  1129. return
  1130. }
  1131. if err = otherIssue.LoadRepo(); err != nil {
  1132. ctx.ServerError("LoadRepo", err)
  1133. return
  1134. }
  1135. // Add link to the issue of the already running stopwatch
  1136. ctx.Data["OtherStopwatchURL"] = otherIssue.HTMLURL()
  1137. }
  1138. }
  1139. ctx.Data["CanUseTimetracker"] = ctx.Repo.CanUseTimetracker(issue, ctx.User)
  1140. } else {
  1141. ctx.Data["CanUseTimetracker"] = false
  1142. }
  1143. if ctx.Data["WorkingUsers"], err = models.TotalTimes(&models.FindTrackedTimesOptions{IssueID: issue.ID}); err != nil {
  1144. ctx.ServerError("TotalTimes", err)
  1145. return
  1146. }
  1147. }
  1148. // Check if the user can use the dependencies
  1149. ctx.Data["CanCreateIssueDependencies"] = ctx.Repo.CanCreateIssueDependencies(ctx.User, issue.IsPull)
  1150. // check if dependencies can be created across repositories
  1151. ctx.Data["AllowCrossRepositoryDependencies"] = setting.Service.AllowCrossRepositoryDependencies
  1152. if issue.ShowRole, err = roleDescriptor(repo, issue.Poster, issue); err != nil {
  1153. ctx.ServerError("roleDescriptor", err)
  1154. return
  1155. }
  1156. marked[issue.PosterID] = issue.ShowRole
  1157. // Render comments and and fetch participants.
  1158. participants[0] = issue.Poster
  1159. for _, comment = range issue.Comments {
  1160. comment.Issue = issue
  1161. if err := comment.LoadPoster(); err != nil {
  1162. ctx.ServerError("LoadPoster", err)
  1163. return
  1164. }
  1165. if comment.Type == models.CommentTypeComment {
  1166. if err := comment.LoadAttachments(); err != nil {
  1167. ctx.ServerError("LoadAttachments", err)
  1168. return
  1169. }
  1170. comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  1171. URLPrefix: ctx.Repo.RepoLink,
  1172. Metas: ctx.Repo.Repository.ComposeMetas(),
  1173. GitRepo: ctx.Repo.GitRepo,
  1174. Ctx: ctx,
  1175. }, comment.Content)
  1176. if err != nil {
  1177. ctx.ServerError("RenderString", err)
  1178. return
  1179. }
  1180. // Check tag.
  1181. role, ok = marked[comment.PosterID]
  1182. if ok {
  1183. comment.ShowRole = role
  1184. continue
  1185. }
  1186. comment.ShowRole, err = roleDescriptor(repo, comment.Poster, issue)
  1187. if err != nil {
  1188. ctx.ServerError("roleDescriptor", err)
  1189. return
  1190. }
  1191. marked[comment.PosterID] = comment.ShowRole
  1192. participants = addParticipant(comment.Poster, participants)
  1193. } else if comment.Type == models.CommentTypeLabel {
  1194. if err = comment.LoadLabel(); err != nil {
  1195. ctx.ServerError("LoadLabel", err)
  1196. return
  1197. }
  1198. } else if comment.Type == models.CommentTypeMilestone {
  1199. if err = comment.LoadMilestone(); err != nil {
  1200. ctx.ServerError("LoadMilestone", err)
  1201. return
  1202. }
  1203. ghostMilestone := &models.Milestone{
  1204. ID: -1,
  1205. Name: ctx.Tr("repo.issues.deleted_milestone"),
  1206. }
  1207. if comment.OldMilestoneID > 0 && comment.OldMilestone == nil {
  1208. comment.OldMilestone = ghostMilestone
  1209. }
  1210. if comment.MilestoneID > 0 && comment.Milestone == nil {
  1211. comment.Milestone = ghostMilestone
  1212. }
  1213. } else if comment.Type == models.CommentTypeProject {
  1214. if err = comment.LoadProject(); err != nil {
  1215. ctx.ServerError("LoadProject", err)
  1216. return
  1217. }
  1218. ghostProject := &models.Project{
  1219. ID: -1,
  1220. Title: ctx.Tr("repo.issues.deleted_project"),
  1221. }
  1222. if comment.OldProjectID > 0 && comment.OldProject == nil {
  1223. comment.OldProject = ghostProject
  1224. }
  1225. if comment.ProjectID > 0 && comment.Project == nil {
  1226. comment.Project = ghostProject
  1227. }
  1228. } else if comment.Type == models.CommentTypeAssignees || comment.Type == models.CommentTypeReviewRequest {
  1229. if err = comment.LoadAssigneeUserAndTeam(); err != nil {
  1230. ctx.ServerError("LoadAssigneeUserAndTeam", err)
  1231. return
  1232. }
  1233. } else if comment.Type == models.CommentTypeRemoveDependency || comment.Type == models.CommentTypeAddDependency {
  1234. if err = comment.LoadDepIssueDetails(); err != nil {
  1235. if !models.IsErrIssueNotExist(err) {
  1236. ctx.ServerError("LoadDepIssueDetails", err)
  1237. return
  1238. }
  1239. }
  1240. } else if comment.Type == models.CommentTypeCode || comment.Type == models.CommentTypeReview || comment.Type == models.CommentTypeDismissReview {
  1241. comment.RenderedContent, err = markdown.RenderString(&markup.RenderContext{
  1242. URLPrefix: ctx.Repo.RepoLink,
  1243. Metas: ctx.Repo.Repository.ComposeMetas(),
  1244. GitRepo: ctx.Repo.GitRepo,
  1245. Ctx: ctx,
  1246. }, comment.Content)
  1247. if err != nil {
  1248. ctx.ServerError("RenderString", err)
  1249. return
  1250. }
  1251. if err = comment.LoadReview(); err != nil && !models.IsErrReviewNotExist(err) {
  1252. ctx.ServerError("LoadReview", err)
  1253. return
  1254. }
  1255. participants = addParticipant(comment.Poster, participants)
  1256. if comment.Review == nil {
  1257. continue
  1258. }
  1259. if err = comment.Review.LoadAttributes(); err != nil {
  1260. if !user_model.IsErrUserNotExist(err) {
  1261. ctx.ServerError("Review.LoadAttributes", err)
  1262. return
  1263. }
  1264. comment.Review.Reviewer = user_model.NewGhostUser()
  1265. }
  1266. if err = comment.Review.LoadCodeComments(); err != nil {
  1267. ctx.ServerError("Review.LoadCodeComments", err)
  1268. return
  1269. }
  1270. for _, codeComments := range comment.Review.CodeComments {
  1271. for _, lineComments := range codeComments {
  1272. for _, c := range lineComments {
  1273. // Check tag.
  1274. role, ok = marked[c.PosterID]
  1275. if ok {
  1276. c.ShowRole = role
  1277. continue
  1278. }
  1279. c.ShowRole, err = roleDescriptor(repo, c.Poster, issue)
  1280. if err != nil {
  1281. ctx.ServerError("roleDescriptor", err)
  1282. return
  1283. }
  1284. marked[c.PosterID] = c.ShowRole
  1285. participants = addParticipant(c.Poster, participants)
  1286. }
  1287. }
  1288. }
  1289. if err = comment.LoadResolveDoer(); err != nil {
  1290. ctx.ServerError("LoadResolveDoer", err)
  1291. return
  1292. }
  1293. } else if comment.Type == models.CommentTypePullPush {
  1294. participants = addParticipant(comment.Poster, participants)
  1295. if err = comment.LoadPushCommits(); err != nil {
  1296. ctx.ServerError("LoadPushCommits", err)
  1297. return
  1298. }
  1299. } else if comment.Type == models.CommentTypeAddTimeManual ||
  1300. comment.Type == models.CommentTypeStopTracking {
  1301. // drop error since times could be pruned from DB..
  1302. _ = comment.LoadTime()
  1303. }
  1304. }
  1305. // Combine multiple label assignments into a single comment
  1306. combineLabelComments(issue)
  1307. getBranchData(ctx, issue)
  1308. if issue.IsPull {
  1309. pull := issue.PullRequest
  1310. pull.Issue = issue
  1311. canDelete := false
  1312. ctx.Data["AllowMerge"] = false
  1313. if ctx.IsSigned {
  1314. if err := pull.LoadHeadRepo(); err != nil {
  1315. log.Error("LoadHeadRepo: %v", err)
  1316. } else if pull.HeadRepo != nil && pull.HeadBranch != pull.HeadRepo.DefaultBranch {
  1317. perm, err := models.GetUserRepoPermission(pull.HeadRepo, ctx.User)
  1318. if err != nil {
  1319. ctx.ServerError("GetUserRepoPermission", err)
  1320. return
  1321. }
  1322. if perm.CanWrite(unit.TypeCode) {
  1323. // Check if branch is not protected
  1324. if protected, err := pull.HeadRepo.IsProtectedBranch(pull.HeadBranch); err != nil {
  1325. log.Error("IsProtectedBranch: %v", err)
  1326. } else if !protected {
  1327. canDelete = true
  1328. ctx.Data["DeleteBranchLink"] = issue.Link() + "/cleanup"
  1329. }
  1330. }
  1331. }
  1332. if err := pull.LoadBaseRepo(); err != nil {
  1333. log.Error("LoadBaseRepo: %v", err)
  1334. }
  1335. perm, err := models.GetUserRepoPermission(pull.BaseRepo, ctx.User)
  1336. if err != nil {
  1337. ctx.ServerError("GetUserRepoPermission", err)
  1338. return
  1339. }
  1340. ctx.Data["AllowMerge"], err = pull_service.IsUserAllowedToMerge(pull, perm, ctx.User)
  1341. if err != nil {
  1342. ctx.ServerError("IsUserAllowedToMerge", err)
  1343. return
  1344. }
  1345. if ctx.Data["CanMarkConversation"], err = models.CanMarkConversation(issue, ctx.User); err != nil {
  1346. ctx.ServerError("CanMarkConversation", err)
  1347. return
  1348. }
  1349. }
  1350. prUnit, err := repo.GetUnit(unit.TypePullRequests)
  1351. if err != nil {
  1352. ctx.ServerError("GetUnit", err)
  1353. return
  1354. }
  1355. prConfig := prUnit.PullRequestsConfig()
  1356. // Check correct values and select default
  1357. if ms, ok := ctx.Data["MergeStyle"].(models.MergeStyle); !ok ||
  1358. !prConfig.IsMergeStyleAllowed(ms) {
  1359. defaultMergeStyle := prConfig.GetDefaultMergeStyle()
  1360. if prConfig.IsMergeStyleAllowed(defaultMergeStyle) && !ok {
  1361. ctx.Data["MergeStyle"] = defaultMergeStyle
  1362. } else if prConfig.AllowMerge {
  1363. ctx.Data["MergeStyle"] = models.MergeStyleMerge
  1364. } else if prConfig.AllowRebase {
  1365. ctx.Data["MergeStyle"] = models.MergeStyleRebase
  1366. } else if prConfig.AllowRebaseMerge {
  1367. ctx.Data["MergeStyle"] = models.MergeStyleRebaseMerge
  1368. } else if prConfig.AllowSquash {
  1369. ctx.Data["MergeStyle"] = models.MergeStyleSquash
  1370. } else if prConfig.AllowManualMerge {
  1371. ctx.Data["MergeStyle"] = models.MergeStyleManuallyMerged
  1372. } else {
  1373. ctx.Data["MergeStyle"] = ""
  1374. }
  1375. }
  1376. if err = pull.LoadProtectedBranch(); err != nil {
  1377. ctx.ServerError("LoadProtectedBranch", err)
  1378. return
  1379. }
  1380. ctx.Data["ShowMergeInstructions"] = true
  1381. if pull.ProtectedBranch != nil {
  1382. var showMergeInstructions bool
  1383. if ctx.User != nil {
  1384. showMergeInstructions = pull.ProtectedBranch.CanUserPush(ctx.User.ID)
  1385. }
  1386. cnt := pull.ProtectedBranch.GetGrantedApprovalsCount(pull)
  1387. ctx.Data["IsBlockedByApprovals"] = !pull.ProtectedBranch.HasEnoughApprovals(pull)
  1388. ctx.Data["IsBlockedByRejection"] = pull.ProtectedBranch.MergeBlockedByRejectedReview(pull)
  1389. ctx.Data["IsBlockedByOfficialReviewRequests"] = pull.ProtectedBranch.MergeBlockedByOfficialReviewRequests(pull)
  1390. ctx.Data["IsBlockedByOutdatedBranch"] = pull.ProtectedBranch.MergeBlockedByOutdatedBranch(pull)
  1391. ctx.Data["GrantedApprovals"] = cnt
  1392. ctx.Data["RequireSigned"] = pull.ProtectedBranch.RequireSignedCommits
  1393. ctx.Data["ChangedProtectedFiles"] = pull.ChangedProtectedFiles
  1394. ctx.Data["IsBlockedByChangedProtectedFiles"] = len(pull.ChangedProtectedFiles) != 0
  1395. ctx.Data["ChangedProtectedFilesNum"] = len(pull.ChangedProtectedFiles)
  1396. ctx.Data["ShowMergeInstructions"] = showMergeInstructions
  1397. }
  1398. ctx.Data["WillSign"] = false
  1399. if ctx.User != nil {
  1400. sign, key, _, err := pull.SignMerge(ctx.User, pull.BaseRepo.RepoPath(), pull.BaseBranch, pull.GetGitRefName())
  1401. ctx.Data["WillSign"] = sign
  1402. ctx.Data["SigningKey"] = key
  1403. if err != nil {
  1404. if models.IsErrWontSign(err) {
  1405. ctx.Data["WontSignReason"] = err.(*models.ErrWontSign).Reason
  1406. } else {
  1407. ctx.Data["WontSignReason"] = "error"
  1408. log.Error("Error whilst checking if could sign pr %d in repo %s. Error: %v", pull.ID, pull.BaseRepo.FullName(), err)
  1409. }
  1410. }
  1411. } else {
  1412. ctx.Data["WontSignReason"] = "not_signed_in"
  1413. }
  1414. ctx.Data["IsPullBranchDeletable"] = canDelete &&
  1415. pull.HeadRepo != nil &&
  1416. git.IsBranchExist(pull.HeadRepo.RepoPath(), pull.HeadBranch) &&
  1417. (!pull.HasMerged || ctx.Data["HeadBranchCommitID"] == ctx.Data["PullHeadCommitID"])
  1418. stillCanManualMerge := func() bool {
  1419. if pull.HasMerged || issue.IsClosed || !ctx.IsSigned {
  1420. return false
  1421. }
  1422. if pull.CanAutoMerge() || pull.IsWorkInProgress() || pull.IsChecking() {
  1423. return false
  1424. }
  1425. if (ctx.User.IsAdmin || ctx.Repo.IsAdmin()) && prConfig.AllowManualMerge {
  1426. return true
  1427. }
  1428. return false
  1429. }
  1430. ctx.Data["StillCanManualMerge"] = stillCanManualMerge()
  1431. }
  1432. // Get Dependencies
  1433. ctx.Data["BlockedByDependencies"], err = issue.BlockedByDependencies()
  1434. if err != nil {
  1435. ctx.ServerError("BlockedByDependencies", err)
  1436. return
  1437. }
  1438. ctx.Data["BlockingDependencies"], err = issue.BlockingDependencies()
  1439. if err != nil {
  1440. ctx.ServerError("BlockingDependencies", err)
  1441. return
  1442. }
  1443. ctx.Data["Participants"] = participants
  1444. ctx.Data["NumParticipants"] = len(participants)
  1445. ctx.Data["Issue"] = issue
  1446. ctx.Data["SignInLink"] = setting.AppSubURL + "/user/login?redirect_to=" + url.QueryEscape(ctx.Data["Link"].(string))
  1447. ctx.Data["IsIssuePoster"] = ctx.IsSigned && issue.IsPoster(ctx.User.ID)
  1448. ctx.Data["HasIssuesOrPullsWritePermission"] = ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)
  1449. ctx.Data["HasProjectsWritePermission"] = ctx.Repo.CanWrite(unit.TypeProjects)
  1450. ctx.Data["IsRepoAdmin"] = ctx.IsSigned && (ctx.Repo.IsAdmin() || ctx.User.IsAdmin)
  1451. ctx.Data["LockReasons"] = setting.Repository.Issue.LockReasons
  1452. ctx.Data["RefEndName"] = git.RefEndName(issue.Ref)
  1453. ctx.HTML(http.StatusOK, tplIssueView)
  1454. }
  1455. // GetActionIssue will return the issue which is used in the context.
  1456. func GetActionIssue(ctx *context.Context) *models.Issue {
  1457. issue, err := models.GetIssueByIndex(ctx.Repo.Repository.ID, ctx.ParamsInt64(":index"))
  1458. if err != nil {
  1459. ctx.NotFoundOrServerError("GetIssueByIndex", models.IsErrIssueNotExist, err)
  1460. return nil
  1461. }
  1462. issue.Repo = ctx.Repo.Repository
  1463. checkIssueRights(ctx, issue)
  1464. if ctx.Written() {
  1465. return nil
  1466. }
  1467. if err = issue.LoadAttributes(); err != nil {
  1468. ctx.ServerError("LoadAttributes", nil)
  1469. return nil
  1470. }
  1471. return issue
  1472. }
  1473. func checkIssueRights(ctx *context.Context, issue *models.Issue) {
  1474. if issue.IsPull && !ctx.Repo.CanRead(unit.TypePullRequests) ||
  1475. !issue.IsPull && !ctx.Repo.CanRead(unit.TypeIssues) {
  1476. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1477. }
  1478. }
  1479. func getActionIssues(ctx *context.Context) []*models.Issue {
  1480. commaSeparatedIssueIDs := ctx.FormString("issue_ids")
  1481. if len(commaSeparatedIssueIDs) == 0 {
  1482. return nil
  1483. }
  1484. issueIDs := make([]int64, 0, 10)
  1485. for _, stringIssueID := range strings.Split(commaSeparatedIssueIDs, ",") {
  1486. issueID, err := strconv.ParseInt(stringIssueID, 10, 64)
  1487. if err != nil {
  1488. ctx.ServerError("ParseInt", err)
  1489. return nil
  1490. }
  1491. issueIDs = append(issueIDs, issueID)
  1492. }
  1493. issues, err := models.GetIssuesByIDs(issueIDs)
  1494. if err != nil {
  1495. ctx.ServerError("GetIssuesByIDs", err)
  1496. return nil
  1497. }
  1498. // Check access rights for all issues
  1499. issueUnitEnabled := ctx.Repo.CanRead(unit.TypeIssues)
  1500. prUnitEnabled := ctx.Repo.CanRead(unit.TypePullRequests)
  1501. for _, issue := range issues {
  1502. if issue.IsPull && !prUnitEnabled || !issue.IsPull && !issueUnitEnabled {
  1503. ctx.NotFound("IssueOrPullRequestUnitNotAllowed", nil)
  1504. return nil
  1505. }
  1506. if err = issue.LoadAttributes(); err != nil {
  1507. ctx.ServerError("LoadAttributes", err)
  1508. return nil
  1509. }
  1510. }
  1511. return issues
  1512. }
  1513. // UpdateIssueTitle change issue's title
  1514. func UpdateIssueTitle(ctx *context.Context) {
  1515. issue := GetActionIssue(ctx)
  1516. if ctx.Written() {
  1517. return
  1518. }
  1519. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1520. ctx.Error(http.StatusForbidden)
  1521. return
  1522. }
  1523. title := ctx.FormTrim("title")
  1524. if len(title) == 0 {
  1525. ctx.Error(http.StatusNoContent)
  1526. return
  1527. }
  1528. if err := issue_service.ChangeTitle(issue, ctx.User, title); err != nil {
  1529. ctx.ServerError("ChangeTitle", err)
  1530. return
  1531. }
  1532. ctx.JSON(http.StatusOK, map[string]interface{}{
  1533. "title": issue.Title,
  1534. })
  1535. }
  1536. // UpdateIssueRef change issue's ref (branch)
  1537. func UpdateIssueRef(ctx *context.Context) {
  1538. issue := GetActionIssue(ctx)
  1539. if ctx.Written() {
  1540. return
  1541. }
  1542. if !ctx.IsSigned || (!issue.IsPoster(ctx.User.ID) && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) || issue.IsPull {
  1543. ctx.Error(http.StatusForbidden)
  1544. return
  1545. }
  1546. ref := ctx.FormTrim("ref")
  1547. if err := issue_service.ChangeIssueRef(issue, ctx.User, ref); err != nil {
  1548. ctx.ServerError("ChangeRef", err)
  1549. return
  1550. }
  1551. ctx.JSON(http.StatusOK, map[string]interface{}{
  1552. "ref": ref,
  1553. })
  1554. }
  1555. // UpdateIssueContent change issue's content
  1556. func UpdateIssueContent(ctx *context.Context) {
  1557. issue := GetActionIssue(ctx)
  1558. if ctx.Written() {
  1559. return
  1560. }
  1561. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull)) {
  1562. ctx.Error(http.StatusForbidden)
  1563. return
  1564. }
  1565. if err := issue_service.ChangeContent(issue, ctx.User, ctx.Req.FormValue("content")); err != nil {
  1566. ctx.ServerError("ChangeContent", err)
  1567. return
  1568. }
  1569. // when update the request doesn't intend to update attachments (eg: change checkbox state), ignore attachment updates
  1570. if !ctx.FormBool("ignore_attachments") {
  1571. if err := updateAttachments(issue, ctx.FormStrings("files[]")); err != nil {
  1572. ctx.ServerError("UpdateAttachments", err)
  1573. return
  1574. }
  1575. }
  1576. content, err := markdown.RenderString(&markup.RenderContext{
  1577. URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
  1578. Metas: ctx.Repo.Repository.ComposeMetas(),
  1579. GitRepo: ctx.Repo.GitRepo,
  1580. Ctx: ctx,
  1581. }, issue.Content)
  1582. if err != nil {
  1583. ctx.ServerError("RenderString", err)
  1584. return
  1585. }
  1586. ctx.JSON(http.StatusOK, map[string]interface{}{
  1587. "content": content,
  1588. "attachments": attachmentsHTML(ctx, issue.Attachments, issue.Content),
  1589. })
  1590. }
  1591. // UpdateIssueMilestone change issue's milestone
  1592. func UpdateIssueMilestone(ctx *context.Context) {
  1593. issues := getActionIssues(ctx)
  1594. if ctx.Written() {
  1595. return
  1596. }
  1597. milestoneID := ctx.FormInt64("id")
  1598. for _, issue := range issues {
  1599. oldMilestoneID := issue.MilestoneID
  1600. if oldMilestoneID == milestoneID {
  1601. continue
  1602. }
  1603. issue.MilestoneID = milestoneID
  1604. if err := issue_service.ChangeMilestoneAssign(issue, ctx.User, oldMilestoneID); err != nil {
  1605. ctx.ServerError("ChangeMilestoneAssign", err)
  1606. return
  1607. }
  1608. }
  1609. ctx.JSON(http.StatusOK, map[string]interface{}{
  1610. "ok": true,
  1611. })
  1612. }
  1613. // UpdateIssueAssignee change issue's or pull's assignee
  1614. func UpdateIssueAssignee(ctx *context.Context) {
  1615. issues := getActionIssues(ctx)
  1616. if ctx.Written() {
  1617. return
  1618. }
  1619. assigneeID := ctx.FormInt64("id")
  1620. action := ctx.FormString("action")
  1621. for _, issue := range issues {
  1622. switch action {
  1623. case "clear":
  1624. if err := issue_service.DeleteNotPassedAssignee(issue, ctx.User, []*user_model.User{}); err != nil {
  1625. ctx.ServerError("ClearAssignees", err)
  1626. return
  1627. }
  1628. default:
  1629. assignee, err := user_model.GetUserByID(assigneeID)
  1630. if err != nil {
  1631. ctx.ServerError("GetUserByID", err)
  1632. return
  1633. }
  1634. valid, err := models.CanBeAssigned(assignee, issue.Repo, issue.IsPull)
  1635. if err != nil {
  1636. ctx.ServerError("canBeAssigned", err)
  1637. return
  1638. }
  1639. if !valid {
  1640. ctx.ServerError("canBeAssigned", models.ErrUserDoesNotHaveAccessToRepo{UserID: assigneeID, RepoName: issue.Repo.Name})
  1641. return
  1642. }
  1643. _, _, err = issue_service.ToggleAssignee(issue, ctx.User, assigneeID)
  1644. if err != nil {
  1645. ctx.ServerError("ToggleAssignee", err)
  1646. return
  1647. }
  1648. }
  1649. }
  1650. ctx.JSON(http.StatusOK, map[string]interface{}{
  1651. "ok": true,
  1652. })
  1653. }
  1654. // UpdatePullReviewRequest add or remove review request
  1655. func UpdatePullReviewRequest(ctx *context.Context) {
  1656. issues := getActionIssues(ctx)
  1657. if ctx.Written() {
  1658. return
  1659. }
  1660. reviewID := ctx.FormInt64("id")
  1661. action := ctx.FormString("action")
  1662. // TODO: Not support 'clear' now
  1663. if action != "attach" && action != "detach" {
  1664. ctx.Status(403)
  1665. return
  1666. }
  1667. for _, issue := range issues {
  1668. if err := issue.LoadRepo(); err != nil {
  1669. ctx.ServerError("issue.LoadRepo", err)
  1670. return
  1671. }
  1672. if !issue.IsPull {
  1673. log.Warn(
  1674. "UpdatePullReviewRequest: refusing to add review request for non-PR issue %-v#%d",
  1675. issue.Repo, issue.Index,
  1676. )
  1677. ctx.Status(403)
  1678. return
  1679. }
  1680. if reviewID < 0 {
  1681. // negative reviewIDs represent team requests
  1682. if err := issue.Repo.GetOwner(); err != nil {
  1683. ctx.ServerError("issue.Repo.GetOwner", err)
  1684. return
  1685. }
  1686. if !issue.Repo.Owner.IsOrganization() {
  1687. log.Warn(
  1688. "UpdatePullReviewRequest: refusing to add team review request for %s#%d owned by non organization UID[%d]",
  1689. issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1690. )
  1691. ctx.Status(403)
  1692. return
  1693. }
  1694. team, err := models.GetTeamByID(-reviewID)
  1695. if err != nil {
  1696. ctx.ServerError("models.GetTeamByID", err)
  1697. return
  1698. }
  1699. if team.OrgID != issue.Repo.OwnerID {
  1700. log.Warn(
  1701. "UpdatePullReviewRequest: refusing to add team review request for UID[%d] team %s to %s#%d owned by UID[%d]",
  1702. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID)
  1703. ctx.Status(403)
  1704. return
  1705. }
  1706. err = issue_service.IsValidTeamReviewRequest(team, ctx.User, action == "attach", issue)
  1707. if err != nil {
  1708. if models.IsErrNotValidReviewRequest(err) {
  1709. log.Warn(
  1710. "UpdatePullReviewRequest: refusing to add invalid team review request for UID[%d] team %s to %s#%d owned by UID[%d]: Error: %v",
  1711. team.OrgID, team.Name, issue.Repo.FullName(), issue.Index, issue.Repo.ID,
  1712. err,
  1713. )
  1714. ctx.Status(403)
  1715. return
  1716. }
  1717. ctx.ServerError("IsValidTeamReviewRequest", err)
  1718. return
  1719. }
  1720. _, err = issue_service.TeamReviewRequest(issue, ctx.User, team, action == "attach")
  1721. if err != nil {
  1722. ctx.ServerError("TeamReviewRequest", err)
  1723. return
  1724. }
  1725. continue
  1726. }
  1727. reviewer, err := user_model.GetUserByID(reviewID)
  1728. if err != nil {
  1729. if user_model.IsErrUserNotExist(err) {
  1730. log.Warn(
  1731. "UpdatePullReviewRequest: requested reviewer [%d] for %-v to %-v#%d is not exist: Error: %v",
  1732. reviewID, issue.Repo, issue.Index,
  1733. err,
  1734. )
  1735. ctx.Status(403)
  1736. return
  1737. }
  1738. ctx.ServerError("GetUserByID", err)
  1739. return
  1740. }
  1741. err = issue_service.IsValidReviewRequest(reviewer, ctx.User, action == "attach", issue, nil)
  1742. if err != nil {
  1743. if models.IsErrNotValidReviewRequest(err) {
  1744. log.Warn(
  1745. "UpdatePullReviewRequest: refusing to add invalid review request for %-v to %-v#%d: Error: %v",
  1746. reviewer, issue.Repo, issue.Index,
  1747. err,
  1748. )
  1749. ctx.Status(403)
  1750. return
  1751. }
  1752. ctx.ServerError("isValidReviewRequest", err)
  1753. return
  1754. }
  1755. _, err = issue_service.ReviewRequest(issue, ctx.User, reviewer, action == "attach")
  1756. if err != nil {
  1757. ctx.ServerError("ReviewRequest", err)
  1758. return
  1759. }
  1760. }
  1761. ctx.JSON(http.StatusOK, map[string]interface{}{
  1762. "ok": true,
  1763. })
  1764. }
  1765. // UpdateIssueStatus change issue's status
  1766. func UpdateIssueStatus(ctx *context.Context) {
  1767. issues := getActionIssues(ctx)
  1768. if ctx.Written() {
  1769. return
  1770. }
  1771. var isClosed bool
  1772. switch action := ctx.FormString("action"); action {
  1773. case "open":
  1774. isClosed = false
  1775. case "close":
  1776. isClosed = true
  1777. default:
  1778. log.Warn("Unrecognized action: %s", action)
  1779. }
  1780. if _, err := models.IssueList(issues).LoadRepositories(); err != nil {
  1781. ctx.ServerError("LoadRepositories", err)
  1782. return
  1783. }
  1784. for _, issue := range issues {
  1785. if issue.IsClosed != isClosed {
  1786. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1787. if models.IsErrDependenciesLeft(err) {
  1788. ctx.JSON(http.StatusPreconditionFailed, map[string]interface{}{
  1789. "error": "cannot close this issue because it still has open dependencies",
  1790. })
  1791. return
  1792. }
  1793. ctx.ServerError("ChangeStatus", err)
  1794. return
  1795. }
  1796. }
  1797. }
  1798. ctx.JSON(http.StatusOK, map[string]interface{}{
  1799. "ok": true,
  1800. })
  1801. }
  1802. // NewComment create a comment for issue
  1803. func NewComment(ctx *context.Context) {
  1804. form := web.GetForm(ctx).(*forms.CreateCommentForm)
  1805. issue := GetActionIssue(ctx)
  1806. if ctx.Written() {
  1807. return
  1808. }
  1809. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  1810. if log.IsTrace() {
  1811. if ctx.IsSigned {
  1812. issueType := "issues"
  1813. if issue.IsPull {
  1814. issueType = "pulls"
  1815. }
  1816. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  1817. "User in Repo has Permissions: %-+v",
  1818. ctx.User,
  1819. log.NewColoredIDValue(issue.PosterID),
  1820. issueType,
  1821. ctx.Repo.Repository,
  1822. ctx.Repo.Permission)
  1823. } else {
  1824. log.Trace("Permission Denied: Not logged in")
  1825. }
  1826. }
  1827. ctx.Error(http.StatusForbidden)
  1828. return
  1829. }
  1830. if issue.IsLocked && !ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) && !ctx.User.IsAdmin {
  1831. ctx.Flash.Error(ctx.Tr("repo.issues.comment_on_locked"))
  1832. ctx.Redirect(issue.HTMLURL(), http.StatusSeeOther)
  1833. return
  1834. }
  1835. var attachments []string
  1836. if setting.Attachment.Enabled {
  1837. attachments = form.Files
  1838. }
  1839. if ctx.HasError() {
  1840. ctx.Flash.Error(ctx.Data["ErrorMsg"].(string))
  1841. ctx.Redirect(issue.HTMLURL())
  1842. return
  1843. }
  1844. var comment *models.Comment
  1845. defer func() {
  1846. // Check if issue admin/poster changes the status of issue.
  1847. if (ctx.Repo.CanWriteIssuesOrPulls(issue.IsPull) || (ctx.IsSigned && issue.IsPoster(ctx.User.ID))) &&
  1848. (form.Status == "reopen" || form.Status == "close") &&
  1849. !(issue.IsPull && issue.PullRequest.HasMerged) {
  1850. // Duplication and conflict check should apply to reopen pull request.
  1851. var pr *models.PullRequest
  1852. if form.Status == "reopen" && issue.IsPull {
  1853. pull := issue.PullRequest
  1854. var err error
  1855. pr, err = models.GetUnmergedPullRequest(pull.HeadRepoID, pull.BaseRepoID, pull.HeadBranch, pull.BaseBranch, pull.Flow)
  1856. if err != nil {
  1857. if !models.IsErrPullRequestNotExist(err) {
  1858. ctx.ServerError("GetUnmergedPullRequest", err)
  1859. return
  1860. }
  1861. }
  1862. // Regenerate patch and test conflict.
  1863. if pr == nil {
  1864. issue.PullRequest.HeadCommitID = ""
  1865. pull_service.AddToTaskQueue(issue.PullRequest)
  1866. }
  1867. }
  1868. if pr != nil {
  1869. ctx.Flash.Info(ctx.Tr("repo.pulls.open_unmerged_pull_exists", pr.Index))
  1870. } else {
  1871. isClosed := form.Status == "close"
  1872. if err := issue_service.ChangeStatus(issue, ctx.User, isClosed); err != nil {
  1873. log.Error("ChangeStatus: %v", err)
  1874. if models.IsErrDependenciesLeft(err) {
  1875. if issue.IsPull {
  1876. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.pr_close_blocked"))
  1877. ctx.Redirect(fmt.Sprintf("%s/pulls/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1878. } else {
  1879. ctx.Flash.Error(ctx.Tr("repo.issues.dependency.issue_close_blocked"))
  1880. ctx.Redirect(fmt.Sprintf("%s/issues/%d", ctx.Repo.RepoLink, issue.Index), http.StatusSeeOther)
  1881. }
  1882. return
  1883. }
  1884. } else {
  1885. if err := stopTimerIfAvailable(ctx.User, issue); err != nil {
  1886. ctx.ServerError("CreateOrStopIssueStopwatch", err)
  1887. return
  1888. }
  1889. log.Trace("Issue [%d] status changed to closed: %v", issue.ID, issue.IsClosed)
  1890. }
  1891. }
  1892. }
  1893. // Redirect to comment hashtag if there is any actual content.
  1894. typeName := "issues"
  1895. if issue.IsPull {
  1896. typeName = "pulls"
  1897. }
  1898. if comment != nil {
  1899. ctx.Redirect(fmt.Sprintf("%s/%s/%d#%s", ctx.Repo.RepoLink, typeName, issue.Index, comment.HashTag()))
  1900. } else {
  1901. ctx.Redirect(fmt.Sprintf("%s/%s/%d", ctx.Repo.RepoLink, typeName, issue.Index))
  1902. }
  1903. }()
  1904. // Fix #321: Allow empty comments, as long as we have attachments.
  1905. if len(form.Content) == 0 && len(attachments) == 0 {
  1906. return
  1907. }
  1908. comment, err := comment_service.CreateIssueComment(ctx.User, ctx.Repo.Repository, issue, form.Content, attachments)
  1909. if err != nil {
  1910. ctx.ServerError("CreateIssueComment", err)
  1911. return
  1912. }
  1913. log.Trace("Comment created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, comment.ID)
  1914. }
  1915. // UpdateCommentContent change comment of issue's content
  1916. func UpdateCommentContent(ctx *context.Context) {
  1917. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1918. if err != nil {
  1919. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1920. return
  1921. }
  1922. if err := comment.LoadIssue(); err != nil {
  1923. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1924. return
  1925. }
  1926. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1927. ctx.Error(http.StatusForbidden)
  1928. return
  1929. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1930. ctx.Error(http.StatusNoContent)
  1931. return
  1932. }
  1933. oldContent := comment.Content
  1934. comment.Content = ctx.FormString("content")
  1935. if len(comment.Content) == 0 {
  1936. ctx.JSON(http.StatusOK, map[string]interface{}{
  1937. "content": "",
  1938. })
  1939. return
  1940. }
  1941. if err = comment_service.UpdateComment(comment, ctx.User, oldContent); err != nil {
  1942. ctx.ServerError("UpdateComment", err)
  1943. return
  1944. }
  1945. if comment.Type == models.CommentTypeComment {
  1946. if err := comment.LoadAttachments(); err != nil {
  1947. ctx.ServerError("LoadAttachments", err)
  1948. return
  1949. }
  1950. }
  1951. // when the update request doesn't intend to update attachments (eg: change checkbox state), ignore attachment updates
  1952. if !ctx.FormBool("ignore_attachments") {
  1953. if err := updateAttachments(comment, ctx.FormStrings("files[]")); err != nil {
  1954. ctx.ServerError("UpdateAttachments", err)
  1955. return
  1956. }
  1957. }
  1958. content, err := markdown.RenderString(&markup.RenderContext{
  1959. URLPrefix: ctx.FormString("context"), // FIXME: <- IS THIS SAFE ?
  1960. Metas: ctx.Repo.Repository.ComposeMetas(),
  1961. GitRepo: ctx.Repo.GitRepo,
  1962. Ctx: ctx,
  1963. }, comment.Content)
  1964. if err != nil {
  1965. ctx.ServerError("RenderString", err)
  1966. return
  1967. }
  1968. ctx.JSON(http.StatusOK, map[string]interface{}{
  1969. "content": content,
  1970. "attachments": attachmentsHTML(ctx, comment.Attachments, comment.Content),
  1971. })
  1972. }
  1973. // DeleteComment delete comment of issue
  1974. func DeleteComment(ctx *context.Context) {
  1975. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  1976. if err != nil {
  1977. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  1978. return
  1979. }
  1980. if err := comment.LoadIssue(); err != nil {
  1981. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  1982. return
  1983. }
  1984. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanWriteIssuesOrPulls(comment.Issue.IsPull)) {
  1985. ctx.Error(http.StatusForbidden)
  1986. return
  1987. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  1988. ctx.Error(http.StatusNoContent)
  1989. return
  1990. }
  1991. if err = comment_service.DeleteComment(ctx.User, comment); err != nil {
  1992. ctx.ServerError("DeleteCommentByID", err)
  1993. return
  1994. }
  1995. ctx.Status(200)
  1996. }
  1997. // ChangeIssueReaction create a reaction for issue
  1998. func ChangeIssueReaction(ctx *context.Context) {
  1999. form := web.GetForm(ctx).(*forms.ReactionForm)
  2000. issue := GetActionIssue(ctx)
  2001. if ctx.Written() {
  2002. return
  2003. }
  2004. if !ctx.IsSigned || (ctx.User.ID != issue.PosterID && !ctx.Repo.CanReadIssuesOrPulls(issue.IsPull)) {
  2005. if log.IsTrace() {
  2006. if ctx.IsSigned {
  2007. issueType := "issues"
  2008. if issue.IsPull {
  2009. issueType = "pulls"
  2010. }
  2011. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  2012. "User in Repo has Permissions: %-+v",
  2013. ctx.User,
  2014. log.NewColoredIDValue(issue.PosterID),
  2015. issueType,
  2016. ctx.Repo.Repository,
  2017. ctx.Repo.Permission)
  2018. } else {
  2019. log.Trace("Permission Denied: Not logged in")
  2020. }
  2021. }
  2022. ctx.Error(http.StatusForbidden)
  2023. return
  2024. }
  2025. if ctx.HasError() {
  2026. ctx.ServerError("ChangeIssueReaction", errors.New(ctx.GetErrMsg()))
  2027. return
  2028. }
  2029. switch ctx.Params(":action") {
  2030. case "react":
  2031. reaction, err := models.CreateIssueReaction(ctx.User, issue, form.Content)
  2032. if err != nil {
  2033. if models.IsErrForbiddenIssueReaction(err) {
  2034. ctx.ServerError("ChangeIssueReaction", err)
  2035. return
  2036. }
  2037. log.Info("CreateIssueReaction: %s", err)
  2038. break
  2039. }
  2040. // Reload new reactions
  2041. issue.Reactions = nil
  2042. if err = issue.LoadAttributes(); err != nil {
  2043. log.Info("issue.LoadAttributes: %s", err)
  2044. break
  2045. }
  2046. log.Trace("Reaction for issue created: %d/%d/%d", ctx.Repo.Repository.ID, issue.ID, reaction.ID)
  2047. case "unreact":
  2048. if err := models.DeleteIssueReaction(ctx.User, issue, form.Content); err != nil {
  2049. ctx.ServerError("DeleteIssueReaction", err)
  2050. return
  2051. }
  2052. // Reload new reactions
  2053. issue.Reactions = nil
  2054. if err := issue.LoadAttributes(); err != nil {
  2055. log.Info("issue.LoadAttributes: %s", err)
  2056. break
  2057. }
  2058. log.Trace("Reaction for issue removed: %d/%d", ctx.Repo.Repository.ID, issue.ID)
  2059. default:
  2060. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  2061. return
  2062. }
  2063. if len(issue.Reactions) == 0 {
  2064. ctx.JSON(http.StatusOK, map[string]interface{}{
  2065. "empty": true,
  2066. "html": "",
  2067. })
  2068. return
  2069. }
  2070. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  2071. "ctx": ctx.Data,
  2072. "ActionURL": fmt.Sprintf("%s/issues/%d/reactions", ctx.Repo.RepoLink, issue.Index),
  2073. "Reactions": issue.Reactions.GroupByType(),
  2074. })
  2075. if err != nil {
  2076. ctx.ServerError("ChangeIssueReaction.HTMLString", err)
  2077. return
  2078. }
  2079. ctx.JSON(http.StatusOK, map[string]interface{}{
  2080. "html": html,
  2081. })
  2082. }
  2083. // ChangeCommentReaction create a reaction for comment
  2084. func ChangeCommentReaction(ctx *context.Context) {
  2085. form := web.GetForm(ctx).(*forms.ReactionForm)
  2086. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  2087. if err != nil {
  2088. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2089. return
  2090. }
  2091. if err := comment.LoadIssue(); err != nil {
  2092. ctx.NotFoundOrServerError("LoadIssue", models.IsErrIssueNotExist, err)
  2093. return
  2094. }
  2095. if !ctx.IsSigned || (ctx.User.ID != comment.PosterID && !ctx.Repo.CanReadIssuesOrPulls(comment.Issue.IsPull)) {
  2096. if log.IsTrace() {
  2097. if ctx.IsSigned {
  2098. issueType := "issues"
  2099. if comment.Issue.IsPull {
  2100. issueType = "pulls"
  2101. }
  2102. log.Trace("Permission Denied: User %-v not the Poster (ID: %d) and cannot read %s in Repo %-v.\n"+
  2103. "User in Repo has Permissions: %-+v",
  2104. ctx.User,
  2105. log.NewColoredIDValue(comment.Issue.PosterID),
  2106. issueType,
  2107. ctx.Repo.Repository,
  2108. ctx.Repo.Permission)
  2109. } else {
  2110. log.Trace("Permission Denied: Not logged in")
  2111. }
  2112. }
  2113. ctx.Error(http.StatusForbidden)
  2114. return
  2115. } else if comment.Type != models.CommentTypeComment && comment.Type != models.CommentTypeCode {
  2116. ctx.Error(http.StatusNoContent)
  2117. return
  2118. }
  2119. switch ctx.Params(":action") {
  2120. case "react":
  2121. reaction, err := models.CreateCommentReaction(ctx.User, comment.Issue, comment, form.Content)
  2122. if err != nil {
  2123. if models.IsErrForbiddenIssueReaction(err) {
  2124. ctx.ServerError("ChangeIssueReaction", err)
  2125. return
  2126. }
  2127. log.Info("CreateCommentReaction: %s", err)
  2128. break
  2129. }
  2130. // Reload new reactions
  2131. comment.Reactions = nil
  2132. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2133. log.Info("comment.LoadReactions: %s", err)
  2134. break
  2135. }
  2136. log.Trace("Reaction for comment created: %d/%d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID, reaction.ID)
  2137. case "unreact":
  2138. if err := models.DeleteCommentReaction(ctx.User, comment.Issue, comment, form.Content); err != nil {
  2139. ctx.ServerError("DeleteCommentReaction", err)
  2140. return
  2141. }
  2142. // Reload new reactions
  2143. comment.Reactions = nil
  2144. if err = comment.LoadReactions(ctx.Repo.Repository); err != nil {
  2145. log.Info("comment.LoadReactions: %s", err)
  2146. break
  2147. }
  2148. log.Trace("Reaction for comment removed: %d/%d/%d", ctx.Repo.Repository.ID, comment.Issue.ID, comment.ID)
  2149. default:
  2150. ctx.NotFound(fmt.Sprintf("Unknown action %s", ctx.Params(":action")), nil)
  2151. return
  2152. }
  2153. if len(comment.Reactions) == 0 {
  2154. ctx.JSON(http.StatusOK, map[string]interface{}{
  2155. "empty": true,
  2156. "html": "",
  2157. })
  2158. return
  2159. }
  2160. html, err := ctx.HTMLString(string(tplReactions), map[string]interface{}{
  2161. "ctx": ctx.Data,
  2162. "ActionURL": fmt.Sprintf("%s/comments/%d/reactions", ctx.Repo.RepoLink, comment.ID),
  2163. "Reactions": comment.Reactions.GroupByType(),
  2164. })
  2165. if err != nil {
  2166. ctx.ServerError("ChangeCommentReaction.HTMLString", err)
  2167. return
  2168. }
  2169. ctx.JSON(http.StatusOK, map[string]interface{}{
  2170. "html": html,
  2171. })
  2172. }
  2173. func addParticipant(poster *user_model.User, participants []*user_model.User) []*user_model.User {
  2174. for _, part := range participants {
  2175. if poster.ID == part.ID {
  2176. return participants
  2177. }
  2178. }
  2179. return append(participants, poster)
  2180. }
  2181. func filterXRefComments(ctx *context.Context, issue *models.Issue) error {
  2182. // Remove comments that the user has no permissions to see
  2183. for i := 0; i < len(issue.Comments); {
  2184. c := issue.Comments[i]
  2185. if models.CommentTypeIsRef(c.Type) && c.RefRepoID != issue.RepoID && c.RefRepoID != 0 {
  2186. var err error
  2187. // Set RefRepo for description in template
  2188. c.RefRepo, err = models.GetRepositoryByID(c.RefRepoID)
  2189. if err != nil {
  2190. return err
  2191. }
  2192. perm, err := models.GetUserRepoPermission(c.RefRepo, ctx.User)
  2193. if err != nil {
  2194. return err
  2195. }
  2196. if !perm.CanReadIssuesOrPulls(c.RefIsPull) {
  2197. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2198. continue
  2199. }
  2200. }
  2201. i++
  2202. }
  2203. return nil
  2204. }
  2205. // GetIssueAttachments returns attachments for the issue
  2206. func GetIssueAttachments(ctx *context.Context) {
  2207. issue := GetActionIssue(ctx)
  2208. var attachments = make([]*api.Attachment, len(issue.Attachments))
  2209. for i := 0; i < len(issue.Attachments); i++ {
  2210. attachments[i] = convert.ToReleaseAttachment(issue.Attachments[i])
  2211. }
  2212. ctx.JSON(http.StatusOK, attachments)
  2213. }
  2214. // GetCommentAttachments returns attachments for the comment
  2215. func GetCommentAttachments(ctx *context.Context) {
  2216. comment, err := models.GetCommentByID(ctx.ParamsInt64(":id"))
  2217. if err != nil {
  2218. ctx.NotFoundOrServerError("GetCommentByID", models.IsErrCommentNotExist, err)
  2219. return
  2220. }
  2221. var attachments = make([]*api.Attachment, 0)
  2222. if comment.Type == models.CommentTypeComment {
  2223. if err := comment.LoadAttachments(); err != nil {
  2224. ctx.ServerError("LoadAttachments", err)
  2225. return
  2226. }
  2227. for i := 0; i < len(comment.Attachments); i++ {
  2228. attachments = append(attachments, convert.ToReleaseAttachment(comment.Attachments[i]))
  2229. }
  2230. }
  2231. ctx.JSON(http.StatusOK, attachments)
  2232. }
  2233. func updateAttachments(item interface{}, files []string) error {
  2234. var attachments []*repo_model.Attachment
  2235. switch content := item.(type) {
  2236. case *models.Issue:
  2237. attachments = content.Attachments
  2238. case *models.Comment:
  2239. attachments = content.Attachments
  2240. default:
  2241. return fmt.Errorf("Unknown Type: %T", content)
  2242. }
  2243. for i := 0; i < len(attachments); i++ {
  2244. if util.IsStringInSlice(attachments[i].UUID, files) {
  2245. continue
  2246. }
  2247. if err := repo_model.DeleteAttachment(attachments[i], true); err != nil {
  2248. return err
  2249. }
  2250. }
  2251. var err error
  2252. if len(files) > 0 {
  2253. switch content := item.(type) {
  2254. case *models.Issue:
  2255. err = content.UpdateAttachments(files)
  2256. case *models.Comment:
  2257. err = content.UpdateAttachments(files)
  2258. default:
  2259. return fmt.Errorf("Unknown Type: %T", content)
  2260. }
  2261. if err != nil {
  2262. return err
  2263. }
  2264. }
  2265. switch content := item.(type) {
  2266. case *models.Issue:
  2267. content.Attachments, err = repo_model.GetAttachmentsByIssueID(content.ID)
  2268. case *models.Comment:
  2269. content.Attachments, err = repo_model.GetAttachmentsByCommentID(content.ID)
  2270. default:
  2271. return fmt.Errorf("Unknown Type: %T", content)
  2272. }
  2273. return err
  2274. }
  2275. func attachmentsHTML(ctx *context.Context, attachments []*repo_model.Attachment, content string) string {
  2276. attachHTML, err := ctx.HTMLString(string(tplAttachment), map[string]interface{}{
  2277. "ctx": ctx.Data,
  2278. "Attachments": attachments,
  2279. "Content": content,
  2280. })
  2281. if err != nil {
  2282. ctx.ServerError("attachmentsHTML.HTMLString", err)
  2283. return ""
  2284. }
  2285. return attachHTML
  2286. }
  2287. // combineLabelComments combine the nearby label comments as one.
  2288. func combineLabelComments(issue *models.Issue) {
  2289. var prev, cur *models.Comment
  2290. for i := 0; i < len(issue.Comments); i++ {
  2291. cur = issue.Comments[i]
  2292. if i > 0 {
  2293. prev = issue.Comments[i-1]
  2294. }
  2295. if i == 0 || cur.Type != models.CommentTypeLabel ||
  2296. (prev != nil && prev.PosterID != cur.PosterID) ||
  2297. (prev != nil && cur.CreatedUnix-prev.CreatedUnix >= 60) {
  2298. if cur.Type == models.CommentTypeLabel && cur.Label != nil {
  2299. if cur.Content != "1" {
  2300. cur.RemovedLabels = append(cur.RemovedLabels, cur.Label)
  2301. } else {
  2302. cur.AddedLabels = append(cur.AddedLabels, cur.Label)
  2303. }
  2304. }
  2305. continue
  2306. }
  2307. if cur.Label != nil { // now cur MUST be label comment
  2308. if prev.Type == models.CommentTypeLabel { // we can combine them only prev is a label comment
  2309. if cur.Content != "1" {
  2310. // remove labels from the AddedLabels list if the label that was removed is already
  2311. // in this list, and if it's not in this list, add the label to RemovedLabels
  2312. addedAndRemoved := false
  2313. for i, label := range prev.AddedLabels {
  2314. if cur.Label.ID == label.ID {
  2315. prev.AddedLabels = append(prev.AddedLabels[:i], prev.AddedLabels[i+1:]...)
  2316. addedAndRemoved = true
  2317. break
  2318. }
  2319. }
  2320. if !addedAndRemoved {
  2321. prev.RemovedLabels = append(prev.RemovedLabels, cur.Label)
  2322. }
  2323. } else {
  2324. // remove labels from the RemovedLabels list if the label that was added is already
  2325. // in this list, and if it's not in this list, add the label to AddedLabels
  2326. removedAndAdded := false
  2327. for i, label := range prev.RemovedLabels {
  2328. if cur.Label.ID == label.ID {
  2329. prev.RemovedLabels = append(prev.RemovedLabels[:i], prev.RemovedLabels[i+1:]...)
  2330. removedAndAdded = true
  2331. break
  2332. }
  2333. }
  2334. if !removedAndAdded {
  2335. prev.AddedLabels = append(prev.AddedLabels, cur.Label)
  2336. }
  2337. }
  2338. prev.CreatedUnix = cur.CreatedUnix
  2339. // remove the current comment since it has been combined to prev comment
  2340. issue.Comments = append(issue.Comments[:i], issue.Comments[i+1:]...)
  2341. i--
  2342. } else { // if prev is not a label comment, start a new group
  2343. if cur.Content != "1" {
  2344. cur.RemovedLabels = append(cur.RemovedLabels, cur.Label)
  2345. } else {
  2346. cur.AddedLabels = append(cur.AddedLabels, cur.Label)
  2347. }
  2348. }
  2349. }
  2350. }
  2351. }
  2352. // get all teams that current user can mention
  2353. func handleTeamMentions(ctx *context.Context) {
  2354. if ctx.User == nil || !ctx.Repo.Owner.IsOrganization() {
  2355. return
  2356. }
  2357. var isAdmin bool
  2358. var err error
  2359. var teams []*models.Team
  2360. var org = models.OrgFromUser(ctx.Repo.Owner)
  2361. // Admin has super access.
  2362. if ctx.User.IsAdmin {
  2363. isAdmin = true
  2364. } else {
  2365. isAdmin, err = org.IsOwnedBy(ctx.User.ID)
  2366. if err != nil {
  2367. ctx.ServerError("IsOwnedBy", err)
  2368. return
  2369. }
  2370. }
  2371. if isAdmin {
  2372. teams, err = org.LoadTeams()
  2373. if err != nil {
  2374. ctx.ServerError("LoadTeams", err)
  2375. return
  2376. }
  2377. } else {
  2378. teams, err = org.GetUserTeams(ctx.User.ID)
  2379. if err != nil {
  2380. ctx.ServerError("GetUserTeams", err)
  2381. return
  2382. }
  2383. }
  2384. ctx.Data["MentionableTeams"] = teams
  2385. ctx.Data["MentionableTeamsOrg"] = ctx.Repo.Owner.Name
  2386. ctx.Data["MentionableTeamsOrgAvatar"] = ctx.Repo.Owner.AvatarLink()
  2387. }