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

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