func UpdateGravatarSource() { gravatarSource = setting.GravatarSource log.Debug("avatar.UpdateGravatarSource(gavatar source): %s", gravatarSource) if !strings.HasPrefix(gravatarSource, "http:") { gravatarSource = "http:" + gravatarSource log.Debug("avatar.UpdateGravatarSource(update gavatar source): %s", gravatarSource) } }
// Contexter initializes a classic context for a request. func Contexter() macaron.Handler { return func(c *macaron.Context, l i18n.Locale, cache cache.Cache, sess session.Store, f *session.Flash, x csrf.CSRF) { ctx := &Context{ Context: c, Cache: cache, csrf: x, Flash: f, Session: sess, Repo: &Repository{ PullRequest: &PullRequest{}, }, Org: &Organization{}, } // Compute current URL for real-time change language. ctx.Data["Link"] = setting.AppSubUrl + strings.TrimSuffix(ctx.Req.URL.Path, "/") ctx.Data["PageStartTime"] = time.Now() // Get user from session if logined. ctx.User, ctx.IsBasicAuth = auth.SignedInUser(ctx.Context, ctx.Session) if ctx.User != nil { ctx.IsSigned = true ctx.Data["IsSigned"] = ctx.IsSigned ctx.Data["SignedUser"] = ctx.User ctx.Data["SignedUserID"] = ctx.User.ID ctx.Data["SignedUserName"] = ctx.User.Name ctx.Data["IsAdmin"] = ctx.User.IsAdmin } else { ctx.Data["SignedUserID"] = 0 ctx.Data["SignedUserName"] = "" } // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") { if err := ctx.Req.ParseMultipartForm(setting.AttachmentMaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size ctx.Handle(500, "ParseMultipartForm", err) return } } ctx.Data["CsrfToken"] = x.GetToken() ctx.Data["CsrfTokenHtml"] = template.HTML(`<input type="hidden" name="_csrf" value="` + x.GetToken() + `">`) log.Debug("Session ID: %s", sess.ID()) log.Debug("CSRF Token: %v", ctx.Data["CsrfToken"]) ctx.Data["ShowRegistrationButton"] = setting.Service.ShowRegistrationButton ctx.Data["ShowFooterBranding"] = setting.ShowFooterBranding ctx.Data["ShowFooterVersion"] = setting.ShowFooterVersion c.Map(ctx) } }
func DetectEncoding(content []byte) (string, error) { if utf8.Valid(content) { log.Debug("Detected encoding: utf-8 (fast)") return "UTF-8", nil } result, err := chardet.NewTextDetector().DetectBest(content) if result.Charset != "UTF-8" && len(setting.Repository.AnsiCharset) > 0 { log.Debug("Using default AnsiCharset: %s", setting.Repository.AnsiCharset) return setting.Repository.AnsiCharset, err } log.Debug("Detected encoding: %s", result.Charset) return result.Charset, err }
// searchEntry : search an LDAP source if an entry (name, passwd) is valide and in the specific filter func (ls Ldapsource) SearchEntry(name, passwd string) (string, string, string, string, bool) { l, err := ldapDial(ls) if err != nil { log.Error(4, "LDAP Connect error, %s:%v", ls.Host, err) ls.Enabled = false return "", "", "", "", false } defer l.Close() nx := fmt.Sprintf(ls.MsAdSAFormat, name) err = l.Bind(nx, passwd) if err != nil { log.Debug("LDAP Authan failed for %s, reason: %s", nx, err.Error()) return "", "", "", "", false } search := ldap.NewSearchRequest( ls.BaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, fmt.Sprintf(ls.Filter, name), []string{ls.AttributeUsername, ls.AttributeName, ls.AttributeSurname, ls.AttributeMail}, nil) sr, err := l.Search(search) if err != nil { log.Debug("LDAP Authen OK but not in filter %s", name) return "", "", "", "", false } log.Debug("LDAP Authen OK: %s", name) if len(sr.Entries) > 0 { cn := sr.Entries[0].GetAttributeValue(ls.AttributeUsername) name := sr.Entries[0].GetAttributeValue(ls.AttributeName) sn := sr.Entries[0].GetAttributeValue(ls.AttributeSurname) mail := sr.Entries[0].GetAttributeValue(ls.AttributeMail) return cn, name, sn, mail, true } return "", "", "", "", true }
func (this *thunderTask) fetch() error { log.Debug("avatar.fetch(fetch new avatar): %s", this.Url) req, _ := http.NewRequest("GET", this.Url, nil) req.Header.Set("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/jpeg,image/png,*/*;q=0.8") req.Header.Set("Accept-Encoding", "deflate,sdch") req.Header.Set("Accept-Language", "zh-CN,zh;q=0.8") req.Header.Set("Cache-Control", "no-cache") req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36") resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() if resp.StatusCode != 200 { return fmt.Errorf("status code: %d", resp.StatusCode) } /* log.Println("headers:", resp.Header) switch resp.Header.Get("Content-Type") { case "image/jpeg": this.SaveFile += ".jpeg" case "image/png": this.SaveFile += ".png" } */ /* imgType := resp.Header.Get("Content-Type") if imgType != "image/jpeg" && imgType != "image/png" { return errors.New("not png or jpeg") } */ tmpFile := this.SaveFile + ".part" // mv to destination when finished fd, err := os.Create(tmpFile) if err != nil { return err } _, err = io.Copy(fd, resp.Body) fd.Close() if err != nil { os.Remove(tmpFile) return err } return os.Rename(tmpFile, this.SaveFile) }
func RepoAssignment(redirect bool, args ...bool) macaron.Handler { return func(ctx *Context) { var ( displayBare bool // To display bare page if it is a bare repo. ) if len(args) >= 1 { displayBare = args[0] } var ( u *models.User err error ) userName := ctx.Params(":username") repoName := ctx.Params(":reponame") refName := ctx.Params(":branchname") if len(refName) == 0 { refName = ctx.Params(":path") } // Check if the user is the same as the repository owner if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { u = ctx.User } else { u, err = models.GetUserByName(userName) if err != nil { if err == models.ErrUserNotExist { ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } } ctx.Repo.Owner = u // Get repository. repo, err := models.GetRepositoryByName(u.Id, repoName) if err != nil { if models.IsErrRepoNotExist(err) { ctx.Handle(404, "GetRepositoryByName", err) } else { ctx.Handle(500, "GetRepositoryByName", err) } return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } mode, err := models.AccessLevel(ctx.User, repo) if err != nil { ctx.Handle(500, "AccessLevel", err) return } ctx.Repo.AccessMode = mode // Check access. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { ctx.Handle(404, "no access right", err) return } ctx.Data["HasAccess"] = true if repo.IsMirror { ctx.Repo.Mirror, err = models.GetMirror(repo.Id) if err != nil { ctx.Handle(500, "GetMirror", err) return } ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval } repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues repo.NumOpenMilestones = repo.NumMilestones - repo.NumClosedMilestones ctx.Repo.Repository = repo ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo ctx.Repo.RepoLink, err = repo.RepoLink() if err != nil { ctx.Handle(500, "RepoLink", err) return } ctx.Data["RepoLink"] = ctx.Repo.RepoLink tags, err := ctx.Repo.GitRepo.GetTags() if err != nil { ctx.Handle(500, "GetTags", err) return } ctx.Data["Tags"] = tags ctx.Repo.Repository.NumTags = len(tags) // Non-fork repository will not return error in this method. if err = repo.GetForkRepo(); err != nil { ctx.Handle(500, "GetForkRepo", err) return } ctx.Data["Title"] = u.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = ctx.Repo.Repository.Owner ctx.Data["IsRepositoryOwner"] = ctx.Repo.AccessMode >= models.ACCESS_MODE_WRITE ctx.Data["IsRepositoryAdmin"] = ctx.Repo.AccessMode >= models.ACCESS_MODE_ADMIN ctx.Data["DisableSSH"] = setting.DisableSSH ctx.Repo.CloneLink, err = repo.CloneLink() if err != nil { ctx.Handle(500, "CloneLink", err) return } ctx.Data["CloneLink"] = ctx.Repo.CloneLink if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = fmt.Sprintf("%s/%s/%s", setting.Domain, u.LowerName, repo.LowerName) } // repo is bare and display enable if ctx.Repo.Repository.IsBare { log.Debug("Bare repository: %s", ctx.Repo.RepoLink) // NOTE: to prevent templating error ctx.Data["BranchName"] = "" if displayBare { ctx.HTML(200, "repo/bare") } return } if ctx.IsSigned { ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.Id, repo.Id) ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.Id, repo.Id) } ctx.Data["TagName"] = ctx.Repo.TagName brs, err := ctx.Repo.GitRepo.GetBranches() if err != nil { ctx.Handle(500, "GetBranches", err) return } ctx.Data["Branches"] = brs ctx.Data["BrancheCount"] = len(brs) // If not branch selected, try default one. // If default branch doesn't exists, fall back to some other branch. if ctx.Repo.BranchName == "" { if ctx.Repo.Repository.DefaultBranch != "" && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch } else if len(brs) > 0 { ctx.Repo.BranchName = brs[0] } } ctx.Data["BranchName"] = ctx.Repo.BranchName ctx.Data["CommitId"] = ctx.Repo.CommitId } }
func RepoAssignment(args ...bool) macaron.Handler { return func(ctx *Context) { var ( displayBare bool // To display bare page if it is a bare repo. ) if len(args) >= 1 { displayBare = args[0] } var ( owner *models.User err error ) userName := ctx.Params(":username") repoName := ctx.Params(":reponame") refName := ctx.Params(":branchname") if len(refName) == 0 { refName = ctx.Params(":path") } // Check if the user is the same as the repository owner if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) { owner = ctx.User } else { owner, err = models.GetUserByName(userName) if err != nil { if models.IsErrUserNotExist(err) { if ctx.Query("go-get") == "1" { earlyResponseForGoGetMeta(ctx) return } ctx.Handle(404, "GetUserByName", err) } else { ctx.Handle(500, "GetUserByName", err) } return } } ctx.Repo.Owner = owner ctx.Data["Username"] = ctx.Repo.Owner.Name // Get repository. repo, err := models.GetRepositoryByName(owner.ID, repoName) if err != nil { if models.IsErrRepoNotExist(err) { if ctx.Query("go-get") == "1" { earlyResponseForGoGetMeta(ctx) return } ctx.Handle(404, "GetRepositoryByName", err) } else { ctx.Handle(500, "GetRepositoryByName", err) } return } else if err = repo.GetOwner(); err != nil { ctx.Handle(500, "GetOwner", err) return } // Admin has super access. if ctx.IsSigned && ctx.User.IsAdmin { ctx.Repo.AccessMode = models.ACCESS_MODE_OWNER } else { mode, err := models.AccessLevel(ctx.User, repo) if err != nil { ctx.Handle(500, "AccessLevel", err) return } ctx.Repo.AccessMode = mode } // Check access. if ctx.Repo.AccessMode == models.ACCESS_MODE_NONE { if ctx.Query("go-get") == "1" { earlyResponseForGoGetMeta(ctx) return } ctx.Handle(404, "no access right", err) return } ctx.Data["HasAccess"] = true if repo.IsMirror { ctx.Repo.Mirror, err = models.GetMirrorByRepoID(repo.ID) if err != nil { ctx.Handle(500, "GetMirror", err) return } ctx.Data["MirrorEnablePrune"] = ctx.Repo.Mirror.EnablePrune ctx.Data["MirrorInterval"] = ctx.Repo.Mirror.Interval ctx.Data["Mirror"] = ctx.Repo.Mirror } ctx.Repo.Repository = repo ctx.Data["RepoName"] = ctx.Repo.Repository.Name ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare gitRepo, err := git.OpenRepository(models.RepoPath(userName, repoName)) if err != nil { ctx.Handle(500, "RepoAssignment Invalid repo "+models.RepoPath(userName, repoName), err) return } ctx.Repo.GitRepo = gitRepo ctx.Repo.RepoLink = repo.Link() ctx.Data["RepoLink"] = ctx.Repo.RepoLink ctx.Data["RepoRelPath"] = ctx.Repo.Owner.Name + "/" + ctx.Repo.Repository.Name tags, err := ctx.Repo.GitRepo.GetTags() if err != nil { ctx.Handle(500, "GetTags", err) return } ctx.Data["Tags"] = tags ctx.Repo.Repository.NumTags = len(tags) ctx.Data["Title"] = owner.Name + "/" + repo.Name ctx.Data["Repository"] = repo ctx.Data["Owner"] = ctx.Repo.Repository.Owner ctx.Data["IsRepositoryOwner"] = ctx.Repo.IsOwner() ctx.Data["IsRepositoryAdmin"] = ctx.Repo.IsAdmin() ctx.Data["IsRepositoryWriter"] = ctx.Repo.IsWriter() ctx.Data["DisableSSH"] = setting.SSH.Disabled ctx.Data["CloneLink"] = repo.CloneLink() ctx.Data["WikiCloneLink"] = repo.WikiCloneLink() if ctx.IsSigned { ctx.Data["IsWatchingRepo"] = models.IsWatching(ctx.User.ID, repo.ID) ctx.Data["IsStaringRepo"] = models.IsStaring(ctx.User.ID, repo.ID) } // repo is bare and display enable if ctx.Repo.Repository.IsBare { log.Debug("Bare repository: %s", ctx.Repo.RepoLink) // NOTE: to prevent templating error ctx.Data["BranchName"] = "" if displayBare { if !ctx.Repo.IsAdmin() { ctx.Flash.Info(ctx.Tr("repo.repo_is_empty"), true) } ctx.HTML(200, "repo/bare") } return } ctx.Data["TagName"] = ctx.Repo.TagName brs, err := ctx.Repo.GitRepo.GetBranches() if err != nil { ctx.Handle(500, "GetBranches", err) return } ctx.Data["Branches"] = brs ctx.Data["BrancheCount"] = len(brs) // If not branch selected, try default one. // If default branch doesn't exists, fall back to some other branch. if len(ctx.Repo.BranchName) == 0 { if len(ctx.Repo.Repository.DefaultBranch) > 0 && gitRepo.IsBranchExist(ctx.Repo.Repository.DefaultBranch) { ctx.Repo.BranchName = ctx.Repo.Repository.DefaultBranch } else if len(brs) > 0 { ctx.Repo.BranchName = brs[0] } } ctx.Data["BranchName"] = ctx.Repo.BranchName ctx.Data["CommitID"] = ctx.Repo.CommitID if repo.IsFork { RetrieveBaseRepo(ctx, repo) if ctx.Written() { return } } // People who have push access or have fored repository can propose a new pull request. if ctx.Repo.IsWriter() || (ctx.IsSigned && ctx.User.HasForkedRepo(ctx.Repo.Repository.ID)) { // Pull request is allowed if this is a fork repository // and base repository accepts pull requests. if repo.BaseRepo != nil { if repo.BaseRepo.AllowsPulls() { ctx.Data["BaseRepo"] = repo.BaseRepo ctx.Repo.PullRequest.BaseRepo = repo.BaseRepo ctx.Repo.PullRequest.Allowed = true ctx.Repo.PullRequest.HeadInfo = ctx.Repo.Owner.Name + ":" + ctx.Repo.BranchName } } else { // Or, this is repository accepts pull requests between branches. if repo.AllowsPulls() { ctx.Data["BaseRepo"] = repo ctx.Repo.PullRequest.BaseRepo = repo ctx.Repo.PullRequest.Allowed = true ctx.Repo.PullRequest.SameRepo = true ctx.Repo.PullRequest.HeadInfo = ctx.Repo.BranchName } } } ctx.Data["PullRequestCtx"] = ctx.Repo.PullRequest if ctx.Query("go-get") == "1" { ctx.Data["GoGetImport"] = composeGoGetImport(owner.Name, repo.Name) prefix := setting.AppUrl + path.Join(owner.Name, repo.Name, "src", ctx.Repo.BranchName) ctx.Data["GoDocDirectory"] = prefix + "{/dir}" ctx.Data["GoDocFile"] = prefix + "{/dir}/{file}#L{line}" } } }
// CommitRepoAction adds new action for committing repository. func CommitRepoAction(userId, repoUserId int64, userName, actEmail string, repoId int64, repoUserName, repoName string, refFullName string, commit *base.PushCommits, oldCommitId string, newCommitId string) error { opType := COMMIT_REPO // Check it's tag push or branch. if strings.HasPrefix(refFullName, "refs/tags/") { opType = PUSH_TAG commit = &base.PushCommits{} } repoLink := fmt.Sprintf("%s%s/%s", setting.AppUrl, repoUserName, repoName) // if not the first commit, set the compareUrl if !strings.HasPrefix(oldCommitId, "0000000") { commit.CompareUrl = fmt.Sprintf("%s/compare/%s...%s", repoLink, oldCommitId, newCommitId) } bs, err := json.Marshal(commit) if err != nil { return errors.New("action.CommitRepoAction(json): " + err.Error()) } refName := git.RefEndName(refFullName) // Change repository bare status and update last updated time. repo, err := GetRepositoryByName(repoUserId, repoName) if err != nil { return errors.New("action.CommitRepoAction(GetRepositoryByName): " + err.Error()) } repo.IsBare = false if err = UpdateRepository(repo, false); err != nil { return errors.New("action.CommitRepoAction(UpdateRepository): " + err.Error()) } err = updateIssuesCommit(userId, repoId, repoUserName, repoName, commit.Commits) if err != nil { log.Debug("action.CommitRepoAction(updateIssuesCommit): ", err) } if err = NotifyWatchers(&Action{ ActUserID: userId, ActUserName: userName, ActEmail: actEmail, OpType: opType, Content: string(bs), RepoID: repoId, RepoUserName: repoUserName, RepoName: repoName, RefName: refName, IsPrivate: repo.IsPrivate, }); err != nil { return errors.New("action.CommitRepoAction(NotifyWatchers): " + err.Error()) } // New push event hook. if err := repo.GetOwner(); err != nil { return errors.New("action.CommitRepoAction(GetOwner): " + err.Error()) } ws, err := GetActiveWebhooksByRepoId(repoId) if err != nil { return errors.New("action.CommitRepoAction(GetActiveWebhooksByRepoId): " + err.Error()) } // check if repo belongs to org and append additional webhooks if repo.Owner.IsOrganization() { // get hooks for org orgws, err := GetActiveWebhooksByOrgId(repo.OwnerId) if err != nil { return errors.New("action.CommitRepoAction(GetActiveWebhooksByOrgId): " + err.Error()) } ws = append(ws, orgws...) } if len(ws) == 0 { return nil } pusher_email, pusher_name := "", "" pusher, err := GetUserByName(userName) if err == nil { pusher_email = pusher.Email pusher_name = pusher.GetFullNameFallback() } commits := make([]*PayloadCommit, len(commit.Commits)) for i, cmt := range commit.Commits { author_username := "" author, err := GetUserByEmail(cmt.AuthorEmail) if err == nil { author_username = author.Name } commits[i] = &PayloadCommit{ Id: cmt.Sha1, Message: cmt.Message, Url: fmt.Sprintf("%s/commit/%s", repoLink, cmt.Sha1), Author: &PayloadAuthor{ Name: cmt.AuthorName, Email: cmt.AuthorEmail, UserName: author_username, }, } } p := &Payload{ Ref: refFullName, Commits: commits, Repo: &PayloadRepo{ Id: repo.Id, Name: repo.LowerName, Url: repoLink, Description: repo.Description, Website: repo.Website, Watchers: repo.NumWatches, Owner: &PayloadAuthor{ Name: repo.Owner.GetFullNameFallback(), Email: repo.Owner.Email, UserName: repo.Owner.Name, }, Private: repo.IsPrivate, }, Pusher: &PayloadAuthor{ Name: pusher_name, Email: pusher_email, UserName: userName, }, Before: oldCommitId, After: newCommitId, CompareUrl: commit.CompareUrl, } for _, w := range ws { w.GetEvent() if !w.HasPushEvent() { continue } var payload BasePayload switch w.HookTaskType { case SLACK: s, err := GetSlackPayload(p, w.Meta) if err != nil { return errors.New("action.GetSlackPayload: " + err.Error()) } payload = s default: payload = p p.Secret = w.Secret } if err = CreateHookTask(&HookTask{ Type: w.HookTaskType, Url: w.Url, BasePayload: payload, ContentType: w.ContentType, EventType: HOOK_EVENT_PUSH, IsSsl: w.IsSsl, }); err != nil { return fmt.Errorf("CreateHookTask: %v", err) } } return nil }
// HTML calls Context.HTML and converts template name to string. func (ctx *Context) HTML(status int, name base.TplName) { log.Debug("Template: %s", name) ctx.Context.HTML(status, string(name)) }