You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

context.go 8.6 kB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
9 years ago
Add lang specific font stacks for CJK (#6007) * Add lang specific font stacks * Force font changes Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix icons Signed-off-by: Andrew Thornton <art27@cantab.net> * Fix octicons and icons Signed-off-by: Andrew Thornton <art27@cantab.net> * Just override the semantic ui fonts only Signed-off-by: Andrew Thornton <art27@cantab.net> * Missed the headers... override them too * Missed some more semantic ui stuff * Fix PT Sans Signed-off-by: Andrew Thornton <art27@cantab.net> * More changes Signed-off-by: Andrew Thornton <art27@cantab.net> * Squashed commit of the following: commit 7d1679e9079541359869c9e677ba7412bfcc59f3 Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 13:53:49 2019 +0100 Remove missed YaHei leftover from _home.less commit 0079121ea91860a323ed4e5cc1a9c0d490d9cefd Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 12:03:54 2019 +0100 Fix overdone fixes (inherit, :lang) commit 62c919915928ec1db4731d547e95885f91a0618d Author: Mike L <cl.jeremy@qq.com> Date: Wed Mar 13 02:29:10 2019 +0100 Fix elements w/ explicit lang (language chooser) commit b3117587aa2eb8570d60bed583a11ee5565418be Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 20:17:26 2019 +0100 Fix textarea also (to match body) commit 81cedf2c3012c4dd05a7680782b4a98e1b947f67 Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 19:41:39 2019 +0100 Revert css temporarily to fix conflict commit 80ff82797f3203cbeaf866f22e961334e137df89 Author: Mike L <cl.jeremy@qq.com> Date: Tue Mar 12 19:15:30 2019 +0100 Tweak CJK, fix Yu Gothic, more monospace inherits commit 581dceb9a869646c2c486dabb925c88c2680d70c Author: Mike L <cl.jeremy@qq.com> Date: Mon Mar 11 13:09:26 2019 +0100 Add Lato for latin extd. & cyrillic, improve CJK * update stylesheet
6 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package context
  5. import (
  6. "html"
  7. "html/template"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "path"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/auth"
  16. "code.gitea.io/gitea/modules/base"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "github.com/Unknwon/com"
  20. "github.com/go-macaron/cache"
  21. "github.com/go-macaron/csrf"
  22. "github.com/go-macaron/i18n"
  23. "github.com/go-macaron/session"
  24. macaron "gopkg.in/macaron.v1"
  25. )
  26. // Context represents context of a request.
  27. type Context struct {
  28. *macaron.Context
  29. Cache cache.Cache
  30. csrf csrf.CSRF
  31. Flash *session.Flash
  32. Session session.Store
  33. Link string // current request URL
  34. EscapedLink string
  35. User *models.User
  36. IsSigned bool
  37. IsBasicAuth bool
  38. Repo *Repository
  39. Org *Organization
  40. }
  41. // HasAPIError returns true if error occurs in form validation.
  42. func (ctx *Context) HasAPIError() bool {
  43. hasErr, ok := ctx.Data["HasError"]
  44. if !ok {
  45. return false
  46. }
  47. return hasErr.(bool)
  48. }
  49. // GetErrMsg returns error message
  50. func (ctx *Context) GetErrMsg() string {
  51. return ctx.Data["ErrorMsg"].(string)
  52. }
  53. // HasError returns true if error occurs in form validation.
  54. func (ctx *Context) HasError() bool {
  55. hasErr, ok := ctx.Data["HasError"]
  56. if !ok {
  57. return false
  58. }
  59. ctx.Flash.ErrorMsg = ctx.Data["ErrorMsg"].(string)
  60. ctx.Data["Flash"] = ctx.Flash
  61. return hasErr.(bool)
  62. }
  63. // HasValue returns true if value of given name exists.
  64. func (ctx *Context) HasValue(name string) bool {
  65. _, ok := ctx.Data[name]
  66. return ok
  67. }
  68. // RedirectToFirst redirects to first not empty URL
  69. func (ctx *Context) RedirectToFirst(location ...string) {
  70. for _, loc := range location {
  71. if len(loc) == 0 {
  72. continue
  73. }
  74. u, err := url.Parse(loc)
  75. if err != nil || (u.Scheme != "" && !strings.HasPrefix(strings.ToLower(loc), strings.ToLower(setting.AppURL))) {
  76. continue
  77. }
  78. ctx.Redirect(loc)
  79. return
  80. }
  81. ctx.Redirect(setting.AppSubURL + "/")
  82. return
  83. }
  84. // HTML calls Context.HTML and converts template name to string.
  85. func (ctx *Context) HTML(status int, name base.TplName) {
  86. log.Debug("Template: %s", name)
  87. ctx.Context.HTML(status, string(name))
  88. }
  89. // RenderWithErr used for page has form validation but need to prompt error to users.
  90. func (ctx *Context) RenderWithErr(msg string, tpl base.TplName, form interface{}) {
  91. if form != nil {
  92. auth.AssignForm(form, ctx.Data)
  93. }
  94. ctx.Flash.ErrorMsg = msg
  95. ctx.Data["Flash"] = ctx.Flash
  96. ctx.HTML(200, tpl)
  97. }
  98. // NotFound displays a 404 (Not Found) page and prints the given error, if any.
  99. func (ctx *Context) NotFound(title string, err error) {
  100. if err != nil {
  101. log.Error(4, "%s: %v", title, err)
  102. if macaron.Env != macaron.PROD {
  103. ctx.Data["ErrorMsg"] = err
  104. }
  105. }
  106. ctx.Data["IsRepo"] = ctx.Repo.Repository != nil
  107. ctx.Data["Title"] = "Page Not Found"
  108. ctx.HTML(http.StatusNotFound, base.TplName("status/404"))
  109. }
  110. // ServerError displays a 500 (Internal Server Error) page and prints the given
  111. // error, if any.
  112. func (ctx *Context) ServerError(title string, err error) {
  113. if err != nil {
  114. log.Error(4, "%s: %v", title, err)
  115. if macaron.Env != macaron.PROD {
  116. ctx.Data["ErrorMsg"] = err
  117. }
  118. }
  119. ctx.Data["Title"] = "Internal Server Error"
  120. ctx.HTML(http.StatusInternalServerError, base.TplName("status/500"))
  121. }
  122. // NotFoundOrServerError use error check function to determine if the error
  123. // is about not found. It responses with 404 status code for not found error,
  124. // or error context description for logging purpose of 500 server error.
  125. func (ctx *Context) NotFoundOrServerError(title string, errck func(error) bool, err error) {
  126. if errck(err) {
  127. ctx.NotFound(title, err)
  128. return
  129. }
  130. ctx.ServerError(title, err)
  131. }
  132. // HandleText handles HTTP status code
  133. func (ctx *Context) HandleText(status int, title string) {
  134. if (status/100 == 4) || (status/100 == 5) {
  135. log.Error(4, "%s", title)
  136. }
  137. ctx.PlainText(status, []byte(title))
  138. }
  139. // ServeContent serves content to http request
  140. func (ctx *Context) ServeContent(name string, r io.ReadSeeker, params ...interface{}) {
  141. modtime := time.Now()
  142. for _, p := range params {
  143. switch v := p.(type) {
  144. case time.Time:
  145. modtime = v
  146. }
  147. }
  148. ctx.Resp.Header().Set("Content-Description", "File Transfer")
  149. ctx.Resp.Header().Set("Content-Type", "application/octet-stream")
  150. ctx.Resp.Header().Set("Content-Disposition", "attachment; filename="+name)
  151. ctx.Resp.Header().Set("Content-Transfer-Encoding", "binary")
  152. ctx.Resp.Header().Set("Expires", "0")
  153. ctx.Resp.Header().Set("Cache-Control", "must-revalidate")
  154. ctx.Resp.Header().Set("Pragma", "public")
  155. http.ServeContent(ctx.Resp, ctx.Req.Request, name, modtime, r)
  156. }
  157. // Contexter initializes a classic context for a request.
  158. func Contexter() macaron.Handler {
  159. return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) {
  160. ctx := &Context{
  161. Context: c,
  162. Cache: cache,
  163. csrf: x,
  164. Flash: f,
  165. Session: sess,
  166. Link: setting.AppSubURL + strings.TrimSuffix(c.Req.URL.EscapedPath(), "/"),
  167. Repo: &Repository{
  168. PullRequest: &PullRequest{},
  169. },
  170. Org: &Organization{},
  171. }
  172. ctx.Data["Language"] = ctx.Locale.Language()
  173. c.Data["Link"] = ctx.Link
  174. ctx.Data["PageStartTime"] = time.Now()
  175. // Quick responses appropriate go-get meta with status 200
  176. // regardless of if user have access to the repository,
  177. // or the repository does not exist at all.
  178. // This is particular a workaround for "go get" command which does not respect
  179. // .netrc file.
  180. if ctx.Query("go-get") == "1" {
  181. ownerName := c.Params(":username")
  182. repoName := c.Params(":reponame")
  183. branchName := "master"
  184. repo, err := models.GetRepositoryByOwnerAndName(ownerName, repoName)
  185. if err == nil && len(repo.DefaultBranch) > 0 {
  186. branchName = repo.DefaultBranch
  187. }
  188. prefix := setting.AppURL + path.Join(url.QueryEscape(ownerName), url.QueryEscape(repoName), "src", "branch", branchName)
  189. c.Header().Set("Content-Type", "text/html")
  190. c.WriteHeader(http.StatusOK)
  191. c.Write([]byte(com.Expand(`<!doctype html>
  192. <html>
  193. <head>
  194. <meta name="go-import" content="{GoGetImport} git {CloneLink}">
  195. <meta name="go-source" content="{GoGetImport} _ {GoDocDirectory} {GoDocFile}">
  196. </head>
  197. <body>
  198. go get {GoGetImport}
  199. </body>
  200. </html>
  201. `, map[string]string{
  202. "GoGetImport": ComposeGoGetImport(ownerName, strings.TrimSuffix(repoName, ".git")),
  203. "CloneLink": models.ComposeHTTPSCloneURL(ownerName, repoName),
  204. "GoDocDirectory": prefix + "{/dir}",
  205. "GoDocFile": prefix + "{/dir}/{file}#L{line}",
  206. })))
  207. return
  208. }
  209. // Get user from session if logged in.
  210. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session)
  211. if ctx.User != nil {
  212. ctx.IsSigned = true
  213. ctx.Data["IsSigned"] = ctx.IsSigned
  214. ctx.Data["SignedUser"] = ctx.User
  215. ctx.Data["SignedUserID"] = ctx.User.ID
  216. ctx.Data["SignedUserName"] = ctx.User.Name
  217. ctx.Data["IsAdmin"] = ctx.User.IsAdmin
  218. } else {
  219. ctx.Data["SignedUserID"] = int64(0)
  220. ctx.Data["SignedUserName"] = ""
  221. }
  222. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  223. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  224. if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  225. ctx.ServerError("ParseMultipartForm", err)
  226. return
  227. }
  228. }
  229. ctx.Resp.Header().Set(`X-Frame-Options`, `SAMEORIGIN`)
  230. ctx.Data["CsrfToken"] = html.EscapeString(x.GetToken())
  231. ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + ctx.Data["CsrfToken"].(string) + `">`)
  232. log.Debug("Session ID: %s", sess.ID())
  233. log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"])
  234. ctx.Data["IsLandingPageHome"] = setting.LandingPageURL == setting.LandingPageHome
  235. ctx.Data["IsLandingPageExplore"] = setting.LandingPageURL == setting.LandingPageExplore
  236. ctx.Data["IsLandingPageOrganizations"] = setting.LandingPageURL == setting.LandingPageOrganizations
  237. ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton
  238. ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding
  239. ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion
  240. ctx.Data["EnableSwagger"] = setting.API.EnableSwagger
  241. ctx.Data["EnableOpenIDSignIn"] = setting.Service.EnableOpenIDSignIn
  242. c.Map(ctx)
  243. }
  244. }