Esempio n. 1
0
 def real_instances(self, exclude_current=False):
     excluded_keys = copy(Instance.SPECIAL_KEYS)
     if exclude_current:
         current_instance = ifilter.get_instance()
         if current_instance is not None:
             excluded_keys.append(ifilter.get_instance().key)
     return sorted(filter(lambda i: i.key not in excluded_keys,
                          self.instances),
                   key=lambda i: i.key)
Esempio n. 2
0
 def real_instances(self, exclude_current=False):
     excluded_keys = copy(Instance.SPECIAL_KEYS)
     if exclude_current:
         current_instance = ifilter.get_instance()
         if current_instance is not None:
             excluded_keys.append(ifilter.get_instance().key)
     return sorted(
         filter(lambda i: i.key not in excluded_keys, self.instances),
         key=lambda i: i.key)
Esempio n. 3
0
def base_url(path='', instance=CURRENT_INSTANCE, absolute=False):
    """
    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 instance or None has to be passed.

    If absolute is True, an absolute URL including the protocol part is
    returned. Otherwise this is avoided if the resulting URL has the same
    domain part as the current URL.
    """

    if asbool(config.get('adhocracy.relative_urls', 'false')):
        if instance == CURRENT_INSTANCE:
            instance = ifilter.get_instance()

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

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

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

        else:
            return '%s%s' % (prefix, path)

    else:
        current_instance = ifilter.get_instance()

        if instance == CURRENT_INSTANCE:
            instance = current_instance
        elif instance != current_instance:
            absolute = True

        if absolute:

            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

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

        else:
            return path
Esempio n. 4
0
def base_url(path='', instance=CURRENT_INSTANCE, absolute=False):
    """
    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 instance or None has to be passed.

    If absolute is True, an absolute URL including the protocol part is
    returned. Otherwise this is avoided if the resulting URL has the same
    domain part as the current URL.
    """

    if asbool(config.get('adhocracy.relative_urls', 'false')):
        if instance == CURRENT_INSTANCE:
            instance = ifilter.get_instance()

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

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

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

        else:
            return '%s%s' % (prefix, path)

    else:
        current_instance = ifilter.get_instance()

        if instance == CURRENT_INSTANCE:
            instance = current_instance
        elif instance != current_instance:
            absolute = True

        if absolute:

            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

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

        else:
            return path
Esempio n. 5
0
def get_value(key,
              converter,
              default=None,
              config=config,
              converter_kwargs={},
              instance_overwrites=True):

    allow_overwrite = (instance_overwrites
                       and get_bool('%s.allow_overwrite' % key,
                                    instance_overwrites=False))

    if allow_overwrite:
        from adhocracy.model import instance_filter as ifilter
        current_instance = ifilter.get_instance()
        if current_instance is not None:
            value = config.get('%s.%s' % (key, current_instance.key))
        else:
            value = None
    else:
        value = None

    if value is None:
        value = config.get(key)

    if value is None:
        if default is not None:
            return default
        else:
            return DEFAULTS.get(key)

    if converter is None:
        return value
    else:
        return converter(value, **converter_kwargs)
Esempio n. 6
0
def get_value(key, converter, default=None, config=config,
              converter_kwargs={}, instance_overwrites=True):

    allow_overwrite = (instance_overwrites
                       and get_bool('%s.allow_overwrite' % key,
                                    instance_overwrites=False))

    if allow_overwrite:
        from adhocracy.model import instance_filter as ifilter
        current_instance = ifilter.get_instance()
        if current_instance is not None:
            value = config.get('%s.%s' % (key, current_instance.key))
        else:
            value = None
    else:
        value = None

    if value is None:
        value = config.get(key)

    if value is None:
        if default is not None:
            return default
        else:
            return DEFAULTS.get(key)

    if converter is None:
        return value
    else:
        return converter(value, **converter_kwargs)
Esempio n. 7
0
 def membership_groups(self):
     groups = []
     for membership in self.memberships:
         if membership.is_expired():
             continue
         if not membership.instance or \
             membership.instance == ifilter.get_instance():
             groups.append(membership.group)
     return groups
Esempio n. 8
0
 def badge_groups(self):
     current_instance = ifilter.get_instance()
     groups = []
     for badge in self.badges:
         group = badge.group
         if (group is not None and group not in groups
                 and badge.instance in [None, current_instance]):
             groups.append(group)
     return groups
Esempio n. 9
0
 def membership_groups(self):
     groups = []
     for membership in self.memberships:
         if membership.is_expired():
             continue
         if not membership.instance or \
             membership.instance == ifilter.get_instance():
             groups.append(membership.group)
     return groups
Esempio n. 10
0
 def badge_groups(self):
     current_instance = ifilter.get_instance()
     groups = []
     for badge in self.badges:
         group = badge.group
         if (group is not None and group not in groups
            and badge.instance in [None, current_instance]):
             groups.append(group)
     return groups
Esempio n. 11
0
 def complete(cls, prefix, limit=5, instance_filter=True):
     q = meta.Session.query(User)
     prefix = prefix.lower()
     q = q.filter(or_(func.lower(User.user_name).like(prefix + u"%"),
                      func.lower(User.display_name).like(prefix + u"%")))
     q = q.limit(limit)
     completions = q.all()
     if ifilter.has_instance() and instance_filter:
         inst = ifilter.get_instance()
         completions = filter(lambda u: u.is_member(inst), completions)
     return completions
Esempio n. 12
0
File: badge.py Progetto: alkadis/vcv
 def by_id(cls, id, instance_filter=True):
     try:
         q = meta.Session.query(cls)
         q = q.filter(cls.id == id)
         if ifilter.has_instance() and instance_filter:
             q = q.filter((cls.instance_id ==
                           ifilter.get_instance().id))
         return q.limit(1).first()
     except Exception, e:
         log.warn("by_id(%s): %s" % (id, e))
         return None
Esempio n. 13
0
 def complete(cls, prefix, limit=5, instance_filter=True):
     q = meta.Session.query(User)
     prefix = prefix.lower()
     q = q.filter(or_(func.lower(User.user_name).like(prefix + u"%"),
                      func.lower(User.display_name).like(prefix + u"%")))
     q = q.limit(limit)
     completions = q.all()
     if ifilter.has_instance() and instance_filter:
         inst = ifilter.get_instance()
         completions = filter(lambda u: u.is_member(inst), completions)
     return completions
Esempio n. 14
0
def base_url(path='', instance=CURRENT_INSTANCE, absolute=False,
             append_slash=False, config=config):
    """
    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 instance 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.
    """

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

    if asbool(config.get('adhocracy.relative_urls', 'false')):

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

        if absolute:
            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 result == '':
        result = '/'

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

    return result
Esempio n. 15
0
File: badge.py Progetto: alkadis/vcv
 def find(cls, title_or_id, instance_filter=True, include_deleted=False):
     """
     Note: include_deleted doesn't have any effect, as badges can not be
     marked as deleted. This parameter is only there for coherence reasons
     with other models' find methods, as this is expected in
     `model.refs.to_entity`.
     """
     q = meta.Session.query(cls)
     try:
         q = q.filter(cls.id == int(title_or_id))
     except ValueError:
         q = q.filter(cls.title == title_or_id)
     if ifilter.has_instance() and instance_filter:
         q = q.filter(cls.instance_id == ifilter.get_instance().id)
     return q.first()
Esempio n. 16
0
 def find_all(cls, unames, instance_filter=True, include_deleted=False):
     from membership import Membership
     q = meta.Session.query(User)
     q = q.filter(User.user_name.in_(unames))
     if not include_deleted:
         q = q.filter(or_(User.delete_time == None,  # noqa
                          User.delete_time > datetime.utcnow()))
     if ifilter.has_instance() and instance_filter:
         q = q.join(Membership)
         q = q.filter(or_(Membership.expire_time == None,  # noqa
                          Membership.expire_time > datetime.utcnow()))
         q = q.filter(Membership.instance == ifilter.get_instance())
     # log.debug("QueryAll: %s" % q)
     # log.debug("LEN: %s" % len(q.all()))
     return q.all()
Esempio n. 17
0
 def find_all(cls, unames, instance_filter=True, include_deleted=False):
     from membership import Membership
     q = meta.Session.query(User)
     q = q.filter(User.user_name.in_(unames))
     if not include_deleted:
         q = q.filter(or_(User.delete_time == None,
                          User.delete_time > datetime.utcnow()))
     if ifilter.has_instance() and instance_filter:
         q = q.join(Membership)
         q = q.filter(or_(Membership.expire_time == None,
                          Membership.expire_time > datetime.utcnow()))
         q = q.filter(Membership.instance == ifilter.get_instance())
     #log.debug("QueryAll: %s" % q)
     #log.debug("LEN: %s" % len(q.all()))
     return q.all()
Esempio n. 18
0
    def test_valid_category_badge(self):
        from formencode import Invalid
        from adhocracy.forms import ValidCategoryBadge
        from adhocracy.model import CategoryBadge, instance_filter

        # the currently set instance ist the test instance. CategoryBadges from
        # the current instance are valid.
        test_instance = tt_get_instance()
        self.assertEqual(test_instance, instance_filter.get_instance())
        test_category = CategoryBadge.create("test_category", "#ccc", "description", test_instance)
        value = ValidCategoryBadge.to_python(str(test_category.id))
        self.assertEqual(value, test_category)

        # from other instances they are not valid
        other_instance = tt_make_instance("other", "Other Instance")
        other_category = CategoryBadge.create("other_category", "#ccc", "description", other_instance)
        self.assertRaises(Invalid, ValidCategoryBadge.to_python, str(other_category.id))
Esempio n. 19
0
    def membership_groups(self):
        from membership import Membership
        current_instance = ifilter.get_instance()

        memberships_q = meta.Session.query(Membership).filter(
            Membership.user_id==self.id)

        if current_instance == None:
            memberships_q = memberships_q.filter(Membership.instance_id==None)
        else:
            memberships_q = memberships_q.filter(or_(
                Membership.instance_id==None,
                Membership.instance_id==current_instance.id
            ))

        memberships = memberships_q.all()
        return [m.group for m in memberships if not m.is_expired()]
Esempio n. 20
0
 def find(cls, user_name, instance_filter=True, include_deleted=False):
     from membership import Membership
     try:
         q = meta.Session.query(User)
         try:
             q = q.filter(User.id == int(user_name))
         except ValueError:
             q = q.filter(User.user_name == unicode(user_name))
         if not include_deleted:
             q = q.filter(or_(User.delete_time == None,
                              User.delete_time > datetime.utcnow()))
         if ifilter.has_instance() and instance_filter:
             q = q.join(Membership)
             q = q.filter(or_(Membership.expire_time == None,
                              Membership.expire_time > datetime.utcnow()))
             q = q.filter(Membership.instance == ifilter.get_instance())
         return q.limit(1).first()
     except Exception, e:
         log.warn("find(%s): %s" % (user_name, e))
         return None
Esempio n. 21
0
 def find(cls, user_name, instance_filter=True, include_deleted=False):
     from membership import Membership
     try:
         q = meta.Session.query(User)
         try:
             q = q.filter(User.id == int(user_name))
         except ValueError:
             q = q.filter(User.user_name == unicode(user_name))
         if not include_deleted:
             q = q.filter(or_(User.delete_time == None,  # noqa
                              User.delete_time > datetime.utcnow()))
         if ifilter.has_instance() and instance_filter:
             q = q.join(Membership)
             q = q.filter(or_(Membership.expire_time == None,  # noqa
                              Membership.expire_time > datetime.utcnow()))
             q = q.filter(Membership.instance == ifilter.get_instance())
         return q.limit(1).first()
     except Exception, e:
         log.debug("find(%s): %s" % (user_name, e))
         return None
Esempio n. 22
0
    def test_valid_category_badge(self):
        from formencode import Invalid
        from adhocracy.forms import ValidCategoryBadge
        from adhocracy.model import CategoryBadge, instance_filter

        # the currently set instance ist the test instance. CategoryBadges from
        # the current instance are valid.
        test_instance = tt_get_instance()
        self.assertEqual(test_instance, instance_filter.get_instance())
        test_category = CategoryBadge.create('test_category', '#ccc',
                                             'description', test_instance)
        value = ValidCategoryBadge.to_python(str(test_category.id))
        self.assertEqual(value, test_category)

        # from other instances they are not valid
        other_instance = tt_make_instance('other', 'Other Instance')
        other_category = CategoryBadge.create('other_category', '#ccc',
                                              'description', other_instance)
        self.assertRaises(Invalid, ValidCategoryBadge.to_python,
                          str(other_category.id))
Esempio n. 23
0
 def current_delegated(self, instance_filter=True):
     ds = filter(lambda d: not d.is_revoked(), self.delegated)
     if ifilter.has_instance() and instance_filter:
         ds = filter(lambda d: d.scope.instance == ifilter.get_instance(),
                     ds)
     return ds
Esempio n. 24
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.

    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 relative_urls(config):

        if instance is None:
            prefix = ''
        elif isinstance(instance, (str, unicode)):
            prefix = '/i/' + instance
        else:
            prefix = '/i/' + instance.key

        if absolute:
            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 = ''
        elif isinstance(instance, (str, unicode)):
            subdomain = '%s.' % instance
        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 '?'
        result += urllib.urlencode(query_params)
    elif query_string:
        result += '&' if '?' in result else '?'
        result += query_string

    return result
Esempio n. 25
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.

    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 relative_urls(config):

        if instance is None:
            prefix = ""
        elif isinstance(instance, (str, unicode)):
            prefix = "/i/" + instance
        else:
            prefix = "/i/" + instance.key

        if absolute:
            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 = ""
        elif isinstance(instance, (str, unicode)):
            subdomain = "%s." % instance
        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
Esempio n. 26
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
Esempio n. 27
0
 def current_delegated(self, instance_filter=True):
     ds = filter(lambda d: not d.is_revoked(), self.delegated)
     if ifilter.has_instance() and instance_filter:
         ds = filter(lambda d: d.scope.instance == ifilter.get_instance(),
                     ds)
     return ds