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

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