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

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