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

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