Exemplo n.º 1
0
def is_configured():
    configured = config.get_bool('adhocracy.use_feedback_instance')
    if not configured:
        return False
    if not config.get_bool('adhocracy.feedback_check_instance'):
        return True
    return get_feedback_instance() is not None
Exemplo n.º 2
0
 def __init__(self):
     self.staticpages_api_token = config.get(
         'adhocracy_service.staticpages.rest_api_token',
         config.get('adhocracy_service.rest_api_token'))
     self.staticpages_api_address = staticpages_api_address()
     self.staticpages_verify = config.get_bool(
         'adhocracy_service.staticpages.verify_ssl',
         config.get_bool('adhocracy_service.verify_ssl'))
     self.staticpages_headers = {"X-API-Token": self.staticpages_api_token}
Exemplo n.º 3
0
 def __init__(self):
     self.staticpages_api_token = config.get(
         'adhocracy_service.staticpages.rest_api_token',
         config.get('adhocracy_service.rest_api_token'))
     self.staticpages_api_address = staticpages_api_address()
     self.staticpages_verify = config.get_bool(
         'adhocracy_service.staticpages.verify_ssl',
         config.get_bool('adhocracy_service.verify_ssl'))
     self.staticpages_headers = {"X-API-Token": self.staticpages_api_token}
Exemplo n.º 4
0
class ShibbolethRegisterForm(formencode.Schema):
    _tok = formencode.validators.String()
    if not config.get_bool('adhocracy.force_randomized_user_names'):
        username = formencode.All(
            formencode.validators.PlainText(not_empty=True),
            forms.UniqueUsername(), forms.ContainsChar())
    if config.get_bool('adhocracy.set_display_name_on_register'):
        display_name = formencode.validators.String(not_empty=False,
                                                    if_missing=None)
    email = formencode.All(
        formencode.validators.Email(
            not_empty=config.get_bool('adhocracy.require_email')),
        forms.UniqueEmail())
Exemplo n.º 5
0
    def _get_allowed_sender_options(cls, user):
        sender_options = {
            'user': {
                'email': user.email,
                'checked': False,
                'enabled': user.is_email_activated(),
                'reason': _("Email isn't activated"),
            },
            'system': {
                'email': config.get('adhocracy.email.from'),
                'checked': False,
                'enabled': config.get_bool(
                    'allow_system_email_in_mass_messages'),
                'reason': _("Not permitted in system settings"),
            },
            'support': {
                'email': config.get('adhocracy.registration_support_email'),
                'checked': False,
                'enabled': (config.get('adhocracy.registration_support_email')
                            is not None),
                'reason': _("adhocracy.registration_support_email not set"),
            }
        }

        if sender_options['user']['enabled']:
            sender_options['user']['checked'] = True
        elif sender_options['system']['enabled']:
            sender_options['system']['checked'] = True

        return sender_options
Exemplo n.º 6
0
Arquivo: debug.py Projeto: alkadis/vcv
    def explain(self):
        if not config.get_bool("adhocracy.debug.sql"):
            raise ValueError("Not in debugging mode")
        statement = request.params.get("statement")
        if not statement.lower().startswith("select"):
            raise ValueError("We explain only select statements")
        parameters = request.params.get("parameters")
        c.parameters = json_loads(parameters)

        # collect explain results
        if engine.name.startswith("sqlite"):
            explain_query = "EXPLAIN QUERY PLAN %s" % statement
        else:
            explain_query = "EXPLAIN %s" % statement

        explain_result = engine.execute(explain_query, c.parameters)
        data_result = engine.execute(statement, c.parameters)
        c.results = []
        for (title, result) in (("Explain", explain_result), ("Data", data_result)):
            c.results.append({"title": title, "result": result.fetchall(), "headers": result.keys()})

        # other data to display
        c.statement = statement
        c.duration = float(request.params["duration"])

        return render("/debug/explain.html")
Exemplo n.º 7
0
    def create(cls, key, label, user, description=None, locale=None):
        from group import Group
        from membership import Membership
        from page import Page

        instance = Instance(unicode(key).lower(), label, user)
        instance.description = description
        instance.default_group = Group.by_code(Group.INSTANCE_DEFAULT)
        if locale is not None:
            instance.locale = locale
        meta.Session.add(instance)
        supervisor_group = Group.by_code(Group.CODE_SUPERVISOR)
        membership = Membership(user, instance, supervisor_group,
                                approved=True)
        meta.Session.add(membership)
        if config.get_bool('adhocracy.create_initial_instance_page'):
            Page.create(instance, label, u"", user)

        # Autojoin the user in instances
        config_autojoin = config.get('adhocracy.instances.autojoin')
        if (config_autojoin and
                (config_autojoin == 'ALL' or
                 key in (k.strip() for k in config_autojoin.split(',')))):
            users = adhocracy.model.User.all()
            for u in users:
                autojoin_membership = Membership(u, instance,
                                                 instance.default_group)
                meta.Session.add(autojoin_membership)

        meta.Session.flush()
        return instance
Exemplo n.º 8
0
    def create(cls, key, label, user, description=None, locale=None):
        from group import Group
        from membership import Membership
        from page import Page

        instance = Instance(unicode(key).lower(), label, user)
        instance.description = description
        instance.default_group = Group.by_code(Group.INSTANCE_DEFAULT)
        if locale is not None:
            instance.locale = locale
        meta.Session.add(instance)
        supervisor_group = Group.by_code(Group.CODE_SUPERVISOR)
        membership = Membership(user, instance, supervisor_group,
                                approved=True)
        meta.Session.add(membership)
        if config.get_bool('adhocracy.create_initial_instance_page'):
            Page.create(instance, label, u"", user)

        # Autojoin the user in instances
        config_autojoin = config.get('adhocracy.instances.autojoin')
        if (config_autojoin and
                (config_autojoin == 'ALL' or
                 key in (k.strip() for k in config_autojoin.split(',')))):
            users = adhocracy.model.User.all()
            for u in users:
                autojoin_membership = Membership(u, instance,
                                                 instance.default_group)
                meta.Session.add(autojoin_membership)

        meta.Session.flush()
        return instance
Exemplo n.º 9
0
    def _get_allowed_sender_options(cls, user):
        sender_options = {
            'user': {
                'email': user.email,
                'checked': False,
                'enabled': user.is_email_activated(),
                'reason': _("Email isn't activated"),
            },
            'system': {
                'email': config.get('adhocracy.email.from'),
                'checked': False,
                'enabled':
                config.get_bool('allow_system_email_in_mass_messages'),
                'reason': _("Not permitted in system settings"),
            },
            'support': {
                'email':
                config.get('adhocracy.registration_support_email'),
                'checked':
                False,
                'enabled': (config.get('adhocracy.registration_support_email')
                            is not None),
                'reason':
                _("adhocracy.registration_support_email not set"),
            }
        }

        if sender_options['user']['enabled']:
            sender_options['user']['checked'] = True
        elif sender_options['system']['enabled']:
            sender_options['system']['checked'] = True

        return sender_options
Exemplo n.º 10
0
    def explain(self):
        if not config.get_bool('adhocracy.debug.sql'):
            raise ValueError('Not in debugging mode')
        statement = request.params.get('statement')
        if not statement.lower().startswith('select'):
            raise ValueError('We explain only select statements')
        parameters = request.params.get('parameters')
        c.parameters = json_loads(parameters)

        # collect explain results
        if engine.name.startswith('sqlite'):
            explain_query = 'EXPLAIN QUERY PLAN %s' % statement
        else:
            explain_query = 'EXPLAIN %s' % statement

        explain_result = engine.execute(explain_query, c.parameters)
        data_result = engine.execute(statement, c.parameters)
        c.results = []
        for (title, result) in (('Explain', explain_result), ('Data',
                                                              data_result)):
            c.results.append({
                'title': title,
                'result': result.fetchall(),
                'headers': result.keys()
            })

        # other data to display
        c.statement = statement
        c.duration = float(request.params['duration'])

        return render('/debug/explain.html')
Exemplo n.º 11
0
    def index(self, format='html'):

        if c.instance:
            redirect(h.entity_url(c.instance))

        if format == 'rss':
            return EventController().all(format='rss')

        name = config.get('adhocracy.redirect_startpage_to_instance')
        if name != u'':
            # get_entity_or_abort does no work for instances
            instance = model.Instance.find(name)
            if instance is not None:
                redirect(h.entity_url(instance))

        data = {}

        instances_in_root = config.get_int(
            'adhocracy.startpage.instances.list_length')
        if instances_in_root > 0:
            data['instances'] = model.Instance.all(limit=instances_in_root)
        elif instances_in_root == -1:
            data['instances'] = model.Instance.all()

        add_static_content(data, u'adhocracy.static_index_path')
        c.body_css_classes += data.get('css_classes', [])
        c.body_css_classes.append('added_static_content')
        if data['title'] is None:
            data['title'] = config.get('adhocracy.site.name')

        proposals_number = config.get_int(
            'adhocracy.startpage.proposals.list_length')

        if proposals_number > 0:
            proposals = model.Proposal.all_q()\
                .join(model.Instance).filter(not_(
                    model.Instance.key.in_(model.Instance.SPECIAL_KEYS)))\
                .order_by(model.Proposal.create_time.desc())

            data['new_proposals_pager'] = pager.proposals(
                proposals, size=proposals_number,
                default_sort=sorting.entity_newest,
                enable_pages=False,
                enable_sorts=False)
        else:
            data['new_proposals_pager'] = None

        if config.get_bool('adhocracy.show_stats_on_frontpage'):
            data['stats_global'] = {
                "members": model.User.all_q().count(),
                "comments": model.Comment.all_q().count(),
                "proposals": model.Proposal.all_q().count(),
                "votes": model.Vote.all_q().count(),
            }

        if format == 'overlay':
            return render('index.html', data, overlay=True)
        else:
            return render('index.html', data)
Exemplo n.º 12
0
    def _register(self, persistent_id):

        # initializing user data dict
        user_data = {}

        user_data['email'] = get_attribute(request, 'shib-email', None)

        if config.get_bool('adhocracy.force_randomized_user_names'):
            user_data['username'] = None
        else:
            user_data['username'] = get_attribute(request, 'shib-username')

        user_data['display_name'] = self._get_display_name()

        locale_attribute = config.get("adhocracy.shibboleth.locale.attribute")
        if locale_attribute is not None:
            user_data['locale'] = get_attribute(request, locale_attribute)

        # what to do
        if request.method == 'GET':
            if config.get_bool('adhocracy.shibboleth.register_form'):
                # render a form for missing uaser data
                return self._register_form(defaults=user_data)
            else:
                # register_form is False -> user data should be complete
                return self._create_user_and_login(persistent_id, **user_data)

        else:  # POST
            check_csrf()

            try:
                form_result = ShibbolethRegisterForm().to_python(
                    request.POST)

                user_data['username'] = form_result.get(
                    'username', user_data['username'])
                user_data['display_name'] = form_result.get(
                    'display_name', user_data['display_name'])
                user_data['email'] = form_result.get(
                    'email', user_data['email'])

                return self._create_user_and_login(persistent_id, **user_data)

            except formencode.Invalid, i:
                return self._register_form(errors=i.unpack_errors())
Exemplo n.º 13
0
    def _register(self, persistent_id):

        # initializing user data dict
        user_data = {}

        user_data['email'] = get_attribute(request, 'shib-email', None)

        if config.get_bool('adhocracy.force_randomized_user_names'):
            user_data['username'] = None
        else:
            user_data['username'] = get_attribute(request, 'shib-username')

        user_data['display_name'] = self._get_display_name()

        locale_attribute = config.get("adhocracy.shibboleth.locale.attribute")
        if locale_attribute is not None:
            user_data['locale'] = get_attribute(request, locale_attribute)

        # what to do
        if request.method == 'GET':
            if config.get_bool('adhocracy.shibboleth.register_form'):
                # render a form for missing uaser data
                return self._register_form(defaults=user_data)
            else:
                # register_form is False -> user data should be complete
                return self._create_user_and_login(persistent_id, **user_data)

        else:  # POST
            check_csrf()

            try:
                form_result = ShibbolethRegisterForm().to_python(request.POST)

                user_data['username'] = form_result.get(
                    'username', user_data['username'])
                user_data['display_name'] = form_result.get(
                    'display_name', user_data['display_name'])
                user_data['email'] = form_result.get('email',
                                                     user_data['email'])

                return self._create_user_and_login(persistent_id, **user_data)

            except formencode.Invalid, i:
                return self._register_form(errors=i.unpack_errors())
Exemplo n.º 14
0
class InstanceVotingEditForm(formencode.Schema):
    allow_extra_fields = True
    allow_delegate = validators.StringBool(not_empty=False, if_empty=False,
                                           if_missing=False)
    if not config.get_bool('adhocracy.hide_final_adoption_votings'):
        allow_adopt = validators.StringBool(not_empty=False, if_empty=False,
                                            if_missing=False)
        activation_delay = validators.Int(not_empty=True)
        required_majority = validators.Number(not_empty=True)
    votedetail_badges = forms.ValidUserBadges()
Exemplo n.º 15
0
Arquivo: index.py Projeto: alkadis/vcv
def make_connection():
    solr_url = config.get_string('adhocracy.solr.url',
                                 'http://localhost:8983/solr/')
    solr_url = solr_url.strip()
    if not solr_url.endswith('/'):
        solr_url = solr_url + '/'
    kwargs = {}
    if config.get_bool('adhocracy.force_no_http_proxy'):
        kwargs['proxy_info'] = None
    http_connection = Http(**kwargs)
    return SolrInterface(solr_url, http_connection=http_connection)
Exemplo n.º 16
0
def show(name, user):
    if not config.get_bool('adhocracy.show_tutorials'):
        return False

    if user is not None and user.no_help:
        return False
    if session.get(ALLKEY, False):
        return False
    elif session.get(ONEKEY % name):
        return False
    else:
        return True
Exemplo n.º 17
0
def render_footer_column(instance, column):
    if not config.get_bool('adhocracy.customize_footer'):
        return None
    path = u'footer_' + unicode(column)
    if instance and\
       instance.key in config.get('adhocracy.instance_footers'):
        path = u'%s_%s' % (path, instance.key)
    page = staticpage.get_static_page(path)
    if page is None:
        return None
    else:
        return page.body
Exemplo n.º 18
0
Arquivo: index.py Projeto: alkadis/vcv
def make_connection():
    solr_url = config.get_string('adhocracy.solr.url',
                                 'http://localhost:8983/solr/')
    solr_url = solr_url.strip()
    if not solr_url.endswith('/'):
        solr_url = solr_url + '/'
    kwargs = {}
    if config.get_bool('adhocracy.force_no_http_proxy'):
        kwargs['proxy_info'] = None
    http_connection = Http(**kwargs)
    return SolrInterface(solr_url,
                         http_connection=http_connection)
Exemplo n.º 19
0
 def __init__(self, app, domain, config):
     self.app = app
     self.domain = domain
     self.config = config
     log.debug("Host name: %s." % domain)
     if aconfig.get_bool('adhocracy.instance_domains.enabled',
                         config=config):
         instances_domains = aconfig.get_json('adhocracy.instance_domains',
                                              {}, config=config)
         self.domains_instances = dict((v, k) for k, v
                                       in instances_domains.items())
     else:
         self.domains_instances = {}
Exemplo n.º 20
0
Arquivo: error.py Projeto: alkadis/vcv
    def document(self):
        resp = request.environ.get('pylons.original_response')
        if resp is None:
            raise abort(404)
        response.status = resp.status
        if resp.content_type == 'text/javascript':
            response.content_type == resp.content_type
            return resp.body

        c.error_code = resp.status_int

        c.hide_notify = (c.error_code not in [400, 500])

        # Try to extract error message from environment, e.g.
        # adhocracy.lib.templating.ret_status sets this.
        c.error_message = request.environ.get('adhocracy.error_message')

        if not c.error_message:
            # Try to extract error message from stub response
            for match in BODY_RE.finditer(resp.body):
                c.error_message = match.group(1).strip()

        if not c.error_message:
            # Fallback to default empty message
            c.error_message = ERROR_MESSAGES.get(c.error_code, '')

        c.error_name = ERROR_NAMES.get(c.error_code, '')

        if config.get_bool('adhocracy.interactive_debugging'):
            c.trace_url = request.environ['pylons.original_response']\
                .headers.get('X-Debug-URL', None)

            if c.trace_url is not None:
                # this may only happen in debug mode
                assert(config.get_bool('debug', False))
        else:
            c.trace_url = None

        return render("/error/http.html")
Exemplo n.º 21
0
Arquivo: error.py Projeto: alkadis/vcv
    def document(self):
        resp = request.environ.get("pylons.original_response")
        if resp is None:
            raise abort(404)
        response.status = resp.status
        if resp.content_type == "text/javascript":
            response.content_type == resp.content_type
            return resp.body

        c.error_code = resp.status_int

        c.hide_notify = c.error_code not in [400, 500]

        # Try to extract error message from environment, e.g.
        # adhocracy.lib.templating.ret_status sets this.
        c.error_message = request.environ.get("adhocracy.error_message")

        if not c.error_message:
            # Try to extract error message from stub response
            for match in BODY_RE.finditer(resp.body):
                c.error_message = match.group(1).strip()

        if not c.error_message:
            # Fallback to default empty message
            c.error_message = ERROR_MESSAGES.get(c.error_code, "")

        c.error_name = ERROR_NAMES.get(c.error_code, "")

        if config.get_bool("adhocracy.interactive_debugging"):
            c.trace_url = request.environ["pylons.original_response"].headers.get("X-Debug-URL", None)

            if c.trace_url is not None:
                # this may only happen in debug mode
                assert config.get_bool("debug", False)
        else:
            c.trace_url = None

        return render("/error/http.html")
Exemplo n.º 22
0
    def _register(self, persistent_id):

        if request.method == 'GET':

            defaults = {
                'email': request.headers.get('shib-email'),
            }
            return self._register_form(defaults=defaults)

        # POST
        check_csrf()

        try:
            form_result = ShibbolethRegisterForm().to_python(request.params)

            if config.get_bool('adhocracy.force_randomized_user_names'):
                username = None
            else:
                username = form_result['username']
            if config.get_bool('adhocracy.set_display_name_on_register'):
                display_name = form_result['display_name']
            else:
                display_name = None
            user = User.create(username,
                               form_result['email'],
                               display_name=display_name,
                               shibboleth_persistent_id=persistent_id)

            # NOTE: We might want to automatically join the current instance
            # here at some point

            meta.Session.commit()

            return self._login(user, h.user.post_register_url(user))

        except formencode.Invalid, i:
            return self._register_form(errors=i.unpack_errors())
Exemplo n.º 23
0
 def __init__(self, options, badge_transform):
     super(UserTransform, self).__init__(options)
     self._badge_transform = badge_transform
     self._opt_personal = self._options.get("user_personal", False)
     if self._opt_personal:
         if config.get_bool("adhocracy.export_personal_email"):
             self._ID_KEY = "email"
         else:
             self._ID_KEY = "user_name"
     else:
         self._ID_KEY = "id"
         self._get_by_key = self._model_class.find
     self._opt_password = self._options.get("user_password", False)
     self._opt_badges = self._options.get("include_badge", False)
     self._opt_welcome = self._options.get("welcome", False)
Exemplo n.º 24
0
    def _register_form(self, defaults=None, errors=None):

        data = {
            'email_required': (config.get_bool('adhocracy.require_email')),
        }
        add_static_content(data,
                           u'adhocracy.static_shibboleth_register_ontop_path',
                           body_key=u'body_ontop')
        add_static_content(data,
                           u'adhocracy.static_shibboleth_register_below_path',
                           body_key=u'body_below', title_key=u'_ignored')
        return formencode.htmlfill.render(
            render("/shibboleth/register.html", data),
            defaults=defaults, errors=errors,
            force_defaults=False)
Exemplo n.º 25
0
 def __init__(self, options, badge_transform):
     super(UserTransform, self).__init__(options)
     self._badge_transform = badge_transform
     self._opt_personal = self._options.get('user_personal', False)
     if self._opt_personal:
         if config.get_bool('adhocracy.export_personal_email'):
             self._ID_KEY = 'email'
         else:
             self._ID_KEY = 'user_name'
     else:
         self._ID_KEY = 'id'
         self._get_by_key = self._model_class.find
     self._opt_password = self._options.get('user_password', False)
     self._opt_badges = self._options.get('include_badge', False)
     self._opt_welcome = self._options.get('welcome', False)
Exemplo n.º 26
0
    def _login(self, user, target):
        self._update_userbadges(user)

        if config.get_bool('adhocracy.shibboleth.display_name.force_update'):
            display_name = self._get_display_name()
            if display_name is not None:
                user.display_name = display_name
                meta.Session.commit()

        login_user(user, request, response)
        session['login_type'] = 'shibboleth'

        came_from = request.GET.get('came_from', target)
        qs = urlencode({'return': came_from})

        return redirect('/Shibboleth.sso/Logout?%s' % qs)
Exemplo n.º 27
0
    def _login(self, user, target):
        self._update_userbadges(user)

        if config.get_bool('adhocracy.shibboleth.display_name.force_update'):
            display_name = self._get_display_name()
            if display_name is not None:
                user.display_name = display_name
                meta.Session.commit()

        login_user(user, request, response)
        session['login_type'] = 'shibboleth'

        came_from = request.GET.get('came_from', target)
        qs = urlencode({'return': came_from})

        return redirect('/Shibboleth.sso/Logout?%s' % qs)
Exemplo n.º 28
0
def area_title(identifier):
    """identifier is typically the value of c.active_subheader_nav"""
    if identifier == 'proposals':
        return _("Proposals")
    elif identifier == 'milestones':
        return _("Milestones")
    elif identifier == 'norms':
        return _("Norms")
    elif identifier == 'category':
        return _("Categories")
    elif identifier == 'members':
        return _("Members")
    else:
        if config.get_bool('adhocracy.wording.intro_for_overview'):
            return _(u"Intro")
        else:
            return _(u"Overview")
Exemplo n.º 29
0
    def new(self, format=u'html'):

        data = {}
        protocol = config.get('adhocracy.protocol').strip()
        domain = config.get('adhocracy.domain').strip()

        if config.get_bool('adhocracy.relative_urls'):
            data['url_pre'] = '%s://%s/i/' % (protocol, domain)
            data['url_post'] = ''
            data['url_right_align'] = False
        else:
            data['url_pre'] = '%s://' % protocol
            data['url_post'] = '.%s' % domain
            data['url_right_align'] = True

        return render("/instance/new.html", data,
                      overlay=format == u'overlay')
Exemplo n.º 30
0
def area_title(identifier):
    """identifier is typically the value of c.active_subheader_nav"""
    if identifier == 'proposals':
        return _("Proposals")
    elif identifier == 'milestones':
        return _("Milestones")
    elif identifier == 'norms':
        return _("Norms")
    elif identifier == 'category':
        return _("Categories")
    elif identifier == 'members':
        return _("Members")
    else:
        if config.get_bool('adhocracy.wording.intro_for_overview'):
            return _(u"Intro")
        else:
            return _(u"Overview")
Exemplo n.º 31
0
    def _register_form(self, defaults=None, errors=None):

        data = {
            'email_required': (config.get_bool('adhocracy.require_email')),
        }
        add_static_content(data,
                           u'adhocracy.static_shibboleth_register_ontop_path',
                           body_key=u'body_ontop')
        add_static_content(data,
                           u'adhocracy.static_shibboleth_register_below_path',
                           body_key=u'body_below',
                           title_key=u'_ignored')
        return formencode.htmlfill.render(render("/shibboleth/register.html",
                                                 data),
                                          defaults=defaults,
                                          errors=errors,
                                          force_defaults=False)
Exemplo n.º 32
0
Arquivo: error.py Projeto: alkadis/vcv
    def show(self):
        """Force an error message.

        Always return status 200, but render the HTML error message.
        """
        if not config.get_bool('debug'):
            raise abort(404)
        status = request.GET.get('force_status')
        if status is None:
            raise abort(404)
        data = {
            'hide_code': 'hide_code' in request.GET,
            'hide_notify': 'hide_notify' in request.GET,
            'error_code': int(status),
            'error_name': ERROR_NAMES.get(int(status), ''),
            'error_message': ERROR_MESSAGES.get(int(status), ''),
        }
        return render("/error/http.html", data)
Exemplo n.º 33
0
Arquivo: error.py Projeto: alkadis/vcv
    def show(self):
        """Force an error message.

        Always return status 200, but render the HTML error message.
        """
        if not config.get_bool("debug"):
            raise abort(404)
        status = request.GET.get("force_status")
        if status is None:
            raise abort(404)
        data = {
            "hide_code": "hide_code" in request.GET,
            "hide_notify": "hide_notify" in request.GET,
            "error_code": int(status),
            "error_name": ERROR_NAMES.get(int(status), ""),
            "error_message": ERROR_MESSAGES.get(int(status), ""),
        }
        return render("/error/http.html", data)
Exemplo n.º 34
0
    def rate(self, id, format):
        # rating is like polling but steps via abstention, i.e. if you have
        # first voted "for", rating will first go to "abstain" and only
        # then produce "against"-
        c.poll = self._get_open_poll(id)
        if c.poll.action not in [model.Poll.RATE, model.Poll.SELECT]:
            abort(400, _("This is not a rating poll."))
        require.poll.vote(c.poll)

        decision = democracy.Decision(c.user, c.poll)
        old = decision.result
        new = self.form_result.get("position")
        positions = {(model.Vote.YES, model.Vote.YES): model.Vote.YES,
                     (model.Vote.ABSTAIN, model.Vote.YES): model.Vote.YES,
                     (model.Vote.NO, model.Vote.YES): model.Vote.ABSTAIN,
                     (model.Vote.YES, model.Vote.NO): model.Vote.ABSTAIN,
                     (model.Vote.ABSTAIN, model.Vote.NO): model.Vote.NO,
                     (model.Vote.NO, model.Vote.NO): model.Vote.NO}
        position = positions.get((old, new), new)
        votes = decision.make(position)
        tally = model.Tally.create_from_poll(c.poll)
        event_type = {model.Poll.RATE: event.T_RATING_CAST,
                      model.Poll.SELECT: event.T_SELECT_VARIANT
                      }.get(c.poll.action)
        model.meta.Session.commit()

        if not config.get_bool('adhocracy.hide_individual_votes'):
            for vote in votes:
                event.emit(event_type, vote.user, instance=c.instance,
                           topics=[c.poll.scope], vote=vote, poll=c.poll)

        if format == 'json':
            vdetail = votedetail.calc_votedetail_dict(c.instance, c.poll)\
                if votedetail.is_enabled() else None
            return render_json(dict(decision=decision,
                                    tally=tally.to_dict(),
                                    votedetail=vdetail))
        elif format == 'ajax':
            return self.widget(id, format=self.form_result.get('cls'))
        elif c.poll.action == model.Poll.SELECT:
            redirect(h.entity_url(c.poll.selection))
        else:
            redirect(h.entity_url(c.poll.subject))
Exemplo n.º 35
0
    def settings_voting_update(self, id, format='html'):
        c.page_instance = self._get_current_instance(id)
        require.instance.edit(c.page_instance)

        updated_attributes = ['allow_delegate']
        if not config.get_bool('adhocracy.hide_final_adoption_votings'):
            updated_attributes.extend(
                ['required_majority', 'activation_delay', 'allow_adopt'])
        updated = update_attributes(
            c.page_instance, self.form_result, updated_attributes)

        if votedetail.is_enabled():
            new_badges = self.form_result['votedetail_badges']
            updated_vd = c.page_instance.votedetail_userbadges != new_badges
            if updated_vd:
                c.page_instance.votedetail_userbadges = new_badges
            updated = updated or updated_vd

        return self._settings_result(updated, c.page_instance, 'voting')
Exemplo n.º 36
0
def render_tile(template_name, def_name, tile, cached=False, **kwargs):
    from adhocracy.lib import templating
    begin_time = time()

    def render():
        return templating.render_def(template_name, def_name,
                                     tile=tile, **kwargs)
    rendered = ""
    if cached and config.get_bool('adhocracy.cache_tiles'):
        @memoize('tile_cache' + template_name + def_name, 7 * 86400)
        def _cached(**kwargs):
            return render()
        rendered = _cached(locale=c.locale, **kwargs)
    else:
        rendered = render()

    if False:
        log.debug("Rendering tile %s:%s took %sms" % (
            template_name, def_name, (time() - begin_time) * 1000))

    return rendered
Exemplo n.º 37
0
def notify(event, database_only=False):
    '''
    been too smart today ;)

    If database_only is True, the given event only creates Notfication
    database entries without sending out email and such notifications.
    '''
    if not event:
        log.warn("Received null as event, shouldn't happen!")
        return
    log.debug("Event notification processing: %s" % event)
    begin_time = time()
    sources = filter(lambda g: g, [
        watchlist_source(event),
        vote_source(event),
        instance_source(event),
        tag_source(event),
        delegation_source(event),
        comment_source(event)
    ])
    pipeline = chain(*sources)
    #pipeline = echo(pipeline)

    pipeline = comment_filter(pipeline)
    pipeline = self_filter(pipeline)
    pipeline = duplicates_filter(pipeline)
    pipeline = hidden_instance_filter(pipeline)

    pipeline = log_sink(pipeline)
    if config.get_bool('adhocracy.store_notification_events'):
        pipeline = database_sink(pipeline)
    if not database_only:
        pipeline = twitter_sink(pipeline)
        pipeline = mail_sink(pipeline)

    for _ in pipeline:
        pass

    end_time = time() - begin_time
    log.debug("-> processing took: %sms" % (end_time * 1000))
Exemplo n.º 38
0
def rewrite_urls(body):
    from adhocracy.lib.helpers import base_url
    if not config.get_bool('adhocracy.track_outgoing_links'):
        return body

    doc = lxml.etree.fromstring('<body>' + body + '</body>')
    for a in doc.xpath('.//a[@href]'):
        if re.match(r'ftps?:|https?:|//', a.attrib['href']):
            url = a.attrib['href']

            # Is it a link to our own site?
            base = base_url('/', instance=None)
            if (url.startswith(base)
                    and not (url.startswith('//') and base == '/')):
                continue

            encoded_url = base64.urlsafe_b64encode(url.encode('utf-8'))
            signed_url = sign(encoded_url, salt=REDIRECT_SALT)
            redirect_url = u'/outgoing_link/' + signed_url.decode('utf-8')
            a.attrib['href'] = base_url(redirect_url)
    res = lxml.etree.tostring(doc)
    return res[len(b'<body>'):-len(b'</body>')]
Exemplo n.º 39
0
    def vote(self, id, format):
        c.poll = self._get_open_poll(id)
        if c.poll.action != model.Poll.ADOPT:
            abort(400, _("This is not an adoption poll."))
        require.poll.vote(c.poll)
        decision = democracy.Decision(c.user, c.poll)
        votes = decision.make(self.form_result.get("position"))
        model.meta.Session.commit()

        if not config.get_bool('adhocracy.hide_individual_votes'):
            for vote in votes:
                event.emit(event.T_VOTE_CAST, vote.user, instance=c.instance,
                           topics=[c.poll.scope], vote=vote, poll=c.poll)

        if format == 'json':
            vdetail = votedetail.calc_votedetail_dict(c.instance, c.poll)\
                if votedetail.is_enabled() else None
            return render_json(dict(decision=decision,
                                    score=c.poll.tally.score,
                                    votedetail=vdetail))
        else:
            redirect(h.entity_url(c.poll.subject))
Exemplo n.º 40
0
def rewrite_urls(body):
    from adhocracy.lib.helpers import base_url
    if not config.get_bool('adhocracy.track_outgoing_links'):
        return body

    doc = lxml.etree.fromstring('<body>' + body + '</body>')
    for a in doc.xpath('.//a[@href]'):
        if re.match(r'ftps?:|https?:|//', a.attrib['href']):
            url = a.attrib['href']

            # Is it a link to our own site?
            base = base_url('/', instance=None)
            if (url.startswith(base)
                    and not(url.startswith('//') and base == '/')):
                continue

            encoded_url = base64.urlsafe_b64encode(url.encode('utf-8'))
            signed_url = sign(encoded_url, salt=REDIRECT_SALT)
            redirect_url = u'/outgoing_link/' + signed_url.decode('utf-8')
            a.attrib['href'] = base_url(redirect_url)
    res = lxml.etree.tostring(doc)
    return res[len(b'<body>'):-len(b'</body>')]
Exemplo n.º 41
0
def notify(event, database_only=False):
    '''
    been too smart today ;)

    If database_only is True, the given event only creates Notfication
    database entries without sending out email and such notifications.
    '''
    if not event:
        log.warn("Received null as event, shouldn't happen!")
        return
    log.debug("Event notification processing: %s" % event)
    begin_time = time()
    sources = filter(lambda g: g, [watchlist_source(event),
                                   vote_source(event),
                                   instance_source(event),
                                   tag_source(event),
                                   delegation_source(event),
                                   comment_source(event)])
    pipeline = chain(*sources)
    #pipeline = echo(pipeline)

    pipeline = comment_filter(pipeline)
    pipeline = self_filter(pipeline)
    pipeline = duplicates_filter(pipeline)
    pipeline = hidden_instance_filter(pipeline)

    pipeline = log_sink(pipeline)
    if config.get_bool('adhocracy.store_notification_events'):
        pipeline = database_sink(pipeline)
    if not database_only:
        pipeline = twitter_sink(pipeline)
        pipeline = mail_sink(pipeline)

    for _ in pipeline:
        pass

    end_time = time() - begin_time
    log.debug("-> processing took: %sms" % (end_time * 1000))
Exemplo n.º 42
0
    def logged_in(self):
        """
        Recieves authentication messages from the velruse service.
        It will log in users or connect their adhocracy account
        to an existing velruse account.
        It also creates adhocracy accounts if it thinks the user has none.
        We expect the ssi service to provide a *verified* email address.
        If none is provided, this function will crash.
        """

        redirect_url = session.get('came_from', h.base_url('/login'))

        token = request.params['token']
        payload = {'format': 'json', 'token': token}
        rsp = get(h.velruse_url('/auth_info'),
                  params=payload,
                  timeout=1,
                  verify=config.get_bool('velruse.verify_ssl'))
        if rsp.status_code >= 400:
            return self._failure(_('Internal server error:'
                                 'velruse service not available.'),
                                 redirect_url=redirect_url)

        auth_info = loads(rsp.content)
        log.debug('received auth_info from velruse:\n' +
                  '<pre>' + dumps(auth_info, indent=4) + '</pre>')

        if 'error' in auth_info:
            error = auth_info['error']
            if error == 'user_denied':
                return self._failure(_('Login failed: ') +
                                     _('You have to give Adhocracy permission '
                                       'to connect to your Facebook account.'),
                                     auth_info,
                                     redirect_url=redirect_url)
            else:
                return self._failure(_('Login failed: ') + auth_info['error'],
                                     auth_info, redirect_url=redirect_url)

        provider_name = auth_info['provider_name']

        if provider_name not in allowed_login_types():
            self._failure(_("Logging in with %s "
                          "is not allowed on this installation.")
                          % provider_name.capitalize(),
                          auth_info, redirect_url=redirect_url)
        else:
            try:
                profile = auth_info['profile']
                email = profile['verifiedEmail']  # FIXME: this is not always available.  we should catch that earlier above.
                display_name = profile['displayName']
                preferred_name = profile['preferredUsername'].replace('.', '_')
                user_name = unused_user_name(preferred_name)
                accounts = profile['accounts']
            except KeyError:
                log.error('could not parse velruse response:\n' +
                          '<pre>' + dumps(auth_info, indent=4) + '</pre>')
                self._failure(_("Error"))

            if c.user is not None:
                adhocracy_user = c.user
                velruse_user = Velruse.by_user_and_domain_first(
                    adhocracy_user,
                    accounts[0]['domain'])

                if velruse_user is not None:
                    self._failure(_("This %(provider)s account"
                                    " is already connected.")
                                  % {'provider': provider_name.capitalize()},
                                  redirect_url=redirect_url)
            else:
                velruse_user = Velruse.find_any(accounts)

                if velruse_user is not None:
                    adhocracy_user = velruse_user.user
                else:
                    adhocracy_user = None

            if velruse_user is not None:
                domain = velruse_user.domain
                domain_user = velruse_user.domain_user
            else:
                domain = accounts[0]['domain']
                domain_user = accounts[0]['userid']  # FIXME: this is not always available.  we should catch that earlier above.

            if not domain or not domain_user:
                log.error('domain and/or domain_user not found:\n' +
                          '<pre>\n' +
                          str(domain, domain_user) + '\n' +
                          dumps(auth_info, indent=4) + '\n' +
                          '</pre>')
                self._failure(_("Error"), redirect_url=redirect_url)

            try:
                # login right away
                if adhocracy_user is not None and velruse_user is not None:
                    update_email_trust(adhocracy_user, email)
                    self._login(adhocracy_user, redirect_url=redirect_url)

                # create new user in both Velruse and User and login
                elif adhocracy_user is None and velruse_user is None:
                    new_user = self._create(user_name,
                                            email,
                                            domain,
                                            domain_user,
                                            email_verified=True,
                                            display_name=display_name,
                                            redirect_url=redirect_url)

                    adhocracy_user, velruse_user = new_user
                    self._login(adhocracy_user, redirect_url=redirect_url)

                # create new user in Velruse for a logged in user
                elif adhocracy_user is not None and velruse_user is None:
                    self._connect(adhocracy_user, domain, domain_user,
                                  provider_name,
                                  email, email_verified=True,
                                  redirect_url=redirect_url)

                # error case
                else:
                    raise DatabaseInconsistent('velruse user is not associated'
                                               ' with any adhocracy user')

            # if users are deleted and we try to create them again
            # we get an IntegrityError
            except IntegrityError:
                self._failure(_("Your %(provider)s account is locked.")
                              % {'provider': provider_name.capitalize()})
Exemplo n.º 43
0
 def requires_valid_email(self):
     return (config.get_bool('adhocracy.require_email')
             and self.require_valid_email)
Exemplo n.º 44
0
 def readonly(self):
     if config.get_bool(u'adhocracy.readonly'):
         e = config.get_bool(u'adhocracy.readonly.global_admin_exception')
         if not (e and has(u'global.admin')):
             self.other_refusals.add(u'readonly')
Exemplo n.º 45
0
Arquivo: base.py Projeto: alkadis/vcv
    def __call__(self, environ, start_response):
        """Invoke the Controller"""

        c.body_css_classes = []
        c.body_css_classes.append('controller-' + self.identifier)

        if self.identifier in ['proposals', 'milestones', 'norms', 'category',
                               'members']:
            c.active_subheader_nav = self.identifier
            c.body_css_classes.append('area-' + self.identifier)

        c.instance = model.instance_filter.get_instance()
        if c.instance is not None:
            c.body_css_classes.append(u'instance-%s' % c.instance.key)
        # setup a global variable to mark the current item in
        # the global navigation
        global_nav = 'instances' if c.instance is not None else 'home'
        c.active_global_nav = global_nav
        c.body_css_classes.append('global_nav_' + global_nav)
        user_id = environ.get('repoze.who.identity', {}).get('user', None)
        user = None
        # make sure we're not using a detached user object
        if user_id is not None:
            user = model.meta.Session.merge(user_id)
        if user and (user.banned or user.delete_time):
            user = None
        if user is not None:
            c.body_css_classes.append('logged_in')
        else:
            c.body_css_classes.append('not_logged_in')
        c.user = user
        c.active_controller = request.environ.get('pylons.routes_dict')\
            .get('controller')
        c.debug = config.get_bool('debug')
        i18n.handle_request()

        if h.site.is_local_url(request.params.get(u'came_from', u'')):
            c.came_from = request.params.get(u'came_from', u'')

        monitor_page_time_interval = config.get_int(
            'adhocracy.monitor_page_time_interval', -1)
        c.page_stats_url = h.base_url('/stats/on_page')
        if monitor_page_time_interval > 0:
            c.monitor_page_time_interval = monitor_page_time_interval

        if config.get_bool('adhocracy.monitor_external_links'):
            c.monitor_external_links_url = h.base_url('/stats/record_external')

        if config.get_bool('adhocracy.monitor_browser_values'):
            c.monitor_browser_values = "enabled"
        if config.get_bool('adhocracy.monitor_extended'):
            c.monitor_extended = "enabled"
        if config.get_bool('adhocracy.monitor_page_performance'):
            c.monitor_page_performance = "enabled"

        if config.get_bool('adhocracy.monitor_pager_clicks'):
            c.monitor_pager_clicks = "enabled"

        h.add_rss("%s News" % h.site.name(),
                  h.base_url('/feed.rss', None))
        if c.instance:
            h.add_rss("%s News" % c.instance.label,
                      h.base_url('/instance/%s.rss' % c.instance.key))

        h.add_meta("description", config.get(
            'adhocracy.site.description',
            _(u"A liquid democracy platform for making decisions in "
              u"distributed, open groups by cooperatively creating "
              u"proposals and voting on them to establish their "
              u"support.")))

        h.add_meta("keywords",
                   _("adhocracy, direct democracy, liquid democracy, liqd, "
                     "democracy, wiki, voting,participation, group decisions, "
                     "decisions, decision-making"))

        try:
            return WSGIController.__call__(self, environ, start_response)
        except Exception, e:
            log.exception(e)
            model.meta.Session.rollback()
            raise
Exemplo n.º 46
0
def base_url(path='', instance=CURRENT_INSTANCE, absolute=False,
             append_slash=False, config=config, query_params=None,
             query_string=None, member=None):
    """
    Constructs an URL.

    Path is expected to start with '/'. If not, a relative path to the current
    object will be created.

    If instance isn't defined, the current instance is assumed. Otherwise,
    either an instance, an instance key, or None has to be passed.

    If absolute is True, an absolute URL including the protocol part is
    returned. Otherwise this is avoided, if relative_urls is set to True and
    instance_domains isn't enabled.

    query_params is a dictionary of parameters for the query string of the URL.

    Alternatively to query_params, query_string can be specified which is
    directly used as the query string of the resulting URL.
    """

    if instance == CURRENT_INSTANCE:
        instance = ifilter.get_instance()

    if instance is None:
        instance_key = None
    else:
        if isinstance(instance, (str, unicode)):
            instance_key = instance
        else:
            instance_key = instance.key

    domain = None

    instance_domains = aconfig.get_bool('adhocracy.instance_domains.enabled')

    if instance and instance_domains:
        domain = aconfig.get_json('adhocracy.instance_domains', {})\
            .get(instance_key)

    if domain is not None:
        protocol = config.get('adhocracy.protocol', 'http').strip()
        result = '%s://%s%s' % (protocol, domain, path)

    elif relative_urls(config):

        if instance is None:
            prefix = ''
        else:
            prefix = '/i/' + instance_key

        if absolute or instance_domains:
            protocol = config.get('adhocracy.protocol', 'http').strip()
            domain = config.get('adhocracy.domain').strip()

            result = '%s://%s%s%s' % (protocol, domain, prefix, path)

        else:
            result = '%s%s' % (prefix, path)

    else:

        protocol = config.get('adhocracy.protocol', 'http').strip()
        domain = config.get('adhocracy.domain').strip()

        if instance is None or g.single_instance:
            subdomain = ''
        else:
            subdomain = '%s.' % instance_key

        result = '%s://%s%s%s' % (protocol, subdomain, domain, path)

    if member is not None:
        result += '/' + member

    if result == '':
        result = '/'

    if append_slash and not result.endswith('/'):
        result += '/'

    if query_params:
        result += '&' if '?' in result else '?'
        u = lambda s: unicode(s).encode('utf-8')
        query_params = [(u(k), u(v)) for (k, v) in query_params.iteritems()]
        result += urllib.urlencode(query_params)
    elif query_string:
        result += '&' if '?' in result else '?'
        result += query_string

    return result
Exemplo n.º 47
0
def get_categories():
    if not config.get_bool('adhocracy.feedback_use_categories'):
        return []
    feedback_instance = get_feedback_instance()
    return model.CategoryBadge.all(feedback_instance, include_global=False)
Exemplo n.º 48
0
def show(check, p):
    check.perm('poll.show')
    check.other('poll_has_ended', p.has_ended())
    check.other('hide_individual_votes',
                config.get_bool('adhocracy.hide_individual_votes'))
Exemplo n.º 49
0
def hide_individual_votes(poll):
    hide = config.get_bool('adhocracy.hide_individual_votes.%s'
                           % poll.scope.instance.key)
    if hide is None:
        hide = config.get_bool('adhocracy.hide_individual_votes')
    return hide
Exemplo n.º 50
0
def show_result(check):
    check.other('result_not_shown_until_frozen',
                config.get_bool('adhocracy.proposal.rate_poll.hide_scores'))
Exemplo n.º 51
0
def use_external_navigation():
    return config.get_bool('adhocracy.use_external_navigation', False)
Exemplo n.º 52
0
def is_enabled():
    return config.get_bool('adhocracy.enable_votedetail')
Exemplo n.º 53
0
def delete(check, u):
    edit(check, u)
    allowed = config.get_bool('adhocracy.self_deletion_allowed', 'true')
    check.other('self_deletion_allowed', not allowed)
Exemplo n.º 54
0
def allow_user_registration():
    return (config.get_bool('adhocracy.allow_registration')
            and not config.get_bool('adhocracy.readonly'))