Changeset - 042d38683d42
[Not reviewed]
beta
0 7 0
Marcin Kuzminski - 15 years ago 2010-12-29 10:39:46
marcin@python-works.com
implemented #89 google analytics code
7 files changed with 64 insertions and 6 deletions:
0 comments (0 inline, 0 general)
rhodecode/controllers/admin/settings.py
Show inline comments
 
@@ -4,70 +4,75 @@
 
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
    
 
    settings controller for rhodecode admin
 
        
 
    :created_on: Jul 14, 2010
 
    :author: marcink
 
    :copyright: (C) 2009-2010 Marcin Kuzminski <marcin@python-works.com>    
 
    :license: GPLv3, see COPYING for more details.
 
"""
 
# This program is free software; you can redistribute it and/or
 
# modify it under the terms of the GNU General Public License
 
# as published by the Free Software Foundation; version 2
 
# of the License or (at your opinion) any later version of the license.
 
# 
 
# This program is distributed in the hope that it will be useful,
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
# GNU General Public License for more details.
 
# 
 
# You should have received a copy of the GNU General Public License
 
# along with this program; if not, write to the Free Software
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 
# MA  02110-1301, USA.
 

	
 
import logging
 
import traceback
 
import formencode
 

	
 
from operator import itemgetter
 
from formencode import htmlfill
 
from pylons import request, session, tmpl_context as c, url, app_globals as g, \
 
    config
 
from pylons.controllers.util import abort, redirect
 
from pylons.i18n.translation import _
 

	
 
from rhodecode.lib import helpers as h
 
from rhodecode.lib.auth import LoginRequired, HasPermissionAllDecorator, \
 
    HasPermissionAnyDecorator, NotAnonymous
 
from rhodecode.lib.base import BaseController, render
 
from rhodecode.lib.celerylib import tasks, run_task
 
from rhodecode.lib.utils import repo2db_mapper, invalidate_cache, \
 
    set_rhodecode_config
 
from rhodecode.model.db import RhodeCodeUi, Repository
 
from rhodecode.model.forms import UserForm, ApplicationSettingsForm, \
 
    ApplicationUiSettingsForm
 
from rhodecode.model.scm import ScmModel
 
from rhodecode.model.settings import SettingsModel
 
from rhodecode.model.user import UserModel
 

	
 
from sqlalchemy import func
 
import formencode
 
import logging
 
import traceback
 

	
 

	
 
log = logging.getLogger(__name__)
 

	
 

	
 
class SettingsController(BaseController):
 
    """REST Controller styled on the Atom Publishing Protocol"""
 
    # To properly map this controller, ensure your config/routing.py
 
    # file has a resource setup:
 
    #     map.resource('setting', 'settings', controller='admin/settings', 
 
    #         path_prefix='/admin', name_prefix='admin_')
 

	
 

	
 
    @LoginRequired()
 
    def __before__(self):
 
        c.admin_user = session.get('admin_user')
 
        c.admin_username = session.get('admin_username')
 
        super(SettingsController, self).__before__()
 

	
 

	
 
    @HasPermissionAllDecorator('hg.admin')
 
    def index(self, format='html'):
 
        """GET /admin/settings: All items in the collection"""
 
        # url('admin_settings')
 

	
 
@@ -102,58 +107,64 @@ class SettingsController(BaseController)
 
        if setting_id == 'mapping':
 
            rm_obsolete = request.POST.get('destroy', False)
 
            log.debug('Rescanning directories with destroy=%s', rm_obsolete)
 

	
 
            initial = ScmModel().repo_scan(g.paths[0][1], g.baseui)
 
            for repo_name in initial.keys():
 
                invalidate_cache('get_repo_cached_%s' % repo_name)
 

	
 
            repo2db_mapper(initial, rm_obsolete)
 

	
 
            h.flash(_('Repositories successfully rescanned'), category='success')
 

	
 
        if setting_id == 'whoosh':
 
            repo_location = self.get_hg_ui_settings()['paths_root_path']
 
            full_index = request.POST.get('full_index', False)
 
            task = run_task(tasks.whoosh_index, repo_location, full_index)
 

	
 
            h.flash(_('Whoosh reindex task scheduled'), category='success')
 
        if setting_id == 'global':
 

	
 
            application_form = ApplicationSettingsForm()()
 
            try:
 
                form_result = application_form.to_python(dict(request.POST))
 
                settings_model = SettingsModel()
 

	
 
                try:
 
                    hgsettings1 = settings_model.get('title')
 
                    hgsettings1.app_settings_value = form_result['rhodecode_title']
 

	
 
                    hgsettings2 = settings_model.get('realm')
 
                    hgsettings2.app_settings_value = form_result['rhodecode_realm']
 

	
 
                    hgsettings3 = settings_model.get('ga_code')
 
                    hgsettings3.app_settings_value = form_result['ga_code']
 

	
 

	
 

	
 
                    self.sa.add(hgsettings1)
 
                    self.sa.add(hgsettings2)
 
                    self.sa.add(hgsettings3)
 
                    self.sa.commit()
 
                    set_rhodecode_config(config)
 
                    h.flash(_('Updated application settings'),
 
                            category='success')
 

	
 
                except:
 
                    log.error(traceback.format_exc())
 
                    h.flash(_('error occurred during updating application settings'),
 
                            category='error')
 

	
 
                    self.sa.rollback()
 

	
 

	
 
            except formencode.Invalid, errors:
 
                return htmlfill.render(
 
                     render('admin/settings/settings.html'),
 
                     defaults=errors.value,
 
                     errors=errors.error_dict or {},
 
                     prefix_error=False,
 
                     encoding="UTF-8")
 

	
 
        if setting_id == 'mercurial':
 
            application_form = ApplicationUiSettingsForm()()
 
            try:
rhodecode/lib/base.py
Show inline comments
 
"""The base Controller API
 

	
 
Provides the BaseController class for subclassing.
 
"""
 
from pylons import config, tmpl_context as c, request, session
 
from pylons.controllers import WSGIController
 
from pylons.templating import render_mako as render
 
from rhodecode import __version__
 
from rhodecode.lib import auth
 
from rhodecode.lib.utils import get_repo_slug
 
from rhodecode.model import meta
 
from rhodecode.model.scm import ScmModel
 
from rhodecode import BACKENDS
 

	
 
class BaseController(WSGIController):
 

	
 
    def __before__(self):
 
        c.rhodecode_version = __version__
 
        c.rhodecode_name = config['rhodecode_title']
 
        c.rhodecode_name = config.get('rhodecode_title')
 
        c.ga_code = config.get('rhodeocode_ga_code')
 
        c.repo_name = get_repo_slug(request)
 
        c.cached_repo_list = ScmModel().get_repos()
 
        c.backends = BACKENDS.keys()
 
        self.cut_off_limit = int(config['cut_off_limit'])
 
        self.cut_off_limit = int(config.get('cut_off_limit'))
 
        self.sa = meta.Session()
 
        scm_model = ScmModel(self.sa)
 
        #c.unread_journal = scm_model.get_unread_journal()
 

	
 
        if c.repo_name:
 
            cached_repo = scm_model.get(c.repo_name)
 
            if cached_repo:
 
                c.repository_tags = cached_repo.tags
 
                c.repository_branches = cached_repo.branches
 
                c.repository_followers = scm_model.get_followers(cached_repo.dbrepo.repo_id)
 
                c.repository_forks = scm_model.get_forks(cached_repo.dbrepo.repo_id)
 
            else:
 
                c.repository_tags = {}
 
                c.repository_branches = {}
 
                c.repository_followers = 0
 
                c.repository_forks = 0
 

	
 

	
 
    def __call__(self, environ, start_response):
 
        """Invoke the Controller"""
 
        # WSGIController.__call__ dispatches to the Controller method
 
        # the request is routed to. This routing information is
 
        # available in environ['pylons.routes_dict']
 
        try:
rhodecode/lib/db_manage.py
Show inline comments
 
@@ -145,95 +145,108 @@ class DbManage(object):
 

	
 
            def __init__(self, klass):
 
                self.klass = klass
 

	
 
            def step_0(self):
 
                #step 0 is the schema upgrade, and than follow proper upgrades
 
                print ('attempting to do database upgrade to version %s' \
 
                                % __dbversion__)
 
                api.upgrade(db_uri, repository_path, __dbversion__)
 
                print ('Schema upgrade completed')
 

	
 
            def step_1(self):
 
                pass
 

	
 
            def step_2(self):
 
                print ('Patching repo paths for newer version of RhodeCode')
 
                self.klass.fix_repo_paths()
 

	
 
                print ('Patching default user of RhodeCode')
 
                self.klass.fix_default_user()
 

	
 
                log.info('Changing ui settings')
 
                self.klass.create_ui_settings()
 

	
 
            def step_3(self):
 
                print ('Adding additional settings into RhodeCode db')
 
                self.klass.fix_settings()
 

	
 
        upgrade_steps = [0] + range(curr_version + 1, __dbversion__ + 1)
 

	
 
        #CALL THE PROPER ORDER OF STEPS TO PERFORM FULL UPGRADE
 
        for step in upgrade_steps:
 
            print ('performing upgrade step %s' % step)
 
            callable = getattr(UpgradeSteps(self), 'step_%s' % step)()
 

	
 

	
 

	
 
    def fix_repo_paths(self):
 
        """Fixes a old rhodecode version path into new one without a '*'
 
        """
 

	
 
        paths = self.sa.query(RhodeCodeUi)\
 
                .filter(RhodeCodeUi.ui_key == '/')\
 
                .scalar()
 

	
 
        paths.ui_value = paths.ui_value.replace('*', '')
 

	
 
        try:
 
            self.sa.add(paths)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
    def fix_default_user(self):
 
        """Fixes a old default user with some 'nicer' default values,
 
        used mostly for anonymous access
 
        """
 
        def_user = self.sa.query(User)\
 
                .filter(User.username == 'default')\
 
                .one()
 

	
 
        def_user.name = 'Anonymous'
 
        def_user.lastname = 'User'
 
        def_user.email = 'anonymous@rhodecode.org'
 

	
 
        try:
 
            self.sa.add(def_user)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
    def fix_settings(self):
 
        """Fixes rhodecode settings adds ga_code key for google analytics
 
        """
 

	
 
        hgsettings3 = RhodeCodeSettings('ga_code', '')
 
        try:
 
            self.sa.add(hgsettings3)
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
    def admin_prompt(self, second=False):
 
        if not self.tests:
 
            import getpass
 

	
 

	
 
            def get_password():
 
                password = getpass.getpass('Specify admin password (min 6 chars):')
 
                confirm = getpass.getpass('Confirm password:')
 

	
 
                if password != confirm:
 
                    log.error('passwords mismatch')
 
                    return False
 
                if len(password) < 6:
 
                    log.error('password is to short use at least 6 characters')
 
                    return False
 

	
 
                return password
 

	
 
            username = raw_input('Specify admin username:')
 

	
 
            password = get_password()
 
            if not password:
 
                #second try
 
@@ -339,58 +352,60 @@ class DbManage(object):
 

	
 
        web2 = RhodeCodeUi()
 
        web2.ui_section = 'web'
 
        web2.ui_key = 'allow_archive'
 
        web2.ui_value = 'gz zip bz2'
 

	
 
        web3 = RhodeCodeUi()
 
        web3.ui_section = 'web'
 
        web3.ui_key = 'allow_push'
 
        web3.ui_value = '*'
 

	
 
        web4 = RhodeCodeUi()
 
        web4.ui_section = 'web'
 
        web4.ui_key = 'baseurl'
 
        web4.ui_value = '/'
 

	
 
        paths = RhodeCodeUi()
 
        paths.ui_section = 'paths'
 
        paths.ui_key = '/'
 
        paths.ui_value = path
 

	
 

	
 
        hgsettings1 = RhodeCodeSettings('realm', 'RhodeCode authentication')
 
        hgsettings2 = RhodeCodeSettings('title', 'RhodeCode')
 
        hgsettings3 = RhodeCodeSettings('ga_code', '')
 

	
 

	
 
        try:
 
            self.sa.add(web1)
 
            self.sa.add(web2)
 
            self.sa.add(web3)
 
            self.sa.add(web4)
 
            self.sa.add(paths)
 
            self.sa.add(hgsettings1)
 
            self.sa.add(hgsettings2)
 
            self.sa.add(hgsettings3)
 

	
 
            self.sa.commit()
 
        except:
 
            self.sa.rollback()
 
            raise
 

	
 
        self.create_ldap_options()
 

	
 
        log.info('created ui config')
 

	
 
    def create_user(self, username, password, email='', admin=False):
 
        log.info('creating administrator user %s', username)
 
        new_user = User()
 
        new_user.username = username
 
        new_user.password = get_crypt_password(password)
 
        new_user.name = 'RhodeCode'
 
        new_user.lastname = 'Admin'
 
        new_user.email = email
 
        new_user.admin = admin
 
        new_user.active = True
 

	
 
        try:
 
            self.sa.add(new_user)
 
            self.sa.commit()
rhodecode/model/forms.py
Show inline comments
 
@@ -417,48 +417,49 @@ def RepoForkForm(edit=False, old_data={}
 
        description = UnicodeString(strip=True, min=1, not_empty=True)
 
        private = StringBoolean(if_missing=False)
 
        repo_type = All(ValidForkType(old_data), OneOf(supported_backends))
 
    return _RepoForkForm
 

	
 
def RepoSettingsForm(edit=False, old_data={}):
 
    class _RepoForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        repo_name = All(UnicodeString(strip=True, min=1, not_empty=True),
 
                        ValidRepoName(edit, old_data))
 
        description = UnicodeString(strip=True, min=1, not_empty=True)
 
        private = StringBoolean(if_missing=False)
 

	
 
        chained_validators = [ValidPerms, ValidSettings]
 
    return _RepoForm
 

	
 

	
 
def ApplicationSettingsForm():
 
    class _ApplicationSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        rhodecode_title = UnicodeString(strip=True, min=1, not_empty=True)
 
        rhodecode_realm = UnicodeString(strip=True, min=1, not_empty=True)
 
        ga_code = UnicodeString(strip=True, min=1, not_empty=False)
 

	
 
    return _ApplicationSettingsForm
 

	
 
def ApplicationUiSettingsForm():
 
    class _ApplicationUiSettingsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = False
 
        web_push_ssl = OneOf(['true', 'false'], if_missing='false')
 
        paths_root_path = All(ValidPath(), UnicodeString(strip=True, min=1, not_empty=True))
 
        hooks_changegroup_update = OneOf(['True', 'False'], if_missing=False)
 
        hooks_changegroup_repo_size = OneOf(['True', 'False'], if_missing=False)
 
        hooks_pretxnchangegroup_push_logger = OneOf(['True', 'False'], if_missing=False)
 
        hooks_preoutgoing_pull_logger = OneOf(['True', 'False'], if_missing=False)
 

	
 
    return _ApplicationUiSettingsForm
 

	
 
def DefaultPermissionsForm(perms_choices, register_choices, create_choices):
 
    class _DefaultPermissionsForm(formencode.Schema):
 
        allow_extra_fields = True
 
        filter_extra_fields = True
 
        overwrite_default = StringBoolean(if_missing=False)
 
        anonymous = OneOf(['True', 'False'], if_missing=False)
 
        default_perm = OneOf(perms_choices)
 
        default_register = OneOf(register_choices)
rhodecode/model/settings.py
Show inline comments
 
@@ -25,48 +25,53 @@ Model for RhodeCode
 

	
 
from rhodecode.lib import helpers as h
 
from rhodecode.model import BaseModel
 
from rhodecode.model.caching_query import FromCache
 
from rhodecode.model.db import  RhodeCodeSettings
 
from sqlalchemy.orm import joinedload
 
import logging
 

	
 
log = logging.getLogger(__name__)
 

	
 
class SettingsModel(BaseModel):
 
    """
 
    Settings model
 
    """
 

	
 
    def get(self, settings_key, cache=False):
 
        r = self.sa.query(RhodeCodeSettings)\
 
            .filter(RhodeCodeSettings.app_settings_name == settings_key).scalar()
 
        if cache:
 
            r = r.options(FromCache("sql_cache_short",
 
                                          "get_setting_%s" % settings_key))
 
        return r
 

	
 
    def get_app_settings(self):
 
        """Get's config from database, each config key is prefixed with 
 
        'rhodecode_' prefix, than global pylons config is updated with such 
 
        keys
 
        """
 

	
 
        ret = self.sa.query(RhodeCodeSettings)\
 
            .options(FromCache("sql_cache_short",
 
                           "get_hg_settings")).all()
 

	
 
        if not ret:
 
            raise Exception('Could not get application settings !')
 
        settings = {}
 
        for each in ret:
 
            settings['rhodecode_' + each.app_settings_name] = each.app_settings_value
 

	
 
        return settings
 

	
 
    def get_ldap_settings(self):
 
        """
 
        Returns ldap settings from database
 
        :returns:
 
        ldap_active
 
        ldap_host
 
        ldap_port 
 
        ldap_ldaps
 
        ldap_dn_user 
 
        ldap_dn_pass 
 
        ldap_base_dn
 
        """
rhodecode/templates/admin/settings/settings.html
Show inline comments
 
@@ -76,49 +76,58 @@
 
    <h3>${_('Global application settings')}</h3> 
 
    ${h.form(url('admin_setting', setting_id='global'),method='put')}
 
    <div class="form">
 
        <!-- fields -->
 
        
 
        <div class="fields">
 
             
 
             <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_title">${_('Application name')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_title',size=30)}
 
                </div>
 
             </div>
 
                          
 
            <div class="field">
 
                <div class="label">
 
                    <label for="rhodecode_realm">${_('Realm text')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('rhodecode_realm',size=30)}
 
                </div>
 
            </div>
 
                                     
 
            
 
            <div class="field">
 
                <div class="label">
 
                    <label for="ga_code">${_('Google analytics code')}:</label>
 
                </div>
 
                <div class="input">
 
                    ${h.text('ga_code',size=30)}
 
                </div>
 
            </div>
 
                                                 
 
            <div class="buttons">
 
                ${h.submit('save','Save settings',class_="ui-button")}
 
                ${h.reset('reset','Reset',class_="ui-button")}
 
           </div>                                                          
 
        </div>
 
    </div>      
 
    ${h.end_form()}
 

	
 
    <h3>${_('Mercurial settings')}</h3> 
 
    ${h.form(url('admin_setting', setting_id='mercurial'),method='put')}
 
    <div class="form">
 
        <!-- fields -->
 
        
 
        <div class="fields">
 
             
 
             <div class="field">
 
                <div class="label label-checkbox">
 
                    <label for="web_push_ssl">${_('Web')}:</label>
 
                </div>
 
                <div class="checkboxes">
 
					<div class="checkbox">
 
						${h.checkbox('web_push_ssl','true')}
 
						<label for="web_push_ssl">${_('require ssl for pushing')}</label>
 
					</div>
rhodecode/templates/base/base.html
Show inline comments
 
## -*- coding: utf-8 -*-
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" id="mainhtml">
 
<head>
 
    <title>${next.title()}</title>
 
    <link rel="icon" href="/images/icons/database_gear.png" type="image/png" />
 
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
 
    <meta name="robots" content="index, nofollow"/>
 
    <!-- stylesheets -->
 
    ${self.css()}
 
    <!-- scripts -->
 
    ${self.js()}
 
%if c.ga_code:
 
<script type="text/javascript">
 

	
 
  var _gaq = _gaq || [];
 
  _gaq.push(['_setAccount', '${c.ga_code}']);
 
  _gaq.push(['_trackPageview']);
 

	
 
  (function() {
 
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
 
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
 
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
 
  })();
 

	
 

	
 
</script>
 
%endif
 
</head>
 
<body>
 
    <!-- header -->
 
    <div id="header">
 
        <!-- user -->
 
        <ul id="logged-user">
 
	            <li class="first">
 
	                <div class="gravatar">
 
	                    <img alt="gravatar" src="${h.gravatar_url(c.rhodecode_user.email,20)}" />
 
	                </div>
 
		            <div class="account">
 
		            %if c.rhodecode_user.username == 'default':
 
                        %if h.HasPermissionAny('hg.admin', 'hg.register.auto_activate', 'hg.register.manual_activate')(): 
 
                            ${h.link_to('anonymous',h.url('register'),title='%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname))}
 
                        %else:
 
                            ${h.link_to('anonymous',h.url('#'),title='%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname))}
 
                        %endif		            
 
                        
 
                    %else:                        		            
 
		            	${h.link_to(c.rhodecode_user.username,h.url('admin_settings_my_account'),title='%s %s'%(c.rhodecode_user.name,c.rhodecode_user.lastname))}
 
		            %endif
 
		            </div>	
 
	            </li>
 
	            <li>
0 comments (0 inline, 0 general)