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.'))
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()})
class ConfigurationForm(forms.Form): """Very simple form for the variation selection.""" variation = forms.ChoiceField(_('Color variation')) def __init__(self, initial=None): forms.Form.__init__(self, initial) choices = sorted(variations.items(), key=lambda x: x[1].lower()) self.fields['variation'].choices = choices
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')
class DeleteGroupForm(_GroupBoundForm): """Used to delete a group from the admin panel.""" action = forms.ChoiceField(lazy_gettext(u'What should Zine do with users ' u'assigned to this group?'), choices=[ ('delete_membership', lazy_gettext(u'Do nothing, just detach the membership')), ('relocate', lazy_gettext(u'Move the users to another group')) ], widget=forms.RadioButtonGroup) relocate_to = forms.ModelField(Group, 'id', lazy_gettext(u'Relocate users to'), widget=forms.SelectBox) def __init__(self, group, initial=None): self.relocate_to.choices = [('', u'')] + [ (g.id, g.name) for g in Group.query.filter(Group.id != group.id) ] _GroupBoundForm.__init__(self, group, forms.fill_dict(initial, action='delete_membership')) def context_validate(self, data): if data['action'] == 'relocate' and not data['relocate_to']: raise ValidationError(_('You have to select a group that ' 'gets the users assigned.')) def delete_group(self): """Deletes a group.""" if self.data['action'] == 'relocate': new_group = Group.query.filter_by(data['reassign_to'].id).first() for user in self.group.users: if not new_group in user.groups: user.groups.append(new_group) db.commit() #! plugins can use this to react to user deletes. They can't stop #! the deleting of the group but they can delete information in #! their own tables so that the database is consistent afterwards. #! Additional to the group object the form data is submitted. emit_event('before-group-deleted', self.group, self.data) db.delete(self.group)
class DeleteUserForm(_UserBoundForm): """Used to delete a user from the admin panel.""" action = forms.ChoiceField(lazy_gettext(u'What should Zine do with posts ' u'written by this user?'), choices=[ ('delete', lazy_gettext(u'Delete them permanently')), ('reassign', lazy_gettext(u'Reassign posts')) ], widget=forms.RadioButtonGroup) reassign_to = forms.ModelField(User, 'id', lazy_gettext(u'Reassign posts to'), widget=forms.SelectBox) def __init__(self, user, initial=None): self.reassign_to.choices = [('', u'')] + [ (u.id, u.username) for u in User.query.filter(User.id != user.id) ] _UserBoundForm.__init__(self, user, forms.fill_dict(initial, action='reassign' )) def context_validate(self, data): if data['action'] == 'reassign' and not data['reassign_to']: # XXX: Bad wording raise ValidationError(_('You have to select the user that ' 'gets the posts assigned.')) def delete_user(self): """Deletes the user.""" if self.data['action'] == 'reassign': db.execute(posts.update(posts.c.author_id == self.user.id), dict( author_id=self.data['reassign_to'].id )) #! plugins can use this to react to user deletes. They can't stop #! the deleting of the user but they can delete information in #! their own tables so that the database is consistent afterwards. #! Additional to the user object the form data is submitted. emit_event('before-user-deleted', self.user, self.data) db.delete(self.user)
class ConfigurationForm(forms.Form): style = forms.ChoiceField(required=True)
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)
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)