<commit_before>from cgi import FieldStorage
import formencode
from formencode import Any, All, htmlfill, Invalid, validators
from pylons import request, tmpl_context as c
from pylons.controllers.util import redirect
from pylons.i18n import _

from adhocracy.forms.common import ValidInstanceGroup
from adhocracy.forms.common import ValidHTMLColor
from adhocracy.forms.common import ContainsChar
from adhocracy.forms.common import ValidBadgeInstance
from adhocracy.forms.common import ValidImageFileUpload
from adhocracy.forms.common import ValidFileUpload
from adhocracy.forms.common import ValidCategoryBadge
from adhocracy.forms.common import ValidParentCategory
from adhocracy.forms.common import ValidateNoCycle
from adhocracy.forms.common import ProposalSortOrder
from adhocracy.model import meta
from adhocracy.model import Badge
from adhocracy.model import Group
from adhocracy.model import CategoryBadge
from adhocracy.model import DelegateableBadge
from adhocracy.model import InstanceBadge
from adhocracy.model import ThumbnailBadge
from adhocracy.model import UserBadge
from adhocracy.lib import helpers as h
from adhocracy.lib.auth.authorization import has
from adhocracy.lib.auth.csrf import RequireInternalRequest
from adhocracy.lib.auth import guard
from adhocracy.lib.base import BaseController
from adhocracy.lib.behavior import behavior_enabled
from adhocracy.lib.templating import render
from adhocracy.lib.pager import PROPOSAL_SORTS


class BadgeForm(formencode.Schema):
    allow_extra_fields = True
    title = All(validators.String(max=40, not_empty=True),
                ContainsChar())
    description = validators.String(max=255)
    color = ValidHTMLColor()
    instance = ValidBadgeInstance()
    if behavior_enabled():
        behavior_proposal_sort_order = ProposalSortOrder()


class CategoryBadgeForm(BadgeForm):
    select_child_description = validators.String(max=255)
    parent = ValidCategoryBadge(not_empty=False)
    chained_validators = [
        # make sure parent has same instance as we
        ValidParentCategory()
    ]


class CategoryBadgeUpdateForm(CategoryBadgeForm):
    id = ValidCategoryBadge(not_empty=True)
    chained_validators = [
        # make sure parent has same instance as we
        ValidParentCategory(),
        # make sure we don't create a cycle
        ValidateNoCycle(),
    ]


class UserBadgeForm(BadgeForm):
    group = Any(validators.Empty, ValidInstanceGroup())
    display_group = validators.StringBoolean(if_missing=False)


class ThumbnailBadgeForm(BadgeForm):
    thumbnail = All(ValidImageFileUpload(not_empty=False),
                    ValidFileUpload(not_empty=False), )


class BadgeController(BaseController):
    """Badge controller base class"""

    form_template = "/badge/form.html"
    index_template = "/badge/index.html"
    base_url_ = None

    def _available_badges(self):
        '''
        Return the badges that are editable by a user.
        '''
        c.groups = [{'permission': 'global.admin',
                     'label': _('In all instances'),
                     'show_label': True}]
        if c.instance:
            c.groups.append(
                {'permission': 'instance.admin',
                 'label': _('In instance "%s"') % c.instance.label,
                 'show_label': h.has_permission('global.admin')})
        badges = {}
        if has('global.admin'):
            badges['global.admin'] = {
                'instance': InstanceBadge.all(instance=None),
                'user': UserBadge.all(instance=None),
                'delegateable': DelegateableBadge.all(instance=None),
                'category': CategoryBadge.all(instance=None),
                'thumbnail': ThumbnailBadge.all(instance=None)}
        if has('instance.admin') and c.instance is not None:
            badges['instance.admin'] = {
                'instance': InstanceBadge.all(instance=c.instance),
                'user': UserBadge.all(instance=c.instance),
                'delegateable': DelegateableBadge.all(instance=c.instance),
                'category': CategoryBadge.all(instance=c.instance),
                'thumbnail': ThumbnailBadge.all(instance=c.instance)}
        return badges

    @property
    def base_url(self):
        if self.base_url_ is None:
            self.base_url_ = h.site.base_url(instance=c.instance,
                                             path='/badge')
        return self.base_url_

    @guard.perm('badge.index')
    def index(self, format='html'):
        c.badges = self._available_badges()
        c.badge_base_url = self.base_url
        return render(self.index_template)

    def _redirect_not_found(self, id):
        h.flash(_("We cannot find the badge with the id %s") % str(id),
                'error')
        redirect(self.base_url)

    def _set_parent_categories(self, exclude=None):
        local_categories = CategoryBadge.all_q(instance=c.instance)

        if exclude is not None:
            local_categories = filter(lambda c: not(c.is_ancester(exclude)),
                                      local_categories)

        c.local_category_parents = sorted(
            [(b.id, b.get_key()) for b in local_categories],
            key=lambda x: x[1])

        if h.has_permission('global.admin'):
            global_categories = CategoryBadge.all_q(instance=None)

            if exclude is not None:
                global_categories = filter(
                    lambda c: not(c.is_ancester(exclude)), global_categories)
            c.global_category_parents = sorted(
                [(b.id, b.get_key()) for b in global_categories],
                key=lambda x: x[1])

    @guard.instance.any_admin()
    def add(self, badge_type=None, errors=None):
        if badge_type is not None:
            c.badge_type = badge_type
        c.form_type = 'add'
        c.groups = Group.all_instance()
        defaults = {'visible': True,
                    'select_child_description': '',
                    }
        defaults.update(dict(request.params))

        self._set_parent_categories()

        return htmlfill.render(render(self.form_template),
                               defaults=defaults,
                               errors=errors,
                               force_defaults=False)

    def _dispatch(self, action, badge_type, id=None):
        '''
        dispatch to a suiteable "create" or "edit" action

        Methods are named <action>_<badge_type>_badge().
        '''
        assert action in ['create', 'update']
        types = ['user', 'delegateable', 'category', 'instance', 'thumbnail']
        if badge_type not in types:<commit_msg>Set sorting_orders in badge/add<commit_after>from cgi import FieldStorage
import formencode
from formencode import Any, All, htmlfill, Invalid, validators
from pylons import request, tmpl_context as c
from pylons.controllers.util import redirect
from pylons.i18n import _

from adhocracy.forms.common import ValidInstanceGroup
from adhocracy.forms.common import ValidHTMLColor
from adhocracy.forms.common import ContainsChar
from adhocracy.forms.common import ValidBadgeInstance
from adhocracy.forms.common import ValidImageFileUpload
from adhocracy.forms.common import ValidFileUpload
from adhocracy.forms.common import ValidCategoryBadge
from adhocracy.forms.common import ValidParentCategory
from adhocracy.forms.common import ValidateNoCycle
from adhocracy.forms.common import ProposalSortOrder
from adhocracy.model import meta
from adhocracy.model import Badge
from adhocracy.model import Group
from adhocracy.model import CategoryBadge
from adhocracy.model import DelegateableBadge
from adhocracy.model import InstanceBadge
from adhocracy.model import ThumbnailBadge
from adhocracy.model import UserBadge
from adhocracy.lib import helpers as h
from adhocracy.lib.auth.authorization import has
from adhocracy.lib.auth.csrf import RequireInternalRequest
from adhocracy.lib.auth import guard
from adhocracy.lib.base import BaseController
from adhocracy.lib.behavior import behavior_enabled
from adhocracy.lib.templating import render
from adhocracy.lib.pager import PROPOSAL_SORTS


class BadgeForm(formencode.Schema):
    allow_extra_fields = True
    title = All(validators.String(max=40, not_empty=True),
                ContainsChar())
    description = validators.String(max=255)
    color = ValidHTMLColor()
    instance = ValidBadgeInstance()
    if behavior_enabled():
        behavior_proposal_sort_order = ProposalSortOrder()


class CategoryBadgeForm(BadgeForm):
    select_child_description = validators.String(max=255)
    parent = ValidCategoryBadge(not_empty=False)
    chained_validators = [
        # make sure parent has same instance as we
        ValidParentCategory()
    ]


class CategoryBadgeUpdateForm(CategoryBadgeForm):
    id = ValidCategoryBadge(not_empty=True)
    chained_validators = [
        # make sure parent has same instance as we
        ValidParentCategory(),
        # make sure we don't create a cycle
        ValidateNoCycle(),
    ]


class UserBadgeForm(BadgeForm):
    group = Any(validators.Empty, ValidInstanceGroup())
    display_group = validators.StringBoolean(if_missing=False)


class ThumbnailBadgeForm(BadgeForm):
    thumbnail = All(ValidImageFileUpload(not_empty=False),
                    ValidFileUpload(not_empty=False), )


class BadgeController(BaseController):
    """Badge controller base class"""

    form_template = "/badge/form.html"
    index_template = "/badge/index.html"
    base_url_ = None

    def _available_badges(self):
        '''
        Return the badges that are editable by a user.
        '''
        c.groups = [{'permission': 'global.admin',
                     'label': _('In all instances'),
                     'show_label': True}]
        if c.instance:
            c.groups.append(
                {'permission': 'instance.admin',
                 'label': _('In instance "%s"') % c.instance.label,
                 'show_label': h.has_permission('global.admin')})
        badges = {}
        if has('global.admin'):
            badges['global.admin'] = {
                'instance': InstanceBadge.all(instance=None),
                'user': UserBadge.all(instance=None),
                'delegateable': DelegateableBadge.all(instance=None),
                'category': CategoryBadge.all(instance=None),
                'thumbnail': ThumbnailBadge.all(instance=None)}
        if has('instance.admin') and c.instance is not None:
            badges['instance.admin'] = {
                'instance': InstanceBadge.all(instance=c.instance),
                'user': UserBadge.all(instance=c.instance),
                'delegateable': DelegateableBadge.all(instance=c.instance),
                'category': CategoryBadge.all(instance=c.instance),
                'thumbnail': ThumbnailBadge.all(instance=c.instance)}
        return badges

    @property
    def base_url(self):
        if self.base_url_ is None:
            self.base_url_ = h.site.base_url(instance=c.instance,
                                             path='/badge')
        return self.base_url_

    @guard.perm('badge.index')
    def index(self, format='html'):
        c.badges = self._available_badges()
        c.badge_base_url = self.base_url
        return render(self.index_template)

    def _redirect_not_found(self, id):
        h.flash(_("We cannot find the badge with the id %s") % str(id),
                'error')
        redirect(self.base_url)

    def _set_parent_categories(self, exclude=None):
        local_categories = CategoryBadge.all_q(instance=c.instance)

        if exclude is not None:
            local_categories = filter(lambda c: not(c.is_ancester(exclude)),
                                      local_categories)

        c.local_category_parents = sorted(
            [(b.id, b.get_key()) for b in local_categories],
            key=lambda x: x[1])

        if h.has_permission('global.admin'):
            global_categories = CategoryBadge.all_q(instance=None)

            if exclude is not None:
                global_categories = filter(
                    lambda c: not(c.is_ancester(exclude)), global_categories)
            c.global_category_parents = sorted(
                [(b.id, b.get_key()) for b in global_categories],
                key=lambda x: x[1])

    @guard.instance.any_admin()
    def add(self, badge_type=None, errors=None):
        data = {
            'form_type': 'add',
            'groups': Group.all_instance(),
            'sorting_orders': PROPOSAL_SORTS,
        }
        if badge_type is not None:
            data['badge_type'] = badge_type
        
        defaults = {'visible': True,
                    'select_child_description': '',
                    }
        defaults.update(dict(request.params))

        self._set_parent_categories()

        html = render(self.form_template, data)
        return htmlfill.render(html,
                               defaults=defaults,
                               errors=errors,
                               force_defaults=False)

    def _dispatch(self, action, badge_type, id=None):
        '''
        dispatch to a suiteable "create" or "edit" action

        Methods are named <action>_<badge_type>_badge().
        '''
        assert action in ['create', 'update']
        types = ['user', 'delegateable', 'category', 'instance', 'thumbnail']
        if badge_type not in types:
{'fraction_non_alphanumeric': 0.09357291977333732, 'fraction_numerical': 0.001789442290486132, 'mean_word_length': 2.6398914518317502, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 6, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6182340', 'n_tokens_mistral': 3869, 'n_tokens_neox': 3689, 'n_words': 868}