Beispiel #1
0
def make_import_form(blog):
    user_choices = [('__zine_create_user', _(u'Create new user'))] + [
        (user.id, user.username)
        for user in User.query.order_by('username').all()
    ]

    _authors = dict((author.id, forms.ChoiceField(author.username,
                                                  choices=user_choices))
                    for author in blog.authors)
    _posts = dict((post.id, forms.BooleanField(help_text=post.title)) for post
                  in blog.posts)
    _comments = dict((post.id, forms.BooleanField()) for post
                     in blog.posts)

    class _ImportForm(forms.Form):
        title = forms.BooleanField(lazy_gettext(u'Blog title'),
                                   help_text=blog.title)
        description = forms.BooleanField(lazy_gettext(u'Blog description'),
                                         help_text=blog.description)
        authors = forms.Mapping(_authors)
        posts = forms.Mapping(_posts)
        comments = forms.Mapping(_comments)
        load_config = forms.BooleanField(lazy_gettext(u'Load config values'),
                                         help_text=lazy_gettext(
                                         u'Load the configuration values '
                                         u'from the import.'))

        def perform_import(self):
            from zine.importers import perform_import
            return perform_import(get_application(), blog, self.data,
                                  stream=True)

    _all_true = dict((x.id, True) for x in blog.posts)
    return _ImportForm({'posts': _all_true.copy(),
                        'comments': _all_true.copy()})
Beispiel #2
0
class PluginForm(forms.Form):
    """The form for plugin activation and deactivation."""
    active_plugins = forms.MultiChoiceField(widget=forms.CheckboxGroup)
    disable_guard = forms.BooleanField(lazy_gettext(u'Disable plugin guard'),
        help_text=lazy_gettext(u'If the plugin guard is disabled errors '
                               u'on plugin setup are not caught.'))

    def __init__(self, initial=None):
        self.app = app = get_application()
        self.active_plugins.choices = sorted([(x.name, x.display_name)
                                              for x in app.plugins.values()],
                                             key=lambda x: x[1].lower())
        if initial is None:
            initial = dict(
                active_plugins=[x.name for x in app.plugins.itervalues()
                                if x.active],
                disable_guard=not app.cfg['plugin_guard']
            )
        forms.Form.__init__(self, initial)

    def apply(self):
        """Apply the changes."""
        t = self.app.cfg.edit()
        t['plugins'] = u', '.join(sorted(self.data['active_plugins']))
        t['plugin_guard'] = not self.data['disable_guard']
        t.commit()
Beispiel #3
0
class ConfigurationForm(forms.Form):
    """Markdown configuration form."""
    extensions = forms.LineSeparated(forms.TextField(),
                                     _(u'Enabled Extensions'))
    makeintro = forms.BooleanField(_(u'Make Intro Section'),
        help_text=_(u'Place <!--more--> on a line by itself with blank '\
                    u'lines above and below to cut the post at that point.'))
Beispiel #4
0
    class _ImportForm(forms.Form):
        title = forms.BooleanField(lazy_gettext(u'Blog title'),
                                   help_text=blog.title)
        description = forms.BooleanField(lazy_gettext(u'Blog description'),
                                         help_text=blog.description)
        authors = forms.Mapping(_authors)
        posts = forms.Mapping(_posts)
        comments = forms.Mapping(_comments)
        load_config = forms.BooleanField(lazy_gettext(u'Load config values'),
                                         help_text=lazy_gettext(
                                         u'Load the configuration values '
                                         u'from the import.'))

        def perform_import(self):
            from zine.importers import perform_import
            return perform_import(get_application(), blog, self.data,
                                  stream=True)
Beispiel #5
0
class LiveJournalImportForm(forms.Form):
    """This form asks the user for authorisation and import options."""
    username = forms.TextField(lazy_gettext(u'LiveJournal username'),
                               required=True,
                               validators=[is_valid_lj_user()])
    password = forms.TextField(lazy_gettext(u'LiveJournal password'),
                               required=True,
                               widget=forms.PasswordInput)
    import_what = forms.ChoiceField(lazy_gettext(u'Import what?'),
        choices=[(IMPORT_JOURNAL, lazy_gettext(u'My Journal')),
              (IMPORT_COMMUNITY, lazy_gettext(u'My Posts in Community')),
              (IMPORT_COMMUNITY_ALL, lazy_gettext(u'Everything in Community'))],
        help_text=lazy_gettext(u'Importing a community requires '\
                               u'administrative access to the community.'),
        default=IMPORT_JOURNAL, required=True,
        widget=forms.RadioButtonGroup)
    community = forms.TextField(lazy_gettext(u'Community name'))
    security_choices = [(SECURITY_DISCARD, lazy_gettext(u'Don’t import')),
                        (SECURITY_PRIVATE, lazy_gettext(u'Private')),
                        (SECURITY_PROTECTED, lazy_gettext(u'Protected')),
                        (SECURITY_PUBLIC, lazy_gettext(u'Public'))]
    security_custom = forms.ChoiceField(lazy_gettext(
            u'Convert custom-security entries to'), choices=security_choices,
            help_text=lazy_gettext(u'Zine only supports public, private and '\
                                   u'protected entries, so you must choose '\
                                   u'what to do with your custom security '\
                                   u'entries.'))
    categories = forms.Multiple(forms.TextField(),
                                lazy_gettext(u'Categories'),
                                help_text=lazy_gettext(u'Choose categories to '\
                                                  u'assign imported posts to.'),
                                widget=forms.CheckboxGroup)
    getcomments = forms.BooleanField(lazy_gettext(u'Download Comments?'))

    def __init__(self, initial=None):
        initial = forms.fill_dict(
            initial,
            getcomments=True,
            import_what=IMPORT_JOURNAL,
            security_custom=SECURITY_PROTECTED,
        )
        self.categories.choices = [(c.name, c.name)
                                   for c in zine.models.Category.query.all()]
        forms.Form.__init__(self, initial)

    def context_validate(self, data):
        lj = LiveJournalConnect(data['username'], data['password'])
        try:
            result = lj.login()
        except xmlrpclib.Fault, fault:
            raise ValidationError(fault.faultString)
        if data['import_what'] in [IMPORT_COMMUNITY, IMPORT_COMMUNITY_ALL]:
            if data['community'] not in result.get('usejournals', []):
                raise ValidationError(lazy_gettext(u'You do not have access '\
                    u'to the specified community.'))
Beispiel #6
0
def setup(app, plugin):
    app.add_parser('markdown', MarkdownParser)
    app.add_config_var(CFG_EXTENSIONS,
                       forms.LineSeparated(forms.TextField(), default=[]))
    app.add_config_var(CFG_MAKEINTRO, forms.BooleanField(default=False))
    app.connect_event('modify-admin-navigation-bar', add_config_link)
    app.add_url_rule('/options/markdown',
                     prefix='admin',
                     endpoint='markdown_parser/config',
                     view=show_markdown_config)
    app.add_template_searchpath(TEMPLATES)
Beispiel #7
0
class EditCommentForm(_CommentBoundForm):
    """Form for comment editing in admin."""
    author = forms.TextField(lazy_gettext(u'Author'), required=True)
    email = forms.TextField(lazy_gettext(u'Email'),
                            validators=[is_valid_email()])
    www = forms.TextField(lazy_gettext(u'Website'),
                          validators=[is_valid_url()])
    text = forms.TextField(lazy_gettext(u'Text'), widget=forms.Textarea)
    pub_date = forms.DateTimeField(lazy_gettext(u'Date'), required=True)
    parser = forms.ChoiceField(lazy_gettext(u'Parser'), required=True)
    blocked = forms.BooleanField(lazy_gettext(u'Block Comment'))
    blocked_msg = forms.TextField(lazy_gettext(u'Reason'))

    def __init__(self, comment, initial=None):
        _CommentBoundForm.__init__(self, comment, forms.fill_dict(initial,
            author=comment.author,
            email=comment.email,
            www=comment.www,
            text=comment.text,
            pub_date=comment.pub_date,
            parser=comment.parser,
            blocked=comment.blocked,
            blocked_msg=comment.blocked_msg
        ))
        self.parser.choices = self.app.list_parsers()
        self.parser_missing = comment.parser_missing
        if self.parser_missing and comment.parser is not None:
            self.parser.choices.append((comment.parser, _('%s (missing)') %
                                        comment.parser.title()))

    def save_changes(self):
        """Save the changes back to the database."""
        old_parser = self.comment.parser
        forms.set_fields(self.comment, self.data, 'pub_date', 'parser',
                         'blocked_msg')

        if (self.data['text'] != self.comment.text
            or self.data['parser'] != old_parser):
            self.comment.text = self.data['text']

        # update status
        if self.data['blocked']:
            if not self.comment.blocked:
                self.comment.status = COMMENT_BLOCKED_USER
        else:
            self.comment.status = COMMENT_MODERATED

        # only apply these if the comment is not anonymous
        if self.comment.anonymous:
            forms.set_fields(self.comment, self.data, 'author', 'email', 'www')
Beispiel #8
0
class LoginForm(forms.Form):
    """The form for the login page."""
    user = forms.ModelField(User, 'username', required=True, messages=dict(
        not_found=lazy_gettext(u'User “%(value)s” does not exist.'),
        required=lazy_gettext(u'You have to enter a username.')
    ), on_not_found=lambda user:
        log.warning(_(u'Failed login attempt, user “%s” does not exist')
                      % user, 'auth')
    )
    password = forms.TextField(widget=forms.PasswordInput)
    permanent = forms.BooleanField()

    def context_validate(self, data):
        if not data['user'].check_password(data['password']):
            log.warning(_(u'Failed login attempt from “%s”, invalid password')
                        % data['user'].username, 'auth')
            raise ValidationError(_('Incorrect password.'))
Beispiel #9
0
def make_config_form():
    """Returns the form for the configuration editor."""
    app = get_application()
    fields = {}
    values = {}
    use_default_label = lazy_gettext(u'Use default value')

    for category in app.cfg.get_detail_list():
        items = {}
        values[category['name']] = category_values = {}
        for item in category['items']:
            items[item['name']] = forms.Mapping(
                value=item['field'],
                use_default=forms.BooleanField(use_default_label)
            )
            category_values[item['name']] = {
                'value':        item['value'],
                'use_default':  False
            }
        fields[category['name']] = forms.Mapping(**items)

    class _ConfigForm(forms.Form):
        values = forms.Mapping(**fields)
        cfg = app.cfg

        def apply(self):
            t = self.cfg.edit()
            for category, items in self.data['values'].iteritems():
                for key, d in items.iteritems():
                    if category != 'zine':
                        key = '%s/%s' % (category, key)
                    if d['use_default']:
                        t.revert_to_default(key)
                    else:
                        t[key] = d['value']
            t.commit()

    return _ConfigForm({'values': values})
Beispiel #10
0
class EditUserForm(_UserBoundForm):
    """Edit or create a user."""

    username = forms.TextField(lazy_gettext(u'Username'), max_length=30,
                               validators=[is_not_whitespace_only()],
                               required=True)
    real_name = forms.TextField(lazy_gettext(u'Realname'), max_length=180)
    display_name = forms.ChoiceField(lazy_gettext(u'Display name'))
    description = forms.TextField(lazy_gettext(u'Description'),
                                  max_length=5000, widget=forms.Textarea)
    email = forms.TextField(lazy_gettext(u'Email'), required=True,
                            validators=[is_valid_email()])
    www = forms.TextField(lazy_gettext(u'Website'),
                          validators=[is_valid_url()])
    password = forms.TextField(lazy_gettext(u'Password'),
                               widget=forms.PasswordInput)
    privileges = forms.MultiChoiceField(lazy_gettext(u'Privileges'),
                                        widget=forms.CheckboxGroup)
    groups = forms.MultiChoiceField(lazy_gettext(u'Groups'),
                                    widget=forms.CheckboxGroup)
    is_author = forms.BooleanField(lazy_gettext(u'List as author'),
        help_text=lazy_gettext(u'This user is listed as author'))

    def __init__(self, user=None, initial=None):
        if user is not None:
            initial = forms.fill_dict(initial,
                username=user.username,
                real_name=user.real_name,
                display_name=user._display_name,
                description=user.description,
                email=user.email,
                www=user.www,
                privileges=[x.name for x in user.own_privileges],
                groups=[g.name for g in user.groups],
                is_author=user.is_author
            )
        _UserBoundForm.__init__(self, user, initial)
        self.display_name.choices = [
            (u'$username', user and user.username or _('Username')),
            (u'$real_name', user and user.real_name or _('Realname'))
        ]
        self.privileges.choices = self.app.list_privileges()
        self.groups.choices = [g.name for g in Group.query.all()]
        self.password.required = user is None

    def validate_username(self, value):
        query = User.query.filter_by(username=value)
        if self.user is not None:
            query = query.filter(User.id != self.user.id)
        if query.first() is not None:
            raise ValidationError(_('This username is already in use'))

    def _set_common_attributes(self, user):
        forms.set_fields(user, self.data, 'www', 'real_name', 'description',
                         'display_name', 'is_author')
        bind_privileges(user.own_privileges, self.data['privileges'])
        bound_groups = set(g.name for g in user.groups)
        choosen_groups = set(self.data['groups'])
        group_mapping = dict((g.name, g) for g in Group.query.all())
        # delete groups
        for group in (bound_groups - choosen_groups):
            user.groups.remove(group_mapping[group])
        # and add new groups
        for group in (choosen_groups - bound_groups):
            user.groups.append(group_mapping[group])

    def make_user(self):
        """A helper function that creates a new user object."""
        user = User(self.data['username'], self.data['password'],
                    self.data['email'])
        self._set_common_attributes(user)
        self.user = user
        return user

    def save_changes(self):
        """Apply the changes."""
        self.user.username = self.data['username']
        if self.data['password']:
            self.user.set_password(self.data['password'])
        self.user.email = self.data['email']
        self._set_common_attributes(self.user)
Beispiel #11
0
class PostForm(forms.Form):
    """This is the baseclass for all forms that deal with posts.  There are
    two builtin subclasses for the builtin content types 'entry' and 'page'.
    """
    title = forms.TextField(lazy_gettext(u'Title'), max_length=150,
                            validators=[is_not_whitespace_only()],
                            required=False)
    text = forms.TextField(lazy_gettext(u'Text'), max_length=65000,
                           widget=forms.Textarea)
    status = forms.ChoiceField(lazy_gettext(u'Publication status'), choices=[
                               (STATUS_DRAFT, lazy_gettext(u'Draft')),
                               (STATUS_PUBLISHED, lazy_gettext(u'Published')),
                               (STATUS_PROTECTED, lazy_gettext(u'Protected')),
                               (STATUS_PRIVATE, lazy_gettext(u'Private'))])
    pub_date = forms.DateTimeField(lazy_gettext(u'Publication date'),
        help_text=lazy_gettext(u'Clear this field to update to current time'))
    slug = forms.TextField(lazy_gettext(u'Slug'), validators=[is_valid_slug()],
        help_text=lazy_gettext(u'Clear this field to autogenerate a new slug'))
    author = forms.ModelField(User, 'username', lazy_gettext('Author'),
                              widget=forms.SelectBox)
    tags = forms.CommaSeparated(forms.TextField(), lazy_gettext(u'Tags'))
    categories = forms.Multiple(forms.ModelField(Category, 'id'),
                                lazy_gettext(u'Categories'),
                                widget=forms.CheckboxGroup)
    parser = forms.ChoiceField(lazy_gettext(u'Parser'))
    comments_enabled = forms.BooleanField(lazy_gettext(u'Enable comments'))
    pings_enabled = forms.BooleanField(lazy_gettext(u'Enable pingbacks'))
    ping_links = forms.BooleanField(lazy_gettext(u'Ping links'))

    #: the content type for this field.
    content_type = None

    def __init__(self, post=None, initial=None):
        self.app = get_application()
        self.post = post

        if post is not None:
            initial = forms.fill_dict(initial,
                title=post.title,
                text=post.text,
                status=post.status,
                pub_date=post.pub_date,
                slug=post.slug,
                author=post.author,
                tags=[x.name for x in post.tags],
                categories=[x.id for x in post.categories],
                parser=post.parser,
                comments_enabled=post.comments_enabled,
                pings_enabled=post.pings_enabled,
                ping_links=not post.parser_missing
            )
        else:
            initial = forms.fill_dict(initial, status=STATUS_DRAFT)

            # if we have a request, we can use the current user as a default
            req = get_request()
            if req and req.user:
                initial['author'] = req.user

        initial.setdefault('parser', self.app.cfg['default_parser'])

        self.author.choices = [x.username for x in User.query.all()]
        self.parser.choices = self.app.list_parsers()
        self.parser_missing = post and post.parser_missing
        if self.parser_missing:
            self.parser.choices.append((post.parser, _('%s (missing)') %
                                        post.parser.title()))

        self.categories.choices = [(c.id, c.name) for c in
                                   Category.query.all()]

        forms.Form.__init__(self, initial)

        # if we have have an old post and the parser is not missing and
        # it was published when the form was created we collect the old
        # posts so that we don't have to ping them another time.
        self._old_links = set()
        if self.post is not None and not self.post.parser_missing and \
           self.post.is_published:
            self._old_links.update(self.post.find_urls())

    def find_new_links(self):
        """Return a list of all new links."""
        for link in self.post.find_urls():
            if not link in self._old_links:
                yield link

    def validate_slug(self, value):
        """Make sure the slug is unique."""
        query = Post.query.filter_by(slug=value)
        if self.post is not None:
            query = query.filter(Post.id != self.post.id)
        existing = query.first()
        if existing is not None:
            raise ValidationError(_('This slug is already in use.'))

    def validate_parser(self, value):
        """Make sure the missing parser is not selected."""
        if self.parser_missing and value == self.post.parser:
            raise ValidationError(_('Selected parser is no longer '
                                    'available on the system.'))

    def as_widget(self, preview=False):
        widget = forms.Form.as_widget(self)
        widget.new = self.post is None
        widget.post = self.post
        widget.preview = preview
        widget.parser_missing = self.parser_missing
        return widget

    def make_post(self):
        """A helper function that creates a post object from the data."""
        data = self.data
        post = Post(data['title'], data['author'], data['text'], data['slug'],
                    parser=data['parser'], content_type=self.content_type,
                    pub_date=data['pub_date'])
        post.bind_categories(data['categories'])
        post.bind_tags(data['tags'])
        self._set_common_attributes(post)
        self.post = post
        return post

    def save_changes(self):
        """Save the changes back to the database.  This also adds a redirect
        if the slug changes.
        """
        if not self.data['pub_date']:
            # If user deleted publication timestamp, make a new one.
            self.data['pub_date'] = datetime.utcnow()
        old_slug = self.post.slug
        old_parser = self.post.parser
        forms.set_fields(self.post, self.data, 'title', 'author', 'parser')
        if (self.data['text'] != self.post.text
            or self.data['parser'] != old_parser):
            self.post.text = self.data['text']
        add_redirect = self.post.is_published and old_slug != self.post.slug

        self.post.touch_times(self.data['pub_date'])
        self.post.bind_slug(self.data['slug'])

        self._set_common_attributes(self.post)
        if add_redirect:
            register_redirect(old_slug, self.post.slug)

    def _set_common_attributes(self, post):
        forms.set_fields(post, self.data, 'comments_enabled', 'pings_enabled',
                         'status')
        post.bind_categories(self.data['categories'])
        post.bind_tags(self.data['tags'])

    def taglist(self):
        """Return all available tags as a JSON-encoded list."""
        tags = [t.name for t in Tag.query.all()]
        return dump_json(tags)